file_path
stringlengths 22
162
| content
stringlengths 19
501k
| size
int64 19
501k
| lang
stringclasses 1
value | avg_line_length
float64 6.33
100
| max_line_length
int64 18
935
| alphanum_fraction
float64 0.34
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.kit.widget.nucleus_info/omni/kit/widget/nucleus_info/ui.py | # Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from typing import Callable
from collections import namedtuple
from omni.kit.window.popup_dialog import PopupDialog
import omni.ui as ui
class NucleusAboutDialog(PopupDialog):
"""Dialog to show the omniverse server info."""
FieldDef = namedtuple("AboutDialogFieldDef", "name version")
_services_names = ["Discovery", "Auth", "Tagging", "NGSearch", "Search"]
def __init__(
self,
nucleus_info,
nucleus_services,
):
"""
Args:
nucleus_info ([ServerInfo]): nucleus server's information.
nucleus_services ([ServicesData]): nucleus server's services
Note:
AboutDialog.FieldDef:
A namedtuple of (name, version) for describing the service's info,
"""
super().__init__(
width=400,
title="About",
ok_handler=lambda self: self.hide(),
ok_label="Close",
modal=True,
)
self._nucleus_info = nucleus_info
self._nucleus_services = self._parse_services(nucleus_services)
self._build_ui()
def _parse_services(self, nucleus_services):
parse_res = set()
if nucleus_services:
for service in nucleus_services:
parse_res.add(
NucleusAboutDialog.FieldDef(
service.service_interface.name,
service.meta.get('version','unknown')
)
)
return parse_res
def _build_ui(self) -> None:
with self._window.frame:
with ui.ZStack(spacing=6):
ui.Rectangle(style_type_name_override="Background")
with ui.VStack(style_type_name_override="Dialog", spacing=6):
ui.Spacer(height=25)
with ui.HStack(style_type_name_override="Dialog", spacing=6, height=60):
ui.Spacer(width=15)
ui.Image(
"resources/glyphs/omniverse_logo.svg",
width=50,
height=50,
alignment=ui.Alignment.CENTER
)
ui.Spacer(width=5)
with ui.VStack(style_type_name_override="Dialog"):
ui.Spacer(height=10)
ui.Label("Nucleus", style={"font_size": 20})
ui.Label(self._nucleus_info.version)
ui.Spacer(height=5)
with ui.HStack(style_type_name_override="Dialog"):
ui.Spacer(width=15)
with ui.VStack(style_type_name_override="Dialog"):
ui.Label("Services", style={"font_size": 20})
for service_name in NucleusAboutDialog._services_names:
self._build_service_item(service_name)
ui.Label("Features", style={"font_size": 20})
self._build_info_item(True, "Versioning")
self._build_info_item(self._nucleus_info.checkpoints_enabled, "Atomic checkpoints")
self._build_info_item(self._nucleus_info.omniojects_enabled, "Omni-objects V2")
self._build_ok_cancel_buttons(disable_cancel_button=True)
def _build_service_item(self, service_name: str):
supported = False
version = "unknown"
for service in self._nucleus_services:
if service.name.startswith(service_name):
supported = True
version = service.version
break
self._build_info_item(supported, service_name + " " + version)
def _build_info_item(self, supported: bool, info: str):
with ui.HStack(style_type_name_override="Dialog", spacing=6):
ui.Spacer(width=5)
image_url = "resources/icons/Ok_64.png" if supported else "resources/icons/Cancel_64.png"
ui.Image(image_url, width=20, height=20, alignment=ui.Alignment.CENTER)
ui.Label(info)
ui.Spacer()
def destroy(self) -> None:
"""Destructor."""
self._window = None
| 4,739 | Python | 42.888888 | 111 | 0.546529 |
omniverse-code/kit/exts/omni.kit.widget.nucleus_info/omni/kit/widget/nucleus_info/tests/test_discovery.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from functools import partial
from unittest.mock import patch
from omni.kit.test.async_unittest import AsyncTestCase
from ..service_discovery import ServiceDiscovery
from ..ui import NucleusAboutDialog
from .. import get_nucleus_info
class MockServiceInterface:
def __init__(self, name):
self.name = name
class MockService:
def __init__(self, name):
self.service_interface = MockServiceInterface(name)
self.meta = {"version": "test_version"}
class MockInfo:
def __init__(self):
self.version = "test_nucleus_version"
self.checkpoints_enabled = True
self.omniojects_enabled = True
class TestDiscovery(AsyncTestCase):
# Before running each test
async def setUp(self):
self._mock_service_content= [MockService("NGSearch"),MockService("Object"),MockService("Search")]
self._mock_service_localhost= [MockService("Object"),MockService("Otherservice")]
# After running each test
async def tearDown(self):
pass
async def _mock_get_nucleus_services_async(self, discovery, url: str):
if url == "omniverse://content":
discovery._nucleus_services["omniverse://content"] = self._mock_service_content
return discovery._nucleus_services["omniverse://content"]
if url == "omniverse://localhost":
discovery._nucleus_services["omniverse://localhost"] = self._mock_service_localhost
return discovery._nucleus_services["omniverse://localhost"]
async def test_service_discovery(self):
discovery = ServiceDiscovery()
test_unknow = await discovery.get_nucleus_services_async("unknow://unknow")
self.assertIsNone(test_unknow)
with patch.object(discovery, "get_nucleus_services_async", side_effect=partial(self._mock_get_nucleus_services_async,discovery)):
content_services = await discovery.get_nucleus_services_async("omniverse://content")
await discovery.get_nucleus_services_async("omniverse://localhost")
self.assertIsNone(discovery.get_nucleus_services("unknow://unknow"))
self.assertTrue(discovery.is_service_supported_for_nucleus("omniverse://content", "NGSearch"))
self.assertFalse(discovery.is_service_supported_for_nucleus("omniverse://localhost", "NGSearch"))
self.assertFalse(discovery.is_service_supported_for_nucleus("l://other", "other"))
self.assertTrue(discovery.is_service_supported_for_nucleus("omniverse://localhost", "Otherservice"))
self.assertEqual(discovery.get_nucleus_services("omniverse://content"), self._mock_service_content)
self.assertEqual(discovery.get_nucleus_services("omniverse://localhost"), self._mock_service_localhost)
dialog = NucleusAboutDialog(MockInfo(), content_services)
dialog.show()
self.assertTrue(dialog._window.visible)
dialog.hide()
self.assertFalse(dialog._window.visible)
dialog.destroy()
discovery.destory()
async def test_interface(self):
inst = get_nucleus_info()
test_unknow = await inst.get_nucleus_services_async("unknow://unknow")
self.assertIsNone(test_unknow)
discovery = ServiceDiscovery()
with patch.object(discovery, "get_nucleus_services_async", side_effect=partial(self._mock_get_nucleus_services_async,discovery)),\
patch.object(discovery, "get_nucleus_services", side_effect=partial(self._mock_get_nucleus_services_async,discovery)),\
patch.object(inst, "_discovery", side_effect=discovery):
await discovery.get_nucleus_services_async("omniverse://content")
await discovery.get_nucleus_services_async("omniverse://localhost")
self.assertTrue(inst.is_service_available("omniverse://content", "NGSearch"))
self.assertTrue(inst.is_service_available("omniverse://localhost", "Otherservice"))
discovery.destory()
inst._discovery = None
self.assertIsNone(inst.get_nucleus_services("omniverse://content"))
self.assertIsNone(inst.get_nucleus_services("omniverse://localhost"))
| 4,619 | Python | 49.76923 | 139 | 0.68976 |
omniverse-code/kit/exts/omni.kit.widget.nucleus_info/omni/kit/widget/nucleus_info/tests/__init__.py | from .test_discovery import *
| 30 | Python | 14.499993 | 29 | 0.766667 |
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/event.py | import carb.events
HOTKEY_REGISTER_EVENT: int = carb.events.type_from_string("omni.kit.hotkeys.core.HOTKEY_REGISTER")
HOTKEY_DEREGISTER_EVENT: int = carb.events.type_from_string("omni.kit.hotkeys.core.HOTKEY_DEREGISTER")
HOTKEY_CHANGED_EVENT: int = carb.events.type_from_string("omni.kit.hotkeys.core.HOTKEY_CHANGED")
| 319 | Python | 52.333325 | 102 | 0.789969 |
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/registry.py | __all__ = ["HotkeyRegistry"]
from typing import List, Optional, Union, Dict, Tuple
import carb
import carb.settings
import omni.kit.app
from .hotkey import Hotkey
from .key_combination import KeyCombination
from .filter import HotkeyFilter
from .storage import HotkeyStorage
from .event import HOTKEY_REGISTER_EVENT, HOTKEY_DEREGISTER_EVENT, HOTKEY_CHANGED_EVENT
from .keyboard_layout import KeyboardLayoutDelegate
# Extension who register hotkey for menu items
HOTKEY_EXT_ID_MENU_UTILS = "omni.kit.menu.utils"
SETTING_DEFAULT_KEYBOARD_LAYOUT = "/exts/omni.kit.hotkeys.core/default_keyboard_layout"
class HotkeyRegistry:
"""
Registry of hotkeys.
"""
class Result:
OK = "OK"
ERROR_NO_ACTION = "No action defined"
ERROR_ACTION_DUPLICATED = "Duplicated action definition"
ERROR_KEY_INVALID = "Invaid key definition"
ERROR_KEY_DUPLICATED = "Duplicated key definition"
def __init__(self):
"""
Define hotkey registry object.
"""
self._hotkeys: List[Hotkey] = []
self._hotkeys_by_key_and_context: Dict[KeyCombination, Dict[str, Hotkey]] = {}
self._hotkeys_by_key_and_window: Dict[KeyCombination, Dict[str, Hotkey]] = {}
self._global_hotkeys_by_key: Dict[KeyCombination, Hotkey] = {}
self._event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
self.__hotkey_storage = HotkeyStorage()
self.__default_key_combinations: Dict[str, str] = {}
self.__default_filters: Dict[str, HotkeyFilter] = {}
self.__last_error = HotkeyRegistry.Result.OK
self.__settings = carb.settings.get_settings()
keyboard_layout = self.__settings.get("/persistent" + SETTING_DEFAULT_KEYBOARD_LAYOUT)
if keyboard_layout is None:
keyboard_layout = self.__settings.get(SETTING_DEFAULT_KEYBOARD_LAYOUT)
self.__keyboard_layout = KeyboardLayoutDelegate.get_instance(keyboard_layout)
# Here we only append user hotkeys.
# For system hotkeys which is changed, update when registering.
self.__append_user_hotkeys()
@property
def last_error(self) -> "HotkeyRegistry.Result":
"""
Error code for last hotkey command.
"""
return self.__last_error
@property
def keyboard_layout(self) -> Optional[KeyboardLayoutDelegate]:
"""
Current keyboard layout object in using.
"""
return self.__keyboard_layout
def switch_layout(self, layout_name: str) -> None:
"""
Change keyboard layout.
Args:
layout_name (str): Name of keyboard layout to use.
"""
def __get_layout_keys() -> List[Hotkey]:
# Ignore user hotkeys and modified hotkeys
return [hotkey for hotkey in self._hotkeys if not self.is_user_hotkey(hotkey) and self.get_hotkey_default(hotkey)[0] == hotkey.key_combination.id]
layout = KeyboardLayoutDelegate.get_instance(layout_name)
if not layout or layout == self.__keyboard_layout:
return
carb.log_info(f"Change keyboard layout to {layout_name}")
refresh_menu = False
# Restore hotkey key combination to default
for hotkey in __get_layout_keys():
# Restore key combination
if self.__keyboard_layout:
restore_key_combination = self.__keyboard_layout.restore_key(hotkey.key_combination)
if restore_key_combination:
self.__edit_hotkey_internal(hotkey, restore_key_combination, filter=hotkey.filter)
# Map to new key combination
new_key_combination = layout.map_key(hotkey.key_combination)
if new_key_combination:
self.__edit_hotkey_internal(hotkey, new_key_combination, filter=hotkey.filter)
self.__default_key_combinations[hotkey.id] = new_key_combination.id
if (restore_key_combination or new_key_combination) and hotkey.hotkey_ext_id == HOTKEY_EXT_ID_MENU_UTILS:
refresh_menu = True
self.__keyboard_layout = layout
self.__settings.set("/persistent" + SETTING_DEFAULT_KEYBOARD_LAYOUT, layout_name)
if refresh_menu:
# Refresh menu items for new hotkey text
try:
import omni.kit.menu.utils # pylint: disable=redefined-outer-name
omni.kit.menu.utils.rebuild_menus()
except ImportError:
pass
def register_hotkey(self, *args, **kwargs) -> Optional[Hotkey]:
"""
Register hotkey by hotkey object or arguments.
Args could be:
.. code:: python
register_hotkey(hotkey: Hotkey)
or
.. code:: python
register_hotkey(
hotkey_ext_id: str,
key: Union[str, KeyCombination],
action_ext_id: str,
action_id: str,
filter: Optional[HotkeyFilter] = None
)
Returns:
Created hotkey object if register succeeded. Otherwise return None.
"""
return self._register_hotkey_obj(args[0]) if len(args) == 1 else self._register_hotkey_args(*args, **kwargs)
def edit_hotkey(
self,
hotkey: Hotkey,
key: Union[str, KeyCombination],
filter: Optional[HotkeyFilter] # noqa: A002 # pylint: disable=redefined-builtin
) -> "HotkeyRegistry.Result":
"""
Change key combination of hotkey object.
Args:
hotkey (Hotkey): Hotkey object to change.
key (Union[str, KeyCombination]): New key combination.
filter (Optional[HotkeyFiler]): New filter.
Returns:
Result code.
"""
key_combination = KeyCombination(key) if isinstance(key, str) else key
self.__last_error = self.verify_hotkey(hotkey, key_combination=key_combination, hotkey_filter=filter)
if self.__last_error != HotkeyRegistry.Result.OK:
return self.__last_error
self.__edit_hotkey_internal(hotkey, key_combination, filter)
self.__hotkey_storage.edit_hotkey(hotkey)
if hotkey.hotkey_ext_id == HOTKEY_EXT_ID_MENU_UTILS:
# Refresh menu items for new hotkey text
try:
import omni.kit.menu.utils # pylint: disable=redefined-outer-name
omni.kit.menu.utils.rebuild_menus()
except ImportError:
pass
return HotkeyRegistry.Result.OK
def __edit_hotkey_internal(
self,
hotkey: Hotkey,
key_combination: KeyCombination,
filter: Optional[HotkeyFilter] # noqa: A002 # pylint: disable=redefined-builtin
) -> None:
self.__deregister_hotkey_maps(hotkey)
hotkey.key_combination = key_combination
hotkey.filter = filter
self.__register_hotkey_maps(hotkey)
self._send_event(HOTKEY_CHANGED_EVENT, hotkey)
def deregister_hotkey(self, *args, **kwargs) -> bool:
"""
Deregister hotkey by hotkey object or arguments.
Args could be:
.. code:: python
deregister_hotkey(hotkey: Hotkey)
or
.. code:: python
deregister_hotkey(
hotkey_ext_id: str,
key: Union[str, KeyCombination],
filter: Optional[HotkeyFilter] = None
)
Returns:
True if hotkey found. Otherwise return False.
"""
return self._deregister_hotkey_obj(args[0]) if len(args) == 1 else self._deregister_hotkey_args(*args, **kwargs)
def deregister_hotkeys(self, hotkey_ext_id: str, key: Union[str, KeyCombination]) -> None:
"""
Deregister hotkeys registered from a special extension with speicial key combination.
Args:
hotkey_ext_id (str): Extension id that hotkeys belongs to.
key (Union[str, KeyCombination]): Key combination.
"""
discovered_hotkeys = self.get_hotkeys(hotkey_ext_id, key)
for hotkey in discovered_hotkeys:
self._deregister_hotkey_obj(hotkey)
def deregister_all_hotkeys_for_extension(self, hotkey_ext_id: Optional[str]) -> None:
"""
Deregister hotkeys registered from a special extension.
Args:
hotkey_ext_id (Optional[str]): Extension id that hotkeys belongs to. If None, discover all global hotkeys
"""
discovered_hotkeys = self.get_all_hotkeys_for_extension(hotkey_ext_id)
for hotkey in discovered_hotkeys:
self._deregister_hotkey_obj(hotkey)
def deregister_all_hotkeys_for_filter(self, filter: HotkeyFilter) -> None: # noqa: A002 # pylint: disable=redefined-builtin
"""
Deregister hotkeys registered with speicial filter.
Args:
filter (HotkeyFilter): Hotkey HotkeyFilter.
"""
discovered_hotkeys = self.get_all_hotkeys_for_filter(filter)
for hotkey in discovered_hotkeys:
self._deregister_hotkey_obj(hotkey)
def get_hotkey(self, hotkey_ext_id: str, key: Union[str, KeyCombination], filter: Optional[HotkeyFilter] = None) -> Optional[Hotkey]: # noqa: A002 # pylint: disable=redefined-builtin
"""
Discover a registered hotkey.
Args:
hotkey_ext_id (str): Extension id which owns the hotkey.
key (Union[str, KeyCombination]): Key combination.
Keyword Args:
filter (Optional[HotkeyFilter]): Hotkey filter. Default None
Returns:
Hotkey object if discovered. Otherwise None.
"""
key_combination = KeyCombination(key) if isinstance(key, str) else key
for hotkey in self._hotkeys:
if hotkey.hotkey_ext_id == hotkey_ext_id and hotkey.key_combination == key_combination and hotkey.filter == filter:
return hotkey
return None
def get_hotkey_for_trigger(self, key: Union[str, KeyCombination], context: Optional[str] = None, window: Optional[str] = None) -> Optional[Hotkey]:
"""
Discover hotkey for trigger from key combination and filter.
Args:
key (Union[str, KeyCombination]): Key combination.
Keyword Args:
context (str): Context assigned to Hotkey
window (str): Window assigned to Hotkey
Returns:
Hotkey object if discovered. Otherwise None.
"""
key_combination = KeyCombination(key) if isinstance(key, str) else key
if context:
return (
self._hotkeys_by_key_and_context[key_combination][context]
if key_combination in self._hotkeys_by_key_and_context and context in self._hotkeys_by_key_and_context[key_combination]
else None
)
if window:
return (
self._hotkeys_by_key_and_window[key_combination][window]
if key_combination in self._hotkeys_by_key_and_window and window in self._hotkeys_by_key_and_window[key_combination]
else None
)
return self._global_hotkeys_by_key[key_combination] if key_combination in self._global_hotkeys_by_key else None
def get_hotkey_for_filter(self, key: Union[str, KeyCombination], filter: HotkeyFilter) -> Optional[Hotkey]: # noqa: A002 # pylint: disable=redefined-builtin
"""
Discover hotkey registered with special key combination and filter
Args:
key (Union[str, KeyCombination]): Key combination.
filter (HotkeyFilter): Hotkey filter.
Returns:
First discovered hotkey. None if nothing found.
"""
if filter:
if filter.context:
return self.get_hotkey_for_trigger(key, context=filter.context)
if filter.windows:
for window in filter.windows:
found = self.get_hotkey_for_trigger(key, window=window)
if found:
return found
return None
return self.get_hotkey_for_trigger(key)
def get_hotkeys(self, hotkey_ext_id: str, key: Union[str, KeyCombination]) -> List[Hotkey]:
"""
Discover hotkeys registered from a special extension with special key combination.
Args:
hotkey_ext_id (str): Extension id that hotkeys belongs to.
key (Union[str, KeyCombination]): Key combination.
Returns:
List of discovered hotkeys.
"""
key_combination = KeyCombination(key) if isinstance(key, str) else key
return [hotkey for hotkey in self._hotkeys if hotkey.hotkey_ext_id == hotkey_ext_id and hotkey.key_combination == key_combination]
def get_all_hotkeys(self) -> List[Hotkey]:
"""
Discover all registered hotkeys.
Returns:
List of all registered hotkeys.
"""
return self._hotkeys
def get_all_hotkeys_for_extension(self, hotkey_ext_id: Optional[str]) -> List[Hotkey]:
"""
Discover hotkeys registered from a special extension.
Args:
hotkey_ext_id (Optional[str]): Extension id that hotkeys belongs to. If None, discover all global hotkeys
Returns:
List of discovered hotkeys.
"""
return [hotkey for hotkey in self._hotkeys if hotkey.filter is None] if hotkey_ext_id is None \
else [hotkey for hotkey in self._hotkeys if hotkey.hotkey_ext_id == hotkey_ext_id]
def get_all_hotkeys_for_key(self, key: Union[str, KeyCombination]) -> List[Hotkey]:
"""
Discover hotkeys registered from a special key.
Args:
key (Union[str, KeyCombination]): Key combination.
Returns:
List of discovered hotkeys.
"""
key_combination = KeyCombination(key) if isinstance(key, str) else key
return [hotkey for hotkey in self._hotkeys if hotkey.key_combination == key_combination]
def get_all_hotkeys_for_filter(self, filter: HotkeyFilter) -> List[Hotkey]: # noqa: A002 # pylint: disable=redefined-builtin
"""
Discover hotkeys registered with speicial filter.
Args:
filter (HotkeyFilter): Hotkey HotkeyFilter.
Returns:
List of discovered hotkeys.
"""
return [hotkey for hotkey in self._hotkeys if hotkey.filter == filter]
def _register_hotkey_obj(self, hotkey: Hotkey) -> Optional[Hotkey]:
self.__last_error = self.has_duplicated_hotkey(hotkey)
if self.__last_error != HotkeyRegistry.Result.OK:
carb.log_warn(f"[Hotkey] Cannot register {hotkey}, error code: {self.__last_error}")
return None
# Record default key binding and filter
default_key_combination = hotkey.key_combination
default_filter = hotkey.filter
# Update key binding from keyboard layout
if self.__keyboard_layout and not self.is_user_hotkey(hotkey):
new_key_combination = self.__keyboard_layout.map_key(hotkey.key_combination)
if new_key_combination:
hotkey.key_combination = new_key_combination
default_key_combination = new_key_combination
# Update key binding/filter definition from storage
user_hotkey = self.__hotkey_storage.get_hotkey(hotkey)
if user_hotkey:
if hotkey.key_combination != user_hotkey.key_combination:
carb.log_info(f"[Hotkey] Replace {hotkey.action_text}.{hotkey.key_text} with {user_hotkey.key_text}")
hotkey.key_combination = user_hotkey.key_combination
if hotkey.filter != user_hotkey.filter:
carb.log_info(f"[Hotkey] Replace {hotkey.action_text}.{hotkey.filter_text} with {user_hotkey.filter_text}")
hotkey.filter = user_hotkey.filter
self.__last_error = self.verify_hotkey(hotkey)
if self.__last_error != HotkeyRegistry.Result.OK:
carb.log_warn(f"[Hotkey] Cannot register {hotkey}, error code: {self.__last_error}")
return None
# Append hotkey
self._hotkeys.append(hotkey)
self.__default_key_combinations[hotkey.id] = default_key_combination.id
self.__default_filters[hotkey.id] = default_filter
self.__register_hotkey_maps(hotkey)
# Save to storage
self.__hotkey_storage.register_user_hotkey(hotkey)
self._send_event(HOTKEY_REGISTER_EVENT, hotkey)
return hotkey
def _register_hotkey_args(
self,
hotkey_ext_id: str,
key: Union[str, KeyCombination],
action_ext_id: str,
action_id: str,
filter: Optional[HotkeyFilter] = None # noqa: A002 # pylint: disable=redefined-builtin
) -> Optional[Hotkey]:
hotkey = Hotkey(hotkey_ext_id, key, action_ext_id, action_id, filter=filter)
return self._register_hotkey_obj(hotkey)
def _deregister_hotkey_obj(self, hotkey: Hotkey) -> bool:
if hotkey in self._hotkeys:
self._hotkeys.remove(hotkey)
self.__deregister_hotkey_maps(hotkey)
self.__default_key_combinations.pop(hotkey.id)
self.__default_filters.pop(hotkey.id)
self.__hotkey_storage.deregister_hotkey(hotkey)
self._send_event(HOTKEY_DEREGISTER_EVENT, hotkey)
return True
return False
def _deregister_hotkey_args(
self,
hotkey_ext_id: str,
key: Union[str, KeyCombination],
filter: Optional[HotkeyFilter] = None # noqa: A002 # pylint: disable=redefined-builtin
) -> bool:
hotkey = self.get_hotkey(hotkey_ext_id, key, filter=filter)
return self._deregister_hotkey_obj(hotkey) if hotkey else False
def _send_event(self, event: int, hotkey: Hotkey):
self._event_stream.push(
event,
payload={
"hotkey_ext_id": hotkey.hotkey_ext_id,
"key": hotkey.key_combination.as_string,
"trigger_press": hotkey.key_combination.trigger_press,
"action_ext_id": hotkey.action.extension_id if hotkey.action else "",
"action_id": hotkey.action.id if hotkey.action else ""
}
)
def __register_hotkey_maps(self, hotkey: Hotkey) -> None:
if hotkey.key_combination.key == "":
return
if hotkey.filter is None:
self._global_hotkeys_by_key[hotkey.key_combination] = hotkey
else:
if hotkey.filter.context:
if hotkey.key_combination not in self._hotkeys_by_key_and_context:
self._hotkeys_by_key_and_context[hotkey.key_combination] = {}
if hotkey.filter.context in self._hotkeys_by_key_and_context[hotkey.key_combination]:
carb.log_warn(f"Hotkey {hotkey.key_combination.as_string} to context {hotkey.filter.context} already exists: ")
old_hotkey = self._hotkeys_by_key_and_context[hotkey.key_combination][hotkey.filter.context]
carb.log_warn(f" existing from {old_hotkey.hotkey_ext_id}")
carb.log_warn(f" replace with the one from {hotkey.hotkey_ext_id}")
self._hotkeys_by_key_and_context[hotkey.key_combination][hotkey.filter.context] = hotkey
if hotkey.filter.windows:
if hotkey.key_combination not in self._hotkeys_by_key_and_window:
self._hotkeys_by_key_and_window[hotkey.key_combination] = {}
for window in hotkey.filter.windows:
if window in self._hotkeys_by_key_and_window[hotkey.key_combination]:
carb.log_warn(f"Hotkey {hotkey.key_combination.as_string} to window {window} already exists: ")
old_hotkey = self._hotkeys_by_key_and_window[hotkey.key_combination][window]
carb.log_warn(f" existing from {old_hotkey.hotkey_ext_id}")
carb.log_warn(f" replace with the one from {hotkey.hotkey_ext_id}")
self._hotkeys_by_key_and_window[hotkey.key_combination][window] = hotkey
def __deregister_hotkey_maps(self, hotkey: Hotkey) -> bool:
if hotkey.key_combination.key == "":
return
if hotkey.filter:
if hotkey.filter.context \
and hotkey.filter.context in self._hotkeys_by_key_and_context[hotkey.key_combination] \
and self._hotkeys_by_key_and_context[hotkey.key_combination][hotkey.filter.context] == hotkey:
self._hotkeys_by_key_and_context[hotkey.key_combination].pop(hotkey.filter.context)
if hotkey.filter.windows:
for window in hotkey.filter.windows:
if window in self._hotkeys_by_key_and_window[hotkey.key_combination] \
and self._hotkeys_by_key_and_window[hotkey.key_combination][window] == hotkey:
self._hotkeys_by_key_and_window[hotkey.key_combination].pop(window)
else:
if hotkey.key_combination in self._global_hotkeys_by_key:
self._global_hotkeys_by_key.pop(hotkey.key_combination)
def __append_user_hotkeys(self):
user_hotkeys = self.__hotkey_storage.get_user_hotkeys()
for hotkey in user_hotkeys:
self._hotkeys.append(hotkey)
self.__default_key_combinations[hotkey.id] = hotkey.key_combination.id
self.__default_filters[hotkey.id] = hotkey.filter
self.__register_hotkey_maps(hotkey)
def clear_storage(self) -> None:
"""
Clear user defined hotkeys.
"""
user_hotkeys = self.__hotkey_storage.get_user_hotkeys()
for hotkey in user_hotkeys:
if hotkey in self._hotkeys:
self._hotkeys.remove(hotkey)
self.__deregister_hotkey_maps(hotkey)
self.__default_key_combinations.pop(hotkey.id)
self.__default_filters.pop(hotkey.id)
self.__hotkey_storage.clear_hotkeys()
def export_storage(self, url: str) -> None:
"""
Export user defined hotkeys to file.
Args:
url (str): File path to export user defined hotkeys.
"""
self.__hotkey_storage.save_preset(url)
def import_storage(self, url: str) -> bool:
"""
Import user defined hotkeys from file.
Args:
url (str): File path to import user defined hotkeys.
"""
preset = self.__hotkey_storage.preload_preset(url)
if preset is None:
return False
# First we need to restore all hotkeys
self.restore_defaults()
self.__hotkey_storage.load_preset(preset)
# For system hotkeys, change to new definition in preset
for hotkey in self._hotkeys:
user_hotkey = self.__hotkey_storage.get_hotkey(hotkey)
if user_hotkey:
self.__deregister_hotkey_maps(hotkey)
if hotkey.key_combination != user_hotkey.key_combination:
carb.log_info(f"[Hotkey] Replace {hotkey.action_text}.{hotkey.key_text} with {user_hotkey.key_text}")
hotkey.key_combination = user_hotkey.key_combination
if hotkey.filter != user_hotkey.filter:
carb.log_info(f"[Hotkey] Replace {hotkey.action_text}.{hotkey.filter_text} with {user_hotkey.filter_text}")
hotkey.filter = user_hotkey.filter
self.__register_hotkey_maps(hotkey)
# Apppend user hotkeys
self.__append_user_hotkeys()
return True
def has_duplicated_hotkey(self, hotkey: Hotkey) -> "HotkeyRegistry.Result":
"""
Check if already have hotkey registered.
Args:
hotkey (Hotkey): Hotkey object to check.
Returns:
Result code.
"""
exist_hotkey = self.__default_key_combinations.get(hotkey.id, None)
if exist_hotkey:
carb.log_warn(f"[Hotkey] duplicated action as {exist_hotkey} with {hotkey.id}!")
return HotkeyRegistry.Result.ERROR_ACTION_DUPLICATED
return HotkeyRegistry.Result.OK
def verify_hotkey(self, hotkey: Hotkey, key_combination: Optional[KeyCombination] = None, hotkey_filter: Optional[HotkeyFilter] = None) -> "HotkeyRegistry.Result":
"""
Verify hotkey.
"""
if not hotkey.action_text:
return HotkeyRegistry.Result.ERROR_NO_ACTION
if key_combination is None:
key_combination = hotkey.key_combination
if not key_combination.is_valid:
return HotkeyRegistry.Result.ERROR_KEY_INVALID
if key_combination.key != "":
hotkey_filter = hotkey.filter if hotkey_filter is None else hotkey_filter
found = self.get_hotkey_for_filter(key_combination, hotkey_filter)
if found and found.id != hotkey.id:
carb.log_warn(f"[Hotkey] duplicated key:'{key_combination}'")
carb.log_warn(f" -- {hotkey}")
carb.log_warn(f" -- {found}")
return HotkeyRegistry.Result.ERROR_KEY_DUPLICATED
return HotkeyRegistry.Result.OK
def get_hotkey_default(self, hotkey: Hotkey) -> Tuple[str, HotkeyFilter]:
"""
Discover hotkey default key binding and filter.
Args:
hotkey (Hotkey): Hotkey object.
Returns:
Tuple of key binding string and hotkey filter object.
"""
return (
self.__default_key_combinations.get(hotkey.id, None),
self.__default_filters.get(hotkey.id, None)
)
def restore_defaults(self) -> None:
"""
Clean user defined hotkeys and restore system hotkey to default
"""
to_remove_hotkeys = []
for hotkey in self._hotkeys:
saved_hotkey = self.__hotkey_storage.get_hotkey(hotkey)
if saved_hotkey:
if self.__hotkey_storage.is_user_hotkey(hotkey):
# User-defined hotkey, remove later
self.__deregister_hotkey_maps(hotkey)
self.__default_key_combinations.pop(hotkey.id, None)
self.__default_filters.pop(hotkey.id, None)
to_remove_hotkeys.append(hotkey)
else:
# System hotkey, restore key-bindings and filter
self.__deregister_hotkey_maps(hotkey)
if hotkey.id in self.__default_key_combinations:
hotkey.key_combination = KeyCombination(self.__default_key_combinations[hotkey.id])
if hotkey.id in self.__default_filters:
hotkey.filter = self.__default_filters[hotkey.id]
self.__register_hotkey_maps(hotkey)
for hotkey in to_remove_hotkeys:
self._hotkeys.remove(hotkey)
self.__hotkey_storage.clear_hotkeys()
def is_user_hotkey(self, hotkey: Hotkey) -> bool:
"""
If a user defined hotkey.
Args:
hotkey (Hotkey): Hotkey object.
Returns:
True if user defined. Otherwise False.
"""
return self.__hotkey_storage.is_user_hotkey(hotkey)
| 27,402 | Python | 40.207519 | 187 | 0.605613 |
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/trigger.py | __all__ = ["HotkeyTrigger"]
import asyncio
import carb
import carb.input
import omni.appwindow
import omni.kit.app
from .registry import HotkeyRegistry
from .context import HotkeyContext
from .key_combination import KeyCombination
from .hovered_window import get_hovered_window
SETTING_ALLOW_LIST = "/exts/omni.kit.hotkeys.core/allow_list"
class HotkeyTrigger:
def __init__(self, registry: HotkeyRegistry, context: HotkeyContext):
"""
Trigger hotkey on keyboard input.
Args:
registry (HotkeyRegistry): Hotkey registry.
context (HotkeyContext): Hotkey context.
"""
self._registry = registry
self._context = context
self._input = carb.input.acquire_input_interface()
self._input_sub_id = self._input.subscribe_to_input_events(self._on_input_event, order=0)
self.__app_window = omni.appwindow.get_default_app_window()
self._stop_event = asyncio.Event()
self._work_queue = asyncio.Queue()
self.__run_future = asyncio.ensure_future(self._run())
self.__settings = carb.settings.get_settings()
self._allow_list = self.__settings.get(SETTING_ALLOW_LIST)
def __on_allow_list_change(value, event_type) -> None:
self._allow_list = self.__settings.get(SETTING_ALLOW_LIST)
self._sub_allow_list = omni.kit.app.SettingChangeSubscription(SETTING_ALLOW_LIST, __on_allow_list_change)
def destroy(self):
self._stop_event.set()
self._work_queue.put_nowait((None, None, None))
self.__run_future.cancel()
self._input.unsubscribe_to_input_events(self._input_sub_id)
self._input_sub_id = None
self._input = None
self._sub_allow_list = None
def _on_input_event(self, event, *_):
if event.deviceType == carb.input.DeviceType.KEYBOARD \
and event.event.type in [carb.input.KeyboardEventType.KEY_PRESS, carb.input.KeyboardEventType.KEY_RELEASE]:
is_down = event.event.type == carb.input.KeyboardEventType.KEY_PRESS
if event.deviceType == carb.input.DeviceType.KEYBOARD:
key_combination = KeyCombination(event.event.input, modifiers=event.event.modifiers, trigger_press=is_down)
if not self._allow_list or key_combination.as_string in self._allow_list and self._registry.get_all_hotkeys_for_key(key_combination):
(mouse_pos_x, mouse_pos_y) = self._input.get_mouse_coords_pixel(self.__app_window.get_mouse())
self._work_queue.put_nowait((key_combination, mouse_pos_x, mouse_pos_y))
return True
def __trigger(self, key_combination: KeyCombination, pos_x: float, pos_y: float):
hotkey = None
# First: find hotkey assigned to current context
current_context = self._context.get()
if current_context:
hotkey = self._registry.get_hotkey_for_trigger(key_combination, context=current_context)
if not hotkey:
current_window = get_hovered_window(pos_x, pos_y)
if current_window:
hotkey = self._registry.get_hotkey_for_trigger(key_combination, window=current_window.title)
if not hotkey:
# Finally: No context/window hotkey found, find global hotkey
hotkey = self._registry.get_hotkey_for_trigger(key_combination)
if hotkey:
hotkey.execute()
async def _run(self):
while not self._stop_event.is_set():
(key_combination, pos_x, pos_y) = await self._work_queue.get()
self.__trigger(key_combination, pos_x, pos_y)
| 3,635 | Python | 38.956044 | 149 | 0.644567 |
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/extension.py | # pylint: disable=attribute-defined-outside-init
__all__ = ["get_hotkey_context", "get_hotkey_registry", "HotkeysExtension"]
import omni.ext
import carb
from .context import HotkeyContext
from .registry import HotkeyRegistry
from .trigger import HotkeyTrigger
from .keyboard_layout import USKeyboardLayout, GermanKeyboardLayout, FrenchKeyboardLayout
_hotkey_context = None
_hotkey_registry = None
# public API
def get_hotkey_context() -> HotkeyContext:
"""
Get the hotkey context.
Return:
HotkeyContext object which implements the hotkey context interface.
"""
return _hotkey_context
def get_hotkey_registry() -> HotkeyRegistry:
"""
Get the hotkey registry.
Return:
HotkeyRegistry object which implements the hotkey registry interface.
"""
return _hotkey_registry
class HotkeysExtension(omni.ext.IExt):
"""
Hotkeys extension.
"""
def on_startup(self, ext_id):
"""
Extension startup entrypoint.
"""
self._us_keyboard_layout = USKeyboardLayout()
self._german_keyboard_layput = GermanKeyboardLayout()
self._french_keyboard_layout = FrenchKeyboardLayout()
global _hotkey_context, _hotkey_registry
_hotkey_context = HotkeyContext()
_hotkey_registry = HotkeyRegistry()
self._hotkey_trigger = None
_settings = carb.settings.get_settings()
enabled = _settings.get("/exts/omni.kit.hotkeys.core/hotkeys_enabled")
if enabled:
self._hotkey_trigger = HotkeyTrigger(_hotkey_registry, _hotkey_context)
else:
carb.log_info("All Hotkeys disabled via carb setting /exts/omni.kit.hotkeys.core/hotkeys_enabled=false")
def on_shutdown(self):
if self._hotkey_trigger:
self._hotkey_trigger.destroy()
self._us_keyboard_layout = None
self._german_keyboard_layput = None
self._french_keyboard_layout = None
global _hotkey_context, _hotkey_registry
_hotkey_context = None
_hotkey_registry = None
| 2,066 | Python | 27.315068 | 116 | 0.668441 |
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/__init__.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""
Omni Kit Hotkeys Core
---------------------
Omni Kit Hotkeys Core is a framework for creating, registering, and discovering hotkeys.
Here is an example of registering an hokey from Python that execute action "omni.kit.window.file::new" to create a new file when CTRL + N pressed:
.. code-block::
hotkey_registry = omni.kit.hotkeys.core.get_hotkey_registry()
hotkey_registry.register_hotkey(
"your_extension_id",
"CTRL + N",
"omni.kit.window.file",
"new",
filter=None,
)
For more examples, please consult the Usage Examples page.
"""
from .key_combination import KeyCombination
from .hotkey import Hotkey
from .registry import HotkeyRegistry
from .filter import HotkeyFilter
from .extension import HotkeysExtension, get_hotkey_context, get_hotkey_registry
from .event import HOTKEY_REGISTER_EVENT, HOTKEY_DEREGISTER_EVENT, HOTKEY_CHANGED_EVENT
from .keyboard_layout import KeyboardLayoutDelegate
__all__ = [
"KeyCombination",
"Hotkey",
"HotkeyRegistry",
"HotkeyFilter",
"HotkeysExtension",
"get_hotkey_context",
"get_hotkey_registry",
"HOTKEY_REGISTER_EVENT",
"HOTKEY_DEREGISTER_EVENT",
"HOTKEY_CHANGED_EVENT",
]
| 1,645 | Python | 30.056603 | 146 | 0.728267 |
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/storage.py | __all__ = ["HotkeyDescription", "HotkeyStorage"]
import json
from dataclasses import dataclass, asdict
from typing import List, Optional, Dict, Tuple
import carb.settings
from .hotkey import Hotkey
from .filter import HotkeyFilter
from .key_combination import KeyCombination
# Hotkey ext id for all hotkeys created from here
USER_HOTKEY_EXT_ID = "omni.kit.hotkeys.window"
SETTING_USER_HOTKEYS = "/persistent/omni.kit.hotkeys.core/userHotkeys"
@dataclass
class HotkeyDescription:
hotkey_ext_id: str = ""
action_ext_id: str = ""
action_id: str = ""
key: str = ""
trigger_press: bool = True
context: str = None
windows: str = None
@staticmethod
def from_hotkey(hotkey: Hotkey):
(context, windows) = HotkeyDescription.get_filter_string(hotkey)
return HotkeyDescription(
hotkey_ext_id=hotkey.hotkey_ext_id,
action_ext_id=hotkey.action_ext_id,
action_id=hotkey.action_id,
key=hotkey.key_combination.as_string,
trigger_press=hotkey.key_combination.trigger_press,
context=context,
windows=windows,
)
@property
def id(self) -> str: # noqa: A003
return self.to_hotkey().id
def to_hotkey(self) -> Hotkey:
if self.context or self.windows:
hotkey_filter = HotkeyFilter(context=self.context if self.context else None, windows=self.windows.split(",") if self.windows else None)
else:
hotkey_filter = None
key = KeyCombination(self.key, trigger_press=self.trigger_press)
return Hotkey(self.hotkey_ext_id, key, self.action_ext_id, self.action_id, filter=hotkey_filter)
def update(self, hotkey: Hotkey) -> None:
self.key = hotkey.key_combination.as_string
self.trigger_press = hotkey.key_combination.trigger_press
(self.context, self.windows) = HotkeyDescription.get_filter_string(hotkey)
@staticmethod
def get_filter_string(hotkey: Hotkey) -> Tuple[str, str]:
return (
hotkey.filter.context if hotkey.filter and hotkey.filter else "",
",".join(hotkey.filter.windows) if hotkey.filter and hotkey.filter.windows else ""
)
class HotkeyStorage:
def __init__(self):
self.__settings = carb.settings.get_settings()
self.__hotkey_descs: List[HotkeyDescription] = [HotkeyDescription(**desc) for desc in self.__settings.get(SETTING_USER_HOTKEYS) or []]
carb.log_info(f"[Hotkey] {len(self.__hotkey_descs)} user defined hotkeys")
def get_hotkey(self, hotkey: Hotkey) -> Optional[Hotkey]:
"""
Get hotkey definition in storage.
"""
hotkey_desc = self.__find_hotkey_desc(hotkey)
return hotkey_desc.to_hotkey() if hotkey_desc else None
def get_user_hotkeys(self) -> List[Hotkey]:
"""
Get all user-defined hotkeys.
"""
user_hotkeys: List[Hotkey] = []
for hotkey_desc in self.__hotkey_descs:
hotkey = hotkey_desc.to_hotkey()
if self.is_user_hotkey(hotkey):
user_hotkeys.append(hotkey)
return user_hotkeys
def get_hotkeys(self) -> List[Hotkey]:
"""
Discover all hotkey definitions in this storage.
"""
return [desc.to_hotkey() for desc in self.__hotkey_descs]
def register_user_hotkey(self, hotkey: Hotkey):
"""
Register user hotkey.
"""
if self.is_user_hotkey(hotkey):
# This is user defined hotkey
hotkey_desc = HotkeyDescription().from_hotkey(hotkey)
self.__hotkey_descs.append(hotkey_desc)
self.__settings.set(SETTING_USER_HOTKEYS, [asdict(desc) for desc in self.__hotkey_descs])
def edit_hotkey(self, hotkey: Hotkey):
"""
Edit hotkey.
This could be a user-defined hotkey or system hotkey but changed by user.
"""
# This is system hotkey but user changed key bindings, etc.
hotkey_desc = self.__find_hotkey_desc(hotkey)
if hotkey_desc:
hotkey_desc.update(hotkey)
else:
hotkey_desc = HotkeyDescription().from_hotkey(hotkey)
self.__hotkey_descs.append(hotkey_desc)
self.__settings.set(SETTING_USER_HOTKEYS, [asdict(desc) for desc in self.__hotkey_descs])
def deregister_hotkey(self, hotkey: Hotkey):
"""
Deregister user hotkey from storage.
For system hotkey, keep in storage to reload when register again
"""
if self.is_user_hotkey(hotkey):
hotkey_desc = HotkeyDescription().from_hotkey(hotkey)
if hotkey_desc in self.__hotkey_descs:
self.__hotkey_descs.remove(hotkey_desc)
self.__settings.set(SETTING_USER_HOTKEYS, [asdict(desc) for desc in self.__hotkey_descs])
def __find_hotkey_desc(self, hotkey: Hotkey) -> Optional[HotkeyDescription]:
"""
Find if there is user-defined hotkey
"""
for hotkey_desc in self.__hotkey_descs:
if hotkey_desc.id == hotkey.id:
return hotkey_desc
return None
def clear_hotkeys(self) -> None:
"""
Clear all hotkeys in storage
"""
self.__hotkey_descs = []
self.__settings.set(SETTING_USER_HOTKEYS, [])
def is_user_hotkey(self, hotkey: Hotkey) -> bool:
"""
If a user-defined hotkey
"""
return hotkey.hotkey_ext_id == USER_HOTKEY_EXT_ID
def save_preset(self, url: str) -> bool:
"""
Save storage to file.
"""
output = {
"Type": "Hotkey Preset",
"Keys": [asdict(desc) for desc in self.__hotkey_descs]
}
try:
with open(url, "w", encoding="utf8") as json_file:
json.dump(output, json_file, indent=4)
json_file.close()
carb.log_info(f"Saved hotkeys preset to {url}!")
except FileNotFoundError:
carb.log_warn(f"Failed to open {url}!")
return False
except PermissionError:
carb.log_warn(f"Cannot write to {url}: permission denied!")
return False
except Exception as e: # pylint: disable=broad-except
carb.log_warn(f"Unknown failure to write to {url}: {e}")
return False
finally:
if json_file:
json_file.close()
return bool(json_file)
def load_preset(self, preset: List[Dict]) -> None:
"""
Load hotkey preset.
"""
self.clear_hotkeys()
self.__hotkey_descs = [HotkeyDescription(**desc) for desc in preset]
self.__settings.set(SETTING_USER_HOTKEYS, [asdict(desc) for desc in self.__hotkey_descs])
def preload_preset(self, url: str) -> Optional[Dict]:
"""
Preload hotkey preset from file.
"""
keys_json = None
try:
with open(url, "r", encoding="utf8") as json_file:
keys_json = json.load(json_file)
except FileNotFoundError:
carb.log_error(f"Failed to open {url}!")
except PermissionError:
carb.log_error(f"Cannot read {url}: permission denied!")
except Exception as exc: # pylint: disable=broad-except
carb.log_error(f"Unknown failure to read {url}: {exc}")
if keys_json is None:
return None
if keys_json.get("Type", None) != "Hotkey Preset":
carb.log_error(f"{url} is not a valid hotkey preset file!")
return None
if "Keys" not in keys_json:
carb.log_error(f"{url} is not a valid hotkey preset: No key found!")
return None
return keys_json["Keys"]
| 7,763 | Python | 34.452055 | 147 | 0.595904 |
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/keyboard_layout.py | import abc
from typing import Dict, List, Optional
import weakref
import carb.input
from .key_combination import KeyCombination
class KeyboardLayoutDelegate(abc.ABC):
"""Base class for keyboard layout delegates and registry of these same delegate instances.
Whenever an instance of this class is created, it is automatically registered.
"""
__g_registered = []
@classmethod
def get_instances(cls) -> List["KeyboardLayoutDelegate"]:
remove = []
for wref in KeyboardLayoutDelegate.__g_registered:
obj = wref()
if obj:
yield obj
else:
remove.append(wref)
for wref in remove:
KeyboardLayoutDelegate.__g_registered.remove(wref)
@classmethod
def get_instance(cls, name: str) -> Optional["KeyboardLayoutDelegate"]:
for inst in KeyboardLayoutDelegate.get_instances():
if inst.get_name() == name:
return inst
return None
def __init__(self):
self.__g_registered.append(weakref.ref(self, lambda r: KeyboardLayoutDelegate.__g_registered.remove(r))) # noqa: PLW0108 # pylint: disable=unnecessary-lambda
self._maps = self.get_maps()
self._restore_maps = {value: key for (key, value) in self._maps.items()}
def __del__(self):
self.destroy()
def destroy(self):
for wref in KeyboardLayoutDelegate.__g_registered:
if wref() == self:
KeyboardLayoutDelegate.__g_registered.remove(wref)
break
@abc.abstractmethod
def get_name(self) -> str:
return ""
@abc.abstractmethod
def get_maps(self) -> dict:
return {}
def map_key(self, key: KeyCombination) -> Optional[KeyCombination]:
return KeyCombination(self._maps[key.key], modifiers=key.modifiers, trigger_press=key.trigger_press) if key.key in self._maps else None
def restore_key(self, key: KeyCombination) -> Optional[KeyCombination]:
return KeyCombination(self._restore_maps[key.key], modifiers=key.modifiers, trigger_press=key.trigger_press) if key.key in self._restore_maps else None
class USKeyboardLayout(KeyboardLayoutDelegate):
def get_name(self) -> str:
return "U.S. QWERTY"
def get_maps(self) -> Dict[carb.input.KeyboardInput, carb.input.KeyboardInput]:
return {}
class GermanKeyboardLayout(KeyboardLayoutDelegate):
def get_name(self) -> str:
return "German QWERTZ"
def get_maps(self) -> Dict[carb.input.KeyboardInput, carb.input.KeyboardInput]:
return {
carb.input.KeyboardInput.Z: carb.input.KeyboardInput.Y,
carb.input.KeyboardInput.Y: carb.input.KeyboardInput.Z,
}
class FrenchKeyboardLayout(KeyboardLayoutDelegate):
def get_name(self) -> str:
return "French AZERTY"
def get_maps(self) -> Dict[carb.input.KeyboardInput, carb.input.KeyboardInput]:
return {
carb.input.KeyboardInput.Q: carb.input.KeyboardInput.A,
carb.input.KeyboardInput.W: carb.input.KeyboardInput.Z,
carb.input.KeyboardInput.A: carb.input.KeyboardInput.Q,
carb.input.KeyboardInput.Z: carb.input.KeyboardInput.W,
}
| 3,239 | Python | 33.105263 | 166 | 0.651436 |
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/filter.py | __all__ = ["HotkeyFilter"]
from typing import List, Optional
class HotkeyFilter:
"""
Hotkey filter class.
"""
def __init__(self, context: Optional[str] = None, windows: Optional[List[str]] = None):
"""
Define a hotkey filter object.
Keyword Args:
context (Optional[str]): Name of context to filter. Default None.
windows (Optional[List[str]]): List of window names to filter. Default None
Returns:
The hotkey filter object that was created.
"""
self.context = context
self.windows = windows
@property
def windows_text(self):
"""
String of windows defined in this filter.
"""
return ",".join(self.windows) if self.windows else ""
def __eq__(self, other):
return isinstance(other, HotkeyFilter) and self.context == other.context and self.windows == other.windows
def __str__(self):
info = ""
if self.context:
info += f"[Context] {self.context}"
if self.windows:
info += "[Windows] " + (",".join(self.windows))
return info
| 1,148 | Python | 27.02439 | 114 | 0.569686 |
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/hotkey.py | from typing import Optional, Union
import carb
from omni.kit.actions.core import get_action_registry, Action
from .key_combination import KeyCombination
from .filter import HotkeyFilter
class Hotkey:
"""
Hotkey object class.
"""
def __init__(
self,
hotkey_ext_id: str,
key: Union[str, KeyCombination],
action_ext_id: str,
action_id: str,
filter: Optional[HotkeyFilter] = None # noqa: A002 # pylint: disable=redefined-builtin
):
"""
Define a hotkey object.
Args:
hotkey_ext_id (str): Extension id which owns the hotkey.
key (Union[str, KeyCombination]): Key combination.
action_ext_id (str): Extension id which owns the action assigned to the hotkey.
action_id (str): Action id assigned to the hotkey.
Keyword Args:
filter (Optional[HotkeyFilter]): Hotkey filter. Default None
Returns:
The hotkey object that was created.
"""
self.hotkey_ext_id = hotkey_ext_id
if key:
self.key_combination = KeyCombination(key) if isinstance(key, str) else key
else:
self.key_combination = None
# For user defined action, the extension may not loaded yet
# So only save action id instead get real action here
self.action_ext_id = action_ext_id
self.action_id = action_id
self.filter = filter
@property
def id(self) -> str: # noqa: A003
"""
Identifier string of this hotkey.
"""
hotkey_id = f"{self.hotkey_ext_id}.{self.action_text}"
if self.filter:
hotkey_id += "." + str(self.filter)
return hotkey_id
@property
def key_text(self) -> str:
"""
String of key bindings assigned to this hotkey.
"""
return self.key_combination.as_string if self.key_combination else ""
@property
def action_text(self) -> str:
"""
String of action object assigned to this hotkey.
"""
return self.action_ext_id + "::" + self.action_id if self.action_ext_id or self.action_id else ""
@property
def filter_text(self) -> str:
"""
String of filter object assigned to this hotkey.
"""
return str(self.filter) if self.filter else ""
@property
def action(self) -> Action:
"""
Action object assigned to this hotkey.
"""
if self.action_ext_id and self.action_id:
action = get_action_registry().get_action(self.action_ext_id, self.action_id)
if action is None:
carb.log_warn(f"[Hotkey] Action '{self.action_ext_id}::{self.action_id}' not FOUND!")
return action
return None
def execute(self) -> None:
"""
Execute action assigned to the hotkey
"""
if self.action:
self.action.execute()
def __eq__(self, other) -> bool:
return isinstance(other, Hotkey)\
and self.hotkey_ext_id == other.hotkey_ext_id \
and self.key_combination == other.key_combination \
and self.action_ext_id == other.action_ext_id \
and self.action_id == other.action_id \
and self.filter == other.filter
def __repr__(self):
basic_info = f"[{self.hotkey_ext_id}] {self.action_text}.{self.key_text}"
if self.filter is None:
return f"Global {basic_info}"
return f"Local {basic_info} for {self.filter}"
| 3,558 | Python | 30.776785 | 105 | 0.578696 |
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/context.py | __all__ = ["HotkeyContext"]
from typing import List, Optional
import carb.settings
SETTING_HOTKEY_CURRENT_CONTEXT = "/exts/omni.kit.hotkeys.core/context"
class HotkeyContext:
def __init__(self):
"""Represent hotkey context."""
self._queue: List[str] = []
self._settings = carb.settings.get_settings()
def push(self, name: str) -> None:
"""
Push a context.
Args:
name (str): name of context
"""
self._queue.append(name)
self._update_settings()
def pop(self) -> Optional[str]:
"""Remove and return last context."""
poped = self._queue.pop() if self._queue else None
self._update_settings()
return poped
def get(self) -> Optional[str]:
"""Get last context."""
return self._queue[-1] if self._queue else None
def clean(self) -> None:
"""Clean all contexts"""
self._queue.clear()
self._update_settings()
def _update_settings(self):
current = self.get()
self._settings.set(SETTING_HOTKEY_CURRENT_CONTEXT, current if current else "")
| 1,132 | Python | 25.97619 | 86 | 0.581272 |
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/key_combination.py | __all__ = ["KeyCombination"]
from typing import Union, Optional, Dict, Tuple
import re
import carb
import carb.input
PREDEFINED_STRING_TO_KEYS: Dict[str, carb.input.Keyboard] = carb.input.KeyboardInput.__members__
class KeyCombination:
"""
Key binding class.
"""
def __init__(self, key: Union[str, carb.input.KeyboardInput], modifiers: int = 0, trigger_press: bool = True):
"""
Create a key binding object.
Args:
key (Union[str, carb.input.KeyboardInput]): could be string or carb.input.KeyboardInput.
if string, use "+" to join carb.input.KeyboardInput and modifiers, for example: "CTRL+D" or "CTRL+SHIFT+D"
Keyword Args:
modifiers (int): Represent combination of keyboard modifier flags, which could be:
carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL
carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT
carb.input.KEYBOARD_MODIFIER_FLAG_ALT
carb.input.KEYBOARD_MODIFIER_FLAG_SUPER
trigger_press (bool): Trigger when key pressed if True. Otherwise trigger when key released. Default True.
"""
self.key: Optional[carb.input.Keyboard] = None
self.modifiers = 0
if isinstance(key, str):
(self.key, self.modifiers, self.trigger_press) = KeyCombination.from_string(key)
else:
self.modifiers = modifiers
if key in [
carb.input.KeyboardInput.LEFT_CONTROL,
carb.input.KeyboardInput.RIGHT_CONTROL,
carb.input.KeyboardInput.LEFT_SHIFT,
carb.input.KeyboardInput.RIGHT_SHIFT,
carb.input.KeyboardInput.LEFT_ALT,
carb.input.KeyboardInput.RIGHT_ALT,
carb.input.KeyboardInput.LEFT_SUPER,
carb.input.KeyboardInput.RIGHT_SUPER,
]:
self.key = ""
else:
self.key = key
self.trigger_press = trigger_press
@property
def as_string(self) -> str:
"""
Get string to describe key combination
"""
if self.key is None:
return ""
descs = []
if self.modifiers & carb.input.KEYBOARD_MODIFIER_FLAG_SUPER:
descs.append("SUPER")
if self.modifiers & carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT:
descs.append("SHIFT")
if self.modifiers & carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL:
descs.append("CTRL")
if self.modifiers & carb.input.KEYBOARD_MODIFIER_FLAG_ALT:
descs.append("ALT")
if self.key in PREDEFINED_STRING_TO_KEYS.values():
key = list(PREDEFINED_STRING_TO_KEYS.keys())[list(PREDEFINED_STRING_TO_KEYS.values()).index(self.key)]
# OM-67426: Remove "KEY_". For example, "KEY_1" to "1".
if key.startswith("KEY_"):
key = key[4:]
descs.append(key)
return " + ".join(descs)
@property
def id(self) -> str: # noqa: A003
"""
Identifier string of this key binding object.
"""
return f"{self.as_string} (On " + ("Press" if self.trigger_press else "Release") + ")"
@property
def is_valid(self) -> bool:
"""
If a valid key binding object.
"""
return self.key is not None
def __repr__(self) -> str:
return self.id
def __eq__(self, other) -> bool:
return isinstance(other, KeyCombination) and self.id == other.id
def __hash__(self):
return hash(self.id)
@staticmethod
def from_string(key_string: str) -> Tuple[carb.input.KeyboardInput, int, bool]:
"""
Get key binding information from a string.
Args:
key_string (str): String represent a key binding.
Returns:
Tuple of carb.input.KeyboardInput, modifiers and flag for press/release.
"""
if key_string is None:
carb.log_error("No key defined!")
return (None, None, None)
key_string = key_string.strip()
if key_string == "":
# Empty key string means no key
return ("", 0, True)
modifiers = 0
key = None
trigger_press = True
m = re.search(r"(.*)\(on (press|release)\)", key_string, flags=re.IGNORECASE)
if m:
trigger = m.groups()[1]
trigger_press = trigger.upper() == "PRESS"
key_string = m.groups()[0]
else:
trigger_press = True
key_descs = key_string.split("+")
for desc in key_descs:
desc = desc.strip().upper()
if desc in ["CTRL", "CTL", "CONTROL"]:
modifiers += carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL
elif desc in ["SHIFT"]:
modifiers += carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT
elif desc in ["ALT"]:
modifiers += carb.input.KEYBOARD_MODIFIER_FLAG_ALT
elif desc in ["SUPER"]:
modifiers += carb.input.KEYBOARD_MODIFIER_FLAG_SUPER
elif desc in ["PRESS", "RELEASE"]:
trigger_press = desc == "PRESS"
elif desc in PREDEFINED_STRING_TO_KEYS:
key = PREDEFINED_STRING_TO_KEYS[desc]
elif desc in [str(i) for i in range(0, 10)]:
# OM-67426: for numbers, convert to original key definition
key = PREDEFINED_STRING_TO_KEYS["KEY_" + desc]
elif desc == "":
key = ""
else:
carb.log_warn(f"Unknown key definition '{desc}' in '{key_string}'")
return (None, None, None)
return (key, modifiers, trigger_press)
@staticmethod
def is_valid_key_string(key: str) -> bool:
"""
If key string valid.
Args:
key (str): Key string to check.
Returns:
True if key string is valid. Otherwise False.
"""
(key, modifiers, press) = KeyCombination.from_string(key)
if key is None or modifiers is None or press is None:
return False
return True
| 6,158 | Python | 34.194286 | 122 | 0.556999 |
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/hovered_window.py | __all__ = ["is_window_hovered", "get_hovered_window"]
from typing import Optional, List
import omni.ui as ui
def is_window_hovered(pos_x: float, pos_y: float, window: ui.Window) -> bool:
"""
Check if window under mouse position.
Args:
pos_x (flaot): X position.
pos_y (flaot): Y position.
window (ui.Window): Window to check.
"""
# if window hasn't been drawn yet docked may not be valid, so check dock_id also
# OM-65505: For ui.ToolBar, is_selected_in_dock always return False if docked.
if not window or not window.visible or ((window.docked or window.dock_id != 0) and (not isinstance(window, ui.ToolBar) and not window.is_selected_in_dock())):
return False
if (window.position_x + window.width > pos_x > window.position_x
and window.position_y + window.height > pos_y > window.position_y):
return True
return False
def get_hovered_window(pos_x: float, pos_y: float) -> Optional[str]:
"""
Get first window under mouse.
Args:
pos_x (flaot): X position.
pos_y (flaot): Y position.
Return None if nothing found.
If muliple window found, float window first. If multiple float window, just first result
"""
hovered_float_windows: List[ui.Window] = []
hovered_doced_windows: List[ui.Window] = []
dpi = ui.Workspace.get_dpi_scale()
pos_x /= dpi
pos_y /= dpi
windows = ui.Workspace.get_windows()
for window in windows:
if is_window_hovered(pos_x, pos_y, window):
if window.docked:
hovered_doced_windows.append(window)
else:
hovered_float_windows.append(window)
if hovered_float_windows:
return hovered_float_windows[0]
if hovered_doced_windows:
return hovered_doced_windows[0]
return None
| 1,841 | Python | 33.11111 | 162 | 0.633351 |
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/tests/test_registry.py | # pylint: disable=attribute-defined-outside-init
import omni.kit.test
import carb.events
from omni.kit.hotkeys.core import get_hotkey_registry, HotkeyFilter, Hotkey, HotkeyRegistry, HOTKEY_CHANGED_EVENT, HOTKEY_REGISTER_EVENT, HOTKEY_DEREGISTER_EVENT
from omni.kit.actions.core import get_action_registry
TEST_HOTKEY_EXT_ID = "omni.kit.hotkey.test.hotkey"
TEST_ACTION_EXT_ID = "omni.kit.hotkey.test.action"
TEST_ACTION_ID = "hotkey_test_action"
TEST_ANOTHER_ACTION_ID = "hotkey_test_action_another"
TEST_CONTEXT_NAME = "[email protected]"
TEST_HOTKEY = "CTRL + T"
TEST_ANOTHER_HOTKEY = "SHIFT + T"
TEST_EDIT_HOTKEY = "T"
CHANGE_HOTKEY = "SHIFT + CTRL + T"
class TestRegistry(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._hotkey_registry = get_hotkey_registry()
self._hotkey_registry.clear_storage()
self._action_registry = get_action_registry()
self._filter = HotkeyFilter(context=TEST_CONTEXT_NAME)
self._register_payload = {}
self._action = self._action_registry.register_action(TEST_ACTION_EXT_ID, TEST_ACTION_ID, lambda: print("this is a hotkey test"))
self._another_action = self._action_registry.register_action(TEST_ACTION_EXT_ID, TEST_ANOTHER_ACTION_ID, lambda: print("this is another hotkey test"))
# After running each test
async def tearDown(self):
self._hotkey_registry.deregister_all_hotkeys_for_extension(TEST_HOTKEY_EXT_ID)
self._hotkey_registry.clear_storage()
self._hotkey_registry = None
self._action_registry.deregister_action(self._action)
self._action_registry = None
async def test_register_global_hotkey(self):
hotkey = self._hotkey_registry.get_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY)
self.assertIsNone(hotkey)
# Register a global hotkey
self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ACTION_ID)
hotkey = self._hotkey_registry.get_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY)
self.assertEqual(hotkey.hotkey_ext_id, TEST_HOTKEY_EXT_ID)
self.assertEqual(hotkey.action, self._action)
self.assertEqual(hotkey.key_combination.as_string, TEST_HOTKEY)
# Deregister the global hotkey
self._hotkey_registry.deregister_hotkey(hotkey)
hotkey = self._hotkey_registry.get_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY)
self.assertIsNone(hotkey)
async def test_register_local_hotkey(self):
global_hotkey = self._hotkey_registry.get_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY)
self.assertIsNone(global_hotkey)
local_hotkey = self._hotkey_registry.get_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, filter=self._filter)
self.assertIsNone(local_hotkey)
# Register a local hotkey
self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ACTION_ID, filter=self._filter)
global_hotkey = self._hotkey_registry.get_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY)
self.assertIsNone(global_hotkey)
local_hotkey = self._hotkey_registry.get_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, filter=self._filter)
self.assertEqual(local_hotkey.hotkey_ext_id, TEST_HOTKEY_EXT_ID)
self.assertEqual(local_hotkey.action, self._action)
self.assertEqual(local_hotkey.key_combination.as_string, TEST_HOTKEY)
# Deregister the local hotkey
self._hotkey_registry.deregister_hotkey(local_hotkey)
hotkey = self._hotkey_registry.get_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, filter=self._filter)
self.assertIsNone(hotkey)
async def test_mixed_hotkey(self):
# Register a global hotkey
global_hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ACTION_ID)
# Register a local hotkey
local_hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ACTION_ID, filter=self._filter)
self.assertNotEqual(global_hotkey, local_hotkey)
discovered_global_hotkey = self._hotkey_registry.get_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY)
self.assertEqual(global_hotkey, discovered_global_hotkey)
discovered_local_hotkey = self._hotkey_registry.get_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, filter=self._filter)
self.assertEqual(local_hotkey, discovered_local_hotkey)
# Deregister the hotkeys
self._hotkey_registry.deregister_hotkey(global_hotkey)
self._hotkey_registry.deregister_hotkey(local_hotkey)
async def test_deregister(self):
# Register a global hotkey
hotkey_1 = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ACTION_ID)
self.assertIsNotNone(hotkey_1)
# Register a local hotkey
hotkey_2 = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ACTION_ID, filter=self._filter)
self.assertIsNotNone(hotkey_2)
# Register with another key, should since already action already defined
hotkey_3 = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, "SHIFT+D", TEST_ACTION_EXT_ID, TEST_ACTION_ID)
self.assertIsNone(hotkey_3)
# Register with another extension id
hotkey_4 = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID + "_another", TEST_ANOTHER_HOTKEY, TEST_ACTION_EXT_ID, TEST_ANOTHER_ACTION_ID, filter=self._filter)
self.assertIsNotNone(hotkey_4)
hotkeys = self._hotkey_registry.get_all_hotkeys_for_extension(TEST_HOTKEY_EXT_ID + "_another")
self.assertEqual(len(hotkeys), 1)
# Deregister hotkey_4
self._hotkey_registry.deregister_all_hotkeys_for_extension(TEST_HOTKEY_EXT_ID + "_another")
hotkeys = self._hotkey_registry.get_all_hotkeys_for_extension(TEST_HOTKEY_EXT_ID + "_another")
self.assertEqual(len(hotkeys), 0)
# Deregister hotkey_1
hotkeys = self._hotkey_registry.get_all_hotkeys_for_extension(None)
self.assertEqual(len(hotkeys), 1)
self._hotkey_registry.deregister_all_hotkeys_for_extension(None)
hotkeys = self._hotkey_registry.get_all_hotkeys_for_extension(None)
self.assertEqual(len(hotkeys), 0)
# Deregister hotkey_2
hotkeys = self._hotkey_registry.get_all_hotkeys_for_filter(self._filter)
self.assertEqual(len(hotkeys), 1)
self._hotkey_registry.deregister_all_hotkeys_for_filter(self._filter)
hotkeys = self._hotkey_registry.get_all_hotkeys_for_filter(self._filter)
self.assertEqual(len(hotkeys), 0)
async def test_discover_hotkeys(self):
hotkeys = self._hotkey_registry.get_all_hotkeys_for_extension(TEST_HOTKEY_EXT_ID)
self.assertEqual(len(hotkeys), 0)
hotkeys = self._hotkey_registry.get_all_hotkeys_for_key(TEST_HOTKEY)
self.assertEqual(len(hotkeys), 0)
hotkeys = self._hotkey_registry.get_hotkeys(TEST_ACTION_EXT_ID, TEST_HOTKEY)
self.assertEqual(len(hotkeys), 0)
# Register a global hotkey
global_hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ACTION_ID)
self.assertIsNotNone(global_hotkey)
# Register a local hotkey
local_hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ACTION_ID, filter=self._filter)
self.assertIsNotNone(local_hotkey)
# Register with another key
hotkey_1 = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, "SHIFT+D", TEST_ACTION_EXT_ID, TEST_ANOTHER_ACTION_ID)
self.assertIsNotNone(hotkey_1)
# Register with another extension id (should be failed since key + filter is same)
hotkey_2 = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID + "_another", TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ANOTHER_ACTION_ID, filter=self._filter)
self.assertIsNone(hotkey_2)
hotkeys = self._hotkey_registry.get_all_hotkeys_for_extension(TEST_HOTKEY_EXT_ID)
self.assertEqual(len(hotkeys), 3)
hotkeys = self._hotkey_registry.get_all_hotkeys_for_extension(None)
self.assertEqual(len(hotkeys), 2)
hotkeys = self._hotkey_registry.get_all_hotkeys_for_key(TEST_HOTKEY)
self.assertEqual(len(hotkeys), 2)
hotkeys = self._hotkey_registry.get_hotkeys(TEST_HOTKEY_EXT_ID, TEST_HOTKEY)
self.assertEqual(len(hotkeys), 2)
self._hotkey_registry.deregister_hotkey(global_hotkey)
self._hotkey_registry.deregister_hotkey(local_hotkey)
self._hotkey_registry.deregister_hotkey(hotkey_1)
self._hotkey_registry.deregister_hotkey(hotkey_2)
async def test_event(self):
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
self._register_event_sub = event_stream.create_subscription_to_pop_by_type(
HOTKEY_REGISTER_EVENT, self._on_hotkey_register)
self._deregister_event_sub = event_stream.create_subscription_to_pop_by_type(
HOTKEY_DEREGISTER_EVENT, self._on_hotkey_deregister)
self._change_event_sub = event_stream.create_subscription_to_pop_by_type(
HOTKEY_CHANGED_EVENT, self._on_hotkey_changed)
# Register hotkey event
test_hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ACTION_ID)
for _ in range(2):
await omni.kit.app.get_app().next_update_async()
self.assertEqual(self._register_payload["hotkey_ext_id"], TEST_HOTKEY_EXT_ID)
self.assertEqual(self._register_payload["key"], TEST_HOTKEY)
self.assertEqual(self._register_payload["action_ext_id"], TEST_ACTION_EXT_ID)
self.assertEqual(self._register_payload["action_id"], TEST_ACTION_ID)
# Change hotkey
error_code = self._hotkey_registry.edit_hotkey(test_hotkey, CHANGE_HOTKEY, None)
self.assertEqual(error_code, HotkeyRegistry.Result.OK)
for _ in range(2):
await omni.kit.app.get_app().next_update_async()
self.assertEqual(self._changed_payload["hotkey_ext_id"], TEST_HOTKEY_EXT_ID)
self.assertEqual(self._changed_payload["key"], CHANGE_HOTKEY)
self.assertEqual(self._changed_payload["action_ext_id"], TEST_ACTION_EXT_ID)
self.assertEqual(self._changed_payload["action_id"], TEST_ACTION_ID)
# Change hotkey back
self._hotkey_registry.edit_hotkey(test_hotkey, TEST_HOTKEY, None)
for _ in range(2):
await omni.kit.app.get_app().next_update_async()
self.assertEqual(self._changed_payload["key"], TEST_HOTKEY)
# Deregister hotkey event
self._hotkey_registry.deregister_hotkey(test_hotkey)
for _ in range(2):
await omni.kit.app.get_app().next_update_async()
self.assertEqual(self._deregister_payload["hotkey_ext_id"], TEST_HOTKEY_EXT_ID)
self.assertEqual(self._deregister_payload["key"], TEST_HOTKEY)
self.assertEqual(self._deregister_payload["action_ext_id"], TEST_ACTION_EXT_ID)
self.assertEqual(self._deregister_payload["action_id"], TEST_ACTION_ID)
self._register_event_sub = None
self._deregister_event_sub = None
self._change_event_sub = None
async def test_error_code_global(self):
hotkey = Hotkey(TEST_HOTKEY_EXT_ID, "CBL", TEST_ACTION_EXT_ID, TEST_ACTION_ID)
registered_hotkey = self._hotkey_registry.register_hotkey(hotkey)
self.assertIsNone(registered_hotkey)
self.assertEqual(self._hotkey_registry.last_error, HotkeyRegistry.Result.ERROR_KEY_INVALID)
registered_hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, "T", "", "")
self.assertIsNone(registered_hotkey)
self.assertEqual(self._hotkey_registry.last_error, HotkeyRegistry.Result.ERROR_NO_ACTION)
registered_hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ACTION_ID)
self.assertIsNotNone(registered_hotkey)
self.assertEqual(self._hotkey_registry.last_error, HotkeyRegistry.Result.OK)
registered_another = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ANOTHER_ACTION_ID)
self.assertIsNone(registered_another)
self.assertEqual(self._hotkey_registry.last_error, HotkeyRegistry.Result.ERROR_KEY_DUPLICATED)
# Edit global hotkey
registered_another = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_ANOTHER_HOTKEY, TEST_ACTION_EXT_ID, TEST_ANOTHER_ACTION_ID)
self.assertIsNotNone(registered_another)
error_code = self._hotkey_registry.edit_hotkey(registered_another, "CBL", None)
self.assertEqual(error_code, HotkeyRegistry.Result.ERROR_KEY_INVALID)
error_code = self._hotkey_registry.edit_hotkey(registered_another, TEST_HOTKEY, None)
self.assertEqual(error_code, HotkeyRegistry.Result.ERROR_KEY_DUPLICATED)
duplicated = self._hotkey_registry.get_hotkey_for_filter(TEST_HOTKEY, None)
self.assertEqual(duplicated.action_ext_id, TEST_ACTION_EXT_ID)
self.assertEqual(duplicated.action_id, TEST_ACTION_ID)
error_code = self._hotkey_registry.edit_hotkey(registered_another, TEST_EDIT_HOTKEY, None)
self.assertEqual(error_code, HotkeyRegistry.Result.OK)
error_code = self._hotkey_registry.edit_hotkey(registered_another, "", None)
self.assertEqual(error_code, HotkeyRegistry.Result.OK)
async def test_error_code_window(self):
# Edit hotkey in window
hotkey_filter = HotkeyFilter(windows=["Test Window"])
registered_hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ACTION_ID, filter=hotkey_filter)
self.assertIsNotNone(registered_hotkey)
self.assertEqual(self._hotkey_registry.last_error, HotkeyRegistry.Result.OK)
registered_another = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_ANOTHER_ACTION_ID, filter=hotkey_filter)
self.assertIsNone(registered_another)
self.assertEqual(self._hotkey_registry.last_error, HotkeyRegistry.Result.ERROR_KEY_DUPLICATED)
registered_another = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_ANOTHER_HOTKEY, TEST_ACTION_EXT_ID, TEST_ANOTHER_ACTION_ID, filter=hotkey_filter)
self.assertEqual(self._hotkey_registry.last_error, HotkeyRegistry.Result.OK)
self.assertIsNotNone(registered_another)
error_code = self._hotkey_registry.edit_hotkey(registered_another, "CBL", hotkey_filter)
self.assertEqual(error_code, HotkeyRegistry.Result.ERROR_KEY_INVALID)
error_code = self._hotkey_registry.edit_hotkey(registered_another, TEST_HOTKEY, hotkey_filter)
self.assertEqual(error_code, HotkeyRegistry.Result.ERROR_KEY_DUPLICATED)
duplicated = self._hotkey_registry.get_hotkey_for_filter(TEST_HOTKEY, hotkey_filter)
self.assertEqual(duplicated.action_ext_id, TEST_ACTION_EXT_ID)
self.assertEqual(duplicated.action_id, TEST_ACTION_ID)
error_code = self._hotkey_registry.edit_hotkey(registered_another, TEST_EDIT_HOTKEY, hotkey_filter)
self.assertEqual(error_code, HotkeyRegistry.Result.OK)
error_code = self._hotkey_registry.edit_hotkey(registered_another, "", hotkey_filter)
self.assertEqual(error_code, HotkeyRegistry.Result.OK)
def _on_hotkey_register(self, event: carb.events.IEvent):
self._register_payload = event.payload
def _on_hotkey_deregister(self, event: carb.events.IEvent):
self._deregister_payload = event.payload
def _on_hotkey_changed(self, event: carb.events.IEvent):
self._changed_payload = event.payload
| 15,929 | Python | 54.3125 | 175 | 0.7013 |
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/tests/test_context.py | from typing import List
import omni.kit.test
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
from omni.kit.hotkeys.core import get_hotkey_context
import carb.settings
SETTING_HOTKEY_CURRENT_CONTEXT = "/exts/omni.kit.hotkeys.core/context"
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class TestContext(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
self._settings = carb.settings.get_settings()
# After running each test
async def tearDown(self):
pass
async def test_empty(self):
context = get_hotkey_context()
self.assertEqual(self._settings.get(SETTING_HOTKEY_CURRENT_CONTEXT), "")
self.assertIsNone(context.get())
self.assertIsNone(context.pop())
async def test_push_pop(self):
max_contexts = 10
context_names: List[str] = [f"context_{i}" for i in range(max_contexts)]
context = get_hotkey_context()
for name in context_names:
context.push(name)
self.assertEqual(self._settings.get(SETTING_HOTKEY_CURRENT_CONTEXT), name)
self.assertEqual(context.get(), name)
for i in range(max_contexts):
self.assertEqual(context.pop(), context_names[-(i + 1)])
if i == max_contexts - 1:
current = None
else:
current = context_names[-(i + 2)]
self.assertEqual(context.get(), current)
self.assertEqual(self._settings.get(SETTING_HOTKEY_CURRENT_CONTEXT), current if current else "")
self.assertIsNone(context.pop())
async def test_clean(self):
max_contexts = 10
context_names: List[str] = [f"context_{i}" for i in range(max_contexts)]
context = get_hotkey_context()
for name in context_names:
context.push(name)
context.clean()
self.assertEqual(self._settings.get(SETTING_HOTKEY_CURRENT_CONTEXT), "")
self.assertIsNone(context.get())
self.assertIsNone(context.pop())
| 2,195 | Python | 35.599999 | 142 | 0.648292 |
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/tests/__init__.py | from .test_key_combination import *
from .test_context import *
from .test_registry import *
from .test_trigger import *
from .test_keyboard_layout import *
| 157 | Python | 25.333329 | 35 | 0.764331 |
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/tests/test_keyboard_layout.py | import omni.kit.test
import omni.kit.ui_test as ui_test
import carb.input
from omni.kit.hotkeys.core import get_hotkey_context, get_hotkey_registry, HotkeyFilter
from omni.kit.actions.core import get_action_registry
TEST_HOTKEY_EXT_ID = "omni.kit.hotkey.test.hotkey"
TEST_ACTION_EXT_ID = "omni.kit.hotkey.test.action"
TEST_CONTEXT_PRESS_ACTION_ID = "hotkey_test_context_press_action"
TEST_CONTEXT_RELEASE_ACTION_ID = "hotkey_test_context_release_action"
TEST_GLOBAL_PRESS_ACTION_ID = "hotkey_test_global_press_action"
TEST_GLOBAL_RELEASE_ACTION_ID = "hotkey_test_global_release_action"
TEST_CONTEXT_NAME = "[email protected]"
TEST_HOTKEY = "CTRL+Z"
_global_press_action_count = 0
def global_press_action_func():
global _global_press_action_count
_global_press_action_count += 1
class TestKeyboardLayout(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._hotkey_registry = get_hotkey_registry()
self._hotkey_context = get_hotkey_context()
self._action_registry = get_action_registry()
self._filter = HotkeyFilter(context=TEST_CONTEXT_NAME)
self._action_registry.register_action(TEST_ACTION_EXT_ID, TEST_GLOBAL_PRESS_ACTION_ID, global_press_action_func)
self._hotkey_registry.clear_storage()
await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.Z, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL)
await ui_test.human_delay()
# After running each test
async def tearDown(self):
self._hotkey_context = None
self._hotkey_registry.deregister_all_hotkeys_for_extension(TEST_HOTKEY_EXT_ID)
self._hotkey_registry = None
self._action_registry.deregister_all_actions_for_extension(TEST_ACTION_EXT_ID)
self._action_registry = None
async def test_hotkey_register_with_new_layout(self):
self._hotkey_registry.switch_layout("German QWERTZ")
# With new keyboard layout, key combination should be changed when register
hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_GLOBAL_PRESS_ACTION_ID)
self.assertIsNotNone(hotkey)
self.assertEqual(hotkey.key_combination.as_string, "CTRL + Y")
await self.__verify_trigger(carb.input.KeyboardInput.Z, False)
await self.__verify_trigger(carb.input.KeyboardInput.Y, True)
async def test_hotkey_switch_layout(self):
self._hotkey_registry.switch_layout("U.S. QWERTY")
# Global pressed hotkey
hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_GLOBAL_PRESS_ACTION_ID)
self.assertIsNotNone(hotkey)
# Trigger hotkey in global, default layout, should trigger
await self.__verify_trigger(carb.input.KeyboardInput.Z, True)
# Switch layout
self._hotkey_registry.switch_layout("German QWERTZ")
self.assertEqual(hotkey.key_combination.as_string, "CTRL + Y")
# Default key, nothing triggered
await self.__verify_trigger(carb.input.KeyboardInput.Z, False)
# Trigger with new key mapping
await self.__verify_trigger(carb.input.KeyboardInput.Y, True)
# Switch layout back to default
self._hotkey_registry.switch_layout("U.S. QWERTY")
self.assertEqual(hotkey.key_combination.as_string, "CTRL + Z")
# New key, nothing triggered
await self.__verify_trigger(carb.input.KeyboardInput.Y, False)
# Trigger with default key mapping
await self.__verify_trigger(carb.input.KeyboardInput.Z, True)
async def test_user_hotkey(self):
self._hotkey_registry.switch_layout("U.S. QWERTY")
hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, "CTRL + M", TEST_ACTION_EXT_ID, TEST_GLOBAL_PRESS_ACTION_ID)
self.assertIsNotNone(hotkey)
self._hotkey_registry.edit_hotkey(hotkey, "CTRL + Z", None)
self.assertEqual(hotkey.key_combination.as_string, "CTRL + Z")
self._hotkey_registry.switch_layout("German QWERTZ")
self.assertEqual(hotkey.key_combination.as_string, "CTRL + Z")
async def __verify_trigger(self, key, should_trigger):
saved_count = _global_press_action_count
await ui_test.emulate_keyboard_press(key, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL)
await ui_test.human_delay()
if should_trigger:
self.assertEqual(_global_press_action_count, saved_count + 1)
else:
self.assertEqual(_global_press_action_count, saved_count)
| 4,565 | Python | 42.075471 | 136 | 0.698138 |
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/tests/test_trigger.py | import omni.kit.test
import omni.kit.ui_test as ui_test
import carb.input
from omni.kit.hotkeys.core import get_hotkey_context, get_hotkey_registry, HotkeyFilter, KeyCombination
from omni.kit.actions.core import get_action_registry
SETTING_ALLOW_LIST = "/exts/omni.kit.hotkeys.core/allow_list"
TEST_HOTKEY_EXT_ID = "omni.kit.hotkey.test.hotkey"
TEST_ACTION_EXT_ID = "omni.kit.hotkey.test.action"
TEST_CONTEXT_PRESS_ACTION_ID = "hotkey_test_context_press_action"
TEST_CONTEXT_RELEASE_ACTION_ID = "hotkey_test_context_release_action"
TEST_GLOBAL_PRESS_ACTION_ID = "hotkey_test_global_press_action"
TEST_GLOBAL_RELEASE_ACTION_ID = "hotkey_test_global_release_action"
TEST_CONTEXT_NAME = "[email protected]"
TEST_HOTKEY = "CTRL+T"
_context_press_action_count = 0
_context_release_action_count = 0
_global_press_action_count = 0
_global_release_action_count = 0
def context_press_action_func():
global _context_press_action_count
_context_press_action_count += 1
def context_release_action_func():
global _context_release_action_count
_context_release_action_count += 1
def global_press_action_func():
global _global_press_action_count
_global_press_action_count += 1
def global_release_action_func():
global _global_release_action_count
_global_release_action_count += 1
class TestTrigger(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._hotkey_registry = get_hotkey_registry()
self._hotkey_context = get_hotkey_context()
self._action_registry = get_action_registry()
self._filter = HotkeyFilter(context=TEST_CONTEXT_NAME)
await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.T, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL)
await ui_test.human_delay()
self.assertEqual(_context_press_action_count, 0)
self.assertEqual(_context_release_action_count, 0)
self.assertEqual(_global_press_action_count, 0)
self.assertEqual(_global_release_action_count, 0)
# Hotkey with context
self._action_registry.register_action(TEST_ACTION_EXT_ID, TEST_CONTEXT_PRESS_ACTION_ID, context_press_action_func)
hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_CONTEXT_PRESS_ACTION_ID, filter=self._filter)
self.assertIsNotNone(hotkey)
# Hotkey with context with key released
self._action_registry.register_action(TEST_ACTION_EXT_ID, TEST_CONTEXT_RELEASE_ACTION_ID, context_release_action_func)
hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, KeyCombination(TEST_HOTKEY, trigger_press=False), TEST_ACTION_EXT_ID, TEST_CONTEXT_RELEASE_ACTION_ID, filter=self._filter)
self.assertIsNotNone(hotkey)
# Global pressed hotkey
self._action_registry.register_action(TEST_ACTION_EXT_ID, TEST_GLOBAL_PRESS_ACTION_ID, global_press_action_func)
hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, TEST_HOTKEY, TEST_ACTION_EXT_ID, TEST_GLOBAL_PRESS_ACTION_ID)
self.assertIsNotNone(hotkey)
# Global released hotkey
self._action_registry.register_action(TEST_ACTION_EXT_ID, TEST_GLOBAL_RELEASE_ACTION_ID, global_release_action_func)
hotkey = self._hotkey_registry.register_hotkey(TEST_HOTKEY_EXT_ID, KeyCombination(TEST_HOTKEY, trigger_press=False), TEST_ACTION_EXT_ID, TEST_GLOBAL_RELEASE_ACTION_ID)
self.assertIsNotNone(hotkey)
# After running each test
async def tearDown(self):
self._hotkey_context = None
self._hotkey_registry.deregister_all_hotkeys_for_extension(TEST_HOTKEY_EXT_ID)
self._hotkey_registry = None
self._action_registry.deregister_all_actions_for_extension(TEST_ACTION_EXT_ID)
self._action_registry = None
async def test_hotkey_in_context(self):
# Trigger hotkey in context
self._hotkey_context.push(TEST_CONTEXT_NAME)
await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.T, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL)
await ui_test.human_delay()
self.assertEqual(_context_press_action_count, 1)
self.assertEqual(_context_release_action_count, 1)
self.assertEqual(_global_press_action_count, 0)
self.assertEqual(_global_release_action_count, 0)
self._hotkey_context.pop()
# Trigger hotkey in global
await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.T, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL)
await ui_test.human_delay()
self.assertEqual(_context_press_action_count, 1)
self.assertEqual(_context_release_action_count, 1)
self.assertEqual(_global_press_action_count, 1)
self.assertEqual(_global_release_action_count, 1)
async def test_allow_list(self):
global _global_press_action_count, _global_release_action_count
settings = carb.settings.get_settings()
try:
# Do not trigger since key not in allow list
settings.set(SETTING_ALLOW_LIST, ["F1"])
await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.T, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL)
await ui_test.human_delay()
self.assertEqual(_global_press_action_count, 0)
self.assertEqual(_global_release_action_count, 0)
# Trigger since key in allow list
settings.set(SETTING_ALLOW_LIST, ["CTRL + T"])
await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.T, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL)
await ui_test.human_delay()
self.assertEqual(_global_press_action_count, 1)
self.assertEqual(_global_release_action_count, 1)
# Trigger since no allow list
settings.set(SETTING_ALLOW_LIST, [])
await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.T, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL)
await ui_test.human_delay()
self.assertEqual(_global_press_action_count, 2)
self.assertEqual(_global_release_action_count, 2)
finally:
settings.set(SETTING_ALLOW_LIST, [])
_global_press_action_count = 0
_global_release_action_count = 0
| 6,265 | Python | 45.414814 | 197 | 0.698324 |
omniverse-code/kit/exts/omni.kit.hotkeys.core/omni/kit/hotkeys/core/tests/test_key_combination.py | # NOTE:
# omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests
# For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html
import omni.kit.test
# Import extension python module we are testing with absolute import path, as if we are external user (other extension)
from omni.kit.hotkeys.core import KeyCombination
import carb.input
# Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test
class TestKeyCombination(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
pass
# After running each test
async def tearDown(self):
pass
# Actual test, notice it is "async" function, so "await" can be used if needed
async def test_key_define_function(self):
key_comb = KeyCombination(carb.input.KeyboardInput.D)
self.assertEqual(key_comb.as_string, "D")
self.assertEqual(key_comb.trigger_press, True)
key_comb = KeyCombination(carb.input.KeyboardInput.D, trigger_press=False)
self.assertEqual(key_comb.as_string, "D")
self.assertEqual(key_comb.trigger_press, False)
key_comb = KeyCombination(carb.input.KeyboardInput.D, modifiers=carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL)
self.assertEqual(key_comb.as_string, "CTRL + D")
key_comb = KeyCombination(carb.input.KeyboardInput.D, modifiers=carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT)
self.assertEqual(key_comb.as_string, "SHIFT + D")
key_comb = KeyCombination(carb.input.KeyboardInput.D, modifiers=carb.input.KEYBOARD_MODIFIER_FLAG_ALT)
self.assertEqual(key_comb.as_string, "ALT + D")
key_comb = KeyCombination(carb.input.KeyboardInput.A, modifiers=carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL + carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT)
self.assertEqual(key_comb.as_string, "SHIFT + CTRL + A")
key_comb = KeyCombination(carb.input.KeyboardInput.A, modifiers=carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL + carb.input.KEYBOARD_MODIFIER_FLAG_ALT)
self.assertEqual(key_comb.as_string, "CTRL + ALT + A")
key_comb = KeyCombination(carb.input.KeyboardInput.A, modifiers=carb.input.KEYBOARD_MODIFIER_FLAG_ALT + carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT)
self.assertEqual(key_comb.as_string, "SHIFT + ALT + A")
key_comb = KeyCombination(carb.input.KeyboardInput.B, modifiers=carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL + carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT + carb.input.KEYBOARD_MODIFIER_FLAG_ALT)
self.assertEqual(key_comb.as_string, "SHIFT + CTRL + ALT + B")
async def test_key_string_function(self):
key_comb = KeyCombination("d")
self.assertEqual(key_comb.as_string, "D")
key_comb = KeyCombination("D")
self.assertEqual(key_comb.as_string, "D")
self.assertTrue(key_comb.trigger_press)
key_comb = KeyCombination("D", trigger_press=False)
self.assertEqual(key_comb.as_string, "D")
self.assertFalse(key_comb.trigger_press)
key_comb = KeyCombination("ctrl+d")
self.assertEqual(key_comb.as_string, "CTRL + D")
key_comb = KeyCombination("ctl+d")
self.assertEqual(key_comb.as_string, "CTRL + D")
key_comb = KeyCombination("control+d")
self.assertEqual(key_comb.as_string, "CTRL + D")
key_comb = KeyCombination("shift+d")
self.assertEqual(key_comb.as_string, "SHIFT + D")
key_comb = KeyCombination("alt+d")
self.assertEqual(key_comb.as_string, "ALT + D")
key_comb = KeyCombination("ctrl+shift+a")
self.assertEqual(key_comb.as_string, "SHIFT + CTRL + A")
key_comb = KeyCombination("shift+ctrl+A")
self.assertEqual(key_comb.as_string, "SHIFT + CTRL + A")
key_comb = KeyCombination("ctrl+ALT+a")
self.assertEqual(key_comb.as_string, "CTRL + ALT + A")
key_comb = KeyCombination("alt+CTRL+a")
self.assertEqual(key_comb.as_string, "CTRL + ALT + A")
key_comb = KeyCombination("ALT+shift+a")
self.assertEqual(key_comb.as_string, "SHIFT + ALT + A")
key_comb = KeyCombination("SHIFT+alt+a")
self.assertEqual(key_comb.as_string, "SHIFT + ALT + A")
key_comb = KeyCombination("Ctrl+shift+alt+b")
self.assertEqual(key_comb.as_string, "SHIFT + CTRL + ALT + B")
key_comb = KeyCombination("Ctrl+alt+shift+b")
self.assertEqual(key_comb.as_string, "SHIFT + CTRL + ALT + B")
| 4,567 | Python | 47.595744 | 196 | 0.680534 |
omniverse-code/kit/exts/omni.gpu_foundation/omni/gpu_foundation_factory/__init__.py | from ._gpu_foundation_factory import *
from .impl.foundation_extension import GpuFoundationConfig
# Cached interface instance pointer
def get_gpu_foundation_factory_interface() -> IGpuFoundationFactory:
"""Returns cached :class:`omni.gpu_foundation.IGpuFoundationFactory` interface"""
if not hasattr(get_gpu_foundation_factory_interface, "gpu_foundation_factory"):
get_gpu_foundation_factory_interface.gpu_foundation_factory = acquire_gpu_foundation_factory_interface()
return get_gpu_foundation_factory_interface.gpu_foundation_factory
| 559 | Python | 49.909086 | 112 | 0.792487 |
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/scripts/material_utils.py | import carb
from pxr import Usd, Sdf, UsdShade
class Constant:
def __setattr__(self, name, value):
raise Exception(f"Can't change Constant.{name}")
ICON_SIZE = 96
BOUND_LABEL_WIDTH = 50
FONT_SIZE = 14.0
SDF_PATH_INVALID = "$NONE$"
PERSISTENT_SETTINGS_PREFIX = "/persistent"
MIXED = "Mixed"
MIXED_COLOR = 0xFFCC9E61
# verify SDF_PATH_INVALID is invalid
if Sdf.Path.IsValidPathString(SDF_PATH_INVALID):
raise Exception(f"SDF_PATH_INVALID is Sdf.Path.IsValidPathString - FIXME")
def _populate_data(stage, material_data, collection_or_prim, material=None, relationship=None):
def update_strength(value, strength):
if value is None:
value = strength
elif value != strength:
value = Constant.MIXED
return value
if isinstance(collection_or_prim, Usd.CollectionAPI):
prim_path = collection_or_prim.GetCollectionPath()
else:
prim_path = collection_or_prim.GetPath()
inherited = False
strength_default = carb.settings.get_settings().get(
Constant.PERSISTENT_SETTINGS_PREFIX + "/app/stage/materialStrength"
)
strength = strength_default
material_name = Constant.SDF_PATH_INVALID
if material:
relationship_source_path = None
if relationship:
relationship_source_path = relationship.GetPrim().GetPath()
if isinstance(collection_or_prim, Usd.CollectionAPI):
relationship_source_path = relationship.GetTargets()[0]
if (
material
and relationship
and prim_path.pathString != relationship_source_path.pathString
):
#If we have a material, but it's not assigned directly to us, it must be inherited
inherited = True
if relationship:
strength = UsdShade.MaterialBindingAPI.GetMaterialBindingStrength(relationship)
material_name = material.GetPrim().GetPath().pathString
if not material_name in material_data["material"]:
material_data["material"][material_name] = {
"bound": set(),
"inherited": set(),
"bound_info": set(),
"inherited_info": set(),
"relationship": set(),
"strength": None,
}
if inherited:
material_data["material"][material_name]["inherited"].add(collection_or_prim)
material_data["material"][material_name]["inherited_info"].add(
(prim_path.pathString, material_name, strength)
)
material_data["inherited"].add(collection_or_prim)
material_data["inherited_info"].add((prim_path.pathString, material_name, strength))
else:
material_data["material"][material_name]["bound"].add(collection_or_prim)
material_data["material"][material_name]["bound_info"].add(
(prim_path.pathString, material_name, strength)
)
material_data["bound"].add(collection_or_prim)
material_data["bound_info"].add((prim_path.pathString, material_name, strength))
if relationship:
material_data["relationship"].add(relationship)
material_data["material"][material_name]["relationship"].add(relationship)
if strength is not None:
material_data["material"][material_name]["strength"] = update_strength(
material_data["material"][material_name]["strength"], strength
)
material_data["strength"] = update_strength(material_data["strength"], strength)
def get_binding_from_prims(stage, prim_paths):
material_data = {"material": {}, "bound": set(), "bound_info": set(), "inherited": set(), "inherited_info": set(), "relationship": set(), "strength": None}
for prim_path in prim_paths:
if prim_path.IsPrimPath():
prim = stage.GetPrimAtPath(prim_path)
if prim:
material, relationship = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
_populate_data(stage, material_data, prim, material, relationship)
elif Usd.CollectionAPI.IsCollectionAPIPath(prim_path):
real_prim_path = prim_path.GetPrimPath()
prim = stage.GetPrimAtPath(real_prim_path)
binding_api = UsdShade.MaterialBindingAPI(prim)
all_bindings = binding_api.GetCollectionBindings()
collection_name = prim_path.pathString[prim_path.pathString.find(".collection:")+12:]
#TODO: test this when we have multiple collections on a prim
if all_bindings:
for b in all_bindings:
collection = b.GetCollection()
if collection_name==collection.GetName():
relationship = b.GetBindingRel()
material = b.GetMaterial()
_populate_data(stage, material_data, collection, material, relationship)
else:
#If there are no bindings we want to set up defaults anyway so the widget appears with "None" assigned
collection = Usd.CollectionAPI.Get(stage, prim_path)
_populate_data(stage, material_data, collection)
return material_data
| 5,252 | Python | 40.690476 | 159 | 0.619954 |
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/scripts/__init__.py | from .material_properties import *
| 35 | Python | 16.999992 | 34 | 0.8 |
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/scripts/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 typing import List
from omni.kit.window.property.templates import SimplePropertyWidget
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidget, UsdPropertyUiEntry
from .subIdentifier_utils import SubIdentifierUtils
import copy
import asyncio
import carb
import omni.ui as ui
import omni.usd
from pxr import Usd, Tf, Vt, Sdf, UsdShade, UsdUI
class UsdMaterialAttributeWidget(UsdPropertiesWidget):
def __init__(self, schema: Usd.SchemaBase, title: str, include_names: List[str], exclude_names: List[str], schema_ignore: Usd.SchemaBase=None):
"""
Constructor.
Args:
schema (Usd.SchemaBase): schema class
schema_ignore (List[Usd.SchemaBase]): ignored schema class
title (str): Title of the widgets on the Collapsable Frame.
include_names (list): list of names to be included
exclude_names (list): list of names to be excluded
"""
super().__init__(title=title, collapsed=False)
self._title = title
self._schema = schema
self._schema_ignore = schema_ignore
self._schema_attr_names = self._schema.GetSchemaAttributeNames(True)
self._schema_attr_names = self._schema_attr_names + include_names
self._schema_attr_names = set(self._schema_attr_names) - set(exclude_names)
self._additional_paths = []
self._lookup_table = {
# materials - should be set
"inputs:diffuse_color_constant": {"name": "Base Color", "group": "Albedo"},
"inputs:diffuse_texture": {"name": "Albedo Map", "group": "Albedo"},
"inputs:albedo_desaturation": {"name": "Albedo Desaturation", "group": "Albedo"},
"inputs:albedo_add": {"name": "Albedo Add", "group": "Albedo"},
"inputs:albedo_brightness": {"name": "Albedo Brightness", "group": "Albedo"},
"inputs:diffuse_tint": {"name": "Color Tint", "group": "Albedo"},
"inputs:reflection_roughness_constant": {"name": "Roughness Amount", "group": "Reflectivity"},
"inputs:reflection_roughness_texture_influence": {
"name": "Roughness Map Influence",
"group": "Reflectivity",
},
"inputs:reflectionroughness_texture": {"name": "Roughness Map", "group": "Reflectivity"},
"inputs:metallic_constant": {"name": "Metallic Amount", "group": "Reflectivity"},
"inputs:metallic_texture_influence": {"name": "Metallic Map Influence", "group": "Reflectivity"},
"inputs:metallic_texture": {"name": "Metallic Map", "group": "Reflectivity"},
"inputs:specular_level": {"name": "Specular", "group": "Reflectivity"},
"inputs:enable_ORM_texture": {"name": "Enable ORM Texture", "group": "Reflectivity"},
"inputs:ORM_texture": {"name": "ORM Map", "group": "Reflectivity"},
"inputs:ao_to_diffuse": {"name": "AO to Diffuse", "group": "AO"},
"inputs:ao_texture": {"name": "Ambient Occlusion Map", "group": "AO"},
"inputs:enable_emission": {"name": "Enable Emission", "group": "Emissive"},
"inputs:emissive_color": {"name": "Emissive Color", "group": "Emissive"},
"inputs:emissive_color_texture": {"name": "Emissive Color map", "group": "Emissive"},
"inputs:emissive_mask_texture": {"name": "Emissive Mask map", "group": "Emissive"},
"inputs:emissive_intensity": {"name": "Emissive Intensity", "group": "Emissive"},
"inputs:bump_factor": {"name": "Normal Map Strength", "group": "Normal"},
"inputs:normalmap_texture": {"name": "Normal Map", "group": "Normal"},
"inputs:detail_bump_factor": {"name": "Detail Normal Strength", "group": "Normal"},
"inputs:detail_normalmap_texture": {"name": "Detail Normal Map", "group": "Normal"},
"inputs:project_uvw": {"name": "Enable Project UVW Coordinates", "group": "UV"},
"inputs:world_or_object": {"name": "Enable World Space", "group": "UV"},
"inputs:uv_space_index": {"name": "UV Space Index", "group": "UV"},
"inputs:texture_translate": {"name": "Texture Translate", "group": "UV"},
"inputs:texture_rotate": {"name": "Texture Rotate", "group": "UV"},
"inputs:texture_scale": {"name": "Texture Scale", "group": "UV"},
"inputs:detail_texture_translate": {"name": "Detail Texture Translate", "group": "UV"},
"inputs:detail_texture_rotate": {"name": "Detail Texture Rotate", "group": "UV"},
"inputs:detail_texture_scale": {"name": "Detail Texture Scale", "group": "UV"},
"inputs:excludeFromWhiteMode": {"group": "Material Flags", "name": "Exclude from White Mode"},
# UsdUVTexture
"inputs:sourceColorSpace": {"group": "UsdUVTexture", "name": "inputs:sourceColorSpace"},
"inputs:fallback": {"group": "UsdUVTexture", "name": "inputs:fallback"},
"inputs:file": {"group": "UsdUVTexture", "name": "inputs:file"},
"inputs:sdrMetadata": {"group": "UsdUVTexture", "name": "inputs:sdrMetadata"},
"inputs:rgb": {"group": "UsdUVTexture", "name": "inputs:rgb"},
"inputs:scale": {"group": "UsdUVTexture", "name": "inputs:scale"},
"inputs:bias": {"group": "UsdUVTexture", "name": "inputs:bias"},
"inputs:wrapS": {"group": "UsdUVTexture", "name": "inputs:wrapS"},
"inputs:wrapT": {"group": "UsdUVTexture", "name": "inputs:wrapT"},
# preview surface inputs
"inputs:diffuseColor": {"name": "Diffuse Color", "group": "Inputs"},
"inputs:emissiveColor": {"name": "Emissive Color", "group": "Inputs"},
"inputs:useSpecularWorkflow": {"name": "Use Specular Workflow", "group": "Inputs"},
"inputs:specularColor": {"name": "Specular Color", "group": "Inputs"},
"inputs:metallic": {"name": "Metallic", "group": "Inputs"},
"inputs:roughness": {"name": "Roughness", "group": "Inputs"},
"inputs:clearcoat": {"name": "Clearcoat", "group": "Inputs"},
"inputs:clearcoatRoughness": {"name": "Clearcoat Roughness", "group": "Inputs"},
"inputs:opacity": {"name": "Opacity", "group": "Inputs"},
"inputs:opacityThreshold": {"name": "Opacity Threshold", "group": "Inputs"},
"inputs:ior": {"name": "Index Of Refraction", "group": "Inputs"},
"inputs:normal": {"name": "Normal", "group": "Inputs"},
"inputs:displacement": {"name": "Displacement", "group": "Inputs"},
"inputs:occlusion": {"name": "Occlusion", "group": "Inputs"},
# info
"info:id": {"name": "ID", "group": "Info"},
"info:implementationSource": {"name": "Implementation Source", "group": "Info"},
"info:mdl:sourceAsset": {"name": "", "group": "Info"},
"info:mdl:sourceAsset:subIdentifier": {"name": "", "group": "Info"},
# nodegraph
"ui:nodegraph:node:displayColor": {"name": "Display Color", "group": "UI Properties"},
"ui:nodegraph:node:expansionState": {"name": "Expansion State", "group": "UI Properties"},
"ui:nodegraph:node:icon": {"name": "Icon", "group": "UI Properties"},
"ui:nodegraph:node:pos": {"name": "Position", "group": "UI Properties"},
"ui:nodegraph:node:size": {"name": "Size", "group": "UI Properties"},
"ui:nodegraph:node:stackingOrder": {"name": "Stacking Order", "group": "UI Properties"},
# backdrop
"ui:description": {"name": "Description", "group": "UI Properties"},
}
def on_new_payload(self, payload):
"""
See PropertyWidget.on_new_payload
"""
self._anchor_prim = None
self._shader_paths = []
self._add_source_color_space_placeholder = False
self._material_annotations = {}
if not super().on_new_payload(payload):
return False
if len(self._payload) == 0:
return False
anchor_prim = None
shader_paths = []
mtl_paths = []
for prim_path in self._payload:
prim = self._get_prim(prim_path)
if not prim or not prim.IsA(self._schema):
return False
if self._schema_ignore and prim.IsA(self._schema_ignore):
return False
shader_prim = omni.usd.get_shader_from_material(prim, True)
if shader_prim:
shader_paths.append(shader_prim.GetPath())
shader = UsdShade.Shader(shader_prim if shader_prim else prim)
asset = shader.GetSourceAsset("mdl") if shader else None
mdl_file = asset.resolvedPath if asset else None
if mdl_file:
def loaded_mdl_subids(mtl_list, filename):
mdl_dict = {}
for mtl in mtl_list:
mdl_dict[mtl.name] = mtl.annotations
self._material_annotations[filename] = mdl_dict
mtl_paths.append(mdl_file)
asyncio.ensure_future(omni.kit.material.library.get_subidentifier_from_mdl(mdl_file=mdl_file, on_complete_fn=lambda l, f=mdl_file: loaded_mdl_subids(mtl_list=l, filename=f)))
anchor_prim = prim
if anchor_prim:
stage = payload.get_stage()
shader = UsdShade.Shader.Get(stage, anchor_prim.GetPath())
if shader and shader.GetShaderId() == "UsdUVTexture":
attr = anchor_prim.GetAttribute("inputs:sourceColorSpace")
if not attr:
self._add_source_color_space_placeholder = True
elif attr.GetTypeName() == Sdf.ValueTypeNames.Token:
tokens = attr.GetMetadata("allowedTokens")
if not tokens:
# fix missing tokens on attribute
attr.SetMetadata("allowedTokens", ["auto", "raw", "sRGB"])
self._mtl_identical = True
if mtl_paths:
self._mtl_identical = mtl_paths.count(mtl_paths[0]) == len(mtl_paths)
self._anchor_prim = anchor_prim
self._shader_paths = shader_paths
if anchor_prim:
return True
return False
def _filter_props_to_build(self, attrs):
if not self._mtl_identical:
for attr in copy.copy(attrs):
if attr.GetName() == "info:mdl:sourceAsset:subIdentifier":
attrs.remove(attr)
return [
attr
for attr in attrs
if isinstance(attr, Usd.Attribute) and (attr.GetName() in self._schema_attr_names and not attr.IsHidden()
or UsdShade.Input.IsInput(attr) and not attr.IsHidden()
or UsdShade.Output.IsOutput(attr) and not attr.IsHidden())
]
def _customize_props_layout(self, attrs):
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.window.property.templates import (
SimplePropertyWidget,
LABEL_WIDTH,
LABEL_HEIGHT,
HORIZONTAL_SPACING,
)
self._additional_paths = []
if not self._anchor_prim:
return []
ignore_list = ["outputs:out", "info:id", "info:implementationSource", "info:mdl:sourceAsset", "info:mdl:sourceAsset:subIdentifier"]
# check for duplicate attributes in material/shader
stage = self._payload.get_stage()
add_source_color_space_placeholder = len(self._payload)
for path in self._payload:
prim = stage.GetPrimAtPath(path)
shader_prim = omni.usd.get_shader_from_material(prim, True)
if shader_prim:
shader = UsdShade.Shader.Get(stage, shader_prim.GetPath())
if shader and shader.GetShaderId() == "UsdUVTexture":
attr = shader_prim.GetAttribute("inputs:sourceColorSpace")
if not attr:
add_source_color_space_placeholder -= 1
if add_source_color_space_placeholder == 0:
self._add_source_color_space_placeholder = True
# get child attributes
attr_added = {}
for path in self._payload:
if not path in attr_added:
attr_added[path.pathString] = {}
material_prim = stage.GetPrimAtPath(path)
shader_prim = omni.usd.get_shader_from_material(material_prim, True)
if shader_prim:
asyncio.ensure_future(omni.usd.get_context().load_mdl_parameters_for_prim_async(shader_prim))
for shader_attr in shader_prim.GetAttributes():
if shader_attr.IsHidden():
continue
# check if shader attribute already exists in material
material_attr = material_prim.GetAttribute(shader_attr.GetName())
if material_attr.IsHidden():
continue
if material_attr:
# use material attribute NOT shader attribute
attr_added[path.pathString][shader_attr.GetName()] = material_attr
continue
# add paths to usd_changed watch list
prim_path = shader_attr.GetPrimPath()
if not prim_path in self._payload and not prim_path in self._additional_paths:
self._additional_paths.append(prim_path)
if not any(name in shader_attr.GetName() for name in ignore_list):
attr_added[path.pathString][shader_attr.GetName()] = shader_attr
if not self._anchor_prim:
return []
# remove uncommon keys
anchor_path = self._anchor_prim.GetPath().pathString
anchor_attr = attr_added[anchor_path]
common_keys = anchor_attr.keys()
for key in attr_added:
if anchor_path != key:
common_keys = common_keys & attr_added[key].keys()
def compare_metadata(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
# remove any keys that metadata's differ
for key in copy.copy(list(common_keys)):
attr1 = attr_added[anchor_path][key]
for path in self._payload:
if path == anchor_path:
continue
attr2 = attr_added[path.pathString][key]
if not (
attr1.GetName() == attr2.GetName() and
attr1.GetDisplayGroup() == attr2.GetDisplayGroup() and
attr1.GetConnections() == attr2.GetConnections() and
compare_metadata(attr1.GetAllMetadata(), attr2.GetAllMetadata()) and
type(attr1) == type(attr2)
):
common_keys.remove(key)
break
# add remaining common keys
# use anchor_attr.keys() to keep the original order as common_keys order has changed
for key in anchor_attr.keys():
if key not in common_keys:
continue
attr = anchor_attr[key]
attrs.append(
UsdPropertyUiEntry(
attr.GetName(),
attr.GetDisplayGroup(),
attr.GetAllMetadata(),
type(attr),
prim_paths=self._shader_paths,
))
if self._add_source_color_space_placeholder:
attrs.append(
UsdPropertyUiEntry(
"inputs:sourceColorSpace",
"UsdUVTexture",
{
Sdf.PrimSpec.TypeNameKey: "token",
"allowedTokens": Vt.TokenArray(3, ("auto", "raw", "sRGB")),
"customData": {"default": "auto"},
},
Usd.Attribute,
)
)
# move inputs/outputs to own group
for attr in attrs:
if attr.attr_name and attr.attr_name in self._lookup_table:
lookup = self._lookup_table[attr.attr_name]
displayName = attr.metadata.get("displayName", None)
if not displayName and lookup["name"]:
attr.override_display_name(lookup["name"])
if not attr.display_group and lookup["group"]:
attr.override_display_group(lookup["group"])
if not attr.display_group:
if attr.prop_name.startswith("output"):
attr.override_display_group("Outputs")
elif attr.prop_name.startswith("inputs"):
attr.override_display_group("Inputs")
if attr.display_group == "UI Properties":
if self._anchor_prim.IsA(UsdUI.Backdrop):
attr.display_group_collapsed = False
else:
attr.display_group_collapsed = True
elif attr.display_group in ["Outputs", "Material Flags"]:
attr.display_group_collapsed = True
#remove inputs: and outputs: prefixes from items w/o explicit display name metadata
if Sdf.PropertySpec.DisplayNameKey not in attr.metadata:
attr.metadata[Sdf.PropertySpec.DisplayNameKey] = attr.attr_name.split(":")[-1]
# move groups to top...
frame = CustomLayoutFrame(hide_extra=False)
with frame:
with CustomLayoutGroup("Info"):
CustomLayoutProperty("info:implementationSource", "implementationSource")
CustomLayoutProperty("info:mdl:sourceAsset", "mdl:sourceAsset")
CustomLayoutProperty("info:mdl:sourceAsset:subIdentifier", "mdl:sourceAsset:subIdentifier")
CustomLayoutProperty("info:id", "id")
material_annotations = SubIdentifierUtils.get_annotations("description", prim, self._material_annotations)
if material_annotations:
with CustomLayoutGroup("Description", collapsed=True):
CustomLayoutProperty(None, None, build_fn=lambda s, a, m, pt, pp, al, aw, mal=material_annotations:
SubIdentifierUtils.annotations_build_fn(stage=s,
attr_name=a,
metadata=m,
property_type=pt,
prim_paths=pp,
additional_label_kwargs=al,
additional_widget_kwarg=aw,
material_annotations=mal))
with CustomLayoutGroup("Outputs", collapsed=True):
CustomLayoutProperty("outputs:mdl:surface", "mdl:surface")
CustomLayoutProperty("outputs:mdl:displacement", "mdl:displacement")
CustomLayoutProperty("outputs:mdl:volume", "mdl:volume")
CustomLayoutProperty("outputs:surface", "surface")
CustomLayoutProperty("outputs:displacement", "displacement")
CustomLayoutProperty("outputs:volume", "volume")
attrs = frame.apply(attrs)
# move Outputs to last, anything appearing after needs adding to CustomLayout above
def output_sort(attr):
if attr.prop_name.startswith("output"):
if attr.prop_name == "outputs:out":
return 2
return 1
return 0
attrs.sort(key=output_sort)
return attrs
def build_property_item(self, stage, ui_attr: UsdPropertyUiEntry, prim_paths: List[Sdf.Path]):
if ui_attr.prop_name == "info:mdl:sourceAsset:subIdentifier":
if self._anchor_prim:
attr = self._anchor_prim.GetAttribute(ui_attr.prop_name)
material_annotations = None
if attr:
shader = UsdShade.Shader(self._anchor_prim)
asset = shader.GetSourceAsset("mdl") if shader else None
mdl_file = asset.resolvedPath if asset else None
if mdl_file and mdl_file in self._material_annotations:
material_annotations = self._material_annotations[mdl_file]
model = SubIdentifierUtils.build_subidentifier(
stage,
attr_name=ui_attr.prop_name,
type_name=ui_attr.property_type,
metadata=ui_attr.metadata,
attr=attr,
prim_paths=prim_paths,
)
return model
return super().build_property_item(stage, ui_attr, prim_paths)
def _on_usd_changed(self, notice, 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
for path in notice.GetChangedInfoOnlyPaths():
if path.name.startswith("info:"):
self.request_rebuild()
return
for path in notice.GetResyncedPaths():
if path in self._additional_paths or path in self._payload:
self.request_rebuild()
return
elif (
path.GetPrimPath() in self._additional_paths
or path.GetPrimPath() in self._shader_paths
or path.GetPrimPath() in self._payload
):
# If prop is added or removed, rebuild frame
# TODO only check against the attributes this widget cares about
if bool(stage.GetPropertyAtPath(path)) != bool(self._models.get(path)):
self.request_rebuild()
return
else:
# OM-75480: For material prim, it needs special treatment. So modifying shader prim
# needs to refresh material prim widget also.
# How to avoid accessing private variable of parent class?
self._pending_dirty_paths.add(path)
super()._on_usd_changed(notice=notice, stage=stage)
| 23,730 | Python | 49.277542 | 190 | 0.55196 |
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/scripts/subIdentifier_utils.py | from typing import List
from collections import defaultdict, OrderedDict
from omni.kit.window.property.templates import SimplePropertyWidget, LABEL_WIDTH, LABEL_HEIGHT, HORIZONTAL_SPACING
from omni.kit.property.usd.usd_property_widget import (
UsdPropertiesWidget,
UsdPropertyUiEntry,
UsdPropertiesWidgetBuilder,
)
from omni.kit.property.usd.usd_attribute_model import UsdAttributeModel, TfTokenAttributeModel
import asyncio
import carb
import omni.ui as ui
import omni.usd
from pxr import Usd, Tf, Vt, Sdf, UsdShade
class SubIdentifierUtils:
class AllowedAnnoItem(ui.AbstractItem):
def __init__(self, item, token=None):
from omni.kit.material.library import MaterialLibraryExtension
super().__init__()
if isinstance(item, MaterialLibraryExtension.SubIDEntry):
if "subid_token" in item.annotations:
self.token = item.annotations["subid_token"]
else:
self.token = item.name
self.model = ui.SimpleStringModel(item.name)
if "subid_display_name" in item.annotations:
self.model = ui.SimpleStringModel(item.annotations['subid_display_name'])
elif "display_name" in item.annotations:
self.model = ui.SimpleStringModel(item.annotations['display_name'])
else:
self.model = ui.SimpleStringModel(item.name)
else:
if token:
self.token = token
self.model = ui.SimpleStringModel(item)
else:
self.token = item
self.model = ui.SimpleStringModel(item)
class SubIdentifierModel(TfTokenAttributeModel):
def __init__(
self,
stage: Usd.Stage,
attribute_paths: List[Sdf.Path],
self_refresh: bool,
metadata: dict,
options: list,
attr: Usd.Attribute,
):
self._widget = None
self._combobox_options = [attr.Get()]
super().__init__(stage=stage, attribute_paths=attribute_paths, self_refresh=self_refresh, metadata=metadata)
self._has_index = False
async def load_subids():
await omni.kit.app.get_app().next_update_async()
await omni.kit.material.library.get_subidentifier_from_material(prim=attr.GetPrim(), on_complete_fn=self._have_list, use_functions=True)
asyncio.ensure_future(load_subids())
def _get_allowed_tokens(self, attr):
return self._combobox_options
def _update_allowed_token(self):
super()._update_allowed_token(SubIdentifierUtils.AllowedAnnoItem)
def _update_value(self, force=False):
from omni.kit.property.usd.usd_model_base import UsdBase
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()
def find_allowed_token(value):
# try to match the full token, i.e. simple name with function parameters
for i in range(0, len(self._allowed_tokens)):
if self._allowed_tokens[i].token == value:
return i
# if the above failed, drop the parameter list of the query
# try to find a match based on the simple name alone
# note, because of overloads there can be more than one match
query = value.split("(", 1)[0]
match_count = 0
first_match_index = -1
for i in range(0, len(self._allowed_tokens)):
if self._allowed_tokens[i].token.split("(", 1)[0] == query:
if match_count == 0:
first_match_index = i
match_count += 1
# if there is one match based on simple name, we can safely return this one
if match_count == 1:
return first_match_index
# the match is not unique, we need to return a `<not found>`
else:
return -1
index = find_allowed_token(self._value)
if self._value and index == -1:
carb.log_warn(f"failed to find '{self._value}' in function name list")
index = len(self._allowed_tokens)
self._allowed_tokens.append(SubIdentifierUtils.AllowedAnnoItem(token=self._value, item=f"<sub-identifier not found: '{self._value}'>"))
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 _have_list(self, mtl_list: list):
if mtl_list:
self._combobox_options = mtl_list
self._set_dirty()
if self._has_index is False:
self._update_value()
self._has_index = True
def build_subidentifier(
stage,
attr_name,
type_name,
metadata,
attr: Usd.Attribute,
prim_paths: List[Sdf.Path],
additional_label_kwargs=None,
additional_widget_kwargs=None,
):
with ui.HStack(spacing=HORIZONTAL_SPACING):
model = None
UsdPropertiesWidgetBuilder._create_label(attr_name, metadata, additional_label_kwargs)
tokens = metadata.get("allowedTokens")
if not tokens:
tokens = [attr.Get()]
model = SubIdentifierUtils.SubIdentifierModel(
stage,
attribute_paths=[path.AppendProperty(attr_name) for path in prim_paths],
self_refresh=False,
metadata=metadata,
options=tokens,
attr=attr,
)
widget_kwargs = {"name": "choices", "no_default": True}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
with ui.ZStack():
value_widget = ui.ComboBox(model, **widget_kwargs)
value_widget.identifier = 'sdf_asset_info:mdl:sourceAsset:subIdentifier'
mixed_overlay = UsdPropertiesWidgetBuilder._create_mixed_text_overlay()
UsdPropertiesWidgetBuilder._create_control_state(
model=model, value_widget=value_widget, mixed_overlay=mixed_overlay, **widget_kwargs
)
return model
def annotations_build_fn(
stage,
attr_name,
metadata,
property_type,
prim_paths: List[Sdf.Path],
additional_label_kwargs,
additional_widget_kwarg,
material_annotations
):
additional_label_kwargs = {"width": ui.Fraction(1), "read_only": True}
description = material_annotations["description"]
description = description.replace("\n\r", "\r").replace("\n", "\r")
description_list = description.split("\r")
if len(description_list) > 1:
with ui.VStack(spacing=2):
for description in description_list:
if not description:
continue
parts = description.split("\t", maxsplit=1)
if len(parts) == 1:
parts = description.split(" ", maxsplit=1)
with ui.HStack(spacing=HORIZONTAL_SPACING):
if len(parts) == 1:
parts.append("")
UsdPropertiesWidgetBuilder._create_label(parts[0])
if parts[1].startswith("http"):
additional_label_kwargs["tooltip"] = f"Click to open \"{parts[1]}\""
else:
additional_label_kwargs["tooltip"] = parts[1]
UsdPropertiesWidgetBuilder._create_text_label(parts[1], additional_label_kwargs=additional_label_kwargs)
else:
with ui.HStack(spacing=HORIZONTAL_SPACING):
UsdPropertiesWidgetBuilder._create_label("Description")
additional_label_kwargs["tooltip"] = description
UsdPropertiesWidgetBuilder._create_text_label(description, additional_label_kwargs=additional_label_kwargs)
def get_annotations(
annotation_key,
prim,
material_annotation_list,
):
if prim.IsA(UsdShade.Material):
shader = omni.usd.get_shader_from_material(prim, False)
attr = shader.GetPrim().GetAttribute("info:mdl:sourceAsset:subIdentifier") if shader else None
else:
attr = prim.GetAttribute("info:mdl:sourceAsset:subIdentifier") if prim else None
shader = UsdShade.Shader(prim)
if attr:
asset = shader.GetSourceAsset("mdl") if shader else None
mdl_file = asset.resolvedPath if asset else None
if mdl_file and mdl_file in material_annotation_list:
material_annotations = material_annotation_list[mdl_file]
if attr.Get() in material_annotations:
material_annotations = material_annotations[attr.Get()]
if annotation_key in material_annotations:
return material_annotations
return None
| 9,774 | Python | 42.061674 | 155 | 0.558625 |
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/scripts/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 omni.kit.context_menu
from typing import Set
from pxr import Usd, Sdf, UsdShade
material_clipboard = []
# menu functions....
def is_material_selected(objects):
material_prim = objects["material_prim"]
if material_prim:
return True
return False
def is_multiple_material_selected(objects):
selected_paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
mtl_list = []
for path in selected_paths:
prim = objects["stage"].GetPrimAtPath(path)
if not prim:
return False
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
if bound_material and bound_material not in mtl_list:
mtl_list.append(bound_material)
return bool(len(mtl_list)>1)
def is_material_copied(objects):
return bool(len(material_clipboard) > 0)
def is_bindable_prim_selected(objects):
for prim_path in omni.usd.get_context().get_selection().get_selected_prim_paths():
prim = objects["stage"].GetPrimAtPath(prim_path)
if prim and omni.usd.is_prim_material_supported(prim):
return True
return False
def is_prim_selected(self, objects: dict):
"""
checks if any prims are selected
"""
if not any(item in objects for item in ["prim", "prim_list"]):
return False
return True
def is_paste_all(objects):
return bool(len(omni.usd.get_context().get_selection().get_selected_prim_paths()) > len(material_clipboard))
def goto_material(objects):
material_prim = objects["material_prim"]
if material_prim:
omni.usd.get_context().get_selection().set_prim_path_selected(material_prim.GetPath().pathString, True, True, True, True)
def copy_material(objects: dict, all: bool):
global material_clipboard
material_clipboard = []
for prim in objects["prim_list"]:
mat, rel = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
material_path = mat.GetPath().pathString if mat else None
material_strength = UsdShade.MaterialBindingAPI.GetMaterialBindingStrength(rel) if rel else UsdShade.Tokens.weakerThanDescendants
material_clipboard.append((material_path, material_strength))
def paste_material(objects: dict):
selected_paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
prims = [objects["stage"].GetPrimAtPath(p) for p in selected_paths]
with omni.kit.undo.group():
max_paste = len(material_clipboard)
for index, prim in enumerate(prims):
if index >= max_paste:
break
material_path, material_strength = material_clipboard[index]
if material_path:
omni.kit.commands.execute(
"BindMaterial",
prim_path=prim.GetPath(),
material_path=material_path,
strength=material_strength,
)
def paste_material_all(objects: dict):
selected_paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
prims = [objects["stage"].GetPrimAtPath(p) for p in selected_paths]
with omni.kit.undo.group():
max_paste = len(material_clipboard)
for index, prim in enumerate(prims):
material_path, material_strength = material_clipboard[index % max_paste]
if material_path:
omni.kit.commands.execute(
"BindMaterial",
prim_path=prim.GetPath(),
material_path=material_path,
strength=material_strength,
)
def get_paste_name(objects):
if len(material_clipboard) <2:
return "Paste"
return f"Paste ({len(material_clipboard)} Materials)"
def show_context_menu(stage, material_path, bound_prims: Set[Usd.Prim]):
# get context menu core functionality & check its enabled
context_menu = omni.kit.context_menu.get_instance()
if context_menu is None:
carb.log_error("context_menu is disabled!")
return None
# setup objects, this is passed to all functions
if not stage:
return
objects = {"material_prim": stage.GetPrimAtPath(material_path), "prim_list": bound_prims}
# setup menu
menu_dict = [
{"name": "Copy", "enabled_fn": [], "onclick_fn": lambda o: copy_material(o, False)},
{"name_fn": get_paste_name, "show_fn": [is_bindable_prim_selected, is_material_copied], "onclick_fn": paste_material},
{"name": "", "show_fn": is_material_selected},
{"name": "Select Material", "show_fn": is_material_selected, "onclick_fn": goto_material},
]
# show menu
menu_dict += omni.kit.context_menu.get_menu_dict("MENU_THUMBNAIL", "")
omni.kit.context_menu.reorder_menu_dict(menu_dict)
context_menu.show_context_menu("material_thumbnail", objects, menu_dict)
| 5,286 | Python | 38.455224 | 137 | 0.659289 |
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/scripts/usd_binding_widget.py | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.kit.window.property.templates import SimplePropertyWidget, LABEL_WIDTH, LABEL_HEIGHT
from omni.kit.material.library.listbox_widget import MaterialListBoxWidget
from omni.kit.material.library.thumbnail_loader import ThumbnailLoader
from omni.kit.material.library.search_widget import SearchWidget
from .material_utils import Constant, get_binding_from_prims
from .context_menu import show_context_menu
from typing import List, Set
from functools import partial
from pxr import Usd, Tf, Sdf, UsdShade
import copy
import os
import weakref
import asyncio
import weakref
import carb
import omni.ui as ui
import omni.usd
import omni.kit.material.library
import omni.kit.context_menu
class UsdBindingAttributeWidget(SimplePropertyWidget):
def __init__(self, extension_path, add_context_menu=False):
super().__init__(title="Materials on selected models", collapsed=False)
self._strengths = {
"Weaker than Descendants": UsdShade.Tokens.weakerThanDescendants,
"Stronger than Descendants": UsdShade.Tokens.strongerThanDescendants,
}
self._extension_path = extension_path
self._thumbnail_loader = ThumbnailLoader()
BUTTON_BACKGROUND_COLOR = 0xFF323434
GENERAL_BACKGROUND_COLOR = 0xFF1F2124
self._theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
if self._theme != "NvidiaDark":
BUTTON_BACKGROUND_COLOR = 0xFF545454
GENERAL_BACKGROUND_COLOR = 0xFF545454
self._listbox_widget = None
self._search_widget = SearchWidget(theme=self._theme, icon_path=None)
self._style = {
"Image::material": {"margin": 12},
"Button::material_mixed": {"margin": 10},
"Button.Image::material_mixed": {"image_url": f"{self._extension_path}/data/icons/[email protected]"},
"Button::material_solo": {"margin": 10},
"Button.Image::material_solo": {"image_url": f"{self._extension_path}/data/icons/[email protected]"},
"Field::prims" : {"font_size": Constant.FONT_SIZE},
"Field::prims_mixed" : {"font_size": Constant.FONT_SIZE, "color": Constant.MIXED_COLOR},
"Label::prim" : {"font_size": Constant.FONT_SIZE},
"ComboBox": {"font_size": Constant.FONT_SIZE},
"Label::combo_mixed": {
"font_size": Constant.FONT_SIZE,
"color": Constant.MIXED_COLOR,
"margin_width": 5,
},
}
self._listener = None
self._pending_frame_rebuild_task = None
self._paste_all_menu = None
if add_context_menu:
# paste all on collapsible frame header
from .context_menu import is_bindable_prim_selected, is_material_copied, is_paste_all, paste_material_all
menu_dict = {"name": "Paste To All", "enabled_fn": [is_bindable_prim_selected, is_material_copied, is_paste_all], "onclick_fn": paste_material_all}
self._paste_all_menu = omni.kit.context_menu.add_menu(menu_dict, "group_context_menu.Materials on selected models", "omni.kit.window.property")
def clean(self):
self._thumbnail_loader = None
if self._listbox_widget:
self._listbox_widget.clean()
self._listbox_widget = None
self._search_widget.clean()
self._paste_all_menu = None
super().clean()
def _materials_changed(self):
self.request_rebuild()
def _get_prim(self, prim_path):
if prim_path:
stage = self._payload.get_stage()
if stage:
return stage.GetPrimAtPath(prim_path)
return None
def on_new_payload(self, payload):
"""
See PropertyWidget.on_new_payload
"""
if not super().on_new_payload(payload):
return False
if not payload:
return False
if len(payload) == 0:
return False
for prim_path in payload:
prim = self._get_prim(prim_path)
if prim and not omni.usd.is_prim_material_supported(prim):
return False
if not prim and not Usd.CollectionAPI.IsCollectionAPIPath(prim_path):
return False
return True
def _get_index(self, items: List[str], value: str, default_value: int = 0):
index = default_value
try:
index = items.index(value)
except:
pass
return index
def _get_theme_name(self, darkname, lightname):
if self._theme=="NvidiaDark":
return darkname
return lightname
def _show_material_popup(self, name_field: ui.StringField, material_index: int, bind_material_fn: callable):
if self._listbox_widget:
self._listbox_widget.clean()
del self._listbox_widget
self._listbox_widget = None
self._listbox_widget = MaterialListBoxWidget(icon_path=None, index=material_index, on_click_fn=bind_material_fn, theme=self._theme)
self._listbox_widget.set_parent(name_field)
self._listbox_widget.set_selection_on_loading_complete(name_field.model.get_value_as_string() if material_index >= 0 else None)
self._listbox_widget.build_ui()
def _build_material_popup(self, material_list: List[str], material_index: int, thumbnail_image: ui.Button, bound_prim_list: Set[Usd.Prim], bind_material_fn: callable, on_goto_fn: callable, on_dragdrop_fn: callable):
def drop_accept(url):
if len(url.split('\n')) > 1:
carb.log_warn(f"build_material_popup multifile drag/drop not supported")
return False
if url.startswith("material::"):
return True
url_ext = os.path.splitext(url)[1]
return url_ext.lower() in [".mdl"]
def dropped_mtl(event, bind_material_fn):
url = event.mime_data
subid = None
# remove omni.kit.browser.material "material::" prefix
if url.startswith("material::"):
url=url[10:]
parts = url.split(".mdl@")
if len(parts) == 2:
subid = parts[1]
url = url.replace(f".mdl@{subid}", ".mdl")
bind_material_fn(url=url, subid=subid)
name_field, listbox_button, goto_button = self._search_widget.build_ui_popup(search_size=LABEL_HEIGHT,
popup_text=material_list[material_index] if material_index >= 0 else "Mixed",
index=material_index,
update_fn=bind_material_fn)
name_field.set_mouse_pressed_fn(lambda x, y, b, m, f=name_field: self._show_material_popup(f, material_index, bind_material_fn))
name_field.set_accept_drop_fn(drop_accept)
name_field.set_drop_fn(partial(dropped_mtl, bind_material_fn=on_dragdrop_fn))
listbox_button.set_mouse_pressed_fn(lambda x, y, b, m, f=name_field: self._show_material_popup(f, material_index, bind_material_fn))
if material_index > 0:
goto_button.set_mouse_pressed_fn(lambda x, y, b, m, f=name_field: on_goto_fn(f.model))
if self._collapsable_frame:
def mouse_clicked(b, f):
if b == 0:
on_goto_fn(f.model)
elif b == 1:
show_context_menu(self._payload.get_stage(), f.model.get_value_as_string(), bound_prim_list)
thumbnail_image.set_mouse_pressed_fn(lambda x, y, b, m, f=name_field: mouse_clicked(b, f))
thumbnail_image.set_accept_drop_fn(drop_accept)
thumbnail_image.set_drop_fn(partial(dropped_mtl, bind_material_fn=on_dragdrop_fn))
def _build_combo(self, material_list: List[str], material_index: int, on_fn: callable):
def set_visible(widget, visible):
widget.visible = visible
with ui.ZStack():
combo = ui.ComboBox(material_index, *material_list)
combo.model.add_item_changed_fn(on_fn)
if material_index == -1:
placeholder = ui.Label(
"Mixed",
height=LABEL_HEIGHT,
name="combo_mixed",
)
self._combo_subscription.append(
combo.model.get_item_value_model().subscribe_value_changed_fn(
lambda m, w=placeholder: set_visible(w, m.as_int < 0)
)
)
return combo
def _build_binding_info(
self,
inherited: bool,
style_name: str,
material_list: List[str],
material_path: str,
strength_value: str,
bound_prim_list: Set[str],
on_material_fn: callable,
on_strength_fn: callable,
on_goto_fn: callable,
on_dragdrop_fn: callable,
):
prim_style = "prims"
## fixup Constant.SDF_PATH_INVALID vs "None"
material_list = copy.copy(material_list)
if material_list[0] == Constant.SDF_PATH_INVALID:
material_list[0] = "None"
if material_path == Constant.SDF_PATH_INVALID:
material_path = "None"
type_label = 'Prim'
if len(bound_prim_list) == 1:
if isinstance(bound_prim_list[0], Usd.Prim):
bound_prims = bound_prim_list[0].GetPath().pathString
elif isinstance(bound_prim_list[0], Usd.CollectionAPI):
bound_prims = bound_prim_list[0].GetCollectionPath().pathString
type_label = 'Collection'
else:
bound_prims = bound_prim_list[0]
elif len(bound_prim_list) > 1:
bound_prims = Constant.MIXED
prim_style = "prims_mixed"
else:
bound_prims = "None"
if not self._first_row:
ui.Separator(height=10)
self._first_row = False
index = self._get_index(material_list, material_path, -1)
with ui.HStack(style=self._style):
with ui.ZStack(width=0):
image_button = ui.Button(
"",
width=Constant.ICON_SIZE,
height=Constant.ICON_SIZE,
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
name=style_name,
identifier="preview_drop_target"
)
if index != -1:
material_prim = self._get_prim(material_path)
if material_prim:
def on_image_progress(button: ui.Button, image: ui.Image, progress: float):
if progress > 0.999:
button.image_url = image.source_url
image.visible = False
thumbnail_image = ui.Image(
width=Constant.ICON_SIZE,
height=Constant.ICON_SIZE,
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
name="material"
)
self._thumbnail_loader.load(material_prim, thumbnail_image)
# callback when image is loading
thumbnail_image.set_progress_changed_fn(lambda p, b=image_button, i=thumbnail_image: on_image_progress(b, i, p))
with ui.VStack(spacing=10):
with ui.HStack():
ui.Label(
type_label,
width=Constant.BOUND_LABEL_WIDTH,
height=LABEL_HEIGHT,
name="prim",
)
ui.StringField(name=prim_style, height=LABEL_HEIGHT, enabled=False).model.set_value(
bound_prims
)
if index != -1 and inherited:
inherited_list = copy.copy(material_list)
inherited_list[index] = f"{inherited_list[index]} (inherited)"
self._build_material_popup(inherited_list, index, image_button, bound_prim_list, on_material_fn, on_goto_fn, on_dragdrop_fn)
else:
self._build_material_popup(material_list, index, image_button, bound_prim_list, on_material_fn, on_goto_fn, on_dragdrop_fn)
with ui.HStack():
ui.Label(
"Strength",
width=Constant.BOUND_LABEL_WIDTH,
height=LABEL_HEIGHT,
name="prim",
)
index = self._get_index(list(self._strengths.values()), strength_value, -1)
self._build_combo(list(self._strengths.keys()), index, on_strength_fn)
def build_items(self):
binding = get_binding_from_prims(self._payload.get_stage(), self._payload)
if binding is None:
return
strengths = self._strengths
material_list = [Constant.SDF_PATH_INVALID] + [mtl for mtl in binding["material"]]
stage = self._payload.get_stage()
if not stage or len(self._payload) == 0:
return
last_prim = self._get_prim(self._payload[-1])
if not self._listener:
self._listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_usd_changed, stage)
def bind_material_to_prims(bind_material_path, items):
prim_path_list = []
strength_list = []
for prim_path, material_name, strength in items:
if str(material_name) != str(bind_material_path):
prim_path_list.append(prim_path)
strength_list.append(strength)
if str(bind_material_path) == Constant.SDF_PATH_INVALID:
bind_material_path = None
omni.kit.commands.execute(
"BindMaterial",
material_path=bind_material_path,
prim_path=prim_path_list,
strength=strength_list,
)
def on_strength_changed(model, item, relationships):
index = model.get_item_value_model().as_int
if index < 0:
carb.log_error(f"on_strength_changed with invalid index {index}")
return
bind_strength = list(strengths.values())[index]
omni.kit.undo.begin_group()
for relationship in relationships:
omni.kit.commands.execute("SetMaterialStrength", rel=relationship, strength=bind_strength)
omni.kit.undo.end_group()
if self._collapsable_frame:
self._collapsable_frame.rebuild()
def on_material_changed(model, item, items):
if isinstance(model, omni.ui._ui.AbstractItemModel):
index = model.get_item_value_model().as_int
if index < 0:
carb.log_error(f"on_material_changed with invalid index {index}")
return
bind_material_path = material_list[index] if material_list[index] != Constant.SDF_PATH_INVALID else None
elif isinstance(model, omni.ui._ui.SimpleStringModel):
bind_material_path = model.get_value_as_string()
if bind_material_path == "None":
bind_material_path = None
else:
carb.log_error(f"on_material_changed model {type(model)} unsupported")
return
bind_material_to_prims(bind_material_path, items)
if self._collapsable_frame:
self._collapsable_frame.rebuild()
def on_dragdrop(url, items, subid=""):
if len(url.split('\n')) > 1:
carb.log_warn(f"build_binding_info multifile drag/drop not supported")
return
def on_create_func(mtl_prim):
bind_material_to_prims(mtl_prim.GetPath(), items)
if self._collapsable_frame:
self._collapsable_frame.rebuild()
def reload_frame(prim):
self._materials_changed()
stage = self._payload.get_stage()
mtl_name, _ = os.path.splitext(os.path.basename(url))
def loaded_mdl_subids(mtl_list, mdl_path, filename, subid):
if not mtl_list:
return
if subid:
omni.kit.material.library.create_mdl_material(
stage=stage,
mtl_url=mdl_path,
mtl_name=subid,
on_create_fn=on_create_func,
mtl_real_name=subid)
return
if len(mtl_list) > 1:
prim_paths = [prim_path for prim_path, material_name, strength in items]
omni.kit.material.library.custom_material_dialog(mdl_path=mdl_path, bind_prim_paths=prim_paths, on_complete_fn=reload_frame)
return
omni.kit.material.library.create_mdl_material(
stage=stage,
mtl_url=mdl_path,
mtl_name=mtl_name,
on_create_fn=on_create_func,
mtl_real_name=mtl_list[0].name if len(mtl_list) > 0 else "")
# get subids from material
asyncio.ensure_future(omni.kit.material.library.get_subidentifier_from_mdl(mdl_file=url, on_complete_fn=lambda l, p=url, n=mtl_name: loaded_mdl_subids(mtl_list=l, mdl_path=p, filename=n, subid=subid), show_alert=True))
def on_material_goto(model, items):
prim_list = sorted(list(set([item[1] for item in items if item[1] != Constant.SDF_PATH_INVALID])))
if prim_list:
omni.usd.get_context().get_selection().set_selected_prim_paths(prim_list, True)
else:
carb.log_warn(f"on_material_goto failed. No materials in list")
self._combo_subscription = []
self._first_row = True
data = binding["material"]
# show mixed material for all selected prims
if len(data) > 1:
self._build_binding_info(
inherited=False,
style_name="material_mixed",
material_list=material_list,
material_path=Constant.MIXED,
strength_value=binding["strength"],
bound_prim_list=list(binding["bound"]),
on_material_fn=partial(on_material_changed, items=list(binding["bound_info"])),
on_strength_fn=partial(on_strength_changed, relationships=list(binding["relationship"])),
on_goto_fn=partial(on_material_goto, items=list(binding["bound_info"] | binding["inherited_info"])),
on_dragdrop_fn=partial(on_dragdrop, items=list(binding["bound_info"])),
)
for material_path in data:
if data[material_path]["bound"]:
self._build_binding_info(
inherited=False,
style_name="material_solo",
material_list=material_list,
material_path=material_path,
strength_value=data[material_path]["strength"],
bound_prim_list=list(data[material_path]["bound"]),
on_material_fn=partial(on_material_changed, items=list(data[material_path]["bound_info"])),
on_strength_fn=partial(
on_strength_changed, relationships=list(data[material_path]["relationship"])
),
on_goto_fn=partial(on_material_goto, items=list(data[material_path]["bound_info"])),
on_dragdrop_fn=partial(on_dragdrop, items=list(data[material_path]["bound_info"])),
)
for material_path in data:
if data[material_path]["inherited"]:
self._build_binding_info(
inherited=True,
style_name="material_solo",
material_list=material_list,
material_path=material_path,
strength_value=data[material_path]["strength"],
bound_prim_list=list(data[material_path]["inherited"]),
on_material_fn=partial(on_material_changed, items=list(data[material_path]["inherited_info"])),
on_strength_fn=partial(
on_strength_changed, relationships=list(data[material_path]["relationship"])
),
on_goto_fn=partial(on_material_goto, items=list(data[material_path]["inherited_info"])),
on_dragdrop_fn=partial(on_dragdrop, items=list(data[material_path]["inherited_info"])),
)
def reset(self):
if self._listener:
self._listener.Revoke()
self._listener = None
if self._pending_frame_rebuild_task:
self._pending_frame_rebuild_task.cancel()
self._pending_frame_rebuild_task = None
def _on_usd_changed(self, notice, stage):
if self._pending_frame_rebuild_task:
return
items = set(notice.GetResyncedPaths()+notice.GetChangedInfoOnlyPaths())
if any(path.elementString == ".material:binding" for path in items):
async def rebuild():
if self._collapsable_frame:
self._collapsable_frame.rebuild()
self._pending_frame_rebuild_task = None
self._pending_frame_rebuild_task = asyncio.ensure_future(rebuild())
| 22,277 | Python | 42.854331 | 230 | 0.558423 |
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/scripts/material_properties.py | import os
import carb
import omni.ext
from pathlib import Path
from pxr import Sdf, UsdShade, UsdUI
from omni.kit.material.library.treeview_model import MaterialListModel, MaterialListDelegate
TEST_DATA_PATH = ""
class MaterialPropertyExtension(omni.ext.IExt):
def __init__(self):
self._registered = False
def on_startup(self, ext_id):
self._extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id)
self._register_widget()
self._hooks = []
manager = omni.kit.app.get_app().get_extension_manager()
extension_path = manager.get_extension_path(ext_id)
global TEST_DATA_PATH
TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests")
def on_shutdown(self):
self._hooks = None
if self._registered:
self._unregister_widget()
def _register_widget(self):
import omni.kit.window.property as p
from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate
from .usd_attribute_widget import UsdMaterialAttributeWidget
from .usd_binding_widget import UsdBindingAttributeWidget
w = p.get_window()
if w:
w.register_widget("prim", "material_binding", UsdBindingAttributeWidget(self._extension_path, add_context_menu=True))
w.register_widget(
"prim",
"material",
UsdMaterialAttributeWidget(
schema=UsdShade.Material,
title="Material and Shader",
include_names=[],
exclude_names=[])
)
w.register_widget(
"prim",
"shader",
UsdMaterialAttributeWidget(
schema=UsdShade.Shader,
title="Shader",
include_names=["info:mdl:sourceAsset", "info:mdl:sourceAsset:subIdentifier"],
exclude_names=[],
),
)
# NOTE: UsdShade.Material is also a UsdShade.NodeGraph. So NodeGraphs ignore Material's
w.register_widget(
"prim",
"nodegraph",
UsdMaterialAttributeWidget(
schema=UsdShade.NodeGraph,
schema_ignore=UsdShade.Material,
title="Node Graph",
include_names=[
"ui:nodegraph:node:displayColor",
"ui:nodegraph:node:expansionState",
"ui:nodegraph:node:icon",
"ui:nodegraph:node:pos",
"ui:nodegraph:node:stackingOrder",
"ui:nodegraph:node:size"],
exclude_names=[],
),
)
w.register_widget(
"prim",
"backdrop",
UsdMaterialAttributeWidget(
schema=UsdUI.Backdrop,
title="Backdrop",
include_names=[
"ui:nodegraph:node:displayColor",
"ui:nodegraph:node:expansionState",
"ui:nodegraph:node:icon",
"ui:nodegraph:node:pos",
"ui:nodegraph:node:stackingOrder",
"ui:nodegraph:node:size"],
exclude_names=[],
),
)
self._registered = True
def _unregister_widget(self):
import omni.kit.window.property as p
w = p.get_window()
if w:
w.unregister_widget("prim", "material")
w.unregister_widget("prim", "shader")
w.unregister_widget("prim", "nodegraph")
w.unregister_widget("prim", "backdrop")
w.unregister_widget("prim", "material_binding")
self._registered = False
| 3,947 | Python | 36.6 | 129 | 0.522169 |
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/tests/test_drag_drop.py | import omni.kit.test
from pathlib import Path
from pxr import Sdf, UsdShade, UsdGeom
from omni.ui.tests.test_base import OmniUiTest
from omni.kit import ui_test
from omni.kit.test_suite.helpers import select_prims, arrange_windows
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
class TestDragDropMDLFile(OmniUiTest):
async def test_drag_drop_single_mdl_file_target(self):
await arrange_windows()
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
mdl_path1 = Path(extension_path).joinpath("data/tests/TESTEXPORT.mdl").absolute()
# setup
await ui_test.find("Stage").focus()
await ui_test.find("Content").focus()
# new stage
usd_context = omni.usd.get_context()
await usd_context.new_stage_async()
stage = usd_context.get_stage()
# create prims
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
await select_prims(["/Sphere"])
await ui_test.human_delay()
# drag/drop
async with ContentBrowserTestHelper() as content_browser_helper:
property_widget = ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'")
await content_browser_helper.drag_and_drop_tree_view(str(mdl_path1), drag_target=property_widget.center)
# verify - TESTEXPORT should be bound
# NOTE: TESTEXPORT.mdl material is named "Material" so that is the prim created
prim = stage.GetPrimAtPath("/Sphere")
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
self.assertTrue(bound_material.GetPrim().IsValid() == True)
self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, "/Looks/Material")
async def test_drag_drop_multi_mdl_file_target(self):
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
mdl_path = str(Path(extension_path).joinpath("data/tests").absolute())
# setup
await ui_test.find("Stage").focus()
await ui_test.find("Content").focus()
# new stage
usd_context = omni.usd.get_context()
await usd_context.new_stage_async()
stage = usd_context.get_stage()
# create prims
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
await select_prims(["/Sphere"])
await ui_test.human_delay()
# drag/drop
async with ContentBrowserTestHelper() as content_browser_helper:
property_widget = ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'")
await content_browser_helper.drag_and_drop_tree_view(
mdl_path, names=["TESTEXPORT.mdl", "TESTEXPORT2.mdl"], drag_target=property_widget.center)
# verify - nothing should be bound as 2 items where selected
prim = stage.GetPrimAtPath("/Sphere")
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
self.assertFalse(bound_material.GetPrim().IsValid())
async def test_drag_drop_single_mdl_file_combo(self):
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
mdl_path1 = Path(extension_path).joinpath("data/tests/TESTEXPORT.mdl").absolute()
# setup
await ui_test.find("Stage").focus()
await ui_test.find("Content").focus()
# new stage
usd_context = omni.usd.get_context()
await usd_context.new_stage_async()
stage = usd_context.get_stage()
# create prims
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
await select_prims(["/Sphere"])
await ui_test.human_delay()
# drag/drop
async with ContentBrowserTestHelper() as content_browser_helper:
property_widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='combo_drop_target'")
await content_browser_helper.drag_and_drop_tree_view(str(mdl_path1), drag_target=property_widget.center)
# verify - TESTEXPORT should be bound
# NOTE: TESTEXPORT.mdl material is named "Material" so that is the prim created
prim = stage.GetPrimAtPath("/Sphere")
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
self.assertTrue(bound_material.GetPrim().IsValid() == True)
self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, "/Looks/Material")
async def test_drag_drop_multi_mdl_file_combo(self):
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
mdl_path = str(Path(extension_path).joinpath("data/tests").absolute())
# setup
await ui_test.find("Stage").focus()
await ui_test.find("Content").focus()
# new stage
usd_context = omni.usd.get_context()
await usd_context.new_stage_async()
stage = usd_context.get_stage()
# create prims
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
await select_prims(["/Sphere"])
await ui_test.human_delay()
# drag/drop
async with ContentBrowserTestHelper() as content_browser_helper:
property_widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='combo_drop_target'")
await content_browser_helper.drag_and_drop_tree_view(
mdl_path, names=["TESTEXPORT.mdl", "TESTEXPORT2.mdl"], drag_target=property_widget.center)
# verify - nothing should be bound as 2 items where selected
prim = stage.GetPrimAtPath("/Sphere")
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
self.assertFalse(bound_material.GetPrim().IsValid())
| 5,948 | Python | 44.412213 | 116 | 0.661903 |
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/tests/test_material_thumb.py | import weakref
import unittest
import pathlib
import omni.kit.test
import omni.ui as ui
import carb
from pathlib import Path
from pxr import Sdf, UsdShade, UsdGeom
from omni.ui.tests.test_base import OmniUiTest
from omni.kit import ui_test
from omni.kit.test_suite.helpers import (
open_stage,
get_test_data_path,
arrange_windows,
select_prims,
wait_stage_loading,
)
class TestMaterialThumb(OmniUiTest):
async def setUp(self):
await super().setUp()
await open_stage(get_test_data_path(__name__, "thumbnail_test.usda"))
await wait_stage_loading()
from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget
import omni.kit.window.property as p
self._w = p.get_window()
async def tearDown(self):
await super().tearDown()
await wait_stage_loading()
async def test_material_thumb(self):
stage = omni.usd.get_context().get_stage()
golden_img_dir = pathlib.Path(get_test_data_path(__name__, "golden_img"))
await self.docked_test_window(
window=self._w._window,
width=450,
height=285,
restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position = ui.DockPosition.BOTTOM)
# select source prim
await select_prims(["/World/Sphere"])
await wait_stage_loading()
await ui_test.human_delay(50)
await self.finalize_test(golden_img_dir=golden_img_dir, golden_img_name="test_thumb_with_alpha.png")
await select_prims([])
| 1,605 | Python | 28.74074 | 108 | 0.654206 |
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/tests/drag_drop_path.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
import omni.usd
import carb
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
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,
arrange_windows
)
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
PERSISTENT_SETTINGS_PREFIX = "/persistent"
class DragDropFilePropertyMaterialPath(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows("Stage", 64)
await open_stage(get_test_data_path(__name__, "bound_material.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "absolute")
async def test_l1_drag_drop_path_drop_target_absolute(self):
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "absolute")
await ui_test.find("Stage").focus()
await ui_test.find("Content").focus()
# new stage
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
# create prims
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
await select_prims(["/World/Sphere"])
await ui_test.human_delay()
# drag file from content window
property_widget = ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'")
drag_target = property_widget.center
async with ContentBrowserTestHelper() as content_browser_helper:
mdl_path = get_test_data_path(__name__, "mtl/badname.mdl")
await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target)
# verify prims
shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/Ue4basedMDL'), False)
self.assertTrue(bool(shader), "/World/Looks/Ue4basedMDL not found")
asset = shader.GetSourceAsset("mdl")
self.assertTrue(os.path.isabs(asset.path))
async def test_l1_drag_drop_path_combo_absolute(self):
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "absolute")
await ui_test.find("Stage").focus()
await ui_test.find("Content").focus()
# new stage
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
# create prims
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
await select_prims(["/World/Sphere"])
await ui_test.human_delay()
# drag file from content window
property_widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='combo_drop_target'")
drag_target = property_widget.center
async with ContentBrowserTestHelper() as content_browser_helper:
mdl_path = get_test_data_path(__name__, "mtl/badname.mdl")
await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target)
# verify prims
shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/Ue4basedMDL'), False)
self.assertTrue(bool(shader), "/World/Looks/Ue4basedMDL not found")
asset = shader.GetSourceAsset("mdl")
self.assertTrue(os.path.isabs(asset.path))
async def test_l1_drag_drop_path_asset_absolute(self):
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "absolute")
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
await select_prims(["/World/Looks/OmniHair/Shader"])
await wait_stage_loading()
# 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:
mdl_path = get_test_data_path(__name__, "mtl/OmniHairTest.mdl")
await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target)
# verify prims
shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/OmniHair'), False)
asset = shader.GetSourceAsset("mdl")
self.assertTrue(os.path.isabs(asset.path))
async def test_l1_drag_drop_path_drop_target_relative(self):
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "relative")
await ui_test.find("Stage").focus()
await ui_test.find("Content").focus()
# new stage
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
# create prims
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
await select_prims(["/World/Sphere"])
await ui_test.human_delay()
# drag file from content window
property_widget = ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'")
drag_target = property_widget.center
async with ContentBrowserTestHelper() as content_browser_helper:
mdl_path = get_test_data_path(__name__, "mtl/badname.mdl")
await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target)
# verify prims
shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/Ue4basedMDL'), False)
self.assertTrue(bool(shader), "/World/Looks/Ue4basedMDL not found")
asset = shader.GetSourceAsset("mdl")
self.assertFalse(os.path.isabs(asset.path))
async def test_l1_drag_drop_path_combo_relative(self):
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "relative")
await ui_test.find("Stage").focus()
await ui_test.find("Content").focus()
# new stage
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
# create prims
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
await select_prims(["/World/Sphere"])
await ui_test.human_delay()
# drag file from content window
property_widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='combo_drop_target'")
drag_target = property_widget.center
async with ContentBrowserTestHelper() as content_browser_helper:
mdl_path = get_test_data_path(__name__, "mtl/badname.mdl")
await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target)
# verify prims
shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/Ue4basedMDL'), False)
self.assertTrue(bool(shader), "/World/Looks/Ue4basedMDL not found")
asset = shader.GetSourceAsset("mdl")
self.assertFalse(os.path.isabs(asset.path))
async def test_l1_drag_drop_path_asset_relative(self):
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "relative")
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
await select_prims(["/World/Looks/OmniHair/Shader"])
await wait_stage_loading()
# 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:
mdl_path = get_test_data_path(__name__, "mtl/OmniHairTest.mdl")
await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target)
# verify prims
shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/OmniHair'), False)
asset = shader.GetSourceAsset("mdl")
self.assertFalse(os.path.isabs(asset.path))
async def test_l1_drag_drop_path_drop_target_multi_absolute(self):
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "absolute")
await ui_test.find("Stage").focus()
await ui_test.find("Content").focus()
# new stage
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
# create prims
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
await select_prims(["/World/Sphere"])
await ui_test.human_delay()
# drag file from content window
property_widget = ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'")
drag_target = property_widget.center
async with ContentBrowserTestHelper() as content_browser_helper:
mdl_path = get_test_data_path(__name__, "mtl/multi_hair.mdl")
await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target)
async with MaterialLibraryTestHelper() as material_test_helper:
await material_test_helper.handle_create_material_dialog(str(mdl_path), "OmniHair_Green")
# verify prims
shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/OmniHair_Green'), False)
self.assertTrue(bool(shader), "/World/Looks/OmniHair_Green not found")
asset = shader.GetSourceAsset("mdl")
self.assertTrue(os.path.isabs(asset.path))
async def test_l1_drag_drop_path_drop_target_multi_relative(self):
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/material/dragDropMaterialPath", "relative")
await ui_test.find("Stage").focus()
await ui_test.find("Content").focus()
# new stage
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
# create prims
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
await select_prims(["/World/Sphere"])
await ui_test.human_delay()
# drag file from content window
property_widget = ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'")
drag_target = property_widget.center
async with ContentBrowserTestHelper() as content_browser_helper:
mdl_path = get_test_data_path(__name__, "mtl/multi_hair.mdl")
await content_browser_helper.drag_and_drop_tree_view(mdl_path, drag_target=drag_target)
async with MaterialLibraryTestHelper() as material_test_helper:
await material_test_helper.handle_create_material_dialog(str(mdl_path), "OmniHair_Green")
# verify prims
shader = omni.usd.get_shader_from_material(stage.GetPrimAtPath('/World/Looks/OmniHair_Green'), False)
self.assertTrue(bool(shader), "/World/Looks/OmniHair_Green not found")
asset = shader.GetSourceAsset("mdl")
self.assertFalse(os.path.isabs(asset.path))
| 11,722 | Python | 43.915709 | 120 | 0.673349 |
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/tests/test_add_mdl_file.py | import omni.kit.test
import omni.kit.app
from pathlib import Path
from pxr import Sdf, UsdShade, UsdGeom
from omni.ui.tests.test_base import OmniUiTest
from omni.kit import ui_test
from omni.kit.test_suite.helpers import arrange_windows, select_prims
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
class TestAddMDLFile(OmniUiTest):
async def test_add_mdl_file(self):
await arrange_windows()
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
mdl_path = Path(extension_path).joinpath("data/tests/TESTEXPORT.mdl").absolute()
# setup
await ui_test.find("Stage").focus()
await ui_test.find("Content").focus()
# new stage
usd_context = omni.usd.get_context()
await usd_context.new_stage_async()
stage = usd_context.get_stage()
# create prims
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
await select_prims(["/Sphere"])
await ui_test.human_delay()
# drag/drop
async with ContentBrowserTestHelper() as content_browser_helper:
property_widget = ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'")
await content_browser_helper.drag_and_drop_tree_view(str(mdl_path), drag_target=property_widget.center)
# verify
# NOTE: TESTEXPORT.mdl material is named "Material" so that is the prim created
shader = UsdShade.Shader(stage.GetPrimAtPath("/Looks/Material/Shader"))
identifier = shader.GetSourceAssetSubIdentifier("mdl")
self.assertTrue(identifier == "Material")
| 1,700 | Python | 38.558139 | 115 | 0.686471 |
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/tests/test_drag_drop_texture_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 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,
build_sdf_asset_frame_dictonary,
arrange_windows
)
from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper
class DragDropTextureProperty(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows("Stage", 64)
await open_stage(get_test_data_path(__name__, "bound_material.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_l1_drag_drop_texture_property(self):
await ui_test.find("Stage").focus()
await ui_test.find("Content").focus()
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
to_select = ["/World/Looks/OmniHair/Shader"]
# wait for material to load & UI to refresh
await wait_stage_loading()
# select prim
await select_prims(to_select)
await ui_test.human_delay()
# open all CollapsableFrames
for frame in ui_test.find_all("Property//Frame/**/CollapsableFrame[*]"):
if frame.widget.title != "Raw USD Properties":
frame.widget.scroll_here_y(0.5)
frame.widget.collapsed = False
await ui_test.human_delay()
# prep content window for drag/drop
texture_path = get_test_data_path(__name__, "textures/granite_a_mask.png")
content_browser_helper = ContentBrowserTestHelper()
# NOTE: cannot keep using widget as they become stale as window refreshes due to set_value
# do tests
widget_table = await build_sdf_asset_frame_dictonary()
for frame_name in widget_table.keys():
for field_name in widget_table[frame_name].keys():
if field_name in ["sdf_asset_info:mdl:sourceAsset"]:
continue
# NOTE: sdf_asset_ could be used more than once, if so skip
if widget_table[frame_name][field_name] == 1:
def get_widget():
return ui_test.find(f"Property//Frame/**/CollapsableFrame[*].title=='{frame_name}'").find(f"**/StringField[*].identifier=='{field_name}'")
# scroll to widget
get_widget().widget.scroll_here_y(0.5)
await ui_test.human_delay()
# reset for test
get_widget().model.set_value("")
# drag/drop
await content_browser_helper.drag_and_drop_tree_view(texture_path, drag_target=get_widget().center)
# verify dragged item(s)
for prim_path in to_select:
prim = stage.GetPrimAtPath(Sdf.Path(prim_path))
self.assertTrue(prim.IsValid())
attr = prim.GetAttribute(field_name[10:])
self.assertTrue(attr.IsValid())
asset_path = attr.Get()
self.assertTrue(asset_path != None)
self.assertTrue(asset_path.resolvedPath.replace("\\", "/").lower() == texture_path.replace("\\", "/").lower())
# reset for next test
get_widget().model.set_value("")
| 3,958 | Python | 39.814433 | 162 | 0.601314 |
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/tests/__init__.py | from .create_prims import *
from .test_material import *
from .test_add_mdl_file import *
from .test_drag_drop import *
from .test_material_thumb_context_menu import *
from .test_material_thumb import *
from .test_drag_drop_texture_property import *
from .drag_drop_path import *
from .test_material_goto import *
from .test_refresh import *
| 342 | Python | 30.181815 | 47 | 0.760234 |
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/tests/test_refresh.py | import math
import weakref
import platform
import unittest
import pathlib
import omni.kit.test
import omni.ui as ui
import carb
from pxr import Usd, Sdf, UsdGeom
from omni.ui.tests.test_base import OmniUiTest
from omni.kit import ui_test
from omni.kit.test_suite.helpers import arrange_windows, open_stage, get_test_data_path, select_prims, wait_stage_loading
class TestMaterialRefreshWidget(OmniUiTest):
async def setUp(self):
await super().setUp()
await arrange_windows()
await open_stage(get_test_data_path(__name__, "thumbnail_test.usda"))
async def tearDown(self):
await super().tearDown()
await select_prims(["/World/Sphere"])
ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Raw USD Properties'").widget.collapsed = True
async def test_material_refresh_ui(self):
stage_widget = ui_test.find("Stage")
await stage_widget.focus()
# Select the prim.
await select_prims(["/World/Sphere"])
# get raw frame & open
raw_frame = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Raw USD Properties'")
raw_frame.widget.collapsed = False
await ui_test.human_delay(10)
# get material:binding label & scroll to it
raw_frame.find("**/Label[*].text=='material:binding'").widget.scroll_here_y(0.5)
await ui_test.human_delay(10)
# get raw relationship widgets
for w in ui_test.find_all("Property//Frame/**/*.identifier!=''"):
if w.widget.identifier == "remove_relationship_World_Looks_Material":
# verify material binding in material widget
self.assertEqual(ui_test.find("Property//Frame/**/StringField[*].identifier=='combo_drop_target'").widget.model.as_string, "/World/Looks/Material")
# remove raw material binding
await w.click()
await ui_test.human_delay(10)
# verify material binding updated in material widget
self.assertEqual(ui_test.find("Property//Frame/**/StringField[*].identifier=='combo_drop_target'").widget.model.as_string, "None")
break
| 2,182 | Python | 37.982142 | 163 | 0.649404 |
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/tests/test_material_thumb_context_menu.py | import weakref
import unittest
import pathlib
import omni.kit.test
import omni.ui as ui
import carb
from pathlib import Path
from pxr import Sdf, UsdShade, UsdGeom
from omni.ui.tests.test_base import OmniUiTest
from omni.kit import ui_test
from omni.kit.test_suite.helpers import (
open_stage,
get_test_data_path,
arrange_windows,
select_prims,
wait_stage_loading,
)
class TestMaterialThumbContextMenu(OmniUiTest):
async def setUp(self):
await super().setUp()
await arrange_windows("Stage", 200)
await open_stage(get_test_data_path(__name__, "material_context.usda"))
await wait_stage_loading()
async def tearDown(self):
await super().tearDown()
await wait_stage_loading()
async def test_material_thumb_context_menu_copy_1_to_1(self):
stage = omni.usd.get_context().get_stage()
# test copy single material from Cone_01 to Sphere_00
bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath("/World/Sphere_00")).ComputeBoundMaterial()
self.assertFalse(bound_material.GetPrim().IsValid())
# select source prim
await select_prims(["/World/Cone_01"])
await wait_stage_loading()
# right click and "copy"
await ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'").click(right_click=True)
await ui_test.select_context_menu("Copy", offset=ui_test.Vec2(10, 10))
# select target prim
await select_prims(["/World/Sphere_00"])
await ui_test.human_delay()
# right click and "paste"
await ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'").click(right_click=True)
await ui_test.select_context_menu("Paste", offset=ui_test.Vec2(10, 10))
# verify binding
bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath("/World/Sphere_00")).ComputeBoundMaterial()
self.assertTrue(bound_material.GetPrim().IsValid() == True)
self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, "/World/Looks/PreviewSurface")
async def test_material_thumb_context_menu_copy_2_to_1(self):
stage = omni.usd.get_context().get_stage()
# test copy single material from Cone_01 to Sphere_00
bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath("/World/Sphere_00")).ComputeBoundMaterial()
self.assertFalse(bound_material.GetPrim().IsValid())
# select source prim
await select_prims(["/World/Cone_01", "/World/Cone_02"])
await wait_stage_loading()
# right click and "copy"
await ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'").click(right_click=True)
await ui_test.select_context_menu("Copy", offset=ui_test.Vec2(10, 10))
# select target prim
await select_prims(["/World/Sphere_00"])
await ui_test.human_delay()
# right click and "paste"
await ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'").click(right_click=True)
await ui_test.select_context_menu("Paste (2 Materials)", offset=ui_test.Vec2(10, 10))
# verify binding
bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath("/World/Sphere_00")).ComputeBoundMaterial()
self.assertTrue(bound_material.GetPrim().IsValid() == True)
self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, "/World/Looks/PreviewSurface")
async def test_material_thumb_context_menu_copy_4_to_2(self):
stage = omni.usd.get_context().get_stage()
# test copy single material from Cone_01 to Sphere_00
bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath("/World/Sphere_00")).ComputeBoundMaterial()
self.assertFalse(bound_material.GetPrim().IsValid())
bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath("/World/Sphere_01")).ComputeBoundMaterial()
self.assertFalse(bound_material.GetPrim().IsValid())
# select source prim
await select_prims(["/World/Cone_01", "/World/Cone_02"])
await wait_stage_loading()
# right click and "copy"
await ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'").click(right_click=True)
await ui_test.select_context_menu("Copy", offset=ui_test.Vec2(10, 10))
# select target prim
await select_prims(["/World/Sphere_00", "/World/Sphere_01"])
await wait_stage_loading()
# right click and "paste"
await ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'").click(right_click=True)
await ui_test.select_context_menu("Paste (2 Materials)", offset=ui_test.Vec2(10, 10))
# verify binding
bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath("/World/Sphere_00")).ComputeBoundMaterial()
self.assertTrue(bound_material.GetPrim().IsValid() == True)
self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, "/World/Looks/PreviewSurface")
bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath("/World/Sphere_01")).ComputeBoundMaterial()
self.assertTrue(bound_material.GetPrim().IsValid() == True)
self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, "/World/Looks/PreviewSurface")
async def test_material_thumb_context_menu_copy_4211_to_2(self):
stage = omni.usd.get_context().get_stage()
def get_bindings(prim_paths):
bindings = []
for prim_path in prim_paths:
prim = stage.GetPrimAtPath(prim_path)
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
bindings.append(bound_material.GetPath().pathString if bound_material else "None")
# fixme - due to get_binding_from_prims using sets which are not ordered
return sorted(bindings)
for index, data in enumerate([("Paste (4 Materials)", ['/World/Looks/OmniGlass_Opacity', '/World/Looks/OmniPBR_ClearCoat', '/World/Looks/PreviewSurface', '/World/Looks/PreviewSurface']),
("Paste (2 Materials)", ['/World/Looks/PreviewSurface', '/World/Looks/PreviewSurface', 'None', 'None']),
("Paste", ['/World/Looks/OmniPBR_ClearCoat', 'None', 'None', 'None']),
("Paste", ['/World/Looks/OmniGlass_Opacity', 'None', 'None', 'None'])]):
# select source prims
await select_prims(["/World/Cone_01", "/World/Cone_02", "/World/Cube_01", "/World/Cube_02"])
await wait_stage_loading()
# verify copy material
materials = get_bindings(["/World/Sphere_00", "/World/Sphere_01", "/World/Sphere_03", "/World/Sphere_04"])
self.assertEqual(materials, ['None', 'None', 'None', 'None'])
# right click and "copy"
widgets = ui_test.find_all("Property//Frame/**/Button[*].identifier=='preview_drop_target'")
await widgets[index].click(right_click=True)
await ui_test.select_context_menu("Copy", offset=ui_test.Vec2(10, 10))
# select target prim
await select_prims(["/World/Sphere_00", "/World/Sphere_01", "/World/Sphere_03", "/World/Sphere_04"])
await wait_stage_loading()
# right click and "paste"
await ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'").click(right_click=True)
await ui_test.select_context_menu(data[0], offset=ui_test.Vec2(10, 10))
materials = get_bindings(["/World/Sphere_00", "/World/Sphere_01", "/World/Sphere_03", "/World/Sphere_04"])
self.assertEqual(materials, data[1])
omni.kit.undo.undo()
async def test_material_thumb_context_menu_copy_1_to_many(self):
stage = omni.usd.get_context().get_stage()
# test copy single material from Cone_01 to Sphere_*
for index in range(0, 64):
bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath(f"/World/Sphere_{index:02d}")).ComputeBoundMaterial()
self.assertFalse(bound_material.GetPrim().IsValid())
# select source prim
await select_prims(["/World/Cone_01"])
await wait_stage_loading()
# right click and "copy"
await ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'").click(right_click=True)
await ui_test.select_context_menu("Copy", offset=ui_test.Vec2(10, 10))
# select target prims
to_select = []
for index in range(0, 64):
to_select.append(f"/World/Sphere_{index:02d}")
await select_prims(to_select)
# right click in frame to "paste"
widget = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Materials on selected models'")
await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True)
await ui_test.select_context_menu("Paste To All", offset=ui_test.Vec2(10, 10))
# verify binding
for index in range(0, 64):
bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath(f"/World/Sphere_{index:02d}")).ComputeBoundMaterial()
self.assertTrue(bound_material.GetPrim().IsValid() == True)
self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, "/World/Looks/PreviewSurface")
async def test_material_thumb_context_menu_copy_2_to_many(self):
stage = omni.usd.get_context().get_stage()
# test copy 2 materials from Cone_01, Cone_02 to Sphere_*
for index in range(0, 64):
bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath(f"/World/Sphere_{index:02d}")).ComputeBoundMaterial()
self.assertFalse(bound_material.GetPrim().IsValid())
# select source prim
await select_prims(["/World/Cone_01", "/World/Cone_02"])
await wait_stage_loading()
# right click and "copy"
await ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'").click(right_click=True)
await ui_test.select_context_menu("Copy", offset=ui_test.Vec2(10, 10))
# select target prims
to_select = []
for index in range(0, 64):
to_select.append(f"/World/Sphere_{index:02d}")
await select_prims(to_select)
# right click in frame to "paste"
widget = ui_test.find("Property//Frame/**/CollapsableFrame[*].title=='Materials on selected models'")
await widget.click(pos=widget.position+ui_test.Vec2(widget.widget.computed_content_width/2, 10), right_click=True)
await ui_test.select_context_menu("Paste To All", offset=ui_test.Vec2(10, 10))
# verify binding
for index in range(0, 64):
bound_material, _ = UsdShade.MaterialBindingAPI(stage.GetPrimAtPath(f"/World/Sphere_{index:02d}")).ComputeBoundMaterial()
self.assertTrue(bound_material.GetPrim().IsValid() == True)
self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, "/World/Looks/PreviewSurface")
| 11,353 | Python | 47.110169 | 194 | 0.642826 |
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/tests/test_material.py | import weakref
import platform
import unittest
import pathlib
import omni.kit.test
import omni.ui as ui
import carb
from pxr import Usd, Sdf, UsdGeom
from omni.ui.tests.test_base import OmniUiTest
from omni.kit import ui_test
from omni.kit.test_suite.helpers import arrange_windows, wait_stage_loading
class TestMaterialWidget(OmniUiTest):
async def setUp(self):
await super().setUp()
await arrange_windows()
from omni.kit.property.material.scripts.material_properties import TEST_DATA_PATH
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute()
self._usd_path = TEST_DATA_PATH.absolute()
self._icon_path = TEST_DATA_PATH.resolve().parent.joinpath("icons")
from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget
import omni.kit.window.property as p
self._w = p.get_window()
async def tearDown(self):
await super().tearDown()
async def test_material_ui(self):
usd_context = omni.usd.get_context()
await usd_context.new_stage_async()
material_prims, bound_prims = omni.kit.property.material.tests.create_test_stage()
await self.docked_test_window(
window=self._w._window,
width=450,
height=285,
restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position = ui.DockPosition.BOTTOM)
# Select the prim.
usd_context.get_selection().set_selected_prim_paths(["/LightPivot_01/AreaLight/Backside"], True)
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(10)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_material_ui.png")
usd_context.get_selection().set_selected_prim_paths([], True)
async def __test_material_multiselect_ui(self):
usd_context = omni.usd.get_context()
await self.docked_test_window(
window=self._w._window,
width=450,
height=520,
restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position = ui.DockPosition.BOTTOM)
# Select the prim.
usd_context.get_selection().set_selected_prim_paths(["/LightPivot_01/AreaLight/Backside", "/LightPivot_01/AreaLight/EmissiveSurface"], True)
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(10)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_material_multiselect_ui.png")
usd_context.get_selection().set_selected_prim_paths([], True)
async def test_material_popup_full_ui(self):
from omni.kit.window.property.templates import SimplePropertyWidget, LABEL_WIDTH, LABEL_HEIGHT
from omni.kit.material.library.listbox_widget import MaterialListBoxWidget
usd_context = omni.usd.get_context()
test_file_path = self._usd_path.joinpath("material_binding.usda").absolute()
await usd_context.open_stage_async(str(test_file_path))
await omni.kit.app.get_app().next_update_async()
# full window
window = await self.create_test_window(width=460, height=380)
with window.frame:
with ui.VStack(width=0, height=0):
with ui.HStack(width=0, height=0):
name_field = ui.StringField(width=400, height=20, enabled=False)
name_field.model.set_value("TEST"*4)
await ui_test.human_delay(10)
listbox_widget = MaterialListBoxWidget(icon_path=None, index=0, on_click_fn=None, theme={})
listbox_widget.set_parent(name_field)
listbox_widget.build_ui()
# material loading is async so alow for loadng
await ui_test.human_delay(50)
await ui_test.human_delay(10)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_material_popup1_ui.png")
async def test_material_popup_search_ui(self):
from omni.kit.window.property.templates import SimplePropertyWidget, LABEL_WIDTH, LABEL_HEIGHT
from omni.kit.material.library.listbox_widget import MaterialListBoxWidget
usd_context = omni.usd.get_context()
test_file_path = self._usd_path.joinpath("material_binding.usda").absolute()
await usd_context.open_stage_async(str(test_file_path))
await omni.kit.app.get_app().next_update_async()
# search
window = await self.create_test_window(width=460, height=380)
with window.frame:
with ui.VStack(width=0, height=0):
with ui.HStack(width=0, height=0):
name_field = ui.StringField(width=400, height=20, enabled=False)
name_field.model.set_value("SEARCH"*4)
await ui_test.human_delay(10)
listbox_widget = MaterialListBoxWidget(icon_path=None, index=0, on_click_fn=None, theme={})
listbox_widget.set_parent(name_field)
listbox_widget.build_ui()
await ui_test.human_delay(10)
listbox_widget._search_updated("PBR")
# material loading is async so alow for loadng
await wait_stage_loading()
await ui_test.human_delay(10)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_material_popup2_ui.png")
async def test_material_description_ui(self):
from omni.kit import ui_test
usd_context = omni.usd.get_context()
test_file_path = self._usd_path.joinpath("material_binding.usda").absolute()
await usd_context.open_stage_async(str(test_file_path))
await self.docked_test_window(
window=self._w._window,
width=450,
height=285,
restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position = ui.DockPosition.BOTTOM)
# Select the prim.
usd_context.get_selection().set_selected_prim_paths(["/World/Looks/OmniPBR"], True)
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay()
for w in ui_test.find_all("Property//Frame/**/CollapsableFrame[*]"):
if w.widget.title != "Raw USD Properties":
w.widget.collapsed = False
await ui_test.human_delay()
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_material_description_ui.png")
usd_context.get_selection().set_selected_prim_paths([], True)
| 6,806 | Python | 40.006024 | 148 | 0.644431 |
omniverse-code/kit/exts/omni.kit.property.material/omni/kit/property/material/tests/test_material_goto.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
import omni.usd
import carb
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
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,
arrange_windows
)
class PropertyMaterialGotoMDL(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows("Stage", 256)
await open_stage(get_test_data_path(__name__, "material_binding_inherited.usda"))
# After running each test
async def tearDown(self):
await wait_stage_loading()
async def test_l1_mesh_goto_material_button(self):
pass
await ui_test.find("Stage").focus()
# setup
stage = omni.usd.get_context().get_stage()
# goto single prims
for prim_list, expected in [("/World/Xform/Cone", ['/World/Looks/OmniSurface']),
("/World/Xform/Cone_01", ['/World/Looks/OmniPBR']),
("/World/Xform_Inherited/Cone_02", ['/World/Looks/OmniSurface_Blood']),
("/World/Xform_Inherited/Cone_03", ['/World/Looks/OmniSurface_Blood']),
("/World/Xform_Unbound/Sphere", ['/World/Xform_Unbound/Sphere'])]:
await select_prims([prim_list])
thumb_widget = ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'")
await thumb_widget.click()
await ui_test.human_delay(50)
# verify
self.assertEqual(omni.usd.get_context().get_selection().get_selected_prim_paths(), expected)
# goto multiple prims
for index, expected in enumerate([['/World/Looks/OmniPBR', '/World/Looks/OmniSurface'], ['/World/Looks/OmniSurface'], ['/World/Looks/OmniPBR']]):
await select_prims(["/World/Xform/Cone", "/World/Xform/Cone_01"])
thumb_widget = ui_test.find_all("Property//Frame/**/Button[*].identifier=='preview_drop_target'")
await thumb_widget[index].click()
await ui_test.human_delay(50)
# verify
self.assertEqual(omni.usd.get_context().get_selection().get_selected_prim_paths(), expected)
# goto multiple selected inherited prims
await select_prims(["/World/Xform_Inherited/Cone_02", "/World/Xform_Inherited/Cone_03"])
thumb_widget = ui_test.find("Property//Frame/**/Button[*].identifier=='preview_drop_target'")
await thumb_widget.click()
await ui_test.human_delay(50)
# verify
self.assertEqual(omni.usd.get_context().get_selection().get_selected_prim_paths(), ['/World/Looks/OmniSurface_Blood'])
| 3,262 | Python | 41.376623 | 153 | 0.642244 |
omniverse-code/kit/exts/omni.kit.widget.fast_search/omni/kit/widget/fast_search/python/delegate.py | """
* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA CORPORATION and its licensors retain all intellectual property
* and proprietary rights in and to this software, related documentation
* and any modifications thereto. Any use, reproduction, disclosure or
* distribution of this software and related documentation without an express
* license agreement from NVIDIA CORPORATION is strictly prohibited.
"""
import omni.ui as ui
import os
ICONS_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "icons")
DICT_ICONS = {
"forbidden": os.path.join(ICONS_DIR, "forbidden.svg"),
"forbidden_black": os.path.join(ICONS_DIR, "forbidden_black.svg"),
"star": os.path.join(ICONS_DIR, "star.svg"),
"star_black": os.path.join(ICONS_DIR, "star_black.svg"),
"plus": os.path.join(ICONS_DIR, "{style}", "Plus.svg"),
"minus": os.path.join(ICONS_DIR, "{style}", "Minus.svg"),
}
class FastSearchDelegate(ui.AbstractItemDelegate):
"""Delegate of the Mapper Batcher"""
def __init__(self):
super(FastSearchDelegate, self).__init__()
self._highlighting_enabled = None
# Text that is highlighted in flat mode
self._highlighting_text = None
self.show_column_visibility = True
self._style = None
self.init_editor_style()
def init_editor_style(self):
import carb.settings
self._style = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
if column_id == 0:
with ui.HStack(width=16 * (level + 2), height=0):
ui.Spacer()
if model.can_item_have_children(item):
# Draw the +/- icon
image_name = "minus" if expanded else "plus"
ui.Image(
DICT_ICONS[image_name].format(style=self._style),
width=10,
height=10,
style_type_name_override="TreeView.Item",
)
ui.Spacer(width=4)
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per item"""
# Disable the item if it's an Instance Proxy because Kit can't interact with such object and crashes.
enabled = True
if column_id == 0:
name = item.name.get_value_as_string()
star_path = self.get_fav_icon(item)
forbidden_path = self.get_block_icon(item)
with ui.HStack(height=20):
label = ui.Label(name)
label.set_mouse_released_fn(lambda x, y, b, m, i=item: self._on_item_clicked(i, b))
ui.Spacer()
fav_icon = ui.Image(star_path, width=15, height=15)
fav_icon.set_mouse_released_fn(lambda x, y, b, m, i=item, f=fav_icon: self._on_fav_clicked(i, f, b))
ui.Spacer(width=10)
blocklist_icon = ui.Image(forbidden_path, width=15, height=15)
blocklist_icon.set_mouse_released_fn(lambda x, y, b, m, i=item, f=blocklist_icon: self._on_block_clicked(i, f, b))
ui.Spacer(width=10)
@staticmethod
def get_fav_icon(item):
"""Get favorite icon path"""
return DICT_ICONS["star_black"] if not item.favorite else DICT_ICONS["star"]
@staticmethod
def get_block_icon(item):
"""Get blocked icon path"""
return DICT_ICONS["forbidden_black"] if not item.blocklist else DICT_ICONS["forbidden"]
def _on_item_clicked(self, item, button):
if button != 0:
return
item.item_mouse_released()
def _on_fav_clicked(self, item, image_widget, button):
"""Called when favorite icon is clicked"""
if button != 0:
return
item.favorite = not item.favorite
image_widget.source_url = self.get_fav_icon(item)
def _on_block_clicked(self, item, image_widget, button):
"""Called when blocked icon is clicked"""
if button != 0:
return
item.blocklist = not item.blocklist
image_widget.source_url = self.get_block_icon(item)
def build_header(self, column_id):
"""Build the header"""
style_type_name = "TreeView.Header"
with ui.HStack():
ui.Label("Node name", style_type_name_override=style_type_name)
| 4,521 | Python | 39.017699 | 130 | 0.597655 |
omniverse-code/kit/exts/omni.kit.widget.fast_search/omni/kit/widget/fast_search/python/model.py | """
* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA CORPORATION and its licensors retain all intellectual property
* and proprietary rights in and to this software, related documentation
* and any modifications thereto. Any use, reproduction, disclosure or
* distribution of this software and related documentation without an express
* license agreement from NVIDIA CORPORATION is strictly prohibited.
"""
import omni.ui as ui
class SimpleItem(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, model, name, fav=False, block=False):
super(SimpleItem, self).__init__()
self._model = model
self.name = name
self._favorite = fav
self._blocklist = block
def item_mouse_released(self):
self._model.item_mouse_released(self)
@property
def favorite(self):
return self._favorite
@favorite.setter
def favorite(self, value: bool):
"""Add favorite"""
if value:
self._model.prepend_item("favorites", self, refresh=False)
else:
if self in self._model.favorites:
self._model.favorites.remove(self)
self._favorite = value
@property
def blocklist(self):
return self._blocklist
@blocklist.setter
def blocklist(self, value: bool):
"""Add blocklist"""
if value:
self._model.prepend_item("blocklist", self, refresh=False)
if self in self._model.favorites:
self._model.favorites.remove(self)
if self in self._model.previous_items:
self._model.previous_items.remove(self)
else:
if self in self._model.blocklist:
self._model.blocklist.remove(self)
if self.favorite and self not in self._model.favorites:
self._model.prepend_item("favorites", self, refresh=False)
if self not in self._model.previous_items:
self._model.prepend_item("previous_items", self, refresh=False)
self._blocklist = value
class SimpleModel(ui.AbstractItemModel):
"""Simple list model that can be used in a lot of different way"""
class _Event(set):
"""
A list of callable objects. Calling an instance of this will cause a
call to each item in the list in ascending order by index.
"""
def __call__(self, *args, **kwargs):
"""Called when the instance is “called” as a function"""
# Call all the saved functions
for f in self:
f(*args, **kwargs)
def __repr__(self):
"""
Called by the repr() built-in function to compute the “official”
string representation of an object.
"""
return f"Event({set.__repr__(self)})"
class _EventSubscription:
"""
Event subscription.
_Event has callback while this object exists.
"""
def __init__(self, event, fn):
"""
Save the function, the event, and add the function to the event.
"""
self._fn = fn
self._event = event
event.add(self._fn)
def __del__(self):
"""Called by GC."""
self._event.remove(self._fn)
def __init__(self, column_count: int):
super(SimpleModel, self).__init__()
self.items = []
self.latest = []
self.favorites = []
self.blocklist = []
self.previous_items = []
self._column_count = column_count
self.__on_item_mouse_released = self._Event()
def item_mouse_released(self, item):
"""Call the event object that has the list of functions"""
self.__on_item_mouse_released(item)
def subscribe_item_mouse_released(self, fn):
"""
Return the object that will automatically unsubscribe when destroyed.
"""
return self._EventSubscription(self.__on_item_mouse_released, fn)
def get_item_children(self, item: SimpleItem) -> list:
"""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.items
def set_items(self, mode_attr: str, items: list, refresh: bool = True):
"""Set items on the list"""
setattr(self, mode_attr, items)
if refresh:
self.refresh()
def append_item(self, mode_attr: str, item, refresh: bool = True):
"""Append items on the list"""
current_items = getattr(self, mode_attr)
indexes = []
for i, current_item in enumerate(current_items):
if item.name.get_value_as_string() == current_item.name.get_value_as_string():
indexes.append(i)
indexes.reverse()
for index in indexes:
current_items.pop(index)
current_items.append(item)
self.set_items(mode_attr, current_items, refresh=refresh)
def prepend_item(self, mode_attr: str, item, refresh: bool = True):
"""Prepend items on the list"""
current_items = getattr(self, mode_attr)
indexes = []
for i, current_item in enumerate(current_items):
if item.name.get_value_as_string() == current_item.name.get_value_as_string():
indexes.append(i)
indexes.reverse()
for index in indexes:
current_items.pop(index)
current_items.insert(0, item)
self.set_items(mode_attr, current_items, refresh=refresh)
def refresh(self):
"""Reset the model"""
self._item_changed(None)
def get_item_value_model_count(self, item) -> int:
"""The number of columns"""
return self._column_count
def get_item_value_model(self, item: SimpleItem, column_id: int):
"""
Return value model.
It's the object that tracks the specific value.
In our case we use ui.SimpleStringModel.
"""
return item.name
| 6,141 | Python | 33.122222 | 90 | 0.586875 |
omniverse-code/kit/exts/omni.kit.widget.fast_search/omni/kit/widget/fast_search/python/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 carb
import omni.ui as ui
from . import delegate, model
class FastSearchWidget(object):
def __init__(self, items_dict):
self._items_dict = items_dict
self._is_visible = False
self._current_selection = []
self._menus_global_selection = []
self._tab_first_item_set = False
self._current_global_selection_index = 0
self._style = {"Menu.ItemSelected": {"color": 0xFFC8C8C8}, "Menu.ItemUnseleted": {"color": 0xFF646464}}
self._default_attr = {
"_model": None,
"_delegate": None,
"_window": None,
"_search_field": None,
"_tree_view": None,
"_menu_all": None,
"_menu_latest": None,
"_menu_favorites": None,
"_menu_blocklist": None,
"_subscription_item_mouse_released": None,
}
for attr, value in self._default_attr.items():
setattr(self, attr, value)
def create_widget(self):
"""Create the widget UI"""
self._model = model.SimpleModel(column_count=1)
self._delegate = delegate.FastSearchDelegate()
self._window = ui.Window(
"Graph search",
width=400,
height=400,
flags=ui.WINDOW_FLAGS_POPUP | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_MENU_BAR,
)
menu_bar = self._window.menu_bar
menu_bar.set_style(self._style)
with menu_bar:
self._menu_all = ui.MenuItem(
"All", triggered_fn=self.show_all, style_type_name_override="Menu.ItemSelected"
)
self._menu_latest = ui.MenuItem(
"Latest", triggered_fn=self.show_only_latest, style_type_name_override="Menu.ItemUnseleted"
)
self._menu_favorites = ui.MenuItem(
"Favorites", triggered_fn=self.show_only_favorites, style_type_name_override="Menu.ItemUnseleted"
)
self._menu_blocklist = ui.MenuItem(
"Blocklist", triggered_fn=self.show_only_blocklist, style_type_name_override="Menu.ItemUnseleted"
)
self._menus_global_selection.extend(
[self._menu_all, self._menu_latest, self._menu_favorites, self._menu_blocklist]
)
self._window.frame.set_key_pressed_fn(self.__on_key_pressed)
with self._window.frame:
with ui.VStack():
with ui.Frame(height=20):
with ui.VStack():
self._search_field = ui.StringField()
self._search_field.model.add_value_changed_fn(self._filter)
ui.Spacer(height=5)
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
):
self._tree_view = ui.TreeView(
self._model,
delegate=self._delegate,
root_visible=False,
header_visible=False,
style={"TreeView.Item": {"margin": 4}},
)
self._tree_view.set_selection_changed_fn(self._on_widget_attr_selection_changed)
self._model.set_items(
"items", [model.SimpleItem(self._model, ui.SimpleStringModel(attr)) for attr in self._items_dict.keys()]
)
self._model.previous_items = self._model.items
self._subscription_item_mouse_released = self._model.subscribe_item_mouse_released(
self.item_mouse_released
)
self._select_first_item()
def show_all(self):
print("show all")
def show_only_latest(self):
print("show latest")
def show_only_favorites(self):
print("show favorites")
def show_only_blocklist(self):
print("show blocklist")
def _select_first_item(self):
"""Select first item of the list"""
if self._model.items:
self._tree_view.selection = [self._model.items[0]]
def _select_down_item(self):
"""Select the item down"""
if self._tree_view.selection:
current_index = self._model.items.index(self._tree_view.selection[-1])
index = current_index + 1
if index >= len(self._model.items) - 1:
index = len(self._model.items) - 1
self._tree_view.selection = [self._model.items[index]]
def _select_up_item(self):
"""Select the item up"""
if self._tree_view.selection:
current_index = self._model.items.index(self._tree_view.selection[-1])
index = current_index - 1
if index <= 0:
index = 0
self._tree_view.selection = [self._model.items[index]]
def _filter(self, str_model):
"""Filter from the windows"""
# set the global mode (all, latest...)
if self._current_global_selection_index == 0:
self._model.items = self._model.previous_items
self._model.refresh()
elif self._current_global_selection_index == 1:
self._model.items = self._model.latest
self._model.refresh()
elif self._current_global_selection_index == 2:
self._model.items = self._model.favorites
self._model.refresh()
elif self._current_global_selection_index == 3:
self._model.items = self._model.blocklist
self._model.refresh()
value = str_model.get_value_as_string()
if not value.strip():
self._select_first_item()
return
items = []
for item in self._model.items:
current_attr = item.name.get_value_as_string()
if value.lower() not in current_attr.lower():
continue
items.append(item)
if not items:
self._model.items = []
self._model.refresh()
return
self._model.items = items
self._model.refresh()
self._select_first_item()
def _on_widget_attr_selection_changed(self, selection):
"""Fill self.current_attrs_selection when the selection change
into the attribute chooser"""
self._current_selection = selection
def set_window_visible(self, visible):
"""Set the widget visible"""
self._window.visible = visible
if visible:
self._search_field.model.set_value("")
self._search_field.focus_keyboard()
self._select_first_item()
def item_mouse_released(self, item):
self.execute_item(item)
def __key_enter_pressed(self):
"""Called when key enter is pressed.
Add the item in the latest list"""
if self.is_visible:
if self._current_selection:
self.execute_item(self._current_selection[0])
def execute_item(self, item):
selection_str = item.name.get_value_as_string()
self._items_dict[selection_str]()
current_latest = [x.name.get_value_as_string() for x in self._model.latest]
if not current_latest or current_latest[-1] != selection_str:
if selection_str in current_latest:
current_latest.remove(selection_str)
current_latest.insert(0, selection_str)
self._model.set_items(
"latest", [model.SimpleItem(self._model, ui.SimpleStringModel(attr)) for attr in current_latest]
)
self.set_window_visible(False)
def __key_escape_pressed(self):
if self.is_visible:
self.set_window_visible(False)
self._tab_first_item_set = False
def __key_tab_pressed(self):
"""Roll modes"""
if self.is_visible and self._model.items and not self._tab_first_item_set:
selection_str = self._current_selection[0].name.get_value_as_string()
self._search_field.model.set_value(selection_str)
self._tab_first_item_set = True
elif self.is_visible and self._model.items and self._tab_first_item_set:
self.__key_enter_pressed()
self._tab_first_item_set = False
def __key_ctrl_tab_pressed(self):
"""Roll modes"""
if self.is_visible:
if self._current_global_selection_index == len(self._menus_global_selection) - 1:
self._current_global_selection_index = 0
else:
self._current_global_selection_index += 1
for i, menu in enumerate(self._menus_global_selection):
if i == self._current_global_selection_index:
menu.style_type_name_override = "Menu.ItemSelected"
else:
menu.style_type_name_override = "Menu.ItemUnseleted"
self._filter(self._search_field.model)
def __key_select_down_pressed(self):
if self.is_visible:
self._select_down_item()
def __key_select_up_pressed(self):
if self.is_visible:
self._select_up_item()
def __on_key_pressed(self, key_index, key_flags, key_down):
key_mod = key_flags & ~ui.Widget.FLAG_WANT_CAPTURE_KEYBOARD
if key_index == int(carb.input.KeyboardInput.ESCAPE) and key_mod == 0 and key_down:
self.__key_escape_pressed()
if key_index == int(carb.input.KeyboardInput.DOWN) and key_mod == 0 and key_down:
self.__key_select_down_pressed()
if key_index == int(carb.input.KeyboardInput.UP) and key_mod == 0 and key_down:
self.__key_select_up_pressed()
if key_index == int(carb.input.KeyboardInput.ENTER) and key_mod == 0 and key_down:
self.__key_enter_pressed()
if key_index == int(carb.input.KeyboardInput.TAB) and key_mod == 0 and key_down:
self.__key_tab_pressed()
if key_index == int(carb.input.KeyboardInput.TAB) and key_mod == 2 and key_down:
self.__key_ctrl_tab_pressed()
if key_index == int(carb.input.KeyboardInput.BACKSPACE) and key_mod == 0 and key_down:
self._tab_first_item_set = False
@property
def is_visible(self):
return self._window.visible
def destroy(self):
"""Delete the UI"""
for attr, value in self._default_attr.items():
m_attr = getattr(self, attr)
del m_attr
setattr(self, attr, value)
| 10,983 | Python | 39.832714 | 116 | 0.575344 |
omniverse-code/kit/exts/omni.kit.ui_test/omni/kit/ui_test/common.py | import omni.ext
import asyncio
import omni.kit.app
import carb
import sys
import logging
logger = logging.getLogger(__name__)
def setup_logging():
printInfoLog = carb.settings.get_settings().get("/exts/omni.kit.ui_test/printInfoLog")
if not printInfoLog:
return
# Always log info to stdout to debug tests. Since we tend to reload modules avoid adding more than once.
logger = logging.getLogger("omni.kit.ui_test")
if len(logger.handlers) == 0:
stdout_hdlr = logging.StreamHandler(sys.stdout)
stdout_hdlr.setLevel(logging.INFO)
stdout_hdlr.setFormatter(logging.Formatter("[%(name)s] [%(levelname)s] %(message)s", "%H:%M:%S"))
logger.addHandler(stdout_hdlr)
class InitExt(omni.ext.IExt):
def on_startup(self):
setup_logging()
async def wait_n_updates_internal(update_count=2):
for _ in range(update_count):
await omni.kit.app.get_app().next_update_async()
async def wait_n_updates(update_count=2):
"""Wait N updates (frames)."""
logger.debug(f"wait {update_count} updates")
await wait_n_updates_internal(update_count)
async def human_delay(human_delay_speed: int = 2):
"""Imitate human delay/slowness.
In practice that function just waits couple of frames, but semantically it is different from other wait function.
It is used when we want to wait because it would look like normal person interaction. E.g. instead of moving mouse
and clicking with speed of light wait a bit.
This is also a place where delay can be increased with a setting to debug UI tests.
"""
logger.debug("human delay")
await wait_n_updates_internal(human_delay_speed)
# Optional extra delay
human_delay = carb.settings.get_settings().get("/exts/omni.kit.ui_test/humanDelay")
if human_delay:
await asyncio.sleep(human_delay)
| 1,858 | Python | 31.614035 | 118 | 0.698062 |
omniverse-code/kit/exts/omni.kit.ui_test/omni/kit/ui_test/vec2.py | from __future__ import annotations
class Vec2:
"""Generic 2D Vector
Constructed from other `Vec2`, tuple of 2 floats or just 2 floats. Common vector operation supported:
.. code-block:: python
v0 = Vec2(1, 2)
v1 = Vec2((1, 2))
v2 = Vec2(v1)
print(v0 + v1) # (2, 4)
print(v2 * 3) # (3, 6)
print(v2 / 4) # (0.25, 0.5)
"""
def __init__(self, *args):
if len(args) == 0:
self.x, self.y = 0, 0
elif len(args) == 1:
v = args[0]
if isinstance(v, Vec2):
self.x, self.y = v.x, v.y
else:
self.x, self.y = v[0], v[1]
else:
self.x, self.y = args[0], args[1]
def __str__(self) -> str:
return f"({self.x}, {self.y})"
def __repr__(self) -> str:
return f"Vec2 ({self.x}, {self.y})"
def __sub__(self, other) -> Vec2:
return Vec2(self.x - other.x, self.y - other.y)
def __add__(self, other) -> Vec2:
return Vec2(self.x + other.x, self.y + other.y)
def __mul__(self, scalar) -> Vec2:
return Vec2(self.x * scalar, self.y * scalar)
def __rmul__(self, scalar) -> Vec2:
return self.__mul__(scalar)
def __neg__(self) -> Vec2:
return Vec2(-self.x, -self.y)
def __truediv__(self, scalar) -> Vec2:
return Vec2(self.x / scalar, self.y / scalar)
def __mod__(self, scalar) -> Vec2:
return Vec2(self.x % scalar, self.y % scalar)
def to_tuple(self):
return (self.x, self.y)
def __eq__(self, other):
if other == None:
return False
return self.x == other.x and self.y == other.y
def __ne__(self, other):
if other == None:
return True
return not (self.x == other.x and self.y == other.y)
def __lt__(self, other):
return self.x < other.x and self.y < other.y
def __le__(self, other):
return self.x <= other.x and self.y <= other.y
def __gt__(self, other):
return self.x > other.x and self.y > other.y
def __ge__(self, other):
return self.x >= other.x and self.y >= other.y
| 2,175 | Python | 25.216867 | 105 | 0.496552 |
omniverse-code/kit/exts/omni.kit.ui_test/omni/kit/ui_test/query.py | from __future__ import annotations
import logging
from typing import List
import carb
from omni import ui
from omni.ui_query import OmniUIQuery
from carb.input import KeyboardInput
from .input import emulate_mouse_move_and_click, emulate_char_press, emulate_keyboard_press, emulate_keyboard, emulate_mouse_drag_and_drop
from .common import wait_n_updates_internal
from .vec2 import Vec2
logger = logging.getLogger(__name__)
class WindowStub():
"""stub window class for use with WidgetRef & """
def undock(_):
pass
def focus(_):
pass
window_stub = WindowStub()
class WidgetRef:
"""Reference to `omni.ui.Widget` and a path it was found with."""
def __init__(self, widget: ui.Widget, path: str, window: ui.Window = None):
self._widget = widget
self._path = path
self._window = window if window else ui.Workspace.get_window(path.split("//")[0])
@property
def widget(self) -> ui.Widget:
return self._widget
@property
def model(self):
return self._widget.model
@property
def window(self) -> ui.Window:
return self._window
@property
def path(self) -> str:
"""Path this widget was found with."""
return self._path
@property
def realpath(self) -> str:
"""Actual unique path to this widget from the window."""
return OmniUIQuery.get_widget_path(self.window, self.widget)
def __str__(self) -> str:
return f"WidgetRef({self.widget}, {self.path})"
@property
def position(self) -> Vec2:
"""Screen position of widget's top left corner."""
return Vec2(self._widget.screen_position_x, self._widget.screen_position_y)
@property
def size(self) -> Vec2:
"""Computed size of the widget."""
return Vec2(self._widget.computed_content_width, self._widget.computed_content_height)
@property
def center(self) -> Vec2:
"""Center of the widget."""
return self.position + (self.size / 2)
def offset(self, *kwargs) -> Vec2:
if len(kwargs) == 2:
return self.position + Vec2(kwargs[0], kwargs[1])
if len(kwargs) == 1 and isinstance(kwargs[0], Vec2):
return self.position + kwargs[0]
return None
async def _wait(self, update_count=2):
await wait_n_updates_internal(update_count)
async def focus(self):
"""Focus on a window this widget belongs to."""
self.window.focus()
await self._wait()
async def undock(self):
"""Undock a window this widget belongs to."""
self.window.undock()
await self._wait()
async def bring_to_front(self):
"""Bring window this widget belongs to on top. Currently this is implemented as undock() + focus()."""
await self.undock()
await self.focus()
async def click(self, pos: Vec2 = None, right_click=False, double=False, human_delay_speed: int = 2):
"""Emulate mouse click on the widget."""
logger.info(f"click on {str(self)} (right_click: {right_click}, double: {double})")
await self.bring_to_front()
if not pos:
pos = self.center
await emulate_mouse_move_and_click(
pos, right_click=right_click, double=double, human_delay_speed=human_delay_speed
)
async def right_click(self, pos=None, human_delay_speed: int = 2):
await self.click(pos=pos, right_click=True, human_delay_speed=human_delay_speed)
async def double_click(self, pos=None, human_delay_speed: int = 2):
await self.click(pos, double=True, human_delay_speed=human_delay_speed)
async def input(self, text: str, end_key = KeyboardInput.ENTER, human_delay_speed: int = 2):
"""Emulate keyboard input of characters (text) into the widget.
It is a helper function for the following sequence:
1. Double click on the widget
2. Input characters
3. Press enter
"""
if type(self.widget) == ui.FloatSlider or type(self.widget) == ui.FloatDrag or type(self.widget) == ui.IntSlider:
from carb.input import MouseEventType, KeyboardEventType
await emulate_keyboard(KeyboardEventType.KEY_PRESS, KeyboardInput.UNKNOWN, KeyboardInput.LEFT_CONTROL)
await wait_n_updates_internal()
await self.click(human_delay_speed=human_delay_speed)
await emulate_keyboard(KeyboardEventType.KEY_RELEASE, KeyboardInput.UNKNOWN, KeyboardInput.LEFT_CONTROL)
await wait_n_updates_internal()
elif type(self.widget) == ui.IntDrag:
await wait_n_updates_internal(20)
await self.double_click(human_delay_speed=human_delay_speed)
else:
await self.double_click(human_delay_speed=human_delay_speed)
await wait_n_updates_internal(human_delay_speed)
await emulate_char_press(text)
await emulate_keyboard_press(end_key)
async def drag_and_drop(self, drop_target: Vec2, human_delay_speed: int = 4):
"""Drag/drop for widget.centre to `drop_target`"""
await emulate_mouse_drag_and_drop(self.center, drop_target, human_delay_speed=human_delay_speed)
def find(self, path: str) -> WidgetRef:
"""Find omni.ui Widget or Window by search query starting from this widget.
.. code-block:: python
stage_window = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
label = stage_window.find("**/Label[*].text=='hello'")
await label.right_click()
Returns:
Found Widget or Window wrapped into `WidgetRef` object.
"""
return _find(path, self)
def find_all(self, path: str) -> List[WidgetRef]:
"""Find all omni.ui Widget or Window by search query starting from this widget.
.. code-block:: python
stage_window = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
labels = stage_window.find_all("**/Label[*]")
for label in labels:
await label.right_click()
Returns:
List of found Widget or Window wrapped into `WidgetRef` objects.
"""
return _find_all(path, self)
class WindowRef(WidgetRef):
"""Reference to `omni.ui.WindowHandle`"""
def __init__(self, widget: ui.WindowHandle, path: str):
super().__init__(widget, path, window=widget)
@property
def position(self) -> Vec2:
return Vec2(self._widget.position_x, self._widget.position_y)
@property
def size(self) -> Vec2:
return Vec2(self._widget.width, self._widget.height)
def _find_all(path: str, root_widget: WidgetRef = None) -> List[WidgetRef]:
# Special case for just window (can be supported in omni.ui.query better)
if "/" not in path and not root_widget:
window = ui.Workspace.get_window(path)
if not window:
carb.log_warn(f"Can't find window at path: {path}")
return None
return [WindowRef(window, path)]
root_widgets = [root_widget.widget] if root_widget else []
widgets = OmniUIQuery.find_widgets(path, root_widgets=root_widgets)
# Build list of Window and Widget references:
res = []
for widget in widgets:
fullpath = path
window = None
if root_widget:
sep = "//" if isinstance(root_widget.widget, ui.WindowHandle) else "/"
fullpath = f"{root_widget.path}{sep}{path}"
window = root_widget.window
if isinstance(widget, ui.WindowHandle):
res.append(WindowRef(widget, fullpath, window=window))
else:
res.append(WidgetRef(widget, fullpath, window=window))
return res
def _find(path: str, root_widget: WidgetRef = None) -> WidgetRef:
widgets = _find_all(path, root_widget)
if not widgets or len(widgets) == 0:
carb.log_warn(f"Can't find any widgets at path: {path}")
return None
MAX_OUTPUT = 10
if len(widgets) > 1:
carb.log_warn(f"Found {len(widgets)} widgets at path: {path} instead of one.")
for i in range(len(widgets)):
carb.log_warn(
"[{0}] {1} name: '{2}', realpath: '{3}'".format(
i, widgets[i], widgets[i].widget.name, widgets[i].realpath
)
)
if i > MAX_OUTPUT:
carb.log_warn("...")
break
return None
return widgets[0]
class MenuRef(WidgetRef):
"""Reference to `omni.ui.Menu`"""
def __init__(self, widget: ui.Menu, path: str):
super().__init__(widget, path, window=window_stub)
@staticmethod
async def menu_click(path, human_delay_speed: int = 8, show: bool=True):
menu_widget = get_menubar()
for menu_name in path.split("/"):
menu_widget = menu_widget.find_menu(menu_name)
if isinstance(menu_widget.widget, ui.Menu):
if menu_widget.widget.shown != show:
await menu_widget.click()
await wait_n_updates_internal(human_delay_speed)
if menu_widget.widget.shown != show:
carb.log_warn(f"ui.Menu item failed to {'show' if show else 'hide'}")
else:
await menu_widget.click()
await wait_n_updates_internal(human_delay_speed)
await wait_n_updates_internal(human_delay_speed)
@property
def center(self) -> Vec2:
# Menu/MenuItem doesn't have width/height
if isinstance(self._widget, ui.Menu):
return self.position + Vec2(10, 5) * ui.Workspace.get_dpi_scale()
return self.position + Vec2(25, 5) * ui.Workspace.get_dpi_scale()
def find_menu(self, path: str, ignore_case: bool=False, contains_path: bool=False) -> MenuRef:
for widget in self.find_all("**/"):
if isinstance(widget.widget, ui.Menu) or isinstance(widget.widget, ui.MenuItem):
menu_path = widget.widget.text.encode('ascii', 'ignore').decode().strip()
if menu_path == path or \
(ignore_case and menu_path.lower() == path.lower()) or \
(contains_path and path in menu_path) or \
(ignore_case and contains_path and path.lower() in menu_path.lower()
):
return MenuRef(widget=widget.widget, path=widget.path)
return None
def find(path: str) -> WidgetRef:
"""Find omni.ui Widget or Window by search query. `omni.ui_query` is used under the hood.
Returned object can be used to get actual found item or/and do UI test operations on it.
.. code-block:: python
stage_window = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
await stage_window.right_click()
viewport = ui_test.find("Viewport")
center = viewport.center
print(center)
Returns:
Found Widget or Window wrapped into `WidgetRef` object.
"""
return _find(path)
def find_all(path: str) -> List[WidgetRef]:
"""Find all omni.ui Widget or Window by search query.
.. code-block:: python
buttons = ui_test.find_all("Stage//Frame/**/Button[*]")
for button in buttons:
await button.click()
Returns:
List of found Widget or Window wrapped into `WidgetRef` objects.
"""
return _find_all(path)
def get_menubar() -> MenuRef:
from omni.kit.mainwindow import get_main_window
window = get_main_window()
return MenuRef(widget=window._ui_main_window.main_menu_bar, path="MainWindow//Frame/MenuBar")
async def menu_click(path, human_delay_speed: int = 32, show: bool=True) -> None:
await MenuRef.menu_click(path, human_delay_speed=human_delay_speed, show=show)
| 11,825 | Python | 34.091988 | 138 | 0.615222 |
omniverse-code/kit/exts/omni.kit.ui_test/omni/kit/ui_test/__init__.py | from .common import human_delay, wait_n_updates, InitExt
from .vec2 import Vec2
from .input import (
emulate_mouse_click,
emulate_mouse_move,
emulate_mouse_move_and_click,
emulate_mouse_drag_and_drop,
emulate_mouse_scroll,
emulate_keyboard_press,
emulate_char_press,
emulate_key_combo,
KeyDownScope,
)
from .query import WidgetRef, WindowRef, find, find_all, get_menubar, menu_click
from .menu import select_context_menu, get_context_menu
| 475 | Python | 28.749998 | 80 | 0.730526 |
omniverse-code/kit/exts/omni.kit.ui_test/omni/kit/ui_test/menu.py | from __future__ import annotations
import re
import logging
from omni import ui
from .input import emulate_mouse_move, emulate_mouse_click
from .common import human_delay, wait_n_updates_internal
from .vec2 import Vec2
logger = logging.getLogger(__name__)
def _find_menu_item(query, menu_root):
menu_items = ui.Inspector.get_children(menu_root)
for menu_item in menu_items:
if isinstance(menu_item, ui.MenuItem) or isinstance(menu_item, ui.Menu):
name = re.sub(r"[^\x00-\x7F]+", " ", menu_item.text).lstrip()
if query == name:
return menu_item
return None
def _find_context_menu_item(query, menu_root, find_fn=_find_menu_item):
tokens = re.split(r'(?<!/)/(?!/)', query)
child = menu_root
for i in range(0, len(tokens)):
token = tokens[i].replace("//", "/")
child = find_fn(token, child)
if not child:
break
return child
async def select_context_menu(
menu_path: str, menu_root: ui.Widget = None, offset=Vec2(100, 10), human_delay_speed: int = 4, find_fn=_find_menu_item
):
"""Emulate selection of context menu item with mouse.
Supports nested menus separated by `/`:
.. code-block:: python
await ui_test.select_context_menu("Option/Select/All")
This function waits for current menu for some time first. Unless `menu_root` was passed explicitly.
When there are nested menu mouse moves to each of them and makes human delay for it to open. Then is emulates mouse
click on final menu item.
"""
logger.info(f"select_context_menu: {menu_path} (offset: {offset})")
MAX_WAIT = 100
# Find active menu
for _ in range(MAX_WAIT):
menu_root = menu_root or ui.Menu.get_current()
if menu_root:
break
await wait_n_updates_internal(1)
if not menu_root:
raise Exception("Can't find context menu, wait time exceeded.")
for _ in range(MAX_WAIT):
if menu_root.shown:
break
await wait_n_updates_internal(1)
if not menu_root.shown:
raise Exception("Context menu is not visible, wait time exceeded.")
sub_items = re.split(r'(?<!/)/(?!/)', menu_path)
sub_menu_item = ""
for item in sub_items:
sub_menu_item = f"{sub_menu_item}/{item}" if sub_menu_item else f"{item}"
menu_item = _find_context_menu_item(sub_menu_item, menu_root, find_fn)
if not menu_item:
raise Exception(f"Can't find menu item with path: '{menu_path}'. sub_menu_item: '{sub_menu_item}'")
await emulate_mouse_move(Vec2(menu_item.screen_position_x, menu_item.screen_position_y) + offset)
await human_delay(human_delay_speed)
await emulate_mouse_click()
await human_delay(human_delay_speed)
async def get_context_menu(menu_root: ui.Widget = None, get_all: bool=False):
logger.info(f"get_context_menu: {menu_root}")
MAX_WAIT = 100
# Find active menu
for _ in range(MAX_WAIT):
menu_root = menu_root or ui.Menu.get_current()
if menu_root:
break
await wait_n_updates_internal(1)
if not menu_root:
raise Exception("Can't find context menu, wait time exceeded.")
for _ in range(MAX_WAIT):
if menu_root.shown:
break
await wait_n_updates_internal(1)
if not menu_root.shown:
raise Exception("Context menu is not visible, wait time exceeded.")
menu_dict = {}
def list_menu(menu_root, menu_dict):
for menu_item in ui.Inspector.get_children(menu_root):
if not get_all and (not menu_item.enabled or not menu_item.visible):
continue
if isinstance(menu_item, ui.MenuItem) or isinstance(menu_item, ui.Menu) or (isinstance(menu_item, ui.Separator) and get_all):
name = re.sub(r"[^\x00-\x7F]+", " ", menu_item.text).lstrip()
if isinstance(menu_item, ui.Menu):
if not name in menu_dict:
menu_dict[name] = {}
list_menu(menu_item, menu_dict[name])
elif menu_item.has_triggered_fn():
if not "_" in menu_dict:
menu_dict["_"] = []
menu_dict["_"].append(name)
elif get_all:
menu_dict["_"].append(name)
list_menu(menu_root, menu_dict)
return menu_dict
| 4,409 | Python | 32.923077 | 137 | 0.603311 |
omniverse-code/kit/exts/omni.kit.ui_test/omni/kit/ui_test/input.py | import carb
import carb.input
import omni.kit.app
import omni.ui as ui
import carb.windowing
import omni.appwindow
from carb.input import MouseEventType, KeyboardEventType, KeyboardInput
import logging
from functools import lru_cache
from itertools import chain
from .vec2 import Vec2
from .common import human_delay, wait_n_updates_internal
logger = logging.getLogger(__name__)
@lru_cache()
def _get_windowing() -> carb.windowing.IWindowing:
return carb.windowing.acquire_windowing_interface()
@lru_cache()
def _get_input_provider() -> carb.input.InputProvider:
return carb.input.acquire_input_provider()
async def emulate_mouse(event_type: MouseEventType, pos: Vec2 = Vec2()):
app_window = omni.appwindow.get_default_app_window()
mouse = app_window.get_mouse()
window_width = ui.Workspace.get_main_window_width()
window_height = ui.Workspace.get_main_window_height()
pos = pos * ui.Workspace.get_dpi_scale()
_get_input_provider().buffer_mouse_event(
mouse, event_type, (pos.x / window_width, pos.y / window_height), 0, pos.to_tuple()
)
if event_type == MouseEventType.MOVE:
_get_windowing().set_cursor_position(app_window.get_window(), (int(pos.x), int(pos.y)))
async def emulate_mouse_click(right_click=False, double=False):
"""Emulate Mouse single or double click."""
for _ in range(2 if double else 1):
await emulate_mouse(MouseEventType.RIGHT_BUTTON_DOWN if right_click else MouseEventType.LEFT_BUTTON_DOWN)
await wait_n_updates_internal()
await emulate_mouse(MouseEventType.RIGHT_BUTTON_UP if right_click else MouseEventType.LEFT_BUTTON_UP)
await wait_n_updates_internal()
async def emulate_mouse_move(pos: Vec2, human_delay_speed: int = 2):
"""Emulate Mouse move into position."""
logger.info(f"emulate_mouse_move to: {pos}")
await emulate_mouse(MouseEventType.MOVE, pos)
await human_delay(human_delay_speed)
async def emulate_mouse_move_and_click(pos: Vec2, right_click=False, double=False, human_delay_speed: int = 2):
"""Emulate Mouse move into position and click."""
logger.info(f"emulate_mouse_move_and_click pos: {pos} (right_click: {right_click}, double: {double})")
await emulate_mouse(MouseEventType.MOVE, pos)
await emulate_mouse_click(right_click=right_click, double=double)
await human_delay(human_delay_speed)
async def emulate_mouse_slow_move(start_pos, end_pos, num_steps=8, human_delay_speed: int = 4):
"""Emulate Mouse slow move. Mouse is moved in steps between start and end with the human delay between each step."""
step = (end_pos - start_pos) / num_steps
for i in range(0, num_steps + 1):
await emulate_mouse(MouseEventType.MOVE, start_pos + step * i)
await human_delay(human_delay_speed)
async def emulate_mouse_drag_and_drop(start_pos, end_pos, right_click=False, human_delay_speed: int = 4):
"""Emulate Mouse Drag & Drop. Click at start position and slowly move to end position."""
logger.info(f"emulate_mouse_drag_and_drop pos: {start_pos} -> {end_pos} (right_click: {right_click})")
await emulate_mouse(MouseEventType.MOVE, start_pos)
await emulate_mouse(MouseEventType.RIGHT_BUTTON_DOWN if right_click else MouseEventType.LEFT_BUTTON_DOWN)
await human_delay(human_delay_speed)
await emulate_mouse_slow_move(start_pos, end_pos, human_delay_speed=human_delay_speed)
await human_delay(human_delay_speed)
await emulate_mouse(MouseEventType.RIGHT_BUTTON_UP if right_click else MouseEventType.LEFT_BUTTON_UP)
await human_delay(human_delay_speed)
async def emulate_mouse_scroll(delta: Vec2, human_delay_speed: int = 2):
"""Emulate Mouse scroll by delta."""
logger.info(f"emulate_mouse_scroll: {delta}")
await emulate_mouse(MouseEventType.SCROLL, delta)
await human_delay(human_delay_speed)
async def emulate_keyboard(event_type: KeyboardEventType, key: KeyboardInput, modifier: carb.input.KeyboardInput = 0):
logger.info(f"emulate_keyboard event_type: {event_type}, key: {key} modifier:{modifier}")
keyboard = omni.appwindow.get_default_app_window().get_keyboard()
_get_input_provider().buffer_keyboard_key_event(keyboard, event_type, key, modifier)
MODIFIERS_TO_KEY = {
carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL: KeyboardInput.LEFT_CONTROL,
carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT: KeyboardInput.LEFT_SHIFT,
carb.input.KEYBOARD_MODIFIER_FLAG_ALT: KeyboardInput.LEFT_ALT,
}
async def emulate_keyboard_press(
key: KeyboardInput, modifier: carb.input.KeyboardInput = 0, human_delay_speed: int = 2
):
"""Emulate Keyboard key press. Down and up."""
# Figure out which modifier keys need to be pressed
mods = []
for k in MODIFIERS_TO_KEY.keys():
if modifier & k:
mods.append(k)
modifier = 0
for k in mods:
modifier = modifier | k # modifier is added for the press
await emulate_keyboard(KeyboardEventType.KEY_PRESS, MODIFIERS_TO_KEY[k], modifier)
await human_delay(human_delay_speed)
await emulate_keyboard(KeyboardEventType.KEY_PRESS, key, modifier)
await human_delay(human_delay_speed)
await emulate_keyboard(KeyboardEventType.KEY_RELEASE, key, modifier)
await human_delay(human_delay_speed)
# Back off the modifiers
for k in reversed(mods):
modifier = modifier & ~k # modifier is removed for the release
await emulate_keyboard(KeyboardEventType.KEY_RELEASE, MODIFIERS_TO_KEY[k], modifier)
await human_delay(human_delay_speed)
MODIFIERS_MAP = {
"CTRL": (KeyboardInput.LEFT_CONTROL, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL),
"CONTROL": (KeyboardInput.LEFT_CONTROL, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL),
"SHIFT": (KeyboardInput.LEFT_SHIFT, carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT),
"ALT": (KeyboardInput.LEFT_ALT, carb.input.KEYBOARD_MODIFIER_FLAG_ALT),
}
async def emulate_key_combo(combo: str, human_delay_speed: int = 2):
"""Emulate Keyboard key combination.
Parse string of keys separated by '+' sign and treat as a key combo to emulate.
Examples: "CTRL+ENTER", "SHIFT+ALT+Y", "Z"
"""
mods = []
keys = []
modifiers = 0
key_map = KeyboardInput.__members__ # pybind11 way to get enum as dict (name -> value)
for key in combo.upper().split("+"):
if key in MODIFIERS_MAP:
mods.append(MODIFIERS_MAP[key])
continue
if key not in key_map:
carb.log_error(f"Can't parse key: '{key}' in combo: '{combo}'")
return
keys.append(key_map[key])
# press modifier keys first
for k in mods:
modifiers = modifiers | k[1] # modifier is added for the press
await emulate_keyboard(KeyboardEventType.KEY_PRESS, k[0], modifiers)
await human_delay(human_delay_speed)
# press non-modifier keys
for k in keys:
await emulate_keyboard(KeyboardEventType.KEY_PRESS, k, modifiers)
await human_delay(human_delay_speed)
# release non-modifier keys and modifier keys in reverse order
for k in reversed(keys):
await emulate_keyboard(KeyboardEventType.KEY_RELEASE, k, modifiers)
await human_delay(human_delay_speed)
for k in reversed(mods):
modifiers = modifiers & ~k[1] # modifier is removed for the release
await emulate_keyboard(KeyboardEventType.KEY_RELEASE, k[0], modifiers)
await human_delay(human_delay_speed)
async def emulate_char_press(chars: str, delay_every_n_symbols: int = 20, human_delay_speed: int = 2):
"""Emulate Keyboard char input. Type N chars immediately and do a delay, then continue."""
keyboard = omni.appwindow.get_default_app_window().get_keyboard()
for i, char in enumerate(chars):
_get_input_provider().buffer_keyboard_char_event(keyboard, char, 0)
if (i + 1) % delay_every_n_symbols == 0:
await human_delay(human_delay_speed)
# Key is down when enter the scope and released when exit
# Usage:
# async with KeyDownScope(carb.input.KeyboardInput.LEFT_CONTROL):
# await ui_test.emulate_mouse_drag_and_drop(Vec2(50, 50), Vec2(350, 350))
class KeyDownScope:
def __init__(
self, key: carb.input.KeyboardInput, modifier: carb.input.KeyboardInput = 0, human_delay_speed: int = 2
):
self._key = key
self._modifier = modifier
self._human_delay_speed = human_delay_speed
async def __aenter__(self):
await emulate_keyboard(carb.input.KeyboardEventType.KEY_PRESS, self._key, self._modifier)
await human_delay(self._human_delay_speed)
async def __aexit__(self, exc_type, exc, tb):
await emulate_keyboard(carb.input.KeyboardEventType.KEY_RELEASE, self._key, self._modifier)
if self._modifier:
await emulate_keyboard(carb.input.KeyboardEventType.KEY_RELEASE, self._modifier)
await human_delay(self._human_delay_speed)
| 8,918 | Python | 40.483721 | 120 | 0.697017 |
omniverse-code/kit/exts/omni.kit.ui_test/omni/kit/ui_test/tests/test_ui_test.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import unittest
import omni.kit.app
from omni.kit.test import AsyncTestCase
import omni.ui as ui
import omni.kit.ui_test as ui_test
import carb.input
import omni.appwindow
from carb.input import KeyboardInput, KeyboardEventType
from contextlib import asynccontextmanager
@asynccontextmanager
async def capture_keyboard():
input = carb.input.acquire_input_interface()
keyboard = omni.appwindow.get_default_app_window().get_keyboard()
events = []
def on_input(e):
events.append((e.input, e.type, e.modifiers))
sub = input.subscribe_to_keyboard_events(keyboard, on_input)
try:
yield events
finally:
input.unsubscribe_to_keyboard_events(keyboard, sub)
@asynccontextmanager
async def capture_mouse():
input = carb.input.acquire_input_interface()
mouse = omni.appwindow.get_default_app_window().get_mouse()
events = []
def on_input(e):
events.append((e.input, e.type))
sub = input.subscribe_to_mouse_events(mouse, on_input)
try:
yield events
finally:
input.unsubscribe_to_mouse_events(mouse, sub)
class TestUITest(AsyncTestCase):
async def setUp(self):
self._clicks = 0
self._window = ui.Window("Cool Window")
with self._window.frame: # the frame can only have 1 widget under it
with ui.HStack():
with ui.VStack():
ui.Label("Test2")
with ui.VStack(width=150):
with ui.HStack(height=30):
ui.Label("Test1")
ui.StringField()
def on_click(*_):
self._clicks += 1
ui.Button("TestButton", clicked_fn=on_click)
await ui_test.wait_n_updates(2)
async def tearDown(self):
self._window = None
async def test_find(self):
# Click a button
button = ui_test.find("Cool Window//Frame/**/Button[*]")
self.assertEqual(button.realpath, "Cool Window//Frame/HStack[0]/VStack[1]/HStack[0]/Button[0]")
await button.click()
self.assertEqual(self._clicks, 1)
# Move mouse away, click and then click button again, that should be +1 click:
await ui_test.emulate_mouse_move(ui_test.Vec2(0, 0))
await ui_test.emulate_mouse_click()
await ui_test.find("Cool Window//Frame/**/Button[*]").click()
self.assertEqual(self._clicks, 2)
async def test_nested_find(self):
# Multiple nested finds
h_stack = ui_test.find("Cool Window//Frame/HStack[0]")
self.assertEqual(h_stack.realpath, "Cool Window//Frame/HStack[0]")
await h_stack.find("**/Button[0]").click()
self.assertEqual(self._clicks, 1)
window = ui_test.find("Cool Window")
h_stack = window.find("HStack[0]")
self.assertEqual(h_stack.realpath, "Cool Window//Frame/HStack[0]")
await h_stack.find("**/Button[0]").click()
self.assertEqual(self._clicks, 2)
async def test_find_all(self):
labels = ui_test.find_all("Cool Window//Frame/**/Label[*]")
self.assertSetEqual({s.widget.text for s in labels}, {"Test1", "Test2"})
h_stack = ui_test.find("Cool Window//Frame/HStack[0]")
labels = h_stack.find_all("**/Label[*]")
self.assertSetEqual({s.widget.text for s in labels}, {"Test1", "Test2"})
class TestInput(AsyncTestCase):
async def test_emulate_keyboard(self):
async with capture_keyboard() as events:
await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.X, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL)
self.assertListEqual(
events,
[
(KeyboardInput.LEFT_CONTROL, KeyboardEventType.KEY_PRESS, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL),
(KeyboardInput.X, KeyboardEventType.KEY_PRESS, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL),
(KeyboardInput.X, KeyboardEventType.KEY_RELEASE, carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL),
(KeyboardInput.LEFT_CONTROL, KeyboardEventType.KEY_RELEASE, 0),
],
)
async def test_emulate_key_combo(self):
async with capture_keyboard() as events:
await ui_test.emulate_key_combo("SHIFT+ctrl+w")
self.assertListEqual(
events,
[
(KeyboardInput.LEFT_SHIFT, KeyboardEventType.KEY_PRESS, carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT),
(KeyboardInput.LEFT_CONTROL, KeyboardEventType.KEY_PRESS, carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT | carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL),
(KeyboardInput.W, KeyboardEventType.KEY_PRESS, carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT | carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL),
(KeyboardInput.W, KeyboardEventType.KEY_RELEASE, carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT | carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL),
(KeyboardInput.LEFT_CONTROL, KeyboardEventType.KEY_RELEASE, carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT),
(KeyboardInput.LEFT_SHIFT, KeyboardEventType.KEY_RELEASE, 0),
],
)
events.clear()
await ui_test.emulate_key_combo("Y")
self.assertListEqual(
events,
[(KeyboardInput.Y, KeyboardEventType.KEY_PRESS, 0), (KeyboardInput.Y, KeyboardEventType.KEY_RELEASE, 0)],
)
@unittest.skip("Subscribe to mouse in carbonite doesn't seem to work")
async def test_emulate_mouse_scroll(self):
async with capture_mouse() as events:
await ui_test.emulate_mouse_scroll(ui_test.Vec2(5.5, 6.5))
print(events)
self.assertListEqual(
events,
[] # TODO
)
| 6,332 | Python | 37.615853 | 163 | 0.624131 |
omniverse-code/kit/exts/omni.kit.ui_test/omni/kit/ui_test/tests/__init__.py | from .test_ui_test import *
from .test_ui_test_doc_snippets import *
| 69 | Python | 22.333326 | 40 | 0.73913 |
omniverse-code/kit/exts/omni.kit.ui_test/omni/kit/ui_test/tests/test_ui_test_doc_snippets.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import builtins
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.ui as ui
import omni.kit.ui_test as ui_test
class TestUITestDocSnippet(AsyncTestCase):
async def test_doc_snippet(self):
clicks = 0
def on_click(*_):
nonlocal clicks
clicks += 1
printed_text = ""
def print(*args, **kwargs):
nonlocal printed_text
printed_text += str(args[0]) + "\n"
return builtins.print(*args, **kwargs)
# begin-doc-1
# Demo:
import omni.kit.ui_test as ui_test
import omni.ui as ui
# Build some UI
window = ui.Window("Nice Window")
with window.frame: # the frame can only have 1 widget under it
with ui.HStack():
ui.Label("Test1")
with ui.VStack(width=150):
ui.Label("Test2")
ui.Button("TestButton", clicked_fn=on_click)
# Let UI build
await ui_test.wait_n_updates(2)
# Find a button
button = ui_test.find("Nice Window//Frame/**/Button[*]")
# Real / Unique path:
print(button.realpath) # Nice Window//Frame/HStack[0]/VStack[0]/Button[0]
# button is a reference, actual omni.ui.Widget can be accessed:
print(type(button.widget)) # <class 'omni.ui._ui.Button'>
# Click on button
await button.click()
# Find can be nested
same_button = ui_test.find("Nice Window").find("**/Button[*]")
# Find multiple:
labels = ui_test.find_all("Nice Window//Frame/**/Label[*]")
print(labels[0].widget.text) # Test 1
print(labels[1].widget.text) # Test 2
# end-doc-1
# Verify snippet operations:
self.assertEqual(
printed_text,
"""Nice Window//Frame/HStack[0]/VStack[0]/Button[0]
<class 'omni.ui._ui.Button'>
Test1
Test2
""",
)
self.assertEqual(button.widget, same_button.widget)
self.assertEqual(clicks, 1)
self.assertEqual(len(labels), 2)
| 2,565 | Python | 29.188235 | 82 | 0.604678 |
omniverse-code/kit/exts/omni.kit.collaboration.stage_columns/omni/kit/collaboration/stage_columns/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.
#
__all__ = ["CollaborationColumnsWidgetExtension"]
import omni.ext
from .delegates import *
from omni.kit.widget.stage.stage_column_delegate_registry import StageColumnDelegateRegistry
class CollaborationColumnsWidgetExtension(omni.ext.IExt):
"""The entry point for Stage Window"""
def on_startup(self):
# Register column delegates
self._live_column_sub = StageColumnDelegateRegistry().register_column_delegate(
"Live", LiveColumnDelegate
)
self._reload_column_sub = StageColumnDelegateRegistry().register_column_delegate(
"Reload", ReloadColumnDelegate
)
self._participants_column_sub = StageColumnDelegateRegistry().register_column_delegate(
"Participants", ParticipantsColumnDelegate
)
def on_shutdown(self):
self._live_column_sub = None
self._reload_column_sub = None
self._participants_column_sub = None
| 1,376 | Python | 36.216215 | 95 | 0.728924 |
omniverse-code/kit/exts/omni.kit.collaboration.stage_columns/omni/kit/collaboration/stage_columns/icons.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__ = ["Icons"]
from .singleton import Singleton
from pathlib import Path
from typing import Union
import omni.kit.app
EXTENSION_FOLDER_PATH = Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
@Singleton
class Icons:
"""A singleton that scans the icon folder and returns the icon depending on the type"""
def __init__(self):
# Read all the svg files in the directory
self.__icons = {icon.stem: str(icon) for icon in EXTENSION_FOLDER_PATH.joinpath("icons").glob("*.svg")}
def get(self, prim_type: str, default: Union[str, Path] = None) -> str:
"""Checks the icon cache and returns the icon if exists"""
found = self.__icons.get(prim_type)
if not found and default:
found = self._icons.get(default)
if found:
return found
return ""
| 1,317 | Python | 31.146341 | 111 | 0.694002 |
omniverse-code/kit/exts/omni.kit.collaboration.stage_columns/omni/kit/collaboration/stage_columns/models/reload_model.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__ = ["ReloadModel"]
import omni.ui as ui
from omni.kit.widget.live_session_management.utils import reload_outdated_layers
class ReloadModel(ui.AbstractValueModel):
def __init__(self, stage_item):
super().__init__()
self._stage_item = stage_item
def destroy(self):
self._stage_item = None
def get_value_as_bool(self) -> bool:
"""Reimplemented get bool"""
return self._stage_item.is_outdated
def set_value(self, value: bool):
"""Reimplemented set bool"""
prim = self._stage_item.prim
if not prim:
return
prim_path = prim.GetPath()
if prim_path:
reload_outdated_layers(self._stage_item.payrefs, self._stage_item.usd_context)
| 1,190 | Python | 30.342104 | 90 | 0.679832 |
omniverse-code/kit/exts/omni.kit.collaboration.stage_columns/omni/kit/collaboration/stage_columns/models/live_model.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__ = ["LiveModel"]
import omni.ui as ui
import omni.kit.usd.layers as layers
import omni.kit.notification_manager as nm
class LiveModel(ui.AbstractValueModel):
def __init__(self, stage_item):
super().__init__()
self._stage_item = stage_item
def destroy(self):
self._stage_item = None
def get_value_as_bool(self) -> bool:
"""Reimplemented get bool"""
return self._stage_item.in_session
def set_value(self, value: bool):
"""Reimplemented set bool"""
live_syncing = layers.get_live_syncing(self._stage_item.usd_context)
if self._stage_item.in_session:
live_syncing.stop_live_session(prim_path=self._stage_item.path)
elif self._stage_item.payrefs:
if len(self._stage_item.payrefs) > 1:
nm.post_notification(
f"Cannot join default session for prim {self._stage_item.path} as it"
" includes multiple references or payloads. Please join from Property"
" Window instead."
)
else:
payref = self._stage_item.payrefs[0]
default_session = live_syncing.find_live_session_by_name(payref, "Default")
if not default_session:
default_session = live_syncing.create_live_session("Default", payref)
if default_session:
live_syncing.join_live_session(default_session, self._stage_item.path)
| 1,936 | Python | 38.530611 | 91 | 0.635847 |
omniverse-code/kit/exts/omni.kit.collaboration.stage_columns/omni/kit/collaboration/stage_columns/delegates/participants_column_delegate.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__ = ["ParticipantsColumnDelegate"]
from omni.kit.widget.stage.abstract_stage_column_delegate import AbstractStageColumnDelegate, StageColumnItem
from omni.kit.widget.stage import StageItem
from pxr import UsdGeom
from ..icons import Icons
from typing import List
import omni.ui as ui
import omni.kit.widget.live_session_management as lsm
class ParticipantsColumnDelegate(AbstractStageColumnDelegate):
"""The column delegate that represents the Live column"""
def __init__(self):
super().__init__()
self.WIDGET_STYLE = {
"TreeView.Header::participants": {"image_url": Icons().get("participants"), "color": 0xFF888888},
}
self.__user_list = {}
def destroy(self):
for user_list in self.__user_list.values():
user_list.destroy()
self.__user_list = {}
@property
def initial_width(self):
"""The width of the column"""
return ui.Pixel(64)
def build_header(self, **kwargs):
"""Build the header"""
with ui.HStack(style=self.WIDGET_STYLE):
ui.Spacer()
with ui.VStack(width=0):
ui.Spacer()
ui.Image(width=22, height=14, name="participants", style_type_name_override="TreeView.Header")
ui.Spacer()
ui.Spacer()
async def build_widget(self, item: StageColumnItem, **kwargs):
"""Build the participants widget"""
stage_item = kwargs.get("stage_item", None)
if not stage_item:
return
user_list = self.__user_list.pop(stage_item, None)
if user_list:
user_list.destroy()
prim = stage_item.prim
if not prim:
return
payrefs = stage_item.payrefs
if not prim.IsA(UsdGeom.Camera) and not payrefs:
return
with ui.HStack():
ui.HStack(width=4)
with ui.HStack():
ui.Spacer()
if payrefs:
user_list = lsm.LiveSessionUserList(
stage_item.usd_context, payrefs[0],
show_myself=False, maximum_users=2,
prim_path=stage_item.path
)
else:
user_list = lsm.LiveSessionCameraFollowerList(
stage_item.usd_context, stage_item.path, maximum_users=2,
show_my_following_users=True
)
self.__user_list[stage_item] = user_list
ui.Spacer()
ui.HStack(width=4)
def on_stage_items_destroyed(self, items: List[StageItem]):
if not items:
return
for item in items:
user_list = self.__user_list.pop(item, None)
if user_list:
user_list.destroy()
@property
def order(self):
return -105
@property
def sortable(self):
return False
@property
def minimum_width(self):
return ui.Pixel(40)
| 3,460 | Python | 30.463636 | 110 | 0.584104 |
omniverse-code/kit/exts/omni.kit.collaboration.stage_columns/omni/kit/collaboration/stage_columns/delegates/reload_column_delegate.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__ = ["ReloadColumnDelegate"]
from omni.kit.widget.stage.abstract_stage_column_delegate import AbstractStageColumnDelegate, StageColumnItem
from omni.kit.widget.stage import StageItem
from typing import List
from ..models.reload_model import ReloadModel
from ..icons import Icons
from functools import partial
from omni.ui import color as cl
from enum import Enum
import weakref
import omni.ui as ui
import omni.kit.app
import omni.kit.usd.layers as layers
import carb
class ReloadColumnSortPolicy(Enum):
DEFAULT = 0
OUTDATE_TO_LATEST = 1
LATEST_TO_OUTDATE = 2
class ReloadColumnDelegate(AbstractStageColumnDelegate):
"""The column delegate that represents the Auto Reload column"""
def __init__(self):
super().__init__()
self.__reload_layout = None
self.__stage_item_models = {}
ITEM_DARK = 0x7723211F
ICON_DARK = 0x338A8777
RELOAD = cl("#eb9d00")
RELOAD_H = cl("#ffaa00")
AUTO_RELOAD = cl("#34C7FF")
AUTO_RELOAD_H = cl("#82dcff")
self.WIDGET_STYLE = {
"Button.Image::reload": {"image_url": Icons().get("reload"), "color": ICON_DARK},
"Button.Image::reload:checked": {"color": RELOAD_H},
"Button.Image::reload:disabled": {"color": 0x608A8777},
"Button.Image::reload:selected": {"color": ITEM_DARK},
"Button.Image::reload:checked:hovered": {"color": 0xFFFFFFFF},
"Button.Image::auto_reload": {"image_url": Icons().get("reload"), "color": AUTO_RELOAD},
"Button.Image::auto_reload:checked": {"color": AUTO_RELOAD},
"Button.Image::auto_reload:disabled": {"color": AUTO_RELOAD},
"Button.Image::auto_reload:checked:hovered": {"color": AUTO_RELOAD_H},
"Button::reload": {"background_color": 0x0, "margin": 0, "margin_width": 1},
"Button::reload:checked": {"background_color": 0x0},
"Button::reload:hovered": {"background_color": 0x0, "color": 0xFFFFFFFF},
"Button::reload:pressed": {"background_color": 0x0},
"Button::auto_reload": {"background_color": 0x0, "margin": 0, "margin_width": 1},
"Button::auto_reload:checked": {"background_color": 0x0},
"Button::auto_reload:hovered": {"background_color": 0x0, "color": 0xFFFFFFFF},
"Button::auto_reload:pressed": {"background_color": 0x0},
"TreeView.Item.Outdated": {"color": RELOAD},
"TreeView.Item.Outdated:hovered": {"color": RELOAD_H},
"TreeView.Item.Outdated:selected": {"color": RELOAD_H},
# Top of the column section (that has sorting options)
"TreeView.Header::reload_header": {"image_url": Icons().get("reload_dark")},
}
self.__stage_model = None
self.__items_sort_policy = ReloadColumnSortPolicy.DEFAULT
def destroy(self):
if self.__reload_layout:
self.__reload_layout.set_mouse_pressed_fn(None)
self.__reload_layout = None
for model in self.__stage_item_models.values():
model.destroy()
self.__stage_item_models = {}
self.__stage_model = None
@property
def initial_width(self):
"""The width of the column"""
return ui.Pixel(24)
@property
def minimum_width(self):
return ui.Pixel(24)
def __on_policy_changed(self):
stage_model = self.__stage_model
if not stage_model:
return
if self.__items_sort_policy == ReloadColumnSortPolicy.OUTDATE_TO_LATEST:
stage_model.set_items_sort_key_func(
lambda item: item.is_outdated if item.payrefs else len(item.payrefs) == 0
)
elif self.__items_sort_policy == ReloadColumnSortPolicy.LATEST_TO_OUTDATE:
stage_model.set_items_sort_key_func(
lambda item: item.is_outdated if item.payrefs else len(item.payrefs) == 0,
reverse=True
)
else:
stage_model.set_items_sort_key_func(None)
def __on_reload_clicked(self, weakref_stage_model, x, y, b, m):
stage_model = weakref_stage_model()
if not stage_model or not stage_model.stage:
return
if b == 1:
usd_context = omni.usd.get_context_from_stage(stage_model.stage)
if not usd_context:
return
layers_state = layers.get_layers_state(usd_context)
from omni.kit.widget.live_session_management.utils import reload_outdated_layers
ref_ids = layers_state.get_outdated_non_sublayer_identifiers()
reload_outdated_layers(ref_ids, usd_context)
elif b == 0:
if self.__items_sort_policy == ReloadColumnSortPolicy.OUTDATE_TO_LATEST:
self.__items_sort_policy = ReloadColumnSortPolicy.LATEST_TO_OUTDATE
elif self.__items_sort_policy == ReloadColumnSortPolicy.LATEST_TO_OUTDATE:
self.__items_sort_policy = ReloadColumnSortPolicy.DEFAULT
else:
self.__items_sort_policy = ReloadColumnSortPolicy.OUTDATE_TO_LATEST
self.__on_policy_changed()
def build_header(self, **kwargs):
"""Build the header"""
stage_model = kwargs.get("stage_model", None)
self.__stage_model = stage_model
if stage_model:
with ui.ZStack(style=self.WIDGET_STYLE):
tooltip = "RMB: Reload All References/Payloads"
ui.Rectangle(name="hovering", style_type_name_override="TreeView.Header", tooltip=tooltip)
self.__reload_layout = ui.HStack()
with self.__reload_layout:
ui.Spacer()
with ui.VStack(width=0):
ui.Spacer()
ui.Image(width=22, height=14, name="reload_header", style_type_name_override="TreeView.Header")
ui.Spacer()
ui.Spacer()
weakref_stage_model = weakref.ref(stage_model)
self.__reload_layout.set_mouse_pressed_fn(
partial(self.__on_reload_clicked, weakref_stage_model)
)
else:
with ui.HStack(style=self.WIDGET_STYLE):
ui.Spacer()
with ui.VStack(width=0):
ui.Spacer()
ui.Image(width=22, height=14, name="reload_header", style_type_name_override="TreeView.Header")
ui.Spacer()
ui.Spacer()
async def build_widget(self, item: StageColumnItem, **kwargs):
"""Build the reload widget"""
stage_item = kwargs.get("stage_item", None)
reloadable = (stage_item.payloads or stage_item.references)
if not stage_item or not stage_item.prim or not reloadable:
return
g_auto_reload = carb.settings.get_settings().get_as_bool(layers.SETTINGS_AUTO_RELOAD_NON_SUBLAYERS)
with ui.ZStack(height=20, style=self.WIDGET_STYLE):
# Min size
ui.Spacer(width=22)
reload_model = self.__stage_item_models.get(stage_item, None)
if not reload_model:
reload_model = ReloadModel(stage_item)
self.__stage_item_models[stage_item] = reload_model
button = ui.ToolButton(reload_model)
stub = "payloads" if stage_item.payloads else "references"
if not reload_model.get_value_as_bool():
tooltip = "All {} up to date".format(stub)
else:
tooltip = "Reload {} on prim".format(stub)
if stage_item.auto_reload:
tooltip = "Auto Reload All Enabled" if g_auto_reload else "Auto Reload Enabled"
button.enabled = False
if stage_item.is_outdated and g_auto_reload and stage_item.in_session:
tooltip = "Auto Reload Blocked by Live Session"
button.tooltip = tooltip
button.name = "auto_reload" if stage_item.auto_reload else "reload"
def on_stage_items_destroyed(self, items: List[StageItem]):
if not items:
return
for item in items:
live_model = self.__stage_item_models.pop(item, None)
if live_model:
live_model.destroy()
@property
def order(self):
return -104
@property
def sortable(self):
return True
| 8,866 | Python | 38.941441 | 119 | 0.596661 |
omniverse-code/kit/exts/omni.kit.collaboration.stage_columns/omni/kit/collaboration/stage_columns/delegates/live_column_delegate.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__ = ["LiveColumnDelegate"]
from omni.kit.widget.stage.abstract_stage_column_delegate import AbstractStageColumnDelegate, StageColumnItem
from omni.kit.widget.stage import StageItem, StageModel
from typing import List
from ..models import LiveModel
from ..icons import Icons
from enum import Enum
import omni.ui as ui
class LiveColumnSortPolicy(Enum):
DEFAULT = 0
LIVE_TO_OFFLINE = 1
OFFLINE_TO_LIVE = 2
class LiveColumnDelegate(AbstractStageColumnDelegate):
"""The column delegate that represents the Live column"""
def __init__(self):
super().__init__()
self.__stage_item_models = {}
from omni.ui import color as cl
ITEM_DARK = 0x7723211F
ICON_DARK = 0x338A8777
LIVE_GREEN = cl("#76b800")
LIVE_SEL = cl("#90e203")
self.WIDGET_STYLE = {
"Button.Image::live": {"image_url": Icons().get("lightning"), "color": ICON_DARK},
"Button.Image::live:checked": {"color": LIVE_GREEN},
"Button.Image::live:checked:hovered": {"color": LIVE_SEL},
"Button.Image::live:disabled": {"color": 0x608A8777},
"Button.Image::live:selected": {"color": ITEM_DARK},
"Button::live": {"background_color": 0x0, "margin": 0, "margin_width": 1},
"Button::live:checked": {"background_color": 0x0},
"Button::live:hovered": {"background_color": 0x0},
"Button::live:pressed": {"background_color": 0x0},
"TreeView.Item.Live": {"color": LIVE_GREEN},
"TreeView.Item.Live:hovered": {"color": LIVE_SEL},
"TreeView.Item.Live:selected": {"color": LIVE_SEL},
# Top of the column section (that has sorting options)
"TreeView.Header::live_header": {"image_url": Icons().get("lightning"), "color": 0xFF888888},
}
self.__stage_model: StageModel = None
self.__items_sort_policy = LiveColumnSortPolicy.DEFAULT
self.__live_header_layout = None
def destroy(self):
for model in self.__stage_item_models.values():
model.destroy()
self.__stage_item_models = {}
self.__stage_model = None
if self.__live_header_layout:
self.__live_header_layout.set_mouse_pressed_fn(None)
self.__live_header_layout = None
@property
def initial_width(self):
"""The width of the column"""
return ui.Pixel(24)
@property
def minimum_width(self):
return ui.Pixel(24)
def __on_policy_changed(self):
stage_model = self.__stage_model
if not stage_model:
return
if self.__items_sort_policy == LiveColumnSortPolicy.LIVE_TO_OFFLINE:
stage_model.set_items_sort_key_func(
lambda item: item.in_session if item.payrefs else len(item.payrefs) == 0
)
elif self.__items_sort_policy == LiveColumnSortPolicy.OFFLINE_TO_LIVE:
stage_model.set_items_sort_key_func(
lambda item: item.in_session if item.payrefs else len(item.payrefs) == 0,
reverse=True
)
else:
stage_model.set_items_sort_key_func(None)
def __on_header_clicked(self, x, y, b, m):
if b != 0 or not self.__stage_model:
return
if self.__items_sort_policy == LiveColumnSortPolicy.LIVE_TO_OFFLINE:
self.__items_sort_policy = LiveColumnSortPolicy.OFFLINE_TO_LIVE
elif self.__items_sort_policy == LiveColumnSortPolicy.OFFLINE_TO_LIVE:
self.__items_sort_policy = LiveColumnSortPolicy.DEFAULT
else:
self.__items_sort_policy = LiveColumnSortPolicy.LIVE_TO_OFFLINE
self.__on_policy_changed()
def build_header(self, **kwargs):
"""Build the header"""
self.__stage_model = kwargs.get("stage_model", None)
with ui.ZStack(style=self.WIDGET_STYLE):
tooltip = "LMB:Sort Live"
ui.Rectangle(name="hovering", style_type_name_override="TreeView.Header", tooltip=tooltip)
self.__live_header_layout = ui.HStack()
with self.__live_header_layout:
ui.Spacer()
with ui.VStack(width=0):
ui.Spacer()
ui.Image(width=22, height=14, name="live_header", style_type_name_override="TreeView.Header")
ui.Spacer()
ui.Spacer()
self.__live_header_layout.set_tooltip(tooltip)
self.__live_header_layout.set_mouse_pressed_fn(self.__on_header_clicked)
async def build_widget(self, item: StageColumnItem, **kwargs):
"""Build the live widget"""
stage_item = kwargs.get("stage_item", None)
reloadable = (stage_item.payloads or stage_item.references)
if not stage_item or not stage_item.prim or not reloadable:
return
with ui.ZStack(height=20, style=self.WIDGET_STYLE):
# Min size
ui.Spacer(width=22)
live_model = self.__stage_item_models.get(stage_item, None)
if not live_model:
live_model = LiveModel(stage_item)
self.__stage_item_models[stage_item] = live_model
tooltip = "Live session status"
ui.ToolButton(live_model, enabled=True, name="live", tooltip=tooltip)
def on_stage_items_destroyed(self, items: List[StageItem]):
if not items:
return
for item in items:
live_model = self.__stage_item_models.pop(item, None)
if live_model:
live_model.destroy()
@property
def order(self):
return -103
@property
def sortable(self):
return True
| 6,147 | Python | 36.260606 | 113 | 0.605661 |
omniverse-code/kit/exts/omni.kit.audio.test.usd/omni/kit/audio/test/usd/tests/test_audio.py | import asyncio
import time
from collections import defaultdict
import pathlib
from PIL import Image
from PIL import ImageEnhance
import random
import omni.kit.test_helpers_gfx.compare_utils
import carb
import carb.tokens
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
import omni.usd.audio
import os
from omni.ui.tests.test_base import OmniUiTest
from omni.kit.test_suite.helpers import wait_stage_loading
OUTPUTS_DIR = pathlib.Path(omni.kit.test.get_test_output_path())
def wait_for_asset(test, audio, prim):
i = 0
while audio.get_sound_asset_status(prim) == omni.usd.audio.AssetLoadStatus.IN_PROGRESS:
time.sleep(0.001)
if i > 5000:
raise Exception("asset load timed out")
i += 1
test.assertEqual(audio.get_sound_asset_status(prim), omni.usd.audio.AssetLoadStatus.DONE)
async def wait_for_prim_change(test, context, audio, prim):
await context.next_frame_async()
# the asset may reload, so we need to wait for it
wait_for_asset(test, audio, prim)
class TestStageAudioMinimal(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._context = omni.usd.get_context()
self.assertIsNotNone(self._context)
self._context.new_stage()
self._stage = self._context.get_stage()
self.assertIsNotNone(self._stage)
self._audio = omni.usd.audio.get_stage_audio_interface()
self.assertIsNotNone(self._audio)
async def test_hydra_plugin(self):
# check that the hydra plugin still works
self.assertTrue(omni.usd.audio.test_hydra_plugin(), "the hydra audio plugin failed to load")
async def test_device(self):
self._audio.set_device("default")
time.sleep(2.0)
self._audio.set_device("apple")
time.sleep(2.0)
self._audio.set_device("Speakers")
time.sleep(2.0)
async def test_set_doppler_default(self):
self._audio.set_doppler_default(omni.usd.audio.FeatureDefault.FORCE_OFF)
self.assertEqual(self._audio.get_doppler_default(), omni.usd.audio.FeatureDefault.FORCE_OFF)
self._audio.set_doppler_default()
self.assertEqual(self._audio.get_doppler_default(), omni.usd.audio.FeatureDefault.OFF)
# FIXME: This is just verifying that we can get/set this value.
# This test should somehow verify that this feature is actually
# detectable in the output audio.
async def test_set_distance_delay_default(self):
self._audio.set_distance_delay_default(omni.usd.audio.FeatureDefault.FORCE_OFF)
self.assertEqual(self._audio.get_distance_delay_default(), omni.usd.audio.FeatureDefault.FORCE_OFF)
self._audio.set_distance_delay_default()
self.assertEqual(self._audio.get_distance_delay_default(), omni.usd.audio.FeatureDefault.OFF)
# FIXME: This is just verifying that we can get/set this value.
# This test should somehow verify that this feature is actually
# detectable in the output audio.
async def test_set_interaural_delay_default(self):
self._audio.set_interaural_delay_default(omni.usd.audio.FeatureDefault.FORCE_OFF)
self.assertEqual(self._audio.get_interaural_delay_default(), omni.usd.audio.FeatureDefault.FORCE_OFF)
self._audio.set_interaural_delay_default()
self.assertEqual(self._audio.get_interaural_delay_default(), omni.usd.audio.FeatureDefault.OFF)
# FIXME: This is just verifying that we can get/set this value.
# This test should somehow verify that this feature is actually
# detectable in the output audio.
async def test_set_concurrent_voices(self):
self._audio.set_concurrent_voices(32)
self.assertEqual(self._audio.get_concurrent_voices(), 32)
self._audio.set_concurrent_voices()
self.assertEqual(self._audio.get_concurrent_voices(), 64)
# FIXME: This is just verifying that we can get/set this value.
# This test should somehow verify that this feature is actually
# detectable in the output audio.
async def test_speed_of_sound(self):
self._audio.set_speed_of_sound(120.0)
self.assertEqual(self._audio.get_speed_of_sound(), 120.0)
self._audio.set_speed_of_sound()
self.assertLess(abs(self._audio.get_speed_of_sound() - 340.0), 0.1)
# FIXME: This is just verifying that we can get/set this value.
# This test should somehow verify that this feature is actually
# detectable in the output audio.
async def test_doppler_scale(self):
self._audio.set_doppler_scale(4.0)
self.assertEqual(self._audio.get_doppler_scale(), 4.0)
self._audio.set_doppler_scale()
self.assertEqual(self._audio.get_doppler_scale(), 1.0)
# FIXME: This is just verifying that we can get/set this value.
# This test should somehow verify that this feature is actually
# detectable in the output audio.
async def test_doppler_limit(self):
self._audio.set_doppler_limit(4.0)
self.assertEqual(self._audio.get_doppler_limit(), 4.0)
self._audio.set_doppler_limit()
self.assertEqual(self._audio.get_doppler_limit(), 2.0)
# FIXME: This is just verifying that we can get/set this value.
# This test should somehow verify that this feature is actually
# detectable in the output audio.
async def test_spatial_time_scale(self):
self._audio.set_spatial_time_scale(4.0)
self.assertEqual(self._audio.get_spatial_time_scale(), 4.0)
self._audio.set_spatial_time_scale()
self.assertEqual(self._audio.get_spatial_time_scale(), 1.0)
# FIXME: This is just verifying that we can get/set this value.
# This test should somehow verify that this feature is actually
# detectable in the output audio.
async def test_nonspatial_time_scale(self):
self._audio.set_nonspatial_time_scale(4.0)
self.assertEqual(self._audio.get_nonspatial_time_scale(), 4.0)
self._audio.set_nonspatial_time_scale()
self.assertEqual(self._audio.get_nonspatial_time_scale(), 1.0)
# FIXME: This is just verifying that we can get/set this value.
# This test should somehow verify that this feature is actually
# detectable in the output audio.
async def test_get_metadata_change_stream(self):
callbacks = 0
event_type = None
def event_callback(event):
nonlocal event_type
nonlocal callbacks
event_type = event.type
callbacks += 1
def wait_for_callback(initial):
nonlocal callbacks
i = 0
while callbacks == initial:
time.sleep(0.001)
if i > 1000:
raise Exception("asset load timed out")
i += 1
self._events = self._audio.get_metadata_change_stream()
self.assertIsNotNone(self._events)
self._stage_event_sub = self._events.create_subscription_to_pop(
event_callback, name="stage audio test callback"
)
initial = callbacks
self._audio.set_doppler_default(omni.usd.audio.FeatureDefault.FORCE_OFF)
wait_for_callback(initial)
self.assertEqual(callbacks, initial + 1)
self.assertEqual(event_type, int(omni.usd.audio.EventType.METADATA_CHANGE))
# try the same thing twice to verify that the value needs to change to
# trigger a callback
initial = callbacks
self._audio.set_doppler_default(omni.usd.audio.FeatureDefault.FORCE_OFF)
try:
wait_for_callback(initial)
self.assertTrue(False)
except Exception:
pass
self.assertEqual(callbacks, initial)
initial = callbacks
self._audio.set_distance_delay_default(omni.usd.audio.FeatureDefault.FORCE_OFF)
wait_for_callback(initial)
self.assertEqual(callbacks, initial + 1)
self.assertEqual(event_type, int(omni.usd.audio.EventType.METADATA_CHANGE))
initial = callbacks
self._audio.set_interaural_delay_default(omni.usd.audio.FeatureDefault.FORCE_OFF)
wait_for_callback(initial)
self.assertEqual(callbacks, initial + 1)
self.assertEqual(event_type, int(omni.usd.audio.EventType.METADATA_CHANGE))
initial = callbacks
self._audio.set_concurrent_voices(32)
wait_for_callback(initial)
self.assertEqual(callbacks, initial + 1)
self.assertEqual(event_type, int(omni.usd.audio.EventType.METADATA_CHANGE))
initial = callbacks
self._audio.set_speed_of_sound(120.0)
wait_for_callback(initial)
self.assertEqual(callbacks, initial + 1)
self.assertEqual(event_type, int(omni.usd.audio.EventType.METADATA_CHANGE))
initial = callbacks
self._audio.set_doppler_scale(4.0)
wait_for_callback(initial)
self.assertEqual(callbacks, initial + 1)
self.assertEqual(event_type, int(omni.usd.audio.EventType.METADATA_CHANGE))
initial = callbacks
self._audio.set_doppler_limit(4.0)
wait_for_callback(initial)
self.assertEqual(callbacks, initial + 1)
self.assertEqual(event_type, int(omni.usd.audio.EventType.METADATA_CHANGE))
initial = callbacks
self._audio.set_spatial_time_scale(4.0)
wait_for_callback(initial)
self.assertEqual(callbacks, initial + 1)
self.assertEqual(event_type, int(omni.usd.audio.EventType.METADATA_CHANGE))
initial = callbacks
self._audio.set_nonspatial_time_scale(4.0)
wait_for_callback(initial)
self.assertEqual(callbacks, initial + 1)
self.assertEqual(event_type, int(omni.usd.audio.EventType.METADATA_CHANGE))
class TestStageAudio(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._context = omni.usd.get_context()
self.assertIsNotNone(self._context)
self._context.new_stage()
self._stage = self._context.get_stage()
self.assertIsNotNone(self._stage)
self._audio = omni.usd.audio.get_stage_audio_interface()
self.assertIsNotNone(self._audio)
extension_path = carb.tokens.get_tokens_interface().resolve("${omni.kit.audio.test.usd}")
self._test_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests").absolute()
self._golden_path = self._test_path.joinpath("golden")
self._prim_no_filename_path = "/sound_no_filename"
self._prim_no_filename = self._stage.DefinePrim(self._prim_no_filename_path, "Sound")
self.assertIsNotNone(self._prim_no_filename)
self._prim_bad_asset_path = "/sound_bad_asset"
self._prim_bad_asset = self._stage.DefinePrim(self._prim_bad_asset_path, "Sound")
self.assertIsNotNone(self._prim_bad_asset)
self._prim_bad_asset.GetAttribute("filePath").Set("/a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/x/y/z")
self._test_sound_1ch_path = self._test_path.joinpath("short-1ch.oga").absolute()
self._prim_1ch_path = "/sound_1ch"
self._prim_1ch = self._stage.DefinePrim(self._prim_1ch_path, "Sound")
self.assertIsNotNone(self._prim_1ch)
self._prim_1ch.GetAttribute("filePath").Set(str(self._test_sound_1ch_path))
self._test_sound_2ch_path = self._test_path.joinpath("short-2ch.oga").absolute()
self._prim_2ch_path = "/sound_2ch"
self._prim_2ch = self._stage.DefinePrim(self._prim_2ch_path, "Sound")
self.assertIsNotNone(self._prim_2ch)
self._prim_2ch.GetAttribute("filePath").Set(str(self._test_sound_2ch_path))
self._test_sound_long_path = self._test_path.joinpath("long.oga").absolute()
self._prim_long_path = "/sound_long"
self._prim_long = self._stage.DefinePrim(self._prim_long_path, "Sound")
self.assertIsNotNone(self._prim_long)
self._prim_long.GetAttribute("filePath").Set(str(self._test_sound_long_path))
wait_for_asset(self, self._audio, self._prim_1ch)
wait_for_asset(self, self._audio, self._prim_2ch)
wait_for_asset(self, self._audio, self._prim_long)
try:
os.mkdir(OUTPUTS_DIR)
except FileExistsError:
pass
async def tearDown(self):
self._stage.RemovePrim(self._prim_no_filename_path)
self._stage.RemovePrim(self._prim_bad_asset_path)
self._stage.RemovePrim(self._prim_1ch_path)
self._stage.RemovePrim(self._prim_2ch_path)
self._stage.RemovePrim(self._prim_long_path)
async def test_get_sound_count(self):
# sounds are only counted if they have a valid asset
self.assertEqual(self._audio.get_sound_count(), 3);
self._audio.draw_waveform(self._prim_no_filename, 1, 1)
self._audio.draw_waveform(self._prim_bad_asset, 1, 1)
self.assertEqual(self._audio.get_sound_count(), 5);
async def test_is_sound_playing(self):
self.assertFalse(self._audio.is_sound_playing(self._prim_long))
# the sound asset for this prim is silent, so the test shouldn't bother testers
# play the sound
self._audio.play_sound(self._prim_long)
self.assertTrue(self._audio.is_sound_playing(self._prim_long))
# stop the sound
self._audio.stop_sound(self._prim_long)
self.assertFalse(self._audio.is_sound_playing(self._prim_long))
# do it again, but use stop_all_sounds() instead
self._audio.play_sound(self._prim_long)
self.assertTrue(self._audio.is_sound_playing(self._prim_long))
self._audio.stop_all_sounds()
self.assertFalse(self._audio.is_sound_playing(self._prim_long))
# do it again but with spawn_voice()
voice = self._audio.spawn_voice(self._prim_long)
# the voice is not managed by IStageAudio
self.assertFalse(self._audio.is_sound_playing(self._prim_long))
self.assertTrue(voice.is_playing())
voice.stop()
self.assertFalse(voice.is_playing())
async def test_subscribe_to_asset_load(self):
loaded = False
def load_callback():
self.assertEqual(self._audio.get_sound_asset_status(self._prim_long), omni.usd.audio.AssetLoadStatus.DONE)
nonlocal loaded
loaded = True
# try it with something that's already loaded to ensure a callback will occur in this case
self.assertTrue(self._audio.subscribe_to_asset_load(self._prim_long, load_callback))
while not loaded:
time.sleep(0.001)
if i > 5000:
raise Exception("asset load timed out")
i += 1
# switch the file path and try again, so a load will actually be needed
self._prim_2ch.GetAttribute("filePath").Set(str(self._test_sound_2ch_path))
loaded = False
self.assertTrue(self._audio.subscribe_to_asset_load(self._prim_long, load_callback))
while not loaded:
time.sleep(0.001)
if i > 5000:
raise Exception("asset load timed out")
i += 1
async def test_draw_waveform(self):
# toggle in case you want to regenerate waveforms
GENERATE_GOLDEN_IMAGES = False
if GENERATE_GOLDEN_IMAGES:
print("!!!!! Golden images are being regenerated to '" + str(pathlib.Path(OUTPUTS_DIR)) + "'.")
print("!!!!! Once regenerated, these files should be copied to '" + str(self._golden_path) + "'.")
print("!!!!! Note: the `GENERATE_GOLDEN_IMAGES` variable being set to 'True' above should never be committed.")
W = 256
H = 256
BASE_NAME = "test_stage_audio.draw_waveform"
TEST_NAMES = [
BASE_NAME + ".1ch.USE_LINES.SPLIT_CHANNELS.png",
BASE_NAME + ".1ch.USE_LINES.SPLIT_CHANNELS.BACKGROUNDCOLOR.png",
BASE_NAME + ".2ch.USE_LINES.SPLIT_CHANNELS.png",
BASE_NAME + ".2ch.USE_LINES.SPLIT_CHANNELS.PARTIAL_COLOR.png",
BASE_NAME + ".2ch.USE_LINES.SPLIT_CHANNELS.COLOR.png",
BASE_NAME + ".1ch.USE_LINES.SPLIT_CHANNELS.MEDIA_OFFSET_START.png",
BASE_NAME + ".1ch.USE_LINES.SPLIT_CHANNELS.MEDIA_OFFSET_START.MEDIA_OFFSET_END.png",
BASE_NAME + ".1ch.png",
BASE_NAME + ".1ch.ALPHA_BLEND.png",
BASE_NAME + ".2ch.ch_2.png",
BASE_NAME + ".2ch.ALPHA_BLEND.MULTI_CHANNEL.png",
BASE_NAME + ".2ch.NOISE_COLOR.2bit.png",
]
raw = self._audio.draw_waveform(self._prim_no_filename, W, H)
self.assertEqual(len(raw), 0)
raw = self._audio.draw_waveform(self._prim_bad_asset, W, H)
self.assertEqual(len(raw), 0)
# render the mono waveform
raw = self._audio.draw_waveform(self._prim_1ch, W, H)
self.assertEqual(len(raw), W * H * 4)
with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img:
img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[0])))
if not GENERATE_GOLDEN_IMAGES:
self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare(
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[0]),
self._golden_path.joinpath(TEST_NAMES[0]),
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[0] + ".diff.png")),
0.1)
# render it with a custom background color
raw = self._audio.draw_waveform(self._prim_1ch, W, H, background = [1.0, 1.0, 1.0, 1.0])
self.assertEqual(len(raw), W * H * 4)
with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img:
img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[1])))
if not GENERATE_GOLDEN_IMAGES:
self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare(
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[1]),
self._golden_path.joinpath(TEST_NAMES[1]),
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[1] + ".diff.png")),
0.1)
# render the stereo waveform
raw = self._audio.draw_waveform(self._prim_2ch, W, H)
self.assertEqual(len(raw), W * H * 4)
with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img:
img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[2])))
if not GENERATE_GOLDEN_IMAGES:
self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare(
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[2]),
self._golden_path.joinpath(TEST_NAMES[2]),
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[2] + ".diff.png")),
0.1)
# add custom channel colors, but only set it for 4 channel to verify that the default still works
raw = self._audio.draw_waveform(self._prim_2ch, W, H, colors = [[1.0, 0, 1.0, 1.0]])
self.assertEqual(len(raw), W * H * 4)
with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img:
img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[3])))
if not GENERATE_GOLDEN_IMAGES:
self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare(
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[3]),
self._golden_path.joinpath(TEST_NAMES[3]),
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[3] + ".diff.png")),
0.1)
# try 2 custom channel colors now
raw = self._audio.draw_waveform(self._prim_2ch, W, H, colors = [[1.0, 0, 0, 1.0], [0, 0, 1.0, 1.0]])
self.assertEqual(len(raw), W * H * 4)
with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img:
img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[4])))
if not GENERATE_GOLDEN_IMAGES:
self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare(
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[4]),
self._golden_path.joinpath(TEST_NAMES[4]),
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[4] + ".diff.png")),
0.1)
# this sound asset is 0.693 seconds, so 0.2 is substantial
self._prim_1ch.GetAttribute("mediaOffsetStart").Set(0.2);
await wait_for_prim_change(self, self._context, self._audio, self._prim_1ch)
raw = self._audio.draw_waveform(self._prim_1ch, W, H)
self.assertEqual(len(raw), W * H * 4)
with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img:
img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[5])))
if not GENERATE_GOLDEN_IMAGES:
self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare(
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[5]),
self._golden_path.joinpath(TEST_NAMES[5]),
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[5] + ".diff.png")),
0.1)
self._prim_1ch.GetAttribute("mediaOffsetEnd").Set(0.4);
await wait_for_prim_change(self, self._context, self._audio, self._prim_1ch)
raw = self._audio.draw_waveform(self._prim_1ch, W, H)
self.assertEqual(len(raw), W * H * 4)
with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img:
img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[6])))
if not GENERATE_GOLDEN_IMAGES:
self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare(
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[6]),
self._golden_path.joinpath(TEST_NAMES[6]),
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[6] + ".diff.png")),
0.1)
# reset prim parameters
self._prim_1ch.GetAttribute("mediaOffsetStart").Set(0.0);
self._prim_1ch.GetAttribute("mediaOffsetEnd").Set(0.0);
await wait_for_prim_change(self, self._context, self._audio, self._prim_1ch)
# test it with no flags
raw = self._audio.draw_waveform(self._prim_1ch, W, H, flags = 0)
self.assertEqual(len(raw), W * H * 4)
with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img:
img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[7])))
if not GENERATE_GOLDEN_IMAGES:
self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare(
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[7]),
self._golden_path.joinpath(TEST_NAMES[7]),
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[7] + ".diff.png")),
0.1)
# test it with alpha blending
raw = self._audio.draw_waveform(self._prim_1ch, W, H, flags = carb.audio.AUDIO_IMAGE_FLAG_ALPHA_BLEND, colors = [[1.0, 1.0, 1.0, 0.2]])
self.assertEqual(len(raw), W * H * 4)
with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img:
img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[8])))
if not GENERATE_GOLDEN_IMAGES:
self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare(
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[8]),
self._golden_path.joinpath(TEST_NAMES[8]),
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[8] + ".diff.png")),
0.1)
# test choosing the second channel in a multi-channel image
raw = self._audio.draw_waveform(self._prim_2ch, W, H, flags = 0, channel = 1)
self.assertEqual(len(raw), W * H * 4)
with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img:
img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[9])))
if not GENERATE_GOLDEN_IMAGES:
self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare(
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[9]),
self._golden_path.joinpath(TEST_NAMES[9]),
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[9] + ".diff.png")),
0.1)
# test choosing the second channel in a multi-channel image
raw = self._audio.draw_waveform(self._prim_2ch, W, H, flags = carb.audio.AUDIO_IMAGE_FLAG_MULTI_CHANNEL | carb.audio.AUDIO_IMAGE_FLAG_ALPHA_BLEND, colors = [[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]])
self.assertEqual(len(raw), W * H * 4)
with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img:
img.convert("RGB").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[10])))
if not GENERATE_GOLDEN_IMAGES:
self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare(
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[10]),
self._golden_path.joinpath(TEST_NAMES[10]),
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[10] + ".diff.png")),
0.1)
# the colors are going to be random, so turn all the pixels to white before comparing
raw = self._audio.draw_waveform(self._prim_2ch, W, H, flags = carb.audio.AUDIO_IMAGE_FLAG_NOISE_COLOR)
self.assertEqual(len(raw), W * H * 4)
with Image.frombytes("RGBX", (W, H), bytes(raw), 'raw') as img:
# increase contrast by a factor of 256.0
ImageEnhance.Contrast(img.convert("RGB")).enhance(256.0).convert("1").save(str(pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[11])))
if not GENERATE_GOLDEN_IMAGES:
self.assertLess(omni.kit.test_helpers_gfx.compare_utils.compare(
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[11]),
self._golden_path.joinpath(TEST_NAMES[11]),
pathlib.Path(OUTPUTS_DIR).joinpath(TEST_NAMES[11] + ".diff.png")),
2.0)
# this won't crash or fail, but which flag is chosen is undefined
raw = self._audio.draw_waveform(self._prim_2ch, W, H, flags = carb.audio.AUDIO_IMAGE_FLAG_MULTI_CHANNEL | carb.audio.AUDIO_IMAGE_FLAG_SPLIT_CHANNELS)
self.assertEqual(len(raw), W * H * 4)
async def test_sound_length(self):
FUZZ = 0.00001
ASSET_LENGTH = 120.0
self.assertLess(abs(self._audio.get_sound_length(self._prim_long) - ASSET_LENGTH), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.PLAY_LENGTH) - ASSET_LENGTH), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.SOUND_LENGTH) - ASSET_LENGTH), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.ASSET_LENGTH) - ASSET_LENGTH), FUZZ);
# start time shouldn't change anything
self._prim_long.GetAttribute("startTime").Set(12.0);
await wait_for_prim_change(self, self._context, self._audio, self._prim_long)
self.assertLess(abs(self._audio.get_sound_length(self._prim_long) - ASSET_LENGTH), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.PLAY_LENGTH) - ASSET_LENGTH), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.SOUND_LENGTH) - ASSET_LENGTH), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.ASSET_LENGTH) - ASSET_LENGTH), FUZZ);
# end time that exceeds the asset length shouldn't change anything
self._prim_long.GetAttribute("endTime").Set(ASSET_LENGTH + 20.0);
await wait_for_prim_change(self, self._context, self._audio, self._prim_long)
self.assertLess(abs(self._audio.get_sound_length(self._prim_long) - ASSET_LENGTH), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.PLAY_LENGTH) - ASSET_LENGTH), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.SOUND_LENGTH) - ASSET_LENGTH), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.ASSET_LENGTH) - ASSET_LENGTH), FUZZ);
# end time 6 seconds after start time
self._prim_long.GetAttribute("endTime").Set(18.0);
await wait_for_prim_change(self, self._context, self._audio, self._prim_long)
self.assertLess(abs(self._audio.get_sound_length(self._prim_long) - 6.0), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.PLAY_LENGTH) - 6.0), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.SOUND_LENGTH) - ASSET_LENGTH), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.ASSET_LENGTH) - ASSET_LENGTH), FUZZ);
# trim the audio track itself
start_trim = 30.0
trimmed_length = ASSET_LENGTH - start_trim
self._prim_long.GetAttribute("mediaOffsetStart").Set(start_trim);
await wait_for_prim_change(self, self._context, self._audio, self._prim_long)
self.assertLess(abs(self._audio.get_sound_length(self._prim_long) - 6.0), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.PLAY_LENGTH) - 6.0), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.SOUND_LENGTH) - trimmed_length), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.ASSET_LENGTH) - ASSET_LENGTH), FUZZ);
# excessive end offset has no effect
self._prim_long.GetAttribute("mediaOffsetEnd").Set(ASSET_LENGTH + 1.0);
await wait_for_prim_change(self, self._context, self._audio, self._prim_long)
self.assertLess(abs(self._audio.get_sound_length(self._prim_long) - 6.0), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.PLAY_LENGTH) - 6.0), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.SOUND_LENGTH) - trimmed_length), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.ASSET_LENGTH) - ASSET_LENGTH), FUZZ);
end_trim = 32.0
trimmed_length = end_trim - start_trim
# use a real trim now
self._prim_long.GetAttribute("mediaOffsetEnd").Set(end_trim);
await wait_for_prim_change(self, self._context, self._audio, self._prim_long)
self.assertLess(abs(self._audio.get_sound_length(self._prim_long) - trimmed_length), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.PLAY_LENGTH) - trimmed_length), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.SOUND_LENGTH) - trimmed_length), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.ASSET_LENGTH) - ASSET_LENGTH), FUZZ);
# speed it up by a factor of 2
self._prim_long.GetAttribute("timeScale").Set(2.0);
await wait_for_prim_change(self, self._context, self._audio, self._prim_long)
self.assertLess(abs(self._audio.get_sound_length(self._prim_long) - trimmed_length / 2), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.PLAY_LENGTH) - trimmed_length / 2), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.SOUND_LENGTH) - trimmed_length / 2), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.ASSET_LENGTH) - ASSET_LENGTH), FUZZ);
# try adding a loop count to double the time now
self._prim_long.GetAttribute("loopCount").Set(1);
self._prim_long.GetAttribute("timeScale").Set(1.0);
await wait_for_prim_change(self, self._context, self._audio, self._prim_long)
self.assertLess(abs(self._audio.get_sound_length(self._prim_long) - 2 * trimmed_length), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.PLAY_LENGTH) - 2 * trimmed_length), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.SOUND_LENGTH) - trimmed_length), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.ASSET_LENGTH) - ASSET_LENGTH), FUZZ);
# try looping infinitely and remove end time
self._prim_long.GetAttribute("loopCount").Set(-1);
self._prim_long.GetAttribute("endTime").Set(-1.0);
await wait_for_prim_change(self, self._context, self._audio, self._prim_long)
# check that it's some enormous number
self.assertGreater(self._audio.get_sound_length(self._prim_long), 2**24);
self.assertGreater(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.PLAY_LENGTH), 2**24);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.SOUND_LENGTH) - trimmed_length), FUZZ);
self.assertLess(abs(self._audio.get_sound_length(self._prim_long, omni.usd.audio.SoundLengthType.ASSET_LENGTH) - ASSET_LENGTH), FUZZ);
class TestCaptureStreamer(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
extension_path = carb.tokens.get_tokens_interface().resolve("${omni.kit.audio.test.usd}")
self._usd_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests").absolute()
from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget
import omni.kit.window.property as p
self._w = p.get_window()
try:
os.mkdir(OUTPUTS_DIR)
except FileExistsError:
pass
async def test_capture_streamer(self):
# ****** test setup ******
audio = omni.usd.audio.get_stage_audio_interface()
self.assertIsNotNone(audio)
usd_context = omni.usd.get_context()
self.assertIsNotNone(usd_context)
# load a test stage that has some audio prims in it.
test_file_path = self._usd_path.joinpath("audio_test.usda").absolute()
await usd_context.open_stage_async(str(test_file_path))
await omni.kit.app.get_app().next_update_async()
# ****** create and setup the streamers ******
# create a streamer to capture the audio from the stage.
streamer = audio.create_capture_streamer()
self.assertNotEqual(streamer, audio.INVALID_STREAMER_ID)
streamer2 = audio.create_capture_streamer()
self.assertNotEqual(streamer2, audio.INVALID_STREAMER_ID)
self.assertNotEqual(streamer, streamer2)
streamer3 = audio.create_capture_streamer()
self.assertNotEqual(streamer3, audio.INVALID_STREAMER_ID)
self.assertNotEqual(streamer, streamer3)
serial = random.randrange(2**32)
def gen_name(name):
return str(OUTPUTS_DIR.joinpath(str(serial) + "-" + name))
audio.set_capture_filename(streamer, gen_name("streamer1.wav"))
audio.set_capture_filename(streamer2, gen_name("streamer2.wav"))
# intentionally don't set the filename for streamer3.
# ****** test some captures ******
# perform a capture on a single streamer with an overridden filename.
success = audio.start_capture(streamer, gen_name("streamer3.wav"))
self.assertTrue(success)
await asyncio.sleep(0.5)
success = audio.stop_capture(streamer)
self.assertTrue(success)
self.assertTrue(audio.wait_for_capture(streamer, 10000))
self.assertTrue(os.path.exists(gen_name("streamer3.wav")))
self.assertTrue(os.path.isfile(gen_name("streamer3.wav")))
self.assertFalse(os.path.exists(gen_name("streamer1.wav")))
self.assertFalse(os.path.exists(gen_name("streamer2.wav")))
streamer3_mtime = os.path.getmtime(gen_name("streamer3.wav"))
await asyncio.sleep(0.5)
self.assertEqual(streamer3_mtime, os.path.getmtime(gen_name("streamer3.wav")))
# perform a capture on multiple streamers simultaneously.
success = audio.start_captures([streamer, streamer2])
self.assertTrue(success)
await asyncio.sleep(0.5)
success = audio.stop_captures([streamer2, streamer])
self.assertTrue(success)
self.assertTrue(audio.wait_for_capture(streamer, 10000))
self.assertTrue(audio.wait_for_capture(streamer2, 10000))
self.assertTrue(os.path.exists(gen_name("streamer1.wav")))
self.assertTrue(os.path.exists(gen_name("streamer2.wav")))
self.assertTrue(os.path.isfile(gen_name("streamer1.wav")))
self.assertTrue(os.path.isfile(gen_name("streamer2.wav")))
# streamer3 shouldn't have been modified
self.assertEqual(streamer3_mtime, os.path.getmtime(gen_name("streamer3.wav")))
streamer1_mtime = os.path.getmtime(gen_name("streamer1.wav"))
streamer2_mtime = os.path.getmtime(gen_name("streamer2.wav"))
# perform a capture on multiple streamers simultaneously where one has not had a filename set.
audio.set_capture_filename(streamer, gen_name("streamer4.wav"))
success = audio.start_captures([streamer, streamer3])
self.assertTrue(success)
await asyncio.sleep(0.5)
success = audio.stop_captures([streamer3, streamer])
self.assertTrue(audio.wait_for_capture(streamer3, 10000))
self.assertTrue(audio.wait_for_capture(streamer, 10000))
self.assertTrue(os.path.exists(gen_name("streamer4.wav")))
self.assertEqual(streamer1_mtime, os.path.getmtime(gen_name("streamer1.wav")))
self.assertEqual(streamer2_mtime, os.path.getmtime(gen_name("streamer2.wav")))
self.assertTrue(os.path.isfile(gen_name("streamer4.wav")))
self.assertEqual(streamer3_mtime, os.path.getmtime(gen_name("streamer3.wav")))
# start a capture while another streamer is already running.
audio.set_capture_filename(streamer, gen_name("streamer5.wav"))
audio.set_capture_filename(streamer2, gen_name("streamer6.wav"))
success = audio.start_capture(streamer, None)
self.assertTrue(success)
await asyncio.sleep(0.5)
success = audio.start_captures([streamer2])
self.assertTrue(success)
await asyncio.sleep(0.5)
success = audio.stop_captures([streamer2, streamer])
self.assertTrue(audio.wait_for_capture(streamer, 10000))
self.assertTrue(audio.wait_for_capture(streamer2, 10000))
self.assertTrue(os.path.exists(gen_name("streamer5.wav")))
self.assertTrue(os.path.exists(gen_name("streamer6.wav")))
self.assertTrue(os.path.isfile(gen_name("streamer5.wav")))
self.assertTrue(os.path.isfile(gen_name("streamer6.wav")))
# start a capture on an invalid filename.
success = audio.start_capture(streamer, "path/does/not/exist/streamer7.wav")
self.assertFalse(success)
if success:
await asyncio.sleep(0.5)
success = audio.stop_capture(streamer)
self.assertFalse(success)
self.assertFalse(os.path.exists("path/does/not/exist/streamer7.wav"))
success = audio.set_capture_filename(streamer, "other/bad/path/streamer.wav")
self.assertFalse(success)
success = audio.set_capture_filename(streamer, "other/bad/path")
self.assertFalse(success)
success = audio.set_capture_filename(streamer, "")
self.assertFalse(success)
# try starting the streamer before destroying them
success = audio.start_capture(streamer2, None)
self.assertTrue(success)
await asyncio.sleep(0.5)
# ****** clean up ******
# destroy the streamers.
audio.destroy_capture_streamer(streamer)
audio.destroy_capture_streamer(streamer2)
audio.destroy_capture_streamer(streamer3)
# try starting a capture on a destroyed streamer.
success = audio.start_capture(streamer, gen_name("streamer8.wav"))
self.assertFalse(success)
self.assertFalse(os.path.exists(gen_name("streamer8.wav")))
success = audio.start_capture(streamer2, gen_name("streamer9.wav"))
self.assertFalse(success)
self.assertFalse(os.path.exists(gen_name("streamer9.wav")))
# Need to wait for an additional frames for omni.ui rebuild to take effect
await wait_stage_loading()
await usd_context.new_stage_async()
await omni.kit.app.get_app().next_update_async()
class TestCaptureEvents(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._context = omni.usd.get_context()
self.assertIsNotNone(self._context)
await self._context.new_stage_async()
self._stage = self._context.get_stage()
self.assertIsNotNone(self._stage)
self._audio = omni.usd.audio.get_stage_audio_interface()
self.assertIsNotNone(self._audio)
extension_path = carb.tokens.get_tokens_interface().resolve("${omni.kit.audio.test.usd}")
self._test_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests").absolute()
self._test_sound_1ch_path = self._test_path.joinpath("short-1ch.oga").absolute()
self._prim_1ch_path = "/sound_1ch"
self._prim_1ch = self._stage.DefinePrim(self._prim_1ch_path, "Sound")
self.assertIsNotNone(self._prim_1ch)
self._prim_1ch.GetAttribute("filePath").Set(str(self._test_sound_1ch_path))
self._prim_1ch.GetAttribute("startTime").Set(-1.0)
self._streamer = self._audio.create_capture_streamer()
self.assertNotEqual(self._streamer, omni.usd.audio.INVALID_STREAMER_ID)
async def tearDown(self):
self._audio.destroy_capture_streamer(self._streamer)
async def test_capture_events(self):
fmt = None
open_count = 0
close_count = 0
data = []
def open_impl(stream_fmt):
nonlocal fmt
nonlocal open_count
fmt = stream_fmt
open_count += 1
def write_impl(stream_data):
nonlocal data
data += stream_data
def close_impl():
nonlocal close_count
close_count += 1
events = self._audio.create_event_stream_for_capture(self._streamer)
self.assertIsNotNone(events)
self.assertTrue(events)
# create the listener in the middle of the stream and verify that nothing
# is actually produced
self._audio.start_capture(self._streamer)
await asyncio.sleep(0.2)
listener = omni.usd.audio.StreamListener(events, open_impl, write_impl, close_impl)
self.assertIsNotNone(listener)
self._audio.stop_capture(self._streamer)
await asyncio.sleep(0.2)
self.assertIsNone(fmt)
self.assertEqual(open_count, 0);
self.assertEqual(close_count, 0);
self.assertEqual(len(data), 0);
# this time, it should actually do something
self._audio.start_capture(self._streamer)
await asyncio.sleep(0.2)
self.assertEqual(open_count, 1);
self.assertIsNotNone(fmt)
self.assertEqual(close_count, 0);
self.assertGreater(len(data), 0);
self._audio.stop_capture(self._streamer)
await asyncio.sleep(0.2)
self.assertEqual(open_count, 1);
self.assertIsNotNone(fmt)
self.assertEqual(close_count, 1);
self.assertGreater(len(data), 0);
# check that nothing was played
silence = 0
if fmt.format == carb.audio.SampleFormat.PCM8:
silence = 127
for v in data:
self.assertEqual(v, silence);
# this time we'll actually play a sound with it
data = []
self._audio.start_capture(self._streamer)
await asyncio.sleep(0.1)
voice = self._audio.spawn_voice(self._prim_1ch)
i = 0
while voice.is_playing():
await asyncio.sleep(0.01)
i += 1
if (i == 2000):
self.assertFalse("test timed out")
self._audio.stop_capture(self._streamer)
await asyncio.sleep(0.2)
self.assertEqual(open_count, 2);
self.assertIsNotNone(fmt)
self.assertEqual(close_count, 2);
self.assertGreater(len(data), 0);
silent = True
for v in data:
if v != silence:
silent = False
break
self.assertFalse(silent)
class TestListenerEnum(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
extension_path = carb.tokens.get_tokens_interface().resolve("${omni.kit.audio.test.usd}")
self._usd_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests").absolute()
from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget
import omni.kit.window.property as p
self._w = p.get_window()
async def test_listener_enum(self):
# ****** test setup ******
audio = omni.usd.audio.get_stage_audio_interface()
self.assertIsNotNone(audio)
usd_context = omni.usd.get_context()
self.assertIsNotNone(usd_context)
# load a test stage that has some audio prims in it.
test_file_path = self._usd_path.joinpath("audio_test2.usda").absolute()
await usd_context.open_stage_async(str(test_file_path))
await omni.kit.app.get_app().next_update_async()
await wait_stage_loading()
# ****** try some bad parameters ******
count = audio.get_listener_count()
self.assertNotEqual(count, 0)
# try an out of range index. Note that we can't try a negative number here because
# pybind freaks out and throws a TypeError exception because it doesn't match the
# `size_t` argument.
prim = audio.get_listener_by_index(count)
self.assertIsNone(prim)
prim = audio.get_listener_by_index(count + 1)
self.assertIsNone(prim)
prim = audio.get_listener_by_index(count + 20000)
self.assertIsNone(prim)
prim = audio.get_listener_by_index(count - 1)
self.assertIsNotNone(prim)
prim = None
# ****** enumerate the stage listeners ******
count = audio.get_listener_count()
self.assertNotEqual(count, 0)
for i in range(0, count):
prim = audio.get_listener_by_index(i)
self.assertIsNotNone(prim)
# Need to wait for an additional frames for omni.ui rebuild to take effect
await wait_stage_loading()
await usd_context.new_stage_async()
await omni.kit.app.get_app().next_update_async()
class TestStageAudioListeners(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._context = omni.usd.get_context()
self.assertIsNotNone(self._context)
self._context.new_stage()
self._stage = self._context.get_stage()
self.assertIsNotNone(self._stage)
self._audio = omni.usd.audio.get_stage_audio_interface()
self.assertIsNotNone(self._audio)
extension_path = carb.tokens.get_tokens_interface().resolve("${omni.kit.audio.test.usd}")
self._prim_path = "/listener"
self._prim = self._stage.DefinePrim(self._prim_path, "Listener")
self.assertIsNotNone(self._prim)
await self._context.next_frame_async()
async def tearDown(self):
self._stage.RemovePrim(self._prim_path)
async def test_get_listener_count(self):
self.assertEqual(self._audio.get_listener_count(), 1)
self._new_prim_path = "/listener1"
self._new_prim = self._stage.DefinePrim(self._new_prim_path, "Listener")
await self._context.next_frame_async()
self.assertEqual(self._audio.get_listener_count(), 2)
self._stage.RemovePrim(self._new_prim_path)
async def test_set_active_listener(self):
self.assertIsNone(self._audio.get_active_listener())
self._new_prim_path = "/sound"
self._new_prim = self._stage.DefinePrim(self._new_prim_path, "Sound")
await self._context.next_frame_async()
self.assertFalse(self._audio.set_active_listener(self._new_prim))
self._stage.RemovePrim(self._new_prim_path)
self.assertTrue(self._audio.set_active_listener(self._prim))
self.assertEqual(self._audio.get_active_listener(), self._prim)
self.assertTrue(self._audio.set_active_listener(None))
self.assertIsNone(self._audio.get_active_listener())
# FIXME: This is just verifying that we can get/set this value.
# This test should somehow verify that this feature is actually
# detectable in the output audio.
async def test_get_listener_by_index(self):
# full enumeration of the 1 sound in the scene
self.assertEqual(self._audio.get_listener_by_index(0), self._prim)
self.assertIsNone(self._audio.get_listener_by_index(1))
| 49,917 | Python | 44.421292 | 209 | 0.638861 |
omniverse-code/kit/exts/omni.kit.audio.test.usd/omni/kit/audio/test/usd/tests/__init__.py | from .test_audio import *
| 26 | Python | 12.499994 | 25 | 0.730769 |
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/ogn/OgnScaleAOVTextureInPlaceDatabase.py | """Support for simplified access to data on nodes of type omni.graph.rtxtest.ScaleAOVTextureInPlace
Test node for the post render graph, to scale (brighten or darken) an AOV texture in place.
"""
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnScaleAOVTextureInPlaceDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.rtxtest.ScaleAOVTextureInPlace
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.exec
inputs.gpu
inputs.height
inputs.inputAOV
inputs.multiplier
inputs.rp
inputs.width
Outputs:
outputs.exec
outputs.gpu
outputs.outputAOVPtr
outputs.rp
outputs.scheduleResult
"""
# Imprint the generator and target ABI versions in the file for JIT generation
GENERATOR_VERSION = (1, 41, 3)
TARGET_VERSION = (2, 139, 12)
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''),
('inputs:gpu', 'uint64', 0, 'gpuFoundations', 'Pointer to shared context containing gpu foundations', {}, True, 0, False, ''),
('inputs:height', 'int', 0, None, 'The output RP height', {ogn.MetadataKeys.DEFAULT: '1080'}, True, 1080, False, ''),
('inputs:inputAOV', 'token', 0, None, 'The name of the AOV used during processing', {ogn.MetadataKeys.DEFAULT: '"LdrColor"'}, True, "LdrColor", False, ''),
('inputs:multiplier', 'float', 0, None, 'Multiplier applied on the inputAOV to obtain the output', {ogn.MetadataKeys.DEFAULT: '1.0'}, True, 1.0, False, ''),
('inputs:rp', 'uint64', 0, 'renderProduct', 'Pointer to render product for this view', {}, True, 0, False, ''),
('inputs:width', 'int', 0, None, 'The output RP width', {ogn.MetadataKeys.DEFAULT: '1920'}, True, 1920, False, ''),
('outputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''),
('outputs:gpu', 'uint64', 0, 'gpuFoundations', 'Pointer to shared context containing gpu foundations', {}, True, None, False, ''),
('outputs:outputAOVPtr', 'uint64', 0, None, 'The output AOV cuda pointer', {}, True, None, False, ''),
('outputs:rp', 'uint64', 0, 'renderProduct', 'Pointer to render product for this view', {}, True, None, False, ''),
('outputs:scheduleResult', 'bool', 0, None, 'If set, the cuda task was scheduled, otherwise it was not.', {}, True, None, False, ''),
])
@classmethod
def _populate_role_data(cls):
"""Populate a role structure with the non-default roles on this node type"""
role_data = super()._populate_role_data()
role_data.inputs.exec = og.AttributeRole.EXECUTION
role_data.outputs.exec = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = []
self._batchedReadValues = []
@property
def exec(self):
data_view = og.AttributeValueHelper(self._attributes.exec)
return data_view.get()
@exec.setter
def exec(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.exec)
data_view = og.AttributeValueHelper(self._attributes.exec)
data_view.set(value)
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._attributes.gpu)
return data_view.get()
@gpu.setter
def gpu(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.gpu)
data_view = og.AttributeValueHelper(self._attributes.gpu)
data_view.set(value)
@property
def height(self):
data_view = og.AttributeValueHelper(self._attributes.height)
return data_view.get()
@height.setter
def height(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.height)
data_view = og.AttributeValueHelper(self._attributes.height)
data_view.set(value)
@property
def inputAOV(self):
data_view = og.AttributeValueHelper(self._attributes.inputAOV)
return data_view.get()
@inputAOV.setter
def inputAOV(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.inputAOV)
data_view = og.AttributeValueHelper(self._attributes.inputAOV)
data_view.set(value)
@property
def multiplier(self):
data_view = og.AttributeValueHelper(self._attributes.multiplier)
return data_view.get()
@multiplier.setter
def multiplier(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.multiplier)
data_view = og.AttributeValueHelper(self._attributes.multiplier)
data_view.set(value)
@property
def rp(self):
data_view = og.AttributeValueHelper(self._attributes.rp)
return data_view.get()
@rp.setter
def rp(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.rp)
data_view = og.AttributeValueHelper(self._attributes.rp)
data_view.set(value)
@property
def width(self):
data_view = og.AttributeValueHelper(self._attributes.width)
return data_view.get()
@width.setter
def width(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.width)
data_view = og.AttributeValueHelper(self._attributes.width)
data_view.set(value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = { }
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedWriteValues = { }
@property
def exec(self):
data_view = og.AttributeValueHelper(self._attributes.exec)
return data_view.get()
@exec.setter
def exec(self, value):
data_view = og.AttributeValueHelper(self._attributes.exec)
data_view.set(value)
@property
def gpu(self):
data_view = og.AttributeValueHelper(self._attributes.gpu)
return data_view.get()
@gpu.setter
def gpu(self, value):
data_view = og.AttributeValueHelper(self._attributes.gpu)
data_view.set(value)
@property
def outputAOVPtr(self):
data_view = og.AttributeValueHelper(self._attributes.outputAOVPtr)
return data_view.get()
@outputAOVPtr.setter
def outputAOVPtr(self, value):
data_view = og.AttributeValueHelper(self._attributes.outputAOVPtr)
data_view.set(value)
@property
def rp(self):
data_view = og.AttributeValueHelper(self._attributes.rp)
return data_view.get()
@rp.setter
def rp(self, value):
data_view = og.AttributeValueHelper(self._attributes.rp)
data_view.set(value)
@property
def scheduleResult(self):
data_view = og.AttributeValueHelper(self._attributes.scheduleResult)
return data_view.get()
@scheduleResult.setter
def scheduleResult(self, value):
data_view = og.AttributeValueHelper(self._attributes.scheduleResult)
data_view.set(value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnScaleAOVTextureInPlaceDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnScaleAOVTextureInPlaceDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnScaleAOVTextureInPlaceDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 10,784 | Python | 42.14 | 164 | 0.629915 |
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/tests/test_viewport_nodes.py | """test viewport nodes"""
import asyncio
import inspect
import pathlib
import carb.input
import omni.graph.core as og
import omni.usd
from omni.kit.ui_test.input import emulate_keyboard_press
from omni.rtx.tests import RtxTest, postLoadTestSettings, testSettings
from omni.rtx.tests.test_common import wait_for_update
from omni.ui.tests.compare_utils import CompareMetric, capture_and_compare
from pxr import UsdGeom
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
GOLDEN_IMG_DIR = EXTENSION_FOLDER_PATH.joinpath("omni/graph/rtxtest/tests/data/golden")
# ======================================================================
class TestViewportNodes(RtxTest):
def __init__(self, tests=()):
super().__init__(tests)
self.test_graph_path = "/World/TestGraph"
async def setUp(self):
await super().setUp()
self.set_settings(testSettings)
omni.usd.get_context().new_stage()
self.add_dir_light()
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadTestSettings)
async def tearDown(self):
await super().tearDown()
await omni.kit.stage_templates.new_stage_async()
@property
def __test_name(self) -> str:
"""
The full name of the test.
It has the name of the module, class and the current test function. We use the stack to get the name of the test
function and since it's only called from create_test_window and finalize_test, we get the third member.
"""
return f"{self.__module__}.{self.__class__.__name__}.{inspect.stack()[2][3]}"
async def capture_and_compare(self, image_name: str, threshold=RtxTest.THRESHOLD, cmp_metric=CompareMetric.MEAN_ERROR_SQUARED):
"""
RtxTest.capture_and_compare() captures directly from the viewport's texture, however,
we need to capture from the swap chain in order to take into account the overlay image
that hides the current frame during viewport render lock.
"""
diff = await capture_and_compare(image_name, threshold, GOLDEN_IMG_DIR, True, cmp_metric)
if diff != 0:
carb.log_warn(f"[{self.__test_name}] the generated image {image_name} has max difference {diff}")
if diff >= threshold:
self._failedImages.append(image_name)
return diff
def create_mesh(self, name):
"""Create a cube mesh"""
cube = UsdGeom.Mesh.Define(self.ctx.get_stage(), name)
cube.CreatePointsAttr(
[
(-50, -50, -50),
(50, -50, -50),
(-50, -50, 50),
(50, -50, 50),
(-50, 50, -50),
(50, 50, -50),
(50, 50, 50),
(-50, 50, 50),
]
)
cube.CreateFaceVertexCountsAttr([4, 4, 4, 4, 4, 4])
cube.CreateFaceVertexIndicesAttr([0, 1, 3, 2, 0, 4, 5, 1, 1, 5, 6, 3, 2, 3, 6, 7, 0, 2, 7, 4, 4, 7, 6, 5])
cube.CreateSubdivisionSchemeAttr("none")
return cube
async def test_lock_viewport_render(self):
"""Validate viewport render lock & unlock for OgnLockViewportRender"""
# create a cube mesh
cube = self.create_mesh("/World/cube")
# create action graph
controller = og.Controller()
graph = controller.create_graph({"graph_path": self.test_graph_path, "evaluator_name": "execution"})
controller.edit(
graph,
{
og.Controller.Keys.CREATE_NODES: [
("on_keyboard_input_l", "omni.graph.action.OnKeyboardInput"),
("on_keyboard_input_u", "omni.graph.action.OnKeyboardInput"),
("lock_viewport_render", "omni.graph.ui_nodes.LockViewportRender"),
],
og.Controller.Keys.CONNECT: [
("on_keyboard_input_l.outputs:released", "lock_viewport_render.inputs:lock"),
("on_keyboard_input_u.outputs:released", "lock_viewport_render.inputs:unlock"),
],
og.Controller.Keys.SET_VALUES: [
("on_keyboard_input_l.inputs:keyIn", "L"),
("on_keyboard_input_l.inputs:onlyPlayback", False),
("on_keyboard_input_u.inputs:keyIn", "U"),
("on_keyboard_input_u.inputs:onlyPlayback", False),
],
},
)
# Initial
await wait_for_update(self.ctx)
await self.capture_and_compare("test_lock_viewport_render.initial.png")
# Lock viewport render
await emulate_keyboard_press(carb.input.KeyboardInput.L)
await wait_for_update(self.ctx)
await self.capture_and_compare("test_lock_viewport_render.locked.png")
# Scale the cube
scale_op = UsdGeom.Xformable(cube).AddScaleOp()
scale = 2.0
scale_op.Set((scale, scale, scale))
await wait_for_update(self.ctx)
await self.capture_and_compare("test_lock_viewport_render.scaled.png")
# Unlock viewport render and wait for the fading duration (1 second by default) to complete
await emulate_keyboard_press(carb.input.KeyboardInput.U)
await asyncio.sleep(1.1)
await self.capture_and_compare("test_lock_viewport_render.unlocked.png")
# Lock viewport render and scale the cube again
await emulate_keyboard_press(carb.input.KeyboardInput.L)
scale = 3.0
scale_op.Set((scale, scale, scale))
await wait_for_update(self.ctx)
await self.capture_and_compare("test_lock_viewport_render.relocked.png")
# Remove the node. The viewport render will be automatically unlocked.
controller.edit(graph, { og.Controller.Keys.DELETE_NODES: "lock_viewport_render" })
await wait_for_update(self.ctx)
await self.capture_and_compare("test_lock_viewport_render.removed.png")
| 6,018 | Python | 38.339869 | 131 | 0.601695 |
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/tests/test_post_render_graph.py | """Tests for the post render graph scaffolding APIs"""
import carb
import inspect
import pathlib
import omni.graph.core as og
import omni.graph.core.tests as ogts
import omni.hydratexture
from omni.kit.viewport.utility import get_active_viewport
import omni.kit.test
from omni.kit.test_helpers_gfx.compare_utils import finalize_capture_and_compare, ComparisonMetric
from omni.rtx.tests import RtxTest, postLoadTestSettings, testSettings, OUTPUTS_DIR
from omni.rtx.tests.test_common import wait_for_update
from pxr import Gf, Sdf, Usd, UsdGeom
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
GOLDEN_DIR = EXTENSION_FOLDER_PATH.joinpath("omni/graph/rtxtest/tests/data/golden")
THRESHOLD = 1e-4
class TestPostRenderGraphs(RtxTest):
@staticmethod
def get_aov_list(stage: Usd.Stage, rp_prim_path) -> list[str]:
aovs : list[str] = []
render_vars = stage.GetPrimAtPath(rp_prim_path).GetRelationship("orderedVars").GetForwardedTargets()
for render_var in render_vars:
aov_name = stage.GetPrimAtPath(render_var).GetAttribute("sourceName").Get()
aovs.append(aov_name)
return aovs
@property
def __test_name(self) -> str:
"""
The full name of the test.
It has the name of the module, class and the current test function. We use the stack to get the name of the test
function and since it's only called from create_test_window and finalize_test, we get the third member.
"""
return f"{self.__module__}.{self.__class__.__name__}.{inspect.stack()[2][3]}"
def render_product_path(self, hydra_texture) -> str:
'''Return a string to the UsdRender.Product used by the texture'''
render_product = hydra_texture.get_render_product_path()
if render_product and (not render_product.startswith('/')):
render_product = '/Render/RenderProduct_' + render_product
return render_product
def compare_output_image(self,
golden_img_name,
threshold,
output_img_dir: pathlib.Path,
golden_img_dir: pathlib.Path,
metric: ComparisonMetric = ComparisonMetric.MEAN_ERROR_SQUARED):
"""Compare an arbitrary image with a golden image. The image generated in the test could be produced by OgnGpuInteropCpuToDisk or some other method."""
diff = finalize_capture_and_compare(golden_img_name, threshold, output_img_dir, golden_img_dir, metric=metric)
if diff != 0:
carb.log_warn(f"[{self.__test_name}] the generated image {golden_img_name} has max difference {diff}")
if (diff is not None) and diff >= threshold:
self._failedImages.append(golden_img_name)
return diff
async def setUpProps(self, stage):
# add a couple of prims in the scene
cube = ogts.create_cube(stage, "Cube", (255, 0, 0))
sphere = ogts.create_sphere(stage, "Sphere", (0, 255, 0))
xform_cube = UsdGeom.Xformable(cube)
xform_cube.AddTranslateOp().Set((0, 30, 40))
xform_cube.AddScaleOp().Set(Gf.Vec3f(30.0))
xform_sphere = UsdGeom.Xformable(sphere)
xform_sphere.AddTranslateOp().Set((0, 30, -40))
xform_sphere.AddScaleOp().Set(Gf.Vec3f(25.0))
await wait_for_update(self.ctx, 10)
async def setUp(self):
await super().setUp()
# must apply the test settings to the renderer to ensure that the test setup matches the SDG setup
self.set_settings(testSettings)
# set up the stage
omni.usd.get_context().new_stage()
self.add_dir_light()
self.add_floor()
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadTestSettings)
# renderer
renderer = "rtx"
if renderer not in self.ctx.get_attached_hydra_engine_names():
omni.usd.add_hydra_engine(renderer, self.ctx)
self._stage = self.ctx.get_stage()
session_layer = self._stage.GetSessionLayer()
with Usd.EditContext(self._stage, session_layer):
# set the render product on the active viewport
viewport_api = get_active_viewport()
if viewport_api:
self._render_product_path_0 = viewport_api.render_product_path
# create the post render graph
pipeline_stage = og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_POSTRENDER
execution_model = "push"
orchestration_graphs = og.get_global_orchestration_graphs_in_pipeline_stage(pipeline_stage)
top_graph = orchestration_graphs[0]
self._og_graph_path = f"{self._render_product_path_0}/TestPostRender"
compound_node1 = top_graph.create_graph_as_node(
"TestPostRender",
self._og_graph_path,
evaluator=execution_model,
is_global_graph=True,
is_backed_by_usd=True,
backing_type=og.GraphBackingType.GRAPH_BACKING_TYPE_FABRIC_SHARED,
pipeline_stage=pipeline_stage)
self._post_render_graph = compound_node1.get_wrapped_graph()
# set the ogPostProcessPath attribute to associate the graph with this render product
attr_name = "ogPostProcessPath"
self._stage.GetPrimAtPath(self._render_product_path_0).CreateAttribute(attr_name, Sdf.ValueTypeNames.String).Set(self._og_graph_path)
# debug sanity check
# carb.log_info(f"!!! rp_path:{self._render_product_path_0}")
# carb.log_info(f"!!! og_path:{self._og_graph_path}")
# carb.log_info(f"!!! rp_aovs: {self.get_aov_list(self._stage, self._render_product_path_0)}")
# carb.log_info(f"!!! rp.ogPostProcessPath={self._stage.GetPrimAtPath(self._render_product_path_0).GetAttribute(attr_name).Get()}")
# carb.log_info(f"!!! og.nodes={self._post_render_graph.get_nodes()}")
async def tearDown(self):
await super().tearDown()
# -----------------------------------------------------------------------------
async def test_modify_aov(self):
"""Validate that the post render graph can modify an AOV in place."""
await self.setUpProps(self._stage)
await self.screenshot_and_diff(
GOLDEN_DIR,
output_subdir="omni.graph.rtxtest",
golden_img_name="test_modify_aov.initial.png",
threshold=THRESHOLD)
keys = og.Controller.Keys
(_, (_, test_node), _, _) = og.Controller.edit(
self._post_render_graph,
{
keys.CREATE_NODES: [
("RenderProductEntry", "omni.graph.nodes.GpuInteropRenderProductEntry"),
("TestNode", "omni.graph.rtxtest.ScaleAOVTextureInPlace"),
],
keys.CONNECT: [
("RenderProductEntry.outputs:gpu", "TestNode.inputs:gpu"),
("RenderProductEntry.outputs:rp", "TestNode.inputs:rp"),
("RenderProductEntry.outputs:exec", "TestNode.inputs:exec"),
],
keys.SET_VALUES: [
("TestNode.inputs:inputAOV", "LdrColor"),
("TestNode.inputs:multiplier", 1.5),
("TestNode.inputs:width", self.WINDOW_SIZE[0]),
("TestNode.inputs:height", self.WINDOW_SIZE[1]),
]
},
)
await wait_for_update(self.ctx, 10)
# Validate that the outputAOVPtr attribute is set.
# This attribute is set after getting from the RenderProduct
# the pointer of the AOV with the token set on the "inputAOV" attribute.
actual = og.Controller.get(og.Controller.attribute("outputs:outputAOVPtr", test_node))
self.assertNotEqual(0, actual)
# validate that the scheduleCudaTask() method returned true
schedule_result = og.Controller.get(og.Controller.attribute("outputs:scheduleResult", test_node))
self.assertEqual(True, schedule_result)
await self.screenshot_and_diff(
GOLDEN_DIR,
output_subdir="omni.graph.rtxtest",
golden_img_name="test_modify_aov.scaled.png",
threshold=THRESHOLD)
# -----------------------------------------------------------------------------
async def test_create_new_aov(self):
"""Validate that the post render graph can create new AOVs without throwing."""
# This test allocates a new AOV, saves it to disk and compares it with a golden image
# NOTE: the image produced by the test seems to be missing the expected details, indicating
# a bug in the test nodes. Since this test does not rely on the actual data in the buffer
# being correct, the test is considered valid.
await self.setUpProps(self._stage)
output_image_dir = OUTPUTS_DIR.joinpath("omni.graph.rtxtest")
keys = og.Controller.Keys
(_, (_, test_node, _, _), _, _) = og.Controller.edit(
self._post_render_graph,
{
keys.CREATE_NODES: [
("RenderProductEntry", "omni.graph.nodes.GpuInteropRenderProductEntry"),
("TestNode", "omni.graph.rtxtest.ScaleAOVTexture"),
("GpuToCpuCopy", "omni.graph.examples.cpp.GpuInteropGpuToCpuCopy"),
("CpuToDisk", "omni.graph.examples.cpp.GpuInteropCpuToDisk"),
],
keys.CONNECT: [
("RenderProductEntry.outputs:gpu", "TestNode.inputs:gpu"),
("RenderProductEntry.outputs:rp", "TestNode.inputs:rp"),
("RenderProductEntry.outputs:exec", "TestNode.inputs:exec"),
("TestNode.outputs:gpu", "GpuToCpuCopy.inputs:gpu"),
("TestNode.outputs:rp", "GpuToCpuCopy.inputs:rp"),
("GpuToCpuCopy.outputs:gpu", "CpuToDisk.inputs:gpu"),
("GpuToCpuCopy.outputs:rp", "CpuToDisk.inputs:rp"),
("GpuToCpuCopy.outputs:aovCpu", "CpuToDisk.inputs:aovCpu"),
],
keys.SET_VALUES: [
("TestNode.inputs:inputAOV", "LdrColor"),
("TestNode.inputs:outputAOV", "scaledColor"),
("TestNode.inputs:multiplier", 1.5),
("TestNode.inputs:width", self.WINDOW_SIZE[0]),
("TestNode.inputs:height", self.WINDOW_SIZE[1]),
("GpuToCpuCopy.inputs:aovGpu", "scaledColor"),
("CpuToDisk.inputs:aovGpu", "scaledColor"),
("CpuToDisk.inputs:frameCount", 1),
("CpuToDisk.inputs:saveLocation", str(output_image_dir)),
("CpuToDisk.inputs:fileName", "test_create_new_aov"), # final name: test_create_new_aov_scaledColor.png
("CpuToDisk.inputs:autoFileNumber", 0),
]
},
)
await wait_for_update(self.ctx, 10)
# validate that the outputAOVPtr attribute is set - this attribute is set after the new AOV is allocated
actual = og.Controller.get(og.Controller.attribute("outputs:outputAOVPtr", test_node))
self.assertNotEqual(0, actual)
# validate that the scheduleCudaTask() method returned true
schedule_result = og.Controller.get(og.Controller.attribute("outputs:scheduleResult", test_node))
self.assertEqual(True, schedule_result)
self.compare_output_image(
"test_create_new_aov_scaledColor.png",
THRESHOLD,
output_image_dir,
GOLDEN_DIR)
# -----------------------------------------------------------------------------
async def test_invalid_input_aov_param__fails(self):
"""Validate that nodes accessing invalid AOVs do not schedule cuda tasks"""
keys = og.Controller.Keys
(_, (_, test_node), _, _) = og.Controller.edit(
self._post_render_graph,
{
keys.CREATE_NODES: [
("RenderProductEntry", "omni.graph.nodes.GpuInteropRenderProductEntry"),
("TestNode", "omni.graph.rtxtest.ScaleAOVTextureInPlace"),
],
keys.CONNECT: [
("RenderProductEntry.outputs:gpu", "TestNode.inputs:gpu"),
("RenderProductEntry.outputs:rp", "TestNode.inputs:rp"),
("RenderProductEntry.outputs:exec", "TestNode.inputs:exec"),
],
keys.SET_VALUES: [
("TestNode.inputs:inputAOV", "InvalidAOVToken"),
("TestNode.inputs:multiplier", 1.5),
("TestNode.inputs:width", self.WINDOW_SIZE[0]),
("TestNode.inputs:height", self.WINDOW_SIZE[1]),
]
},
)
await wait_for_update(self.ctx, 10)
# the builder will log a warning if an AOV is not found
self.assertEqual(len(test_node.get_compute_messages(og.WARNING)), 1)
# validate that the scheduleCudaTask() method returned false
schedule_result = og.Controller.get(og.Controller.attribute("outputs:scheduleResult", test_node))
self.assertEqual(False, schedule_result)
| 13,459 | Python | 45.413793 | 159 | 0.58838 |
omniverse-code/kit/exts/omni.graph.rtxtest/omni/graph/rtxtest/tests/test_gpu_interop.py | """test gpu interop nodes"""
import pathlib
import omni.graph.core as og
import omni.kit.commands
import omni.kit.stage_templates
import omni.kit.test
import omni.usd
from omni.rtx.tests import RtxTest, postLoadTestSettings, testSettings
from omni.rtx.tests.test_common import wait_for_update
from pxr import UsdGeom
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
GOLDEN_DIR = EXTENSION_FOLDER_PATH.joinpath("omni/graph/rtxtest/tests/data/golden")
# ======================================================================
class TestPreRender(RtxTest):
async def setUp(self):
await super().setUp()
self.set_settings(testSettings)
omni.usd.get_context().new_stage()
self.add_dir_light()
await omni.kit.app.get_app().next_update_async()
self.set_settings(postLoadTestSettings)
async def tearDown(self):
await super().tearDown()
await omni.kit.stage_templates.new_stage_async()
def create_mesh(self, name):
box = UsdGeom.Mesh.Define(self.ctx.get_stage(), name)
box.CreatePointsAttr(
[
(-50, -50, -50),
(50, -50, -50),
(-50, -50, 50),
(50, -50, 50),
(-50, 50, -50),
(50, 50, -50),
(50, 50, 50),
(-50, 50, 50),
]
)
box.CreateFaceVertexCountsAttr([4, 4, 4, 4, 4, 4])
box.CreateFaceVertexIndicesAttr([0, 1, 3, 2, 0, 4, 5, 1, 1, 5, 6, 3, 2, 3, 6, 7, 0, 2, 7, 4, 4, 7, 6, 5])
box.CreateSubdivisionSchemeAttr("none")
return box
# ----------------------------------------------------------------------
async def test_prerender_gpuinterop(self):
controller = og.Controller()
keys = og.Controller.Keys()
(_, _, _, _) = controller.edit(
{"graph_path": "/PushGraph", "pipeline_stage": og.GraphPipelineStage.GRAPH_PIPELINE_STAGE_PRERENDER},
{
keys.CREATE_NODES: [
("ConstantString", "omni.graph.nodes.ConstantString"),
("ToToken", "omni.graph.nodes.ToToken"),
("ReadPoints", "omni.graph.nodes.ReadPrimAttribute"),
("Entry", "omni.graph.nodes.RenderPreProcessEntry"),
("Allocator", "omni.graph.nodes.RpResourceExampleAllocator"),
("Deformer", "omni.graph.nodes.RpResourceExampleDeformer"),
("ToHydra", "omni.graph.nodes.RpResourceExampleHydra"),
],
keys.CONNECT: [
("ConstantString.inputs:value", "ToToken.inputs:value"),
("ToToken.outputs:converted", "ReadPoints.inputs:primPath"),
("ToToken.outputs:converted", "Allocator.inputs:primPath"),
("ReadPoints.outputs:value", "Allocator.inputs:points"),
("Entry.outputs:stream", "Allocator.inputs:stream"),
("Allocator.outputs:pointCountCollection", "Deformer.inputs:pointCountCollection"),
("Allocator.outputs:primPathCollection", "Deformer.inputs:primPathCollection"),
("Allocator.outputs:resourcePointerCollection", "Deformer.inputs:resourcePointerCollection"),
("Allocator.outputs:stream", "Deformer.inputs:stream"),
("Deformer.outputs:pointCountCollection", "ToHydra.inputs:pointCountCollection"),
("Deformer.outputs:primPathCollection", "ToHydra.inputs:primPathCollection"),
("Deformer.outputs:resourcePointerCollection", "ToHydra.inputs:resourcePointerCollection"),
],
keys.SET_VALUES: [
("ConstantString.inputs:value", "/World/box"),
("ReadPoints.inputs:usePath", True),
("ReadPoints.inputs:name", "points"),
("Deformer.inputs:deformScale", 50.0),
("Deformer.inputs:positionScale", 100.0),
("ToHydra.inputs:sendToHydra", True),
],
},
)
self.create_mesh("/World/box")
await wait_for_update(self.ctx, 30)
await self.screenshot_and_diff(
GOLDEN_DIR,
output_subdir="omni.graph.rtxtest",
golden_img_name="gpuinterop_prerender_deformer.png",
threshold=1e-4,
)
| 4,519 | Python | 42.461538 | 113 | 0.547466 |
omniverse-code/kit/exts/omni.rtx.shadercache.vulkan/omni/rtx/shadercache/vulkan/__init__.py | from .shadercache_vulkan import ShaderCacheConfig
| 50 | Python | 24.499988 | 49 | 0.88 |
omniverse-code/kit/exts/omni.rtx.shadercache.vulkan/omni/rtx/shadercache/vulkan/shadercache_vulkan.py | import omni.ext
class ShaderCacheConfig(omni.ext.IExt):
def on_startup(self, ext_id):
"""Callback when the extension is starting up"""
pass
def on_shutdown(self):
"""Callback when the extension is shutting down"""
pass
| 261 | Python | 22.81818 | 58 | 0.636015 |
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/connector.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import omni.client
import carb
from typing import Callable
from functools import partial
from .ui import ConnectorDialog, AlertPane
class NucleusConnector:
"""
NucleusConnector object helps with connecting to Nucleus servers.
"""
def __init__(self):
self._dialog = None
def start_auth_flow(self, host_name, auth_handle: int):
"""
Called at the start of the authentication cycle. Most importantly, prepares a cancel button
so that the user can cancel out of the process if it hangs for any reason.
Args:
host_name (str): The server host name that the authentication is for
auth_handle (int): An integer handle that should be passed to cancel authentication
"""
# OM-76995: for authentication callback, it is okay to re-use dialogs created since it most often comes from
# connection operations already
if not self._dialog:
self._dialog = ConnectorDialog()
# Set dialog fields only if they're empty
name = self._dialog.get_value('name') or host_name
url = omni.client.make_url(scheme='omniverse', host=self._dialog.get_value('url') or host_name)
self._dialog.show_authenticate(name=name, url=url)
self._dialog.set_cancel_clicked_fn(partial(self.cancel_auth, auth_handle))
def end_auth_flow(self, auth_handle: int):
"""Called at the end of the authentication cycle; hides the app dialog"""
if self._dialog:
self._dialog.hide()
self._dialog = None
def cancel_auth(self, auth_handle: int, dialog: ConnectorDialog):
"""
This callback is attached to the dialog's cancel button. It cancels the authentication process.
Args:
auth_handle (int): An integer handle that should be passed to cancel authentication
"""
# Cancel the dialog task
if self._dialog:
self._dialog.cancel_task()
self._dialog.hide()
self._dialog = None
# Cancel the auth flow in the browser
omni.client.authentication_cancel(auth_handle)
def connect_with_callback(self,
name: str = None, url: str = None, on_success_fn: Callable = None, on_failed_fn: Callable = None):
"""
Unless specified, prompts for server name and Url and proceeds to connect to it.
Args:
name (str): Name of server
url (str): Url of server
on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str)
on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str)
"""
def on_connect_server(on_success_fn: Callable, on_failed_fn: Callable, dialog: ConnectorDialog,
name: str = None, url: str = None, show_waiting: bool = True):
if not name:
name = dialog.get_value("name")
if not url:
url = dialog.get_value("url")
# OMFP-2249: If no name/url is present, we do nothing (when "ok" button is clicked)
if not url and not name:
return
if show_waiting:
dialog.show_waiting()
# Give dialog ownership of the task so that it can cancel at will.
asyncio.ensure_future(dialog.run_cancellable_task(
self.connect_server_async(name, url, on_success_fn, on_failed_fn, dialog=dialog)))
def on_cancel(dialog):
dialog.cancel_task()
dialog.hide()
# OM-76995: Create the dialog on demand, so in detached window the dialog window shows up correctly
self._dialog = ConnectorDialog()
if url:
self._dialog.show_authenticate(name=name, url=url)
# If server is explicitly specified, then proceed to connect rather than wait for user input.
on_connect_server(on_success_fn, on_failed_fn, self._dialog, name=name, url=url)
return
self._dialog.show(name=name, url=url)
self._dialog.set_okay_clicked_fn(partial(on_connect_server, on_success_fn, on_failed_fn))
self._dialog.set_cancel_clicked_fn(on_cancel)
async def connect_server_async(self, name: str, url: str, on_success_fn: Callable = None, on_failed_fn: Callable = None, retry: bool = False, dialog: ConnectorDialog = None):
"""
Connects to the named server.
Args:
name (str): Name of server
url (str): Url of server
on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str)
on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str)
retry (bool): True if re-trying for second time.
dialog (ConnectorDialog): A dialog instance to re-use from parent operation.
"""
if not url:
carb.log_warn(f"Error connecting server, missing Url.")
return
elif not url.startswith("omniverse://"):
url = f"omniverse://{url}"
if not name:
# If no name specified, then use name of child directory
name = list(filter(None, url.split("/")))[-1]
if not dialog:
dialog = ConnectorDialog()
dialog.show_authenticate(name=name, url=url)
result, stats = None, None
try:
# This stat triggers the start of the authentication flow
result, stats = await omni.client.stat_async(url)
except asyncio.CancelledError:
# If this task is cancelled, then sign out completely in order to clear the auth process
omni.client.sign_out(url)
carb.log_warn(f"Cancelled attempted connection to '{url}'.")
return
if result == omni.client.Result.OK:
dialog.hide()
dialog.destroy()
if on_success_fn:
on_success_fn(name, url)
elif result == omni.client.Result.ERROR_CONNECTION and not retry:
# Note: Strangely, omni.client returns error if the user has previously connected or disconnected from
# this server. In this case, only a reconnect will succeed.
omni.client.reconnect(url)
await self.connect_server_async(
name, url, on_success_fn=on_success_fn, on_failed_fn=on_failed_fn, retry=True, dialog=dialog)
else:
msg = f"Unable to connect server '{url}'. Please check your internet connection then try again."
dialog.show_alert(msg, AlertPane.Warn)
if on_failed_fn:
on_failed_fn(name, url)
async def reconnect_server_async(self, url: str, on_success_fn: Callable = None, on_failed_fn: Callable = None):
"""
Re-connects to the named server.
Args:
url (str): Url of server
on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str)
on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str)
"""
if not url:
carb.log_warn(f"Error reconnecting server, missing Url.")
return
name = list(filter(None, url.split("/")))[-1]
# OM-76995: Create the dialog on demand, so in detached window the dialog window shows up correctly
self._dialog = ConnectorDialog()
self._dialog.show_authenticate(name=name, url=url)
# Do the reconnect
omni.client.reconnect(url)
result, stats = None, None
try:
result, stats = await omni.client.stat_async(url)
except asyncio.CancelledError:
# If this task is cancelled, then sign out completely in order to clear the auth process
omni.client.sign_out(url)
carb.log_warn(f"Cancelled attempted connection to '{url}'.")
return
if result == omni.client.Result.OK:
if self._dialog:
self._dialog.hide()
self._dialog = None
if on_success_fn:
on_success_fn(name, url)
else:
msg = f"Unable to connect server '{url}'. Please check your internet connection then try again."
if not self._dialog:
self._dialog = ConnectorDialog()
self._dialog.show_alert(msg, AlertPane.Warn)
if on_failed_fn:
on_failed_fn(name, url)
def destroy(self):
"""Destructor."""
if self._dialog:
self._dialog.destroy()
self._dialog = None
| 9,046 | Python | 40.884259 | 178 | 0.609441 |
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/style.py | from omni import ui
from pathlib import Path
CURRENT_PATH = Path(__file__).parent
DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data")
ICON_PATH = DATA_PATH.joinpath("icons")
class Colors:
Background = ui.color.shade(0xFF23211F, light=0xFF535354)
Border = ui.color.shade(0xFFA1A1A1, light=0xFFE0E0E0)
ButtonHovered = ui.color.shade(0xFF9A9A9A, light=0xFF9A9A9A)
ButtonSelected = ui.color.shade(0xFF9A9A9A, light=0xFF9A9A9A)
Text = ui.color.shade(0xFFA1A1A1, light=0xFFE0E0E0)
TextWarn = ui.color.shade(0xFF3333A1, light=0xFF3333E0)
Url = ui.color.shade(0xFFE8AD4B, light=0xFFE00000)
Image = ui.color.shade(0xFFA8A8A8, light=0xFFA8A8A8)
ProgressBackground = ui.color.shade(0xFF24211F, light=0xFF24211F)
ProgressBorder = ui.color.shade(0xFF323434, light=0xFF323434)
ProgressBar = ui.color.shade(0xFFC9974C, light=0xFFC9974C)
AlertPaneBackground = ui.color.shade(0xFF3A3A3A, light=0xFF323434)
InfoPaneBorder = ui.color.shade(0xFFC9974C, light=0xFFC9974C)
WarningPaneBorder = ui.color.shade(0xFF318693, light=0xFF318693)
UI_STYLES = {
"Dialog": {
"background_color": Colors.Background,
"margin_width": 8,
"margin_height": 8,
},
"Image": {
"background_color": 0x0,
"margin": 0,
"padding": 0,
"color": Colors.Image,
"alignment": ui.Alignment.CENTER,
},
"QrCode": {
"background_color": 0x0,
"margin": 10,
"padding": 0,
"alignment": ui.Alignment.CENTER,
},
"Image.Label": {"color": Colors.Text, "alignment": ui.Alignment.CENTER},
"ProgressBar": {
"background_color": Colors.ProgressBackground,
"border_width": 2,
"border_radius": 0,
"border_color": Colors.ProgressBorder,
"color": Colors.ProgressBar,
"margin": 0,
"padding": 0,
"alignment": ui.Alignment.LEFT_CENTER,
},
"ProgressBar.Frame": {
"background_color": 0xFF23211F,
"margin": 0,
"padding": 0,
},
"ProgressBar.Puck": {
"background_color": Colors.ProgressBar,
"margin": 2,
},
"StringField.Url": {
"color": Colors.Url,
"background_color": 0x0,
},
"Label": {"color": Colors.Text},
"Label.Code": {
"color": Colors.Text,
"alignment": ui.Alignment.CENTER,
"font_size": 40,
},
"Label.TimeRemaining": {"color": Colors.Url},
"Label.Expired": {
"color": Colors.TextWarn,
"alignment": ui.Alignment.CENTER
},
"AlertPane": {
"background_color": Colors.AlertPaneBackground,
"color": Colors.Text,
"margin": 0,
"border_radius": 0.0
},
"AlertPane::info": {
"border_color": Colors.InfoPaneBorder,
"border_width": 2,
},
"AlertPane::warn": {
"border_color": Colors.WarningPaneBorder,
"border_width": 2,
},
"AlertPane.Content": {
"background_color": 0x0,
"margin_width": 8,
"margin_height": 12
},
"AlertPanePane.Clear": {
"background_color": 0x0,
"border_radius": 0.0,
"border_color": Colors.Text,
"border_width": 1,
"margin": 0,
"padding": 2,
},
"AlertPane.Clear:hovered": {"background_color": Colors.ButtonHovered},
"AlertPane.Clear.Image": {"image_url": f"{ICON_PATH}/close.svg", "color": Colors.Text},
} | 3,437 | Python | 30.833333 | 91 | 0.601688 |
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/device_auth.py | # Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import omni.client
import carb
from typing import Callable
from functools import partial
from .ui import DeviceAuthFlowDialog, ConnectorDialog, AlertPane
class DeviceAuthConnector:
"""
DeviceAuthConnector object that helps with connecting to Nucleus servers via device flow.
"""
def __init__(self):
self._conn_status_sub = omni.client.register_connection_status_callback(self._connection_status_changed)
self._pending_results = {} # url: (auth_handle, dialog instance)
def start_auth_flow(self, auth_handle: int, params: omni.client.AuthDeviceFlowParams):
"""
Called at the start of the authentication cycle. Shows the user a qrcode of auth url and code that needs to be
entered in the auth page. User can cancel the process by clicking the cancel button.
Args:
auth_handle (int): An integer handle that should be passed to cancel authentication
"""
dialog = DeviceAuthFlowDialog(params)
self._pending_results[params.server] = (auth_handle, dialog)
dialog.set_cancel_clicked_fn(partial(self.cancel_auth, auth_handle, params.server))
def end_auth_flow(self, auth_handle: int):
"""Called at the end of the authentication cycle; hides the app dialog"""
# find server from auth handle
server = None
for server_name, (handle, _) in self._pending_results.items():
if handle == auth_handle:
server = server_name
break
if not server:
return
_, dialog = self._pending_results.pop(server)
if dialog:
dialog.hide()
dialog = None
def cancel_auth(self, auth_handle: int, server: str, dialog: DeviceAuthFlowDialog):
"""
This callback is attached to the dialog's cancel button. It cancels the authentication process.
Args:
auth_handle (int): An integer handle that should be passed to cancel authentication
server (str): The server url that the auth handle is binding to
"""
if dialog:
dialog.hide()
dialog = None
if server in self._pending_results:
self._pending_results.pop(server)
# Cancel the auth flow
omni.client.authentication_cancel(auth_handle)
def _connection_status_changed(self, server: str, status: omni.client.ConnectionStatus) -> None:
"""Collect signed in server's service information based upon server status changed."""
# need to strip off the omniverse:// here from the server
if server.startswith("omniverse://"):
server = server[12:]
if server not in self._pending_results:
return
if status == omni.client.ConnectionStatus.CONNECTED:
_, dialog = self._pending_results.pop(server)
if dialog:
dialog.hide()
dialog = None
def connect_with_callback(self,
name: str = None, url: str = None, on_success_fn: Callable = None, on_failed_fn: Callable = None):
"""
Unless specified, prompts for server name and Url and proceeds to connect to it.
Args:
name (str): Name of server
url (str): Url of server
on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str)
on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str)
"""
def on_connect_server(on_success_fn: Callable, on_failed_fn: Callable, dialog: ConnectorDialog,
name: str = None, url: str = None, show_waiting: bool = True):
if show_waiting:
dialog.show_waiting()
if not name:
name = dialog.get_value("name")
if not url:
url = dialog.get_value("url")
# Give dialog ownership of the task so that it can cancel at will.
asyncio.ensure_future(dialog.run_cancellable_task(
self.connect_server_async(name, url, on_success_fn, on_failed_fn, dialog=dialog)))
def on_cancel(dialog):
dialog.cancel_task()
dialog.hide()
# OM-76995: Create the dialog on demand, so in detached window the dialog window shows up correctly
self._dialog = ConnectorDialog()
if url:
# If server is explicitly specified, then proceed to connect rather than wait for user input.
on_connect_server(on_success_fn, on_failed_fn, self._dialog, name=name, url=url)
return
self._dialog.show(name=name, url=url)
self._dialog.set_okay_clicked_fn(partial(on_connect_server, on_success_fn, on_failed_fn))
self._dialog.set_cancel_clicked_fn(on_cancel)
async def connect_server_async(self, name: str, url: str, on_success_fn: Callable = None, on_failed_fn: Callable = None, retry: bool = False, dialog: ConnectorDialog = None):
"""
Connects to the named server.
Args:
name (str): Name of server
url (str): Url of server
on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str)
on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str)
retry (bool): True if re-trying for second time.
dialog (ConnectorDialog): A dialog instance to re-use from parent operation.
"""
if not url:
carb.log_warn(f"Error connecting server, missing Url.")
return
elif not url.startswith("omniverse://"):
url = f"omniverse://{url}"
if not name:
# If no name specified, then use name of child directory
name = list(filter(None, url.split("/")))[-1]
result, stats = None, None
try:
# This stat triggers the start of the authentication flow
result, stats = await omni.client.stat_async(url)
except asyncio.CancelledError:
# If this task is cancelled, then sign out completely in order to clear the auth process
omni.client.sign_out(url)
carb.log_warn(f"Cancelled attempted connection to '{url}'.")
return
if result == omni.client.Result.OK:
if dialog:
dialog.hide()
if on_success_fn:
on_success_fn(name, url)
elif result == omni.client.Result.ERROR_CONNECTION and not retry:
# Note: Strangely, omni.client returns error if the user has previously connected or disconnected from
# this server. In this case, only a reconnect will succeed.
omni.client.reconnect(url)
await self.connect_server_async(
name, url, on_success_fn=on_success_fn, on_failed_fn=on_failed_fn, retry=True, dialog=dialog)
else:
msg = f"Unable to connect server '{url}'. Please check your internet connection then try again."
if not dialog:
dialog = ConnectorDialog()
dialog.show_alert(msg, AlertPane.Warn)
if on_failed_fn:
on_failed_fn(name, url)
async def reconnect_server_async(self, url: str, on_success_fn: Callable = None, on_failed_fn: Callable = None):
"""
Re-connects to the named server.
Args:
url (str): Url of server
on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str)
on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str)
"""
if not url:
carb.log_warn(f"Error reconnecting server, missing Url.")
return
name = list(filter(None, url.split("/")))[-1]
# Do the reconnect
omni.client.reconnect(url)
result, stats = None, None
try:
result, stats = await omni.client.stat_async(url)
except asyncio.CancelledError:
# If this task is cancelled, then sign out completely in order to clear the auth process
omni.client.sign_out(url)
carb.log_warn(f"Cancelled attempted connection to '{url}'.")
return
if result == omni.client.Result.OK:
if on_success_fn:
on_success_fn(name, url)
else:
if on_failed_fn:
on_failed_fn(name, url)
def destroy(self):
"""Destructor."""
if self._pending_results:
self._pending_results.clear()
self._conn_status_sub = None
# Cleanup temp img files created for qrcode
import os
if os.path.exists(DeviceAuthFlowDialog.TEMP_DIR):
try:
import shutil
shutil.rmtree(DeviceAuthFlowDialog.TEMP_DIR)
except OSError as e:
carb.log_warn(
f"Failed to clean up temp directory {DeviceAuthFlowDialog.TEMP_DIR}, error encountered: {str(e)}")
| 9,463 | Python | 40.69163 | 178 | 0.609426 |
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/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.settings
import omni.ext
import omni.kit.app
import omni.client
import asyncio
from typing import Callable
from functools import partial
from .connector import NucleusConnector
from .device_auth import DeviceAuthConnector
from . import NUCLEUS_CONNECTION_SUCCEEDED_EVENT
g_singleton = None
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class NucleusConnectorExtension(omni.ext.IExt):
"""Helper extension for connecting to Nucleus servers"""
def __init__(self):
super().__init__()
self._connector = None
def on_startup(self, ext_id):
# Save away this instance as singleton
global g_singleton
g_singleton = self
# OM-98449: Register device auth flow callback if device auth flow is turned on in settings
self._device_auth_sub = None
settings = carb.settings.get_settings()
device_auth = settings.get_as_bool("exts/omni.kit.widget.nucleus_connector/device_auth_flow")
if device_auth: # pragma: no cover
self._connector = DeviceAuthConnector()
self._device_auth_sub = omni.client.register_device_flow_auth_callback(self._on_device_auth)
else:
self._connector = NucleusConnector()
# Set the callback to invoke when authentication requires opening a web browser to complete sign-in.
omni.client.set_authentication_message_box_callback(self._on_authenticate)
def _on_device_auth(self, auth_handle: int, params: omni.client.AuthDeviceFlowParams):
"""
This callback is invoked when authentication for device auth flow, instead of auth in the web browser.
Args:
auth_handle (int): The auth handle that could be used for canceling.
params (omni.client.AuthDeviceFlowParams): An object containing info to display to user to complete the auth.
if it is None, it means the auth attempt is finished.
"""
if self._connector:
if not params:
# Auth is done, either succeeded or failed, result needed to be determined from status callback;
# Here we just close out the dialog.
self._connector.end_auth_flow(auth_handle)
return
self._connector.start_auth_flow(auth_handle, params)
def _on_authenticate(self, show_alert: bool, host_name: str, auth_handle: int):
"""
This callback is invoked when the application should show a dialog box letting the user know that a
browser window has opened and to complete signing in using the web browser.
Args:
show_alert (bool): True means to start the authentication cycle and False means to end it
host_name (str): The server host name that the authentication is for
auth_handle (int): An integer handle that should be passed to cancel authentication
"""
if self._connector:
if show_alert:
self._connector.start_auth_flow(host_name, auth_handle)
else:
self._connector.end_auth_flow(auth_handle)
def _on_connect_succeeded(self, callback: Callable, name: str, url: str):
"""Called when connection is made successfully; invokes the given callback"""
# Emit event on successful connection
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
if event_stream:
event_stream.push(NUCLEUS_CONNECTION_SUCCEEDED_EVENT, payload={"url": url})
if callback:
callback(name, url)
def _on_connect_failed(self, callback: Callable, name: str, url: str):
"""Called when connection fails; invokes the given callback"""
if callback:
callback(name, url)
def connect_with_dialog(self, on_success_fn: Callable = None, on_failed_fn: Callable = None):
"""
Prompts for server name and Url and proceeds to connect to it.
Args:
on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str)
on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str)
"""
if self._connector:
self._connector.connect_with_callback(
on_success_fn=partial(self._on_connect_succeeded, on_success_fn), on_failed_fn=partial(self._on_connect_failed, on_failed_fn))
def connect(self, name: str, url: str, on_success_fn: Callable = None, on_failed_fn: Callable = None):
"""
Connects to the named server.
Args:
name (str): Name of server
url (str): Url of server
on_success_fn (Callable): Invoked when successful, on_success_fn(name: str, url: str)
on_faild_fn (Callable): Invoked when failed, on_faild_fn(name: str, url: str)
"""
if self._connector:
self._connector.connect_with_callback(name=name, url=url,
on_success_fn=partial(self._on_connect_succeeded, on_success_fn), on_failed_fn=partial(self._on_connect_failed, on_failed_fn))
def reconnect(self, url: str, on_success_fn: Callable = None, on_failed_fn: Callable = None):
"""
Reconnects to the named server.
Args:
url (str): Url of server
on_success_fn (Callable): Invoked when successful, on_success_fn(url: str)
on_faild_fn (Callable): Invoked when failed, on_faild_fn(url: str)
"""
if self._connector:
asyncio.ensure_future(self._connector.reconnect_server_async(
url, partial(self._on_connect_succeeded, on_success_fn), partial(self._on_connect_failed, on_failed_fn)))
def disconnect(self, url: str):
"""
Disconnects from the server.
Args:
url (str): Url of server
"""
omni.client.sign_out(url)
def on_shutdown(self):
# Clears the auth callback
omni.client.set_authentication_message_box_callback(None)
# OM-98449: Clears device auth flow connector and callback
self._device_auth_sub = None
# Clean up the connector
if self._connector:
self._connector.destroy()
self._connector = None
global g_singleton
g_singleton = None
def get_instance():
return g_singleton
| 6,993 | Python | 40.141176 | 142 | 0.648649 |
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/__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.
#
import carb.events
NUCLEUS_CONNECTION_SUCCEEDED_EVENT: int = carb.events.type_from_string("omni.kit.widget.nucleus_connector.CONNECTION_SUCCEEDED")
from .extension import NucleusConnectorExtension, get_instance
def get_nucleus_connector() -> NucleusConnectorExtension:
"""Returns :class:`NucleusConnectorExtension` interface"""
return get_instance()
| 795 | Python | 40.894735 | 128 | 0.801258 |
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/test_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
from typing import Optional, Union
import omni.kit.app
from omni.kit import ui_test
from .ui import ConnectorDialog, DeviceAuthFlowDialog
from . import get_nucleus_connector
from .connector import NucleusConnector
from .device_auth import DeviceAuthConnector
class NucleusConnectorTestHelper:
# NOTE Since the file dialog is a singleton, use an async lock to ensure mutex access in unit tests.
# During run-time, this is not a issue because the dialog is effectively modal.
__async_lock = asyncio.Lock()
async def __aenter__(self):
await self.__async_lock.acquire()
return self
async def __aexit__(self, *args):
self.__async_lock.release()
def get_connector_dialog(self, url: str = None) -> Optional[Union[ConnectorDialog, DeviceAuthFlowDialog]]:
ext = get_nucleus_connector()
if ext and ext._connector:
if isinstance(ext._connector, NucleusConnector) or url is None:
return ext._connector._dialog
if isinstance(ext._connector, DeviceAuthConnector) and url:
return ext._connector._pending_results.get(url, (None, None))[1]
return None # pragma: no cover
async def wait_for_popup(self, timeout: int = 100, url: str = None):
dialog = self.get_connector_dialog(url=url)
if dialog:
for _ in range(timeout):
if dialog.visible:
return
await omni.kit.app.get_app().next_update_async()
raise Exception("Error: The connector dialog never opened.")
async def wait_for_close(self, timeout: int = 100, url: str = None):
dialog = self.get_connector_dialog(url=url)
# OM-76995: Since we are creating the dialog on demand, it is considered ok if the dialog doesn't exist
if dialog:
for _ in range(timeout):
if not dialog.visible:
return
await omni.kit.app.get_app().next_update_async()
raise Exception("Error: The connector dialog never closed.") # pragma: no cover
async def click_apply_async(self, name: str = None, url: str = None):
"""Helper function to click the apply button"""
dialog = self.get_connector_dialog()
if dialog:
dialog.set_value('name', name)
dialog.set_value('url', url)
ok_button = ui_test.find(f"{dialog._window.title}//Frame/**/Button[0]")
await ok_button.click()
await ui_test.human_delay()
async def click_cancel_async(self, url: str = None):
"""Helper function to click the cancel button"""
dialog = self.get_connector_dialog(url=url)
if dialog:
cancel_button = ui_test.find(f"{dialog._window.title}//Frame/**/Button[1]")
await cancel_button.click()
await ui_test.human_delay()
| 3,329 | Python | 42.246753 | 111 | 0.648243 |
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/ui.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 os
import sys
import tempfile
import carb
import carb.settings
import omni.ui as ui
import asyncio
import omni.kit.app
from omni.kit.async_engine import run_coroutine
from typing import Coroutine, Any, Callable, Union
from omni.kit.window.popup_dialog.dialog import PopupDialog
from omni.kit.window.popup_dialog.form_dialog import FormDialog, FormWidget
from .style import UI_STYLES, ICON_PATH
class ConnectorDialog(PopupDialog):
"""The main connection dialog"""
def __init__(self):
super().__init__(
width=400,
title="Add Nucleus connection",
ok_label="Ok",
cancel_label="Cancel",
modal=True
)
self._form_widget = None
self._progress_bar = None
self._alert_pane = None
self._task = None
self._build_ui()
def _build_ui(self):
field_defs = [
FormDialog.FieldDef("url", "Omniverse:// ", ui.StringField, "", True),
FormDialog.FieldDef("name", "Optional Name: ", ui.StringField, ""),
]
with self._window.frame:
with ui.VStack(style=UI_STYLES, style_type_name_override="Dialog"):
# OM-81873: This is a temporary solution for the authentication dialog; add the form widget in a frame
# so that it could be easily hidden/shown
self._form_frame = ui.Frame()
with self._form_frame:
self._form_widget = FormWidget("Add a new connection with optional name.", field_defs)
with ui.ZStack():
ui.Spacer(height=60)
with ui.VStack():
ui.Spacer(height=8)
self._progress_bar = LoopProgressBar(puck_size=40)
ui.Spacer()
# OM-86699: Fix issue with randomly resized connector dialog, specify ZStack width with window width
# OM-98771: Substract padding from window width when specifying AlertPane width
self._alert_pane = AlertPane(width=self._window.width - 24)
self._build_ok_cancel_buttons()
self.hide()
self.set_cancel_clicked_fn(lambda _: self._on_cancel_fn())
def _on_cancel_fn(self):
self.cancel_task()
self.hide()
def get_value(self, name: str) -> str:
if self._form_widget:
return self._form_widget.get_value(name)
return None
def set_value(self, name: str, value: str):
if self._form_widget:
field = self._form_widget.get_field(name)
if field:
field.model.set_value(value or '')
def destroy(self):
self.cancel_task()
if self._form_widget:
self._form_widget.destroy()
self._form_widget = None
if self._form_frame:
self._form_frame = None
self._progress_bar = None
if self._alert_pane:
self._alert_pane.destroy()
self._alert_pane = None
super().destroy()
def __del__(self):
self.destroy()
async def run_cancellable_task(self, task: Coroutine) -> Any:
"""Manages running and cancelling the given task"""
if self._task:
self.cancel_task()
self._task = asyncio.create_task(task)
try:
return await self._task
except asyncio.CancelledError:
carb.log_info(f"Cancelling task ... {self._task}")
raise
except Exception as e:
raise
finally:
self._task = None
def cancel_task(self):
"""Cancels the managed task"""
if self._task is not None:
self._task.cancel()
self._task = None
@property
def frame(self):
return self._window.frame
@property
def visible(self) -> bool:
if self._window:
return self._window.visible
return False
def show(self, name: str = None, url: str = None):
"""Shows the dialog after resetting to a default state"""
broken_url = omni.client.break_url(url or '')
host = broken_url.host if broken_url.scheme == 'omniverse' else None
self.set_value('url', host)
self.set_value('name', name)
self._progress_bar.hide()
self._alert_pane.hide()
self._okay_button.enabled = True
self._cancel_button.enabled = True
self._okay_button.visible = True
self._form_frame.visible = True
self._window.visible = True
# focus fields on show
self._form_widget.focus()
def hide(self):
self._window.visible = False
# reset window title on hide; authentication mode might have reset the window title.
self._window.title = self._title
def show_waiting(self):
if self._alert_pane:
self._alert_pane.hide()
if self._progress_bar:
self._progress_bar.show()
# Disable apply button
self._okay_button.enabled = False
def show_alert(self, msg: str = "", alert_type: int = 0):
# hide form widget and OK button
self._okay_button.visible = False
self._form_frame.visible = False
if self._alert_pane:
self._alert_pane.show(msg, alert_type=alert_type)
if self._progress_bar:
self._progress_bar.hide()
# Disable apply button
self._okay_button.enabled = False
self._window.visible = True
def show_authenticate(self, name: str, url: str):
"""Shows the dialog for authentication, when the name and url is already given."""
# hide form widget and OK button
self._okay_button.visible = False
self._form_frame.visible = False
# show login info
broken_url = omni.client.break_url(url or '')
host = broken_url.host if broken_url.scheme == 'omniverse' else None
if self._alert_pane:
msg = f"Connecting to ({host}) requires login authentication. Please login from your web browser."
self._alert_pane.show(msg, alert_type=AlertPane.Info)
# update window title
self._window.title = "Login Required"
self._window.visible = True
class LoopProgressBar:
"""A looping progress bar"""
def __init__(self, puck_size: int = 20, period: float = 120):
self._puck_size = puck_size
self._period = period
self._widget = None
self._spacer_left = None
self._spacer_right = None
self._loop_task = None
self._build_ui()
def _build_ui(self):
self._widget = ui.Frame(visible=False)
with self._widget:
with ui.ZStack(height=20):
ui.Rectangle(style_type_name_override="ProgressBar")
with ui.HStack():
self._spacer_left = ui.Spacer(width=ui.Fraction(0))
ui.Rectangle(width=self._puck_size, style_type_name_override="ProgressBar.Puck")
self._spacer_right = ui.Spacer(width=ui.Fraction(1))
async def _inf_loop(self):
counter = 0
while True:
await omni.kit.app.get_app().next_update_async()
width = float(counter % self._period) / self._period
# Ping-pong
width = width * 2
if width > 1.0:
width = 2.0 - width
self._spacer_left.width = ui.Fraction(width)
self._spacer_right.width = ui.Fraction(1.0 - width)
counter += 1
def __del__(self):
self.hide()
self._widget = None
def show(self):
if self._widget:
self._loop_task = asyncio.ensure_future(self._inf_loop())
self._widget.visible = True
def hide(self):
if self._widget:
if self._loop_task is not None:
self._loop_task.cancel()
self._loop_task = None
self._widget.visible = False
class AlertPane:
"""An alert pane for the app dialog."""
Info = 0
Warn = 1
def __init__(self, width: int = 400):
self._widget: ui.Frame = None
self._frame: ui.Frame = None
self._icon_frame: ui.Frame = None
self._label: ui.Label = None
self._build_ui(width=width)
def destroy(self):
self._label = None
self._frame = None
self._widget = None
def _build_ui(self, width: int = 400):
self._widget = ui.Frame(visible=False, height=0)
with self._widget:
with ui.ZStack(width=width, style=UI_STYLES):
self._frame = ui.Frame()
with ui.HStack(spacing=4, style_type_name_override="AlertPane.Content"):
self._icon_frame = ui.Frame()
self._label = ui.Label("", height=20, word_wrap=True, style_type_name_override="Label")
def show(self, msg: str = "", alert_type: int = 0):
if self._widget:
with self._frame:
style_name = "warn" if alert_type == AlertPane.Warn else "info"
ui.Rectangle(style_type_name_override="AlertPane", name=style_name)
with self._icon_frame:
icon = f"{ICON_PATH}/warn.svg" if alert_type == AlertPane.Warn else f"{ICON_PATH}/info.svg"
ui.ImageWithProvider(icon, width=16, height=16,
fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT, style_type_name_override="Image")
if self._label:
self._label.text = msg
self._widget.visible = True
def hide(self):
if self._widget:
self._widget.visible = False
# OM-98450: Add UI for device auth flow
class DeviceAuthFlowDialog(PopupDialog):
TEMP_DIR = os.path.join(tempfile.gettempdir(), "kit_device_auth_qrcode/")
"""The main authentication dialog for device auth flow."""
def __init__(self, params: omni.client.AuthDeviceFlowParams):
super().__init__(
width=400,
title="Device Authentication",
ok_label="Retry",
cancel_label="Cancel",
modal=True
)
self._image = None
self._time_remaining = params.expiration
self._server = params.server
self._expiration_frame = None
self._build_ui(params)
self._count_down_task = run_coroutine(self._count_expiration_async())
self._generate_qrcode(params.url)
@property
def visible(self) -> bool:
if self._window:
return self._window.visible
return False
def _build_ui(self, params: omni.client.AuthDeviceFlowParams):
with self._window.frame:
with ui.VStack(style=UI_STYLES, style_type_name_override="Dialog"):
ui.Label(f"Connecting to {params.server}", alignment=ui.Alignment.CENTER)
with ui.HStack():
ui.Spacer()
self._image = ui.Image(width=128, height=128, style_type_name_override="QrCode")
ui.Spacer()
with ui.HStack():
ui.Label(f"Please go to ", width=0)
# OM-102092: Change URL to be a string field so it is selectable and could be copied
# TODO: Note that if the URL is too long, currently it could get clipped and will not display the
# entire url; Solution could be:
# 1) Have both a label and a string field, and when mouse pressed, switch to string field for
# selection; which is a bit hacky, since the string field height need to be dynamically adjusted
# 2) have omni.ui.Label support selection of text
ui.StringField(ui.SimpleStringModel(params.url), style=UI_STYLES,
style_type_name_override="StringField.Url", read_only=True)
ui.Label("or scan the qrcode above, and enter the code below:")
ui.Spacer(height=2)
ui.Label(params.code, style_type_name_override="Label.Code")
ui.Spacer(height=2)
self._expiration_frame = ui.Frame()
with self._expiration_frame:
with ui.HStack(spacing=4):
ui.Spacer()
ui.Label("Code expires in", width=0)
self._time_remaining_label = ui.Label(
str(self._time_remaining), style_type_name_override="Label.TimeRemaining", width=0)
ui.Label("seconds", width=0)
ui.Spacer()
ui.Spacer(height=10)
self._build_ok_cancel_buttons()
ui.Spacer(height=30)
self.set_cancel_clicked_fn(lambda _: self._on_cancel_fn())
self.set_okay_clicked_fn(lambda _: self._on_retry())
self._okay_button.visible = False
def _on_cancel_fn(self):
self._count_down_task.cancel()
self.hide()
def _on_retry(self):
self._on_cancel()
if not self._server.startswith("omniverse://"):
server = "omniverse://" + self._server
else:
server = self._server
omni.client.reconnect(server)
def destroy(self):
if self._count_down_task:
self._count_down_task.cancel()
self._count_down_task = None
super().destroy()
def __del__(self):
self.destroy()
def hide(self):
self._window.visible = False
# reset window title on hide; authentication mode might have reset the window title.
self._window.title = self._title
def show_expired(self):
"""Show the user when the code has expired."""
with self._expiration_frame:
ui.Label("Code has expired. Please try again.", style_type_name_override="Label.Expired")
self._okay_button.visible = True
def _generate_qrcode(self, url: str): # pragma: no cover
"""Generates a qrcode from the given url."""
if not os.path.exists(self.TEMP_DIR):
os.mkdir(self.TEMP_DIR)
# Swap out the : && / since the url we are dealing with are usually something like: "https://a.b.c/x/y",
# replacing these special characters with "_" here so we don't end up violating OS naming conventions
img_name = url.replace("/", "_").replace(":", "_")
img_path = os.path.join(self.TEMP_DIR, f"qr_{img_name}.png")
# we could skip generating the qrcode for the same url, since the image would be the same with the same encoding
if not os.path.exists(img_path):
# try to use qrcode module to generate the image
try:
import qrcode
except ImportError:
carb.log_error("Package qrcode not installed. Skipping qr code generation.")
return
img = qrcode.make(url)
img.save(img_path)
# update image source url
self._image.source_url = img_path
async def _count_expiration_async(self):
"""Counts down the remaining time in seconds before expiration."""
while(self._time_remaining > 0):
await asyncio.sleep(1)
self._time_remaining -= 1
self._time_remaining_label.text = str(self._time_remaining)
self.show_expired()
| 15,818 | Python | 37.026442 | 120 | 0.573145 |
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/tests/test_ui.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import asyncio
from unittest.mock import patch, Mock
import carb.settings
import omni.kit.test
import omni.ui as ui
import omni.kit.ui_test as ui_test
from ..ui import ConnectorDialog, DeviceAuthFlowDialog
class TestConnectorDialog(omni.kit.test.AsyncTestCase):
"""Tests for dialog base class"""
async def setUp(self):
pass
async def tearDown(self):
pass
async def _mock_task_with_results(self):
return 1, 2, 3
async def _mock_cancellable_task(self):
"""After a short delay, hide the dialog. This should result in cancelling this long-lasting task."""
while True:
try:
await asyncio.sleep(1)
except asyncio.CancelledError:
return
async def test_dialog_resturns_task_results(self):
"""Test that the dialog returns the results from it child task"""
dialog = ConnectorDialog()
dialog.show()
with dialog.frame:
ui.Label("Test label", height=20)
results = await dialog.run_cancellable_task(self._mock_task_with_results())
# Confirm returned result
self.assertEqual(results, (1, 2, 3))
dialog.destroy()
async def test_dialog_cancels_task(self):
"""Test that hiding the dialog window cancels child task"""
dialog = ConnectorDialog()
# Hide the dialog a short time later.
loop = asyncio.get_event_loop()
loop.call_later(2, dialog.cancel_task)
dialog.show()
with dialog.frame:
ui.Label("Test label")
await dialog.run_cancellable_task(self._mock_cancellable_task())
# Confirm that child task was cancelled
self.assertEqual(dialog._task, None)
dialog.destroy()
class TestDeviceAuthFlowDialog(omni.kit.test.AsyncTestCase):
"""Tests for DeviceAuthFlowDialog."""
# omni.client.AuthDeviceFlowParams can't be initiated directly in python since it didn't define constructors; so
# for testing had to fake an object with those attrs.
class _MockParams():
def __init__(self, server, url, expiration, code) -> None:
self.server = server
self.url = url
self.expiration = expiration
self.code = code
async def setUp(self):
pass
async def tearDown(self):
pass
@staticmethod
def _mock_params(server, url, expiration, code):
return TestDeviceAuthFlowDialog._MockParams(server, url, expiration, code)
async def test_display_and_count_down(self):
"""Test that the dialog displays correctly and counts down correctly."""
# mock qrcode generation so we don't actually generate that
with patch.object(DeviceAuthFlowDialog, "_generate_qrcode") as mock_gen_qrcode:
dialog = DeviceAuthFlowDialog(self._mock_params("dummy", "https://dummy/auth/url", 100, "FOOBAR42"))
self.assertEqual(100, dialog._time_remaining)
# test count down
await asyncio.sleep(1.5)
self.assertGreaterEqual(99, dialog._time_remaining)
# test that qrcode generation is triggered
mock_gen_qrcode.assert_called_once_with("https://dummy/auth/url")
dialog.hide()
dialog.destroy()
async def test_cancel(self):
"""Test that the dialog cancel cancels the authentication and closes."""
# mock qrcode generation so we don't actually generate that
with patch.object(DeviceAuthFlowDialog, "_generate_qrcode"):
dialog = DeviceAuthFlowDialog(self._mock_params("dummy", "https://dummy/auth/url", 100, "FOOBAR42"))
self.assertTrue(dialog.window.visible)
self.assertIsNotNone(dialog._count_down_task)
await ui_test.human_delay(5)
button = ui_test.find_all("Device Authentication//Frame/**/Button[*]")[-1]
self.assertIsNotNone(button)
self.assertEqual(button.widget.text, "Cancel")
await button.click()
await ui_test.human_delay(5)
# check that count down is cancelled and window is hidden
self.assertTrue(dialog._count_down_task.cancelled())
self.assertFalse(dialog.window.visible)
async def test_dialog_expiration_and_retry(self):
"""Test that the dialog correctly counts down and expires, and retry works."""
# mock qrcode generation so we don't actually generate that
with patch.object(DeviceAuthFlowDialog, "_generate_qrcode"), patch("omni.client.reconnect") as mock_reconnect:
dialog = DeviceAuthFlowDialog(self._mock_params("dummy", "https://dummy/auth/url", 1, "FOOBAR42"))
await ui_test.human_delay(5)
buttons = ui_test.find_all("Device Authentication//Frame/**/Button[*]")
retry, cancel = buttons[0], buttons[1]
self.assertFalse(retry.widget.visible)
self.assertTrue(cancel.widget.visible)
# make sure we meet expiration
await asyncio.sleep(1.5)
# retry button should be enabled now
self.assertTrue(retry.widget.visible)
self.assertTrue(cancel.widget.visible)
# click retry should cancel and hide the window, and issue a new reconnect
await retry.click()
await ui_test.human_delay(10)
mock_reconnect.assert_called_once_with("omniverse://dummy")
self.assertFalse(dialog.window.visible)
| 5,927 | Python | 39.054054 | 118 | 0.650076 |
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/tests/test_device_auth.py | ## Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import asyncio
from unittest.mock import patch, Mock
import carb.settings
import omni.kit.test
import omni.client
import omni.kit.ui_test as ui_test
from .. import get_nucleus_connector
from ..test_helper import NucleusConnectorTestHelper
from ..device_auth import DeviceAuthConnector
from ..ui import DeviceAuthFlowDialog
class TestAddServerWithValidationDeviceAuth(omni.kit.test.AsyncTestCase):
"""Testing FilePickerView.add_server_with_validation"""
# omni.client.AuthDeviceFlowParams can't be initiated directly in python since it didn't define constructors; so
# for testing had to fake an object with those attrs.
class _MockParams():
def __init__(self, server, url, expiration, code) -> None:
self.server = server
self.url = url
self.expiration = expiration
self.code = code
async def setUp(self):
self._test_name = "ov-test"
self._test_url = "omniverse://ov-test"
self._expected_stat_results = [omni.client.Result.OK, omni.client.Result.OK]
self._stat_latency = 1
self._iter = 0
# patch qrcode generation so we don't acutally install qrcode module and generates the image
patch_qrcode_gen = patch.object(DeviceAuthFlowDialog, "_generate_qrcode")
patch_qrcode_gen.start()
self.addCleanup(patch_qrcode_gen.stop)
async def tearDown(self):
pass
async def _mock_stat_async_impl(self, url: str):
# During a stat, omni.client triggers the device auth callback.
# The callback was previously set via the subscription method: omni.client.register_device_flow_auth_callback.
ext = get_nucleus_connector()
if self._iter == 0:
if ext:
mock_param = TestAddServerWithValidationDeviceAuth._MockParams(url, "https://dummy/auth", 10, "FOOBAR42")
ext._on_device_auth(1, mock_param)
result = self._expected_stat_results[self._iter]
self._iter += 1
# Simulates the latency due to user signing in through device auth
await asyncio.sleep(self._stat_latency)
ext._on_device_auth(1, None)
return result, {}
def _mock_auth_cancel_impl(self, auth_handle: int):
# A cancellation event also executes the device auth callback, but with the params set to None.
ext = get_nucleus_connector()
if ext:
ext._on_device_auth(auth_handle, None)
async def test_connect_with_dialog_succeeds(self):
"""Testing that connecting to server through dialog succeeds"""
under_test = get_nucleus_connector()
under_test._connector = DeviceAuthConnector()
async with NucleusConnectorTestHelper() as connector_helper:
with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl):
mock_success_fn, mock_failed_fn = Mock(), Mock()
under_test.connect_with_dialog(on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn)
# Connector dialog will show up first prompting for user input
await connector_helper.wait_for_popup()
await connector_helper.click_apply_async(name=self._test_name, url=self._test_url)
await connector_helper.wait_for_close()
# The device auth flow dialog will show up displaying the qrcode etc.
await connector_helper.wait_for_popup(url=self._test_url)
await connector_helper.wait_for_close(timeout=1000, url=self._test_url)
# Confirm on_success callback called
await ui_test.human_delay(10)
mock_success_fn.assert_called_once_with(self._test_name, self._test_url)
mock_failed_fn.assert_not_called()
async def test_connect_with_given_url_succeeds(self):
under_test = get_nucleus_connector()
under_test._connector = DeviceAuthConnector()
async with NucleusConnectorTestHelper() as connector_helper:
with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl):
mock_success_fn, mock_failed_fn = Mock(), Mock()
under_test.connect(self._test_name, self._test_url, on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn)
await ui_test.human_delay(10)
# Only the device auth dialog will show up
await connector_helper.wait_for_popup(url=self._test_url)
await connector_helper.wait_for_close(timeout=1000, url=self._test_url)
# Confirm on_success callback called
await ui_test.human_delay(10)
mock_success_fn.assert_called_once_with(self._test_name, self._test_url)
mock_failed_fn.assert_not_called()
async def test_connect_then_reconnect_succeeds(self):
"""Testing that when connect fails the first time, retries with a reconnect"""
under_test = get_nucleus_connector()
under_test._connector = DeviceAuthConnector()
# In this case, the first stat will result in an error, but will succeed after a reconnect
self._expected_stat_results = [omni.client.Result.ERROR_CONNECTION, omni.client.Result.OK]
async with NucleusConnectorTestHelper() as connector_helper:
with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\
patch("omni.client.reconnect") as mock_reconnect:
mock_success_fn, mock_failed_fn = Mock(), Mock()
under_test.connect(self._test_name, self._test_url, on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn)
await ui_test.human_delay(10)
await connector_helper.wait_for_popup(url=self._test_url)
#await connector_helper.click_apply_async(name=self._test_name, url=self._test_url)
await connector_helper.wait_for_close(timeout=1000, url=self._test_url)
# auth dialog is closed during second stat_async, need wait more time for connect completed
await asyncio.sleep(self._stat_latency)
# Confirm reconnect attempted and connection succeeded
mock_reconnect.assert_called_once_with(self._test_url)
mock_success_fn.assert_called_once_with(self._test_name, self._test_url)
mock_failed_fn.assert_not_called()
async def test_connect_with_url_cancelled(self):
"""Testing that user is able to cancel out of connection flow"""
under_test = get_nucleus_connector()
under_test._connector = DeviceAuthConnector()
async with NucleusConnectorTestHelper() as connector_helper:
with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\
patch("omni.client.authentication_cancel", side_effect=self._mock_auth_cancel_impl):
mock_success_fn, mock_failed_fn = Mock(), Mock()
under_test.connect(self._test_name, self._test_url, on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn)
await ui_test.human_delay(10)
# Only the device auth dialog will show up
await connector_helper.wait_for_popup(url=self._test_url)
# Click cancel after some time
await asyncio.sleep(.5*self._stat_latency)
await connector_helper.click_cancel_async(url=self._test_url)
await connector_helper.wait_for_close(timeout=1000, url=self._test_url)
# Confirm neither callbacks invoked
mock_success_fn.assert_not_called()
mock_failed_fn.assert_not_called()
# make sure we finish the mock stat return
await asyncio.sleep(0.5* self._stat_latency)
async def test_reconnect_with_given_url_succeeds(self):
under_test = get_nucleus_connector()
under_test._connector = DeviceAuthConnector()
self._expected_stat_results = [omni.client.Result.OK]
async with NucleusConnectorTestHelper() as connector_helper:
with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\
patch("omni.client.reconnect") as mock_reconnect:
mock_success_fn, mock_failed_fn = Mock(), Mock()
under_test.reconnect(self._test_url, on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn)
for _ in range(1000):
await omni.kit.app.get_app().next_update_async()
# Confirm on_success callback called
mock_success_fn.assert_called_once_with(self._test_name, self._test_url)
mock_failed_fn.assert_not_called()
mock_reconnect.assert_called_once_with(self._test_url)
| 9,286 | Python | 53.629411 | 127 | 0.645919 |
omniverse-code/kit/exts/omni.kit.widget.nucleus_connector/omni/kit/widget/nucleus_connector/tests/test_connector.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import asyncio
import omni.kit.test
import omni.client
from unittest.mock import patch, Mock
from .. import get_nucleus_connector
from ..test_helper import NucleusConnectorTestHelper
class TestAddServerWithValidation(omni.kit.test.AsyncTestCase):
"""Testing FilePickerView.add_server_with_validation"""
async def setUp(self):
self._test_name = "ov-test"
self._test_url = "omniverse://ov-test"
self._expected_stat_results = [omni.client.Result.OK, omni.client.Result.OK]
self._stat_latency = 1
self._iter = 0
async def tearDown(self):
pass
async def _mock_stat_async_impl(self, url: str):
# During a stat, omni.client triggers the browser sign in flow by executing the _on_authenticate callback.
# The callback was previously set via the subscription method: omni.client.set_authentication_message_box_callback.
if self._iter == 0:
ext = get_nucleus_connector()
if ext:
ext._on_authenticate(True, url, 1)
result = self._expected_stat_results[self._iter]
self._iter += 1
# Simulates the latency due to user signing in through brower
await asyncio.sleep(self._stat_latency)
return result, {}
def _mock_auth_cancel_impl(self, auth_handle: int):
# A cancellation event also executes the _on_authenticate callback, but with the first input set to False.
ext = get_nucleus_connector()
if ext:
ext._on_authenticate(False, None, auth_handle)
async def test_connect_with_dialog_succeeds(self):
"""Testing that connecting to server through dialog succeeds"""
under_test = get_nucleus_connector()
async with NucleusConnectorTestHelper() as connector_helper:
with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl):
mock_success_fn, mock_failed_fn = Mock(), Mock()
under_test.connect_with_dialog(on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn)
await connector_helper.wait_for_popup()
await connector_helper.click_apply_async(name=self._test_name, url=self._test_url)
await connector_helper.wait_for_close(timeout=1000)
# Confirm on_success callback called
mock_success_fn.assert_called_once_with(self._test_name, self._test_url)
mock_failed_fn.assert_not_called()
async def test_connect_with_given_url_succeeds(self):
under_test = get_nucleus_connector()
async with NucleusConnectorTestHelper() as connector_helper:
with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl):
mock_success_fn, mock_failed_fn = Mock(), Mock()
under_test.connect(self._test_name, self._test_url, on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn)
await connector_helper.wait_for_popup()
# Note that it's not necessary to click the apply button; the dialog automatically proceeds to make the
# connection, using the given server name and url.
await connector_helper.wait_for_close(timeout=1000)
# Confirm on_success callback called
mock_success_fn.assert_called_once_with(self._test_name, self._test_url)
mock_failed_fn.assert_not_called()
async def test_connect_with_dialog_cancelled(self):
"""Testing that user is able to cancel out of connection flow"""
under_test = get_nucleus_connector()
async with NucleusConnectorTestHelper() as connector_helper:
with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\
patch("omni.client.authentication_cancel", side_effect=self._mock_auth_cancel_impl):
mock_success_fn, mock_failed_fn = Mock(), Mock()
under_test.connect_with_dialog(on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn)
await connector_helper.wait_for_popup()
await connector_helper.click_apply_async(name=self._test_name, url=self._test_url)
# Click cancel after some time
await asyncio.sleep(.5*self._stat_latency)
await connector_helper.click_cancel_async()
await connector_helper.wait_for_close(timeout=1000)
# Confirm neither callbacks invoked
mock_success_fn.assert_not_called()
mock_failed_fn.assert_not_called()
async def test_connect_then_reconnect_succeeds(self):
"""Testing that when connect fails the first time, retries with a reconnect"""
under_test = get_nucleus_connector()
# In this case, the first stat will result in an error, but will succeed after a reconnect
self._expected_stat_results = [omni.client.Result.ERROR_CONNECTION, omni.client.Result.OK]
async with NucleusConnectorTestHelper() as connector_helper:
with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\
patch("omni.client.reconnect") as mock_reconnect:
mock_success_fn, mock_failed_fn = Mock(), Mock()
under_test.connect_with_dialog(on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn)
await connector_helper.wait_for_popup()
await connector_helper.click_apply_async(name=self._test_name, url=self._test_url)
await connector_helper.wait_for_close(timeout=1000)
# Confirm reconnect attempted and connection succeeded
mock_reconnect.assert_called_once_with(self._test_url)
mock_success_fn.assert_called_once_with(self._test_name, self._test_url)
mock_failed_fn.assert_not_called()
async def test_connect_and_reconnect_fails(self):
"""Testing that both the connect and reconnect attempts fail"""
under_test = get_nucleus_connector()
# In this case, the first stat will result in an error, but will succeed after a reconnect
self._expected_stat_results = [omni.client.Result.ERROR_CONNECTION, omni.client.Result.ERROR_CONNECTION]
async with NucleusConnectorTestHelper() as connector_helper:
with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\
patch("omni.client.reconnect") as mock_reconnect:
mock_success_fn, mock_failed_fn = Mock(), Mock()
under_test.connect_with_dialog(on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn)
await connector_helper.wait_for_popup()
await connector_helper.click_apply_async(name=self._test_name, url=self._test_url)
# Cancel to close the dialog after some time
await asyncio.sleep(2.5*self._stat_latency)
await connector_helper.click_cancel_async()
await connector_helper.wait_for_close(timeout=1000)
# Confirm reconnect attempted and connection succeeded
mock_reconnect.assert_called_once_with(self._test_url)
mock_failed_fn.assert_called_once_with(self._test_name, self._test_url)
mock_success_fn.assert_not_called()
async def test_reconnect_with_given_url_succeeds(self):
under_test = get_nucleus_connector()
self._expected_stat_results = [omni.client.Result.OK]
async with NucleusConnectorTestHelper() as connector_helper:
with patch("omni.client.stat_async", side_effect=self._mock_stat_async_impl),\
patch("omni.client.reconnect") as mock_reconnect:
mock_success_fn, mock_failed_fn = Mock(), Mock()
under_test.reconnect(self._test_url, on_success_fn=mock_success_fn, on_failed_fn=mock_failed_fn)
for _ in range(100):
dialog = connector_helper.get_connector_dialog()
if dialog and dialog.visible:
break
await omni.kit.app.get_app().next_update_async()
await connector_helper.wait_for_close(timeout=1000)
# Confirm on_success callback called
mock_success_fn.assert_called_once_with(self._test_name, self._test_url)
mock_failed_fn.assert_not_called()
mock_reconnect.assert_called_once_with(self._test_url) | 8,946 | Python | 55.626582 | 127 | 0.645093 |
omniverse-code/kit/exts/omni.graph.expression/omni/graph/expression/__init__.py | """There is no public API to this module."""
__all__ = []
from ._impl.extension import _PublicExtension # noqa: F401
import omni.graph.tools as ogt
ogt.DeprecatedImport("Use the omni.graph.scriptnode extension instead")
| 223 | Python | 26.999997 | 71 | 0.735426 |
omniverse-code/kit/exts/omni.graph.expression/omni/graph/expression/_impl/extension.py | """Support required by the Carbonite extension loader."""
import omni.ext
# binding for C++ plugin interface
from ..bindings._omni_graph_expression import acquire_interface as _acquire_interface # noqa: PLE0402
from ..bindings._omni_graph_expression import release_interface as _release_interface # noqa: PLE0402
# python scripted node
from ..nodes.OgnExpression import OgnExpression as _OgnExpression # noqa: PLE0402
class _PublicExtension(omni.ext.IExt):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__interface = None
def on_startup(self):
self.__interface = _acquire_interface()
def on_shutdown(self):
if self.__interface is not None:
_release_interface(self.__interface)
self.__interface = None
_OgnExpression.on_shutdown()
| 845 | Python | 32.839999 | 102 | 0.680473 |
omniverse-code/kit/exts/omni.graph.expression/omni/graph/expression/nodes/OgnExpression.py | import asteval
import carb
import carb.settings
import numpy as np
import omni.graph.core as cg
import omni.kit.pipapi
import omni.stageupdate
from pxr import Sdf
__IMPORT_WHITELIST__ = ["torch", "carb"]
def do_import(module, as_name=""):
if not as_name:
as_name = module
as_name = as_name[as_name.rfind(".") + 1 :]
if not module.startswith("omni."):
exec( # noqa: PLW0122
f"""
try:
globals()["{as_name}"] = __import__("{module}")
except ImportError:
print("{module} not found. attempting to install...")
omni.kit.pipapi.install("{module}")
globals()["{as_name}"] = __import__("{module}")
"""
)
return as_name, globals()[as_name]
def filter_import_list(modules):
out = []
for m in modules:
if m not in __IMPORT_WHITELIST__:
carb.log_warn(f"OgnExpression: import of {m} is not allowed")
else:
out.append(m)
return out
__expr_cache__ = {}
__stage_subscription__ = None
# dummy class for attribute placeholder
class Attrs:
def __init__(self):
return
class ExprCache:
def __init__(self, node):
global __stage_subscription__
self.node = node
if not __stage_subscription__:
stage_update = omni.stageupdate.get_stage_update_interface()
__stage_subscription__ = stage_update.create_stage_update_node(
"OgnExpression", None, OgnExpression.on_detach, None, None, None, OgnExpression.on_removed
)
self.symTable = asteval.make_symbol_table(use_numpy=False, np=np)
self.symTable["inputs"] = Attrs()
# self.symTable["outputs"] = Attrs()
self.eval = asteval.Interpreter(symtable=self.symTable)
@staticmethod
def get(node):
pp = Sdf.Path(node.get_prim_path())
if pp not in __expr_cache__:
return None
return __expr_cache__[pp]
@staticmethod
def clear(prim):
if prim in __expr_cache__:
# print("clear cache",prim)
c = __expr_cache__[prim]
c._stage_subscription = None # noqa: PLW0212
del __expr_cache__[prim]
@staticmethod
def init(node):
pp = Sdf.Path(node.get_prim_path())
cache = ExprCache(node)
__expr_cache__[pp] = cache
return cache
class OgnExpression:
"""Implementation of the OmniGraph expression node"""
@staticmethod
def get_node_type():
return "Expression"
@staticmethod
def get_upstream_attr_or_self(attr):
"""Returns the list of attributes upstream from the given one, or itself if there is nothing upstream"""
attributes_upstream = attr.get_upstream_connections()
return attributes_upstream if attributes_upstream else [attr]
@staticmethod
def compute(context, node):
# if not carb.settings.get_settings().get("/persistent/omnigraph/allowExprNodeExe"):
# return True
need_init = False
_cache = ExprCache.get(node)
if not _cache:
# print("initCache", Sdf.Path(node.get_prim_path()))
_cache = ExprCache.init(node)
if node.get_attribute_exists("import"):
# print("import", Sdf.Path(node.get_prim_path()))
import_list = OgnExpression.get_upstream_attr_or_self(node.get_attribute("import"))
import_list = [m.strip() for m in context.get_attr_value(import_list).split(",") if len(m.strip())]
for m in import_list:
try:
as_name, module = do_import(m)
_cache.symTable[as_name] = module
except (ImportError, KeyError, NameError):
carb.log_error("OgnExpression: failed importing " + m)
continue
need_init = True
attr_names = [n.get_name() for n in node.get_attributes()]
in_attr_names = [a for a in attr_names if a.startswith("inputs:")]
for ia in in_attr_names:
attr = OgnExpression.get_upstream_attr_or_self(node.get_attribute(ia))
setattr(_cache.symTable["inputs"], ia.split(":")[-1], context.get_attr_value(attr))
out_attrs = Attrs()
_cache.symTable["outputs"] = out_attrs
# for oa in out_attr_names:
# attr = OgnExpression.get_upstream_attr_or_self(node.get_attribute(oa))
# setattr(_cache.symTable["outputs"], oa.split(":")[-1], context.get_attr_value(attr))
if need_init and node.get_attribute_exists("initExpr"):
init_expr = OgnExpression.get_upstream_attr_or_self(node.get_attribute("initExpr"))
init_expr = context.get_attr_value(init_expr)
_cache.eval(init_expr)
# exec(init_expr)
expr = OgnExpression.get_upstream_attr_or_self(node.get_attribute("updateExpr"))
expr = context.get_attr_value(expr)
_cache.eval(expr)
# exec(expr)
# lazy update of output values
cach_out_attrs_dict = out_attrs.__dict__
out_attr_names = [a for a in attr_names if a.startswith("outputs:")]
for out_attr_name in out_attr_names:
attr_short_name = out_attr_name[8:] # without "outputs:" prefix
if attr_short_name in cach_out_attrs_dict:
cache_out_attr_val = cach_out_attrs_dict[attr_short_name]
attr = OgnExpression.get_upstream_attr_or_self(node.get_attribute(out_attr_name))
# print("!", out_attr_name, len(cache_out_attr_val), cache_out_attr_val[0])
context.set_attr_value(cache_out_attr_val, attr)
return True
@staticmethod
def on_shutdown():
global __stage_subscription__
__stage_subscription__ = None
@staticmethod
def on_detach():
global __expr_cache__, __stage_subscription__
__expr_cache__ = {}
__stage_subscription__ = None
@staticmethod
def on_removed(prim):
ExprCache.clear(prim)
cg.register_node_type(OgnExpression, 1)
| 6,066 | Python | 33.276836 | 115 | 0.587867 |
omniverse-code/kit/exts/omni.graph.expression/omni/graph/expression/tests/test_api.py | """Testing the stability of the API in this module"""
import omni.graph.core.tests as ogts
import omni.graph.expression as oge
from omni.graph.tools.tests.internal_utils import _check_module_api_consistency, _check_public_api_contents
# ======================================================================
class _TestOmniGraphExpressionApi(ogts.OmniGraphTestCase):
_UNPUBLISHED = ["bindings", "nodes", "tests"]
async def test_api(self):
_check_module_api_consistency(oge, self._UNPUBLISHED) # noqa: PLW0212
_check_module_api_consistency(oge.tests, [], is_test_module=True) # noqa: PLW0212
async def test_api_features(self):
"""Test that the known public API features continue to exist"""
_check_public_api_contents(oge, [], self._UNPUBLISHED, only_expected_allowed=True) # noqa: PLW0212
_check_public_api_contents(oge.tests, [], [], only_expected_allowed=True) # noqa: PLW0212
| 939 | Python | 48.473682 | 107 | 0.654952 |
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/omni/kit/widget/searchable_combobox/combo_model.py | import omni.ui as ui
import omni.kit.app
class ComboBoxListItem(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, text):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
# True when the item is visible
self.filtered = True
def prefilter(self, filter_name_text: str):
if not filter_name_text:
self.filtered = True
else:
self.filtered = filter_name_text in self.name_model.as_string.lower()
def __repr__(self):
return f'"{self.name_model.as_string}"'
class ComboBoxListModel(ui.AbstractItemModel):
_instance = None
def __init__(self, item_list):
super().__init__()
self._children = [ComboBoxListItem(item) for item in item_list]
global _instance
_instance = self
def clean(self):
global _instance
_instance = None
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
return []
return [c for c in self._children if c.filtered]
def get_item_value_model_count(self, item):
"""The number of columns"""
return 1
def get_drag_mime_data(self, item):
"""Returns Multipurpose Internet Mail Extensions (MIME) data for be able to drop this item somewhere"""
# As we don't do Drag and Drop to the operating system, we return the string.
return item.name_model.as_string
def get_item_value_model(self, item, column_id):
return item.name_model
def filter_by_text(self, filter_name_text: str):
"""Specify the filter string that is used to reduce the model"""
for c in self._children:
c.prefilter(filter_name_text.lower())
self._item_changed(None)
def get_index_for_item(self, item_text: str):
for index, item in enumerate(self._children):
if item.name_model.get_value_as_string() == item_text:
return index
return -1
class ComboBoxListDelegate(ui.AbstractItemDelegate):
"""
Delegate is the representation layer. TreeView calls the methods
of the delegate to create custom widgets for each item.
"""
def __init__(self, flat=False):
super().__init__()
def clean(self):
pass
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):
ui.Label(
model.get_item_value_model(item, column_id).as_string,
skip_draw_when_clipped=True,
elided_text=True,
height=18,
)
| 2,759 | Python | 29 | 111 | 0.608191 |
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/omni/kit/widget/searchable_combobox/search_widget.py | import asyncio
import omni.kit.app
import omni.ui as ui
from enum import IntFlag
class SearchModel(ui.AbstractValueModel):
def __init__(self, modified_fn):
super().__init__()
self._modified_fn = modified_fn
self.__str = ""
def is_in_string(self, string: str):
if self.__str == "":
return True
return self.__str.upper() in string.upper()
def set_value(self, value):
self.__str = str(value)
self._value_changed()
if self._modified_fn:
self._modified_fn(self.__str)
def get_value_as_string(self):
return self.__str
class SearchWidget:
def __init__(self, theme: str, icon_path: str, modified_fn: callable = None):
self._search_model = SearchModel(modified_fn=modified_fn)
if not icon_path:
icon_path = (
f"{omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)}/data/icons"
)
if theme == "NvidiaDark":
SEARCH_BODY_COLOR = 0xFF2D2D2D
SEARCH_PLACEHOLDER = 0xFF666666
BUTTON_BACKGROUND_COLOR = 0xFF323434
COMBO_BACKGROUND_COLOR = 0xFF92929
GENERAL_BACKGROUND_COLOR = 0xFF24211F
else:
SEARCH_BODY_COLOR = 0xFF2D2D2D
SEARCH_PLACEHOLDER = 0xFF666666
BUTTON_BACKGROUND_COLOR = 0xFF545454
COMBO_BACKGROUND_COLOR = 0xFF545454
GENERAL_BACKGROUND_COLOR = 0xFF545454
self._style = {
# search_button
"Button.Image::search_button": {
"image_url": f"{icon_path}/search.svg",
"background_color": SEARCH_BODY_COLOR,
"margin": 0,
},
"Button::search_button": {"margin": 0},
"Field::search_button": {"background_color": SEARCH_BODY_COLOR},
"Field::search_button:hovered": {"background_color": SEARCH_BODY_COLOR},
# search placeholder
"Label::search_placeholder": {"color": SEARCH_PLACEHOLDER},
# remove button
"Button.Image::remove": {"image_url": f"{icon_path}/remove.svg"},
"Button.Image::remove:hovered": {"image_url": f"{icon_path}/remove-hovered.svg"},
"Button::remove": {"background_color": SEARCH_BODY_COLOR, "margin": 0},
"Button::remove:hovered": {"background_color": SEARCH_BODY_COLOR, "margin": 0},
# remove button popup (different colors)
"Button::remove_popup": {"background_color": GENERAL_BACKGROUND_COLOR, "margin": 0},
"Button::remove_popup:hovered": {"background_color": GENERAL_BACKGROUND_COLOR, "margin": 0},
"Button.Image::remove_popup": {"image_url": f"{icon_path}/remove.svg"},
"Button.Image::remove_popup:hovered": {"image_url": f"{icon_path}/remove-hovered.svg"},
# find button
"Button::find": {"background_color": BUTTON_BACKGROUND_COLOR},
"Button.Image::find": {"image_url": f"{icon_path}/find.svg"},
# listbox button
"Button.Image::listbox": {"image_url": f"{icon_path}/listbox.svg"},
"Button::listbox": {"background_color": COMBO_BACKGROUND_COLOR, "padding": 6, "margin": 0},
}
def clean(self):
self._field = None
self._search_field = None
self._search_clear = None
self._update_fn = None
def destroy(self):
self._field = None
self._search_field = None
self._search_clear = None
self._update_fn = None
del self._search_model
def update(self, string):
self._placeholder.visible = bool(string == "")
self._search_clear.enabled = not self._placeholder.visible
def focus(self):
async def focus(field):
await omni.kit.app.get_app().next_update_async()
field.focus_keyboard()
asyncio.ensure_future(focus(self._field))
def build_ui(self, width, search_size):
def clear_name(field):
field.model.set_value("")
field.focus_keyboard()
with ui.HStack(width=0, height=0, style=self._style):
ui.Button("", width=search_size, height=search_size, enabled=False, name="search_button")
with ui.ZStack(width=0, height=0):
with ui.HStack(width=0, height=0):
field = ui.StringField(
model=self._search_model, width=width - 46, height=search_size, name="search_button"
)
self._search_clear = ui.Button(
"",
width=search_size,
height=search_size,
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
enabled=False,
clicked_fn=lambda f=field: clear_name(f),
name="remove",
)
self._placeholder = ui.Label(" Search....", height=search_size, name="search_placeholder")
self._field = field
self.focus()
def set_placeholder_text(self, msg: str):
self._placeholder.text = f" {msg}...."
enabled = bool(msg == "Search")
self._field.enabled = enabled
self._field.focus_keyboard(enabled)
def set_text(self, new_text: str):
changed = bool(self._search_field.model.get_value_as_string() != new_text)
self._search_field.model.set_value(new_text)
if changed and self._update_fn:
self._update_fn(self._search_field.model)
def get_text(self):
return self._search_field.model.get_value_as_string()
def build_ui_popup(self, search_size: float, default_value: str, popup_text: str, index: int, update_fn: callable):
def clear_name(name_field):
name_field.model.set_value(default_value)
if update_fn:
update_fn(name_field.model)
self._update_fn = update_fn
open_button = None
name_field = None
with omni.ui.VStack(height=0, spacing=0, style={"margin_width": 0}):
with ui.HStack(style=self._style):
name_field = ui.StringField(height=search_size, enabled=False)
name_field.model.set_value(popup_text)
ui.Button(
"",
width=20,
height=20,
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
clicked_fn=lambda f=name_field: clear_name(f),
name="remove_popup",
)
open_button = ui.Button("", width=20, height=20, image_width=8, name="listbox")
self._search_field = name_field
return name_field, open_button
| 6,818 | Python | 38.877193 | 119 | 0.552655 |
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/omni/kit/widget/searchable_combobox/__init__.py | from .search_widget import SearchModel, SearchWidget
from .combo_model import ComboBoxListItem, ComboBoxListModel, ComboBoxListDelegate
from .combo_widget import ComboListBoxWidget, build_searchable_combo_widget
| 212 | Python | 52.249987 | 82 | 0.863208 |
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/omni/kit/widget/searchable_combobox/combo_widget.py | import asyncio
import carb.input
import omni.kit.app
import omni.appwindow
import omni.ui as ui
from typing import List
from .combo_model import ComboBoxListModel, ComboBoxListDelegate
from .search_widget import SearchWidget
class ComboListBoxWidget:
def __init__(
self,
search_widget: SearchWidget,
item_list: list,
theme: str,
window_id: str = "SearchableComboBoxWindow",
delegate: ui.AbstractItemDelegate = ComboBoxListDelegate(),
):
icon_path = (
f"{omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)}/data/icons"
)
self._height = 32
self._theme = theme
self.__parent = None
self._window = None
self.__frame = None
self._placeholder_search_widget = search_widget
self._search_widget = SearchWidget(theme=theme, icon_path=icon_path, modified_fn=self._search_updated)
self._search_size = 22
self._window_id = window_id
self._name_value_model = ComboBoxListModel(item_list)
self._name_value_delegate = delegate
if theme == "NvidiaDark":
BACKGROUND_COLOR = 0xFF3D3B38
FIELD_TEXT_COLOR = 0xFFD5D5D5
FIELD_BORDER_COLOR = 0
FIELD_HOVER_COLOR = 0xFF383838
else:
BACKGROUND_COLOR = 0xFF545454
FIELD_TEXT_COLOR = 0xFFD5D5D5
FIELD_BORDER_COLOR = 0
FIELD_HOVER_COLOR = 0xFFACACAF
self._window_style = {
"Window": {
"background_color": BACKGROUND_COLOR,
"border_radius": 6,
"border_width": 1,
"border_color": FIELD_BORDER_COLOR,
},
"ScrollingFrame": {"background_color": BACKGROUND_COLOR},
"Field": {
"background_color": BACKGROUND_COLOR,
"color": FIELD_TEXT_COLOR,
"border_color": FIELD_BORDER_COLOR,
"border_radius": 1,
"border_width": 0.5,
"font_size": 16.0,
},
"Field:hovered": {"background_color": FIELD_HOVER_COLOR},
"Field:pressed": {"background_color": FIELD_HOVER_COLOR},
"Field::text_field": {"border_width": 0, "font_size": 14.0},
# search
"TreeView.Item::search_view": {"margin": 4},
"TreeView:selected": {"background_color": 0xFF333333},
}
def set_parent(self, parent):
self.__parent = parent
def clean(self):
if self._name_value_model:
self._name_value_model.clean()
if self._name_value_delegate:
self._name_value_delegate.clean()
if self._search_widget:
self._search_widget.clean()
del self._name_value_model
del self._name_value_delegate
self._placeholder_search_widget = None
self._scrolling_frame = None
self._combo_view = None
del self._window
def _search_updated(self, string):
self._search_widget.update(string)
self._name_value_model.filter_by_text(string)
self._combo_view.scroll_here_y(0.0)
def _select_next(self, comboview: ui.TreeView, model: ui.AbstractItemModel, after=True):
full_list = model.get_item_children(None)
selection = comboview.selection
if not selection:
comboview.selection = [full_list[0]]
else:
index = full_list.index(selection[0])
index += 1 if after else -1
if index < 0 or index >= len(full_list):
return
comboview.selection = [full_list[index]]
def _select_index(self, comboview: ui.TreeView, model: ui.AbstractItemModel, index: int):
full_list = model.get_item_children(None)
selection = comboview.selection
if index >= 0 and index < len(full_list):
comboview.selection = [full_list[index]]
def _get_view_height(self):
item_count = len(self._name_value_model.get_item_children(None))
view_height = (min(10, item_count) * self._height + 1.5) + 4
view_height_min = (3 * self._height + 1.5) + 4
try:
appwindow = omni.appwindow.get_default_app_window()
window_height = appwindow.get_height()
window_height = (window_height / ui.Workspace.get_dpi_scale()) - 8
if self._window.position_y + view_height > window_height:
adj = ((self._window.position_y + view_height) - window_height) + self._search_size
view_height -= adj
if view_height < view_height_min:
view_height = view_height_min
except:
pass
return view_height
def destroy_ui(self, visible):
if not visible:
self.set_parent(None)
self.clean()
def build_ui(self):
if self._window and self._window.visible:
return
# Create and show the window
self._window = ui.Window(
self._window_id,
flags=ui.WINDOW_FLAGS_POPUP
| ui.WINDOW_FLAGS_NO_TITLE_BAR
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_MOVE,
auto_resize=True,
padding_x=0,
padding_y=0,
)
self._window.frame.set_style(self._window_style)
self._window.set_visibility_changed_fn(self.destroy_ui)
def view_clicked(view):
async def get_selection():
await omni.kit.app.get_app().next_update_async()
selection = view.selection
model = selection[0].name_model
self._placeholder_search_widget.set_text(model.get_value_as_string())
self._window.visible = False
asyncio.ensure_future(get_selection())
self._window.position_x = self.__parent.screen_position_x
self._window.position_y = self.__parent.screen_position_y + 20
with self._window.frame:
with ui.VStack(width=0, height=0):
self._search_widget.build_ui(self.__parent.computed_content_width + 40, self._search_size)
self._scrolling_frame = ui.ScrollingFrame(
height=self._get_view_height(),
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with self._scrolling_frame:
self._combo_view = ui.TreeView(
self._name_value_model,
delegate=self._name_value_delegate,
root_visible=False,
header_visible=False,
name="search_view",
)
self._combo_view.set_mouse_released_fn(lambda x, y, b, c: view_clicked(self._combo_view))
async def scroll_to_item():
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
item_index = self._name_value_model.get_index_for_item(self._placeholder_search_widget.get_text())
self._select_index(self._combo_view, self._name_value_model, item_index)
asyncio.ensure_future(scroll_to_item())
def destroy(self):
self.__parent = None
self.__frame = None
self._scrolling_frame = None
self._combo_view = None
del self._window
def build_searchable_combo_widget(
combo_list: List[str],
combo_index: int,
combo_click_fn: callable,
widget_height: int,
default_value: str,
window_id: str = "SearchableComboBoxWindow",
delegate: ui.AbstractItemDelegate = ComboBoxListDelegate(),
) -> SearchWidget:
theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
def show_combo_popup(
search_widget: SearchWidget, name_field: ui.StringField, combo_index: int, combo_click_fn: callable
):
window = ui.Workspace.get_window(window_id)
if window:
window.visible = False
return
listbox_widget = ComboListBoxWidget(
search_widget=search_widget, item_list=combo_list, window_id=window_id, delegate=delegate, theme=theme
)
listbox_widget.set_parent(name_field)
listbox_widget.build_ui()
search_widget = SearchWidget(theme=theme, icon_path=None)
name_field, listbox_button = search_widget.build_ui_popup(
search_size=widget_height,
default_value=default_value,
popup_text=combo_list[combo_index] if combo_index >= 0 else default_value,
index=combo_index,
update_fn=combo_click_fn,
)
name_field.set_mouse_pressed_fn(
lambda x, y, b, m, s=search_widget, f=name_field: show_combo_popup(s, f, combo_index, combo_click_fn)
)
listbox_button.set_mouse_pressed_fn(
lambda x, y, b, m, s=search_widget, f=name_field: show_combo_popup(s, f, combo_index, combo_click_fn)
)
return search_widget
| 9,205 | Python | 36.57551 | 118 | 0.576534 |
omniverse-code/kit/exts/omni.kit.widget.searchable_combobox/omni/kit/widget/searchable_combobox/tests/test_search.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import pathlib
import carb
import omni.ui as ui
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from omni.kit.widget.searchable_combobox import build_searchable_combo_widget, ComboBoxListDelegate
class TestSearchableComboWidget(AsyncTestCase):
async def test_searchable_combo_widget(self):
delegate_called = False
class TestDelegate(ComboBoxListDelegate):
def build_widget(self, model, item, column_id, level, expanded):
nonlocal delegate_called
delegate_called = True
ui.Label(
model.get_item_value_model(item, column_id).as_string,
skip_draw_when_clipped=True,
elided_text=True,
height=18,
)
callback_calls = 0
callback_value = None
window = ui.Window("WidgetTest", width=1000, height=700)
with window.frame:
with ui.VStack(height=0, spacing=8, style={"margin_width": 2}):
ui.Spacer()
with ui.HStack():
ui.Label("Component", width=140)
def on_combo_click_fn(model):
nonlocal callback_calls
callback_calls += 1
self.assertTrue(model.get_value_as_string() == callback_value)
component_list = [
"3d Reconstruction",
"AEC Experience",
"AI Framework",
"AI Toybox",
"AR Experience",
"ArtTech",
"Asset Converter Service",
"Asset Management",
"Physics Research",
"PhysX Third Party Integrations",
"Pinocchio",
"PLC",
"Point Clouds",
"Pose Tracker",
"QA Builds",
"QA Needs Repro",
"Repo Tools",
"Reshade",
"Resolvers",
"RTX",
"RTX Hydra",
"RTX MGPU",
"RTX Renderer",
"Sample Content",
"SDG",
"Sequencer",
"Server Installer",
"Showroom",
"Synthetic Data",
"USD",
"USD Delta Library",
"USD Hydra",
"Kit",
"USDRT",
"UX",
"UX / UI",
"Virtual Production",
"XR",
]
component_index = -1
component_combo = build_searchable_combo_widget(
component_list,
component_index,
on_combo_click_fn,
widget_height=18,
default_value="Kit",
window_id="SearchableComboBoxWindow##test_searchable_combo_widget",
delegate=TestDelegate(),
)
# test set_text & get_text
await ui_test.human_delay()
callback_value = "USD"
component_combo.set_text("USD")
await ui_test.human_delay()
self.assertTrue(component_combo.get_text() == "USD")
self.assertTrue(callback_calls == 1)
# test clear & default
clear_widget = ui_test.find("WidgetTest//Frame/**/Button[*].name=='remove_popup'")
callback_value = "Kit"
await clear_widget.click()
self.assertTrue(component_combo.get_text() == "Kit")
self.assertTrue(callback_calls == 2)
# test combo open and typing
text_field = ui_test.find("WidgetTest//Frame/**/StringField[*]")
await text_field.click()
# TODO: text_field.input("ArtTech") don't work here as it does a double_click
await ui_test.emulate_char_press("ArtTech")
await ui_test.human_delay()
treeview_widget = ui_test.find("SearchableComboBoxWindow##test_searchable_combo_widget//Frame/**/TreeView[*]")
callback_value = "ArtTech"
# y+8 to make sure mouse pointer is on popup window (combobox item list), so 1st item is selected
await ui_test.emulate_mouse_move_and_click(
ui_test.Vec2(treeview_widget.center.x, treeview_widget.widget.screen_position_y + 8)
)
self.assertTrue(component_combo.get_text() == callback_value)
self.assertTrue(callback_calls == 3)
# holding onto this varaible prevents ComboListBoxWidget from getting garbage collected.
treeview_widget = None
# test combo open button and typing
open_widget = ui_test.find("WidgetTest//Frame/**/Button[*].name=='listbox'")
await open_widget.click()
# as this opens popup window, need to wait for that to be created and ready to use
await ui_test.human_delay()
await ui_test.emulate_char_press("Pinocchio")
treeview_widget = ui_test.find("SearchableComboBoxWindow##test_searchable_combo_widget//Frame/**/TreeView[*]")
callback_value = "Pinocchio"
# y+8 to make sure mouse pointer is on popup window (combobox item list), so 1st item is selected
await ui_test.emulate_mouse_move_and_click(
ui_test.Vec2(treeview_widget.center.x, treeview_widget.widget.screen_position_y + 8)
)
self.assertTrue(component_combo.get_text() == callback_value)
self.assertTrue(callback_calls == 4)
# holding onto this varaible prevents ComboListBoxWidget from getting garbage collected.
treeview_widget = None
# test search clear
await text_field.click()
await ui_test.emulate_char_press("this will be cleared...")
await ui_test.human_delay()
clear_widget = ui_test.find(
"SearchableComboBoxWindow##test_searchable_combo_widget//Frame/**/Button[*].name=='remove'"
)
await clear_widget.click()
await ui_test.emulate_char_press("Asset Converter Service")
treeview_widget = ui_test.find("SearchableComboBoxWindow##test_searchable_combo_widget//Frame/**/TreeView[*]")
callback_value = "Asset Converter Service"
await ui_test.emulate_mouse_move_and_click(
ui_test.Vec2(treeview_widget.center.x, treeview_widget.widget.screen_position_y + 8)
)
self.assertTrue(component_combo.get_text() == "Asset Converter Service")
self.assertTrue(callback_calls == 5)
# holding onto this varaible prevents ComboListBoxWidget from getting garbage collected.
treeview_widget = None
# test delegate was called
self.assertTrue(delegate_called)
| 7,501 | Python | 43.390532 | 118 | 0.54926 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/camera_widget_delegate_manager.py | from .abstract_camera_widget_delegate import AbstractCameraButtonDelegate, AbstractCameraMenuItemDelegate
from pxr import Sdf
class CameraWidgetDelegateManager:
def destroy(self):
for delegate in AbstractCameraButtonDelegate.get_instances():
delegate.destroy()
for delegate in AbstractCameraMenuItemDelegate.get_instances():
delegate.destroy()
def __get_all_delegates(self, camera_button_or_menu_item: bool):
all_widget_delegates = []
if camera_button_or_menu_item:
for delegate in AbstractCameraButtonDelegate.get_instances():
all_widget_delegates.append(delegate)
else:
for delegate in AbstractCameraMenuItemDelegate.get_instances():
all_widget_delegates.append(delegate)
# Sort list in ascending order.
all_widget_delegates.sort(key=lambda item: item.order)
return all_widget_delegates
def build_widgets(
self, parent_id, viewport_api, camera_path: Sdf.Path, camera_button_or_menu_item: bool
):
"""Build all camera widgets for specific camera path with sort based on their orders."""
all_widget_delegates = self.__get_all_delegates(camera_button_or_menu_item)
for delegate in all_widget_delegates:
delegate.build_widget(parent_id, viewport_api, camera_path)
def on_parent_destroyed(self, parent_id, camera_button_or_menu_item: bool) -> None:
# Clean up when parent widget destroyed
all_widget_delegates = self.__get_all_delegates(camera_button_or_menu_item)
for delegate in all_widget_delegates:
delegate.on_parent_destroyed(parent_id)
def on_camera_path_changed(self, parent_id, camera_path, camera_button_or_menu_item: bool):
"""The camera tracked has changed."""
all_widget_delegates = self.__get_all_delegates(camera_button_or_menu_item)
for delegate in all_widget_delegates:
delegate.on_camera_path_changed(parent_id, camera_path) | 2,035 | Python | 40.55102 | 105 | 0.682555 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/camera_list_delegate.py | __all__ = ["CameraListDelegate"]
import carb
import omni.usd
import omni.ui as ui
from typing import Optional
from omni.kit.viewport.menubar.core import IconMenuDelegate, USDAttributeModel
from pxr import Sdf
from .camera_widget_delegate_manager import CameraWidgetDelegateManager
class CameraListDelegate(IconMenuDelegate):
def __init__(self, viewport_api, widget_delegate_manager: CameraWidgetDelegateManager):
self.__model: Optional[USDAttributeModel] = None
self.__sub = None
self.__viewport_api = viewport_api
self.__selected_camera_path = Sdf.Path.emptyPath
self.__widget_delegate_manager = widget_delegate_manager
super().__init__("UnlockedCamera", text=True, build_custom_widgets=self.__build_custom_widgets)
def destroy(self):
self.__sub = None
if self.__widget_delegate_manager:
self.__widget_delegate_manager.on_parent_destroyed(id(self), True)
self.__widget_delegate_manager = None
super().destroy()
def __build_custom_widgets(self, item: ui.MenuItem):
if not self.__widget_delegate_manager:
return
try:
self.__widget_delegate_manager.build_widgets(
id(self), self.__viewport_api, self.__selected_camera_path, True
)
except Exception as e:
carb.log_error(f"Failed to build widget: {str(e)}")
def _build_icon(self):
# with vstack to not trigger menu if click on icon
if self._text:
with ui.VStack(content_clipping=True, width=0):
icon = super()._build_icon()
icon.set_mouse_pressed_fn(lambda x, y, b, a: self.__toggle_lock())
else:
icon = super()._build_icon()
icon.name = self.__get_icon_name()
return icon
@property
def camera_path(self) -> Sdf.Path:
return self.__selected_camera_path
@camera_path.setter
def camera_path(self, path):
self.__selected_camera_path = path
if self.__widget_delegate_manager:
self.__widget_delegate_manager.on_camera_path_changed(id(self), path, True)
@property
def model(self) -> USDAttributeModel:
return self.__model
@model.setter
def model(self, new_model: USDAttributeModel) -> None:
self.__model = new_model
icon_name = self.__get_icon_name()
if hasattr(self, "icon"):
self.icon.name = icon_name
else:
self._name = icon_name
if self.__sub:
self.__sub = None
if self.__model:
self.__sub = self.__model.subscribe_value_changed_fn(self._on_lock_changed)
def __get_icon_name(self):
if not self.__model:
return "UnlockedCameraWithoutHovered"
hov_text = "" if bool(self._text) else "WithoutHovered"
lock_text = "LockedCamera" if self.__model.as_bool else "UnlockedCamera"
return f"{lock_text}{hov_text}"
def _on_lock_changed(self, model: ui.AbstractValueModel) -> None:
icon_name = self.__get_icon_name()
if hasattr(self, "icon"):
self.icon.name = icon_name
else:
self._name = icon_name
def __toggle_lock(self):
if self.__model:
self.__model.set_value(not self.__model.as_bool) | 3,346 | Python | 33.505154 | 103 | 0.604603 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/style.py | from omni.ui import color as cl
import carb.tokens
from pathlib import Path
ICON_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.viewport.menubar.camera}")).joinpath("data").joinpath("icons").absolute()
ICON_CORE_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.kit.viewport.menubar.core}")).joinpath("data").joinpath("icons").absolute()
UI_STYLE = {
"Menu.Item.Icon::UnlockedCamera": {"image_url": f"{ICON_PATH}/camera_viewport.svg"},
"Menu.Item.Icon::UnlockedCameraWithoutHovered": {"image_url": f"{ICON_PATH}/camera_viewport.svg"},
"Menu.Item.Icon::UnlockedCamera:hovered": {"image_url": f"{ICON_PATH}/lock_dark.svg"},
"Menu.Item.Icon::LockedCamera": {"image_url": f"{ICON_PATH}/viewport_cameras_locked.svg"},
"Menu.Item.Icon::LockedCameraWithoutHovered": {"image_url": f"{ICON_PATH}/viewport_cameras_locked.svg"},
"Menu.Item.Icon::LockedCamera:hovered": {"image_url": f"{ICON_PATH}/unlock_dark.svg"},
"Menu.Item.Icon::Expand": {"image_url": f"{ICON_PATH}/expand.svg", "color": cl.viewport_menubar_background},
"Menu.Item.Icon::Expand:checked": {"image_url": f"{ICON_PATH}/contract.svg"},
"Menu.Item.Icon::Lock": {"image_url": f"{ICON_PATH}/unlock_dark.svg", "color": cl.viewport_menubar_background},
"Menu.Item.Icon::Lock:checked": {"image_url": f"{ICON_PATH}/lock_dark.svg"},
"Menu.Item.Icon::Sample": {"image_url": f"{ICON_PATH}/focalSample_viewport.svg"},
"Menu.Item.Icon::Sample:disabled": {"color": cl.viewport_menubar_medium},
"Menu.Item.Icon::Add": {"image_url": f"{ICON_PATH}/add.svg", "color": cl.viewport_menubar_selection_border},
"Menu.Item.Icon::Lens": {"image_url": f"{ICON_PATH}/lens.svg"},
"Menu.Item.Icon::FocalDistance": {"image_url": f"{ICON_PATH}/focal_distance.svg"},
"Menu.Item.Icon::FStop": {"image_url": f"{ICON_PATH}/Fstop.svg"},
"Menu.Item.Button": {
"background_color": 0,
"margin": 0,
"padding": 0,
},
"Menu.Item.Button.Image::OptionBox": {"image_url": f"{ICON_CORE_PATH}/settings_submenu.svg"},
"Menu.Item.Button.Image::CameraLocked": {"image_url": f"{ICON_PATH}/lock_dark.svg"},
"Menu.Item.Button.Image::CameraUnlocked": {"image_url": f"{ICON_PATH}/unlock_dark.svg"},
"MenuBar.Item::transparent": {
# "color": 0,
},
}
| 2,311 | Python | 61.486485 | 148 | 0.663349 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/commands.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.kit.commands
import omni.usd
from pxr import Gf, Sdf, Usd, UsdGeom
from typing import Union
import carb
CAMERA_LOCK_NAME = "omni:kit:cameraLock"
class DuplicateCameraCommand(omni.kit.commands.Command):
"""
Duplicates a camera at a specific time
Args:
camera_path (str): name of the camera to duplicate.
time (float): Time at which to duplicate, or None to use active time
usd_context_name (str): The name of a valid omni.UsdContext to target
new_camera_path (str): Path to create the new camera at (None for automatic path)
"""
def __init__(self, camera_path: str = "", time: float = None, usd_context_name: str = '', new_camera_path: str = None):
self.__camera_path = camera_path
self.__usd_context_name = usd_context_name
self.__time = time if time is not None else omni.timeline.get_timeline_interface().get_current_time()
self.__new_camera_path = new_camera_path
def do(self):
if not self.__camera_path:
return
usd_context = omni.usd.get_context(self.__usd_context_name)
if not usd_context:
raise RuntimeError(f'UsdContext "{self.self.__usd_context_name}" could not be found')
stage = usd_context.get_stage()
if not stage:
raise RuntimeError(f'UsdContext "{self.self.__usd_context_name}" has no stage')
old_prim = stage.GetPrimAtPath(self.__camera_path)
if not old_prim:
raise RuntimeError(f'Could not find camera prim at "{self.__camera_path}"')
if self.__new_camera_path is None:
target_path = omni.usd.get_stage_next_free_path(stage, "/Camera", True)
else:
target_path, self.__new_camera_path = self.__new_camera_path, None
omni.kit.commands.execute("CreatePrimWithDefaultXformCommand", prim_path=target_path,
prim_type="Camera", create_default_xform=False, stage=stage)
new_prim = stage.GetPrimAtPath(target_path)
if not new_prim:
raise RuntimeError(f'Could not find duplicated prim at "{target_path}"')
# Save the created camera path now so any failure below won't kill our undo
self.__new_camera_path = target_path
timecode = self.__time * stage.GetTimeCodesPerSecond()
for attr in old_prim.GetAttributes():
attr_name = attr.GetName()
# Skip over any xformOp property (they are not duplicated but created below)
if UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(attr_name):
continue
# Skip over the locked property
if attr_name == CAMERA_LOCK_NAME:
continue
value = attr.Get(timecode)
if value is not None:
new_prim.CreateAttribute(attr.GetName(), attr.GetTypeName()).Set(value)
# Now create the transform, taking the original world-space of the source camera and putting it into
# the new camera's parent's space. We do this always so that TransformPrim can create the correct
# rotation ordering now.
parent_xformable = UsdGeom.Xformable(new_prim.GetParent())
if parent_xformable:
parent_world_xform = omni.usd.get_world_transform_matrix(parent_xformable.GetPrim(), timecode)
else:
parent_world_xform = Gf.Matrix4d(1)
old_camera_prim_world_mtx = omni.usd.get_world_transform_matrix(old_prim, timecode)
new_camera_prim_local_mtx = old_camera_prim_world_mtx * parent_world_xform.GetInverse()
omni.kit.commands.execute(
"TransformPrim", path=new_prim.GetPath(),
new_transform_matrix=new_camera_prim_local_mtx,
usd_context_name=self.__usd_context_name
)
# These won't be undone, but that's ok..undo will delete the prim
omni.usd.editor.set_no_delete(new_prim, False)
omni.usd.editor.set_hide_in_stage_window(new_prim, False)
def undo(self):
pass
class SetViewportCameraCommand(omni.kit.commands.Command):
"""
Sets a Viewport's actively bound camera to camera at given path
Args:
camera_path (Union[str, Sdf.Path): New camera path to bind to viewport.
viewport_api: the viewport to target.
"""
def __init__(self, camera_path: Union[str, Sdf.Path], viewport_api, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__viewport_api = viewport_api
self.__prev_camera = viewport_api.camera_path
self.__target_camera = camera_path
self.__look_target = None
self.__coi_value = None
@staticmethod
def read_camera_path(viewport_api) -> Sdf.Path:
stage = viewport_api.stage
if stage:
# TODO: 104 Put in proper namespace and per viewport
# camera_path = stage.GetMetadataByDictKey("customLayerData", f"cameraSettings:{viewport_api.id}:boundCamera") or
# Fallback to < 103.1 boundCamera
camera_path = stage.GetMetadataByDictKey("customLayerData", "cameraSettings:boundCamera")
if camera_path:
prim = stage.GetPrimAtPath(camera_path)
if prim and UsdGeom.Camera(prim):
return prim.GetPath()
return None
def __save_to_file(self, camera_path: str):
viewport_api = self.__viewport_api
stage = viewport_api.stage
# Allow (but warn) the case if no Usd.Stage
if not stage:
carb.log_warn("No Usd.Stage to set boundCamera to")
return
# Error if not root-layer
layer = stage.GetRootLayer()
if not layer:
carb.log_error("No Usd.Layer to set boundCamera to")
return
# Move the EditTarget to the root-layer and set meta-data there
with Usd.EditContext(stage, Usd.EditTarget(layer)):
# TODO: 104 Put in proper namespace and per viewport
# stage.SetMetadataByDictKey("customLayerData", f"cameraSettings:{viewport_api.id}boundCamera", camera_path)
# Save the legacy version for opening in versions < 103.1
stage.SetMetadataByDictKey("customLayerData", "cameraSettings:boundCamera", camera_path)
def do(self):
self.__viewport_api.camera_path = self.__target_camera
self.__save_to_file(str(self.__target_camera))
def undo(self, look_through=None):
# Set the viewport to use the previous camera
self.__viewport_api.camera_path = self.__prev_camera
self.__save_to_file(str(self.__prev_camera))
class DuplicateViewportCameraCommand(omni.kit.commands.Command):
"""
Duplicates a Viewport's actively bound camera and bind active camera to the duplicated one.
Args:
viewport_api: The viewport to target
"""
def __init__(self, viewport_api, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__viewport_api = viewport_api
def do(self):
viewport_api = self.__viewport_api
new_camera_path = omni.usd.get_stage_next_free_path(viewport_api.stage, "/Camera", True)
omni.kit.commands.execute("DuplicateCameraCommand", camera_path=viewport_api.camera_path, usd_context_name=viewport_api.usd_context_name, new_camera_path=new_camera_path)
omni.kit.commands.execute("SetViewportCameraCommand", camera_path=new_camera_path, viewport_api=viewport_api)
def undo(self):
pass
def register_commands():
return omni.kit.commands.register_all_commands_in_module(__name__)
def unregister_commands(cmds):
omni.kit.commands.unregister_module_commands(cmds)
| 8,066 | Python | 41.457895 | 178 | 0.651128 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/extension.py | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ViewportCameraMenuBarExtension", "get_instance", "SingleCameraMenuItemBase", "SingleCameraMenuItem"]
from typing import Callable
from .camera_menu_container import CameraMenuContainer
from .commands import register_commands, unregister_commands
import omni.ext
import omni.ui as ui
from .menu_item.single_camera_menu_item import SingleCameraMenuItemBase, SingleCameraMenuItem
_extension_instance = None
def get_instance():
global _extension_instance
return _extension_instance
class ViewportCameraMenuBarExtension(omni.ext.IExt):
"""The Entry Point for the Display Settings in Viewport Menu Bar"""
def on_startup(self, ext_id):
self._camera_menu = CameraMenuContainer()
self._cmds = register_commands()
global _extension_instance
_extension_instance = self
def on_shutdown(self):
if self._camera_menu:
self._camera_menu.destroy()
self._camera_menu = None
cmds, self._cmds = self._cmds, None
unregister_commands(cmds)
global _extension_instance
_extension_instance = None
def register_menu_item_type(self, menu_item_type: Callable[..., "SingleCameraMenuItemBase"]):
"""
Register a custom menu type for the default created camera
Args:
menu_item_type: callable that will create the menu item
"""
if self._camera_menu:
self._camera_menu.set_menu_item_type(menu_item_type)
def register_menu_item(self, create_menu_item_fn: Callable[["viewport_context", ui.Menu], None], order: int = 0):
"""
Register a custom menu item.
Args:
create_menu_item_fn (Callable): Callback function to create custom menu item.
Kwargs:
order (int): Position to put cusom menu item in popup menu window.
"""
if self._camera_menu:
self._camera_menu.register_menu_item(create_menu_item_fn, order=order)
def deregister_menu_item(self, create_menu_item_fn: Callable[["viewport_context", ui.Menu], None]):
"""
Deregister a custom menu item.
Args:
create_menu_item_fn (Callable): Callback function to create custom menu item.
"""
if self._camera_menu:
self._camera_menu.deregister_menu_item(create_menu_item_fn)
| 2,773 | Python | 35.5 | 117 | 0.681212 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/__init__.py | from .extension import *
from .abstract_camera_widget_delegate import * | 71 | Python | 34.999983 | 46 | 0.802817 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/utils.py | import omni.usd
from pxr import Sdf, Usd
from typing import Optional
SESSION_CAMERAS = {
"/OmniverseKit_Persp": "Perspective",
"/OmniverseKit_Top": "Top",
"/OmniverseKit_Front": "Front",
"/OmniverseKit_Right": "Right",
}
def get_camera_display(path: Sdf.Path, stage: Optional[Usd.Stage] = None):
name = SESSION_CAMERAS.get(path.pathString, None)
if name:
return name
if stage:
camera_prim = stage.GetPrimAtPath(path)
if camera_prim:
display_name = omni.usd.editor.get_display_name(camera_prim)
if display_name:
return display_name
return path.name
| 650 | Python | 23.11111 | 74 | 0.635385 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/abstract_camera_widget_delegate.py | __all__ = ["AbstractCameraButtonDelegate", "AbstractCameraMenuItemDelegate"]
import abc
import weakref
import omni.ui as ui
from enum import IntEnum
from pxr import Sdf
from typing import Optional
class AbstractWidgetDelegate(abc.ABC):
"""
The base class for camera widget delegate. This delegate works for providing the
additional camera widget for items of camera list.
"""
@abc.abstractmethod
def build_widget(self, parent_id, viewport_api, camera_path: Sdf.Path) -> Optional[ui.Widget]:
"""
Builds widget. This must be overrided to provide the layout.
parent_id: It's unique id of the camera item, with which you
can use to manage the camera widget.
viewport_api: Viewport interface.
camera_path (Sdf.Path): The camera path to build widget for.
"""
pass
@abc.abstractmethod
def on_parent_destroyed(self, parent_id) -> None:
"""
Called before the destroy of the parent widget. This function
can be overrided to release the bound resources specific to
the parent.
"""
pass
@abc.abstractmethod
def on_camera_path_changed(self, parent_id, camera_path):
"""The camera tracked has changed."""
pass
def destroy(self):
"""Place to release resources."""
pass
@property
def order(self) -> int:
"""
The order of the widget relative to the right of camera label.
The lower the order number, the closer the widget to the camera label.
"""
return 0
class AbstractCameraButtonDelegate(AbstractWidgetDelegate):
# Use a list to track all instances
__g_registered = []
@classmethod
def get_instances(cls):
remove = []
# Return a copy to avoid remove in the middle of iterating.
all_instances = AbstractCameraButtonDelegate.__g_registered.copy()
for wref in all_instances:
obj = wref()
if obj:
yield obj
else:
remove.append(wref)
for wref in remove:
AbstractCameraButtonDelegate.__g_registered.remove(wref)
def __init__(self):
super().__init__()
self.__g_registered.append(
weakref.ref(self, lambda r: AbstractCameraButtonDelegate.__g_registered.remove(r))
)
def __del__(self):
self.destroy()
def destroy(self):
"""Place for releasing resources."""
for wref in AbstractCameraButtonDelegate.__g_registered:
if wref() == self:
AbstractCameraButtonDelegate.__g_registered.remove(wref)
break
super().destroy()
class AbstractCameraMenuItemDelegate(AbstractWidgetDelegate):
# Use a list to track all instances
__g_registered = []
@classmethod
def get_instances(cls):
remove = []
# Return a copy to avoid remove in the middle of iterating.
all_instances = AbstractCameraMenuItemDelegate.__g_registered.copy()
for wref in all_instances:
obj = wref()
if obj:
yield obj
else:
remove.append(wref)
for wref in remove:
AbstractCameraMenuItemDelegate.__g_registered.remove(wref)
def __init__(self):
super().__init__()
self.__g_registered.append(
weakref.ref(self, lambda r: AbstractCameraMenuItemDelegate.__g_registered.remove(r))
)
def __del__(self):
self.destroy()
def destroy(self):
"""Place for releasing resources."""
for wref in AbstractCameraMenuItemDelegate.__g_registered:
if wref() == self:
AbstractCameraMenuItemDelegate.__g_registered.remove(wref)
break
super().destroy()
class CameraWidgetDelegateManager:
def destroy(self):
for delegate in AbstractCameraButtonDelegate.get_instances():
delegate.destroy()
for delegate in AbstractCameraMenuItemDelegate.get_instances():
delegate.destroy()
def __get_all_delegates(self, camera_button_or_menu_item: bool):
all_widget_delegates = []
if camera_button_or_menu_item:
for delegate in AbstractCameraButtonDelegate.get_instances():
all_widget_delegates.append(delegate)
else:
for delegate in AbstractCameraMenuItemDelegate.get_instances():
all_widget_delegates.append(delegate)
# Sort list in ascending order.
all_widget_delegates.sort(key=lambda item: item.order)
def build_widgets(
self, parent_id, viewport_api, camera_path: Sdf.Path, camera_button_or_menu_item: bool
):
"""Build all camera widgets for specific camera path with sort based on their orders."""
all_widget_delegates = self.__get_all_delegates(camera_button_or_menu_item)
for delegate in all_widget_delegates:
delegate.build_widget(parent_id, viewport_api, camera_path)
def on_parent_destroyed(self, parent_id, camera_button_or_menu_item: bool) -> None:
all_widget_delegates = self.__get_all_delegates(camera_button_or_menu_item)
for delegate in all_widget_delegates:
delegate.on_parent_destroyed(parent_id)
def on_camera_path_changed(self, parent_id, camera_path, camera_button_or_menu_item: bool):
all_widget_delegates = self.__get_all_delegates(camera_button_or_menu_item)
for delegate in all_widget_delegates:
delegate.on_camera_path_changed(parent_id, camera_path) | 5,626 | Python | 30.261111 | 98 | 0.626911 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/camera_menu_container.py | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["CameraMenuContainer"]
from omni.kit.async_engine import run_coroutine
from omni.kit.viewport.menubar.core import (
ViewportMenuDelegate,
SeparatorDelegate,
ViewportMenuContainer,
USDAttributeModel,
USDFloatAttributeModel,
menu_is_tearable,
MenuDisplayStatus
)
from .menu_item.lens import CameraLens
from .menu_item.focal_distance import CameraFocalDistance
from .menu_item.fstop import CameraFStop
from .menu_item.auto_exposure import CameraAutoExposure
from .menu_item.single_camera_menu_item import SingleCameraMenuItem, NoCameraMenuItem
from .menu_item.expand_menu_item import ExpandMenuItem
from .commands import SetViewportCameraCommand
from .camera_list_delegate import CameraListDelegate
from .style import UI_STYLE
from .utils import SESSION_CAMERAS, get_camera_display
from functools import partial
from pxr import Sdf, Tf, Trace, Usd, UsdGeom
from typing import Callable, Dict, List, Optional, Set, TYPE_CHECKING, Tuple, Union
from .camera_widget_delegate_manager import CameraWidgetDelegateManager
import asyncio
from dataclasses import dataclass, fields, field
import carb
import functools
import omni.ui as ui
import omni.usd
import omni.kit.commands
import omni.timeline
import traceback
import weakref
import concurrent.futures
if TYPE_CHECKING:
from .menu_item.single_camera_menu_item import SingleCameraMenuItemBase
CAMERA_LOCK_NAME = "omni:kit:cameraLock"
def handle_exception(func):
"""
Decorator to print exception in async functions
"""
@functools.wraps(func)
async def wrapper(*args, **kwargs):
try:
return await func(*args, **kwargs)
except Exception as e:
carb.log_error(f"Exception when async '{func}'")
carb.log_error(f"{e}")
carb.log_error(f"{traceback.format_exc()}")
return wrapper
def _show_camera_in_menu(prim: Usd.Prim):
return prim and prim.IsA(UsdGeom.Camera) and not omni.usd.editor.is_hide_in_ui(prim)
class _CameraList:
"""The object that watches USD for the list of cameras"""
def __init__(self, stage, callback):
self.__stage: Usd.Stage = stage
self.__callback: Callable[[], None] = callback
self.__cameras: Set[Sdf.Path] = set()
self.__listener = None
self.__dirty = True
self.__camera_filters = carb.settings.get_settings().get("/exts/omni.kit.viewport.menubar.camera/filters") or []
self.__usdrt_stage = self.__get_usd_rt_stage(stage)
self.__listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self.__on_usd_changed, stage) if stage else None
self.__dirty_prim_paths: Set[Sdf.Path] = set()
self.__prim_changed_task: Optional[concurrent.futures.Future] = None
def __del__(self):
self.destroy()
def destroy(self):
if self.__listener:
self.__listener.Revoke()
self.__listener = None
@property
def is_dirty(self):
return self.__dirty
@property
def camera_list(self) -> List[Sdf.Path]:
# If it's called the first time, we just iterate the whole USD stage for cameras
# Note the cast to bool is important in case self.__stage is not None, but also an invalid stage
was_dirty, self.__dirty = self.__dirty, False
has_stage = bool(self.__stage)
if was_dirty and has_stage:
self.__cameras: Set[Sdf.Path] = set()
if self.__usdrt_stage:
for prim_path in self.__usdrt_stage.GetPrimsWithTypeName("Camera"):
usd_prim = self.__stage.GetPrimAtPath(prim_path.GetString())
if _show_camera_in_menu(usd_prim) and self.__filter(usd_prim):
self.__cameras.add(usd_prim.GetPath())
else:
# If it's called the first time, we just iterate the whole USD stage for cameras
# Note the cast to bool is important in case self.__stage is not None, but also an invalid stage
predicate = Usd.TraverseInstanceProxies(Usd.PrimIsActive and Usd.PrimIsDefined and Usd.PrimIsLoaded)
for usd_prim in self.__stage.Traverse(predicate):
if _show_camera_in_menu(usd_prim) and self.__filter(usd_prim):
self.__cameras.add(usd_prim.GetPath())
return self.__cameras
def __filter(self, camera_prim: Usd.Prim) -> bool:
path = camera_prim.GetPath().pathString
for filter in self.__camera_filters:
if path.startswith(filter):
return False
return True
@staticmethod
def __get_usd_rt_stage(stage: Usd.Stage):
if carb.settings.get_settings().get("/exts/omni.kit.viewport.menubar.camera/primQuery/useUsdRt"):
try:
from pxr import UsdUtils
from usdrt import Usd as UsdRtUsd
stage_id = UsdUtils.StageCache.Get().GetId(stage).ToLongInt()
fabric_active_for_stage = UsdRtUsd.Stage.StageWithHistoryExists(stage_id)
if fabric_active_for_stage:
return UsdRtUsd.Stage.Attach(stage_id)
except (ImportError, ModuleNotFoundError):
pass
return None
@Trace.TraceFunction
def __on_usd_changed(self, notice: Tf.Notice, stage: Usd.Stage):
"""Called by Usd.Notice.ObjectsChanged"""
if not bool(self.__stage) or stage != self.__stage:
return
dirty_prims_paths: List[Sdf.Path] = []
for p in notice.GetResyncedPaths():
if p.IsAbsoluteRootOrPrimPath():
dirty_prims_paths.append(p)
if not dirty_prims_paths:
return
self.__dirty_prim_paths.update(dirty_prims_paths)
# Update in the next frame. We need it because we want to accumulate the affected prims
if self.__prim_changed_task is None or self.__prim_changed_task.done():
self.__prim_changed_task_or_future = run_coroutine(self.__delayed_prim_changed())
@handle_exception
@Trace.TraceFunction
async def __delayed_prim_changed(self):
"""
Create/remove dirty items that was collected from TfNotice. Can be
called any time to pump changes.
"""
if not bool(self.__stage):
return
# Swap the dirty list to a local and reset the instance state
dirty = False
dirty_prim_paths, self.__dirty_prim_paths = self.__dirty_prim_paths, set()
removed_camera, added_camera = None, None
for path in dirty_prim_paths:
prim = self.__stage.GetPrimAtPath(path)
if _show_camera_in_menu(prim):
# Changed or created
self.__cameras.add(path)
added_camera = path
dirty = True
else:
# Removed or changed type
try:
self.__cameras.remove(path)
removed_camera = path
except KeyError:
pass
dirty = True
# For the case with one event that represents and removal and addition of a camera, pass it along as -hint-.
# There could be fals-positives (a layer event where only one camera is gone and one added), but even in
# that case hinting to the Viewport what to do (leave camera if removed camera was active) isn't horrible.
if len(dirty_prim_paths) != 2 or (removed_camera is None) or (added_camera is None):
removed_camera, added_camera = None, None
if dirty:
self.__dirty = True
self.__callback(removed_camera, added_camera)
self.__prim_changed_task = None
@dataclass
class MenuContext:
root_menu: ui.Menu = None
delegate: ui.MenuDelegate = None
settings_menu: ui.Menu = None
settings_container: ui.ZStack = None
settings_width: int = 0
expand_container: ui.ZStack = None
expand_item: ExpandMenuItem = None
expand_width: int = 0
expand_model: ui.SimpleBoolModel = None
saved_expand = False
camera_collection: ui.MenuItemCollection = None
camera_path: str = None
selected_camera_item: ui.MenuItem = None
camera_list: Optional[_CameraList] = None
stage_sub: carb.Subscription = None
expanded_sub: carb.Subscription = None
render_settings_changed_sub: carb.Subscription = None
lock_menu_sub: carb.Subscription = None
settings_items: List[ui.MenuItem] = field(default_factory=list)
camera_to_menu: Dict[Sdf.Path, Tuple[SingleCameraMenuItem, bool]] = field(default_factory=dict)
def __init__(self, **kwargs):
names = set([f.name for f in fields(self)])
for k, v in kwargs.items():
if k in names:
setattr(self, k, v)
if not hasattr(self, "settings_items"):
self.settings_items = []
if not hasattr(self, "camera_to_menu"):
self.camera_to_menu = {}
class CameraMenuContainer(ViewportMenuContainer):
"""The menu with the list of cameras"""
def __init__(self):
super().__init__(
name="Camera",
delegate=None,
visible_setting_path="/exts/omni.kit.viewport.menubar.camera/visible",
order_setting_path="/exts/omni.kit.viewport.menubar.camera/order",
expand_setting_path="/exts/omni.kit.viewport.menubar.camera/expand",
style=UI_STYLE
)
self.__menu_item_type = SingleCameraMenuItem
self.__lock_models: Dict[Sdf.Path, USDAttributeModel] = {}
self.__menu_context: Dict[int, MenuContext] = {}
self._create_menu_item_fns: List[List[Callable[["viewport_context", ui.Menu], None]], int] = []
self.register_menu_item(self._build_camera_collections, -100)
self.register_menu_item(self._build_create_camera, -90)
self.__custom_camera_widget_delegate_manager = CameraWidgetDelegateManager()
def set_menu_item_type(self, menu_item_type: Callable[..., "SingleCameraMenuItemBase"]):
"""
Set the menu type for the default created camera
Args:
menu_item_type: callable that will create the menu item
"""
if not menu_item_type:
menu_item_type = SingleCameraMenuItem
if self.__menu_item_type != menu_item_type:
self.__menu_item_type = menu_item_type
self.__full_invalidate()
def __del__(self):
self.destroy()
def destroy(self):
self.__lock_models = {}
for context in self.__menu_context.values():
context.expanded_sub = None
context.lock_menu_sub = None
if context.render_settings_changed_sub:
context.render_settings_changed_sub.destroy()
context.render_settings_changed_sub = None
self.__custom_camera_widget_delegate_manager.destroy()
super().destroy()
def __full_invalidate(self):
for context in self.__menu_context.values():
context.root_menu.invalidate()
context.settings_menu.invalidate()
def get_display_status(self, factory_args: Dict) -> MenuDisplayStatus:
viewport_api_id = factory_args['viewport_api'].id
context = self.__menu_context[viewport_api_id]
if context.expand_container.visible:
return MenuDisplayStatus.EXPAND
elif context.delegate.text_visible:
return MenuDisplayStatus.LABEL
else:
return MenuDisplayStatus.MIN
def get_require_size(self, factory_args: Dict, expand: bool=False) -> float:
viewport_api_id = factory_args['viewport_api'].id
context = self.__menu_context[viewport_api_id]
display_status = self.get_display_status(factory_args)
if expand:
if display_status == MenuDisplayStatus.EXPAND:
return 0
elif display_status == MenuDisplayStatus.LABEL:
return context.settings_width + context.expand_width
else:
return context.delegate.text_size
else:
if display_status == MenuDisplayStatus.EXPAND:
if context.expand_model.as_bool:
return 0
else:
return context.settings_width
elif display_status == MenuDisplayStatus.LABEL:
return 0
else:
return context.delegate.text_size
def expand(self, factory_args: Dict) -> None:
viewport_api_id = factory_args['viewport_api'].id
context = self.__menu_context[viewport_api_id]
if context.expand_container.visible:
return
elif context.delegate.text_visible:
context.expand_model.set_value(context.saved_expand)
context.expand_container.visible = True
else:
context.delegate.text_visible = True
if context.root_menu:
context.root_menu.invalidate()
def can_contract(self, factory_args: Dict) -> bool:
display_status = self.get_display_status(factory_args)
return display_status == MenuDisplayStatus.LABEL or display_status == MenuDisplayStatus.EXPAND
def contract(self, factory_args: Dict) -> bool:
viewport_api_id = factory_args['viewport_api'].id
if viewport_api_id not in self.__menu_context:
return False
context = self.__menu_context[viewport_api_id]
display_status = self.get_display_status(factory_args)
if display_status == MenuDisplayStatus.EXPAND:
context.saved_expand = context.expand_model.as_bool
context.expand_model.set_value(False)
context.expand_container.visible = False
return True
elif display_status == MenuDisplayStatus.LABEL:
context.delegate.text_visible = False
if context.root_menu:
context.root_menu.invalidate()
return True
return False
def register_menu_item(self, create_menu_item_fn: Callable[["viewport_context", ui.Menu], None], order: int = 0):
self._create_menu_item_fns.append((create_menu_item_fn, order))
self.__full_invalidate()
def deregister_menu_item(self, create_menu_item_fn: Callable[["viewport_context", ui.Menu], None]):
found = [item for item in self._create_menu_item_fns if item[0] == create_menu_item_fn]
if found:
for item in found:
self._create_menu_item_fns.remove(item)
self.__full_invalidate()
def build_fn(self, viewport_context: Dict):
"""Entry point for the menu bar"""
viewport_api = viewport_context.get('viewport_api')
viewport_api_id = viewport_api.id
# Empty out any existing menu objects
self.__menu_context[viewport_api_id] = MenuContext(
delegate=CameraListDelegate(viewport_api, self.__custom_camera_widget_delegate_manager)
)
# Get a local reference to the new mapped value
_menu_context = self.__menu_context[viewport_api_id]
_menu_context.root_menu = ui.Menu(menu_compatibility=False, delegate=_menu_context.delegate, style=self._style)
_menu_context.root_menu.set_on_build_fn(lambda *args, **kwargs: self._build_menu(viewport_context))
# The Camera property widgets selection menu
_menu_context.settings_container = ui.ZStack(width=0)
with _menu_context.settings_container:
ui.Rectangle(style_type_name_override="Menu.Item.Background")
with ui.HStack(width=0):
ui.Spacer(width=5)
_menu_context.settings_menu = ui.Menu(menu_compatibility=False, direction=ui.Direction.LEFT_TO_RIGHT, style=self._style)
_menu_context.settings_menu.set_on_build_fn(lambda *args, **kwargs: self._build_expand(viewport_context))
ui.Spacer(width=5)
def __on_settings_changed(id):
menu_context = self.__menu_context[viewport_api_id]
menu_context.settings_width = max(menu_context.settings_width, menu_context.settings_container.computed_content_width)
_menu_context.settings_container.set_computed_content_size_changed_fn(partial(__on_settings_changed, viewport_api_id))
# Delay a frame to hide camera settings if required to get settings width for contract/expand when startup
_menu_context.expand_model = ui.SimpleBoolModel(self.expand_model.as_bool)
async def __hide_camera_settings_async(menu_context):
await omni.kit.app.get_app().next_update_async()
menu_context.settings_container.visible = menu_context.expand_model.as_bool
if not self.expand_model.as_bool:
self.__hide_camera_settings_task_or_future = run_coroutine(__hide_camera_settings_async(_menu_context))
# Menu to expand/contract camera properties
_menu_context.expand_container = ui.ZStack(width=0, height=0, style={"padding": 0, "margin": 0})
with _menu_context.expand_container:
with ui.Menu(menu_compatibility=False, direction=ui.Direction.LEFT_TO_RIGHT, style=self._style):
_menu_context.expand_item = ExpandMenuItem(_menu_context.expand_model)
def __on_expand_changed(*args, **kwargs):
menu_context = self.__menu_context[viewport_api_id]
menu_context.expand_width = max(menu_context.expand_width, menu_context.expand_container.computed_content_width)
_menu_context.expand_container.set_computed_content_size_changed_fn(__on_expand_changed)
def __on_toggle_expand(*args, **kwargs):
menu_context = self.__menu_context[viewport_api_id]
menu_context.settings_container.visible = menu_context.expand_model.as_bool
menu_context.expand_item.checked = menu_context.expand_model.as_bool
# Reset global expand status
# Once at least one expanded, set global expanded
# Otherwise, set global callpased
self.__unsub_global_expand()
if menu_context.expand_model.as_bool:
self.expand_model.set_value(True)
else:
expand = False
for menu_context in self.__menu_context.values():
if menu_context.expand_model.as_bool:
expand = True
break
self.expand_model.set_value(expand)
self.__sub_global_expand()
_menu_context.expanded_sub = _menu_context.expand_model.subscribe_value_changed_fn(__on_toggle_expand)
self.__sub_global_expand()
# When stage opened, rebuild the root menu
def on_usd_context_event(event: omni.usd.StageEventType):
if event.type == int(omni.usd.StageEventType.OPENED):
camera_path = self.__ensure_valid_camera(viewport_api, viewport_api.camera_path)
if camera_path:
viewport_api.camera_path = camera_path
menu_context = self.__menu_context.get(viewport_api_id)
if menu_context:
menu_context.root_menu.invalidate()
menu_context.settings_menu.invalidate()
_menu_context.stage_sub = viewport_api.usd_context.get_stage_event_stream().create_subscription_to_pop(
on_usd_context_event, name="Viewport MenuBar CameraMenuContainer"
)
# Clear out this reference to validate its not being held or used by any callback
_menu_context = None
def __render_settings_changed(self, camera_path: Sdf.Path, resolution: Tuple[int, int], viewport_api):
# The Viewport may have switched to a new camera before out camera list was dirtied
context = self.__menu_context[viewport_api.id]
if context.camera_to_menu.get(camera_path) is None:
# Rebuild but don't check camera validity; the Viewport is sending us the path it is rendering with
self.__rebuild_cameras(viewport_api, False)
self.__camera_changed(camera_path, viewport_api)
def __camera_clicked(self, camera_path: Sdf.Path, viewport_api):
context = self.__menu_context[viewport_api.id]
if context.camera_path != camera_path:
SetViewportCameraCommand(camera_path, viewport_api).do()
return
# Force the check state back on as it's being toggled off
async def force_check(id):
selected_cam_item = self.__menu_context[id].selected_camera_item
if selected_cam_item and not selected_cam_item.checked:
selected_cam_item.checked = True
self.__force_check_task_or_future = run_coroutine(force_check(viewport_api.id))
def __camera_changed(self, camera_path: Sdf.Path, viewport_api):
context = self.__menu_context[viewport_api.id]
if context.camera_path == camera_path:
cam_item = context.camera_to_menu.get(camera_path)
if cam_item and not cam_item.checked:
cam_item.checked = True
return
# Save the current state now
context.camera_path = camera_path
# Uncheck anything that is currently selected
selected_cam_item = context.selected_camera_item
if selected_cam_item:
selected_cam_item.checked = False
selected_cam_item = None
# There is also chance the Camera was changed to an item that doesn't exist
cam_item = context.camera_to_menu.get(camera_path)
if cam_item:
context.selected_camera_item = cam_item
# And reset the check state on the new selection
cam_item.checked = True
# Update the root menu item
if context.delegate:
context.delegate.text = get_camera_display(camera_path, viewport_api.stage)
# Toggle the cam collection marker accordingly
if context.camera_collection:
context.camera_collection.checked = str(camera_path) not in SESSION_CAMERAS
# Need to update the lock item to new camera
self.__build_lock_item(viewport_api, camera_path)
# Update the active Camera's property widgets by rebuilding them
if context:
context.settings_menu.invalidate()
def __build_lock_item(self, viewport_api, camera_path: Sdf.Path):
stage = viewport_api.stage
# Lock menu sub is always destroyed
context = self.__menu_context.get(viewport_api.id, None)
context.lock_menu_sub = None
# Possibly no path, so clear any state
if not camera_path:
self.__lock_models = {}
if context and context.delegate:
context.delegate.model = None
context.delegate.camera_path = None
return
context.delegate.camera_path = camera_path
lock_model = self.__get_lock_model(stage, camera_path)
if context and context.delegate:
context.delegate.model = lock_model
if lock_model:
context.lock_menu_sub = lock_model.subscribe_value_changed_fn(lambda m, api=viewport_api: self._on_lock_changed(m, api))
def __get_lock_model(self, stage: Usd.Stage, camera_path: Sdf.Path):
if camera_path not in self.__lock_models:
if camera_path.pathString in ("/OmniverseKit_Persp", "/OmniverseKit_Front", "/OmniverseKit_Top", "/OmniverseKit_Right"):
return None
# Lock - Should probably use meta-data, but that needs to be added into allowed-metadata schema
# self.__lock_models[camera_path] = USDMetadataModel(stage, camera_path, CAMERA_LOCK_NAME)
self.__lock_models[camera_path] = USDAttributeModel(stage, camera_path, CAMERA_LOCK_NAME)
return self.__lock_models.get(camera_path)
def __get_session_camera_paths(self, stage: Usd.Stage):
session_camera_paths = [Sdf.Path(path_str) for path_str in SESSION_CAMERAS]
if stage:
session_camera_paths = [path for path in session_camera_paths if stage.GetPrimAtPath(path)]
return session_camera_paths
def _build_cameras(self, viewport_api, session_cameras: bool, ui_shown: bool = False, force_build: bool = False):
"""Build the menu with the list of the cameras"""
context = self.__menu_context.get(viewport_api.id, None)
if (not session_cameras) and (not force_build):
camera_collection = context.camera_collection
if camera_collection and not camera_collection.shown and not camera_collection.teared:
return
if session_cameras:
camera_list = self.__get_session_camera_paths(viewport_api.stage)
elif not context.camera_list.is_dirty:
# If nothing changed, menu should be up-to-date
return
else:
def sorting_key(sdf_path: Sdf.Path):
# Sort based on parentPath/displayName which may lead to an invalid Sdf.Path durring AppendChild
display_name = get_camera_display(sdf_path, viewport_api.stage)
return f"{sdf_path.GetParentPath().pathString}/{display_name}".lower()
camera_list = context.camera_list.camera_list
camera_list = sorted(camera_list, key=sorting_key)
camera_list = [path for path in camera_list if path.pathString not in SESSION_CAMERAS]
if context.camera_collection:
context.camera_collection.clear()
stage = viewport_api.stage
# Check that the current camera path is valid
current_camera = viewport_api.camera_path
valid_camera_path = self.__ensure_valid_camera(viewport_api, current_camera)
if valid_camera_path and (valid_camera_path != current_camera):
current_camera = valid_camera_path
viewport_api.camera_path = current_camera
# Clear any selected selected_cam_item now, its going to be an invalid item soon
if context and context.selected_camera_item:
context.selected_camera_item.checked = False
context.selected_camera_item = None
class MenuParentContext:
def __enter__(self, *args, **kwargs):
return context.camera_collection.__enter__(*args, **kwargs) if not session_cameras else None
def __exit__(self, *args, **kwargs):
return context.camera_collection.__exit__(*args, **kwargs) if not session_cameras else None
with MenuParentContext():
if session_cameras or camera_list:
for camera_path in camera_list:
checked = current_camera == camera_path
menu_item = self.__menu_item_type(
camera_path,
viewport_api,
self.__get_lock_model(stage, camera_path),
context.root_menu,
lambda camera_path=camera_path: self.__camera_clicked(camera_path, viewport_api),
self.__custom_camera_widget_delegate_manager
)
context.camera_to_menu[camera_path] = menu_item
if checked:
context.selected_camera_item = menu_item
else:
NoCameraMenuItem()
# Call camera_changed for the case the camera menu has been invalidated
context.camera_path = None
self.__camera_changed(current_camera, viewport_api)
def __rebuild_cameras(self, viewport_api, check_validity: bool = False, removed_camera: Sdf.Path = None, added_camera: Sdf.Path = None):
context = self.__menu_context.get(viewport_api.id, None)
camera_collection = context.camera_collection
if camera_collection and (camera_collection.shown or camera_collection.teared):
# Force a rebuild of the stage cameras now
camera_collection.invalidate()
camera_collection.clear()
self._build_cameras(viewport_api, False, True, True)
if not check_validity:
return
camera_path = viewport_api.camera_path
# If there was a single re-synch event where this camera was removed, and a new one added, go to added
valid_camera_path = self.__ensure_valid_camera(viewport_api, added_camera if removed_camera == camera_path else camera_path)
if valid_camera_path and (valid_camera_path != camera_path):
viewport_api.camera_path = valid_camera_path
def __ensure_valid_camera(self, viewport_api, camera_path: Sdf.Path):
stage = viewport_api.stage
if not stage:
return camera_path
def validate_camera(camera_path):
if camera_path:
prim = stage.GetPrimAtPath(camera_path)
# OM-59033: It does not need the followed camera to be shown in the camera list by checking
# _show_camera_in_menu(prim) as follow user mode in live session needs this to switch
# camera binding dynamically without adding the camera into camera list.
if prim:
return Sdf.Path(camera_path)
return None
# Check if the camera_path is actually a valid camera_path
camera_path = validate_camera(camera_path)
if camera_path:
return camera_path
# Check if the info is held in the stage metadata.
try:
# Wrap in a try-catch so failure reading metadata does not cascade to caller.
camera_path = validate_camera(stage.GetMetadataByDictKey('customLayerData', 'cameraSettings:boundCamera'))
if camera_path:
return camera_path
except Tf.ErrorException as e:
carb.log_error(f"Error reading Usd.Stage's boundCamera metadata {e}")
# Fallback to implicit Perspective if possible (it is deterministic)
camera_path = validate_camera('/OmniverseKit_Persp')
if camera_path:
return camera_path
# Finally, try an pass the first valid camera in the list
context = self.__menu_context[viewport_api.id]
if context and context.camera_list:
for known_camera in context.camera_list.camera_list:
camera_path = validate_camera(known_camera)
if camera_path:
return camera_path
return None
def _build_camera_collections(self, viewport_context, root: ui.Menu):
viewport_api = viewport_context.get("viewport_api")
context = self.__menu_context.get(viewport_api.id, None)
if context.camera_list:
context.camera_list.destroy()
context.camera_list = _CameraList(viewport_api.stage, partial(self.__rebuild_cameras, viewport_api, True))
# Clear out the Camera-path to MenuItem mapping
context.camera_to_menu = {}
# Verify current camera exists, changing it if it does not
camera_path = viewport_api.camera_path
valid_camera_path = self.__ensure_valid_camera(viewport_api, camera_path)
if valid_camera_path and (valid_camera_path != camera_path):
camera_path = valid_camera_path
viewport_api.camera_path = camera_path
# Order views
session_cameras = self.__get_session_camera_paths(viewport_api.stage)
show_stage_cameras = carb.settings.get_settings().get("/exts/omni.kit.viewport.menubar.camera/showStageCameras")
if show_stage_cameras:
tearable = menu_is_tearable("omni.kit.viewport.menubar.camera.Cameras")
context.camera_collection = ui.MenuItemCollection(
"Cameras",
checkable=True,
checked=camera_path not in session_cameras,
delegate=ViewportMenuDelegate(),
shown_changed_fn=partial(self._build_cameras, viewport_api, False),
tearable=tearable,
hide_on_click=False
)
def reset_checked():
context.camera_collection.checked = str(viewport_api.camera_path) in SESSION_CAMERAS
context.camera_collection.set_triggered_fn(reset_checked)
# XXX: This isn't sticking from the usage in constructor
context.camera_collection.tearable = tearable
self._build_cameras(viewport_api, True)
ui.Separator()
def _build_create_camera(self, viewport_context, root: ui.Menu):
viewport_api = viewport_context.get("viewport_api")
ui.MenuItem(
"Create from View",
delegate=ViewportMenuDelegate(icon_name="Add"),
triggered_fn=lambda *args, **kwargs: self._create_from_view(viewport_api),
hide_on_click=False
)
def _build_menu(self, viewport_context):
"""Build the first level menu"""
# Create a weak-reference to the active Camera menu; this will be passed to registered build functions
viewport_api = viewport_context.get("viewport_api")
context = self.__menu_context.get(viewport_api.id, None)
cam_menu = weakref.proxy(context.root_menu)
context.camera_path = viewport_api.camera_path
# Need to watch for external changes to Viewport's camera, this is delivered in a render-settings change.
if context.render_settings_changed_sub:
context.render_settings_changed_sub.destroy()
context.render_settings_changed_sub = None
context.render_settings_changed_sub = viewport_api.subscribe_to_render_settings_change(self.__render_settings_changed)
if context and context.delegate:
context.delegate.model = None
context.delegate.camera_path = None
self.__lock_models = {}
self.__build_lock_item(viewport_api, context.camera_path)
# Active camera
if context.camera_path:
text = get_camera_display(context.camera_path, viewport_api.stage)
else:
text = self.name
context.root_menu.text = text
# Menu items
self._create_menu_item_fns.sort(key=lambda item: item[1])
for (create_fn, order) in self._create_menu_item_fns:
create_fn(viewport_context, cam_menu)
# The rest of the menu on the case someone wants to put custom stuff
if self._children:
for child in self._children:
child.build_fn(viewport_context)
def _build_expand(self, viewport_context) -> None:
# This menu has the number of widgets on the right side.
# Check if the widgets are expanded
viewport_api = viewport_context.get("viewport_api")
context = self.__menu_context[viewport_api.id]
stage = viewport_api.stage
camera_path = viewport_api.camera_path
context.settings_items = []
if camera_path:
locked = self.__lock_models[camera_path].as_bool if camera_path in self.__lock_models and self.__lock_models[camera_path] else False
enabled = not locked
show_manual_exposure = carb.settings.get_settings().get("/exts/omni.kit.viewport.menubar.camera/showManualExposure")
if show_manual_exposure:
context.settings_items.append(
CameraLens(
USDFloatAttributeModel(stage, camera_path, "focalLength", draggable=True),
enabled=enabled,
)
)
ui.MenuItem("", delegate=SeparatorDelegate())
context.settings_items.append(
CameraFocalDistance(
USDFloatAttributeModel(stage, camera_path, "focusDistance"),
viewport_context,
enabled=enabled,
)
)
ui.MenuItem("", delegate=SeparatorDelegate())
context.settings_items.append(
CameraFStop(
USDFloatAttributeModel(stage, camera_path, "fStop"),
enabled=enabled,
)
)
show_auto_exposure = carb.settings.get_settings().get("/exts/omni.kit.viewport.menubar.camera/showAutoExposure")
if show_auto_exposure:
if show_manual_exposure:
ui.MenuItem("", delegate=SeparatorDelegate())
context.settings_items.append(CameraAutoExposure(None, enabled=enabled))
if camera_path in self.__lock_models and self.__lock_models[camera_path]:
self._on_lock_changed(self.__lock_models[camera_path], viewport_api)
def _create_from_view(self, viewport_api):
omni.kit.commands.execute("DuplicateViewportCameraCommand", viewport_api=viewport_api)
def _on_lock_changed(self, model: ui.AbstractValueModel, viewport_api) -> None:
is_locked = model.as_bool
settings_items = self.__menu_context[viewport_api.id].settings_items
for setting in settings_items:
setting.enabled = not is_locked
def _on_menu_collection_triggered(self, menu: ui.MenuItemCollection, checked: bool):
# Revert status here to keep checked status no changing when clicked
menu.checked = not checked
def __sub_global_expand(self):
# Watch for the carb setting, for now treat it as global state and apply to all Viewports
def __on_toggle_global_expand(*args, **kwargs):
expanded = self.expand_model.as_bool
for menu_context in self.__menu_context.values():
menu_context.expand_model.set_value(expanded)
self.__expanded_sub = self.expand_model.subscribe_value_changed_fn(__on_toggle_global_expand)
def __unsub_global_expand(self):
self.__expanded_sub = None
| 38,301 | Python | 43.641026 | 144 | 0.626119 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/menu_item/single_camera_menu_item.py | import abc
from typing import Optional, Callable
import carb
import omni.ui as ui
from typing import Optional, Callable
from pxr import Sdf
from omni.kit.viewport.menubar.core import ViewportMenuDelegate, LabelMenuDelegate
from ..camera_widget_delegate_manager import CameraWidgetDelegateManager
from ..utils import get_camera_display
class SingleCameraMenuItemBase(ui.MenuItem):
"""
A single menu item represent a single camera in the camera list
"""
def __init__(
self, camera_path: Sdf.Path, viewport_api, lock_model, root: ui.Menu, triggered_fn: Callable,
widget_delegate_manager: CameraWidgetDelegateManager
):
self._lock_model = lock_model
self.__root = root
self.__camera_path = camera_path
self.__viewport_api = viewport_api
self.__lock_button: Optional[ui.Button] = None
self.__lock_model_sub = None
self.__options_button = None
self.__widget_delegate_manager = widget_delegate_manager
super().__init__(
get_camera_display(camera_path, viewport_api.stage),
checkable=True,
checked=viewport_api.camera_path == camera_path,
hide_on_click=False,
triggered_fn=triggered_fn,
delegate=ViewportMenuDelegate(
force_checked=False, build_custom_widgets=lambda delegate, item: self._build_menuitem_widgets()
),
)
@property
def camera_path(self):
return self.__camera_path
@property
def viewport_api(self):
return self.__viewport_api
def destroy(self):
if self.__widget_delegate_manager:
self.__widget_delegate_manager.on_parent_destroyed(id(self), False)
self.__widget_delegate_manager = None
self.__options_button = None
super().destroy()
self.__lock_model_sub = None
def __build_custom_widgets(self):
if not self.__widget_delegate_manager:
return
try:
self.__widget_delegate_manager.build_widgets(
id(self), self.__viewport_api, self.__camera_path, False
)
except Exception as e:
carb.log_error(f"Failed to build widget: {str(e)}")
def _build_menuitem_widgets(self):
"""Build additional buttons in the camera menu item"""
ui.Spacer(width=10)
with ui.VStack(content_clipping=1, width=0):
# Button to select camera
self.__options_button = ui.Button(
style_type_name_override="Menu.Item.Button",
name="OptionBox",
width=16,
height=16,
image_width=16,
image_height=16,
visible=self.checked,
clicked_fn=self._option_clicked,
)
if self._lock_model:
# Button to toggle lock status
with ui.VStack(content_clipping=1, width=0):
self.__lock_button = ui.Button(
style_type_name_override="Menu.Item.Button",
name=self.__get_lock_button_name(),
width=16,
height=16,
image_width=16,
image_height=16,
clicked_fn=self.__toggle_camera_lock,
)
self.__lock_model_sub = self._lock_model.subscribe_value_changed_fn(self._on_lock_changed)
self.__build_custom_widgets()
@abc.abstractmethod
def _option_clicked(self):
"""Function to implement when the option is clicked. Used by RTX Remix"""
pass
def __toggle_camera_lock(self):
self._lock_model.set_value(not self._lock_model.as_bool)
self.__lock_button.name = self.__get_lock_button_name()
def _on_lock_changed(self, model: ui.AbstractValueModel) -> None:
self.__lock_button.name = self.__get_lock_button_name()
def __get_lock_button_name(self):
return "CameraLocked" if self._lock_model.as_bool else "CameraUnlocked"
def set_checked(self, checked: bool) -> None:
self.checked = checked
self.delegate.checked = checked
# Only show options button when it is current camera
self.__options_button.visible = checked
class SingleCameraMenuItem(SingleCameraMenuItemBase):
"""
A single menu item represent a single camera in the camera list
"""
def _option_clicked(self):
self.viewport_api.usd_context.get_selection().set_selected_prim_paths([self.camera_path.pathString], True)
class NoCameraMenuItem(ui.MenuItem):
"""
A single menu item represent a no camera in the camera list
"""
def __init__(self):
super().__init__(
"No camera",
hide_on_click=False,
delegate=LabelMenuDelegate(enabled=False, width=120, alignment=ui.Alignment.CENTER),
)
| 4,901 | Python | 33.041666 | 114 | 0.599878 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/menu_item/lens.py | import asyncio
from typing import Tuple, List
from pxr import Usd, Sdf
import omni.kit.app
import omni.ui as ui
from omni.ui import constant as fl
from .camera_setting import AbstractCameraSetting
from omni.kit.viewport.menubar.core import (
SeparatorDelegate,
SliderMenuDelegate,
ComboBoxMenuDelegate,
USDAttributeModel,
USDFloatAttributeModel,
ComboBoxItem,
ComboBoxModel,
)
DEFAULT_LENS = [8, 15, 24, 28, 35, 50, 85, 105, 135, 200, (17, 35), (35, 70), (70, 200), (0, 300)]
class _CameraLensModel(ComboBoxModel):
"""The camera lens model has all the lens"""
def __init__(self, lens_model: USDFloatAttributeModel):
self._values = DEFAULT_LENS
self._lens_model = lens_model
self.range: Tuple(float, float) = ()
texts = []
for value in self._values:
if isinstance(value, int):
texts.append(f"{value} mm")
else:
texts.append(f"{value[0]} - {value[1]} mm")
self._lens_model.add_value_changed_fn(self.__on_lens_changed)
super().__init__(texts, self._values, self.display)
def destroy(self):
super().destroy()
self._lens_model.remove_value_changed_fn(self.__on_lens_changed)
@property
def display(self):
lens = self._lens_model.as_float
for value in self._values:
if isinstance(value, int):
if lens == float(value):
self.range = (value, value)
return value
else:
min = value[0]
max = value[1]
if lens <= max and lens >= min:
self.range = (min, max)
return value
default = self._values[-1]
return default
def _on_current_item_changed(self, item: ComboBoxItem) -> None:
if isinstance(item.value, int):
self.range = (item.value, item.value)
self._lens_model.set_value(float(item.value))
else:
# Don't allow 0 for focalLength
self.range = (max(0.00001, item.value[0]), item.value[1])
value = self._lens_model.as_float
if value > self.range[1] or value < self.range[0]:
self._lens_model.set_value(float(self.range[0]))
def __on_lens_changed(self, model: ui.AbstractValueModel):
# If current value still in current lens range, keep range no change
value = self._values[self.current_index.as_int]
if isinstance(value, int):
if model.as_float == float(value):
return
elif float(value[0]) <= model.as_float and float(value[1]) >= model.as_float:
return
self.current_index.set_value(self._get_current_index_by_value(self.display))
class CameraLens(AbstractCameraSetting):
def __init__(self, model: USDAttributeModel, enabled: bool = True):
self._lens_model = _CameraLensModel(model)
self._sub = self._lens_model.subscribe_item_changed_fn(self._on_lens_changed)
super().__init__(model, enabled=enabled)
def destroy(self):
self._lens_model.destroy()
self._sub = None
def _build_ui(self) -> List[ui.MenuDelegate]:
self._lens_delegate = ComboBoxMenuDelegate(
model=self._lens_model,
height=26,
icon_height=26,
enabled=self._enabled,
text=False,
icon_name="Lens",
tooltip="Camera Lens",
use_in_menubar=True,
)
ui.MenuItem("Lens", delegate=self._lens_delegate, identifier="viewport.camera.lens")
self._separator = ui.MenuItem("", delegate=SeparatorDelegate())
self._zoom_delegate = SliderMenuDelegate(model=self._property_model, width=0, enabled=self._enabled, tooltip="Camera Zoom")
self._zoom_menu = ui.MenuItem("Zoom", delegate=self._zoom_delegate, enabled=self._enabled, identifier="viewport.camera.zoom")
async def __delay_init():
await omni.kit.app.get_app().next_update_async()
self._on_lens_changed(self._lens_model, None)
asyncio.ensure_future(__delay_init())
return [self._lens_delegate, self._zoom_delegate]
def _on_lens_changed(self, model: _CameraLensModel, item: ComboBoxItem):
range = self._lens_model.range
if range[0] == range[1]:
self._zoom_delegate.visible = False
self._separator.visible = False
else:
self._zoom_delegate.visible = True
self._separator.visible = True
self._zoom_delegate.set_range(range[0], range[1])
| 4,640 | Python | 34.7 | 133 | 0.591379 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/menu_item/fstop.py | from pxr import Usd, Sdf
from typing import List
import omni.ui as ui
from omni.ui import constant as fl
from .camera_setting import AbstractCameraSetting
from omni.kit.viewport.menubar.core import SpinnerMenuDelegate, USDAttributeModel
__all__ = ["CameraFStop"]
class CameraFStop(AbstractCameraSetting):
def __init__(self, model: USDAttributeModel, enabled: bool = True):
super().__init__(model, enabled=enabled)
def destroy(self):
pass
def _build_ui(self) -> List[ui.MenuDelegate]:
self._fstop_delegate = SpinnerMenuDelegate(
model=self._property_model,
min=0.0,
max=22.0,
step=0.1,
height=26,
enabled=self._enabled,
text=False,
icon_name="FStop",
tooltip="Camera F Stop",
icon_height=26,
use_in_menubar=True,
)
ui.MenuItem("F Stop", delegate=self._fstop_delegate, identifier="viewport.camera.f_stop")
return [self._fstop_delegate]
| 1,032 | Python | 28.514285 | 97 | 0.617248 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/menu_item/auto_exposure.py | from pxr import Usd, Sdf
from typing import List
import omni.ui as ui
from omni.ui import constant as fl
from .camera_setting import AbstractCameraSetting
from omni.kit.viewport.menubar.core import (
CheckboxMenuDelegate,
SpinnerMenuDelegate,
SliderMenuDelegate,
USDAttributeModel,
SettingModel,
)
SETTING_AUTO_EXPOSURE = "/rtx/post/histogram/enabled"
SETTING_ISO = "/rtx/post/tonemap/filmIso"
SETTING_WHITE_SCALE = "/rtx/post/histogram/whiteScale"
__all__ = ["CameraAutoExposure", "SETTING_AUTOEXPOSURE", "SETTING_ISO", "SETTING_WHITE_SCALE"]
class CameraAutoExposure(AbstractCameraSetting):
def __init__(self, model: USDAttributeModel, enabled: bool = True):
self._auto_exposure_model = SettingModel(SETTING_AUTO_EXPOSURE)
self._white_scale_model = SettingModel(SETTING_WHITE_SCALE)
self._iso_model = SettingModel(SETTING_ISO)
self._sub = self._auto_exposure_model.subscribe_value_changed_fn(self._on_auto_exposure_changed)
super().__init__(model, enabled=enabled)
def destroy(self):
self._sub = None
def _build_ui(self) -> List[ui.MenuDelegate]:
self._auto_exposure_delegate = CheckboxMenuDelegate(
model=self._auto_exposure_model, width=0, height=26, enabled=self._enabled, use_in_menubar=True
)
ui.MenuItem("AE", delegate=self._auto_exposure_delegate, identifier="viewport.camera.auto_exposure")
self._white_scale_item = ui.MenuItem(
"",
delegate=SliderMenuDelegate(model=self._white_scale_model, min=00, max=20, width=0),
visible=self._auto_exposure_model.as_bool,
)
self._iso_item = ui.MenuItem(
"ISO",
delegate=SpinnerMenuDelegate(
model=self._iso_model, min=50, max=1600, height=26, use_in_menubar=True,
),
visible=not self._auto_exposure_model.as_bool,
identifier="viewport.camera.iso",
)
return [self._auto_exposure_delegate, self._white_scale_item.delegate, self._iso_item.delegate]
def _on_auto_exposure_changed(self, model: ui.AbstractValueModel) -> None:
self._white_scale_item.visible = model.as_bool
self._iso_item.visible = not model.as_bool
| 2,258 | Python | 37.948275 | 108 | 0.670062 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/menu_item/camera_setting.py | import abc
from pxr import Usd, Sdf
from typing import List
import omni.ui as ui
from omni.kit.viewport.menubar.core import USDAttributeModel
__all__ = ["AbstractCameraSetting"]
class AbstractCameraSetting:
def __init__(self, model: USDAttributeModel, enabled: bool = True):
self._property_model = model
self._enabled = enabled
self._delegates = self._build_ui()
@property
def enabled(self) -> bool:
return self._enabled
@enabled.setter
def enabled(self, value: bool) -> None:
self._enabled = value
for delegate in self._delegates:
delegate.enabled = value
@abc.abstractclassmethod
def _build_ui(self) -> List[ui.MenuDelegate]:
return []
| 740 | Python | 24.551723 | 71 | 0.654054 |
omniverse-code/kit/exts/omni.kit.viewport.menubar.camera/omni/kit/viewport/menubar/camera/menu_item/focal_distance.py |
from .camera_setting import AbstractCameraSetting
import omni.usd
import omni.ui as ui
from omni.ui import scene as sc
from omni.ui import constant as fl
import omni.kit.undo
import omni.kit.app
import omni.kit.commands
from omni.kit.viewport.menubar.core import SpinnerMenuDelegate, IconMenuDelegate, USDAttributeModel
import carb
from pxr import Usd, Sdf, Gf
import asyncio
import weakref
import math
from typing import List
__all__ = ["CamFocalData", "FocusClickGesture", "FocusDragGesture", "PreventOthers", "ViewportClickManipulator", "FocalPickerScene", "CameraFocalDistance"]
class CamFocalData:
def __init__(self, cam_focal: "CameraFocalDistance", viewport_api):
self.__main_cursor = None
self.__cam_focal = cam_focal
self.viewport_api = viewport_api
self.__undo = False
self.__auto_destruct = False
try:
import omni.kit.window.cursor
self.__main_cursor = omni.kit.window.cursor.get_main_window_cursor()
if self.__main_cursor:
self.__main_cursor.override_cursor_shape(carb.windowing.CursorStandardShape.CROSSHAIR)
except ImportError:
pass
def __del__(self):
self.destroy()
def destroy(self):
if self.__undo:
self.__undo = False
omni.kit.undo.end_group()
if self.__main_cursor:
self.__main_cursor.clear_overridden_cursor_shape()
self.__main_cursor = None
if self.__cam_focal:
self.__cam_focal._destroy_scene()
self.__cam_focal = False
self.viewport_api = None
def focus_query_completed(self, prim_path: str, world_space_pos, *args):
try:
viewport_api = self.viewport_api
if prim_path and world_space_pos and viewport_api:
cam_path = viewport_api.camera_path
cam_prim = viewport_api.stage.GetPrimAtPath(cam_path)
if not cam_prim:
carb.log_error(f'Could not get camera prim at "{cam_path}"')
return
# Compute world-space camera position to get distance
world_space_camera = viewport_api.transform.Transform(Gf.Vec3d(0, 0, 0))
distance = (Gf.Vec3d(*world_space_pos) - world_space_camera).GetLength()
if math.isfinite(distance):
# Set to the focusDistance attribute on the Camera
focus_attr = cam_prim.GetAttribute('focusDistance')
# Start an undo-group in case of a drag
if not self.__undo:
self.__undo = True
omni.kit.undo.begin_group()
omni.kit.commands.execute('ChangeProperty', prop_path=focus_attr.GetPath(), value=distance,
prev=focus_attr.Get() if focus_attr else None)
# XXX: Setting to change center of interest TOO ?
except Exception:
pass
finally:
if self.__auto_destruct:
self.__auto_destruct = None
self.destroy()
def set_focus_position(self, ndc_mouse, auto_destruct: bool = True):
mouse, viewport_api = self.viewport_api.map_ndc_to_texture_pixel(ndc_mouse)
if mouse and viewport_api:
self.__auto_destruct = auto_destruct
viewport_api.request_query(mouse, self.focus_query_completed, query_name='omni.kit.viewport.menubar.camera.FocusQuery')
elif auto_destruct:
self.destroy()
class FocusClickGesture(sc.ClickGesture):
def __init__(self, cam_focal_data: CamFocalData, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__cam_focal_data = cam_focal_data
def on_ended(self, *args, **kwargs):
if self.state != sc.GestureState.CANCELED:
self.__cam_focal_data.set_focus_position(self.sender.gesture_payload.mouse)
class FocusDragGesture(sc.DragGesture):
def __init__(self, cam_focal_data: CamFocalData, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__cam_focal_data = cam_focal_data
def on_changed(self, *args, **kwargs):
self.__cam_focal_data.set_focus_position(self.sender.gesture_payload.mouse, False)
def on_ended(self, *args, **kwargs):
if self.state != sc.GestureState.CANCELED:
self.__cam_focal_data.set_focus_position(self.sender.gesture_payload.mouse)
class PreventOthers(sc.GestureManager):
'''Class to prevent any gestures (like selection) from interfering with the focus pick'''
def can_be_prevented(self, gesture):
# Never prevent in the middle of drag
return gesture.state != sc.GestureState.CHANGED
def should_prevent(self, gesture, preventer):
if isinstance(gesture, FocusDragGesture):
return False
if isinstance(gesture, FocusClickGesture):
return False
return True
class ViewportClickManipulator(sc.Manipulator):
def __init__(self, cam_focal_data: CamFocalData, mouse_button: int = 0, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__gestures = [FocusDragGesture(cam_focal_data, mouse_button=mouse_button, manager=PreventOthers()),
FocusClickGesture(cam_focal_data, mouse_button=mouse_button, manager=PreventOthers())]
self.__transform = None
def __del__(self):
self.destroy()
def on_build(self):
# Need to hold a reference to this or the sc.Screen would be destroyed when out of scope
self.__transform = sc.Transform()
with self.__transform:
self.__screen = sc.Screen(gestures=self.__gestures)
def destroy(self):
self.__gestures = None
self.__screen = None
if self.__transform:
self.__transform.clear()
self.__transform = None
class FocalPickerScene:
def __init__(self, cam_focal_data: CamFocalData, ui_frame):
self.__ui_frame = ui_frame
self.__manip = None
self.__scene = None
with ui_frame:
# Need to insert a stack to get content_clipping and block events from going below us
self.__container = ui.VStack(content_clipping=True)
with self.__container:
self.__scene = sc.SceneView()
with self.__scene.scene:
self.__manip = ViewportClickManipulator(cam_focal_data)
def __del__(self):
self.destroy()
def destroy(self):
manip, self.__manip = self.__manip, None
if manip:
manip.destroy()
scene, self.__scene = self.__scene, None
if scene:
scene.destroy()
container, self.__container = self.__container, None
if container:
container.clear()
container.destroy()
# Clear ui.Frame, but kep it alive for next click
ui_frame, self.__ui_frame = self.__ui_frame, None
if ui_frame:
ui_frame.clear()
class CameraFocalDistance(AbstractCameraSetting):
def __init__(self, model: USDAttributeModel, viewport_context, enabled: bool = True):
self.__registered_scene = None
self.__viewport_api = viewport_context.get("viewport_api")
self.__ui_get_frame = viewport_context.get("layer_provider")
super().__init__(model, enabled=enabled)
def destroy(self):
self.__viewport_api = None
self.__ui_get_frame = None
self._destroy_scene()
def _build_ui(self) -> List[ui.MenuDelegate]:
self._focal_delegate = SpinnerMenuDelegate(
model=self._property_model,
height=26,
enabled=self._enabled,
text=False,
icon_name="FocalDistance",
tooltip="Camera Focal Distance",
icon_height=26,
use_in_menubar=True,
)
ui.MenuItem("Focal Distance", delegate=self._focal_delegate, identifier="viewport.camera.focal_distance")
self._sample_delegate = IconMenuDelegate(name="Sample", height=26, has_triangle=False, enabled=self._enabled, tooltip="Sample Focal Distance")
ui.MenuItem("Sample", delegate=self._sample_delegate, triggered_fn=self._sample, enabled=self._enabled, identifier="viewport.camera.sample")
return [self._focal_delegate, self._sample_delegate]
def _sample(self):
if self.__registered_scene:
# stop sample
self._destroy_scene()
elif self._enabled:
# start sample
asyncio.ensure_future(self.__create_focus_picker_scene())
async def __create_focus_picker_scene(self):
await omni.kit.app.get_app().next_update_async()
self.__destroy_scene_sync()
self.__registered_scene = FocalPickerScene(CamFocalData(weakref.proxy(self), self.__viewport_api),
self.__ui_get_frame.get_frame("omni.kit.viewport.menubar.camera.FocalPickerScene"))
def __destroy_scene_sync(self):
if self.__registered_scene:
self.__registered_scene.destroy()
self.__registered_scene = None
def _destroy_scene(self):
# Destroy on next event
async def ui_async_destroy():
await omni.kit.app.get_app().next_update_async()
self.__destroy_scene_sync()
asyncio.ensure_future(ui_async_destroy())
| 9,444 | Python | 37.868313 | 155 | 0.606417 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.