file_path
stringlengths 21
202
| content
stringlengths 19
1.02M
| size
int64 19
1.02M
| lang
stringclasses 8
values | avg_line_length
float64 5.88
100
| max_line_length
int64 12
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.kit.stage_templates/omni/kit/stage_templates/stage_templates_page.py | import re
import os
import carb.settings
import omni.kit.app
import omni.ui as ui
from functools import partial
from omni.kit.window.preferences import PreferenceBuilder, show_file_importer, SettingType, PERSISTENT_SETTINGS_PREFIX
class StageTemplatesPreferences(PreferenceBuilder):
def __init__(self):
super().__init__("Template Startup")
# update on setting change
def on_change(item, event_type):
if event_type == carb.settings.ChangeEventType.CHANGED:
omni.kit.window.preferences.rebuild_pages()
self._update_setting = omni.kit.app.SettingChangeSubscription(PERSISTENT_SETTINGS_PREFIX + "/app/newStage/templatePath", on_change)
def build(self):
template_paths = carb.settings.get_settings().get("/persistent/app/newStage/templatePath")
default_template = omni.kit.stage_templates.get_default_template()
script_names = []
new_templates = omni.kit.stage_templates.get_stage_template_list()
for templates in new_templates:
for template in templates.items():
script_names.append(template[0])
if len(script_names) == 0:
script_names = ["None##None"]
with ui.VStack(height=0):
with self.add_frame("New Stage Template"):
with ui.VStack():
for index, path in enumerate(template_paths):
with ui.HStack(height=24):
self.label("Path to user templates")
widget = ui.StringField(height=20)
widget.model.set_value(path)
ui.Button(style={"image_url": "resources/icons/folder.png"}, clicked_fn=lambda p=self.cleanup_slashes(carb.tokens.get_tokens_interface().resolve(path)), i=index, w=widget: self._on_browse_button_fn(p, i, w), width=24)
self.create_setting_widget_combo("Default Template", PERSISTENT_SETTINGS_PREFIX + "/app/newStage/defaultTemplate", script_names)
def _on_browse_button_fn(self, path, index, widget):
""" Called when the user picks the Browse button. """
show_file_importer(
"Select Template Directory",
click_apply_fn=lambda p=self.cleanup_slashes(path), i=index, w=widget: self._on_file_pick(
p, index=i, widget=w),
filename_url=path)
def _on_file_pick(self, full_path, index, widget):
""" Called when the user accepts directory in the Select Directory dialog. """
directory = self.cleanup_slashes(full_path, True)
settings = carb.settings.get_settings()
template_paths = settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/newStage/templatePath")
template_paths[index] = directory
settings.set(PERSISTENT_SETTINGS_PREFIX + "/app/newStage/templatePath", template_paths)
widget.model.set_value(directory)
| 2,921 | Python | 46.901639 | 245 | 0.636768 |
omniverse-code/kit/exts/omni.kit.stage_templates/omni/kit/stage_templates/new_stage.py | import os
import carb
import carb.settings
import omni.ext
import omni.kit.app
import omni.usd
import asyncio
import glob
import omni.kit.actions.core
from inspect import signature
from functools import partial
from pxr import Sdf, UsdGeom, Usd, Gf
from contextlib import suppress
from .stage_templates_menu import get_action_name
_extension_instance = None
_extension_path = None
_template_list = []
_clear_dirty_task = None
def _try_unregister_page(page: str):
with suppress(Exception):
import omni.kit.window.preferences
omni.kit.window.preferences.unregister_page(page)
# must be initalized before templates
class NewStageExtension(omni.ext.IExt):
def on_startup(self, ext_id):
global _extension_path
global clear_dirty_task
_extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id)
_clear_dirty_task = None
register_template("empty", self.new_stage_empty, 0)
omni.kit.stage_templates.templates.load_templates()
self.load_user_templates()
# as omni.kit.stage_templates loads before the UI, it cannot depend on omni.kit.window.preferences or other extensions.
self._preferences_page = None
self._menu_button1 = None
self._menu_button2 = None
self._hooks = []
manager = omni.kit.app.get_app().get_extension_manager()
self._hooks.append(
manager.subscribe_to_extension_enable(
on_enable_fn=lambda _: self._register_page(),
on_disable_fn=lambda _: self._unregister_page(),
ext_name="omni.kit.window.preferences",
hook_name="omni.kit.stage_templates omni.kit.window.preferences listener",
)
)
self._stage_template_menu = None
self._hooks.append(
manager.subscribe_to_extension_enable(
on_enable_fn=lambda _: self._register_menu(),
on_disable_fn=lambda _: self._unregister_menu(),
ext_name="omni.kit.menu.utils",
hook_name="omni.kit.stage_templates omni.kit.menu.utils listener",
)
)
self._hooks.append(
manager.subscribe_to_extension_enable(
on_enable_fn=lambda _: self._register_property_menu(),
on_disable_fn=lambda _: self._unregister_property_menu(),
ext_name="omni.kit.property.usd",
hook_name="omni.kit.stage_templates omni.kit.property.usd listener",
)
)
global _extension_instance
_extension_instance = self
def on_shutdown(self):
global _extension_instance
global _template_list
global _clear_dirty_task
if _clear_dirty_task:
_clear_dirty_task.cancel()
_clear_dirty_task = None
unregister_template("empty")
self._unregister_page()
self._unregister_menu()
self._unregister_property_menu()
self._hooks = None
_extension_instance = None
_template_list = None
for user_template in self._user_scripts:
del user_template
omni.kit.stage_templates.templates.unload_templates()
self._user_scripts = None
def _register_page(self):
try:
from omni.kit.window.preferences import register_page
from .stage_templates_page import StageTemplatesPreferences
self._preferences_page = register_page(StageTemplatesPreferences())
except ModuleNotFoundError:
pass
def _unregister_page(self):
if self._preferences_page:
try:
import omni.kit.window.preferences
omni.kit.window.preferences.unregister_page(self._preferences_page)
self._preferences_page = None
except ModuleNotFoundError:
pass
def _register_menu(self):
try:
from .stage_templates_menu import StageTemplateMenu
self._stage_template_menu = StageTemplateMenu()
self._stage_template_menu.on_startup()
except ModuleNotFoundError:
pass
def _unregister_menu(self):
if self._stage_template_menu:
try:
self._stage_template_menu.on_shutdown()
self._stage_template_menu = None
except ModuleNotFoundError:
pass
def _has_axis(self, objects, axis):
if not "stage" in objects:
return False
stage = objects["stage"]
if stage:
return UsdGeom.GetStageUpAxis(stage) != axis
else:
carb.log_error("_click_set_up_axis stage not found")
return False
def _click_set_up_axis(self, payload, axis):
stage = payload.get_stage()
if stage:
rootLayer = stage.GetRootLayer()
if rootLayer:
rootLayer.SetPermissionToEdit(True)
with Usd.EditContext(stage, rootLayer):
UsdGeom.SetStageUpAxis(stage, axis)
from omni.kit.property.usd import PrimPathWidget
PrimPathWidget.rebuild()
else:
carb.log_error("_click_set_up_axis rootLayer not found")
else:
carb.log_error("_click_set_up_axis stage not found")
def _register_property_menu(self):
# +add menu item(s)
from omni.kit.property.usd import PrimPathWidget
context_menu = omni.kit.context_menu.get_instance()
if context_menu is None:
self._menu_button1 = None
self._menu_button2 = None
carb.log_error("context_menu is disabled!")
return None
self._menu_button1 = PrimPathWidget.add_button_menu_entry(
"Stage/Set up axis +Y",
show_fn=partial(self._has_axis, axis=UsdGeom.Tokens.y),
onclick_fn=partial(self._click_set_up_axis, axis=UsdGeom.Tokens.y),
add_to_context_menu=False,
)
self._menu_button2 = PrimPathWidget.add_button_menu_entry(
"Stage/Set up axis +Z",
show_fn=partial(self._has_axis, axis=UsdGeom.Tokens.z),
onclick_fn=partial(self._click_set_up_axis, axis=UsdGeom.Tokens.z),
add_to_context_menu=False,
)
def _unregister_property_menu(self):
if self._menu_button1 or self._menu_button2:
try:
from omni.kit.property.usd import PrimPathWidget
if self._menu_button1:
PrimPathWidget.remove_button_menu_entry(self._menu_button1)
self._menu_button1 = None
if self._menu_button2:
PrimPathWidget.remove_button_menu_entry(self._menu_button2)
self._menu_button2 = None
except ModuleNotFoundError:
pass
def new_stage_empty(self, rootname):
pass
def load_user_templates(self):
settings = carb.settings.get_settings()
template_paths = settings.get("/persistent/app/newStage/templatePath")
# Create template directories
original_umask = os.umask(0)
for path in template_paths:
path = carb.tokens.get_tokens_interface().resolve(path)
if not os.path.isdir(path):
try:
os.makedirs(path)
except Exception:
carb.log_error(f"Failed to create directory {path}")
os.umask(original_umask)
# Load template scripts
self._user_scripts = []
for path in template_paths:
for full_path in glob.glob(f"{path}/*.py"):
try:
with open(os.path.normpath(full_path)) as f:
user_script = f.read()
carb.log_verbose(f"loaded new_stage template {full_path}")
exec(user_script)
self._user_scripts.append(user_script)
except Exception as e:
carb.log_error(f"error loading {full_path}: {e}")
def register_template(name, new_stage_fn, group=0, rebuild=True):
"""Register new_stage Template
Args:
param1 (str): template name
param2 (callable): function to create template
param3 (int): group number. User by menu to split into groups with seperators
Returns:
bool: True for success, False when template already exists.
"""
# check if element exists
global _template_list
exists = get_stage_template(name)
if exists:
carb.log_warn(f"template {name} already exists")
return False
try:
exists = _template_list[group]
except IndexError:
_template_list.insert(group, {})
_template_list[group][name] = (name, new_stage_fn)
omni.kit.actions.core.get_action_registry().register_action(
"omni.kit.stage.templates",
f"create_new_stage_{get_action_name(name)}",
lambda t=name: omni.kit.window.file.new(t),
display_name=f"Create New Stage {name}",
description=f"Create New Stage {name}",
tag="Create Stage Template",
)
if rebuild:
rebuild_stage_template_menu()
return True
def unregister_template(name, rebuild: bool=True):
"""Remove registered new_stage Template
Args:
param1 (str): template name
Returns:
nothing
"""
global _template_list
if _template_list is not None:
for templates in _template_list:
if name in templates:
del templates[name]
if rebuild:
rebuild_stage_template_menu()
omni.kit.actions.core.get_action_registry().deregister_action("omni.kit.stage.templates", f"create_new_stage_{get_action_name(name)}")
def rebuild_stage_template_menu() -> None:
if _extension_instance and _extension_instance._stage_template_menu:
_extension_instance._stage_template_menu._rebuild_sub_menu()
def get_stage_template_list():
"""Get list of loaded new_stage templates
Args:
none
Returns:
list: list of groups of new_stage template names & create function pointers
"""
global _template_list
if not _template_list or len(_template_list) == 0:
return None
return _template_list
def get_stage_template(name):
"""Get named new_stage template & create function pointer
Args:
param1 (str): template name
Returns:
tuple: new_stage template name & create function pointer
"""
global _template_list
if not _template_list:
return None
for templates in _template_list:
if name in templates:
return templates[name]
return None
def get_default_template():
"""Get name of default new_stage template. Used when new_stage is called without template name specified
Args:
param1 (str): template name
Returns:
str: new_stage template name
"""
settings = carb.settings.get_settings()
return settings.get("/persistent/app/newStage/defaultTemplate")
def new_stage_finalize(create_result, error_message, usd_context, template=None, on_new_stage_fn=None):
global _clear_dirty_task
if _clear_dirty_task:
_clear_dirty_task.cancel()
_clear_dirty_task = None
if create_result:
stage = usd_context.get_stage()
# already finilized
if stage.HasDefaultPrim():
return
with Usd.EditContext(stage, stage.GetRootLayer()):
settings = carb.settings.get_settings()
default_prim_name = settings.get("/persistent/app/stage/defaultPrimName")
up_axis = settings.get("/persistent/app/stage/upAxis")
time_codes_per_second = settings.get_as_float("/persistent/app/stage/timeCodesPerSecond")
time_code_range = settings.get("/persistent/app/stage/timeCodeRange")
if time_code_range is None:
time_code_range = [0, 100]
rootname = f"/{default_prim_name}"
# Set up axis
if up_axis == "Y" or up_axis == "y":
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y)
else:
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
# Set timecodes per second
stage.SetTimeCodesPerSecond(time_codes_per_second)
# Start and end time code
if time_code_range:
stage.SetStartTimeCode(time_code_range[0])
stage.SetEndTimeCode(time_code_range[1])
# Create defaultPrim
default_prim = UsdGeom.Xform.Define(stage, Sdf.Path(rootname)).GetPrim()
if not default_prim:
carb.log_error("Failed to create defaultPrim at {rootname}")
return
stage.SetDefaultPrim(default_prim)
if template is None:
template = get_default_template()
# Run script
item = get_stage_template(template)
if item and item[1]:
try:
create_fn = item[1]
sig = signature(create_fn)
if len(sig.parameters) == 1:
create_fn(rootname)
elif len(sig.parameters) == 2:
create_fn(rootname, usd_context.get_name())
else:
carb.log_error(f"template {template} has incorrect parameter count")
except Exception as error:
carb.log_error(f"exception in {template} {error}")
omni.kit.undo.clear_stack()
usd_context.set_pending_edit(False)
# Clear the stage dirty state again, as bound materials can set it
async def clear_dirty(usd_context):
import omni.kit.app
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
usd_context.set_pending_edit(False)
_clear_dirty_task = None
if on_new_stage_fn:
on_new_stage_fn(create_result, error_message)
_clear_dirty_task = asyncio.ensure_future(clear_dirty(usd_context))
def new_stage(on_new_stage_fn=None, template="empty", usd_context=None):
"""Execute new_stage
Args:
param2 (str): template name, if not specified default name is used
param3 (omni.usd.UsdContext): usd_context, the usd_context to create new stage
Returns:
nothing
"""
if usd_context is None:
usd_context = omni.usd.get_context()
if on_new_stage_fn is not None:
carb.log_warn(
"omni.kit.stage_templates.new_stage(callback, ...) is deprecated. \
Use `omni.kit.stage_templates.new_stage_with_callback` instead."
)
new_stage_with_callback(on_new_stage_fn, template, usd_context)
else:
new_stage_finalize(usd_context.new_stage(), "", usd_context, template=template, on_new_stage_fn=None)
def new_stage_with_callback(on_new_stage_fn=None, template="empty", usd_context=None):
"""Execute new_stage
Args:
param1 (callable): callback when new_stage is created
param2 (str): template name, if not specified default name is used
param3 (omni.usd.UsdContext): usd_context, the usd_context to create new stage
Returns:
nothing
"""
if usd_context is None:
usd_context = omni.usd.get_context()
usd_context.new_stage_with_callback(
partial(new_stage_finalize, usd_context=usd_context, template=template, on_new_stage_fn=on_new_stage_fn)
)
async def new_stage_async(template="empty", usd_context=None):
"""Execute new_stage asynchronously
Args:
param1 (str): template name, if not specified default name is used
param2 (omni.usd.UsdContext): usd_context, the usd_context to create new stage
Returns:
awaitable object until stage is created
"""
if usd_context is None:
usd_context = omni.usd.get_context()
f = asyncio.Future()
def on_new_stage(result, err_msg):
if not f.done():
f.set_result((result, err_msg))
new_stage_with_callback(on_new_stage, template, usd_context)
return await f
def get_extension_path(sub_directory):
global _extension_path
path = _extension_path
if sub_directory:
path = os.path.normpath(os.path.join(path, sub_directory))
return path
def set_transform_helper(
prim_path,
translate=Gf.Vec3d(0, 0, 0),
euler=Gf.Vec3d(0, 0, 0),
scale=Gf.Vec3d(1, 1, 1),
):
rotation = (
Gf.Rotation(Gf.Vec3d.ZAxis(), euler[2])
* Gf.Rotation(Gf.Vec3d.YAxis(), euler[1])
* Gf.Rotation(Gf.Vec3d.XAxis(), euler[0])
)
xform = Gf.Matrix4d().SetScale(scale) * Gf.Matrix4d().SetRotate(rotation) * Gf.Matrix4d().SetTranslate(translate)
omni.kit.commands.execute(
"TransformPrim",
path=prim_path,
new_transform_matrix=xform,
)
| 17,039 | Python | 31.706334 | 138 | 0.601326 |
omniverse-code/kit/exts/omni.kit.stage_templates/omni/kit/stage_templates/templates/default_stage.py | import carb
import omni.ext
import omni.kit.commands
from pxr import UsdLux, UsdShade, Kind, Vt, Gf, UsdGeom, Sdf
from ..new_stage import *
class DefaultStage:
def __init__(self):
register_template("default stage", self.new_stage)
def __del__(self):
unregister_template("default stage")
def new_stage(self, rootname, usd_context_name):
# S3 URL's
carlight_hdr = Sdf.AssetPath("https://omniverse-content-production.s3.us-west-2.amazonaws.com/Assets/Scenes/Templates/Default/SubUSDs/textures/CarLight_512x256.hdr")
grid_basecolor = Sdf.AssetPath("https://omniverse-content-production.s3.us-west-2.amazonaws.com/Assets/Scenes/Templates/Default/SubUSDs/textures/ov_uv_grids_basecolor_1024.png")
# change ambientLightColor
carb.settings.get_settings().set("/rtx/sceneDb/ambientLightColor", (0, 0, 0))
carb.settings.get_settings().set("/rtx/indirectDiffuse/enabled", True)
carb.settings.get_settings().set("/rtx/domeLight/upperLowerStrategy", 0)
carb.settings.get_settings().set("/rtx/post/lensFlares/flareScale", 0.075)
carb.settings.get_settings().set("/rtx/sceneDb/ambientLightIntensity", 0)
# get up axis
usd_context = omni.usd.get_context(usd_context_name)
stage = usd_context.get_stage()
up_axis = UsdGeom.GetStageUpAxis(stage)
with Usd.EditContext(stage, stage.GetRootLayer()):
# create Environment
omni.kit.commands.execute(
"CreatePrim",
prim_path="/Environment",
prim_type="Xform",
select_new_prim=False,
create_default_xform=True,
context_name=usd_context_name
)
prim = stage.GetPrimAtPath("/Environment")
prim.CreateAttribute("ground:size", Sdf.ValueTypeNames.Int, False).Set(1400)
prim.CreateAttribute("ground:type", Sdf.ValueTypeNames.String, False).Set("On")
# create Sky
omni.kit.commands.execute(
"CreatePrim",
prim_path="/Environment/Sky",
prim_type="DomeLight",
select_new_prim=False,
attributes={
UsdLux.Tokens.inputsIntensity: 1,
UsdLux.Tokens.inputsColorTemperature: 6250,
UsdLux.Tokens.inputsEnableColorTemperature: True,
UsdLux.Tokens.inputsExposure: 9,
UsdLux.Tokens.inputsTextureFile: carlight_hdr,
UsdLux.Tokens.inputsTextureFormat: UsdLux.Tokens.latlong,
UsdGeom.Tokens.visibility: "inherited",
} if hasattr(UsdLux.Tokens, 'inputsIntensity') else \
{
UsdLux.Tokens.intensity: 1,
UsdLux.Tokens.colorTemperature: 6250,
UsdLux.Tokens.enableColorTemperature: True,
UsdLux.Tokens.exposure: 9,
UsdLux.Tokens.textureFile: carlight_hdr,
UsdLux.Tokens.textureFormat: UsdLux.Tokens.latlong,
UsdGeom.Tokens.visibility: "inherited",
},
create_default_xform=True,
context_name=usd_context_name
)
prim = stage.GetPrimAtPath("/Environment/Sky")
prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 1))
if up_axis == "Y":
prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 305, 0))
prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, -90, -90))
else:
prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 305))
prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"])
# create DistantLight
omni.kit.commands.execute(
"CreatePrim",
prim_path="/Environment/DistantLight",
prim_type="DistantLight",
select_new_prim=False,
attributes={UsdLux.Tokens.inputsAngle: 2.5,
UsdLux.Tokens.inputsIntensity: 1,
UsdLux.Tokens.inputsColorTemperature: 7250,
UsdLux.Tokens.inputsEnableColorTemperature: True,
UsdLux.Tokens.inputsExposure: 10,
UsdGeom.Tokens.visibility: "inherited",
} if hasattr(UsdLux.Tokens, 'inputsIntensity') else \
{
UsdLux.Tokens.angle: 2.5,
UsdLux.Tokens.intensity: 1,
UsdLux.Tokens.colorTemperature: 7250,
UsdLux.Tokens.enableColorTemperature: True,
UsdLux.Tokens.exposure: 10,
UsdGeom.Tokens.visibility: "inherited",
},
create_default_xform=True,
context_name=usd_context_name
)
prim = stage.GetPrimAtPath("/Environment/DistantLight")
if up_axis == "Y":
prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 305, 0))
prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(-105, 0, 0))
else:
prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 305))
prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(-15, 0, 0))
prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"])
# Material "Grid"
mtl_path = omni.usd.get_stage_next_free_path(stage, "/Environment/Looks/Grid", False)
omni.kit.commands.execute("CreateMdlMaterialPrim", mtl_url="OmniPBR.mdl", mtl_name="Grid", mtl_path=mtl_path, context_name=usd_context_name)
mat_prim = stage.GetPrimAtPath(mtl_path)
shader = UsdShade.Material(mat_prim).ComputeSurfaceSource("mdl")[0]
shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl")
# set inputs
omni.usd.create_material_input(mat_prim, "albedo_add", 0, Sdf.ValueTypeNames.Float)
omni.usd.create_material_input(mat_prim, "albedo_brightness", 0.52, Sdf.ValueTypeNames.Float)
omni.usd.create_material_input(mat_prim, "albedo_desaturation", 1, Sdf.ValueTypeNames.Float)
omni.usd.create_material_input(mat_prim, "project_uvw", False, Sdf.ValueTypeNames.Bool)
omni.usd.create_material_input(mat_prim, "reflection_roughness_constant", 0.333, Sdf.ValueTypeNames.Float)
omni.usd.create_material_input(mat_prim, "diffuse_texture", grid_basecolor, Sdf.ValueTypeNames.Asset, def_value=Sdf.AssetPath(""), color_space="sRGB")
omni.usd.create_material_input(mat_prim, "texture_rotate", 0, Sdf.ValueTypeNames.Float, def_value=Vt.Float(0.0))
omni.usd.create_material_input(mat_prim, "texture_scale", Gf.Vec2f(0.5, 0.5), Sdf.ValueTypeNames.Float2, def_value=Gf.Vec2f(1, 1))
omni.usd.create_material_input(mat_prim, "texture_translate", Gf.Vec2f(0, 0), Sdf.ValueTypeNames.Float2, def_value=Gf.Vec2f(0, 0))
omni.usd.create_material_input(mat_prim, "world_or_object", False, Sdf.ValueTypeNames.Bool, def_value=Vt.Bool(False))
# Ground
ground_path = "/Environment/ground"
omni.kit.commands.execute(
"CreateMeshPrimWithDefaultXform",
prim_path=ground_path,
prim_type="Plane",
select_new_prim=False,
prepend_default_prim=False,
context_name=usd_context_name
)
prim = stage.GetPrimAtPath(ground_path)
prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 1))
prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:translate", "xformOp:rotateXYZ", "xformOp:scale"])
if up_axis == "Y":
prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, -90, -90))
else:
prim.CreateAttribute("xformOp:rotateXYZ", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
mesh = UsdGeom.Mesh(prim)
mesh.CreateSubdivisionSchemeAttr("none")
mesh.GetFaceVertexCountsAttr().Set([4])
mesh.GetFaceVertexIndicesAttr().Set([0, 1, 3, 2])
mesh.GetPointsAttr().Set(Vt.Vec3fArray([(-50, -50, 0), (50, -50, 0), (-50, 50, 0), (50, 50, 0)]))
mesh.GetNormalsAttr().Set(Vt.Vec3fArray([(0, 0, 1), (0, 0, 1), (0, 0, 1), (0, 0, 1)]))
mesh.SetNormalsInterpolation("faceVarying")
# https://github.com/PixarAnimationStudios/USD/commit/592b4d39edf5daf0534d467e970c95462a65d44b
# UsdGeom.Imageable.CreatePrimvar deprecated in v19.03 and removed in v22.08
primvar = UsdGeom.PrimvarsAPI(prim).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying)
primvar.Set(Vt.Vec2fArray([(0, 0), (1, 0), (1, 1), (0, 1)]))
# Create a ground plane collider
# NOTE: replace with USD plane prim after the next USD update
try:
from pxr import UsdPhysics
colPlanePath = "/Environment/groundCollider"
planeGeom = UsdGeom.Plane.Define(stage, colPlanePath)
planeGeom.CreatePurposeAttr().Set("guide")
planeGeom.CreateAxisAttr().Set(up_axis)
colPlanePrim = stage.GetPrimAtPath(colPlanePath)
UsdPhysics.CollisionAPI.Apply(colPlanePrim)
except ImportError:
carb.log_warn("Failed to create a ground plane collider. Please load the omni.physx.bundle extension and create a new stage from this template if you need it.")
# bind "Grid" to "Ground"
omni.kit.commands.execute("BindMaterialCommand", prim_path=ground_path, material_path=mtl_path, strength=None, context_name=usd_context_name)
# update extent
attr = prim.GetAttribute(UsdGeom.Tokens.extent)
if attr:
bounds = UsdGeom.Boundable.ComputeExtentFromPlugins(UsdGeom.Boundable(prim), Usd.TimeCode.Default())
if bounds:
attr.Set(bounds)
| 11,151 | Python | 57.694737 | 185 | 0.59896 |
omniverse-code/kit/exts/omni.kit.stage_templates/omni/kit/stage_templates/templates/sunlight.py | import carb
import omni.ext
import omni.kit.commands
from pxr import UsdLux
from ..new_stage import *
class SunlightStage:
def __init__(self):
register_template("sunlight", self.new_stage)
def __del__(self):
unregister_template("sunlight")
def new_stage(self, rootname, usd_context_name):
# Create basic DistantLight
usd_context = omni.usd.get_context(usd_context_name)
stage = usd_context.get_stage()
with Usd.EditContext(stage, stage.GetRootLayer()):
# create Environment
omni.kit.commands.execute(
"CreatePrim",
prim_path="/Environment",
prim_type="Xform",
select_new_prim=False,
create_default_xform=True,
context_name=usd_context_name
)
omni.kit.commands.execute(
"CreatePrim",
prim_path="/Environment/defaultLight",
prim_type="DistantLight",
select_new_prim=False,
# https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7
attributes={UsdLux.Tokens.inputsAngle: 1.0, UsdLux.Tokens.inputsIntensity: 3000} if hasattr(UsdLux.Tokens, 'inputsIntensity') else \
{UsdLux.Tokens.angle: 1.0, UsdLux.Tokens.intensity: 3000},
create_default_xform=True,
context_name=usd_context_name
)
| 1,486 | Python | 35.268292 | 148 | 0.588156 |
omniverse-code/kit/exts/omni.kit.stage_templates/omni/kit/stage_templates/templates/__init__.py | from .sunlight import SunlightStage
from .default_stage import DefaultStage
new_stage_template_list = None
def load_templates():
global new_stage_template_list
new_stage_template_list = [SunlightStage(), DefaultStage()]
def unload_templates():
global new_stage_template_list
new_stage_template_list = None
| 327 | Python | 20.866665 | 63 | 0.746177 |
omniverse-code/kit/exts/omni.kit.stage_templates/omni/kit/stage_templates/tests/test_new_stage_menu.py | import omni.kit.test
import asyncio
import carb
import omni.usd
import omni.ui as ui
from omni.kit import ui_test
from omni.kit.menu.utils import MenuItemDescription, MenuLayout
class TestMenuFile(omni.kit.test.AsyncTestCase):
async def setUp(self):
# 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()
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")
async def tearDown(self):
pass
def _on_stage_event(self, event):
if self._future_test and int(self._required_stage_event) == int(event.type):
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_file_new_from_stage_template_empty(self):
stage = omni.usd.get_context().get_stage()
layer_name = stage.GetRootLayer().identifier if stage else "None"
await self.reset_stage_event(omni.usd.StageEventType.OPENED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("New From Stage Template").click()
# select empty and wait for stage open
await menu_widget.find_menu("Empty").click()
await self.wait_for_stage_event()
# verify Empty stage
stage = omni.usd.get_context().get_stage()
self.assertFalse(stage.GetRootLayer().identifier == layer_name)
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()]
self.assertTrue(prim_list == ['/World'])
async def test_file_new_from_stage_template_sunlight(self):
stage = omni.usd.get_context().get_stage()
layer_name = stage.GetRootLayer().identifier if stage else "None"
await self.reset_stage_event(omni.usd.StageEventType.OPENED)
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("File").click()
await menu_widget.find_menu("New From Stage Template").click()
# select Sunlight and wait for stage open
await menu_widget.find_menu("Sunlight").click()
await self.wait_for_stage_event()
# verify Sunlight stage
stage = omni.usd.get_context().get_stage()
self.assertFalse(stage.GetRootLayer().identifier == layer_name)
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()]
self.assertTrue(prim_list == ['/World', '/Environment', '/Environment/defaultLight'])
| 3,227 | Python | 38.851851 | 155 | 0.657577 |
omniverse-code/kit/exts/omni.kit.stage_templates/omni/kit/stage_templates/tests/__init__.py | from .test_commands import *
from .test_new_stage import *
from .test_new_stage_menu import *
from .test_templates import *
from .test_preferences import *
| 156 | Python | 25.166662 | 34 | 0.75641 |
omniverse-code/kit/exts/omni.kit.stage_templates/omni/kit/stage_templates/tests/test_new_stage.py | import unittest
import carb.settings
import omni.kit.app
import omni.kit.test
import omni.kit.stage_templates
from pxr import UsdGeom
class TestNewStage(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._staged_called = 0
self._stage_name = "$$_test_stage_$$"
async def tearDown(self):
pass
def new_stage_test(self, rootname):
self._staged_called += 1
async def test_dirty_status_after_new_stage(self):
await omni.kit.stage_templates.new_stage_async(template="sunflowers")
self.assertFalse(omni.usd.get_context().has_pending_edit())
# Puts some delay to make sure no pending events to handle.
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
self.assertFalse(omni.usd.get_context().has_pending_edit())
async def test_command_new_stage(self):
# check template already exists
item = omni.kit.stage_templates.get_stage_template(self._stage_name)
self.assertTrue(item == None)
# add new template
omni.kit.stage_templates.register_template(self._stage_name, self.new_stage_test, 0)
# check new template exists
item = omni.kit.stage_templates.get_stage_template(self._stage_name)
self.assertTrue(item != None)
self.assertTrue(item[0] == self._stage_name)
self.assertTrue(item[1] == self.new_stage_test)
# run template & check was called once
await omni.kit.stage_templates.new_stage_async(self._stage_name)
self.assertTrue(self._staged_called == 1)
stage = omni.usd.get_context().get_stage()
settings = carb.settings.get_settings()
default_prim_name = settings.get("/persistent/app/stage/defaultPrimName")
rootname = f"/{default_prim_name}"
# create cube
cube_path = omni.usd.get_stage_next_free_path(stage, "{}/Cube".format(rootname), False)
omni.kit.commands.execute(
"CreatePrim",
prim_path=cube_path,
prim_type="Cube",
select_new_prim=False,
attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]},
)
prim = stage.GetPrimAtPath(cube_path)
self.assertTrue(prim, "Cube Prim exists")
# create sphere
sphere_path = omni.usd.get_stage_next_free_path(stage, "{}/Sphere".format(rootname), False)
omni.kit.commands.execute("CreatePrim", prim_path=sphere_path, prim_type="Sphere", select_new_prim=False)
prim = stage.GetPrimAtPath(sphere_path)
self.assertTrue(prim, "Sphere Prim exists")
# delete template
omni.kit.stage_templates.unregister_template(self._stage_name)
item = omni.kit.stage_templates.get_stage_template(self._stage_name)
self.assertTrue(item == None)
| 2,881 | Python | 38.479452 | 113 | 0.646303 |
omniverse-code/kit/exts/omni.kit.stage_templates/omni/kit/stage_templates/tests/test_preferences.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 carb
import omni.usd
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
# duplicate of kit\source\extensions\omni.kit.window.preferences\python\omni\kit\window\preferences\tests\test_pages.py
# added here for coverage
class PreferencesTestPages(AsyncTestCase):
# Before running each test
async def setUp(self):
omni.kit.window.preferences.show_preferences_window()
async def test_show_pages(self):
pages = omni.kit.window.preferences.get_page_list()
page_names = [page._title for page in pages]
# is list alpha sorted. Don't compare with fixed list as members can change
self.assertEqual(page_names, sorted(page_names))
for page in pages:
omni.kit.window.preferences.select_page(page)
await ui_test.human_delay(50)
| 1,319 | Python | 40.249999 | 119 | 0.745262 |
omniverse-code/kit/exts/omni.kit.stage_templates/omni/kit/stage_templates/tests/test_templates.py | import asyncio
import unittest
import carb.settings
import omni.kit.app
import omni.kit.test
import omni.kit.stage_templates
# also see kit\source\extensions\omni.kit.menu.file\python\omni\kit\menu\file\tests\test_func_templates.py as simular test
# added here for coverage
class TestNewStageTemplates(omni.kit.test.AsyncTestCase):
async def setUp(self):
pass
async def tearDown(self):
pass
async def test_stage_template_empty(self):
await omni.kit.stage_templates.new_stage_async(template="empty")
# verify Empty stage
stage = omni.usd.get_context().get_stage()
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()]
self.assertTrue(prim_list == ['/World'])
async def test_stage_template_sunlight(self):
await omni.kit.stage_templates.new_stage_async(template="sunlight")
# verify Sunlight stage
stage = omni.usd.get_context().get_stage()
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()]
self.assertTrue(prim_list == ['/World', '/Environment', '/Environment/defaultLight'])
async def test_stage_template_default_stage(self):
await omni.kit.stage_templates.new_stage_async(template="default stage")
# verify Default stage
stage = omni.usd.get_context().get_stage()
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()]
self.assertTrue(set(prim_list) == set([
'/World', '/Environment', '/Environment/Sky',
'/Environment/DistantLight', '/Environment/Looks',
'/Environment/Looks/Grid', '/Environment/Looks/Grid/Shader',
'/Environment/ground', '/Environment/groundCollider']), prim_list)
async def test_stage_template_noname(self):
await omni.kit.stage_templates.new_stage_async()
# verify Empty stage
stage = omni.usd.get_context().get_stage()
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll()]
self.assertTrue(prim_list == ['/World'])
| 2,077 | Python | 36.781818 | 122 | 0.666346 |
omniverse-code/kit/exts/omni.kit.widget.inspector/config/extension.toml | [package]
title = "UI Inspector (Preview)"
description = "Inspect your UI Elements"
version = "1.0.3"
category = "Developer"
authors = ["NVIDIA"]
repository = ""
keywords = ["stage", "outliner", "scene"]
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
preview_image = "data/inspector_full.png"
icon = "data/clouseau.png"
[package.writeTarget]
kit = true
[dependencies]
"omni.ui" = {}
"omni.kit.pip_archive" = {}
[[native.library]]
path = "bin/${lib_prefix}omni.kit.widget.inspector${lib_ext}"
[[python.module]]
name = "omni.kit.widget.inspector"
[[test]]
args = []
stdoutFailPatterns.exclude = [
] | 616 | TOML | 18.281249 | 61 | 0.680195 |
omniverse-code/kit/exts/omni.kit.widget.inspector/omni/kit/widget/inspector/__init__.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.
##
"""
InspectorWidget
------
InspectorWidget provides a way to display Widget Internals
:class:`.InspectorWidget`
"""
# Import the ICef bindings right away
from ._inspector_widget import *
from .scripts.extension import *
| 664 | Python | 30.666665 | 77 | 0.778614 |
omniverse-code/kit/exts/omni.kit.widget.inspector/omni/kit/widget/inspector/scripts/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
import omni.ui
import omni.kit.app
import omni.kit.widget.inspector
class InspectorWidgetExtension(omni.ext.IExt):
def __init__(self):
super().__init__()
pass
def on_startup(self, ext_id):
pass
# extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id)
# omni.kit.widget.inspector.startup(extension_path)
def on_shutdown(self):
pass
# omni.kit.widget.inspector.shutdown()
| 939 | Python | 31.413792 | 100 | 0.724175 |
omniverse-code/kit/exts/omni.kit.widget.inspector/omni/kit/widget/inspector/tests/test_widget.py | import omni.kit.test
from omni.kit.widget.inspector import PreviewMode, InspectorWidget
import functools
class TestInspectorWidget(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._widget = InspectorWidget()
def test_widget_init(self):
self.assertTrue(self._widget)
def test_widget_get_set_widget(self):
widget = self._widget.widget
self.assertEqual(widget, None) # Check default
label = omni.ui.Label("Blah")
self._widget.widget = label
self.assertEqual(self._widget.widget, label)
def test_widget_get_set_preview(self):
preview_mode = self._widget.preview_mode
self.assertEqual(preview_mode, PreviewMode.WIREFRAME_AND_COLOR) # Check default
self._widget.preview_mode = PreviewMode.WIRE_ONLY
self.assertEqual(self._widget.preview_mode, PreviewMode.WIRE_ONLY)
def test_widget_get_set_selected_widget(self):
self.assertEqual(self._widget.selected_widget, None) # Check default
label = omni.ui.Label("Blah")
self._widget.selected_widget = label
self.assertEqual(self._widget.selected_widget, label)
def test_widget_get_set_start_depth(self):
start_depth = self._widget.start_depth
self.assertEqual(start_depth, 0) # Check default
self._widget.start_depth = 25
self.assertEqual(self._widget.start_depth, 25)
def test_widget_get_set_end_depth(self):
end_depth = self._widget.end_depth
self.assertEqual(end_depth, 65535) # Check default
self._widget.end_depth = 25
self.assertEqual(self._widget.end_depth, 25)
def test_widget_set_widget_changed_fn(self):
def selection_changed(the_list, widget):
the_list.append(widget)
the_list = []
self._widget.set_selected_widget_changed_fn(functools.partial(selection_changed, the_list))
label = omni.ui.Label("Blah")
self.assertTrue(len(the_list) == 0)
self._widget.selected_widget = label
self.assertTrue(len(the_list) == 1)
self.assertEqual(the_list[0], label)
def test_widget_set_preview_mode_changed_fn(self):
def preview_mode_value_changed(the_list, value):
the_list.append(value)
the_list = []
self._widget.set_preview_mode_change_fn(functools.partial(preview_mode_value_changed, the_list))
self.assertTrue(len(the_list) == 0)
self._widget.preview_mode = PreviewMode.WIRE_ONLY
self.assertTrue(len(the_list) == 1)
self.assertTrue(the_list[0] == PreviewMode.WIRE_ONLY)
| 2,603 | Python | 34.671232 | 104 | 0.659624 |
omniverse-code/kit/exts/omni.kit.widget.inspector/omni/kit/widget/inspector/tests/__init__.py | from .test_widget import *
| 27 | Python | 12.999994 | 26 | 0.740741 |
omniverse-code/kit/exts/omni.kit.widget.inspector/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.3] - 2022-10-17
### Changes
- New mode COLOR_NO_NAVIGATION
## [1.0.2] - 2022-05-16
### Changes
- Added tests
## [1.0.1] - 2021-11-24
### Changes
- Update to latest omni.ui_query
## [1.0.0] - 2021-10-07
- Initial Release
| 326 | Markdown | 16.210525 | 80 | 0.631902 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/usd_model_base.py | # Copyright (c) 2020-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 typing import List
import carb
import copy
import carb.profiler
import omni.kit.commands
import omni.kit.undo
import omni.timeline
import omni.usd
import omni.kit.notification_manager as nm
from omni.kit.usd.layers import get_layers, LayerEventType, get_layer_event_payload
from pxr import Ar, Gf, Sdf, Tf, Trace, Usd, UsdShade
from .control_state_manager import ControlStateManager
from .placeholder_attribute import PlaceholderAttribute
class UsdBase:
def __init__(
self,
stage: Usd.Stage,
object_paths: List[Sdf.Path],
self_refresh: bool,
metadata: dict = {},
change_on_edit_end: bool = False,
treat_array_entry_as_comp: bool = False,
**kwargs,
):
self._control_state_mgr = ControlStateManager.get_instance()
self._stage = stage
self._usd_context = None
self._object_paths = object_paths
self._object_paths_set = set(object_paths)
self._metadata = metadata
self._change_on_edit_end = change_on_edit_end
# Whether each array entry should be treated as a comp, if this property is of an array type.
# If set to True, each array entry will have ambiguous and different from default state checked. It may have
# huge perf impact if the array size is big.
# It is useful if you need to build each array entry as a single widget with mixed/non-default indicator
# an example would SdfAssetPathAttributeModel and _sdf_asset_path_array_builder
self._treat_array_entry_as_comp = treat_array_entry_as_comp
self._dirty = True
self._value = None # The value to be displayed on widget
self._has_default_value = False
self._default_value = None
self._real_values = [] # The actual values in usd, might be different from self._value if ambiguous.
self._connections = []
self._is_big_array = False
self._prev_value = None
self._prev_real_values = []
self._editing = 0
self._ignore_notice = False
self._ambiguous = False
# "comp" is the first dimension of an array (when treat_array_entry_as_comp is enabled) or vector attribute.
# - If attribute is non-array vector type, comp indexes into the vector itself. e.g. for vec3 type, comp=1 means
# the 2nd channel of the vector vec3[1].
# - If attribute is an array type:
# - When treat_array_entry_as_comp is enabled) is enabled:
# - If the attribute is an array of scalar (i.e. float[]), `comp`` is the entry index. e.g. for
# SdfAssetArray type, comp=1 means the 2nd path in the path array.
# - If the attribute is an array of vector (i.e. vec3f[]), `comp` only indexes the array entry, it does
# not support indexing into the channel of the vector within the array entry. i.e a "2D" comp is not
# supported yet.
# - When treat_array_entry_as_comp is enabled) is disabled:
# - comp is 0 and the entire array is treated as one scalar value.
#
# This applies to all `comp` related functionality in this model base.
self._comp_ambiguous = []
self._might_be_time_varying = False # Inaccurate named. It really means if timesamples > 0
self._timeline = omni.timeline.get_timeline_interface()
self._current_time = self._timeline.get_current_time()
self._timeline_sub = None
self._on_set_default_fn = None
self._soft_range_min = None
self._soft_range_max = None
# get soft_range userdata settings
attributes = self._get_attributes()
if attributes:
attribute = attributes[-1]
if isinstance(attribute, Usd.Attribute):
soft_range = attribute.GetCustomDataByKey("omni:kit:property:usd:soft_range_ui")
if soft_range:
self._soft_range_min = soft_range[0]
self._soft_range_max = soft_range[1]
# Hard range for the value. For vector type, range value is a float/int that compares against each component individually
self._min = kwargs.get("min", None)
self._max = kwargs.get("max", None)
# Invalid range
if self._min is not None and self._max is not None and self._min >= self._max:
self._min = self._max = None
# The state of the icon on the right side of the line with widgets
self._control_state = 0
# Callback when the control state is changing. We use it to redraw UI
self._on_control_state_changed_fn = None
# Callback when the value is reset. We use it to redraw UI
self._on_set_default_fn = None
# True if the attribute has the default value and the current value is not default
self._different_from_default = False
# Per component different from default
self._comp_different_from_default = []
# Whether the UsdModel should self register Tf.Notice or let UsdPropertiesWidget inform a property change
if self_refresh:
self._listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_usd_changed, self._stage)
else:
self._listener = None
# Notification handler to throttle notifications.
self._notification = None
usd_context = self._get_usd_context()
layers = get_layers(usd_context)
self._spec_locks_subscription = layers.get_event_stream().create_subscription_to_pop(
self._on_spec_locks_changed, name="Property USD"
)
@property
def control_state(self):
"""Returns the current control state, it's the icon on the right side of the line with widgets"""
return self._control_state
@property
def stage(self):
return self._stage
@property
def metadata(self):
return self._metadata
def update_control_state(self):
control_state, force_refresh = self._control_state_mgr.update_control_state(self)
# Redraw control state icon when the control state is changed
if self._control_state != control_state or force_refresh:
self._control_state = control_state
if self._on_control_state_changed_fn:
self._on_control_state_changed_fn()
def set_on_control_state_changed_fn(self, fn):
"""Callback that is called when control state is changed"""
self._on_control_state_changed_fn = fn
def set_on_set_default_fn(self, fn):
"""Callback that is called when value is reset"""
self._on_set_default_fn = fn
def clean(self):
self._notification = None
self._timeline_sub = None
self._stage = None
self._spec_locks_subscription = None
if self._listener:
self._listener.Revoke()
self._listener = None
def is_different_from_default(self) -> bool:
"""Returns True if the attribute has the default value and the current value is not default"""
self._update_value()
# soft_range has been overridden
if self._soft_range_min != None and self._soft_range_max != None:
return True
return self._different_from_default
def might_be_time_varying(self) -> bool:
self._update_value()
return self._might_be_time_varying
def is_ambiguous(self) -> bool:
self._update_value()
return self._ambiguous
def is_comp_ambiguous(self, index: int) -> bool:
self._update_value()
comp_len = len(self._comp_ambiguous)
if comp_len == 0 or index < 0:
return self.is_ambiguous()
if index < comp_len:
return self._comp_ambiguous[index]
return False
def is_array_type(self) -> bool:
return self._is_array_type()
def get_all_comp_ambiguous(self) -> List[bool]:
"""Empty array if attribute value is a scalar, check is_ambiguous instead"""
self._update_value()
return self._comp_ambiguous
def get_attribute_paths(self) -> List[Sdf.Path]:
return self._object_paths
def get_property_paths(self) -> List[Sdf.Path]:
return self.get_attribute_paths()
def get_connections(self):
return self._connections
def set_default(self, comp=-1):
"""Set the UsdAttribute default value if it exists in metadata"""
self.set_soft_range_userdata(None, None)
if self.is_different_from_default() is False or self._has_default_value is False:
if self._soft_range_min != None and self._soft_range_max != None:
if self._on_set_default_fn:
self._on_set_default_fn()
self.update_control_state()
return
current_time_code = self.get_current_time_code()
with omni.kit.undo.group():
# TODO clear timesample
# However, when a value is timesampled, the "default" button is overridden by timesampled button,
# so there's no way to invoke this function
for attribute in self._get_attributes():
if isinstance(attribute, Usd.Attribute):
current_value = attribute.Get(current_time_code)
if comp >= 0:
# OM-46294: Make a value copy to avoid changing with reference.
default_value = copy.copy(current_value)
default_value[comp] = self._default_value[comp]
else:
default_value = self._default_value
self._change_property(attribute.GetPath(), default_value, current_value)
# We just set all the properties to the same value, it's no longer ambiguous
self._ambiguous = False
self._comp_ambiguous.clear()
self._different_from_default = False
self._comp_different_from_default.clear()
if self._on_set_default_fn:
self._on_set_default_fn()
def _create_placeholder_attributes(self, attributes):
# NOTE: PlaceholderAttribute.CreateAttribute cannot throw exceptions
for index, attribute in enumerate(attributes):
if isinstance(attribute, PlaceholderAttribute):
self._editing += 1
attributes[index] = attribute.CreateAttribute()
self._editing -= 1
def set_value(self, value, comp: int = -1):
if self._min is not None:
if hasattr(value, "__len__"):
for i in range(len(value)):
if value[i] < self._min:
value[i] = self._min
else:
if value < self._min:
value = self._min
if self._max is not None:
if hasattr(value, "__len__"):
for i in range(len(value)):
if value[i] > self._max:
value[i] = self._max
else:
if value > self._max:
value = self._max
if not self._ambiguous and not any(self._comp_ambiguous) and value == self._value:
return False
if self.is_instance_proxy():
self._post_notification("Cannot edit attributes of instance proxy.")
self._update_value(True) # reset value
return False
if self.is_locked():
self._post_notification("Cannot edit locked attributes.")
self._update_value(True) # reset value
return False
if self._might_be_time_varying:
self._post_notification("Setting time varying attribute is not supported yet")
return False
self._value = value if comp == -1 else UsdBase.update_value_by_comp(value, self._value, comp)
attributes = self._get_attributes()
if len(attributes) == 0:
return False
self._create_placeholder_attributes(attributes)
if self._editing:
for i, attribute in enumerate(attributes):
self._ignore_notice = True
if comp == -1:
self._real_values[i] = self._value
if not self._change_on_edit_end:
attribute.Set(self._value)
else:
# Only update a single component of the value (for vector type)
value = self._real_values[i]
self._real_values[i] = self._update_value_by_comp(value, comp)
if not self._change_on_edit_end:
attribute.Set(value)
self._ignore_notice = False
else:
with omni.kit.undo.group():
for i, attribute in enumerate(attributes):
self._ignore_notice = True
# begin_edit is not called for certain widget (like Checkbox), issue the command directly
if comp == -1:
self._change_property(attribute.GetPath(), self._value, None)
else:
# Only update a single component of the value (for vector type)
value = self._real_values[i]
self._real_values[i] = self._update_value_by_comp(value, comp)
self._change_property(attribute.GetPath(), value, None)
self._ignore_notice = False
if comp == -1:
# We just set all the properties to the same value, it's no longer ambiguous
self._ambiguous = False
self._comp_ambiguous.clear()
else:
self._comp_ambiguous[comp] = False
self._ambiguous = any(self._comp_ambiguous)
if self._has_default_value:
self._comp_different_from_default = [False] * self._get_comp_num()
if comp == -1:
self._different_from_default = value != self._default_value
if self._different_from_default:
for comp in range(len(self._comp_different_from_default)):
self._comp_different_from_default[comp] = not self._compare_value_by_comp(
value, self._default_value, comp
)
else:
self._comp_different_from_default[comp] = not self._compare_value_by_comp(
value, self._default_value, comp
)
self._different_from_default = any(self._comp_different_from_default)
else:
self._different_from_default = False
self._comp_different_from_default.clear()
self.update_control_state()
return True
def _is_prev_same(self):
return self._prev_real_values == self._real_values
def begin_edit(self):
self._editing = self._editing + 1
self._prev_value = self._value
self._save_real_values_as_prev()
def end_edit(self):
self._editing = self._editing - 1
if self._is_prev_same():
return
attributes = self._get_attributes()
self._create_placeholder_attributes(attributes)
with omni.kit.undo.group():
self._ignore_notice = True
for i in range(len(attributes)):
attribute = attributes[i]
self._change_property(attribute.GetPath(), self._real_values[i], self._prev_real_values[i])
self._ignore_notice = False
# Set flags. It calls _on_control_state_changed_fn when the user finished editing
self._update_value(True)
def _post_notification(self, message):
if not self._notification or self._notification.dismissed:
status = nm.NotificationStatus.WARNING
self._notification = nm.post_notification(message, status=status)
carb.log_warn(message)
def _change_property(self, path: Sdf.Path, new_value, old_value):
# OM-75480: For props inside sesison layer, it will always change specs
# in the session layer to avoid shadowing. Why it needs to be def is that
# session layer is used for several runtime data for now as built-in cameras,
# MDL material params, and etc. Not all of them create runtime prims inside
# session layer. For those that are not defined inside session layer, we should
# avoid leaving delta inside other sublayers as they are shadowed and useless after
# stage close.
target_layer, _ = omni.usd.find_spec_on_session_or_its_sublayers(
self._stage, path.GetPrimPath(), lambda spec: spec.specifier == Sdf.SpecifierDef
)
if not target_layer:
target_layer = self._stage.GetEditTarget().GetLayer()
omni.kit.commands.execute(
"ChangeProperty", prop_path=path,
value=new_value, prev=old_value,
target_layer=target_layer,
usd_context_name=self._stage
)
def get_value_by_comp(self, comp: int):
self._update_value()
if comp == -1:
return self._value
return self._get_value_by_comp(self._value, comp)
def _save_real_values_as_prev(self):
# It's like copy.deepcopy but not all USD types support pickling (e.g. Gf.Quat*)
self._prev_real_values = [type(value)(value) for value in self._real_values]
def _get_value_by_comp(self, value, comp: int):
if value.__class__.__module__ == "pxr.Gf":
if value.__class__.__name__.startswith("Quat"):
if comp == 0:
return value.real
else:
return value.imaginary[comp - 1]
elif value.__class__.__name__.startswith("Matrix"):
dimension = len(value)
row = comp // dimension
col = comp % dimension
return value[row, col]
elif value.__class__.__name__.startswith("Vec"):
return value[comp]
else:
if comp < len(value):
return value[comp]
return None
def _update_value_by_comp(self, value, comp: int):
"""update value from self._value"""
return UsdBase.update_value_by_comp(self._value, value, comp)
@staticmethod
def update_value_by_comp(from_value, to_value, comp: int):
"""update value from from_value to to_value"""
if from_value.__class__.__module__ == "pxr.Gf":
if from_value.__class__.__name__.startswith("Quat"):
if comp == 0:
to_value.real = from_value.real
else:
imaginary = from_value.imaginary
imaginary[comp - 1] = from_value.imaginary[comp - 1]
to_value.SetImaginary(imaginary)
elif from_value.__class__.__name__.startswith("Matrix"):
dimension = len(from_value)
row = comp // dimension
col = comp % dimension
to_value[row, col] = from_value[row, col]
elif from_value.__class__.__name__.startswith("Vec"):
to_value[comp] = from_value[comp]
else:
to_value[comp] = from_value[comp]
return to_value
def _compare_value_by_comp(self, val1, val2, comp: int):
return self._get_value_by_comp(val1, comp) == self._get_value_by_comp(val2, comp)
def _get_comp_num(self):
# TODO any better wan than this??
# Checks if the value type is a vector type
if self._value.__class__.__module__ == "pxr.Gf":
if self._value.__class__.__name__.startswith("Quat"):
return 4
elif self._value.__class__.__name__.startswith("Matrix"):
mat_dimension = len(self._value)
return mat_dimension * mat_dimension
elif hasattr(self._value, "__len__"):
return len(self._value)
elif self._is_array_type() and self._treat_array_entry_as_comp:
return len(self._value)
return 0
@Trace.TraceFunction
def _on_usd_changed(self, notice, stage):
if stage != self._stage:
return
if self._editing > 0:
return
if self._ignore_notice:
return
for path in notice.GetResyncedPaths():
if path in self._object_paths_set:
self._set_dirty()
return
for path in notice.GetChangedInfoOnlyPaths():
if path in self._object_paths_set:
self._set_dirty()
return
def _on_dirty(self):
pass
def _set_dirty(self):
if self._editing > 0:
return
self._dirty = True
self._on_dirty()
def _get_type_name(self, obj=None):
if obj:
if hasattr(obj, "GetTypeName"):
return obj.GetTypeName()
elif hasattr(obj, "typeName"):
return obj.typeName
else:
return None
else:
type_name = self._metadata.get(Sdf.PrimSpec.TypeNameKey, "unknown type")
return Sdf.ValueTypeNames.Find(type_name)
def _is_array_type(self, obj=None):
type_name = self._get_type_name(obj)
if isinstance(type_name, Sdf.ValueTypeName):
return type_name.isArray
else:
return False
def _get_obj_type_default_value(self, obj):
type_name = self._get_type_name(obj)
if isinstance(type_name, Sdf.ValueTypeName):
return type_name.defaultValue
else:
return None
def _update_value(self, force=False):
return self._update_value_objects(force, self._get_attributes())
def _update_value_objects(self, force: bool, objects: list):
if (self._dirty or force) and self._stage:
with Ar.ResolverContextBinder(self._stage.GetPathResolverContext()):
with Ar.ResolverScopedCache():
carb.profiler.begin(1, "UsdBase._update_value_objects")
current_time_code = self.get_current_time_code()
self._might_be_time_varying = False
self._value = None
self._has_default_value = False
self._default_value = None
self._real_values.clear()
self._connections.clear()
self._ambiguous = False
self._comp_ambiguous.clear()
self._different_from_default = False
self._comp_different_from_default.clear()
for index, object in enumerate(objects):
value = self._read_value(object, current_time_code)
self._real_values.append(value)
if isinstance(object, Usd.Attribute):
self._might_be_time_varying = self._might_be_time_varying or object.GetNumTimeSamples() > 0
self._connections.append(
[conn for conn in object.GetConnections()] if object.HasAuthoredConnections() else []
)
# only need to check the first prim. All other prims are supposedly to be the same
if index == 0:
self._value = value
if self._value and self._is_array_type(object) and len(self._value) > 16:
self._is_big_array = True
comp_num = self._get_comp_num()
self._comp_ambiguous = [False] * comp_num
self._comp_different_from_default = [False] * comp_num
# Loads the default value
self._has_default_value, self._default_value = self._get_default_value(object)
elif self._value != value:
self._value = value
self._ambiguous = True
comp_num = len(self._comp_ambiguous)
if comp_num > 0:
for i in range(comp_num):
if not self._comp_ambiguous[i]:
self._comp_ambiguous[i] = not self._compare_value_by_comp(
value, self._real_values[0], i
)
if self._has_default_value:
comp_num = len(self._comp_different_from_default)
if comp_num > 0:
for i in range(comp_num):
if not self._comp_different_from_default[i]:
self._comp_different_from_default[i] = not self._compare_value_by_comp(
value, self._default_value, i
)
self._different_from_default |= any(self._comp_different_from_default)
else:
self._different_from_default |= value != self._default_value
self._dirty = False
self._timeline_sub = self._timeline.get_timeline_event_stream().create_subscription_to_pop(
self._on_timeline_event
)
self.update_control_state()
carb.profiler.end(1)
return True
return False
def _get_default_value(self, property):
default_values = {"xformOp:scale": (1.0, 1.0, 1.0), "visibleInPrimaryRay": True, "primvars:multimatte_id": -1}
if isinstance(property, Usd.Attribute):
prim = property.GetPrim()
if prim:
custom = property.GetCustomData()
if "default" in custom:
# This is not the standard USD way to get default.
return True, custom["default"]
elif "customData" in self._metadata:
# This is to fetch default value for custom property.
default_value = self._metadata["customData"].get("default", None)
if default_value:
return True, default_value
else:
prim_definition = prim.GetPrimDefinition()
prop_spec = prim_definition.GetSchemaPropertySpec(property.GetPath().name)
if prop_spec and prop_spec.default != None:
return True, prop_spec.default
if property.GetName() in default_values:
return True, default_values[property.GetName()]
# If we still don't find default value, use type's default value
value_type = property.GetTypeName()
default_value = value_type.defaultValue
return True, default_value
elif isinstance(property, PlaceholderAttribute):
return True, property.Get()
return False, None
def _get_attributes(self):
if not self._stage:
return []
attributes = []
if not self._stage:
return attributes
for path in self._object_paths:
prim = self._stage.GetPrimAtPath(path.GetPrimPath())
if prim:
attr = prim.GetAttribute(path.name)
if attr:
if not attr.IsHidden():
attributes.append(attr)
else:
attr = PlaceholderAttribute(name=path.name, prim=prim, metadata=self._metadata)
attributes.append(attr)
return attributes
def _get_objects(self):
objects = []
if not self._stage:
return objects
for path in self._object_paths:
obj = self._stage.GetObjectAtPath(path)
if obj and not obj.IsHidden():
objects.append(obj)
return objects
def _on_timeline_event(self, e):
if e.type == int(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED) or e.type == int(
omni.timeline.TimelineEventType.CURRENT_TIME_CHANGED
):
current_time = e.payload["currentTime"]
if current_time != self._current_time:
self._current_time = current_time
if self._might_be_time_varying:
self._set_dirty()
elif e.type == int(omni.timeline.TimelineEventType.TENTATIVE_TIME_CHANGED):
tentative_time = e.payload["tentativeTime"]
if tentative_time != self._current_time:
self._current_time = tentative_time
if self._might_be_time_varying:
self._set_dirty()
def _read_value(self, object: Usd.Object, time_code: Usd.TimeCode):
carb.profiler.begin(1, "UsdBase._read_value")
val = object.Get(time_code)
if val is None:
result, val = self._get_default_value(object)
if not result:
val = self._get_obj_type_default_value(object)
carb.profiler.end(1)
return val
def _on_spec_locks_changed(self, event: carb.events.IEvent):
payload = get_layer_event_payload(event)
if payload and payload.event_type == LayerEventType.SPECS_LOCKING_CHANGED:
self.update_control_state()
def _get_usd_context(self):
if not self._usd_context:
self._usd_context = omni.usd.get_context_from_stage(self._stage)
return self._usd_context
def set_locked(self, locked):
usd_context = self._get_usd_context()
if not usd_context:
carb.log_warn(f"Current stage is not attached to any usd context.")
return
if locked:
omni.kit.usd.layers.lock_specs(usd_context, self._object_paths, False)
else:
omni.kit.usd.layers.unlock_specs(usd_context, self._object_paths, False)
def is_instance_proxy(self):
if not self._object_paths:
return False
path = Sdf.Path(self._object_paths[0]).GetPrimPath()
prim = self._stage.GetPrimAtPath(path)
return prim and prim.IsInstanceProxy()
def is_locked(self):
usd_context = self._get_usd_context()
if not usd_context:
carb.log_warn(f"Current stage is not attached to any usd context.")
return
for path in self._object_paths:
if not omni.kit.usd.layers.is_spec_locked(usd_context, path):
return False
return True
def has_connections(self):
return bool(len(self._connections[-1]) > 0)
def get_value(self):
self._update_value()
return self._value
def get_current_time_code(self):
return Usd.TimeCode(omni.usd.get_frame_time_code(self._current_time, self._stage.GetTimeCodesPerSecond()))
def set_soft_range_userdata(self, soft_range_min, soft_range_max):
# set soft_range userdata settings
for attribute in self._get_attributes():
if isinstance(attribute, Usd.Attribute):
if soft_range_min == None and soft_range_max == None:
attribute.SetCustomDataByKey("omni:kit:property:usd:soft_range_ui", None)
else:
attribute.SetCustomDataByKey(
"omni:kit:property:usd:soft_range_ui", Gf.Vec2f(soft_range_min, soft_range_max)
)
self._soft_range_min = soft_range_min
self._soft_range_max = soft_range_max
| 32,333 | Python | 40.667526 | 129 | 0.561408 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/relationship.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 weakref
from functools import partial
from typing import Callable, List, Optional
import omni.kit.commands
import omni.ui as ui
from omni.kit.widget.stage import StageWidget
from pxr import Sdf
class SelectionWatch(object):
def __init__(self, stage, on_selection_changed_fn, filter_type_list, filter_lambda, tree_view=None):
self._stage = weakref.ref(stage)
self._last_selected_prim_paths = None
self._filter_type_list = filter_type_list
self._filter_lambda = filter_lambda
self._on_selection_changed_fn = on_selection_changed_fn
self._targets_limit = 0
if tree_view:
self.set_tree_view(tree_view)
def reset(self, targets_limit):
self._targets_limit = targets_limit
self.clear_selection()
def set_tree_view(self, tree_view):
self._tree_view = tree_view
self._tree_view.set_selection_changed_fn(self._on_widget_selection_changed)
self._last_selected_prim_paths = None
def clear_selection(self):
if not self._tree_view:
return
self._tree_view.model.update_dirty()
self._tree_view.selection = []
if self._on_selection_changed_fn:
self._on_selection_changed_fn([])
def _on_widget_selection_changed(self, selection):
stage = self._stage()
if not stage:
return
prim_paths = [str(item.path) for item in selection if item]
# Deselect instance proxy items if they were selected
selection = [item for item in selection if item and not item.instance_proxy]
# Although the stage view has filter, you can still select the ancestor of filtered prims, which might not match the type.
if len(self._filter_type_list) != 0:
filtered_selection = []
for item in selection:
prim = stage.GetPrimAtPath(item.path)
if prim:
for type in self._filter_type_list:
if prim.IsA(type):
filtered_selection.append(item)
break
if filtered_selection != selection:
selection = filtered_selection
# or the ancestor might not match the lambda filter
if self._filter_lambda is not None:
selection = [item for item in selection if self._filter_lambda(stage.GetPrimAtPath(item.path))]
# Deselect if over the limit
if self._targets_limit > 0 and len(selection) > self._targets_limit:
selection = selection[: self._targets_limit]
if self._tree_view.selection != selection:
self._tree_view.selection = selection
prim_paths = [str(item.path) for item in selection]
if prim_paths == self._last_selected_prim_paths:
return
self._last_selected_prim_paths = prim_paths
if self._on_selection_changed_fn:
self._on_selection_changed_fn(self._last_selected_prim_paths)
def enable_filtering_checking(self, enable: bool):
"""
It is used to prevent selecting the prims that are filtered out but
still displayed when such prims have filtered children. When `enable`
is True, SelectionWatch should consider filtering when changing Kit's
selection.
"""
pass
def set_filtering(self, filter_string: Optional[str]):
pass
class RelationshipTargetPicker:
def __init__(
self, stage, relationship_widget, filter_type_list, filter_lambda, on_add_targets: Optional[Callable] = None
):
self._weak_stage = weakref.ref(stage)
self._relationship_widget = relationship_widget
self._filter_lambda = filter_lambda
self._selected_paths = []
self._filter_type_list = filter_type_list
self._on_add_targets = on_add_targets
def on_window_visibility_changed(visible):
if not visible:
self._stage_widget.open_stage(None)
else:
# Only attach the stage when picker is open. Otherwise the Tf notice listener in StageWidget kills perf
self._stage_widget.open_stage(self._weak_stage())
self._window = ui.Window(
"Select Target(s)",
width=400,
height=400,
visible=False,
flags=0,
visibility_changed_fn=on_window_visibility_changed,
)
with self._window.frame:
with ui.VStack():
with ui.Frame():
self._stage_widget = StageWidget(None, columns_enabled=["Type"])
self._selection_watch = SelectionWatch(
stage=stage,
on_selection_changed_fn=self._on_selection_changed,
filter_type_list=filter_type_list,
filter_lambda=filter_lambda,
)
self._stage_widget.set_selection_watch(self._selection_watch)
def on_select(weak_self):
weak_self = weak_self()
if not weakref:
return
pending_add = []
for relationship in weak_self._relationship_widget._relationships:
if relationship:
existing_targets = relationship.GetTargets()
for selected_path in weak_self._selected_paths:
selected_path = Sdf.Path(selected_path)
if selected_path not in existing_targets:
pending_add.append((relationship, selected_path))
if len(pending_add):
omni.kit.undo.begin_group()
for add in pending_add:
omni.kit.commands.execute("AddRelationshipTarget", relationship=add[0], target=add[1])
omni.kit.undo.end_group()
if self._on_add_targets:
self._on_add_targets(pending_add)
weak_self._window.visible = False
with ui.VStack(
height=0, style={"Button.Label:disabled": {"color": 0xFF606060}}
): # TODO consolidate all styles
self._label = ui.Label("Selected Path(s):\n\tNone")
self._button = ui.Button(
"Add",
height=10,
clicked_fn=partial(on_select, weak_self=weakref.ref(self)),
enabled=False,
identifier="add_button"
)
def clean(self):
self._window.set_visibility_changed_fn(None)
self._window = None
self._selection_watch = None
self._stage_widget.open_stage(None)
self._stage_widget.destroy()
self._stage_widget = None
self._filter_type_list = None
self._filter_lambda = None
self._on_add_targets = None
def show(self, targets_limit):
self._targets_limit = targets_limit
self._selection_watch.reset(targets_limit)
self._window.visible = True
if self._filter_lambda is not None:
self._stage_widget._filter_by_lambda({"relpicker_filter": self._filter_lambda}, True)
if self._filter_type_list:
self._stage_widget._filter_by_type(self._filter_type_list, True)
self._stage_widget.update_filter_menu_state(self._filter_type_list)
def _on_selection_changed(self, paths):
self._selected_paths = paths
if self._button:
self._button.enabled = len(self._selected_paths) > 0
if self._label:
text = "\n\t".join(self._selected_paths)
label_text = "Selected Path(s)"
if self._targets_limit > 0:
label_text += f" ({len(self._selected_paths)}/{self._targets_limit})"
label_text += f":\n\t{text if len(text) else 'None'}"
self._label.text = label_text
class RelationshipEditWidget:
def __init__(self, stage, attr_name, prim_paths, additional_widget_kwargs=None):
self._id_name = f"{prim_paths[-1]}_{attr_name}".replace('/', '_')
self._relationships = [stage.GetPrimAtPath(path).GetRelationship(attr_name) for path in prim_paths]
self._additional_widget_kwargs = additional_widget_kwargs if additional_widget_kwargs else {}
self._targets_limit = self._additional_widget_kwargs.get("targets_limit", 0)
self._button = None
self._target_picker = RelationshipTargetPicker(
stage,
self,
self._additional_widget_kwargs.get("target_picker_filter_type_list", []),
self._additional_widget_kwargs.get("target_picker_filter_lambda", None),
self._additional_widget_kwargs.get("target_picker_on_add_targets", None),
)
self._frame = ui.Frame()
self._frame.set_build_fn(self._build)
self._on_remove_target = self._additional_widget_kwargs.get("on_remove_target", None)
self._enabled = self._additional_widget_kwargs.get("enabled", True)
self._shared_targets = None
def clean(self):
self._target_picker.clean()
self._target_picker = None
self._frame = None
self._button = None
self._label = None
self._on_remove_target = None
self._enabled = True
def is_ambiguous(self) -> bool:
return self._shared_targets is None
def get_all_comp_ambiguous(self) -> List[bool]:
return []
def get_relationship_paths(self) -> List[Sdf.Path]:
return [rel.GetPath() for rel in self._relationships]
def get_property_paths(self) -> List[Sdf.Path]:
return self.get_relationship_paths()
def get_targets(self) -> List[Sdf.Path]:
return self._shared_targets
def set_targets(self, targets: List[Sdf.Path]):
with omni.kit.undo.group():
for relationship in self._relationships:
if relationship:
omni.kit.commands.execute("SetRelationshipTargets", relationship=relationship, targets=targets)
def set_value(self, targets: List[Sdf.Path]):
self.set_targets(targets)
def _build(self):
self._shared_targets = None
for relationship in self._relationships:
targets = relationship.GetTargets()
if self._shared_targets is None:
self._shared_targets = targets
elif self._shared_targets != targets:
self._shared_targets = None
break
with ui.VStack(spacing=2):
if self._shared_targets is not None:
for target in self._shared_targets:
with ui.HStack(spacing=2):
ui.StringField(name="models", read_only=True).model.set_value(target.pathString)
def on_remove_target(weak_self, target):
weak_self = weak_self()
if weak_self:
with omni.kit.undo.group():
for relationship in weak_self._relationships:
if relationship:
omni.kit.commands.execute(
"RemoveRelationshipTarget", relationship=relationship, target=target
)
if self._on_remove_target:
self._on_remove_target(target)
ui.Button(
"-",
enabled=self._enabled,
width=ui.Pixel(14),
clicked_fn=partial(on_remove_target, weak_self=weakref.ref(self), target=target),
identifier=f"remove_relationship{target.pathString.replace('/', '_')}"
)
def on_add_target(weak_self):
weak_self = weak_self()
if weak_self:
weak_self._target_picker.show(weak_self._targets_limit - len(weak_self._shared_targets))
within_target_limit = self._targets_limit == 0 or len(self._shared_targets) < self._targets_limit
button = ui.Button(
"Add Target(s)",
width=ui.Pixel(30),
clicked_fn=partial(on_add_target, weak_self=weakref.ref(self)),
enabled=within_target_limit and self._enabled,
identifier=f"add_relationship{self._id_name}"
)
if not within_target_limit:
button.set_tooltip(
f"Targets limit of {self._targets_limit} has been reached. To add more target(s), remove current one(s) first."
)
else:
ui.StringField(name="models", read_only=True).model.set_value("Mixed")
def _set_dirty(self):
self._frame.rebuild()
| 13,672 | Python | 41.070769 | 135 | 0.559611 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/usd_property_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.
#
import asyncio
import traceback
from collections import defaultdict
from typing import Any, DefaultDict, Dict, List, Sequence, Set, Tuple
import carb
import carb.events
import carb.profiler
import omni.kit.app
import omni.kit.context_menu
import omni.ui as ui
import omni.usd
from omni.kit.window.property.templates import SimplePropertyWidget, build_frame_header
from pxr import Sdf, Tf, Trace, Usd
from .usd_model_base import UsdBase
from .usd_property_widget_builder import *
from .message_bus_events import ADDITIONAL_CHANGED_PATH_EVENT_TYPE
# Clipboard to store copied group properties
__properties_to_copy: Dict[Sdf.Path, Any] = {}
def get_group_properties_clipboard():
return __properties_to_copy
def set_group_properties_clipboard(properties_to_copy: Dict[Sdf.Path, Any]):
global __properties_to_copy
__properties_to_copy = properties_to_copy
class UsdPropertyUiEntry:
def __init__(
self,
prop_name: str,
display_group: str,
metadata,
property_type,
build_fn=None,
display_group_collapsed: bool = False,
prim_paths: List[Sdf.Path] = None,
):
"""
Constructor.
Args:
prop_name: name of the Usd Property. This is not the display name.
display_group: group of the Usd Property when displayed on UI.
metadata: metadata associated with the Usd Property.
property_type: type of the property. Either Usd.Property or Usd.Relationship.
build_fn: a custom build function to build the UI. If not None the default builder will not be used.
display_group_collapsed: if the display group should be collapsed. Group only collapses when ALL its contents request such.
prim_paths: to override what prim paths this property will be built upon. Leave it to None to use default (currently selected paths, or last selected path if multi-edit is off).
"""
self.prop_name = prop_name
self.display_group = display_group
self.display_group_collapsed = display_group_collapsed
self.metadata = metadata
self.property_type = property_type
self.prim_paths = prim_paths
self.build_fn = build_fn
def add_custom_metadata(self, key: str, value):
"""
If value is not None, add it to the custom data of the metadata using the specified key. Otherwise, remove that
key from the custom data.
Args:
key: the key that should containt the custom metadata value
value: the value that should be added to the custom metadata if not None
"""
custom_data = self.metadata.get(Sdf.PrimSpec.CustomDataKey, {})
if value is not None:
custom_data[key] = value
elif key in custom_data:
del custom_data[key]
self.metadata[Sdf.PrimSpec.CustomDataKey] = custom_data
def override_display_group(self, display_group: str, collapsed: bool = False):
"""
Overrides the display group of the property. It only affects UI and DOES NOT write back DisplayGroup metadata to USD.
Args:
display_group: new display group to override to.
collapsed: if the display group should be collapsed. Group only collapses when ALL its contents request such.
"""
self.display_group = display_group
self.display_group_collapsed = collapsed
def override_display_name(self, display_name: str):
"""
Overrides the display name of the property. It only affects UI and DOES NOT write back DisplayName metadata to USD.
Args:
display_group: new display group to override to.
"""
self.metadata[Sdf.PropertySpec.DisplayNameKey] = display_name
# for backward compatibility
def __getitem__(self, key):
if key == 0:
return self.prop_name
elif key == 1:
return self.display_group
elif key == 2:
return self.metadata
return None
@property
def attr_name(self):
return self.prop_name
@attr_name.setter
def attr_name(self, value):
self.prop_name = value
def get_nested_display_groups(self):
if len(self.display_group) == 0:
return []
# Per USD documentation nested display groups are separated by colon
return self.display_group.split(":")
def __eq__(self, other):
return (
type(self) == type(other)
and self.prop_name == other.prop_name
and self.display_group == other.display_group
and self._compare_metadata(self.metadata, other.metadata)
and self.property_type == other.property_type
and self.prim_paths == other.prim_paths
)
def _compare_metadata(self, meta1, meta2) -> bool:
ignored_metadata = {"default", "colorSpace"}
for key, value in meta1.items():
if key not in ignored_metadata and (key not in meta2 or meta2[key] != value):
return False
for key, value in meta2.items():
if key not in ignored_metadata and (key not in meta1 or meta1[key] != value):
return False
return True
class UiDisplayGroup:
def __init__(self, name):
self.name = name
self.sub_groups = DefaultDict()
self.props = []
class UsdPropertiesWidget(SimplePropertyWidget):
"""
UsdPropertiesWidget provides functionalities to automatically populates UsdProperties on given prim(s). The UI will
and models be generated according to UsdProperties's value type. Multi-prim editing works for shared Properties
between all selected prims if instantiated with multi_edit = True.
"""
def __init__(self, title: str, collapsed: bool, multi_edit: bool = True):
"""
Constructor.
Args:
title: title of the widget.
collapsed: whether the collapsable frame should be collapsed for this widget.
multi_edit: whether multi-editing is supported.
If False, properties will only be collected from the last selected prim.
If True, shared properties among all selected prims will be collected.
"""
super().__init__(title=title, collapsed=collapsed)
self._multi_edit = multi_edit
self._models = defaultdict(list)
self._message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
self._bus_sub = None
self._listener = None
self._pending_dirty_task = None
self._pending_dirty_paths = set()
self._group_menu_entries = []
def clean(self):
"""
See PropertyWidget.clean
"""
self.reset_models()
super().clean()
def reset(self):
"""
See PropertyWidget.reset
"""
self.reset_models()
super().reset()
def reset_models(self):
# models can be shared among multiple prims. Only clean once!
unique_models = set()
if self._models is not None:
for models in self._models.values():
for model in models:
unique_models.add(model)
for model in unique_models:
model.clean()
self._models = defaultdict(list)
if self._listener:
self._listener.Revoke()
self._listener = None
self._bus_sub = None
if self._pending_dirty_task is not None:
self._pending_dirty_task.cancel()
self._pending_dirty_task = None
self._pending_dirty_paths.clear()
for entry in self._group_menu_entries:
entry.release()
self._group_menu_entries.clear()
def get_additional_kwargs(self, ui_prop: UsdPropertyUiEntry):
"""
Override this function if you want to supply additional arguments when building the label or ui widget.
"""
additional_label_kwargs = None
additional_widget_kwargs = None
return additional_label_kwargs, additional_widget_kwargs
def build_property_item(self, stage, ui_prop: UsdPropertyUiEntry, prim_paths: List[Sdf.Path]):
"""
Override this function to customize property building.
"""
# override prim paths to build if UsdPropertyUiEntry specifies one
if ui_prop.prim_paths:
prim_paths = ui_prop.prim_paths
build_fn = ui_prop.build_fn if ui_prop.build_fn else UsdPropertiesWidgetBuilder.build
additional_label_kwargs, additional_widget_kwargs = self.get_additional_kwargs(ui_prop)
models = build_fn(
stage,
ui_prop.prop_name,
ui_prop.metadata,
ui_prop.property_type,
prim_paths,
additional_label_kwargs,
additional_widget_kwargs,
)
if models:
if not isinstance(models, list):
models = [models]
for model in models:
for prim_path in prim_paths:
self._models[prim_path.AppendProperty(ui_prop.prop_name)].append(model)
def build_nested_group_frames(self, stage, display_group: UiDisplayGroup):
"""
Override this function to build group frames differently.
"""
if self._multi_edit:
prim_paths = self._payload.get_paths()
else:
prim_paths = self._payload[-1:]
def build_props(props):
collapse_frame = len(props) > 0
# we need to build those property in 2 different possible locations
for prop in props:
self.build_property_item(stage, prop, prim_paths)
collapse_frame &= prop.display_group_collapsed
return collapse_frame
def get_sub_props(group: UiDisplayGroup, sub_prop_list: list):
if len(group.sub_groups) > 0:
for name, sub_group in group.sub_groups.items():
for sub_prop in sub_group.props:
sub_prop_list.append(sub_prop)
get_sub_props(sub_group, sub_prop_list)
def build_nested(display_group: UiDisplayGroup, level: int, prefix: str):
# Only create a collapsable frame if the group is not "" (for root level group)
if len(display_group.name) > 0:
id = prefix + ":" + display_group.name
frame = ui.CollapsableFrame(
title=display_group.name,
build_header_fn=lambda collapsed, text, id=id: self._build_frame_header(collapsed, text, id),
name="subFrame",
)
else:
id = prefix
frame = ui.Frame(name="subFrame")
prop_list = []
sub_props = get_sub_props(display_group, prop_list)
with frame:
with ui.VStack(height=0, spacing=5, name="frame_v_stack"):
for name, sub_group in display_group.sub_groups.items():
build_nested(sub_group, level + 1, id)
# Only do "Extra Properties" for root level group
if len(display_group.sub_groups) > 0 and len(display_group.props) > 0 and level == 0:
extra_group_name = "Extra Properties"
extra_group_id = prefix + ":" + extra_group_name
with ui.CollapsableFrame(
title=extra_group_name,
build_header_fn=lambda collapsed, text, id=extra_group_id: self._build_frame_header(
collapsed, text, id
),
name="subFrame",
):
with ui.VStack(height=0, spacing=5, name="frame_v_stack"):
build_props(display_group.props)
self._build_header_context_menu(
group_name=extra_group_name, group_id=extra_group_id, props=sub_props
)
else:
collapse = build_props(display_group.props)
if collapse and isinstance(frame, ui.CollapsableFrame):
frame.collapsed = collapse
# if level is 0, this is the root level group, and we use the self._title for its name
self._build_header_context_menu(
group_name=display_group.name if level > 0 else self._title, group_id=id, props=sub_props
)
build_nested(display_group, 0, self._title)
# if we have subFrame we need the main frame to assume the groupFrame styling
if len(display_group.sub_groups) > 0:
# here we reach into the Parent class frame
self._collapsable_frame.name = "groupFrame"
def build_items(self):
"""
See SimplePropertyWidget.build_items
"""
self.reset()
if len(self._payload) == 0:
return
last_prim = self._get_prim(self._payload[-1])
if not last_prim:
return
stage = last_prim.GetStage()
if not stage:
return
self._listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_usd_changed, stage)
self._bus_sub = self._message_bus.create_subscription_to_pop_by_type(
ADDITIONAL_CHANGED_PATH_EVENT_TYPE, self._on_bus_event
)
shared_props = self._get_shared_properties_from_selected_prims(last_prim)
if not shared_props:
return
shared_props = self._customize_props_layout(shared_props)
grouped_props = UiDisplayGroup("")
for prop in shared_props:
nested_groups = prop.get_nested_display_groups()
sub_group = grouped_props
for sub_group_name in nested_groups:
sub_group = sub_group.sub_groups.setdefault(sub_group_name, UiDisplayGroup(sub_group_name))
sub_group.props.append(prop)
self.build_nested_group_frames(stage, grouped_props)
def _build_header_context_menu(self, group_name: str, group_id: str, props: List[UsdPropertyUiEntry] = None):
"""
Override this function to build the context menu when right click on a Collapsable group header
Args:
group_name: Display name of the group. If it's not a subgroup, it's the title of the widget.
group_id: A unique identifier for group context menu.
props: Properties under this group. It contains all properties in its subgroups as well.
"""
self._build_group_builtin_header_context_menu(group_name, group_id, props)
self._build_group_additional_header_context_menu(group_name, group_id, props)
def _build_group_builtin_header_context_menu(
self, group_name: str, group_id: str, props: List[UsdPropertyUiEntry] = None
):
from .usd_attribute_model import GfVecAttributeSingleChannelModel
prop_names: Set[str] = set()
if props:
for prop in props:
prop_names.add(prop.prop_name)
def can_copy(object):
# Only support single selection copy oer OM-20206
return len(self._payload) == 1
def on_copy(object):
visited_models = set()
properties_to_copy: Dict[Sdf.Path, Any] = dict()
for models in self._models.values():
for model in models:
if model in visited_models:
continue
visited_models.add(model)
# Skip "Mixed"
if model.is_ambiguous():
continue
paths = model.get_property_paths()
if paths:
# Copy from the last path
# In theory if the value is not mixed all paths should have same value, so which one to pick doesn't matter
last_path = paths[-1]
# Only copy from the properties from this group
if props is not None and last_path.name not in prop_names:
continue
if issubclass(type(model), UsdBase):
# No need to copy single channel model. Each vector attribute also has a GfVecAttributeModel
if isinstance(model, GfVecAttributeSingleChannelModel):
continue
properties_to_copy[paths[-1]] = model.get_value()
elif isinstance(model, RelationshipEditWidget):
properties_to_copy[paths[-1]] = model.get_targets().copy()
if properties_to_copy:
set_group_properties_clipboard(properties_to_copy)
menu = {
"name": f'Copy All Property Values in "{group_name}"',
"show_fn": lambda object: True,
"enabled_fn": can_copy,
"onclick_fn": on_copy,
}
self._group_menu_entries.append(self._register_header_context_menu_entry(menu, group_id))
def on_paste(object):
properties_to_copy = get_group_properties_clipboard()
if not properties_to_copy:
return
unique_model_prim_paths: Set[Sdf.Path] = set()
for prop_path in self._models:
unique_model_prim_paths.add(prop_path.GetPrimPath())
with omni.kit.undo.group():
try:
for path, value in properties_to_copy.items():
for prim_path in unique_model_prim_paths:
# Only paste to the properties in this group
if props is not None and path.name not in prop_names:
continue
paste_to_model_path = prim_path.AppendProperty(path.name)
models = self._models.get(paste_to_model_path, [])
for model in models:
if isinstance(model, GfVecAttributeSingleChannelModel):
continue
else:
model.set_value(value)
except Exception as e:
carb.log_warn(traceback.format_exc())
menu = {
"name": f'Paste All Property Values to "{group_name}"',
"show_fn": lambda object: True,
"enabled_fn": lambda object: get_group_properties_clipboard(),
"onclick_fn": on_paste,
}
self._group_menu_entries.append(self._register_header_context_menu_entry(menu, group_id))
def can_reset(object):
visited_models = set()
for models in self._models.values():
for model in models:
if model in visited_models:
continue
visited_models.add(model)
paths = model.get_property_paths()
if paths:
last_path = paths[-1]
# Only reset from the properties from this group
if props is not None and last_path.name not in prop_names:
continue
if issubclass(type(model), UsdBase):
if model.is_different_from_default():
return True
return False
def on_reset(object):
visited_models = set()
for models in self._models.values():
for model in models:
if model in visited_models:
continue
visited_models.add(model)
paths = model.get_property_paths()
if paths:
last_path = paths[-1]
# Only reset from the properties from this group
if props is not None and last_path.name not in prop_names:
continue
if issubclass(type(model), UsdBase):
model.set_default()
menu = {
"name": f'Reset All Property Values in "{group_name}"',
"show_fn": lambda object: True,
"enabled_fn": can_reset,
"onclick_fn": on_reset,
}
self._group_menu_entries.append(self._register_header_context_menu_entry(menu, group_id))
def _build_group_additional_header_context_menu(
self, group_name: str, group_id: str, props: List[UsdPropertyUiEntry] = None
):
"""
Override this function to build the additional context menu to Kit's built-in ones when right click on a Collapsable group header
Args:
group_name: Display name of the group. If it's not a subgroup, it's the title of the widget.
group_id: A unique identifier for group context menu.
props: Properties under this group. It contains all properties in its subgroups as well.
"""
...
def _register_header_context_menu_entry(self, menu: Dict, group_id: str):
"""
Registers a menu entry to Collapsable group header
Args:
menu: The menu entry to be registered.
group_id: A unique identifier for group context menu.
Return:
The subscription object of the menu entry to be kept alive during menu's life span.
"""
return omni.kit.context_menu.add_menu(menu, "group_context_menu." + group_id, "omni.kit.window.property")
def _filter_props_to_build(self, props):
"""
When deriving from UsdPropertiesWidget, override this function to filter properties to build.
Args:
props: List of Usd.Property on a selected prim.
"""
return [prop for prop in props if not prop.IsHidden()]
def _customize_props_layout(self, props):
"""
When deriving from UsdPropertiesWidget, override this function to reorder/regroup properties to build.
To reorder the properties display order, reorder entries in props list.
To override display group or name, call prop.override_display_group or prop.override_display_name respectively.
If you want to hide/add certain property, remove/add them to the list.
NOTE: All above changes won't go back to USD, they're pure UI overrides.
Args:
props: List of Tuple(property_name, property_group, metadata)
Example:
for prop in props:
# Change display group:
prop.override_display_group("New Display Group")
# Change display name (you can change other metadata, it won't be write back to USD, only affect UI):
prop.override_display_name("New Display Name")
# add additional "property" that doesn't exist.
props.append(UsdPropertyUiEntry("PlaceHolder", "Group", { Sdf.PrimSpec.TypeNameKey: "bool"}, Usd.Property))
"""
return props
@Trace.TraceFunction
def _on_usd_changed(self, notice, stage):
carb.profiler.begin(1, "UsdPropertyWidget._on_usd_changed")
try:
if stage != self._payload.get_stage():
return
if not self._collapsable_frame:
return
if len(self._payload) == 0:
return
# Widget is pending rebuild, no need to check for dirty
if self._pending_rebuild_task is not None:
return
dirty_paths = set()
for path in notice.GetResyncedPaths():
if path in self._payload:
self.request_rebuild()
return
elif path.GetPrimPath() in self._payload:
prop = stage.GetPropertyAtPath(path)
# If prop is added or removed, rebuild frame
# TODO only check against the properties this widget cares about
if (not prop.IsValid()) != (self._models.get(path) is None):
self.request_rebuild()
return
# else trigger existing model to reload the value
else:
dirty_paths.add(path)
for path in notice.GetChangedInfoOnlyPaths():
dirty_paths.add(path)
self._pending_dirty_paths.update(dirty_paths)
if self._pending_dirty_task is None:
self._pending_dirty_task = asyncio.ensure_future(self._delayed_dirty_handler())
finally:
carb.profiler.end(1)
def _on_bus_event(self, event: carb.events.IEvent):
# TODO from C++?
# stage = event.payload["stage"]
# if stage != self._payload.get_stage():
# return
if not self._collapsable_frame:
return
if len(self._payload) == 0:
return
# Widget is pending rebuild, no need to check for dirty
if self._pending_rebuild_task is not None:
return
path = event.payload["path"]
self._pending_dirty_paths.add(Sdf.Path(path))
if self._pending_dirty_task is None:
self._pending_dirty_task = asyncio.ensure_future(self._delayed_dirty_handler())
def _get_prim(self, prim_path):
if prim_path:
stage = self._payload.get_stage()
if stage:
return stage.GetPrimAtPath(prim_path)
return None
def _get_shared_properties_from_selected_prims(self, anchor_prim):
shared_props_dict = None
if self._multi_edit:
prim_paths = self._payload.get_paths()
else:
prim_paths = self._payload[-1:]
for prim_path in prim_paths:
prim = self._get_prim(prim_path)
if not prim:
continue
props = self._filter_props_to_build(prim.GetProperties())
prop_dict = {}
for prop in props:
if prop.IsHidden():
continue
prop_dict[prop.GetName()] = UsdPropertyUiEntry(
prop.GetName(), prop.GetDisplayGroup(), prop.GetAllMetadata(), type(prop)
)
if shared_props_dict is None:
shared_props_dict = prop_dict
else:
# Find intersection of the dicts
intersect_shared_props = {}
for prop_name, prop_info in shared_props_dict.items():
if prop_dict.get(prop_name) == prop_info:
intersect_shared_props[prop_name] = prop_info
if len(intersect_shared_props) == 0:
# No intersection, nothing to build
# early return
return
shared_props_dict = intersect_shared_props
shared_props = list(shared_props_dict.values())
# Sort properties to PropertyOrder using the last selected object
order = anchor_prim.GetPropertyOrder()
shared_prop_order = []
shared_prop_unordered = []
for prop in shared_props:
if prop[0] in order:
shared_prop_order.append(prop[0])
else:
shared_prop_unordered.append(prop[0])
shared_prop_order.extend(shared_prop_unordered)
sorted(shared_props, key=lambda x: shared_prop_order.index(x[0]))
return shared_props
def request_rebuild(self):
# If widget is going to be rebuilt, _pending_dirty_task does not need to run.
if self._pending_dirty_task is not None:
self._pending_dirty_task.cancel()
self._pending_dirty_task = None
self._pending_dirty_paths.clear()
super().request_rebuild()
async def _delayed_dirty_handler(self):
while True:
# Do not refresh UI until visible/uncollapsed
if not self._collapsed:
break
await omni.kit.app.get_app().next_update_async()
# clear the pending dirty tasks BEFORE dirting model.
# dirtied model may trigger additional USD notice that needs to be scheduled.
self._pending_dirty_task = None
if self._pending_dirty_paths:
# Make a copy of the paths. It may change if USD edits are made during iteration
pending_dirty_paths = self._pending_dirty_paths.copy()
self._pending_dirty_paths.clear()
carb.profiler.begin(1, "UsdPropertyWidget._delayed_dirty_handler")
# multiple path can share the same model. Only dirty once!
dirtied_models = set()
for path in pending_dirty_paths:
models = self._models.get(path)
if models:
for model in models:
if model not in dirtied_models:
model._set_dirty()
dirtied_models.add(model)
carb.profiler.end(1)
class SchemaPropertiesWidget(UsdPropertiesWidget):
"""
SchemaPropertiesWidget only filters properties and only show the onces from a given IsA schema or applied API schema.
"""
def __init__(self, title: str, schema, include_inherited: bool):
"""
Constructor.
Args:
title (str): Title of the widgets on the Collapsable Frame.
schema: The USD IsA schema or applied API schema to filter properties.
include_inherited (bool): Whether the filter should include inherited properties.
"""
super().__init__(title, collapsed=False)
self._title = title
self._schema = schema
self._include_inherited = include_inherited
def on_new_payload(self, payload):
"""
See PropertyWidget.on_new_payload
"""
if not super().on_new_payload(payload):
return False
if not self._payload or len(self._payload) == 0:
return False
for prim_path in self._payload:
prim = self._get_prim(prim_path)
if not prim:
return False
is_api_schema = Usd.SchemaRegistry().IsAppliedAPISchema(self._schema)
if not (is_api_schema and prim.HasAPI(self._schema) or not is_api_schema and prim.IsA(self._schema)):
return False
return True
def _filter_props_to_build(self, props):
"""
See UsdPropertiesWidget._filter_props_to_build
"""
if len(props) == 0:
return props
if Usd.SchemaRegistry().IsMultipleApplyAPISchema(self._schema):
prim = props[0].GetPrim()
schema_instances = set()
schema_type_name = Usd.SchemaRegistry().GetSchemaTypeName(self._schema)
for schema in prim.GetAppliedSchemas():
if schema.startswith(schema_type_name):
schema_instances.add(schema[len(schema_type_name) + 1 :])
filtered_props = []
api_path_func_name = f"Is{schema_type_name}Path"
api_path_func = getattr(self._schema, api_path_func_name)
# self._schema.GetSchemaAttributeNames caches the query result in a static variable and any new instance
# token passed into it won't change the cached property names. This can potentially cause problems as other
# code calling same function with different instance name will get wrong result.
#
# There's any other function IsSchemaPropertyBaseName but it's not implemented on all applied schemas. (not
# implemented in a few PhysicsSchema, for example.
#
# if include_inherited is True, it returns SchemaTypeName:BaseName for properties, otherwise it only returns
# BaseName.
schema_attr_names = self._schema.GetSchemaAttributeNames(self._include_inherited, "")
for prop in props:
if prop.IsHidden():
continue
prop_path = prop.GetPath().pathString
for instance_name in schema_instances:
instance_seg = prop_path.find(":" + instance_name + ":")
if instance_seg != -1:
api_path = prop_path[0 : instance_seg + 1 + len(instance_name)]
if api_path_func(api_path):
base_name = prop_path[instance_seg + 1 + len(instance_name) + 1 :]
if base_name in schema_attr_names:
filtered_props.append(prop)
break
return filtered_props
else:
schema_attr_names = self._schema.GetSchemaAttributeNames(self._include_inherited)
return [prop for prop in props if prop.GetName() in schema_attr_names]
class MultiSchemaPropertiesWidget(UsdPropertiesWidget):
"""
MultiSchemaPropertiesWidget filters properties and only show the onces from a given IsA schema or schema subclass list.
"""
__known_api_schemas = set()
def __init__(
self,
title: str,
schema,
schema_subclasses: list,
include_list: list = [],
exclude_list: list = [],
api_schemas: Sequence[str] = None,
group_api_schemas: bool = False,
):
"""
Constructor.
Args:
title (str): Title of the widgets on the Collapsable Frame.
schema: The USD IsA schema or applied API schema to filter properties.
schema_subclasses (list): list of subclasses
include_list (list): list of additional schema named to add
exclude_list (list): list of additional schema named to remove
api_schemas (sequence): a sequence of AppliedAPI schema names that this widget handles
group_api_schemas (bool): whether to create default groupings for any AppliedSchemas on the Usd.Prim
"""
super().__init__(title=title, collapsed=False)
self._title = title
self._schema = schema
# create schema_attr_names
self._schema_attr_base = schema.GetSchemaAttributeNames(False)
for subclass in schema_subclasses:
self._schema_attr_base += subclass.GetSchemaAttributeNames(False)
self._schema_attr_base += include_list
self._schema_attr_base = set(self._schema_attr_base) - set(exclude_list)
# Setup the defaults for handling applied API schemas
self._applied_schemas = {}
self._schema_attr_names = None
self._group_api_schemas = group_api_schemas
# Save any custom Applied Schemas and mark them to be ignored when building default widget
self._custom_api_schemas = api_schemas
if self._custom_api_schemas:
MultiSchemaPropertiesWidget.__known_api_schemas.update(self._custom_api_schemas)
def __del__(self):
# Mark any custom Applied Schemas to start being handled by the defaut widget
if self._custom_api_schemas:
MultiSchemaPropertiesWidget.__known_api_schemas.difference_update(self._custom_api_schemas)
def clean(self):
"""
See PropertyWidget.clean
"""
self._applied_schemas = {}
self._schema_attr_names = None
super().clean()
def on_new_payload(self, payload):
"""
See PropertyWidget.on_new_payload
"""
if not super().on_new_payload(payload):
return False
if not self._payload or len(self._payload) == 0:
return False
used = []
schema_reg = Usd.SchemaRegistry()
self._applied_schemas = {}
# Build out our _schema_attr_names variable to include properties from the base schema and any applied schemas
self._schema_attr_names = self._schema_attr_base
for prim_path in self._payload:
prim = self._get_prim(prim_path)
if not prim or not prim.IsA(self._schema):
return False
# If the base-schema has requested auto-grouping of all Applied Schemas, handle that grouping now
if self._group_api_schemas:
# XXX: Should this be delayed until _customize_props_layout ?
for api_schema in prim.GetAppliedSchemas():
# Ignore any API schemas that are already registered as custom widgets
if api_schema in MultiSchemaPropertiesWidget.__known_api_schemas:
continue
# Skip over any API schemas that USD doesn't actually know about
prim_def = schema_reg.FindAppliedAPIPrimDefinition(api_schema)
if not prim_def:
continue
api_prop_names = prim_def.GetPropertyNames()
self._schema_attr_names = self._schema_attr_names.union(api_prop_names)
for api_prop in api_prop_names:
display_group = prim_def.GetPropertyMetadata(api_prop, "displayGroup")
prop_grouping = self._applied_schemas.setdefault(api_schema, {}).setdefault(display_group, [])
prop_grouping.append((api_prop, prim_def.GetPropertyMetadata(api_prop, "displayName")))
used += self._filter_props_to_build(prim.GetProperties())
return used
def _filter_props_to_build(self, props):
"""
See UsdPropertiesWidget._filter_props_to_build
"""
return [prop for prop in props if prop.GetName() in self._schema_attr_names and not prop.IsHidden()]
def _customize_props_layout(self, attrs):
# If no applied schemas, just use the base class' layout.
if not self._applied_schemas:
return super()._customize_props_layout(attrs)
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
# We can't really escape the parent group, so all default/base and applied-schemas will be common to a group
frame = CustomLayoutFrame(hide_extra=False)
with frame:
# Add all base properties at the top
base_attrs = [attr for attr in attrs if attr.prop_name in self._schema_attr_base]
if base_attrs:
with CustomLayoutGroup(self._title):
for attr in base_attrs:
CustomLayoutProperty(attr.prop_name, attr.display_group)
attr.override_display_group(self._title)
# Now create a master-group for each applied schema, and possibly sub-groups for it's properties
# Here's where we may want to actually escape the parent and create a totally new group
with frame:
for api_schema, api_schema_groups in self._applied_schemas.items():
with CustomLayoutGroup(api_schema):
for prop_group, props in api_schema_groups.items():
with CustomLayoutGroup(prop_group):
for prop in props:
CustomLayoutProperty(*prop)
return frame.apply(attrs)
class RawUsdPropertiesWidget(UsdPropertiesWidget):
MULTI_SELECTION_LIMIT_SETTING_PATH = "/persistent/exts/omni.kit.property.usd/raw_widget_multi_selection_limit"
MULTI_SELECTION_LIMIT_DO_NOT_ASK_SETTING_PATH = (
"/exts/omni.kit.property.usd/multi_selection_limit_do_not_ask" # session only, not persistent!
)
def __init__(self, title: str, collapsed: bool, multi_edit: bool = True):
super().__init__(title=title, collapsed=collapsed, multi_edit=multi_edit)
self._settings = carb.settings.get_settings()
self._settings.set_default(RawUsdPropertiesWidget.MULTI_SELECTION_LIMIT_DO_NOT_ASK_SETTING_PATH, False)
self._skip_multi_selection_protection = False
def on_new_payload(self, payload):
if not super().on_new_payload(payload):
return False
for prim_path in self._payload:
if not prim_path.IsPrimPath():
return False
self._skip_multi_selection_protection = False
return bool(self._payload and len(self._payload) > 0)
def build_impl(self):
# rebuild frame when frame is opened
super().build_impl()
self._collapsable_frame.set_collapsed_changed_fn(self._on_collapsed_changed)
def build_items(self):
# only show raw items if frame is open
if self._collapsable_frame and not self._collapsable_frame.collapsed:
if not self._multi_selection_protected():
super().build_items()
def _on_collapsed_changed(self, collapsed):
if not collapsed:
self.request_rebuild()
def _multi_selection_protected(self):
if self._no_multi_selection_protection_this_session():
return False
def show_all(do_not_ask: bool):
self._settings.set(RawUsdPropertiesWidget.MULTI_SELECTION_LIMIT_DO_NOT_ASK_SETTING_PATH, do_not_ask)
self._skip_multi_selection_protection = True
self.request_rebuild()
multi_select_limit = self._settings.get(RawUsdPropertiesWidget.MULTI_SELECTION_LIMIT_SETTING_PATH)
if multi_select_limit and len(self._payload) > multi_select_limit and not self._skip_multi_selection_protection:
ui.Separator()
ui.Label(
f"You have selected {len(self._payload)} Prims, to preserve fast performance the Raw Usd Properties Widget is not showing above the current limit of {multi_select_limit} Prims. Press the button below to show it anyway but expect potential performance penalty.",
width=omni.ui.Percent(100),
alignment=ui.Alignment.CENTER,
name="label",
word_wrap=True,
)
button = ui.Button("Skip Multi Selection Protection")
with ui.HStack(width=0):
checkbox = ui.CheckBox()
ui.Spacer(width=5)
ui.Label("Do not ask again for current session.", name="label")
button.set_clicked_fn(lambda: show_all(checkbox.model.get_value_as_bool()))
return True
return False
def _no_multi_selection_protection_this_session(self):
return self._settings.get(RawUsdPropertiesWidget.MULTI_SELECTION_LIMIT_DO_NOT_ASK_SETTING_PATH)
| 43,336 | Python | 39.38863 | 277 | 0.581595 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/property_preferences_page.py | import carb.settings
import omni.ui as ui
from omni.kit.window.preferences import PreferenceBuilder, SettingType, PERSISTENT_SETTINGS_PREFIX
class PropertyUsdPreferences(PreferenceBuilder):
def __init__(self):
super().__init__("Property Widgets")
def build(self):
with ui.VStack(height=0):
with self.add_frame("Property Window"):
with ui.VStack():
w = self.create_setting_widget(
"Large selections threshold. This prevents slowdown/stalls on large selections, after this number of prims is selected most of the property window will be hidden.\n\nSet to zero to disable this feature\n\n",
PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.usd/large_selection",
SettingType.INT,
height=20
)
w.identifier = "large_selection"
w = self.create_setting_widget(
"Raw Usd Properties Widget multi-selection limit. This prevents slowdown/stalls on large selections, after this number of prims is selected content of Raw Usd Properties Widget will be hidden.\n\nSet to zero to disable this feature\n\n",
PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.usd/raw_widget_multi_selection_limit",
SettingType.INT,
height=20
)
w.identifier = "raw_widget_multi_selection_limit"
| 1,536 | Python | 51.999998 | 261 | 0.599609 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/placeholder_attribute.py | import carb
from pxr import Sdf, Usd, UsdGeom, UsdShade
## this is a placeholder for Usd.Attribute as that class cannot be created unless attached to a prim
class PlaceholderAttribute:
def __init__(self, name, prim: Usd.Prim = None, metadata=None):
self._name = name
self._prim = prim
self._metadata = metadata if metadata else {}
def Get(self, time_code=0):
if self._metadata:
custom_data = self._metadata.get("customData")
if custom_data is not None and "default" in custom_data:
return custom_data["default"]
default = self._metadata.get("default")
if default is not None:
return default
carb.log_warn(f"PlaceholderAttribute.Get() customData.default or default not found in metadata")
return None
def GetPath(self):
if self._prim:
return self._prim.GetPath()
return None
def ValueMightBeTimeVarying(self):
return False
def GetMetadata(self, token):
if token in self._metadata:
return self._metadata[token]
return False
def GetAllMetadata(self):
return self._metadata
def GetPrim(self):
return self._prim
def CreateAttribute(self):
try:
if not self._name:
carb.log_warn(f"PlaceholderAttribute.CreateAttribute() error no attribute name")
return None
if not self._prim:
carb.log_warn(f"PlaceholderAttribute.CreateAttribute() error no target prim")
return None
type_name_key = self._metadata.get(Sdf.PrimSpec.TypeNameKey)
if not type_name_key:
carb.log_warn(f"PlaceholderAttribute.CreateAttribute() error TypeNameKey")
return None
type_name = Sdf.ValueTypeNames.Find(type_name_key)
if self._name.startswith("primvars:"):
pv = UsdGeom.PrimvarsAPI(self._prim)
attribute = UsdGeom.PrimvarsAPI(self._prim).CreatePrimvar(self._name[9:], type_name).GetAttr()
elif self._name.startswith("inputs:"):
shader = UsdShade.Shader(self._prim)
attribute = shader.CreateInput(self._name[7:], type_name).GetAttr()
else:
attribute = self._prim.CreateAttribute(self._name, type_name, custom=False)
filter = {"customData", "displayName", "displayGroup", "documentation"}
if attribute:
for key in self._metadata:
if key not in filter:
attribute.SetMetadata(key, self._metadata[key])
attribute.Set(self.Get())
return attribute
except Exception as exc:
carb.log_warn(f"PlaceholderAttribute.CreateAttribute() error {exc}")
return None
def HasAuthoredConnections(self):
return False
| 2,948 | Python | 33.694117 | 110 | 0.591927 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/widgets.py | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import weakref
from pathlib import Path
from typing import List
import carb
import omni.ext
import omni.kit.app
import omni.ui as ui
import omni.usd
from pxr import Sdf, UsdGeom
from .attribute_context_menu import AttributeContextMenu
from .control_state_manager import ControlStateManager
from .prim_path_widget import PrimPathWidget
from .prim_selection_payload import PrimSelectionPayload
ICON_PATH = ""
TEST_DATA_PATH = ""
class UsdPropertyWidgets(omni.ext.IExt):
def __init__(self):
self._registered = False
self._examples = None
self._selection_notifiers = []
def on_startup(self, ext_id):
manager = omni.kit.app.get_app().get_extension_manager()
extension_path = manager.get_extension_path(ext_id)
global ICON_PATH
ICON_PATH = Path(extension_path).joinpath("data").joinpath("icons")
global TEST_DATA_PATH
TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests")
self._selection_notifiers.append(SelectionNotifier()) # default context
self._usd_preferences = None
self._hooks = []
self._attribute_context_menu = AttributeContextMenu()
self._control_state_manager = ControlStateManager(ICON_PATH)
self._hooks.append(
manager.subscribe_to_extension_enable(
lambda _: self._register_widget(),
lambda _: self._unregister_widget(),
ext_name="omni.kit.window.property",
hook_name="omni.usd listener",
)
)
from .usd_property_widget_builder import UsdPropertiesWidgetBuilder
UsdPropertiesWidgetBuilder.startup()
manager = omni.kit.app.get_app().get_extension_manager()
self._hooks.append(
manager.subscribe_to_extension_enable(
on_enable_fn=lambda _: self._register_preferences(),
on_disable_fn=lambda _: self._unregister_preferences(),
ext_name="omni.kit.window.preferences",
hook_name="omni.kit.property.usd omni.kit.window.preferences listener",
)
)
def on_shutdown(self):
from .usd_property_widget_builder import UsdPropertiesWidgetBuilder
UsdPropertiesWidgetBuilder.shutdown()
self._control_state_manager.destory()
self._control_state_manager = None
self._attribute_context_menu.destroy()
self._attribute_context_menu = None
for notifier in self._selection_notifiers:
notifier.stop()
self._selection_notifiers.clear()
self._hooks = None
if self._registered:
self._unregister_widget()
self._unregister_preferences()
def _register_preferences(self):
from omni.kit.window.preferences import register_page
from .property_preferences_page import PropertyUsdPreferences
self._usd_preferences = omni.kit.window.preferences.register_page(PropertyUsdPreferences())
def _unregister_preferences(self):
if self._usd_preferences:
import omni.kit.window.preferences
omni.kit.window.preferences.unregister_page(self._usd_preferences)
self._usd_preferences = None
def _register_widget(self):
try:
import omni.kit.window.property as p
from .references_widget import PayloadReferenceWidget
from .usd_property_widget import RawUsdPropertiesWidget, UsdPropertiesWidget
from .variants_widget import VariantsWidget
w = p.get_window()
if w:
w.register_widget("prim", "path", PrimPathWidget())
w.register_widget("prim", "references", PayloadReferenceWidget())
w.register_widget("prim", "payloads", PayloadReferenceWidget(use_payloads=True))
w.register_widget("prim", "variants", VariantsWidget())
w.register_widget(
"prim", "attribute", RawUsdPropertiesWidget(title="Raw USD Properties", collapsed=True), False
)
# A few examples. Expected to be removed at some point.
# self._examples = Examples(w)
for notifier in self._selection_notifiers:
notifier.start()
notifier._notify_property_window() # force a refresh
self._registered = True
except Exception as exc:
carb.log_warn(f"error {exc}")
def _unregister_widget(self):
try:
import omni.kit.window.property as p
w = p.get_window()
if w:
for notifier in self._selection_notifiers:
notifier.stop()
w.unregister_widget("prim", "attribute")
w.unregister_widget("prim", "variants")
w.unregister_widget("prim", "references")
w.unregister_widget("prim", "payloads")
w.unregister_widget("prim", "path")
if self._examples:
self._examples.clean(w)
self._examples = None
self._registered = False
except Exception as e:
carb.log_warn(f"Unable to unregister omni.usd.widget: {e}")
class SelectionNotifier:
def __init__(self, usd_context_id="", property_window_context_id=""):
self._usd_context = omni.usd.get_context(usd_context_id)
self._selection = self._usd_context.get_selection()
self._property_window_context_id = property_window_context_id
def start(self):
self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop(
self._on_stage_event, name="omni.usd.widget"
)
def stop(self):
self._stage_event_sub = None
def _on_stage_event(self, event):
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED) or event.type == int(
omni.usd.StageEventType.CLOSING
):
self._notify_property_window()
def _notify_property_window(self):
import omni.kit.window.property as p
# TODO _property_window_context_id
w = p.get_window()
if w and self._usd_context:
stage = None
selected_paths = []
if self._usd_context.get_stage_state() == omni.usd.StageState.OPENED:
stage = weakref.ref(self._usd_context.get_stage())
selected_paths = [Sdf.Path(path) for path in self._selection.get_selected_prim_paths()]
payload = PrimSelectionPayload(stage, selected_paths)
w.notify("prim", payload)
class Examples: # pragma: no cover
"""
Examples of showing how to use PropertyWindow APIs.
"""
def __init__(self, w):
from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate
from .usd_property_widget import SchemaPropertiesWidget, UsdPropertiesWidget
# Example of PropertySchemeDelegate
class MeshWidget(SchemaPropertiesWidget):
def __init__(self):
super().__init__("Mesh", UsdGeom.Mesh, False)
def _group_helper(self, attr, group_prefix):
if attr.attr_name.startswith(group_prefix):
import re
attr.override_display_group(group_prefix.capitalize())
attr.override_display_name(re.sub(r"(\w)([A-Z])", r"\1 \2", attr.attr_name[len(group_prefix) :]))
return True
return False
def _filter_props_to_build(self, attrs):
schema_attr_names = self._schema.GetSchemaAttributeNames(self._include_inherited)
schema_attr_names.append("material:binding")
return [attr for attr in attrs if attr.GetName() in schema_attr_names]
# Example of how to use _customize_props_layout
def _customize_props_layout(self, attrs):
auto_arrange = False
if auto_arrange:
for attr in attrs:
if not self._group_helper(attr, "crease"):
if not self._group_helper(attr, "corner"):
if not self._group_helper(attr, "face"):
attr.override_display_group("Other")
return attrs
else:
from omni.kit.property.usd.usd_property_widget_builder import UsdPropertiesWidgetBuilder
from omni.kit.window.property.templates import (HORIZONTAL_SPACING, LABEL_HEIGHT, LABEL_WIDTH,
SimplePropertyWidget)
from .custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty
frame = CustomLayoutFrame(hide_extra=False)
with frame:
with CustomLayoutGroup("Face"):
CustomLayoutProperty("faceVertexCounts", "Vertex Counts")
CustomLayoutProperty("faceVertexIndices", "Vertex Indices")
with CustomLayoutGroup("Corner"):
CustomLayoutProperty("cornerIndices", "Indices")
CustomLayoutProperty("cornerSharpnesses", "Sharpnesses")
with CustomLayoutGroup("Crease"):
CustomLayoutProperty("creaseIndices", "Indices")
CustomLayoutProperty("creaseLengths", "Lengths")
with CustomLayoutGroup("CustomItems"):
with CustomLayoutGroup("Nested"):
def build_fn(
stage,
attr_name,
metadata,
property_type,
prim_paths: List[Sdf.Path],
additional_label_kwargs={},
additional_widget_kwarg={},
):
with ui.HStack(spacing=HORIZONTAL_SPACING):
UsdPropertiesWidgetBuilder._create_label(
"Cool Label", additional_label_kwargs={"tooltip": "Cool Tooltip"}
)
ui.Button("Cool Button")
with ui.HStack(spacing=HORIZONTAL_SPACING):
UsdPropertiesWidgetBuilder._create_label("Very Cool Label")
ui.Button("Super Cool Button")
CustomLayoutProperty(None, None, build_fn=build_fn)
return frame.apply(attrs)
def get_additional_kwargs(self, ui_attr):
if ui_attr[0] == "material:binding":
from pxr import UsdShade
return None, {"target_picker_filter_type_list": [UsdShade.Material], "targets_limit": 1}
return None, None
w.register_widget("prim", "mesh", MeshWidget())
def clean(self, w):
pass
| 11,778 | Python | 40.769503 | 117 | 0.569282 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/asset_filepicker.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
import asyncio
import os
import omni.usd
from typing import Tuple, Any, Callable
from functools import partial
from pxr import Sdf
import carb.settings
import omni.client
import omni.ui as ui
from omni.kit.window.file_importer import get_file_importer
from .usd_attribute_model import SdfAssetPathAttributeModel
DEFAULT_FILE_EXTS = ("*.*", "All Files")
def show_asset_file_picker(
title: str,
assign_value_fn: Callable[[Any, str], None],
model_weak,
stage_weak,
layer_weak=None,
file_exts: Tuple[Tuple[str, str]] = None,
frame=None,
multi_selection: bool = False,
on_selected_fn=None,
):
model = model_weak()
if not model:
return
navigate_to = None
fallback = None
if isinstance(model, SdfAssetPathAttributeModel):
navigate_to = model.get_resolved_path()
if navigate_to:
navigate_to = f"{omni.usd.correct_filename_case(os.path.dirname(navigate_to))}/{os.path.basename(navigate_to)}"
elif isinstance(model, ui.AbstractValueModel):
if not hasattr(model, "is_array_type") or not model.is_array_type():
navigate_to = model.get_value_as_string()
if navigate_to is None:
stage = stage_weak()
if stage and not stage.GetRootLayer().anonymous:
# If asset path is empty, open the USD rootlayer folder
# But only if filepicker didn't already have a folder remembered (thus fallback)
fallback = stage.GetRootLayer().identifier
if layer_weak:
layer = layer_weak()
if layer:
navigate_to = layer.ComputeAbsolutePath(navigate_to)
if navigate_to:
navigate_to = replace_query(navigate_to, None)
file_importer = get_file_importer()
if file_importer:
file_exts = None
if isinstance(model, SdfAssetPathAttributeModel):
custom_data = model.metadata.get(Sdf.PrimSpec.CustomDataKey, {})
file_exts_dict = custom_data.get("fileExts", {})
file_exts = tuple((key, value) for (key, value) in file_exts_dict.items())
if not file_exts:
file_exts = (DEFAULT_FILE_EXTS,)
def on_import(model_weak, stage_weak, filename, dirname, selections=[]):
paths = selections.copy()
if not paths:
# fallback to filename
paths.append(omni.client.combine_urls(dirname, filename))
# get_current_selections comes in random (?) order, it does not follow selection order. sort it so
# at least the result is ordered alphabetically.
paths.sort()
if not multi_selection:
paths = paths[-1:]
async def check_paths(paths):
for path in paths:
result, entry = await omni.client.stat_async(path)
if result == omni.client.Result.OK:
if (
file_exts
and file_exts != (DEFAULT_FILE_EXTS,)
and entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN
):
carb.log_warn("Please select a file, not a folder!")
return
else:
carb.log_warn(f"Selected file {path} does not exist!")
return
asyncio.ensure_future(check_paths(paths))
if on_selected_fn:
on_selected_fn(stage_weak, model_weak, "\n".join(paths), assign_value_fn, frame)
file_importer.show_window(
title=title,
import_button_label="Select",
import_handler=partial(on_import, model_weak, stage_weak),
file_extension_types=file_exts,
filename_url=navigate_to,
)
# fallback to a fallback directory if the filepicker dialog didn't have saved history
if fallback and not file_importer._dialog.get_current_directory():
file_importer._dialog.show(fallback)
def replace_query(url, new_query):
client_url = omni.client.break_url(url)
return omni.client.make_url(
scheme=client_url.scheme,
user=client_url.user,
host=client_url.host,
port=client_url.port,
path=client_url.path,
query=new_query,
fragment=client_url.fragment,
)
| 4,854 | Python | 34.181159 | 123 | 0.61166 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/variants_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.
#
from typing import List
import omni.kit.commands
import omni.ui as ui
from .usd_model_base import UsdBase
from pxr import Sdf, Usd
class VariantSetModel(ui.AbstractItemModel, UsdBase):
def __init__(self, stage: Usd.Stage, object_paths: List[Sdf.Path], variant_set_name: str, self_refresh: bool):
UsdBase.__init__(self, stage, object_paths, self_refresh, {})
ui.AbstractItemModel.__init__(self)
self._variant_set_name = variant_set_name
self._variant_names = []
self._current_index = ui.SimpleIntModel()
self._current_index.add_value_changed_fn(self._current_index_changed)
self._has_index = False
self._update_value()
self._has_index = True
def clean(self):
UsdBase.clean(self)
def get_item_children(self, item):
self._update_value()
return self._variant_names
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
def begin_edit(self, item):
UsdBase.begin_edit(self)
def end_edit(self, item):
UsdBase.end_edit(self)
def set_value(self, value, comp=-1):
# if one than one item selected then don't early exit as
# anchor might be same but others may not
if value == self._value and len(self._variant_names) == 1:
return
omni.kit.commands.execute(
"SelectVariantPrim",
prim_path=self._object_paths,
vset_name=self._variant_set_name,
var_name=value,
)
def _current_index_changed(self, model):
if not self._has_index:
return
index = model.as_int
if self.set_value(self._variant_names[index].model.get_value_as_string()):
self._item_changed(None)
def _update_variant_names(self):
self._variant_names = []
vset = self._get_variant_set()
if vset:
vnames = vset.GetVariantNames()
class AllowedTokenItem(ui.AbstractItem):
def __init__(self, name):
super().__init__()
self.model = ui.SimpleStringModel(name)
self._variant_names.append(AllowedTokenItem("")) # Empty variant
for name in vnames:
self._variant_names.append(AllowedTokenItem(name))
def _update_value(self, force=False):
if self._update_value_objects(force, self._get_objects()):
# TODO don't have to do this every time. Just needed when "VariantNames" actually changed
self._update_variant_names()
index = -1
for i in range(0, len(self._variant_names)):
if self._variant_names[i].model.get_value_as_string() == self._value:
index = i
if index != -1 and self._current_index.as_int != index:
self._current_index.set_value(index)
self._item_changed(None)
def _on_dirty(self):
self._item_changed(None)
def _read_value(self, object: Usd.Object, time_code: Usd.TimeCode):
vsets = object.GetVariantSets()
vset = vsets.GetVariantSet(self._variant_set_name)
return vset.GetVariantSelection()
def _get_variant_set(self):
prims = self._get_objects()
prim = prims[0] if len(prims) > 0 else None
if prim:
vsets = prim.GetVariantSets()
return vsets.GetVariantSet(self._variant_set_name)
return None
# Temporary commands. Expected to be moved when we have better support for variants
class SelectVariantPrimCommand(omni.kit.commands.Command):
def __init__(self, prim_path: str, vset_name: str, var_name: str, usd_context_name: str = ""):
self._usd_context = omni.usd.get_context(usd_context_name)
self._prim_path = prim_path if isinstance(prim_path, list) else [prim_path]
self._vset_name = vset_name
self._var_name = var_name
def do(self):
stage = self._usd_context.get_stage()
self._previous_selection = {}
for prim_path in self._prim_path:
prim = stage.GetPrimAtPath(prim_path)
vset = prim.GetVariantSets().GetVariantSet(self._vset_name)
self._previous_selection[prim_path] = vset.GetVariantSelection()
if self._var_name:
vset.SetVariantSelection(self._var_name)
else:
vset.ClearVariantSelection()
def undo(self):
stage = self._usd_context.get_stage()
for prim_path in self._prim_path:
prim = stage.GetPrimAtPath(prim_path)
vset = prim.GetVariantSets().GetVariantSet(self._vset_name)
if prim_path in self._previous_selection:
vset.SetVariantSelection(self._previous_selection[prim_path])
else:
vset.ClearVariantSelection()
self._previous_selection = {}
omni.kit.commands.register_all_commands_in_module(__name__)
| 5,447 | Python | 34.148387 | 115 | 0.615385 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/prim_selection_payload.py | import weakref
from typing import List
from pxr import Sdf, Usd
class PrimSelectionPayload:
def __init__(self, stage: weakref.ReferenceType(Usd.Stage), paths: List[Sdf.Path]):
self._stage = stage # weakref
self._payload = paths
self._ignore_large_selection_override = False
import omni.kit.property.usd
self._large_selection_count = omni.kit.property.usd.get_large_selection_count()
def __len__(self):
# Ignore payload if stage is not valid anymore
if self._stage is None or self._stage() is None:
return 0
return len(self._payload)
# Forward calls to list to keep backward compatibility/easy access
def __iter__(self):
return self._payload.__iter__()
def __getitem__(self, key):
return self._payload.__getitem__(key)
def __setitem__(self, key, value):
return self._payload.__setitem__(key, value)
def __delitem__(self, key):
return self._payload.__delitem__(key)
def __bool__(self):
return self._stage is not None and self._stage() is not None and len(self._payload) > 0
def get_stage(self):
return self._stage() if self._stage else None # weakref -> ref
def get_paths(self) -> List[Sdf.Path]:
return self._payload
def set_large_selection_override(self, state: bool):
self._ignore_large_selection_override = state
def get_large_selection_count(self):
return self._large_selection_count
def is_large_selection(self) -> bool:
if not self._ignore_large_selection_override:
return bool(self._large_selection_count and len(self._payload) > self._large_selection_count)
return False
| 1,724 | Python | 30.363636 | 105 | 0.635151 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/variants_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.
#
import omni.ui as ui
from .usd_property_widget import UsdPropertiesWidget
from .usd_property_widget_builder import UsdPropertiesWidgetBuilder
from .variants_model import VariantSetModel
from pxr import Tf, Usd
class VariantsWidget(UsdPropertiesWidget):
def __init__(self):
super().__init__(title="Variants", collapsed=False, multi_edit=False)
def reset(self):
if self._listener:
self._listener.Revoke()
self._listener = None
super().reset()
def on_new_payload(self, payload):
"""
See PropertyWidget.on_new_payload
"""
if not super().on_new_payload(payload):
return False
if not self._payload:
return False
for prim_path in self._payload:
prim = self._get_prim(prim_path)
if not prim:
return False
if not prim.HasVariantSets():
return False
return True
def build_items(self):
self.reset()
if len(self._payload) == 0:
return
last_prim = self._get_prim(self._payload[-1])
if not last_prim:
return
stage = last_prim.GetStage()
if not stage:
return
self._listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_usd_changed, stage)
vsets = last_prim.GetVariantSets()
set_names = set(vsets.GetNames())
# remove any lists elements that are not common
for prim_path in self._payload:
prim = self._get_prim(prim_path)
set_names = set_names & set(prim.GetVariantSets().GetNames())
with ui.VStack():
for name in set_names:
self._build_variant_set(stage, last_prim.GetPath(), name)
def _build_variant_set(self, stage, prim_path, name):
with ui.HStack():
UsdPropertiesWidgetBuilder._create_label(name)
model = VariantSetModel(stage, self._payload.get_paths(), name, False)
with ui.ZStack(alignment=ui.Alignment.CENTER):
combo_widget = ui.ComboBox(model)
combo_widget.identifier = f"combo_variant_{name.lower()}"
mixed_widget = UsdPropertiesWidgetBuilder._create_mixed_text_overlay()
mixed_widget.identifier = f"mixed_variant_{name.lower()}"
if model.is_ambiguous():
mixed_widget.visible = True
| 2,875 | Python | 31.314606 | 99 | 0.619478 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/prim_path_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.
#
import weakref
from functools import lru_cache
from typing import Callable
import carb
import omni.ui as ui
import omni.usd
from omni.kit.window.property.templates import HORIZONTAL_SPACING, LABEL_HEIGHT, LABEL_WIDTH, SimplePropertyWidget
from .add_attribute_popup import AddAttributePopup
from .context_menu import ContextMenu, ContextMenuEvent
from .prim_selection_payload import PrimSelectionPayload
g_singleton = None
@lru_cache()
def _get_plus_glyph():
return omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_context.svg")
class Constant:
def __setattr__(self, name, value):
raise Exception(f"Can't change Constant.{name}")
MIXED = "Mixed"
MIXED_COLOR = 0xFFCC9E61
LABEL_COLOR = 0xFF9E9E9E
LABEL_FONT_SIZE = 14
LABEL_WIDTH = 80
ADD_BUTTON_SIZE = 52
class ButtonMenuEntry:
def __init__(
self,
path: str,
glyph: str = None,
name_fn: Callable = None,
show_fn: Callable = None,
enabled_fn: Callable = None,
onclick_fn: Callable = None,
add_to_context_menu: bool = False,
):
self.path = path
self.glyph = glyph
self.name_fn = name_fn
self.show_fn = show_fn
self.enabled_fn = enabled_fn
self.onclick_fn = onclick_fn
if add_to_context_menu:
self.context_menu = omni.kit.context_menu.add_menu(self.get_context_menu(), "ADD", "")
else:
self.context_menu = None
def clean(self):
self.context_menu = None
def get_dict(self, payload, name=None):
data = {}
if name:
data = {"name": name}
else:
data = {"name": self.path}
data["glyph"] = self.glyph
if self.name_fn:
data["name_fn"] = self.name_fn
if self.show_fn:
data["show_fn"] = self.show_fn
if self.enabled_fn:
data["enabled_fn"] = self.enabled_fn
if self.onclick_fn:
data["onclick_fn"] = lambda o, p=payload: self.onclick_fn(payload=p)
return data
def get_context_menu(self):
menu_sublist = []
sublist = menu_sublist
parts = self.path.split("/")
if len(parts) > 1:
last_name = parts.pop()
first_name = parts.pop(0)
context_root = {'name': { first_name: []}}
context_item = context_root["name"][first_name]
while parts:
name = parts.pop(0)
context_item.append({'name': {name: []}})
context_item = context_item[0]["name"][name]
context_item.append({
"name": last_name,
"glyph": self.glyph,
"name_fn": self.name_fn,
"show_fn": self.show_fn,
"enabled_fn": self.enabled_fn,
"onclick_fn": lambda o, f=weakref.ref(
self.onclick_fn
) if self.onclick_fn else None: PrimPathWidget.payload_wrapper(
objects=o, onclick_fn_weak=f
),
})
return context_root
else:
context_item = {
"name": self.path,
"glyph": self.glyph,
"name_fn": self.name_fn,
"show_fn": self.show_fn,
"enabled_fn": self.enabled_fn,
"onclick_fn": lambda o, f=weakref.ref(
self.onclick_fn
) if self.onclick_fn else None: PrimPathWidget.payload_wrapper(objects=o, onclick_fn_weak=f),
}
return context_item
class PrimPathWidget(SimplePropertyWidget):
def __init__(self):
super().__init__(title="Path", collapsable=False)
self._context_menu = ContextMenu()
self._path_draw_items = []
self._button_menu_items = []
self._path_item_padding = 0.0
global g_singleton
g_singleton = self
self.add_path_item(self._build_prim_name_widget)
self.add_path_item(self._build_prim_path_widget)
# self.add_path_item(self._build_prim_stage_widget)
self.add_path_item(self._build_prim_instanceable_widget)
self.add_path_item(self._build_prim_large_selection_widget)
self._add_create_attribute_menu()
def __del__(self):
global g_singleton
g_singleton = None
def clean(self):
self._path_draw_items = []
if self._add_attribute_popup:
self._add_attribute_popup.destroy()
self._add_attribute_popup = None
super().clean()
def on_new_payload(self, payload):
if not super().on_new_payload(payload, ignore_large_selection=True):
return False
self._anchor_prim = None
stage = payload.get_stage()
instance = []
if stage:
for prim_path in payload:
prim = stage.GetPrimAtPath(prim_path)
if prim:
self._anchor_prim = prim
instance.append(prim.IsInstanceable())
self._show_instance = len(set(instance)) == 1
return payload and len(payload) > 0
@staticmethod
def payload_wrapper(objects, onclick_fn_weak):
onclick_fn = onclick_fn_weak()
if onclick_fn:
prim_paths = []
if "prim_list" in objects:
prim_paths = [prim.GetPath() for prim in objects["prim_list"]]
payload = PrimSelectionPayload(weakref.ref(objects["stage"]), prim_paths)
onclick_fn(payload=payload)
def build_items(self):
for item in self._path_draw_items:
item()
def _build_prim_name_widget(self):
from omni.kit.property.usd.usd_property_widget import get_ui_style
def get_names_as_string(prim_paths):
paths = ""
for index, path in enumerate(prim_paths):
paths += f"{path.name}\n"
return paths
prim_paths = self._payload
selected_info_name = "(nothing selected)"
stage = self._payload.get_stage()
tooltip = ""
if len(prim_paths) > 1:
selected_info_name = f"({len(prim_paths)} models selected) common attributes shown"
for index, path in enumerate(prim_paths):
tooltip += f"{path.name}\n"
if index > 9:
tooltip += f"...."
break
elif len(prim_paths) == 1:
selected_info_name = f"{prim_paths[0].name}"
with ui.HStack(height=0):
weakref_menu = weakref.ref(self._context_menu)
ui.Spacer(width=8)
button_width = Constant.ADD_BUTTON_SIZE
if get_ui_style() == "NvidiaLight":
button_width = Constant.ADD_BUTTON_SIZE + 25
add_button = ui.Button(f"{_get_plus_glyph()} Add", width=button_width, height=LABEL_HEIGHT, name="add")
add_button.set_mouse_pressed_fn(
lambda x, y, b, m, widget=add_button: self._on_mouse_pressed(b, weakref_menu, widget)
)
ui.Spacer(width=(Constant.LABEL_WIDTH + self._path_item_padding) - button_width)
ui.Spacer(width=8)
if get_ui_style() == "NvidiaLight":
ui.Spacer(width=10)
widget = ui.StringField(
name="prims_name", height=LABEL_HEIGHT, tooltip=tooltip, tooltip_offset_y=22, enabled=False
)
widget.model.set_value(selected_info_name)
widget.set_mouse_pressed_fn(
lambda x, y, b, m, model=widget.model: self._build_copy_menu(
buttons=b,
context_menu=weakref_menu,
copy_fn=lambda _: self._copy_to_clipboard(to_copy=get_names_as_string(prim_paths=prim_paths)),
)
)
def _build_prim_path_widget(self):
from omni.kit.property.usd.usd_property_widget import get_ui_style
def get_paths_as_string(prim_paths):
paths = ""
for index, path in enumerate(prim_paths):
paths += f"{path}\n"
return paths
prim_paths = self._payload
weakref_menu = weakref.ref(self._context_menu)
selected_info_name = ""
tooltip = ""
style = {}
if len(prim_paths) == 1:
selected_info_name = f"{prim_paths[0]}"
elif len(prim_paths) > 1:
selected_info_name = Constant.MIXED
style = {"Field": {"color": Constant.MIXED_COLOR}, "Tooltip": {"color": 0xFF333333}}
for index, path in enumerate(prim_paths):
tooltip += f"{path}\n"
if index > 9:
tooltip += f"...."
break
with ui.HStack(height=0):
ui.Spacer(width=8)
ui.Label(
"Prim Path",
name="path_label",
width=Constant.LABEL_WIDTH + self._path_item_padding,
height=LABEL_HEIGHT,
style={"font_size": Constant.LABEL_FONT_SIZE},
)
ui.Spacer(width=8)
if get_ui_style() == "NvidiaLight":
ui.Spacer(width=10)
widget = ui.StringField(
name="prims_path", height=LABEL_HEIGHT, enabled=False, tooltip=tooltip, tooltip_offset_y=22, style=style
)
widget.model.set_value(selected_info_name)
widget.set_mouse_pressed_fn(
lambda x, y, b, m: self._build_copy_menu(
buttons=b,
context_menu=weakref_menu,
copy_fn=lambda _: self._copy_to_clipboard(to_copy=get_paths_as_string(prim_paths=prim_paths)),
)
)
def _build_prim_stage_widget(self):
from omni.kit.property.usd.usd_property_widget import get_ui_style
stage_path = "unsaved"
stage = self._payload.get_stage()
weakref_menu = weakref.ref(self._context_menu)
if stage and stage.GetRootLayer() and stage.GetRootLayer().realPath:
stage_path = stage.GetRootLayer().realPath
with ui.HStack(height=0):
ui.Spacer(width=8)
ui.Label(
"Stage Path",
name="stage_label",
width=Constant.LABEL_WIDTH + self._path_item_padding,
height=LABEL_HEIGHT,
style={"font_size": Constant.LABEL_FONT_SIZE},
)
ui.Spacer(width=8)
widget = ui.StringField(name="prims_stage", height=LABEL_HEIGHT, enabled=False)
widget.model.set_value(stage_path)
widget.set_mouse_pressed_fn(
lambda x, y, b, m, model=widget.model: self._build_copy_menu(
buttons=b,
context_menu=weakref_menu,
copy_fn=lambda _: self._copy_to_clipboard(to_copy=model.as_string),
)
)
def _build_prim_instanceable_widget(self):
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder, get_ui_style
if not self._anchor_prim or not self._show_instance:
return
def on_instanceable_changed(model):
index = model.as_bool
stage = self._payload.get_stage()
for path in self._payload:
prim = stage.GetPrimAtPath(path)
if prim:
prim.SetInstanceable(model.as_bool)
self._collapsable_frame.rebuild()
additional_label_kwargs = {}
with ui.HStack(spacing=HORIZONTAL_SPACING):
settings = carb.settings.get_settings()
left_aligned = settings.get("ext/omni.kit.window.property/checkboxAlignment") == "left"
if not left_aligned:
additional_label_kwargs["width"] = 0
else:
additional_label_kwargs["width"] = (Constant.LABEL_WIDTH + self._path_item_padding) - 8
if get_ui_style() == "NvidiaLight":
additional_label_kwargs["word_wrap"] = False
ui.Spacer(width=3)
UsdPropertiesWidgetBuilder._create_label("Instanceable", {}, additional_label_kwargs)
if not left_aligned:
ui.Spacer(width=15)
else:
ui.Spacer(width=0)
with ui.VStack(width=10):
ui.Spacer()
check_box = ui.CheckBox(width=10, height=0, name="greenCheck")
check_box.model.set_value(self._anchor_prim.IsInstanceable())
check_box.model.add_value_changed_fn(on_instanceable_changed)
ui.Spacer()
if left_aligned:
ui.Spacer(width=5)
def _build_prim_large_selection_widget(self):
def show_all():
if self._payload:
self._payload.set_large_selection_override(True)
property_window = omni.kit.window.property.get_window()
if property_window:
property_window.request_rebuild()
if self._payload.is_large_selection():
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder
ui.Separator()
UsdPropertiesWidgetBuilder._create_label(
f"You have selected {len(self._payload)} Prims, to preserve fast performance the Property Widget is not showing above the current limit of {self._payload.get_large_selection_count()} Prims. Press the button below to show it anyway but expect it to take some time",
{},
additional_label_kwargs={"width": omni.ui.Percent(100), "alignment": ui.Alignment.CENTER},
)
ui.Button("Skip Large Selection Protection", clicked_fn=lambda: show_all())
def _add_create_attribute_menu(self):
self._add_attribute_popup = AddAttributePopup()
self.add_button_menu_entry(
"Attribute",
show_fn=lambda objects, weak_self=weakref.ref(self): weak_self()._add_attribute_popup.show_fn(objects)
if weak_self()
else None,
onclick_fn=lambda payload, weak_self=weakref.ref(self): weak_self()._add_attribute_popup.click_fn(payload)
if weak_self()
else None,
)
def _on_mouse_pressed(self, button, context_menu, widget):
"""Called when the user press the mouse button on the item"""
if button != 0:
# It's for LMB menu only
return
if not context_menu():
return
# Show the menu
xpos = (int)(widget.screen_position_x)
ypos = (int)(widget.screen_position_y + widget.computed_content_height)
context_menu().on_mouse_event(ContextMenuEvent(self._payload, self._button_menu_items, xpos, ypos))
def _build_copy_menu(self, buttons, context_menu, copy_fn):
if buttons != 1:
# It's for right mouse button for menu only
return
if not context_menu():
return
# setup menu
menu_list = [{"name": "Copy to clipboard", "glyph": "menu_link.svg", "onclick_fn": copy_fn}]
# show menu
context_menu().show_context_menu(menu_list=menu_list)
def _copy_to_clipboard(self, to_copy):
omni.kit.clipboard.copy(to_copy)
@staticmethod
def add_button_menu_entry(
path: str,
glyph: str = None,
name_fn=None,
show_fn: Callable = None,
enabled_fn: Callable = None,
onclick_fn: Callable = None,
add_to_context_menu: bool = True,
):
item = None
if g_singleton:
item = ButtonMenuEntry(path, glyph, name_fn, show_fn, enabled_fn, onclick_fn, add_to_context_menu)
g_singleton._button_menu_items.append(item)
else:
carb.log_error(f"PrimPathWidget not initalized")
return item
@staticmethod
def remove_button_menu_entry(item: ButtonMenuEntry):
if g_singleton:
g_singleton._button_menu_items.remove(item)
item.clean()
else:
carb.log_error(f"PrimPathWidget not initalized")
@staticmethod
def get_button_menu_entries():
if g_singleton:
return g_singleton._button_menu_items
else:
carb.log_error(f"PrimPathWidget not initalized")
@staticmethod
def add_path_item(draw_fn: Callable):
if g_singleton:
g_singleton._path_draw_items.append(draw_fn)
else:
carb.log_error(f"PrimPathWidget not initalized")
@staticmethod
def remove_path_item(draw_fn: Callable):
if g_singleton:
g_singleton._path_draw_items.remove(draw_fn)
else:
carb.log_error(f"PrimPathWidget not initalized")
@staticmethod
def get_path_items():
if g_singleton:
return g_singleton._path_draw_items
else:
carb.log_error(f"PrimPathWidget not initalized")
@staticmethod
def rebuild():
if g_singleton:
if g_singleton._collapsable_frame:
g_singleton._collapsable_frame.rebuild()
else:
carb.log_error(f"PrimPathWidget not initalized")
@staticmethod
def set_path_item_padding(padding: float):
if g_singleton:
g_singleton._path_item_padding = padding
else:
carb.log_error(f"PrimPathWidget not initalized")
@staticmethod
def get_path_item_padding(padding: float):
if g_singleton:
return g_singleton._path_item_padding
else:
carb.log_error(f"PrimPathWidget not initalized")
return 0.0
| 18,264 | Python | 35.53 | 280 | 0.559735 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/__init__.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .widgets import *
from .message_bus_events import *
def get_large_selection_count():
import carb.settings
return carb.settings.get_settings().get("/persistent/exts/omni.kit.property.usd/large_selection")
| 653 | Python | 37.470586 | 101 | 0.787136 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/usd_attribute_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, build_frame_header
from .usd_property_widget_builder import *
from collections import defaultdict, OrderedDict
from .usd_property_widget import *
import asyncio
import carb
import omni.ui as ui
import omni.usd
from typing import List, Dict
from pxr import Usd, Tf, Sdf
class UsdAttributeUiEntry(UsdPropertyUiEntry):
def __init__(
self,
attr_name: str,
display_group: str,
metadata,
property_type,
build_fn=None,
display_group_collapsed: bool = False,
prim_paths: List[Sdf.Path] = None,
):
super().__init__(
attr_name, display_group, metadata, property_type, build_fn, display_group_collapsed, prim_paths
)
class UsdAttributesWidget(UsdPropertiesWidget):
"""
DEPRECATED! KEEP FOR BACKWARD COMPATIBILITY. Use UsdPropertiesWidget instead.
UsdAttributesWidget provides functionalities to automatically populates UsdAttributes on given prim(s). The UI will
and models be generated according to UsdAttributes's value type. Multi-prim editing works for shared Attributes
between all selected prims if instantiated with multi_edit = True.
"""
def __init__(self, title: str, collapsed: bool, multi_edit: bool = True):
"""
Constructor.
Args:
title: title of the widget.
collapsed: whether the collapsable frame should be collapsed for this widget.
multi_edit: whether multi-editing is supported.
If False, properties will only be collected from the last selected prim.
If True, shared properties among all selected prims will be collected.
"""
super().__init__(title, collapsed, multi_edit)
def build_attribute_item(self, stage, ui_attr: UsdAttributeUiEntry, prim_paths: List[Sdf.Path]):
return super().build_property_item(stage, ui_attr, prim_paths)
def _filter_attrs_to_build(self, attrs):
return super()._filter_props_to_build(attrs)
def _customize_attrs_layout(self, attrs):
return super()._customize_props_layout(attrs)
def _get_shared_attributes_from_selected_prims(self, anchor_prim):
return super()._get_shared_properties_from_selected_prims(anchor_prim)
def build_property_item(self, stage, ui_prop: UsdPropertyUiEntry, prim_paths: List[Sdf.Path]):
return self.build_attribute_item(stage, ui_prop, prim_paths)
def _filter_props_to_build(self, props):
return self._filter_attrs_to_build(props)
def _customize_props_layout(self, props):
return self._customize_attrs_layout(props)
def _get_shared_properties_from_selected_prims(self, anchor_prim):
return self._get_shared_attributes_from_selected_prims(anchor_prim)
class SchemaAttributesWidget(SchemaPropertiesWidget):
"""
DEPRECATED! KEEP FOR BACKWARD COMPATIBILITY. Use SchemaPropertiesWidget instead.
SchemaAttributesWidget only filters attributes and only show the onces from a given IsA schema or applied API schema.
"""
def __init__(self, title: str, schema, include_inherited: bool):
"""
Constructor.
Args:
title (str): Title of the widgets on the Collapsable Frame.
schema: The USD IsA schema or applied API schema to filter attributes.
include_inherited (bool): Whether the filter should include inherited attributes.
"""
super().__init__(title, schema, include_inherited)
def build_attribute_item(self, stage, ui_attr: UsdAttributeUiEntry, prim_paths: List[Sdf.Path]):
return super().build_property_item(stage, ui_attr, prim_paths)
def _filter_attrs_to_build(self, attrs):
return super()._filter_props_to_build(attrs)
def _customize_attrs_layout(self, attrs):
return super()._customize_props_layout(attrs)
def _get_shared_attributes_from_selected_prims(self, anchor_prim):
return super()._get_shared_properties_from_selected_prims(anchor_prim)
def build_property_item(self, stage, ui_prop: UsdPropertyUiEntry, prim_paths: List[Sdf.Path]):
return self.build_attribute_item(stage, ui_prop, prim_paths)
def _filter_props_to_build(self, props):
return self._filter_attrs_to_build(props)
def _customize_props_layout(self, props):
return self._customize_attrs_layout(props)
def _get_shared_properties_from_selected_prims(self, anchor_prim):
return self._get_shared_attributes_from_selected_prims(anchor_prim)
class MultiSchemaAttributesWidget(MultiSchemaPropertiesWidget):
"""
DEPRECATED! KEEP FOR BACKWARD COMPATIBILITY. Use MultiSchemaPropertiesWidget instead.
MultiSchemaAttributesWidget filters attributes and only show the onces from a given IsA schema or schema subclass list.
"""
def __init__(self, title: str, schema, schema_subclasses: list, include_list: list = [], exclude_list: list = []):
"""
Constructor.
Args:
title (str): Title of the widgets on the Collapsable Frame.
schema: The USD IsA schema or applied API schema to filter attributes.
schema_subclasses (list): list of subclasses
include_list (list): list of additional schema named to add
exclude_list (list): list of additional schema named to remove
"""
super().__init__(title, schema, schema_subclasses, include_list, exclude_list)
def build_attribute_item(self, stage, ui_attr: UsdAttributeUiEntry, prim_paths: List[Sdf.Path]):
return super().build_property_item(stage, ui_attr, prim_paths)
def _filter_attrs_to_build(self, attrs):
return super()._filter_props_to_build(attrs)
def _customize_attrs_layout(self, attrs):
return super()._customize_props_layout(attrs)
def _get_shared_attributes_from_selected_prims(self, anchor_prim):
return super()._get_shared_properties_from_selected_prims(anchor_prim)
def build_property_item(self, stage, ui_prop: UsdPropertyUiEntry, prim_paths: List[Sdf.Path]):
return self.build_attribute_item(stage, ui_prop, prim_paths)
def _filter_props_to_build(self, props):
return self._filter_attrs_to_build(props)
def _customize_props_layout(self, props):
return self._customize_attrs_layout(props)
def _get_shared_properties_from_selected_prims(self, anchor_prim):
return self._get_shared_attributes_from_selected_prims(anchor_prim)
| 6,973 | Python | 39.08046 | 123 | 0.695397 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/usd_property_widget_builder.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 fnmatch
import weakref
from functools import lru_cache
from typing import Any, Callable, List
import carb
import carb.settings
import omni.client
import omni.kit.ui
import omni.ui as ui
import omni.usd
from omni.kit.window.property.templates import HORIZONTAL_SPACING, LABEL_HEIGHT, LABEL_WIDTH, LABEL_WIDTH_LIGHT
from omni.kit.window.file_importer import get_file_importer
from pxr import Ar, Sdf, Usd
from .asset_filepicker import show_asset_file_picker
from .attribute_context_menu import AttributeContextMenu, AttributeContextMenuEvent
from .control_state_manager import ControlStateManager
from .relationship import RelationshipEditWidget
from .usd_attribute_model import (
GfVecAttributeModel,
GfVecAttributeSingleChannelModel,
MdlEnumAttributeModel,
SdfAssetPathArrayAttributeItemModel,
SdfAssetPathAttributeModel,
SdfTimeCodeModel,
TfTokenAttributeModel,
UsdAttributeModel,
)
from .usd_object_model import MetadataObjectModel
from .widgets import ICON_PATH
@lru_cache()
def _get_plus_glyph():
return omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_context.svg")
def get_ui_style():
return carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
def get_model_cls(cls, args, key="model_cls"):
if args:
return args.get(key, cls)
return cls
def get_model_kwargs(args, key="model_kwargs"):
if args:
return args.get(key, {})
return {}
class UsdPropertiesWidgetBuilder:
# We don't use Tf.Type.FindByName(name) directly because the name depends
# on the compiler. For example the line `Sdf.ValueTypeNames.Int64.type`
# resolves to `Tf.Type.FindByName('long')` on Linux and on Windows it's
# `Tf.Type.FindByName('__int64')`.
tf_half = Sdf.ValueTypeNames.Half.type
tf_float = Sdf.ValueTypeNames.Float.type
tf_double = Sdf.ValueTypeNames.Double.type
tf_uchar = Sdf.ValueTypeNames.UChar.type
tf_uint = Sdf.ValueTypeNames.UInt.type
tf_int = Sdf.ValueTypeNames.Int.type
tf_int64 = Sdf.ValueTypeNames.Int64.type
tf_uint64 = Sdf.ValueTypeNames.UInt64.type
tf_bool = Sdf.ValueTypeNames.Bool.type
tf_string = Sdf.ValueTypeNames.String.type
tf_gf_vec2i = Sdf.ValueTypeNames.Int2.type
tf_gf_vec2h = Sdf.ValueTypeNames.Half2.type
tf_gf_vec2f = Sdf.ValueTypeNames.Float2.type
tf_gf_vec2d = Sdf.ValueTypeNames.Double2.type
tf_gf_vec3i = Sdf.ValueTypeNames.Int3.type
tf_gf_vec3h = Sdf.ValueTypeNames.Half3.type
tf_gf_vec3f = Sdf.ValueTypeNames.Float3.type
tf_gf_vec3d = Sdf.ValueTypeNames.Double3.type
tf_gf_vec4i = Sdf.ValueTypeNames.Int4.type
tf_gf_vec4h = Sdf.ValueTypeNames.Half4.type
tf_gf_vec4f = Sdf.ValueTypeNames.Float4.type
tf_gf_vec4d = Sdf.ValueTypeNames.Double4.type
tf_tf_token = Sdf.ValueTypeNames.Token.type
tf_sdf_asset_path = Sdf.ValueTypeNames.Asset.type
tf_sdf_time_code = Sdf.ValueTypeNames.TimeCode.type
# array type builders
tf_sdf_asset_array_path = Sdf.ValueTypeNames.AssetArray.type
@classmethod
def init_builder_table(cls):
cls.widget_builder_table = {
cls.tf_half: cls._floating_point_builder,
cls.tf_float: cls._floating_point_builder,
cls.tf_double: cls._floating_point_builder,
cls.tf_uchar: cls._integer_builder,
cls.tf_uint: cls._integer_builder,
cls.tf_int: cls._integer_builder,
cls.tf_int64: cls._integer_builder,
cls.tf_uint64: cls._integer_builder,
cls.tf_bool: cls._bool_builder,
cls.tf_string: cls._string_builder,
cls.tf_gf_vec2i: cls._vec2_per_channel_builder,
cls.tf_gf_vec2h: cls._vec2_per_channel_builder,
cls.tf_gf_vec2f: cls._vec2_per_channel_builder,
cls.tf_gf_vec2d: cls._vec2_per_channel_builder,
cls.tf_gf_vec3i: cls._vec3_per_channel_builder,
cls.tf_gf_vec3h: cls._vec3_per_channel_builder,
cls.tf_gf_vec3f: cls._vec3_per_channel_builder,
cls.tf_gf_vec3d: cls._vec3_per_channel_builder,
cls.tf_gf_vec4i: cls._vec4_per_channel_builder,
cls.tf_gf_vec4h: cls._vec4_per_channel_builder,
cls.tf_gf_vec4f: cls._vec4_per_channel_builder,
cls.tf_gf_vec4d: cls._vec4_per_channel_builder,
cls.tf_tf_token: cls._tftoken_builder,
cls.tf_sdf_asset_path: cls._sdf_asset_path_builder,
cls.tf_sdf_time_code: cls._time_code_builder,
# array type builders
cls.tf_sdf_asset_array_path: cls._sdf_asset_path_array_builder,
}
cls.reset_builder_coverage_table()
@classmethod
def reset_builder_coverage_table(cls):
cls.widget_builder_coverage_table = {
cls.tf_half: False,
cls.tf_float: False,
cls.tf_double: False,
cls.tf_uchar: False,
cls.tf_uint: False,
cls.tf_int: False,
cls.tf_int64: False,
cls.tf_uint64: False,
cls.tf_bool: False,
cls.tf_string: False,
cls.tf_gf_vec2i: False,
cls.tf_gf_vec2h: False,
cls.tf_gf_vec2f: False,
cls.tf_gf_vec2d: False,
cls.tf_gf_vec3i: False,
cls.tf_gf_vec3h: False,
cls.tf_gf_vec3f: False,
cls.tf_gf_vec3d: False,
cls.tf_gf_vec4i: False,
cls.tf_gf_vec4h: False,
cls.tf_gf_vec4f: False,
cls.tf_gf_vec4d: False,
cls.tf_tf_token: False,
cls.tf_sdf_asset_path: False,
cls.tf_sdf_time_code: False,
cls.tf_sdf_asset_array_path: False,
}
@classmethod
def startup(cls):
cls.init_builder_table()
cls.default_range_steps = {}
@classmethod
def shutdown(cls):
pass
@classmethod
def build(
cls,
stage,
attr_name,
metadata,
property_type,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
if property_type == Usd.Attribute:
type_name = cls._get_type_name(metadata)
tf_type = type_name.type
build_func = cls.widget_builder_table.get(tf_type, cls._fallback_builder)
cls.widget_builder_coverage_table[tf_type] = True
return build_func(
stage, attr_name, type_name, metadata, prim_paths, additional_label_kwargs, additional_widget_kwargs
)
elif property_type == Usd.Relationship:
return cls._relationship_builder(
stage, attr_name, metadata, prim_paths, additional_label_kwargs, additional_widget_kwargs
)
###### builder funcs ######
@classmethod
def _relationship_builder(
cls,
stage,
attr_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
with ui.HStack(spacing=HORIZONTAL_SPACING):
cls._create_label(attr_name, metadata, additional_label_kwargs)
return RelationshipEditWidget(stage, attr_name, prim_paths, additional_widget_kwargs)
@classmethod
def _fallback_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
with ui.HStack(spacing=HORIZONTAL_SPACING):
model_kwargs = get_model_kwargs(additional_widget_kwargs)
model_cls = get_model_cls(UsdAttributeModel, additional_widget_kwargs)
model = model_cls(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs)
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
kwargs = {
"name": "models_readonly",
"model": model,
"enabled": False,
"tooltip": model.get_value_as_string(),
}
if additional_widget_kwargs:
kwargs.update(additional_widget_kwargs)
with ui.ZStack():
value_widget = ui.StringField(**kwargs)
value_widget.identifier = f"fallback_{attr_name}"
mixed_overlay = cls._create_mixed_text_overlay()
cls._create_control_state(value_widget=value_widget, mixed_overlay=mixed_overlay, **kwargs, label=label)
return model
@classmethod
def _floating_point_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
with ui.HStack(spacing=HORIZONTAL_SPACING):
model_kwargs = cls._get_attr_value_range_kwargs(metadata)
model_kwargs.update(get_model_kwargs(additional_widget_kwargs))
model_cls = get_model_cls(UsdAttributeModel, additional_widget_kwargs)
model = model_cls(
stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs
)
# insert hard-range min/max before soft-range
widget_kwargs = {"model": model}
widget_kwargs.update(model_kwargs)
soft_range_min, soft_range_max = cls._get_attr_value_soft_range(metadata, model)
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
widget_kwargs.update(cls._get_attr_value_soft_range_kwargs(metadata, model))
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.ZStack():
if soft_range_min < soft_range_max:
value_widget = cls._create_drag_or_slider(ui.FloatDrag, ui.FloatDrag, **widget_kwargs)
cls._setup_soft_float_dynamic_range(attr_name, metadata, value_widget.step, model, value_widget)
else:
value_widget = cls._create_drag_or_slider(ui.FloatDrag, ui.FloatSlider, **widget_kwargs)
value_widget.identifier = f"float_slider_{attr_name}"
mixed_overlay = cls._create_mixed_text_overlay()
cls._create_control_state(
value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs, label=label
)
return model
@classmethod
def _integer_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
with ui.HStack(spacing=HORIZONTAL_SPACING):
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
is_mdl_enum = False
if metadata.get("renderType", None):
sdr_metadata = metadata.get("sdrMetadata", None)
if sdr_metadata and sdr_metadata.get("options", None):
is_mdl_enum = True
if is_mdl_enum:
model_kwargs = get_model_kwargs(additional_widget_kwargs)
model_cls = get_model_cls(MdlEnumAttributeModel, additional_widget_kwargs)
model = model_cls(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs)
widget_kwargs = {"name": "choices", "model": model}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.ZStack():
value_widget = ui.ComboBox(model, **widget_kwargs)
mixed_overlay = cls._create_mixed_text_overlay()
else:
model_kwargs = cls._get_attr_value_range_kwargs(metadata)
if type_name.type == cls.tf_uint:
model_kwargs["min"] = 0
model_kwargs.update(get_model_kwargs(additional_widget_kwargs))
model_cls = get_model_cls(UsdAttributeModel, additional_widget_kwargs)
model = model_cls(
stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs
)
# insert hard-range min/max before soft-range
widget_kwargs = {"model": model}
widget_kwargs.update(model_kwargs)
widget_kwargs.update(cls._get_attr_value_soft_range_kwargs(metadata, model))
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.ZStack():
value_widget = cls._create_drag_or_slider(ui.IntDrag, ui.IntSlider, **widget_kwargs)
mixed_overlay = cls._create_mixed_text_overlay()
value_widget.identifier = f"integer_slider_{attr_name}"
cls._create_control_state(
value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs, label=label
)
return model
@classmethod
def _bool_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
with ui.HStack(spacing=HORIZONTAL_SPACING):
model_kwargs = get_model_kwargs(additional_widget_kwargs)
model_cls = get_model_cls(UsdAttributeModel, additional_widget_kwargs)
model = model_cls(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs)
settings = carb.settings.get_settings()
left_aligned = settings.get("ext/omni.kit.window.property/checkboxAlignment") == "left"
if not left_aligned:
if not additional_label_kwargs:
additional_label_kwargs = {}
additional_label_kwargs["width"] = 0
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
if not left_aligned:
ui.Spacer(width=10)
ui.Line(style={"color": 0x338A8777}, width=ui.Fraction(1))
ui.Spacer(width=5)
with ui.VStack(width=10):
ui.Spacer()
widget_kwargs = {"width": 10, "height": 0, "name": "greenCheck", "model": model}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.ZStack():
with ui.Placer(offset_x=0, offset_y=-2):
value_widget = ui.CheckBox(**widget_kwargs)
value_widget.identifier = f"bool_{attr_name}"
with ui.Placer(offset_x=1, offset_y=-1):
mixed_overlay = ui.Rectangle(
height=8, width=8, name="mixed_overlay", alignment=ui.Alignment.CENTER, visible=False
)
ui.Spacer()
if left_aligned:
ui.Spacer(width=5)
ui.Line(style={"color": 0x338A8777}, width=ui.Fraction(1))
cls._create_control_state(
value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs, label=label
)
return model
@classmethod
def _string_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
model = cls._create_filepath_for_ui_type(
stage, attr_name, metadata, prim_paths, additional_label_kwargs, additional_widget_kwargs
)
if model:
return model
with ui.HStack(spacing=HORIZONTAL_SPACING):
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
model_kwargs = get_model_kwargs(additional_widget_kwargs)
model_cls = get_model_cls(UsdAttributeModel, additional_widget_kwargs)
model = model_cls(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs)
widget_kwargs = {"name": "string"}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.ZStack():
value_widget = ui.StringField(model, **widget_kwargs)
value_widget.identifier = f"string_{attr_name}"
mixed_overlay = cls._create_mixed_text_overlay()
cls._create_control_state(
model=model, value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs, label=label
)
return model
@classmethod
def _vec2_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
): # pragma: no cover
"""
The entire vector is built as one multi-drag field
"""
with ui.HStack(spacing=HORIZONTAL_SPACING):
model_kwargs = cls._get_attr_value_range_kwargs(metadata)
model_kwargs.update(get_model_kwargs(additional_widget_kwargs))
model_cls = get_model_cls(GfVecAttributeModel, additional_widget_kwargs)
model = model_cls(
stage,
[path.AppendProperty(attr_name) for path in prim_paths],
2,
type_name.type,
False,
metadata,
**model_kwargs,
)
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
widget_kwargs = {"model": model}
widget_kwargs.update(cls._get_attr_value_soft_range_kwargs(metadata, model))
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
create_drag_fn = (
cls._create_multi_int_drag_with_labels
if type_name.type.typeName.endswith("i")
else cls._create_multi_float_drag_with_labels
)
value_widget, mixed_overlay = create_drag_fn(
labels=[("X", 0xFF5555AA), ("Y", 0xFF76A371)], comp_count=2, **widget_kwargs
)
value_widget.identifier = f"vec2_{attr_name}"
cls._create_control_state(
value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs, label=label
)
return model
@classmethod
def _vec2_per_channel_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
"""
The vector is split into components and each one has their own drag field and status control
"""
custom_data = metadata.get(Sdf.PrimSpec.CustomDataKey, {})
with ui.HStack(spacing=HORIZONTAL_SPACING):
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
if (
custom_data
and "mdl" in custom_data
and "type" in custom_data["mdl"]
and custom_data["mdl"]["type"] == "bool2"
):
return cls._create_bool_per_channel(
stage,
attr_name,
prim_paths,
2,
type_name,
type_name.type,
metadata,
label,
additional_widget_kwargs,
)
else:
return cls._create_color_or_drag_per_channel(
stage,
attr_name,
prim_paths,
2,
type_name,
type_name.type,
metadata,
label,
additional_widget_kwargs,
)
@classmethod
def _vec3_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
): # pragma: no cover
"""
The entire vector is built as one multi-drag field
"""
with ui.HStack(spacing=HORIZONTAL_SPACING):
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
return cls._create_color_or_multidrag(
stage, attr_name, prim_paths, 3, type_name, type_name.type, metadata, label, additional_widget_kwargs
)
@classmethod
def _vec3_per_channel_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
"""
The vector is split into components and each one has their own drag field and status control
"""
custom_data = metadata.get(Sdf.PrimSpec.CustomDataKey, {})
with ui.HStack(spacing=HORIZONTAL_SPACING):
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
if (
custom_data
and "mdl" in custom_data
and "type" in custom_data["mdl"]
and custom_data["mdl"]["type"] == "bool3"
):
return cls._create_bool_per_channel(
stage,
attr_name,
prim_paths,
3,
type_name,
type_name.type,
metadata,
label,
additional_widget_kwargs,
)
else:
return cls._create_color_or_drag_per_channel(
stage,
attr_name,
prim_paths,
3,
type_name,
type_name.type,
metadata,
label,
additional_widget_kwargs,
)
@classmethod
def _vec4_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
): # pragma: no cover
"""
The entire vector is built as one multi-drag field
"""
with ui.HStack(spacing=HORIZONTAL_SPACING):
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
return cls._create_color_or_multidrag(
stage, attr_name, prim_paths, 4, type_name, type_name.type, metadata, label, additional_widget_kwargs
)
@classmethod
def _vec4_per_channel_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
"""
The vector is split into components and each one has their own drag field and status control
"""
custom_data = metadata.get(Sdf.PrimSpec.CustomDataKey, {})
with ui.HStack(spacing=HORIZONTAL_SPACING):
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
if (
custom_data
and "mdl" in custom_data
and "type" in custom_data["mdl"]
and custom_data["mdl"]["type"] == "bool4"
):
return cls._create_bool_per_channel(
stage,
attr_name,
prim_paths,
4,
type_name,
type_name.type,
metadata,
label,
additional_widget_kwargs,
)
else:
return cls._create_color_or_drag_per_channel(
stage,
attr_name,
prim_paths,
4,
type_name,
type_name.type,
metadata,
label,
additional_widget_kwargs,
)
@classmethod
def _tftoken_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
model = cls._create_filepath_for_ui_type(
stage, attr_name, metadata, prim_paths, additional_label_kwargs, additional_widget_kwargs
)
if model:
return model
with ui.HStack(spacing=HORIZONTAL_SPACING):
model = None
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
tokens = metadata.get("allowedTokens")
if tokens is not None and len(tokens) > 0:
model_kwargs = get_model_kwargs(additional_widget_kwargs)
model_cls = get_model_cls(TfTokenAttributeModel, additional_widget_kwargs)
model = model_cls(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs)
widget_kwargs = {"name": "choices"}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.ZStack():
value_widget = ui.ComboBox(model, **widget_kwargs)
mixed_overlay = cls._create_mixed_text_overlay()
else:
model_kwargs = get_model_kwargs(additional_widget_kwargs)
model_cls = get_model_cls(
UsdAttributeModel, additional_widget_kwargs, key="no_allowed_tokens_model_cls"
)
model = model_cls(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs)
widget_kwargs = {"name": "models"}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.ZStack():
value_widget = ui.StringField(model, **widget_kwargs)
mixed_overlay = cls._create_mixed_text_overlay()
value_widget.identifier = f"token_{attr_name}"
cls._create_control_state(
model=model, value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs, label=label
)
return model
@classmethod
def _build_asset_checkpoint_ui(cls, model, frame):
try:
from .versioning_helper import VersioningHelper
absolute_asset_path = model.get_resolved_path()
if VersioningHelper.is_versioning_enabled() and absolute_asset_path:
# Use checkpoint widget in the drop down menu for more detailed information
from omni.kit.widget.versioning.checkpoint_combobox import CheckpointCombobox
spacer = ui.Spacer(height=5)
stack = ui.HStack()
with stack:
UsdPropertiesWidgetBuilder._create_label("Checkpoint", additional_label_kwargs={"width": 80})
def on_selection_changed(model_or_item, model):
url = model.get_resolved_path()
try:
from omni.kit.widget.versioning.checkpoints_model import CheckpointItem
if isinstance(model_or_item, CheckpointItem):
checkpoint = model_or_item.get_relative_path()
elif model_or_item is None:
checkpoint = ""
except Exception as e:
pass
client_url = omni.client.break_url(url)
new_path = omni.client.make_url(
scheme=client_url.scheme,
user=client_url.user,
host=client_url.host,
port=client_url.port,
path=client_url.path,
query=checkpoint,
fragment=client_url.fragment,
)
if url != new_path:
model.set_value(new_path)
frame.rebuild()
checkpoint_combobox = CheckpointCombobox(
absolute_asset_path, lambda si, m=model: on_selection_changed(si, m)
)
# reset button
def reset_func(model):
on_selection_changed(None, model)
frame.rebuild()
checkpoint = ""
client_url = omni.client.break_url(model.get_resolved_path())
if client_url.query:
_, checkpoint = omni.client.get_branch_and_checkpoint_from_query(client_url.query)
ui.Spacer(width=4)
ui.Image(
f"{ICON_PATH}/Default value.svg" if checkpoint == "" else f"{ICON_PATH}/Changed value.svg",
mouse_pressed_fn=lambda x, y, b, a, m=model: reset_func(m),
width=12,
height=18,
tooltip="Reset Checkpoint" if checkpoint else "",
)
def on_have_server_info(server: str, support_checkpoint: bool, ui_items: list):
if not support_checkpoint:
for item in ui_items:
item.visible = False
VersioningHelper.check_server_checkpoint_support(
VersioningHelper.extract_server_from_url(absolute_asset_path),
lambda s, c, i=[spacer, stack]: on_have_server_info(s, c, i),
)
return None
except ImportError as e:
# If the widget is not available, create a simple combo box instead
carb.log_warn(f"Checkpoint widget in Asset is not available due to: {e}")
@classmethod
def _sdf_asset_path_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
model_kwargs = get_model_kwargs(additional_widget_kwargs)
model_cls = get_model_cls(SdfAssetPathAttributeModel, additional_widget_kwargs)
model = model_cls(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs)
# List of models. It's possible that the path is texture related path, which
# will return colorSpace model also.
return cls._create_path_widget(
model, stage, attr_name, metadata, prim_paths, additional_label_kwargs, additional_widget_kwargs
)
@classmethod
def _sdf_asset_path_array_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
widget_kwargs = {"name": "models"}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
models = []
class SdfAssetPathDelegate(ui.AbstractItemDelegate):
"""
Delegate is the representation layer. TreeView calls the methods
of the delegate to create custom widgets for each item.
"""
def __init__(self):
super().__init__()
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
pass
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per column per item"""
with ui.VStack():
ui.Spacer(height=2)
with ui.ZStack():
ui.Rectangle(name="backdrop")
frame = ui.Frame(
height=0,
spacing=5,
style={
"Frame": {"margin_width": 2, "margin_height": 2},
"Button": {"background_color": 0x0},
},
)
with frame:
(item_value_model, value_model) = model.get_item_value_model(item, column_id)
extra_widgets = []
with ui.HStack(spacing=HORIZONTAL_SPACING, width=ui.Percent(100)):
with ui.VStack(spacing=0, height=ui.Percent(100), width=0):
ui.Spacer()
# Create ||| grab area
grab = ui.HStack(
identifier=f"sdf_asset_array_{attr_name}[{item_value_model.index}].reorder_grab",
height=LABEL_HEIGHT,
)
with grab:
for i in range(3):
ui.Line(
width=3,
alignment=ui.Alignment.H_CENTER,
name="grab",
)
ui.Spacer()
# do a content_clipping for the rest of the widget so only dragging on the grab triggers
# reorder
with ui.HStack(content_clipping=1):
widget_kwargs["model"] = item_value_model
cls._build_path_field(
item_value_model, stage, attr_name, widget_kwargs, frame, extra_widgets
)
def remove_entry(index: int, value_model: UsdAttributeModel):
value = list(value_model.get_value())
new_value = value[:index] + value[index + 1 :]
value_model.set_value(new_value)
remove_style = {
"image_url": str(ICON_PATH.joinpath("remove.svg")),
"margin": 0,
"padding": 0,
}
ui.Spacer(width=HORIZONTAL_SPACING)
ui.Button(
"",
width=12,
height=ui.Percent(100),
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
clicked_fn=lambda index=item_value_model.index, value_model=value_model: remove_entry(
index, value_model
),
name="remove",
style=remove_style,
tooltip="Remove Asset",
identifier=f"sdf_asset_array_{attr_name}[{item_value_model.index}].remove",
)
ui.Spacer(height=2)
with ui.HStack(spacing=HORIZONTAL_SPACING):
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
with ui.VStack():
delegate_cls = get_model_cls(SdfAssetPathDelegate, additional_widget_kwargs, key="delegate_cls")
delegate = delegate_cls()
model_cls = get_model_cls(SdfAssetPathArrayAttributeItemModel, additional_widget_kwargs)
item_model = model_cls(
stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, delegate
)
# content_clipping so drag n drop in tree view doesn't scroll the outer frame
tree_frame_stack = ui.HStack(spacing=HORIZONTAL_SPACING, content_clipping=1)
with tree_frame_stack:
with ui.Frame(height=0):
tree_view = ui.TreeView(
item_model,
delegate=delegate,
root_visible=False,
header_visible=False,
drop_between_items=True,
style={
"TreeView:selected": {"background_color": 0x00},
"TreeView": {"background_color": 0xFFFFFFFF}, # reorder indicator
},
)
tree_view.identifier = f"sdf_asset_array_{attr_name}"
ui.Spacer(width=12)
with ui.HStack(spacing=HORIZONTAL_SPACING, height=LABEL_HEIGHT):
extra_widgets = []
with ui.ZStack():
def assign_value_fn(model, path):
value = list(model.get_value())
value.append(Sdf.AssetPath(path))
model.set_value(Sdf.AssetPathArray(value))
button = ui.Button(
f"{_get_plus_glyph()} Add Asset...",
clicked_fn=lambda model_weak=weakref.ref(item_model.value_model), stage_weak=weakref.ref(
stage
): show_asset_file_picker(
"Select Asset...",
assign_value_fn,
model_weak,
stage_weak,
multi_selection=True,
on_selected_fn=cls._assign_asset_path_value
),
)
button.identifier = f"sdf_asset_array_{attr_name}.add_asset"
button.set_accept_drop_fn(
lambda url, model_weak=weakref.ref(item_model.value_model): cls.can_accept_file_drop(
url, model_weak, True
)
)
def on_drop_fn(event, model_weak):
model_weak = model_weak()
if not model_weak:
return
paths = event.mime_data.split("\n")
with omni.kit.undo.group():
for path in paths:
path = cls._convert_asset_path(path)
assign_value_fn(model_weak, path)
button.set_drop_fn(
lambda event, model_weak=weakref.ref(item_model.value_model): on_drop_fn(event, model_weak)
)
extra_widgets.append(button)
mixed_overlay = cls._create_mixed_text_overlay(content_clipping=1)
def on_model_value_changed(model: UsdAttributeModel):
value = model.get_value()
# hide treeview if mixed-editing or no node
tree_frame_stack.visible = not model.is_ambiguous() and bool(value)
button.visible = not model.is_ambiguous()
item_model.value_model.add_value_changed_fn(on_model_value_changed)
on_model_value_changed(item_model.value_model)
cls._create_control_state(
item_model.value_model,
value_widget=tree_view,
mixed_overlay=mixed_overlay,
extra_widgets=extra_widgets,
**widget_kwargs,
label=label,
)
models.append(item_model)
return models
@classmethod
def _get_alignment(cls):
settings = carb.settings.get_settings()
return (
ui.Alignment.RIGHT
if settings.get("/ext/omni.kit.window.property/labelAlignment") == "right"
else ui.Alignment.LEFT
)
@classmethod
def _create_label(cls, attr_name, metadata=None, additional_label_kwargs=None):
alignment = cls._get_alignment()
label_kwargs = {
"name": "label",
"word_wrap": True,
"width": LABEL_WIDTH,
"height": LABEL_HEIGHT,
"alignment": alignment,
}
if get_ui_style() == "NvidiaLight":
label_kwargs["width"] = LABEL_WIDTH_LIGHT
if additional_label_kwargs:
label_kwargs.update(additional_label_kwargs)
if metadata and "tooltip" not in label_kwargs:
label_kwargs["tooltip"] = cls._generate_tooltip_string(attr_name, metadata)
label = ui.Label(cls._get_display_name(attr_name, metadata), **label_kwargs)
ui.Spacer(width=5)
return label
@classmethod
def _create_text_label(cls, attr_name, metadata=None, additional_label_kwargs=None):
alignment = cls._get_alignment()
label_kwargs = {
"name": "label",
"word_wrap": True,
"width": LABEL_WIDTH,
"height": LABEL_HEIGHT,
"alignment": alignment,
}
def open_url(url):
import webbrowser
webbrowser.open(url)
if get_ui_style() == "NvidiaLight":
label_kwargs["width"] = LABEL_WIDTH_LIGHT
if additional_label_kwargs:
label_kwargs.update(additional_label_kwargs)
if metadata and "tooltip" not in label_kwargs:
label_kwargs["tooltip"] = cls._generate_tooltip_string(attr_name, metadata)
display_name = cls._get_display_name(attr_name, metadata)
if display_name.startswith("http"):
label_kwargs["name"] = "url"
label = ui.StringField(**label_kwargs)
label.model.set_value(display_name)
label.set_mouse_pressed_fn(lambda x, y, b, m, url=display_name: open_url(url))
else:
label = ui.StringField(**label_kwargs)
label.model.set_value(display_name)
ui.Spacer(width=5)
return label
@classmethod
def _generate_tooltip_string(cls, attr_name, metadata):
doc_string = metadata.get(Sdf.PropertySpec.DocumentationKey)
type_name = cls._get_type_name(metadata)
tooltip = f"{attr_name} ({type_name})" if not doc_string else f"{attr_name} ({type_name})\n\t\t{doc_string}"
return tooltip
@classmethod
def _create_attribute_context_menu(cls, widget, model, comp_index=-1):
def show_attribute_context_menu(b, widget_ref, model_ref):
if b != 1:
return
if not model_ref:
return
if not widget_ref:
return
event = AttributeContextMenuEvent(
widget_ref,
model.get_attribute_paths(),
model_ref._stage,
model_ref.get_current_time_code(),
model_ref,
comp_index,
)
AttributeContextMenu.get_instance().on_mouse_event(event)
widget.set_mouse_pressed_fn(
lambda x, y, b, _: show_attribute_context_menu(b, weakref.proxy(widget), weakref.proxy(model))
)
###### helper funcs ######
@staticmethod
def _get_attr_value_range(metadata):
custom_data = metadata.get(Sdf.PrimSpec.CustomDataKey, {})
range = custom_data.get("range", {})
range_min = range.get("min", 0)
range_max = range.get("max", 0)
# TODO: IMGUI DragScalarN only support scalar range for all vector component.
# Need to change it to support per component range.
if hasattr(range_min, "__getitem__"):
range_min = range_min[0]
if hasattr(range_max, "__getitem__"):
range_max = range_max[0]
return range_min, range_max
@staticmethod
def _get_attr_value_ui_type(metadata):
custom_data = metadata.get(Sdf.PrimSpec.CustomDataKey, {})
return custom_data.get("uiType")
@classmethod
def _setup_soft_float_dynamic_range(cls, attr_name, metadata, default_step, model, widget):
soft_range_min, soft_range_max = cls._get_attr_value_soft_range(metadata, model)
if soft_range_min < soft_range_max:
def on_end_edit(model, widget, attr_name, metadata, soft_range_min, soft_range_max):
default_range = True
value = model.get_value()
# TODO: IMGUI DragScalarN only support scalar range for all vector component.
# Need to change it to support per component range.
if hasattr(value, "__getitem__"):
value = value[0]
if model._soft_range_min != None and model._soft_range_min < soft_range_min:
soft_range_min = model._soft_range_min
default_range = False
if model._soft_range_max != None and model._soft_range_max > soft_range_max:
soft_range_max = model._soft_range_max
default_range = False
if value < soft_range_min:
soft_range_min = value
model.set_soft_range_userdata(soft_range_min, soft_range_max)
default_range = False
if value > soft_range_max:
soft_range_max = value
model.set_soft_range_userdata(soft_range_min, soft_range_max)
default_range = False
widget.min = soft_range_min
widget.max = soft_range_max
if not default_range:
if not attr_name in cls.default_range_steps:
cls.default_range_steps[attr_name] = widget.step
widget.step = max(0.1, (soft_range_max - soft_range_min) / 1000.0)
def on_set_default(model, widget, attr_name, metadata):
soft_range_min, soft_range_max = cls._get_attr_value_soft_range(metadata, model, False)
widget.min = soft_range_min
widget.max = soft_range_max
if attr_name in cls.default_range_steps:
widget.step = cls.default_range_steps[attr_name]
model.add_end_edit_fn(
lambda m, w=widget, n=attr_name, md=metadata, min=soft_range_min, max=soft_range_max: on_end_edit(
m, w, n, md, min, max
)
)
model.set_on_set_default_fn(lambda m=model, w=widget, n=attr_name, md=metadata: on_set_default(m, w, n, md))
@classmethod
def _get_attr_value_range_kwargs(cls, metadata):
kwargs = {}
min, max = cls._get_attr_value_range(metadata)
# only set range if soft_range is valid (min < max)
if min < max:
kwargs["min"] = min
kwargs["max"] = max
return kwargs
@staticmethod
def _get_attr_value_soft_range(metadata, model=None, use_override=True):
custom_data = metadata.get(Sdf.PrimSpec.CustomDataKey, {})
soft_range = custom_data.get("soft_range", {})
soft_range_min = soft_range.get("min", 0)
soft_range_max = soft_range.get("max", 0)
# TODO: IMGUI DragScalarN only support scalar range for all vector component.
# Need to change it to support per component range.
if hasattr(soft_range_min, "__getitem__"):
soft_range_min = soft_range_min[0]
if hasattr(soft_range_max, "__getitem__"):
soft_range_max = soft_range_max[0]
if model and use_override:
value = model.get_value()
if hasattr(value, "__getitem__"):
value = value[0]
if model._soft_range_min != None and model._soft_range_min < soft_range_min:
soft_range_min = model._soft_range_min
if model._soft_range_max != None and model._soft_range_max > soft_range_max:
soft_range_max = model._soft_range_max
if soft_range_min < soft_range_max:
if value < soft_range_min:
soft_range_min = value
model.set_soft_range_userdata(soft_range_min, soft_range_max)
if value > soft_range_max:
soft_range_max = value
model.set_soft_range_userdata(soft_range_min, soft_range_max)
return soft_range_min, soft_range_max
@classmethod
def _get_attr_value_soft_range_kwargs(cls, metadata, model=None):
kwargs = {}
min, max = cls._get_attr_value_soft_range(metadata, model)
# only set soft_range if soft_range is valid (min < max)
if min < max:
kwargs["min"] = min
kwargs["max"] = max
model.update_control_state()
return kwargs
@staticmethod
def _create_drag_or_slider(drag_widget, slider_widget, **kwargs):
if "min" in kwargs and "max" in kwargs:
range_min = kwargs["min"]
range_max = kwargs["max"]
if range_max - range_min < 100:
return slider_widget(name="value", **kwargs)
else:
if "step" not in kwargs:
kwargs["step"] = max(0.1, (range_max - range_min) / 1000.0)
else:
if "step" not in kwargs:
kwargs["step"] = 0.1
# If range is too big or no range, don't use a slider
return drag_widget(name="value", **kwargs)
@classmethod
def _create_multi_float_drag_with_labels(cls, model, labels, comp_count, **kwargs): # pragma: no cover
return cls._create_multi_drag_with_labels(ui.MultiFloatDragField, model, labels, comp_count, **kwargs)
@classmethod
def _create_multi_int_drag_with_labels(cls, model, labels, comp_count, **kwargs): # pragma: no cover
return cls._create_multi_drag_with_labels(ui.MultiIntDragField, model, labels, comp_count, **kwargs)
@classmethod
def _create_multi_drag_with_labels(cls, drag_field_widget, model, labels, comp_count, **kwargs): # pragma: no cover
RECT_WIDTH = 13
SPACING = 4
with ui.ZStack():
with ui.HStack():
ui.Spacer(width=RECT_WIDTH)
widget_kwargs = {"name": "multivalue", "h_spacing": RECT_WIDTH + SPACING}
widget_kwargs.update(kwargs)
value_widget = drag_field_widget(model, **widget_kwargs)
with ui.HStack():
for i in range(comp_count):
if i != 0:
ui.Spacer(width=SPACING)
label = labels[i]
with ui.ZStack(width=RECT_WIDTH + 1):
ui.Rectangle(name="vector_label", style={"background_color": label[1]})
ui.Label(label[0], name="vector_label", alignment=ui.Alignment.CENTER)
ui.Spacer()
mixed_overlay = []
with ui.HStack():
for i in range(comp_count):
ui.Spacer(width=RECT_WIDTH + SPACING)
item_model = model.get_item_value_model(model.get_item_children(None)[i], 0)
mixed_overlay.append(cls._create_mixed_text_overlay(item_model, model, i))
return value_widget, mixed_overlay
@classmethod
def _create_float_drag_per_channel_with_labels_and_control(cls, models, metadata, labels, **kwargs):
return cls._create_drag_per_channel_with_labels_and_control(
ui.FloatDrag, ui.FloatSlider, models, metadata, labels, **kwargs
)
@classmethod
def _create_int_drag_per_channel_with_labels_and_control(cls, models, metadata, labels, **kwargs):
return cls._create_drag_per_channel_with_labels_and_control(
ui.IntDrag, ui.IntSlider, models, metadata, labels, **kwargs
)
@classmethod
def _create_drag_per_channel_with_labels_and_control(
cls, drag_field_widget, slider_field_widget, models, metadata, labels, **kwargs
):
RECT_WIDTH = 13
SPACING = 4
hstack = ui.HStack()
with hstack:
for i, model in enumerate(models):
with ui.HStack():
if i != 0:
ui.Spacer(width=SPACING)
label = labels[i]
with ui.ZStack(width=RECT_WIDTH + 1):
ui.Rectangle(name="vector_label", style={"background_color": label[1]})
ui.Label(label[0], name="vector_label", alignment=ui.Alignment.CENTER)
widget_kwargs = {"model": model}
widget_kwargs.update(cls._get_attr_value_soft_range_kwargs(metadata, model))
widget_kwargs.update(**kwargs)
soft_range_min, soft_range_max = cls._get_attr_value_soft_range(metadata, model)
with ui.ZStack():
if soft_range_min < soft_range_max:
value_widget = cls._create_drag_or_slider(
drag_field_widget, drag_field_widget, **widget_kwargs
)
cls._setup_soft_float_dynamic_range(
model._object_paths[-1], metadata, value_widget.step, model, value_widget
)
else:
value_widget = cls._create_drag_or_slider(
drag_field_widget, slider_field_widget, **widget_kwargs
)
mixed_overlay = cls._create_mixed_text_overlay(model, model)
ui.Spacer(width=SPACING)
widget_kwargs["widget_comp_index"] = i
cls._create_control_state(value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs)
return hstack
@classmethod
def _create_color_or_multidrag(
cls,
stage,
attr_name,
prim_paths,
comp_count,
type_name,
tf_type,
metadata,
label,
additional_widget_kwargs=None,
): # pragma: no cover
model_kwargs = cls._get_attr_value_range_kwargs(metadata)
model_kwargs.update(get_model_kwargs(additional_widget_kwargs))
extra_widgets = []
model_cls = get_model_cls(GfVecAttributeModel, additional_widget_kwargs)
model = model_cls(
stage,
[path.AppendProperty(attr_name) for path in prim_paths],
comp_count,
tf_type,
False,
metadata,
**model_kwargs,
)
ui_type = ""
if comp_count == 3 or comp_count == 4:
ui_type = cls._get_attr_value_ui_type(metadata)
if (
type_name == Sdf.ValueTypeNames.Color3h
or type_name == Sdf.ValueTypeNames.Color3f
or type_name == Sdf.ValueTypeNames.Color3d
or type_name == Sdf.ValueTypeNames.Color4h
or type_name == Sdf.ValueTypeNames.Color4f
or type_name == Sdf.ValueTypeNames.Color4d
or ui_type == "color"
):
widget_kwargs = {"min": 0.0, "max": 2.0, "model": model}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.HStack(spacing=4):
value_widget, mixed_overlay = cls._create_multi_float_drag_with_labels(
labels=[("R", 0xFF5555AA), ("G", 0xFF76A371), ("B", 0xFFA07D4F), ("A", 0xFFFFFFFF)],
comp_count=comp_count,
**widget_kwargs,
)
extra_widgets.append(ui.ColorWidget(model, width=65, height=0))
else:
widget_kwargs = {"model": model}
widget_kwargs.update(cls._get_attr_value_soft_range_kwargs(metadata, model))
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
create_drag_fn = (
cls._create_multi_int_drag_with_labels
if type_name.type.typeName.endswith("i")
else cls._create_multi_float_drag_with_labels
)
value_widget, mixed_overlay = create_drag_fn(
labels=[("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F), ("W", 0xFFFFFFFF)],
comp_count=comp_count,
**widget_kwargs,
)
value_widget.identifier = f"color_{attr_name}"
cls._create_control_state(
value_widget=value_widget,
mixed_overlay=mixed_overlay,
extra_widgets=extra_widgets,
**widget_kwargs,
label=label,
)
return model
@classmethod
def _create_bool_per_channel(
cls,
stage,
attr_name,
prim_paths,
comp_count,
type_name,
tf_type,
metadata,
label,
additional_widget_kwargs=None,
):
model_kwargs = cls._get_attr_value_range_kwargs(metadata)
model_kwargs.update(get_model_kwargs(additional_widget_kwargs))
models = []
# We need a UsdAttributeModel here for context menu and default button:
model_cls = get_model_cls(UsdAttributeModel, additional_widget_kwargs)
model = model_cls(
stage,
[path.AppendProperty(attr_name) for path in prim_paths],
False,
metadata,
False,
**model_kwargs,
)
def on_model_value_changed(model: UsdAttributeModel):
model._update_value()
model.add_value_changed_fn(on_model_value_changed)
single_channel_model_cls = get_model_cls(
GfVecAttributeSingleChannelModel, additional_widget_kwargs, "single_channel_model_cls"
)
for i in range(comp_count):
models.append(
single_channel_model_cls(
stage,
[path.AppendProperty(attr_name) for path in prim_paths],
i,
False,
metadata,
False,
**model_kwargs,
)
)
widget_kwargs = {}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
mixed_overlay = []
with ui.ZStack():
with ui.HStack(spacing=4, width=32):
with ui.HStack(spacing=HORIZONTAL_SPACING, identifier=f"boolean_per_channel_{attr_name}"):
for i, channel_model in enumerate(models):
with ui.VStack(width=10):
ui.Spacer()
with ui.ZStack():
with ui.Placer(offset_x=0, offset_y=-2):
with ui.ZStack():
ui.CheckBox(width=10, height=0, name="greenCheck", model=channel_model)
mixed_overlay.append(
ui.Rectangle(
width=12,
height=12,
name="mixed_overlay",
alignment=ui.Alignment.CENTER,
visible=False,
)
)
ui.Spacer()
ui.Line(style={"color": 0x338A8777}, width=ui.Fraction(1))
ui.Spacer(width=5)
models.append(model)
cls._create_control_state(model=model, mixed_overlay=mixed_overlay, label=label)
model._update_value() # trigger an initial refresh. Only needed if the model is not assigned to a widget
return models
@classmethod
def _create_color_or_drag_per_channel(
cls,
stage,
attr_name,
prim_paths,
comp_count,
type_name,
tf_type,
metadata,
label,
additional_widget_kwargs=None,
):
model_kwargs = cls._get_attr_value_range_kwargs(metadata)
model_kwargs.update(get_model_kwargs(additional_widget_kwargs))
extra_widgets = []
models = []
# We need a GfVecAttributeModel here for:
# If attribute is a color, the color picker widget needs this model type
# When copying value from attribute label, this model is used to fetch value.
model_cls = get_model_cls(GfVecAttributeModel, additional_widget_kwargs)
model = model_cls(
stage,
[path.AppendProperty(attr_name) for path in prim_paths],
comp_count,
tf_type,
False,
metadata,
**model_kwargs,
)
single_channel_model_cls = get_model_cls(
GfVecAttributeSingleChannelModel, additional_widget_kwargs, "single_channel_model_cls"
)
for i in range(comp_count):
models.append(
single_channel_model_cls(
stage,
[path.AppendProperty(attr_name) for path in prim_paths],
i,
False,
metadata,
False,
**model_kwargs,
)
)
ui_type = ""
if comp_count == 3 or comp_count == 4:
ui_type = cls._get_attr_value_ui_type(metadata)
if (
type_name == Sdf.ValueTypeNames.Color3h
or type_name == Sdf.ValueTypeNames.Color3f
or type_name == Sdf.ValueTypeNames.Color3d
or type_name == Sdf.ValueTypeNames.Color4h
or type_name == Sdf.ValueTypeNames.Color4f
or type_name == Sdf.ValueTypeNames.Color4d
or ui_type == "color"
):
widget_kwargs = {"min": 0.0, "max": 2.0}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.HStack(spacing=4):
labels = [("R", 0xFF5555AA), ("G", 0xFF76A371), ("B", 0xFFA07D4F), ("A", 0xFFFFFFFF)]
value_widget = cls._create_float_drag_per_channel_with_labels_and_control(
models, metadata, labels, **widget_kwargs
)
color_picker = ui.ColorWidget(model, width=LABEL_HEIGHT, height=0)
extra_widgets.append(color_picker)
# append model AFTER _create_float_drag_per_channel_with_labels_and_control call
widget_kwargs["model"] = model
models.append(model)
cls._create_control_state(
value_widget=color_picker,
mixed_overlay=None,
extra_widgets=extra_widgets,
**widget_kwargs,
label=label,
)
else:
widget_kwargs = {}
widget_kwargs.update(cls._get_attr_value_soft_range_kwargs(metadata, model))
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
labels = [("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F), ("W", 0xFFFFFFFF)]
if type_name.type.typeName.endswith("i"):
value_widget = cls._create_int_drag_per_channel_with_labels_and_control(
models, metadata, labels, **widget_kwargs
)
else:
value_widget = cls._create_float_drag_per_channel_with_labels_and_control(
models, metadata, labels, **widget_kwargs
)
# append model AFTER _create_float_drag_per_channel_with_labels_and_control call
models.append(model)
cls._create_attribute_context_menu(label, model)
value_widget.identifier = f"drag_per_channel_{attr_name}"
return models
@staticmethod
def _get_display_name(attr_name, metadata):
if not metadata:
return attr_name
return metadata.get(Sdf.PropertySpec.DisplayNameKey, attr_name)
@staticmethod
def _get_type_name(metadata):
type_name = metadata.get(Sdf.PrimSpec.TypeNameKey, "unknown type")
return Sdf.ValueTypeNames.Find(type_name)
@staticmethod
def _create_mixed_text_overlay(widget_model=None, model=None, comp=-1, content_clipping: bool = False):
with ui.ZStack(alignment=ui.Alignment.CENTER):
stack = ui.ZStack(alignment=ui.Alignment.CENTER, visible=False, content_clipping=content_clipping)
with stack:
ui.Rectangle(alignment=ui.Alignment.CENTER, name="mixed_overlay_text")
ui.Label("Mixed", name="mixed_overlay", alignment=ui.Alignment.CENTER)
if widget_model and model is not None:
hidden_on_edit = False
def begin_edit(_):
nonlocal hidden_on_edit
if stack.visible:
stack.visible = False
hidden_on_edit = True
def end_edit(_):
nonlocal hidden_on_edit
if hidden_on_edit:
if model.is_comp_ambiguous(comp):
stack.visible = True
hidden_on_edit = False
widget_model.add_begin_edit_fn(begin_edit)
widget_model.add_end_edit_fn(end_edit)
return stack
@classmethod
def _create_control_state(cls, model, value_widget=None, mixed_overlay=None, extra_widgets=[], **kwargs):
# Allow widgets to be displayed without the control state
if kwargs.get("no_control_state"):
return
control_state_mgr = ControlStateManager.get_instance()
no_default = kwargs.get("no_default", False)
widget_comp_index = kwargs.get("widget_comp_index", -1)
original_widget_name = value_widget.name if value_widget else ""
original_widget_state = {}
if value_widget:
original_widget_state["value_widget"] = value_widget.enabled
else:
original_widget_state["value_widget"] = True
for index, widget in enumerate(extra_widgets):
original_widget_state[f"extra_widgets_{index}"] = widget.enabled
def build_fn():
state = model.control_state
# no_default is actually no state
if no_default:
state = 0
action, icon_path, tooltip = control_state_mgr.build_control_state(
control_state=state,
model=model,
value_widget=value_widget,
extra_widgets=extra_widgets,
mixed_overlay=mixed_overlay,
original_widget_name=original_widget_name,
**kwargs,
)
with ui.VStack():
ui.Spacer()
button = ui.ImageWithProvider(
icon_path,
mouse_pressed_fn=action,
width=12,
height=5 if state == 0 else 12, # TODO let state decide
tooltip=tooltip,
)
ui.Spacer()
attr_paths = model.get_attribute_paths()
if attr_paths and len(attr_paths) > 0:
button.identifier = f"control_state_{attr_paths[0].elementString[1:]}"
frame = ui.Frame(build_fn=build_fn, width=0)
model.set_on_control_state_changed_fn(frame.rebuild)
if value_widget:
cls._create_attribute_context_menu(value_widget, model, widget_comp_index)
label_widget = kwargs.get("label", None)
if label_widget:
# When right click on label, always copy entire value
cls._create_attribute_context_menu(label_widget, model)
@classmethod
def _time_code_builder(
cls,
stage,
attr_name,
type_name,
metadata,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
with ui.HStack(spacing=HORIZONTAL_SPACING):
model_kwargs = get_model_kwargs(additional_widget_kwargs)
model_cls = get_model_cls(SdfTimeCodeModel, additional_widget_kwargs)
model = model_cls(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs)
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
range_min, range_max = cls._get_attr_value_range(metadata)
widget_kwargs = {"model": model}
widget_kwargs.update(cls._get_attr_value_soft_range_kwargs(metadata, model))
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.ZStack():
value_widget = cls._create_drag_or_slider(ui.FloatDrag, ui.FloatSlider, **widget_kwargs)
value_widget.identifier = f"timecode_{attr_name}"
mixed_overlay = cls._create_mixed_text_overlay()
cls._create_control_state(
value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs, label=label
)
return model
@staticmethod
def can_accept_file_drop(payload: str, model_weak, allow_multi_files=False) -> bool:
model_weak = model_weak()
if not model_weak:
return False
urls = payload.split("\n")
if not urls:
return False
if not allow_multi_files and len(urls) > 1:
carb.log_warn(f"sdf_asset_path_builder multifile drag/drop not supported")
return False
custom_data = model_weak.metadata.get(Sdf.PrimSpec.CustomDataKey, {})
file_exts_dict = custom_data.get("fileExts", {})
for url in urls:
accepted = False
if file_exts_dict:
for ext in file_exts_dict:
if fnmatch.fnmatch(url, ext):
accepted = True
break
if not accepted:
carb.log_warn(f"Dropped file {url} does not match allowed extensions {list(file_exts_dict.keys())}")
else:
# TODO support filtering by file extension
if "." in url:
# TODO dragging from stage view also result in a drop, which is a prim path not an asset path
# For now just check if dot presents in the url (indicating file extension).
accepted = True
if not accepted:
return False
return True
@staticmethod
def _convert_asset_path(path: str) -> str:
path_method = carb.settings.get_settings().get("/persistent/app/material/dragDropMaterialPath") or "relative"
if path_method.lower() == "relative":
if not Ar.GetResolver().IsRelativePath(path):
path = omni.usd.make_path_relative_to_current_edit_target(path)
return path
@classmethod
def _build_path_field(cls, model, stage, attr_name, widget_kwargs, frame, extra_widgets):
with ui.HStack():
def clear_name(widget: ui.StringField):
widget.model.set_value("")
def name_changed(model, widget: ui.Button, type):
val = model.get_value()
setattr(widget, type, not bool(val == "" or val == "@@"))
def locate_name_changed(model, widget: ui.Button, type):
# NOTE: changing style makes image dispear
enabled = True
if isinstance(model, SdfAssetPathAttributeModel):
enabled = model.is_valid_path()
# update widget
widget.enabled = enabled
widget.visible = enabled
widget.tooltip = "Locate File" if enabled else ""
def assign_value_fn(model, path: str, resolved_path: str=""):
model.set_value(path, resolved_path)
remove_style = {
"Button.Image::remove": {"image_url": str(ICON_PATH.joinpath("remove-text.svg"))},
"Button.Image::remove:hovered": {"image_url": str(ICON_PATH.joinpath("remove-text-hovered.svg"))},
}
with ui.ZStack():
with ui.ZStack(style=remove_style):
value_widget = ui.StringField(**widget_kwargs)
with ui.HStack():
ui.Spacer()
clear_widget_stack = ui.VStack(width=0, content_clipping=True) # vertically center the button
with clear_widget_stack:
ui.Spacer()
clear_widget = ui.Button(
"",
width=20,
height=20,
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
clicked_fn=lambda f=value_widget: clear_name(f),
name="remove",
)
ui.Spacer()
value_widget.model.add_value_changed_fn(
lambda m, w=clear_widget_stack: name_changed(m, w, "visible")
)
value_widget.model._value_changed()
value_widget.set_accept_drop_fn(
lambda url, model_weak=weakref.ref(model): cls.can_accept_file_drop(url, model_weak)
)
value_widget.set_drop_fn(
lambda event, model_weak=weakref.ref(model), stage_weak=weakref.ref(
stage
): cls._assign_asset_path_value(stage_weak, model_weak, event.mime_data, assign_value_fn, frame)
)
value_widget.identifier = f"sdf_asset_{attr_name}" + (
f"[{model.index}]" if hasattr(model, "index") else ""
)
clear_widget.identifier = f"sdf_clear_asset_{attr_name}" + (
f"[{model.index}]" if hasattr(model, "index") else ""
)
mixed_overlay = cls._create_mixed_text_overlay()
ui.Spacer(width=3)
style = {"image_url": str(ICON_PATH.joinpath("small_folder.png"))}
enabled = get_file_importer() is not None
browse_button = ui.Button(
style=style,
width=20,
tooltip="Browse..." if enabled else "File importer not available",
clicked_fn=lambda model_weak=weakref.ref(model), stage_weak=weakref.ref(
stage
): show_asset_file_picker(
"Select Asset...",
assign_value_fn,
model_weak,
stage_weak,
on_selected_fn=cls._assign_asset_resolved_value
),
enabled=enabled,
identifier=f"sdf_browse_asset_{attr_name}" + (f"[{model.index}]" if hasattr(model, "index") else ""),
)
extra_widgets.append(browse_button)
extra_widgets.append(ui.Spacer(width=3))
# Button to jump to the file in Content Window
def locate_file(model):
async def locate_file_async(model):
# omni.kit.window.content_browser is optional dependency
try:
import omni.client
import omni.kit.app
import os
await omni.kit.app.get_app().next_update_async()
url = ""
if isinstance(model, SdfAssetPathAttributeModel):
url = model.get_resolved_path()
if url:
url = f"{omni.usd.correct_filename_case(os.path.dirname(url))}/{os.path.basename(url)}"
elif isinstance(model, ui.AbstractValueModel):
url = model.get_value_as_string()
if not url:
return
client_url = omni.client.break_url(url)
if client_url:
url = omni.client.make_url(
scheme=client_url.scheme,
user=client_url.user,
host=client_url.host,
port=client_url.port,
path=client_url.path,
)
import omni.kit.window.content_browser
instance = omni.kit.window.content_browser.get_instance()
instance.navigate_to(url)
except Exception as e:
carb.log_warn(f"Failed to locate file: {e}")
asyncio.ensure_future(locate_file_async(model))
style["image_url"] = str(ICON_PATH.joinpath("find.png"))
enabled = True
if isinstance(model, SdfAssetPathAttributeModel):
enabled = model.is_valid_path()
locate_widget = ui.Button(
style=style,
width=20,
enabled=enabled,
visible=enabled,
tooltip="Locate File" if enabled else "",
clicked_fn=lambda model=model: locate_file(model),
identifier=f"sdf_locate_asset_{attr_name}" + (f"[{model.index}]" if hasattr(model, "index") else ""),
)
value_widget.model.add_value_changed_fn(lambda m, w=locate_widget: locate_name_changed(m, w, "enabled"))
return value_widget, mixed_overlay
@classmethod
def _assign_asset_path_value(
cls, stage_weak, model_weak, payload: str, assign_value_fn: Callable[[Any, str], None], frame=None
):
stage_weak = stage_weak()
if not stage_weak:
return
model_weak = model_weak()
if not model_weak:
return
urls = payload.split("\n")
with omni.kit.undo.group():
for path in urls:
path = cls._convert_asset_path(path)
assign_value_fn(model_weak, path.replace("\\", "/"))
if frame:
frame.rebuild()
@classmethod
def _assign_asset_resolved_value(
cls, stage_weak, model_weak, payload: str, assign_value_fn: Callable[[Any, str], None], frame=None
):
model = model_weak()
if not model:
return
urls = payload.split("\n")
with omni.kit.undo.group():
for path in urls:
assign_value_fn(model, cls._convert_asset_path(path).replace("\\", "/"), path)
if frame:
frame.rebuild()
@classmethod
def _create_path_widget(
cls, model, stage, attr_name, metadata, prim_paths, additional_label_kwargs, additional_widget_kwargs
):
if "colorSpace" in metadata:
colorspace_model = MetadataObjectModel(
stage,
[path.AppendProperty(attr_name) for path in prim_paths],
False,
metadata,
key="colorSpace",
default="auto",
options=["auto", "raw", "sRGB"],
)
else:
colorspace_model = None
def build_frame(
cls, model, colorspace_model, frame, stage, attr_name, metadata, prim_paths,
additional_label_kwargs, additional_widget_kwargs
):
extra_widgets = []
with ui.VStack():
with ui.HStack(spacing=HORIZONTAL_SPACING):
label = cls._create_label(attr_name, metadata, additional_label_kwargs)
widget_kwargs = {"name": "models", "model": model}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
value_widget, mixed_overlay = cls._build_path_field(
model, stage, attr_name, widget_kwargs, frame, extra_widgets
)
cls._create_control_state(
value_widget=value_widget,
mixed_overlay=mixed_overlay,
extra_widgets=extra_widgets,
**widget_kwargs,
label=label,
)
if isinstance(model, SdfAssetPathAttributeModel):
cls._build_asset_checkpoint_ui(model, frame)
if colorspace_model:
ui.Spacer(height=5)
with ui.HStack(spacing=HORIZONTAL_SPACING):
label = cls._create_label(
cls._get_display_name(attr_name, metadata) + " Color Space", {}, additional_label_kwargs
)
with ui.ZStack():
value_widget = ui.ComboBox(colorspace_model, name="choices")
value_widget.identifier = f"colorspace_{attr_name}"
mixed_overlay = cls._create_mixed_text_overlay()
widget_kwargs = {"no_default": True}
cls._create_control_state(
colorspace_model, value_widget, mixed_overlay, **widget_kwargs, label=label
)
frame = ui.Frame(width=omni.ui.Percent(100))
frame.set_build_fn(
lambda: build_frame(
cls,
model,
colorspace_model,
frame,
stage,
attr_name,
metadata,
prim_paths,
additional_label_kwargs,
additional_widget_kwargs,
)
)
if colorspace_model:
# Returns colorspace model also so it could receive updates.
return [model, colorspace_model]
else:
return [model]
@classmethod
def _create_filepath_for_ui_type(
cls, stage, attr_name, metadata, prim_paths: List[Sdf.Path], additional_label_kwargs, additional_widget_kwargs
):
model = None
ui_type = cls._get_attr_value_ui_type(metadata)
if ui_type == "filePath":
model_kwargs = get_model_kwargs(additional_widget_kwargs)
model_cls = get_model_cls(UsdAttributeModel, additional_widget_kwargs, key="no_allowed_tokens_model_cls")
model = model_cls(stage, [path.AppendProperty(attr_name) for path in prim_paths], False, metadata, **model_kwargs)
widget_kwargs = {"name": "models"}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
cls._create_path_widget(
model, stage, attr_name, metadata, prim_paths, additional_label_kwargs, widget_kwargs
)
return model
| 85,426 | Python | 40.65139 | 130 | 0.524735 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/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 os, sys
import carb
import omni.kit.ui
import weakref
from functools import partial
from pxr import Usd, Sdf, UsdShade, UsdGeom, UsdLux
from .prim_selection_payload import PrimSelectionPayload
class ContextMenuEvent:
"""The object comatible with ContextMenu"""
def __init__(self, payload: PrimSelectionPayload, menu_items: list, xpos: int, ypos: int):
self.menu_items = menu_items
self.payload = payload
self.type = 0
self.xpos = xpos
self.ypos = ypos
class ContextMenu:
def __init__(self):
pass
def on_mouse_event(self, event: ContextMenuEvent):
# check its expected event
if event.type != int(omni.kit.ui.MenuEventType.ACTIVATE):
return
# setup objects, this is passed to all functions
objects = {
"stage": event.payload.get_stage(),
"prim_list": event.payload._payload,
"menu_xpos": event.xpos,
"menu_ypos": event.ypos,
}
menu_list = []
for item in event.menu_items:
name = item.path
parts = item.path.split("/")
if len(parts) < 2:
menu_list.append(item.get_dict(event.payload))
else:
last_name = parts.pop()
first_name = parts.pop(0)
menu_sublist = None
for menu_item in menu_list:
if first_name in menu_item["name"]:
menu_sublist = menu_item["name"][first_name]
break
if menu_sublist is None:
menu_list.append({"glyph": item.glyph, "name": {first_name: []}})
menu_sublist = menu_list[-1]["name"][first_name]
for part in parts:
sublist = None
for menu_item in menu_sublist:
if part in menu_item["name"]:
sublist = menu_item["name"][part]
break
if sublist is None:
menu_sublist.append({"glyph": item.glyph, "name": {part: []}})
menu_sublist = menu_sublist[-1]["name"][part]
else:
menu_sublist = sublist
menu_sublist.append(item.get_dict(event.payload, last_name))
# show menu
self.show_context_menu(objects=objects, menu_list=menu_list)
def show_context_menu(self, objects: dict = {}, menu_list: list = []):
# get context menu core functionality & check its enabled
context_menu = omni.kit.context_menu.get_instance()
if context_menu is None:
carb.log_warn("context_menu is disabled!")
return None
context_menu.show_context_menu("prim_path_widget", objects, menu_list)
| 3,295 | Python | 34.826087 | 94 | 0.567527 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/usd_attribute_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 copy
import weakref
from typing import List
import omni.ui as ui
from pxr import Gf, Sdf, Tf, Usd, UsdShade
from .usd_model_base import *
class FloatModel(ui.SimpleFloatModel):
def __init__(self, parent):
super().__init__()
self._parent = weakref.ref(parent)
def begin_edit(self):
parent = self._parent()
parent.begin_edit(None)
def end_edit(self):
parent = self._parent()
parent.end_edit(None)
class IntModel(ui.SimpleIntModel):
def __init__(self, parent):
super().__init__()
self._parent = weakref.ref(parent)
def begin_edit(self):
parent = self._parent()
parent.begin_edit(None)
def end_edit(self):
parent = self._parent()
parent.end_edit(None)
class UsdAttributeModel(ui.AbstractValueModel, UsdBase):
"""The value model that is reimplemented in Python to watch a USD attribute path"""
def __init__(
self,
stage: Usd.Stage,
attribute_paths: List[Sdf.Path],
self_refresh: bool,
metadata: dict,
change_on_edit_end=False,
**kwargs,
):
UsdBase.__init__(self, stage, attribute_paths, self_refresh, metadata, change_on_edit_end, **kwargs)
ui.AbstractValueModel.__init__(self)
def clean(self):
UsdBase.clean(self)
def begin_edit(self):
UsdBase.begin_edit(self)
ui.AbstractValueModel.begin_edit(self)
def end_edit(self):
UsdBase.end_edit(self)
ui.AbstractValueModel.end_edit(self)
def get_value_as_string(self, elide_big_array=True) -> str:
self._update_value()
if self._value is None:
return ""
elif self._is_big_array and elide_big_array:
return "[...]"
else:
return str(self._value)
def get_value_as_float(self) -> float:
self._update_value()
if self._value is None:
return 0.0
else:
if hasattr(self._value, "__len__"):
return float(self._value[self._channel_index])
return float(self._value)
def get_value_as_bool(self) -> bool:
self._update_value()
if self._value is None:
return False
else:
if hasattr(self._value, "__len__"):
return bool(self._value[self._channel_index])
return bool(self._value)
def get_value_as_int(self) -> int:
self._update_value()
if self._value is None:
return 0
else:
if hasattr(self._value, "__len__"):
return int(self._value[self._channel_index])
return int(self._value)
def set_value(self, value):
if UsdBase.set_value(self, value):
self._value_changed()
def _on_dirty(self):
self._value_changed()
class GfVecAttributeSingleChannelModel(UsdAttributeModel):
def __init__(
self,
stage: Usd.Stage,
attribute_paths: List[Sdf.Path],
channel_index: int,
self_refresh: bool,
metadata: dict,
change_on_edit_end=False,
**kwargs,
):
self._channel_index = channel_index
super().__init__(stage, attribute_paths, self_refresh, metadata, change_on_edit_end, **kwargs)
def get_value_as_string(self, **kwargs) -> str:
self._update_value()
if self._value is None:
return ""
else:
return str(self._value[self._channel_index])
def get_value_as_float(self) -> float:
self._update_value()
if self._value is None:
return 0.0
else:
if hasattr(self._value, "__len__"):
return float(self._value[self._channel_index])
return float(self._value)
def get_value_as_bool(self) -> bool:
self._update_value()
if self._value is None:
return False
else:
if hasattr(self._value, "__len__"):
return bool(self._value[self._channel_index])
return bool(self._value)
def get_value_as_int(self) -> int:
self._update_value()
if self._value is None:
return 0
else:
if hasattr(self._value, "__len__"):
return int(self._value[self._channel_index])
return int(self._value)
def set_value(self, value):
vec_value = copy.copy(self._value)
vec_value[self._channel_index] = value
if UsdBase.set_value(self, vec_value, self._channel_index):
self._value_changed()
def is_different_from_default(self):
"""Override to only check channel"""
if super().is_different_from_default():
return self._comp_different_from_default[self._channel_index]
return False
class TfTokenAttributeModel(ui.AbstractItemModel, UsdBase):
class AllowedTokenItem(ui.AbstractItem):
def __init__(self, item):
super().__init__()
self.token = item
self.model = ui.SimpleStringModel(item)
def __init__(self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], self_refresh: bool, metadata: dict):
UsdBase.__init__(self, stage, attribute_paths, self_refresh, metadata)
ui.AbstractItemModel.__init__(self)
self._allowed_tokens = []
self._current_index = ui.SimpleIntModel()
self._current_index.add_value_changed_fn(self._current_index_changed)
self._updating_value = False
self._has_index = False
self._update_value()
self._has_index = True
def clean(self):
UsdBase.clean(self)
def get_item_children(self, item):
self._update_value()
return self._allowed_tokens
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
def begin_edit(self, item):
UsdBase.begin_edit(self)
def end_edit(self, item):
UsdBase.end_edit(self)
def _current_index_changed(self, model):
if not self._has_index:
return
# if we're updating from USD notice change to UI, don't call set_value
if self._updating_value:
return
index = model.as_int
if self.set_value(self._get_value_from_index(index)):
self._item_changed(None)
def _get_allowed_tokens(self, attr):
return attr.GetMetadata("allowedTokens")
def _update_allowed_token(self, token_item=AllowedTokenItem):
self._allowed_tokens = []
# For multi prim editing, the allowedTokens should all be the same
attributes = self._get_attributes()
attr = attributes[0] if len(attributes) > 0 else None
if attr:
for t in self._get_allowed_tokens(attr):
self._allowed_tokens.append(token_item(t))
def _update_value(self, force=False):
was_updating_value = self._updating_value
self._updating_value = True
if UsdBase._update_value(self, force):
# TODO don't have to do this every time. Just needed when "allowedTokens" actually changed
self._update_allowed_token()
index = -1
for i in range(0, len(self._allowed_tokens)):
if self._allowed_tokens[i].token == self._value:
index = i
if index != -1 and self._current_index.as_int != index:
self._current_index.set_value(index)
self._item_changed(None)
self._updating_value = was_updating_value
def _on_dirty(self):
self._item_changed(None)
def get_value_as_token(self):
index = self._current_index.as_int
return self._allowed_tokens[index].token
def is_allowed_token(self, token):
return token in [allowed.token for allowed in self._allowed_tokens]
def _get_value_from_index(self, index):
return self._allowed_tokens[index].token
class MdlEnumAttributeModel(ui.AbstractItemModel, UsdBase):
def __init__(self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], self_refresh: bool, metadata: dict):
UsdBase.__init__(self, stage, attribute_paths, self_refresh, metadata)
ui.AbstractItemModel.__init__(self)
self._options = []
self._current_index = ui.SimpleIntModel()
self._current_index.add_value_changed_fn(self._current_index_changed)
self._updating_value = False
self._has_index = False
self._update_value()
self._has_index = True
def clean(self):
UsdBase.clean(self)
def get_item_children(self, item):
self._update_value()
return self._options
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
def begin_edit(self, item):
UsdBase.begin_edit(self)
def end_edit(self, item):
UsdBase.end_edit(self)
def _current_index_changed(self, model):
if not self._has_index:
return
# if we're updating from USD notice change to UI, don't call set_value
if self._updating_value:
return
index = model.as_int
if self.set_value(self._options[index].value):
self._item_changed(None)
def _update_option(self):
self._options = []
# For multi prim editing, the options should all be the same
attributes = self._get_attributes()
attr = attributes[0] if len(attributes) > 0 else None
if attr and isinstance(attr, Usd.Attribute):
shade_input = UsdShade.Input(attr)
if shade_input and shade_input.HasRenderType() and shade_input.HasSdrMetadataByKey("options"):
options = shade_input.GetSdrMetadataByKey("options").split("|")
class OptionItem(ui.AbstractItem):
def __init__(self, display_name: str, value: int):
super().__init__()
self.model = ui.SimpleStringModel(display_name)
self.value = value
for option in options:
kv = option.split(":")
self._options.append(OptionItem(kv[0], int(kv[1])))
def _update_value(self, force=False):
was_updating_value = self._updating_value
self._updating_value = True
if UsdBase._update_value(self, force):
# TODO don't have to do this every time. Just needed when "option" actually changed
self._update_option()
index = -1
for i in range(0, len(self._options)):
if self._options[i].value == self._value:
index = i
if index != -1 and self._current_index.as_int != index:
self._current_index.set_value(index)
self._item_changed(None)
self._updating_value = was_updating_value
def _on_dirty(self):
self._item_changed(None)
def get_value_as_string(self):
index = self._current_index.as_int
return self._options[index].model.as_string
def is_allowed_enum_string(self, enum_str):
return enum_str in [allowed.model.as_string for allowed in self._options]
def set_from_enum_string(self, enum_str):
if not self.is_allowed_enum_string(enum_str):
return
new_index = -1
for index, option in enumerate(self._options):
if option.model.as_string == enum_str:
new_index = index
break
if new_index != -1:
self._current_index.set_value(new_index)
class GfVecAttributeModel(ui.AbstractItemModel, UsdBase):
def __init__(
self,
stage: Usd.Stage,
attribute_paths: List[Sdf.Path],
comp_count: int,
tf_type: Tf.Type,
self_refresh: bool,
metadata: dict,
**kwargs,
):
UsdBase.__init__(self, stage, attribute_paths, self_refresh, metadata, **kwargs)
ui.AbstractItemModel.__init__(self)
self._comp_count = comp_count
self._data_type_name = "Vec" + str(self._comp_count) + tf_type.typeName[-1]
self._data_type = getattr(Gf, self._data_type_name)
class UsdVectorItem(ui.AbstractItem):
def __init__(self, model):
super().__init__()
self.model = model
# Create root model
self._root_model = ui.SimpleIntModel()
self._root_model.add_value_changed_fn(lambda a: self._item_changed(None))
# Create three models per component
if self._data_type_name.endswith("i"):
self._items = [UsdVectorItem(IntModel(self)) for i in range(self._comp_count)]
else:
self._items = [UsdVectorItem(FloatModel(self)) for i in range(self._comp_count)]
for item in self._items:
item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item))
self._edit_mode_counter = 0
def clean(self):
UsdBase.clean(self)
def _construct_vector_from_item(self):
if self._data_type_name.endswith("i"):
data = [item.model.get_value_as_int() for item in self._items]
else:
data = [item.model.get_value_as_float() for item in self._items]
return self._data_type(data)
def _on_value_changed(self, item):
"""Called when the submodel is changed"""
if self._edit_mode_counter > 0:
vector = self._construct_vector_from_item()
index = self._items.index(item)
if vector and self.set_value(vector, index):
# Read the new value back in case hard range clamped it
item.model.set_value(self._value[index])
self._item_changed(item)
else:
# If failed to update value in model, revert the value in submodel
item.model.set_value(self._value[index])
def _update_value(self, force=False):
if UsdBase._update_value(self, force):
if not self._value:
for i in range(len(self._items)):
self._items[i].model.set_value(0.0)
return
for i in range(len(self._items)):
self._items[i].model.set_value(self._value[i])
def _on_dirty(self):
self._item_changed(None)
def get_item_children(self, item):
"""Reimplemented from the base class"""
self._update_value()
return self._items
def get_item_value_model(self, item, column_id):
"""Reimplemented from the base class"""
if item is None:
return self._root_model
return item.model
def begin_edit(self, item):
"""
Reimplemented from the base class.
Called when the user starts editing.
"""
self._edit_mode_counter += 1
UsdBase.begin_edit(self)
def end_edit(self, item):
"""
Reimplemented from the base class.
Called when the user finishes editing.
"""
UsdBase.end_edit(self)
self._edit_mode_counter -= 1
class SdfAssetPathAttributeModel(UsdAttributeModel):
"""The value model that is reimplemented in Python to watch a USD attribute path"""
def __init__(self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], self_refresh: bool, metadata: dict):
super().__init__(stage, attribute_paths, self_refresh, metadata, True, treat_array_entry_as_comp=True)
def get_value_as_string(self, **kwargs):
self._update_value()
return self._get_value_as_string(self._value)
def is_valid_path(self) -> bool:
return self._is_valid_path(self._value)
def get_resolved_path(self):
self._update_value()
return self._get_resolved_path(self._value)
def set_value(self, path, resolved_path: str=""):
value = path
if not isinstance(path, Sdf.AssetPath):
if resolved_path:
value = Sdf.AssetPath(path, resolved_path)
else:
value = Sdf.AssetPath(path)
if UsdBase.set_value(self, value):
self._value_changed()
def _is_prev_same(self):
# Strip the resolvedPath from the AssetPath for the comparison, since the prev values don't have resolvedPath.
return [Sdf.AssetPath(value.path) for value in self._real_values] == self._prev_real_values
def _save_real_values_as_prev(self):
# Strip the resolvedPath from the AssetPath so that it can be recomputed.
self._prev_real_values = [Sdf.AssetPath(value.path) for value in self._real_values]
def _change_property(self, path: Sdf.Path, new_value, old_value):
if path.name == "info:mdl:sourceAsset" and new_value.path:
if isinstance(new_value, Sdf.AssetPath):
# make the path relative to current edit target layer
relative_path = omni.usd.make_path_relative_to_current_edit_target(new_value.path)
new_value = Sdf.AssetPath(relative_path, new_value.resolvedPath)
if path.name == "info:mdl:sourceAsset":
if isinstance(new_value, Sdf.AssetPath):
# "info:mdl:sourceAsset" when is changed update "info:mdl:sourceAsset:subIdentifier"
stage = self._stage
asset_attr = stage.GetAttributeAtPath(path)
subid_attr = stage.GetAttributeAtPath(
path.GetPrimPath().AppendElementString(".info:mdl:sourceAsset:subIdentifier")
)
if asset_attr and subid_attr:
mdl_path = new_value.resolvedPath if new_value.resolvedPath else new_value.path
if mdl_path:
import asyncio
baseclass = super()
def have_subids(id_list: list):
if len(id_list) > 0:
with omni.kit.undo.group():
baseclass._change_property(subid_attr.GetPath(), str(id_list[0]), None)
baseclass._change_property(path, new_value, old_value)
asyncio.ensure_future(
omni.kit.material.library.get_subidentifier_from_mdl(
mdl_file=mdl_path, on_complete_fn=have_subids, use_functions=True, show_alert=True
)
)
return
else:
super()._change_property(subid_attr.GetPath(), "", None)
super()._change_property(path, new_value, old_value)
# private functions to be shared with SdfAssetPathArrayAttributeSingleEntryModel
def _get_value_as_string(self, value, **kwargs):
return value.path if value else ""
def _is_valid_path(self, value) -> bool:
if not value:
return False
path = value.path
if path.lower().startswith("http"):
return False
return bool(path)
def _get_resolved_path(self, value):
if self._ambiguous:
return "Mixed"
else:
return value.resolvedPath.replace("\\", "/") if value else ""
class SdfAssetPathArrayAttributeSingleEntryModel(SdfAssetPathAttributeModel):
def __init__(
self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], index: int, self_refresh: bool, metadata: dict
):
self._index = index
super().__init__(stage, attribute_paths, self_refresh, metadata)
@property
def index(self):
return self._index
def get_value_as_string(self, **kwargs):
self._update_value()
return self._get_value_as_string(self._value[self._index])
def get_value(self):
return super().get_value()[self._index]
def is_valid_path(self) -> bool:
self._update_value()
return self._is_valid_path(self._value[self._index])
def get_resolved_path(self):
self._update_value()
return self._get_resolved_path(self._value[self._index])
def set_value(self, path, resolved_path: str=""):
value = path
if not isinstance(path, Sdf.AssetPath):
if resolved_path:
value = Sdf.AssetPath(path, resolved_path)
else:
value = Sdf.AssetPath(path)
vec_value = Sdf.AssetPathArray(self._value)
vec_value[self._index] = value
if UsdBase.set_value(self, vec_value, self._index):
self._value_changed()
def _is_prev_same(self):
# Strip the resolvedPath from the AssetPath for the comparison, since the prev values don't have resolvedPath.
return [
[Sdf.AssetPath(value.path) for value in values] for values in self._real_values
] == self._prev_real_values
def _save_real_values_as_prev(self):
# Strip the resolvedPath from the AssetPath so that it can be recomputed.
self._prev_real_values = [[Sdf.AssetPath(value.path) for value in values] for values in self._real_values]
class SdfAssetPathArrayAttributeItemModel(ui.AbstractItemModel):
class SdfAssetPathItem(ui.AbstractItem):
"""Single item of the model"""
def __init__(
self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], index: int, self_refresh: bool, metadata: dict
):
super().__init__()
self.sdf_asset_path_model = SdfAssetPathArrayAttributeSingleEntryModel(
stage, attribute_paths, index, self_refresh, metadata
)
def destroy(self):
self.sdf_asset_path_model.clean()
def __init__(self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], self_refresh: bool, metadata: dict, delegate):
super().__init__()
self._delegate = delegate # keep a reference of the delegate os it's not destroyed
self._value_model = UsdAttributeModel(stage, attribute_paths, False, metadata)
value = self._value_model.get_value()
self._entries = []
self._repopulate_entries(value)
def clean(self):
self._delegate = None
for entry in self._entries:
entry.destroy()
self._entries.clear()
if self._value_model:
self._value_model.clean()
self._value_model = None
@property
def value_model(self) -> UsdAttributeModel:
return self._value_model
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return.
return []
return self._entries
def get_item_value_model_count(self, item):
return 1
def get_item_value_model(self, item, column_id):
return (item.sdf_asset_path_model, self._value_model)
def get_drag_mime_data(self, item):
return str(item.sdf_asset_path_model.index)
def drop_accepted(self, target_item, source, drop_location=-1):
try:
source_id = self._entries.index(source)
except ValueError:
# Not in the list. This is the source from another model.
return False
return not target_item and drop_location >= 0
def drop(self, target_item, source, drop_location=-1):
try:
source_id = self._entries.index(source)
except ValueError:
# Not in the list. This is the source from another model.
return
if source_id == drop_location:
# Nothing to do
return
value = list(self._value_model.get_value())
moved_entry_value = value[source_id]
del value[source_id]
if drop_location > len(value):
# Drop it to the end
value.append(moved_entry_value)
else:
if source_id < drop_location:
# Because when we removed source, the array became shorter
drop_location = drop_location - 1
value.insert(drop_location, moved_entry_value)
self._value_model.set_value(value)
def _repopulate_entries(self, value: Sdf.AssetPathArray):
for entry in self._entries:
entry.destroy()
self._entries.clear()
stage = self._value_model.stage
metadata = self._value_model.metadata
attribute_paths = self._value_model.get_attribute_paths()
for i in range(len(value)):
model = SdfAssetPathArrayAttributeItemModel.SdfAssetPathItem(stage, attribute_paths, i, False, metadata)
self._entries.append(model)
self._item_changed(None)
def _on_usd_changed(self, *args, **kwargs):
# forward to all sub-models
self._value_model._on_usd_changed(*args, **kwargs)
for entry in self._entries:
entry.sdf_asset_path_model._on_usd_changed(*args, **kwargs)
def _set_dirty(self, *args, **kwargs):
# forward to all sub-models
self._value_model._set_dirty(*args, **kwargs)
new_value = self._value_model.get_value()
if len(new_value) != len(self._entries):
self._repopulate_entries(new_value)
else:
for entry in self._entries:
entry.sdf_asset_path_model._set_dirty(*args, **kwargs)
def get_value(self, *args, **kwargs):
return self._value_model.get_value(*args, **kwargs)
def set_value(self, *args, **kwargs):
return self._value_model.set_value(*args, **kwargs)
class GfQuatAttributeModel(ui.AbstractItemModel, UsdBase):
def __init__(
self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], tf_type: Tf.Type, self_refresh: bool, metadata: dict
):
UsdBase.__init__(self, stage, attribute_paths, self_refresh, metadata)
ui.AbstractItemModel.__init__(self)
data_type_name = "Quat" + tf_type.typeName[-1]
self._data_type = getattr(Gf, data_type_name)
class UsdQuatItem(ui.AbstractItem):
def __init__(self, model):
super().__init__()
self.model = model
# Create root model
self._root_model = ui.SimpleIntModel()
self._root_model.add_value_changed_fn(lambda a: self._item_changed(None))
# Create four models per component
self._items = [UsdQuatItem(FloatModel(self)) for i in range(4)]
for item in self._items:
item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item))
self._edit_mode_counter = 0
def clean(self):
UsdBase.clean(self)
def _on_value_changed(self, item):
"""Called when the submodel is chaged"""
if self._edit_mode_counter > 0:
quat = self._construct_quat_from_item()
if quat and self.set_value(quat, self._items.index(item)):
self._item_changed(item)
def _update_value(self, force=False):
if UsdBase._update_value(self, force):
for i in range(len(self._items)):
if i == 0:
self._items[i].model.set_value(self._value.real)
else:
self._items[i].model.set_value(self._value.imaginary[i - 1])
def _on_dirty(self):
self._item_changed(None)
def get_item_children(self, item):
"""Reimplemented from the base class"""
self._update_value()
return self._items
def get_item_value_model(self, item, column_id):
"""Reimplemented from the base class"""
if item is None:
return self._root_model
return item.model
def begin_edit(self, item):
"""
Reimplemented from the base class.
Called when the user starts editing.
"""
self._edit_mode_counter += 1
UsdBase.begin_edit(self)
def end_edit(self, item):
"""
Reimplemented from the base class.
Called when the user finishes editing.
"""
UsdBase.end_edit(self)
self._edit_mode_counter -= 1
def _construct_quat_from_item(self):
data = [item.model.get_value_as_float() for item in self._items]
return self._data_type(data[0], data[1], data[2], data[3])
# A data model for display orient(quaternion) as rotate(Euler)
class GfQuatEulerAttributeModel(ui.AbstractItemModel, UsdBase):
axes = [Gf.Vec3d(1, 0, 0), Gf.Vec3d(0, 1, 0), Gf.Vec3d(0, 0, 1)]
def __init__(
self, stage: Usd.Stage, attribute_paths: List[Sdf.Path], tf_type: Tf.Type, self_refresh: bool, metadata: dict
):
UsdBase.__init__(self, stage, attribute_paths, self_refresh, metadata)
ui.AbstractItemModel.__init__(self)
# The underline USD data is still a quaternion
data_type_name = "Quat" + tf_type.typeName[-1]
self._data_type = getattr(Gf, data_type_name)
class UsdFloatItem(ui.AbstractItem):
def __init__(self, model):
super().__init__()
self.model = model
self._root_model = ui.SimpleIntModel()
self._root_model.add_value_changed_fn(lambda a: self._item_changed(None))
# Create three models per component
self._items = [UsdFloatItem(FloatModel(self)) for _ in range(3)]
for item in self._items:
item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item))
self._edit_mode_counter = 0
def clean(self):
UsdBase.clean(self)
# Should be used to set the self._items to USD attribute
def _on_value_changed(self, item):
if self._edit_mode_counter > 0:
quat = self._compose([item.model.as_float for item in self._items])
if quat and self.set_value(quat):
self._item_changed(item)
# Unlike normal Vec3 or Quat, we have to update all four values all together
def update_to_submodels(self):
if self._edit_mode_counter != 0:
return
if self._value is not None:
e = self._decompose(self._value)
for i, item in enumerate(self._items):
item.model.set_value(e[i])
def _update_value(self, force=False):
if UsdBase._update_value(self, force):
self.update_to_submodels()
def _on_dirty(self):
self._item_changed(None)
def get_item_children(self, item):
self._update_value()
return self._items
def get_item_value_model(self, item, column_id):
if item is None:
return self._root_model
return item.model
def begin_edit(self, item):
self._edit_mode_counter += 1
UsdBase.begin_edit(self)
def end_edit(self, item):
UsdBase.end_edit(self)
self._edit_mode_counter -= 1
def _compose(self, eulers):
nrs = [Gf.Rotation(axis, eulers[i]) for i, axis in enumerate(self.axes)]
nr = nrs[2] * nrs[1] * nrs[0]
result = self._data_type(nr.GetQuat())
return result
def _decompose(self, value):
rot = Gf.Rotation(value)
eulers = rot.Decompose(*self.axes)
# round epsilons from decompose
eulers = [round(angle + 1e-4, 3) for angle in eulers]
return eulers
def _get_comp_num(self):
return 3
def _get_value_by_comp(self, value, comp: int):
e = self._decompose(value)
return e[comp]
def _update_value_by_comp(self, value, comp: int):
self_e = self._decompose(self._value)
e = self._decompose(value)
e[comp] = self_e[comp]
value = self._compose(e)
return value
def _compare_value_by_comp(self, val1, val2, comp: int):
return Gf.IsClose(self._get_value_by_comp(val1, comp), self._get_value_by_comp(val2, comp), 1e-6)
class GfMatrixAttributeModel(ui.AbstractItemModel, UsdBase):
def __init__(
self,
stage: Usd.Stage,
attribute_paths: List[Sdf.Path],
comp_count: int,
tf_type: Tf.Type,
self_refresh: bool,
metadata: dict,
):
UsdBase.__init__(self, stage, attribute_paths, self_refresh, metadata)
ui.AbstractItemModel.__init__(self)
self._comp_count = comp_count
data_type_name = "Matrix" + str(self._comp_count) + tf_type.typeName[-1]
self._data_type = getattr(Gf, data_type_name)
class UsdMatrixItem(ui.AbstractItem):
def __init__(self, model):
super().__init__()
self.model = model
# Create root model
self._root_model = ui.SimpleIntModel()
self._root_model.add_value_changed_fn(lambda a: self._item_changed(None))
# Create three models per component
self._items = [UsdMatrixItem(FloatModel(self)) for i in range(self._comp_count * self._comp_count)]
for item in self._items:
item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item))
self._edit_mode_counter = 0
def clean(self):
UsdBase.clean(self)
def _on_value_changed(self, item):
"""Called when the submodel is chaged"""
if self._edit_mode_counter > 0:
matrix = self._construct_matrix_from_item()
if matrix and self.set_value(matrix, self._items.index(item)):
self._item_changed(item)
def _update_value(self, force=False):
if UsdBase._update_value(self, force):
for i in range(len(self._items)):
self._items[i].model.set_value(self._value[i // self._comp_count][i % self._comp_count])
def _on_dirty(self):
self._item_changed(None)
# it's still better to call _value_changed for all child items
for child in self._items:
child.model._value_changed()
def get_item_children(self, item):
"""Reimplemented from the base class."""
self._update_value()
return self._items
def get_item_value_model(self, item, column_id):
"""Reimplemented from the base class."""
if item is None:
return self._root_model
return item.model
def begin_edit(self, item):
"""
Reimplemented from the base class.
Called when the user starts editing.
"""
self._edit_mode_counter += 1
UsdBase.begin_edit(self)
def end_edit(self, item):
"""
Reimplemented from the base class.
Called when the user finishes editing.
"""
UsdBase.end_edit(self)
self._edit_mode_counter -= 1
def _construct_matrix_from_item(self):
data = [item.model.get_value_as_float() for item in self._items]
matrix = []
for i in range(self._comp_count):
matrix_row = []
for j in range(self._comp_count):
matrix_row.append(data[i * self._comp_count + j])
matrix.append(matrix_row)
return self._data_type(matrix)
class UsdAttributeInvertedModel(UsdAttributeModel):
def get_value_as_bool(self) -> bool:
return not super().get_value_as_bool()
def get_value_as_string(self, **kwargs) -> str:
return str(self.get_value_as_bool())
def set_value(self, value):
super().set_value(not value)
def get_value(self):
return not super().get_value()
class SdfTimeCodeModel(UsdAttributeModel):
def _save_real_values_as_prev(self):
# SdfTimeCode cannot be inited from another SdfTimeCode, only from float (double in C++)..
self._prev_real_values = [Sdf.TimeCode(float(value)) for value in self._real_values]
| 36,215 | Python | 33.360531 | 120 | 0.586829 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/message_bus_events.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb.events
ADDITIONAL_CHANGED_PATH_EVENT_TYPE = carb.events.type_from_string("omni.usd.property.usd.additional_changed_path")
| 564 | Python | 42.461535 | 114 | 0.806738 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/references_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.
#
import weakref
import asyncio
from functools import lru_cache, partial
from typing import Callable, Union, Any
import carb
import omni.client
import omni.client.utils as clientutils
import omni.kit.app
import omni.kit.commands
import omni.kit.ui
import omni.ui as ui
import omni.usd
from omni.kit.window.file_importer import get_file_importer, ImportOptionsDelegate
from pxr import Sdf, Tf, Usd
from .asset_filepicker import show_asset_file_picker, replace_query
from .prim_selection_payload import PrimSelectionPayload
from .usd_property_widget import UsdPropertiesWidget
from .usd_property_widget_builder import UsdPropertiesWidgetBuilder, get_ui_style
from .widgets import ICON_PATH
from .versioning_helper import VersioningHelper
DEFAULT_PRIM_TAG = "<Default Prim>"
REF_LABEL_WIDTH = 80
@lru_cache()
def _get_plus_glyph():
return omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_context.svg")
def anchor_reference_asset_path_to_layer(ref: Sdf.Reference, intro_layer: Sdf.Layer, anchor_layer: Sdf.Layer):
asset_path = ref.assetPath
if asset_path:
asset_path = intro_layer.ComputeAbsolutePath(asset_path)
asset_url = clientutils.make_relative_url_if_possible(anchor_layer.identifier, asset_path)
# make a copy as Reference is immutable
ref = Sdf.Reference(
assetPath=asset_url,
primPath=ref.primPath,
layerOffset=ref.layerOffset,
customData=ref.customData,
)
return ref
def anchor_payload_asset_path_to_layer(ref: Sdf.Payload, intro_layer: Sdf.Layer, anchor_layer: Sdf.Layer):
asset_path = ref.assetPath
if asset_path:
asset_path = intro_layer.ComputeAbsolutePath(asset_path)
asset_url = clientutils.make_relative_url_if_possible(anchor_layer.identifier, asset_path)
# make a copy as Payload is immutable
ref = Sdf.Payload(
assetPath=asset_url,
primPath=ref.primPath,
layerOffset=ref.layerOffset,
)
return ref
# Model that calls edited_fn when end_edit or set_value (not when typing)
class TrackEditingStringModel(ui.SimpleStringModel):
def __init__(self, value: str = ""):
super().__init__()
self._editing = False
self._edited_fn = []
self.set_value(value)
def begin_edit(self):
super().begin_edit()
self._editing = True
def end_edit(self):
self._editing = False
super().end_edit()
self._call_edited_fn()
def set_value(self, value: str):
super().set_value(value)
if not self._editing:
self._call_edited_fn()
def add_edited_fn(self, fn):
self._edited_fn.append(fn)
def clear_edited_fn(self):
self._edited_fn.clear()
def _call_edited_fn(self):
for fn in self._edited_fn:
fn(self)
class PayloadReferenceInfo:
def __init__(self, asset_path_field, prim_path_field, prim_path_field_model, checkpoint_model):
self.asset_path_field = asset_path_field
self.prim_path_field = prim_path_field
self.prim_path_field_model = prim_path_field_model
self.checkpoint_model = checkpoint_model
def destroy(self):
if self.checkpoint_model:
self.checkpoint_model.destroy()
self.asset_path_field = None
self.prim_path_field = None
self.prim_path_field_model = None
self.checkpoint_model = None
def build_path_field(stage, init_value: str, jump_button: bool, use_payloads: bool, layer: Sdf.Layer = None):
with ui.HStack(style={"Button": {"margin": 0, "padding": 3, "border_radius": 2, "background_color": 0x00000000}}):
def assign_value_fn(model, path):
model.set_value(path)
def assign_reference_value(stage_weak, model_weak, path: str, assign_value_fn: Callable[[Any, str], None], frame=None):
stage = stage_weak()
if not stage:
return
model = model_weak()
if not model:
return
edit_layer = stage.GetEditTarget().GetLayer()
# make the path relative to current edit target layer
relative_url = clientutils.make_relative_url_if_possible(edit_layer.identifier, path)
assign_value_fn(model, relative_url)
def drop_accept(url: str):
if len(url.split('\n')) > 1:
carb.log_warn(f"build_path_field multifile drag/drop not supported")
return False
# TODO support filtering by file extension
if "." not in url:
# TODO dragging from stage view also result in a drop, which is a prim path not an asset path
# For now just check if dot presents in the url (indicating file extension).
return False
return True
with ui.ZStack():
model = TrackEditingStringModel(value=init_value)
string_field = ui.StringField(model=model)
string_field.set_accept_drop_fn(drop_accept)
string_field.set_drop_fn(
lambda event, model_weak=weakref.ref(model), stage_weak=weakref.ref(stage): assign_reference_value(
stage_weak, model_weak, event.mime_data, assign_value_fn=assign_value_fn
)
)
ui.Spacer(width=3)
def on_refresh_layer(model, weak_layer):
intro_layer = weak_layer()
url = model.get_value_as_string()
if url and intro_layer:
layer = Sdf.Find(intro_layer.ComputeAbsolutePath(url))
if layer:
async def reload(layer):
layer.Reload(force=True)
asyncio.ensure_future(reload(layer))
changed = False
ui.Button(
style={
"image_url": str(ICON_PATH.joinpath("refresh.svg")),
"padding": 1,
"margin": 0,
"Button.Image": {
"color": 0xFF9E9E9E if not changed else 0xFF248AE3,
},
"Button:hovered": {
"background_color": 0x00000000
}
},
width=20,
tooltip="Refresh Payload" if use_payloads else "Refresh Reference",
clicked_fn=lambda model=model, layer_weak=weakref.ref(layer) if layer else None: on_refresh_layer(model, layer_weak),
)
style = {
"image_url": str(ICON_PATH.joinpath("small_folder.png")),
"padding": 1,
"margin": 0,
"Button:hovered": {
"background_color": 0x00000000
}
}
ui.Button(
style=style,
width=20,
tooltip="Browse..." if get_file_importer() is not None else "File importer not available",
clicked_fn=lambda model_weak=weakref.ref(model), stage_weak=weakref.ref(stage), layer_weak=weakref.ref(
layer
) if layer else None: show_asset_file_picker(
"Select Payload..." if use_payloads else "Select Reference...",
assign_value_fn,
model_weak,
stage_weak,
layer_weak=layer_weak,
on_selected_fn=assign_reference_value,
),
enabled=get_file_importer() is not None,
)
if jump_button:
ui.Spacer(width=3)
# Button to jump to the file in Content Window
def locate_file(model, weak_layer):
# omni.kit.window.content_browser is optional dependency
try:
url = model.get_value_as_string()
if len(url) == 0:
return
if weak_layer:
weak_layer = weak_layer()
if weak_layer:
url = weak_layer.ComputeAbsolutePath(url)
# Remove the checkpoint and branch so navigate_to works
url = replace_query(url, None)
import omni.kit.window.content_browser
instance = omni.kit.window.content_browser.get_instance()
instance.navigate_to(url)
except Exception as e:
carb.log_warn(f"Failed to locate file: {e}")
style["image_url"] = str(ICON_PATH.joinpath("find.png"))
ui.Button(
style=style,
width=20,
tooltip="Locate File",
clicked_fn=lambda model=model, weak_layer=weakref.ref(layer) if layer else None: locate_file(
model, weak_layer
),
)
return string_field
class AddPayloadReferenceOptionsDelegate(ImportOptionsDelegate):
def __init__(self, prim_path_model):
super().__init__(
build_fn=self._build_ui_impl,
destroy_fn=self._destroy_impl
)
self._widget = None
self._prim_path_model = prim_path_model
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.HStack(height=0, spacing=2):
ui.Label("Prim Path", width=0)
ui.StringField().model = self._prim_path_model
def _destroy_impl(self, _):
self._prim_path_model = None
self._widget = None
class AddPayloadReferenceWindow:
def __init__(self, payload: PrimSelectionPayload, on_payref_added_fn: Callable, use_payloads=False):
self._payrefs = None
self._use_payloads = use_payloads
self._prim_path_model = ui.SimpleStringModel()
self._stage = payload.get_stage()
self._payload = payload
self._on_payref_added_fn = on_payref_added_fn
def set_payload(self, payload: PrimSelectionPayload):
self._stage = payload.get_stage()
self._payload = payload
def show(self, payrefs: Union[Sdf.Reference, Sdf.Payload]):
self._payrefs = payrefs
fallback = None
if self._stage and not self._stage.GetRootLayer().anonymous:
# If asset path is empty, open the USD rootlayer folder
# But only if filepicker didn't already have a folder remembered (thus fallback)
fallback = self._stage.GetRootLayer().identifier
self._prim_path_model.set_value(DEFAULT_PRIM_TAG)
def _on_file_selected(weak_self, filename, dirname, selections=[]):
weak_self = weak_self()
if not weak_self:
return
if not selections:
return
asset_path = f"{dirname or ''}/{filename}"
edit_layer = weak_self._stage.GetEditTarget().GetLayer()
# make the path relative to current edit target layer
asset_url = clientutils.make_relative_url_if_possible(edit_layer.identifier, asset_path)
prim_path = self._prim_path_model.get_value_as_string()
if prim_path == DEFAULT_PRIM_TAG:
prim_path = Sdf.Path()
payrefs = weak_self._payrefs
if not payrefs:
stage = weak_self._stage
payload_prim_path = weak_self._payload[-1]
if not stage or not payload_prim_path:
carb.log_warn(f"Cannot create payload/reference as stage/prim {payload_prim_path} is invalid")
return
anchor_prim = stage.GetPrimAtPath(payload_prim_path)
if not anchor_prim:
carb.log_warn(f"Cannot create payload/reference as failed to get prim {payload_prim_path}")
return
if weak_self._use_payloads:
anchor_prim.GetPayloads().SetPayloads([])
payrefs = anchor_prim.GetPayloads()
if not payrefs:
carb.log_warn("Failed to create payload")
return
else:
anchor_prim.GetReferences().SetReferences([])
payrefs = anchor_prim.GetReferences()
if not payrefs:
carb.log_warn("Failed to create reference")
return
command_kwargs = {
'stage': payrefs.GetPrim().GetStage(),
'prim_path': payrefs.GetPrim().GetPath()
}
if weak_self._use_payloads:
if prim_path:
payref = Sdf.Payload(asset_url, prim_path)
else:
payref = Sdf.Payload(asset_url)
command = "AddPayload"
command_kwargs['payload'] = payref
else:
if prim_path:
payref = Sdf.Reference(asset_url, prim_path)
else:
payref = Sdf.Reference(asset_url)
command = "AddReference"
command_kwargs['reference'] = payref
omni.kit.commands.execute(command, **command_kwargs)
weak_self._on_payref_added_fn(payrefs.GetPrim())
file_importer = get_file_importer()
if file_importer:
file_importer.show_window(
title="Select Payload..." if self._use_payloads else "Select Reference...",
import_button_label="Select",
import_handler=partial(_on_file_selected, weakref.ref(self)),
)
if fallback and not file_importer._dialog.get_current_directory():
file_importer._dialog.set_current_directory(fallback)
file_importer.add_import_options_frame(
"Payload Options" if self._use_payloads else "Reference Options",
AddPayloadReferenceOptionsDelegate(self._prim_path_model)
)
def destroy(self):
self._payrefs = None
self._prim_path_model = None
class PayloadReferenceWidget(UsdPropertiesWidget):
def __init__(self, use_payloads=False):
super().__init__(title="Payloads" if use_payloads else "References", collapsed=False, multi_edit=False)
self._ref_list_op = None
self._payrefs = None
self._ref_dict = {}
self._add_ref_window = [None, None]
self._ref_and_layers = []
self._checkpoint_combobox = None
self._use_payloads = use_payloads
self._payload_loaded_cb = None
self._stage_event_sub = (
omni.usd.get_context()
.get_stage_event_stream()
.create_subscription_to_pop(self._on_stage_event, name="PayloadReferenceWidget stage update")
)
# +add menu item(s)
from .prim_path_widget import PrimPathWidget
PrimPathWidget.add_button_menu_entry(
"Payload" if use_payloads else "Reference", show_fn=self._prim_is_selected, onclick_fn=lambda payload, u=self._use_payloads: self._on_add_payload_reference(payload, u)
)
def _undo_redo_on_change(self, cmds):
async def update_value(cmds):
if cmds and "SetPayLoadLoadSelectedPrimsCommand" in cmds:
last_prim = self._get_prim(self._payload[-1])
if last_prim:
self._payload_loaded_cb.model.set_value(last_prim.IsLoaded())
if cmds and self._payload_loaded_cb:
asyncio.ensure_future(update_value(cmds))
def _on_stage_event(self, event):
if event.type == int(omni.usd.StageEventType.CLOSING) or event.type == int(omni.usd.StageEventType.OPENED):
for window in self._add_ref_window:
if window:
window.destroy()
self._add_ref_window = [None, None]
def _on_add_payload_reference(self, payload: PrimSelectionPayload, use_payloads: bool):
ref_window_index = 0 if self._use_payloads else 1
if not self._add_ref_window[ref_window_index]:
self._add_ref_window[ref_window_index] = AddPayloadReferenceWindow(payload, self._on_payload_reference_added, use_payloads=use_payloads)
else:
self._add_ref_window[ref_window_index].set_payload(payload)
self._add_ref_window[ref_window_index].show(self._payrefs)
def _on_payload_reference_added(self, prim: Usd.Prim):
property_window = omni.kit.window.property.get_window()
if property_window:
property_window.request_rebuild()
def _prim_is_selected(self, objects: dict):
if not "prim_list" in objects or not "stage" in objects:
return False
stage = objects["stage"]
if not stage:
return False
return len(objects["prim_list"]) == 1
def clean(self):
self.reset()
for window in self._add_ref_window:
if window:
window.destroy()
self._add_ref_window = [None, None]
self._stage_event_sub = None
super().clean()
def reset(self):
if self._listener:
self._listener.Revoke()
self._listener = None
omni.kit.undo.unsubscribe_on_change(self._undo_redo_on_change)
self._ref_list_op = None
self._payrefs = None
for ref, info in self._ref_dict.items():
info.destroy()
self._ref_dict.clear()
self._ref_and_layers.clear()
if self._checkpoint_combobox:
self._checkpoint_combobox.destroy()
self._checkpoint_combobox = None
super().reset()
def on_new_payload(self, payload):
"""
See PropertyWidget.on_new_payload
"""
if not super().on_new_payload(payload):
return False
if not self._payload or len(self._payload) != 1: # single edit for now
return False
anchor_prim = None
for prim_path in self._payload:
prim = self._get_prim(prim_path)
if not prim:
return False
anchor_prim = prim
# only show if prim has payloads/references
if anchor_prim:
if self._use_payloads:
ref_and_layers = omni.usd.get_composed_payloads_from_prim(anchor_prim)
return len(ref_and_layers) > 0
ref_and_layers = omni.usd.get_composed_references_from_prim(anchor_prim)
return len(ref_and_layers) > 0
return False
def build_impl(self):
"""
See PropertyWidget.build_impl
"""
if not self._use_payloads:
super().build_impl()
else:
def on_checkbox_toggle(layer_name, model):
async def set_loaded(layer_name, state):
omni.kit.commands.execute("SetPayLoadLoadSelectedPrimsCommand", selected_paths=[layer_name], value=state)
asyncio.ensure_future(set_loaded(layer_name, model.get_value_as_bool()))
last_prim = self._get_prim(self._payload[-1])
if not last_prim:
return
self._button_frame = ui.Frame()
with self._button_frame:
with ui.ZStack():
super().build_impl()
with ui.HStack():
ui.Spacer(width=ui.Fraction(0.5))
with ui.VStack(width=0, content_clipping=True):
ui.Spacer(height=5)
self._payload_loaded_cb = ui.CheckBox()
self._payload_loaded_cb.model.set_value(last_prim.IsLoaded())
self._payload_loaded_cb.model.add_value_changed_fn(
partial(on_checkbox_toggle, last_prim.GetPath().pathString))
ui.Spacer(width=5)
def build_items(self):
self.reset()
if len(self._payload) == 0:
return
last_prim = self._get_prim(self._payload[-1])
if not last_prim:
return
stage = last_prim.GetStage()
if not stage:
return
self._listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_usd_changed, stage)
omni.kit.undo.subscribe_on_change(self._undo_redo_on_change)
if self._use_payloads:
self._payrefs = last_prim.GetPayloads()
self._ref_and_layers = omni.usd.get_composed_payloads_from_prim(last_prim, False)
else:
self._payrefs = last_prim.GetReferences()
self._ref_and_layers = omni.usd.get_composed_references_from_prim(last_prim, False)
ref_window_index = 0 if self._use_payloads else 1
self._add_ref_window[ref_window_index] = AddPayloadReferenceWindow(self._payload, self._on_payload_reference_added, use_payloads=self._use_payloads)
with ui.VStack(height=0, spacing=5, name="frame_v_stack"):
if self._payrefs:
for (ref, layer) in self._ref_and_layers:
self._build_payload_reference(ref, layer)
def on_add_payload_reference(weak_self):
weak_self = weak_self()
if not weak_self:
return
weak_self._add_ref_window[ref_window_index].show(weak_self._payrefs)
ui.Button(
f"{_get_plus_glyph()} Add Payload" if self._use_payloads else f"{_get_plus_glyph()} Add Reference",
clicked_fn=lambda weak_self=weakref.ref(self): on_add_payload_reference(weak_self),
)
def _build_payload_reference(self, payref: Sdf.Reference, intro_layer: Sdf.Layer):
with ui.Frame():
with ui.ZStack():
ui.Rectangle(name="backdrop")
with ui.VStack(
name="ref_group", spacing=5, style={"VStack::ref_group": {"margin_width": 2, "margin_height": 2}}
):
with ui.HStack(spacing=5):
ui.Spacer(width=5)
with ui.VStack(spacing=5):
asset_path_field = self._build_asset_path_ui(payref, intro_layer)
prim_path_field, prim_path_field_model = self._build_prim_path_ui(payref, intro_layer)
checkpoint_model = self._build_checkpoint_ui(payref, intro_layer)
self._build_remove_payload_reference_button(payref, intro_layer)
self._ref_dict[payref] = PayloadReferenceInfo(
asset_path_field, prim_path_field, prim_path_field_model, checkpoint_model
)
def _build_asset_path_ui(self, payref: Union[Sdf.Reference, Sdf.Payload], intro_layer: Sdf.Layer):
with ui.HStack():
UsdPropertiesWidgetBuilder._create_label("Asset Path", additional_label_kwargs={"width": REF_LABEL_WIDTH})
asset_path_field = build_path_field(
self._payload.get_stage(),
payref.assetPath,
True,
self._use_payloads,
intro_layer,
)
# If payload/reference is not existed
if payref.assetPath:
absolute_path = intro_layer.ComputeAbsolutePath(payref.assetPath)
status, _ = omni.client.stat(absolute_path)
if status != omni.client.Result.OK:
asset_path_field.set_style({"color": 0xFF6F72FF})
asset_path_field.model.add_edited_fn(
lambda model, stage=self._payrefs.GetPrim().GetStage(), prim_path=self._payrefs.GetPrim().GetPath(), payref=payref: self._on_payload_reference_edited(
model, stage, prim_path, payref, intro_layer
)
)
return asset_path_field
def _build_prim_path_ui(self, payref: Union[Sdf.Reference,Sdf.Payload], intro_layer: Sdf.Layer):
with ui.HStack():
UsdPropertiesWidgetBuilder._create_label("Prim Path", additional_label_kwargs={"width": REF_LABEL_WIDTH})
prim_path = payref.primPath
if not prim_path:
prim_path = DEFAULT_PRIM_TAG
prim_path_field_model = TrackEditingStringModel(str(prim_path))
prim_path_field = ui.StringField(model=prim_path_field_model)
prim_path_field.model.add_edited_fn(
lambda model, stage=self._payrefs.GetPrim().GetStage(), prim_path=self._payrefs.GetPrim().GetPath(), payref=payref: self._on_payload_reference_edited(
model, stage, prim_path, payref, intro_layer
)
)
return prim_path_field, prim_path_field_model
def _build_checkpoint_ui(self, payref: Union[Sdf.Reference,Sdf.Payload], intro_layer: Sdf.Layer):
if VersioningHelper.is_versioning_enabled():
try:
# Use checkpoint widget in the drop down menu for more detailed information
from omni.kit.widget.versioning.checkpoint_combobox import CheckpointCombobox
stack = ui.HStack()
with stack:
UsdPropertiesWidgetBuilder._create_label(
"Checkpoint", additional_label_kwargs={"width": REF_LABEL_WIDTH}
)
absolute_asset_path = payref.assetPath
if len(absolute_asset_path):
absolute_asset_path = omni.client.combine_urls(intro_layer.identifier, absolute_asset_path)
def on_selection_changed(
selection,
stage: Usd.Stage,
prim_path: Sdf.Path,
payref: Union[Sdf.Reference, Sdf.Payload],
intro_layer: Sdf.Layer,
):
self._on_payload_reference_checkpoint_edited(selection, stage, prim_path, payref)
self._checkpoint_combobox = CheckpointCombobox(
absolute_asset_path,
lambda selection, stage=self._payrefs.GetPrim().GetStage(), prim_path=self._payrefs.GetPrim().GetPath(), payref=payref: on_selection_changed(
selection, stage, prim_path, payref, intro_layer
),
)
# reset button
def reset_func(payref, stage, prim_path):
client_url = omni.client.break_url(payref.assetPath)
on_selection_changed(None, stage, prim_path, payref, intro_layer)
checkpoint = ""
client_url = omni.client.break_url(payref.assetPath)
if client_url.query:
_, checkpoint = omni.client.get_branch_and_checkpoint_from_query(client_url.query)
ui.Spacer(width=4)
ui.Image(
f"{ICON_PATH}/Default value.svg" if checkpoint == "" else f"{ICON_PATH}/Changed value.svg",
mouse_pressed_fn=lambda x, y, b, a, s=self._payrefs.GetPrim().GetStage(), r=payref, p=self._payrefs.GetPrim().GetPath(): reset_func(r, s, p),
width=12,
height=18,
tooltip="Reset Checkpoint" if checkpoint else "",
)
def on_have_server_info(server:str, support_checkpoint: bool, stack: ui.HStack):
if not support_checkpoint:
stack.visible = False
VersioningHelper.check_server_checkpoint_support(
VersioningHelper.extract_server_from_url(absolute_asset_path),
lambda s, c, t=stack: on_have_server_info(s,c, t)
)
return None
except ImportError as e:
# If the widget is not available, create a simple combo box instead
carb.log_warn(f"Checkpoint widget in Payload/Reference is not availble due to: {e}")
def _build_remove_payload_reference_button(self, payref, intro_layer):
def on_remove_payload_reference(ref, layer_weak, payrefs):
if not ref or not payrefs:
return
stage = payrefs.GetPrim().GetStage()
edit_target_layer = stage.GetEditTarget().GetLayer()
intro_layer = layer_weak() if layer_weak else None
if self._use_payloads:
# When removing a payload on a different layer, the deleted assetPath should be relative to edit target layer, not introducing layer
if intro_layer and intro_layer != edit_target_layer:
ref = anchor_payload_asset_path_to_layer(ref, intro_layer, edit_target_layer)
omni.kit.commands.execute(
"RemovePayload",
stage=stage,
prim_path=payrefs.GetPrim().GetPath(),
payload=ref,
),
else:
# When removing a reference on a different layer, the deleted assetPath should be relative to edit target layer, not introducing layer
if intro_layer and intro_layer != edit_target_layer:
ref = anchor_reference_asset_path_to_layer(ref, intro_layer, edit_target_layer)
omni.kit.commands.execute(
"RemoveReference",
stage=stage,
prim_path=payrefs.GetPrim().GetPath(),
reference=ref,
),
style = {"image_url": str(ICON_PATH.joinpath("remove.svg")), "margin": 0, "padding": 0}
ui.Button(
style=style,
clicked_fn=lambda ref=payref, layer_weak=weakref.ref(
intro_layer
) if intro_layer else None, refs=self._payrefs: on_remove_payload_reference(ref, layer_weak, refs),
width=16,
)
def _on_payload_reference_edited(
self, model_or_item, stage: Usd.Stage, prim_path: Sdf.Path, payref: Union[Sdf.Reference, Sdf.Payload], intro_layer: Sdf.Layer
):
ref_prim_path = self._ref_dict[payref].prim_path_field.model.get_value_as_string()
ref_prim_path = Sdf.Path(ref_prim_path) if ref_prim_path and ref_prim_path != DEFAULT_PRIM_TAG else Sdf.Path()
new_asset_path = self._ref_dict[payref].asset_path_field.model.get_value_as_string()
try:
from omni.kit.widget.versioning.checkpoints_model import CheckpointItem
if isinstance(model_or_item, CheckpointItem):
new_asset_path = replace_query(new_asset_path, model_or_item.get_relative_path())
elif model_or_item is None:
new_asset_path = replace_query(new_asset_path, None)
except Exception as e:
pass
if self._use_payloads:
new_ref = Sdf.Payload(assetPath=new_asset_path.replace("\\", "/"), primPath=ref_prim_path)
edit_target_layer = stage.GetEditTarget().GetLayer()
# When replacing a payload on a different layer, the replaced assetPath should be relative to edit target layer, not introducing layer
if intro_layer != edit_target_layer:
payref = anchor_payload_asset_path_to_layer(payref, intro_layer, edit_target_layer)
if payref == new_ref:
return False
omni.kit.commands.execute(
"ReplacePayload",
stage=stage,
prim_path=prim_path,
old_payload=payref,
new_payload=new_ref,
)
return True
new_ref = Sdf.Reference(assetPath=new_asset_path.replace("\\", "/"), primPath=ref_prim_path)
edit_target_layer = stage.GetEditTarget().GetLayer()
# When replacing a reference on a different layer, the replaced assetPath should be relative to edit target layer, not introducing layer
if intro_layer != edit_target_layer:
payref = anchor_reference_asset_path_to_layer(payref, intro_layer, edit_target_layer)
if payref == new_ref:
return False
omni.kit.commands.execute(
"ReplaceReference",
stage=stage,
prim_path=prim_path,
old_reference=payref,
new_reference=new_ref,
)
return True
def _on_payload_reference_checkpoint_edited(
self, model_or_item, stage: Usd.Stage, prim_path: Sdf.Path, payref: Union[Sdf.Reference, Sdf.Payload]
):
new_asset_path = self._ref_dict[payref].asset_path_field.model.get_value_as_string()
try:
from omni.kit.widget.versioning.checkpoints_model import CheckpointItem
if isinstance(model_or_item, CheckpointItem):
new_asset_path = replace_query(new_asset_path, model_or_item.get_relative_path())
elif model_or_item is None:
new_asset_path = replace_query(new_asset_path, None)
except Exception as e:
pass
if self._use_payloads:
new_ref = Sdf.Payload(assetPath=new_asset_path.replace("\\", "/"), primPath=payref.primPath, layerOffset=payref.layerOffset)
if payref != new_ref:
omni.kit.commands.execute(
"ReplacePayload",
stage=stage,
prim_path=prim_path,
old_payload=payref,
new_payload=new_ref,
)
return
new_ref = Sdf.Reference(assetPath=new_asset_path.replace("\\", "/"), primPath=payref.primPath, layerOffset=payref.layerOffset)
if payref != new_ref:
omni.kit.commands.execute(
"ReplaceReference",
stage=stage,
prim_path=prim_path,
old_reference=payref,
new_reference=new_ref,
)
| 34,439 | Python | 40.048868 | 179 | 0.568106 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/control_state_manager.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 weakref
from typing import Callable
import omni.usd
from pxr import Usd
class ControlStateHandler:
def __init__(self, on_refresh_state: Callable, on_build_state: Callable, icon_path: str):
"""
Args:
on_refresh_state (Callable): function to be called when control state refreshes. Callable should returns a tuple(bool, bool).
The first bool decides if the flag of this state should be set. The second bool descides if a force rebuild should be triggered.
on_build_state (Callable): function to be called when build control state UI. Callable should returns a tuple(bool, Callable, str).
If first bool is True, subsequent states with lower (larger value) priority will be skipped.
Second Callable is the action to perform when click on the icon.
Third str is tooltip when hovering over icon.
icon_path (str): path to an SVG file to show next to attribute when this state wins.
"""
self.on_refresh_state = on_refresh_state
self.on_build_state = on_build_state
self.icon_path = icon_path
class ControlStateManager:
_instance = None
@classmethod
def get_instance(cls):
return weakref.proxy(cls._instance)
def __init__(self, icon_path):
self._icon_path = icon_path
self._next_flag = 1
self._control_state_handlers = {}
ControlStateManager._instance = self
self._builtin_handles = []
self._default_icon_path = f"{self._icon_path}/Default value.svg"
self._register_builtin_handlers()
def __del__(self):
self.destory()
def destory(self):
for handle_flag in self._builtin_handles:
self.unregister_control_state(handle_flag)
ControlStateManager.instance = None
def register_control_state(
self, on_refresh_state: Callable, on_build_state: Callable, icon_path: str, priority: float = 0.0
) -> int:
entry = ControlStateHandler(on_refresh_state, on_build_state, icon_path)
flag = self._next_flag
self._next_flag <<= 1
self._add_entry(flag, priority, entry)
return flag
def unregister_control_state(self, flag):
self._control_state_handlers.pop(flag)
def update_control_state(self, usd_model_base):
control_state = 0
force_refresh = False
for flag, (_, handler) in self._control_state_handlers.items():
set_flag, f_refresh = handler.on_refresh_state(usd_model_base)
force_refresh |= f_refresh
if set_flag:
control_state |= flag
return control_state, force_refresh
def build_control_state(self, control_state, **kwargs):
for flag, (_, handler) in self._control_state_handlers.items():
handled, action, tooltip = handler.on_build_state(flag & control_state, **kwargs)
if handled:
return action, handler.icon_path, tooltip
return None, self._default_icon_path, ""
def _add_entry(self, flag: int, priority: float, entry: ControlStateHandler):
self._control_state_handlers[flag] = (priority, entry)
# sort by priority
self._control_state_handlers = {
k: v for k, v in sorted(self._control_state_handlers.items(), key=lambda item: item[1][0])
}
def _register_builtin_handlers(self):
self._builtin_handles.append(self._register_mixed())
self._builtin_handles.append(self._register_connected())
self._builtin_handles.append(self._register_keyed())
self._builtin_handles.append(self._register_sampled())
self._builtin_handles.append(self._register_not_default())
self._builtin_handles.append(self._register_locked())
def _register_mixed(self):
def on_refresh(usd_model_base):
return usd_model_base._ambiguous, True
def on_build(has_state_flag, **kwargs):
model = kwargs.get("model")
widget_comp_index = kwargs.get("widget_comp_index", -1)
mixed_overlay = kwargs.get("mixed_overlay", None)
if mixed_overlay and not isinstance(mixed_overlay, list):
mixed_overlay = [mixed_overlay]
no_mixed = kwargs.get("no_mixed", False)
if not has_state_flag or no_mixed or not model.is_comp_ambiguous(widget_comp_index):
if mixed_overlay:
for overlay in mixed_overlay:
overlay.visible = False
return False, None, None
else:
if mixed_overlay:
# for array only one mixed overlay
if model.is_array_type() and len(mixed_overlay) == 1:
mixed_overlay[0].visible = model.is_ambiguous()
else:
for i, overlay in enumerate(mixed_overlay):
comp_index = max(widget_comp_index, i)
overlay.visible = model.is_comp_ambiguous(comp_index)
return True, None, "Mixed value among selected prims"
icon_path = f"{self._icon_path}/mixed properties.svg"
return self.register_control_state(on_refresh, on_build, icon_path, 0)
def _register_connected(self):
def on_refresh(usd_model_base):
return any(usd_model_base._connections), False
def on_build(has_state_flag, **kwargs):
if not has_state_flag:
return False, None, None
model = kwargs.get("model")
value_widget = kwargs.get("value_widget", None)
extra_widgets = kwargs.get("extra_widgets", [])
action = None
tooltip = ""
connections = model.get_connections()
if not all(ele == connections[0] for ele in connections):
tooltip = "Attribute have different connections among selected prims."
last_prim_connections = connections[-1]
if len(last_prim_connections) > 0:
if value_widget:
value_widget.enabled = False
for widget in extra_widgets:
widget.enabled = False
if not tooltip:
for path in last_prim_connections:
tooltip += f"{path}\n"
def on_click_connection(*arg, path=last_prim_connections[-1]):
# Get connection on last selected prim
last_prim_connections = model.get_connections()[-1]
if len(last_prim_connections) > 0:
# TODO multi-context, pass context name in payload??
selection = omni.usd.get_context().get_selection()
selection.set_selected_prim_paths([path.GetPrimPath().pathString], True)
action = on_click_connection
return True, action, tooltip
icon_path = f"{self._icon_path}/Expression.svg"
return self.register_control_state(on_refresh, on_build, icon_path, 10)
def _register_locked(self):
def on_refresh(usd_model_base):
return usd_model_base.is_locked(), False
def on_build(has_state_flag, **kwargs):
if not has_state_flag:
return False, None, None
return True, None, "Value is locked"
icon_path = f"{self._icon_path}/Locked Value.svg"
return self.register_control_state(on_refresh, on_build, icon_path, 20)
def _register_keyed(self):
def on_refresh(usd_model_base):
current_time_code = usd_model_base.get_current_time_code()
for attribute in usd_model_base._get_attributes():
if isinstance(attribute, Usd.Attribute) and omni.usd.attr_has_timesample_on_key(
attribute, current_time_code
):
return True, False
return False, False
def on_build(has_state_flag, **kwargs):
if not has_state_flag:
return False, None, None
return True, None, "Timesampled keyframe"
icon_path = f"{self._icon_path}/TimeSamples.svg"
return self.register_control_state(on_refresh, on_build, icon_path, 20)
def _register_sampled(self):
def on_refresh(usd_model_base):
return usd_model_base._might_be_time_varying, False
def on_build(has_state_flag, **kwargs):
if not has_state_flag:
return False, None, None
return True, None, "Timesampled value"
icon_path = f"{self._icon_path}/TimeVarying.svg"
return self.register_control_state(on_refresh, on_build, icon_path, 30)
def _register_not_default(self):
def on_refresh(usd_model_base):
return usd_model_base.is_different_from_default(), False
def on_build(has_state_flag, **kwargs):
if not has_state_flag:
return False, None, None
model = kwargs.get("model")
widget_comp_index = kwargs.get("widget_comp_index", -1)
return True, lambda *_: model.set_default(widget_comp_index), "Value different from default"
icon_path = f"{self._icon_path}/Changed value.svg"
return self.register_control_state(on_refresh, on_build, icon_path, 40)
| 9,864 | Python | 38.778226 | 144 | 0.598844 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/attribute_context_menu.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 weakref
from functools import partial
import carb
import omni.kit.commands
import omni.kit.context_menu
import omni.kit.undo
import omni.usd
from omni.kit.usd.layers import LayerEditMode, get_layers
from pxr import Sdf
from .usd_attribute_model import (
GfVecAttributeModel,
MdlEnumAttributeModel,
TfTokenAttributeModel,
UsdAttributeModel,
UsdBase,
)
class AttributeContextMenuEvent:
def __init__(self, widget, attribute_paths, stage, time_code, model, comp_index):
self.widget = widget
self.attribute_paths = attribute_paths
self.stage = stage
self.time_code = time_code
self.model = model
self.comp_index = comp_index
self.type = 0
class AttributeContextMenu:
_instance = None
@classmethod
def get_instance(cls):
return weakref.proxy(cls._instance)
def __init__(self):
self._register_context_menus()
AttributeContextMenu._instance = self
def __del__(self):
self.destroy()
def destroy(self):
self._copy_menu_entry = None
self._paste_menu_entry = None
self._delete_menu_entry = None
self._copy_path_menu_entry = None
AttributeContextMenu._instance = None
def on_mouse_event(self, event: AttributeContextMenuEvent):
# check its expected event
if event.type != int(omni.kit.ui.MenuEventType.ACTIVATE):
return
# setup objects, this is passed to all functions
objects = {
"widget": event.widget,
"stage": event.stage,
"attribute_paths": event.attribute_paths,
"time_code": event.time_code,
"model": event.model,
"comp_index": event.comp_index,
}
menu_list = omni.kit.context_menu.get_menu_dict("attribute", "omni.kit.property.usd")
stage = event.stage
if stage:
usd_context = omni.usd.get_context()
layers = get_layers(usd_context)
edit_mode = layers.get_edit_mode()
auto_authoring = layers.get_auto_authoring()
layers_state = layers.get_layers_state()
if edit_mode == LayerEditMode.SPECS_LINKING:
per_layer_link_menu = []
for layer in stage.GetLayerStack():
if auto_authoring.is_auto_authoring_layer(layer.identifier):
continue
layer_name = layers_state.get_layer_name(layer.identifier)
per_layer_link_menu.append(
{
"name": {
f"{layer_name}": [
{
"name": "Link",
"show_fn": [],
"onclick_fn": partial(self._link_attributes, True, layer.identifier),
},
{
"name": "Unlink",
"show_fn": [],
"onclick_fn": partial(self._link_attributes, False, layer.identifier),
},
]
}
}
)
menu_list.append(
{
"name": {"Layers": per_layer_link_menu},
"glyph": "",
}
)
menu_list.extend([{"name": ""}])
menu_list.append(
{
"name": {
"Locks": [
{
"name": "Lock",
"show_fn": [],
"onclick_fn": partial(self._lock_attributes, True),
},
{
"name": "Unlock",
"show_fn": [],
"onclick_fn": partial(self._lock_attributes, False),
},
]
},
"glyph": "",
}
)
omni.kit.context_menu.get_instance().show_context_menu("attribute", objects, menu_list)
def _link_attributes(self, link_or_unlink, layer_identifier, objects):
attribute_paths = objects.get("attribute_paths", None)
if not attribute_paths:
return
if link_or_unlink:
command = "LinkSpecs"
else:
command = "UnlinkSpecs"
omni.kit.commands.execute(command, spec_paths=attribute_paths, layer_identifiers=layer_identifier)
def _lock_attributes(self, lock_or_unlock, objects):
attribute_paths = objects.get("attribute_paths", None)
if not attribute_paths:
return
if lock_or_unlock:
command = "LockSpecs"
else:
command = "UnlockSpecs"
omni.kit.commands.execute(command, spec_paths=attribute_paths)
def _register_context_menus(self):
self._register_copy_paste_menus()
self._register_delete_prop_menu()
self._register_copy_prop_path_menu()
def _register_copy_paste_menus(self):
def can_show_copy_paste(object):
model = object.get("model", None)
if not model:
return False
return isinstance(model, UsdBase)
def can_copy(object):
model: UsdBase = object.get("model", None)
if not model:
return False
# Only support copying during single select per OM-20206
paths = model.get_property_paths()
if len(paths) > 1:
return False
comp_index = object.get("comp_index", -1)
return not model.is_comp_ambiguous(comp_index) and (
isinstance(model, UsdAttributeModel)
or isinstance(model, TfTokenAttributeModel)
or isinstance(model, MdlEnumAttributeModel)
or isinstance(model, GfVecAttributeModel)
)
def on_copy(object):
model = object.get("model", None)
if not model:
return
if isinstance(model, UsdAttributeModel):
value_str = model.get_value_as_string(elide_big_array=False)
elif isinstance(model, TfTokenAttributeModel):
value_str = model.get_value_as_token()
elif isinstance(model, MdlEnumAttributeModel):
value_str = model.get_value_as_string()
elif isinstance(model, GfVecAttributeModel):
value_str = str(model._construct_vector_from_item())
else:
carb.log_warn("Unsupported type to copy")
return
omni.kit.clipboard.copy(value_str)
menu = {
"name": "Copy",
"show_fn": can_show_copy_paste,
"enabled_fn": can_copy,
"onclick_fn": on_copy,
}
self._copy_menu_entry = omni.kit.context_menu.add_menu(menu, "attribute", "omni.kit.property.usd")
# If type conversion fails, function raise exception and disables menu entry/quit paste
def convert_type(value_type, value_str: str):
if value_type == str or value_type == Sdf.AssetPath or value_type == Sdf.Path:
return value_str
if value_type == Sdf.AssetPathArray:
# Copied AssetPathArray is in this format:
# [@E:/USD/foo.usd@, @E:/USD/bar.usd@]
# parse it manually
value_str = value_str.strip("[] ")
paths = value_str.split(", ")
paths = [path.strip("@") for path in paths]
return paths
else:
# Use an eval here so tuple/list/etc correctly converts from string. May need revisit.
return value_type(eval(value_str))
def can_paste(object):
model = object.get("model", None)
widget = object.get("widget", None)
if not model:
return False
if not widget or not widget.enabled:
return False
comp_index = object.get("comp_index", -1)
paste = omni.kit.clipboard.paste()
if paste:
try:
ret = True
if isinstance(model, UsdAttributeModel):
value = model.get_value_by_comp(comp_index)
convert_type(type(value), paste)
elif isinstance(model, TfTokenAttributeModel):
if not model.is_allowed_token(paste):
raise ValueError(f"Token {paste} is not allowed on this attribute")
elif isinstance(model, MdlEnumAttributeModel):
if not model.is_allowed_enum_string(paste):
raise ValueError(f"Enum {paste} is not allowed on this attribute")
elif isinstance(model, GfVecAttributeModel):
value = model.get_value()
convert_type(type(value), paste)
else:
carb.log_warn("Unsupported type to paste to")
ret = False
return ret
except Exception as e:
carb.log_warn(f"{e}")
pass
return False
def on_paste(object):
model = object.get("model", None)
if not model:
return
comp_index = object.get("comp_index", -1)
value = model.get_value_by_comp(comp_index)
paste = omni.kit.clipboard.paste()
if paste:
try:
if (
isinstance(model, UsdAttributeModel)
or isinstance(model, TfTokenAttributeModel)
or isinstance(model, GfVecAttributeModel)
):
typed_value = convert_type(type(value), paste)
model.set_value(typed_value)
elif isinstance(model, MdlEnumAttributeModel):
model.set_from_enum_string(paste)
except Exception as e:
carb.log_warn(f"Failed to paste: {e}")
menu = {
"name": "Paste",
"show_fn": can_show_copy_paste,
"enabled_fn": can_paste,
"onclick_fn": on_paste,
}
self._paste_menu_entry = omni.kit.context_menu.add_menu(menu, "attribute", "omni.kit.property.usd")
def _register_delete_prop_menu(self):
def can_show_delete(object):
model = object.get("model", None)
if not model:
return False
stage = model.stage
if not stage:
return False
# OM-49324 Hide the Remove context menu for xformOp attributes
# Cannot simply remove an xformOp attribute. Leave it to transform widget context menu
paths = model.get_attribute_paths()
for path in paths:
prop = stage.GetPropertyAtPath(path)
if not prop or prop.GetName().startswith("xformOp:"):
return False
return isinstance(model, UsdBase)
def can_delete(object):
model = object.get("model", None)
if not model:
return False
stage = model.stage
if not stage:
return False
paths = model.get_attribute_paths()
for path in paths:
prop = stage.GetPropertyAtPath(path)
if prop:
prim = prop.GetPrim()
prim_definition = prim.GetPrimDefinition()
# If the property is part of a schema, it cannot be completely removed. Removing it will simply reset to default value
prop_spec = prim_definition.GetSchemaPropertySpec(prop.GetPath().name)
if prop_spec:
return False
else:
return False
return True
def on_delete(object):
model = object.get("model", None)
if not model:
return
paths = model.get_attribute_paths()
with omni.kit.undo.group():
for path in paths:
omni.kit.commands.execute("RemoveProperty", prop_path=path)
menu = {
"name": "Remove",
"show_fn": can_show_delete,
"enabled_fn": can_delete,
"onclick_fn": on_delete,
}
self._delete_menu_entry = omni.kit.context_menu.add_menu(menu, "attribute", "omni.kit.property.usd")
def _register_copy_prop_path_menu(self):
def can_show_copy_path(object):
model = object.get("model", None)
if not model:
return False
stage = model.stage
if not stage:
return False
return isinstance(model, UsdBase)
def can_copy_path(object):
model = object.get("model", None)
if not model:
return False
stage = model.stage
if not stage:
return False
paths = model.get_attribute_paths()
return len(paths) == 1
def on_copy_path(object):
model = object.get("model", None)
if not model:
return
paths = model.get_attribute_paths()
omni.kit.clipboard.copy(paths[-1].pathString)
menu = {
"name": "Copy Property Path",
"show_fn": can_show_copy_path,
"enabled_fn": can_copy_path,
"onclick_fn": on_copy_path,
}
self._copy_path_menu_entry = omni.kit.context_menu.add_menu(menu, "attribute", "omni.kit.property.usd")
| 14,703 | Python | 34.602905 | 138 | 0.504183 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/usd_object_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 carb
import omni.kit.commands
import omni.timeline
import omni.ui as ui
import omni.usd
from .usd_model_base import UsdBase
from typing import List
from pxr import Usd, Sdf
class MetadataObjectModel(ui.AbstractItemModel, UsdBase):
"""The value model that is reimplemented in Python to watch a USD paths.
Paths can be either Attribute or Prim paths"""
def __init__(
self,
stage: Usd.Stage,
object_paths: List[Sdf.Path],
self_refresh: bool,
metadata: dict,
key: str,
default,
options: list,
):
UsdBase.__init__(self, stage, object_paths, self_refresh, metadata)
ui.AbstractItemModel.__init__(self)
self._key = key
self._default_value = default
self._combobox_options = options
self._update_option()
self._current_index = ui.SimpleIntModel()
self._current_index.add_value_changed_fn(self._current_index_changed)
self._has_index = False
self._update_value()
self._has_index = True
def clean(self):
UsdBase.clean(self)
def get_item_children(self, item):
self._update_value()
return self._options
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
def begin_edit(self):
carb.log_warn("begin_edit not supported in MetadataObjectModel")
def end_edit(self):
carb.log_warn("end_edit not supported in MetadataObjectModel")
def _current_index_changed(self, model):
if not self._has_index:
return
index = model.as_int
if self.set_value(self._options[index].value):
self._item_changed(None)
def _update_option(self):
class OptionItem(ui.AbstractItem):
def __init__(self, display_name: str, value: int):
super().__init__()
self.model = ui.SimpleStringModel(display_name)
self.value = value
self._options = []
for index, option in enumerate(self._combobox_options):
self._options.append(OptionItem(option, int(index)))
def _update_value(self, force=False):
if self._update_value_objects(force, self._get_objects()):
index = -1
for i in range(0, len(self._options)):
if self._options[i].model.get_value_as_string() == self._value:
index = i
if index != -1 and self._current_index.as_int != index:
self._has_index = False
self._current_index.set_value(index)
self._item_changed(None)
self._has_index = True
def _on_dirty(self):
self._update_value()
def set_value(self, value, comp=-1):
if comp != -1:
carb.log_warn("Arrays not supported in MetadataObjectModel")
self._update_value(True) # reset value
return False
if not self._ambiguous and not any(self._comp_ambiguous) and value == self._value:
return False
self._value = self._combobox_options[int(value)]
objects = self._get_objects()
if len(objects) == 0:
return False
self._write_value(objects=objects, key=self._key, value=self._value)
# We just set all the properties to the same value, it's no longer ambiguous
self._ambiguous = False
self._comp_ambiguous.clear()
self.update_control_state()
return True
def _read_value(self, object: Usd.Object, time_code: Usd.TimeCode):
value = object.GetMetadata(self._key)
if not value:
value = self._default_value
return value
def _write_value(self, objects: list, key: str, value):
path_list = []
for object in objects:
path_list.append(object.GetPath())
omni.kit.commands.execute("ChangeMetadata", object_paths=path_list, key=key, value=value)
| 4,450 | Python | 31.97037 | 97 | 0.613034 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/versioning_helper.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 omni.client
class VersioningHelper:
server_cache = {}
@staticmethod
def is_versioning_enabled():
try:
import omni.kit.widget.versioning
enable_versioning = True
except:
enable_versioning = False
return enable_versioning
@staticmethod
def extract_server_from_url(url):
client_url = omni.client.break_url(url)
server_url = omni.client.make_url(scheme=client_url.scheme, host=client_url.host, port=client_url.port)
return server_url
@staticmethod
def check_server_checkpoint_support(server: str, on_complete: callable):
if not server:
on_complete(server, False)
return
if server in VersioningHelper.server_cache:
on_complete(server, VersioningHelper.server_cache[server])
return
async def update_server_can_save_checkpoint():
result, server_info = await omni.client.get_server_info_async(server)
support_checkpoint = result and server_info and server_info.checkpoints_enabled
on_complete(server, support_checkpoint)
VersioningHelper.server_cache[server] = support_checkpoint
asyncio.ensure_future(update_server_can_save_checkpoint())
| 1,743 | Python | 31.296296 | 111 | 0.686173 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/custom_layout_helper.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 collections import OrderedDict
from .usd_property_widget import UsdPropertyUiEntry
stack = []
class Container:
def __init__(self, hide_if_true=None, show_if_true=None):
self._children = []
self._container_name = ""
self._collapsed = False
self._is_visible = True
if isinstance(hide_if_true, bool):
self._is_visible = not hide_if_true
if isinstance(show_if_true, bool):
self._is_visible = show_if_true
def __enter__(self):
stack.append(self)
def __exit__(self, exc_type, exc_value, tb):
stack.pop()
def add_child(self, item):
self._children.append(item)
def get_name(self):
return self._container_name
def get_collapsed(self):
return self._collapsed
def is_visible(self):
return self._is_visible
class CustomLayoutProperty:
def __init__(self, prop_name, display_name=None, build_fn=None, hide_if_true=None, show_if_true=None):
self._prop_name = prop_name
self._display_name = display_name
self._build_fn = build_fn # TODO
self._is_visible = True
if isinstance(hide_if_true, bool):
self._is_visible = not hide_if_true
if isinstance(show_if_true, bool):
self._is_visible = show_if_true
global stack
stack[-1].add_child(self)
def get_property_name(self):
return self._prop_name
def get_display_name(self):
return self._display_name
def get_build_fn(self):
return self._build_fn
def is_visible(self):
return self._is_visible
class CustomLayoutGroup(Container):
def __init__(self, container_name, collapsed=False, hide_if_true=None, show_if_true=None):
super().__init__(hide_if_true=hide_if_true, show_if_true=show_if_true)
self._container_name = container_name
self._collapsed = collapsed
global stack
stack[-1].add_child(self)
class CustomLayoutFrame(Container):
def __init__(self, hide_extra=False):
super().__init__()
self._hide_extra = hide_extra
def apply(self, props):
customized_props = []
# preprocess to speed up lookup
props_dict = OrderedDict()
for prop in props:
props_dict[prop[0]] = prop
self._process_container(self, props_dict, customized_props, "")
# add the remaining
if not self._hide_extra:
for prop in props_dict.values():
customized_props.append(prop)
return customized_props
def _process_container(self, container, props_dict, customized_props, group_name):
for child in container._children:
if isinstance(child, Container):
if child.is_visible():
prefix = group_name + f":{child.get_name()}" if group_name else child.get_name()
self._process_container(child, props_dict, customized_props, prefix)
elif isinstance(child, CustomLayoutProperty):
if child.is_visible():
prop_name = child.get_property_name()
collapsed = container.get_collapsed()
prop = props_dict.pop(prop_name, None) # get and remove
if prop:
if group_name != "":
prop.override_display_group(group_name, collapsed)
display_name = child.get_display_name()
if display_name:
prop.override_display_name(display_name)
prop.build_fn = child.get_build_fn()
customized_props.append(prop)
elif child.get_build_fn():
prop = UsdPropertyUiEntry("", group_name, "", None, child.get_build_fn(), collapsed)
customized_props.append(prop)
| 4,362 | Python | 33.904 | 108 | 0.592618 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/add_attribute_popup.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 weakref
import carb
import omni.kit.commands
import omni.kit.undo
import omni.ui as ui
from pxr import Sdf
from .prim_selection_payload import PrimSelectionPayload
class ValueTypeNameItem(ui.AbstractItem):
def __init__(self, value_type_name: Sdf.ValueTypeName, value_type_name_str: str):
super().__init__()
self.value_type_name = value_type_name
self.model = ui.SimpleStringModel(value_type_name_str)
class VariabilityItem(ui.AbstractItem):
def __init__(self, variability: Sdf.Variability, Variability_str: str):
super().__init__()
self.variability = variability
self.model = ui.SimpleStringModel(Variability_str)
class ComboBoxModel(ui.AbstractItemModel):
def __init__(self):
super().__init__()
self._current_index = ui.SimpleIntModel()
self._current_index.add_value_changed_fn(lambda a: self._item_changed(None))
self._items = []
self._populate_items()
def _populate_items(self):
...
def get_item_children(self, item):
return self._items
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
def get_selected_item(self):
return self._items[self._current_index.get_value_as_int()]
class ValueTypeNameModel(ComboBoxModel):
def _populate_items(self):
for property in dir(Sdf.ValueTypeNames):
type_name = getattr(Sdf.ValueTypeNames, property)
if isinstance(type_name, Sdf.ValueTypeName):
self._items.append(ValueTypeNameItem(type_name, property))
class VariabilityModel(ComboBoxModel):
def _populate_items(self):
self._items = [
VariabilityItem(Sdf.VariabilityVarying, "Varying"),
VariabilityItem(Sdf.VariabilityUniform, "Uniform"),
]
class AddAttributePopup:
def __init__(self):
self._add_attribute_window = ui.Window(
"Add Attribute...", visible=False, flags=ui.WINDOW_FLAGS_NO_RESIZE, auto_resize=True
)
with self._add_attribute_window.frame:
with ui.VStack(height=0, spacing=5):
LABEL_WIDTH = 80
WIDGET_WIDTH = 300
with ui.HStack(width=0):
ui.Label("Name", width=LABEL_WIDTH)
self._add_attr_name_field = ui.StringField(width=WIDGET_WIDTH)
self._add_attr_name_field.model.set_value("new_attr")
with ui.HStack(width=0):
ui.Label("Type", width=LABEL_WIDTH)
self._value_type_name_model = ValueTypeNameModel()
ui.ComboBox(self._value_type_name_model, width=WIDGET_WIDTH)
with ui.HStack(width=0):
ui.Label("Custom", width=LABEL_WIDTH)
self._custom_checkbox = ui.CheckBox()
self._custom_checkbox.model.set_value(True)
with ui.HStack(width=0):
ui.Label("Variability", width=LABEL_WIDTH)
self._variability_model = VariabilityModel()
ui.ComboBox(self._variability_model, width=WIDGET_WIDTH)
self._error_msg_label = ui.Label(
"",
visible=False,
style={"color": 0xFF0000FF},
)
with ui.HStack():
ui.Spacer()
def on_add(weak_self):
ref_self = weak_self()
error_message = ""
if ref_self:
stage = ref_self._add_attribute_window_payload.get_stage()
if stage:
selected_item = ref_self._value_type_name_model.get_selected_item()
value_type_name = selected_item.value_type_name
attr_name = ref_self._add_attr_name_field.model.get_value_as_string()
custom = ref_self._custom_checkbox.model.get_value_as_bool()
variability = ref_self._variability_model.get_selected_item().variability
if Sdf.Path.IsValidNamespacedIdentifier(attr_name):
try:
omni.kit.undo.begin_group()
for path in ref_self._add_attribute_window_payload:
path = Sdf.Path(path).AppendProperty(attr_name)
prop = stage.GetPropertyAtPath(path)
if prop:
error_message = "One or more attribute to be created already exists."
else:
omni.kit.commands.execute(
"CreateUsdAttributeOnPath",
attr_path=path,
attr_type=value_type_name,
custom=custom,
variability=variability,
)
finally:
omni.kit.undo.end_group()
else:
error_message = f'Invalid identifier "{attr_name}"'
if error_message:
ref_self._error_msg_label.visible = True
ref_self._error_msg_label.text = error_message
carb.log_warn(error_message)
else:
ref_self._add_attribute_window.visible = False
ui.Button("Add", clicked_fn=lambda weak_self=weakref.ref(self): on_add(weak_self))
def on_cancel(weak_self):
ref_self = weak_self()
if ref_self:
ref_self._add_attribute_window.visible = False
ui.Button("Cancel", clicked_fn=lambda weak_self=weakref.ref(self): on_cancel(weak_self))
ui.Spacer()
def show_fn(self, objects: dict):
if not "prim_list" in objects or not "stage" in objects:
return False
stage = objects["stage"]
if not stage:
return False
return len(objects["prim_list"]) >= 1
def click_fn(self, payload: PrimSelectionPayload):
self._add_attribute_window.visible = True
self._add_attribute_window_payload = payload
self._error_msg_label.visible = False
def __del__(self):
self.destroy()
def destroy(self):
self._add_attribute_window = None
self._add_attribute_window_payload = None
self._error_msg_label = None
self._add_attr_name_field = None
self._value_type_name_model = None
| 7,633 | Python | 39.391534 | 117 | 0.51749 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_shader_material_subid_property.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
from omni.kit import ui_test
from pxr import Sdf, UsdShade
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows
class ShaderMaterialSubidProperty(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
await open_stage(get_test_data_path(__name__, "usd/bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_l1_shader_material_subid_property(self):
import omni.kit.commands
await ui_test.find("Property").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
to_select = ['/World/Cone', '/World/Cylinder', '/World/Cube', '/World/Sphere']
# bind OmniSurface_Plastic to prims
omni.kit.commands.execute('BindMaterial', material_path='/World/Looks/OmniSurface_Plastic', prim_path=to_select)
# wait for material to load & UI to refresh
await wait_stage_loading()
# select OmniSurface_Plastic shader
await select_prims(['/World/Looks/OmniSurface_Plastic/Shader'])
await ui_test.human_delay()
# get OmniSurface_Plastic shader
prim = stage.GetPrimAtPath('/World/Looks/OmniSurface_Plastic/Shader')
shader = UsdShade.Shader(prim)
# get subid widget
property_widget = ui_test.find("Property//Frame/**/ComboBox[*].identifier=='sdf_asset_info:mdl:sourceAsset:subIdentifier'")
if property_widget.widget.enabled:
items = property_widget.model.get_item_children(None)
for item in items:
# change selection
property_widget.model.set_value(item.token)
# wait for material to load & UI to refresh
await wait_stage_loading()
# verify shader value
self.assertTrue(shader.GetSourceAssetSubIdentifier('mdl') == item.token)
| 2,547 | Python | 37.02985 | 131 | 0.681979 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_material_edits_and_undo.py |
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import carb
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.ui.tests.test_base import OmniUiTest
from pxr import Kind, Sdf, Gf, Usd
class TestMaterialEditsAndUndo(omni.kit.test.AsyncTestCase):
def __init__(self, tests=()):
super().__init__(tests)
# Before running each test
async def setUp(self):
self._usd_context = omni.usd.get_context()
await self._usd_context.new_stage_async()
self._stage = self._usd_context.get_stage()
from omni.kit.test_suite.helpers import arrange_windows
await arrange_windows(topleft_window="Property", topleft_height=64, topleft_width=800.0)
renderer = "rtx"
if renderer not in self._usd_context.get_attached_hydra_engine_names():
omni.usd.add_hydra_engine(renderer, self._usd_context)
await self.wait()
# After running each test
async def tearDown(self):
from omni.kit.test_suite.helpers import wait_stage_loading
await wait_stage_loading()
async def wait(self, updates=3):
for i in range(updates):
await omni.kit.app.get_app().next_update_async()
async def test_l2_material_edits_and_undo(self):
widget_compare_table = {
Sdf.ValueTypeNames.Half2.type: (Gf.Vec2h(0.12345, 0.12345), 3),
Sdf.ValueTypeNames.Float2.type: (Gf.Vec2f(0.12345, 0.12345), 4),
Sdf.ValueTypeNames.Double2.type: (Gf.Vec2d(0.12345, 0.12345), 4),
Sdf.ValueTypeNames.Half3.type: (Gf.Vec3h(0.12345, 0.12345, 0.12345), 3),
Sdf.ValueTypeNames.Float3.type: (Gf.Vec3f(0.12345, 0.12345, 0.12345), 4),
Sdf.ValueTypeNames.Double3.type: (Gf.Vec3d(0.12345, 0.12345, 0.12345), 4),
Sdf.ValueTypeNames.Half4.type: (Gf.Vec4h(0.12345, 0.12345, 0.12345, 0.12345), 3),
Sdf.ValueTypeNames.Float4.type: (Gf.Vec4f(0.12345, 0.12345, 0.12345, 0.12345), 4),
Sdf.ValueTypeNames.Double4.type: (Gf.Vec4d(0.12345, 0.12345, 0.12345, 0.12345), 4),
Sdf.ValueTypeNames.Int2.type: Gf.Vec2i(9999, 9999),
Sdf.ValueTypeNames.Int3.type: Gf.Vec3i(9999, 9999, 9999),
Sdf.ValueTypeNames.Int4.type: Gf.Vec4i(9999, 9999, 9999, 9999),
Sdf.ValueTypeNames.UChar.type: 99,
Sdf.ValueTypeNames.UInt.type: 99,
Sdf.ValueTypeNames.Int.type: 9999,
Sdf.ValueTypeNames.Int64.type: 9999,
Sdf.ValueTypeNames.UInt64.type: 9999,
}
from omni.kit.test_suite.helpers import select_prims, wait_stage_loading
from omni.kit import ui_test
# wait for material to load & UI to refresh
await wait_stage_loading()
material_path = "/OmniPBR"
omni.kit.commands.execute("CreateMdlMaterialPrim", mtl_url="OmniPBR.mdl", mtl_name="OmniPBR", mtl_path=material_path)
prim_path = "/OmniPBR/Shader"
self._usd_context.add_to_pending_creating_mdl_paths(prim_path, True, True)
await self.wait()
await select_prims([prim_path])
# Loading all inputs
await self.wait()
all_widgets = ui_test.find_all("Property//Frame/**/.identifier!=''")
for w in all_widgets:
id = w.widget.identifier
if id.startswith("float_slider_"):
attr = self._stage.GetPrimAtPath(prim_path).GetAttribute(id[13:])
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
old_value = attr.Get()
widget_old_value = w.widget.model.get_value()
new_value = 0.3456
# Sets value to make sure current layer includes this property
# so it will not be removed after undo to refresh property
# window to resync all widgets.
await w.input(str(new_value))
await ui_test.human_delay()
attr = self._stage.GetPrimAtPath(prim_path).GetAttribute(id[13:])
self.assertAlmostEqual(attr.Get(), new_value, places=4)
self.assertAlmostEqual(w.widget.model.get_value(), new_value, places=4)
omni.kit.undo.undo()
w.widget.scroll_here_y(0.5)
self.assertAlmostEqual(attr.Get(), old_value, places=4)
await self.wait()
self.assertAlmostEqual(w.widget.model.get_value(), widget_old_value, places=4)
elif id.startswith("integer_slider_"):
w.widget.scroll_here_y(0.5)
attr = self._stage.GetPrimAtPath(prim_path).GetAttribute(id[15:])
await ui_test.human_delay()
old_value = attr.Get()
new_value = old_value + 1
sdr_metadata = attr.GetMetadata("sdrMetadata")
if sdr_metadata and sdr_metadata.get("options", None):
is_mdl_enum = True
else:
is_mdl_enum = False
# Sets value to make sure current layer includes this property
# so it will not be removed after undo to refresh property
# window to resync all widgets.
if is_mdl_enum:
attr.Set(old_value)
w.widget.model.set_value(new_value)
else:
await w.input(str(new_value))
await ui_test.human_delay()
self.assertEqual(attr.Get(), new_value)
omni.kit.undo.undo()
await self.wait()
self.assertEqual(attr.Get(), old_value)
self.assertEqual(w.widget.model.get_value(), old_value)
elif id.startswith("drag_per_channel_int"):
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
sub_widgets = w.find_all("**/IntSlider[*]")
if sub_widgets == []:
sub_widgets = w.find_all("**/IntDrag[*]")
self.assertNotEqual(sub_widgets, [])
attr = self._stage.GetPrimAtPath(prim_path).GetAttribute(id[17:])
old_value = attr.Get()
for child in sub_widgets:
child.model.set_value(0)
await child.input("9999")
await ui_test.human_delay()
metadata = attr.GetAllMetadata()
type_name = Sdf.ValueTypeNames.Find(metadata.get(Sdf.PrimSpec.TypeNameKey, "unknown type")).type
value = widget_compare_table[type_name]
self.assertEqual(attr.Get(), value)
omni.kit.undo.undo()
await self.wait()
self.assertEqual(attr.Get(), old_value)
self.assertEqual(w.widget.model.get_value(), old_value)
elif id.startswith("drag_per_channel_"):
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
sub_widgets = w.find_all("**/FloatSlider[*]")
if sub_widgets == []:
sub_widgets = w.find_all("**/FloatDrag[*]")
self.assertNotEqual(sub_widgets, [])
attr = self._stage.GetPrimAtPath(prim_path).GetAttribute(id[17:])
old_value = attr.Get()
for child in sub_widgets:
await child.input("0.12345")
await self.wait()
metadata = attr.GetAllMetadata()
type_name = Sdf.ValueTypeNames.Find(metadata.get(Sdf.PrimSpec.TypeNameKey, "unknown type")).type
value, places = widget_compare_table[type_name]
self.assertTrue(Gf.IsClose(attr.Get(), value, 1e-3))
# Undo all channels
for i in range(len(sub_widgets)):
omni.kit.undo.undo()
await self.wait()
self.assertTrue(Gf.IsClose(attr.Get(), old_value, 1e-04), f"{attr.Get()} != {old_value}")
for i, child in enumerate(sub_widgets):
self.assertAlmostEqual(child.model.get_value()[i], old_value[i], places=places)
elif id.startswith("bool_"):
w.widget.scroll_here_y(0.5)
attr = self._stage.GetPrimAtPath(prim_path).GetAttribute(id[5:])
await ui_test.human_delay()
old_value = attr.Get()
new_value = not old_value
# Sets value to make sure current layer includes this property
# so it will not be removed after undo to refresh property
# window to resync all widgets.
attr.Set(old_value)
w.widget.model.set_value(new_value)
await ui_test.human_delay()
self.assertEqual(attr.Get(), new_value)
omni.kit.undo.undo()
await self.wait()
self.assertEqual(attr.Get(), old_value)
self.assertEqual(w.widget.model.get_value(), old_value)
elif id.startswith("sdf_asset_"):
w.widget.scroll_here_y(0.5)
attr = self._stage.GetPrimAtPath(prim_path).GetAttribute(id[10:])
await ui_test.human_delay()
old_value = attr.Get()
if isinstance(old_value, Sdf.AssetPath):
old_value = old_value.path
# Skips mdl field
if old_value.startswith("OmniPBR"):
continue
new_value = "testpath/abc.png"
# Sets value to make sure current layer includes this property
# so it will not be removed after undo to refresh property
# window to resync all widgets.
attr.Set(old_value)
w.widget.model.set_value(new_value)
await ui_test.human_delay()
self.assertEqual(attr.Get(), new_value)
omni.kit.undo.undo()
await self.wait()
self.assertEqual(attr.Get(), old_value)
self.assertEqual(w.widget.model.get_value(), old_value)
| 10,657 | Python | 43.781512 | 125 | 0.559444 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_mixed_variant.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import omni.kit.app
import omni.usd
import omni.kit.undo
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from pxr import Vt, Gf
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows
class PrimMixedVariantProperty(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
await open_stage(get_test_data_path(__name__, "usd_variants/ThreeDollyVariantStage.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_l1_mixed_variant_property(self):
import omni.kit.commands
await ui_test.find("Property").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
# select single variant prim
await select_prims(['/World/Dolly_Blueprint_ALL_VariantsPLB_viz_dual'])
await ui_test.human_delay()
# verify mixed is not shown
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_palettevariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, False)
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_boxvariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, False)
# select two variant prims
await select_prims(['/World/Dolly_Blueprint_ALL_VariantsPLB_viz_dual', '/World/Dolly_Blueprint_ALL_VariantsPLB_viz_dual_01'])
await ui_test.human_delay()
# verify mixed is shown
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_palettevariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, False)
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_boxvariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, True)
# select two variant prims
await select_prims(['/World/Dolly_Blueprint_ALL_VariantsPLB_viz_dual_01', '/World/Dolly_Blueprint_ALL_VariantsPLB_viz_dual_02'])
await ui_test.human_delay()
# verify mixed is shown
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_palettevariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, True)
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_boxvariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, False)
# select all threee variant prims
await select_prims(['/World/Dolly_Blueprint_ALL_VariantsPLB_viz_dual', '/World/Dolly_Blueprint_ALL_VariantsPLB_viz_dual_01', '/World/Dolly_Blueprint_ALL_VariantsPLB_viz_dual_02'])
await ui_test.human_delay()
# verify mixed is shown
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_palettevariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, True)
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_boxvariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, True)
async def test_l1_mixed_variant_property_set_value(self):
import omni.kit.commands
await ui_test.find("Property").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
# select all threee variant prims
await select_prims(['/World/Dolly_Blueprint_ALL_VariantsPLB_viz_dual', '/World/Dolly_Blueprint_ALL_VariantsPLB_viz_dual_01', '/World/Dolly_Blueprint_ALL_VariantsPLB_viz_dual_02'])
# verify mixed is shown
widget = ui_test.find("Property//Frame/**/*.identifier=='combo_variant_boxvariant'")
items = [item.model.get_value_as_string() for item in widget.model.get_item_children(None) if item.model.get_value_as_string() != ""]
for item in items:
# verify mixed is shown
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_boxvariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, True)
widget = ui_test.find("Property//Frame/**/*.identifier=='combo_variant_boxvariant'")
widget.model.set_value(item)
await ui_test.human_delay()
# verify mixed is not shown
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_boxvariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, False)
# verify mixed is shown
omni.kit.undo.undo()
await ui_test.human_delay()
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_boxvariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, True)
# verify mixed is not shown
omni.kit.undo.redo()
await ui_test.human_delay()
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_boxvariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, False)
# verify mixed is shown
omni.kit.undo.undo()
await ui_test.human_delay()
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_boxvariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, True)
# verify mixed is shown
widget = ui_test.find("Property//Frame/**/*.identifier=='combo_variant_palettevariant'")
items = [item.model.get_value_as_string() for item in widget.model.get_item_children(None) if item.model.get_value_as_string() != ""]
for item in items:
# verify mixed is shown
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_palettevariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, True)
widget = ui_test.find("Property//Frame/**/*.identifier=='combo_variant_palettevariant'")
widget.model.set_value(item)
await ui_test.human_delay()
# verify mixed is not shown
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_palettevariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, False)
# verify mixed is shown
omni.kit.undo.undo()
await ui_test.human_delay()
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_palettevariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, True)
# verify mixed is not shown
omni.kit.undo.redo()
await ui_test.human_delay()
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_palettevariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, False)
# verify mixed is shown
omni.kit.undo.undo()
await ui_test.human_delay()
widget = ui_test.find("Property//Frame/**/*.identifier=='mixed_variant_palettevariant'")
self.assertEqual(widget.widget.enabled, True)
self.assertEqual(widget.widget.visible, True)
| 8,289 | Python | 46.102272 | 187 | 0.654241 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/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():
stage = omni.usd.get_context().get_stage()
rootname = ""
if stage.HasDefaultPrim():
rootname = stage.GetDefaultPrim().GetPath().pathString
prim_path = "{}/defaultLight".format(rootname)
# Create basic DistantLight
omni.kit.commands.execute(
"CreatePrim",
prim_path=prim_path,
prim_type="DistantLight",
select_new_prim=False,
attributes={UsdLux.Tokens.angle: 1.0, UsdLux.Tokens.intensity: 3000},
create_default_xform=True,
)
return prim_path
| 686 | Python | 24.444444 | 77 | 0.663265 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_usd_api.py | import carb
import unittest
import omni.kit.test
from omni.kit import ui_test
from omni.kit.test_suite.helpers import wait_stage_loading
class TestUsdAPI(omni.kit.test.AsyncTestCase):
async def setUp(self):
from omni.kit.test_suite.helpers import arrange_windows
await arrange_windows("Stage", 200)
await omni.usd.get_context().new_stage_async()
self._prim_path = omni.kit.property.usd.tests.create_test_stage()
async def tearDown(self):
pass
async def test_usd_api(self):
from omni.kit.property.usd import PrimPathWidget
# test PrimPathWidget.*_button_menu_entry
button_menu_entry = PrimPathWidget.add_button_menu_entry(
path="TestUsdAPI/Test Entry", glyph=None, name_fn=None, show_fn=None, enabled_fn=None, onclick_fn=None
)
self.assertTrue(button_menu_entry != None)
button_menu_entries = PrimPathWidget.get_button_menu_entries()
self.assertTrue(button_menu_entry in button_menu_entries)
PrimPathWidget.remove_button_menu_entry(button_menu_entry)
button_menu_entries = PrimPathWidget.get_button_menu_entries()
self.assertFalse(button_menu_entry in button_menu_entries)
# test PrimPathWidget.*_path_item
path_func_updates = 0
def my_path_func():
nonlocal path_func_updates
path_func_updates += 1
# select prim so prim path widget is drawn
usd_context = omni.usd.get_context()
usd_context.get_selection().set_selected_prim_paths([self._prim_path], True)
PrimPathWidget.add_path_item(my_path_func)
path_items = PrimPathWidget.get_path_items()
self.assertTrue(my_path_func in path_items)
await ui_test.human_delay(10)
self.assertTrue(path_func_updates == 1)
PrimPathWidget.rebuild()
await ui_test.human_delay(10)
self.assertTrue(path_func_updates == 2)
PrimPathWidget.remove_path_item(my_path_func)
self.assertFalse(my_path_func in path_items)
PrimPathWidget.rebuild()
await ui_test.human_delay(10)
self.assertTrue(path_func_updates == 2)
usd_context.get_selection().set_selected_prim_paths([], True)
| 2,239 | Python | 36.966101 | 114 | 0.667262 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/basic_types_ui.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.commands
import omni.kit.test
import omni.ui as ui
from omni.ui.tests.test_base import OmniUiTest
from pxr import Kind, Sdf, Gf
class TestBasicTypesRange(OmniUiTest):
def __init__(self, tests=()):
super().__init__(tests)
self._widget_compare_table = {
Sdf.ValueTypeNames.Half2.type: (Gf.Vec2h(0.12345, 0.12345), 3),
Sdf.ValueTypeNames.Float2.type: (Gf.Vec2f(0.12345, 0.12345), 4),
Sdf.ValueTypeNames.Double2.type: (Gf.Vec2d(0.12345, 0.12345), 4),
Sdf.ValueTypeNames.Half3.type: (Gf.Vec3h(0.12345, 0.12345, 0.12345), 3),
Sdf.ValueTypeNames.Float3.type: (Gf.Vec3f(0.12345, 0.12345, 0.12345), 4),
Sdf.ValueTypeNames.Double3.type: (Gf.Vec3d(0.12345, 0.12345, 0.12345), 4),
Sdf.ValueTypeNames.Half4.type: (Gf.Vec4h(0.12345, 0.12345, 0.12345, 0.12345), 3),
Sdf.ValueTypeNames.Float4.type: (Gf.Vec4f(0.12345, 0.12345, 0.12345, 0.12345), 4),
Sdf.ValueTypeNames.Double4.type: (Gf.Vec4d(0.12345, 0.12345, 0.12345, 0.12345), 4),
}
# Before running each test
async def setUp(self):
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, arrange_windows
await arrange_windows(topleft_window="Property", topleft_height=64, topleft_width=800.0)
await open_stage(get_test_data_path(__name__, "usd/types.usda"))
await self._show_raw(False)
# After running each test
async def tearDown(self):
from omni.kit.test_suite.helpers import wait_stage_loading
await wait_stage_loading()
await self._show_raw(True)
async def _show_raw(self, new_state):
from omni.kit import ui_test
from omni.kit.test_suite.helpers import select_prims
await select_prims(["/defaultPrim/in_0"])
for w in ui_test.find_all("Property//Frame/**/CollapsableFrame[*]"):
if w.widget.title == "Raw USD Properties":
w.widget.collapsed = new_state
# change prim selection immediately after collapsed state change can result in one bad frame
# i.e. selection change event happens before frame UI rebuild, and old widget models are already destroyed.
await ui_test.human_delay()
await select_prims([])
async def test_l1_basic_type_coverage_ui(self):
from omni.kit.test_suite.helpers import select_prims, wait_stage_loading
from omni.kit import ui_test
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder
UsdPropertiesWidgetBuilder.reset_builder_coverage_table()
stage = omni.usd.get_context().get_stage()
# wait for material to load & UI to refresh
await wait_stage_loading()
for prim_path in ["/defaultPrim/in_0", "/defaultPrim/in_1", "/defaultPrim/out_0"]:
await select_prims([prim_path])
# scroll so all prims are queryable
for w in ui_test.find_all("Property//Frame/**/.identifier!=''"):
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
# create attribute used table
prim = stage.GetPrimAtPath(Sdf.Path(prim_path))
attr_list = {}
for attr in prim.GetAttributes():
attr_list[attr.GetPath().name] = attr.GetTypeName().type.typeName
# remove all widgets from attribute used table
for w in ui_test.find_all("Property//Frame/**/.identifier!=''"):
id = w.widget.identifier
for type in [
"bool_",
"float_slider_",
"integer_slider_",
"drag_per_channel_",
"boolean_per_channel_",
"token_",
"string_",
"timecode_",
"sdf_asset_array_", # must before "sdf_asset_"
"sdf_asset_",
"fallback_",
]:
if id.startswith(type):
attr_id = id[len(type) :]
# ignore placeholder widgets
if attr_id in attr_list:
del attr_list[attr_id]
break
# check attribute used table is empty
self.assertTrue(attr_list == {}, f"USD attribute {attr_list} have no widgets")
widget_builder_coverage_table = UsdPropertiesWidgetBuilder.widget_builder_coverage_table
for widget_type, builder_state in widget_builder_coverage_table.items():
self.assertTrue(builder_state, f"Failed to test {widget_type}")
async def test_l2_float_rounding(self):
from omni.kit.test_suite.helpers import select_prims, wait_stage_loading
from omni.kit import ui_test
# wait for material to load & UI to refresh
await wait_stage_loading()
stage = omni.usd.get_context().get_stage()
for prim_path in ["/defaultPrim/in_0", "/defaultPrim/in_1", "/defaultPrim/out_0"]:
await select_prims([prim_path])
# test float types
for w in ui_test.find_all("Property//Frame/**/.identifier!=''"):
id = w.widget.identifier
if id.startswith("float_slider_"):
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
await w.input("0.12345")
await ui_test.human_delay()
attr = stage.GetPrimAtPath(prim_path).GetAttribute(id[13:])
self.assertAlmostEqual(attr.Get(), 0.12345, places=4)
elif id.startswith("drag_per_channel_"):
if id.startswith("drag_per_channel_int"):
continue
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
sub_widgets = w.find_all("**/FloatSlider[*]")
if sub_widgets == []:
sub_widgets = w.find_all("**/FloatDrag[*]")
self.assertNotEqual(sub_widgets, [])
for child in sub_widgets:
child.model.set_value(0)
await child.input("0.12345")
await ui_test.human_delay()
attr = stage.GetPrimAtPath(prim_path).GetAttribute(id[17:])
metadata = attr.GetAllMetadata()
type_name = Sdf.ValueTypeNames.Find(metadata.get(Sdf.PrimSpec.TypeNameKey, "unknown type")).type
value, places = self._widget_compare_table[type_name]
self.assertAlmostEqual(attr.Get(), value, places=places)
async def test_l2_float_rounding_tab(self):
from omni.kit.test_suite.helpers import select_prims, wait_stage_loading
from omni.kit import ui_test
from carb.input import KeyboardInput
# wait for material to load & UI to refresh
await wait_stage_loading()
stage = omni.usd.get_context().get_stage()
for prim_path in ["/defaultPrim/in_0", "/defaultPrim/in_1", "/defaultPrim/out_0"]:
await select_prims([prim_path])
# test float types
for w in ui_test.find_all("Property//Frame/**/.identifier!=''"):
id = w.widget.identifier
if id.startswith("float_slider_"):
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
await w.input("0.12345", end_key=KeyboardInput.TAB)
await ui_test.human_delay()
attr = stage.GetPrimAtPath(prim_path).GetAttribute(id[13:])
self.assertAlmostEqual(attr.Get(), 0.12345, places=4)
elif id.startswith("drag_per_channel_"):
if id.startswith("drag_per_channel_int"):
continue
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
sub_widgets = w.find_all("**/FloatSlider[*]")
if sub_widgets == []:
sub_widgets = w.find_all("**/FloatDrag[*]")
self.assertNotEqual(sub_widgets, [])
for child in sub_widgets:
child.model.set_value(0)
await child.input("0.12345", end_key=KeyboardInput.TAB)
await ui_test.human_delay()
attr = stage.GetPrimAtPath(prim_path).GetAttribute(id[17:])
metadata = attr.GetAllMetadata()
type_name = Sdf.ValueTypeNames.Find(metadata.get(Sdf.PrimSpec.TypeNameKey, "unknown type")).type
value, places = self._widget_compare_table[type_name]
self.assertAlmostEqual(attr.Get(), value, places=places)
| 9,380 | Python | 44.985294 | 116 | 0.566418 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/hard_softrange_array_ui.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 sys
import math
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
class HardSoftRangeArrayUI(AsyncTestCase):
# Before running each test
async def setUp(self):
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
await arrange_windows("Stage", 64, 800)
await open_stage(get_test_data_path(__name__, "usd/soft_range_float3.usda"))
await ui_test.find("Property").focus()
# select prim
await select_prims(["/World/Looks/float3_softrange/Shader"])
# wait for material to load & UI to refresh
await wait_stage_loading()
# After running each test
async def tearDown(self):
from omni.kit import ui_test
from omni.kit.test_suite.helpers import select_prims, wait_stage_loading
# de-select prims to prevent _delayed_dirty_handler exception
await select_prims([])
await wait_stage_loading()
def _verify_values(self, widget_name: str, expected_value, model_soft_min, model_soft_max, hard_min, hard_max):
from omni.kit import ui_test
frame = ui_test.find(f"Property//Frame/**/.identifier=='{widget_name}'")
for widget in frame.find_all(f"**/FloatDrag[*]"):
self.assertAlmostEqual(widget.model.get_value_as_float(), expected_value.pop(0))
if model_soft_min and widget.model._soft_range_min:
self.assertAlmostEqual(widget.model._soft_range_min, model_soft_min)
if model_soft_max and widget.model._soft_range_max:
self.assertAlmostEqual(widget.model._soft_range_max, model_soft_max)
self.assertAlmostEqual(widget.widget.min, hard_min)
self.assertAlmostEqual(widget.widget.max, hard_max)
async def _click_type(self, widget_name: str, values):
from omni.kit import ui_test
frame = ui_test.find(f"Property//Frame/**/.identifier=='{widget_name}'")
for widget in frame.find_all(f"**/FloatDrag[*]"):
await widget.input(str(values.pop(0)))
async def test_hard_softrange_float3_ui(self):
from omni.kit import ui_test
# check default values
self._verify_values("drag_per_channel_inputs:float3_1",
expected_value=[0.75, 0.5, 0.25],
model_soft_min=None,
model_soft_max=None,
hard_min=0,
hard_max=1)
# change values
await self._click_type("drag_per_channel_inputs:float3_1", values=[0.25, 1.45, 1.35])
# verify changed values
self._verify_values("drag_per_channel_inputs:float3_1",
expected_value=[0.25, 1.45, 1.35],
model_soft_min=0.0,
model_soft_max=1.25,
hard_min=0,
hard_max=1)
# change values
await self._click_type("drag_per_channel_inputs:float3_1", values=[23.25, 21.45, 24.5, 99.35])
# verify changed values
self._verify_values("drag_per_channel_inputs:float3_1",
[10.0, 10.0, 10.0, 10.0],
model_soft_min=0.0,
model_soft_max=10.0,
hard_min=0,
hard_max=10.0)
# click reset
frame = ui_test.find("Property//Frame/**/.identifier=='drag_per_channel_inputs:float3_1'")
for widget in frame.find_all(f"**/ImageWithProvider[*]"):
await widget.click()
# check default values
self._verify_values("drag_per_channel_inputs:float3_1",
expected_value=[0.75, 0.5, 0.25],
model_soft_min=None,
model_soft_max=None,
hard_min=0,
hard_max=1)
async def test_hard_softrange_float4_ui(self):
from omni.kit import ui_test
# check default values
self._verify_values("drag_per_channel_inputs:float4_1",
expected_value=[0.75, 0.5, 0.45, 0.25],
model_soft_min=None,
model_soft_max=None,
hard_min=0,
hard_max=1)
# change values
await self._click_type("drag_per_channel_inputs:float4_1", values=[1.25, 1.45, 1.5, 1.35])
# verify changed values
self._verify_values("drag_per_channel_inputs:float4_1",
expected_value=[1.25, 1.45, 1.5, 1.35],
model_soft_min=0.0,
model_soft_max=1.25,
hard_min=0,
hard_max=1.25)
# change values
await self._click_type("drag_per_channel_inputs:float4_1", values=[10.25, 10.45, 10.5, 10.35])
# verify changed values
self._verify_values("drag_per_channel_inputs:float4_1",
[5.0, 5.0, 5.0, 5.0],
model_soft_min=0.0,
model_soft_max=5.0,
hard_min=0,
hard_max=5.0)
# click reset
frame = ui_test.find("Property//Frame/**/.identifier=='drag_per_channel_inputs:float4_1'")
for widget in frame.find_all(f"**/ImageWithProvider[*]"):
await widget.click()
# check default values
self._verify_values("drag_per_channel_inputs:float4_1",
expected_value=[0.75, 0.5, 0.45, 0.25],
model_soft_min=None,
model_soft_max=None,
hard_min=0,
hard_max=1)
async def test_hard_softrange_float2_ui(self):
from omni.kit import ui_test
# check default values
self._verify_values("drag_per_channel_inputs:float2_1", [0.75, 0.25], None, None, 0, 1)
# change values
await self._click_type("drag_per_channel_inputs:float2_1", values=[0.25, 1.35])
# verify changed values
self._verify_values("drag_per_channel_inputs:float2_1",
expected_value=[0.25, 1.0],
model_soft_min=0.0,
model_soft_max=1.0,
hard_min=0,
hard_max=1)
# change values
await self._click_type("drag_per_channel_inputs:float2_1", values=[-2.45, -2.35])
# verify changed values
self._verify_values("drag_per_channel_inputs:float2_1",
[0.0, 0.0],
model_soft_min=0.0,
model_soft_max=1.0,
hard_min=0,
hard_max=1.0)
# click reset
frame = ui_test.find("Property//Frame/**/.identifier=='drag_per_channel_inputs:float2_1'")
for widget in frame.find_all(f"**/ImageWithProvider[*]"):
await widget.click()
# check default values
self._verify_values("drag_per_channel_inputs:float2_1", [0.75, 0.25], None, None, 0, 1)
| 7,564 | Python | 37.994845 | 129 | 0.556716 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_widget.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.commands
import omni.kit.test
import omni.ui as ui
from omni.ui.tests.test_base import OmniUiTest
from pxr import Gf, Kind, Sdf, UsdShade
from ..usd_attribute_model import GfVecAttributeSingleChannelModel
class TestWidget(OmniUiTest):
# Before running each test
async def setUp(self):
from omni.kit import ui_test
from omni.kit.test_suite.helpers import arrange_windows
await super().setUp()
await arrange_windows("Stage", 200)
from omni.kit.property.usd.widgets import TEST_DATA_PATH
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute()
self._usd_path = TEST_DATA_PATH.absolute().joinpath("usd").absolute()
import omni.kit.window.property as p
from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget
self._w = p.get_window()
INT32_MIN = -2147483648
INT32_MAX = 2147483647
INT64_MIN = -9223372036854775808
INT64_MAX = 9223372036854775807
HALF_LOWEST = -65504.0
HALF_MAX = 65504.0
# In double precision
FLT_LOWEST = -3.4028234663852886e38
FLT_MIN = 1.1754943508222875e-38
FLT_MAX = 3.4028234663852886e38
FLT_EPS = 1.1920928955078125e-07
DBL_LOWEST = -1.7976931348623158e308
DBL_MIN = 2.2250738585072014e-308
DBL_MAX = 1.7976931348623158e308
DBL_EPS = 2.2204460492503131e-016
# (attr_name, attr_type, value_0, value_1, value_2, expected_model_count)
self._test_data = [
("bool_attr", Sdf.ValueTypeNames.Bool, True, False, True, 1),
("uchar_attr", Sdf.ValueTypeNames.UChar, ord("o"), ord("v"), ord("k"), 1),
("int_attr", Sdf.ValueTypeNames.Int, -1, 0, 1, 1),
("uint_attr", Sdf.ValueTypeNames.UInt, 1, 2, 3, 1),
("int64_attr", Sdf.ValueTypeNames.Int64, INT64_MIN, 0, INT64_MAX, 1),
(
"uint64_attr",
Sdf.ValueTypeNames.UInt64,
0,
2,
INT64_MAX,
1,
), # omni.ui only supports int64 range, thus uint max won't work
(
"half_attr",
Sdf.ValueTypeNames.Half,
HALF_LOWEST,
0.333251953125,
HALF_MAX,
1,
), # half is stored as double in model
(
"float_attr",
Sdf.ValueTypeNames.Float,
FLT_MIN,
FLT_MAX,
FLT_EPS,
1,
), # Float is stored as double in model
("double_attr", Sdf.ValueTypeNames.Double, DBL_MIN, DBL_MAX, DBL_EPS, 1),
("timdcode_attr", Sdf.ValueTypeNames.TimeCode, Sdf.TimeCode(10), Sdf.TimeCode(20), Sdf.TimeCode(30), 1),
("string_attr", Sdf.ValueTypeNames.String, "This", "is a", "string", 1),
(
"token_attr",
Sdf.ValueTypeNames.Token,
Kind.Tokens.subcomponent,
Kind.Tokens.component,
Kind.Tokens.group,
1,
),
("asset_attr", Sdf.ValueTypeNames.Asset, "/This", "/is/an", "/asset", 1),
(
"int2_attr",
Sdf.ValueTypeNames.Int2,
Gf.Vec2i(INT32_MIN, INT32_MAX),
Gf.Vec2i(INT32_MAX, INT32_MIN),
Gf.Vec2i(INT32_MIN, INT32_MAX),
2 + 1, # Vector has one additional model for label context menu
),
(
"int3_attr",
Sdf.ValueTypeNames.Int3,
Gf.Vec3i(INT32_MIN, INT32_MAX, INT32_MIN),
Gf.Vec3i(INT32_MAX, INT32_MIN, INT32_MAX),
Gf.Vec3i(INT32_MIN, INT32_MAX, INT32_MIN),
3 + 1,
),
(
"int4_attr",
Sdf.ValueTypeNames.Int4,
Gf.Vec4i(INT32_MIN, INT32_MAX, INT32_MIN, INT32_MAX),
Gf.Vec4i(INT32_MAX, INT32_MIN, INT32_MAX, INT32_MIN),
Gf.Vec4i(INT32_MIN, INT32_MAX, INT32_MIN, INT32_MAX),
4 + 1,
),
(
"half2_attr",
Sdf.ValueTypeNames.Half2,
Gf.Vec2h(HALF_LOWEST, HALF_MAX),
Gf.Vec2h(HALF_MAX, HALF_LOWEST),
Gf.Vec2h(HALF_LOWEST, HALF_MAX),
2 + 1,
),
(
"half3_attr",
Sdf.ValueTypeNames.Half3,
Gf.Vec3h(HALF_LOWEST, HALF_MAX, HALF_LOWEST),
Gf.Vec3h(HALF_MAX, HALF_LOWEST, HALF_MAX),
Gf.Vec3h(HALF_LOWEST, HALF_MAX, HALF_LOWEST),
3 + 1,
),
(
"half4_attr",
Sdf.ValueTypeNames.Half4,
Gf.Vec4h(HALF_LOWEST, HALF_MAX, HALF_LOWEST, HALF_MAX),
Gf.Vec4h(HALF_MAX, HALF_LOWEST, HALF_LOWEST, HALF_MAX),
Gf.Vec4h(HALF_LOWEST, HALF_MAX, HALF_LOWEST, HALF_MAX),
4 + 1,
),
(
"float2_attr",
Sdf.ValueTypeNames.Float2,
Gf.Vec2f(FLT_LOWEST, FLT_MAX),
Gf.Vec2f(FLT_MAX, FLT_LOWEST),
Gf.Vec2f(FLT_MAX, FLT_MAX),
2 + 1,
),
(
"float3_attr",
Sdf.ValueTypeNames.Float3,
Gf.Vec3f(FLT_LOWEST, FLT_MAX, FLT_LOWEST),
Gf.Vec3f(FLT_MAX, FLT_LOWEST, FLT_MAX),
Gf.Vec3f(FLT_MAX, FLT_MAX, FLT_MAX),
3 + 1,
),
(
"float4_attr",
Sdf.ValueTypeNames.Float4,
Gf.Vec4f(FLT_LOWEST, FLT_MAX, FLT_LOWEST, FLT_MAX),
Gf.Vec4f(FLT_MAX, FLT_LOWEST, FLT_MAX, FLT_LOWEST),
Gf.Vec4f(FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX),
4 + 1,
),
(
"double2_attr",
Sdf.ValueTypeNames.Double2,
Gf.Vec2d(DBL_LOWEST, DBL_MAX),
Gf.Vec2d(DBL_MAX, DBL_LOWEST),
Gf.Vec2d(DBL_MAX, DBL_MAX),
2 + 1,
),
(
"double3_attr",
Sdf.ValueTypeNames.Double3,
Gf.Vec3d(DBL_LOWEST, DBL_MAX, DBL_LOWEST),
Gf.Vec3d(DBL_MAX, DBL_LOWEST, DBL_MAX),
Gf.Vec3d(DBL_MAX, DBL_MAX, DBL_MAX),
3 + 1,
),
(
"double4_attr",
Sdf.ValueTypeNames.Double4,
Gf.Vec4d(DBL_LOWEST, DBL_MAX, DBL_LOWEST, DBL_MAX),
Gf.Vec4d(DBL_MAX, DBL_LOWEST, DBL_MAX, DBL_LOWEST),
Gf.Vec4d(DBL_MAX, DBL_MAX, DBL_MAX, DBL_MAX),
4 + 1,
),
(
"point3h_attr",
Sdf.ValueTypeNames.Point3h,
Gf.Vec3h(HALF_LOWEST, HALF_MAX, HALF_LOWEST),
Gf.Vec3h(HALF_MAX, HALF_LOWEST, HALF_MAX),
Gf.Vec3h(HALF_LOWEST, HALF_MAX, HALF_LOWEST),
3 + 1,
),
(
"point3f_attr",
Sdf.ValueTypeNames.Point3f,
Gf.Vec3f(FLT_LOWEST, FLT_MAX, FLT_LOWEST),
Gf.Vec3f(FLT_MAX, FLT_LOWEST, FLT_MAX),
Gf.Vec3f(FLT_MAX, FLT_MAX, FLT_MAX),
3 + 1,
),
(
"point3d_attr",
Sdf.ValueTypeNames.Point3d,
Gf.Vec3d(DBL_LOWEST, DBL_MAX, DBL_LOWEST),
Gf.Vec3d(DBL_MAX, DBL_LOWEST, DBL_MAX),
Gf.Vec3d(DBL_MAX, DBL_MAX, DBL_MAX),
3 + 1,
),
(
"vector3h_attr",
Sdf.ValueTypeNames.Vector3h,
Gf.Vec3h(HALF_LOWEST, HALF_MAX, HALF_LOWEST),
Gf.Vec3h(HALF_MAX, HALF_LOWEST, HALF_MAX),
Gf.Vec3h(HALF_LOWEST, HALF_MAX, HALF_LOWEST),
3 + 1,
),
(
"vector3f_attr",
Sdf.ValueTypeNames.Vector3f,
Gf.Vec3f(FLT_LOWEST, FLT_MAX, FLT_LOWEST),
Gf.Vec3f(FLT_MAX, FLT_LOWEST, FLT_MAX),
Gf.Vec3f(FLT_MAX, FLT_MAX, FLT_MAX),
3 + 1,
),
(
"vector3d_attr",
Sdf.ValueTypeNames.Vector3d,
Gf.Vec3d(DBL_LOWEST, DBL_MAX, DBL_LOWEST),
Gf.Vec3d(DBL_MAX, DBL_LOWEST, DBL_MAX),
Gf.Vec3d(DBL_MAX, DBL_MAX, DBL_MAX),
3 + 1,
),
(
"normal3h_attr",
Sdf.ValueTypeNames.Normal3h,
Gf.Vec3h(1.0, 0.0, 0.0),
Gf.Vec3h(0.0, 1.0, 0.0),
Gf.Vec3h(0.0, 0.0, 1.0),
3 + 1,
),
(
"normal3f_attr",
Sdf.ValueTypeNames.Normal3f,
Gf.Vec3f(1.0, 0.0, 0.0),
Gf.Vec3f(0.0, 1.0, 0.0),
Gf.Vec3f(0.0, 0.0, 1.0),
3 + 1,
),
(
"normal3d_attr",
Sdf.ValueTypeNames.Normal3d,
Gf.Vec3d(1.0, 0.0, 0.0),
Gf.Vec3d(0.0, 1.0, 0.0),
Gf.Vec3d(0.0, 0.0, 1.0),
3 + 1,
),
(
"color3h_attr",
Sdf.ValueTypeNames.Color3h,
Gf.Vec3h(1.0, 0.0, 0.0),
Gf.Vec3h(0.0, 1.0, 0.0),
Gf.Vec3h(0.0, 0.0, 1.0),
3 + 1, # Color attr has one model per channel + one model for the color picker
),
(
"color3f_attr",
Sdf.ValueTypeNames.Color3f,
Gf.Vec3f(1.0, 0.0, 0.0),
Gf.Vec3f(0.0, 1.0, 0.0),
Gf.Vec3f(0.0, 0.0, 1.0),
3 + 1,
),
(
"color3d_attr",
Sdf.ValueTypeNames.Color3d,
Gf.Vec3d(1.0, 0.0, 0.0),
Gf.Vec3d(0.0, 1.0, 0.0),
Gf.Vec3d(0.0, 0.0, 1.0),
3 + 1,
),
(
"color4h_attr",
Sdf.ValueTypeNames.Color4h,
Gf.Vec4h(1.0, 0.0, 0.0, 1.0),
Gf.Vec4h(0.0, 1.0, 0.0, 1.0),
Gf.Vec4h(0.0, 0.0, 1.0, 1.0),
4 + 1,
),
(
"color4f_attr",
Sdf.ValueTypeNames.Color4f,
Gf.Vec4f(1.0, 0.0, 0.0, 1.0),
Gf.Vec4f(0.0, 1.0, 0.0, 1.0),
Gf.Vec4f(0.0, 0.0, 1.0, 1.0),
4 + 1,
),
(
"color4d_attr",
Sdf.ValueTypeNames.Color4d,
Gf.Vec4d(1.0, 0.0, 0.0, 1.0),
Gf.Vec4d(0.0, 1.0, 0.0, 1.0),
Gf.Vec4d(0.0, 0.0, 1.0, 1.0),
4 + 1,
),
("quath_attr", Sdf.ValueTypeNames.Quath, Gf.Quath(-1), Gf.Quath(0), Gf.Quath(1), 1),
("quatf_attr", Sdf.ValueTypeNames.Quatf, Gf.Quatf(-1), Gf.Quatf(0), Gf.Quatf(1), 1),
("quatd_attr", Sdf.ValueTypeNames.Quatd, Gf.Quatd(-1), Gf.Quatd(0), Gf.Quatd(1), 1),
("matrix2d_attr", Sdf.ValueTypeNames.Matrix2d, Gf.Matrix2d(-1), Gf.Matrix2d(0), Gf.Matrix2d(1), 1),
("matrix3d_attr", Sdf.ValueTypeNames.Matrix3d, Gf.Matrix3d(-1), Gf.Matrix3d(0), Gf.Matrix3d(1), 1),
("matrix4d_attr", Sdf.ValueTypeNames.Matrix4d, Gf.Matrix4d(-1), Gf.Matrix4d(0), Gf.Matrix4d(1), 1),
("frame4d_attr", Sdf.ValueTypeNames.Frame4d, Gf.Matrix4d(-1), Gf.Matrix4d(0), Gf.Matrix4d(1), 1),
(
"texCoord2f_attr",
Sdf.ValueTypeNames.TexCoord2f,
Gf.Vec2f(1.0, 0.0),
Gf.Vec2f(0.0, 1.0),
Gf.Vec2f(1.0, 1.0),
2 + 1,
),
(
"texCoord2d_attr",
Sdf.ValueTypeNames.TexCoord2d,
Gf.Vec2d(1.0, 0.0),
Gf.Vec2d(0.0, 1.0),
Gf.Vec2d(1.0, 1.0),
2 + 1,
),
(
"texCoord2h_attr",
Sdf.ValueTypeNames.TexCoord2h,
Gf.Vec2h(1.0, 0.0),
Gf.Vec2h(0.0, 1.0),
Gf.Vec2h(1.0, 1.0),
2 + 1,
),
(
"texCoord3f_attr",
Sdf.ValueTypeNames.TexCoord3f,
Gf.Vec3f(1.0, 0.0, 1.0),
Gf.Vec3f(0.0, 1.0, 0.0),
Gf.Vec3f(1.0, 1.0, 1.0),
3 + 1,
),
(
"texCoord3d_attr",
Sdf.ValueTypeNames.TexCoord3d,
Gf.Vec3d(1.0, 0.0, 1.0),
Gf.Vec3d(0.0, 1.0, 0.0),
Gf.Vec3d(1.0, 1.0, 1.0),
3 + 1,
),
(
"texCoord3h_attr",
Sdf.ValueTypeNames.TexCoord3h,
Gf.Vec3h(1.0, 0.0, 1.0),
Gf.Vec3h(0.0, 1.0, 0.0),
Gf.Vec3h(1.0, 1.0, 1.0),
3 + 1,
),
# Add array types
(
"asset_array_attr",
Sdf.ValueTypeNames.AssetArray,
Sdf.AssetPathArray(2, [Sdf.AssetPath("foo.ext"), Sdf.AssetPath("bar.ext")]),
Sdf.AssetPathArray(),
Sdf.AssetPathArray(3, [Sdf.AssetPath("foo.ext"), Sdf.AssetPath("bar.ext"), Sdf.AssetPath("baz.ext")]),
1,
),
]
self._test_widget = UsdPropertiesWidget(title="Test USD Properties", collapsed=False)
self._w.register_widget("prim", "test_raw_attribute", self._test_widget)
self._usd_context = omni.usd.get_context()
await self._usd_context.new_stage_async()
self._stage = self._usd_context.get_stage()
self._test_prim = self._stage.DefinePrim("/TestPrim")
self._usd_context.get_selection().set_selected_prim_paths(["/TestPrim"], True)
await ui_test.human_delay(10)
# After running each test
async def tearDown(self):
from omni.kit import ui_test
self._usd_context.get_selection().set_selected_prim_paths([], False)
await ui_test.human_delay()
await self._usd_context.close_stage_async()
self._w.unregister_widget("prim", "test_raw_attribute")
self._test_widget = None
self._test_prim = None
self._stage = None
await super().tearDown()
# This tests read/write between USD attribute model and USD data
async def test_attribute_model(self):
def verify_model_value(value_idx: int):
models = self._test_widget._models
for attr_data in self._test_data:
attr_path = prim_path.AppendProperty(attr_data[0])
attr_model_list = models.get(attr_path, None)
self.assertNotEqual(attr_model_list, None, msg=attr_data[0])
self.assertEqual(len(attr_model_list), attr_data[5], msg=attr_data[0])
for model in attr_model_list:
self.assertEqual(model.get_value(), attr_data[value_idx], msg=attr_data[0])
# Test Resync event
for attr_data in self._test_data:
attr = self._test_prim.CreateAttribute(attr_data[0], attr_data[1])
self.assertTrue(attr is not None)
attr.Set(attr_data[2])
# Wait for a frame for widget to process all pending changes
await omni.kit.app.get_app().next_update_async()
# Need to wait for an additional frame for omni.ui rebuild to take effect
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
prim_path = self._test_prim.GetPrimPath()
# Verify the model has fetched the correct data
verify_model_value(2)
# Test info changed only event
for attr_data in self._test_data:
attr = self._test_prim.GetAttribute(attr_data[0])
self.assertTrue(attr is not None)
attr.Set(attr_data[3])
# Wait for a frame for widget to process all pending changes
await omni.kit.app.get_app().next_update_async()
# Verify the model has fetched the correct data
verify_model_value(3)
# Test set value to model
# TODO ideally new value should be set via UI, and have UI update the model instead of setting model directly,
# it is less useful of a test to write to model directly from user-interaction perspective.
# Update the test once we can locate UI element and emulate input.
models = self._test_widget._models
for attr_data in self._test_data:
attr_path = prim_path.AppendProperty(attr_data[0])
attr_model_list = models.get(attr_path, None)
for i, model in enumerate(attr_model_list):
if isinstance(model, GfVecAttributeSingleChannelModel):
model.set_value(attr_data[4][i])
# Wait for a frame for the rest of the channel model to sync the change
await omni.kit.app.get_app().next_update_async()
else:
model.set_value(attr_data[4])
# verify value updated in USD
for attr_data in self._test_data:
attr = self._test_prim.GetAttribute(attr_data[0])
self.assertNotEqual(attr, None)
self.assertEqual(attr.Get(), attr_data[4], msg=attr_data[0])
async def _test_attribute_ui_base(self, start, end):
await self.docked_test_window(
window=self._w._window,
width=800,
height=950,
restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position=ui.DockPosition.BOTTOM,
)
# Populate USD attributes
for attr_data in self._test_data[start:end]:
attr = self._test_prim.CreateAttribute(attr_data[0], attr_data[1])
self.assertTrue(attr is not None)
attr.Set(attr_data[2])
# Wait for a frame for widget to process all pending changes
await omni.kit.app.get_app().next_update_async()
# Need to wait for an additional frame for omni.ui rebuild to take effect
await omni.kit.app.get_app().next_update_async()
# Capture screenshot of property window and compare with golden image (1/2)
# The property list is too long and Window limits max window size base on primary monitor height,
# the test has to be split into 2 each tests half of the attributes
async def test_attribute_ui_1(self):
await self._test_attribute_ui_base(0, int(len(self._test_data) / 2))
# finalize needs to be called here to get proper test name
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_attribute_ui_1.png")
# Capture screenshot of property window and compare with golden image (2/2)
# The property list is too long and Window limits max window size base on primary monitor height,
# the test has to be split into 2 each tests half of the attributes
async def test_attribute_ui_2(self):
await self._test_attribute_ui_base(int(len(self._test_data) / 2), len(self._test_data))
# finalize needs to be called here to get proper test name
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_attribute_ui_2.png")
# Tests the relationship UI
async def test_relationship_ui(self):
await self.docked_test_window(
window=self._w._window,
width=800,
height=950,
restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position=ui.DockPosition.BOTTOM,
)
target_prim_paths = ["/Target1", "/Target2", "/Target3"]
for prim_path in target_prim_paths:
self._stage.DefinePrim(prim_path)
rel = self._test_prim.CreateRelationship("TestRelationship")
for prim_path in target_prim_paths:
omni.kit.commands.execute("AddRelationshipTarget", relationship=rel, target=prim_path)
# Wait for a frame for widget to process all pending changes
await omni.kit.app.get_app().next_update_async()
omni.kit.commands.execute("RemoveRelationshipTarget", relationship=rel, target=target_prim_paths[-1])
# Need to wait for an additional frame for omni.ui rebuild to take effect
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_relationship_ui.png")
# Tests SdfReferences UI
async def test_references_ui(self):
await self.docked_test_window(
window=self._w._window,
width=800,
height=420,
restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position=ui.DockPosition.BOTTOM,
)
usd_context = omni.usd.get_context()
test_file_path = self._usd_path.joinpath("ref_test.usda").absolute()
await usd_context.open_stage_async(str(test_file_path))
self._stage = usd_context.get_stage()
ref_prim = self._stage.GetPrimAtPath("/World")
ref = Sdf.Reference(primPath="/Xform")
omni.kit.commands.execute(
"AddReference",
stage=self._stage,
prim_path="/World",
reference=ref,
)
ref = Sdf.Reference(assetPath="cube.usda", primPath="/Xform")
omni.kit.commands.execute(
"AddReference",
stage=self._stage,
prim_path="/World",
reference=ref,
)
ref = Sdf.Reference(assetPath="sphere.usda")
omni.kit.commands.execute(
"AddReference",
stage=self._stage,
prim_path="/World",
reference=ref,
)
ref = Sdf.Reference(primPath="/Xform2")
omni.kit.commands.execute(
"AddReference",
stage=self._stage,
prim_path="/World",
reference=ref,
)
await omni.kit.app.get_app().next_update_async()
# Select the prim after references are created because the widget hide itself when there's no reference
# Property window does not refresh itself when new ref is added. This is a limitation to property window that
# needs to be fixed.
usd_context.get_selection().set_selected_prim_paths(["/World"], True)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
ref = Sdf.Reference(primPath="/Xform2")
omni.kit.commands.execute(
"RemoveReference",
stage=self._stage,
prim_path="/World",
reference=ref,
)
await omni.kit.app.get_app().next_update_async()
# Need to wait for an additional frame for omni.ui rebuild to take effect
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_references_ui.png")
# Tests mixed TfToken (with allowedTokens) and MDL enum that when one changes
# The bug was when selecting 2+ prims with TfToken(or MDL enum) that results in a mixed state,
# changing last selected prim's value from USD API will overwrite the value for other untouched attributes.
async def test_mixed_combobox_attributes(self):
shader_a = UsdShade.Shader.Define(self._stage, "/PrimA")
shader_b = UsdShade.Shader.Define(self._stage, "/PrimB")
enum_options = "a:0|b:1|c:2"
input_a = shader_a.CreateInput("mdl_enum", Sdf.ValueTypeNames.Int)
input_a.SetSdrMetadataByKey("options", enum_options)
input_a.SetRenderType("::dummy::enum")
input_a.Set(0)
input_b = shader_b.CreateInput("mdl_enum", Sdf.ValueTypeNames.Int)
input_b.SetSdrMetadataByKey("options", enum_options)
input_b.SetRenderType("::dummy::enum")
input_b.Set(1)
prim_a = shader_a.GetPrim()
prim_b = shader_b.GetPrim()
allowed_tokens = ["a", "b", "c"]
attr_a = prim_a.CreateAttribute("token", Sdf.ValueTypeNames.Token)
attr_a.SetMetadata("allowedTokens", allowed_tokens)
attr_a.Set(allowed_tokens[0])
attr_b = prim_b.CreateAttribute("token", Sdf.ValueTypeNames.Token)
attr_b.SetMetadata("allowedTokens", allowed_tokens)
attr_b.Set(allowed_tokens[1])
omni.usd.get_context().get_selection().set_selected_prim_paths(["/PrimA", "/PrimB"], True)
# took 5 frames to trigger the bug
for i in range(5):
await omni.kit.app.get_app().next_update_async()
input_b.Set(2)
attr_b.Set(allowed_tokens[2])
await omni.kit.app.get_app().next_update_async()
# if bug happens, input_a's value will be set to 2
self.assertEqual(input_a.Get(), 0)
# if bug happens, attr_a's value will be set to "c"
self.assertEqual(attr_a.Get(), allowed_tokens[0])
| 26,055 | Python | 37.947683 | 118 | 0.526578 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_softrange_ui.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 sys
import math
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
from omni.kit import ui_test
from pxr import Sdf, UsdShade
from omni.kit.test_suite.helpers import (
open_stage,
get_test_data_path,
select_prims,
wait_stage_loading,
arrange_windows
)
class SoftRangeUI(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows("Stage", 64)
await open_stage(get_test_data_path(__name__, "usd/soft_range.usda"))
# After running each test
async def tearDown(self):
# de-select prims to prevent _delayed_dirty_handler exception
await select_prims([])
await wait_stage_loading()
def _verify_values(self, widget_name: str, expected_value, model_soft_min, model_soft_max, min, max, places=4):
for widget in ui_test.find_all(f"Property//Frame/**/.identifier=='{widget_name}'"):
self.assertAlmostEqual(widget.model.get_value(), expected_value, places=places)
if model_soft_min != None:
self.assertAlmostEqual(widget.model._soft_range_min, model_soft_min, places=places)
if model_soft_max != None:
self.assertAlmostEqual(widget.model._soft_range_max, model_soft_max, places=places)
self.assertAlmostEqual(widget.widget.min, min, places=places)
self.assertAlmostEqual(widget.widget.max, max, places=places)
async def _click_type_verify(self, widget_name: str, value, expected_value, model_soft_min, model_soft_max, min, max, places=4):
for widget in ui_test.find_all(f"Property//Frame/**/.identifier=='{widget_name}'"):
await widget.input(str(value))
self._verify_values(widget_name, expected_value, model_soft_min, model_soft_max, min, max, places=places)
async def _hide_frames(self, show_list):
for w in ui_test.find_all("Property//Frame/**/CollapsableFrame[*]"):
if show_list == None:
w.widget.collapsed = False
elif w.widget.title in show_list:
w.widget.collapsed = False
else:
w.widget.collapsed = True
await ui_test.human_delay()
async def test_l2_softrange_ui(self):
await ui_test.find("Property").focus()
range_name = "float_slider_inputs:glass_ior"
# select prim
await select_prims(["/World/Looks/OmniGlass/Shader"])
# wait for material to load & UI to refresh
await wait_stage_loading()
# test soft_range unlimited inputs:glass_ior
await self._hide_frames(["Shader", "Refraction"])
# check default values
self._verify_values(range_name, 1.491, None, None, 1, 4)
# something not right here, accuracy of 0.2 ?
await self._click_type_verify(range_name, 1500, 1500, 1, 1500, 1, 1500) # value & max 1500
await self._click_type_verify(range_name, -150, -150, -150, 1500, -150, 1500) # value & min -150 & max 1500
await self._click_type_verify(range_name, 500, 500, -150, 1500, -150, 1500) # value 500 & min -150 & max 1500
await self._click_type_verify(range_name, 0, 0, -150, 1500, -150, 1500) # value 0 & min -150 & max 1500
# reset values
await ui_test.find(f"Property//Frame/**/ImageWithProvider[*].identifier=='control_state_inputs:glass_ior'").click()
# verify
self._verify_values(range_name, 1.491, None, None, 1, 4)
| 3,952 | Python | 41.967391 | 132 | 0.652834 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/__init__.py | from .create_prims import *
from .test_widget import *
from .test_usd_api import *
from .test_placeholder import *
from .test_path_menu import *
from .test_shader_goto_material_property import *
from .test_shader_goto_UDIM_material_property import *
from .hard_softrange_ui import *
from .hard_softrange_array_ui import *
from .test_shader_drag_drop_mdl import *
from .test_references import *
from .test_payloads import *
from .basic_types_ui import *
from .test_drag_drop_material_property_combobox import *
from .test_drag_drop_material_property_preview import *
from .test_material_widget_refresh_on_binding import *
from .test_property_bind_material_combo import *
from .test_shader_material_subid_property import *
from .test_softrange_ui import *
from .test_variant import *
from .test_mixed_variant import *
from .test_path_add_menu import *
from .test_asset_array_widget import *
from .test_relationship import *
from .test_usd_preferences import *
from .test_bool_arrays import *
from .test_material_edits_and_undo import *
| 1,034 | Python | 35.964284 | 56 | 0.773694 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_placeholder.py | import carb
import unittest
import omni.kit.test
from pxr import Sdf, Usd
class TestPlaceholderAttribute(omni.kit.test.AsyncTestCase):
async def setUp(self):
await omni.usd.get_context().new_stage_async()
async def tearDown(self):
pass
async def test_placeholder_attribute(self):
from omni.kit.property.usd.placeholder_attribute import PlaceholderAttribute
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
prim = stage.GetPrimAtPath("/Sphere")
attr_dict = {Sdf.PrimSpec.TypeNameKey: "bool", "customData": {"default": True}}
# verifty attribute doesn't exist
self.assertFalse(prim.GetAttribute("primvars:doNotCastShadows"))
#################################################################
# test expected usage
#################################################################
attr = PlaceholderAttribute(name="primvars:doNotCastShadows", prim=prim, metadata=attr_dict)
# test stubs
self.assertFalse(attr.ValueMightBeTimeVarying())
self.assertFalse(attr.HasAuthoredConnections())
# test get functions
self.assertTrue(attr.Get())
self.assertEqual(attr.GetPath(), "/Sphere")
self.assertEqual(attr.GetPrim(), prim)
self.assertEqual(attr.GetMetadata("customData"), attr_dict["customData"])
self.assertFalse(attr.GetMetadata("test"))
self.assertEqual(attr.GetAllMetadata(), attr_dict)
# test CreateAttribute
attr.CreateAttribute()
# verifty attribute does exist
self.assertTrue(prim.GetAttribute("primvars:doNotCastShadows"))
prim.RemoveProperty("primvars:doNotCastShadows")
self.assertFalse(prim.GetAttribute("primvars:doNotCastShadows"))
#################################################################
# test no metadata usage
#################################################################
attr = PlaceholderAttribute(name="primvars:doNotCastShadows", prim=prim, metadata={})
# test stubs
self.assertFalse(attr.ValueMightBeTimeVarying())
self.assertFalse(attr.HasAuthoredConnections())
# test get functions
self.assertEqual(attr.Get(), None)
self.assertEqual(attr.GetPath(), "/Sphere")
self.assertEqual(attr.GetPrim(), prim)
self.assertEqual(attr.GetMetadata("customData"), False)
self.assertFalse(attr.GetMetadata("test"))
self.assertEqual(attr.GetAllMetadata(), {})
# test CreateAttribute
attr.CreateAttribute()
# verifty attribute doesn't exist
self.assertFalse(prim.GetAttribute("primvars:doNotCastShadows"))
#################################################################
# test no prim usage
#################################################################
attr = PlaceholderAttribute(name="primvars:doNotCastShadows", prim=None, metadata=attr_dict)
# test stubs
self.assertFalse(attr.ValueMightBeTimeVarying())
self.assertFalse(attr.HasAuthoredConnections())
# test get functions
self.assertTrue(attr.Get())
self.assertEqual(attr.GetPath(), None)
self.assertEqual(attr.GetPrim(), None)
self.assertEqual(attr.GetMetadata("customData"), attr_dict["customData"])
self.assertFalse(attr.GetMetadata("test"))
self.assertEqual(attr.GetAllMetadata(), attr_dict)
# test CreateAttribute
attr.CreateAttribute()
# verifty attribute doesn't exist
self.assertFalse(prim.GetAttribute("primvars:doNotCastShadows"))
#################################################################
# test no name
#################################################################
attr = PlaceholderAttribute(name="", prim=prim, metadata=attr_dict)
# test stubs
self.assertFalse(attr.ValueMightBeTimeVarying())
self.assertFalse(attr.HasAuthoredConnections())
# test get functions
self.assertTrue(attr.Get())
self.assertEqual(attr.GetPath(), "/Sphere")
self.assertEqual(attr.GetPrim(), prim)
self.assertEqual(attr.GetMetadata("customData"), attr_dict["customData"])
self.assertFalse(attr.GetMetadata("test"))
self.assertEqual(attr.GetAllMetadata(), attr_dict)
# test CreateAttribute
attr.CreateAttribute()
# verifty attribute doesn't exist
self.assertFalse(prim.GetAttribute("primvars:doNotCastShadows"))
| 4,689 | Python | 37.76033 | 100 | 0.587545 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_relationship.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
from omni.kit import ui_test
from pxr import Vt, Gf
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, wait_for_window, arrange_windows
class PrimRelationship(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows("Stage", 224)
await open_stage(get_test_data_path(__name__, "usd/relationship.usda"))
await self._open_raw_frame(False)
# After running each test
async def tearDown(self):
await self._open_raw_frame(True)
await wait_stage_loading()
async def _open_raw_frame(self, state):
await select_prims(['/World'])
frame = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Raw USD Properties'")
frame.widget.collapsed = state
async def handle_select_targets(self, prim_name):
from pxr import Sdf
# handle assign dialog
window_name = "Select Target(s)"
await wait_for_window(window_name)
# select prim
stage_widget = ui_test.find(f"{window_name}//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await stage_widget.find(f"**/StringField[*].model.path=='{prim_name}'").click()
await ui_test.human_delay()
# click add
await ui_test.find(f"{window_name}//Frame/**/Button[*].identifier=='add_button'").click()
await ui_test.human_delay(50)
async def test_l1_relationship(self):
def get_buttons():
buttons={}
frame = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Raw USD Properties'")
for widget in frame.find_all("**/Button[*]"):
buttons[widget.widget.identifier] = widget
return buttons
def remove_add_buttons():
buttons = get_buttons()
for w in buttons.copy():
if w.startswith("add_relationship_"):
del buttons[w]
return buttons
await ui_test.find("Property").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
# select relationship prim
await select_prims(['/World/Sphere_02'])
# Raw USD Properties as relationship attribute is not part of any schema
widgets = get_buttons()
await widgets["remove_relationship_World_Sphere_01"].click()
await ui_test.human_delay(50)
# verify only "add_relationship"
widgets = remove_add_buttons()
self.assertEqual(widgets, {})
# "add_relationship"
await get_buttons()["add_relationship_World_Sphere_02_Attr2"].click()
await self.handle_select_targets("/World/Sphere_01")
# "add_relationship"
await get_buttons()["add_relationship_World_Sphere_02_Attr2"].click()
await self.handle_select_targets("/World/Cube_01")
# "add_relationship"
await get_buttons()["add_relationship_World_Sphere_02_Attr2"].click()
await self.handle_select_targets("/World/Cube_02")
# verify
widgets = remove_add_buttons()
self.assertEqual(list(widgets.keys()), ['remove_relationship_World_Sphere_01', 'remove_relationship_World_Cube_01', 'remove_relationship_World_Cube_02'])
| 3,808 | Python | 36.712871 | 161 | 0.648372 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_property_bind_material_combo.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
from omni.kit import ui_test
from pxr import Sdf, UsdShade
from omni.kit.test_suite.helpers import (
open_stage,
get_test_data_path,
select_prims,
wait_stage_loading,
arrange_windows
)
class PropertyBindMaterialCombo(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows("Stage", 64)
await open_stage(get_test_data_path(__name__, "usd/bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_l1_property_bind_material_combo(self):
await ui_test.find("Content").focus()
stage_window = ui_test.find("Stage")
await stage_window.focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
to_select = ["/World/Cube", "/World/Cone", "/World/Sphere", "/World/Cylinder"]
await wait_stage_loading()
await select_prims(to_select)
await ui_test.human_delay()
bound_materials = ["None", "/World/Looks/OmniGlass", "/World/Looks/OmniPBR", "/World/Looks/OmniSurface_Plastic"]
for index in range(0, 4):
# show combobox
# NOTE: delay of 4 as that opens a new popup window
topmost_button = sorted(ui_test.find_all("Property//Frame/**/Button[*].identifier=='combo_open_button'"), key=lambda f: f.position.y)[0]
await topmost_button.click(human_delay_speed=4)
# activate menu item
await ui_test.find(f"MaterialPropertyPopupWindow//Frame/**/Label[*].text=='{bound_materials[index]}'").click()
# wait for material to load & UI to refresh
await wait_stage_loading()
# verify
for prim_path in to_select:
prim = stage.GetPrimAtPath(prim_path)
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
if bound_materials[index] != "None":
self.assertTrue(bound_material.GetPrim().IsValid() == True)
self.assertTrue(bound_material.GetPrim().GetPrimPath().pathString == bound_materials[index])
else:
self.assertTrue(bound_material.GetPrim().IsValid() == False)
| 2,812 | Python | 38.069444 | 148 | 0.64936 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/hard_softrange_ui.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 sys
import math
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
class HardSoftRangeUI(AsyncTestCase):
# Before running each test
async def setUp(self):
from omni.kit import ui_test
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, arrange_windows
await arrange_windows("Stage", 64, 800)
await open_stage(get_test_data_path(__name__, "usd/soft_range.usda"))
await ui_test.find("Property").focus()
# After running each test
async def tearDown(self):
from omni.kit import ui_test
from omni.kit.test_suite.helpers import select_prims, wait_stage_loading
# de-select prims to prevent _delayed_dirty_handler exception
await select_prims([])
await wait_stage_loading()
async def _hide_frames(self, show_list):
from omni.kit import ui_test
for w in ui_test.find_all("Property//Frame/**/CollapsableFrame[*]"):
if show_list == None:
w.widget.collapsed = False
elif w.widget.title in show_list:
w.widget.collapsed = False
else:
w.widget.collapsed = True
await ui_test.human_delay()
async def test_hard_softrange_float_ui(self):
from omni.kit import ui_test
from omni.kit.test_suite.helpers import select_prims, wait_stage_loading
def verify_values(widget_name: str, expected_value, model_soft_min, model_soft_max, hard_min, hard_max):
for widget in ui_test.find_all(f"Property//Frame/**/.identifier=='{widget_name}'"):
self.assertAlmostEqual(widget.model.get_value(), expected_value)
if model_soft_min != None:
self.assertAlmostEqual(widget.model._soft_range_min, model_soft_min)
if model_soft_max != None:
self.assertAlmostEqual(widget.model._soft_range_max, model_soft_max)
self.assertAlmostEqual(widget.widget.min, hard_min)
self.assertAlmostEqual(widget.widget.max, hard_max)
# select prim
await select_prims(["/World/Looks/OmniGlass/Shader"])
# wait for material to load & UI to refresh
await wait_stage_loading()
# test hard range 0-1000 & soft range 0-1 inputs:depth
await self._hide_frames(["Shader", "Color"])
# check default values
verify_values("float_slider_inputs:depth",
expected_value=0.001,
model_soft_min=None,
model_soft_max=None,
hard_min=0,
hard_max=1)
# something not right here, accuracy of 0.2 ?
# change values
await ui_test.find(f"Property//Frame/**/.identifier=='float_slider_inputs:depth'").input("1500")
# verify changed value
verify_values("float_slider_inputs:depth",
expected_value=1000,
model_soft_min=0,
model_soft_max=1000,
hard_min=0,
hard_max=1000)
# change values
await ui_test.find(f"Property//Frame/**/.identifier=='float_slider_inputs:depth'").input("-150")
# verify changed value
verify_values("float_slider_inputs:depth",
expected_value=0,
model_soft_min=0,
model_soft_max=1000,
hard_min=0,
hard_max=1000)
# change values
await ui_test.find(f"Property//Frame/**/.identifier=='float_slider_inputs:depth'").input("500")
# verify changed value
verify_values("float_slider_inputs:depth",
expected_value=500,
model_soft_min=0,
model_soft_max=1000,
hard_min=0,
hard_max=1000)
# change values
await ui_test.find(f"Property//Frame/**/.identifier=='float_slider_inputs:depth'").input("0")
# verify changed value
verify_values("float_slider_inputs:depth",
0,
model_soft_min=0,
model_soft_max=1000,
hard_min=0,
hard_max=1000)
# click reset
await ui_test.find(f"Property//Frame/**/ImageWithProvider[*].identifier=='control_state_inputs:depth'").click()
# verify
verify_values("float_slider_inputs:depth",
expected_value=0.001,
model_soft_min=None,
model_soft_max=None,
hard_min=0,
hard_max=1)
| 5,215 | Python | 37.352941 | 119 | 0.574305 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_path_menu.py | import carb
import unittest
import omni.kit.test
class TestPathMenu(omni.kit.test.AsyncTestCase):
async def setUp(self):
from omni.kit.test_suite.helpers import arrange_windows
await arrange_windows()
async def tearDown(self):
pass
async def test_path_menu(self):
from omni.kit import ui_test
from omni.kit.property.usd import PrimPathWidget
from omni.kit.property.usd.prim_selection_payload import PrimSelectionPayload
from omni.kit.test_suite.helpers import open_stage, wait_stage_loading, select_prims, get_test_data_path, get_prims
test_path_fn_clicked = False
menu_path = "PxrHydraEngine/does/not/support/divergent/render/and/simulation/times"
# setup path button
def test_path_fn(payload: PrimSelectionPayload):
nonlocal test_path_fn_clicked
test_path_fn_clicked = True
self._button_menu_entry = PrimPathWidget.add_button_menu_entry(
menu_path,
onclick_fn=test_path_fn,
)
# load stage
await open_stage(get_test_data_path(__name__, "usd/cube.usda"))
stage = omni.usd.get_context().get_stage()
await select_prims(["/Xform/Cube"])
# test "+add" menu
test_path_fn_clicked = False
for widget in ui_test.find_all("Property//Frame/**/Button[*]"):
if widget.widget.text.endswith(" Add"):
await widget.click()
await ui_test.human_delay()
await ui_test.select_context_menu(menu_path, offset=ui_test.Vec2(10, 10))
#verify clicked
self.assertTrue(test_path_fn_clicked)
# test stage window context menu
test_path_fn_clicked = False
# right click on Cube
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await stage_widget.find(f"**/StringField[*].model.path=='/Xform/Cube'").right_click()
await ui_test.human_delay()
# click on context menu item
await ui_test.select_context_menu(f"Add/{menu_path}", offset=ui_test.Vec2(10, 10))
#verify clicked
self.assertTrue(test_path_fn_clicked)
| 2,217 | Python | 34.774193 | 123 | 0.628327 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_path_add_menu.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 os
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
from omni.kit import ui_test
from pxr import Gf
from omni.kit.test_suite.helpers import (
open_stage,
get_test_data_path,
select_prims,
wait_stage_loading,
wait_for_window,
arrange_windows
)
class PropertyPathAddMenu(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows("Stage", 64)
await open_stage(get_test_data_path(__name__, "usd/bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_property_path_add(self):
await ui_test.find("Content").focus()
stage_window = ui_test.find("Stage")
await stage_window.focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
await wait_stage_loading()
# select cone
await select_prims(["/World/Cone"])
await ui_test.human_delay()
# click "Add"
add_widget = [w for w in ui_test.find_all("Property//Frame/**/Button[*].identifier==''") if w.widget.text.endswith("Add")][0]
await add_widget.click()
# select Attribute from menu
await ui_test.select_context_menu("Attribute", offset=ui_test.Vec2(10, 10))
# use "Add Attribute..." window
await wait_for_window("Add Attribute...")
# select settings in window
for w in ui_test.find_all("Add Attribute...//Frame/**"):
if isinstance(w.widget, omni.ui.StringField):
await w.input("MyTestAttribute")
elif isinstance(w.widget, omni.ui.ComboBox):
items = w.widget.model.get_item_children(None)
if len(items) == 2:
w.widget.model.get_item_value_model(None, 0).set_value(1)
else:
bool_index = [index for index, i in enumerate(w.widget.model.get_item_children(None))if i.value_type_name == "bool" if i.value_type_name == "bool"][0]
w.widget.model.get_item_value_model(None, 0).set_value(bool_index)
# click "Add"
await ui_test.find("Add Attribute...//Frame/**/Button[*].text=='Add'").click()
await ui_test.human_delay()
# verify attribute correct type
attr = stage.GetPrimAtPath("/World/Cone").GetAttribute("MyTestAttribute")
self.assertEqual(attr.GetTypeName().cppTypeName, "bool")
| 2,933 | Python | 36.615384 | 170 | 0.640641 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_material_widget_refresh_on_binding.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import omni.kit.app
import omni.usd
import omni.kit.commands
import omni.kit.undo
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from pxr import Sdf, UsdShade
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows
class MaterialWidgetRefreshOnBinding(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
await open_stage(get_test_data_path(__name__, "usd/bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_l1_material_widget_refresh_on_binding(self):
widget_name = "Property//Frame/**/StringField[*].identifier=='combo_drop_target'"
to_select = "/World/Cylinder"
# property window to front
await ui_test.find("Property").focus()
# select prim
await select_prims([to_select])
# wait for material to load & UI to refresh
await wait_stage_loading()
# verify property_widget is correct
self.assertTrue(ui_test.find(widget_name).model.get_value_as_string() == "/World/Looks/OmniPBR")
# change material binding
omni.kit.commands.execute("BindMaterialCommand", prim_path=to_select, material_path="/World/Looks/OmniGlass", strength=None)
# wait for material to load & UI to refresh
await wait_stage_loading()
# verify widget has been refreshed
self.assertTrue(ui_test.find(widget_name).model.get_value_as_string() == "/World/Looks/OmniGlass")
# change material binding back
omni.kit.undo.undo()
# wait for material to load & UI to refresh
await wait_stage_loading()
# verify widget has been refreshed
self.assertTrue(ui_test.find(widget_name).model.get_value_as_string() == "/World/Looks/OmniPBR")
| 2,376 | Python | 36.140624 | 132 | 0.700337 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_drag_drop_material_property_combobox.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.app
import omni.usd
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from pxr import UsdShade
from omni.kit.material.library.test_helper import MaterialLibraryTestHelper
from omni.kit.test_suite.helpers import (
open_stage,
get_test_data_path,
select_prims,
wait_stage_loading,
delete_prim_path_children,
arrange_windows
)
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
class DragDropMaterialPropertyComboBox(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows("Stage", 64)
await open_stage(get_test_data_path(__name__, "usd/bound_shapes.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
def _verify_material(self, stage, mtl_name, to_select):
# verify material created
prim_paths = [p.GetPrimPath().pathString for p in stage.Traverse()]
self.assertTrue(f"/World/Looks/{mtl_name}" in prim_paths)
self.assertTrue(f"/World/Looks/{mtl_name}/Shader" in prim_paths)
# verify bound material
if to_select:
for prim_path in to_select:
prim = stage.GetPrimAtPath(prim_path)
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
self.assertTrue(bound_material.GetPrim().IsValid() == True)
self.assertTrue(bound_material.GetPrim().GetPrimPath().pathString == f"/World/Looks/{mtl_name}")
async def test_l2_drag_drop_material_property_combobox(self):
await ui_test.find("Content").focus()
await ui_test.find("Stage").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
to_select = "/World/Cylinder"
# select prim
await select_prims([to_select])
# wait for material to load & UI to refresh
await wait_stage_loading()
# drag to bottom of stage window
# NOTE: Material binding is done on selected prim
mdl_list = await omni.kit.material.library.get_mdl_list_async()
property_widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='combo_drop_target'")
drag_target = property_widget.center
async with ContentBrowserTestHelper() as content_browser_helper:
for mtl_name, mdl_path, submenu in mdl_list:
await delete_prim_path_children("/World/Looks")
await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target)
# use create materialdialog
async with MaterialLibraryTestHelper() as material_test_helper:
await material_test_helper.handle_create_material_dialog(mdl_path, mtl_name)
# wait for material to load & UI to refresh
await wait_stage_loading()
# verify
self._verify_material(stage, mtl_name, [to_select])
| 3,517 | Python | 39.436781 | 116 | 0.66079 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_usd_preferences.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import carb
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
from omni.kit import ui_test
from pxr import Vt, Gf
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, wait_for_window, arrange_windows
PERSISTENT_SETTINGS_PREFIX = "/persistent"
class TestUsdPreferences(AsyncTestCase):
def set_defaults():
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.usd/large_selection", 100)
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.usd/raw_widget_multi_selection_limit", 1)
# Before running each test
async def setUp(self):
await arrange_windows()
TestUsdPreferences.set_defaults()
# After running each test
async def tearDown(self):
TestUsdPreferences.set_defaults()
async def test_l1_usd_preferences_test(self):
omni.kit.window.preferences.show_preferences_window()
await ui_test.human_delay(50)
for page in omni.kit.window.preferences.get_page_list():
if page.get_title() == "Property Widgets":
omni.kit.window.preferences.select_page(page)
await ui_test.human_delay(50)
frame = ui_test.find("Preferences//Frame/**/CollapsableFrame[*].identifier=='preferences_builder_Property Window'")
w = frame.find("**/IntDrag[*].identifier=='large_selection'")
await w.click(double=True)
await w.input("10")
w = frame.find("**/IntDrag[*].identifier=='raw_widget_multi_selection_limit'")
await w.click(double=True)
await w.input("20")
await ui_test.human_delay(50)
self.assertEqual(carb.settings.get_settings().get(PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.usd/large_selection"), 10)
self.assertEqual(carb.settings.get_settings().get(PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.usd/raw_widget_multi_selection_limit"), 20)
return
self.assertTrue(False, "Property Widgets preferences page not found")
| 2,655 | Python | 41.15873 | 163 | 0.684369 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_shader_goto_UDIM_material_property.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
from pxr import Sdf, UsdShade
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows
from omni.kit.window.content_browser import get_content_window
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
from omni.kit.window.file_importer.test_helper import FileImporterTestHelper
from omni.kit import ui_test
class ShaderGotoUDIMMaterialProperty(AsyncTestCase):
# Before running each test
async def setUp(self):
async with ContentBrowserTestHelper() as content_browser_helper:
await content_browser_helper.set_config_menu_settings({'hide_unknown': True, 'hide_thumbnails': True, 'show_details': False, 'show_udim_sequence': True})
await arrange_windows("Stage", 128)
await open_stage(get_test_data_path(__name__, "usd/locate_file_UDIM_material.usda"))
# After running each test
async def tearDown(self):
from omni.kit.test_suite.helpers import wait_stage_loading
await wait_stage_loading()
async def test_l1_shader_goto_UDIM_material_property(self):
await ui_test.find("Content").focus()
stage_window = ui_test.find("Stage")
await stage_window.focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
await select_prims(["/World/Looks/OmniPBR/Shader"])
await wait_stage_loading()
# verify corrent prim is selected
content_browser = get_content_window()
for material_attr, enabled, expected in [
("sdf_locate_asset_inputs:ao_texture", False, []), # ""
("sdf_locate_asset_inputs:diffuse_texture", True, ["T_Hood_A1_Albedo.<UDIM>.png"]), # T_Hood_A1_1001_Albedo.png
("sdf_locate_asset_inputs:emissive_mask_texture", True, ["T_Hood_A1_Emissive.<UDIM>.png"]), # granite_a_mask.png
("sdf_locate_asset_inputs:opacity_texture", False, []), # http
("sdf_locate_asset_inputs:reflectionroughness_texture", True, [])]: # test
content_browser.navigate_to(get_test_data_path(__name__, ""))
widget = ui_test.find(f"Property//Frame/**/Button[*].identifier=='{material_attr}'")
self.assertEqual(widget.widget.visible, enabled)
if enabled:
widget.widget.scroll_here_y(0.0)
await ui_test.human_delay(10)
await widget.click()
await ui_test.human_delay(10)
selected = [os.path.basename(path) for path in content_browser.get_current_selections()]
self.assertEqual(selected, expected)
async def test_l1_shader_change_UDIM_material_property(self):
await ui_test.find("Content").focus()
stage_window = ui_test.find("Stage")
await stage_window.focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
await select_prims(["/World/Looks/OmniPBR/Shader"])
await wait_stage_loading()
# verfiy prim asset
prim = stage.GetPrimAtPath("/World/Looks/OmniPBR/Shader")
attr = prim.GetAttribute("inputs:diffuse_texture")
self.assertTrue(attr.Get().resolvedPath.replace("\\", "/").endswith("omni.kit.property.usd/data/tests/usd/textures/T_Hood_A1_Albedo.<UDIM>.png"))
# change prim asset
content_browser = get_content_window()
content_browser.navigate_to(get_test_data_path(__name__, ""))
widget = ui_test.find(f"Property//Frame/**/Button[*].identifier=='sdf_browse_asset_inputs:diffuse_texture'")
await widget.click()
await ui_test.human_delay(50)
#grid_view = ui_test.find("Select Asset...//Frame/**/VGrid[*].identifier=='file_importer_grid_view'")
#await grid_view.find(f"**/Label[*].text=='granite_a_mask2.png'").click(double=True)
url = omni.usd.correct_filename_case(get_test_data_path(__name__, "usd/textures/").replace("\\", "/")) + "/"
async with FileImporterTestHelper() as file_import_helper:
await file_import_helper.select_items_async(url, names=["granite_a_mask2.png"])
await file_import_helper.click_apply_async(filename_url="granite_a_mask2.png")
await ui_test.human_delay(4)
# verfiy prim asset
self.assertTrue(attr.Get().resolvedPath.replace("\\", "/").endswith("omni.kit.property.usd/data/tests/usd/textures/granite_a_mask2.png"))
| 5,222 | Python | 51.229999 | 165 | 0.635963 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_shader_drag_drop_mdl.py | import omni.kit.test
import omni.kit.ui_test as ui_test
from pathlib import Path
from omni.ui.tests.test_base import OmniUiTest
from omni.kit.test_suite.helpers import open_stage, wait_stage_loading, get_test_data_path, select_prims, arrange_windows
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
class TestDragDropFileToMaterial(OmniUiTest):
# Before running each test
async def setUp(self):
await arrange_windows("Stage", 200)
await open_stage(get_test_data_path(__name__, "usd/locate_file_material.usda"))
await wait_stage_loading()
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_drag_drop_single_mdl_asset_path(self):
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
await select_prims(["/World/Looks/OmniPBR/Shader"])
await wait_stage_loading()
# verify material is correct
shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath("/World/Looks/OmniPBR"))
asset = shader.GetSourceAsset("mdl")
self.assertTrue(shader.GetPrim().IsValid())
self.assertEqual(asset.path, "OmniPBR.mdl")
# drag file from content window
property_widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='sdf_asset_info:mdl:sourceAsset'")
drag_target = property_widget.center
async with ContentBrowserTestHelper() as content_browser_helper:
usd_path = get_test_data_path(__name__, "usd/TESTEXPORT.mdl")
await content_browser_helper.drag_and_drop_tree_view(usd_path, drag_target=drag_target)
# verify asset
shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath("/World/Looks/OmniPBR"))
asset = shader.GetSourceAsset("mdl")
self.assertTrue(shader.GetPrim().IsValid())
self.assertTrue(asset.path.endswith("/TESTEXPORT.mdl"))
async def test_drag_drop_single_png_asset_path(self):
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
await select_prims(["/World/Looks/OmniPBR/Shader"])
await wait_stage_loading()
# verify material is correct
shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath("/World/Looks/OmniPBR"))
asset = shader.GetSourceAsset("mdl")
self.assertTrue(shader.GetPrim().IsValid())
self.assertEqual(asset.path, "OmniPBR.mdl")
# drag file from content window
property_widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='sdf_asset_inputs:ao_texture'")
drag_target = property_widget.center
async with ContentBrowserTestHelper() as content_browser_helper:
usd_path = get_test_data_path(__name__, "usd/textures/granite_a_mask.png")
await content_browser_helper.drag_and_drop_tree_view(usd_path, drag_target=drag_target)
# verify asset
prim = omni.usd.get_shader_from_material(stage.GetPrimAtPath("/World/Looks/OmniPBR"), True)
asset_path = prim.GetAttribute("inputs:ao_texture").Get()
self.assertTrue(prim.IsValid())
self.assertTrue(asset_path.path.endswith("textures/granite_a_mask.png"))
async def test_drag_drop_multi_mdl_asset_path(self):
# Test that dropping multiple material files results in no changes
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
await select_prims(["/World/Looks/OmniPBR/Shader"])
await wait_stage_loading()
# verify material is correct
shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath("/World/Looks/OmniPBR"))
asset = shader.GetSourceAsset("mdl")
self.assertTrue(shader.GetPrim().IsValid())
self.assertEqual(asset.path, "OmniPBR.mdl")
# drag file from content window
property_widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='sdf_asset_info:mdl:sourceAsset'")
drag_target = property_widget.center
async with ContentBrowserTestHelper() as content_browser_helper:
usd_path = get_test_data_path(__name__, "usd")
await content_browser_helper.drag_and_drop_tree_view(
usd_path, names=["TESTEXPORT.mdl", "TESTEXPORT2.mdl"], drag_target=drag_target)
# verify material not changed
shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath("/World/Looks/OmniPBR"))
asset = shader.GetSourceAsset("mdl")
self.assertTrue(shader.GetPrim().IsValid())
self.assertEqual(asset.path, "OmniPBR.mdl")
async def test_drag_drop_multi_png_asset_path(self):
# Test that dropping multiple texture files results in no changes.
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
await select_prims(["/World/Looks/OmniPBR/Shader"])
await wait_stage_loading()
# verify material is correct
shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath("/World/Looks/OmniPBR"))
asset = shader.GetSourceAsset("mdl")
self.assertTrue(shader.GetPrim().IsValid())
self.assertEqual(asset.path, "OmniPBR.mdl")
# drag file from content window
property_widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='sdf_asset_inputs:ao_texture'")
drag_target = property_widget.center
async with ContentBrowserTestHelper() as content_browser_helper:
usd_path = get_test_data_path(__name__, "usd/textures")
await content_browser_helper.drag_and_drop_tree_view(
usd_path, names=["granite_a_mask.png", "granite_a_mask2.png"], drag_target=drag_target)
# verify asset
prim = omni.usd.get_shader_from_material(stage.GetPrimAtPath("/World/Looks/OmniPBR"), True)
asset_path = prim.GetAttribute("inputs:ao_texture").Get()
self.assertTrue(prim.IsValid())
self.assertEqual(asset_path.path, "")
| 6,031 | Python | 44.696969 | 121 | 0.668048 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_shader_goto_material_property.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
from pxr import Sdf, UsdShade
class ShaderGotoMaterialProperty(AsyncTestCase):
# Before running each test
async def setUp(self):
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, arrange_windows
await arrange_windows("Stage", 128)
await open_stage(get_test_data_path(__name__, "usd/locate_file_material.usda"))
# After running each test
async def tearDown(self):
from omni.kit.test_suite.helpers import wait_stage_loading
await wait_stage_loading()
async def test_l1_shader_goto_material_property(self):
from omni.kit import ui_test
from omni.kit.test_suite.helpers import get_test_data_path, select_prims, wait_stage_loading
from omni.kit.window.content_browser import get_content_window
await ui_test.find("Content").focus()
stage_window = ui_test.find("Stage")
await stage_window.focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
await select_prims(["/World/Looks/OmniPBR/Shader"])
await wait_stage_loading()
# verify corrent prim is selected
content_browser = get_content_window()
for material_attr, enabled, expected in [
("sdf_locate_asset_inputs:ao_texture", False, []), # ""
("sdf_locate_asset_inputs:diffuse_texture", True, ["granite_a_mask.png"]), # granite_a_mask.png
("sdf_locate_asset_inputs:emissive_mask_texture", True, ["granite_a_mask.png"]), # granite_a_mask.png
("sdf_locate_asset_inputs:opacity_texture", False, []), # http
("sdf_locate_asset_inputs:reflectionroughness_texture", True, [])]: # test
content_browser.navigate_to(get_test_data_path(__name__, ""))
widget = ui_test.find(f"Property//Frame/**/Button[*].identifier=='{material_attr}'")
self.assertEqual(widget.widget.visible, enabled)
if enabled:
widget.widget.scroll_here_y(0.0)
await ui_test.human_delay(10)
await widget.click()
await ui_test.human_delay(10)
selected = [os.path.basename(path) for path in content_browser.get_current_selections()]
self.assertEqual(selected, expected)
| 3,081 | Python | 47.156249 | 148 | 0.610191 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_references.py | import carb
import omni.kit.ui_test as ui_test
import omni.usd
from pathlib import Path
from pxr import Sdf, UsdShade, UsdGeom
from omni.ui.tests.test_base import OmniUiTest
from omni.kit.test_suite.helpers import open_stage, wait_stage_loading, get_test_data_path, select_prims, arrange_windows
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
class TestDragDropFileToReference(OmniUiTest):
# Before running each test
async def setUp(self):
carb.settings.get_settings().set("/persistent/app/stage/dragDropImport", "reference")
await arrange_windows("Stage", 200)
await open_stage(get_test_data_path(__name__, "usd/reference_prim.usda"))
await wait_stage_loading()
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_drag_drop_single_usda_to_reference(self):
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
await select_prims(["/World/XformReference"])
await wait_stage_loading()
# verify refs are correct
prim = stage.GetPrimAtPath("/World/XformReference")
ref_and_layers = omni.usd.get_composed_references_from_prim(prim)
self.assertEqual(len(ref_and_layers), 1)
self.assertEqual(ref_and_layers[0][0], Sdf.Reference("./cube.usda"))
# drag from content window and drop into reference path
for w in ui_test.find_all("Property//Frame/**/StringField[*]"):
if w.widget.has_drop_fn() and w.model.get_value_as_string() == "./cube.usda":
drag_target = w.center
break
async with ContentBrowserTestHelper() as content_browser_helper:
usd_path = get_test_data_path(__name__, "usd/sphere.usda")
await content_browser_helper.drag_and_drop_tree_view(usd_path, drag_target=drag_target)
# verify refs are correct
prim = stage.GetPrimAtPath("/World/XformReference")
ref_and_layers = omni.usd.get_composed_references_from_prim(prim)
self.assertEqual(len(ref_and_layers), 1)
self.assertEqual(ref_and_layers[0][0], Sdf.Reference("./sphere.usda"))
async def test_drag_drop_multi_usda_to_reference(self):
# Test that dropping multiple usd files results in no changes.
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
await select_prims(["/World/XformReference"])
await wait_stage_loading()
# verify refs are correct
prim = stage.GetPrimAtPath("/World/XformReference")
ref_and_layers = omni.usd.get_composed_references_from_prim(prim)
self.assertEqual(len(ref_and_layers), 1)
self.assertEqual(ref_and_layers[0][0], Sdf.Reference("./cube.usda"))
# drag from content window and drop into reference path
for w in ui_test.find_all("Property//Frame/**/StringField[*]"):
if w.widget.has_drop_fn() and w.model.get_value_as_string() == "./cube.usda":
drag_target = w.center
break
async with ContentBrowserTestHelper() as content_browser_helper:
usd_path = get_test_data_path(__name__, "usd")
await content_browser_helper.drag_and_drop_tree_view(
usd_path, names=["sphere.usda", "locate_file_material.usda"], drag_target=drag_target)
# verify refs are correct
prim = stage.GetPrimAtPath("/World/XformReference")
ref_and_layers = omni.usd.get_composed_references_from_prim(prim)
self.assertEqual(len(ref_and_layers), 1)
self.assertEqual(ref_and_layers[0][0], Sdf.Reference("./cube.usda"))
| 3,684 | Python | 43.939024 | 121 | 0.657709 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_bool_arrays.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
import omni.kit.undo
from omni.ui.tests.test_base import OmniUiTest
from pxr import Kind, Sdf, Gf
from omni.kit import ui_test
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, wait_stage_loading, select_prims, arrange_windows
class TestBoolType(OmniUiTest):
def __init__(self, tests=()):
super().__init__(tests)
# Before running each test
async def setUp(self):
await arrange_windows(topleft_window="Property", topleft_height=256, topleft_width=800.0)
await open_stage(get_test_data_path(__name__, "usd/bools.usda"))
await self._show_raw(False)
# After running each test
async def tearDown(self):
await wait_stage_loading()
await self._show_raw(True)
async def _show_raw(self, new_state):
await select_prims(["/defaultPrim/in_0"])
for w in ui_test.find_all("Property//Frame/**/CollapsableFrame[*]"):
if w.widget.title == "Raw USD Properties":
w.widget.collapsed = new_state
# change prim selection immediately after collapsed state change can result in one bad frame
# i.e. selection change event happens before frame UI rebuild, and old widget models are already destroyed.
await ui_test.human_delay()
await select_prims([])
async def test_l1_bool_test(self):
# setup
await wait_stage_loading()
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath('/World/Looks/bool_types/Shader')
await select_prims(["/World/Looks/bool_types/Shader"])
await ui_test.human_delay()
# test bool checkbox
attr = prim.GetAttribute("inputs:MyBool")
self.assertTrue(attr.Get())
await ui_test.find("Property//Frame/**/.identifier=='bool_inputs:MyBool'").click()
self.assertFalse(attr.Get())
await ui_test.find("Property//Frame/**/.identifier=='control_state_inputs:MyBool'").click()
self.assertTrue(attr.Get())
# test bool vec2 checkboxes
attr = prim.GetAttribute("inputs:MyBool2")
self.assertEqual(attr.Get(), (0, 0))
widget = ui_test.find("Property//Frame/**/.identifier=='boolean_per_channel_inputs:MyBool2'")
for index, expected in enumerate([(0, 0), (0, 1), (1, 0), (1, 1)]):
checkwidgets = widget.find_all("**/CheckBox[*]")
if index & 1:
await checkwidgets[1].click()
if index & 2:
await checkwidgets[0].click()
self.assertEqual(attr.Get(), expected)
await ui_test.find("Property//Frame/**/.identifier=='control_state_inputs:MyBool2'").click()
self.assertEqual(attr.Get(), (0, 0))
omni.kit.undo.undo()
self.assertEqual(attr.Get(), expected)
omni.kit.undo.redo()
self.assertEqual(attr.Get(), (0, 0))
# test bool vec3 checkboxes
attr = prim.GetAttribute("inputs:MyBool3")
self.assertEqual(attr.Get(), (0, 0, 0))
widget = ui_test.find("Property//Frame/**/.identifier=='boolean_per_channel_inputs:MyBool3'")
for index, expected in enumerate([(0, 0, 0),
(0, 0, 1),
(0, 1, 0),
(0, 1, 1),
(1, 0, 0),
(1, 0, 1),
(1, 1, 0),
(1, 1, 1)]):
checkwidgets = widget.find_all("**/CheckBox[*]")
if index & 1:
await checkwidgets[2].click()
if index & 2:
await checkwidgets[1].click()
if index & 4:
await checkwidgets[0].click()
self.assertEqual(attr.Get(), expected)
await ui_test.find("Property//Frame/**/.identifier=='control_state_inputs:MyBool3'").click()
self.assertEqual(attr.Get(), (0, 0, 0))
omni.kit.undo.undo()
self.assertEqual(attr.Get(), expected)
omni.kit.undo.redo()
self.assertEqual(attr.Get(), (0, 0, 0))
# test bool vec4 checkboxes
attr = prim.GetAttribute("inputs:MyBool4")
self.assertEqual(attr.Get(), (0, 0, 0, 0))
widget = ui_test.find("Property//Frame/**/.identifier=='boolean_per_channel_inputs:MyBool4'")
for index, expected in enumerate([(0, 0, 0, 0),
(0, 0, 0, 1),
(0, 0, 1, 0),
(0, 0, 1, 1),
(0, 1, 0, 0),
(0, 1, 0, 1),
(0, 1, 1, 0),
(0, 1, 1, 1),
(1, 0, 0, 0),
(1, 0, 0, 1),
(1, 0, 1, 0),
(1, 0, 1, 1),
(1, 1, 0, 0),
(1, 1, 0, 1),
(1, 1, 1, 0),
(1, 1, 1, 1)]):
checkwidgets = widget.find_all("**/CheckBox[*]")
if index & 1:
await checkwidgets[3].click()
if index & 2:
await checkwidgets[2].click()
if index & 4:
await checkwidgets[1].click()
if index & 8:
await checkwidgets[0].click()
self.assertEqual(attr.Get(), expected)
await ui_test.find("Property//Frame/**/.identifier=='control_state_inputs:MyBool4'").click()
self.assertEqual(attr.Get(), (0, 0, 0, 0))
omni.kit.undo.undo()
self.assertEqual(attr.Get(), expected)
omni.kit.undo.redo()
self.assertEqual(attr.Get(), (0, 0, 0, 0))
| 6,594 | Python | 44.482758 | 121 | 0.506976 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_variant.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
from omni.kit import ui_test
from pxr import Vt, Gf
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows
class PrimVariantColorProperty(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
await open_stage(get_test_data_path(__name__, "usd_variants/variant.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_l1_shader_material_subid_property(self):
import omni.kit.commands
await ui_test.find("Property").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
# select variant prim
await select_prims(['/World'])
await ui_test.human_delay()
# verify displayColor is red
prim = stage.GetPrimAtPath('/World/Sphere')
attr = prim.GetAttribute('primvars:displayColor')
self.assertEqual(attr.Get(), Vt.Vec3fArray(1, (Gf.Vec3f(1.0, 0.0, 0.0))))
# change variant to blue
variant_widget = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Variants'")
combo_widget = variant_widget.find("Property//Frame/**/ComboBox[*]")
combo_widget.model.set_value("blue")
await ui_test.human_delay(100)
# verify displayColor is blue
self.assertEqual(attr.Get(), Vt.Vec3fArray(1, (Gf.Vec3f(0.0, 0.0, 1.0))))
# NOTE: previous set_value will have refreshed property widget, so old values are not valid
# change variant to red
variant_widget = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Variants'")
combo_widget = variant_widget.find("Property//Frame/**/ComboBox[*]")
combo_widget.model.set_value("red")
await ui_test.human_delay(100)
# verify displayColor is red
self.assertEqual(attr.Get(), Vt.Vec3fArray(1, (Gf.Vec3f(1.0, 0.0, 0.0))))
| 2,521 | Python | 37.799999 | 121 | 0.679889 |
omniverse-code/kit/exts/omni.kit.property.usd/omni/kit/property/usd/tests/test_asset_array_widget.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from pathlib import Path
from typing import List
import carb.input
import carb.settings
import omni.kit.app
import omni.kit.test
import omni.kit.ui_test as ui_test
import omni.kit.undo
import omni.usd
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
from omni.kit.test_suite.helpers import arrange_windows
from omni.kit.window.file_importer.test_helper import FileImporterTestHelper
TEST_DATA_PATH = Path(
f"{omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)}/data/tests"
)
ASSIGN_PATH_SETTINGS = "/persistent/app/material/dragDropMaterialPath"
ADD_ASSET_BUTTON_QUERY = "Property//Frame/**/Button[*].identifier=='sdf_asset_array_asset_array.add_asset'"
class TestAssetArray(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._context = omni.usd.get_context()
self._settings = carb.settings.get_settings()
self._prev_path_setting = self._settings.get(ASSIGN_PATH_SETTINGS)
self._settings.set(ASSIGN_PATH_SETTINGS, "relative")
await arrange_windows("Stage", 1)
async with ContentBrowserTestHelper() as content_browser_helper:
await content_browser_helper.set_config_menu_settings({'hide_unknown': False, 'hide_thumbnails': True, 'show_details': False, 'show_udim_sequence': False})
async def tearDown(self):
self._settings.set(ASSIGN_PATH_SETTINGS, self._prev_path_setting)
async def _add_asset(self, asset_names: List[str]):
await self._browse_and_select_asset(ADD_ASSET_BUTTON_QUERY, asset_names)
async def _browse_and_select_asset(self, browse_button_identifier: str, asset_names: List[str]):
browse_button = ui_test.find(browse_button_identifier)
await browse_button.click()
async with FileImporterTestHelper() as file_importer:
await file_importer.wait_for_popup()
dir_url = TEST_DATA_PATH.absolute().resolve().joinpath("usd").joinpath("asset_array")
await file_importer.select_items_async(str(dir_url), asset_names)
await file_importer.click_apply_async(filename_url=None)
async def test_asset_array_widget(self):
usd_path = TEST_DATA_PATH.absolute().resolve().joinpath("usd").joinpath("asset_array").joinpath("main.usda")
success, error = await self._context.open_stage_async(str(usd_path))
self.assertTrue(success, error)
self._context.get_selection().set_selected_prim_paths(["/Test"], True)
asset_array_attr = self._context.get_stage().GetAttributeAtPath("/Test.asset_array")
await ui_test.human_delay()
# Expand Raw USD Properties section
raw_properties_frame = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Raw USD Properties'")
raw_properties_frame.widget.collapsed = False
await ui_test.human_delay()
# Add first asset
await self._add_asset(["dummy0.txt"])
await ui_test.human_delay()
self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt"])
# Add second asset
await self._add_asset(["dummy1.txt"])
await ui_test.human_delay()
self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt", "./dummy1.txt"])
# Reorder assets
reorder_grab = ui_test.find(
"Property//Frame/**/HStack[*].identifier=='sdf_asset_array_asset_array[0].reorder_grab'"
)
reorder_target_grab = ui_test.find(
"Property//Frame/**/HStack[*].identifier=='sdf_asset_array_asset_array[1].reorder_grab'"
)
drag_target = reorder_target_grab.position + reorder_target_grab.size
await reorder_grab.drag_and_drop(drag_target)
self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy1.txt", "./dummy0.txt"])
# Clear the first asset
clear_asset = ui_test.find("Property//Frame/**/Button[*].identifier=='sdf_clear_asset_asset_array[0]'")
await clear_asset.click()
self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["", "./dummy0.txt"])
# Readd the first asset from file picker
await self._browse_and_select_asset(
"Property//Frame/**/Button[*].identifier=='sdf_browse_asset_asset_array[0]'", ["dummy1.txt"]
)
await ui_test.human_delay()
self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy1.txt", "./dummy0.txt"])
# Remove the first asset
remove_asset = ui_test.find("Property//Frame/**/Button[*].identifier=='sdf_asset_array_asset_array[0].remove'")
await remove_asset.click()
self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt"])
# Add 2 assets from file picker
await self._add_asset(["dummy0.txt", "dummy1.txt"])
await ui_test.human_delay()
self.assertEqual(
[asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt", "./dummy0.txt", "./dummy1.txt"]
)
# drag drop 2 assets from content window
await ui_test.find("Content").focus()
await ui_test.find("Property").focus()
async with ContentBrowserTestHelper() as content_browser_helper:
# await content_browser_helper.navigate_to_async(str(usd_path.parent))
browse_button = ui_test.find(ADD_ASSET_BUTTON_QUERY)
await content_browser_helper.drag_and_drop_tree_view(
str(usd_path.parent), ["dummy0.txt", "dummy1.txt"], browse_button.center
)
await ui_test.human_delay()
self.assertEqual(
[asset_path.path for asset_path in asset_array_attr.Get()],
["./dummy0.txt", "./dummy0.txt", "./dummy1.txt", "./dummy0.txt", "./dummy1.txt"],
)
# Test undo
omni.kit.undo.undo()
self.assertEqual(
[asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt", "./dummy0.txt", "./dummy1.txt"]
)
omni.kit.undo.undo()
self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt"])
omni.kit.undo.undo()
self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy1.txt", "./dummy0.txt"])
omni.kit.undo.undo()
self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["", "./dummy0.txt"])
omni.kit.undo.undo()
self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy1.txt", "./dummy0.txt"])
omni.kit.undo.undo()
self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt", "./dummy1.txt"])
omni.kit.undo.undo()
self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt"])
omni.kit.undo.undo()
self.assertEqual(asset_array_attr.Get(), None)
# Test redo
omni.kit.undo.redo()
self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt"])
omni.kit.undo.redo()
self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt", "./dummy1.txt"])
omni.kit.undo.redo()
self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy1.txt", "./dummy0.txt"])
omni.kit.undo.redo()
self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["", "./dummy0.txt"])
omni.kit.undo.redo()
self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy1.txt", "./dummy0.txt"])
omni.kit.undo.redo()
self.assertEqual([asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt"])
omni.kit.undo.redo()
self.assertEqual(
[asset_path.path for asset_path in asset_array_attr.Get()], ["./dummy0.txt", "./dummy0.txt", "./dummy1.txt"]
)
omni.kit.undo.redo()
self.assertEqual(
[asset_path.path for asset_path in asset_array_attr.Get()],
["./dummy0.txt", "./dummy0.txt", "./dummy1.txt", "./dummy0.txt", "./dummy1.txt"],
)
| 8,762 | Python | 44.170103 | 167 | 0.644488 |
omniverse-code/kit/exts/omni.kit.property.usd/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [3.18.17] - 2023-01-18
### Added
- `SdfAssetPathAttributeModel` sets builds SdfAssetPath with path/resolvedPath for UDIM paths
## [3.18.16] - 2023-01-11
### Added
- Updated UDIM support and updated tests
## [3.18.15] - 2022-12-16
### Added
- Fix issue that cannot undo properties of materials
## [3.18.13] - 2022-12-13
### Added
- Don't allow to edit instance proxies.
## [3.18.12] - 2022-12-05
### Added
- Added ability to pass arbitrary model_kwargs to model_cls and single_channel_model_cls specified in
addional_widget_kwargs
## [3.18.11] - 2022-11-28
### Changed
- Now using platform-agnostic copy/paste rather than pyperclip.
- Removed context menu test and made its own extension.
## [3.18.10] - 2022-11-07
### Changed
- Added reset-user option for test.
- Update test_assert_array_widget to use grid view for file picker.
## [3.18.9] - 2022-11-02
### Added
- Added kwarg to hide the control state part of a widget
## [3.18.8] - 2022-10-13
### Fixed
- Fixed browsing reference/payload path not resolving wildcard tokens in filepath
- Fixed browsing asset path/array attribute not navigating to the correct path
- Brought back detail options panel in filepicker when adding reference/payload
### Changed
- Use `omni.kit.window.file_importer` instead of wrapped version of file picker
## [3.18.7] - 2022-10-18
### Fixed
- Fix change value on multi-select Variants
## [3.18.6] - 2022-09-14
### Fixed
- Variants now support multiple selections & mixed
## [3.18.5] - 2022-09-20
### Added
- Added listener for `ADDITIONAL_CHANGED_PATH_EVENT_TYPE` event in message bus to trigger additional property invalidation.
## [3.18.4] - 2022-09-06
### Fixed
- Fixed unittests.
## [3.18.3] - 2022-08-30
### Added
- Supported drag&drop and Filepicker to add multiple files to `SdfAssetPathArray`.
- Added `Copy Property Path` to property context menu.
### Changed
- If `SdfAssetPath` and `SdfAssetPathArray` has no `fileExts` customData, allow folder to be selected.
## [3.18.2] - 2022-08-19
### Fixed
- Fixed performance regression when building model for attribute whose value is a big array.
## [3.18.1] - 2022-08-16
### Changed
- Adjusted alignment for `SdfAssetPath` and `SdfAssetPathArray` widgets.
## [3.18.0] - 2022-08-08
### Added
- Added widget builder and models for SdfAssetArray.
## [3.17.20] - 2022-08-08
### Changes
- Added relationship widget identifiers
## [3.17.19] - 2022-08-03
### Changes
- OM-58170: Custom Layout Group that can have a condition
## [3.17.18] - 2022-08-02
### Changes
- Ensure relative path by default for texture path.
## [3.17.17] - 2022-07-25
### Changes
- Refactored unittests to make use of content_browser test helpers
## [3.17.16] - 2022-07-15
- OM-55770: RGB/RGBA color swatches in property window
## [3.17.15] - 2022-07-13
- OM-55771: File browser button
## [3.17.14] - 2022-06-23
- Support Reset all attributes for the Property Widget
## [3.17.13] - 2022-06-22
### Added
- supported event type omni.timeline.TimelineEventType.TENTATIVE_TIME_CHANGED
## [3.17.12] - 2022-05-31
### Changes
- Changed create_control_state to use ImageWithProvider to prevent flicker
## [3.17.11] - 2022-05-26
### Changes
- added `reset_builder_coverage_table` function
- added `widget_builder_coverage_table` for converage testing
## [3.17.10] - 2022-05-13
### Changes
- Cleaned up ImageWithProvider vs Image usage
## [3.17.9] - 2022-05-17
### Changes
- Support multi-file drag & drop
## [3.17.8] - 2022-05-03
### Changes
- Fixed manual input on float2/float3/float4 types
- Fixed soft range on float2/float3/float4 types
- Fixed hard range on float2/float3/float4 types
## [3.17.7] - 2022-05-05
### Changes
- Hide the Remove context menu for the transform property widget
## [3.17.6] - 2022-05-02
### Changes
- Goto URL supports UDIM wildcards
## [3.17.5] - 2022-04-22
### Changes
- No longer supported copy and group copy of properties when multiple prims are selected.
## [3.17.4] - 2022-04-07
### Changes
- Locate button not visible when not valid. Like http or empty
## [3.17.3] - 2022-04-14
### Added
- Supported copy partially mixed vector value in group copy.
## [3.17.2] - 2022-04-12
### Changes
- Fix issue with add_button_menu_entry and context menu submenu depth
## [3.17.1] - 2022-03-30
### Changes
- PlaceholderAttribute doesn't error if the metadata doesn't contain "customData.default" or "default"
## [3.17.0] - 2022-03-17
### Changes
- Changed builder function to a class member
## [3.16.0] - 2022-02-18
### Added
- Added Copy/Paste all properties to collapseable frame header.
## [3.15.2] - 2022-02-10
### Added
- Added `set_path_item_padding` and `get_path_item_padding` to `PrimPathWidget`
## [3.15.1] - 2022-02-09
### Added
- Don't fix window slashes in payload reference widget
## [3.15.0] - 2022-02-01
### Added
- Allow Raw Usd Properties Widget to show with multi-selection protection.
## [3.14.0] - 2021-12-08
### Added
- Add -> Attribute to create new attribute on selected prim.
- Right click to remove a Property. However, if Property belongs to a schema, remove is disabled.
## [3.13.1] - 2021-12-02
### Changes
- Softrange update/fixes for array types
## [3.13.0] - 2021-11-29
### Changes
- Added `_get_alignment` and `_create_text_label` UsdPropertiesWidgetBuilder functions
## [3.12.5] - 2021-11-10
### Changes
- `TfTokenAttributeModel` can have custom `AbstractItem` passed into `_update_allowed_token function` to display different values in combobox
## [3.12.4] - 2021-11-10
### Fixed
- Fixed property widget refresh when Usd.Property is removed from Prim.
## [3.12.3] - 2021-10-18
### Changes
- Hard ranges show draggable range in widgets
- Soft ranges can be overridden by user
- Added support for `Sdf.ValueTypeNames.UChar`
## [3.12.2] - 2021-10-27
### Changes
- Prevent crash in event callback
## [3.12.1] - 2021-09-16
### Changes
- Added widget identifiers
## [3.12.0] - 2021-09-29
### Added
- `UsdPropertiesWidget` subclasses can now register a custom subclass of `UsdAttributeModel` to create the widget's models using the `model_cls` key in additional_widget_kwargs, and `single_channel_model_cls` for vector attributes.
## [3.11.3] - 2021-09-07
### Changed
- Fixed mixed `TfTokenAttributeModel` and `MdlEnumAttributeModel` overwriting unchanged values on other prims when last selected prim's value changed by USD API.
## [3.11.2] - 2021-07-20
### Changed
- Added Sdf.Payload support
## [3.11.1] - 2021-07-20
### Changed
- Fixed jump to path icon to handle versioning info in URL
## [3.11.0] - 2021-07-06
### Added
- Added hook for property context menu to add custom context menu entry for property value field.
- Added `ControlStateManager` to allow adding external control state.
- Added `GfVecAttributeSingleChannelModel` which backs value widgets with single channel of a vector.
### Changed
- All vector builder now builds each channel separately and have separated control state.
### Fixed
- A few fixes on models.
## [3.10.1] - 2021-06-15
### Changed
- Fixed asset path refresh issue
## [3.10.0] - 2021-05-21
### Changed
- Added refresh layer to Reference prims
## [3.9.7] - 2021-05-18
### Changed
- Added reset button to asset path selector
## [3.9.6] - 2021-05-18
### Changed
- Added tooltip to asset path stringbox
## [3.9.5] - 2021-05-12
### Fixed
- The default value of NoneGraph
## [3.9.4] - 2021-05-10
### Added
- Updated Sdf.Reference creation so it doesn't use windows slash "\"
## [3.9.3] - 2021-05-06
### Changes
- Only show references checkpoints when server supports them
## [3.9.2] - 2021-04-21
### Changes
- Improvements for large selection of prims
## [3.9.1] - 2021-04-15
### Changed
- Connected attributes are not editable
## [3.9.0] - 2021-04-09
### Added
- Supported hard range and soft range in USD property widget builder/model.
## [3.8.1] - 2021-04-08
### Changed
- Fixed Search in `Add Target(s)` window of relationship widget.
## [3.8.0] - 2021-03-25
### Added
- Supported checkpoint in Reference Widget. Requires `omni.kit.widget.versioning extension` to be enabled.
## [3.7.0] - 2021-03-16
### Added
- Supported `SdfTimeCode` type.
- Added `_save_real_values_as_prev` function in `UsdBase`. It can be overridden to deep copy `self._real_values` to `self._prev_real_values`
## [3.6.0] - 2021-03-11
### Added
- Supported nested display group from both USD and CustomLayoutGroup.
## [3.5.3] - 2021-02-19
### Added
- Added PrimPathWidget API tests
## [3.5.2] - 2021-02-18
### Changed
- Updated UI tests to use new docked_test_window function
## [3.5.1] - 2021-02-17
### Changed
- Fixed References Widget not able to fix broken references.
## [3.5.0] - 2021-02-10
### Added
- Added `change_on_edit_end` to `UsdAttributeModel` and `UsdBase` 's constructor (default to False). When set to True, value will be written back to USD when EditEnd.
### Changed
- `SdfAssetPathAttributeModel` now only updates value to USD on EditEnd.
## [3.4.4] - 2021-02-10
### Changes
- Updated StyleUI handling
## [3.4.3] - 2021-01-22
### Changed
- Show schema default value on UI if the Attribute value is undefined in USD file.
## [3.4.2] - 2020-12-09
### Changes
- Added extension icon
- Added readme
- Updated preview image
## [3.4.1] - 2020-12-07
## Changed
- Don't show "Raw Usd Properties" frame when its empty
## [3.4.0] - 2020-12-03
## Added
- Supported `default` value for more attributes. It first checks for `PropertySpec.default`, if not found, falls back to `ValueTypeName.defaultValue` on the value type.
## [3.3.1] - 2020-11-20
## Changed
- Added get_allowed_tokens function to usd_attribute_model class.
## [3.3.0] - 2020-11-19
## Added
- Added `ReferencesWidget` with preliminary support for Reference, It supports add/remove/replace Reference on prim with no multi-prim editing support yet.
## [3.2.0] - 2020-11-17
## Added
- Added `VariantsWidget` with preliminary support for VariantSet(s). It only supports changing current variant selection, and no multi-prim editing support.
## [3.1.0] - 2020-11-16
## Added
- Added `target_picker_filter_lambda` to `RelationshipEditWidget`'s `additional_widget_kwargs`, giving access to a custom lambda filter for relationships when filtering by type is not enough.
- Exposed `stage_widget` on `RelationshipTargetPicker` for a more flexible access to the widget when needed.
### Changed
- Skip `displayName`, `displayGroup` and `documentation` (in addition to `customData`) when writing metadata for a `PlaceholderAttribute`.
## [3.0.0] - 2020-11-13
### Changed
- Renamed all occurrences of "Attribute", "attr" to "Property" and "prop" to properly reflect the widgets are built on Usd Property (Attribute and Relationship), not just Attribute. The change is backward compatible, so existing code will continue to work, but should be updated asap before old classes and functions become deprecated in future.
- `UsdAttributesWidget` is now `UsdPropertiesWidget`.
- `UsdAttributesWidgetBuilder` is now `UsdPropertiesWidgetBuilder`.
- `UsdAttributeUiEntry` is now `UsdPropertyUiEntry`
- `usd_attribute_widget` is now `usd_property_widget`
- `usd_attribute_widget_builder` is now `usd_property_widget_builder`
- On `UsdPropertiesWidget(prev UsdAttributesWidget)` class:
- `build_attribute_item` is now `build_property_item`
- `_filter_attrs_to_build` is now `_filter_props_to_build`
- `_customize_attrs_layout` is now `_customize_props_layout`
- `_get_shared_attributes_from_selected_prims` is now `_get_shared_attributes_from_selected_prims`
## [2.11.0] - 2020-11-06
### Added
- Added colorspace combobox to sdf path widget
- Added MetadataObjectModel classes
## [2.10.0] - 2020-11-05
## Added
- Added `no_mixed` flag to `additional_widget_kwargs`. If set to True, the value field will not display "Mixed" overlay, but display the value from last selected prim. Editing the value still applies to all attributes.
## [2.9.0] - 2020-11-04
### Added
- Supported showing and clicking to jump authored Connections on Attribute.
## [2.8.1] - 2020-11-03
### Changed
- Added context menu to path widget for copy to clipboard
- Added additional frame padding to borderless frames
## [2.8.0] - 2020-11-02
### Changed
- Improved support for multi-prim property editing (i.e. "mixed" value).
- All field that has different values across selected prims will properly show blue "Mixed" text on the UI.
- When dragging on a Mixed value, all properties snap to the value on the last selected prim.
- On vector types, each component can be shown as Mixed and edited individually.
## [2.7.0] - 2020-10-30
### Added
- Added `multi_edit` to `UsdAttributesWidget`'s constructor. Set it to False if you want the widget to only work on the last selected prim. Set it to True to work on shared properties across all selected prims. Default is True.
- Added `prim_paths` to `UsdAttributeUiEntry` to allow overriding of what prim path(s) the properties are going to built upon.
## [2.6.0] - 2020-10-28
### Added
- Supported drag-and-drop, file picker and "jump to" button on SdfAssetPath widget.
## [2.5.0] - 2020-10-27
### Added
- Added `targets_limit` to `RelationshipEditWidget`'s `additional_widget_kwargs`, allowing limiting the maximum number of targets can be set on a relationship.
## [2.4.0] - 2020-10-23
### Added
- Added `MdlEnumAttributeModel` and supported building MDL enum type in `UsdAttributesWidgetBuilder`.
## [2.3.3] - 2020-10-22
### Added
- Added optional `collapsed` parameter to `CustomLayoutGroup`
## [2.3.2] - 2020-10-19
### Changed
- Removed `PrimPathSchemeDelegate` and `XformbalePrimSchemeDelegate` so now controlled by omni.kit.property.bundle
## [2.3.1] - 2020-10-19
### Changed
- Fixed USD widget not cleared after current scene is closed.
- Fixed instance parsing error in SchemaAttributesWidget.
## [2.3.0] - 2020-10-14
### Added
- Added optional parameters `additional_label_kwargs` and `additional_widget_kwargs` to `UsdAttributesWidgetBuilder` to allow supplying additional kwargs to builders.
- Added `get_additional_kwargs` function to `UsdAttributesWidget` class. Override it to supply `additional_label_kwargs` and `additional_widget_kwargs` for specific USD property.
- An special parameter to add type filtering to Relationship target picker. See example in `MeshWidget.get_additional_kwargs`.
## [2.2.0] - 2020-10-14
### Added
- Placeholder attribute.
## [2.1.0] - 2020-10-13
### Added
- Added custom_layout_helper module to help declaratively build customized USD property layout.
- ext."omni.kit.window.property".labelAlignment setting to globally control property label alignment.
- ext."omni.kit.window.property".checkboxAlignment setting to globally control bool checkbox alignment.
- UsdAttributesWidgetBuilder._create_label as separated function.
### Changed
- Fixed UI models not cleaned up on new payload.
- Fixed string/token being mistakenly treated as array and clipped for being too long.
- Fallback builder now creates StringField with disabled style.
## [2.0.0] - 2020-10-09
### Added
- Supported Usd.Relationship.
## [1.2.0] - 2020-10-02
### Changed
- Updated Style & Path widget display
## [1.1.0] - 2020-10-06
### Added
- UsdAttributesWidget._customize_attrs_layout to customize attribute display name/group/order, operating on UsdAttributeUiEntry.
### Changed
- UsdAttributesWidget._get_shared_attributes_from_selected_prims now returns list of UsdAttributeUiEntry.
- Removed is_api_schema parameter from SchemaAttributesWidget constructor.
- SchemaAttributesWidget now works on multiple applied schema.
## [1.0.0] - 2020-09-18
### Added
- USD Widgets Released.
| 15,666 | Markdown | 32.052743 | 345 | 0.721563 |
omniverse-code/kit/exts/omni.kit.property.usd/docs/README.md | # omni.kit.property.usd
## Introduction
Property window extensions are for viewing and editing Usd Prim Attributes
## This extension enables USD property windows
| 166 | Markdown | 17.555554 | 74 | 0.795181 |
omniverse-code/kit/exts/omni.kit.property.usd/docs/index.rst | omni.kit.property.usd: USD Property Widget Extension
#####################################################
.. toctree::
:maxdepth: 1
CHANGELOG
USD Property Widget
==========================
.. automodule:: omni.kit.property.usd.usd_property_widget
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
USD Property Widget Builder
============================
.. automodule:: omni.kit.property.usd.usd_property_widget_builder
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
:private-members:
USD Attribute Model
==========================
.. automodule:: omni.kit.property.usd.usd_attribute_model
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:imported-members:
:show-inheritance:
USD Object Model
==========================
.. automodule:: omni.kit.property.usd.usd_object_model
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
USD Variants Model
==========================
.. automodule:: omni.kit.property.usd.variants_model
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
USD Property Widget Custom Layout Helper
=========================================
.. automodule:: omni.kit.property.usd.custom_layout_helper
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance: | 1,502 | reStructuredText | 25.368421 | 65 | 0.583222 |
omniverse-code/kit/exts/omni.kit.welcome.whats_new/omni/kit/welcome/whats_new/style.py | from pathlib import Path
import omni.ui as ui
from omni.ui import color as cl
from omni.ui import constant as fl
CURRENT_PATH = Path(__file__).parent
ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("icons")
WHATS_NEW_PAGE_STYLE = {}
DOCUMENT_STYLE = {
"ScrollingFrame": {"background_color": 0},
"Circle": {"background_color": 0xFF000000},
} | 367 | Python | 23.533332 | 70 | 0.713896 |
omniverse-code/kit/exts/omni.kit.welcome.whats_new/omni/kit/welcome/whats_new/extension.py | import webbrowser
import carb.settings
import carb.tokens
import omni.client
import omni.ext
import omni.ui as ui
from omni.kit.documentation.builder import DocumentationBuilderMd, DocumentationBuilderPage
from omni.kit.documentation.builder import get_style as get_doc_style
from omni.kit.welcome.window import register_page
from omni.ui import constant as fl
from .style import ICON_PATH, WHATS_NEW_PAGE_STYLE, DOCUMENT_STYLE
_extension_instance = None
class WhatsNewPageExtension(omni.ext.IExt):
def on_startup(self, ext_id):
self.__ext_name = omni.ext.get_extension_name(ext_id)
register_page(self.__ext_name, self.build_ui)
self.__settings = carb.settings.get_settings()
url = self.__settings.get(f"/exts/{self.__ext_name}/url")
self._url = carb.tokens.get_tokens_interface().resolve(url)
def on_shutdown(self):
global _extension_instance
_extension_instance = None
def build_ui(self) -> None:
with ui.ZStack(style=WHATS_NEW_PAGE_STYLE):
# Background
ui.Rectangle(style_type_name_override="Content")
with ui.VStack():
with ui.VStack(height=fl._find("welcome_page_title_height")):
ui.Spacer()
with ui.HStack():
ui.Spacer()
ui.Button(
text="VIEW ON THE WEB",
width=0,
spacing=10,
image_url=f"{ICON_PATH}/external_link.svg",
clicked_fn=self.__view_on_web,
style_type_name_override="Title.Button"
)
ui.Spacer()
ui.Spacer()
with ui.HStack():
ui.Spacer(width=fl._find("welcome_content_padding_x"))
with ui.ZStack(style=get_doc_style()):
ui.Rectangle(style_type_name_override="Doc.Background")
with ui.ScrollingFrame(
style=DOCUMENT_STYLE,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
):
doc_builder = DocumentationBuilderPage(DocumentationBuilderMd(self._url))
doc_builder._dont_scale_images = True
ui.Spacer(width=fl._find("welcome_content_padding_x"))
ui.Spacer(height=fl._find("welcome_content_padding_y"))
def __view_on_web(self):
web_url = self.__settings.get(f"/exts/{self.__ext_name}/web_url")
if not web_url:
web_url = self._url
webbrowser.open(web_url) | 2,858 | Python | 39.842857 | 102 | 0.551435 |
omniverse-code/kit/exts/omni.hsscclient/omni/hsscclient/tests/load_usd.py | import argparse
import asyncio
import json
import time
from pathlib import Path
import carb
import carb.events
import omni.kit
import omni.renderer_capture
import omni.stats
import omni.usd
from omni.hydra.engine.stats import get_device_info, get_mem_stats
class StageLoader:
def __init__(self) -> None:
self._current_url = ""
self._stage_event_sub = (
omni.usd.get_context()
.get_stage_event_stream()
.create_subscription_to_pop(self.on_stage_event, name="Stage Load Timer Subscription")
)
self._loading = False
self._future_usd_loaded = asyncio.Future()
self._start_ts = 0
self._duration = 0
def duration(self):
return self._duration
async def wait(self):
await self._future_usd_loaded
def result(self):
return self._future_usd_loaded.result()
def load(self, url: str) -> None:
if self._loading:
carb.log_error("*** Cannot load a new stage while one is loading")
return
# enable the flag, track the current url being loaded
self._loading = True
self._current_url = url
omni.usd.get_context().open_stage(self._current_url)
return
def on_stage_event(self, e: carb.events.IEvent):
event = omni.usd.StageEventType(e.type)
payload: dict = e.payload
carb.log_info(f"***Stage Event: {event} {payload}")
if event == omni.usd.StageEventType.OPENING:
url = payload.get("val", None)
if self._loading and url and url in self._current_url:
self._start_ts = time.time()
elif event == omni.usd.StageEventType.ASSETS_LOADED:
if self._loading:
self._loading = False
self._duration = time.time() - self._start_ts
carb.log_warn(f"{self._current_url} is loaded in {self._duration}s.")
self._future_usd_loaded.set_result(True)
elif event == omni.usd.StageEventType.OPEN_FAILED and self._loading:
self._loading = False
carb.log_error(f"{self._current_url} failed to load.")
self._future_usd_loaded.set_result(False)
usd_loader = StageLoader()
def get_omni_stats():
stats_value = {}
_stats = omni.stats.get_stats_interface()
scopes = _stats.get_scopes()
for scope in scopes:
scope_name = scope["name"]
# print(scope_name)
stats_value[scope_name] = {}
stat_nodes = _stats.get_stats(scope["scopeId"])
for stat in stat_nodes:
stat_item = {
"name": stat["name"],
"value": stat["value"],
"description": stat["description"],
}
stats_value[scope_name][stat["name"]] = stat_item
return stats_value
async def wait_stage_loading(wait_frames: int = 2):
"""
Waits for the USD stage in the given USD Context to load.
Args:
wait_frames (int): How many frames to wait after loading the stage if given (2 by default)
"""
usd_context = omni.usd.get_context()
frame_count = 0
while True:
_, files_loaded, total_files = usd_context.get_stage_loading_status()
if files_loaded or total_files:
await omni.kit.app.get_app().next_update_async()
continue
if frame_count != wait_frames:
await omni.kit.app.get_app().next_update_async()
frame_count += 1
continue
break
async def main(largs):
try:
app = omni.kit.app.get_app()
settings_interface = carb.settings.get_settings()
except AttributeError:
app = omni.kit.app.get_app_interface()
settings_interface = omni.kit.settings.get_settings_interface()
usd_context = omni.usd.get_context()
await usd_context.new_stage_async()
carb.log_warn("NEW STAGE ASYNC")
await wait_stage_loading(120)
carb.log_warn("WAIT STAGE LOADING")
output_path = Path(largs.output_folder)
# load the scene
usd_loader.load(largs.stage)
carb.log_warn("Start loading")
await usd_loader.wait()
carb.log_warn("End loading")
if not usd_loader.result():
app.post_quit()
return
# set renderer mode
if largs.renderer == "rt":
settings_interface.set_string("/rtx/rendermode", "RaytracedLighting")
elif largs.renderer == "pt":
settings_interface.set_string("/rtx/rendermode", "PathTracing")
settings_interface.set_float("/rtx/pathtracing/totalSpp", 0)
from omni.kit.viewport.utility import get_active_viewport_window
viewport_window = get_active_viewport_window()
resolution = viewport_window.viewport_api.resolution
await asyncio.sleep(largs.screenshot_pause)
if largs.fps:
# measure FPS
carb.log_warn("Start FPS measuring")
frame_info = viewport_window.viewport_api.frame_info
multiplier = frame_info.get("subframe_count", 1)
fps = viewport_window.viewport_api.fps * multiplier
carb.log_warn(f"End FPS measuring: {fps}")
else:
fps = None
renderer = omni.renderer_capture.acquire_renderer_capture_interface()
renderer.capture_next_frame_swapchain(str(output_path / largs.screenshot_file))
carb.log_warn("PRE-CAPTURE")
await app.next_update_async()
renderer.wait_async_capture()
carb.log_warn("POST-CAPTURE")
stats_file = output_path / "stats.json"
stats = {
"load_time": usd_loader.duration(),
"fps": fps,
"resolution": resolution,
"omni.hydra.engine.stats.get_device_info()": get_device_info(),
"omni.hydra.engine.stats.get_mem_stats()": get_mem_stats(detailed=False),
"omni.stats.get_stats_interface()": get_omni_stats(),
}
stats_file.write_text(json.dumps(stats, indent=4))
carb.log_warn(f"Stats are saved to: {stats_file}")
if largs.keep_running:
carb.log_warn("You can quit Kit manually.")
else:
app.post_quit()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--stage", help="Full path to USD stage to render", required=True)
parser.add_argument("--output_folder", help="Full path to the Output Folder", required=True)
parser.add_argument("--renderer", help="Renderer mode, rt or pt", default="rt")
parser.add_argument("--screenshot_file", help="Name of screenshot file to dump", default="screenshot.png")
parser.add_argument("--screenshot_pause", help="Seconds to wait before taking screenshot", default=5, type=int)
parser.add_argument("--fps", help="Collect FPS", default=False)
parser.add_argument(
"--keep_running", help="Whether to keep Kit running after benchmark is complete.", action="store_true"
)
args, unknown = parser.parse_known_args()
asyncio.ensure_future(main(args))
| 6,903 | Python | 32.192308 | 115 | 0.623207 |
omniverse-code/kit/exts/omni.hsscclient/omni/hsscclient/tests/__init__.py | from .test_hssc_integration import *
| 37 | Python | 17.999991 | 36 | 0.783784 |
omniverse-code/kit/exts/omni.hsscclient/omni/hsscclient/tests/test_hssc_integration.py | import csv
import json
import os
import pathlib
import shutil
import socket
import subprocess
import time
from collections import abc
import carb
import omni.kit.test
import toml
from omni.kit.core.tests.test_base import KitLaunchTest
from omni.ui.tests.compare_utils import CompareMetric, compare
def deep_update(sdict, udict):
"""Update nested-dict sdict with also-nested-dict udict, only where udict has keys set"""
for k, v in udict.items():
if isinstance(v, abc.Mapping) and v:
sdict[k] = deep_update(sdict.get(k, {}), v)
else:
sdict[k] = udict[k]
return sdict
def keychain(default, dictionary, keys):
"""Take iterable `keys` and dictionary-of-dictionaries, and keep resolving until you run out of keys. If we fail to look up, return default. Otherwise, return final value"""
try:
for k in keys:
dictionary = dictionary[k]
return dictionary
except KeyError:
return default
class Memcached:
"""Class to manage memcached server shard
TODO: Add multi-platform support."""
def __init__(self, objsize, poolsize, threads):
"""Ensure memcached is installed, then start with:
- `objsize`: maximum allowed object size
- `poolsize`: total memory pool size
- `threads`: # of threads
This will try to pick port 11211 and probe for a for a failed one."""
self.objsize = objsize
self.poolsize = poolsize
self.threads = threads
self.ip = "127.0.0.1"
tokens = carb.tokens.get_tokens_interface()
thisdir = pathlib.Path(__file__).resolve().parents[7]
testlibs = thisdir.joinpath(tokens.resolve("${platform}/${config}/testlibs/"))
self.binpath = os.path.realpath(testlibs.joinpath(tokens.resolve("memcached/${platform}/${config}/memcached")))
self.start()
def binary(self):
"""Memcached binary."""
return self.binpath
def start(self):
"""Start memcached, probing for free port. Will give up after 50 tries."""
code = 71 # code 71 is "port was busy"
tries = 0
port = 11211
while code == 71:
args = [self.binary(), "-p", str(port), "-I", self.objsize, "-m", self.poolsize, "-t", str(self.threads)]
proc = subprocess.Popen(args) # noqa: PLR1732
time.sleep(1)
code = proc.poll()
if code != 71:
break
tries += 1
port += 1
if tries > 50:
raise RuntimeError("Can't start memcached!")
assert proc.poll() is None
self.proc = proc # Hang on to process context
print(f"Started memcached @ port {port}")
self.port = port # hand on to successful port
@staticmethod
def flush(ip, port):
"""This sends a `flush_all` to the memcached server at ip:port"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip, port))
s.send(bytes("flush_all\r\n", "ascii"))
reply = ""
dat = s.recv(4096)
reply = str(dat, "utf-8")
assert reply == "OK\r\n"
s.close()
def flush_this(self):
"""Member version of above"""
Memcached.flush(self.ip, self.port)
def stop(self):
"""Kills memcached process."""
self.proc.kill()
@staticmethod
def format_uris(uris):
"""Format URIs in list-of (ip, port) tuples to pass to kit."""
return ",".join((f"memcache://{ip}:{port}" for (ip, port) in uris))
def get_hssc_log(logfile):
"""Read CSV file at `logfile`, returning dict of columns (lists)"""
with open(logfile, mode="r", encoding="utf-8") as fp:
reader = csv.reader(fp, delimiter=",")
items = [(s.strip(), []) for s in next(reader)]
for li in reader:
for idx, it in enumerate(li):
items[idx][1].append(it)
return {field[0]: field[1] for field in items}
scenes = [
("testtex", pathlib.Path(__file__).resolve().parents[0].joinpath("data/testtex/testtex.usda")),
]
async def compare_images(golden_path: str, capture_path: str, diff_path: str, threshold: float):
"""Compare golden image with test image and provide diff image MSE match status."""
mse = compare(
pathlib.Path(golden_path),
pathlib.Path(capture_path),
pathlib.Path(diff_path),
cmp_metric=CompareMetric.MEAN_ERROR_SQUARED,
)
matches_golden_image = mse <= threshold
if matches_golden_image:
carb.log_info(f"MSE of ref {golden_path} with capture {capture_path} is {mse} (PASSES {threshold})")
else:
carb.log_info(
f"MSE of ref {golden_path} with capture {capture_path} is {mse} (FAILS {threshold}, diff image in {diff_path})"
)
return mse, matches_golden_image
class TestHSSCIntegration(KitLaunchTest): # pragma: no cover
"""Main test harness for HSS$. Starts up memcached shards and runs series of tests"""
async def setUp(self):
"""Initialize shards"""
self.shards = [Memcached("1024m", "101024", 16)]
await super().setUp()
async def tearDown(self):
"""Take down shards"""
await super().tearDown()
for s in self.shards:
s.stop()
def flush_all(self):
"""Clear shard states"""
for s in self.shards:
s.flush_this()
async def runkit(self, config):
"""Start kit with given args, with particular knobs in `config`
Returns a dict with information about output directories & logs."""
base_args = [
"--no-audio",
"--enable",
"omni.kit.uiapp",
"--enable",
"omni.hydra.rtx",
"--enable",
"omni.usd",
"--enable",
"omni.kit.window.extensions",
"--enable",
"omni.kit.viewport.utility",
"--enable",
"omni.kit.viewport.bundle",
"--enable",
"omni.kit.viewport.rtx",
"--enable",
"omni.kit.renderer.capture",
"--enable",
"omni.mdl",
"--enable",
"omni.mdl.neuraylib",
"--enable",
"omni.hydra.engine.stats",
"--/crashreporter/skipOldDumpUpload=true",
"--/crashreporter/gatherUserStory=0", # don't pop up the GUI on crash
"--/app/skipOldDumpUpload=true",
"--/app/renderer/sleepMsOutOfFocus=0",
"--/rtx/ecoMode/enabled=false",
"--/app/asyncRendering=false",
"--/app/fastShutdown=true",
"--/foundation/verifyOsVersion/enabled=false",
"--/rtx/verifyDriverVersion/enabled=false",
"--/persistent/renderer/startupMessageDisplayed=true",
"--no-window",
"--/app/window/hideUi=true",
"--/app/docks/disabled=true",
"--/app/viewport/forceHideFps=true",
"--/persistent/app/viewport/displayOptions=1024",
"--/app/viewport/show/lights=false",
"--/app/viewport/show/audio=false",
"--/app/viewport/show/camera=false",
"--/app/viewport/grid/enabled=false",
"--/app/window/scaleToMonitor=false",
"--/app/window/dpiScaleOverride=1.0",
"--/rtx-transient/dlssg/enabled=false", # OM-97205: Disable DLSS-G for now globally, so L40 tests will all pass. DLSS-G tests will have to enable it
]
# Create directory, (delete if already exists)
output_dir = config["test"]["resdir"]
try:
os.makedirs(output_dir)
except FileExistsError:
shutil.rmtree(output_dir)
os.makedirs(output_dir)
run_res = {}
args = base_args[:]
args += [
f"--/app/renderer/resolution/width={config['kit']['resolution'][0]}",
f"--/app/renderer/resolution/height={config['kit']['resolution'][1]}",
]
run_res["kit_log"] = os.path.join(output_dir, "kit.log")
args += [f"--/log/file={run_res['kit_log']}"]
if "hssc_config" in config:
args += [
"--enable",
"omni.hsscclient",
f"--/rtx-transient/resourcemanager/hsscUri={Memcached.format_uris(config['hssc_config']['uris'])}",
"--/rtx-transient/resourcemanager/UJITSO/enabled=true",
]
if "log" in config["hssc_config"]:
run_res["hssc_log"] = os.path.join(output_dir, config["hssc_config"]["log"])
args += [f"--/rtx-transient/resourcemanager/hsscLogFile={run_res['hssc_log']}"]
if keychain(False, config, ("hssc_config", "preflush")):
for s in config["hssc_config"]["uris"]:
Memcached.flush(*s)
geometry = keychain(False, config, ("ujitso", "geometry"))
textures = keychain(False, config, ("ujitso", "textures"))
remote = keychain(False, config, ("ujitso", "remote"))
args += [f"--/rtx-transient/resourcemanager/UJITSO/geometry={str(geometry).lower()}"]
args += [f"--/rtx-transient/resourcemanager/UJITSO/textures={str(textures).lower()}"]
args += [f"--/rtx-transient/resourcemanager/useRemoteCache={str(remote).lower()}"]
run_res["load_usd_output"] = output_dir
extra_args = ["load_usd.py", f'--stage {config["test"]["usd_url"]}', "--output_folder", f"{output_dir}"]
root = pathlib.Path(__file__).resolve().parent
path = os.path.join(root, "load_usd.py")
with open(path, mode="r", encoding="utf-8") as fp:
script = fp.read()
await self._run_kit_with_script(script, args=args, script_extra_args=" " + " ".join(extra_args), timeout=600)
return run_res
def default_config(self):
"""Default params for tests"""
config = """[kit]
resolution = [ 1280, 720]
[hssc_config]
log = "hssclog.csv"
preflush = false
[ujitso]
textures = true
geometry = true
remote = true
[test]
"""
return toml.loads(config)
@staticmethod
def get_load_time(resdict):
"""Return load time from json file indicated by dict"""
with open(os.path.join(resdict["load_usd_output"], "stats.json"), mode="r", encoding="utf-8") as fp:
stats = json.load(fp)
return stats["load_time"]
async def run_warm_cold(self, name, usd, overrides=None, imagecomp=False, checkwarmfaster=False):
"""Load `usd` twice; the expectation is that the caches are 'cold' to start with, and then 'warm' the second time."""
if overrides is None:
overrides = {}
self.flush_all()
config = self.default_config()
config = deep_update(config, overrides)
config["test"]["usd_url"] = usd
config["hssc_config"]["uris"] = [(s.ip, s.port) for s in self.shards]
if imagecomp:
hssc_config = config["hssc_config"]
ujitso_config = config["ujitso"]
del config["hssc_config"]
del config["ujitso"]
config["test"]["resdir"] = os.path.join(omni.kit.test.get_test_output_path(), f"ref_{name}")
res = await self.runkit(config)
ref_image = os.path.join(config["test"]["resdir"], "screenshot.png")
# _ref_load = self.get_load_time(res)
config["hssc_config"] = hssc_config
config["ujitso"] = ujitso_config
with self.subTest(f"cold {name}"):
config["test"]["resdir"] = os.path.join(omni.kit.test.get_test_output_path(), f"cold_{name}")
res = await self.runkit(config)
if imagecomp:
cold_image = os.path.join(config["test"]["resdir"], "screenshot.png")
_mse, matches = await compare_images(
ref_image, cold_image, os.path.join(config["test"]["resdir"], "refdiff.png"), 0.01
)
self.assertTrue(matches)
log = get_hssc_log(res["hssc_log"])
self.assertGreater(
len(log["id"]), 5
) # This is a punt; we should do more detailed investation. For now, anything in the log indicates that we are talking to the HSS$
cold_load = self.get_load_time(res)
with self.subTest(f"warm {name}"):
config["test"]["resdir"] = os.path.join(omni.kit.test.get_test_output_path(), f"warm_{name}")
res = await self.runkit(config)
if imagecomp:
warm_image = os.path.join(config["test"]["resdir"], "screenshot.png")
_mse, matches = await compare_images(
ref_image, warm_image, os.path.join(config["test"]["resdir"], "refdiff.png"), 0.01
)
self.assertTrue(matches)
log = get_hssc_log(res["hssc_log"])
self.assertGreater(
len(log["id"]), 5
) # This is a punt; we should do more detailed investation. For now, anything in the log indicates that we are talking to the HSS$
warm_load = self.get_load_time(res)
if checkwarmfaster: # Ideally, we could mark this as a "not critical" test, since it could be noisy.
self.assertGreater(cold_load, warm_load)
async def test_tex_remote(self):
odict = {
"ujitso": {
"geometry": False,
"textures": True,
"remote": True,
}
}
for name, usd in scenes:
name = f"{name}_tex"
with self.subTest(name):
await self.run_warm_cold(name, usd, odict, imagecomp=False)
async def test_tex_remote_image(self):
odict = {
"ujitso": {
"geometry": False,
"textures": True,
"remote": True,
}
}
for name, usd in scenes:
name = f"{name}_tex"
with self.subTest(name):
await self.run_warm_cold(name, usd, odict, imagecomp=True)
| 14,137 | Python | 35.913838 | 177 | 0.56101 |
omniverse-code/kit/exts/omni.kit.commands/omni/kit/undo/undo.py | from datetime import datetime
from collections import namedtuple, deque
from functools import partial
import traceback
from contextlib import contextmanager
import carb
import omni.kit.commands
from typing import Any, Tuple
from .history import add_history, change_history, get_history, get_history_item
from ..commands.command import _call_callbacks as call_callbacks
# register undo/redo commands on system startup
def register_undo_commands():
omni.kit.commands.register_all_commands_in_module(__name__)
Entry = namedtuple("Entry", ["command", "name", "level", "history_key", "time"])
_undo_stack = deque()
_redo_stack = deque()
_on_change = set()
_on_change_detailed = set()
_level = 0
_group_entry = None
_group_count = 0
_disabled_count = 0
_in_redo_command = False
_in_repeat_command = False
def _incr_command_level():
global _level
_level = _level + 1
def _decr_command_level():
global _level
if _level <= 0:
carb.log_error(f"Can't decrement command level. Incr/decr mismatch. {_level}")
return False
_level = _level - 1
def _get_command_level():
return _level
def _create_entry(command, name, level, history_key):
global _redo_stack
global _undo_stack
global _in_redo_command
entry = Entry(command, name, level, history_key, datetime.now())
# Reset the redo stack if the command being executed is a root level command
# and we are not in the middle of a redo command. Leave the stack alone in that
# case since we re-execute the commands as a fresh copy to tie in with the history system
# but don't want to lose the ability to redo the remaining commands
if level == 0 and not _in_redo_command:
_redo_stack.clear()
_undo_stack.append(entry)
return entry
def execute(command, name, kwargs) -> Tuple[bool, Any]:
level = _get_command_level()
history_key = add_history(name, kwargs, level)
_incr_command_level()
global _group_entry
try:
# If command has "undo()" method it is executed using Undo System,
# unless undo functionality has been disabled using "begin_disabled()"
# Otherwise just call "do()".
if _disabled_count == 0 and callable(getattr(command, "undo", None)):
result = _execute(command, name, level, history_key)
else:
call_callbacks(command, name, kwargs, omni.kit.commands.PRE_DO_CALLBACK)
result = command.do()
call_callbacks(command, name, kwargs, omni.kit.commands.POST_DO_CALLBACK)
except Exception as e:
# update the history to flag it as having an error so we can render it different
change_history(history_key, error=True)
# if there is an active group being created, flag it as being in error state as well
if _group_entry:
change_history(_group_entry.history_key, error=True)
omni.kit.commands._log_error(f"Failed to execute a command: {name}.\n{omni.kit.undo.format_exception(e)}")
return (False, None)
finally:
# always decrement the group level so we don't end up with a mismatch due to an error being raised
_decr_command_level()
# History changed -> dispatch change event
omni.kit.commands._dispatch_changed()
return (True, result)
def subscribe_on_change(on_change):
global _on_change
_on_change.add(on_change)
def unsubscribe_on_change(on_change):
global _on_change
_on_change.discard(on_change)
def subscribe_on_change_detailed(on_change):
global _on_change_detailed
_on_change_detailed.add(on_change)
def unsubscribe_on_change_detailed(on_change):
global _on_change_detailed
_on_change_detailed.discard(on_change)
def can_undo():
return len(_undo_stack) > 0
def can_redo():
return len(_redo_stack) > 0
def can_repeat():
return len(_undo_stack) > 0
def clear_stack():
_undo_stack.clear()
_redo_stack.clear()
def get_undo_stack():
return _undo_stack
def get_redo_stack():
return _redo_stack
# implement these as bare commands so they integrate properly with the history part of the system
class Undo(omni.kit.commands.Command):
def __init__(self):
super().__init__()
def do(self):
global _redo_stack
if not can_undo():
return False
keep_going = True
cmds = []
history_entries = []
while keep_going and len(_undo_stack) > 0:
entry = _undo_stack.pop()
if entry.level == 0:
_redo_stack.append(entry)
keep_going = False
try:
history_entry = get_history_item(entry.history_key)
kwargs = history_entry.kwargs if history_entry else dict()
call_callbacks(entry.command, entry.name, kwargs, omni.kit.commands.PRE_UNDO_CALLBACK)
entry.command.undo()
call_callbacks(entry.command, entry.name, kwargs, omni.kit.commands.POST_UNDO_CALLBACK)
cmds.append(entry.name)
if history_entry:
history_entries.append(history_entry)
except Exception as e:
carb.log_error(f"Failed to undo a command: {entry.name}.\n{format_exception(e)}")
# take care of alerting the undo set of listeners here
# the command side will be handled in the calling code
#
# Note: The on_change events sent when undoing a command are identical to the
# ones generated when the command was originally executed or is then redone,
# except when a command group is undone in which case all commands that are
# part of the group will be sent as a list to a single call of the callback.
#
# I don't think this makes sense, firstly because when commands are executed
# individually (as opposed to part of a group), there is no way to determine
# whether the command is being executed, undone, or redone. Secondly, groups
# of commands will generate individual callbacks when originally executed or
# redone, but only a single callback for the entire group when it is undone.
#
# Another confusing aspect of these on_change callbacks is that there is an
# identically named API exposed via the 'omni.kit.commands' module which is
# used to notify subscribers when a command is registered, deregistered, or
# added to the command history (which is distinct from the undo/redo stack).
#
# Ideally we should clean up both of these APIs, but there is existing code
# that depends on the existing behaviour. There have been discussions about
# deprecating this entire 'omni.kit.undo' module in favour of new APIs that
# are exposed through 'omni.kit.commands' instead, which may be a good time
# to address this.
_dispatch_changed(cmds)
_dispatch_changed_detailed(history_entries)
return True
class Redo(omni.kit.commands.Command):
def __init__(self):
super().__init__()
def do(self):
global _redo_stack
global _in_redo_command
if not can_redo():
return False
# we have to play with the command level to make it look like redo isn't in the stack
# the entry that is executed should be at the root level, not redo
_decr_command_level()
try:
# treat this as a group of 1
entry = _redo_stack.pop()
_in_redo_command = True
return _execute_group_entries([entry])
finally:
_in_redo_command = False
_incr_command_level()
class Repeat(omni.kit.commands.Command):
def __init__(self):
super().__init__()
def do(self):
global _undo_stack
global _in_repeat_command
if not can_repeat():
return False
# we have to play with the command level to make it look like repeat isn't in the stack
# the entry that is executed should be at the root level, not repeat
_decr_command_level()
try:
# find the last base level command and treat it as a group of 1
for entry in reversed(_undo_stack):
if entry.level == 0:
_in_repeat_command = True
return _execute_group_entries([entry])
finally:
_in_repeat_command = False
_incr_command_level()
def undo():
(success, ret_val) = omni.kit.commands.execute("Undo")
return success and ret_val
def redo():
(success, ret_val) = omni.kit.commands.execute("Redo")
return success and ret_val
def repeat():
(success, ret_val) = omni.kit.commands.execute("Repeat")
return success and ret_val
# helper used to execute commands in the group scope when 'redo' or 'repeat' is called on the group
def _execute_group_entries(entries):
history = get_history()
for e in entries:
kwargs = history[e.history_key].kwargs if e.history_key in history else {}
command = e.command
if _in_repeat_command:
# If we're repeating the command, we must create a new instance,
# and if it's a group command we must also copy the 'do' function.
command = e.command.__class__(**kwargs)
if isinstance(command, GroupCommand):
command.do = e.command.do
(success, _) = execute(command, e.name, kwargs)
if not success:
raise Exception("Failed to redo or repeat commands")
return True
class GroupCommand(object):
def __init__(self):
super().__init__()
# this is set once all the children run and the group is closed
# it will capture all of the children (and their descendants) so we can redo them later
self.do = lambda *_: carb.log_error("Descendants for group not set")
# there is never anythign to do 'undo' for a group command
# all the undo work is handled by the children of the group
def undo(self):
pass
def begin_group():
"""Begin group of **Commands**."""
global _group_entry
global _group_count
_group_count = _group_count + 1
if _group_count == 1:
level = _get_command_level()
_incr_command_level() # this should only be called if an undo entry is created
history_key = add_history("Group", {}, level)
_group_entry = _create_entry(GroupCommand(), "Group", level, history_key)
def end_group():
"""End group of **Commands**."""
global _group_entry
global _group_count
global _undo_stack
_group_count = _group_count - 1
if _group_count == 0 and _group_entry is not None:
_decr_command_level()
try:
# create a real do function now that we have the full list of entries associated with the group
# grab all entries after the group until the end of the list and capture that list in a partial
# function for processing if 'redo' is called on the group
group_index = _undo_stack.index(_group_entry)
group_entries = list(filter(lambda entry: entry.level == 1, list(_undo_stack)[group_index + 1 :]))
if group_entries:
_group_entry.command.do = partial(_execute_group_entries, group_entries)
finally:
# have to manually call the listeners since groups don't go through higher level command code
_dispatch_changed([_group_entry.name])
history_entry = get_history_item(_group_entry.history_key)
if history_entry:
_dispatch_changed_detailed([history_entry])
omni.kit.commands._dispatch_changed()
# whether there was anything to capture or not, this group is closed, so clear out the entry
_group_entry = None
@contextmanager
def group():
"""Group multiple commands in one.
This function is a context manager.
Example:
.. code-block:: python
with omni.kit.undo.group():
omni.kit.commands.execute("Foo1")
omni.kit.commands.execute("Foo2")
"""
begin_group()
try:
yield
finally:
end_group()
def begin_disabled():
"""
Begin preventing **Commands** being added to the undo stack.
Must be paired with a subsequent call to end_disabled()
"""
global _disabled_count
_disabled_count = _disabled_count + 1
def end_disabled():
"""
Stop preventing **Commands** being added to the undo stack.
Must be paired with a prior call to begin_disabled()
"""
global _disabled_count
if _disabled_count > 0:
_disabled_count = _disabled_count - 1
else:
carb.log_error(f"undo.end_disabled() called without matching prior call to undo.begin_disabled()")
@contextmanager
def disabled():
"""Prevent commands being added to the undo stack.
This function is a context manager.
Example:
.. code-block:: python
with omni.kit.undo.disabled():
omni.kit.commands.execute("Foo1")
omni.kit.commands.execute("Foo2")
"""
begin_disabled()
try:
yield
finally:
end_disabled()
def _execute(command, name, level, history_key):
try:
# create an undo entry on the stack and execute its do function
entry = _create_entry(command, name, level, history_key)
# We want the callbacks to execute within the same undo group as the command
# so that any commands they execute will be undone at the same time as this.
history_entry = get_history_item(history_key)
kwargs = history_entry.kwargs if history_entry else dict()
call_callbacks(command, name, kwargs, omni.kit.commands.PRE_DO_CALLBACK)
result = command.do()
call_callbacks(command, name, kwargs, omni.kit.commands.POST_DO_CALLBACK)
except Exception as error:
# If the current command fails we need to unwind anything that came from it.
# Undo entries on the stack until we get back to the current entry.
# Any commands after this one in the stack were spawned by this command.
cmd_names = []
history_entries = []
while True:
last_entry = _undo_stack.pop()
# run undo on the command so we don't leave things in a half complete state
# trap any errors individually so each command has a chance to run
try:
last_entry.command.undo()
# make sure to alert the system of changes to all involved commands
# only add to the list if the undo command completed successfully
cmd_names.append(last_entry.name)
history_entry = get_history_item(last_entry.history_key)
if history_entry:
history_entries.append(history_entry)
except Exception as e:
carb.log_error(f"Failed to undo a command: {last_entry.name}.\n{format_exception(e)}")
if last_entry == entry:
# add it to the redo stack if it is a base level command
if level == 0:
_redo_stack.append(entry)
# when we get back to the current command we are done
break
# pump the callbacks with all commands that changed
_dispatch_changed(cmd_names)
_dispatch_changed_detailed(history_entries)
# re-raise the original error so the command system can handle it
# only need to manage the undo stack here, command system will take care of the rest
raise error
if name:
_dispatch_changed([name])
history_entry = get_history_item(history_key)
if history_entry:
_dispatch_changed_detailed([history_entry])
return result
def _dispatch_changed(cmd_names=[]):
for f in _on_change:
f(cmd_names)
def _dispatch_changed_detailed(cmd_entries=[]):
for f in _on_change_detailed:
f(cmd_entries)
def format_exception(e: Exception, remove_n_last_frames: int = 2) -> str:
"""Pretty format exception. Include exception info, call stack of exception itself and this function callstack.
This function is meant to be used in ``except`` clause.
Args:
e: Exception.
remove_n_last_frames: Number of last call stack frames to be removed. Usually this function and few above are meaningless to the user.
Returns:
Formatted string.
"""
stack = traceback.format_list(traceback.extract_stack()[:-remove_n_last_frames])
stack.extend(["[...skipped...]\n"])
stack.extend(traceback.format_list(traceback.extract_tb(e.__traceback__)))
return "".join(stack) + f"\n {e.__class__} {e}"
| 16,807 | Python | 32.955555 | 142 | 0.631463 |
omniverse-code/kit/exts/omni.kit.commands/omni/kit/undo/history.py | import carb.settings
from collections import namedtuple, OrderedDict
from functools import lru_cache
from itertools import islice
# implementing the history as an OrderedDict so we can cap the max size
# while keeping consistent indices that outside systems can hold on to
# doing it as a deque would let us cap the size, but the indices change
# when the cap is hit and it slides the oldest item off
# this way outside code can keep the index as well as iterate over it and things stay in the proper order
MAX_HISTORY_SIZE = 1000000
_history = OrderedDict()
_history_index = 0
HistoryEntry = namedtuple("HistoryEntry", ["name", "kwargs", "level", "error"])
@lru_cache()
def _get_crash_report_history_count():
return carb.settings.get_settings().get("/exts/omni.kit.commands/crashReportHistoryCount")
# Only convert to string primitive types, others may lead to crash (UsdStage was one of them).
PRIMITIVE_TYPES = {"<class 'str'>", "<class 'int'>", "<class 'float'>", "<class 'bool'>", "<class 'pxr.Sdf.Path'>"}
def _format_history_entry(history: HistoryEntry):
s = ""
for k, v in history.kwargs.items():
s += "(" if not s else ","
value = str(v) if str(type(v)) in PRIMITIVE_TYPES else "?"
s += f"{k}={value}"
if s:
s += ")"
return history.name + s
def add_history(name: str, kwargs: dict, level: int):
"""Add a **Command** execution to the history.
Takes: (Command name, Arguments, Groupping level).
Return: index that can be used to modify it later"""
global _history_index
_history_index = _history_index + 1
_history[_history_index] = HistoryEntry(name, kwargs, level, False)
# now make sure we have <= MAX_HISTORY_SIZE elements in the history
while True:
# if the head of the history is a root command and we are under the size limit, we are done
# otherwise we need to remove the entire group so we don't end up with children at the front of the history
key = next(iter(_history)) if len(_history) else None
if not key or (_history[key].level == 0 and len(_history) < MAX_HISTORY_SIZE):
break
# pop the entry from the front of the list and move on
_history.popitem(last=False)
# store last N commands for crash report (if we crash later)
n = _get_crash_report_history_count()
if n > 0:
# join last N elements of history into comma separted string
lastCommands = [_format_history_entry(x) for x in islice(reversed(_history.values()), n)]
settings = carb.settings.get_settings()
settings.set("/crashreporter/data/lastCommands", ",".join(reversed(lastCommands)))
settings.set("/crashreporter/data/lastCommand", next(iter(lastCommands), ""))
return _history_index
def change_history(key: int, **kwargs):
"""Update the history entry for **key**.
key: Index of the history entry to modify.
kwargs: any of the properties of HistoryEntry."""
if key in _history:
_history[key] = _history[key]._replace(**kwargs)
def get_history():
"""Get **Command** execution history.
Returns a list of tuples: HistoryEntry(Command name, Arguments, Groupping level, Error status)."""
return _history
def get_history_item(history_key: int) -> HistoryEntry:
try:
return _history[history_key]
# if the key is missing return None, any other erros should flow through to the caller
except KeyError:
return None
def clear_history():
"""Clear **Command** execution history."""
_history.clear()
| 3,568 | Python | 35.050505 | 115 | 0.672926 |
omniverse-code/kit/exts/omni.kit.commands/omni/kit/undo/__init__.py | from .history import clear_history, get_history
from .undo import (
execute,
begin_group,
end_group,
begin_disabled,
end_disabled,
disabled,
format_exception,
get_redo_stack,
get_undo_stack,
clear_stack,
group,
redo,
undo,
repeat,
can_undo,
can_redo,
can_repeat,
subscribe_on_change,
unsubscribe_on_change,
register_undo_commands,
subscribe_on_change_detailed,
unsubscribe_on_change_detailed,
)
# register undo/redo commands on system startup
register_undo_commands()
| 557 | Python | 18.241379 | 47 | 0.660682 |
omniverse-code/kit/exts/omni.kit.commands/omni/kit/commands/_kit_commands.pyi | """pybind11 omni.kit.commands bindings"""
from __future__ import annotations
import omni.kit.commands._kit_commands
import typing
__all__ = [
"ICommand",
"ICommandBridge",
"acquire_command_bridge",
"release_command_bridge"
]
class ICommand():
def do(self) -> None:
"""
Called when this command object is being executed,
either originally or in response to a redo request.
"""
def undo(self) -> None:
"""
Called when this command object is being undone.
"""
pass
class ICommandBridge():
@staticmethod
def create_cpp_command_object(*args, **kwargs) -> typing.Any:
"""
Bridge function to call from Python to create a new instance of a C++ command.
Args:
extension_id: The id of the source extension that registered the command.
command_name: The command name, unique to the extension that registered it.
**kwargs: Arbitrary keyword arguments that the command will be executed with.
Return:
The command object if it was created, an empty object otherwise.
"""
def disable(self) -> None:
"""
Disable the command bridge so that new command types can no longer be registered and deregistered from C++,
and so that existing command types can no longer be executed in Python (where commands are held) from C++.
Calling this will also cause any remaining command types previously registered in C++ to be deregistered.
"""
def enable(self, register_function: function, deregister_function: function, execute_function: function, undo_function: function, redo_function: function, repeat_function: function, begin_undo_group_function: function, end_undo_group_function: function, begin_undo_disabled_function: function, end_undo_disabled_function: function) -> None:
"""
Enable the command bridge so that new command types can be registered and deregistered from C++,
and so that existing command types can be executed in Python (where commands are held) from C++.
Args:
register_function: Function responsible for registering new C++ command types with Python.
deregister_function: Function responsible for deregistering C++ command types from Python.
execute_function: Function responsible for executing existing commands in Python from C++.
"""
pass
def acquire_command_bridge(plugin_name: str = None, library_path: str = None) -> ICommandBridge:
pass
def release_command_bridge(arg0: ICommandBridge) -> None:
pass
| 2,631 | unknown | 42.866666 | 345 | 0.676169 |
omniverse-code/kit/exts/omni.kit.commands/omni/kit/commands/command_actions.py | import omni.kit.actions.core
def register_actions(extension_id):
import omni.kit.undo
action_registry = omni.kit.actions.core.get_action_registry()
actions_tag = "Command Actions"
action_registry.register_action(
extension_id,
"undo",
omni.kit.undo.undo,
display_name="Command->Undo",
description="Undo the last command that was executed.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"redo",
omni.kit.undo.redo,
display_name="Command->Redo",
description="Redo the last command that was undone.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"repeat",
omni.kit.undo.repeat,
display_name="Command->Repeat",
description="Repeat the last command that was executed or redone.",
tag=actions_tag,
)
def deregister_actions(extension_id):
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.deregister_all_actions_for_extension(extension_id)
| 1,097 | Python | 27.153845 | 75 | 0.642662 |
omniverse-code/kit/exts/omni.kit.commands/omni/kit/commands/__init__.py | """Commands for Omniverse Kit.
:mod:`omni.kit.commands` module is used to register and execute **Commands**. It is built on top of :mod:`omni.kit.undo` module to enable undo/redo operations with **Commands**.
**Command** is any class with ``do()`` method and optionally ``undo()`` method. If **Command** has ``undo()`` method it is put on the undo stack when executed.
It must be inherited from :class:`Command` class for type checking.
Example of creating your command, registering it, passing arguments and undoing.
.. code-block:: python
class MyOrange(omni.kit.commands.Command):
def __init__(self, bar: list):
self._bar = bar
def do(self):
self._bar.append('orange')
def undo(self):
del self._bar[-1]
>>> import omni.kit.commands
>>> omni.kit.commands.register(MyOrangeCommand)
>>> my_list = []
>>> omni.kit.commands.execute("MyOrange", bar=my_list)
>>> my_list
['orange']
>>> import omni.kit.undo
>>> omni.kit.undo.undo()
>>> my_list
[]
>>> omni.kit.undo.redo()
>>> my_list
['orange']
"""
__all__ = [
"Command",
"create",
"register",
"register_all_commands_in_module",
"unregister_module_commands",
"unregister",
"PRE_DO_CALLBACK",
"POST_DO_CALLBACK",
"PRE_UNDO_CALLBACK",
"POST_UNDO_CALLBACK",
"register_callback",
"unregister_callback",
"get_command_class",
"get_command_class_signature",
"get_command_doc",
"get_command_parameters",
"get_commands",
"get_commands_list",
"execute",
"execute_argv",
"get_argument_parser_from_function",
"set_logging_enabled",
]
from .command import (
Command,
create,
register,
register_all_commands_in_module,
unregister_module_commands,
unregister,
PRE_DO_CALLBACK,
POST_DO_CALLBACK,
PRE_UNDO_CALLBACK,
POST_UNDO_CALLBACK,
register_callback,
unregister_callback,
get_command_class,
get_command_class_signature,
get_command_doc,
get_command_parameters,
get_commands,
get_commands_list,
execute,
execute_argv,
get_argument_parser_from_function,
_log_error,
set_logging_enabled,
)
from .command_actions import register_actions, deregister_actions
from .command_bridge import CommandBridge
from .on_change import subscribe_on_change, unsubscribe_on_change, _dispatch_changed
import omni.ext
import omni.kit.app
# this is needed for physx.ui
# once it properly imports its own dependencies, it can be removed
from typing import Any
class CommandExt(omni.ext.IExt):
"""Monitor for new extensions and register all commands in python modules of those extensions,
along with setting up a bridge that allows commands to be registered and executed from C++,
and registration of actions that wrap some basic command functionality like undo and redo.
"""
def on_startup(self, ext_id):
# Setup the command bridge
self._command_bridge = CommandBridge()
self._command_bridge.on_startup()
# Register command related actions
self._ext_name = omni.ext.get_extension_name(ext_id)
register_actions(self._ext_name)
# Monitor for commands in new or reloaded extensions
manager = omni.kit.app.get_app().get_extension_manager()
def on_change(e):
if e.type == omni.ext.EXTENSION_EVENT_SCRIPT_CHANGED:
def register_subclasses(cls):
register(cls)
for subcls in cls.__subclasses__():
register_subclasses(subcls)
register_subclasses(Command)
self._change_script_sub = manager.get_change_event_stream().create_subscription_to_pop(
on_change, name="kit.commands ExtensionChange"
)
def on_shutdown(self):
# Stop monitoring for commands in new or reloaded extensions
self._change_script_sub = None
# Deregister command related actions
deregister_actions(self._ext_name)
# Shutdown the command bridge
self._command_bridge.on_shutdown()
self._command_bridge = None
| 4,133 | Python | 28.319149 | 177 | 0.651585 |
omniverse-code/kit/exts/omni.kit.commands/omni/kit/commands/on_change.py | _on_change = set()
def subscribe_on_change(on_change):
"""Subscribe to module change events. Triggered when commands added, executed."""
global _on_change
_on_change.add(on_change)
def unsubscribe_on_change(on_change):
"""Unsubscribe to module change events."""
global _on_change
_on_change.discard(on_change)
def _dispatch_changed():
for f in _on_change:
f()
| 402 | Python | 20.210525 | 85 | 0.661692 |
omniverse-code/kit/exts/omni.kit.commands/omni/kit/commands/command_bridge.py | import carb
from ._kit_commands import *
from .command import (
Command,
execute,
register,
unregister,
get_command_class,
)
class CommandBridge:
def on_startup(self):
self._command_bridge = acquire_command_bridge()
def register_cpp_command(
extension_id: str, command_name: str, default_kwargs: dict, optional_kwargs: dict, required_kwargs: dict
):
def constructor(self, **kwargs):
# Check whether all the required keyword arguments specified from C++ have been provided.
for required_kwarg in self._required_kwargs:
if not required_kwarg in kwargs:
carb.log_error(
f"Required keyword argument '{required_kwarg}' not found when executing C++ command '{self.__class__.__name__}'."
)
# Check whether all the provided keyword arguments were specified as expected from C++.
for supplied_key, supplied_value in kwargs.items():
expected_value = self._all_kwargs.get(supplied_key, None)
if expected_value is None:
carb.log_warn(
f"Unexpected keyword argument '{supplied_key}' encountered when executing C++ command '{self.__class__.__name__}'."
)
# Merge the provided keyword arguments with the defaults specified from C++.
kwargs_with_defaults = {}
kwargs_with_defaults.update(self._default_kwargs)
kwargs_with_defaults.update(kwargs)
# Create the underlying C++ command object that can later be 'done' and 'undone.
self._cpp_command_object = self._command_bridge.create_cpp_command_object(
self.__class__.__module__, self.__class__.__name__, **kwargs_with_defaults
)
def do(self):
return self._cpp_command_object.do()
def undo(self):
self._cpp_command_object.undo()
new_cpp_command_class = type(
command_name,
(omni.kit.commands.Command,),
{
"__module__": extension_id,
"__init__": constructor,
"_default_kwargs": default_kwargs,
"_optional_kwargs": optional_kwargs,
"_required_kwargs": required_kwargs,
"_all_kwargs": {**default_kwargs, **optional_kwargs, **required_kwargs},
"_command_bridge": self._command_bridge,
"do": do,
"undo": undo,
},
)
omni.kit.commands.register(new_cpp_command_class)
def get_qualified_command_name(extension_id: str, command_name: str):
return extension_id + "." + command_name if extension_id else command_name
def deregister_cpp_command(extension_id: str, command_name: str):
qualified_command_name = get_qualified_command_name(extension_id, command_name)
command_class = omni.kit.commands.get_command_class(qualified_command_name)
if command_class:
omni.kit.commands.unregister(command_class)
command_class._command_bridge = None
def execute_command_from_cpp(extension_id: str, command_name: str, **kwargs):
qualified_command_name = get_qualified_command_name(extension_id, command_name)
return omni.kit.commands.execute(qualified_command_name, **kwargs)
import omni.kit.undo
self._command_bridge.enable(
register_cpp_command,
deregister_cpp_command,
execute_command_from_cpp,
omni.kit.undo.undo,
omni.kit.undo.redo,
omni.kit.undo.repeat,
omni.kit.undo.begin_group,
omni.kit.undo.end_group,
omni.kit.undo.begin_disabled,
omni.kit.undo.end_disabled,
)
def on_shutdown(self):
self._command_bridge.disable()
release_command_bridge(self._command_bridge)
self._command_bridge = None
| 4,240 | Python | 40.174757 | 143 | 0.554245 |
omniverse-code/kit/exts/omni.kit.commands/omni/kit/commands/command.py | import argparse
import carb
from collections import defaultdict
import inspect
import re
import sys
from abc import ABC, abstractmethod
from typing import Any, Callable, Dict, List, Tuple, Type
from .on_change import _dispatch_changed
_commands = defaultdict(dict)
LOGGING_ENABLED = True
# Callback types
PRE_DO_CALLBACK = 'pre_do'
POST_DO_CALLBACK = 'post_do'
PRE_UNDO_CALLBACK = 'pre_undo'
POST_UNDO_CALLBACK = 'post_undo'
# Callback dictionary:
# Keys: tuple(command class name minus any trailing 'Command', module name), callback type.
# Value: list of callables.
_callbacks: Dict[Tuple[str, str], Dict[str, List[Callable]]] = defaultdict(lambda: defaultdict(list))
# Callback ID object. We don't expose this publicly to prevent users from relying on its internal representation.
class CallbackID:
def __init__(self, command_name, module_name, callback_type, callback):
self.__command_name = command_name
self.__module_name = module_name
self.__cb_type = callback_type
self.__callable = callback
def get(self):
return (self.__command_name, self.__module_name, self.__cb_type, self.__callable)
class Command(ABC):
"""Base class for all **Commands**."""
@abstractmethod
def do(self):
pass
def modify_callback_info(self, cb_type: str, args: Dict[str, Any]) -> Dict[str, Any]:
"""Returns a dictionary of information to be passed to callbacks of the given type.
By default callbacks are passed a copy of the arguments which were passed to **execute()** when the command
was invoked. This method can be overridden to modify that information for specific callback types.
Args:
cb_type: Type of callback the information will be passed to.
args: A dictionary containing a copy of the arguments with which the command was invoked. This is a
shallow copy so implementations may add, remove or replace dictionary elements but should not
modify any of the objects contained within it.
Returns:
A dictionary of information to be passed to callbacks of the specified type.
"""
return args
def _log_error(message: str):
if LOGGING_ENABLED:
carb.log_error(message)
def set_logging_enabled(enabled: bool):
global LOGGING_ENABLED
LOGGING_ENABLED = enabled
def _get_module_and_class(name: str) -> Tuple[str, str]:
x = name.rsplit(".", 1)
if len(x) > 1:
return x[0], x[1]
return "", x[0]
def _get_module_and_stripped_class(name: str) -> Tuple[str, str]:
if name.endswith('Command'):
name = name[:-7]
return _get_module_and_class(name)
def create(name, **kwargs):
"""Create **Command** object.
Args:
name: **Command** name.
**kwargs: Arbitrary keyword arguments to be passed into into **Command** constructor.
Returns:
**Command** object if succeeded. `None` if failed.
"""
command_class = get_command_class(name)
if not command_class:
return None
return command_class(**kwargs)
def register(command_class: Type[Command]):
"""Register a **Command**.
Args:
command_class: **Command** class.
"""
if not issubclass(command_class, Command):
_log_error(f"Can't register command: {command_class} it is not a subclass of a Command.")
return
global _commands
name = command_class.__name__
module = command_class.__module__
if module in _commands[name]:
carb.log_verbose('Command: "{}" is already registered. Overwriting it.'.format(name))
# If the class contains the "Command" suffix, register it without the suffix
if name.endswith("Command"):
name = name[:-7]
_commands[name][module] = command_class
_dispatch_changed()
def register_all_commands_in_module(module):
"""Register all **Commands** found in specified module.
Register all classes in module which inherit :class:`omni.kit.commands.Command`.
Args:
module: Module name or module object.
Returns:
An accessor object that contains a function for every command to execute it. e.g. if you register
the commands "Run" and "Hide" then the accessor behaves like:
.. code-block:: python
class Accessor:
@staticmethod
def Run(**kwargs):
execute("Run", **kwargs)
@staticmethod
def Hide(**kwargs):
execute("Hide", **kwargs)
This gives you a nicer syntax for running your commands:
.. code-block:: python
cmds = register_all_commands_in_module(module)
cmds.Run(3.14)
cmds.Hide("Behind the tree")
"""
class CommandInterface:
class Immediate:
pass
def add_command(cls, name: str, command: Command):
def execute_command(cls, **kwargs):
return execute(command.__name__, **kwargs)
def execute_command_immediate(cls, **kwargs):
return command.do_immediate(**kwargs)
execute_command.__doc__ = command.__doc__
execute_command.__name__ = name
setattr(cls, name, execute_command)
# If the command has an immediate mode add that to the command interface too
if hasattr(command, "do_immediate"):
if not hasattr(cls, "imm"):
setattr(cls, "imm", CommandInterface.Immediate())
execute_command_immediate.__doc__ = command.do_immediate.__doc__
execute_command_immediate.__name__ = name
setattr(cls.imm, name, command.do_immediate)
if isinstance(module, str) and module in sys.modules:
module = sys.modules[module]
for name in dir(module):
obj = getattr(module, name)
if isinstance(obj, type) and issubclass(obj, Command) and obj is not Command:
register(obj)
# Strip the redundant "Command" suffix if it exists on the command, so you can run "CreateNodeCommand"
# by calling command_interface.CreateNode()
if obj.__name__.endswith("Command"):
add_command(CommandInterface, obj.__name__[:-7], obj)
else:
add_command(CommandInterface, obj.__name__, obj)
return CommandInterface()
def unregister_module_commands(command_interface):
"""Unregister the list of commands registered by register_all_commands_in_module
Args:
command_interface: An object whose only members are command classes that were registered
"""
if command_interface is None:
return
for command_name in dir(command_interface):
command_class = get_command_class(command_name)
if command_class is not None:
unregister(command_class)
def unregister(command_class: Type[Command]):
"""Unregister a **Command**.
Args:
command_class: **Command** class.
"""
if not issubclass(command_class, Command):
_log_error(f"Can't unregister command: {command_class} it is not a subclass of a Command.")
return
global _commands, _callbacks
name = command_class.__name__
# If the class contains the "Command" suffix, unregister it without the suffix
if name.endswith("Command"):
name = name[:-7]
module = command_class.__module__
_commands[name].pop(module, None)
_callbacks.pop((name, module), None)
_dispatch_changed()
def get_command_class(name: str) -> Type[Command]:
"""Get **Command** class(type) by name.
Args:
name: **Command** name. It may include a module name to be more specific and avoid conflicts.
Returns:
**Command** class if succeeded. `None` if can't find a command with this name.
"""
module_name, class_name = _get_module_and_class(name)
cmds = _commands[class_name]
if len(cmds) == 0:
# Backward compatibility - allow commands to be invoked with "Command" suffix in their name
if name.endswith("Command"):
stripped_name = name[:-7]
module_name, class_name = _get_module_and_class(stripped_name)
cmds = _commands[class_name]
if not cmds:
return None
else:
return None
if len(cmds) == 1:
return next(iter(cmds.values()))
else:
if module_name == "":
_log_error(f"There are multiple commands with {name}. Pass full command name including module name.")
return None
return cmds.get(module_name, None)
def get_command_class_signature(name: str):
"""Get the init signature for a **Command**.
Args:
name: **Command** name. It may include a module name to be more specific and avoid conflicts.
Returns:
__init__ signature
"""
command_class = get_command_class(name)
if command_class is None:
return None
function = command_class.__init__
return inspect.signature(function)
def get_command_doc(name: str) -> str:
"""Get **Command** docstring by name.
Args:
name: **Command** name. It may include a module name to be more specific and avoid conflicts.
Returns:
Python docstring (__doc__) from a command type.
"""
command_class = get_command_class(name)
return inspect.getdoc(command_class) if command_class else ""
def register_callback(name: str, cb_type: str, callback: Callable[[Dict[str, Any]], None]) -> CallbackID:
"""Register a callback for a command.
Args:
name: **Command** name. It may include a module name to be more specific and avoid conflicts.
cb_type: Type of callback. Currently supported types are:
PRE_DO_CALLBACK - called before the command is executed
POST_DO_CALLBACK - called after the command is executed
PRE_UNDO_CALLBACK - called before the command is undone
POST_UNDO_CALLBACK - called after the command is undone
callback: Callable to be called. Will be passed a dictionary of information specific to that
command invocation. By default the dictionary will contain the parameters passed to
execute(), but this may be overridden by individual commands so check their documentation.
Many command parameters are optional so it is important that callbacks check for their
presence before attempting to access them. The callback must not make any changes to
the dictionary passed to it.
Returns:
An ID that can be passed to **unregister_callback**.
"""
global _callbacks
module_name, class_name = _get_module_and_stripped_class(name)
_callbacks[(class_name, module_name)][cb_type] += [callback]
return CallbackID(class_name, module_name, cb_type, callback)
def unregister_callback(id: CallbackID):
"""Unregister a command callback previously registered through **register_callback**.
Args:
id: The ID returned by **register_callback** when the callback was registered.
"""
global _callbacks
if isinstance(id, CallbackID):
class_name, module_name, cb_type, callback = id.get()
cbs = _callbacks[(class_name, module_name)][cb_type]
try:
cbs.remove(callback)
return
except:
pass
carb.log_error(f'Attempt to unregister a {cb_type} callback on {module_name}.{class_name} which was not registered.')
else:
carb.log_error('Invalid callback id')
class CommandParameter:
"""Parameter details from inspect.Parameter with documentation if present"""
def __init__(self, param: inspect.Parameter, doc):
self._param = param
self._doc = doc
@property
def name(self) -> str:
if self._param.kind == inspect.Parameter.VAR_POSITIONAL:
return "*" + self._param.name
elif self._param.kind == inspect.Parameter.VAR_KEYWORD:
return "**" + self._param.name
return self._param.name
@property
def type(self):
if self._param.annotation is inspect._empty:
return None
return self._param.annotation
@property
def type_str(self) -> str:
if self._param.annotation is inspect._empty:
return ""
return inspect.formatannotation(self._param.annotation)
@property
def default(self):
if self._param.default is inspect._empty:
return None
return self._param.default
@property
def default_str(self) -> str:
if self._param.default is inspect._empty:
return ""
return str(self._param.default)
@property
def doc(self) -> str:
return self._doc
def get_command_parameters(name: str) -> List[Type[CommandParameter]]:
"""Get all parameters for a **Commands**.
Args:
name: **Command** name. It may include a module name to be more specific and avoid conflicts.
Returns:
A list of **CommandParameter** (except 'self' parameter)
"""
command_class = get_command_class(name)
if command_class is None:
return []
result = []
function = command_class.__init__
vardata = _get_argument_doc(function.__doc__ or command_class.__doc__)
sig = inspect.signature(function)
for param in sig.parameters.values():
if param.name == "self":
continue
var_help = ""
if param.name in vardata and "doc" in vardata[param.name]:
var_help = vardata[param.name]["doc"]
result.append(CommandParameter(param, var_help))
return result
def get_commands():
"""Get all registered **Commands**."""
return _commands
def get_commands_list() -> List[Type[Command]]:
"""Return list of all **Command** classes registered."""
return [c for m in _commands.values() for c in m.values()]
def _get_callback_info(cb_type:str, command: Command, cmd_args: Dict[str, Any]) -> Dict[str, Any]:
cmd_args = cmd_args.copy()
info = command.modify_callback_info(cb_type, cmd_args)
if isinstance(info, dict):
return info
return cmd_args
def _call_callbacks(command: Command, name: str, kwargs: Dict[str, Any], cb_type: str):
module_name, class_name = _get_module_and_stripped_class(name)
callbacks = _callbacks[(class_name, module_name)][cb_type]
if callbacks:
info = _get_callback_info(cb_type, command, kwargs)
for cb in callbacks:
cb(info)
def execute(name, **kwargs) -> Tuple[bool, Any]:
"""Execute **Command**.
Args:
name: **Command** name. Can be class name (e.g. "My") or full name including module (e.g. "foo.bar.MyCommand")
**kwargs: Arbitrary keyword arguments to be passed into into **Command** constructor.
"""
# Create command using passed params
command = create(name, **kwargs)
# Check command is valid
if not command:
_log_error("Can't execute command: \"{}\", it wasn't registered or ambigious.".format(name))
return (False, None)
if not callable(getattr(command, "do", None)):
_log_error("Can't execute command: \"{}\", it doesn't have do() method.".format(name))
return (False, None)
import omni.kit.undo # Prevent a circular dependency which breaks the doc-gen
# Execute the command.
result = omni.kit.undo.execute(command, name, kwargs)
return result
def execute_argv(name, argv: list) -> Tuple[bool, Any]:
"""Execute **Command** using argument list..
Attempts to convert argument list into **Command**'s kwargs. If a **Command** has *get_argument_parser* method defined, it will be called to get :class:`argparse.ArgumentParser` instance to use for parsing.
Otherwise command docstring is used to extract argument information.
Args:
name: **Command** name.
argv: Argument list.
"""
command_class = get_command_class(name)
if not command_class:
return (False, None)
kwargs = {}
cmd_argparse = None
if hasattr(command_class, "get_argument_parser"):
cmd_argparse = command_class.get_argument_parser()
else:
cmd_argparse = get_argument_parser_from_function(command_class.__init__)
try:
parsed_args = cmd_argparse.parse_known_args(argv)
kwargs = vars(parsed_args[0])
except SystemExit:
pass
return execute(name, **kwargs)
def _get_argument_doc(doc):
if doc is None:
return {}
vardata = {}
param_name = None
for line in doc.splitlines():
stripped = line.strip()
if stripped:
m = re.match(r"\s*(?P<param>\w+)(?P<type>.*): (?P<doc>.*)", line)
if m is not None:
param_name = m.group("param")
vardata[param_name] = {}
vardata[param_name]["doc"] = m.group("doc")
elif param_name is not None:
# group multiline doc with previous param
vardata[param_name]["doc"] += " " + stripped
else:
param_name = None
return vardata
def get_argument_parser_from_function(function):
fn_argparse = argparse.ArgumentParser()
# Note: should probably be replaced with `vardata = _get_argument_doc(function)`
param_regex = re.compile(r":param (?P<param>\w+)[\[\s\[]*(?P<meta>[\w\s\,]*)[\]\]*]*: (?P<doc>.*)")
vardata = {}
for var_match in re.finditer(param_regex, function.__doc__):
param_name = var_match.group("param")
vardata[param_name] = {}
vardata[param_name]["doc"] = var_match.group("doc")
vardata[param_name]["meta"] = var_match.group("meta")
varnames = function.__code__.co_varnames
for var_name in varnames:
if var_name == "self":
continue
var_help = ""
is_required = True
nargs = None
if var_name in vardata:
var_help = vardata[var_name]["doc"]
if "optional" in vardata[var_name]["meta"]:
is_required = False
if "list" in vardata[var_name]["meta"]:
nargs = "*"
if nargs is not None:
fn_argparse.add_argument(
"--" + var_name, nargs=nargs, metavar=var_name, help=var_help, required=is_required
)
else:
fn_argparse.add_argument("--" + var_name, metavar=var_name, help=var_help, required=is_required)
return fn_argparse
| 18,541 | Python | 32.529837 | 210 | 0.621434 |
omniverse-code/kit/exts/omni.kit.commands/omni/kit/commands/builtin/__init__.py | from .settings_commands import *
| 33 | Python | 15.999992 | 32 | 0.787879 |
omniverse-code/kit/exts/omni.kit.commands/omni/kit/commands/builtin/settings_commands.py | import carb.settings
import omni.kit.commands
class ChangeSettingCommand(omni.kit.commands.Command):
"""
Change setting **Command**.
Args:
path: Path to the setting to change.
value: New value to change to.
prev: Previous value to for undo operation. If `None` current value would be saved as previous.
"""
def __init__(self, path, value, prev=None):
super().__init__()
self._value = value
self._prev = prev
self._path = path
self._settings = carb.settings.get_settings()
def do(self):
if self._prev is None:
self._prev = self._settings.get(self._path)
self._settings.set(self._path, self._value)
def undo(self):
self._settings.set(self._path, self._prev)
class ChangeDraggableSettingCommand(omni.kit.commands.Command):
"""
Change draggable setting **Command**.
Args:
path: Path to the setting to change.
value: New value to change to.
"""
def __init__(self, path, value):
super().__init__()
self._value = value
self._path = path
self._settings = carb.settings.get_settings()
def do(self):
self._settings.set(self._path, self._value)
| 1,253 | Python | 25.124999 | 103 | 0.596169 |
omniverse-code/kit/exts/omni.kit.commands/omni/kit/commands/tests/test_commands.py | import carb.settings
import omni.kit.test
import omni.kit.commands
import omni.kit.undo
from functools import partial
from ._kit_command_tests import *
_result = []
_command_tests = None
def setUpModule():
global _command_tests
_command_tests = acquire_command_tests()
def tearDownModule():
global _command_tests
release_command_tests(_command_tests)
_command_tests = None
class TestAppendCommand(omni.kit.commands.Command):
def __init__(self, x, y):
self._x = x
self._y = y
def do(self):
global _result
_result.append(self._x)
_result.append(self._y)
def undo(self):
global _result
del _result[-1]
del _result[-1]
def modify_callback_info(self, cb_type, cmd_args):
if cb_type == omni.kit.commands.PRE_DO_CALLBACK:
cmd_args['pre_do'] = 1
elif cb_type == omni.kit.commands.POST_DO_CALLBACK:
cmd_args['post_do'] = 2
elif cb_type == omni.kit.commands.PRE_UNDO_CALLBACK:
cmd_args['pre_undo'] = 3
elif cb_type == omni.kit.commands.POST_UNDO_CALLBACK:
cmd_args['post_undo'] = 4
else:
cmd_args['other'] = 5
return cmd_args
class TestAppendNoUndoCommand(omni.kit.commands.Command):
def __init__(self, x, y):
self._x = x
self._y = y
def do(self):
global _result
_result.append(self._x)
_result.append(self._y)
class TestRaiseException(omni.kit.commands.Command):
def __init__(self, x, y):
self._x = x
self._y = y
def do(self):
raise Exception("testing an error happening")
global _result
_result.append(self._x)
_result.append(self._y)
class TestNoBaseCommand:
def __init__(self, x, y):
self._x = x
self._y = y
def do(self):
global _result
_result.append(self._x)
_result.append(self._y)
class TestMissingDoMethod(omni.kit.commands.Command):
def __init__(self, x, y):
global _result
_result.append(x)
_result.append(y)
class TestCommandParameters(omni.kit.commands.Command):
"""
TestCommandParameters **Command**.
Args:
x: x argument doc
yy: int: yy argument doc slightly longer
zzz: zzz argument doc but
on 2 lines
More info here.
"""
def __init__(self, x, yy: int, zzz="some default value"):
self._x = x
self._y = yy
self._z = zzz
def do(self):
pass
def undo(self):
pass
class TestCommands(omni.kit.test.AsyncTestCase):
async def setUp(self):
# Cache the command tests interface.
global _command_tests
self.command_tests = _command_tests
# Disable logging for the time of tests to avoid spewing errors
omni.kit.commands.set_logging_enabled(False)
# make sure we are starting from a clean state
omni.kit.undo.clear_stack()
# Register all commands
omni.kit.commands.register(TestAppendCommand)
omni.kit.commands.register(TestAppendNoUndoCommand)
omni.kit.commands.register(TestRaiseException)
omni.kit.commands.register(TestNoBaseCommand)
omni.kit.commands.register(TestMissingDoMethod)
omni.kit.commands.register(TestCommandParameters)
async def tearDown(self):
# Unregister all commands
omni.kit.commands.unregister(TestAppendCommand)
omni.kit.commands.unregister(TestAppendNoUndoCommand)
omni.kit.commands.unregister(TestRaiseException)
omni.kit.commands.unregister(TestNoBaseCommand)
omni.kit.commands.unregister(TestMissingDoMethod)
omni.kit.commands.unregister(TestCommandParameters)
omni.kit.commands.set_logging_enabled(True)
# Clear the command tests interface.
self.command_tests = None
async def test_commands(self):
global _result
# Execute and undo
_result = []
omni.kit.commands.execute("TestAppend", x=1, y=2)
self.assertListEqual(_result, [1, 2])
omni.kit.undo.undo()
self.assertListEqual(_result, [])
# Execute and undo command with undo
_result = []
undo_stack_len = len(omni.kit.undo.get_undo_stack())
omni.kit.commands.execute("TestAppendNoUndo", x=1, y=2)
self.assertListEqual(_result, [1, 2])
self.assertEqual(undo_stack_len, len(omni.kit.undo.get_undo_stack()))
# Execute command without base, it should not be registered
_result = []
omni.kit.commands.execute("TestNoBase", x=1, y=2)
self.assertListEqual(_result, [])
# Unregister -> execution does nothing
omni.kit.commands.unregister(TestAppendCommand)
omni.kit.commands.execute("TestAppend", x=1, y=2)
self.assertListEqual(_result, [])
# Register twice works fine
omni.kit.commands.register(TestAppendCommand)
omni.kit.commands.register(TestAppendCommand)
omni.kit.commands.execute("omni.kit.builtin.tests.core.test_commands.TestAppendCommand", x=1, y=2)
self.assertListEqual(_result, [1, 2])
# Automatically register command from a module
_result = []
omni.kit.commands.unregister(TestAppendCommand)
omni.kit.commands.register_all_commands_in_module(__name__)
omni.kit.commands.execute("TestAppend", x=1, y=2)
omni.kit.commands.execute("TestAppend", x=3, y=4)
self.assertListEqual(_result, [1, 2, 3, 4])
omni.kit.undo.undo()
self.assertListEqual(_result, [1, 2])
omni.kit.undo.undo()
self.assertListEqual(_result, [])
_result = []
omni.kit.commands.execute("TestAppendNoUndo", x=1, y=2)
self.assertListEqual(_result, [1, 2])
_result = []
omni.kit.commands.execute("TestNoBase", x=1, y=2)
self.assertListEqual(_result, [])
async def test_multiple_calls(self):
global _result
# make sure that Undo/Redo work properly when called on multiple commands
_result = []
omni.kit.commands.execute("TestAppend", x=1, y=2)
self.assertListEqual(_result, [1, 2])
omni.kit.commands.execute("TestAppend", x=3, y=4)
self.assertListEqual(_result, [1, 2, 3, 4])
# first call should do actual work and return True
res = omni.kit.undo.undo()
self.assertListEqual(_result, [1, 2])
self.assertTrue(res)
# same for second since 2 commands were run
res = omni.kit.undo.undo()
self.assertListEqual(_result, [])
self.assertTrue(res)
# third call should do nothing and return False
res = omni.kit.undo.undo()
self.assertListEqual(_result, [])
self.assertFalse(res)
# now do the same for Redo
# first call should do actual work and return True
res = omni.kit.undo.redo()
self.assertListEqual(_result, [1, 2])
self.assertTrue(res)
# test undo while there are still commands on the redo stack
res = omni.kit.undo.undo()
self.assertListEqual(_result, [])
self.assertTrue(res)
# now redo both of the original commands
res = omni.kit.undo.redo()
self.assertListEqual(_result, [1, 2])
self.assertTrue(res)
res = omni.kit.undo.redo()
self.assertListEqual(_result, [1, 2, 3, 4])
self.assertTrue(res)
# third call should do nothing and return False
res = omni.kit.undo.redo()
self.assertListEqual(_result, [1, 2, 3, 4])
self.assertFalse(res)
def test_group(self):
global _result
# Group multiple commands
_result = []
omni.kit.undo.begin_group()
omni.kit.commands.execute("TestAppend", x=1, y=2)
omni.kit.commands.execute("TestAppend", x=3, y=4)
omni.kit.undo.end_group()
self.assertListEqual(_result, [1, 2, 3, 4])
omni.kit.undo.undo()
self.assertListEqual(_result, [])
# Context manager version
_result = []
with omni.kit.undo.group():
omni.kit.commands.execute("TestAppend", x=1, y=2)
omni.kit.commands.execute("TestAppend", x=3, y=4)
self.assertListEqual(_result, [1, 2, 3, 4])
omni.kit.undo.undo()
self.assertListEqual(_result, [])
# Nested groups do nothing different:
_result = []
omni.kit.undo.begin_group()
omni.kit.commands.execute("TestAppend", x=1, y=2)
omni.kit.commands.execute("TestAppend", x=3, y=4)
omni.kit.undo.begin_group()
omni.kit.commands.execute("TestAppend", x=5, y=6)
omni.kit.commands.execute("TestAppend", x=7, y=8)
omni.kit.undo.end_group()
omni.kit.undo.end_group()
self.assertListEqual(_result, [1, 2, 3, 4, 5, 6, 7, 8])
omni.kit.undo.undo()
self.assertListEqual(_result, [])
# test redo/undo multiple times with groups
omni.kit.undo.redo()
self.assertListEqual(_result, [1, 2, 3, 4, 5, 6, 7, 8])
omni.kit.undo.undo()
self.assertListEqual(_result, [])
omni.kit.undo.redo()
self.assertListEqual(_result, [1, 2, 3, 4, 5, 6, 7, 8])
omni.kit.undo.undo()
self.assertListEqual(_result, [])
# Group multiple commands from C++
_result = []
self.command_tests.test_begin_undo_group_from_cpp()
omni.kit.commands.execute("TestAppend", x=1, y=2)
omni.kit.commands.execute("TestAppend", x=3, y=4)
self.command_tests.test_end_undo_group_from_cpp()
self.assertListEqual(_result, [1, 2, 3, 4])
omni.kit.undo.undo()
self.assertListEqual(_result, [])
def test_disabled(self):
global _result
# Disable undo
_result = []
omni.kit.undo.begin_disabled()
omni.kit.commands.execute("TestAppend", x=1, y=2)
omni.kit.commands.execute("TestAppend", x=3, y=4)
omni.kit.undo.end_disabled()
self.assertListEqual(_result, [1, 2, 3, 4])
omni.kit.undo.undo()
self.assertListEqual(_result, [1, 2, 3, 4])
# Context manager version
_result = []
with omni.kit.undo.disabled():
omni.kit.commands.execute("TestAppend", x=1, y=2)
omni.kit.commands.execute("TestAppend", x=3, y=4)
self.assertListEqual(_result, [1, 2, 3, 4])
omni.kit.undo.undo()
self.assertListEqual(_result, [1, 2, 3, 4])
omni.kit.commands.execute("TestAppend", x=5, y=6)
omni.kit.commands.execute("TestAppend", x=7, y=8)
omni.kit.undo.undo()
omni.kit.undo.undo()
self.assertListEqual(_result, [1, 2, 3, 4])
# Disable undo then enable
_result = []
omni.kit.undo.begin_disabled()
omni.kit.commands.execute("TestAppend", x=1, y=2)
omni.kit.commands.execute("TestAppend", x=3, y=4)
omni.kit.undo.end_disabled()
omni.kit.commands.execute("TestAppend", x=5, y=6)
omni.kit.commands.execute("TestAppend", x=7, y=8)
self.assertListEqual(_result, [1, 2, 3, 4, 5, 6, 7, 8])
omni.kit.undo.undo()
self.assertListEqual(_result, [1, 2, 3, 4, 5, 6])
omni.kit.undo.undo()
self.assertListEqual(_result, [1, 2, 3, 4])
omni.kit.undo.undo()
self.assertListEqual(_result, [1, 2, 3, 4])
# Nested calls to disable undo
_result = []
omni.kit.undo.begin_disabled()
omni.kit.commands.execute("TestAppend", x=1, y=2)
omni.kit.commands.execute("TestAppend", x=3, y=4)
omni.kit.undo.begin_disabled()
omni.kit.commands.execute("TestAppend", x=5, y=6)
omni.kit.commands.execute("TestAppend", x=7, y=8)
omni.kit.undo.end_disabled()
omni.kit.undo.end_disabled()
self.assertListEqual(_result, [1, 2, 3, 4, 5, 6, 7, 8])
omni.kit.undo.undo()
self.assertListEqual(_result, [1, 2, 3, 4, 5, 6, 7, 8])
# Disable undo then enable from C++
_result = []
self.command_tests.test_begin_undo_disabled_from_cpp()
omni.kit.commands.execute("TestAppend", x=1, y=2)
omni.kit.commands.execute("TestAppend", x=3, y=4)
self.command_tests.test_end_undo_disabled_from_cpp()
omni.kit.commands.execute("TestAppend", x=5, y=6)
omni.kit.commands.execute("TestAppend", x=7, y=8)
self.assertListEqual(_result, [1, 2, 3, 4, 5, 6, 7, 8])
omni.kit.undo.undo()
self.assertListEqual(_result, [1, 2, 3, 4, 5, 6])
omni.kit.undo.undo()
self.assertListEqual(_result, [1, 2, 3, 4])
omni.kit.undo.undo()
self.assertListEqual(_result, [1, 2, 3, 4])
async def test_error(self):
global _result
# test command raising and exception during `do()`
_result = []
res = omni.kit.commands.execute("TestRaiseException", x=1, y=2)
self.assertEqual(res, (False, None))
self.assertListEqual(_result, [])
# test command TypeError exception because `do()` is missing
_result = [1, 2]
try:
omni.kit.commands.execute("TestMissingDoMethod", x=3, y=4)
except TypeError:
_result = []
self.assertListEqual(_result, [])
async def test_command_parameters(self):
params = omni.kit.commands.get_command_parameters("TestCommandParameters")
# test parameters
self.assertEqual(len(params), 3)
self.assertEqual(params[0].name, "x")
self.assertEqual(params[1].name, "yy")
self.assertEqual(params[2].name, "zzz")
self.assertEqual(params[0].type_str, "")
self.assertEqual(params[1].type_str, "int")
self.assertEqual(params[2].type_str, "")
self.assertEqual(params[0].default_str, "")
self.assertEqual(params[1].default_str, "")
self.assertEqual(params[2].default_str, "some default value")
# test documentation in parameters
self.assertEqual(params[0].doc, "x argument doc")
self.assertEqual(params[1].doc, "yy argument doc slightly longer")
self.assertEqual(params[2].doc, "zzz argument doc but on 2 lines")
async def test_callbacks(self):
self.x = None
self.y = None
self.pre_do_count = 0
self.post_do_count = 0
self.pre_undo_count = 0
self.post_undo_count = 0
self.cmd_specific_pre_do_count = 0
self.cmd_specific_post_do_count = 0
self.cmd_specific_pre_undo_count = 0
self.cmd_specific_post_undo_count = 0
self.cmd_specific_other_count = 0
def pre_do_callback(self, info):
self.pre_do_count += 1
self.x = info.get('x', None)
if info.get('pre_do', None):
self.cmd_specific_pre_do_count += 1
if info.get('post_do', None):
self.cmd_specific_post_do_count += 1
if info.get('pre_undo', None):
self.cmd_specific_pre_undo_count += 1
if info.get('post_undo', None):
self.cmd_specific_post_undo_count += 1
if info.get('other', None):
self.cmd_specific_other_count += 1
def post_do_callback(self, info):
self.post_do_count += 1
self.y = info.get('y', None)
if info.get('pre_do', None):
self.cmd_specific_pre_do_count += 1
if info.get('post_do', None):
self.cmd_specific_post_do_count += 1
if info.get('pre_undo', None):
self.cmd_specific_pre_undo_count += 1
if info.get('post_undo', None):
self.cmd_specific_post_undo_count += 1
if info.get('other', None):
self.cmd_specific_other_count += 1
def pre_undo_callback(self, info):
self.pre_undo_count += 1
self.x = info.get('x', None)
if info.get('pre_do', None):
self.cmd_specific_pre_undo_count += 1
if info.get('post_do', None):
self.cmd_specific_post_undo_count += 1
if info.get('pre_undo', None):
self.cmd_specific_pre_undo_count += 1
if info.get('post_undo', None):
self.cmd_specific_post_undo_count += 1
if info.get('other', None):
self.cmd_specific_other_count += 1
def post_undo_callback(self, info):
self.post_undo_count += 1
self.y = info.get('y', None)
if info.get('pre_do', None):
self.cmd_specific_pre_undo_count += 1
if info.get('post_do', None):
self.cmd_specific_post_undo_count += 1
if info.get('pre_undo', None):
self.cmd_specific_pre_undo_count += 1
if info.get('post_undo', None):
self.cmd_specific_post_undo_count += 1
if info.get('other', None):
self.cmd_specific_other_count += 1
# With no callbacks registered, nothing should change.
omni.kit.commands.execute("TestAppend", x=1, y=2)
self.assertEqual(self.x, None)
self.assertEqual(self.y, None)
self.assertEqual(self.pre_do_count, 0)
self.assertEqual(self.post_do_count, 0)
self.assertEqual(self.cmd_specific_pre_do_count, 0)
self.assertEqual(self.cmd_specific_post_do_count, 0)
self.assertEqual(self.pre_undo_count, 0)
self.assertEqual(self.post_undo_count, 0)
self.assertEqual(self.cmd_specific_pre_undo_count, 0)
self.assertEqual(self.cmd_specific_post_undo_count, 0)
self.assertEqual(self.cmd_specific_other_count, 0)
# With only the pre- callback registered only x, pre_do_count and cmd_specific_pre_do_count should
# change.
pre_do_cb = omni.kit.commands.register_callback("TestAppend", omni.kit.commands.PRE_DO_CALLBACK, partial(pre_do_callback, self))
omni.kit.commands.execute("TestAppend", x=3, y=4)
self.assertEqual(self.x, 3)
self.assertEqual(self.y, None)
self.assertEqual(self.pre_do_count, 1)
self.assertEqual(self.post_do_count, 0)
self.assertEqual(self.cmd_specific_pre_do_count, 1)
self.assertEqual(self.cmd_specific_post_do_count, 0)
self.assertEqual(self.pre_undo_count, 0)
self.assertEqual(self.post_undo_count, 0)
self.assertEqual(self.cmd_specific_pre_undo_count, 0)
self.assertEqual(self.cmd_specific_post_undo_count, 0)
self.assertEqual(self.cmd_specific_other_count, 0)
# With both callbacks registered, everything except cmd_specific_other_count and various *_undo_counts should change.
post_do_cb = omni.kit.commands.register_callback("TestAppend", omni.kit.commands.POST_DO_CALLBACK, partial(post_do_callback, self))
omni.kit.commands.execute("TestAppend", x=5, y=6)
self.assertEqual(self.x, 5)
self.assertEqual(self.y, 6)
self.assertEqual(self.pre_do_count, 2)
self.assertEqual(self.post_do_count, 1)
self.assertEqual(self.cmd_specific_pre_do_count, 2)
self.assertEqual(self.cmd_specific_post_do_count, 1)
self.assertEqual(self.pre_undo_count, 0)
self.assertEqual(self.post_undo_count, 0)
self.assertEqual(self.cmd_specific_pre_undo_count, 0)
self.assertEqual(self.cmd_specific_post_undo_count, 0)
self.assertEqual(self.cmd_specific_other_count, 0)
# With callbacks removed, nothing should change.
omni.kit.commands.unregister_callback(pre_do_cb)
omni.kit.commands.unregister_callback(post_do_cb)
omni.kit.commands.execute("TestAppend", x=7, y=8)
self.assertEqual(self.x, 5)
self.assertEqual(self.y, 6)
self.assertEqual(self.pre_do_count, 2)
self.assertEqual(self.post_do_count, 1)
self.assertEqual(self.cmd_specific_pre_do_count, 2)
self.assertEqual(self.cmd_specific_post_do_count, 1)
self.assertEqual(self.pre_undo_count, 0)
self.assertEqual(self.post_undo_count, 0)
self.assertEqual(self.cmd_specific_pre_undo_count, 0)
self.assertEqual(self.cmd_specific_post_undo_count, 0)
self.assertEqual(self.cmd_specific_other_count, 0)
# TestAppendNoUndoCommand doesn't provide any special callback info
# so none of the 'specific' data counts should change.
pre_do_cb = omni.kit.commands.register_callback("TestAppendNoUndoCommand", omni.kit.commands.PRE_DO_CALLBACK, partial(pre_do_callback, self))
post_do_cb = omni.kit.commands.register_callback("TestAppendNoUndoCommand", omni.kit.commands.POST_DO_CALLBACK, partial(post_do_callback, self))
omni.kit.commands.execute("TestAppendNoUndoCommand", x=9, y=10)
self.assertEqual(self.x, 9)
self.assertEqual(self.y, 10)
self.assertEqual(self.pre_do_count, 3)
self.assertEqual(self.post_do_count, 2)
self.assertEqual(self.cmd_specific_pre_do_count, 2)
self.assertEqual(self.cmd_specific_post_do_count, 1)
self.assertEqual(self.pre_undo_count, 0)
self.assertEqual(self.post_undo_count, 0)
self.assertEqual(self.cmd_specific_pre_undo_count, 0)
self.assertEqual(self.cmd_specific_post_undo_count, 0)
self.assertEqual(self.cmd_specific_other_count, 0)
omni.kit.commands.unregister_callback(pre_do_cb)
omni.kit.commands.unregister_callback(post_do_cb)
# With no undo callbacks registered, nothing should change.
omni.kit.undo.undo()
self.assertEqual(self.x, 9)
self.assertEqual(self.y, 10)
self.assertEqual(self.pre_do_count, 3)
self.assertEqual(self.post_do_count, 2)
self.assertEqual(self.cmd_specific_pre_do_count, 2)
self.assertEqual(self.cmd_specific_post_do_count, 1)
self.assertEqual(self.pre_undo_count, 0)
self.assertEqual(self.post_undo_count, 0)
self.assertEqual(self.cmd_specific_pre_undo_count, 0)
self.assertEqual(self.cmd_specific_post_undo_count, 0)
self.assertEqual(self.cmd_specific_other_count, 0)
# With only the pre-undo callback registered only x, pre_undo_count and cmd_specific_pre_undo_count should change.
pre_undo_cb = omni.kit.commands.register_callback("TestAppend", omni.kit.commands.PRE_UNDO_CALLBACK, partial(pre_undo_callback, self))
omni.kit.undo.undo()
self.assertEqual(self.x, 5)
self.assertEqual(self.y, 10)
self.assertEqual(self.pre_do_count, 3)
self.assertEqual(self.post_do_count, 2)
self.assertEqual(self.cmd_specific_pre_do_count, 2)
self.assertEqual(self.cmd_specific_post_do_count, 1)
self.assertEqual(self.pre_undo_count, 1)
self.assertEqual(self.post_undo_count, 0)
self.assertEqual(self.cmd_specific_pre_undo_count, 1)
self.assertEqual(self.cmd_specific_post_undo_count, 0)
self.assertEqual(self.cmd_specific_other_count, 0)
# With both callbacks registered, everything except cmd_specific_other_count and various *_do_counts should change.
post_undo_cb = omni.kit.commands.register_callback("TestAppend", omni.kit.commands.POST_UNDO_CALLBACK, partial(post_undo_callback, self))
omni.kit.undo.undo()
self.assertEqual(self.x, 3)
self.assertEqual(self.y, 4)
self.assertEqual(self.pre_do_count, 3)
self.assertEqual(self.post_do_count, 2)
self.assertEqual(self.cmd_specific_pre_do_count, 2)
self.assertEqual(self.cmd_specific_post_do_count, 1)
self.assertEqual(self.pre_undo_count, 2)
self.assertEqual(self.post_undo_count, 1)
self.assertEqual(self.cmd_specific_pre_undo_count, 2)
self.assertEqual(self.cmd_specific_post_undo_count, 1)
self.assertEqual(self.cmd_specific_other_count, 0)
# With callbacks removed, nothing should change.
omni.kit.commands.unregister_callback(pre_undo_cb)
omni.kit.commands.unregister_callback(post_undo_cb)
omni.kit.undo.undo()
self.assertEqual(self.x, 3)
self.assertEqual(self.y, 4)
self.assertEqual(self.pre_do_count, 3)
self.assertEqual(self.post_do_count, 2)
self.assertEqual(self.cmd_specific_pre_do_count, 2)
self.assertEqual(self.cmd_specific_post_do_count, 1)
self.assertEqual(self.pre_undo_count, 2)
self.assertEqual(self.post_undo_count, 1)
self.assertEqual(self.cmd_specific_pre_undo_count, 2)
self.assertEqual(self.cmd_specific_post_undo_count, 1)
self.assertEqual(self.cmd_specific_other_count, 0)
# With callbacks registered again but nothing left to undo, nothing should change.
pre_undo_cb = omni.kit.commands.register_callback("TestAppend", omni.kit.commands.PRE_UNDO_CALLBACK, partial(pre_undo_callback, self))
post_undo_cb = omni.kit.commands.register_callback("TestAppend", omni.kit.commands.POST_UNDO_CALLBACK, partial(post_undo_callback, self))
omni.kit.undo.undo()
self.assertEqual(self.x, 3)
self.assertEqual(self.y, 4)
self.assertEqual(self.pre_do_count, 3)
self.assertEqual(self.post_do_count, 2)
self.assertEqual(self.cmd_specific_pre_do_count, 2)
self.assertEqual(self.cmd_specific_post_do_count, 1)
self.assertEqual(self.pre_undo_count, 2)
self.assertEqual(self.post_undo_count, 1)
self.assertEqual(self.cmd_specific_pre_undo_count, 2)
self.assertEqual(self.cmd_specific_post_undo_count, 1)
self.assertEqual(self.cmd_specific_other_count, 0)
async def test_subscribe_on_undo_stack_change(self):
self.command_names = []
self.command_entries = []
def on_undo_stack_change(command_names):
self.command_names += command_names
def on_undo_stack_change_detailed(command_entries):
self.command_entries += command_entries
# Execute a command before subscribing to on_change callbacks.
omni.kit.commands.execute("TestAppend", x=1, y=2)
self.assertListEqual(self.command_names, [])
self.assertListEqual(self.command_entries, [])
# Subscribe to on_change callbacks.
omni.kit.undo.subscribe_on_change(on_undo_stack_change)
omni.kit.undo.subscribe_on_change_detailed(on_undo_stack_change_detailed)
# Execute a command.
omni.kit.commands.execute("TestAppend", x=1, y=2)
self.assertListEqual(self.command_names, ["TestAppend"])
self.assertEqual(len(self.command_entries), 1)
self.assertEqual(self.command_entries[0].name, "TestAppend")
self.assertDictEqual(self.command_entries[0].kwargs, {"x":1, "y":2})
self.assertEqual(self.command_entries[0].level, 0)
self.assertEqual(self.command_entries[0].error, False)
# Undo the command.
self.command_names = []
self.command_entries = []
omni.kit.undo.undo()
self.assertListEqual(self.command_names, ["TestAppend"])
self.assertEqual(len(self.command_entries), 1)
self.assertEqual(self.command_entries[0].name, "TestAppend")
self.assertDictEqual(self.command_entries[0].kwargs, {"x":1, "y":2})
self.assertEqual(self.command_entries[0].level, 0)
self.assertEqual(self.command_entries[0].error, False)
# Redo the command.
self.command_names = []
self.command_entries = []
omni.kit.undo.redo()
self.assertListEqual(self.command_names, ["TestAppend"])
self.assertEqual(len(self.command_entries), 1)
self.assertEqual(self.command_entries[0].name, "TestAppend")
self.assertDictEqual(self.command_entries[0].kwargs, {"x":1, "y":2})
self.assertEqual(self.command_entries[0].level, 0)
self.assertEqual(self.command_entries[0].error, False)
# Group multiple commands
omni.kit.undo.begin_group()
self.command_names = []
self.command_entries = []
omni.kit.commands.execute("TestAppend", x=1, y=2)
self.assertListEqual(self.command_names, ["TestAppend"])
self.assertEqual(len(self.command_entries), 1)
self.assertEqual(self.command_entries[0].name, "TestAppend")
self.assertDictEqual(self.command_entries[0].kwargs, {"x":1, "y":2})
self.assertEqual(self.command_entries[0].level, 1)
self.assertEqual(self.command_entries[0].error, False)
self.command_names = []
self.command_entries = []
omni.kit.commands.execute("TestAppend", x=3, y=4)
self.assertListEqual(self.command_names, ["TestAppend"])
self.assertEqual(len(self.command_entries), 1)
self.assertEqual(self.command_entries[0].name, "TestAppend")
self.assertDictEqual(self.command_entries[0].kwargs, {"x":3, "y":4})
self.assertEqual(self.command_entries[0].level, 1)
self.assertEqual(self.command_entries[0].error, False)
self.command_names = []
self.command_entries = []
omni.kit.undo.end_group()
self.assertListEqual(self.command_names, ["Group"])
self.assertEqual(len(self.command_entries), 1)
self.assertEqual(self.command_entries[0].name, "Group")
self.assertDictEqual(self.command_entries[0].kwargs, {})
self.assertEqual(self.command_entries[0].level, 0)
self.assertEqual(self.command_entries[0].error, False)
# Undo the grouped commands (the callback will only be invoked once for the whole group).
self.command_names = []
self.command_entries = []
omni.kit.undo.undo()
self.assertListEqual(self.command_names, ["TestAppend", "TestAppend", "Group"])
self.assertEqual(len(self.command_entries), 3)
self.assertEqual(self.command_entries[0].name, "TestAppend")
self.assertDictEqual(self.command_entries[0].kwargs, {"x":3, "y":4})
self.assertEqual(self.command_entries[0].level, 1)
self.assertEqual(self.command_entries[0].error, False)
self.assertEqual(self.command_entries[1].name, "TestAppend")
self.assertDictEqual(self.command_entries[1].kwargs, {"x":1, "y":2})
self.assertEqual(self.command_entries[1].level, 1)
self.assertEqual(self.command_entries[1].error, False)
self.assertEqual(self.command_entries[2].name, "Group")
self.assertDictEqual(self.command_entries[2].kwargs, {})
self.assertEqual(self.command_entries[2].level, 0)
self.assertEqual(self.command_entries[2].error, False)
# Redo the grouped commands (the callback will be invoked once for each command being redone).
self.command_names = []
self.command_entries = []
omni.kit.undo.redo()
self.assertListEqual(self.command_names, ["TestAppend", "TestAppend", "Group"])
self.assertEqual(len(self.command_entries), 3)
self.assertEqual(self.command_entries[0].name, "TestAppend")
self.assertDictEqual(self.command_entries[0].kwargs, {"x":1, "y":2})
self.assertEqual(self.command_entries[0].level, 1)
self.assertEqual(self.command_entries[0].error, False)
self.assertEqual(self.command_entries[1].name, "TestAppend")
self.assertDictEqual(self.command_entries[1].kwargs, {"x":3, "y":4})
self.assertEqual(self.command_entries[1].level, 1)
self.assertEqual(self.command_entries[1].error, False)
self.assertEqual(self.command_entries[2].name, "Group")
self.assertDictEqual(self.command_entries[2].kwargs, {})
self.assertEqual(self.command_entries[2].level, 0)
self.assertEqual(self.command_entries[2].error, False)
# Unsubscribe from on_change callbacks.
omni.kit.undo.unsubscribe_on_change_detailed(on_undo_stack_change_detailed)
omni.kit.undo.unsubscribe_on_change(on_undo_stack_change)
async def test_cpp_commands(self):
global _result
_result = []
# Give the C++ test code access to the global test result list
self.command_tests.set_test_result_list(_result)
# Register a new command type from C++
self.command_tests.test_register_cpp_command("omni.kit.command_tests", "TestCppAppendCommand")
# Execute the C++ command from Python
res = omni.kit.commands.execute("TestCppAppend", x=7, y=9)
self.assertListEqual(_result, [7, 9])
self.assertEqual(res, (True, None))
# Undo the C++ command from C++
res = self.command_tests.test_undo_command_from_cpp()
self.assertListEqual(_result, [])
self.assertTrue(res)
# Redo the C++ command from Python
res = omni.kit.undo.redo()
self.assertListEqual(_result, [7, 9])
self.assertTrue(res)
# Execute the C++ command from C++
res = self.command_tests.test_execute_command_from_cpp("TestCppAppend", x=99, y=0)
self.assertListEqual(_result, [7, 9, 99, 0])
self.assertTrue(res)
# Undo the C++ command from Python
res = omni.kit.undo.undo()
self.assertListEqual(_result, [7,9])
self.assertTrue(res)
# Execute the C++ command from C++ with a default argument
res = self.command_tests.test_execute_command_from_cpp("TestCppAppend", x=99)
self.assertListEqual(_result, [7, 9, 99, -1])
self.assertTrue(res)
# Execute the C++ command from Python with a default argument
res = omni.kit.commands.execute("TestCppAppend", y=-9)
self.assertListEqual(_result, [7, 9, 99, -1, 9, -9])
self.assertEqual(res, (True, None))
# Undo the C++ command from C++
res = self.command_tests.test_undo_command_from_cpp()
self.assertListEqual(_result, [7, 9, 99, -1])
self.assertTrue(res)
# Undo the C++ command from Python
res = omni.kit.undo.undo()
self.assertListEqual(_result, [7,9])
self.assertTrue(res)
# Execute an existng Python command from C++
res = self.command_tests.test_execute_command_from_cpp("TestAppend", x=1, y=2)
self.assertListEqual(_result, [7, 9, 1, 2])
self.assertTrue(res)
# Undo the Python command from C++
res = self.command_tests.test_undo_command_from_cpp()
self.assertListEqual(_result, [7,9])
self.assertTrue(res)
# Redo the Python command from C++
res = self.command_tests.test_redo_command_from_cpp()
self.assertListEqual(_result, [7,9, 1, 2])
self.assertTrue(res)
# Undo the Python command from Python
res = omni.kit.undo.undo()
self.assertListEqual(_result, [7,9])
self.assertTrue(res)
# Deregister the C++ command from C++
self.command_tests.test_deregister_cpp_command("omni.kit.command_tests", "TestCppAppendCommand")
# Undo the C++ command from Python after it has been deregistered
res = omni.kit.undo.undo()
self.assertListEqual(_result, [])
self.assertTrue(res)
# Execute the C++ command from C++ after it has been deregistered (does nothing)
res = self.command_tests.test_execute_command_from_cpp("TestCppAppend", x=10, y=20)
self.assertListEqual(_result, [])
self.assertFalse(res)
# Execute the C++ command from Python after it has been deregistered (does nothing)
res = omni.kit.commands.execute("TestCppAppend", x=10, y=20)
self.assertListEqual(_result, [])
self.assertEqual(res, (False, None))
# Redo the C++ command from C++ after it has been deregistered
res = self.command_tests.test_redo_command_from_cpp()
self.assertListEqual(_result, [7, 9])
self.assertTrue(res)
# Undo the C++ command from C++ after it has been deregistered
res = self.command_tests.test_undo_command_from_cpp()
self.assertListEqual(_result, [])
self.assertTrue(res)
# Release the C++ reference to the global test result list
self.command_tests.clear_test_result_list()
def test_repeat(self):
global _result
_result = []
# Execute a command
res = omni.kit.commands.execute("TestAppend", x=1, y=2)
self.assertListEqual(_result, [1, 2])
self.assertEqual(res, (True, None))
# Repeat the command
res = omni.kit.undo.repeat()
self.assertListEqual(_result, [1, 2, 1, 2])
self.assertTrue(res)
# Undo the repeated command
res = omni.kit.undo.undo()
self.assertListEqual(_result, [1, 2])
self.assertTrue(res)
# Redo the repeated command
res = omni.kit.undo.redo()
self.assertListEqual(_result, [1, 2, 1, 2])
self.assertTrue(res)
# Repeat the command from C++
res = self.command_tests.test_repeat_command_from_cpp()
self.assertListEqual(_result, [1, 2, 1, 2, 1, 2])
self.assertTrue(res)
# Undo the repeated and original commands
res = omni.kit.undo.undo()
self.assertListEqual(_result, [1, 2, 1, 2])
self.assertTrue(res)
res = omni.kit.undo.undo()
self.assertListEqual(_result, [1, 2])
self.assertTrue(res)
res = omni.kit.undo.undo()
self.assertListEqual(_result, [])
self.assertTrue(res)
# Group multiple commands
omni.kit.undo.begin_group()
omni.kit.commands.execute("TestAppend", x=1, y=2)
omni.kit.commands.execute("TestAppend", x=3, y=4)
omni.kit.undo.end_group()
self.assertListEqual(_result, [1, 2, 3, 4])
# Repeat the grouped commands
res = omni.kit.undo.repeat()
self.assertListEqual(_result, [1, 2, 3, 4, 1, 2, 3, 4])
self.assertTrue(res)
# Undo the repeated grouped commands
res = omni.kit.undo.undo()
self.assertListEqual(_result, [1, 2, 3, 4])
self.assertTrue(res)
# Redo the repeated grouped commands
res = omni.kit.undo.redo()
self.assertListEqual(_result, [1, 2, 3, 4, 1, 2, 3, 4])
self.assertTrue(res)
# Repeat the grouped commands from C++
res = self.command_tests.test_repeat_command_from_cpp()
self.assertListEqual(_result, [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
self.assertTrue(res)
# Undo the repeated and original grouped commands
res = omni.kit.undo.undo()
self.assertListEqual(_result, [1, 2, 3, 4, 1, 2, 3, 4])
self.assertTrue(res)
res = omni.kit.undo.undo()
self.assertListEqual(_result, [1, 2, 3, 4])
self.assertTrue(res)
res = omni.kit.undo.undo()
self.assertListEqual(_result, [])
self.assertTrue(res)
def test_change_setting_command(self):
# Set the default value of our draggable setting
test_setting_default_value = -1
test_setting_path = "/test/some/setting"
settings = carb.settings.get_settings()
settings.set_default(test_setting_path, test_setting_default_value)
self.assertEqual(settings.get(test_setting_path), test_setting_default_value)
# Execute a change setting command
test_setting_new_value = 9
res = omni.kit.commands.execute("ChangeSetting", path=test_setting_path, value=test_setting_new_value)
self.assertEqual(settings.get(test_setting_path), test_setting_new_value)
# Verify that undoing the change setting command resets the setting to the default value
omni.kit.undo.undo()
self.assertEqual(settings.get(test_setting_path), test_setting_default_value)
def test_change_draggable_setting_command(self):
# Set the default value of our draggable setting
test_draggable_setting_default_value = -1
test_draggable_setting_path = "/test/draggable/setting"
settings = carb.settings.get_settings()
settings.set_default(test_draggable_setting_path, test_draggable_setting_default_value)
self.assertEqual(settings.get(test_draggable_setting_path), test_draggable_setting_default_value)
# Execute a change draggable setting command
test_draggable_setting_new_value = 9
res = omni.kit.commands.execute("ChangeDraggableSetting", path=test_draggable_setting_path, value=test_draggable_setting_new_value)
self.assertEqual(settings.get(test_draggable_setting_path), test_draggable_setting_new_value)
# Verify that undoing the change draggable setting command does nothing
omni.kit.undo.undo()
self.assertEqual(settings.get(test_draggable_setting_path), test_draggable_setting_new_value)
def test_last_command(self):
# Set the current and default values of a test setting
test_setting_default_value = -1
test_setting_path = "/test/some/setting"
settings = carb.settings.get_settings()
settings.set(test_setting_path, test_setting_default_value)
settings.set_default(test_setting_path, test_setting_default_value)
self.assertEqual(settings.get(test_setting_path), test_setting_default_value)
# Execute a change draggable setting command
test_setting_new_value = 9
res = omni.kit.commands.execute("ChangeDraggableSetting", path=test_setting_path, value=test_setting_new_value)
self.assertEqual(settings.get(test_setting_path), test_setting_new_value)
# Verify that the 'last command' was set
last_command_setting_path = "/crashreporter/data/lastCommand"
last_command = settings.get(last_command_setting_path)
self.assertEqual(last_command, "ChangeDraggableSetting(path=/test/some/setting,value=9)")
# Execute a change setting command
test_setting_new_value = 99
res = omni.kit.commands.execute("ChangeSetting", path=test_setting_path, value=test_setting_new_value)
self.assertEqual(settings.get(test_setting_path), test_setting_new_value)
# Verify that the 'last command' was set
last_command = settings.get(last_command_setting_path)
self.assertEqual(last_command, "ChangeSetting(path=/test/some/setting,value=99)")
| 42,395 | Python | 40.081395 | 152 | 0.625593 |
omniverse-code/kit/exts/omni.kit.widget.filebrowser/scripts/demo_filebrowser.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import sys
import omni.ui as ui
import asyncio
import omni.client
from omni.kit.mainwindow import get_main_window
from omni.kit.widget.filebrowser import *
from functools import partial
class FileBrowserView:
SERVER_TYPE_FILESYSTEM = "fileSystem"
SERVER_TYPE_NUCLEUS = "nucleus"
def __init__(self, title: str, **kwargs):
self._title = title
self._filebrowser = None
self._item_menu = None
self._server_menu = None
self._style = self._init_style()
self._layout = kwargs.get("layout", LAYOUT_DEFAULT)
self._tooltip = kwargs.get("tooltip", False)
self._allow_multi_selection = kwargs.get("allow_multi_selection", True)
def build_ui(self):
""" """
main_window = get_main_window()
self._menu_bar = main_window.get_main_menu_bar()
self._menu_bar.set_style(self._style["MenuBar"])
self._menu_bar.visible = True
options = [
("Split Panes", LAYOUT_SPLIT_PANES, False),
("Single Pane Slim", LAYOUT_SINGLE_PANE_SLIM, False),
("Single Pane Wide", LAYOUT_SINGLE_PANE_WIDE, False),
("Grid View", LAYOUT_SPLIT_PANES, True),
]
with ui.VStack(spacing=10):
with ui.HStack(height=30):
collection = ui.RadioCollection()
for option in options:
button = ui.RadioButton(text=option[0], radio_collection=collection, width=120)
button.set_clicked_fn(partial(self._build_filebrowser, option[1], option[2]))
ui.Spacer()
self._frame = ui.Frame()
self._build_filebrowser(LAYOUT_DEFAULT)
asyncio.ensure_future(self._dock_window(self._title, ui.DockPosition.SAME))
def _build_filebrowser(self, layout: int, show_grid: bool = False):
if self._filebrowser:
self._filebrowser.destroy()
with self._frame:
self._filebrowser = FileBrowserWidget(
"Omniverse",
layout=layout,
tooltip=self._tooltip,
allow_multi_selection=self._allow_multi_selection,
show_grid_view=show_grid,
mouse_pressed_fn=lambda b, item: self._on_mouse_pressed(b, item),
)
# Initialize interface with this default list of connections
self.add_connection("C:", "C:")
self.add_connection("ov-content", "omniverse://ov-content")
def add_connection(self, name: str, path: str):
asyncio.ensure_future(self._add_connection(name, path))
def _init_style(self) -> dict:
style = {
"MenuBar": {
"background_color": 0xFF23211F,
"background_selected_color": 0x664F4D43,
"color": 0xFFAAAAAA,
"border_width": 0.5,
"border_color": 0xFF8A8777,
"padding": 8,
}
}
return style
def _on_mouse_pressed(self, button: ui.Button, item: FileBrowserItem):
if button == 1:
if self._filebrowser.is_root_of_model(item):
self._show_server_menu(item)
else:
self._show_item_menu(item)
def _show_server_menu(self, item: FileBrowserItem):
if not self._server_menu:
self._server_menu = ui.Menu("server-menu")
self._server_menu.clear()
with self._server_menu:
ui.MenuItem("Connection Menu")
self._server_menu.show()
def _show_item_menu(self, item: FileBrowserItem):
if not self._item_menu:
self._item_menu = ui.Menu("item-menu")
self._item_menu.clear()
with self._item_menu:
ui.MenuItem("Item Info")
ui.Separator()
ui.MenuItem(item.name)
ui.MenuItem(item.path)
self._item_menu.show()
def _refresh_ui(self, item: FileBrowserItem = None):
if self._filebrowser:
self._filebrowser.refresh_ui(item)
# ---------------------------------------------- Event Handlers ----------------------------------------------
async def _dock_window(self, window_title: str, position: ui.DockPosition, ratio: float = 1.0):
frames = 3
while frames > 0:
if ui.Workspace.get_window(window_title):
break
frames = frames - 1
await omni.kit.app.get_app().next_update_async()
window = ui.Workspace.get_window(window_title)
dockspace = ui.Workspace.get_window("DockSpace")
if window and dockspace:
window.dock_in(dockspace, position, ratio=ratio)
window.dock_tab_bar_visible = False
async def _add_connection(self, name: str, path: str):
try:
await self._stat_path(path)
except Exception as e:
self._warn(f"{e}\n")
else:
if path.startswith("omniverse://"):
model_creator = NucleusModel
else:
model_creator = FileSystemModel
# Append the new model of desired server type
server = model_creator(name, path)
self._filebrowser.add_model_as_subtree(server)
self._refresh_ui()
async def _stat_path(self, path: str, timeout: int = 3.0) -> omni.client.ListEntry:
""" Returns stats for path if valid """
if not path:
return False, None
path = path.replace("\\", "/")
try:
result, stats = await asyncio.wait_for(omni.client.stat_async(path), timeout=timeout)
except asyncio.TimeoutError:
raise RuntimeWarning(f"Error unable to stat '{path}': Timed out after {timeout} secs.")
except Exception as e:
raise RuntimeWarning(f"Error unable to stat '{path}': {e}")
if result != omni.client.Result.OK:
raise RuntimeWarning(f"Error unable to stat '{path}': {result}")
return stats
if __name__ == "__main__":
window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR
window = ui.Window("DemoFileBrowser", width=1000, height=500, flags=window_flags)
with window.frame:
view = FileBrowserView("DemoFileBrowser")
view.build_ui()
| 6,656 | Python | 35.779005 | 114 | 0.581731 |
omniverse-code/kit/exts/omni.kit.widget.filebrowser/config/extension.toml | [package]
title = "Kit FileBrowser Widget"
version = "2.3.10"
category = "Internal"
description = "Filebrowser embeddable widget"
authors = ["NVIDIA"]
slackids = ["UQY4RMR3N"]
repository = ""
keywords = ["kit", "ui"]
readme = "docs/README.md"
changelog = "docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[dependencies]
"omni.ui" = {}
"omni.client" = {}
[[python.module]]
name = "omni.kit.widget.filebrowser"
[[python.scriptFolder]]
path = "scripts"
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
[documentation]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
| 683 | TOML | 17.486486 | 45 | 0.65593 |
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/zoom_bar.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ZoomBar"]
import carb.settings
import omni.ui as ui
from .style import UI_STYLES, ICON_PATH
# key is scale level and value is the actual scale value
SCALE_MAP = {0: 0.25, 1: 0.5, 2: 0.75, 3: 1, 4: 1.5, 5: 2.0}
class ZoomBar:
def __init__(self, **kwargs):
self._show_grid_view = kwargs.get("show_grid_view", True)
self._grid_view_scale = kwargs.get("grid_view_scale", 2)
self._on_toggle_grid_view_fn = kwargs.get("on_toggle_grid_view_fn", None)
self._on_scale_grid_view_fn = kwargs.get("on_scale_grid_view_fn", None)
settings = carb.settings.get_settings()
theme = settings.get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
self._theme = theme
self._style = UI_STYLES[theme]
self._slider = None
self._layout_button = None
self._build_ui()
# Notify any potential listeners registered through the "_on_toggle_grid_view_fn" argument that the view has
# been enabled in the initial state depicted by the resolved `self._show_grid_view` property:
self._toggle_grid_view(self._show_grid_view)
def destroy(self):
self._on_toggle_grid_view_fn = None
self._on_scale_grid_view_fn = None
self._slider = None
self._layout_button = None
def _build_ui(self):
with ui.HStack(height=0, style=self._style):
ui.Spacer()
with ui.ZStack(width=0, style=self._style, content_clipping=True):
ui.Rectangle(height=20, style_type_name_override="ZoomBar")
with ui.HStack():
ui.Spacer(width=6)
self._slider = ui.IntSlider(min=0, max=5, width=150, style=self._style["ZoomBar.Slider"])
self._slider.model.add_value_changed_fn(self._scale_grid_view)
self._layout_button = ui.Button(
image_url=self._get_layout_icon(not self._show_grid_view),
width=16,
style_type_name_override="ZoomBar.Button",
clicked_fn=lambda: self._toggle_grid_view(not self._show_grid_view),
)
ui.Spacer(width=6)
ui.Spacer(width=16)
def _get_layout_icon(self, grid_view: bool) -> str:
if grid_view:
return f"{ICON_PATH}/{self._theme}/thumbnail.svg"
else:
return f"{ICON_PATH}/{self._theme}/list.svg"
def _scale_grid_view(self, model: ui.SimpleIntModel):
scale_level = model.get_value_as_int()
scale = SCALE_MAP.get(scale_level, 2)
if self._on_scale_grid_view_fn:
self._on_scale_grid_view_fn(scale)
# If currently displaying the "Grid" View, remember the scale level so it can be rehabilitated later when
# toggling back from the "List" View, for which the scale level is set to `0`:
if self._show_grid_view:
self._grid_view_scale = scale_level
def _toggle_grid_view(self, show_grid_view: bool):
self._layout_button.image_url = self._get_layout_icon(not show_grid_view)
self._show_grid_view = show_grid_view
# If showing the "Grid" View, restore the scale level previously set. Showing the "List" View otherwise sets the
# scale level to `0`:
if show_grid_view:
self._slider.model.set_value(self._grid_view_scale)
else:
self._slider.model.set_value(0)
if self._on_toggle_grid_view_fn:
self._on_toggle_grid_view_fn(show_grid_view)
| 4,001 | Python | 42.5 | 120 | 0.615346 |
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/date_format_menu.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["DatetimeFormatMenu"]
import omni.ui as ui
import carb.settings
import omni.kit.app
from typing import Callable
from functools import partial
DATETIME_FORMAT_SETTING = "/persistent/app/datetime/format"
DATETIME_FORMATS = [
"MM/DD/YYYY",
"DD.MM.YYYY",
"DD-MM-YYYY",
"YYYY-MM-DD",
"YYYY/MM/DD",
"YYYY.MM.DD"
]
class DatetimeFormatMenu:
def __init__(
self,
value_changed_fn: Callable=None,
):
self._menu = ui.Menu()
self._menu_items = {}
self._value_changed_fn = value_changed_fn
self._update_setting = omni.kit.app.SettingChangeSubscription(
DATETIME_FORMAT_SETTING,
self._on_datetime_format_changed,
)
with self._menu:
self._build_dateformat_items()
def _on_datetime_format_changed(self, item, event_type):
if event_type == carb.settings.ChangeEventType.CHANGED:
format = carb.settings.get_settings().get(DATETIME_FORMAT_SETTING)
menu_item = self._menu_items.get(format, None)
if menu_item:
for item in self._menu_items.values():
item.checked = False
menu_item.checked = True
if self._value_changed_fn:
self._value_changed_fn()
def _build_dateformat_items(self):
def set_datetime_format(owner, format, menu_item):
for item in owner._menu_items.values():
if item != menu_item:
item.checked = False
if menu_item.checked:
if format != carb.settings.get_settings().get(DATETIME_FORMAT_SETTING):
carb.settings.get_settings().set(DATETIME_FORMAT_SETTING, format)
for format in DATETIME_FORMATS:
menu_item = ui.MenuItem(
format,
checkable=True,
checked=False,
direction=ui.Direction.RIGHT_TO_LEFT
)
menu_item.set_triggered_fn(partial(set_datetime_format, self, format, menu_item))
if format == carb.settings.get_settings().get(DATETIME_FORMAT_SETTING):
menu_item.checked = True
self._menu_items[format] = menu_item
@property
def visible(self):
return self._menu.visible
@visible.setter
def visible(self, value: bool):
self._menu.visible = value
def show_at(self, x, y):
self._menu.show_at(x, y)
def destroy(self):
"""Destructor"""
self._menu = None
self._menu_items = None
self._update_setting = None
self._value_changed_fn = None
def get_datetime_format():
format = carb.settings.get_settings().get(DATETIME_FORMAT_SETTING)
if format not in DATETIME_FORMATS:
# if not valid format, using current system format
return "%x"
return format.replace("MM", "%m").replace("DD", "%d").replace("YYYY", "%Y")
| 3,491 | Python | 32.902912 | 93 | 0.590662 |
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/view.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""
An abstract View class, subclassed by TreeView and GridView
"""
import asyncio
import threading
import omni.kit.app
from typing import Callable
from abc import abstractmethod
from .model import FileBrowserItem, FileBrowserModel
__all__ = ["FileBrowserView"]
class FileBrowserView:
def __init__(self, model: FileBrowserModel):
self._widget = None
self._visible = True
self._futures = []
# Setting the property to setup the subscription
self.model = model
self._loop = asyncio.get_event_loop()
# Enables thread-safe reads/writes to shared data
self._mutex_lock: threading.Lock = threading.Lock()
self._refresh_pending = False
@abstractmethod
def build_ui(self):
pass
@property
def model(self):
return self._model
@model.setter
def model(self, model):
self._model = model
if self._model:
self._model_subscription = self._model.subscribe_item_changed_fn(self._on_item_changed)
else:
self._model_subscription = None
self._on_model_changed(self._model)
@property
def visible(self):
return self._visible
@visible.setter
def visible(self, visible: bool):
if self._widget:
self._widget.visible = visible
self._visible = visible
def set_root(self, item: FileBrowserItem):
if self._model:
self._model.root = item
@abstractmethod
def refresh_ui(self, item: FileBrowserItem = None):
pass
def _throttled_refresh_ui(self, item: FileBrowserItem = None, callback: Callable = None, throttle_frames: int = 1):
"""
Refreshes the view. Delays the redraw to a later frame so that multiple calls to this function
are queued up and handled in one go. For example, when multiple files are copied to the current
directory, it will trigger a refresh for each file. If there are many of them, it could swamp
the render queue with unnecessary redraws. By queueing up these tasks, we can limit the redraws
to once per frame.
"""
if not self._visible:
return
self._futures = list(filter(lambda f: not f.done(), self._futures))
if threading.current_thread() is threading.main_thread():
future = asyncio.ensure_future(
self._throttled_refresh_ui_async(item, callback, throttle_frames))
else:
future = asyncio.run_coroutine_threadsafe(
self._throttled_refresh_ui_async(item, callback, throttle_frames), self._loop)
self._futures.append(future)
async def _throttled_refresh_ui_async(self, item: FileBrowserItem, callback: Callable, throttle_frames: int = 1):
# If there's already a pending redraw, then skip.
with self._mutex_lock:
if self._refresh_pending:
return
else:
self._refresh_pending = True
# NOTE: Wait a beat to absorb adjacent redraw events so that we build the grid only once.
for _ in range(throttle_frames):
await omni.kit.app.get_app().next_update_async()
if callback:
callback(item)
with self._mutex_lock:
self._refresh_pending = False
@abstractmethod
def select_and_center(self, item: FileBrowserItem):
pass
@abstractmethod
def _on_selection_changed(self, selections: [FileBrowserItem]):
pass
@abstractmethod
def destroy(self):
for future in self._futures:
future.cancel()
self._futures.clear()
self._loop = None
self._mutex_lock = None
self._refresh_pending = False
def _on_item_changed(self, model, item):
"""Called by the model when something is changed"""
pass
def _on_model_changed(self, model):
"""Called by the model when something is changed"""
pass
| 4,409 | Python | 32.157894 | 119 | 0.641415 |
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/filesystem_model.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["FileSystemItem", "FileSystemItemFactory", "FileSystemModel"]
import os
import stat
import asyncio
import omni.client
from datetime import datetime
from typing import Callable, Any
from omni import ui
from .model import FileBrowserItem, FileBrowserItemFields, FileBrowserModel
from .style import ICON_PATH
from carb import log_warn
class FileSystemItem(FileBrowserItem):
def __init__(self, path: str, fields: FileBrowserItemFields, is_folder: bool = False):
super().__init__(path, fields, is_folder=is_folder)
async def populate_async(self, callback_async: Callable, timeout: float = 10.0) -> Any:
"""
Populates current item asynchronously if not already. Overrides base method.
Args:
callback_async (Callable): Function signature is void callback(result, children: [FileBrowserItem]),
where result is an Exception type upon error.
timeout (float): Time out duration on failed server connections. Default 10.0.
Returns:
Any: Result of executing callback.
"""
result = None
if not self.populated:
if self.is_folder:
try:
with os.scandir(self.path) as it:
self.children.clear()
entries = {entry.name: entry for entry in it}
for name in sorted(entries):
entry = entries[name]
if not FileSystemItem.keep_entry(entry):
continue
self.add_child(FileSystemItemFactory.create_entry_item(entry))
except asyncio.CancelledError:
# NOTE: Return early if operation cancelled, without marking as 'populated'.
return None
except PermissionError as e:
log_warn(f"Can't list files. Permission denied for {self.path}")
result = e
except Exception as e:
result = e
# NOTE: Mark this item populated even when there's an error so we don't repeatedly try.
self.populated = True
if callback_async:
try:
return await callback_async(result, self.children)
except asyncio.CancelledError:
return None
else:
return result
def on_list_change_event(self, event: omni.client.ListEvent, entry: omni.client.ListEntry) -> bool:
"""
Handles ListEvent changes, should update this item's children list with the corresponding ListEntry.
Args:
event (:obj:`omni.client.ListEvent`): One of of {UNKNOWN, CREATED, UPDATED, DELETED, METADATA, LOCKED, UNLOCKED}.
entry (:obj:`omni.client.ListEntry`): Updated entry as defined by omni.client.
"""
if not entry:
return False
item_changed = False
child_name = entry.relative_path
child_name = child_name[:-1] if child_name.endswith("/") else child_name
full_path = f"{self.path}/{entry.relative_path}"
if event == omni.client.ListEvent.CREATED:
if not child_name in self.children:
item_changed = True
self.add_child(FileSystemItemFactory.create_omni_entry_item(entry, full_path))
elif event == omni.client.ListEvent.DELETED:
self.del_child(child_name)
item_changed = True
elif event == omni.client.ListEvent.UPDATED:
child = self.children.get(child_name)
if child:
# Update file size
size_model = child.get_subitem_model(2)
size_model.set_value(FileBrowserItem.size_as_string(entry.size))
return item_changed
@staticmethod
def keep_entry(entry: os.DirEntry) -> bool:
if os.name == "nt":
# On Windows, test for hidden directories & files
try:
file_attrs = entry.stat().st_file_attributes
except:
return False
if file_attrs & stat.FILE_ATTRIBUTE_SYSTEM:
return False
elif os.name == "posix":
if entry.is_symlink():
try:
entry.stat()
except:
# NOTE: What accounts for the return value here?
return False
return True
@property
def readable(self) -> bool:
return (self._fields.permissions & omni.client.AccessFlags.READ) > 0
@property
def writeable(self) -> bool:
return (self._fields.permissions & omni.client.AccessFlags.WRITE) > 0
class FileSystemItemFactory:
@staticmethod
def create_group_item(name: str, path: str) -> FileSystemItem:
if not name:
return None
access = omni.client.AccessFlags.READ | omni.client.AccessFlags.WRITE
fields = FileBrowserItemFields(name, datetime.now(), 0, access)
item = FileSystemItem(path, fields, is_folder=True)
item._models = (ui.SimpleStringModel(item.name), datetime.now(), ui.SimpleStringModel(""))
return item
@staticmethod
def create_entry_item(entry: os.DirEntry) -> FileSystemItem:
if not entry:
return None
modified_time = datetime.fromtimestamp(entry.stat().st_mtime)
stats = entry.stat()
# OM-73238 Translate system access flags to omni.client flags
access = 0
if entry.stat().st_mode & stat.S_IRUSR:
access |= omni.client.AccessFlags.READ
if entry.stat().st_mode & stat.S_IWUSR:
access |= omni.client.AccessFlags.WRITE
fields = FileBrowserItemFields(entry.name, modified_time, stats.st_size, access)
item = FileSystemItem(entry.path, fields, is_folder=entry.is_dir())
size_model = ui.SimpleStringModel(FileBrowserItem.size_as_string(entry.stat().st_size))
item._models = (ui.SimpleStringModel(item.name), modified_time, size_model)
return item
@staticmethod
def create_omni_entry_item(entry: omni.client.ListEntry, path: str) -> FileSystemItem:
if not entry:
return None
name = entry.relative_path
name = name[:-1] if name.endswith("/") else name
modified_time = entry.modified_time
fields = FileBrowserItemFields(name, modified_time, entry.size, entry.access)
is_folder = (entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN) > 0
item = FileSystemItem(path, fields, is_folder=is_folder)
size_model = ui.SimpleStringModel(FileBrowserItem.size_as_string(entry.size))
item._models = (ui.SimpleStringModel(item.name), modified_time, size_model)
return item
class FileSystemModel(FileBrowserModel):
"""
A Filebrowser model class for navigating a the local filesystem in a tree view. Sub-classed from
:obj:`FileBrowserModel`.
Args:
name (str): Name of root item..
root_path (str): Root path. If None, then create empty model. Default "C:".
Keyword Args:
drop_fn (Callable): Function called to handle drag-n-drops. Function signature:
void drop_fn(dst_item: :obj:`FileBrowserItem`, src_item: :obj:`FileBrowserItem`)
filter_fn (Callable): This handler should return True if the given tree view item is visible,
False otherwise. Function signature: bool filter_fn(item: :obj:`FileBrowserItem`)
sort_by_field (str): Name of column by which to sort items in the same folder. Default "name".
sort_ascending (bool): Sort in ascending order. Default True.
"""
def __init__(self, name: str, root_path: str = "C:", **kwargs):
import carb.settings
super().__init__(**kwargs)
if not root_path:
return
if not root_path.endswith("/"):
root_path += "/"
self._root = FileSystemItemFactory.create_group_item(name, root_path)
theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
self._root.icon = f"{ICON_PATH}/{theme}/hdd.svg"
| 8,628 | Python | 40.68599 | 125 | 0.617177 |
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/style.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
from pathlib import Path
CURRENT_PATH = Path(__file__).parent.absolute()
ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("icons")
THUMBNAIL_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data").joinpath("thumbnails")
UI_STYLES = {}
UI_STYLES["NvidiaLight"] = {
"Rectangle::Splitter": {"background_color": 0xFFE0E0E0, "margin_width": 2},
"Rectangle::Splitter:hovered": {"background_color": 0xFFB0703B},
"Rectangle::Splitter:pressed": {"background_color": 0xFFB0703B},
"Splitter": {"background_color": 0xFFE0E0E0, "margin_width": 2},
"TreeView": {
"background_color": 0xFF535354,
"background_selected_color": 0xFF6E6E6E,
"secondary_color": 0xFFACACAC,
},
"TreeView:hovered": {"background_color": 0xFF6E6E6E},
"TreeView:selected": {"background_color": 0xFFBEBBAE},
"TreeView.Column": {"background_color": 0x0, "color": 0xFFD6D6D6, "margin": 0},
"TreeView.Header": {
"background_color": 0xFF535354,
"color": 0xFFD6D6D6,
"border_color": 0xFF707070,
"border_width": 0.5,
},
"TreeView.Header::name": {"margin": 3, "alignment": ui.Alignment.LEFT},
"TreeView.Header::date": {"margin": 3, "alignment": ui.Alignment.CENTER},
"TreeView.Header::size": {"margin": 3, "alignment": ui.Alignment.RIGHT},
"TreeView.Icon:selected": {"color": 0xFF535354},
"TreeView.Header.Icon": {"color": 0xFF8A8777},
"TreeView.Icon::default": {"color": 0xFF8A8777},
"TreeView.Icon::file": {"color": 0xFF8A8777},
"TreeView.Item": {"color": 0xFFD6D6D6},
"TreeView.Item:selected": {"color": 0xFF2A2825},
"TreeView.ScrollingFrame": {"background_color": 0xFF535354, "secondary_color": 0xFFE0E0E0},
"GridView.ScrollingFrame": {"background_color": 0xFF535354, "secondary_color": 0xFFE0E0E0},
"GridView.Grid": {"background_color": 0x0, "margin_width": 10},
"Card": {"background_color": 0x0, "margin": 8},
"Card:hovered": {"background_color": 0xFF6E6E6E, "border_color": 0xFF3A3A3A, "border_width": 0},
"Card:pressed": {"background_color": 0xFF6E6E6E, "border_color": 0xFF3A3A3A, "border_width": 0},
"Card:selected": {"background_color": 0xFFBEBBAE, "border_color": 0xFF8A8777, "border_width": 0},
"Card.Image": {
"background_color": 0xFFC9C9C9,
"color": 0xFFFFFFFF,
"corner_flag": ui.CornerFlag.TOP,
"alignment": ui.Alignment.CENTER,
"margin": 8,
},
"Card.Badge": {"background_color": 0xFFC9C9C9, "color": 0xFFFFFFFF},
"Card.Badge::shadow": {"background_color": 0xFFC9C9C9, "color": 0xDD444444},
"Card.Label": {
"background_color": 0xFFC9C9C9,
"color": 0xFFD6D6D6,
"font_size": 12,
"alignment": ui.Alignment.CENTER_TOP,
"margin_width": 8,
"margin_height": 2,
},
"Card.Label:checked": {"color": 0xFF23211F},
"ZoomBar": {"background_color": 0x0, "border_radius": 2},
"ZoomBar.Slider": {
"draw_mode": ui.SliderDrawMode.HANDLE,
"background_color": 0xFF23211F,
"secondary_color": 0xFF9D9D9D,
"color": 0x0,
"alignment": ui.Alignment.CENTER,
"padding": 0,
"margin": 5,
"font_size": 8,
},
"ZoomBar.Button": {"background_color": 0x0, "margin": 0, "padding": 0},
"ZoomBar.Button.Image": {"color": 0xFFFFFFFF, "alignment": ui.Alignment.CENTER},
"Recycle.Button.Label": {"color": 0xFF9E9E9E, "alignment": ui.Alignment.LEFT_CENTER},
"Recycle.Button.Image": {"image_url": "resources/glyphs/trash.svg", "background_color": 0xFF535354, "alignment": ui.Alignment.CENTER},
"Recycle.Button:hovered": {"background_color": 0xFF3A3A3A},
"RecycleFrame.Button": {"background_color": 0xFF23211F, "margin": 0, "padding": 0},
"RecycleFrame.Button:hovered": {"background_color": 0xFF3A3A3A},
"RecycleFrame.Button:checked": {"background_color": 0xFF3A3A3A},
}
UI_STYLES["NvidiaDark"] = {
"Splitter": {"background_color": 0x0, "margin_width": 0},
"Splitter:hovered": {"background_color": 0xFFB0703B},
"Splitter:pressed": {"background_color": 0xFFB0703B},
"TreeView.ScrollingFrame": {"background_color": 0xFF23211F},
"TreeView": {"background_color": 0xFF23211F, "background_selected_color": 0x663A3A3A},
"TreeView:selected": {"background_color": 0xFF8A8777},
"TreeView.Column": {"background_color": 0x0, "color": 0xFFADAC9F, "margin": 0},
"TreeView.Header": {"background_color": 0xFF343432, "color": 0xFF9E9E9E},
"TreeView.Icon": {"color": 0xFFFFFFFF, "padding": 0},
"TreeView.Icon::Cut": {"background_color": 0x0, "color": 0x88FFFFFF},
"TreeView.Icon::Cut:selected": {"background_color": 0x0, "color": 0x88FFFFFF},
"TreeView.Icon::shadow": {"background_color": 0x0, "color": 0xDD444444},
"TreeView.Icon::expand": {"color": 0xFFFFFFFF},
"TreeView.Icon:selected": {"color": 0xFFFFFFFF},
"TreeView.Item": {"color": 0xFF9E9E9E, "alignment": ui.Alignment.LEFT_CENTER},
"TreeView.Item:selected": {"color": 0xFF2A2825},
"TreeView.Item::Cut": {"color": 0x889E9E9E, "alignment": ui.Alignment.LEFT_CENTER},
"TreeView.Item::Cut:selected": {"color": 0x882A2825},
"GridView.ScrollingFrame": {"background_color": 0xFF23211F},
"GridView.Grid": {"background_color": 0x0, "margin_width": 10},
"Card": {"background_color": 0x0, "margin": 8},
"Card:hovered": {"background_color": 0xFF3A3A3A, "border_color": 0xFF3A3A3A, "border_width": 2},
"Card:pressed": {"background_color": 0xFF3A3A3A, "border_color": 0xFF42413F, "border_width": 2},
"Card:selected": {"background_color": 0xFF8A8777, "border_color": 0xFF8A8777, "border_width": 2},
"Card.Image": {
"background_color": 0x0,
"color": 0xFFFFFFFF,
"corner_flag": ui.CornerFlag.TOP,
"alignment": ui.Alignment.CENTER,
"margin": 8,
},
"Card.Image::Cut": {"color": 0x88FFFFFF},
"Card.Badge": {"background_color": 0x0, "color": 0xFFFFFFFF},
"Card.Badge::shadow": {"background_color": 0x0, "color": 0xDD444444},
"Card.Label": {
"background_color": 0x0,
"color": 0xFF9E9E9E,
"alignment": ui.Alignment.CENTER_TOP,
"margin_width": 8,
"margin_height": 2,
},
"Card.Label::Cut": {"color": 0x889E9E9E},
"Card.Label:checked": {"color": 0xFF23211F},
"Card.Label::Cut:checked": {"color": 0x8823211F},
"ZoomBar": {"background_color": 0xFF454545, "border_radius": 2},
"ZoomBar.Slider": {
"draw_mode": ui.SliderDrawMode.HANDLE,
"background_color": 0xDD23211F,
"secondary_color": 0xFF9E9E9E,
"color": 0x0,
"alignment": ui.Alignment.CENTER,
"padding": 0,
"margin": 3,
},
"ZoomBar.Button": {"background_color": 0x0, "margin": 0, "padding": 0},
"ZoomBar.Button.Image": {"color": 0xFFFFFFFF, "alignment": ui.Alignment.CENTER},
"Recycle.Button.Label": {"color": 0xFF9E9E9E, "alignment": ui.Alignment.LEFT_CENTER},
"Recycle.Button": {"background_color": 0x0, "margin": 0, "padding": 0},
"Recycle.Button.Image": {"image_url": "resources/glyphs/trash.svg","background_color": 0x0, "color": 0xFF9E9E9E, "alignment": ui.Alignment.CENTER},
"Recycle.Button.Image:hovered": {"background_color": 0x0,"color": 0xFFFFFFFF},
"Recycle.Button.Image:checked": {"background_color": 0x0,"color": 0xFFFFFFFF},
"Recycle.Rectangle": {"background_color": 0xFF23211F, "margin": 0, "padding": 0},
"RecycleFrame.Button": {"background_color": 0x0, "margin": 0, "padding": 0},
"RecycleFrame.Button:hovered": {"background_color": 0xFF3A3A3A},
"RecycleFrame.Button:checked": {"background_color": 0xFF3A3A3A},
"RecycleFrame.Button.Label": {"alignment": ui.Alignment.LEFT},
"RecycleView.Frame": {"background_color": 0x0},
}
| 8,234 | Python | 50.149068 | 151 | 0.651202 |
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/tree_view.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""
A generic Tree View Widget for File Systems
"""
import asyncio
import carb
from omni import ui
from typing import List
from typing import Tuple
from functools import partial
from datetime import datetime
from carb import log_warn
from .view import FileBrowserView
from .model import FileBrowserItem, FileBrowserItemFields, FileBrowserModel
from .style import UI_STYLES, ICON_PATH
from .abstract_column_delegate import ColumnItem
from .column_delegate_registry import ColumnDelegateRegistry
from .date_format_menu import DatetimeFormatMenu
from . import ALERT_WARNING, ALERT_ERROR
from .clipboard import is_path_cut
__all__ = ["AwaitWithFrame", "FileBrowserTreeView", "FileBrowserTreeViewDelegate"]
class AwaitWithFrame:
"""
A future-like object that runs the given future and makes sure it's
always in the given frame's scope. It allows for creating widgets
asynchronously.
"""
def __init__(self, frame: ui.Frame, future: asyncio.Future):
self._frame = frame
self._future = future
def __await__(self):
# create an iterator object from that iterable
iter_obj = iter(self._future.__await__())
# infinite loop
while True:
try:
with self._frame:
yield next(iter_obj)
except StopIteration:
break
except Exception as e:
log_warn(f"Error rendering frame: {str(e)}")
break
self._frame = None
self._future = None
class FileBrowserTreeView(FileBrowserView):
def __init__(self, model: FileBrowserModel, **kwargs):
import carb.settings
self._tree_view = None
self._delegate = None
super().__init__(model)
self._headers = FileBrowserItemFields._fields
theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
use_default_style = carb.settings.get_settings().get_as_string("/persistent/app/window/useDefaultStyle") or False
if use_default_style:
self._style = {}
else:
self._style = UI_STYLES[theme]
self._root_visible = kwargs.get("root_visible", True)
self._header_visible = kwargs.get("header_visible", True)
self._allow_multi_selection = kwargs.get("allow_multi_selection", True)
self._selection_changed_fn = kwargs.get("selection_changed_fn", None)
self._mouse_pressed_fn = kwargs.get("mouse_pressed_fn", None)
self._mouse_double_clicked_fn = kwargs.get("mouse_double_clicked_fn", None)
self._treeview_identifier = kwargs.get('treeview_identifier', None)
# Callback when the tag registry is changed
self._column_delegate_sub = ColumnDelegateRegistry().subscribe_delegate_changed(
self._on_column_delegate_changed
)
kwargs["mouse_pressed_fn"] = self._on_mouse_pressed
kwargs["mouse_double_clicked_fn"] = self._on_mouse_double_clicked
kwargs["column_clicked_fn"] = lambda column_id: self._on_column_clicked(column_id)
kwargs["datetime_format_changed_fn"] = self._on_datetime_format_changed
kwargs["sort_by_column"] = self._headers.index(self._model.sort_by_field)
kwargs["sort_ascending"] = self._model.sort_ascending
kwargs["builtin_column_count"] = self._model.builtin_column_count
self._delegate = FileBrowserTreeViewDelegate(self._headers, theme, **kwargs)
self._widget = ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
mouse_pressed_fn=partial(self._on_mouse_pressed, None),
mouse_double_clicked_fn=partial(self._on_mouse_double_clicked, None),
style_type_name_override="TreeView.ScrollingFrame",
)
def build_ui(self):
# Tree View
with self._widget:
selection_changed_fn = lambda selections: self._on_selection_changed(selections)
self._tree_view = ui.TreeView(
self._model,
delegate=self._delegate,
root_visible=self._root_visible,
header_visible=self._header_visible,
selection_changed_fn=selection_changed_fn,
columns_resizable=True,
)
if self._treeview_identifier:
self._tree_view.identifier = self._treeview_identifier
# It should set the column widths and pass tag delegated to the main delegate
self._on_column_delegate_changed()
@property
def tree_view(self):
return self._tree_view
@property
def selections(self):
if self._tree_view:
return self._tree_view.selection
return []
def refresh_ui(self, item: FileBrowserItem = None):
"""Throttle the refreshes so that the UI can keep up with multiple refresh directives in succession."""
def update_view(item: FileBrowserItem):
if self._tree_view:
self._tree_view.dirty_widgets()
if self._model:
# NOTE: The following action is not publicized but is required for a proper redraw
self._model._item_changed(item)
self._throttled_refresh_ui(item=item, callback=update_view, throttle_frames=2)
def is_expanded(self, item: FileBrowserItem) -> bool:
if self._tree_view and item:
return self._tree_view.is_expanded(item)
return False
def set_expanded(self, item: FileBrowserItem, expanded: bool, recursive: bool = False):
"""
Sets the expansion state of the given item.
Args:
item (:obj:`FileBrowserItem`): The item to effect.
expanded (bool): True to expand, False to collapse.
recursive (bool): Apply state recursively to descendent nodes. Default False.
"""
if self._tree_view and item:
self._tree_view.set_expanded(item, expanded, recursive)
def select_and_center(self, item: FileBrowserItem):
if not self._visible:
return
item = item or self._model.root
if not item:
return
def set_expanded_recursive(item: FileBrowserItem):
if not item:
return
set_expanded_recursive(item.parent)
self.set_expanded(item, True)
set_expanded_recursive(item)
self._tree_view.selection = [item]
self.refresh_ui()
def _on_mouse_pressed(self, item: FileBrowserItem, x, y, button, key_mod):
if self._mouse_pressed_fn:
self._mouse_pressed_fn(button, key_mod, item, x=x, y=y)
def _on_mouse_double_clicked(self, item: FileBrowserItem, x, y, button, key_mod):
if self._mouse_double_clicked_fn:
self._mouse_double_clicked_fn(button, key_mod, item, x=x, y=y)
def _on_selection_changed(self, selections: [FileBrowserItem]):
if not self._allow_multi_selection:
if selections:
selections = selections[-1:]
self._tree_view.selection = selections
if self._model:
self._model.drag_mime_data = [sel.path for sel in selections]
if self._selection_changed_fn:
self._selection_changed_fn(selections)
def _on_column_clicked(self, column_id: int):
column_id = min(column_id, len(FileBrowserItemFields._fields) - 1)
if column_id == self._delegate.sort_by_column:
self._delegate.sort_ascending = not self._delegate.sort_ascending
else:
self._delegate.sort_by_column = column_id
if self._model:
self._model.sort_by_field = self._headers[column_id]
self._model.sort_ascending = self._delegate.sort_ascending
self.refresh_ui()
def _on_datetime_format_changed(self):
self.refresh_ui()
def _on_item_changed(self, model, item):
"""Called by the model when something is changed"""
if self._delegate and item is None:
self._delegate.clear_futures()
def _on_model_changed(self, model):
"""Called by super when the model is changed"""
if model and self._tree_view:
self._tree_view.model = model
if self._delegate:
self._delegate.clear_futures()
def _on_column_delegate_changed(self):
"""Called by ColumnDelegateRegistry"""
# Single column should fill all available space
if not self._model.single_column:
column_delegate_names = ColumnDelegateRegistry().get_column_delegate_names()
column_delegate_types = [ColumnDelegateRegistry().get_column_delegate(name) for name in column_delegate_names]
# Create the tag delegates
column_delegates = [delegate_type() for delegate_type in column_delegate_types]
self._delegate.set_column_delegates(column_delegates)
# Set column widths
# OM-30768: Make file-name dominant and push with left list view separator
self._tree_view.column_widths = [ui.Fraction(.75), ui.Fraction(0.15), ui.Fraction(0.1)] + [
d.initial_width for d in column_delegates
]
else:
self._tree_view.column_widths = [ui.Fraction(1)]
# Update the widget
self._model._item_changed(None)
def scroll_top(self):
"""Scrolls the widget to top"""
if self._widget:
# Scroll to top upon refresh
self._widget.scroll_y = 0.0
def destroy(self):
super().destroy()
if self._model:
self._model.destroy()
self._model = None
if self._tree_view:
self._tree_view.destroy()
self._tree_view = None
if self._widget:
self._widget.destroy()
self._widget = None
if self._delegate:
self._delegate.destroy()
self._delegate = None
self._headers = None
self._style = None
self._selection_changed_fn = None
self._mouse_pressed_fn = None
self._mouse_double_clicked_fn = None
self._column_delegate_sub = None
class FileBrowserTreeViewDelegate(ui.AbstractItemDelegate):
def __init__(self, headers: Tuple, theme: str, **kwargs):
super().__init__()
self._headers = headers
self._theme = theme
use_default_style = carb.settings.get_settings().get_as_string("/persistent/app/window/useDefaultStyle") or False
if use_default_style:
self._style = {}
else:
self._style = UI_STYLES[theme]
self._hide_files = not kwargs.get("files_visible", True)
self._tooltip = kwargs.get("tooltip", False)
self._mouse_pressed_fn = kwargs.get("mouse_pressed_fn", None)
self._mouse_double_clicked_fn = kwargs.get("mouse_double_clicked_fn", None)
self._column_clicked_fn = kwargs.get("column_clicked_fn", None)
self._datetime_format_changed_fn = kwargs.get("datetime_format_changed_fn", None)
self._sort_by_column = kwargs.get("sort_by_column", 0)
self._sort_ascending = kwargs.get("sort_ascending", True)
self._builtin_column_count = kwargs.get("builtin_column_count", 1)
self._column_delegates = []
self._icon_provider = kwargs.get("icon_provider", None)
# The futures that are created by column delegates. We need to store
# them to cancel when the model is changed.
self._column_futures: List["Future"] = []
self._date_format_menu = None
def destroy(self):
self.clear_futures()
self._headers = None
self._style = None
self._mouse_pressed_fn = None
self._mouse_double_clicked_fn = None
self._column_clicked_fn = None
self._column_delegates = None
self._icon_provider = None
if self._date_format_menu:
self._date_format_menu.destroy()
self._date_format_menu = None
def clear_futures(self):
"""Stop and destroy all working futures"""
for future in self._column_futures:
if not future.done():
future.cancel()
self._column_futures = []
@property
def sort_by_column(self) -> int:
return self._sort_by_column
@sort_by_column.setter
def sort_by_column(self, column_id: int):
self._sort_by_column = column_id
@property
def sort_ascending(self) -> bool:
return self._sort_ascending
@sort_ascending.setter
def sort_ascending(self, value: bool):
self._sort_ascending = value
def _on_date_format_clicked(self):
if not self._date_format_menu:
self._date_format_menu = DatetimeFormatMenu(self._datetime_format_changed_fn)
self._date_format_menu.visible = True
self._date_format_menu.show_at(
self._date_format_button.screen_position_x,
self._date_format_button.screen_position_y+30
)
def build_header(self, column_id: int):
if column_id >= self._builtin_column_count:
# Additional columns from the extensions.
self._column_delegates[column_id - self._builtin_column_count].build_header()
return
def on_column_clicked(column_id):
if self._column_clicked_fn:
self._column_clicked_fn(column_id)
with ui.ZStack(style=self._style):
with ui.HStack():
ui.Spacer(width=4)
ui.Label(self._headers[column_id].capitalize(), height=20, style_type_name_override="TreeView.Header")
# Invisible click area fills entire header frame
if self._headers[column_id] == "date":
with ui.HStack():
button = ui.Button(" ", height=20, style_type_name_override="TreeView.Column")
self._date_format_button = ui.Button(" ", width=30, height=20, style_type_name_override="TreeView.Column")
self._date_format_button.set_clicked_fn(lambda: self._on_date_format_clicked())
else:
button = ui.Button(" ", height=20, style_type_name_override="TreeView.Column")
if column_id == self._sort_by_column:
with ui.HStack():
ui.Spacer()
icon = (
f"{ICON_PATH}/{self._theme}/arrow_up.svg"
if self._sort_ascending
else f"{ICON_PATH}/{self._theme}/arrow_down.svg"
)
ui.ImageWithProvider(icon, width=30, style_type_name_override="TreeView.Column")
if self._headers[column_id] == "date":
icon_date = (
f"{ICON_PATH}/{self._theme}/date_format.svg"
)
ui.ImageWithProvider(icon_date, width=30, style_type_name_override="TreeView.Column")
elif self._headers[column_id] == "date":
with ui.HStack():
ui.Spacer()
icon_date = (
f"{ICON_PATH}/{self._theme}/date_format.svg"
)
ui.ImageWithProvider(icon_date, width=30, style_type_name_override="TreeView.Column")
button.set_clicked_fn(lambda: on_column_clicked(column_id))
def build_branch(self, model: FileBrowserModel, item: FileBrowserItem, column_id: int, level: int, expanded: bool):
"""Create a branch widget that opens or closes subtree"""
def get_branch_icon(item: FileBrowserItem, expanded: bool) -> Tuple[str, str]:
icon = "minus.svg" if expanded else "plus.svg"
tooltip = ""
if item.alert:
sev, tooltip = item.alert
if sev == ALERT_WARNING:
icon = "warn.svg"
elif sev == ALERT_ERROR:
icon = "error.svg"
else:
icon = "info.svg"
return f"{ICON_PATH}/{self._theme}/{icon}", tooltip
item_or_root = item or model.root
if not item_or_root or not isinstance(item_or_root, FileBrowserItem):
# Makes sure item has expected type, else may crash the process (See OM-34661).
return
if column_id == 0:
with ui.HStack(width=20 * (level + 1), height=0):
ui.Spacer()
# don't create branch icon for unexpandable items
if item_or_root.is_folder and item_or_root.expandable:
# Draw the +/- icon
icon, tooltip = get_branch_icon(item_or_root, expanded)
ui.ImageWithProvider(
icon, tooltip=tooltip, name="expand", width=10, height=10, style_type_name_override="TreeView.Icon"
)
def build_widget(self, model: FileBrowserModel, item: FileBrowserItem, column_id: int, level: int, expanded: bool):
"""Create a widget per item"""
item_or_root = item or model.root
if not item_or_root or not isinstance(item_or_root, FileBrowserItem):
# Makes sure item has expected type, else may crash the process (See OM-34661).
return
if column_id >= self._builtin_column_count:
# Additional columns from the extensions.
# Async run the delegate. The widget can be created later.
future = self._column_delegates[column_id - self._builtin_column_count].build_widget(
ColumnItem(item_or_root.path)
)
self._column_futures.append(asyncio.ensure_future(AwaitWithFrame(ui.Frame(), future)))
return
if self._hide_files and not item_or_root.is_folder and item_or_root.hideable:
# Don't show file items
return
value_model = model.get_item_value_model(item_or_root, column_id)
if not value_model:
return
style_variant = self._get_style_variant(item_or_root)
# File Name Column
if column_id == 0:
def mouse_pressed_fn(item: FileBrowserItem, *args):
if self._mouse_pressed_fn:
self._mouse_pressed_fn(item, *args)
def mouse_double_clicked_fn(item: FileBrowserItem, *args):
if self._mouse_double_clicked_fn:
self._mouse_double_clicked_fn(item, *args)
with ui.HStack(height=20,
mouse_pressed_fn=partial(mouse_pressed_fn, item_or_root),
mouse_double_clicked_fn=partial(mouse_double_clicked_fn, item_or_root)):
ui.Spacer(width=2)
self._draw_item_icon(item_or_root, expanded)
ui.Spacer(width=5)
ui.Label(
value_model.get_value_as_string(),
tooltip=item_or_root.path if self._tooltip else "",
tooltip_offset=22,
style_type_name_override="TreeView.Item",
name=style_variant,
)
# Date Column
elif column_id == 1:
with ui.HStack():
ui.Spacer(width=4)
if isinstance(value_model, datetime):
ui.Label(
FileBrowserItem.datetime_as_string(value_model),
style_type_name_override="TreeView.Item", name=style_variant)
elif isinstance(value_model, str):
ui.Label(value_model.get_value_as_string(), style_type_name_override="TreeView.Item", name=style_variant)
# Size Column
elif column_id == 2:
if not item_or_root.is_folder:
with ui.HStack():
ui.Spacer(width=4)
ui.Label(value_model.get_value_as_string(), style_type_name_override="TreeView.Item", name=style_variant)
def set_column_delegates(self, delegates):
"""Add custom columns"""
self._column_delegates = delegates
def _get_style_variant(self, item: FileBrowserItem):
return "Cut" if is_path_cut(item.path) else ""
def _draw_item_icon(self, item: FileBrowserItem, expanded: bool):
if not item:
return
style_variant = self._get_style_variant(item)
icon = item.icon
if not icon and self._icon_provider:
icon = self._icon_provider(item, expanded)
if not icon:
if item and not item.is_folder:
icon = f"{ICON_PATH}/{self._theme}/file.svg"
else:
icon = (
f"{ICON_PATH}/{self._theme}/folder_open.svg"
if expanded
else f"{ICON_PATH}/{self._theme}/folder.svg"
)
with ui.ZStack(width=0):
if icon:
# Draw the icon
with ui.HStack():
ui.Spacer(width=4)
ui.ImageWithProvider(icon, width=18, height=18, style_type_name_override="TreeView.Icon", name=style_variant)
if not item.writeable:
# Draw the lock
lock_icon = f"{ICON_PATH}/{self._theme}/lock.svg"
with ui.Placer(stable_size=True, offset_x=-1, offset_y=1):
with ui.HStack():
ui.ImageWithProvider(lock_icon, width=17, height=17, style_type_name_override="TreeView.Icon", name="shadow")
ui.Spacer()
with ui.Placer(stable_size=True, offset_x=-2, offset_y=1):
with ui.HStack():
ui.ImageWithProvider(lock_icon, width=17, height=17, style_type_name_override="TreeView.Icon", name=style_variant)
ui.Spacer()
| 22,351 | Python | 40.623836 | 138 | 0.588296 |
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/grid_view.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""
A generic GridView Widget for File Systems
"""
__all__ = ["FileBrowserGridView", "FileBrowserGridViewDelegate"]
import asyncio
import carb
import omni.kit.app
from typing import Dict, List, Optional, Callable
from functools import partial
from omni import ui
from carb import events, log_warn
from carb.input import KEYBOARD_MODIFIER_FLAG_CONTROL, KEYBOARD_MODIFIER_FLAG_SHIFT
from .view import FileBrowserView
from .model import FileBrowserItem, FileBrowserModel, FileBrowserUdimItem
from .style import UI_STYLES
from .card import FileBrowserItemCard
from .thumbnails import find_thumbnails_for_files_async
from . import THUMBNAILS_GENERATED_EVENT
from .clipboard import is_path_cut
class FileBrowserGridView(FileBrowserView):
def __init__(self, model: FileBrowserModel, **kwargs):
self._delegate = None
super().__init__(model)
theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
use_default_style = carb.settings.get_settings().get_as_string("/persistent/app/window/useDefaultStyle") or False
if use_default_style:
self._style = {}
else:
self._style = UI_STYLES[theme]
self._allow_multi_selection = kwargs.get("allow_multi_selection", True)
self._selection_changed_fn = kwargs.get("selection_changed_fn", None)
self._widget = ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
style_type_name_override="GridView.ScrollingFrame",
)
self._delegate = FileBrowserGridViewDelegate(self._widget, theme, **kwargs)
self.build_ui()
@property
def selections(self):
if self._delegate:
return self._delegate.selections
return []
@selections.setter
def selections(self, selections):
if self._delegate:
self._delegate.selections = selections or []
def build_ui(self, restore_selections: Optional[List[FileBrowserItem]] = None):
if self._delegate:
self._delegate.build_grid(self.model)
self.refresh_ui(selections=restore_selections)
def scale_view(self, scale: float):
if self._delegate:
self._delegate.scale = scale
def refresh_ui(self, item: Optional[FileBrowserItem] = None, selections: Optional[List[FileBrowserItem]] = None):
"""Throttle the refreshes so that the UI can keep up with multiple refresh directives in succession."""
if not self._delegate:
return
def apply_selections(selections):
self.selections = selections
def refresh_ui_callback(selections):
self._delegate.update_grid(self.model)
# OM-70157: Switching between List/different Grid View sizes shouldn't reset user selections
if selections:
self.select_and_center(selections[0], callback=lambda _: apply_selections(selections))
self._throttled_refresh_ui(
item=item,
callback=lambda _: refresh_ui_callback(selections),
throttle_frames=2)
def select_and_center(self, item: FileBrowserItem, callback: Optional[Callable[[FileBrowserItem], None]] = None):
if not self._visible or not item:
return
self.selections = [item]
# OM-70154: add the ability to center the selected item in file browser grid view
# calculate the scroll ratio by item index
items = self.model.get_item_children(None)
# This should not happen, but add it here as a fail-safe
if item not in items:
carb.log_warn(f"Failed to select and center item [ {item.path} ] in file browser grid view.")
return
item_index = items.index(item)
scroll_ratio = float((item_index + 1) / len(items))
asyncio.ensure_future(
self._delegate.center_selection_async(
item, scroll_frame=self._widget, scroll_ratio=scroll_ratio, refresh_interval=3, callback=callback))
def _on_selection_changed(self, selections: List[FileBrowserItem]):
if not self._allow_multi_selection:
if selections:
selections = selections[-1:]
self._widget.selection = selections
if self._selection_changed_fn:
self._selection_changed_fn(selections)
def _on_item_changed(self, model, _):
self.refresh_ui()
def _on_model_changed(self, model):
"""Called by super when the model is changed"""
self.build_ui()
def scroll_top(self):
"""Scrolls the widget to top"""
# Scroll to top upon refresh
self._widget.scroll_y = 0.0
def destroy(self):
super().destroy()
if self._delegate:
self._delegate.destroy()
self._delegate = None
if self._widget:
self._widget.destroy()
self._widget = None
self._style = None
self._selection_changed_fn = None
class FileBrowserGridViewDelegate:
def __init__(self, widget: ui.Widget, theme: str, **kwargs):
self._widget: ui.Widget = widget
self._grid: ui.VGrid = None
self._cards: Dict[str, FileBrowserItemCard] = {}
self._card_paths: List[str] = []
self._custom_thumbnails: Dict[str, str] = {}
self._selections = []
self._pending_selections = []
self._style = UI_STYLES[theme]
self._tooltip = kwargs.get("tooltip", False)
self._mouse_pressed_fn = kwargs.get("mouse_pressed_fn", None)
self._mouse_double_clicked_fn = kwargs.get("mouse_double_clicked_fn", None)
self._selection_changed_fn = kwargs.get("selection_changed_fn", None)
self._drop_fn = kwargs.get("drop_fn", None)
self._thumbnail_provider = kwargs.get("thumbnail_provider", None)
self._badges_provider = kwargs.get("badges_provider", None)
self._treeview_identifier = kwargs.get("treeview_identifier", None)
self._testing = kwargs.get("testing", False)
self._card_width = 120
self._card_height = 120
self._scale = 1
self._update_grid_future = None
self._thumbnails_generated_subscription = None
self._was_dragging = False
# Monitor for new thumbnails being generated
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
self._thumbnails_generated_subscription = event_stream.create_subscription_to_pop_by_type(
THUMBNAILS_GENERATED_EVENT, self.update_cards_on_thumbnails_generated, name="filebrowser grid_view")
@property
def scale(self) -> float:
return self._scale
@scale.setter
def scale(self, scale: float):
self._scale = scale
@property
def selections(self) -> List[FileBrowserItem]:
return [card.item for card in self._selections]
@selections.setter
def selections(self, selections: List[FileBrowserItem]):
self._pending_selections = []
if self._cards:
# grid been build, set selection
cards = [self._cards[item.path] for item in selections if item.path in self._cards]
self.clear_selections()
self.extend_selections(cards)
else:
# grid has not been build yet, set pending_selection
self._pending_selections = selections
def build_grid(self, model: FileBrowserModel):
self.clear_selections()
for _, card in self._cards.items():
card.destroy()
self._cards.clear()
self._card_paths.clear()
with self._widget:
with ui.ZStack():
with ui.VStack():
if self._grid:
self._grid = None
self._grid = ui.VGrid(
column_width=self._scale * self._card_width,
row_height=self._scale * self._card_height + 20,
mouse_pressed_fn=partial(self._on_mouse_pressed, model, None),
mouse_double_clicked_fn=partial(self._on_mouse_double_clicked, None),
style_type_name_override="GridView.Grid",
content_clipping=True,
)
if self._treeview_identifier:
self._grid.identifier = self._treeview_identifier
ui.Spacer(height=30)
# OM-70157: Since we cannot clip the mouse event for the button in Zoombar for the VGrid, we have to add a invisibleButton here, whose clicked_fn
# will not be triggered if the ZoomBar switch layout button is on top of it; this way it will not clear out the selections when the user click
# on the layout switch button when it is on top of the VGrid.
def grid_clicked(*args, **kwargs):
self._on_mouse_released(model, None, None, None, 0, 0)
ui.InvisibleButton(clicked_fn=grid_clicked)
def update_grid(self, model: FileBrowserModel):
"""Generates a grid of cards and renders them with custom thumbnails"""
if not self._grid:
return
if model:
children = model.get_item_children(None)
else:
return
# make sure the grid not rebuild more than once
rebuilt_grid = False
for path in self._cards:
# If items got deleted then re-build the grid
if path not in [c.path for c in children]:
self.build_grid(model)
rebuilt_grid = True
break
# update card style if path in cut clipboard
if is_path_cut(path):
self._cards[path].apply_cut_style()
else:
self._cards[path].remove_cut_style()
for item in children:
# Add cards for any new children
if item.item_changed :
item.item_changed = False
if not rebuilt_grid:
self.build_grid(model)
rebuilt_grid = True
with self._grid:
for item in children:
# Add cards for any new children
# OM-91073: check paths to prevent build card more than once in sometimes
# not use the self._cards because it not create immediately in frame's build_fn
# so we need store and check the card path directly
if item.path in self._card_paths:
continue
def __build_card(file_item):
self._cards[file_item.path] = self.build_card(model, file_item)
self._card_paths.append(item.path)
if self._testing:
# In testing mode, forces cards to immediately be built and made available
with ui.Frame():
self._cards[item.path] = self.build_card(model, item)
else:
# OM-63433: Use content_clipping to speed up item display in file picker
ui.Frame(content_clipping=True, build_fn=lambda i=item: __build_card(i))
async def refresh_thumbnails(model: FileBrowserModel):
# Get custom thumbnails for parent folder and synchronously render them if they exist
if model and model.root:
self._custom_thumbnails = await model.root.get_custom_thumbnails_for_folder_async()
try:
await self.refresh_thumbnails_async(list(self._cards))
except asyncio.CancelledError:
return
# selections was set before cards created, update now
if self._pending_selections:
cards = [self._cards[item.path] for item in self._pending_selections if item.path in self._cards]
self._pending_selections = []
self.clear_selections()
self.extend_selections(cards)
# Store away future so that it can be cancelled, e.g. when switching directories
if self._update_grid_future and not self._update_grid_future.done():
self._update_grid_future.cancel()
self._update_grid_future = asyncio.ensure_future(refresh_thumbnails(model))
def update_cards_on_thumbnails_generated(self, event: events.IEvent):
"""When new thumbnails are generated, re-renders associated cards"""
if event.type != THUMBNAILS_GENERATED_EVENT:
return
try:
payload = event.payload.get_dict()
urls = payload.get('paths', [])
except Exception as e:
log_warn(f"Failed to retrieve payload from generated thumbnails event: {str(e)}")
return
async def refresh_thumbnails(urls: str):
# Get custom thumbnails for given urls. Don't try to generate (again) if not found.
self._custom_thumbnails.update(await find_thumbnails_for_files_async(urls, generate_missing=False))
try:
await self.refresh_thumbnails_async(urls)
except asyncio.CancelledError:
return
refresh_urls = [url for url in urls if url in self._cards]
if refresh_urls:
# Execute and forget
asyncio.ensure_future(refresh_thumbnails(refresh_urls))
def build_card(self, model: FileBrowserModel, item: FileBrowserItem) -> FileBrowserItemCard:
"""Create a widget per item"""
if not item:
return
if isinstance(item, FileBrowserUdimItem):
custom_thumbnail = self._custom_thumbnails.get(item.repr_path)
else:
custom_thumbnail = self._custom_thumbnails.get(item.path)
card = FileBrowserItemCard(
item,
width=self._scale * self._card_width,
height=self._scale * self._card_height,
mouse_pressed_fn=partial(self._on_mouse_pressed, model),
mouse_released_fn=partial(self._on_mouse_released, model),
mouse_double_clicked_fn=self._on_mouse_double_clicked,
drag_fn=self._on_drag,
drop_fn=self._drop_fn,
get_thumbnail_fn=self._thumbnail_provider,
get_badges_fn=self._badges_provider,
custom_thumbnail=custom_thumbnail,
timeout=model._timeout if model else 10.0,
)
return card
async def refresh_thumbnails_async(self, urls: str):
if not self._custom_thumbnails:
return
tasks = []
for url in urls:
card = self._cards.get(url, None)
item = card.item
if isinstance(item, FileBrowserUdimItem):
custom_thumbnail = self._custom_thumbnails.get(item.repr_path)
else:
custom_thumbnail = self._custom_thumbnails.get(item.path)
if card and custom_thumbnail:
tasks.append(card.refresh_thumbnail_async(custom_thumbnail))
if tasks:
try:
await asyncio.gather(*tasks, return_exceptions=True)
except Exception as e:
carb.log_error(f"Failed to refresh thumbnails: {e}")
except asyncio.CancelledError:
return
def _on_mouse_pressed(self, model: FileBrowserModel, card: FileBrowserItemCard, x, y, b, key_mod):
if self._mouse_pressed_fn:
self._mouse_pressed_fn(b, key_mod, card.item if card else None, x=x, y=y)
def _on_mouse_released(self, model: FileBrowserModel, card: FileBrowserItemCard, x, y, b, key_mod):
# Don't cancel selections
# FIXME: mouse release event will be triggered for both card and grid. It
# needs to check card to make sure mouse release event from grid will not influence selections.
if self._was_dragging:
if card:
self._was_dragging = False
return
if b == 0:
# Update selection list on left mouse clicks
if key_mod & KEYBOARD_MODIFIER_FLAG_CONTROL:
if card in self._selections:
self.remove_selection(card)
else:
self.add_selection(card)
elif key_mod & KEYBOARD_MODIFIER_FLAG_SHIFT:
if not self._selections:
self.add_selection(card)
elif card:
last_selection = self._selections[-1].item
current_selection = card.item
children = model.get_item_children(None)
# Note: Search items may re-generate frame to frame, so find by path rather than by object ref
last_selection_index = next((i for i, item in enumerate(children) if item.path == last_selection.path), -1)
current_selection_index = next((i for i, item in enumerate(children) if item.path == current_selection.path), -1)
if last_selection_index >= 0 and current_selection_index >=0:
first_index = min(last_selection_index, current_selection_index)
last_index = max(last_selection_index, current_selection_index)
self.clear_selections()
selection_indices = range(first_index, last_index+1)
# OM-72965: only add selection in reverse order if current selection is after last selection, so
# that the last element in selection remains the oldest (similar to file explorer)
if current_selection_index > last_selection_index:
selection_indices = reversed(selection_indices)
for i in selection_indices:
card = self._cards.get(children[i].path)
self.add_selection(card)
else:
self.clear_selections()
self.add_selection(card)
if self._selection_changed_fn:
self._selection_changed_fn(self.selections)
def _on_mouse_double_clicked(self, card: FileBrowserItemCard, x, y, b, key_mod):
if self._mouse_double_clicked_fn:
self._mouse_double_clicked_fn(b, key_mod, card.item if card else None, x=x, y=y)
def _on_drag(self, card: FileBrowserItemCard, thumbnail: str):
self._was_dragging = True
result: List[str] = []
if card not in self._selections:
return card.on_drag()
with ui.VStack():
for card in self._selections:
result.append(card.on_drag())
return "\n".join(result)
def clear_selections(self):
for selection in self._selections:
selection.selected = False
self._selections.clear()
def extend_selections(self, cards: List[FileBrowserItemCard]):
for card in cards:
self.add_selection(card)
def add_selection(self, card: FileBrowserItemCard):
if card and card not in self._selections:
card.selected = True
self._selections.append(card)
def remove_selection(self, card: FileBrowserItemCard):
if card and card in self._selections:
card.selected = False
self._selections.remove(card)
async def center_selection_async(
self,
selection : FileBrowserItem,
scroll_frame=None, scroll_ratio=0.0,
refresh_interval=2,
callback: Optional[Callable[[FileBrowserItem], None]] = None
):
# OM-70154: add the ability to center the selected item in file browser grid view
async def _wait_for_ui_build(refresh_interval=refresh_interval):
for _ in range(refresh_interval):
await omni.kit.app.get_app().next_update_async()
await _wait_for_ui_build()
cards = list(self._cards.values())
if not cards:
return
card_height = cards[0]._widget.computed_content_height
card = self._cards.get(selection.path)
if not scroll_frame and not card:
return
# card is not built yet, need to scroll to the y position in the scrolling frame to trigger card build
if not card:
# scroll one line to trigger calculation for scroll_y_max
scroll_frame.scroll_y = card_height
await _wait_for_ui_build()
# scroll to the card by using the item index ratio
if scroll_ratio > 0:
scroll_frame.scroll_y = scroll_ratio * scroll_frame.scroll_y_max - card_height * 0.5
await _wait_for_ui_build()
card = self._cards.get(selection.path)
if card:
card._widget.scroll_here()
self.add_selection(card)
if callback:
callback(selection)
def destroy(self):
self._grid = None
self._cards.clear()
self._card_paths.clear()
self._custom_thumbnails.clear()
self._selections.clear()
if self._update_grid_future and not self._update_grid_future.done():
self._update_grid_future.cancel()
self._update_grid_future = None
self._thumbnails_generated_subscription = None
self._style = None
self._mouse_pressed_fn = None
self._mouse_double_clicked_fn = None
self._selection_changed_fn = None
self._drop_fn = None
self._thumbnail_provider = None
self._badges_provider = None
| 22,038 | Python | 41.301343 | 161 | 0.600554 |
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/__init__.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""
The basic UI widget and set of supporting classes for navigating the filesystem through a tree view.
The filesystem can either be from your local machine or the Omniverse server.
Example:
.. code-block:: python
With just a few lines of code, you can create a powerful, flexible tree view widget that you
can embed into your view.
filebrowser = FileBrowserWidget(
"Omniverse",
layout=SPLIT_PANES,
mouse_pressed_fn=on_mouse_pressed,
selection_changed_fn=on_selection_changed,
drop_fn=drop_handler,
filter_fn=item_filter_fn,
)
Module Constants:
layout: {LAYOUT_SINGLE_PANE_SLIM, LAYOUT_SINGLE_PANE_WIDE, LAYOUT_SPLIT_PANES, LAYOUT_DEFAULT}
"""
LAYOUT_SINGLE_PANE_SLIM = 1
LAYOUT_SINGLE_PANE_WIDE = 2
LAYOUT_SPLIT_PANES = 3
LAYOUT_SINGLE_PANE_LIST = 4
LAYOUT_DEFAULT = 3
TREEVIEW_PANE = 1
LISTVIEW_PANE = 2
import carb.events
CONNECTION_ERROR_EVENT: int = carb.events.type_from_string("omni.kit.widget.filebrowser.CONNECTION_ERROR")
MISSING_IMAGE_THUMBNAILS_EVENT: int = carb.events.type_from_string("omni.services.thumbnails.MISSING_IMAGE_THUMBNAILS")
THUMBNAILS_GENERATED_EVENT: int = carb.events.type_from_string("omni.services.thumbnails.THUMBNAILS_GENERATED")
ALERT_INFO = 1
ALERT_WARNING = 2
ALERT_ERROR = 3
from .widget import FileBrowserWidget
from .card import FileBrowserItemCard
from .model import FileBrowserModel, FileBrowserItem, FileBrowserUdimItem, FileBrowserItemFactory
from .filesystem_model import FileSystemModel, FileSystemItem
from .nucleus_model import NucleusModel, NucleusItem, NucleusConnectionItem
from .column_delegate_registry import ColumnDelegateRegistry
from .abstract_column_delegate import ColumnItem
from .abstract_column_delegate import AbstractColumnDelegate
from .thumbnails import find_thumbnails_for_files_async, list_thumbnails_for_folder_async
from .clipboard import save_items_to_clipboard, get_clipboard_items, is_clipboard_cut, is_path_cut, clear_clipboard
| 2,447 | Python | 38.48387 | 119 | 0.7736 |
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/card.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""
Base Model classes for the filebrowser entity.
"""
__all__ = ["FileBrowserItemCard"]
import carb
from typing import Optional
from functools import partial
from omni import ui
from .clipboard import is_path_cut
from .model import FileBrowserItem
from .style import UI_STYLES, THUMBNAIL_PATH, ICON_PATH
from . import ALERT_WARNING, ALERT_ERROR
class FileBrowserItemCard(ui.Widget):
def __init__(self, item: FileBrowserItem, **kwargs):
import carb.settings
self._item = item
self._widget = None
self._rectangle = None
self._image_frame = None
self._image_buffer = None
self._image_buffer_thumbnail = None
self._overlay_frame = None
self._back_buffer = None
self._back_buffer_thumbnail = None
self._label = None
self._selected = False
self._theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
use_default_style = carb.settings.get_settings().get_as_string("/persistent/app/window/useDefaultStyle") or False
if use_default_style:
self._style = {}
else:
self._style = kwargs.get("style", UI_STYLES[self._theme])
self._width = kwargs.get("width", 60)
self._height = kwargs.get("height", 60)
self._mouse_pressed_fn = kwargs.get("mouse_pressed_fn", None)
self._mouse_released_fn = kwargs.get("mouse_released_fn", None)
self._mouse_double_clicked_fn = kwargs.get("mouse_double_clicked_fn", None)
self._drop_fn = kwargs.get("drop_fn", None)
self._get_thumbnail_fn = kwargs.get("get_thumbnail_fn", None)
self._get_badges_fn = kwargs.get("get_badges_fn", None)
self._custom_thumbnail = kwargs.get("custom_thumbnail", None)
self._timeout = kwargs.get("timeout", 10.0)
super().__init__()
self._drag_fn = kwargs.get("drag_fn", None)
if self._drag_fn:
self._drag_fn = partial(self._drag_fn, self)
else:
# If nothing is set, use the default one
self._drag_fn = self.on_drag
self._tooltip = f"Path: {item.path}\n"
self._tooltip += f"Size: {FileBrowserItem.size_as_string(item.fields.size)}\n"
self._tooltip += f"Modified: {FileBrowserItem.datetime_as_string(item.fields.date)}"
self._cached_thumbnail: Optional[str] = None
self._build_ui()
@property
def item(self) -> FileBrowserItem:
return self._item
@property
def selected(self) -> bool:
return self._selected
@selected.setter
def selected(self, value: bool):
self._rectangle.selected = value
self._label.checked = value
self._selected = value
def apply_cut_style(self):
for widget in (self._back_buffer_thumbnail, self._image_buffer_thumbnail, self._label):
if widget:
widget.name = "Cut"
def remove_cut_style(self):
for widget in (self._back_buffer_thumbnail, self._image_buffer_thumbnail, self._label):
if widget:
widget.name = ""
def _build_ui(self):
if not self._item:
return
def on_mouse_pressed(card: "FileBrowserItemCard", *args):
if self._mouse_pressed_fn:
self._mouse_pressed_fn(card, *args)
def on_mouse_released(card: "FileBrowserItemCard", *args):
if self._mouse_released_fn:
self._mouse_released_fn(card, *args)
def on_mouse_double_clicked(card: "FileBrowserItemCard", *args):
if self._mouse_double_clicked_fn:
self._mouse_double_clicked_fn(card, *args)
def mouse_hovered_fn(hovered: bool):
self._label.selected = hovered
self._widget = ui.ZStack(width=0, height=0, style=self._style)
with self._widget:
self._rectangle = ui.Rectangle(
mouse_pressed_fn=partial(on_mouse_pressed, self),
mouse_released_fn=partial(on_mouse_released, self),
mouse_double_clicked_fn=partial(on_mouse_double_clicked, self),
style_type_name_override="Card",
)
self._rectangle.set_mouse_hovered_fn(mouse_hovered_fn)
with ui.VStack(spacing=0):
with ui.ZStack():
thumbnail = self._custom_thumbnail or self._get_thumbnail(self._item)
self._image_frame = ui.Frame(
width=self._width,
height=self._height,
drag_fn=lambda: self.on_drag(thumbnail),
accept_drop_fn=lambda url: self._item.is_folder,
drop_fn=lambda event: self._on_drop(event),
)
self._overlay_frame = ui.Frame(
width=self._width,
height=self._height,
)
self.draw_thumbnail(self._custom_thumbnail)
self.draw_badges()
with ui.HStack(height=40):
# Note: This Placer nudges the label closer to the image. The inherent
# margin would otherwise create a less pleasing separation.
with ui.Placer(stable_size=True, offset_x=0, offset_y=-8):
self._label = ui.Label(
self._item.name,
style_type_name_override="Card.Label",
word_wrap=True,
elided_text=True if self._theme == "NvidiaDark" else False,
tooltip=self._tooltip,
)
ui.Spacer()
# add cut style if path is in cut clipboard on build
if is_path_cut(self._item.path):
self.apply_cut_style()
def _get_thumbnail(self, item: FileBrowserItem) -> str:
thumbnail = None
if self._get_thumbnail_fn:
thumbnail = self._get_thumbnail_fn(item)
if not thumbnail:
# Set to default thumbnails
if self._item.is_folder:
thumbnail = f"{THUMBNAIL_PATH}/folder_256.png"
else:
thumbnail = f"{THUMBNAIL_PATH}/file_256.png"
return thumbnail
def on_drag(self, thumbnail: Optional[str] = None):
with ui.VStack():
if not thumbnail and self._cached_thumbnail:
thumbnail = self._cached_thumbnail
elif not thumbnail:
if self._item.is_folder:
thumbnail = f"{THUMBNAIL_PATH}/folder_256.png"
else:
thumbnail = f"{THUMBNAIL_PATH}/file_256.png"
ui.Image(thumbnail, width=32, height=32)
ui.Label(self._item.path)
return self._item.path
def _on_drop(self, event: ui.WidgetMouseDropEvent):
if self._drop_fn:
self._drop_fn(self._item, event.mime_data)
async def draw_thumbnail_async(self, thumbnail: str):
self.draw_thumbnail(thumbnail)
if is_path_cut(self._item.path):
self.apply_cut_style()
def draw_thumbnail(self, thumbnail: str):
"""Asynchronously redraws thumbnail with the given file"""
def on_image_progress(frame: ui.Frame, thumbnail_image: ui.Image, progress: float):
"""Called when the image loading progress is changed."""
if progress != 1.0:
# We only need to catch the moment when the image is loaded.
return
# Hide the icon on the background.
if frame:
frame.visible = False
# Remove the callback to avoid circular references.
thumbnail_image.set_progress_changed_fn(None)
if thumbnail:
self._cached_thumbnail = thumbnail
with self._image_frame:
if not self._image_buffer:
self._image_buffer = ui.ZStack()
with self._image_buffer:
self._back_buffer = ui.Frame()
with self._back_buffer:
default_thumbnail = self._get_thumbnail(self._item)
self._back_buffer_thumbnail = ui.ImageWithProvider(
default_thumbnail,
fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT,
style_type_name_override="Card.Image",
)
self._image_frame.set_drag_fn(lambda: self._drag_fn(default_thumbnail))
if not thumbnail:
return
with self._image_buffer:
front_buffer = ui.Frame()
with front_buffer:
# NOTE: Ideally, we could use ui.ImageProvider here for consistency. However, if that
# method doesn't allow loading images from "omniverse://".
thumbnail_image = ui.Image(
thumbnail,
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
style_type_name_override="Card.Image",
)
thumbnail_image.set_progress_changed_fn(partial(on_image_progress, self._back_buffer, thumbnail_image))
self._image_buffer_thumbnail = thumbnail_image
self._image_frame.set_drag_fn(lambda: self._drag_fn(thumbnail))
self._back_buffer = None
def draw_badges(self):
if not self._item or not self._get_badges_fn:
return
badges = self._get_badges_fn(self._item)
if self._item.alert:
sev, msg = self._item.alert
if sev == ALERT_WARNING:
badges.append((f"{ICON_PATH}/{self._theme}/warn.svg", msg))
elif sev == ALERT_ERROR:
badges.append((f"{ICON_PATH}/{self._theme}/error.svg", msg))
else:
badges.append((f"{ICON_PATH}/{self._theme}/info.svg", msg))
if not badges:
return
size = 14
margin_width = 6
margin_height = 8
shadow_offset = 1
with self._overlay_frame:
# First, the shadows
with ui.ZStack():
with ui.VStack():
ui.Spacer()
with ui.HStack(height=size, spacing=2):
ui.Spacer()
for badge in badges:
icon, _ = badge
ui.ImageWithProvider(
icon,
width=size,
name="shadow",
fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT,
style_type_name_override="Card.Badge",
)
ui.Spacer(width=margin_width - shadow_offset)
ui.Spacer(height=margin_height - shadow_offset)
# Then, the image itself
with ui.VStack():
ui.Spacer()
with ui.HStack(height=size, spacing=2):
ui.Spacer()
for badge in badges:
icon, tooltip = badge
ui.ImageWithProvider(
icon,
tooltip=tooltip,
width=size,
fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT,
style_type_name_override="Card.Badge",
)
ui.Spacer(width=margin_width)
ui.Spacer(height=margin_height)
async def refresh_thumbnail_async(self, thumbnail: str):
try:
await self.draw_thumbnail_async(thumbnail)
except Exception as exc:
carb.log_error(f"Failed to redraw thumbnail {exc}")
def destroy(self):
self._item = None
self._label = None
self._image_frame = None
self._overlay_frame = None
self._image_buffer = None
self._image_buffer_thumbnail = None
self._back_buffer = None
self._back_buffer_thumbnail = None
self._rectangle = None
self._widget = None
| 12,874 | Python | 39.109034 | 123 | 0.536197 |
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/model.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["FileBrowserItem", "FileBrowserItemFactory", "FileBrowserModel"]
import os
import asyncio
import omni.client
import omni.kit.app
import threading
from typing import List, Dict, Tuple, Union, Callable, Any
from datetime import datetime
from collections import OrderedDict
from omni import ui
from carb import log_warn
from omni.kit.helper.file_utils import asset_types
from .thumbnails import list_thumbnails_for_folder_async
from .column_delegate_registry import ColumnDelegateRegistry
from .date_format_menu import get_datetime_format
from . import CONNECTION_ERROR_EVENT
from collections import namedtuple
FileBrowserItemFields = namedtuple("FileBrowserItemFields", "name date size permissions")
compiled_regex = None
# A hacky way to get the number of fields in FileBrowserItemFields. Otherwise we need to set hardcoded "3".
BUILTIN_COLUMNS = len(dir(FileBrowserItemFields)) - len(dir(namedtuple("_", "")))
class NoLock(object):
def __init__(self):
pass
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
pass
class FileBrowserItem(ui.AbstractItem):
"""
Base class for the Filebrowser tree view Item. Should be sub-classed to implement specific filesystem
behavior. The Constructor should not be called directly. Instead there are factory methods available
for creating instances when needed.
"""
# flags for item display
expandable = True # whether this type of FileBrowserItem is expandable
hideable = True # whether this type of FileBrowserItem is hideable
def __init__(self, path: str, fields: FileBrowserItemFields, is_folder: bool = False, is_deleted: bool = False):
super().__init__()
self._path = path.replace("\\", "/")
self._fields = fields # Raw field values
self._models = () # Formatted values for display
self._parent = None
self._children = OrderedDict()
self._is_folder = is_folder
self._is_deleted = is_deleted
self._populated = False
self._is_udim_file = False
self._populate_func = None
self._populate_future = None
self._enable_sorting = True # Enables children to be sorted
self._icon = None
self._alert: Tuple[int, str] = None
self._item_changed = False
# Enables thread-safe reads/writes to shared data, e.g. children dict
self._mutex_lock: threading.Lock = threading.Lock() if is_folder else NoLock()
@property
def name(self) -> str:
"""str: Item name."""
return getattr(self._fields, "name", "")
@property
def path(self) -> str:
"""str: Full path name."""
return self._path
@property
def fields(self) -> FileBrowserItemFields:
""":obj:`FileBrowserItemFields`: A subset of the item's stats stored as a string tuple."""
return self._fields
@property
def models(self) -> Tuple:
"""Tuple[:obj:`ui.AbstractValueModel`]: The columns of this item."""
return self._models
@property
def parent(self) -> object:
""":obj:`FileBrowserItem`: Parent of this item."""
return self._parent
@property
def children(self) -> OrderedDict:
"""dict[:obj:`FileBrowserItem`]: Children of this item. Does not populate the item if not already populated."""
children = {}
with self._mutex_lock:
for name, child in self._children.items():
children[name] = child
return children
@property
def is_folder(self) -> bool:
"""bool: True if this item is a folder."""
return self._is_folder
@property
def item_changed (self) -> bool:
"""bool: True if this item is has been restore/delete aready."""
return self._item_changed
@item_changed .setter
def item_changed (self, value: bool):
self._item_changed = value
@property
def is_deleted(self) -> bool:
"""bool: True if this item is a deleted folder/file."""
return self._is_deleted
@is_deleted.setter
def is_deleted(self, value: bool):
self._is_deleted = value
@property
def populated(self) -> bool:
"""bool: Gets/Sets item populated state."""
return self._populated
@populated.setter
def populated(self, value: bool):
self._populated = value
@property
def is_udim_file(self) -> bool:
"""bool: Gets/Sets item udim_file state."""
return self._is_udim_file
@is_udim_file.setter
def is_udim_file(self, value: bool):
self._is_udim_file = value
@property
def enable_sorting(self) -> bool:
"""bool: True if item's children are sortable."""
return self._enable_sorting
@property
def icon(self) -> str:
"""str: Gets/sets path to icon file."""
return self._icon
@icon.setter
def icon(self, icon: str):
self._icon = icon
@property
def readable(self) -> bool:
return True
@property
def writeable(self) -> bool:
return True
@property
def alert(self) -> Tuple[int, str]:
return self._alert
@alert.setter
def alert(self, alert: Tuple[int, str]):
self._alert = alert
@property
def expandable(self) -> bool:
"""whether this FileBrowserItem is expandable. Override to change behavior"""
return True
@property
def hideable(self) -> bool:
"""whether this FileBrowserItem is hideable. Override to change behavior"""
return True
async def on_populated_async(self, result=None, children=None, callback=None):
if isinstance(result, Exception) and not isinstance(result, asyncio.CancelledError):
log_warn(f"Error populating '{self.path}': {str(result)}")
else:
# add udim placeholders
FileBrowserUdimItem.populate_udim(self)
if callback:
callback(children)
def get_subitem_model(self, index: int) -> object:
"""
Returns ith column of this item.
Returns:
:obj:`AbstractValueModel`
"""
if self._models and index < len(self._models):
return self._models[index]
return None
def populate_with_callback(self, callback: Callable, timeout: float = 10.0):
"""
Populates this item if not already populated. When done, executes callback.
Args:
callback (Callable): Function signature is void callback(children: [FileBrowserItem]).
timeout (float): Time out duration on failed server connections. Default 10.0.
"""
if self._populate_future and not self._populate_future.done():
# If there is an ongoing task for populating this folder
# Just add the call back instead of cancel it.
# populate_with_callback is only called by get_item_children
# the callback only need one place holder parameter, so could use here.
# simply cancel the furture cause the expand invalid, see OM-35385
self._populate_future.add_done_callback(callback)
else:
self._populate_future = asyncio.ensure_future(self.populate_async(lambda result, children: self.on_populated_async(result, children, callback), timeout=timeout))
async def populate_async(self, callback_async: Callable = None, timeout: float = 10.0) -> Any:
"""
Populates current item asynchronously if not already. Override this method to customize for specific
file systems.
Args:
callback_async (Callable): Function signature is void callback(result, children: [FileBrowserItem]),
where result is an Exception type upon error.
timeout (float): Time out duration on failed server connections. Default 10.0.
Returns:
Any: Result of executing callback.
"""
if not self._populated:
for _, child in self._children.items():
child._parent = self
self._populated = True
result = None
if callback_async:
return await callback_async(result, self.children)
else:
return result
def on_list_change_event(self, event: omni.client.ListEvent, entry: omni.client.ListEntry) -> bool:
"""
Virtual method to be implemented by sub-class. When called with a ListEvent, should update
this item's children list with the corresponding ListEntry.
Args:
event (:obj:`omni.client.ListEvent`): One of of {UNKNOWN, CREATED, UPDATED, DELETED, METADATA, LOCKED, UNLOCKED}.
entry (:obj:`omni.client.ListEntry`): Updated entry as defined by omni.client.
"""
return True
def add_child(self, item: object):
"""
Adds item as child.
Args:
item (:obj:`FileBrowserItem`): Child item.
"""
with self._mutex_lock:
if item:
self._children[item.name] = item
item._parent = self
def del_child(self, item_name: str):
"""
Deletes child item by name.
Args:
item_name (str): Name of child item.
"""
with self._mutex_lock:
if item_name in self._children:
# Note: Pop (instead of del) item here so as not to destory it. Let garbage collection clean it up when
# all references are released. Otherwise may result in a race condition (See OM-34661).
self._children.pop(item_name)
async def get_custom_thumbnails_for_folder_async(self) -> Dict:
"""
Returns the thumbnail dictionary for this (folder) item.
Returns:
Dict: With children url's as keys, and url's to thumbnail files as values.
"""
# If item is 'None' them interpret as root node
if self.is_folder:
return await list_thumbnails_for_folder_async(self.path)
return {}
@staticmethod
def size_as_string(value: int) -> str:
one_kb = 1024.0
one_mb = 1024.0 * one_kb
one_gb = 1024.0 * one_mb
return (
f"{value/one_gb:.2f} GB" if value > one_gb else (
f"{value/one_mb:.2f} MB" if value > one_mb else f"{value/one_kb:.2f} KB"
)
)
@staticmethod
def datetime_as_string(value: datetime) -> str:
return value.strftime(f"{get_datetime_format()} %I:%M%p")
class FileBrowserUdimItem(FileBrowserItem):
def __init__(self, path: str, fields: FileBrowserItemFields, range_start: int, range_end: int, repr_frame: int = None):
super().__init__(path, fields, is_folder=False)
self._range_start = range_start
self._range_end = range_end
self._repr_frame = repr_frame
@property
def repr_path(self) -> str:
"""str: Full thumbnail path name."""
url_parts = self._path.split(".<UDIM>.")
if self._repr_frame and len(url_parts) == 2:
return f"{url_parts[0]}.{self._repr_frame}.{url_parts[1]}"
else:
return self._path
@staticmethod
def populate_udim(parent: FileBrowserItem):
udim_added_items = {}
for _, item in parent._children.items():
if not item.is_folder and asset_types.is_asset_type(item.path, asset_types.ASSET_TYPE_IMAGE):
udim_full_path, udim_index = FileBrowserUdimItem.get_udim_sequence(item.path)
if udim_full_path:
if not udim_full_path in udim_added_items:
udim_added_items[udim_full_path] = {"placeholder": udim_full_path, "range": [udim_index], "items": [item]}
else:
udim_added_items[udim_full_path]["range"].append(udim_index)
udim_added_items[udim_full_path]["items"].append(item)
for udim in udim_added_items:
range = udim_added_items[udim]["range"]
udim_full_path = udim_added_items[udim]["placeholder"]
udim_name = os.path.basename(udim_full_path)
for item in udim_added_items[udim]["items"]:
item.is_udim_file = True
# get 1st udim item to use for thumbnail
item = FileBrowserItemFactory.create_udim_item(udim_name, udim_full_path, range[0], range[-1], range[0])
parent.add_child(item)
@staticmethod
def get_udim_sequence(full_path: str):
import re
global compiled_regex
if compiled_regex == None:
types = '|'.join([t[1:] for t in asset_types.asset_type_exts(asset_types.ASSET_TYPE_IMAGE)])
numbers = "[0-9][0-9][0-9][0-9]"
compiled_regex = re.compile(r'([\w.-]+)(.)('+numbers+')\.('+types+')$')
udim_name = compiled_regex.sub(r"\1\2<UDIM>.\4", full_path)
if udim_name and udim_name != full_path:
udim_index = compiled_regex.sub(r"\3", os.path.basename(full_path))
return udim_name, udim_index
return None, None
class FileBrowserItemFactory:
@staticmethod
def create_group_item(name: str, path: str) -> FileBrowserItem:
if not name:
return None
fields = FileBrowserItemFields(name, datetime.now(), 0, 0)
item = FileBrowserItem(path, fields, is_folder=True)
item._models = (ui.SimpleStringModel(item.name), datetime.now(), ui.SimpleStringModel(""))
item._enable_sorting = False
return item
@staticmethod
def create_dummy_item(name: str, path: str) -> FileBrowserItem:
if not name:
return None
fields = FileBrowserItemFields(name, datetime.now(), 0, 0)
item = FileBrowserItem(path, fields, is_folder=False)
item._models = (ui.SimpleStringModel(item.name), datetime.now(), ui.SimpleStringModel(""))
return item
@staticmethod
def create_udim_item(name: str, path: str, range_start: int, range_end: int, repr_frame: int):
modified_time = datetime.now()
fields = FileBrowserItemFields(name, modified_time, 0, omni.client.AccessFlags.READ)
item = FileBrowserUdimItem(path, fields, range_start, range_end, repr_frame=repr_frame)
item._models = (ui.SimpleStringModel(f"{name} [{range_start}-{range_end}]"), modified_time, ui.SimpleStringModel("N/A"))
return item
class FileBrowserModel(ui.AbstractItemModel):
"""
Base class for the Filebrowser tree view Model. Should be sub-classed to implement specific filesystem
behavior.
Args:
name (str): Name of root item. If None given, then create an initally empty model.
Keyword Args:
drop_fn (Callable): Function called to handle drag-n-drops. Function signature:
void drop_fn(dst_item: :obj:`FileBrowserItem`, src_item: :obj:`FileBrowserItem`)
filter_fn (Callable): This handler should return True if the given tree view item is visible,
False otherwise. Function signature: bool filter_fn(item: :obj:`FileBrowserItem`)
sort_by_field (str): Name of column by which to sort items in the same folder. Default "name".
sort_ascending (bool): Sort in ascending order. Default True.
"""
_main_loop = asyncio.get_event_loop()
def __init__(self, name: str = None, root_path: str = "", **kwargs):
super().__init__()
if name:
self._root = FileBrowserItemFactory.create_group_item(name, root_path)
else:
self._root = None
# By default, display these number of columns
self._single_column = False
self._show_udim_sequence = False
self._drop_fn = kwargs.get("drop_fn", None)
self._filter_fn = kwargs.get("filter_fn", None)
self._sort_by_field = kwargs.get("sort_by_field", "name")
self._sort_ascending = kwargs.get("sort_ascending", True)
self._timeout = kwargs.get("timeout", 10.0)
self._list_change_subscription = None
self._loop = self._main_loop
# Enables thread-safe reads/writes to shared data
self._pending_item_changed: List = []
self._mutex_lock: threading.Lock = threading.Lock()
self._drag_mime_data = None
self._pending_drop_items: List = []
@property
def show_udim_sequence(self):
return self._show_udim_sequence
@show_udim_sequence.setter
def show_udim_sequence(self, value: bool):
self._show_udim_sequence = value
@property
def root(self) -> FileBrowserItem:
""":obj:`FileBrowserItem`: Gets/sets the root item of this model."""
return self._root
@root.setter
def root(self, item: FileBrowserItem):
self._root = item
self._item_changed(None)
@property
def sort_by_field(self) -> str:
""":obj:`FileBrowserItem`: Gets/sets the sort-by field name."""
return self._sort_by_field
@sort_by_field.setter
def sort_by_field(self, field: str):
self._sort_by_field = field
@property
def sort_ascending(self) -> bool:
""":obj:`FileBrowserItem`: Gets/sets the sort ascending state."""
return self._sort_ascending
@sort_ascending.setter
def sort_ascending(self, value: bool):
self._sort_ascending = value
def set_filter_fn(self, filter_fn: Callable[[str], bool]):
self._filter_fn = filter_fn
def copy_presets(self, model: 'FileBrowserModel'):
# By default, display these number of columns
if self._drop_fn is None:
self._drop_fn = model._drop_fn
if self._filter_fn is None:
self._filter_fn = model._filter_fn
self._single_column = model._single_column
self._sort_by_field = model._sort_by_field
self._sort_ascending = model._sort_ascending
def get_item_children(self, item: FileBrowserItem) -> [FileBrowserItem]:
"""
Returns the list of items that are nested to the given parent item.
Args:
item (:obj:`FileBrowserItem`): Parent item.
Returns:
list[:obj:`FileBrowserItem`]
"""
# If item is 'None' them interpret as root node
item_or_root = item or self._root
if not item_or_root or not item_or_root.is_folder:
return []
if item_or_root.children:
children = list(item_or_root.children.values())
if item_or_root.enable_sorting and self._sort_by_field in FileBrowserItemFields._fields:
# Skip root level but otherwise, sort by specified field
def get_value(item: FileBrowserItem):
value = getattr(item.fields, self._sort_by_field)
return value.lower() if isinstance(value, str) else value
children = sorted(children, key=get_value, reverse=not self._sort_ascending)
# List folders before files
children = [
item
for item, is_folder in [(c, f) for f in [True, False] for c in children]
if item.is_folder == is_folder
]
if self._filter_fn:
children = self.filter_items(children)
else:
children = []
if not item_or_root.populated:
# If item not yet populated, then do it asynchronously. Force redraw when done. Note: When notifying
# the TreeView with item_changed events, it's important to pass 'None' for the root node.
item_or_root.populate_with_callback(lambda _: self._delayed_item_changed(item), timeout=self._timeout)
return children
def filter_items(self, items: List[FileBrowserItem]) -> List[FileBrowserItem]:
results = []
for item in items:
if item.is_folder == False:
if (self._show_udim_sequence and item.is_udim_file) or \
(not self._show_udim_sequence and isinstance(item, FileBrowserUdimItem)):
continue
if self._filter_fn and self._filter_fn(item):
results.append(item)
return results
def get_item_value_model_count(self, item: FileBrowserItem) -> int:
"""
Returns the number of columns this model item contains.
Args:
item (:obj:`FileBrowserItem`): The item in question.
Returns:
int
"""
if self._single_column:
return 1
if item is None:
return self.builtin_column_count + len(ColumnDelegateRegistry().get_column_delegate_names())
return len(item._models)
def get_item_value_model(self, item: FileBrowserItem, index: int) -> object:
"""
Get the value model associated with this item.
Args:
item (:obj:`FileBrowserItem`): The item in question.
Returns:
:obj:`AbstractValueModel`
"""
if not item:
item = self._root
if item:
return item.get_subitem_model(index)
else:
return None
def auto_refresh_item(self, item: FileBrowserItem, throttle_frames: int = 4):
"""
Watches the given folder and updates the children list as soon as its contents are changed.
Args:
item (:obj:`FileBrowserItem`): The folder item to watch.
throttle_frames: Number of frames to throttle the UI refresh.
"""
# If item is 'None' them interpret as root node
item_or_root = item or self._root
if not item_or_root or not item_or_root.is_folder:
return
self._list_change_subscription = omni.client.list_subscribe_with_callback(
item_or_root.path, None,
lambda result, event, entry: self.on_list_change_event(item_or_root, result, event, entry, throttle_frames=throttle_frames))
def sync_up_item_changes(self, item: FileBrowserItem):
"""
Scans given folder for missed changes; processes any changes found.
Args:
item (:obj:`FileBrowserItem`): The folder item to watch.
"""
item_or_root = item or self._root
if not item_or_root or not item_or_root.is_folder:
return
async def sync_up_item_changes_async(item: FileBrowserItem):
if not item.is_folder:
return
entries = []
try:
include_deleted_option = omni.client.ListIncludeOption.INCLUDE_DELETED_FILES
result, entries = await asyncio.wait_for(omni.client.list_async(item.path, include_deleted_option=include_deleted_option), timeout=self._timeout)
except Exception as e:
log_warn(f"Can't list directory '{item.path}': {str(e)}")
return
else:
if result != omni.client.Result.OK:
result = RuntimeWarning(f"Error listing directory '{item.path}': {result}")
# Emit notification event
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
event_stream.push(CONNECTION_ERROR_EVENT, payload={"url": item.path, "exception": result})
return
children = item.children
for entry in entries:
if entry.relative_path not in children:
# Entry was added
self.on_list_change_event(item, result, omni.client.ListEvent.CREATED, entry)
entry_names = [entry.relative_path for entry in entries]
for name in children:
if name not in entry_names:
if asset_types.is_udim_sequence(name):
continue
# Entry was deleted
MockListEntry = namedtuple("MockListEntry", "relative_path")
entry = MockListEntry(name)
self.on_list_change_event(item, result, omni.client.ListEvent.DELETED, entry)
asyncio.ensure_future(sync_up_item_changes_async(item_or_root))
def on_list_change_event(self, item: FileBrowserItem,
result: omni.client.Result, event: omni.client.ListEvent, entry: omni.client.ListEntry,
throttle_frames: int = 4):
"""
Processes change events for the given folder.
Args:
item (:obj:`FileBrowserItem`): The folder item.
result (omni.client.Result): Set by omni.client upon listing the folder.
event (omni.client.ListEvent): Event type.
throttle_frames: Number of frames to throttle the UI refresh.
"""
if item and result == omni.client.Result.OK:
item_changed = item.on_list_change_event(event, entry)
# Limit item changed to these events (See OM-29866: Kit crashes during live sync due to auto refresh)
if item_changed:
# There may be many change events issued at once. To scale properly, we queue up the changes over a
# few frames before triggering a single redraw of the UI.
self._delayed_item_changed(item, throttle_frames=throttle_frames)
def _delayed_item_changed(self, item: FileBrowserItem, throttle_frames: int = 1):
"""
Produces item changed event after skipping a beat. This is necessary for guaranteeing that async updates
are properly recognized and generate their own redraws.
Args:
item (:obj:`FileBrowserItem`): The item in question.
"""
async def item_changed_async(item: FileBrowserItem, throttle_frames: int):
with self._mutex_lock:
if item in self._pending_item_changed:
return
else:
self._pending_item_changed.append(item)
# NOTE: Wait a few beats to absorb nearby change events so that we process the changes in one chunk.
for _ in range(throttle_frames):
await omni.kit.app.get_app().next_update_async()
self._item_changed(item)
with self._mutex_lock:
try:
self._pending_item_changed.remove(item)
except Exception:
pass
if threading.current_thread() is threading.main_thread():
asyncio.ensure_future(item_changed_async(item, throttle_frames))
else:
asyncio.run_coroutine_threadsafe(item_changed_async(item, throttle_frames), self._loop)
@property
def single_column(self):
"""The panel on the left side works in one-column mode"""
return self._single_column
@single_column.setter
def single_column(self, value: bool):
"""Set the one-column mode"""
self._single_column = not not value
self._item_changed(None)
@property
def builtin_column_count(self):
"""Return the number of available columns without tag delegates"""
return 3
@property
def drag_mime_data(self):
return self._drag_mime_data
@drag_mime_data.setter
def drag_mime_data(self, data: Union[str, List[str]]):
if isinstance(data, List):
self._drag_mime_data = "\n".join(data)
else:
self._drag_mime_data = data
def get_drag_mime_data(self, item: FileBrowserItem):
"""Returns Multipurpose Internet Mail Extensions (MIME) data for be able to drop this item somewhere"""
if self._drag_mime_data:
return self._drag_mime_data
return (item or self._root).path
def drop_accepted(self, dst_item: FileBrowserItem, src_item: FileBrowserItem) -> bool:
"""
Reimplemented from AbstractItemModel. Called to highlight target when drag and drop.
Returns True if destination item is able to accept a drop. This function can be
overriden to implement a different behavior.
Args:
dst_item (:obj:`FileBrowserItem`): Target item.
src_item (:obj:`FileBrowserItem`): Source item.
Returns:
bool
"""
if dst_item and dst_item.is_folder:
# Returns True if item is a folder.
return True
return False
def drop(self, dst_item: FileBrowserItem, source: Union[str, FileBrowserItem]):
"""
Invokes user-supplied function to handle dropping source onto destination item.
Args:
dst_item (:obj:`FileBrowserItem`): Target item.
src_item (:obj:`FileBrowserItem`): Source item.
"""
if self._drop_fn and source:
# OM-87075: Delay a frame and batch process source items, if the source arg passed in is a FileBrowserItem
# FIXME: The reason for adding this delay is that, when the drop happens between within the same treeview
# (eg. selected multiple items and drop to another item in the same tree view the the list view panel)
# this ``drop`` is called once per selected item, this causes hang if in `_drop_fn` there's UI related
# operation; Thus, here we have to cache pending items and delay a frame;
# Ideally, ``omni.ui.TreeView`` might adjust the drop trigger to batch items instead of calling once per
# selected item.
if isinstance(source, FileBrowserItem):
with self._mutex_lock:
self._pending_drop_items.append(source)
else:
self._drop_fn(dst_item, source)
return
async def delay_drop():
await omni.kit.app.get_app().next_update_async()
if self._pending_drop_items:
self._drop_fn(dst_item, '\n'.join([item.path for item in self._pending_drop_items]))
self._pending_drop_items = []
if threading.current_thread() is threading.main_thread():
asyncio.ensure_future(delay_drop())
else:
asyncio.run_coroutine_threadsafe(delay_drop(), self._loop)
def destroy(self):
self._root = None
self._drop_fn = None
self._filter_fn = None
self._list_change_subscription = None
self._loop = None
self._pending_item_changed: List = []
self._pending_drop_items.clear()
| 30,905 | Python | 36.968059 | 173 | 0.605824 |
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/thumbnails.py | __all__ = ["MissingThumbnailError", "find_thumbnails_for_files_async", "list_thumbnails_for_folder_async", "generate_missing_thumbnails_async"]
import os
import asyncio
import omni.client
import omni.kit.app
from typing import List, Dict, Set
from carb import log_warn
from omni.kit.helper.file_utils import asset_types
from . import MISSING_IMAGE_THUMBNAILS_EVENT
# Module globals
_thumbnails_dir: str = ".thumbs/256x256"
_missing_thumbnails_cache: Set = set()
class MissingThumbnailError(Exception):
""" Raised when Moebius server error
"""
def __init__(self, msg: str = '', url: str = None):
super().__init__(msg)
self.url = url
async def find_thumbnails_for_files_async(urls: List[str], generate_missing: bool = True) -> Dict:
"""
Returns a dictionary of thumbnails for the given files.
Args:
urls (List[str]): List of file Urls.
generate_missing (bool): When True, emits a carb event for the missing thumbnails. Set to False to
disable this behavior.
Returns:
Dict: Dict of all found thumbnails, with file Url as key, and thumbnail Url as value.
"""
tasks = [_find_thumbnail_async(url, auto=False) for url in urls if url]
results = await asyncio.gather(*tasks, return_exceptions=True)
thumbnail_dict = {}
missing_thumbnails = []
for result in results:
if isinstance(result, MissingThumbnailError):
missing_thumbnails.append(result.url)
else:
url, thumbnail_url = result
if url and thumbnail_url:
thumbnail_dict[url] = thumbnail_url
# Generate any missing thumbnails
if missing_thumbnails and generate_missing:
await generate_missing_thumbnails_async(missing_thumbnails)
return thumbnail_dict
async def _find_thumbnail_async(url: str, auto=False):
if not url:
return None
broken_url = omni.client.break_url(url)
if _thumbnails_dir in broken_url.path:
return None
parent_path = os.path.dirname(broken_url.path)
filename = os.path.basename(broken_url.path)
thumbnail_path = f"{parent_path.rstrip('/')}/{_thumbnails_dir}/{filename}" + (".auto.png" if auto else ".png")
thumbnail_url = omni.client.make_url(scheme=broken_url.scheme, host=broken_url.host, port=broken_url.port, path=thumbnail_path)
result = None
try:
result, stats = await omni.client.stat_async(thumbnail_url)
except (Exception, asyncio.CancelledError, asyncio.TimeoutError) as e:
result = omni.client.Result.ERROR_NOT_FOUND
if result == omni.client.Result.OK:
return (url, thumbnail_url)
elif not auto:
return await _find_thumbnail_async(url, auto=True)
else:
raise MissingThumbnailError(url=url)
async def list_thumbnails_for_folder_async(url: str, timeout: float = 30.0, generate_missing: bool = True) -> Dict:
"""
Returns a dictionary of thumbnails for the files in the given folder.
Args:
url (str): Folder Url.
generate_missing (bool): When True, emits a carb event for the missing thumbnails. Set to False to
disable this behavior.
Returns:
Dict: Dict of all found thumbnails, with file Url as key, and thumbnail Url as value.
"""
thumbnail_dict = {}
if not url or _thumbnails_dir in url:
return {}
url = url.rstrip('/')
try:
result, stats = await omni.client.stat_async(url)
except (Exception, asyncio.CancelledError, asyncio.TimeoutError) as e:
result = omni.client.Result.ERROR_NOT_FOUND
else:
if stats and result == omni.client.Result.OK:
if not (stats.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN):
# Not a folder
return await find_thumbnails_for_files_async([url])
else:
log_warn(f"Failed to stat url {url}")
return {}
# 1. List the given folder and populate keys of thumbnail_dict
result, entries = None, {}
try:
result, entries = await asyncio.wait_for(omni.client.list_async(url), timeout=timeout)
except (Exception, asyncio.CancelledError, asyncio.TimeoutError) as e:
log_warn(f"Failed to list the folder at {url}: {str(e)}")
return {}
if result == omni.client.Result.OK:
for entry in entries:
thumbnail_dict[f"{url}/{entry.relative_path}"] = None
# 2. List thumbnail folder and match up thumbnail Url's
thumbnail_folder_url = f"{url}/{_thumbnails_dir}"
result = entries = None, {}
try:
result, entries = await asyncio.wait_for(omni.client.list_async(thumbnail_folder_url), timeout=timeout)
except (Exception, asyncio.CancelledError, asyncio.TimeoutError) as e:
result = omni.client.Result.ERROR_NOT_FOUND
if result == omni.client.Result.OK:
for entry in entries:
if entry.relative_path.endswith(".auto.png"):
asset_name = entry.relative_path[:-len(".auto.png")]
auto = True
elif entry.relative_path.endswith(".png"):
asset_name = entry.relative_path[:-len(".png")]
auto = False
else:
continue
asset_url = f"{url}/{asset_name}"
if not auto or (auto and thumbnail_dict.get(asset_url) is None):
# Take manual thumbnails over auto thumbnails
thumbnail_dict[asset_url] = f"{thumbnail_folder_url}/{entry.relative_path}"
# 3. Separate haves and have nots. Missing thumbnails have thumbnail Url == None
missing_thumbnails = [k for k, v in thumbnail_dict.items() if v == None]
thumbnail_dict = {k: v for k, v in thumbnail_dict.items() if v != None}
# 4. Generate any missing thumbnails
if missing_thumbnails and generate_missing:
asyncio.ensure_future(generate_missing_thumbnails_async(missing_thumbnails))
return thumbnail_dict
async def generate_missing_thumbnails_async(missing_thumbnails: List[str]):
"""
When missing thumbnails are discovered, send an event to have them generated. The generator
service is a separate process. Once generated, a reciprocal event is sent to update the UI.
The flow is diagramed below::
+-------------------------------+ +------------------------------+
| Filebrowser | | |
| +-------------------------+ | Missing thumbnails | |
| | | | event | |
| | update_grid +---------------------------> Thumbnail generator |
| | | | | service |
| +-------------------------+ | | |
| +-------------------------+ | Thumbnails | |
| | | | generated event | |
| | update_cards_on <---------------------------+ |
| | thumbnails_generated | | | |
| +-------------------------+ | | |
| | | |
+-------------------------------+ +------------------------------+
"""
image_urls = []
for url in missing_thumbnails:
if asset_types.is_asset_type(url, asset_types.ASSET_TYPE_IMAGE) and (url not in _missing_thumbnails_cache):
# Check that this file is an image type and not already submitted
image_urls.append(url)
if image_urls:
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
event_stream.push(MISSING_IMAGE_THUMBNAILS_EVENT, payload={"urls": image_urls})
_missing_thumbnails_cache.update(set(image_urls))
| 8,168 | Python | 40.892307 | 143 | 0.557786 |
omniverse-code/kit/exts/omni.kit.widget.filebrowser/omni/kit/widget/filebrowser/nucleus_model.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["NucleusItem", "NucleusItemFactory", "NucleusModel", "NucleusConnectionItem"]
import asyncio
from datetime import datetime
from typing import Callable, Any
import omni.client
import omni.kit.app
from omni import ui
from .model import FileBrowserItem, FileBrowserItemFields, FileBrowserModel
from .style import ICON_PATH
from . import CONNECTION_ERROR_EVENT
class NucleusItem(FileBrowserItem):
def __init__(self, path: str, fields: FileBrowserItemFields, is_folder: bool = True, is_deleted: bool = False):
super().__init__(path, fields, is_folder=is_folder, is_deleted=is_deleted)
async def populate_async(self, callback_async: Callable = None, timeout: float = 10.0) -> Any:
"""
Populates current item asynchronously if not already. Overrides base method.
Args:
callback_async (Callable): Function signature is void callback(result, children: [FileBrowserItem]),
where result is an Exception type upon error.
timeout (float): Time out duration on failed server connections. Default 10.0.
Returns:
Any: Result of executing callback.
"""
result = omni.client.Result.OK
if not self.populated:
entries = []
try:
result, entries = await asyncio.wait_for(omni.client.list_async(self.path), timeout=timeout)
except asyncio.CancelledError:
# NOTE: Return early if operation cancelled, without marking as 'populated'.
return omni.client.Result.OK
except (asyncio.TimeoutError, Exception) as e:
result = omni.client.Result.ERROR
finally:
if result == omni.client.Result.OK:
self.children.clear()
else:
result = RuntimeWarning(f"Error listing directory '{self.path}': {result}")
# Emit connection error event
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
event_stream.push(CONNECTION_ERROR_EVENT, payload={"url": self.path, "exception": result})
for entry in entries:
full_path = f"{self.path}/{entry.relative_path}"
self.add_child(NucleusItemFactory.create_entry_item(entry, full_path))
# NOTE: Mark this item populated even when there's an error so we don't repeatedly try.
self.populated = True
if callback_async:
try:
return await callback_async(result, self.children)
except asyncio.CancelledError:
return omni.client.Result.OK
else:
return result
def on_list_change_event(self, event: omni.client.ListEvent, entry: omni.client.ListEntry) -> bool:
"""
Handles ListEvent changes, should update this item's children list with the corresponding ListEntry.
Args:
event (:obj:`omni.client.ListEvent`): One of of {UNKNOWN, CREATED, UPDATED, DELETED, METADATA, LOCKED, UNLOCKED}.
entry (:obj:`omni.client.ListEntry`): Updated entry as defined by omni.client.
"""
if not entry:
return False
item_changed = False
child_name = entry.relative_path
child_name = child_name[:-1] if child_name.endswith("/") else child_name
full_path = f"{self.path}/{entry.relative_path}"
if event == omni.client.ListEvent.CREATED:
if not child_name in self.children:
self.add_child(NucleusItemFactory.create_entry_item(entry, full_path))
else:
item = self.children[child_name]
if item.is_deleted:
item.is_deleted = False
item.item_changed = True
item_changed = True
elif event == omni.client.ListEvent.DELETED:
if child_name in self.children:
item = self.children[child_name]
item.is_deleted = True
item.item_changed = True
item_changed = True
elif event == omni.client.ListEvent.OBLITERATED:
self.del_child(child_name)
item_changed = True
elif event == omni.client.ListEvent.UPDATED:
child = self.children.get(child_name)
if child:
# Update file size
size_model = child.get_subitem_model(2)
size_model.set_value(FileBrowserItem.size_as_string(entry.size))
return item_changed
@property
def readable(self) -> bool:
return (self._fields.permissions & omni.client.AccessFlags.READ) > 0
@property
def writeable(self) -> bool:
return (self._fields.permissions & omni.client.AccessFlags.WRITE) > 0
class NucleusConnectionItem(NucleusItem):
"""NucleusItem that represents a nucleus connection."""
def __init__(self, path: str, fields: FileBrowserItemFields, is_folder: bool = True):
super().__init__(path, fields, is_folder=is_folder)
self._signed_in = False
@property
def signed_in(self):
return self._signed_in
@signed_in.setter
def signed_in(self, value):
self._signed_in = value
class NucleusItemFactory:
@staticmethod
def create_group_item(name: str, path: str) -> NucleusItem:
if not name:
return None
access = omni.client.AccessFlags.READ | omni.client.AccessFlags.WRITE
fields = FileBrowserItemFields(name, datetime.now(), 0, access)
item = NucleusConnectionItem(path, fields)
item._models = (ui.SimpleStringModel(item.name), datetime.now(), ui.SimpleStringModel(""))
return item
@staticmethod
def create_entry_item(entry: omni.client.ListEntry, path: str) -> NucleusItem:
if not entry:
return None
name = entry.relative_path.rstrip("/")
modified_time = entry.modified_time
fields = FileBrowserItemFields(name, modified_time, entry.size, entry.access)
is_folder = (entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN) > 0
is_deleted = (entry.flags & omni.client.ItemFlags.IS_DELETED) > 0
item = NucleusItem(path, fields, is_folder=is_folder, is_deleted=is_deleted)
size_model = ui.SimpleStringModel(FileBrowserItem.size_as_string(entry.size))
item._models = (ui.SimpleStringModel(item.name), modified_time, size_model)
return item
class NucleusModel(FileBrowserModel):
"""
A Filebrowser model class for navigating a Nucleus server in a tree view. Sub-classed from
:obj:`FileBrowserModel`.
Args:
name (str): Name of root item..
root_path (str): Root path. If None, then create empty model. Example: "omniverse://ov-content".
Keyword Args:
drop_fn (Callable): Function called to handle drag-n-drops. Function signature:
void drop_fn(dst_item: :obj:`FileBrowserItem`, src_item: :obj:`FileBrowserItem`)
filter_fn (Callable): This handler should return True if the given tree view item is visible,
False otherwise. Function signature: bool filter_fn(item: :obj:`FileBrowserItem`)
sort_by_field (str): Name of column by which to sort items in the same folder. Default "name".
sort_ascending (bool): Sort in ascending order. Default True.
"""
def __init__(self, name: str, root_path: str, **kwargs):
import carb.settings
super().__init__(**kwargs)
if not root_path:
return
self._root = NucleusItemFactory.create_group_item(name, root_path)
theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
self._root.icon = f"{ICON_PATH}/{theme}/hdd.svg"
| 8,244 | Python | 41.282051 | 125 | 0.634522 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.