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.window.popup_dialog/omni/kit/window/popup_dialog/tests/test_options_menu.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import unittest import asyncio import omni.kit.app from pathlib import Path from omni.ui.tests.test_base import OmniUiTest from unittest.mock import Mock from ..options_menu import OptionsMenu, OptionsMenuWidget CURRENT_PATH = Path(__file__).parent.absolute() TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data/tests") class TestOptionsMenu(OmniUiTest): """Testing FormDialog""" async def setUp(self): self._field_defs = [ OptionsMenu.FieldDef("audio", "Audio", None, False), OptionsMenu.FieldDef("materials", "Materials", None, True), OptionsMenu.FieldDef("scripts", "Scripts", None, False), OptionsMenu.FieldDef("textures", "Textures", None, False), OptionsMenu.FieldDef("usd", "USD", None, True), ] self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("images") async def tearDown(self): pass async def test_ui_layout(self): """Testing that the UI layout looks consistent""" window = await self.create_test_window() with window.frame: OptionsMenuWidget( title="Options", field_defs=self._field_defs, ) await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="options_menu.png") window.destroy() # wait one frame so that widget is destroyed await omni.kit.app.get_app().next_update_async() async def test_okay_handler(self): """Test clicking okay button triggers the callback""" mock_value_changed_fn = Mock() under_test = OptionsMenu( title="Options", field_defs=self._field_defs, value_changed_fn=mock_value_changed_fn, ) under_test.show() self.assertEqual(under_test.get_value('usd'), True) under_test.destroy()
2,415
Python
37.349206
105
0.662112
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/tests/test_message_dialog.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import omni.kit.app from pathlib import Path from omni.ui.tests.test_base import OmniUiTest from unittest.mock import Mock from ..message_dialog import MessageWidget, MessageDialog CURRENT_PATH = Path(__file__).parent.absolute() TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data/tests") class TestMessageDialog(OmniUiTest): """Testing FormDialog""" async def setUp(self): self._message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("images") async def tearDown(self): pass async def test_message_widget(self): """Testing the look of message widget""" window = await self.create_test_window() with window.frame: under_test = MessageWidget() under_test.set_message(self._message) await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="message_dialog.png") window.destroy() # wait one frame so that widget is destroyed await omni.kit.app.get_app().next_update_async() async def test_messgae_dialog(self): """Testing the look of message dialog""" mock_cancel_handler = Mock() under_test = MessageDialog(title="Message", cancel_handler=mock_cancel_handler,) under_test.set_message("Hello World") under_test.show() await omni.kit.app.get_app().next_update_async() under_test._on_cancel() mock_cancel_handler.assert_called_once() under_test.destroy()
2,155
Python
41.274509
149
0.703016
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/tests/test_form_dialog.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import omni.ui as ui import omni.kit.app from pathlib import Path from omni.ui.tests.test_base import OmniUiTest from unittest.mock import Mock from ..form_dialog import FormDialog, FormWidget CURRENT_PATH = Path(__file__).parent.absolute() TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data/tests") class TestFormDialog(OmniUiTest): """Testing FormDialog""" async def setUp(self): self._field_defs = [ FormDialog.FieldDef("string", "String: ", ui.StringField, "default"), FormDialog.FieldDef("int", "Integer: ", ui.IntField, 1), FormDialog.FieldDef("float", "Float: ", ui.FloatField, 2.0), FormDialog.FieldDef( "tuple", "Tuple: ", lambda **kwargs: ui.MultiFloatField(column_count=3, h_spacing=2, **kwargs), None ), FormDialog.FieldDef("slider", "Slider: ", lambda **kwargs: ui.FloatSlider(min=0, max=10, **kwargs), 3.5), FormDialog.FieldDef("bool", "Boolean: ", ui.CheckBox, True), ] self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("images") async def tearDown(self): pass async def test_ui_layout(self): """Testing that the UI layout looks consistent""" window = await self.create_test_window() with window.frame: FormWidget( message="Test fields:", field_defs=self._field_defs, ) await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="form_dialog.png") window.destroy() # wait one frame so that widget is destroyed await omni.kit.app.get_app().next_update_async() async def test_okay_handler(self): """Test clicking okay button triggers the callback""" mock_okay_handler = Mock() under_test = FormDialog( message="Test fields:", field_defs=self._field_defs, ok_handler=mock_okay_handler, ) under_test.show() under_test._on_okay() await omni.kit.app.get_app().next_update_async() mock_okay_handler.assert_called_once() under_test.destroy() async def test_get_field_value(self): """Test that get_value returns the value of the named field""" under_test = FormDialog( message="Test fields:", field_defs=self._field_defs, ) for field in self._field_defs: name, label, _, default_value, focused = field self.assertEqual(default_value, under_test.get_value(name)) under_test.destroy() async def test_reset_dialog_value(self): """Test reset dialog value""" under_test = FormDialog( message="Test fields:", field_defs=self._field_defs, ) string_field = under_test.get_field("string") string_field.model.set_value("test") self.assertEqual(under_test.get_value("string"), "test") under_test.reset_values() self.assertEqual(under_test.get_value("string"), "default") under_test.destroy()
3,641
Python
39.021978
118
0.629223
omniverse-code/kit/exts/omni.kit.window.popup_dialog/omni/kit/window/popup_dialog/tests/test_options_dialog.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import unittest import asyncio import omni.kit.app from pathlib import Path from omni.ui.tests.test_base import OmniUiTest from unittest.mock import Mock from ..options_dialog import OptionsDialog, OptionsWidget CURRENT_PATH = Path(__file__).parent.absolute() TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data/tests") class TestOptionsDialog(OmniUiTest): """Testing FormDialog""" async def setUp(self): self._field_defs = [ OptionsDialog.FieldDef("hard", "Hard place", False), OptionsDialog.FieldDef("harder", "Harder place", True), OptionsDialog.FieldDef("hardest", "Hardest place", False), ] self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("images") async def tearDown(self): pass async def test_ui_layout(self): """Testing that the UI layout looks consistent""" window = await self.create_test_window() with window.frame: OptionsWidget( message="Please make your choice:", field_defs=self._field_defs, radio_group=False, ) await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="options_dialog.png") window.destroy() # wait one frame so that widget is destroyed await omni.kit.app.get_app().next_update_async() async def test_okay_handler(self): """Test clicking okay button triggers the callback""" mock_okay_handler = Mock() under_test = OptionsDialog( message="Please make your choice:", field_defs=self._field_defs, width=300, radio_group=False, ok_handler=mock_okay_handler, ) under_test.show() await asyncio.sleep(1) under_test._on_okay() mock_okay_handler.assert_called_once() # TODO: # self.assertEqual(under_test.get_choice(), 'harder') under_test.destroy()
2,523
Python
36.117647
107
0.653983
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/extension.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ChannelManagerExtension", "join_channel_async"] import carb import omni.ext from .manager import Channel, ChannelManager _global_instance = None class ChannelManagerExtension(omni.ext.IExt): # pragma: no cover def on_startup(self): global _global_instance _global_instance = self self._channel_manager = ChannelManager() self._channel_manager.on_startup() def on_shutdown(self): global _global_instance _global_instance = None self._channel_manager.on_shutdown() self._channel_manager = None async def join_channel_async(self, url, get_users_only) -> Channel: channel = await self._channel_manager.join_channel_async(url, get_users_only) return channel def _has_channel(self, url) -> bool: """Internal for testing.""" return self._channel_manager.has_channel(url) @staticmethod def _get_instance(): global _global_instance return _global_instance async def join_channel_async(url: str, get_users_only=False) -> Channel: """ Joins a channel and starts listening. The typical life cycle is as follows of a channel session if get_users_only is False: 1. User joins and sends a JOIN message to the channel. 2. Other clients receive JOIN message will respond with HELLO to broadcast its existence. 3. Clients communicate with each other by sending MESSAGE to each other. 4. Clients send LEFT before quit this channel. Args: url (str): The channel url to join. The url could be stage url or url with `.__omni_channel__` or `.channel` suffix. If the suffix is not provided, it will be appended internally with `.__omni_channel__` to be compatible with old version. get_users_only (bool): It will join channel without sending JOIN/HELLO/LEFT message but only receives message from other clients. For example, it can be used to fetch user list without broadcasting its existence. After joining, all users inside the channel will respond HELLO message. Returns: omni.kit.collaboration.channel_manager.Channel. The instance of channel that could be used to publish/subscribe channel messages. Examples: >>> import omni.kit.collaboration.channel_manager as nm >>> >>> async join_channel_async(url): >>> channel = await nm.join_channel_async(url) >>> if channel: >>> channel.add_subscriber(...) >>> await channel.send_message_async(...) >>> else: >>> # Failed to join >>> pass """ if not url.startswith("omniverse:"): carb.log_warn(f"Only Omniverse URL supports to create channel: {url}.") return None if not ChannelManagerExtension._get_instance(): carb.log_warn(f"Channel Manager Extension is not enabled.") return None channel = await ChannelManagerExtension._get_instance().join_channel_async(url, get_users_only=get_users_only) return channel
3,571
Python
38.252747
131
0.66508
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/manager.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__ = ["Channel", "ChannelSubscriber"] import asyncio import concurrent.futures import weakref import json import carb import carb.settings import omni.client import omni.kit.app import time import omni.kit.collaboration.telemetry import zlib from typing import Callable, Dict, List from .types import Message, MessageType, PeerUser CHANNEL_PING_TIME_IN_SECONDS = 60 # Period to ping. KIT_OMNIVERSE_CHANNEL_MESSAGE_HEADER = b'__OVUM__' KIT_CHANNEL_MESSAGE_VERSION = "3.0" OMNIVERSE_CHANNEL_URL_SUFFIX = ".__omni_channel__" OMNIVERSE_CHANNEL_NEW_URL_SUFFIX = ".channel" MESSAGE_VERSION_KEY = "version" MESSAGE_FROM_USER_NAME_KEY = "from_user_name" MESSAGE_CONTENT_KEY = "content" MESSAGE_TYPE_KEY = "message_type" MESSAGE_APP_KEY = "app" def _get_app(): # pragma: no cover settings = carb.settings.get_settings() app_name = settings.get("/app/name") or "Kit" if app_name.lower().endswith(".next"): # FIXME: OM-55917: temp hack for Create. return app_name[:-5] return app_name def _build_message_in_bytes(from_user, message_type, content): # pragma: no cover content = { MESSAGE_VERSION_KEY: KIT_CHANNEL_MESSAGE_VERSION, MESSAGE_TYPE_KEY: message_type, MESSAGE_FROM_USER_NAME_KEY: from_user, MESSAGE_CONTENT_KEY: content, MESSAGE_APP_KEY: _get_app(), } content_bytes = json.dumps(content).encode() return KIT_OMNIVERSE_CHANNEL_MESSAGE_HEADER + content_bytes class ChannelSubscriber: # pragma: no cover """Handler of subscription to a channel.""" def __init__(self, message_handler: Callable[[Message], None], channel: weakref) -> None: """ Constructor. Internal only. Args: message_handler (Callable[[Message], None]): Message handler to handle message. channel (weakref): Weak holder of channel. """ self._channel = channel self._message_handler = message_handler def __del__(self): self.unsubscribe() def unsubscribe(self): """Stop subscribe.""" self._message_handler = None if self._channel and self._channel(): self._channel()._remove_subscriber(self) def _on_message(self, message: Message): if self._message_handler: self._message_handler(message) class NativeChannelWrapper: # pragma: no cover """ Channel is the manager that manages message receive and distribution to MessageSubscriber. It works in subscribe/publish pattern. """ def __init__(self, url: str, get_users_only): """ Constructor. Internal only. """ self._url = url self._logged_user_name = "" self._logged_user_id = "" self._peer_users: Dict[str, PeerUser] = {} self._channel_handler = None self._subscribers = [] self._message_queue = [] self._stopped = False self._get_users_only = get_users_only self._stopping = False self._last_ping_time = time.time() self._last_user_response_time = {} self._all_pending_tasks = [] self._joining = False self._telemetry = omni.kit.collaboration.telemetry.Schema_omni_kit_collaboration_1_0() def _track_asyncio_task(self, task): self._all_pending_tasks.append(task) def _remove_asyncio_task(self, task): if task in self._all_pending_tasks: self._all_pending_tasks.remove(task) def _run_asyncio_task(self, func, *args): task = asyncio.ensure_future(func(*args)) self._track_asyncio_task(task) task.add_done_callback(lambda task: self._remove_asyncio_task(task)) return task def _remove_all_tasks(self): for task in self._all_pending_tasks: task.cancel() self._all_pending_tasks = [] def destroy(self): self._remove_all_tasks() self._telemetry = None @property def url(self) -> str: """Property. The channel url in Omniverse.""" return self._url @property def stopped(self) -> bool: """Property. If this channel is stopped already.""" return self._stopped or not self._channel_handler or self._channel_handler.is_finished() @property def stopping(self) -> bool: return self._stopping @property def logged_user_name(self) -> str: """Property. The logged user name for this channel.""" return self._logged_user_name @property def logged_user_id(self) -> str: """Property. The unique logged user id.""" return self._logged_user_id @property def peer_users(self) -> Dict[str, PeerUser]: """Property. All the peer clients that joined to this channel.""" return self._peer_users def _emit_channel_event(self, event_name:str): """ Generates a structured log event noting that a join or leave event has occurred. This event is sent through the 'omni.kit.collaboration.telemetry' extension. Args: event_name: the name of the event to send. This must be either 'join' or 'leave'. """ # build up the event data to emit. Note that the live-edit session's URL will be hashed # instead of exposed directly. This is because the URL contains both the USD stage name # and potential PII in the session's name tag itself (ie: "Bob_session". Both of these # are potentially considered either personal information or intellectual property and # should not be exposed in telemetry events. The hashed value will at least be stable # for any given URL. event = omni.kit.collaboration.telemetry.Struct_liveEdit_liveEdit() event.id = str(zlib.crc32(bytes(self.url, "utf-8"))) event.action = event_name settings = carb.settings.get_settings() cloud_link_id = settings.get("/cloud/cloudLinkId") or "" self._telemetry.liveEdit_sendEvent(cloud_link_id, event) async def join_channel_async(self): """ Async function. Join Omniverse Channel. Args: url: The url to create/join a channel. get_users_only: Johns channel as a monitor only or not. """ if self._get_users_only: carb.log_info(f"Getting users from channel: {self.url}") else: carb.log_info(f"Starting to join channel: {self.url}") if self._channel_handler: self._channel_handler.stop() self._channel_handler = None # Gets the logged user information. try: result, server_info = await omni.client.get_server_info_async(self.url) if result != omni.client.Result.OK: return False self._logged_user_name = server_info.username self._logged_user_id = server_info.connection_id except Exception as e: carb.log_error(f"Failed to join channel {self.url} since user token cannot be got: {str(e)}.") return False channel_connect_future = concurrent.futures.Future() # TODO: Should this function be guarded with mutex? # since it's called in another native thread. def on_channel_message( result: omni.client.Result, event_type: omni.client.ChannelEvent, from_user: str, content ): if not channel_connect_future.done(): if not self._get_users_only: carb.log_info(f"Join channel {self.url} successfully.") self._emit_channel_event("join") channel_connect_future.set_result(result == omni.client.Result.OK) if result != omni.client.Result.OK: carb.log_warn(f"Stop channel since it has errors: {result}.") self._stopped = True return self._on_message(event_type, from_user, content) self._joining = True self._channel_handler = omni.client.join_channel_with_callback(self.url, on_channel_message) result = channel_connect_future.result() if result: if self._get_users_only: await self._send_message_internal_async(MessageType.GET_USERS, {}) else: await self._send_message_internal_async(MessageType.JOIN, {}) self._joining = False return result def stop(self): """Stop this channel.""" if self._stopping or self.stopped: return if not self._get_users_only: carb.log_info(f"Stopping channel {self.url}") self._emit_channel_event("leave") self._stopping = True return self._run_asyncio_task(self._stop_async) async def _stop_async(self): if self._channel_handler and not self._channel_handler.is_finished(): if not self._get_users_only and not self._joining: await self._send_message_internal_async(MessageType.LEFT, {}) self._channel_handler.stop() self._channel_handler = None self._stopped = True self._stopping = False self._subscribers.clear() self._peer_users.clear() self._last_user_response_time.clear() def add_subscriber(self, on_message: Callable[[Message], None]) -> ChannelSubscriber: subscriber = ChannelSubscriber(on_message, weakref.ref(self)) self._subscribers.append(weakref.ref(subscriber)) return subscriber def _remove_subscriber(self, subscriber: ChannelSubscriber): to_be_removed = [] for item in self._subscribers: if not item() or item() == subscriber: to_be_removed.append(item) for item in to_be_removed: self._subscribers.remove(item) async def send_message_async(self, content: dict) -> omni.client.Request: if self.stopped or self.stopping: return return await self._send_message_internal_async(MessageType.MESSAGE, content) async def _send_message_internal_async(self, message_type: MessageType, content: dict): carb.log_verbose(f"Send {message_type} message to channel {self.url}, content: {content}") message = _build_message_in_bytes(self._logged_user_name, message_type, content) return await omni.client.send_message_async(self._channel_handler.id, message) def _update(self): if self.stopped or self._stopping: return # FIXME: Is this a must? pending_messages, self._message_queue = self._message_queue, [] for message in pending_messages: self._handle_message(message[0], message[1], message[2]) current_time = time.time() duration_in_seconds = current_time - self._last_ping_time if duration_in_seconds > CHANNEL_PING_TIME_IN_SECONDS: self._last_ping_time = current_time carb.log_verbose("Ping all users...") self._run_asyncio_task(self._send_message_internal_async, MessageType.GET_USERS, {}) dropped_users = [] for user_id, last_response_time in self._last_user_response_time.items(): duration = current_time - last_response_time if duration > CHANNEL_PING_TIME_IN_SECONDS: dropped_users.append(user_id) for user_id in dropped_users: peer_user = self._peer_users.pop(user_id, None) if not peer_user: continue message = Message(peer_user, MessageType.LEFT, {}) self._broadcast_message(message) def _broadcast_message(self, message: Message): for subscriber in self._subscribers: if subscriber(): subscriber()._on_message(message) def _on_message(self, event_type: omni.client.ChannelEvent, from_user: str, content): # Queue message handling to main looper. self._message_queue.append((event_type, from_user, content)) def _handle_message(self, event_type: omni.client.ChannelEvent, from_user: str, content): # Sent from me, skip them if not from_user: return self._last_user_response_time[from_user] = time.time() peer_user = None payload = {} message_type = None new_user = False if event_type == omni.client.ChannelEvent.JOIN: # We don't use JOIN from server pass elif event_type == omni.client.ChannelEvent.LEFT: peer_user = self._peer_users.pop(from_user, None) if peer_user: message_type = MessageType.LEFT elif event_type == omni.client.ChannelEvent.DELETED: self._channel_handler.stop() self._channel_handler = None elif event_type == omni.client.ChannelEvent.MESSAGE: carb.log_verbose(f"Message received from user with id {from_user}.") try: header_len = len(KIT_OMNIVERSE_CHANNEL_MESSAGE_HEADER) bytes = memoryview(content).tobytes() if len(bytes) < header_len: carb.log_error(f"Unsupported message received from user {from_user}.") else: bytes = bytes[header_len:] message = json.loads(bytes) except Exception: carb.log_error(f"Failed to decode message sent from user {from_user}.") return version = message.get(MESSAGE_VERSION_KEY, None) if not version or version != KIT_CHANNEL_MESSAGE_VERSION: carb.log_warn(f"Message version sent from user {from_user} does not match expected one: {message}.") return from_user_name = message.get(MESSAGE_FROM_USER_NAME_KEY, None) if not from_user_name: carb.log_warn(f"Message sent from unknown user: {message}") return message_type = message.get(MESSAGE_TYPE_KEY, None) if not message_type: carb.log_warn(f"Message sent from user {from_user} does not include message type.") return if message_type == MessageType.GET_USERS: carb.log_verbose(f"Fetch message from user with id {from_user}, name {from_user_name}.") if not self._get_users_only: self._run_asyncio_task(self._send_message_internal_async, MessageType.HELLO, {}) return peer_user = self._peer_users.get(from_user, None) if not peer_user: # Don't handle non-recorded user's left. if message_type == MessageType.LEFT: carb.log_verbose(f"User {from_user}, name {from_user_name} left channel.") return else: from_app = message.get(MESSAGE_APP_KEY, "Unknown") peer_user = PeerUser(from_user, from_user_name, from_app) self._peer_users[from_user] = peer_user new_user = True else: new_user = False if message_type == MessageType.HELLO: carb.log_verbose(f"Hello message from user with id {from_user}, name {from_user_name}.") if not new_user: return elif message_type == MessageType.JOIN: carb.log_verbose(f"Join message from user with id {from_user}, name {from_user_name}.") if not new_user: return if not self._get_users_only: self._run_asyncio_task(self._send_message_internal_async, MessageType.HELLO, {}) elif message_type == MessageType.LEFT: carb.log_verbose(f"Left message from user with id {from_user}, name {from_user_name}.") self._peer_users.pop(from_user, None) else: message_content = message.get(MESSAGE_CONTENT_KEY, None) if not message_content or not isinstance(message_content, dict): carb.log_warn(f"Message content sent from user {from_user} is empty or invalid format: {message}.") return carb.log_verbose(f"Message received from user with id {from_user}: {message}.") payload = message_content message_type = MessageType.MESSAGE if message_type and peer_user: # It's possible that user blocks its main thread and hang over the duration time to reponse ping command. # This is to notify user is back again. if new_user and message_type != MessageType.HELLO and message_type != MessageType.JOIN: message = Message(peer_user, MessageType.HELLO, {}) self._broadcast_message(message) message = Message(peer_user, message_type, payload) self._broadcast_message(message) class Channel: # pragma: no cover def __init__(self, handler: weakref, channel_manager: weakref) -> None: self._handler = handler self._channel_manager = channel_manager if self._handler and self._handler(): self._url = self._handler().url self._logged_user_name = self._handler().logged_user_name self._logged_user_id = self._handler().logged_user_id else: self._url = "" @property def stopped(self): return not self._handler or not self._handler() or self._handler().stopped @property def logged_user_name(self): return self._logged_user_name @property def logged_user_id(self): return self._logged_user_id @property def peer_users(self) -> Dict[str, PeerUser]: """Property. All the peer clients that joined to this channel.""" if self._handler and self._handler(): return self._handler().peer_users return None @property def url(self): return self._url def stop(self) -> asyncio.Future: if not self.stopped and self._channel_manager and self._channel_manager(): task = self._channel_manager()._stop_channel(self._handler()) else: task = None self._handler = None return task def add_subscriber(self, on_message: Callable[[Message], None]) -> ChannelSubscriber: """ Add subscriber. Args: on_message (Callable[[Message], None]): The message handler. Returns: Instance of ChannelSubscriber. The channel will be stopped if instance is release. So it needs to hold the instance before it's stopped. You can manually call `stop` to stop this channel, or set the returned instance to None. """ if not self.stopped: return self._handler().add_subscriber(on_message) return None async def send_message_async(self, content: dict) -> omni.client.Request: """ Async function. Send message to all peer clients. Args: content (dict): The message composed in dictionary. Return: omni.client.Request. """ if not self.stopped: return await self._handler().send_message_async(content) return None class ChannelManager: # pragma: no cover def __init__(self) -> None: self._all_channels: List[NativeChannelWrapper] = [] self._update_subscription = None def on_startup(self): carb.log_info("Starting Omniverse Channel Manager...") self._all_channels.clear() app = omni.kit.app.get_app() self._update_subscription = app.get_update_event_stream().create_subscription_to_pop( self._on_update, name="omni.kit.collaboration.channel_manager update" ) def on_shutdown(self): carb.log_info("Shutting down Omniverse Channel Manager...") self._update_subscription = None for channel in self._all_channels: self._stop_channel(channel) channel.destroy() self._all_channels.clear() def _stop_channel(self, channel: NativeChannelWrapper): if channel and not channel.stopping: task = channel.stop() return task return None def _on_update(self, dt): to_be_removed = [] for channel in self._all_channels: if channel.stopped: to_be_removed.append(channel) else: channel._update() for channel in to_be_removed: channel.destroy() self._all_channels.remove(channel) # Internal interface def has_channel(self, url: str): for channel in self._all_channels: if url == channel: return True return False async def join_channel_async(self, url: str, get_users_only: bool): """ Async function. Join Omniverse Channel. Args: url: The url to create/join a channel. get_users_only: Joins channel as a monitor only or not. """ channel_wrapper = NativeChannelWrapper(url, get_users_only) success = await channel_wrapper.join_channel_async() if success: self._all_channels.append(channel_wrapper) channel = Channel(weakref.ref(channel_wrapper), weakref.ref(self)) else: channel = None return channel
21,927
Python
35.304636
119
0.602727
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/types.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. # class PeerUser: """Information of peer user that's joined to the same channel.""" def __init__(self, user_id: str, user_name: str, from_app: str) -> None: """ Constructor. Internal only. Args: user_id (str): Unique user id. user_name (str): Readable user name. from_app (str): Which app this users join from. """ self._user_id = user_id self._user_name = user_name self._from_app = from_app @property def user_id(self): """Property. Unique user id.""" return self._user_id @property def user_name(self): """Property. Readable user name.""" return self._user_name @property def from_app(self): """Property. Readable app name, like 'Kit', 'Maya', etc.""" return self._from_app class MessageType: JOIN = "JOIN" # User is joined. Client should respond HELLO if it receives JOIN from new user. HELLO = "HELLO" # Someone said hello to me. Normally, client sends HELLO when it receives GET_USERS = "GET_USERS" # User does not join this channel, but wants to find who are inside this channel. # Clients receive this message should respond with HELLO to broadcast its existence. # Clients implement this command does not need to send JOIN firstly, and no LEFT sent # also before quitting channel. LEFT = "LEFT" # User left this channel. MESSAGE = "MESSAGE" # Normal message after JOIN. class Message: def __init__(self, from_user: PeerUser, message_type: MessageType, content: dict) -> None: """ Constructor. Internal only. Args: from_user (PeerUser): User that message sent from. message_type (MessageType): Message type. content (dict): Message content in dict. """ self._from_user = from_user self._message_type = message_type self._content = content @property def from_user(self) -> PeerUser: """Property. User that message sent from.""" return self._from_user @property def message_type(self) -> MessageType: """Property. Message type.""" return self._message_type @property def content(self) -> dict: """Property. Message content in dictionary.""" return self._content def __str__(self) -> str: return f"from: {self.from_user.user_name}, message_type: {self.message_type}, content: {self.content}"
3,048
Python
32.505494
113
0.613517
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/tests/__init__.py
from .channel_manager_tests import TestChannelManager
54
Python
26.499987
53
0.87037
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/tests/channel_manager_tests.py
import unittest import omni.client import omni.kit.test import omni.kit.app import omni.kit.collaboration.channel_manager as cm from omni.kit.collaboration.channel_manager.manager import _build_message_in_bytes from .test_base import enable_server_tests class TestChannelManager(omni.kit.test.AsyncTestCase): # pragma: no cover BASE_URL = "omniverse://localhost/Projects/tests/omni.kit.collaboration.channel_manger/" # Before running each test async def setUp(self): self.app = omni.kit.app.get_app() self.current_message = None async def tearDown(self): pass async def _wait(self, frames=10): for i in range(frames): await self.app.next_update_async() async def test_join_invalid_omniverse_url(self): channel = await cm.join_channel_async("file://c/invalid_url.channel") self.assertFalse(channel) channel = await cm.join_channel_async("omniverse://invalid-server/invalid_url.channel") self.assertFalse(channel) async def test_peer_user_and_message_api(self): peer_user = cm.PeerUser("test_id", "test", "Create") self.assertEqual(peer_user.user_id, "test_id") self.assertEqual(peer_user.user_name, "test") self.assertEqual(peer_user.from_app, "Create") content = {"key" : "value"} message = cm.Message(peer_user, cm.MessageType.HELLO, content=content) self.assertEqual(message.from_user, peer_user) self.assertEqual(message.message_type, cm.MessageType.HELLO) self.assertEqual(message.content, content) @unittest.skipIf(not enable_server_tests(), "") async def test_api(self): test_url = self.BASE_URL + "test.channel" def subscriber(message: cm.Message): self.current_message = message channel = await cm.join_channel_async(test_url) handle = channel.add_subscriber(subscriber) self.assertTrue(channel is not None, f"Failed to connect channel.") self.assertTrue(channel.url is not None) self.assertTrue(channel.logged_user_name is not None) self.assertTrue(channel.logged_user_id is not None) self.assertTrue(channel.stopped is False) # Send empty message result = await channel.send_message_async({}) self.assertTrue(result == omni.client.Result.OK) # Send more result = await channel.send_message_async({"test": "message_content"}) self.assertTrue(result == omni.client.Result.OK) # Simulates multi-users user_id = 0 for message_type in [cm.MessageType.JOIN, cm.MessageType.HELLO, cm.MessageType.LEFT]: self.current_message = None content = _build_message_in_bytes("test", message_type, {}) channel._handler()._handle_message(omni.client.ChannelEvent.MESSAGE, str(user_id), content) self.assertTrue(self.current_message is not None) self.assertEqual(self.current_message.message_type, message_type) self.assertEqual(self.current_message.from_user.user_id, str(user_id)) self.assertEqual(self.current_message.from_user.user_name, "test") # Don't increment user id for LEFT message as LEFT message will not be handled if user is not logged. if message_type == cm.MessageType.JOIN: user_id += 1 # Simulates customized message self.current_message = None content = {"test_key": "content"} message = _build_message_in_bytes("test", cm.MessageType.MESSAGE, content) channel._handler()._handle_message(omni.client.ChannelEvent.MESSAGE, str(user_id), message) self.assertTrue(self.current_message) self.assertEqual(self.current_message.message_type, cm.MessageType.MESSAGE) self.assertEqual(self.current_message.content, content) # Channel's LEFT message will be treated as left too. self.current_message = None channel._handler()._handle_message(omni.client.ChannelEvent.LEFT, str(user_id), None) self.assertEqual(self.current_message.message_type, cm.MessageType.LEFT) handle.unsubscribe() @unittest.skipIf(not enable_server_tests(), "") async def test_synchronization(self): test_url = self.BASE_URL + "test.channel" for i in range(20): channel = await cm.join_channel_async(test_url) self.assertTrue(not not channel)
4,456
Python
40.654205
113
0.665619
omniverse-code/kit/exts/omni.kit.collaboration.channel_manager/omni/kit/collaboration/channel_manager/tests/test_base.py
import carb.settings def enable_server_tests(): settings = carb.settings.get_settings() enabled = settings.get_as_bool("/exts/omni.kit.collaboration.channel_manager/enable_server_tests") return enabled
218
Python
20.899998
102
0.738532
omniverse-code/kit/exts/omni.debugdraw/omni/debugdraw/__init__.py
from ._debugDraw import IDebugDraw from ._debugDraw import acquire_debug_draw_interface, release_debug_draw_interface def _get_interface(func, acq): if not hasattr(func, "iface"): func.iface = acq() return func.iface def get_debug_draw_interface() -> IDebugDraw: return _get_interface(get_debug_draw_interface, acquire_debug_draw_interface) from .scripts.extension import *
397
Python
29.615382
82
0.735516
omniverse-code/kit/exts/omni.debugdraw/omni/debugdraw/scripts/extension.py
import omni.ext from .. import get_debug_draw_interface class DebugDrawExtension(omni.ext.IExt): def on_startup(self): get_debug_draw_interface() def on_shutdown(self): pass
201
Python
17.363635
40
0.676617
omniverse-code/kit/exts/omni.debugdraw/omni/debugdraw/tests/visualtests.py
import omni.kit.test from omni.ui.tests.test_base import OmniUiTest from omni.debugdraw import get_debug_draw_interface from omni.debugdraw._debugDraw import SimplexPoint import carb from pathlib import Path import inspect from omni.kit.viewport.utility import get_active_viewport_window, next_viewport_frame_async from omni.kit.viewport.utility.camera_state import ViewportCameraState from omni.kit.viewport.utility.tests import setup_viewport_test_window, capture_viewport_and_compare EXTENSION_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${omni.debugdraw}")).resolve().absolute() GOLDEN_IMAGES = EXTENSION_ROOT.joinpath("data", "tests") OUTPUTS_DIR = Path(omni.kit.test.get_test_output_path()) COLOR_RED = 0xffff0000 class DebugDrawVisualTest(OmniUiTest): def set_camera(self): camera_state = ViewportCameraState("/OmniverseKit_Persp") camera_state.set_position_world((10, 0, 0), False) camera_state.set_target_world((0, 0, 0), True) async def setup_viewport(self, resolution_x: int = 800, resolution_y: int = 600): await self.create_test_area(resolution_x, resolution_y) return await setup_viewport_test_window(resolution_x, resolution_y) async def base(self, fn): viewport_window = await self.setup_viewport() viewport = viewport_window.viewport_api await omni.usd.get_context().new_stage_async() self.set_camera() # Wait until the Viewport has delivered some frames await next_viewport_frame_async(viewport, 2) # Draw for 20 frames (TC: Windows requires ~5 Linux requires ~20) for _ in range(20): fn() await omni.kit.app.get_app().next_update_async() # Capture and compare the image test_caller = inspect.stack()[1][3] image_name = f"{test_caller}.png" passed, fail_msg = await capture_viewport_and_compare(image_name=image_name, output_img_dir=OUTPUTS_DIR, golden_img_dir=GOLDEN_IMAGES, viewport=viewport) self.assertTrue(passed, msg=fail_msg) def get_point(self, pos, width=2): p = SimplexPoint() p.position = pos p.color = COLOR_RED p.width = width return p async def setUp(self): await super().setUp() self._iface = get_debug_draw_interface() async def test_debugdraw_visual_sphere(self): await self.base(lambda: self._iface.draw_sphere(carb.Float3(0.0, 0.0, 0.0), 2, COLOR_RED)) async def test_debugdraw_visual_line(self): await self.base(lambda: self._iface.draw_line( carb.Float3(0.0, 0.0, 0.0), COLOR_RED, 2, carb.Float3(0.0, 2.0, 0.0), COLOR_RED, 2 )) async def test_debugdraw_visual_line_list(self): line_list = [ self.get_point(carb.Float3(0.0, 0.0, 0.0)), self.get_point(carb.Float3(0.0, -2.0, 0.0)), self.get_point(carb.Float3(0.0, 0.0, 0.0)), self.get_point(carb.Float3(0.0, 2.0, 0.0)), ] await self.base(lambda: self._iface.draw_lines(line_list)) async def test_debugdraw_visual_point(self): await self.base(lambda: self._iface.draw_point(carb.Float3(0.0, 0.0, 0.0), COLOR_RED, 10)) async def test_debugdraw_visual_box(self): await self.base(lambda: self._iface.draw_box( carb.Float3(0.0, 0.0, 0.0), carb.Float4(0.3535534, 0.3535534, 0.1464466, 0.8535534), carb.Float3(2, 2, 2), COLOR_RED )) async def test_debugdraw_visual_points(self): point_list = [ self.get_point(carb.Float3(0.0, 0.0, 0.0), 10), self.get_point(carb.Float3(0.0, -2.0, 0.0), 10), self.get_point(carb.Float3(0.0, 2.0, 0.0), 10), ] await self.base(lambda: self._iface.draw_points(point_list))
3,833
Python
38.122449
161
0.639969
omniverse-code/kit/exts/omni.debugdraw/omni/debugdraw/tests/__init__.py
from .visualtests import *
27
Python
12.999994
26
0.777778
omniverse-code/kit/exts/omni.kit.app_snippets/omni/kit/app_snippets/__init__.py
from ._app_snippets import *
29
Python
13.999993
28
0.724138
omniverse-code/kit/exts/omni.kit.app_snippets/omni/kit/app_snippets/tests/__init__.py
from .test_app_snippets import *
33
Python
15.999992
32
0.757576
omniverse-code/kit/exts/omni.kit.app_snippets/omni/kit/app_snippets/tests/test_app_snippets.py
import inspect import carb import carb.settings import omni.kit.app import omni.kit.test import omni.kit.app_snippets class RendererTest(omni.kit.test.AsyncTestCase): async def setUp(self): self._settings = carb.settings.acquire_settings_interface() self._app_snippets = omni.kit.app_snippets.acquire_app_snippets_interface() self._app_snippets.startup() def __test_name(self) -> str: return f"{self.__module__}.{self.__class__.__name__}.{inspect.stack()[2][3]}" async def tearDown(self): self._app_snippets.shutdown() self._app_snippets = None self._settings = None async def test_0_cpp_snippets(self): carb.log_warn("\n\n\ntest 0!!\n\n") failed_test_count = self._app_snippets.execute() carb.log_warn("failed test count: %d" % (failed_test_count)) self.assertEqual(0, failed_test_count)
902
Python
27.218749
85
0.648559
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/ogn/OgnScriptNodeDatabase.py
"""Support for simplified access to data on nodes of type omni.graph.scriptnode.ScriptNode This script node allows you to execute arbitrary Python code. `import` statements, function/class definitions, and global variables may be placed outside of the callbacks, and variables may be added to the ``db.internal_state`` state object The following callback functions may be defined in the script - ``setup(db)`` is called before compute the first time, or after reset is pressed - ``compute(db)`` is called every time the node computes (should always be defined) - ``cleanup(db)`` is called when the node is deleted or the reset button is pressed Predefined Variables - ``db (og.Database)`` is the node interface, attributes are exposed like ``db.inputs.foo``. Use ``db.log_error``, ``db.log_warning`` to report problems - ``og``: is the `omni.graph.core` module """ import carb import sys import traceback import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnScriptNodeDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.graph.scriptnode.ScriptNode Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.execIn inputs.script inputs.scriptPath inputs.usePath Outputs: outputs.execOut State: state.omni_initialized """ # 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:execIn', 'execution', 0, None, 'The input execution', {}, True, None, False, ''), ('inputs:script', 'string', 0, 'Inline Script', 'A string containing a Python script that may define code to be executed when the script node computes.\nSee the default and example scripts for more info.', {}, False, None, False, ''), ('inputs:scriptPath', 'token', 0, 'Script File Path', 'The path of a file containing a Python script that may define code to be executed when the script node computes.\nSee the default and example scripts for more info.', {ogn.MetadataKeys.UI_TYPE: 'filePath', 'fileExts': 'Python Scripts (*.py)'}, False, None, False, ''), ('inputs:usePath', 'bool', 0, 'Use Script File', "When true, the python script is read from the file specified in 'Script File Path', instead of the string in 'Inline Script'", {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('outputs:execOut', 'execution', 0, None, 'The output execution', {}, True, None, False, ''), ('state:omni_initialized', 'bool', 0, None, 'State attribute used to control when the script should be reloaded.\nThis should be set to False to trigger a reload of the script.', {}, 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.execIn = og.AttributeRole.EXECUTION role_data.inputs.script = og.AttributeRole.TEXT role_data.outputs.execOut = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"execIn", "script", "scriptPath", "usePath", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.execIn, self._attributes.script, self._attributes.scriptPath, self._attributes.usePath] self._batchedReadValues = [None, None, None, False] @property def execIn(self): return self._batchedReadValues[0] @execIn.setter def execIn(self, value): self._batchedReadValues[0] = value @property def script(self): return self._batchedReadValues[1] @script.setter def script(self, value): self._batchedReadValues[1] = value @property def scriptPath(self): return self._batchedReadValues[2] @scriptPath.setter def scriptPath(self, value): self._batchedReadValues[2] = value @property def usePath(self): return self._batchedReadValues[3] @usePath.setter def usePath(self, value): self._batchedReadValues[3] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"execOut", "_batchedWriteValues"} """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def execOut(self): value = self._batchedWriteValues.get(self._attributes.execOut) if value: return value else: data_view = og.AttributeValueHelper(self._attributes.execOut) return data_view.get() @execOut.setter def execOut(self, value): self._batchedWriteValues[self._attributes.execOut] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) @property def omni_initialized(self): data_view = og.AttributeValueHelper(self._attributes.omni_initialized) return data_view.get() @omni_initialized.setter def omni_initialized(self, value): data_view = og.AttributeValueHelper(self._attributes.omni_initialized) data_view.set(value) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnScriptNodeDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnScriptNodeDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnScriptNodeDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnScriptNodeDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.graph.scriptnode.ScriptNode' @staticmethod def compute(context, node): def database_valid(): return True try: per_node_data = OgnScriptNodeDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnScriptNodeDatabase(node) per_node_data['_db'] = db if not database_valid(): per_node_data['_db'] = None return False except: db = OgnScriptNodeDatabase(node) try: compute_function = getattr(OgnScriptNodeDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnScriptNodeDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnScriptNodeDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnScriptNodeDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) per_node_data = OgnScriptNodeDatabase.PER_NODE_DATA[node.node_id()] def on_connection_or_disconnection(*args): per_node_data['_db'] = None node.register_on_connected_callback(on_connection_or_disconnection) node.register_on_disconnected_callback(on_connection_or_disconnection) @staticmethod def release(node): release_function = getattr(OgnScriptNodeDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnScriptNodeDatabase._release_per_node_data(node) @staticmethod def release_instance(node, target): OgnScriptNodeDatabase._release_per_node_instance_data(node, target) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnScriptNodeDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnScriptNodeDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.scriptnode") node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Script Node") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "script") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This script node allows you to execute arbitrary Python code.\n `import` statements, function/class definitions, and global variables may be placed\n outside of the callbacks, and variables may be added to the ``db.internal_state`` state object\n \n The following callback functions may be defined in the script\n - ``setup(db)`` is called before compute the first time, or after reset is pressed\n - ``compute(db)`` is called every time the node computes (should always be defined)\n - ``cleanup(db)`` is called when the node is deleted or the reset button is pressed\n \n Predefined Variables\n - ``db (og.Database)`` is the node interface, attributes are exposed like ``db.inputs.foo``. Use ``db.log_error``, ``db.log_warning`` to report problems\n - ``og``: is the `omni.graph.core` module\n \n") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.scriptnode}") icon_path = icon_path + '/' + "ogn/icons/omni.graph.scriptnode.ScriptNode.svg" node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path) __hints = node_type.get_scheduling_hints() if __hints is not None: __hints.set_data_access(og.eAccessLocation.E_USD, og.eAccessType.E_WRITE) OgnScriptNodeDatabase.INTERFACE.add_to_node_type(node_type) node_type.set_has_state(True) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnScriptNodeDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None @staticmethod def register(node_type_class): OgnScriptNodeDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnScriptNodeDatabase.abi, 2) @staticmethod def deregister(): og.deregister_node_type("omni.graph.scriptnode.ScriptNode")
15,498
Python
47.586207
890
0.639115
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/ogn/python/nodes/OgnScriptNode.py
import inspect import os import tempfile import traceback import omni.client import omni.graph.core as og import omni.graph.tools.ogn as ogn import omni.usd from omni.graph.scriptnode.ogn.OgnScriptNodeDatabase import OgnScriptNodeDatabase # A hacky context manager that captures local variable name declarations and saves them in a dict class ScriptContextSaver: def __init__(self, script_context: dict): self.script_context = script_context self.local_names = None def __enter__(self): caller_frame = inspect.currentframe().f_back self.local_names = set(caller_frame.f_locals) return self def __exit__(self, exc_type, exc_val, exc_tb): caller_frame = inspect.currentframe().f_back caller_locals = caller_frame.f_locals for name in caller_locals: if name not in self.local_names: self.script_context[name] = caller_locals[name] class UserCode: """The cached data associated with a user script""" def __init__(self): self.code_object = None # The compiled code object self.setup_fn = None # setup() self.cleanup_fn = None # cleanup() self.compute_fn = None # compute() self.script_context = {} # namespace for the executed code class OgnScriptNodeState: def __init__(self): self.code = UserCode() # The cached code data self.tempfile_path: str = None # Name of the temporary file for storing the script self.script_path: str = None # The last value of inputs:scriptPath self.script: str = None # The last value of inputs:script self.use_path: bool = None # The last value of inputs:usePath self.node_initialized: bool = False # Flag used to check if the per-instance node state is initialized. class OgnScriptNode: @staticmethod def internal_state(): return OgnScriptNodeState() @staticmethod def _is_initialized(node: og.Node) -> bool: return og.Controller.get(og.Controller.attribute("state:omni_initialized", node)) @staticmethod def _set_initialized(node: og.Node, init: bool): return og.Controller.set(og.Controller.attribute("state:omni_initialized", node), init) @staticmethod def initialize(context, node: og.Node): state = OgnScriptNodeDatabase.per_node_internal_state(node) state.node_initialized = True # Create a temporary file for storing the script with tempfile.NamedTemporaryFile(suffix=".py", delete=False) as tf: state.tempfile_path = tf.name OgnScriptNode._set_initialized(node, False) @staticmethod def release(node: og.Node): state = OgnScriptNodeDatabase.per_node_internal_state(node) # Same logic as when the reset button is pressed OgnScriptNode.try_cleanup(node) # Delete the temporary file for storing the script if os.path.exists(state.tempfile_path): os.remove(state.tempfile_path) @staticmethod def try_cleanup(node: og.Node): # Skip if not setup in the fist place if not OgnScriptNode._is_initialized(node): return state = OgnScriptNodeDatabase.per_node_internal_state(node) # Call the user-defined cleanup function if state.code.cleanup_fn is not None: # Get the database object per_node_data = OgnScriptNodeDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get("_db") try: db.inputs._setting_locked = True # noqa: PLW0212 state.code.cleanup_fn(db) db.inputs._setting_locked = False # noqa: PLW0212 except Exception: # pylint: disable=broad-except OgnScriptNode._print_stacktrace(db) OgnScriptNode._set_initialized(node, False) @staticmethod def _print_stacktrace(db: OgnScriptNodeDatabase): stacktrace = traceback.format_exc().splitlines(keepends=True) stacktrace_iter = iter(stacktrace) stacktrace_output = "" for stacktrace_line in stacktrace_iter: if "OgnScriptNode.py" in stacktrace_line: # The stack trace shows that the exception originates from this file # Removing this useless information from the stack trace next(stacktrace_iter, None) else: stacktrace_output += stacktrace_line db.log_error(stacktrace_output) @staticmethod def _read_script_file(file_path: str) -> str: """Reads the given file and returns the contents""" # Get the absolute path from the possibly relative path in inputs:scriptPath with the edit layer edit_layer = omni.usd.get_context().get_stage().GetEditTarget().GetLayer() if not edit_layer.anonymous: file_path = omni.client.combine_urls(edit_layer.realPath, file_path).replace("\\", "/") del edit_layer # Try to read the script at the specified path result, _, content = omni.client.read_file(file_path) if result != omni.client.Result.OK: raise RuntimeError(f"Could not open/read the script at '{file_path}': error code: {result}") script_bytes = memoryview(content).tobytes() if len(script_bytes) < 2: return "" cur_script = script_bytes.decode("utf-8") return cur_script @staticmethod def _legacy_compute(db: OgnScriptNodeDatabase): # Legacy compute we just exec the whole script every compute with ScriptContextSaver(db.internal_state.code.script_context): exec(db.internal_state.code.code_object) # noqa: PLW0122 @staticmethod def compute(db) -> bool: # Note that we initialize this node's OgnScriptNodeState in the OgnScriptNode initialize # method. While this works for non-instanced workflows, if we try to instance an OmniGraph # that contains a ScriptNode we run into issues, mainly because the instanced ScriptNode # will NOT have an initialized OgnScriptNodeState (since the instanced node's initialize() # method was never actually executed). To account for this, in the compute method we'll # simply call the OgnScriptNode initialize() if said method was never called. if not db.internal_state.node_initialized: OgnScriptNode.initialize(db.abi_context, db.abi_node) use_path = db.inputs.usePath cur_script: str = "" # The script contents tempfile_path = db.internal_state.tempfile_path # The path to the script file to be compiled/executed initialized = db.state.omni_initialized if use_path: script_path = db.inputs.scriptPath if not script_path: return True else: # Use inputs:script for the script and the temporary file for the script path cur_script = db.inputs.script if not cur_script: return True if use_path != db.internal_state.use_path: initialized = False db.internal_state.use_path = use_path try: # Compile / Execute the script if necessary if not initialized: db.state.omni_initialized = True db.internal_state.code = UserCode() db.internal_state.script = None try: if use_path: cur_script = OgnScriptNode._read_script_file(script_path) db.internal_state.script_path = script_path # If the script content has changed we need to re-compile if db.internal_state.script != cur_script: with open(tempfile_path, "w", encoding="utf-8") as tf: tf.write(cur_script) db.internal_state.code.code_object = compile(cur_script, tempfile_path, "exec") db.internal_state.script = cur_script except Exception as ex: # pylint: disable=broad-except # No need for a callstack for an i/o or compilation error db.log_error(str(ex)) return False # Execute the script inside a context manager that captures the names defined in it with ScriptContextSaver(db.internal_state.code.script_context): exec(db.internal_state.code.code_object) # noqa: PLW0122 # Extract the user-defined setup, compute, and cleanup functions db.internal_state.code.compute_fn = db.internal_state.code.script_context.get("compute") if not callable(db.internal_state.code.compute_fn): db.internal_state.code.compute_fn = None if db.internal_state.code.compute_fn is None: # Assume the script is legacy, so execute on every compute db.log_warning("compute(db) not defined in user script, running in legacy mode") db.internal_state.code.compute_fn = OgnScriptNode._legacy_compute return True db.internal_state.code.setup_fn = db.internal_state.code.script_context.get("setup") if not callable(db.internal_state.code.setup_fn): db.internal_state.code.setup_fn = None db.internal_state.code.cleanup_fn = db.internal_state.code.script_context.get("cleanup") if not callable(db.internal_state.code.cleanup_fn): db.internal_state.code.cleanup_fn = None # Inject script-global names into the function globals if db.internal_state.code.compute_fn is not None: db.internal_state.code.compute_fn.__globals__.update(db.internal_state.code.script_context) if db.internal_state.code.setup_fn is not None: db.internal_state.code.setup_fn.__globals__.update(db.internal_state.code.script_context) if db.internal_state.code.cleanup_fn is not None: db.internal_state.code.cleanup_fn.__globals__.update(db.internal_state.code.script_context) # Call the user-defined setup function if db.internal_state.code.setup_fn is not None: db.internal_state.code.setup_fn(db) # ------------------------------------------------------------------------------------ # Call the user-defined compute function if db.internal_state.code.compute_fn is not None: db.internal_state.code.compute_fn(db) # Set outputs:execOut if not hidden if db.node.get_attribute("outputs:execOut").get_metadata(ogn.MetadataKeys.HIDDEN) != "1": db.outputs.execOut = og.ExecutionAttributeState.ENABLED except Exception: # pylint: disable=broad-except OgnScriptNode._print_stacktrace(db) return False return True
11,103
Python
43.594377
112
0.618752
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/_impl/extension.py
"""Support required by the Carbonite extension loader""" import asyncio from contextlib import suppress from typing import List import carb import carb.dictionary import omni.ext import omni.graph.core as og from omni.kit.app import get_app SCRIPTNODE_OPT_IN_SETTING = "/app/omni.graph.scriptnode/opt_in" SCRIPTNODE_ENABLE_OPT_IN_SETTING = "/app/omni.graph.scriptnode/enable_opt_in" OMNIGRAPH_STAGEUPDATE_ORDER = 100 # We want our attach() to run after OG so that nodes have been instantiated # ============================================================================================================== def set_all_graphs_enabled(enable: bool): """Set the enabled state of all OmniGraphs""" graphs = og.get_all_graphs() if graphs and not isinstance(graphs, list): graphs = [graphs] for graph in graphs: graph.set_disabled(not enable) def is_check_enabled(): """Returns True if scriptnode opt-in is enabled""" settings = carb.settings.get_settings() if not settings.is_accessible_as(carb.dictionary.ItemType.BOOL, SCRIPTNODE_ENABLE_OPT_IN_SETTING): # The enable-setting is not present, we enable the check return True if not settings.get(SCRIPTNODE_ENABLE_OPT_IN_SETTING): # The enable-setting is present and False, disable the check return False # the enable-setting is present and True, enable the check return True def on_opt_in_change(item: carb.dictionary.Item, change_type: carb.settings.ChangeEventType): """Update the local cache of the setting value""" if change_type != carb.settings.ChangeEventType.CHANGED: return settings = carb.settings.get_settings() should_run = bool(settings.get(SCRIPTNODE_OPT_IN_SETTING)) if should_run: set_all_graphs_enabled(True) def verify_scriptnode_load(script_nodes: List[og.Node]): """ Get verification from the user that they want to run scriptnodes. This opt-in applies to the current session only. Args: script_nodes: The list of script nodes on the stage that have been disabled. """ from omni.kit.window.popup_dialog import MessageDialog def on_cancel(dialog: MessageDialog): settings = carb.settings.get_settings() settings.set(SCRIPTNODE_OPT_IN_SETTING, False) dialog.hide() def on_ok(dialog: MessageDialog): settings = carb.settings.get_settings() settings.set(SCRIPTNODE_OPT_IN_SETTING, True) dialog.hide() message = """ This stage contains scriptnodes. There is currently no limitation on what code can be executed by this node. This means that graphs that contain these nodes should only be used when the author of the graph is trusted. Do you want to enable the scriptnode functionality for this session? """ dialog = MessageDialog( title="Warning", width=400, message=message, cancel_handler=on_cancel, ok_handler=on_ok, ok_label="Yes", cancel_label="No", ) async def show_async(): # wait a few frames to allow the app ui to finish loading await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() dialog.show() asyncio.ensure_future(show_async()) def check_for_scriptnodes(): """ Check for presence of omni.graph.scriptnode instances and confirm user wants to enable them. """ # If the check is not enabled then we are good if not is_check_enabled(): return # Check is enabled - see if they already opted-in settings = carb.settings.get_settings() scriptnode_opt_in = settings.get(SCRIPTNODE_OPT_IN_SETTING) if scriptnode_opt_in: # The check is enabled, and they opted-in return # The check is enabled but they opted out, or haven't been prompted yet try: import omni.kit.window.popup_dialog # noqa except ImportError: # Don't prompt in headless mode return script_nodes = [] graphs = og.get_all_graphs() if graphs and not isinstance(graphs, list): graphs = [graphs] for graph in graphs: for node in graph.get_nodes(): node_type = node.get_node_type() if node_type.get_node_type() == "omni.graph.scriptnode.ScriptNode": # Found one script_nodes.append(node) if not script_nodes: # No script nodes means we can leave them enabled return # Disable them until we get the opt-in via the async dialog set_all_graphs_enabled(False) verify_scriptnode_load(script_nodes) def on_attach(ext_id: int, _): """Called when USD stage is attached""" check_for_scriptnodes() # ============================================================================================================== class _PublicExtension(omni.ext.IExt): """Object that tracks the lifetime of the Python part of the extension loading""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.__stage_subscription = None self.__opt_in_setting_sub = None with suppress(ImportError): manager = get_app().get_extension_manager() # This is a bit of a hack to make the template directory visible to the OmniGraph UI extension # if it happens to already be enabled. The "hack" part is that this logic really should be in # omni.graph.ui, but it would be much more complicated there, requiring management of extensions # that both do and do not have dependencies on omni.graph.ui. if manager.is_extension_enabled("omni.graph.ui"): import omni.graph.ui as ogui # noqa: PLW0621 ogui.ComputeNodeWidget.get_instance().add_template_path(__file__) def on_startup(self): stage_update = omni.stageupdate.get_stage_update_interface() self.__stage_subscription = stage_update.create_stage_update_node("OmniGraphAttach", on_attach_fn=on_attach) assert self.__stage_subscription nodes = stage_update.get_stage_update_nodes() stage_update.set_stage_update_node_order(len(nodes) - 1, OMNIGRAPH_STAGEUPDATE_ORDER + 1) self.__opt_in_setting_sub = omni.kit.app.SettingChangeSubscription(SCRIPTNODE_OPT_IN_SETTING, on_opt_in_change) assert self.__opt_in_setting_sub def on_shutdown(self): self.__stage_subscription = None self.__opt_in_setting_sub = None
6,536
Python
35.316666
184
0.643666
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/_impl/scriptnode_example_scripts.py
# This file contains the set of example scripts for the script node. # User can click on the Code Snippets button in the UI to display these scripts. # To add new example scripts to the script node, # simply add the delimiter to the bottom of this file, followed by the new script. # Declare og to suppress linter warnings about undefined variables og = None # # # DELIMITER # # # Title = "Default Script" # This script is executed the first time the script node computes, or the next time it computes after this script # is modified or the 'Reset' button is pressed. # The following callback functions may be defined in this script: # setup(db): Called immediately after this script is executed # compute(db): Called every time the node computes (should always be defined) # cleanup(db): Called when the node is deleted or the reset button is pressed (if setup(db) was called before) # Defining setup(db) and cleanup(db) is optional, but if compute(db) is not defined then this script node will run # in legacy mode, where the entire script is executed on every compute and the callback functions above are ignored. # Available variables: # db: og.Database The node interface, attributes are db.inputs.data, db.outputs.data. # Use db.log_error, db.log_warning to report problems. # Note that this is available outside of the callbacks only to support legacy mode. # og: The OmniGraph module # Import statements, function/class definitions, and global variables may be placed outside of the callbacks. # Variables may also be added to the db.internal_state state object. # Example code snippet: import math UNITS = "cm" def calculate_circumfrence(radius): return 2 * math.pi * radius def setup(db): state = db.internal_state state.radius = 1 def compute(db): state = db.internal_state circumfrence = calculate_circumfrence(state.radius) print(f"{circumfrence} {UNITS}") state.radius += 1 # To see more examples, click on the Code Snippets button below. # # # DELIMITER # # # Title = "Compute Count" # In this example, we retrieve the number of times this script node has been computed # and assign it to Output Data so that downstream nodes can use this information. def compute(db): compute_count = db.node.get_compute_count() db.outputs.my_output_attribute = compute_count # # # DELIMITER # # # Title = "Fibonacci" # In this example, we produce the Fibonacci sequence 0, 1, 1, 2, 3, 5, 8, 13, 21... # Each time this node is evaluated, the next Fibonacci number will be set as the output value. # This illustrates how variables declared in the setup script can be used to keep persistent information. # Remember to add an output attribute of type 'int' named my_output_attribute first. def setup(db): state = db.internal_state state.num1 = 0 state.num2 = 1 def compute(db): state = db.internal_state total = state.num1 + state.num2 state.num1 = state.num2 state.num2 = total db.outputs.my_output_attribute = state.num1 # # # DELIMITER # # # Title = "Controller" # In this example, we use omni.graph.core.Controller to create cube prims. # Each time this node is evaluated, it will create a new cube prim on the scene. # When the 'Reset' button is pressed or the node is deleted, the created cube prims will be deleted. import omni.kit.commands def setup(db): state = db.internal_state state.cube_count = 0 def compute(db): state = db.internal_state state.cube_count += 1 og.Controller.edit( db.node.get_graph(), {og.Controller.Keys.CREATE_PRIMS: [(f"/World/Cube{state.cube_count}", "Cube")]} ) def cleanup(db): state = db.internal_state omni.kit.commands.execute("DeletePrims", paths=[f"/World/Cube{i}" for i in range(1, state.cube_count + 1)]) # # # DELIMITER # # # Title = "Random Vectors with Warp" # In this example, we compute the lengths of random 3D vectors using Warp import numpy as np import warp as wp wp.init() NUM_POINTS = 1024 DEVICE = "cuda" @wp.kernel def length(points: wp.array(dtype=wp.vec3), lengths: wp.array(dtype=float)): # thread index tid = wp.tid() # compute distance of each point from origin lengths[tid] = wp.length(points[tid]) def compute(db): # allocate an array of 3d points points = wp.array(np.random.rand(NUM_POINTS, 3), dtype=wp.vec3, device=DEVICE) lengths = wp.zeros(NUM_POINTS, dtype=float, device=DEVICE) # launch kernel wp.launch(kernel=length, dim=len(points), inputs=[points, lengths], device=DEVICE) print(lengths) # # # DELIMITER # # # Title = "Value Changed Callbacks" # In this example, we register a value changed callback function for inputs:my_input_attribute. # The callback is called when the value of inputs:my_input_attribute is changed from the property panel. # Remember to add an input attribute named my_input_attribute first. def on_my_input_attribute_changed(attr): print(f"inputs:my_input_attribute = {attr.get_attribute_data().get()}") def setup(db): attr = db.node.get_attribute("inputs:my_input_attribute") attr.register_value_changed_callback(on_my_input_attribute_changed) def compute(db): pass
5,239
Python
30.190476
116
0.712541
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/_impl/templates/template_omni.graph.scriptnode.ScriptNode.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 shutil import subprocess from functools import partial from pathlib import Path import carb.settings import omni.client import omni.graph.core as og import omni.graph.tools as ogt import omni.graph.tools.ogn as ogn import omni.ui as ui from omni.graph.scriptnode.ogn.OgnScriptNodeDatabase import OgnScriptNodeDatabase from omni.graph.ui import OmniGraphAttributeModel from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty from omni.kit.property.usd.usd_attribute_widget import UsdPropertyUiEntry from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidgetBuilder from omni.kit.widget.text_editor import TextEditor EXT_PATH = Path(__file__).absolute().parent.parent.parent.parent.parent.parent ICONS_PATH = EXT_PATH.joinpath("icons") FONTS_PATH = EXT_PATH.joinpath("fonts") class ComboBoxOption(ui.AbstractItem): """Provide a conversion from simple text to a StringModel to be used in ComboBox options""" def __init__(self, text: str): super().__init__() self.model = ui.SimpleStringModel(text) def destroy(self): self.model = None class ComboBoxModel(ui.AbstractItemModel): """The underlying model of a combo box""" def __init__(self, option_names, option_values, current_value, on_value_changed_callback): super().__init__() self.option_names = option_names self.option_values = option_values self.on_value_changed_callback = on_value_changed_callback self._current_index = ui.SimpleIntModel(self.option_values.index(current_value)) self._current_index.add_value_changed_fn(self._on_index_changed) self._items = [ComboBoxOption(option) for option in self.option_names] def destroy(self): ogt.destroy_property(self, "_current_index") ogt.destroy_property(self, "_items") def get_item_children(self, item): return self._items def get_item_value_model(self, item, column_id: int): if item is None: return self._current_index # combo box expects index model on item == None return item.model def _on_index_changed(self, new_index: ui.SimpleIntModel): new_value = self.option_values[new_index.as_int] self.on_value_changed_callback(new_value) self._item_changed(None) class CreateAttributePopupDialog: """The popup dialog for creating new dynamic attribute on the script node""" def __init__(self, create_new_attribute_callback, **kwargs): self.create_new_attribute_callback = create_new_attribute_callback self.all_supported_types = [] self.all_displayed_types = [] self.window = None self.attribute_name_field = None self.port_type_radio_collection = None self.input_port_button = None self.output_port_button = None self.state_port_button = None self.scrolling_frame = None self.selected_type_button = None self.selected_memory_type = None self.selected_cuda_pointers = None self.error_message_label = None self.get_all_supported_types() self.build_popup_dialog() def get_all_supported_types(self): """Get a list of types that can be added to the script node""" # "any" types need to be manually resolved by script writers, # "transform" types are marked for deprecation in USD, so we don't want to support them self.all_supported_types = [ attr_type for attr_type in ogn.supported_attribute_type_names() if attr_type != "any" and attr_type[:9] != "transform" ] self.all_displayed_types = self.all_supported_types def build_scrolling_frame(self): """Build the scrolling frame underneath the search bar""" def _on_type_selected(button): if self.selected_type_button is not None: self.selected_type_button.checked = False self.selected_type_button = button self.selected_type_button.checked = True self.scrolling_frame.clear() with self.scrolling_frame: with ui.VStack(): for displayed_type in self.all_displayed_types: button = ui.Button(displayed_type, height=20) button.set_clicked_fn(partial(_on_type_selected, button)) def build_popup_dialog(self): def filter_types_by_prefix(text): """Callback executed when the user presses enter in the search bar""" if text is None: self.all_displayed_types = self.all_supported_types else: text = text[0] self.all_displayed_types = [ displayed_type for displayed_type in self.all_supported_types if displayed_type[: len(text)] == text ] self.build_scrolling_frame() self.selected_type_button = None def on_create_new_attribute(): """Callback executed when the user creates a new dynamic attribute""" if not self.attribute_name_field.model.get_value_as_string(): self.error_message_label.text = "Error: Attribute name cannot be empty!" return if not self.attribute_name_field.model.get_value_as_string()[0].isalpha(): self.error_message_label.text = "Error: The first character of attribute name must be a letter!" return if ( not self.input_port_button.checked and not self.output_port_button.checked and not self.state_port_button.checked ): self.error_message_label.text = "Error: You must select a port type!" return if self.selected_type_button is None: self.error_message_label.text = "Error: You must select a type for the new attribute!" return attrib_name = self.attribute_name_field.model.get_value_as_string() attrib_port_type = og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT if self.output_port_button.checked: attrib_port_type = og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT elif self.state_port_button.checked: attrib_port_type = og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE attrib_type_name = self.selected_type_button.text attrib_type = og.AttributeType.type_from_ogn_type_name(attrib_type_name) self.create_new_attribute_callback( attrib_name, attrib_port_type, attrib_type, self.selected_memory_type, self.selected_cuda_pointers ) self.window.visible = False def on_cancel_clicked(): self.window.visible = False window_flags = ui.WINDOW_FLAGS_NO_RESIZE self.window = ui.Window( "Create Attribute", width=400, height=0, padding_x=15, padding_y=15, flags=window_flags, ) input_field_width = ui.Percent(60) with self.window.frame: with ui.VStack(spacing=10): # Attribute name string field with ui.HStack(height=0): ui.Label("Attribute Name: ") self.attribute_name_field = ui.StringField(width=input_field_width, height=20) # Attribute port type radio button with ui.HStack(height=0): ui.Label("Attribute Port Type: ") self.port_type_radio_collection = ui.RadioCollection() with ui.HStack(width=input_field_width, height=20): self.input_port_button = ui.RadioButton( text="input", radio_collection=self.port_type_radio_collection ) self.output_port_button = ui.RadioButton( text="output", radio_collection=self.port_type_radio_collection ) self.state_port_button = ui.RadioButton( text="state", radio_collection=self.port_type_radio_collection ) # Attribute type search bar with ui.HStack(height=0): ui.Label("Attribute Type: ", alignment=ui.Alignment.LEFT_TOP) with ui.VStack(width=input_field_width): # Search bar try: from omni.kit.widget.searchfield import SearchField SearchField(show_tokens=False, on_search_fn=filter_types_by_prefix) except ImportError: # skip the search bar if the module cannot be imported pass # List of attribute types self.scrolling_frame = ui.ScrollingFrame( height=150, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, style_type_name_override="TreeView", ) self.build_scrolling_frame() # TODO: Uncomment this block when dynamic attributes support memory types # # Attribute memory type combo box # with ui.HStack(height=0): # ui.Label("Attribute Memory Type: ") # memory_type_option_names = ["CPU", "CUDA", "Any"] # memory_type_option_values = [ogn.MemoryTypeValues.CPU, # ogn.MemoryTypeValues.CUDA, ogn.MemoryTypeValues.ANY] # self.selected_memory_type = ogn.MemoryTypeValues.CPU # def _on_memory_type_selected(new_memory_type): # self.selected_memory_type = new_memory_type # ui.ComboBox( # ComboBoxModel( # memory_type_option_names, # memory_type_option_values, # self.selected_memory_type, # _on_memory_type_selected, # ), # width=input_field_width, # ) # # CUDA pointers combo box # with ui.HStack(height=0): # ui.Label("CUDA Pointers: ") # cuda_pointers_option_names = ["CUDA", "CPU"] # cuda_pointers_option_values = [ogn.CudaPointerValues.CUDA, ogn.CudaPointerValues.CPU] # self.selected_cuda_pointers = ogn.CudaPointerValues.CUDA # def _on_cuda_pointers_selected(new_cuda_pointers): # self.selected_cuda_pointers = new_cuda_pointers # ui.ComboBox( # ComboBoxModel( # cuda_pointers_option_names, # cuda_pointers_option_values, # self.selected_cuda_pointers, # _on_cuda_pointers_selected, # ), # width=input_field_width, # ) # OK button to confirm selection with ui.HStack(height=0): ui.Spacer() with ui.HStack(width=input_field_width, height=20): ui.Button( "OK", clicked_fn=on_create_new_attribute, ) ui.Button( "Cancel", clicked_fn=on_cancel_clicked, ) # Some empty space to display error messages if needed self.error_message_label = ui.Label( " ", height=20, alignment=ui.Alignment.H_CENTER, style={"color": 0xFF0000FF} ) class ScriptTextbox(TextEditor): def __init__(self, script_model: OmniGraphAttributeModel): super().__init__( syntax=TextEditor.Syntax.PYTHON, style={"font": str(FONTS_PATH.joinpath("DejaVuSansMono.ttf"))}, text=script_model.get_value_as_string(), ) self.script_model = script_model self.script_model_callback_id = self.script_model.add_value_changed_fn(self._on_script_model_changed) self.set_edited_fn(self._on_script_edited) def _on_script_edited(self, text_changed: bool): if text_changed: # Don't trigger the model changed callback when script is edited self.script_model.remove_value_changed_fn(self.script_model_callback_id) # Remove the newline that TextEditor adds or else it will accumulate self.script_model.set_value(self.text[:-1]) self.script_model_callback_id = self.script_model.add_value_changed_fn(self._on_script_model_changed) def _on_script_model_changed(self, script_model): self.text = script_model.get_value_as_string() # noqa: PLW0201 class CustomLayout: def __init__(self, compute_node_widget): self._remove_attribute_menu = None self._code_snippets_menu = None self.enable = True self.compute_node_widget = compute_node_widget self.node_prim_path = self.compute_node_widget._payload[-1] self.node = og.Controller.node(self.node_prim_path) self.script_textbox_widget = None self.script_textbox_model = None self.script_textbox_resizer = None self.script_path_widget = None self.script_selector_window = None self.external_script_editor = None self.external_script_editor_ui_name = None self.DEFAULT_SCRIPT = "" self.EXAMPLE_SCRIPTS = [] self.EXAMPLE_SCRIPTS_TITLE = [] self.add_attribute_button = None self.remove_attribute_button = None self.code_snippets_button = None self.reset_button = None self.initialized_model = None self.EXISTING_ATTRIBUTES = [ "inputs:script", "inputs:scriptPath", "inputs:usePath", "inputs:execIn", "outputs:execOut", "state:omni_initialized", "node:type", "node:typeVersion", ] # Retrieve the example scripts cur_file_path = os.path.abspath(os.path.dirname(__file__)) example_scripts_path = os.path.join(cur_file_path, "..", "scriptnode_example_scripts.py") with open(example_scripts_path, "r", encoding="utf-8") as file: file_contents = file.read().split("# # # DELIMITER # # #") for script in file_contents[1:]: script = script.strip() script_lines = script.splitlines(keepends=True) script_title_line = script_lines[0] script_title = script_title_line.strip()[9:-1] script_content = "".join(script_lines[1:]) if script_title == "Default Script": self.DEFAULT_SCRIPT = script_content else: self.EXAMPLE_SCRIPTS.append(script_content) self.EXAMPLE_SCRIPTS_TITLE.append(script_title) # Determine the external script editor # Check the settings editor = carb.settings.get_settings().get("/app/editor") if not editor: # Check the environment variable EDITOR editor = os.environ.get("EDITOR", None) if not editor: # Default to VSCode editor = "code" # Remove quotes from the editor name if present if editor[0] == '"' and editor[-1] == '"': editor = editor[1:-1] # Get the user-friendly editor name editor_ui_name = editor if editor == "code": editor_ui_name = "VSCode" elif editor == "notepad": editor_ui_name = "Notepad" # Check that the editor exists and is executable if not (os.path.isfile(editor) and os.access(editor, os.X_OK)): try: editor = shutil.which(editor) except shutil.Error: editor = None if not editor: # Resort to notepad on windows and gedit on linux if os.name == "nt": editor = "notepad" editor_ui_name = "Notepad" else: editor = "gedit" editor_ui_name = "gedit" self.external_script_editor = editor self.external_script_editor_ui_name = editor_ui_name def retrieve_existing_attributes(self): """Retrieve the dynamic attributes that already exist on the node""" all_attributes = self.node.get_attributes() inputs = [ attrib for attrib in all_attributes if attrib.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT ] outputs = [ attrib for attrib in all_attributes if attrib.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ] states = [ attrib for attrib in all_attributes if attrib.get_port_type() == og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE ] return (all_attributes, inputs, outputs, states) def _on_script_textbox_resizer_dragged(self, offset_y: ui.Length): self.script_textbox_resizer.offset_y = max(offset_y.value, 50) def _script_textbox_build_fn(self, *args): """Build the textbox used to input custom scripts""" self.script_textbox_model = OmniGraphAttributeModel( self.compute_node_widget.stage, [self.node_prim_path.AppendProperty("inputs:script")], False, {} ) if self.script_textbox_model.get_value_as_string() == "": self.script_textbox_model.set_value(self.DEFAULT_SCRIPT) with ui.VStack(): with ui.HStack(): UsdPropertiesWidgetBuilder._create_label( # noqa: PLW0212 "Script", {}, {"style": {"alignment": ui.Alignment.RIGHT_TOP}} ) ui.Spacer(width=7) with ui.ZStack(): with ui.VStack(): self.script_textbox_widget = ScriptTextbox(self.script_textbox_model) # Disable editing if the script value comes from an upstream connection if og.Controller.attribute("inputs:script", self.node).get_upstream_connection_count() > 0: self.script_textbox_widget.read_only = True # noqa: PLW0201 ui.Spacer(height=12) # Add a draggable bar below the script textbox to resize it self.script_textbox_resizer = ui.Placer(offset_y=200, draggable=True, drag_axis=ui.Axis.Y) self.script_textbox_resizer.set_offset_y_changed_fn(self._on_script_textbox_resizer_dragged) with self.script_textbox_resizer: script_textbox_resizer_style = { ":hovered": {"background_color": 0xFFB0703B}, ":pressed": {"background_color": 0xFFB0703B}, } with ui.ZStack(height=12): ui.Rectangle(style=script_textbox_resizer_style) with ui.HStack(): ui.Spacer() ui.Label("V", width=0) ui.Spacer() ui.Spacer(height=5) with ui.HStack(): ui.Spacer() self._code_snippets_button_build_fn() def _code_snippets_button_build_fn(self, *args): """Build the code snippets button used to show example scripts""" def _code_snippets_menu_build_fn(): """Build the code snippets popup menu""" self._code_snippets_menu = ui.Menu("Code Snippets") with self._code_snippets_menu: for example_script_title, example_script in zip(self.EXAMPLE_SCRIPTS_TITLE, self.EXAMPLE_SCRIPTS): ui.MenuItem( example_script_title, triggered_fn=partial(self.script_textbox_model.set_value, example_script) ) self._code_snippets_menu.show() self.code_snippets_button = ui.Button("Code Snippets", width=135, clicked_fn=_code_snippets_menu_build_fn) def _on_initialized_changed(self, initialized_model): self.reset_button.enabled = initialized_model.as_bool def _reset_button_build_fn(self, *args): """Build button that calls the cleanup script and forces the setup script to be called on next compute""" def do_reset(): """Call the user-defined cleanup function and set state:omni_initialized to false""" OgnScriptNodeDatabase.NODE_TYPE_CLASS._try_cleanup(self.node) # noqa: PLW0212 self.reset_button.enabled = False def get_initialized(): """Get the value of state:omni_initialized""" initialized_attr = og.Controller.attribute("state:omni_initialized", self.node) return og.Controller.get(initialized_attr) self.reset_button = ui.Button( "Reset", width=135, clicked_fn=do_reset, enabled=get_initialized(), tooltip="Execute the setup script again on the next compute", ) self.initialized_model = OmniGraphAttributeModel( self.compute_node_widget.stage, [self.node_prim_path.AppendProperty("state:omni_initialized")], False, {} ) self.initialized_model.add_value_changed_fn(self._on_initialized_changed) def _add_attribute_button_build_fn(self, *args): def create_dynamic_attribute(attrib_name, attrib_port_type, attrib_type, attrib_memory_type, cuda_pointers): if ( attrib_name == "execOut" and attrib_port_type == og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT and attrib_type.get_ogn_type_name() == "execution" ): # Unhide outputs:execOut instead of creating it self.node.get_attribute("outputs:execOut").set_metadata(ogn.MetadataKeys.HIDDEN, None) return new_attribute = og.Controller.create_attribute(self.node, attrib_name, attrib_type, attrib_port_type) if new_attribute is None: return if attrib_type.get_type_name() == "prim" and attrib_port_type in ( og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE, ): # For bundle output/state attribs, the default UI name contains the port type, so we set it here instead def make_ui_name(attrib_name: str): parts_out = [] words = attrib_name.replace("_", " ").split(" ") for word in words: # noqa: PLR1702 if word.islower() or word.isupper(): parts_out += [word] else: # Mixed case. # Lower-case followed by upper-case breaks between them. E.g. 'usdPrim' -> 'usd Prim' # Upper-case followed by lower-case breaks before them. E.g: 'USDPrim' -> 'USD Prim' # Combined example: abcDEFgHi -> abc DE Fg Hi sub_word = "" uppers = "" for c in word: if c.isupper(): if not uppers: # noqa: SIM102 if sub_word: parts_out += [sub_word] sub_word = "" uppers += c else: if len(uppers) > 1: parts_out += [uppers[:-1]] sub_word += uppers[-1:] + c uppers = "" if sub_word: parts_out += [sub_word] elif uppers: parts_out += [uppers] # Title-case any words which are all lower case. parts_out = [part.title() if part.islower() else part for part in parts_out] return " ".join(parts_out) new_attribute.set_metadata(ogn.MetadataKeys.UI_NAME, make_ui_name(attrib_name)) # TODO: Uncomment this when dynamic attributes support memory types # new_attribute.set_metadata(ogn.MetadataKeys.MEMORY_TYPE, attrib_memory_type) # new_attribute.set_metadata(ogn.MetadataKeys.CUDA_POINTERS, cuda_pointers) self.compute_node_widget.rebuild_window() def on_click_add(): CreateAttributePopupDialog(create_dynamic_attribute) self.add_attribute_button = ui.Button("Add +", width=100, clicked_fn=on_click_add) def _remove_attribute_button_build_fn(self, *args): def remove_dynamic_attribute(attrib): if attrib.get_name() == "outputs:execOut": # Hide outputs:execOut instead of removing it og.Controller.disconnect_all(("outputs:execOut", self.node)) attrib.set_metadata(ogn.MetadataKeys.HIDDEN, "1") return success = og.Controller.remove_attribute(attrib) if not success: return self.compute_node_widget.rebuild_window() def _remove_attribute_menu_build_fn(): self._remove_attribute_menu = ui.Menu("Remove Attribute") (all_attributes, _, _, _) = self.retrieve_existing_attributes() with self._remove_attribute_menu: for attrib in all_attributes: name = attrib.get_name() # These attributes were not created by user so they are not deletable, # except for outputs:execOut, which can be hidden if not already hidden if not attrib.is_dynamic() and not ( name == "outputs:execOut" and attrib.get_metadata(ogn.MetadataKeys.HIDDEN) != "1" ): continue # Any attribute without the inputs:/outputs:/state: prefix were not created by user so they are # not deletable, except for bundle output and state attributes, which are delimited with '_' if ( name[:7] != "inputs:" and name[:8] != "outputs:" and name[:6] != "state:" and not ( attrib.get_type_name() == "bundle" and (name[:8] == "outputs_" or name[:6] == "state_") ) ): continue # Otherwise we should allow user to delete this attribute ui.MenuItem(name, triggered_fn=partial(remove_dynamic_attribute, attrib)) self._remove_attribute_menu.show() self.remove_attribute_button = ui.Button("Remove -", width=100, clicked_fn=_remove_attribute_menu_build_fn) def _special_control_build_fn(self, *args): with ui.HStack(): self._add_attribute_button_build_fn() ui.Spacer(width=8) self._remove_attribute_button_build_fn() def _get_absolute_script_path(self): """Get the possibly relative path in inputs:scriptPath as an aboslute path""" script_path = og.Controller.get(og.Controller.attribute("inputs:scriptPath", self.node)) edit_layer = self.compute_node_widget.stage.GetEditTarget().GetLayer() if not edit_layer.anonymous: script_path = omni.client.combine_urls(edit_layer.realPath, script_path).replace("\\", "/") return script_path def _show_script_selector_window(self): """Create and show the file browser window which is used to select the script for inputs:scriptPath""" try: from omni.kit.window.filepicker import FilePickerDialog except ImportError: # Do nothing if the module cannot be imported return def _on_click_okay(filename: str, dirname: str): # Get the relative path relative to the edit layer chosen_file = omni.client.combine_urls(dirname, filename) edit_layer = self.compute_node_widget.stage.GetEditTarget().GetLayer() if not edit_layer.anonymous: chosen_file = omni.client.make_relative_url(edit_layer.realPath, chosen_file) chosen_file = chosen_file.replace("\\", "/") # Set the value of inputs:scriptPath self.script_path_widget.set_value(chosen_file) self.script_selector_window.hide() def _on_click_cancel(filename: str, dirname: str): self.script_selector_window.hide() self.script_selector_window = FilePickerDialog( "Select a Python script", click_apply_handler=_on_click_okay, click_cancel_handler=_on_click_cancel, allow_multi_selection=False, file_extension_options=[("*.py", "Python scripts (*.py)")], ) self.script_selector_window.show(self._get_absolute_script_path()) def _launch_external_script_editor(self): """Launch an external editor targeting the path specified in inputs:scriptPath""" # Use cmd in case the editor is a bat or cmd file call_command = ["cmd", "/c"] if os.name == "nt" else [] call_command.append(self.external_script_editor) call_command.append(self._get_absolute_script_path()) subprocess.Popen(call_command) # noqa: PLR1732 def _script_path_build_fn(self, ui_prop: UsdPropertyUiEntry, *args): """Build the attribute label, textbox, browse button, and edit button for inputs:scriptPath""" self.script_path_widget = UsdPropertiesWidgetBuilder._string_builder( # noqa: PLW0212 self.compute_node_widget.stage, ui_prop.prop_name, ui_prop.property_type, ui_prop.metadata, [self.node_prim_path], {"style": {"alignment": ui.Alignment.RIGHT_TOP}}, ) ui.Spacer(width=5) ui.Button( image_url=str(ICONS_PATH.joinpath("folder_open.svg")), width=22, height=22, style={"Button": {"background_color": 0x1F2124}}, clicked_fn=self._show_script_selector_window, tooltip="Browse...", ) ui.Spacer(width=5) ui.Button( image_url=str(ICONS_PATH.joinpath("external_link.svg")), width=22, height=22, style={"Button": {"background_color": 0x1F2124}}, clicked_fn=self._launch_external_script_editor, tooltip=f"Open in {self.external_script_editor_ui_name}\n(set the preferred editor from the '/app/editor' setting)", ) def apply(self, props): """Called by compute_node_widget to apply UI when selection changes""" def find_prop(name): try: return next((p for p in props if p.prop_name == name)) except StopIteration: return None frame = CustomLayoutFrame(hide_extra=True) (_, inputs, outputs, states) = self.retrieve_existing_attributes() with frame: with ui.HStack(): ui.Spacer() self._reset_button_build_fn() with CustomLayoutGroup("Add and Remove Attributes"): CustomLayoutProperty(None, None, self._special_control_build_fn) with CustomLayoutGroup("Inputs"): prop = find_prop("inputs:script") CustomLayoutProperty(prop.prop_name, "Script", partial(self._script_textbox_build_fn, prop)) prop = find_prop("inputs:usePath") CustomLayoutProperty(prop.prop_name, "Use Path") prop = find_prop("inputs:scriptPath") CustomLayoutProperty(prop.prop_name, "Script Path", partial(self._script_path_build_fn, prop)) for input_attrib in inputs: attrib_name = input_attrib.get_name() if input_attrib.is_dynamic(): prop = find_prop(attrib_name) if prop is not None: CustomLayoutProperty(prop.prop_name, attrib_name[7:]) with CustomLayoutGroup("Outputs"): for output_attrib in outputs: attrib_name = output_attrib.get_name() if output_attrib.is_dynamic(): prop = find_prop(attrib_name) if prop is not None: CustomLayoutProperty(prop.prop_name, attrib_name[8:]) with CustomLayoutGroup("State"): for state_attrib in states: attrib_name = state_attrib.get_name() if state_attrib.is_dynamic(): prop = find_prop(attrib_name) if prop is not None: CustomLayoutProperty(prop.prop_name, attrib_name) return frame.apply(props)
34,537
Python
44.325459
128
0.559603
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/tests/test_scriptnode_ui.py
"""Tests for scriptnode which exercise the UI""" import os import tempfile import omni.graph.core as og import omni.graph.ui._impl.omnigraph_attribute_base as ogab import omni.kit.app import omni.kit.commands import omni.kit.test import omni.ui as ui import omni.usd from omni.kit import ui_test from omni.kit.test_suite.helpers import wait_for_window from omni.ui.tests.test_base import OmniUiTest class TestScriptNodeUI(OmniUiTest): """ Tests for scriptnode which exercise the UI """ TEST_GRAPH_PATH = "/World/TestGraph" # Before running each test async def setUp(self): await super().setUp() # Ensure we have a clean stage for the test await omni.usd.get_context().new_stage_async() # Give OG a chance to set up on the first stage update await omni.kit.app.get_app().next_update_async() self._temp_file_path = None # A temporary file we need to clean up import omni.kit.window.property as p self._w = p.get_window() # The OG attribute-base UI should refresh every frame ogab.AUTO_REFRESH_PERIOD = 0 async def tearDown(self): if (self._temp_file_path is not None) and os.path.isfile(self._temp_file_path): os.remove(self._temp_file_path) # Close the stage to avoid dangling references to the graph. (OM-84680) await omni.usd.get_context().close_stage_async() await super().tearDown() async def test_interaction(self): """ Exercise the controls on the custom template """ usd_context = omni.usd.get_context() keys = og.Controller.Keys controller = og.Controller() (_, (script_node,), _, _) = controller.edit( self.TEST_GRAPH_PATH, { keys.CREATE_NODES: [ ("ScriptNode", "omni.graph.scriptnode.ScriptNode"), ], keys.SET_VALUES: [("ScriptNode.inputs:usePath", False), ("ScriptNode.inputs:scriptPath", "")], }, ) ok = script_node.create_attribute( "outputs:out", og.Type(og.BaseDataType.INT), og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT ) self.assertTrue(ok) attr_out = script_node.get_attribute("outputs:out") attr_script = script_node.get_attribute("inputs:script") # Select the node. usd_context.get_selection().set_selected_prim_paths([script_node.get_prim_path()], True) # Wait for property panel to converge await ui_test.human_delay(5) # Set the inline script back to empty attr_script.set("") reset_button = ui_test.find("Property//Frame/**/Button[*].identifier=='_scriptnode_reset'") script_path_model = ui_test.find("Property//Frame/**/.identifier=='sdf_asset_inputs:scriptPath'") use_path_toggle = ui_test.find("Property//Frame/**/.identifier=='bool_inputs:usePath'") snippets_button = ui_test.find("Property//Frame/**/Button[*].identifier=='_scriptnode_snippets'") # write out a script and change the file path await use_path_toggle.click() await ui_test.human_delay(5) # NamedTemporaryFile is not very nice on Windows, need to ensure we close before node tries to read with tempfile.NamedTemporaryFile(mode="w+t", encoding="utf-8", delete=False) as tf: self._temp_file_path = tf.name tf.write( """ def compute(db: og.Database): db.outputs.out = 42 return True""" ) await script_path_model.input(self._temp_file_path) await omni.kit.app.get_app().next_update_async() # verify it has now computed, because `input` above will trigger the widget `end_edit` self.assertEqual(attr_out.get(), 42) # change the script, verify it doesn't take effect until reset is pressed with open(self._temp_file_path, mode="w+t", encoding="utf-8") as tf: tf.write( """ def compute(db: og.Database): db.outputs.out = 1000 return True""" ) await omni.kit.app.get_app().next_update_async() # verify it has now computed self.assertEqual(attr_out.get(), 42) await reset_button.click() await ui_test.human_delay(1) # Verify the script now computed with the new script self.assertEqual(attr_out.get(), 1000) # Switch it back to inline script attr_script.set( """ def compute(db): db.outputs.out = 1 """ ) await ui_test.human_delay(1) await use_path_toggle.click() await reset_button.click() await ui_test.human_delay(1) self.assertEqual(attr_out.get(), 1) # Switch it back to external script await use_path_toggle.click() await ui_test.human_delay(1) self.assertEqual(attr_out.get(), 1000) # Now add an attribute using the dialog await ui_test.find("Property//Frame/**/Button[*].identifier=='_scriptnode_add_attribute'").click() await wait_for_window("Add Attribute") await ui_test.find("Add Attribute//Frame/**/StringField[*].identifier=='_scriptnode_name'").input("test_attrib") # Find the only string field without an identifier, that is the search field await ui_test.find("Add Attribute//Frame/**/StringField[*].identifier!='_scriptnode_name'").input("int64") await ui_test.find("Add Attribute//Frame/**/Button[*].text=='int64'").click() await ui_test.human_delay(1) await ui_test.find("Add Attribute//Frame/**/Button[*].identifier=='_scriptnode_add_ok'").click() await ui_test.human_delay(3) # Check the attribute was actually added attr_test = script_node.get_attribute("inputs:test_attrib") self.assertEqual(attr_test.get_resolved_type(), og.Type(og.BaseDataType.INT64, 1, 0)) # Show the remove menu, remove the item we added await ui_test.find("Property//Frame/**/Button[*].identifier=='_scriptnode_remove_attribute'").click() await ui_test.human_delay(1) menu = ui.Menu.get_current() test_item = next((item for item in ui.Inspector.get_children(menu) if item.text == "inputs:test_attrib")) test_item.call_triggered_fn() await ui_test.human_delay(1) self.assertFalse(script_node.get_attribute_exists("inputs:test_attrib")) menu.hide() # Clear the current script attr_script.set("") await ui_test.human_delay(1) # Show the snippets menu await snippets_button.click() await ui_test.human_delay(1) menu = ui.Menu.get_current() # select the first one, verify the script was changed ui.Inspector.get_children(menu)[0].call_triggered_fn() await ui_test.human_delay(1) self.assertTrue("def compute(db)" in attr_script.get())
6,930
Python
37.082417
120
0.623665
omniverse-code/kit/exts/omni.graph.scriptnode/omni/graph/scriptnode/tests/test_api.py
"""Testing the stability of the API in this module""" import omni.graph.core.tests as ogts import omni.graph.scriptnode as ogs from omni.graph.tools.tests.internal_utils import _check_module_api_consistency, _check_public_api_contents # ====================================================================== class _TestOmniGraphScriptNodeApi(ogts.OmniGraphTestCase): _UNPUBLISHED = ["bindings", "ogn", "tests"] async def test_api(self): _check_module_api_consistency(ogs, self._UNPUBLISHED) # noqa: PLW0212 _check_module_api_consistency(ogs.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(ogs.tests, [], [], only_expected_allowed=True) # noqa: PLW0212
825
Python
44.888886
107
0.653333
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/rtx_settings_widget.py
from pathlib import Path from typing import Callable, Dict, List import os import traceback import sys import omni.ui as ui import carb import omni.kit.commands import omni.kit.app from omni.kit.widget.settings import get_style, get_ui_style_name from .rtx_settings_stack import RTXSettingsStack from omni.kit.window.file_importer import get_file_importer from omni.kit.window.file_exporter import get_file_exporter from .usd_serializer import USDSettingsSerialiser CURRENT_PATH = Path(__file__).parent.absolute() ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("icons") RENDERER_CHANGED_EVT = carb.events.type_from_string( "render_settings.renderer.CHANGED" ) RENDERER_EVT_PAYLOAD_KEY = "renderer" # global renderers/stacks so any widget can use them registered_renderers: Dict[str, List[str]] = {} registered_stacks: Dict[str, Callable] = {} class RTXSettingsWidget(): engine_to_mode = { 'iray': '/rtx/iray/rendermode', 'rtx': '/rtx/rendermode', 'pxr': '/pxr/rendermode' } rendermode_to_settings = { 'RaytracedLighting': 'Real-Time', 'PathTracing': 'Interactive (Path Tracing)', 'iray': 'Accurate (Iray)' } def __init__(self, frame): style = None use_default_style = carb.settings.get_settings().get_as_bool("/persistent/app/window/useDefaultStyle") or False if not use_default_style: style = get_style() ui_style_name = get_ui_style_name() if ui_style_name == "NvidiaLight": option_icon_style = {"image_url": f"{ICON_PATH}/NvidiaLight/options.svg","color": 0xFF535354} else: option_icon_style = {"image_url": f"{ICON_PATH}/NvidiaDark/options.svg","color": 0xFF8A8777} self._option_icon_style = option_icon_style self._style = style self._frame = frame self._stack_frame = None self._renderer_model = None self._visible_stacks: Dict[str, RTXSettingsStack] = {} self.picker_open = False self._folder_exist_popup = None self._event_stream = omni.kit.app.get_app().get_message_bus_event_stream() def renderChangedSubscription(path): return omni.kit.app.SettingChangeSubscription(path, self.__active_renderer_changed) # If the viewport renderer is changed, update render settings to reflect it self._renderer_subscriptions = [renderChangedSubscription("/renderer/active")] # Also need to watch all engine-mode changes for _, path in self.engine_to_mode.items(): self._renderer_subscriptions.append(renderChangedSubscription(path)) # menu self._options_menu = ui.Menu("Options") with self._options_menu: ui.MenuItem("Load Settings", triggered_fn=self.load_from_usd) ui.MenuItem("Save Settings", triggered_fn=self.save_to_usd) ui.MenuItem("Reset Settings", triggered_fn=self.restore_all_settings) def destroy(self) -> None: """ """ for k, s in self._visible_stacks.items(): s.destroy() self._renderer_subscriptions = None def get_current_viewport_renderer(self, hydra_engine: str = None, render_mode: str = None): settings = carb.settings.get_settings() if hydra_engine is None: hydra_engine = settings.get('/renderer/active') if hydra_engine in self.engine_to_mode: if render_mode is None: render_mode = settings.get(self.engine_to_mode[hydra_engine]) # XXX: Delegate this to the render-settings-extension instance # (i.e.) let omni.hydra.pxr map HdStormRenderPlugin => Storm return self.rendermode_to_settings.get(render_mode, render_mode) return None def set_render_settings_to_viewport_renderer(self, hydra_engine: str = None, render_mode: str = None): renderer = self.get_current_viewport_renderer(hydra_engine, render_mode) if not renderer or not self._renderer_model: return renderer_list = list(registered_renderers.keys()) if renderer in renderer_list: index = renderer_list.index(renderer) self._renderer_model.get_item_value_model().set_value(index) def __active_renderer_changed(self, *args, **kwargs): self.set_render_settings_to_viewport_renderer() def build_ui(self) -> None: if not self._frame: return if self._style is not None: self._frame.set_style(self._style) self._frame.clear() with self._frame: with ui.VStack(spacing=5): ui.Spacer(height=5) with ui.HStack(height=20): ui.Spacer(width=20) ui.Label("Renderer", name="RenderLabel", width=80) renderer_list = list(registered_renderers.keys()) index = 0 current_renderer = self.get_current_viewport_renderer() #Set to the default renderer if it's there if current_renderer in renderer_list: index = renderer_list.index(current_renderer) self._renderer_model = ui.ComboBox(index, *renderer_list, name="renderer_choice").model self._renderer_model.add_item_changed_fn(lambda i, m: self.renderer_item_changed()) # build_stacks()) ui.Spacer(width=10) ui.Button( style=self._option_icon_style, width=20, clicked_fn=lambda: self._options_menu.show() ) ui.Spacer(width=10) ui.Spacer(height=0) self._stack_frame = ui.VStack() def build_stacks(self): """ "stacks" are the tabs in the Render Settings UI that contain groups of settings They can be reused amongst different renderers. This method is called every time the renderer is changed """ if not self._stack_frame: return for k, s in self._visible_stacks.items(): s.destroy() self._stack_frame.clear() if not registered_renderers: return current_renderer = self.get_current_renderer() current_renderer_stacks = registered_renderers.get(current_renderer, None) if not current_renderer_stacks: print("RTXSettingsWidget: renderer Not supported") return with self._stack_frame: # Build the stacks ("Common", "Ray Tracing" etc) self._collection = ui.RadioCollection() with ui.HStack(height=30): ui.Spacer(width=15) for name in current_renderer_stacks: ui.RadioButton( text=name, radio_collection=self._collection, clicked_fn=lambda p=name: self.show_stack_from_name(p), ) ui.Spacer(width=10) ui.Spacer(height=7) with ui.ScrollingFrame(): # stack pages with ui.ZStack(): for name in current_renderer_stacks: stack_class = registered_stacks.get(name, None) if not stack_class: continue self._visible_stacks[name] = stack_class() ui.Spacer(height=1) # Assume we want to show the middle stack - the renderer specific one if len(current_renderer_stacks) > 1 and self.have_stack(current_renderer_stacks[1]): self.show_stack_from_name(current_renderer_stacks[1]) def register_renderer(self, name: str, stacks_list: List[str]) -> None: registered_renderers[name] = stacks_list def register_stack(self, name: str, stack_class: Callable) -> None: registered_stacks[name] = stack_class self.build_stacks() def unregister_renderer(self, name): if name in registered_renderers: del registered_renderers[name] def unregister_stack(self, name): if name in registered_stacks: del registered_stacks[name] def set_current_renderer(self, renderer_name: str) -> None: """ sets the current renderer and updates the UI model """ if renderer_name in registered_renderers.keys(): renderer_names = list(registered_renderers.keys()) for cnt, r in enumerate(renderer_names): if r == renderer_name: self._renderer_model.get_item_value_model().set_value(cnt) def get_registered_renderers(self): return list(registered_renderers.keys()) def get_current_renderer(self) -> str: return list(registered_renderers.keys())[self._renderer_model.get_item_value_model().as_int] def have_stack(self, name: str) -> None: return name in self._visible_stacks.keys() def show_stack_from_name(self, name: str) -> None: if name not in self._visible_stacks.keys(): print("RTXSettingsWidget: Error No Key of that Name ") return for _, stack in self._visible_stacks.items(): stack.set_visible(False) # work out which index the named stack is in the current UI stack_index = 0 current_renderer_stack_names = registered_renderers.get(self.get_current_renderer(), None) for cnt, curr_stack_name in enumerate(current_renderer_stack_names): if curr_stack_name == name: stack_index = cnt self._visible_stacks[name].set_visible(True) self._collection.model.set_value(stack_index) def get_current_stack(self) -> str: for name, stack in self._visible_stacks.items(): if stack.get_visible(): return name return "" def get_renderer_stacks(self, renderer_name): return registered_renderers.get(renderer_name, None) def restore_all_settings(btn_widget): omni.kit.commands.execute("RestoreDefaultRenderSettingSection", path="/rtx") def save_to_usd(self): def save_handler(filename: str, dirname: str, extension: str = "", selections: List[str] = []): final_path = f"{dirname}{filename}{extension}" try: if os.path.exists(final_path): self._show_folder_exist_popup(final_path) else: serialiser = USDSettingsSerialiser() serialiser.save_to_usd(final_path) except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback) file_exporter = get_file_exporter() if file_exporter: file_exporter.show_window( title="Save USD File", export_button_label="Save", export_handler=save_handler, file_postfix_options=["settings"]) def load_from_usd(self): def load_handler(filename: str, dirname: str, selections: List[str]): final_path = f"{dirname}{filename}" try: serialiser = USDSettingsSerialiser() serialiser.load_from_usd(final_path) except: exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback) file_importer = get_file_importer() if file_importer: file_importer.show_window( title="Load USD File", import_button_label="Load", import_handler=load_handler, file_postfix_options=["settings"]) def renderer_item_changed(self) -> None: try: self._emit_renderer_changed_event() finally: self.build_stacks() def _emit_renderer_changed_event(self) -> None: payload = {RENDERER_EVT_PAYLOAD_KEY: self.get_current_renderer()} self._event_stream.push( event_type=RENDERER_CHANGED_EVT, payload=payload )
12,147
Python
37.811501
122
0.595044
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/rtx_settings_window.py
import omni.ui as ui import carb from typing import Callable, Dict, List from .rtx_settings_widget import RTXSettingsWidget class RTXSettingsWindow: def __init__(self): self._window = None if carb.settings.get_settings().get("/exts/omni.rtx.window.settings/startup/autoCreateWindow"): self._window = ui.Window("Render Settings", dockPreference=ui.DockPreference.RIGHT_TOP) self._window.deferred_dock_in("Stage", ui.DockPolicy.TARGET_WINDOW_IS_ACTIVE) self._settings_widget = RTXSettingsWidget(self._window.frame) self._build_ui() else: self._settings_widget = RTXSettingsWidget(None) def register_renderer(self, name: str, stacks_list: List[str]) -> None: return self._settings_widget.register_renderer(name, stacks_list) def get_registered_renderers(self): return self._settings_widget.get_registered_renderers() def get_current_renderer(self): return self._settings_widget.get_current_renderer() def set_current_renderer(self, renderer_name: str) -> None: return self._settings_widget.set_current_renderer(renderer_name) def register_stack(self, name: str, stack_class: Callable) -> None: return self._settings_widget.register_stack(name, stack_class) def show_stack_from_name(self, name: str) -> None: return self._settings_widget.show_stack_from_name(name) def get_renderer_stacks(self, renderer_name): return self._settings_widget.get_renderer_stacks(renderer_name) def get_current_stack(self) -> str: return self._settings_widget.get_current_stack() def unregister_renderer(self, name): return self._settings_widget.unregister_renderer(name) def unregister_stack(self, name): return self._settings_widget.unregister_stack(name) def set_visibility_changed_listener(self, listener): if self._window: self._window.set_visibility_changed_fn(listener) def set_render_settings_to_viewport_renderer(self, *args, **kwargs): return self._settings_widget.set_render_settings_to_viewport_renderer(*args, **kwargs) def set_visible(self, value: bool) -> None: if self._window: self._window.visible = value def destroy(self) -> None: """ """ self._settings_widget.destroy() self._settings_widget = None self._window = None def _build_ui(self) -> None: """ """ self._settings_widget.build_ui() def _build_stacks(self) -> None: """ "stacks" are the tabs in the Render Settings UI that contain groups of settings They can be reused amongst different renderers. This method is called every time the renderer is changed """ self._settings_widget.build_stacks()
2,843
Python
35.935064
103
0.663384
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/commands.py
import carb import carb.dictionary import carb.settings import omni.kit.commands from omni.rtx.window.settings.rendersettingsdefaults import RenderSettingsDefaults from omni.rtx.window.settings import RendererSettingsFactory class RestoreDefaultRenderSettingCommand(omni.kit.commands.Command): """ Restore default setting for Renderer **Command**. Args: path: Path to the setting to be reset. """ def __init__(self, path: str): self._path = path self._settings = carb.settings.get_settings() def do(self): self._value = self._settings.get(self._path) RenderSettingsDefaults().reset_setting_to_default(self._path) def undo(self): self._settings.set(self._path, self._value) class RestoreDefaultRenderSettingSectionCommand(omni.kit.commands.Command): """ Restore default settings for the whole section **Command**. Args: path: Path to the settings section to be reset. """ def __init__(self, path: str): self._path = path self._settings = carb.settings.get_settings() def do(self): self._section_copy = self._settings.create_dictionary_from_settings(self._path) RenderSettingsDefaults().reset_setting_to_default(self._path) def undo(self): self._settings.destroy_item(self._path) self._settings.update(self._path, self._section_copy, "", carb.dictionary.UpdateAction.OVERWRITE) class SetCurrentRenderer(omni.kit.commands.Command): """ Sets the current renderer Args: renderer_name: name of the renderer """ def __init__(self, renderer_name: str): self._renderer = renderer_name self._prev_renderer = None def do(self): self._prev_renderer = RendererSettingsFactory.get_current_renderer() RendererSettingsFactory.set_current_renderer(self._renderer) def undo(self): if self._prev_renderer: RendererSettingsFactory.set_current_renderer(self._prev_renderer) class SetCurrentStack(omni.kit.commands.Command): """ Sets the current stack (needs to be one which is valid for the current renderer) Args: stack_name: name of the stack """ def __init__(self, stack_name: str): self._stack = stack_name self._prev_stack = None def do(self): self._prev_stack = RendererSettingsFactory.get_current_stack() RendererSettingsFactory.set_current_stack(self._stack) def undo(self): if self._prev_stack: RendererSettingsFactory.set_current_stack(self._prev_stack) omni.kit.commands.register_all_commands_in_module(__name__)
2,664
Python
28.285714
105
0.671547
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/rtx_settings_stack.py
import omni.ui as ui from omni.rtx.window.settings.settings_collection_frame import SettingsCollectionFrame class RTXSettingsStack: """ define a stack of Settings Widgets """ def __init__(self) -> None: self._stack: ui.VStack = None def set_visible(self, value: bool): if self._stack: self._stack.visible = value def get_visible(self) -> bool: if self._stack: return self._stack.visible return False def destroy(self): if self in SettingsCollectionFrame.parents: mySettingsFrames = SettingsCollectionFrame.parents[self] for frame in mySettingsFrames: frame.destroy() del SettingsCollectionFrame.parents[self]
751
Python
27.923076
86
0.637816
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/extension.py
from functools import partial from typing import Callable, List import omni.ext import omni.kit.ui import omni.ui as ui import carb.settings from .rtx_settings_window import RTXSettingsWindow class RTXSettingsExtension(omni.ext.IExt): """The entry point for the extension""" WINDOW_NAME = "Render Settings" def __init__(self) -> None: super().__init__() RendererSettingsFactory.render_settings_extension_instance = self self._settings_window = RTXSettingsWindow() self._settings_window.set_visibility_changed_listener(self._visiblity_changed_fn) def on_startup(self): ui.Workspace.set_show_window_fn(self.WINDOW_NAME, partial(self.show_window, None)) window_menu = carb.settings.get_settings().get("exts/omni.rtx.window.settings/window_menu") self._menu_path = f"{window_menu}/{self.WINDOW_NAME}" editor_menu = omni.kit.ui.get_editor_menu() self._menu = None if editor_menu: self._menu = editor_menu.add_item( f"{self._menu_path}", self.show_window, priority=21, toggle=True, value=True, ) ui.Workspace.show_window(self.WINDOW_NAME) def on_shutdown(self): self._menu = None if self._settings_window: self._settings_window.set_visibility_changed_listener(None) self._settings_window.destroy() self._settings_window = None RendererSettingsFactory.render_settings_extension_instance = None ui.Workspace.set_show_window_fn(RTXSettingsExtension.WINDOW_NAME, None) def _set_menu(self, value): """Set the menu to create this window on and off""" editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.set_value(f"{self._menu_path}", value) def _visiblity_changed_fn(self, visible): if visible: self._set_menu(visible) else: self.show_window(None, False) def show_window(self, menu, value): self._set_menu(value) self._settings_window.set_visible(value) def show_render_settings(self, hd_engine: str, render_mode: str, show_window: bool = True): self._settings_window.set_render_settings_to_viewport_renderer(hd_engine, render_mode) if not show_window: return self.show_window(self._menu_path, True) async def focus_async(): window = ui.Workspace.get_window(self.WINDOW_NAME) if window: window.focus() import asyncio asyncio.ensure_future(focus_async()) class RendererSettingsFactory: """ entry point for other extensions to register renderers and settings stacks """ render_settings_extension_instance = None @classmethod def _get_render_settings_extension(cls): if not cls.render_settings_extension_instance: cls.render_settings_extension_instance = RTXSettingsExtension() return cls.render_settings_extension_instance @classmethod def register_renderer(cls, name: str, stacks_list: List[str]): rs = cls._get_render_settings_extension() rs._settings_window.register_renderer(name, stacks_list) rs._settings_window._build_ui() @classmethod def unregister_renderer(cls, name): rs = cls._get_render_settings_extension() rs._settings_window.unregister_renderer(name) @classmethod def build_ui(cls): """ This method may be called by either: + a dependent extension that's shutting down or starting up + when the app is shutting down We want to distinguish between them """ if omni.kit.app.get_app().is_running(): rs = cls._get_render_settings_extension() rs._settings_window._build_ui() rs._settings_window._build_stacks() @classmethod def set_current_renderer(cls, renderer_name: str) -> None: """ sets the current stack and updates the UI model """ rs = cls._get_render_settings_extension() rs._settings_window.set_current_renderer(renderer_name) @classmethod def get_current_renderer(cls): rs = cls._get_render_settings_extension() return rs._settings_window.get_current_renderer() @classmethod def register_stack(cls, name: str, stack_class: Callable): rs = cls._get_render_settings_extension() rs._settings_window.register_stack(name, stack_class) @classmethod def unregister_stack(cls, name) -> None: rs = cls._get_render_settings_extension() rs._settings_window.unregister_stack(name) @classmethod def set_current_stack(cls, name) -> None: """ sets the current stack and updates the UI model """ rs = cls._get_render_settings_extension() rs._settings_window.show_stack_from_name(name) @classmethod def get_current_stack(cls) -> str: rs = cls._get_render_settings_extension() return rs._settings_window.get_current_stack() @classmethod def get_registered_renderers(cls) -> list: rs = cls._get_render_settings_extension() return rs._settings_window.get_registered_renderers() @classmethod def get_renderer_stacks(cls, renderer) -> list: rs = cls._get_render_settings_extension() return rs._settings_window.get_renderer_stacks(renderer)
5,518
Python
32.858896
99
0.633563
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/__init__.py
from .extension import * from .commands import *
50
Python
11.749997
24
0.74
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/usd_serializer.py
import carb import os.path import omni.kit.commands import rtx.settings from omni.rtx.window.settings.rendersettingsdefaults import RenderSettingsDefaults from pxr import Usd, Gf class USDSettingsSerialiser: """ Save and Load RTX settings to/from USD @TOOD: get rtx:fog:fogColor working """ def __init__(self): self._settings = carb.settings.get_settings() def iterate_settings(self, usd_dict, d, path_string=""): for k, v in d.items(): key_string = path_string + "/" + str(k) if isinstance(v, dict): self.iterate_settings(usd_dict, v, path_string=path_string + "/" + k) else: default_flags = self._settings.get(rtx.settings.get_associated_setting_flags_path(key_string)) if default_flags is None or (default_flags & rtx.settings.SETTING_FLAGS_TRANSIENT): continue val = self._settings.get(key_string) default_key = RenderSettingsDefaults._get_associated_defaults_path(key_string) default_val = self._settings.get(default_key) usd_str = key_string.replace("/", ":") if default_val != val: # TODO: This code looks fairly dodgy if isinstance(val, list) and len(val) in [3, 4]: if isinstance(val[0], float): usd_dict[usd_str[1:]] = Gf.Vec3f(val) else: usd_dict[usd_str[1:]] = Gf.Vec3d(val) else: usd_dict[usd_str[1:]] = val def save_to_usd(self, stage_file_path=""): if os.path.exists(stage_file_path): curr_stage = Usd.Stage.Open(stage_file_path) # Save or overwrite else: curr_stage = Usd.Stage.CreateNew(stage_file_path) rootLayer = curr_stage.GetRootLayer() customLayerData = rootLayer.customLayerData settings_dict = self._settings.get_settings_dictionary("/rtx") usdDict = {} self.iterate_settings(usdDict, settings_dict.get_dict(), "/rtx") customLayerData["renderSettings"] = usdDict rootLayer.customLayerData = customLayerData curr_stage.Save() carb.log_info(f"saved {stage_file_path} {len(usdDict)} settings") def load_from_usd(self, stage_file_path=""): currStage = Usd.Stage.Open(stage_file_path) rootLayer = currStage.GetRootLayer() customLayerData = rootLayer.customLayerData renderSettingsVtVal = customLayerData["renderSettings"] loaded_count = 0 if renderSettingsVtVal: omni.kit.commands.execute("RestoreDefaultRenderSettingSection", path="/rtx") for k, v in renderSettingsVtVal.items(): rtx_key = k.replace(":", "/") default_flags = self._settings.get(rtx.settings.get_associated_setting_flags_path(rtx_key)) if default_flags is None or (default_flags & rtx.settings.SETTING_FLAGS_TRANSIENT): continue if isinstance(v, Gf.Vec3f) or isinstance(v, Gf.Vec3d): self._settings.set("/" + rtx_key, [v[0], v[1], v[2]]) else: self._settings.set(rtx_key, v) loaded_count += 1 carb.log_info(f"loaded {stage_file_path} {loaded_count} settings")
3,440
Python
39.011627
110
0.575291
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/rendersettingsdefaults.py
import carb.dictionary import carb.settings class SettingsDefaultHandler: def __init__(self): self._settings = carb.settings.get_settings() self._dictionary = carb.dictionary.get_dictionary() def _get_sanitized_path(self, path): if path is not None and len(path) > 0 and path[0] == "/": return path[1:] return "" def get_type(self, path): settings_dict = self._settings.get_settings_dictionary("") path = self._get_sanitized_path(path) item = self._dictionary.get_item(settings_dict, path) item_type = self._dictionary.get_item_type(item) return item_type def does_exist(self, path): return self.get_type(path) != carb.dictionary.ItemType.COUNT def set_default(self, path): item_type = self.get_type(path) if item_type == carb.dictionary.ItemType.FLOAT: self._settings.set(path, 0.0) elif item_type == carb.dictionary.ItemType.INT: self._settings.set(path, 0) elif item_type == carb.dictionary.ItemType.BOOL: self._settings.set(path, False) else: print("SettingsDefaultHandler unrecognised type", item_type) class RenderSettingsDefaults: """ This is a partial python implementation of Kit/rendering/include/rtx/utils/Settings.h which only provides sufficient functionality for getting/resetting default values by """ _settings = carb.settings.get_settings() _settings_dict = _settings.get_settings_dictionary("") @classmethod def _get_associated_defaults_path(cls, settings_path: str): bits = settings_path.split("/") if len(bits) == 2: return "/" + bits[1] + "-defaults" else: return "/" + bits[1] + "-defaults/" + "/".join(bits[2:]) def reset_setting_to_default(self, settings_path: str): defaultsPathStorage = self._get_associated_defaults_path(settings_path) srcItem = self._settings.get_settings_dictionary(defaultsPathStorage) # If we can't find a dictionary item, it's likely to be leaf node/scalar value if not srcItem: defaultValue = self._settings.get(defaultsPathStorage) self._settings.set(settings_path, defaultValue) # It's a dictionary Item.. just update the whole section elif isinstance(srcItem, carb.dictionary._dictionary.Item): self._settings.update(settings_path, srcItem, "", carb.dictionary.UpdateAction.OVERWRITE) else: print("reset_setting_to_default: unknown type")
2,597
Python
37.205882
101
0.640739
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/settings_collection_frame.py
from typing import Union, Any import carb.settings from omni.kit.widget.settings import SettingType import omni.kit.commands import omni.rtx.window.settings import omni.ui as ui from omni.kit.widget.settings import create_setting_widget, create_setting_widget_combo from omni.kit.widget.settings import SettingsWidgetBuilder, SettingsSearchableCombo import rtx.settings class FrameSessionState: """ stre any state we would like to persist across the Session """ frame_state = {} @classmethod def get_state(cls, frame_id: str, key: str) -> Any: if frame_id not in cls.frame_state: return None if key not in cls.frame_state[frame_id]: return None return cls.frame_state[frame_id][key] @classmethod def has_state(cls, frame_id: str, key: str) -> bool: if frame_id not in cls.frame_state: return False if key not in cls.frame_state[frame_id]: return False return True @classmethod def set_state(cls, frame_id: str, key: str, value: Any) -> None: if frame_id not in cls.frame_state: cls.frame_state[frame_id] = {} cls.frame_state[frame_id][key] = value class SettingsCollectionFrame: parents = {} # For later deletion of parents def __init__(self, frame_label: str, collapsed=True, parent=None) -> None: self.classNamespace = ".".join([self.__class__.__module__, self.__class__.__name__]) self._settings = carb.settings.get_settings() self._collapsedState = collapsed self._setting_path = self._frame_setting_path() if FrameSessionState.has_state(self.classNamespace, "collapsed"): self._collapsedState = FrameSessionState.get_state(self.classNamespace, "collapsed") self._widget = ui.CollapsableFrame( frame_label, height=0, build_fn=self.build_ui, build_header_fn=self.build_header, skip_draw_when_clipped=True, collapsed=self._collapsedState, ) self._widget.identifier = frame_label self._widget.set_collapsed_changed_fn(self.on_collapsed_changed) self.sub_widgets = [] self.sub_models = [] # store a reference to our parent to allow later destruction if parent: if parent in self.parents: self.parents[parent].append(self) else: self.parents[parent] = [self] def _frame_setting_path(self): """ subclass can overtide that to get a checkbox in the frame """ return None def destroy(self): """ We need to explicitly destroy widgets/models - there's usually a number of circular ref between model and Widget which can be difficult to track down and keep widgets alive after the Frame is rebuilt """ for w in self.sub_models: w.destroy() self.sub_models = [] for w in self.sub_widgets: del w self.sub_widgets = [] self._widget.set_collapsed_changed_fn(None) self._widget.set_build_fn(None) self._widget.clear() self._widget = None def _on_change(self, *_): self._rebuild() def on_collapsed_changed(self, collapsed): FrameSessionState.set_state(self.classNamespace, "collapsed", collapsed) def build_header(self, collapsed, title): triangle_alignment = ui.Alignment.RIGHT_CENTER triangle_width = 4 triangle_height = 6 if not collapsed: triangle_alignment = ui.Alignment.CENTER_BOTTOM triangle_width = 7 triangle_height = 5 with ui.HStack(height=20, style={"HStack": {"margin_height": 5}}): ui.Spacer(width=5) with ui.VStack(width=15): ui.Spacer() ui.Triangle( alignment=triangle_alignment, name="title", width=triangle_width, height=triangle_height, # Using the style defined in style.py" # style={"background_color": 0xFFCCCCCC}, ) ui.Spacer() ui.Label(title, name="title", width=0) ui.Spacer() if self._setting_path: with ui.VStack(width=20, content_clipping=True): ui.Spacer(height=4) widget, model = create_setting_widget(self._setting_path, SettingType.BOOL) if widget and model: widget.set_tooltip("Check to Activate") def expand_frame(model, frame): if frame: frame.collapsed = not model.get_value_as_bool() model.add_value_changed_fn(lambda m, frame=self._widget: expand_frame(m, frame)) ui.Spacer() def build_ui(self): with ui.VStack(height=0, spacing=5, style={"VStack": {"margin_width": 10}}): ui.Spacer(height=5) self._build_ui() ui.Spacer(height=5) def _rebuild(self): if self._widget: self._widget.rebuild() def _restore_defaults(self, path: str): omni.kit.commands.execute("RestoreDefaultSetting", path=path) def _add_setting( self, setting_type, name: str, path: str, range_from=0, range_to=0, speed=1, has_reset=True, tooltip="", hard_range=False, cleartext_path=None ): the_stack = ui.HStack(skip_draw_when_clipped=True) the_stack.identifier = "HStack_" + name.replace(" ","_") with the_stack: SettingsWidgetBuilder._create_label(name, path if not cleartext_path else cleartext_path, tooltip) widget, model = create_setting_widget(path, setting_type, range_from, range_to, speed, hard_range=hard_range) self.sub_widgets.append(widget) self.sub_models.append(model) if has_reset: button = SettingsWidgetBuilder._build_reset_button(path) model.set_reset_button(button) return widget def _add_internal_setting( self, setting_type, name: str, path: str, range_from=0, range_to=0, speed=1, has_reset=True, tooltip="" ): internal_path = rtx.settings.get_internal_setting_string(path) return self._add_setting(setting_type, name, internal_path, range_from, range_to, speed, has_reset, tooltip, cleartext_path=path) def _add_setting_combo( self, name: str, path: str, items: Union[list, dict], callback=None, has_reset=True, tooltip="", cleartext_path=None ): the_stack = ui.HStack(skip_draw_when_clipped=True) the_stack.identifier = "HStack_" + name.replace(" ","_") with the_stack: SettingsWidgetBuilder._create_label(name, path if not cleartext_path else cleartext_path, tooltip) widget, model = create_setting_widget_combo(path, items) self.sub_widgets.append(widget) self.sub_models.append(model) if has_reset: button = SettingsWidgetBuilder._build_reset_button(path) model.set_reset_button(button) return widget def _add_setting_searchable_combo(self, name: str, path: str, items: dict, default_item: str, tooltip=""): with ui.HStack(): SettingsWidgetBuilder._create_label(name, path, tooltip) widget = SettingsSearchableCombo(path, items, default_item) self.sub_widgets.append(widget) def _add_internal_setting_combo( self, name: str, path: str, items: Union[list, dict], callback=None, has_reset=True, tooltip="" ): internal_path = rtx.settings.get_internal_setting_string(path) return self._add_setting_combo(name, internal_path, items, callback, has_reset, tooltip, cleartext_path=path) def _get_internal_setting(self, path: str): return self._settings.get(rtx.settings.get_internal_setting_string(path)) def _subscribe_to_internal_setting_change(self, path: str): omni.kit.app.SettingChangeSubscription(rtx.settings.get_internal_setting_string(path), self._on_change) def _build_ui(self): """ virtual function that will be called in the Collapsable frame """ pass
8,412
Python
37.240909
124
0.601046
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/tests/test_defaults.py
import omni.kit.test import carb.settings from omni.rtx.window.settings.rendersettingsdefaults import RenderSettingsDefaults from omni.rtx.window.settings import commands from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows import omni.kit.commands class TestDefaults(omni.kit.test.AsyncTestCase): async def setUp(self): super().setUp() await arrange_windows() await omni.usd.get_context().new_stage_async() await omni.kit.app.get_app().next_update_async() settings = carb.settings.get_settings() # Am not sure what sets the default normally.. settings.set("/rtx-defaults/pathtracing/maxBounces", 4) async def test_rtx_setting(self): """ Test single item /rtx/pathtracing/maxBounces """ settings = carb.settings.get_settings() blah = RenderSettingsDefaults() blah.reset_setting_to_default("/rtx/pathtracing/maxBounces") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4) settings.set("/rtx/pathtracing/maxBounces", 12) currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 12) blah.reset_setting_to_default("/rtx/pathtracing/maxBounces") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4) async def test_rtx_setting_section(self): """ Test section /rtx/pathtracing """ settings = carb.settings.get_settings() blah = RenderSettingsDefaults() blah.reset_setting_to_default("/rtx/pathtracing") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4) settings.set("/rtx/pathtracing/maxBounces", 12) currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 12) blah.reset_setting_to_default("/rtx/pathtracing") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4) async def test_rtx_settings_all(self): """ Test entire section /rtx """ settings = carb.settings.get_settings() blah = RenderSettingsDefaults() blah.reset_setting_to_default("/rtx") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4) settings.set("/rtx/pathtracing/maxBounces", 12) currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 12) blah.reset_setting_to_default("/rtx") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4) async def test_commands(self): settings = carb.settings.get_settings() settings.set("/rtx/pathtracing/maxBounces", 15) omni.kit.commands.execute("RestoreDefaultRenderSetting", path="/rtx/pathtracing/maxBounces") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4) settings.set("/rtx/pathtracing/maxBounces", 16) omni.kit.commands.execute("RestoreDefaultRenderSettingSection", path="/rtx/pathtracing/maxBounces") currVal = settings.get("/rtx/pathtracing/maxBounces") self.assertEqual(currVal, 4)
3,336
Python
40.19753
121
0.668465
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/tests/test_serialiser.py
import os import tempfile import omni.kit.test import carb.settings import omni.kit.commands from omni.rtx.window.settings import RendererSettingsFactory from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows class TestSerialiser(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows() # After running each test async def tearDown(self): pass async def test_serialiser(self): from omni.rtx.window.settings.usd_serializer import USDSettingsSerialiser with tempfile.TemporaryDirectory() as tempdir: file = os.path.join(tempdir, "test.usd") serialiser = USDSettingsSerialiser() serialiser.save_to_usd(file) serialiser.load_from_usd(file)
925
Python
30.931033
121
0.724324
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/tests/__init__.py
from .test_defaults import * from .test_ui import * from .test_serialiser import *
83
Python
19.999995
30
0.746988
omniverse-code/kit/exts/omni.rtx.window.settings/omni/rtx/window/settings/tests/test_ui.py
import omni.kit.test import carb.settings import omni.kit.commands from omni.rtx.window.settings import RendererSettingsFactory import random class SettingsIterator(object): def __init__(self, output_dict): self._settings = carb.settings.get_settings() self._output_dict = output_dict def iterate(self, settings_dict, path_string=""): """ iterate rtx settings and get a flat dictionary back we can work with """ for k, v in settings_dict.items(): key_string = path_string + "/" + str(k) if isinstance(v, dict): self.iterate(v, path_string=path_string + "/" + k) else: val = self._settings.get(key_string) self._output_dict[key_string] = val class TestSetRenderSettings: @classmethod def generate_change_setting_command(cls, setting_path, current_value): if isinstance(current_value, bool): bool_choice = random.choice([True, False]) omni.kit.commands.execute("ChangeSetting", path=setting_path, value=bool_choice) elif isinstance(current_value, float): float_choice = 0.0 if abs(current_value) < 0.1: float_choice = random.uniform(0, 100) else: # TODO: We can make a better guess if we have more info about the range float_choice = random.uniform(current_value / 2, current_value * 2) omni.kit.commands.execute("ChangeSetting", path=setting_path, value=float_choice) elif isinstance(current_value, int): int_choice = 0 if current_value == 0: int_choice = random.choice(range(0, 100)) else: int_range = range(int(current_value / 2), int(current_value * 2)) if len(int_range) > 1: int_choice = random.choice(range(int(current_value / 2), int(current_value * 2))) omni.kit.commands.execute("ChangeSetting", path=setting_path, value=int_choice) elif isinstance(current_value, list): # TODO: add pass elif isinstance(current_value, str): # TODO: Without a bit more info (e.g from the "add_setting" calls in the UI) # it's hard to know what to do with strings - they could be filepaths/assets, # combo box elements etc. We should probably look at extracting that data pass else: print("this type is not supported") async def run_test_render_settings_ui(self, settings_path: str): """ we're really not attempting to assert anything here, just cycle through a bunch of commands and hope it doesn't segfault """ settings = carb.settings.get_settings() # if the renderers have initialised properly, this should have items settings_dict = settings.get_settings_dictionary(settings_path) output_dict = {} settingsIt = SettingsIterator(output_dict) settingsIt.iterate(settings_dict.get_dict(), settings_path) setting_list = list(output_dict) # TODO: add in ResetAllSettings and other commands # Set some settings, switch renderer, set stack, and do the same again several times for x in range(0, 20): for y in range(0, 10): key = random.choice(setting_list) self.generate_change_setting_command(key, output_dict[key]) await omni.kit.app.get_app().next_update_async() renderers = RendererSettingsFactory.get_registered_renderers() if renderers: renderer_choice = random.choice(RendererSettingsFactory.get_registered_renderers()) omni.kit.commands.execute("SetCurrentRenderer", renderer_name=renderer_choice) await omni.kit.app.get_app().next_update_async() for y in range(0, 10): key = random.choice(setting_list) self.generate_change_setting_command(key, output_dict[key]) await omni.kit.app.get_app().next_update_async() stacks = RendererSettingsFactory.get_renderer_stacks(renderer_choice) if stacks: stack_choice = random.choice(stacks) omni.kit.commands.execute("SetCurrentStack", stack_name=stack_choice) await omni.kit.app.get_app().next_update_async() # If we have get a crash, we should be able to replay it outside the unit testing framework # with commands... history = omni.kit.undo.get_history().values() for cmd in history: continue # print (cmd) class TestRTXCommandsDefaults(TestSetRenderSettings, omni.kit.test.AsyncTestCase): async def test_rtx_settings_ui(self): import omni.ui as ui w = ui.Workspace.get_window("Render Settings") w.position_x = 0 w.position_y = 20 w.width = 1440 w.height = 840 return await self.run_test_render_settings_ui("/rtx")
5,121
Python
41.683333
101
0.603788
omniverse-code/kit/exts/omni.kit.mainwindow/omni/kit/mainwindow/scripts/main_window.py
import asyncio import carb.settings import omni.kit.app import omni.ui as ui class MainWindow(object): def __init__(self): # Show gray color the first several frames. It will hode the windows # that are not yet docked. self._ui_main_window = ui.MainWindow(show_foreground=True) # this will be False for Release self.get_main_menu_bar().visible = False settings = carb.settings.get_settings() margin_width = settings.get_as_float("ext/omni.kit.mainwindow/margin/width") margin_height = settings.get_as_float("ext/omni.kit.mainwindow/margin/height") background_color = settings.get_as_int("ext/omni.kit.mainwindow/backgroundColor") self._ui_main_window.main_frame.set_style( {"margin_width": margin_width, "margin_height": margin_height, "background_color": background_color} ) self._setup_window_task = asyncio.ensure_future(self._dock_windows()) def destroy(self): self._ui_main_window = None def get_main_menu_bar(self) -> ui.MenuBar: return self._ui_main_window.main_menu_bar def get_status_bar_frame(self) -> ui.Frame: return self._ui_main_window.status_bar_frame def show_hide_menu(self): self.get_main_menu_bar().visible = not self.get_main_menu_bar().visible def show_hide_status_bar(self): self.get_status_bar_frame().visible = not self.get_status_bar_frame().visible async def _dock_windows(self): stage_win = None viewport = None property_win = None toolbar = None console = None frames = 3 while frames > 0: # setup the docking Space if not stage_win: stage_win = ui.Workspace.get_window("Stage") if not viewport: viewport = ui.Workspace.get_window("Viewport") if not property_win: property_win = ui.Workspace.get_window("Property") if not toolbar: toolbar = ui.Workspace.get_window("Main ToolBar") if not console: console = ui.Workspace.get_window("Console") if stage_win and viewport and property_win and toolbar and console: break # early out frames = frames - 1 await omni.kit.app.get_app().next_update_async() main_dockspace = ui.Workspace.get_window("DockSpace") if viewport: viewport.dock_in(main_dockspace, ui.DockPosition.SAME) if stage_win: stage_win.dock_in(viewport, ui.DockPosition.RIGHT, 0.3) if property_win: if stage_win: property_win.dock_in(stage_win, ui.DockPosition.BOTTOM, 0.5) else: property_win.dock_in(viewport, ui.DockPosition.RIGHT, 0.3) if console: console.dock_in(viewport, ui.DockPosition.BOTTOM, 0.3) if toolbar: toolbar.dock_in(viewport, ui.DockPosition.LEFT) self._setup_window_task = None # Hide foreground after 5 frames. It's enough for windows to appear. for _ in range(5): await omni.kit.app.get_app().next_update_async() self._ui_main_window.show_foreground = False
3,270
Python
33.431579
112
0.606422
omniverse-code/kit/exts/omni.kit.mainwindow/omni/kit/mainwindow/scripts/extension.py
import omni.ext from .main_window import MainWindow global g_main_window g_main_window = None def get_main_window() -> MainWindow: global g_main_window return g_main_window class MainWindowExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): global g_main_window self._main_window = MainWindow() g_main_window = self._main_window def on_shutdown(self): global g_main_window if (g_main_window): g_main_window.destroy() self._main_window = None g_main_window = None
727
Python
23.266666
119
0.662999
omniverse-code/kit/exts/omni.kit.mainwindow/omni/kit/mainwindow/tests/test_main_window.py
## Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from ..scripts.extension import get_main_window from omni.ui.tests.test_base import OmniUiTest import omni.kit.app import omni.kit.mainwindow import omni.kit.test import omni.ui as ui import carb.settings from pathlib import Path GOLDEN_IMAGE_PATH = Path(omni.kit.test.get_test_output_path()).resolve().absolute() class Test(OmniUiTest): # Before running each test async def setUp(self): pass # After running each test async def tearDown(self): pass async def test_dockspace(self): """Checking mainwindow is initialized""" self.assertIsNotNone(get_main_window()) await omni.kit.app.get_app().next_update_async() main_dockspace = ui.Workspace.get_window("DockSpace") self.assertIsNotNone(main_dockspace) async def test_windows(self): """Testing windows""" await self.create_test_area() width = ui.Workspace.get_main_window_width() height = ui.Workspace.get_main_window_height() window1 = ui.Window("Viewport", width=width, height=height) window2 = ui.Window("Viewport", width=width, height=height) window3 = ui.Window("Something Else", width=width, height=height) with window1.frame: ui.Rectangle(style={"background_color": ui.color.indigo}) with window2.frame: ui.Label("NVIDIA") for i in range(10): await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=GOLDEN_IMAGE_PATH) for i in range(3): await omni.kit.app.get_app().next_update_async()
2,054
Python
32.688524
83
0.685492
omniverse-code/kit/exts/omni.kit.mainwindow/omni/kit/mainwindow/tests/__init__.py
from .test_main_window import *
32
Python
15.499992
31
0.75
omniverse-code/kit/exts/omni.kit.window.stats/omni/kit/window/stats/stats_window.py
import carb import sys import os import omni.ext import omni.ui import omni.kit.ui import omni.kit.app import omni.stats import carb.settings WINDOW_NAME = "Statistics" class Extension(omni.ext.IExt): """Statistics view extension""" class ComboBoxItem(omni.ui.AbstractItem): def __init__(self, text): super().__init__() self.model = omni.ui.SimpleStringModel(text) class ComboBoxModel(omni.ui.AbstractItemModel): def __init__(self): super().__init__() self._current_index = omni.ui.SimpleIntModel() self._current_index.add_value_changed_fn(self._changed_model) self._items = [] def _changed_model(self, model): # update stats at the end of the frame instead self._item_changed(None) def get_item_children(self, item): return self._items def get_item_value_model(self, item, column_id): if item is None: return self._current_index return item.model def _update_scopes(self, stat_iface): scopes = stat_iface.get_scopes() scope_count = len(scopes) item_count = len(self._items) if item_count != scope_count: selected_scope = "" if item_count != 0: selected_scope = self._current_index self._items.clear() for i in range(scope_count): scope = scopes[i] self._items.append(Extension.ComboBoxItem(scope["name"])) # verify if a scope is already selected if selected_scope == scope["name"]: self._current_index.as_int = i # A default selection if it is not already picked if not selected_scope: self._current_index.as_int = 0 # update stats if scope_count != 0: selected_scope_node = scopes[self._current_index.as_int] self._item_changed(None) return selected_scope_node return None def __init__(self): self._window = None self._app = None self._stats_mode = None self._scope_description = None self._stats = None self._stat_grid = None self._scope_combo_model = None self._stats_names = None self._stats_values = None self._stats_desc = None self._show_names = False # Don't show names by default, just descriptions super().__init__() def get_name(self): return WINDOW_NAME def _menu_callback(self, menu, value): self._window.visible = value # update menu state if self._menu: omni.kit.ui.get_editor_menu().set_value(f"Window/{WINDOW_NAME}", value) def on_startup(self): self._app = omni.kit.app.get_app() self._stats = omni.stats.get_stats_interface() menu_path = f"Window/{WINDOW_NAME}" self._window = omni.ui.Window( WINDOW_NAME, width=400, height=600, padding_x=10, visible=False, dockPreference=omni.ui.DockPreference.RIGHT_TOP, ) self._window.deferred_dock_in("Details", omni.ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE) with self._window.frame: with omni.ui.VStack(height=0, spacing=8): with omni.ui.HStack(): omni.ui.Label("Scope to display:") self._scope_combo_model = Extension.ComboBoxModel() self._scope_combo = omni.ui.ComboBox(self._scope_combo_model) with omni.ui.HStack(): omni.ui.Label("Scope description:") self._scope_description = omni.ui.Label("", word_wrap=True) omni.ui.Line() # green color for header style_header = {"color": 0xFF00B976} with omni.ui.HStack(style=style_header): if self._show_names: omni.ui.Label("Name", alignment=omni.ui.Alignment.LEFT) omni.ui.Label("Description", alignment=omni.ui.Alignment.LEFT) omni.ui.Label("Amount", alignment=omni.ui.Alignment.RIGHT) omni.ui.Line() # For performance, draw with two labels (per-frame update) with omni.ui.HStack(style=style_header): if self._show_names: self._stats_names = omni.ui.Label("", alignment=omni.ui.Alignment.LEFT) self._stats_desc = omni.ui.Label("", alignment=omni.ui.Alignment.LEFT) self._stats_values = omni.ui.Label("", alignment=omni.ui.Alignment.RIGHT) try: editor_menu = omni.kit.ui.get_editor_menu() self._menu = editor_menu.add_item(menu_path, self._menu_callback, toggle=True) editor_menu.set_priority(menu_path, 15) except: pass self._sub_event = self._app.get_update_event_stream().create_subscription_to_pop( self._on_update, name="omni.stats frame statistics" ) self._window.set_visibility_changed_fn(self._visiblity_changed_fn) def on_shutdown(self): self._menu = None self._window = None self._sub_event = None def _visiblity_changed_fn(self, visible): # update menu state if self._menu: omni.kit.ui.get_editor_menu().set_value(f"Window/{WINDOW_NAME}", visible) carb.settings.get_settings().set("/profiler/enableDeviceUtilizationQuery", visible) def _update_stats(self, scope_node): stat_nodes = self._stats.get_stats(scope_node["scopeId"]) stats_names = "" stats_values = "" stats_descs = "" # Sort nodes in descending order based on the alphabet stat_nodes = sorted(stat_nodes, key=lambda node: node["description"].lower(), reverse=False) for node in stat_nodes: if self._show_names: stats_names += node["name"] + "\n" stats_descs += node["description"] + "\n" if node["type"] == 0: stats_values += "{:,}".format(node["value"]) + "\n" elif node["type"] == 1: stats_values += "{:.3f}".format(node["value"]) + "\n" if self._show_names: self._stats_names.text = stats_names self._stats_values.text = stats_values self._stats_desc.text = stats_descs def _on_update(self, evt): if not self._window.visible: return scope_node = self._scope_combo_model._update_scopes(self._stats) if scope_node is not None: self._scope_description.text = scope_node["description"] self._update_stats(scope_node)
6,944
Python
37.15934
100
0.548819
omniverse-code/kit/exts/omni.kit.window.stats/omni/kit/window/stats/__init__.py
from .stats_window import *
28
Python
13.499993
27
0.75
omniverse-code/kit/exts/omni.kit.window.stats/omni/kit/window/stats/tests/__init__.py
from .test_stats import *
26
Python
12.499994
25
0.730769
omniverse-code/kit/exts/omni.kit.window.stats/omni/kit/window/stats/tests/test_stats.py
import asyncio import carb import unittest import carb import omni.kit.test import omni.usd import omni.ui as ui from omni.kit import ui_test class TestStats(omni.kit.test.AsyncTestCase): async def setUp(self): pass async def tearDown(self): pass async def test_stats_window(self): stats_window = ui_test.find("Statistics") stats_window.widget.visible = True await stats_window.focus() line_count = [0, 0, 0] for index in range(0, 3): # can't use widget.click as open combobox has no readable size and clicks goto stage window stats_window.find("**/ComboBox[*]").model.get_item_value_model(None, 0).set_value(index) await ui_test.human_delay(10) for widget in stats_window.find_all("**/Label[*]"): line_count[index] += len(widget.widget.text.split('\n')) self.assertNotEqual(line_count[0], 0) self.assertNotEqual(line_count[1], 0) self.assertNotEqual(line_count[2], 0)
1,031
Python
29.35294
103
0.634336
omniverse-code/kit/exts/omni.kit.manipulator.prim/omni/kit/manipulator/prim/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. # from __future__ import annotations import asyncio import math import traceback from enum import Enum, Flag, IntEnum, auto from typing import Dict, List, Sequence, Set, Tuple, Union import concurrent.futures import carb import carb.dictionary import carb.events import carb.profiler import carb.settings import omni.kit.app from omni.kit.async_engine import run_coroutine import omni.kit.commands import omni.kit.undo import omni.timeline from omni.kit.manipulator.tool.snap import SnapProviderManager from omni.kit.manipulator.tool.snap import settings_constants as snap_c from omni.kit.manipulator.transform import AbstractTransformManipulatorModel, Operation from omni.kit.manipulator.transform.gestures import ( RotateChangedGesture, RotateDragGesturePayload, ScaleChangedGesture, ScaleDragGesturePayload, TransformDragGesturePayload, TranslateChangedGesture, TranslateDragGesturePayload, ) from omni.kit.manipulator.transform.settings_constants import c from omni.kit.manipulator.transform.settings_listener import OpSettingsListener, SnapSettingsListener from omni.ui import scene as sc from pxr import Gf, Sdf, Tf, Usd, UsdGeom, UsdUtils from .settings_constants import Constants as prim_c from .utils import * # Settings needed for zero-gravity TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_ENABLED = "/app/transform/gizmoCustomManipulatorEnabled" TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_PRIMS = "/app/transform/gizmoCustomManipulatorPrims" TRANSFORM_GIZMO_IS_USING = "/app/transform/gizmoIsUsing" TRANSFORM_GIZMO_TRANSLATE_DELTA_XYZ = "/app/transform/gizmoTranslateDeltaXYZ" TRANSFORM_GIZMO_PIVOT_WORLD_POSITION = "/app/transform/tempPivotWorldPosition" TRANSFORM_GIZMO_ROTATE_DELTA_XYZW = "/app/transform/gizmoRotateDeltaXYZW" TRANSFORM_GIZMO_SCALE_DELTA_XYZ = "/app/transform/gizmoScaleDeltaXYZ" TRANSLATE_DELAY_FRAME_SETTING = "/exts/omni.kit.manipulator.prim/visual/delayFrame" class OpFlag(Flag): TRANSLATE = auto() ROTATE = auto() SCALE = auto() class Placement(Enum): LAST_PRIM_PIVOT = auto() SELECTION_CENTER = auto() BBOX_CENTER = auto() REF_PRIM = auto() BBOX_BASE = auto() class ManipulationMode(IntEnum): PIVOT = 0 # transform around manipulator pivot UNIFORM = 1 # set same world transform from manipulator to all prims equally INDIVIDUAL = 2 # 2: (TODO) transform around each prim's own pivot respectively class Viewport1WindowState: def __init__(self): self._focused_windows = None focused_windows = [] try: # For some reason is_focused may return False, when a Window is definitely in fact is the focused window! # And there's no good solution to this when multiple Viewport-1 instances are open; so we just have to # operate on all Viewports for a given usd_context. import omni.kit.viewport_legacy as vp vpi = vp.acquire_viewport_interface() for instance in vpi.get_instance_list(): window = vpi.get_viewport_window(instance) if not window: continue focused_windows.append(window) if focused_windows: self._focused_windows = focused_windows for window in self._focused_windows: # Disable the selection_rect, but enable_picking for snapping window.disable_selection_rect(True) # Schedule a picking request so if snap needs it later, it may arrive by the on_change event window.request_picking() except Exception: pass def get_picked_world_pos(self): if self._focused_windows: # Try to reduce to the focused window now after, we've had some mouse-move input focused_windows = [window for window in self._focused_windows if window.is_focused()] if focused_windows: self._focused_windows = focused_windows for window in self._focused_windows: window.disable_selection_rect(True) # request picking FOR NEXT FRAME window.request_picking() # get PREVIOUSLY picked pos, it may be None the first frame but that's fine return window.get_picked_world_pos() return None def __del__(self): self.destroy() def destroy(self): self._focused_windows = None def get_usd_context_name(self): if self._focused_windows: return self._focused_windows[0].get_usd_context_name() else: return "" class PrimTransformChangedGestureBase: def __init__(self, usd_context_name: str = "", viewport_api=None): self._settings = carb.settings.get_settings() self._usd_context_name = usd_context_name self._usd_context = omni.usd.get_context(self._usd_context_name) self._viewport_api = viewport_api # VP2 self._vp1_window_state = None self._stage_id = None def on_began(self, payload_type=TransformDragGesturePayload): self._viewport_on_began() if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, payload_type): return model = self.sender.model if not model: return item = self.gesture_payload.changing_item self._current_editing_op = item.operation # NOTE! self._begin_xform has no scale. To get the full matrix, do self._begin_scale_mtx * self._begin_xform self._begin_xform = Gf.Matrix4d(*model.get_as_floats(model.get_item("no_scale_transform_manipulator"))) manip_scale = Gf.Vec3d(*model.get_as_floats(model.get_item("scale_manipulator"))) self._begin_scale_mtx = Gf.Matrix4d(1.0) self._begin_scale_mtx.SetScale(manip_scale) model.set_floats(model.get_item("viewport_fps"), [0.0]) model.on_began(self.gesture_payload) def on_changed(self, payload_type=TransformDragGesturePayload): if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, payload_type): return model = self.sender.model if not model: return if self._viewport_api: fps = self._viewport_api.frame_info.get("fps") model.set_floats(model.get_item("viewport_fps"), [fps]) model.on_changed(self.gesture_payload) def on_ended(self, payload_type=TransformDragGesturePayload): self._viewport_on_ended() if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, payload_type): return model = self.sender.model if not model: return item = self.gesture_payload.changing_item if item.operation != self._current_editing_op: return model.set_floats(model.get_item("viewport_fps"), [0.0]) model.on_ended(self.gesture_payload) self._current_editing_op = None def on_canceled(self, payload_type=TransformDragGesturePayload): self._viewport_on_ended() if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, payload_type): return model = self.sender.model if not model: return item = self.gesture_payload.changing_item if item.operation != self._current_editing_op: return model.on_canceled(self.gesture_payload) self._current_editing_op = None def _publish_delta(self, operation: Operation, delta: List[float]): # pragma: no cover if operation == Operation.TRANSLATE: self._settings.set_float_array(TRANSFORM_GIZMO_TRANSLATE_DELTA_XYZ, delta) elif operation == Operation.ROTATE: self._settings.set_float_array(TRANSFORM_GIZMO_ROTATE_DELTA_XYZW, delta) elif operation == Operation.SCALE: self._settings.set_float_array(TRANSFORM_GIZMO_SCALE_DELTA_XYZ, delta) def __set_viewport_manipulating(self, value: int): # Signal that user-manipulation has started for this stage if self._stage_id is None: self._stage_id = UsdUtils.StageCache.Get().GetId(self._usd_context.get_stage()).ToLongInt() key = f"/app/viewport/{self._stage_id}/manipulating" cur_value = self._settings.get(key) or 0 self._settings.set(key, cur_value + value) def _viewport_on_began(self): self._viewport_on_ended() if self._viewport_api is None: self._vp1_window_state = Viewport1WindowState() self.__set_viewport_manipulating(1) def _viewport_on_ended(self): if self._vp1_window_state: self._vp1_window_state.destroy() self._vp1_window_state = None if self._stage_id: self.__set_viewport_manipulating(-1) self._stage_id = None class PrimTranslateChangedGesture(TranslateChangedGesture, PrimTransformChangedGestureBase): def __init__(self, snap_manager: SnapProviderManager, **kwargs): PrimTransformChangedGestureBase.__init__(self, **kwargs) TranslateChangedGesture.__init__(self) self._accumulated_translate = Gf.Vec3d(0) self._snap_manager = snap_manager def on_began(self): PrimTransformChangedGestureBase.on_began(self, TranslateDragGesturePayload) self._accumulated_translate = Gf.Vec3d(0) model = self._get_model(TranslateDragGesturePayload) if model and self._can_snap(model): # TODO No need for gesture=self when VP1 has viewport_api self._snap_manager.on_began(model.consolidated_xformable_prim_data_curr.keys(), gesture=self) if model: model.set_floats(model.get_item("translate_delta"), [0, 0, 0]) def on_ended(self): PrimTransformChangedGestureBase.on_ended(self, TranslateDragGesturePayload) model = self._get_model(TranslateDragGesturePayload) if model and self._can_snap(model): self._snap_manager.on_ended() def on_canceled(self): PrimTransformChangedGestureBase.on_canceled(self, TranslateDragGesturePayload) model = self._get_model(TranslateDragGesturePayload) if model and self._can_snap(model): self._snap_manager.on_ended() @carb.profiler.profile def on_changed(self): PrimTransformChangedGestureBase.on_changed(self, TranslateDragGesturePayload) model = self._get_model(TranslateDragGesturePayload) if not model: return manip_xform = Gf.Matrix4d(*model.get_as_floats(model.get_item("no_scale_transform_manipulator"))) new_manip_xform = Gf.Matrix4d(manip_xform) rotation_mtx = manip_xform.ExtractRotationMatrix() rotation_mtx.Orthonormalize() translate_delta = self.gesture_payload.moved_delta translate = self.gesture_payload.moved axis = self.gesture_payload.axis # slow Gf.Vec3d(*translate_delta) translate_delta = Gf.Vec3d(translate_delta[0], translate_delta[1], translate_delta[2]) if model.op_settings_listener.translation_mode == c.TRANSFORM_MODE_LOCAL: translate_delta = translate_delta * rotation_mtx self._accumulated_translate += translate_delta def apply_position(snap_world_pos=None, snap_world_orient=None, keep_spacing: bool = True): nonlocal new_manip_xform if self.state != sc.GestureState.CHANGED: return # only set translate if no snap or only snap to position item_name = "translate" if snap_world_pos and ( math.isfinite(snap_world_pos[0]) and math.isfinite(snap_world_pos[1]) and math.isfinite(snap_world_pos[2]) ): if snap_world_orient is None: new_manip_xform.SetTranslateOnly(Gf.Vec3d(snap_world_pos[0], snap_world_pos[1], snap_world_pos[2])) new_manip_xform = self._begin_scale_mtx * new_manip_xform else: new_manip_xform.SetTranslateOnly(Gf.Vec3d(snap_world_pos[0], snap_world_pos[1], snap_world_pos[2])) new_manip_xform.SetRotateOnly(snap_world_orient) # set transform if snap both position and orientation item_name = "no_scale_transform_manipulator" else: new_manip_xform.SetTranslateOnly(self._begin_xform.ExtractTranslation() + self._accumulated_translate) new_manip_xform = self._begin_scale_mtx * new_manip_xform model.set_floats(model.get_item("translate_delta"), translate_delta) if model.custom_manipulator_enabled: self._publish_delta(Operation.TRANSLATE, translate_delta) if keep_spacing is False: mode_item = model.get_item("manipulator_mode") prev_mode = model.get_as_ints(mode_item) model.set_ints(mode_item, [int(ManipulationMode.UNIFORM)]) model.set_floats(model.get_item(item_name), flatten(new_manip_xform)) if keep_spacing is False: model.set_ints(mode_item, prev_mode) # only do snap to surface if drag the center point if ( model.snap_settings_listener.snap_enabled and model.snap_settings_listener.snap_provider and axis == [1, 1, 1] ): ndc_location = None if self._viewport_api: # No mouse location is available, have to convert back to NDC space ndc_location = self.sender.transform_space( sc.Space.WORLD, sc.Space.NDC, self.gesture_payload.ray_closest_point ) if self._snap_manager.get_snap_pos( new_manip_xform, ndc_location, self.sender.scene_view, lambda **kwargs: apply_position( kwargs.get("position", None), kwargs.get("orient", None), kwargs.get("keep_spacing", True) ), ): return apply_position() def _get_model(self, payload_type) -> PrimTransformModel: if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, payload_type): return None return self.sender.model def _can_snap(self, model: PrimTransformModel): axis = self.gesture_payload.axis if ( model.snap_settings_listener.snap_enabled and model.snap_settings_listener.snap_provider and axis == [1, 1, 1] ): return True return False class PrimRotateChangedGesture(RotateChangedGesture, PrimTransformChangedGestureBase): def __init__(self, **kwargs): PrimTransformChangedGestureBase.__init__(self, **kwargs) RotateChangedGesture.__init__(self) def on_began(self): PrimTransformChangedGestureBase.on_began(self, RotateDragGesturePayload) model = self.sender.model if model: model.set_floats(model.get_item("rotate_delta"), [0, 0, 0, 0]) def on_ended(self): PrimTransformChangedGestureBase.on_ended(self, RotateDragGesturePayload) def on_canceled(self): PrimTransformChangedGestureBase.on_canceled(self, RotateDragGesturePayload) @carb.profiler.profile def on_changed(self): PrimTransformChangedGestureBase.on_changed(self, RotateDragGesturePayload) if ( not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, RotateDragGesturePayload) ): return model = self.sender.model if not model: return axis = self.gesture_payload.axis angle = self.gesture_payload.angle angle_delta = self.gesture_payload.angle_delta screen_space = self.gesture_payload.screen_space free_rotation = self.gesture_payload.free_rotation axis = Gf.Vec3d(*axis[:3]) rotate = Gf.Rotation(axis, angle) delta_axis = Gf.Vec4d(*axis, 0.0) rot_matrix = Gf.Matrix4d(1) rot_matrix.SetRotate(rotate) if free_rotation: rotate = Gf.Rotation(axis, angle_delta) rot_matrix = Gf.Matrix4d(1) rot_matrix.SetRotate(rotate) xform = Gf.Matrix4d(*model.get_as_floats(model.get_item("no_scale_transform_manipulator"))) full_xform = self._begin_scale_mtx * xform translate = full_xform.ExtractTranslation() no_translate_mtx = Gf.Matrix4d(full_xform) no_translate_mtx.SetTranslateOnly(Gf.Vec3d(0)) no_translate_mtx = no_translate_mtx * rot_matrix new_transform_matrix = no_translate_mtx.SetTranslateOnly(translate) delta_axis = no_translate_mtx * delta_axis elif model.op_settings_listener.rotation_mode == c.TRANSFORM_MODE_GLOBAL or screen_space: begin_full_xform = self._begin_scale_mtx * self._begin_xform translate = begin_full_xform.ExtractTranslation() no_translate_mtx = Gf.Matrix4d(begin_full_xform) no_translate_mtx.SetTranslateOnly(Gf.Vec3d(0)) no_translate_mtx = no_translate_mtx * rot_matrix new_transform_matrix = no_translate_mtx.SetTranslateOnly(translate) delta_axis = no_translate_mtx * delta_axis else: self._begin_xform = Gf.Matrix4d(*model.get_as_floats(model.get_item("no_scale_transform_manipulator"))) new_transform_matrix = self._begin_scale_mtx * rot_matrix * self._begin_xform delta_axis.Normalize() delta_rotate = Gf.Rotation(delta_axis[:3], angle_delta) quat = delta_rotate.GetQuaternion() real = quat.GetReal() imaginary = quat.GetImaginary() rd = [imaginary[0], imaginary[1], imaginary[2], real] model.set_floats(model.get_item("rotate_delta"), rd) if model.custom_manipulator_enabled: self._publish_delta(Operation.ROTATE, rd) model.set_floats(model.get_item("rotate"), flatten(new_transform_matrix)) class PrimScaleChangedGesture(ScaleChangedGesture, PrimTransformChangedGestureBase): def __init__(self, **kwargs): PrimTransformChangedGestureBase.__init__(self, **kwargs) ScaleChangedGesture.__init__(self) def on_began(self): PrimTransformChangedGestureBase.on_began(self, ScaleDragGesturePayload) model = self.sender.model if model: model.set_floats(model.get_item("scale_delta"), [0, 0, 0]) def on_ended(self): PrimTransformChangedGestureBase.on_ended(self, ScaleDragGesturePayload) def on_canceled(self): PrimTransformChangedGestureBase.on_canceled(self, ScaleDragGesturePayload) @carb.profiler.profile def on_changed(self): PrimTransformChangedGestureBase.on_changed(self, ScaleDragGesturePayload) if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, ScaleDragGesturePayload): return model = self.sender.model if not model: return axis = self.gesture_payload.axis scale = self.gesture_payload.scale axis = Gf.Vec3d(*axis[:3]) scale_delta = scale * axis scale_vec = Gf.Vec3d() for i in range(3): scale_vec[i] = scale_delta[i] if scale_delta[i] else 1 scale_matrix = Gf.Matrix4d(1.0) scale_matrix.SetScale(scale_vec) scale_matrix *= self._begin_scale_mtx new_transform_matrix = scale_matrix * self._begin_xform s = Gf.Vec3d(*model.get_as_floats(model.get_item("scale_manipulator"))) sd = [s_n / s_o for s_n, s_o in zip([scale_matrix[0][0], scale_matrix[1][1], scale_matrix[2][2]], s)] model.set_floats(model.get_item("scale_delta"), sd) if model.custom_manipulator_enabled: self._publish_delta(Operation.SCALE, sd) model.set_floats(model.get_item("scale"), flatten(new_transform_matrix)) class PrimTransformModel(AbstractTransformManipulatorModel): def __init__(self, usd_context_name: str = "", viewport_api=None): super().__init__() self._transform = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] # visual transform of manipulator self._no_scale_transform_manipulator = Gf.Matrix4d(1.0) # transform of manipulator without scale self._scale_manipulator = Gf.Vec3d(1.0) # scale of manipulator self._settings = carb.settings.get_settings() self._dict = carb.dictionary.get_dictionary() self._timeline = omni.timeline.get_timeline_interface() self._app = omni.kit.app.get_app() self._usd_context_name = usd_context_name self._usd_context = omni.usd.get_context(usd_context_name) self._stage: Usd.Stage = None self._enabled_hosting_widget_count: int = 0 self._stage_listener = None self._xformable_prim_paths: List[Sdf.Path] = [] self._xformable_prim_paths_sorted: List[Sdf.Path] = [] self._xformable_prim_paths_set: Set[Sdf.Path] = set() self._xformable_prim_paths_prefix_set: Set[Sdf.Path] = set() self._consolidated_xformable_prim_paths: List[Sdf.Path] = [] self._pivot_prim: Usd.Prim = None self._update_prim_xform_from_prim_task_or_future: Union[asyncio.Task, concurrent.futures.Future, None] = None self._current_editing_op: Operation = None self._ignore_xform_data_change = False self._timeline_sub = None self._pending_changed_paths: Dict[Sdf.Path, bool] = {} self._pending_changed_paths_for_xform_data: Set[Sdf.Path] = set() self._mode = ManipulationMode.PIVOT self._viewport_fps: float = 0.0 # needed this as heuristic for delaying the visual update of manipulator to match rendering self._viewport_api = viewport_api self._delay_dirty_tasks_or_futures: Dict[int, Union[asyncio.Task, concurrent.futures.Future]] = {} self._no_scale_transform_manipulator_item = sc.AbstractManipulatorItem() self._items["no_scale_transform_manipulator"] = self._no_scale_transform_manipulator_item self._scale_manipulator_item = sc.AbstractManipulatorItem() self._items["scale_manipulator"] = self._scale_manipulator_item self._transform_manipulator_item = sc.AbstractManipulatorItem() self._items["transform_manipulator"] = self._transform_manipulator_item self._manipulator_mode_item = sc.AbstractManipulatorItem() self._items["manipulator_mode"] = self._manipulator_mode_item self._viewport_fps_item = sc.AbstractManipulatorItem() self._items["viewport_fps"] = self._viewport_fps_item self._set_default_settings() # subscribe to snap events self._snap_settings_listener = SnapSettingsListener( enabled_setting_path=None, move_x_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH, move_y_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH, move_z_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH, rotate_setting_path=snap_c.SNAP_ROTATE_SETTING_PATH, scale_setting_path=snap_c.SNAP_SCALE_SETTING_PATH, provider_setting_path=snap_c.SNAP_PROVIDER_NAME_SETTING_PATH, ) # subscribe to operation/mode events self._op_settings_listener = OpSettingsListener() self._op_settings_listener_sub = self._op_settings_listener.subscribe_listener(self._on_op_listener_changed) self._placement_sub = self._settings.subscribe_to_node_change_events( prim_c.MANIPULATOR_PLACEMENT_SETTING, self._on_placement_setting_changed ) self._placement = Placement.LAST_PRIM_PIVOT placement = self._settings.get(prim_c.MANIPULATOR_PLACEMENT_SETTING) self._update_placement(placement) # cache unique setting path for selection pivot position # vp1 default self._selection_pivot_position_path = TRANSFORM_GIZMO_PIVOT_WORLD_POSITION + "/Viewport" # vp2 if self._viewport_api: self._selection_pivot_position_path = ( TRANSFORM_GIZMO_PIVOT_WORLD_POSITION + "/" + self._viewport_api.id.split("/")[0] ) # update setting with pivot placement position on init self._update_temp_pivot_world_position() def subscribe_to_value_and_get_current(setting_val_name: str, setting_path: str): sub = self._settings.subscribe_to_node_change_events( setting_path, lambda item, type: setattr(self, setting_val_name, self._dict.get(item)) ) setattr(self, setting_val_name, self._settings.get(setting_path)) return sub # subscribe to zero-gravity settings self._custom_manipulator_enabled_sub = subscribe_to_value_and_get_current( "_custom_manipulator_enabled", TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_ENABLED ) # subscribe to USD related events self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop( self._on_stage_event, name="PrimTransformModel stage event" ) if self._usd_context.get_stage_state() == omni.usd.StageState.OPENED: self._on_stage_opened() self._warning_notification = None self._selected_instance_proxy_paths = set() def __del__(self): self.destroy() def destroy(self): if self._warning_notification: self._warning_notification.dismiss() self._warning_notification = None self._op_settings_listener_sub = None if self._op_settings_listener: self._op_settings_listener.destroy() self._op_settings_listener = None self._stage_event_sub = None if self._stage_listener: self._stage_listener.Revoke() self._stage_listener = None if self._usd_context.get_stage_state() == omni.usd.StageState.OPENED: self._on_stage_closing() self._timeline_sub = None if self._snap_settings_listener: self._snap_settings_listener.destroy() self._snap_settings_listener = None if self._custom_manipulator_enabled_sub: self._settings.unsubscribe_to_change_events(self._custom_manipulator_enabled_sub) self._custom_manipulator_enabled_sub = None if self._placement_sub: self._settings.unsubscribe_to_change_events(self._placement_sub) self._placement_sub = None for task_or_future in self._delay_dirty_tasks_or_futures.values(): task_or_future.cancel() self._delay_dirty_tasks_or_futures.clear() def set_pivot_prim_path(self, path: Sdf.Path) -> bool: if path not in self._xformable_prim_paths_set: carb.log_warn(f"Cannot set pivot prim path to {path}") return False if not self._pivot_prim or self._pivot_prim.GetPath() != path: self._pivot_prim = self._stage.GetPrimAtPath(path) else: return False if self._update_transform_from_prims(): self._item_changed(self._transform_item) return True def get_pivot_prim_path(self) -> Sdf.Path: if self._pivot_prim: return self._pivot_prim.GetPath() return None def on_began(self, payload): item = payload.changing_item self._current_editing_op = item.operation # All selected xformable prims' transforms. Store this for when `Keep Spacing` option is off during snapping, # because it can modify parent's and child're transform differently. self._all_xformable_prim_data_prev: Dict[Sdf.Path, Tuple[Gf.Vec3d, Gf.Vec3d, Gf.Vec3i, Gf.Vec3d, Gf.Vec3d]] = {} # consolidated xformable prims' transforms. If parent is in the dict, child will be excluded. self._consolidated_xformable_prim_data_prev: Dict[Sdf.Path, Tuple[Gf.Vec3d, Gf.Vec3d, Gf.Vec3i, Gf.Vec3d]] = {} for path in self._xformable_prim_paths: prim = self.stage.GetPrimAtPath(path) xform_tuple = omni.usd.get_local_transform_SRT(prim, self._get_current_time_code()) pivot = get_local_transform_pivot_inv(prim, self._get_current_time_code()).GetInverse() self._all_xformable_prim_data_prev[path] = xform_tuple + (pivot,) if path in self._consolidated_xformable_prim_paths: self._consolidated_xformable_prim_data_prev[path] = xform_tuple + (pivot,) self.all_xformable_prim_data_curr = self._all_xformable_prim_data_prev.copy() self.consolidated_xformable_prim_data_curr = self._consolidated_xformable_prim_data_prev.copy() self._pending_changed_paths_for_xform_data.clear() if self.custom_manipulator_enabled: self._settings.set(TRANSFORM_GIZMO_IS_USING, True) def on_changed(self, payload): # Always re-fetch the changed transform on_changed. Although it might not be manipulated by manipulator, # prim's transform can be modified by other runtime (e.g. omnigraph), and we always want the latest. self._update_xform_data_from_dirty_paths() def on_ended(self, payload): # Always re-fetch the changed transform on_changed. Although it might not be manipulated by manipulator, # prim's transform can be modified by other runtime (e.g. omnigraph), and we always want the latest. self._update_xform_data_from_dirty_paths() carb.profiler.begin(1, "PrimTransformChangedGestureBase.TransformPrimSRT.all") paths = [] new_translations = [] new_rotation_eulers = [] new_rotation_orders = [] new_scales = [] old_translations = [] old_rotation_eulers = [] old_rotation_orders = [] old_scales = [] for path, (s, r, ro, t, pivot) in self.all_xformable_prim_data_curr.items(): # Data didn't change if self._all_xformable_prim_data_prev[path] == self.all_xformable_prim_data_curr[path]: # carb.log_info(f"Skip {path}") continue (old_s, old_r, old_ro, old_t, old_pivot) = self._all_xformable_prim_data_prev[path] paths.append(path.pathString) new_translations += [t[0], t[1], t[2]] new_rotation_eulers += [r[0], r[1], r[2]] new_rotation_orders += [ro[0], ro[1], ro[2]] new_scales += [s[0], s[1], s[2]] old_translations += [old_t[0], old_t[1], old_t[2]] old_rotation_eulers += [old_r[0], old_r[1], old_r[2]] old_rotation_orders += [old_ro[0], old_ro[1], old_ro[2]] old_scales += [old_s[0], old_s[1], old_s[2]] self._ignore_xform_data_change = True self._on_ended_transform( paths, new_translations, new_rotation_eulers, new_rotation_orders, new_scales, old_translations, old_rotation_eulers, old_rotation_orders, old_scales, ) self._ignore_xform_data_change = False carb.profiler.end(1) if self.custom_manipulator_enabled: self._settings.set(TRANSFORM_GIZMO_IS_USING, False) # if the manipulator was locked to orientation or translation, # refresh it on_ended so the transform is up to date mode = self._get_transform_mode_for_current_op() if self._should_keep_manipulator_orientation_unchanged( mode ) or self._should_keep_manipulator_translation_unchanged(mode): # set editing op to None AFTER _should_keep_manipulator_*_unchanged but # BEFORE self._update_transform_from_prims self._current_editing_op = None if self._update_transform_from_prims(): self._item_changed(self._transform_item) self._current_editing_op = None def _on_ended_transform( self, paths: List[str], new_translations: List[float], new_rotation_eulers: List[float], new_rotation_orders: List[int], new_scales: List[float], old_translations: List[float], old_rotation_eulers: List[float], old_rotation_orders: List[int], old_scales: List[float], ): """Function ran by on_ended(). Can be overridden to change the behavior. Do not remove this function: can be used outside of this code""" self._alert_if_selection_has_instance_proxies() omni.kit.commands.execute( "TransformMultiPrimsSRTCpp", count=len(paths), paths=paths, new_translations=new_translations, new_rotation_eulers=new_rotation_eulers, new_rotation_orders=new_rotation_orders, new_scales=new_scales, old_translations=old_translations, old_rotation_eulers=old_rotation_eulers, old_rotation_orders=old_rotation_orders, old_scales=old_scales, usd_context_name=self._usd_context_name, time_code=self._get_current_time_code().GetValue(), ) def on_canceled(self, payload): if self.custom_manipulator_enabled: self._settings.set(TRANSFORM_GIZMO_IS_USING, False) self._current_editing_op = None def widget_enabled(self): self._enabled_hosting_widget_count += 1 # just changed from no active widget to 1 active widget if self._enabled_hosting_widget_count == 1: # listener only needs to be activated if manipulator is visible if self._consolidated_xformable_prim_paths: assert self._stage_listener is None self._stage_listener = Tf.Notice.Register( Usd.Notice.ObjectsChanged, self._on_objects_changed, self._stage ) carb.log_info("Tf.Notice.Register in PrimTransformModel") def _clear_temp_pivot_position_setting(self): if self._settings.get(self._selection_pivot_position_path): self._settings.destroy_item(self._selection_pivot_position_path) def widget_disabled(self): self._enabled_hosting_widget_count -= 1 self._clear_temp_pivot_position_setting() assert self._enabled_hosting_widget_count >= 0 if self._enabled_hosting_widget_count < 0: carb.log_error(f"manipulator enabled widget tracker out of sync: {self._enabled_hosting_widget_count}") self._enabled_hosting_widget_count = 0 # If no hosting manipulator is active, revoke the listener since there's no need to sync Transform if self._enabled_hosting_widget_count == 0: if self._stage_listener: self._stage_listener.Revoke() self._stage_listener = None carb.log_info("Tf.Notice.Revoke in PrimTransformModel") for task_or_future in self._delay_dirty_tasks_or_futures.values(): task_or_future.cancel() self._delay_dirty_tasks_or_futures.clear() def set_floats(self, item: sc.AbstractManipulatorItem, value: Sequence[float]): if item == self._viewport_fps_item: self._viewport_fps = value[0] return flag = None if issubclass(type(item), AbstractTransformManipulatorModel.OperationItem): if ( item.operation == Operation.TRANSLATE_DELTA or item.operation == Operation.ROTATE_DELTA or item.operation == Operation.SCALE_DELTA ): return if item.operation == Operation.TRANSLATE: flag = OpFlag.TRANSLATE elif item.operation == Operation.ROTATE: flag = OpFlag.ROTATE elif item.operation == Operation.SCALE: flag = OpFlag.SCALE transform = Gf.Matrix4d(*value) elif item == self._transform_manipulator_item: flag = OpFlag.TRANSLATE | OpFlag.ROTATE | OpFlag.SCALE transform = Gf.Matrix4d(*value) elif item == self._no_scale_transform_manipulator_item: flag = OpFlag.TRANSLATE | OpFlag.ROTATE old_manipulator_scale_mtx = Gf.Matrix4d(1.0) old_manipulator_scale_mtx.SetScale(self._scale_manipulator) transform = old_manipulator_scale_mtx * Gf.Matrix4d(*value) if flag is not None: if self._mode == ManipulationMode.PIVOT: self._transform_selected_prims( transform, self._no_scale_transform_manipulator, self._scale_manipulator, flag ) elif self._mode == ManipulationMode.UNIFORM: self._transform_all_selected_prims_to_manipulator_pivot(transform, flag) else: carb.log_warn(f"Unsupported item {item}") def set_ints(self, item: sc.AbstractManipulatorItem, value: Sequence[int]): if item == self._manipulator_mode_item: try: self._mode = ManipulationMode(value[0]) except: carb.log_error(traceback.format_exc()) else: carb.log_warn(f"unsupported item {item}") return None def get_as_floats(self, item: sc.AbstractManipulatorItem): if item == self._transform_item: return self._transform elif item == self._no_scale_transform_manipulator_item: return flatten(self._no_scale_transform_manipulator) elif item == self._scale_manipulator_item: return [self._scale_manipulator[0], self._scale_manipulator[1], self._scale_manipulator[2]] elif item == self._transform_manipulator_item: scale_mtx = Gf.Matrix4d(1) scale_mtx.SetScale(self._scale_manipulator) return flatten(scale_mtx * self._no_scale_transform_manipulator) else: carb.log_warn(f"unsupported item {item}") return None def get_as_ints(self, item: sc.AbstractManipulatorItem): if item == self._manipulator_mode_item: return [int(self._mode)] else: carb.log_warn(f"unsupported item {item}") return None def get_operation(self) -> Operation: if self._op_settings_listener.selected_op == c.TRANSFORM_OP_MOVE: return Operation.TRANSLATE elif self._op_settings_listener.selected_op == c.TRANSFORM_OP_ROTATE: return Operation.ROTATE elif self._op_settings_listener.selected_op == c.TRANSFORM_OP_SCALE: return Operation.SCALE return Operation.NONE def get_snap(self, item: AbstractTransformManipulatorModel.OperationItem): if not self._snap_settings_listener.snap_enabled: return None if item.operation == Operation.TRANSLATE: if self._snap_settings_listener.snap_provider: return None return ( self._snap_settings_listener.snap_move_x, self._snap_settings_listener.snap_move_y, self._snap_settings_listener.snap_move_z, ) elif item.operation == Operation.ROTATE: return self._snap_settings_listener.snap_rotate elif item.operation == Operation.SCALE: return self._snap_settings_listener.snap_scale return None @property def stage(self): return self._stage @property def custom_manipulator_enabled(self): return self._custom_manipulator_enabled @property def snap_settings_listener(self): return self._snap_settings_listener @property def op_settings_listener(self): return self._op_settings_listener @property def usd_context(self) -> omni.usd.UsdContext: return self._usd_context @property def xformable_prim_paths(self) -> List[Sdf.Path]: return self._xformable_prim_paths @carb.profiler.profile def _update_xform_data_from_dirty_paths(self): for p in self._pending_changed_paths_for_xform_data: prim_path = p.GetPrimPath() if prim_path in self.all_xformable_prim_data_curr and self._path_may_affect_transform(p): prim = self.stage.GetPrimAtPath(prim_path) xform_tuple = omni.usd.get_local_transform_SRT(prim, self._get_current_time_code()) pivot = get_local_transform_pivot_inv(prim, self._get_current_time_code()).GetInverse() self.all_xformable_prim_data_curr[prim_path] = xform_tuple + (pivot,) if prim_path in self._consolidated_xformable_prim_paths: self.consolidated_xformable_prim_data_curr[prim_path] = xform_tuple + (pivot,) self._pending_changed_paths_for_xform_data.clear() @carb.profiler.profile def _transform_selected_prims( self, new_manipulator_transform: Gf.Matrix4d, old_manipulator_transform_no_scale: Gf.Matrix4d, old_manipulator_scale: Gf.Vec3d, dirty_ops: OpFlag, ): carb.profiler.begin(1, "omni.kit.manipulator.prim.model._transform_selected_prims.prepare_data") paths = [] new_translations = [] new_rotation_eulers = [] new_rotation_orders = [] new_scales = [] self._xform_cache.Clear() # any op may trigger a translation change if multi-manipulating should_update_translate = dirty_ops & OpFlag.TRANSLATE or len( self._xformable_prim_paths) > 1 or self._placement != Placement.LAST_PRIM_PIVOT should_update_rotate = dirty_ops & OpFlag.ROTATE should_update_scale = dirty_ops & OpFlag.SCALE old_manipulator_scale_mtx = Gf.Matrix4d(1.0) old_manipulator_scale_mtx.SetScale(old_manipulator_scale) old_manipulator_transform_inv = (old_manipulator_scale_mtx * old_manipulator_transform_no_scale).GetInverse() for path in self._consolidated_xformable_prim_paths: if self._custom_manipulator_enabled and self._should_skip_custom_manipulator_path(path.pathString): continue selected_prim = self._stage.GetPrimAtPath(path) # We check whether path is in consolidated_xformable_prim_data_curr because it may have not made it the dictionary if an error occured if not selected_prim or path not in self.consolidated_xformable_prim_data_curr: continue (s, r, ro, t, selected_pivot) = self.consolidated_xformable_prim_data_curr[path] selected_pivot_inv = selected_pivot.GetInverse() selected_local_to_world_mtx = self._xform_cache.GetLocalToWorldTransform(selected_prim) selected_parent_to_world_mtx = self._xform_cache.GetParentToWorldTransform(selected_prim) # Transform the prim from world space to pivot's space # Then apply the new pivotPrim-to-world-space transform matrix selected_local_to_world_pivot_mtx = ( selected_pivot * selected_local_to_world_mtx * old_manipulator_transform_inv * new_manipulator_transform ) world_to_parent_mtx = selected_parent_to_world_mtx.GetInverse() selected_local_mtx_new = selected_local_to_world_pivot_mtx * world_to_parent_mtx * selected_pivot_inv if should_update_translate: translation = selected_local_mtx_new.ExtractTranslation() if should_update_rotate: # Construct the new rotation from old scale and translation. # Don't use Factor because it won't be able to tell if scale is positive or negative and can result in flipped rotation old_s_mtx = Gf.Matrix4d(1.0) old_s_mtx.SetScale(Gf.Vec3d(s)) old_t_mtx = Gf.Matrix4d(1.0) old_t_mtx.SetTranslate(Gf.Vec3d(t)) rot_new = (old_s_mtx.GetInverse() * selected_local_mtx_new * old_t_mtx.GetInverse()).ExtractRotation() axes = [Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()] decomp_rot = rot_new.Decompose(axes[ro[2]], axes[ro[1]], axes[ro[0]]) index_order = Gf.Vec3i() for i in range(3): index_order[ro[i]] = 2 - i rotation = Gf.Vec3d(decomp_rot[index_order[0]], decomp_rot[index_order[1]], decomp_rot[index_order[2]]) rotation = find_best_euler_angles(Gf.Vec3d(r), rotation, ro) if should_update_scale: # Construct the new scale from old rotation and translation. # Don't use Factor because it won't be able to tell if scale is positive or negative and can result in flipped rotation old_rt_mtx = compose_transform_ops_to_matrix(t, r, ro, Gf.Vec3d(1)) new_s_mtx = selected_local_mtx_new * old_rt_mtx.GetInverse() scale = Gf.Vec3d(new_s_mtx[0][0], new_s_mtx[1][1], new_s_mtx[2][2]) translation = translation if should_update_translate else t rotation = rotation if should_update_rotate else r scale = scale if should_update_scale else s paths.append(path.pathString) new_translations += [translation[0], translation[1], translation[2]] new_rotation_eulers += [rotation[0], rotation[1], rotation[2]] new_rotation_orders += [ro[0], ro[1], ro[2]] new_scales += [scale[0], scale[1], scale[2]] xform_tuple = (scale, rotation, ro, translation, selected_pivot) self.consolidated_xformable_prim_data_curr[path] = xform_tuple self.all_xformable_prim_data_curr[path] = xform_tuple carb.profiler.end(1) self._ignore_xform_data_change = True self._do_transform_selected_prims(paths, new_translations, new_rotation_eulers, new_rotation_orders, new_scales) self._ignore_xform_data_change = False def _do_transform_selected_prims( self, paths: List[str], new_translations: List[float], new_rotation_eulers: List[float], new_rotation_orders: List[int], new_scales: List[float], ): """Function ran by _transform_selected_prims(). Can be overridden to change the behavior Do not remove this function: can be used outside of this code""" self._alert_if_selection_has_instance_proxies() omni.kit.commands.create( "TransformMultiPrimsSRTCpp", count=len(paths), no_undo=True, paths=paths, new_translations=new_translations, new_rotation_eulers=new_rotation_eulers, new_rotation_orders=new_rotation_orders, new_scales=new_scales, usd_context_name=self._usd_context_name, time_code=self._get_current_time_code().GetValue(), ).do() @carb.profiler.profile def _transform_all_selected_prims_to_manipulator_pivot( self, new_manipulator_transform: Gf.Matrix4d, dirty_ops: OpFlag, ): paths = [] new_translations = [] new_rotation_eulers = [] new_rotation_orders = [] new_scales = [] old_translations = [] old_rotation_eulers = [] old_rotation_orders = [] old_scales = [] self._xform_cache.Clear() # any op may trigger a translation change if multi-manipulating should_update_translate = dirty_ops & OpFlag.TRANSLATE or len(self._xformable_prim_paths) > 1 should_update_rotate = dirty_ops & OpFlag.ROTATE should_update_scale = dirty_ops & OpFlag.SCALE for path in self._xformable_prim_paths_sorted: if self._custom_manipulator_enabled and self._should_skip_custom_manipulator_path(path.pathString): continue selected_prim = self._stage.GetPrimAtPath(path) # We check whether path is in all_xformable_prim_data_curr because it may have not made it the dictionary if an error occured if not selected_prim or path not in self.all_xformable_prim_data_curr: continue (s, r, ro, t, selected_pivot) = self.all_xformable_prim_data_curr[path] selected_parent_to_world_mtx = self._xform_cache.GetParentToWorldTransform(selected_prim) world_to_parent_mtx = selected_parent_to_world_mtx.GetInverse() selected_local_mtx_new = new_manipulator_transform * world_to_parent_mtx * selected_pivot.GetInverse() if should_update_translate: translation = selected_local_mtx_new.ExtractTranslation() if should_update_rotate: # Construct the new rotation from old scale and translation. # Don't use Factor because it won't be able to tell if scale is positive or negative and can result in flipped rotation old_s_mtx = Gf.Matrix4d(1.0) old_s_mtx.SetScale(Gf.Vec3d(s)) old_t_mtx = Gf.Matrix4d(1.0) old_t_mtx.SetTranslate(Gf.Vec3d(t)) rot_new = (old_s_mtx.GetInverse() * selected_local_mtx_new * old_t_mtx.GetInverse()).ExtractRotation() axes = [Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()] decomp_rot = rot_new.Decompose(axes[ro[2]], axes[ro[1]], axes[ro[0]]) index_order = Gf.Vec3i() for i in range(3): index_order[ro[i]] = 2 - i rotation = Gf.Vec3d(decomp_rot[index_order[0]], decomp_rot[index_order[1]], decomp_rot[index_order[2]]) rotation = find_best_euler_angles(Gf.Vec3d(r), rotation, ro) if should_update_scale: # Construct the new scale from old rotation and translation. # Don't use Factor because it won't be able to tell if scale is positive or negative and can result in flipped rotation old_rt_mtx = compose_transform_ops_to_matrix(t, r, ro, Gf.Vec3d(1)) new_s_mtx = selected_local_mtx_new * old_rt_mtx.GetInverse() scale = Gf.Vec3d(new_s_mtx[0][0], new_s_mtx[1][1], new_s_mtx[2][2]) # any op may trigger a translation change if multi-manipulating translation = translation if should_update_translate else t rotation = rotation if should_update_rotate else r scale = scale if should_update_scale else s paths.append(path.pathString) new_translations += [translation[0], translation[1], translation[2]] new_rotation_eulers += [rotation[0], rotation[1], rotation[2]] new_rotation_orders += [ro[0], ro[1], ro[2]] new_scales += [scale[0], scale[1], scale[2]] old_translations += [t[0], t[1], t[2]] old_rotation_eulers += [r[0], r[1], r[2]] old_rotation_orders += [ro[0], ro[1], ro[2]] old_scales += [s[0], s[1], s[2]] xform_tuple = (scale, rotation, ro, translation, selected_pivot) self.all_xformable_prim_data_curr[path] = xform_tuple if path in self.consolidated_xformable_prim_data_curr: self.consolidated_xformable_prim_data_curr[path] = xform_tuple self._ignore_xform_data_change = True self._do_transform_all_selected_prims_to_manipulator_pivot( paths, new_translations, new_rotation_eulers, new_rotation_orders, new_scales ) self._ignore_xform_data_change = False def _alert_if_selection_has_instance_proxies(self): if self._selected_instance_proxy_paths and (not self._warning_notification or self._warning_notification.dismissed): try: import omni.kit.notification_manager as nm self._warning_notification = nm.post_notification( "Children of an instanced prim cannot be modified, uncheck Instanceable on the instanced prim to modify child prims.", status=nm.NotificationStatus.WARNING ) except ImportError: pass def _do_transform_all_selected_prims_to_manipulator_pivot( self, paths: List[str], new_translations: List[float], new_rotation_eulers: List[float], new_rotation_orders: List[int], new_scales: List[float], ): """Function ran by _transform_all_selected_prims_to_manipulator_pivot(). Can be overridden to change the behavior. Do not remove this function: can be used outside of this code""" self._alert_if_selection_has_instance_proxies() omni.kit.commands.create( "TransformMultiPrimsSRTCpp", count=len(paths), no_undo=True, paths=paths, new_translations=new_translations, new_rotation_eulers=new_rotation_eulers, new_rotation_orders=new_rotation_orders, new_scales=new_scales, usd_context_name=self._usd_context_name, time_code=self._get_current_time_code().GetValue(), ).do() def _on_stage_event(self, event: carb.events.IEvent): if event.type == int(omni.usd.StageEventType.OPENED): self._on_stage_opened() elif event.type == int(omni.usd.StageEventType.CLOSING): self._on_stage_closing() def _on_stage_opened(self): self._stage = self._usd_context.get_stage() self._timeline_sub = self._timeline.get_timeline_event_stream().create_subscription_to_pop( self._on_timeline_event ) self._current_time = self._timeline.get_current_time() self._xform_cache = UsdGeom.XformCache(self._get_current_time_code()) def _on_stage_closing(self): self._stage = None self._xform_cache = None self._xformable_prim_paths.clear() self._xformable_prim_paths_sorted.clear() self._xformable_prim_paths_set.clear() self._xformable_prim_paths_prefix_set.clear() self._consolidated_xformable_prim_paths.clear() self._pivot_prim = None self._timeline_sub = None if self._stage_listener: self._stage_listener.Revoke() self._stage_listener = None carb.log_info("Tf.Notice.Revoke in PrimTransformModel") self._pending_changed_paths.clear() if self._update_prim_xform_from_prim_task_or_future is not None: self._update_prim_xform_from_prim_task_or_future.cancel() self._update_prim_xform_from_prim_task_or_future = None def on_selection_changed(self, selection: List[Sdf.Path]): if self._update_prim_xform_from_prim_task_or_future is not None: self._update_prim_xform_from_prim_task_or_future.cancel() self._update_prim_xform_from_prim_task_or_future = None self._selected_instance_proxy_paths.clear() self._xformable_prim_paths.clear() self._xformable_prim_paths_set.clear() self._xformable_prim_paths_prefix_set.clear() self._consolidated_xformable_prim_paths.clear() self._pivot_prim = None for sdf_path in selection: prim = self._stage.GetPrimAtPath(sdf_path) if prim and prim.IsA(UsdGeom.Xformable) and prim.IsActive(): self._xformable_prim_paths.append(sdf_path) if self._xformable_prim_paths: # Make a sorted list so parents always appears before child self._xformable_prim_paths_sorted = self._xformable_prim_paths.copy() self._xformable_prim_paths_sorted.sort() # Find the most recently selected valid xformable prim as the pivot prim where the transform gizmo is located at. self._pivot_prim = self._stage.GetPrimAtPath(self._xformable_prim_paths[-1]) # Get least common prims ancestors. # We do this so that if one selected prim is a descendant of other selected prim, the descendant prim won't be # transformed twice. self._consolidated_xformable_prim_paths = Sdf.Path.RemoveDescendentPaths(self._xformable_prim_paths) # Filter all instance proxy paths. for path in self._consolidated_xformable_prim_paths: prim = self._stage.GetPrimAtPath(path) if prim.IsInstanceProxy(): self._selected_instance_proxy_paths.add(sdf_path) self._xformable_prim_paths_set.update(self._xformable_prim_paths) for path in self._xformable_prim_paths_set: self._xformable_prim_paths_prefix_set.update(path.GetPrefixes()) if self._update_transform_from_prims(): self._item_changed(self._transform_item) # Happens when host widget is already enabled and first selection in a new stage if self._enabled_hosting_widget_count > 0 and self._stage_listener is None: self._stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_objects_changed, self._stage) carb.log_info("Tf.Notice.Register in PrimTransformModel") def _should_keep_manipulator_orientation_unchanged(self, mode: str) -> bool: # Exclude snap_to_face. During snap_to_face operation, it may modify the orientation of object to confrom to surface # normal and the `new_manipulator_transform` param for `_transform_selected_prims` is set to the final transform # of the manipulated prim. However, if we use old rotation in the condition below, _no_scale_transform_manipulator # will not confrom to the new orientation, and _transform_selected_prims would double rotate the prims because it # sees the rotation diff between the old prim orientation (captured at on_began) vs new normal orient, instead of # current prim orientation vs new normal orientation. # Plus, it is nice to see the normal of the object changing while snapping. snap_provider_enabled = self.snap_settings_listener.snap_enabled and self.snap_settings_listener.snap_provider # When the manipulator is being manipulated as local translate or scale, we do not want to change the rotation of # the manipulator even if it's rotated, otherwise the direction of moving or scaling will change and can be very hard to control. # It can happen when you move a prim that has a constraint on it (e.g. lookAt) # In this case keep the rotation the same as on_began return ( mode == c.TRANSFORM_MODE_LOCAL and (self._current_editing_op == Operation.TRANSLATE or self._current_editing_op == Operation.SCALE) and not snap_provider_enabled ) def _should_keep_manipulator_translation_unchanged(self, mode: str) -> bool: # When the pivot placement is BBOX_CENTER and multiple prims being rotated, the bbox center may shifts, and the # rotation center will shift with them. This causes weird user experience. So we pin the rotation center until # mouse is released. return ( self._current_editing_op == Operation.ROTATE and (self._placement == Placement.BBOX_CENTER or self._placement == Placement.BBOX_BASE) ) def _get_transform_mode_for_current_op(self) -> str: mode = c.TRANSFORM_MODE_LOCAL if self._op_settings_listener.selected_op == c.TRANSFORM_OP_ROTATE: mode = self._op_settings_listener.rotation_mode elif self._op_settings_listener.selected_op == c.TRANSFORM_OP_MOVE: mode = self._op_settings_listener.translation_mode return mode # Adds a delay to the visual update during translate (only) manipulation # It's due to the renderer having a delay of rendering the mesh and the manipulator appears to drift apart. # It's only an estimation and may varying from scene/renderer setup. async def _delay_dirty(self, transform, id): if self._viewport_fps: render_frame_time = 1.0 / self._viewport_fps * self._settings.get(TRANSLATE_DELAY_FRAME_SETTING) while True: dt = await self._app.next_update_async() render_frame_time -= dt # break a frame early if render_frame_time < dt: break # cancel earlier job if a later one catches up (fps suddenly changed?) earlier_tasks_or_futures = [] for key, task_or_future in self._delay_dirty_tasks_or_futures.items(): if key < id: earlier_tasks_or_futures.append(key) task_or_future.cancel() else: break for key in earlier_tasks_or_futures: self._delay_dirty_tasks_or_futures.pop(key) self._transform = transform self._item_changed(self._transform_item) self._delay_dirty_tasks_or_futures.pop(id) def _update_temp_pivot_world_position(self): if type(self._transform) is not list: return new_world_position = self._transform[12:15] self._settings.set_float_array( self._selection_pivot_position_path, new_world_position ) @carb.profiler.profile def _update_transform_from_prims(self): xform_flattened = self._calculate_transform_from_prim() if self._transform != xform_flattened: self._transform = xform_flattened # update setting with new pivot placement position self._update_temp_pivot_world_position() return True return False def _calculate_transform_from_prim(self): if not self._stage: return False if not self._pivot_prim: return False self._xform_cache.Clear() cur_time = self._get_current_time_code() mode = self._get_transform_mode_for_current_op() pivot_inv = get_local_transform_pivot_inv(self._pivot_prim, cur_time) if self._should_keep_manipulator_orientation_unchanged(mode): pivot_prim_path = self._pivot_prim.GetPath() (s, r, ro, t) = omni.usd.get_local_transform_SRT(self._pivot_prim, cur_time) pivot = get_local_transform_pivot_inv(self._pivot_prim, self._get_current_time_code()).GetInverse() self.all_xformable_prim_data_curr[pivot_prim_path] = (s, r, ro, t) + (pivot,) # This method may be called from _on_op_listener_changed, before any gesture has started # in which case _all_xformable_prim_data_prev would be empty piv_xf_tuple = self._all_xformable_prim_data_prev.get(pivot_prim_path, False) if not piv_xf_tuple: piv_xf_tuple = omni.usd.get_local_transform_SRT(self._pivot_prim, cur_time) pv_xf_pivot = get_local_transform_pivot_inv( self._pivot_prim, self._get_current_time_code() ).GetInverse() self._all_xformable_prim_data_prev[self._pivot_prim.GetPath()] = piv_xf_tuple + (pv_xf_pivot,) (s_p, r_p, ro_p, t_p, t_piv) = piv_xf_tuple xform = self._construct_transform_matrix_from_SRT(t, r_p, ro_p, s, pivot_inv) parent = self._xform_cache.GetLocalToWorldTransform(self._pivot_prim.GetParent()) xform *= parent else: xform = self._xform_cache.GetLocalToWorldTransform(self._pivot_prim) xform = pivot_inv.GetInverse() * xform if self._should_keep_manipulator_translation_unchanged(mode): xform.SetTranslateOnly((self._transform[12], self._transform[13], self._transform[14])) else: # if there's only one selection, we always use LAST_PRIM_PIVOT though if ( self._placement != Placement.LAST_PRIM_PIVOT and self._placement != Placement.REF_PRIM ): average_translation = Gf.Vec3d(0.0) if self._placement == Placement.BBOX_CENTER or self._placement == Placement.BBOX_BASE: world_bound = Gf.Range3d() def get_prim_translation(xformable): xformable_world_mtx = self._xform_cache.GetLocalToWorldTransform(xformable) xformable_pivot_inv = get_local_transform_pivot_inv(xformable, cur_time) xformable_world_mtx = xformable_pivot_inv.GetInverse() * xformable_world_mtx return xformable_world_mtx.ExtractTranslation() for path in self._xformable_prim_paths: xformable = self._stage.GetPrimAtPath(path) if self._placement == Placement.SELECTION_CENTER: average_translation += get_prim_translation(xformable) elif self._placement == Placement.BBOX_CENTER or Placement.BBOX_BASE: bound_range = self._usd_context.compute_path_world_bounding_box(path.pathString) bound_range = Gf.Range3d(Gf.Vec3d(*bound_range[0]), Gf.Vec3d(*bound_range[1])) if not bound_range.IsEmpty(): world_bound = Gf.Range3d.GetUnion(world_bound, bound_range) else: # extend world bound with tranlation for prims with zero bbox, e.g. Xform, Camera prim_translation = get_prim_translation(xformable) world_bound.UnionWith(prim_translation) if self._placement == Placement.SELECTION_CENTER: average_translation /= len(self._xformable_prim_paths) elif self._placement == Placement.BBOX_CENTER: average_translation = world_bound.GetMidpoint() elif self._placement == Placement.BBOX_BASE: # xform may not have bbox but its descendants may have, exclude cases that only xform are selected if not world_bound.IsEmpty(): bbox_center = world_bound.GetMidpoint() bbox_size = world_bound.GetSize() if UsdGeom.GetStageUpAxis(self._stage) == UsdGeom.Tokens.y: # Y-up world average_translation = bbox_center - Gf.Vec3d(0.0, bbox_size[1] / 2.0, 0.0) else: # Z-up world average_translation = bbox_center - Gf.Vec3d(0.0, 0.0, bbox_size[2] / 2.0) else: # fallback to SELECTION_CENTER average_translation /= len(self._xformable_prim_paths) # Only take the translate from selected prim average. # The rotation and scale still comes from pivot prim xform.SetTranslateOnly(average_translation) # instead of using RemoveScaleShear, additional steps made to handle negative scale properly scale, _, _, _ = omni.usd.get_local_transform_SRT(self._pivot_prim, cur_time) scale_epsilon = 1e-6 for i in range(3): if Gf.IsClose(scale[i], 0.0, scale_epsilon): scale[i] = -scale_epsilon if scale[i] < 0 else scale_epsilon inverse_scale = Gf.Matrix4d().SetScale(Gf.Vec3d(1.0 / scale[0], 1.0 / scale[1], 1.0 / scale[2])) xform = inverse_scale * xform # this is the average xform without scale self._no_scale_transform_manipulator = Gf.Matrix4d(xform) # store the scale separately self._scale_manipulator = Gf.Vec3d(scale) # Visual transform of the manipulator xform = xform.RemoveScaleShear() if mode == c.TRANSFORM_MODE_GLOBAL: xform = xform.SetTranslate(xform.ExtractTranslation()) return flatten(xform) def _construct_transform_matrix_from_SRT( self, translation: Gf.Vec3d, rotation_euler: Gf.Vec3d, rotation_order: Gf.Vec3i, scale: Gf.Vec3d, pivot_inv: Gf.Matrix4d, ): trans_mtx = Gf.Matrix4d() rot_mtx = Gf.Matrix4d() scale_mtx = Gf.Matrix4d() trans_mtx.SetTranslate(Gf.Vec3d(translation)) axes = [Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()] rotation = ( Gf.Rotation(axes[rotation_order[0]], rotation_euler[rotation_order[0]]) * Gf.Rotation(axes[rotation_order[1]], rotation_euler[rotation_order[1]]) * Gf.Rotation(axes[rotation_order[2]], rotation_euler[rotation_order[2]]) ) rot_mtx.SetRotate(rotation) scale_mtx.SetScale(Gf.Vec3d(scale)) return pivot_inv * scale_mtx * rot_mtx * pivot_inv.GetInverse() * trans_mtx def _on_op_listener_changed(self, type: OpSettingsListener.CallbackType, value: str): if type == OpSettingsListener.CallbackType.OP_CHANGED: # cancel all delayed tasks for task_or_future in self._delay_dirty_tasks_or_futures.values(): task_or_future.cancel() self._delay_dirty_tasks_or_futures.clear() self._update_transform_from_prims() self._item_changed(self._transform_item) elif type == OpSettingsListener.CallbackType.TRANSLATION_MODE_CHANGED: if self._op_settings_listener.selected_op == c.TRANSFORM_OP_MOVE: if self._update_transform_from_prims(): self._item_changed(self._transform_item) elif type == OpSettingsListener.CallbackType.ROTATION_MODE_CHANGED: if self._op_settings_listener.selected_op == c.TRANSFORM_OP_ROTATE: if self._update_transform_from_prims(): self._item_changed(self._transform_item) def _update_placement(self, placement_str: str): if placement_str == prim_c.MANIPULATOR_PLACEMENT_SELECTION_CENTER: placement = Placement.SELECTION_CENTER elif placement_str == prim_c.MANIPULATOR_PLACEMENT_BBOX_CENTER: placement = Placement.BBOX_CENTER elif placement_str == prim_c.MANIPULATOR_PLACEMENT_PICK_REF_PRIM: placement = Placement.REF_PRIM elif placement_str == prim_c.MANIPULATOR_PLACEMENT_BBOX_BASE: placement = Placement.BBOX_BASE else: # placement == prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT or bad values placement = Placement.LAST_PRIM_PIVOT if placement != self._placement: if placement == Placement.LAST_PRIM_PIVOT and self._placement == Placement.REF_PRIM: # reset the pivot prim in case it was changed by MANIPULATOR_PLACEMENT_PICK_REF_PRIM if self._xformable_prim_paths: self._pivot_prim = self._stage.GetPrimAtPath(self._xformable_prim_paths[-1]) self._placement = placement if self._update_transform_from_prims(): self._item_changed(self._transform_item) def _on_placement_setting_changed(self, item, event_type): placement_str = self._dict.get(item) self._update_placement(placement_str) def _check_update_selected_instance_proxy_list(self, path: Sdf.Path, resynced): def track_or_remove_from_instance_proxy_list(prim): valid_proxy = prim and prim.IsActive() and prim.IsInstanceProxy() if valid_proxy: self._selected_instance_proxy_paths.add(prim.GetPath()) else: self._selected_instance_proxy_paths.discard(prim.GetPath()) prim_path = path.GetPrimPath() changed_prim = self._stage.GetPrimAtPath(prim_path) # Update list of instance proxy paths. if resynced and path.IsPrimPath(): if prim_path in self._consolidated_xformable_prim_paths: # Quick path if it's selected already. track_or_remove_from_instance_proxy_list(changed_prim) else: # Slow path to verify if any of its ancestors are changed. for path in self._consolidated_xformable_prim_paths: if not path.HasPrefix(prim_path): continue prim = self._stage.GetPrimAtPath(path) track_or_remove_from_instance_proxy_list(prim) @carb.profiler.profile async def _update_transform_from_prims_async(self): try: check_all_prims = ( self._placement != Placement.LAST_PRIM_PIVOT and self._placement != Placement.REF_PRIM and len(self._xformable_prim_paths) > 1 ) pivot_prim_path = self._pivot_prim.GetPath() for p, resynced in self._pending_changed_paths.items(): self._check_update_selected_instance_proxy_list(p, resynced) prim_path = p.GetPrimPath() # Update either check_all_prims # or prim_path is a prefix of pivot_prim_path (pivot prim's parent affect pivot prim transform) # Note: If you move the manipulator and the prim flies away while manipulator stays in place, check this # condition! if ( # check _xformable_prim_paths_prefix_set so that if the parent path of selected prim(s) changed, it # can still update manipulator transform prim_path in self._xformable_prim_paths_prefix_set if check_all_prims else pivot_prim_path.HasPrefix(prim_path) ): if self._path_may_affect_transform(p): # only delay the visual update in translate mode. should_delay_frame = self._settings.get(TRANSLATE_DELAY_FRAME_SETTING) > 0 if self._op_settings_listener.selected_op == c.TRANSFORM_OP_MOVE and should_delay_frame: xform = self._calculate_transform_from_prim() id = self._app.get_update_number() self._delay_dirty_tasks_or_futures[id] = run_coroutine(self._delay_dirty(xform, id)) else: if self._update_transform_from_prims(): self._item_changed(self._transform_item) break except Exception as e: carb.log_error(traceback.format_exc()) finally: self._pending_changed_paths.clear() self._update_prim_xform_from_prim_task_or_future = None @carb.profiler.profile def _on_objects_changed(self, notice, sender): if not self._pivot_prim: return # collect resynced paths so that removed/added xformOps triggers refresh for path in notice.GetResyncedPaths(): self._pending_changed_paths[path] = True # collect changed only paths for path in notice.GetChangedInfoOnlyPaths(): self._pending_changed_paths[path] = False # if an operation is in progess, record all dirty xform path if self._current_editing_op is not None and not self._ignore_xform_data_change: self._pending_changed_paths_for_xform_data.update(notice.GetChangedInfoOnlyPaths()) if self._update_prim_xform_from_prim_task_or_future is None or self._update_prim_xform_from_prim_task_or_future.done(): self._update_prim_xform_from_prim_task_or_future = run_coroutine(self._update_transform_from_prims_async()) def _on_timeline_event(self, e: carb.events.IEvent): if e.type == int(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED): current_time = e.payload["currentTime"] if current_time != self._current_time: self._current_time = current_time self._xform_cache.SetTime(self._get_current_time_code()) # TODO only update transform if this prim or ancestors transforms are time varying? if self._update_transform_from_prims(): self._item_changed(self._transform_item) def _get_current_time_code(self): return Usd.TimeCode(omni.usd.get_frame_time_code(self._current_time, self._stage.GetTimeCodesPerSecond())) def _set_default_settings(self): self._settings.set_default(TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_ENABLED, False) self._settings.set_default(TRANSFORM_GIZMO_IS_USING, False) self._settings.set_default(TRANSFORM_GIZMO_TRANSLATE_DELTA_XYZ, [0, 0, 0]) self._settings.set_default(TRANSFORM_GIZMO_ROTATE_DELTA_XYZW, [0, 0, 0, 1]) self._settings.set_default(TRANSFORM_GIZMO_SCALE_DELTA_XYZ, [0, 0, 0]) def _should_skip_custom_manipulator_path(self, path: str) -> bool: custom_manipulator_path_prims_settings_path = TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_PRIMS + path return self._settings.get(custom_manipulator_path_prims_settings_path) def _path_may_affect_transform(self, path: Sdf.Path) -> bool: # Batched changes sent in a SdfChangeBlock may not have property name but only the prim path return not path.ContainsPropertyElements() or UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(path.name)
78,021
Python
44.308943
146
0.623922
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/inspector_preview.py
__all__ = ["InspectorPreview"] from typing import Union import omni.ui as ui import omni.kit.app import carb.events import carb from omni.ui_query import OmniUIQuery from omni.kit.widget.inspector import InspectorWidget, PreviewMode class InspectorPreview: """The Stage widget""" def destroy(self): self._window = None self._inspector = None def __init__(self, window: ui.Window, **kwargs): self._window = window self._widget = window.frame if window else None self._preview_mode = ["BOTH", "WIRE", "COLOR"] self._preview_mode_model = None self._inspector: Union[ui.Inspector, None] = None self._main_stack = ui.VStack() self._sender_id = hash("InspectorPreview") & 0xFFFFFFFF self._build_ui() app = omni.kit.app.get_app() self._update_sub = app.get_message_bus_event_stream().create_subscription_to_pop( self.on_selection_changed, name="Inspector Selection Changed" ) def on_selection_changed(self, event: carb.events.IEvent): if event.sender == self._sender_id: # we don't respond to our own events return from .inspector_widget import INSPECTOR_ITEM_SELECTED_ID, INSPECTOR_PREVIEW_CHANGED_ID if event.type == INSPECTOR_ITEM_SELECTED_ID: selection = OmniUIQuery.find_widget(event.payload["item_path"]) if selection: self.set_widget(selection) elif event.type == INSPECTOR_PREVIEW_CHANGED_ID: selection = OmniUIQuery.find_widget(event.payload["item_path"]) if selection: if "window_name" in event.payload: window_name = event.payload["window_name"] window = ui.Workspace.get_window(window_name) if window: self._window = window else: carb.log_error(f"Failed to find {window_name}") self.set_main_widget(selection) def toggle_visibility(self): self._main_stack.visible = not self._main_stack.visible def _build_ui(self): with self._main_stack: ui.Spacer(height=5) with ui.ZStack(): ui.Rectangle(name="render_background", style={"background_color": 0xFF333333}) with ui.VStack(): ui.Spacer(height=10) with ui.ZStack(): ui.Rectangle() with ui.HStack(): self._inspector = InspectorWidget(widget=self._widget) def selection_changed(widget): # Send the Selection Changed Message from .inspector_widget import INSPECTOR_ITEM_SELECTED_ID stream = omni.kit.app.get_app().get_message_bus_event_stream() widget_path = OmniUIQuery.get_widget_path(self._window, widget) if widget_path: stream.push( INSPECTOR_ITEM_SELECTED_ID, sender=self._sender_id, payload={"item_path": widget_path}, ) self._inspector.set_selected_widget_changed_fn(selection_changed) with ui.HStack(height=0): ui.Label("Depth", width=0) ui.Spacer(width=4) def value_changed_fn(model: ui.AbstractValueModel): self._inspector.depth_scale = float(model.as_int) model = ui.IntDrag(min=0, max=300, width=40).model model.set_value(50) model.add_value_changed_fn(value_changed_fn) ui.Spacer() # def build Preview Type Radio with ui.HStack(width=0, style={"margin": 0, "padding_width": 6, "border_radius": 0}): self._preview_mode_collection = ui.RadioCollection() def preview_mode_changed(item: ui.AbstractValueModel): index = item.as_int if index == 0: self._inspector.preview_mode = PreviewMode.WIREFRAME_AND_COLOR elif index == 1: self._inspector.preview_mode = PreviewMode.WIRE_ONLY else: self._inspector.preview_mode = PreviewMode.COLOR_ONLY self._preview_mode_collection.model.add_value_changed_fn(preview_mode_changed) for preview_mode in self._preview_mode: style = {} radius = 4 if preview_mode == "BOTH": style = {"border_radius": radius, "corner_flag": ui.CornerFlag.LEFT} if preview_mode == "COLOR": style = {"border_radius": radius, "corner_flag": ui.CornerFlag.RIGHT} ui.RadioButton( width=50, style=style, text=preview_mode, radio_collection=self._preview_mode_collection ) def preview_mode_value_changed(value): if value == PreviewMode.WIREFRAME_AND_COLOR: self._preview_mode_collection.model.set_value(0) elif value == PreviewMode.WIRE_ONLY: self._preview_mode_collection.model.set_value(1) elif value == PreviewMode.COLOR_ONLY: self._preview_mode_collection.model.set_value(2) self._inspector.set_preview_mode_change_fn(preview_mode_value_changed) ui.Spacer() ui.Label("Range ", width=0) def min_value_changed_fn(model: ui.AbstractValueModel): self._inspector.start_depth = model.as_int model = ui.IntDrag(min=0, max=20, width=50).model.add_value_changed_fn(min_value_changed_fn) ui.Spacer(width=4) def max_value_changed_fn(model: ui.AbstractValueModel): self._inspector.end_depth = model.as_int ui.IntDrag(min=0, max=6000, width=50).model.add_value_changed_fn(max_value_changed_fn) def set_main_widget(self, widget: ui.Widget): self._widget = widget self._inspector.widget = widget def set_widget(self, widget: ui.Widget): self._inspector.selected_widget = widget def update_window(self, window: ui.Window): self._inspector = None self._window = window self._widget = window.frame self._main_stack.clear() self._build_ui()
6,936
Python
40.047337
116
0.523933
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/inspector_window.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__ = ["InspectorWindow"] import omni.ui as ui import carb.events import omni.kit.app from typing import cast from .tree.inspector_tree import WindowListModel, WindowItem from .demo_window import InspectorDemoWindow from .inspector_widget import InspectorWidget from pathlib import Path ICON_PATH = Path(__file__).parent.parent.parent.parent.parent.joinpath("icons") class InspectorWindow: """The inspector window""" def __init__(self): window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR self._window = ui.Window( "Inspector", width=1000, height=800, flags=window_flags, dockPreference=ui.DockPreference.RIGHT_TOP, padding_x=0, padding_y=0, ) # Create a Demo Window to show case the general feature self._demo_window = None use_demo_window = carb.settings.get_settings().get("/exts/omni.kit.window.inspector/use_demo_window") with self._window.frame: if use_demo_window: self._demo_window = InspectorDemoWindow() self._inspector_widget = InspectorWidget(self._demo_window.window) else: self._inspector_widget = InspectorWidget(None) def destroy(self): """ Called by extension before destroying this object. It doesn't happen automatically. Without this hot reloading doesn't work. """ if self._demo_window: self._demo_window.destroy() self._demo_window = None self._inspector_widget.destroy() self._inspector_widget = None self._window = None
2,094
Python
32.790322
109
0.661891
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/inspector_tests.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__ = ["test_widget_tool_button", "test_select_frame", "test_change_query", "test_menu_activation"] from omni.ui_query import OmniUIQuery import omni.kit.app import asyncio import carb import omni.ui as ui wait = None def test_widget_tool_button(): preview_tool_button = OmniUIQuery.find_widget("Inspector/Frame[0]/ZStack[1]/VStack[0]/HStack[2]/ToolButton") if preview_tool_button: preview_tool_button.call_clicked_fn() property_tool_button = OmniUIQuery.find_widget("Inspector/Frame[0]/ZStack[1]/VStack[0]/HStack[3]/ToolButton") if property_tool_button: property_tool_button.call_clicked_fn() style_tool_button = OmniUIQuery.find_widget("Inspector/Frame[0]/ZStack[1]/VStack[0]/HStack[4]/ToolButton") if style_tool_button: style_tool_button.call_clicked_fn() def test_select_frame(): global wait from .inspector_widget import INSPECTOR_ITEM_SELECTED_ID stream = omni.kit.app.get_app().get_message_bus_event_stream() stream.push(INSPECTOR_ITEM_SELECTED_ID, sender=444, payload={"item_path": "DemoWindow/Frame[0]/VStack"}) async def wait_a_frame(): await omni.kit.app.get_app().next_update_async() spacing_label_path = "Inspector/Frame[0]/ZStack[1]/VStack[2]/HStack[3]/VStack[3]/CollapsableFrame[0]/Frame[0]/VStack[1]/HStack[0]/Label" spacing_value_path = "Inspector/Frame[0]/ZStack[1]/VStack[2]/HStack[3]/VStack[3]/CollapsableFrame[0]/Frame[0]/VStack[1]/HStack[2]/FloatDrag" spacing_label = OmniUIQuery.find_widget(spacing_label_path) print("spacing_label", spacing_label) if spacing_label and isinstance(spacing_label, ui.Label): if not spacing_label.text == "spacing": carb.log_error(f"Failed the Frame Selection Test , Label is {spacing_label.text}") return spacing_value = OmniUIQuery.find_widget(spacing_value_path) print("spacing_value", spacing_value) if spacing_value and isinstance(spacing_value, ui.FloatDrag): if not spacing_value.model.as_float == 0.0: carb.log_error(f"Failed the Frame Selection Test , spacing value is {spacing_value.model.as_float}") return carb.log_warn("Frame Selection Test PASSED") wait = asyncio.ensure_future(wait_a_frame()) def test_change_query(): query_field = OmniUIQuery.find_widget( "Inspector/Frame[0]/ZStack[1]/VStack[4]/ZStack[1]/VStack[1]/HStack[2]/StringField" ) if query_field and isinstance(query_field, ui.StringField): response_field_path = "Inspector/Frame[0]/ZStack[1]/VStack[4]/ZStack[1]/VStack[1]/HStack[4]/StringField" query_field.model.set_value(response_field_path) query_field.model.end_edit() response_field = OmniUIQuery.find_widget(response_field_path) if not isinstance(response_field, ui.StringField): carb.log_error(f"Faild to find the right widget at {response_field_path}") else: print(response_field, response_field.model.as_string) def test_menu_activation(): menu_item = OmniUIQuery.find_menu_item("MainWindow/MenuBar[0]/Menu[14]/MenuItem") print(menu_item) if isinstance(menu_item, ui.MenuItem): print(menu_item.text) menu_item.call_triggered_fn()
3,737
Python
41
148
0.693069
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/demo_window.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__ = ["InspectorDemoWindow"] from typing import cast from pathlib import Path import omni.ui as ui ICON_PATH = Path(__file__).parent.parent.parent.parent.parent.joinpath("icons") class InspectorDemoWindow: """The demo window for the inspector""" @property def window(self) -> ui.Window: return cast(ui.Window, self._window) def destroy(self): self._window = None def __init__(self): self._window = ui.Window("DemoWindow", width=300, height=900) style_testing = { "Label:hovered": {"color": 0xFF00FFFF}, "Label::title": {"font_size": 18, "color": 0xFF00EEEE, "alignment": ui.Alignment.LEFT}, "Label": {"font_size": 14, "color": 0xFFEEEEEE}, "Button.Label": {"font_size": 15, "color": 0xFF33FF33}, "Line": {"color": 0xFFFF0000}, "Slider": {"draw_mode": ui.SliderDrawMode.FILLED, "secondary_color": 0xFFAA0000}, "Stack::blue": {"stack_direction": ui.Direction.RIGHT_TO_LEFT}, "Button::green": { "background_color": 0xFF333333, "color": 0xFF00FFFF, "border_width": 2, "border_color": 0xFF00FF00, "border_radius": 3, "corner_flag": ui.CornerFlag.BOTTOM, "alignment": ui.Alignment.CENTER, }, "Button.Image::green": { # "image_url": "c:/path/to/an/image.png", "fill_policy": ui.FillPolicy.PRESERVE_ASPECT_FIT }, } self._window.frame.set_style(style_testing) with self._window.frame: with ui.VStack(): ui.Label("Title", height=0, name="title") with ui.HStack(height=0): ui.Label("THis is Cool", style={"Label": {"font_size": 12, "color": 0xFF0000FF}}) def button_fn(name: str): print(f"Executed Button Labled {name}") ui.Button("Button 1", name="button1", clicked_fn=lambda n="Button 1": button_fn(n)) ui.Button("Button 2", name="green", clicked_fn=lambda n="Button 2": button_fn(n)) ui.Line(height=2) ui.Spacer(height=10) ui.IntSlider(height=0, min=0, max=100) ui.Spacer(height=10) with ui.HStack(height=0): ui.Label("Field", style={"color": 0xFF00FF00}) ui.StringField().model.set_value("This is Cool ") with ui.HStack(height=0): ui.Rectangle( height=30, style={ "backgroun_color": 0xFFAAAAAA, "border_width": 2, "border_radius": 3, "border_color": 0xFFAADDAA, }, ) with ui.Frame(height=100): with ui.Placer(draggable=True): ui.Rectangle(width=20, height=20, style={"background_color": 0xFF0000FF}) ui.ComboBox(1, "One", "Two", "Inspector", "Is", "Amazing", height=0) ui.Spacer(height=10) with ui.VGrid(height=50, column_count=5, row_height=50): for i in range(5): ui.Rectangle(style={"background_color": 0xFF000000}) ui.Rectangle(style={"background_color": 0xFFFFFFFF}) with ui.HGrid(height=50, column_width=30, row_count=3): for i in range(10): ui.Rectangle(style={"background_color": 0xFF00FFAA}) ui.Rectangle(style={"background_color": 0xFFF00FFF}) ui.Spacer(height=10) with ui.CollapsableFrame(title="Image", height=0): # ui.Image("/dfagnou/Desktop/omniverse_background.png", height=100) ui.Image(f"{ICON_PATH}/sync.svg", height=100) with ui.HStack(height=30): ui.Triangle(height=20, style={"background_color": 0xFFAAFFAA}) ui.Circle(style={"background_color": 0xFFAAFFFF}) canvas = ui.CanvasFrame(height=20, style={"background_color": 0xFFDD00DD}) # canvas.set_pan_key_shortcut(1, carb.K) with canvas: # ui.Image("/dfagnou/Desktop/omniverse_background.png") ui.Image(f"{ICON_PATH}/sync.svg", height=20)
4,997
Python
41.355932
103
0.529518
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/inspector_widget.py
__all__ = ["InspectorWidget"] import omni.ui as ui from .tree.inspector_tree import InspectorTreeView from .style.style_tree import StyleTreeView from .property.inspector_property_widget import InspectorPropertyWidget from .inspector_preview import InspectorPreview from omni.ui_query import OmniUIQuery # move the test into a menu on the top widget to experiment from .inspector_tests import test_widget_tool_button, test_select_frame, test_change_query, test_menu_activation from .inspector_style import INSPECTOR_STYLE DARK_BACKGROUND = 0xFF333333 INSPECTOR_ITEM_SELECTED_ID = 427273737 # hash("INSPECTOR_ITEM_SELECTED") INSPECTOR_PREVIEW_CHANGED_ID = 427273738 # hash("INSPECTOR_PREVIEW_CHANGED") INSPECTOR_ITEM_EXPANDED_ID = 427273739 KIT_GREEN = 0xFF888888 class InspectorWidget: def destroy(self): self._tree_view.destroy() self._tree_view = None self._render_view.set_widget(None) self._render_view._window = None self._render_view = None self._property_view.set_widget(None) self._property_view = None def __init__(self, window: ui.Window, **kwargs): self._test_menu = None self._window = window self._render_view = None self._main_stack = ui.ZStack(style=INSPECTOR_STYLE) self._build_ui() def _build_ui(self): with self._main_stack: ui.Rectangle(name="background") with ui.VStack(): with ui.HStack(height=30): bt = ui.Button("TestMenu", width=0) def show_test_menu(): self._test_menu = ui.Menu("Test") with self._test_menu: ui.MenuItem("ToolButton1", triggered_fn=test_widget_tool_button) ui.MenuItem("Select Frame", triggered_fn=test_select_frame) ui.MenuItem("Change Query", triggered_fn=test_change_query) ui.MenuItem("Test Menu", triggered_fn=test_menu_activation) self._test_menu.show_at(bt.screen_position_x, bt.screen_position_y + bt.computed_height) bt.set_clicked_fn(show_test_menu) ui.Spacer() # self._tree_vis_model = ui.ToolButton(text="Tree", width=100).model self._preview_vis_model = ui.ToolButton(text="Preview", name="toolbutton", width=100).model self._property_vis_model = ui.ToolButton(text="Property", name="toolbutton", width=100).model self._style_vis_model = ui.ToolButton(text="Style", name="toolbutton", width=100).model ui.Spacer() ui.Line(height=3, name="dark_separator") with ui.HStack(): # Build adjustable Inspector Tree Widget with "Splitter" with ui.ZStack(width=0): handle_width = 3 # the placer will increate the stack width with ui.Placer(offset_x=300, draggable=True, drag_axis=ui.Axis.X): ui.Rectangle(width=handle_width, name="splitter") # the tree view will fit the all ZStack Width minus the Handle Width with ui.HStack(name="tree", style={"HStack::tree": {"margin_width": 5}}): # Extensions List Widget (on the left) self._tree_view = InspectorTreeView(self._window, self.update_window) ui.Spacer(width=handle_width) # Build Inspector Preview self._render_view = InspectorPreview(self._window) ui.Line(alignment=ui.Alignment.H_CENTER, width=2, style={"color": 0xFF222222, "border_width": 2}) # Build Inspector Property Window self._property_view = InspectorPropertyWidget() ui.Line(alignment=ui.Alignment.H_CENTER, width=2, style={"color": 0xFF222222, "border_width": 2}) self._style_view = StyleTreeView() ui.Line(height=3, style={"color": 0xFF222222, "border_width": 3}) with ui.ZStack(height=30): ui.Rectangle(name="background") with ui.VStack(): ui.Spacer() with ui.HStack(height=0): ui.Spacer(width=10) ui.Label("Query : ", width=0) model = ui.StringField(width=400).model model.set_value("DemoWindow//Frame/VStack[1]/HStack[1]/Button") ui.Spacer(width=10) result = ui.StringField(width=200, read_only=True).model def execute_query(model: ui.AbstractValueModel): query = model.as_string children = OmniUIQuery.find_widget(query) if children: result.set_value(children.__class__.__name__) else: result.set_value("NO RESULT") if type(children) == ui.Button: print("Has Clicked Fn", children.has_clicked_fn) children.call_clicked_fn() model.add_end_edit_fn(execute_query) ui.Spacer() def visiblity_changed_fn(w): w.toggle_visibility() self._preview_vis_model.set_value(True) self._property_vis_model.set_value(True) self._style_vis_model.set_value(True) # self._tree_vis_model.add_value_changed_fn(lambda m, w=self._tree_view: visiblity_changed_fn(w)) self._preview_vis_model.add_value_changed_fn(lambda m, w=self._render_view: visiblity_changed_fn(w)) self._property_vis_model.add_value_changed_fn(lambda m, w=self._property_view: visiblity_changed_fn(w)) self._style_vis_model.add_value_changed_fn(lambda m, w=self._style_view: visiblity_changed_fn(w)) self._preview_vis_model.set_value(False) self._property_vis_model.set_value(False) self._style_vis_model.set_value(False) def update_window(self, window: ui.Window): self._window = window if self._render_view: self._render_view.update_window(window)
6,568
Python
42.503311
117
0.549635
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/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 omni.ext import omni.kit.ui from .inspector_window import InspectorWindow class InspectorExtension(omni.ext.IExt): """The entry point for Inspector Window""" MENU_PATH = "Window/Inspector" def on_startup(self): editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item(InspectorExtension.MENU_PATH, self.show_window, toggle=True, value=True) self.show_window(None, True) def on_shutdown(self): self._menu = None self._window.destroy() self._window = None def _visiblity_changed_fn(self, visible): editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: editor_menu.set_value(InspectorExtension.MENU_PATH, visible) def show_window(self, menu, value): if value: self._window = InspectorWindow() elif self._window: self._window.destroy() self._window = None
1,408
Python
31.767441
118
0.683239
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/inspector_style.py
__all__ = ["INSPECTOR_STYLE"] import omni.ui as ui KIT_GREEN = 0xFF888888 DARK_BACKGROUND = 0xFF333333 INSPECTOR_STYLE = { "Rectangle::background": {"background_color": DARK_BACKGROUND}, # toolbutton "Button.Label::toolbutton": {"color": 0xFF7B7B7B}, "Button.Label::toolbutton:checked": {"color": 0xFFD4D4D4}, "Button::toolbutton": {"background_color": 0xFF424242, "margin": 2.0}, "Button::toolbutton:checked": {"background_color": 0xFF5D5D5D}, "CheckBox::greenCheck": {"font_size": 10, "background_color": KIT_GREEN, "color": 0xFF23211F}, "Line::dark_separator": {"color": 0xFF222222, "border_width": 3}, "Rectangle::splitter": {"background_color": 0xFF222222}, "Rectangle::splitter:hovered": {"background_color": 0xFFFFCA83}, "Tooltip": {"background_color": 0xFF000000, "color": 0xFF333333}, }
845
Python
35.782607
98
0.67574
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/style/style_model.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. __all__ = ["StyleComboValueModel", "StyleComboNameValueItem", "StyleComboItemModel", "StylePropertyType", "StyleColorComponentItem", "StyleColorModel", "StyleItem", "StyleGroupItem", "StyleModel"] from os import remove from typing import Callable, Union, List, cast import omni.ui as ui from enum import Enum import copy, carb StyleFloatProperty = [ "border_radius", "border_width", "font_size", "margin", "margin_width", "margin_height", "padding", "padding_width", "padding_height", "secondary_padding", "scrollbar_size", ] StyleColorProperties = [ "background_color", "background_gradient_color", "background_selected_color", "border_color", "color", "selected_color", "secondary_color", "secondary_selected_color", "debug_color", ] StyleEnumProperty = ["corner_flag", "alignment", "fill_policy", "draw_mode", "stack_direction"] StyleStringProperty = ["image_url"] def get_enum_class(property_name: str) -> Union[Callable, None]: if property_name == "corner_flag": return ui.CornerFlag elif property_name == "alignment": return ui.Alignment elif property_name == "fill_policy": return ui.FillPolicy elif property_name == "draw_mode": return ui.SliderDrawMode elif property_name == "stack_direction": return ui.Direction else: return None class StyleComboValueModel(ui.AbstractValueModel): """ Model to store a pair (label, value of arbitrary type) for use in a ComboBox """ def __init__(self, key, value): """ Args: value: the instance of the Style value """ ui.AbstractValueModel.__init__(self) self.key = key self.value = value def __repr__(self): return f'"StyleComboValueModel name:{self.key} value:{int(self.value)}"' def get_value_as_string(self) -> str: """ this is called to get the label of the combo box item """ return self.key def get_style_value(self) -> int: """ we call this to get the value of the combo box item """ return int(self.value) class StyleComboNameValueItem(ui.AbstractItem): def __init__(self, key, value): super().__init__() self.model = StyleComboValueModel(key, value) def __repr__(self): return f'"StyleComboNameValueItem {self.model}"' class StyleComboItemModel(ui.AbstractItemModel): """ Model for a combo box - for each setting we have a dictionary of key, values """ def __init__(self, class_obj: Callable, default_value: int): super().__init__() self._class = class_obj self._items = [] self._default_value = default_value default_index = 0 current_index = 0 for key, value in class_obj.__members__.items(): if self._default_value == value: default_index = current_index self._items.append(StyleComboNameValueItem(key, value)) current_index += 1 self._current_index = ui.SimpleIntModel(default_index) self._current_index.add_value_changed_fn(self._current_index_changed) def get_current_value(self): return self._items[self._current_index.as_int].model.get_style_value() def _current_index_changed(self, model): self._item_changed(None) def get_item_children(self, item): return self._items def get_item_value_model(self, item, column_id: int): if item is None: return self._current_index return item.model class StylePropertyType(Enum): ENUM = 0 COLOR = 1 FLOAT = 2 STRING = 3 def get_property_type(property_name: str) -> StylePropertyType: if property_name in StyleStringProperty: return StylePropertyType.STRING elif property_name in StyleEnumProperty: return StylePropertyType.ENUM elif property_name in StyleColorProperties: return StylePropertyType.COLOR elif property_name in StyleFloatProperty: return StylePropertyType.FLOAT else: return StylePropertyType.FLOAT class StyleColorComponentItem(ui.AbstractItem): def __init__(self, model: ui.SimpleFloatModel) -> None: super().__init__() self.model = model class StyleColorModel(ui.AbstractItemModel): """ define a model for a style color, and enable coversion from int32 etc """ def __init__(self, value: int) -> None: super().__init__() self._value = value # Create root model self._root_model = ui.SimpleIntModel() self._root_model.add_value_changed_fn(lambda a: self._item_changed(None)) # convert Value from int red = self._value & 255 green = (self._value >> 8) & 255 blue = (self._value >> 16) & 255 alpha = (self._value >> 24) & 255 rgba_values = [red / 255, green / 255, blue / 255, alpha / 255] # Create three models per component self._items: List[StyleColorComponentItem] = [ StyleColorComponentItem(ui.SimpleFloatModel(rgba_values[i])) for i in range(4) ] for item in self._items: item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item)) def set_value(self, value: int): self._value = value def set_components_values(self, values: List[float]): if len(values) != 4: print("Error: List need to be exactly 4 long") return for i in range(4): self._items[i].model.set_value(values[i]) def set_components_values_as_int(self, values: List[int]): if len(values) != 4: print("Error: List need to be exactly 4 long") return for i in range(4): self._items[i].model.set_value(values[i] / 255) def get_value_as_int8s(self) -> List[int]: result: List[int] = [] for i in range(4): result.append(int(round(self._items[i].model.get_value_as_float() * 255))) return result def get_value_as_floats(self) -> List[float]: result: List[float] = [] for i in range(4): result.append(self._items[i].model.get_value_as_float()) return result def get_value_as_int32(self) -> int: red, green, blue, alpha = self.get_value_as_int8s() # we store then in AABBGGRR result = (alpha << 24) + (blue << 16) + (green << 8) + red return result def _on_value_changed(self, item): self._item_changed(item) def get_item_children(self, parentItem: ui.AbstractItem) -> List[StyleColorComponentItem]: return self._items def get_item_value_model(self, item: ui.AbstractItem, column_id: int) -> ui.AbstractValueModel: if item is None: return self._root_model return item.model def begin_edit(self, item): """ TODO: if we don't add this override (even without a real implementation) we get crashes """ pass def end_edit(self, item): """ TODO: if we don't add this override (even without a real implementation) we get crashes """ pass class StyleItem(ui.AbstractItem): """A single AbstractItemModel item that represents a single prim""" def __init__( self, property_name: str, style_type: StylePropertyType, values: dict, parent_model: "StyleModel", parent_item: "StyleGroupItem", ): super().__init__() self.parent_item = parent_item self.parent_model = parent_model self.property = property_name self.style_type = style_type self.value = values[property_name] self._values = values self._model: Union[ui.AbstractValueModel, ui.AbstractItemModel, None] = None if self.style_type == StylePropertyType.STRING: self._model = ui.SimpleStringModel(str(self.value)) elif self.style_type == StylePropertyType.ENUM: enum_cls = get_enum_class(property_name) self._model = StyleComboItemModel(enum_cls, self.value) elif self.style_type == StylePropertyType.COLOR: self._model = StyleColorModel(int(self.value)) elif self.style_type == StylePropertyType.FLOAT: self._model = ui.SimpleFloatModel(float(self.value)) else: raise ValueError("The Style Type need to be either STRING, ENUM, COLOR or FLOAT") if self.style_type in [StylePropertyType.STRING, StylePropertyType.FLOAT]: def value_changed(model: ui.AbstractValueModel): self._values[self.property] = model.as_float self.parent_model.update() self._model.add_value_changed_fn(value_changed) elif self.style_type == StylePropertyType.COLOR: def value_changed(model: StyleColorModel, item: ui.AbstractItem): self._values[self.property] = model.get_value_as_int32() self.parent_model.update() self._model.add_item_changed_fn(value_changed) elif self.style_type == StylePropertyType.ENUM: def value_changed(model: StyleComboItemModel, item: ui.AbstractItem): self._values[self.property] = model.get_current_value() self.parent_model.update() self._model.add_item_changed_fn(value_changed) def delete(self): # we simply remove the key from the referenced Value Dict del self._values[self.property] def get_model(self) -> Union[ui.AbstractValueModel, None]: return self._model def __repr__(self): return f"<StyleItem '{self.property} . {self.style_type}'>" def __str__(self): return f"<StyleItem '{self.property} . {self.style_type}'>" class StyleGroupItem(ui.AbstractItem): """A single AbstractItemModel item that represents a single prim""" def __init__(self, type_name: str, style_dict: dict, parent_model: "StyleModel"): super().__init__() self.children = [] self.type_name = type_name self._parent_dict = style_dict self.style_dict = self._parent_dict[type_name] self.parent_model = parent_model self._name_model = ui.SimpleStringModel() self._name_model.set_value(type_name) def value_changed(model: ui.AbstractValueModel): new_name = model.as_string if new_name in self._parent_dict: carb.log_warn(f"Entry with type {new_name} already exits, skipping") return self._parent_dict[new_name] = self.style_dict del self._parent_dict[self.type_name] self.type_name = new_name self.parent_model.update() self._name_model.add_value_changed_fn(value_changed) def get_model(self): return self._name_model def delete_item(self, item: StyleItem): # we call delete on the item but also make sure we clear our cach for it self.children.remove(item) item.delete() def delete(self): # we simply remove the key from the referenced Value Dict del self._parent_dict[self.type_name] def __repr__(self): return f"<StyleItem '{self.type_name} . {self.style_dict}'>" def __str__(self): return f"<StyleItem '{self.type_name} . {self.style_dict}'>" class StyleModel(ui.AbstractItemModel): """The item model that watches the stage""" def __init__(self, treeview): """Flat means the root node has all the children and children of children, etc.""" super().__init__() self._widget = None self._style_dict: dict = {} self._is_generic = False self._root: List[StyleGroupItem] = [] self._treeview: "StyleTreeView" = treeview def _update_style_dict(self, style: dict) -> dict: style_dict = copy.copy(style) # find if there are "Generic" entry (with no sub dictionary) and move them around remove_keys = [] has_generic_entries = False for key, value in style_dict.items(): if not type(value) == dict: has_generic_entries = True break if has_generic_entries: style_dict["All"] = {} for key, value in style_dict.items(): if not type(value) == dict: style_dict["All"][key] = value remove_keys.append(key) for a_key in remove_keys: del style_dict[a_key] return style_dict def set_widget(self, widget: ui.Widget): self._widget = widget self.update_cached_style() self._root: List[StyleGroupItem] = [] self._item_changed(None) def update_cached_style(self): if not self._widget.style: style_dict = {} else: style_dict = cast(dict, self._widget.style) self._style_dict = self._update_style_dict(style_dict) # rebuild self._item_changed(None) def can_item_have_children(self, parentItem: Union[StyleGroupItem, StyleItem]) -> bool: if not parentItem: return True if isinstance(parentItem, StyleGroupItem): return True return False def get_item_children(self, item: Union[StyleGroupItem, StyleItem, None]) -> Union[None, list]: """Reimplemented from AbstractItemModel""" if not item: if not self._root: self._root = [] for key, value in self._style_dict.items(): group_item = StyleGroupItem(key, self._style_dict, self) self._root.append(group_item) return self._root if isinstance(item, StyleItem): return [] if isinstance(item, StyleGroupItem): children = [] for key, value in item.style_dict.items(): property_type = get_property_type(key) # value is passed by reference and updated internally on change style_item = StyleItem(key, property_type, item.style_dict, self, item) children.append(style_item) item.children = children return item.children # we should not get here .. return [] def duplicate_item(self, item: StyleGroupItem): new_item = item.type_name + "1" self._style_dict[new_item] = copy.copy(self._style_dict[item.type_name]) new_item = StyleGroupItem(new_item, self._style_dict, self) self._root.append(new_item) self._item_changed(None) self.update() def delete_item(self, item: Union[StyleGroupItem, StyleItem]): if isinstance(item, StyleItem): item.parent_item.delete_item(item) self._item_changed(item.parent_item) self.update() elif isinstance(item, StyleGroupItem): item.delete() self._root.remove(item) self._item_changed(None) self.update() else: carb.log_error("Delete_item only support Union[StyleGroupItem, StyleItem]") def update(self): style_dict = cast(dict, copy.copy(self._style_dict)) if "All" in style_dict: # update Generic Entry for key, value in style_dict["All"].items(): style_dict[key] = value del style_dict["All"] self._widget.set_style(style_dict) def get_item_value_model_count(self, item): """Reimplemented from AbstractItemModel""" return 1 def get_item_value_model(self, item: Union[StyleItem, StyleGroupItem], column_id: int): """Reimplemented from AbstractItemModel""" if isinstance(item, StyleGroupItem): if column_id == 0: return item.get_model() elif isinstance(item, StyleItem): if column_id == 0: return ui.SimpleStringModel(item.property) if column_id == 1: return item.get_model() def destroy(self): self._widget = None
16,635
Python
30.992308
196
0.603727
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/style/style_delegate.py
__all__ = ["StyleTreeDelegate"] import omni.ui as ui from typing import Union from .style_model import StyleGroupItem, StyleModel, StyleItem, StylePropertyType from .widget_styles import ClassStyles from pathlib import Path ICON_PATH = Path(__file__).parent.parent.parent.parent.parent.parent.joinpath("icons") LINE_COLOR = 0x00555555 STYLE_NAME_DEFAULT = { "Colors": { "background_color": 0xFFAAAAAA, "color": 0xFFAAAAAA, "secondary_color": 0xFFAAAAAA, "selected_color": 0xFFAAAAAA, "secondary_selected_color": 0xFFAAAAAA, "debug_color": 0xAAAAFFAA, }, "Border": {"border_radius": 2.0, "border_width": 1.0, "border_color": 0xFFAAFFAA, "corner_flag": ui.CornerFlag.ALL}, "Text": {"alignment": ui.Alignment.LEFT, "font_size": 16.0}, "Images": {"image_url": "", "fill_policy": ui.FillPolicy.STRETCH}, "-Margin-": {"margin": 0, "margin_width": 0, "margin_height": 0}, "-Padding-": {"padding": 0, "padding_width": 0, "padding_height": 0}, "-Misc-": {"secondary_padding": 0, "scrollbar_size": 10, "draw_mode": ui.SliderDrawMode.DRAG}, } class StyleTreeDelegate(ui.AbstractItemDelegate): def __init__(self, model: StyleModel): super().__init__() self._add_menu = None self._model = model self._delete_menu = None self._delete_group_menu = None def _show_group_menu(self, b, item: StyleGroupItem): if not b == 1: return if not self._delete_group_menu: self._delete_group_menu = ui.Menu("Delete") self._delete_group_menu.clear() def duplicate_item(): self._model.duplicate_item(item) def delete_item(): self._model.delete_item(item) with self._delete_group_menu: ui.MenuItem("Delete", triggered_fn=delete_item) ui.MenuItem("Duplicate", triggered_fn=duplicate_item) self._delete_group_menu.show() def _show_delete_menu(self, b, item: StyleItem): if not b == 1: return if not self._delete_menu: self._delete_menu = ui.Menu("Delete") self._delete_menu.clear() def delete_item(): self._model.delete_item(item) with self._delete_menu: ui.MenuItem("Delete", triggered_fn=delete_item) self._delete_menu.show() def _show_add_menu(self, x, y, b, m, type: str, item: StyleGroupItem): if not self._add_menu: self._add_menu = ui.Menu("Add") # menu is dynamically built based on type self._add_menu.clear() def add_style(key, value): # this is capture by the closure item.style_dict[key] = value self._model._item_changed(item) self._model.update() # we extact the base type item_type = item.type_name.split(":")[0] if "." in item_type: item_type = item_type.split(".")[0] filtered_style = ClassStyles.get(item_type, None) def add_menu_item(name: str, default): if filtered_style and name not in filtered_style: return ui.MenuItem(name, triggered_fn=lambda key=name, value=default: add_style(key, value)) with self._add_menu: for category, values in STYLE_NAME_DEFAULT.items(): if category[0] == "-" or filtered_style: ui.Separator() for style, default in values.items(): add_menu_item(style, default) else: with ui.Menu(category): for style, default in values.items(): add_menu_item(style, default) self._add_menu.show() def build_branch(self, model, item, column_id, level, expanded): """Create a branch widget that opens or closes subtree""" if column_id == 0: if isinstance(item, StyleGroupItem): with ui.VStack(height=0): ui.Spacer(height=10) with ui.ZStack(width=10 * (level + 1), height=0): ui.Rectangle(height=25) with ui.HStack(width=10 * (level + 1)): ui.Spacer(height=10) ui.Spacer() if model.can_item_have_children(item): with ui.VStack(): ui.Spacer() image_name = "Minus" if expanded else "Plus" ui.Image( f"{ICON_PATH}/{image_name}.svg", width=10, height=10, style={"color": 0xFFCCCCCC}, ) ui.Spacer() ui.Spacer(width=5) else: ui.Spacer(width=20) def build_widget(self, model, item: Union[StyleGroupItem, StyleItem], column_id: int, level, expanded): """Create a widget per column per item""" value_model: ui.AbstractValueModel = model.get_item_value_model(item, column_id) # some cells are empty if not value_model: ui.Spacer() return # Group Instance = Group Title and Add Button if isinstance(item, StyleGroupItem): with ui.VStack(): # small Space before Group Title ui.Spacer(height=10) with ui.ZStack( height=25, mouse_pressed_fn=lambda x, y, b, m, item=item: self._show_group_menu(b, item) ): ui.Rectangle(style={"background_color": 0xFF222222}) with ui.HStack(): ui.Spacer(width=5) with ui.VStack(): ui.Spacer() ui.StringField( value_model, height=20, style={"font_size": 16, "background_color": 0xFF222222} ) ui.Spacer() ui.Spacer(width=5) group_type = model.get_item_value_model(item, 0).as_string with ui.VStack(width=0): ui.Spacer() ui.Button( image_url=f"{ICON_PATH}/Add.svg", width=20, height=20, style={"background_color": 0xFF556655, "border_radius": 5}, mouse_pressed_fn=lambda x, y, b, m, type=group_type, item=item: self._show_add_menu( x, y, b, m, type, item ), ) ui.Spacer() # Style Property Row else: with ui.HStack(height=25, mouse_pressed_fn=lambda x, y, b, m, item=item: self._show_delete_menu(b, item)): ui.Spacer(width=5) with ui.VStack(): ui.Spacer() ui.Label( value_model.as_string, height=0, style={"font_size": 14, "alignment": ui.Alignment.RIGHT_CENTER, "margin_width": 5}, ) ui.Spacer() # Value Model for the Second Columns value_model: ui.AbstractValueModel = model.get_item_value_model(item, 1) with ui.VStack(): ui.Spacer() with ui.HStack(height=0): # key: str = model.get_item_value_model(item, 0).as_string if item.style_type == StylePropertyType.COLOR: # color_model = StyleColorModel(value_model.as_int) ui.ColorWidget(value_model, width=12, height=12) elif item.style_type == StylePropertyType.FLOAT: ui.FloatDrag(value_model).step = 1 elif item.style_type == StylePropertyType.STRING: ui.StringField(value_model) elif item.style_type == StylePropertyType.ENUM: ui.ComboBox(value_model) ui.Spacer(width=20) ui.Spacer()
8,610
Python
37.271111
120
0.483275
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/style/resolved_style.py
__all__ = ["ResolvedStyleWidget"] from typing import Union import omni.ui as ui from .widget_styles import ClassStyles from .style_model import get_property_type, StylePropertyType, StyleColorModel, StyleComboItemModel, get_enum_class class ResolvedStyleWidget: """The Stage widget""" def __init__(self, **kwargs): self._widget = None # self._frame_widget = ui.CollapsableFrame("Resolved Styles", height=0, build_fn=self._build_ui) # with self._frame_widget: self._stack = ui.VStack(height=0, spacing=5) self._class_name_mapping = { "CollapsableFrame": "Frame", "VStack": "Stack", "HStack": "Stack", "ZStack": "Stack", "IntSlider": "AbstractSlider", "FloatSlider": "AbstractSlider", "IntDrag": "AbstractSlider", "FloatDrag": "AbstractSlider", } def set_widget(self, widget: ui.Widget): self._widget = widget self._widget_type = self._widget.__class__.__name__ self._widget_type = self._class_name_mapping.get(self._widget_type, self._widget_type) self._widget_styles = ClassStyles.get(self._widget_type, []) self._build_ui() def _build_ui(self): self._stack.clear() if not self._widget: return with self._stack: ui.Label("Resolved Styles", height=0) ui.Spacer(height=5) for name in self._widget_styles: with ui.HStack(height=0): ui.Spacer(width=10) ui.Label(name, width=150) prop_type = get_property_type(name) if prop_type == StylePropertyType.COLOR: print(ui.Inspector.get_resolved_style(self._widget)) value = False # value: Union[int, bool] = ui.Inspector.get_resolved_style(self._widget.get_resolved_style_value(name) if value: model = StyleColorModel(value) color_widget = ui.ColorWidget(enabled=False) color_widget.model = model else: ui.Label("Default") elif prop_type == StylePropertyType.FLOAT: print(ui.Inspector.get_resolved_style(self._widget)) value = False # value: Union[float, bool] = self._widget.get_resolved_style_value(name) if value: field = ui.FloatField().model field.set_value(value) else: ui.Label("Default") elif prop_type == StylePropertyType.STRING: print(ui.Inspector.get_resolved_style(self._widget)) value = False # value: Union[str, bool] = self._widget.get_resolved_style_value(name) if value: ui.StringField().model.set_value(value) else: ui.Label("Default") elif prop_type == StylePropertyType.ENUM: print(ui.Inspector.get_resolved_style(self._widget)) value = False # value: Union[int, bool] = self._widget.get_resolved_style_value(name) if value: enum_cls = get_enum_class(name) self._model = StyleComboItemModel(enum_cls, value) ui.ComboBox(self._model) else: ui.Label("Default") else: ui.Label("MISSING ... TYPE")
3,885
Python
39.905263
127
0.487259
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/style/style_tree.py
__all__ = ["StyleTreeView"] from typing import Dict, cast from ..tree.inspector_tree import ICON_PATH import omni.ui as ui import omni.kit.app import carb.events from omni.ui_query import OmniUIQuery from .style_model import StyleModel from .style_delegate import StyleTreeDelegate from .resolved_style import ResolvedStyleWidget from .style_model import StyleEnumProperty, StyleColorProperties import json import omni.kit.clipboard def int32_color_to_hex(value: int) -> str: # convert Value from int red = value & 255 green = (value >> 8) & 255 blue = (value >> 16) & 255 alpha = (value >> 24) & 255 def hex_value_only(value: int): hex_value = f"{value:#0{4}x}" return hex_value[2:].upper() hex_color = f"HEX<0x{hex_value_only(alpha)}{hex_value_only(blue)}{hex_value_only(green)}{hex_value_only(red)}>HEX" return hex_color def int_enum_to_constant(value: int, key: str) -> str: result = "" if key == "corner_flag": enum = ui.CornerFlag(value) result = f"UI.CONSTANT<ui.CornerFlag.{enum.name}>UI.CONSTANT" elif key == "alignment": enum = ui.Alignment(value) result = f"UI.CONSTANT<ui.Alignment.{enum.name}>UI.CONSTANT" elif key == "fill_policy": enum = ui.FillPolicy(value) result = f"UI.CONSTANT<ui.FillPolicy.{enum.name}>UI.CONSTANT" elif key == "draw_mode": enum = ui.SliderDrawMode(value) result = f"UI.CONSTANT<ui.SliderDrawMode.{enum.name}>UI.CONSTANT" elif key == "stack_direction": enum = ui.Direction(value) result = f"UI.CONSTANT<ui.Direction.{enum.name}>UI.CONSTANT" return result class StyleTreeView: """The Stage widget""" def __init__(self, **kwargs): self._widget = None self._model = StyleModel(self) self._delegate = StyleTreeDelegate(self._model) self._main_stack = ui.VStack() self._build_ui() app = omni.kit.app.get_app() self._update_sub = app.get_message_bus_event_stream().create_subscription_to_pop( self.on_selection_changed, name="Inspector Selection Changed" ) def on_selection_changed(self, event: carb.events.IEvent): from ..inspector_widget import INSPECTOR_ITEM_SELECTED_ID if event.type == INSPECTOR_ITEM_SELECTED_ID: selection = OmniUIQuery.find_widget(event.payload["item_path"]) if selection: self.set_widget(selection) def toggle_visibility(self): self._main_stack.visible = not self._main_stack.visible def set_widget(self, widget: ui.Widget): self._widget = widget # self._resolved_style.set_widget(widget) self._model.set_widget(widget) self._tree_view.set_expanded(None, True, True) def _build_ui(self): with self._main_stack: ui.Spacer(height=5) with ui.HStack(height=0): ui.Spacer(width=10) ui.Button( image_url=f"{ICON_PATH}/copy.svg", width=20, height=20, style={"margin": 0}, clicked_fn=self._copy_style, ) ui.Label("Styles", height=0, style={"font_size": 16}, alignment=ui.Alignment.CENTER) ui.Button( image_url=f"{ICON_PATH}/Add.svg", style={"margin": 0}, height=20, width=20, clicked_fn=self._add_style, ) ui.Spacer(width=10) ui.Spacer(height=3) ui.Line(height=1, style={"color": 0xFF222222, "border_width": 1}) with ui.HStack(): ui.Spacer(width=5) with ui.VStack(): # ResolvedStyleWidget: Omni.UI API is Broken # self._resolved_style = ResolvedStyleWidget() # ui.Spacer(height=10) ui.Label("Local Styles", height=0) with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style_type_name_override="TreeView.ScrollingFrame", style={"TreeView.ScrollingFrame": {"background_color": 0xFF333333}}, ): self._tree_view = ui.TreeView( self._model, delegate=self._delegate, column_widths=[ui.Fraction(1), 150], header_visible=False, root_visible=False, ) self._tree_view.set_expanded(None, True, True) ui.Spacer(width=5) def _add_style(self): if not self._widget: return style = cast(dict, self._widget.style) if not style: style = {} style["color"] = 0xFF000000 self._widget.set_style(style) self._model.update_cached_style() def _copy_style(self): if self._widget: style: Dict = cast(Dict, self._widget.style) if not style: style = {} has_type_names = False # convert numbers to for key, value in style.items(): if type(value) == dict: has_type_names = True for name, internal_value in value.items(): if name in StyleColorProperties: value[name] = int32_color_to_hex(internal_value) if name in StyleEnumProperty: value[name] = int_enum_to_constant(internal_value, name) else: if key in StyleColorProperties: style[key] = int32_color_to_hex(value) if key in StyleEnumProperty: style[key] = int_enum_to_constant(value, key) if has_type_names: style_json = json.dumps(style, indent=4) else: style_json = json.dumps(style) # remove HEX Markers style_json = style_json.replace('"HEX<', "") style_json = style_json.replace('>HEX"', "") # remove Constant Markers style_json = style_json.replace('"UI.CONSTANT<', "") style_json = style_json.replace('>UI.CONSTANT"', "") omni.kit.clipboard.copy(style_json)
6,562
Python
34.475675
118
0.535812
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/style/widget_styles.py
__all__ = ["ClassStyles"] ClassStyles = { "AbstractField": ["background_selected_color", "color", "padding"], "AbstractSlider": [ "background_color", "border_color", "border_radius", "border_width", "color", "draw_mode", "padding", "secondary_color", "secondary_selected_color", "font_size", ], "Button": [ "background_color", "border_color", "border_radius", "border_width", "color", "padding", "font_size", "stack_direction", ], "CanvasFrame": ["background_color"], "CheckBox": ["background_color", "border_radius", "font_size", "color"], "Circle": ["background_color", "border_color", "border_width"], "ColorWidget": ["background_color", "border_color", "border_radius", "border_width", "color"], "ComboBox": [ "font_size", "background_color", "border_radius", "color", "padding", "padding_height", "padding_width", "secondary_color", "secondary_padding", "secondary_selected_color", "selected_color", ], "DockSpace": ["background_color"], "Frame": ["padding"], "FreeBezierCurve": ["border_width", "color"], "Image": [ "alignment", "border_color", "border_radius", "border_width", "color", "corner_flag", "fill_policy", "image_url", ], "ImageWithProvider": [ "alignment", "border_color", "border_radius", "border_width", "color", "corner_flag", "fill_policy", "image_url", ], "Label": ["padding", "alignment", "color", "font_size"], "Line": ["border_width", "color"], "MainWindow": ["background_color", "Margin_height", "margin_width"], "Menu": [ "background_color", "BackgroundSelected_color", "border_color", "border_radius", "border_width", "color", "padding", "secondary_color", ], "MenuBar": [ "background_color", "BackgroundSelected_color", "border_color", "border_radius", "border_width", "color", "padding", ], "MenuItem": ["BackgroundSelected_color", "color", "secondary_color"], "Plot": [ "background_color", "BackgroundSelected_color", "border_color", "border_radius", "border_width", "color", "secondary_color", "selected_color", ], "ProgressBar": [ "background_color", "border_color", "border_radius", "border_width", "color", "padding", "secondary_color", ], "Rectangle": [ "background_color", "BackgroundGradient_color", "border_color", "border_radius", "border_width", "corner_flag", ], "ScrollingFrame": ["background_color", "ScrollbarSize", "secondary_color"], "Separator": ["color"], "Stack": ["debug_color"], "TreeView": ["background_color", "background_selected_color", "secondary_color", "secondary_selected_color"], "Triangle": ["background_color", "border_color", "border_width"], "Widget": [ "background_color", "border_color", "border_radius", "border_width", "Debug_color", "margin", "margin_height", "margin_width", ], "Window": ["background_color", "border_color", "border_radius", "border_width"], }
3,607
Python
25.725926
113
0.512337
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/tree/inspector_tree.py
__all__ = ["WindowItem", "WindowListModel", "InspectorTreeView"] from typing import List, cast import asyncio import omni.ui as ui import omni.kit.app import carb import carb.events from .inspector_tree_model import InspectorTreeModel, WidgetItem from .inspector_tree_delegate import InspectorTreeDelegate from omni.ui_query import OmniUIQuery from pathlib import Path ICON_PATH = Path(__file__).parent.parent.parent.parent.parent.parent.joinpath("icons") DARK_BACKGROUND = 0xFF333333 class WindowItem(ui.AbstractItem): def __init__(self, window_name: str, display_name: str = ""): super().__init__() self.model = ui.SimpleStringModel(display_name if display_name else window_name) self.window_name = window_name class WindowListModel(ui.AbstractItemModel): def __init__(self): super().__init__() self._current_index = ui.SimpleIntModel() self._current_index.add_value_changed_fn(lambda a: self._item_changed(None)) self._items = [] self._forbidden_windows = ["Inspector"] async def refresh_later(): await omni.kit.app.get_app().next_update_async() self.refresh() asyncio.ensure_future(refresh_later()) def refresh(self): self._items = [] window_list = [] for w in ui.Workspace.get_windows(): if isinstance(w, ui.Window) and not w.title in self._forbidden_windows and w.visible: window_list.append(w) window_list = sorted(window_list, key=lambda a: a.title) for index, w in enumerate(window_list): self._items.append(WindowItem(w.title)) if w.title == "DemoWindow": self._current_index.set_value(index) self._item_changed(None) def get_current_window(self) -> str: index = self.get_item_value_model(None, 0).as_int if not self._items: print ("no other windows available!") return None item = self._items[index] return item.window_name def get_item_children(self, item): return self._items def get_item_value_model(self, item, column_id): if item is None: return self._current_index return item.model class InspectorTreeView: def destroy(self): self._window = None self._frame = None self._model = None self._delegate.set_window(None) def __init__(self, window: ui.Window, update_window_cb: callable, **kwargs): self._delegate = InspectorTreeDelegate() self._preview_window = None self._tree_view = None self._model = None self._sender_id = hash("InspectorTreeView") & 0xFFFFFFFF self._window = window self._frame = window.frame if window else None self._update_window_cb = update_window_cb self._main_stack = ui.VStack() self._update_window(window) self._build_ui() app = omni.kit.app.get_app() self._update_sub_sel = app.get_message_bus_event_stream().create_subscription_to_pop( self.on_selection_changed, name="Inspector Selection Changed" ) self._update_sub_exp = app.get_message_bus_event_stream().create_subscription_to_pop( self.on_expansion_changed, name="Inspector Expand" ) def on_expansion_changed(self, event: carb.events.IEvent): if not self._model: # carb.log_error("NO Model setup") return if event.sender == self._sender_id: # we don't respond to our own changes return from ..inspector_widget import INSPECTOR_ITEM_EXPANDED_ID def set_expansion_state(item, exp_state): for c in item.children: c.expanded = exp_state set_expansion_state(c, exp_state) if event.type == INSPECTOR_ITEM_EXPANDED_ID: expansion_path = OmniUIQuery.find_widget(event.payload["item_path"]) expansion_item = cast(ui.AbstractItem, self._model.get_item_for_widget(expansion_path)) expand = event.payload["expand"] self.set_expanded(expansion_item, expand, True) expansion_item.expanded = expand set_expansion_state(expansion_item, expand) def on_selection_changed(self, event: carb.events.IEvent): if not self._model: # carb.log_error("NO Model setup") return if event.sender == self._sender_id: # we don't respond to our own changes return from ..inspector_widget import INSPECTOR_ITEM_SELECTED_ID if event.type == INSPECTOR_ITEM_SELECTED_ID: selection = OmniUIQuery.find_widget(event.payload["item_path"]) if selection: selection_item, items = cast(ui.AbstractItem, self._model.get_item_with_path_for_widget(selection)) if selection_item: if len(self._tree_view.selection) == 1 and self._tree_view.selection[0] != selection_item: for item in reversed(items): self._tree_view.set_expanded(item, True, False) self._selection = [selection_item] self._tree_view.selection = self._selection def _update_window(self, window: ui.Window): self._window = window self._frame = window.frame if window else None if self._update_window_cb: self._update_window_cb(window) self._model = InspectorTreeModel(window) self._delegate.set_window(window) self._selection: List[WidgetItem] = [] if self._tree_view: self._tree_view.model = self._model def toggle_visibility(self): self._main_stack.visible = not self._main_stack.visible def set_expanded(self, item: WidgetItem, expanded: bool, recursive: bool = False): """ Sets the expansion state of the given item. Args: item (:obj:`WidgetItem`): The item to effect. expanded (bool): True to expand, False to collapse. recursive (bool): Apply state recursively to descendent nodes. Default False. """ if self._tree_view and item: self._tree_view.set_expanded(item, expanded, recursive) def _build_ui(self): with self._main_stack: with ui.ZStack(height=0): ui.Rectangle(style={"background_color": DARK_BACKGROUND}) with ui.VStack(): ui.Spacer(height=5) with ui.HStack(height=0): ui.Spacer(width=5) ui.Label("Windows", height=20, width=0) ui.Spacer(width=10) def combo_changed_fn(model: WindowListModel, item: WindowItem): window_name = model.get_current_window() if window_name: window: ui.Window = ui.Workspace.get_window(window_name) if window: self._update_window(window) self._window_list_model = WindowListModel() self._window_list_model.add_item_changed_fn(combo_changed_fn) ui.ComboBox(self._window_list_model, identifier="WindowListComboBox") ui.Spacer(width=5) def refresh_windows(): self._window_list_model.refresh() ui.Button( image_url=f"{ICON_PATH}/sync.svg", style={"margin": 0}, width=19, height=19, clicked_fn=refresh_windows, ) ui.Spacer(width=5) ui.Spacer(height=10) with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style_type_name_override="TreeView.ScrollingFrame", style={"TreeView.ScrollingFrame": {"background_color": 0xFF23211F}}, ): with ui.VStack(): ui.Spacer(height=5) self._tree_view = ui.TreeView( self._model, delegate=self._delegate, column_widths=[ui.Fraction(1), 40], header_visible=False, root_visible=False, selection_changed_fn=self._widget_selection_changed, identifier="WidgetInspectorTree" ) def _widget_selection_changed(self, selection: list): if len(selection) == 0: self._selection = selection return if not selection[0]: return if len(self._selection) > 0 and self._selection[0] == selection[0]: return self._selection = selection first_widget_path = self._selection[0].path # Send the Selection Changed Message from ..inspector_widget import INSPECTOR_ITEM_SELECTED_ID stream = omni.kit.app.get_app().get_message_bus_event_stream() stream.push(INSPECTOR_ITEM_SELECTED_ID, sender=self._sender_id, payload={"item_path": first_widget_path}) return for a_selection in self._selection: widget: ui.Widget = a_selection.widget print("style", widget.get_style()) print(widget.checked) print(widget.computed_content_width) print(widget.computed_content_height) print(widget.computed_height) print(widget.computed_width) print(widget.width) print(widget.height) print(widget.screen_position_x) print(widget.screen_position_y) properties = ["font_size", "border_width", "border_color", "alignment"] color = widget.get_resolved_style_value("color") if color: print("color", hex(color)) bg_color = widget.get_resolved_style_value("background_color") if bg_color: print("background_color", hex(bg_color)) for a_style in properties: print(a_style, widget.get_resolved_style_value(a_style)) # widget.set_style({"debug_color": 0x1100DD00})
10,521
Python
35.282758
115
0.564015
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/tree/inspector_tree_model.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. __all__ = ["WidgetItem", "InspectorTreeModel"] from typing import Union import omni.ui as ui from omni.ui_query import OmniUIQuery class WidgetItem(ui.AbstractItem): """A single AbstractItemModel item that represents a single prim""" def __init__(self, widget: ui.Widget, path: str): super().__init__() self.widget = widget self.path = path self.children = [] # True when it's necessary to repopulate its children self.populated = False widget_name = path.split("/")[-1] self._widget_name = widget_name # Get Type self._widget_type = str(type(widget)).split(".")[-1] self._widget_type = self._widget_type.split("'")[0] self.type_model = ui.SimpleStringModel(self._widget_type) self.expanded = False def __repr__(self): return f"<Omni::UI Widget '{str(type(self.widget))}'>" def __str__(self): return f"WidgetItem: {self.widget} @ {self.path}" class InspectorTreeModel(ui.AbstractItemModel): """The item model that watches the stage""" def __init__(self, window: ui.Window): """Flat means the root node has all the children and children of children, etc.""" super().__init__() self._root = None self._frame = window.frame if window else None self._window_name = window.title if window else "" self._window = window self._frame_item = WidgetItem(self._frame, f"{self._window_name}//Frame") def get_item_for_widget(self, widget: ui.Widget) -> Union[WidgetItem, None]: def search_for_item(item: WidgetItem, widget: ui.Widget) -> Union[WidgetItem, None]: if item.widget == widget: return item if isinstance(item.widget, ui.Container) or isinstance(item.widget, ui.TreeView): for a_child_item in self.get_item_children(item): matched_item = search_for_item(a_child_item, widget) if matched_item: return matched_item return None return search_for_item(self._frame_item, widget) def get_item_with_path_for_widget(self, widget: ui.Widget): parents = [] def search_for_item(item: WidgetItem, widget: ui.Widget): if item.widget == widget: return item if isinstance(item.widget, ui.Container) or isinstance(item.widget, ui.TreeView): for a_child_item in self.get_item_children(item): matched_item = search_for_item(a_child_item, widget) if matched_item: parents.append(item) return matched_item return None item = search_for_item(self._frame_item, widget) return item, parents def can_item_have_children(self, parentItem: WidgetItem) -> bool: if not parentItem: return True if not parentItem.widget: return True if issubclass(type(parentItem.widget), ui.Container): return True elif issubclass(type(parentItem.widget), ui.TreeView): return True else: return False def get_item_children(self, item: WidgetItem): """Reimplemented from AbstractItemModel""" if item is None: return [self._frame_item] if item.populated: return item.children widget = item.widget # return the children of the Container item.children = [] index = 0 for w in ui.Inspector.get_children(widget): widget_path = OmniUIQuery.get_widget_path(self._window, w) if widget_path: # TODO: There are widgets that have no paths... why? new_item = WidgetItem(w, widget_path) item.children.append(new_item) item.populated = True return item.children def get_item_value_model_count(self, item): """Reimplemented from AbstractItemModel""" return 2 def get_widget_type(self, item): return item._widget_type def get_widget_path(self, item): return item.path def get_item_value_model(self, item, column_id): """Reimplemented from AbstractItemModel""" if item is None: return ui.SimpleStringModel("Window") if column_id == 0: return ui.SimpleStringModel(item._widget_name) if column_id == 1: style = item.widget.style if item and item.widget else None return ui.SimpleBoolModel(not style == None) if column_id == 2: height = item.widget.computed_height return ui.SimpleStringModel("{:10.2f}".format(height))
5,207
Python
33.039215
93
0.604955
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/tree/inspector_tree_delegate.py
__all__ = ["InspectorTreeDelegate"] import os.path import omni.ui as ui import omni.kit.app import carb from .inspector_tree_model import WidgetItem, InspectorTreeModel from pathlib import Path ICON_PATH = Path(__file__).parent.parent.parent.parent.parent.parent.joinpath("icons") class InspectorTreeDelegate(ui.AbstractItemDelegate): def __init__(self): super().__init__() self._context_menu = None self._window_title = None self._icon_alternatives = { "CollapsableFrame": "Frame", "InvisibleButton": "Button", "ImageWithProvider": "Image", "FloatDrag": "FloatField", } def set_window(self, window: ui.Window): if window: self._window_title = window.title def _copy_path(self, item: WidgetItem): try: import omni.kit.clipboard omni.kit.clipboard.copy(item.path) except ImportError: carb.log_warn("Could not import omni.kit.clipboard.") def _expand_nodes(self, item: WidgetItem, expand=False): from ..inspector_widget import INSPECTOR_ITEM_EXPANDED_ID stream = omni.kit.app.get_app().get_message_bus_event_stream() stream.push(INSPECTOR_ITEM_EXPANDED_ID, payload={"item_path": item.path, "expand": expand}) def _show_context_menu(self, button: int, item: WidgetItem): if not self._context_menu: self._context_menu = ui.Menu("Context") self._context_menu.clear() if not button == 1: return def send_selected_message(item: WidgetItem): from ..inspector_widget import INSPECTOR_PREVIEW_CHANGED_ID stream = omni.kit.app.get_app().get_message_bus_event_stream() stream.push( INSPECTOR_PREVIEW_CHANGED_ID, payload={"item_path": item.path, "window_name": self._window_title} ) with self._context_menu: ui.MenuItem("Preview", triggered_fn=lambda item=item: send_selected_message(item)) ui.MenuItem("Copy Path", triggered_fn=lambda item=item: self._copy_path(item)) if item.expanded: ui.MenuItem( "Collapse All", triggered_fn=lambda item=item, expand=False: self._expand_nodes(item, expand) ) else: ui.MenuItem("Expand All", triggered_fn=lambda item=item, expand=True: self._expand_nodes(item, expand)) self._context_menu.show() def build_branch(self, model: InspectorTreeModel, item: WidgetItem, column_id, level, expanded): """Create a branch widget that opens or closes subtree""" if column_id == 0: with ui.HStack(width=25 * (level + 1), height=0, style={"Line": {"color": 0xFFAAAAAA}}): ui.Spacer(width=25 * level + 10) if model.can_item_have_children(item): # ui.Spacer() with ui.VStack(): ui.Spacer() image_name = "Minus" if expanded else "Plus" ui.Image(f"{ICON_PATH}/{image_name}.svg", width=10, height=10, style={"color": 0xFFCCCCCC}) ui.Spacer() else: ui.Spacer(width=10) ui.Spacer() def build_widget(self, model: InspectorTreeModel, item: WidgetItem, column_id, level, expanded): """Create a widget per column per item""" value_model: ui.AbstractValueModel = model.get_item_value_model(item, column_id) widget_type = model.get_widget_type(item) if column_id == 0: with ui.HStack(height=30, mouse_pressed_fn=lambda x, y, b, m, item=item: self._show_context_menu(b, item)): with ui.VStack(width=25): ui.Spacer() icon = f"{widget_type}" if not os.path.isfile(f"{ICON_PATH}/{icon}.svg"): if icon in self._icon_alternatives: icon = self._icon_alternatives[icon] else: carb.log_warn(f"{ICON_PATH}/{icon}.svg not found") icon = "Missing" ui.Image(f"{ICON_PATH}/{icon}.svg", width=25, height=25) ui.Spacer() ui.Spacer(width=10) with ui.VStack(): ui.Spacer() ui.Label( value_model.as_string, height=0, style={"color": 0xFFEEEEEE}, tooltip=model.get_widget_path(item), ) ui.Spacer() elif column_id == 1: # does it contain a Local Style if value_model.as_bool: with ui.HStack(): ui.Label("Style", alignment=ui.Alignment.RIGHT) ui.Spacer(width=5) def build_header(self, column_id): """Create a widget per column per item""" label = "" if column_id == 0: label = "Type" if column_id == 1: label = "Has Style" ui.Label(label, alignment=ui.Alignment.CENTER)
5,239
Python
37.529411
119
0.538271
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/create_widget.py
__all__ = ["get_property_enum_class", "PropertyType", "create_property_widget"] from typing import Tuple, Union, Callable import omni.ui as ui import enum from .widget_model import WidgetModel, WidgetComboItemModel from .widget_builder import PropertyWidgetBuilder def get_property_enum_class(property: str) -> Callable: if property == "direction": return ui.Direction elif property == "alignment": return ui.Alignment elif property == "fill_policy": return ui.FillPolicy elif property == "arc": return ui.Alignment elif property == "size_policy": return ui.CircleSizePolicy elif property == "drag_axis": return ui.Axis else: return ui.Direction class PropertyType(enum.Enum): FLOAT = 0 INT = 1 COLOR3 = 2 BOOL = 3 STRING = 4 DOUBLE3 = 5 INT2 = 6 DOUBLE2 = 7 ENUM = 8 # TODO: Section will be moved to some location like omni.ui.settings # ############################################################################################# def create_property_widget( widget: ui.Widget, property: str, property_type: PropertyType, range_from=0, range_to=0, speed=1, **kwargs ) -> Tuple[Union[ui.Widget, None], Union[ui.AbstractValueModel, None]]: """ Create a UI widget connected with a setting. If ``range_from`` >= ``range_to`` there is no limit. Undo/redo operations are also supported, because changing setting goes through the :mod:`omni.kit.commands` module, using :class:`.ChangeSettingCommand`. Args: setting_path: Path to the setting to show and edit. property_type: Type of the setting to expect. range_from: Limit setting value lower bound. range_to: Limit setting value upper bound. Returns: :class:`ui.Widget` connected with the setting on the path specified. """ property_widget: Union[ui.Widget, None] = None model = None # Create widget to be used for particular type if property_type == PropertyType.INT: model = WidgetModel(widget, property) property_widget = PropertyWidgetBuilder.createIntWidget(model, range_from, range_to, **kwargs) elif property_type == PropertyType.FLOAT: model = WidgetModel(widget, property) property_widget = PropertyWidgetBuilder.createFloatWidget(model, range_from, range_to, **kwargs) elif property_type == PropertyType.BOOL: model = WidgetModel(widget, property) property_widget = PropertyWidgetBuilder.createBoolWidget(model, **kwargs) elif property_type == PropertyType.STRING: model = WidgetModel(widget, property) property_widget = ui.StringField(**kwargs) elif property_type == PropertyType.ENUM: enum_cls = get_property_enum_class(property) model = WidgetComboItemModel(widget, property, enum_cls) property_widget = ui.ComboBox(model, **kwargs) else: print("Couldnt find widget for ", property_type, property) # Do we have any right now? return property_widget, None if property_widget: try: property_widget.model = model except: print(widget, "doesn't have model") return property_widget, model
3,241
Python
34.626373
122
0.650417
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widget_builder.py
__all__ = ["PropertyWidgetBuilder"] import omni.ui as ui LABEL_HEIGHT = 18 HORIZONTAL_SPACING = 4 LABEL_WIDTH = 150 class PropertyWidgetBuilder: @classmethod def _build_reset_button(cls, path) -> ui.Rectangle: with ui.VStack(width=0, height=0): ui.Spacer() with ui.ZStack(width=15, height=15): with ui.HStack(style={"margin_width": 0}): ui.Spacer() with ui.VStack(width=0): ui.Spacer() ui.Rectangle(width=5, height=5, name="reset_invalid") ui.Spacer() ui.Spacer() btn = ui.Rectangle(width=12, height=12, name="reset", tooltip="Click to reset value") btn.visible = False btn.set_mouse_pressed_fn(lambda x, y, m, w, p=path, b=btn: cls._restore_defaults(path, b)) ui.Spacer() return btn @staticmethod def _create_multi_float_drag_with_labels(model, labels, comp_count, **kwargs) -> None: RECT_WIDTH = 13 SPACING = 4 with ui.ZStack(): with ui.HStack(): ui.Spacer(width=RECT_WIDTH) widget_kwargs = {"name": "multivalue", "h_spacing": RECT_WIDTH + SPACING} widget_kwargs.update(kwargs) ui.MultiFloatDragField(model, **widget_kwargs) with ui.HStack(): for i in range(comp_count): if i != 0: ui.Spacer(width=SPACING) label = labels[i] with ui.ZStack(width=RECT_WIDTH + 1): ui.Rectangle(name="vector_label", style={"background_color": label[1]}) ui.Label(label[0], name="vector_label", alignment=ui.Alignment.CENTER) ui.Spacer() @classmethod def createColorWidget(cls, model, comp_count=3, additional_widget_kwargs=None) -> ui.HStack: with ui.HStack(spacing=HORIZONTAL_SPACING) as widget: widget_kwargs = {"min": 0.0, "max": 1.0} if additional_widget_kwargs: widget_kwargs.update(additional_widget_kwargs) # TODO probably need to support "A" if comp_count is 4, but how many assumptions can we make? with ui.HStack(spacing=4): cls._create_multi_float_drag_with_labels( model=model, labels=[("R", 0xFF5555AA), ("G", 0xFF76A371), ("B", 0xFFA07D4F)], comp_count=comp_count, **widget_kwargs, ) widget = ui.ColorWidget(model, width=30, height=0) # cls._create_control_state(model) return widget @classmethod def createVecWidget(cls, model, range_min, range_max, comp_count=3, additional_widget_kwargs=None): widget_kwargs = {"min": range_min, "max": range_max} if additional_widget_kwargs: widget_kwargs.update(additional_widget_kwargs) cls._create_multi_float_drag_with_labels( model=model, labels=[("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F), ("W", 0xFFFFFFFF)], comp_count=comp_count, **widget_kwargs, ) return model @staticmethod def _create_drag_or_slider(drag_widget, slider_widget, **kwargs): if "min" in kwargs and "max" in kwargs: range_min = kwargs["min"] range_max = kwargs["max"] if range_max - range_min < 100: return slider_widget(name="value", **kwargs) else: if "step" not in kwargs: kwargs["step"] = max(0.1, (range_max - range_min) / 1000.0) else: if "step" not in kwargs: kwargs["step"] = 0.1 # If range is too big or no range, don't use a slider widget = drag_widget(name="value", **kwargs) return widget @classmethod def _create_label(cls, attr_name, label_width=150, additional_label_kwargs=None): label_kwargs = { "name": "label", "word_wrap": True, "width": label_width, "height": LABEL_HEIGHT, "alignment": ui.Alignment.LEFT, } if additional_label_kwargs: label_kwargs.update(additional_label_kwargs) ui.Label(attr_name, **label_kwargs) ui.Spacer(width=5) @classmethod def createBoolWidget(cls, model, additional_widget_kwargs=None): widget = None with ui.HStack(): with ui.HStack(style={"margin_width": 0}, width=10): ui.Spacer() widget_kwargs = {"font_size": 16, "height": 16, "width": 16, "model": model} if additional_widget_kwargs: widget_kwargs.update(additional_widget_kwargs) widget = ui.CheckBox(**widget_kwargs, style={"color": 0xFFDDDDDD, "background_color": 0xFF666666}) ui.Spacer() return widget @classmethod def createFloatWidget(cls, model, range_min, range_max, additional_widget_kwargs=None): widget_kwargs = {"model": model} # only set range if range is valid (min < max) if range_min < range_max: widget_kwargs["min"] = range_min widget_kwargs["max"] = range_max if additional_widget_kwargs: widget_kwargs.update(additional_widget_kwargs) widget_kwargs.update(style={"secondary_color": 0xFF444444}) return cls._create_drag_or_slider(ui.FloatDrag, ui.FloatSlider, **widget_kwargs) @classmethod def createIntWidget(cls, model, range_min, range_max, additional_widget_kwargs=None): widget_kwargs = {"model": model} # This passes the model into the widget # only set range if range is valid (min < max) if range_min < range_max: widget_kwargs["min"] = range_min widget_kwargs["max"] = range_max if additional_widget_kwargs: widget_kwargs.update(additional_widget_kwargs) widget_kwargs.update(style={"secondary_color": 0xFF444444}) return cls._create_drag_or_slider(ui.IntDrag, ui.IntSlider, **widget_kwargs)
6,266
Python
39.694805
114
0.555538
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widget_model.py
__all__ = ["WidgetModel", "WidgetComboValueModel", "WidgetComboNameValueItem", "WidgetComboItemModel"] from typing import Callable import omni.ui as ui class WidgetModel(ui.AbstractValueModel): """ Model for widget Properties """ def __init__(self, widget: ui.Widget, property: str, dragable=True): """ Args: """ super().__init__() self._widget = widget self._property = property self.initialValue = None self._reset_button = None self._editing = False # def _on_change(owner, value, event_type) -> None: # if event_type == carb.settings.ChangeEventType.CHANGED: # owner._on_dirty() # if owner._editing == False: # owner._update_reset_button() # def begin_edit(self) -> None: # self._editing = True # ui.AbstractValueModel.begin_edit(self) # self.initialValue = self._settings.get(self._path) # def end_edit(self) -> None: # ui.AbstractValueModel.end_edit(self) # omni.kit.commands.execute( # "ChangeSettingCommand", path=self._path, value=self._settings.get(self._path), prev=self.initialValue # ) # self._update_reset_button() # self._editing = False def get_value_as_string(self) -> str: return str(self._widget.__getattribute__(self._property)) def get_value_as_float(self) -> float: return self._widget.__getattribute__(self._property) def get_value_as_bool(self) -> bool: return self._widget.__getattribute__(self._property) def get_value_as_int(self) -> int: # print("here int ") return self._widget.__getattribute__(self._property) def set_value(self, value): print(type(self._widget.__getattribute__(self._property))) if type(self._widget.__getattribute__(self._property)) == ui.Length: print("Is Length") self._widget.__setattr__(self._property, ui.Pixel(value)) else: self._widget.__setattr__(self._property, value) self._value_changed() def destroy(self): self._widget = None self._reset_button = None class WidgetComboValueModel(ui.AbstractValueModel): """ Model to store a pair (label, value of arbitrary type) for use in a ComboBox """ def __init__(self, key, value): """ Args: value: the instance of the Style value """ ui.AbstractValueModel.__init__(self) self.key = key self.value = value def __repr__(self): return f'"WidgetComboValueModel name:{self.key} value:{int(self.value)}"' def get_value_as_string(self) -> str: """ this is called to get the label of the combo box item """ return self.key def get_style_value(self) -> int: """ we call this to get the value of the combo box item """ return int(self.value) class WidgetComboNameValueItem(ui.AbstractItem): def __init__(self, key, value): super().__init__() self.model = WidgetComboValueModel(key, value) def __repr__(self): return f'"StyleComboNameValueItem {self.model}"' class WidgetComboItemModel(ui.AbstractItemModel): """ Model for a combo box - for each setting we have a dictionary of key, values """ def __init__(self, widget: ui.Widget, property: str, class_obj: Callable): super().__init__() self._widget = widget self._property = property self._class = class_obj self._items = [] self._default_value = self._widget.__getattribute__(property) default_index = 0 current_index = 0 for key, value in class_obj.__members__.items(): if self._default_value == value: default_index = current_index self._items.append(WidgetComboNameValueItem(key, value)) current_index += 1 self._current_index = ui.SimpleIntModel(default_index) self._current_index.add_value_changed_fn(self._current_index_changed) def get_current_value(self): return self._items[self._current_index.as_int].model.get_style_value() def _current_index_changed(self, model): self._item_changed(None) value = self.get_current_value() self._widget.__setattr__(self._property, self._class(value)) def get_item_children(self, item): return self._items def get_item_value_model(self, item, column_id: int): if item is None: return self._current_index return item.model
4,648
Python
29.993333
115
0.593589
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/inspector_property_widget.py
__all__ = ["InspectorPropertyWidget"] import omni.ui as ui import carb.events import omni.kit.app from omni.ui_query import OmniUIQuery from .widgets.button import ButtonPropertyFrame from .widgets.canvas_frame import CanvasPropertyFrame from .widgets.circle import CirclePropertyFrame from .widgets.collapsable_frame import CollapsableFramePropertyFrame from .widgets.combox_box import ComboBoxPropertyFrame from .widgets.frame import FramePropertyFrame from .widgets.grid import GridPropertyFrame from .widgets.image import ImagePropertyFrame from .widgets.image_with_provider import ImageWithProviderPropertyFrame from .widgets.label import LabelPropertyFrame from .widgets.line import LinePropertyFrame from .widgets.placer import PlacerPropertyFrame from .widgets.scrolling_frame import ScrollingFramePropertyFrame from .widgets.slider import SliderPropertyFrame from .widgets.stack import StackPropertyFrame from .widgets.string_field import StringFieldPropertyFrame from .widgets.tree_view import TreeViewPropertyFrame from .widgets.triangle import TrianglePropertyFrame from .widgets.widget import WidgetPropertyFrame class InspectorPropertyWidget: """The Stage widget""" def __init__(self, **kwargs): self._widget = None self._main_stack = ui.VStack( spacing=5, width=300, style={ "VStack": {"margin_width": 10}, "CollapsableFrame": {"background_color": 0xFF2A2A2A, "secondary_color": 0xFF2A2A2A}, }, ) self._build_ui() app = omni.kit.app.get_app() self._update_sub = app.get_message_bus_event_stream().create_subscription_to_pop( self.on_selection_changed, name="Inspector Selection Changed" ) def on_selection_changed(self, event: carb.events.IEvent): from ..inspector_widget import INSPECTOR_ITEM_SELECTED_ID if event.type == INSPECTOR_ITEM_SELECTED_ID: selection = OmniUIQuery.find_widget(event.payload["item_path"]) if selection: self.set_widget(selection) def toggle_visibility(self): self._main_stack.visible = not self._main_stack.visible def set_widget(self, widget: ui.Widget): self._widget = widget self._build_ui() def _build_ui(self): self._main_stack.clear() with self._main_stack: ui.Spacer(height=0) ui.Label("Properties", height=0, style={"font_size": 16}, alignment=ui.Alignment.CENTER) ui.Spacer(height=0) if not self._widget: return if isinstance(self._widget, ui.Label): LabelPropertyFrame("Label", self._widget) elif isinstance(self._widget, ui.Stack): StackPropertyFrame("Stack", self._widget) elif isinstance(self._widget, ui.Button): ButtonPropertyFrame("Button", self._widget) elif isinstance(self._widget, ui.Image): ImagePropertyFrame("Image", self._widget) elif isinstance(self._widget, ui.CanvasFrame): CanvasPropertyFrame("CanvasFrame", self._widget) elif isinstance(self._widget, ui.AbstractSlider): SliderPropertyFrame("Slider", self._widget) elif isinstance(self._widget, ui.Circle): CirclePropertyFrame("Circle", self._widget) elif isinstance(self._widget, ui.ComboBox): ComboBoxPropertyFrame("ComboBox", self._widget) elif isinstance(self._widget, ui.ScrollingFrame): ScrollingFramePropertyFrame("ScrollingFrame", self._widget) FramePropertyFrame("Frame", self._widget) elif isinstance(self._widget, ui.CollapsableFrame): CollapsableFramePropertyFrame("CollapsableFrame", self._widget) FramePropertyFrame("Frame", self._widget) elif isinstance(self._widget, ui.Frame): FramePropertyFrame("Frame", self._widget) elif isinstance(self._widget, ui.Grid): GridPropertyFrame("Grid", self._widget) elif isinstance(self._widget, ui.ImageWithProvider): ImageWithProviderPropertyFrame("ImageWithProvider", self._widget) elif isinstance(self._widget, ui.Line): LinePropertyFrame("Line", self._widget) elif isinstance(self._widget, ui.Placer): PlacerPropertyFrame("Placer", self._widget) elif isinstance(self._widget, ui.ScrollingFrame): ScrollingFramePropertyFrame("ScrollingFrame", self._widget) elif isinstance(self._widget, ui.StringField): StringFieldPropertyFrame("StringField", self._widget) elif isinstance(self._widget, ui.TreeView): TreeViewPropertyFrame("TreeView", self._widget) elif isinstance(self._widget, ui.Triangle): TrianglePropertyFrame("Triangle", self._widget) WidgetPropertyFrame("Widget", self._widget)
5,087
Python
41.049586
100
0.653823
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/base_frame.py
__all__ = ["WidgetCollectionFrame"] # from typing import Union, Any from .create_widget import PropertyType import omni.ui as ui from .create_widget import create_property_widget from .widget_builder import PropertyWidgetBuilder class WidgetCollectionFrame: parents = {} # For later deletion of parents def __init__(self, frame_label: str, widget: ui.Widget) -> None: self._models = [] self._widget = widget self._frame_widget = ui.CollapsableFrame(frame_label, height=0, build_fn=self.build_ui) def destroy(self): """""" self._frame_widget.clear() self._frame_widget = None def build_ui(self): with ui.VStack(height=0, spacing=5, style={"VStack": {"margin_width": 10}}): ui.Spacer(height=5) self._build_ui() ui.Spacer(height=5) def _rebuild(self): if self._frame_widget: self._frame_widget.rebuild() def _add_property( self, widget: ui.Widget, property: str, property_type: PropertyType, range_from=0, range_to=0, speed=1, has_reset=True, tooltip="", label_width=150, ): with ui.HStack(skip_draw_when_clipped=True): PropertyWidgetBuilder._create_label(property, label_width=label_width) property_widget, model = create_property_widget( widget, property, property_type, range_from, range_to, speed ) self._models.append(model) # if has_reset: # button = PropertyWidgetBuilder._build_reset_button(path) # model.set_reset_button(button) return property_widget, model # def _add_setting_combo( # self, name: str, path: str, items: Union[list, dict], callback=None, has_reset=True, tooltip="" # ): # with ui.HStack(skip_draw_when_clipped=True): # PropertyWidgetBuilder._create_label(name, path, tooltip) # property_widget, model = create_property_widget_combo(widget, items) # #if has_reset: # # button = PropertyWidgetBuilder._build_reset_button(path) # # model.set_reset_button(button) # return property_widget def _build_ui(self): """ virtual function that will be called in the Collapsable frame """ pass
2,377
Python
29.883116
105
0.595709
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/button.py
__all__ = ["ButtonPropertyFrame"] import omni.ui as ui from ..base_frame import WidgetCollectionFrame from ..create_widget import PropertyType class ButtonPropertyFrame(WidgetCollectionFrame): def __init__(self, frame_label: str, widget: ui.Widget) -> None: super().__init__(frame_label, widget) def _build_ui(self): self._add_property(self._widget, "image_url", PropertyType.STRING) self._add_property(self._widget, "text", PropertyType.STRING) self._add_property(self._widget, "image_width", PropertyType.FLOAT) self._add_property(self._widget, "image_height", PropertyType.FLOAT) self._add_property(self._widget, "spacing", PropertyType.FLOAT)
712
Python
29.999999
76
0.688202
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/canvas_frame.py
__all__ = ["CanvasPropertyFrame"] import omni.ui as ui from ..base_frame import WidgetCollectionFrame from ..create_widget import PropertyType class CanvasPropertyFrame(WidgetCollectionFrame): def __init__(self, frame_label: str, widget: ui.Widget) -> None: super().__init__(frame_label, widget) def _build_ui(self): self._add_property(self._widget, "zoom", PropertyType.FLOAT, range_from=0) self._add_property(self._widget, "pan_x", PropertyType.FLOAT) self._add_property(self._widget, "pan_y", PropertyType.FLOAT) self._add_property(self._widget, "draggable", PropertyType.BOOL)
636
Python
30.849998
82
0.685535
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/tree_view.py
__all__ = ["TreeViewPropertyFrame"] import omni.ui as ui from ..base_frame import WidgetCollectionFrame from ..create_widget import PropertyType class TreeViewPropertyFrame(WidgetCollectionFrame): def __init__(self, frame_label: str, widget: ui.Widget) -> None: super().__init__(frame_label, widget) def _build_ui(self): self._add_property(self._widget, "columns_resizable", PropertyType.BOOL) self._add_property(self._widget, "header_visible", PropertyType.BOOL) self._add_property(self._widget, "root_visible", PropertyType.BOOL) self._add_property(self._widget, "expand_on_branch_click", PropertyType.BOOL) self._add_property(self._widget, "keep_alive", PropertyType.BOOL) self._add_property(self._widget, "keep_expanded", PropertyType.BOOL) self._add_property(self._widget, "drop_between_items", PropertyType.BOOL)
897
Python
39.81818
85
0.696767
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/grid.py
__all__ = ["GridPropertyFrame"] import omni.ui as ui from ..base_frame import WidgetCollectionFrame from ..create_widget import PropertyType class GridPropertyFrame(WidgetCollectionFrame): def __init__(self, frame_label: str, widget: ui.Widget) -> None: super().__init__(frame_label, widget) def _build_ui(self): self._add_property(self._widget, "columnWidth", PropertyType.FLOAT) self._add_property(self._widget, "rowHeight", PropertyType.FLOAT) self._add_property(self._widget, "columnCount", PropertyType.INT, range_from=0) self._add_property(self._widget, "rowCount", PropertyType.INT, range_from=0)
659
Python
31.999998
87
0.693475
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/slider.py
__all__ = ["SliderPropertyFrame"] import omni.ui as ui from ..base_frame import WidgetCollectionFrame from ..create_widget import PropertyType class SliderPropertyFrame(WidgetCollectionFrame): def __init__(self, frame_label: str, widget: ui.Widget) -> None: super().__init__(frame_label, widget) def _build_ui(self): self._add_property(self._widget, "min", PropertyType.INT) self._add_property(self._widget, "max", PropertyType.INT)
471
Python
26.764704
68
0.687898
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/frame.py
__all__ = ["FramePropertyFrame"] import omni.ui as ui from ..base_frame import WidgetCollectionFrame from ..create_widget import PropertyType class FramePropertyFrame(WidgetCollectionFrame): def __init__(self, frame_label: str, widget: ui.Widget) -> None: super().__init__(frame_label, widget) def _build_ui(self): self._add_property(self._widget, "horizontal_clipping", PropertyType.BOOL) self._add_property(self._widget, "vertical_clipping", PropertyType.BOOL) self._add_property(self._widget, "separate_window", PropertyType.BOOL)
580
Python
31.277776
82
0.701724
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/image.py
__all__ = ["ImagePropertyFrame"] import omni.ui as ui from ..base_frame import WidgetCollectionFrame from ..create_widget import PropertyType class ImagePropertyFrame(WidgetCollectionFrame): def __init__(self, frame_label: str, widget: ui.Widget) -> None: super().__init__(frame_label, widget) def _build_ui(self): self._add_property(self._widget, "source_url", PropertyType.STRING, label_width=80) self._add_property(self._widget, "alignment", PropertyType.ENUM, label_width=80) self._add_property(self._widget, "fill_policy", PropertyType.ENUM, label_width=80)
609
Python
32.888887
91
0.697865
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/string_field.py
__all__ = ["StringFieldPropertyFrame"] import omni.ui as ui from ..base_frame import WidgetCollectionFrame from ..create_widget import PropertyType class StringFieldPropertyFrame(WidgetCollectionFrame): def __init__(self, frame_label: str, widget: ui.Widget) -> None: super().__init__(frame_label, widget) def _build_ui(self): self._add_property(self._widget, "password_mode", PropertyType.BOOL) self._add_property(self._widget, "read_only", PropertyType.BOOL) self._add_property(self._widget, "multiline", PropertyType.BOOL)
572
Python
30.833332
76
0.699301
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/collapsable_frame.py
__all__ = ["CollapsableFramePropertyFrame"] import omni.ui as ui from ..base_frame import WidgetCollectionFrame from ..create_widget import PropertyType class CollapsableFramePropertyFrame(WidgetCollectionFrame): def __init__(self, frame_label: str, widget: ui.Widget) -> None: super().__init__(frame_label, widget) def _build_ui(self): self._add_property(self._widget, "collapsed", PropertyType.BOOL) self._add_property(self._widget, "title", PropertyType.STRING) self._add_property(self._widget, "alignment", PropertyType.ENUM)
576
Python
31.055554
72
0.704861
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/placer.py
__all__ = ["PlacerPropertyFrame"] import omni.ui as ui from ..base_frame import WidgetCollectionFrame from ..create_widget import PropertyType class PlacerPropertyFrame(WidgetCollectionFrame): def __init__(self, frame_label: str, widget: ui.Widget) -> None: super().__init__(frame_label, widget) def _build_ui(self): self._add_property(self._widget, "offset_x", PropertyType.FLOAT) self._add_property(self._widget, "offset_y", PropertyType.FLOAT) self._add_property(self._widget, "draggable", PropertyType.BOOL) self._add_property(self._widget, "drag_axis", PropertyType.ENUM) self._add_property(self._widget, "stable_size", PropertyType.BOOL)
705
Python
36.157893
74
0.689362
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/scrolling_frame.py
__all__ = ["ScrollingFramePropertyFrame"] import omni.ui as ui from ..base_frame import WidgetCollectionFrame from ..create_widget import PropertyType class ScrollingFramePropertyFrame(WidgetCollectionFrame): def __init__(self, frame_label: str, widget: ui.Widget) -> None: super().__init__(frame_label, widget) def _build_ui(self): self._add_property(self._widget, "scroll_x", PropertyType.FLOAT) self._add_property(self._widget, "scroll_y", PropertyType.FLOAT) self._add_property(self._widget, "horizontal_scrollbar_policy", PropertyType.ENUM) self._add_property(self._widget, "vertical_scrollbar_policy", PropertyType.ENUM)
681
Python
34.894735
90
0.707783
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/label.py
__all__ = ["LabelPropertyFrame"] import omni.ui as ui from ..base_frame import WidgetCollectionFrame from ..create_widget import PropertyType class LabelPropertyFrame(WidgetCollectionFrame): def __init__(self, frame_label: str, widget: ui.Widget) -> None: super().__init__(frame_label, widget) def _build_ui(self): self._add_property(self._widget, "text", PropertyType.STRING) self._add_property(self._widget, "alignment", PropertyType.ENUM) self._add_property(self._widget, "word_wrap", PropertyType.BOOL) self._add_property(self._widget, "elided_text", PropertyType.BOOL)
628
Python
32.105261
74
0.68949
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/circle.py
__all__ = ["CirclePropertyFrame"] import omni.ui as ui from ..base_frame import WidgetCollectionFrame from ..create_widget import PropertyType class CirclePropertyFrame(WidgetCollectionFrame): def __init__(self, frame_label: str, widget: ui.Widget) -> None: super().__init__(frame_label, widget) def _build_ui(self): self._add_property(self._widget, "radius", PropertyType.FLOAT, range_from=0) self._add_property(self._widget, "alignment", PropertyType.ENUM) self._add_property(self._widget, "arc", PropertyType.ENUM) self._add_property(self._widget, "size_policy", PropertyType.ENUM)
640
Python
31.049998
84
0.689062
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/widget.py
__all__ = ["WidgetPropertyFrame"] import omni.ui as ui from ..base_frame import WidgetCollectionFrame from ..create_widget import PropertyType class WidgetPropertyFrame(WidgetCollectionFrame): def __init__(self, frame_label: str, widget: ui.Widget) -> None: super().__init__(frame_label, widget) def _build_ui(self): self._add_property(self._widget, "width", PropertyType.FLOAT, 0, 2000) self._add_property(self._widget, "height", PropertyType.FLOAT, 0, 2000) self._add_property(self._widget, "tooltip_offset_x", PropertyType.FLOAT, 0, 2000) self._add_property(self._widget, "tooltip_offset_y", PropertyType.FLOAT, 0, 2000) ui.Line(height=2, style={"color": 0xFF666666}) self._add_property(self._widget, "name", PropertyType.STRING) ui.Line(height=2, style={"color": 0xFF666666}) self._add_property(self._widget, "checked", PropertyType.BOOL) self._add_property(self._widget, "enabled", PropertyType.BOOL) self._add_property(self._widget, "selected", PropertyType.BOOL) self._add_property(self._widget, "opaque_for_mouse_events", PropertyType.BOOL) self._add_property(self._widget, "visible", PropertyType.BOOL) self._add_property(self._widget, "skip_draw_when_clipped", PropertyType.BOOL) ui.Spacer(height=10) ui.Line(height=5, style={"color": 0xFF666666, "border_width": 5}) ui.Label("Read Only", alignment=ui.Alignment.CENTER) self._add_property(self._widget, "computed_width", PropertyType.FLOAT, 0, 2000) self._add_property(self._widget, "computed_height", PropertyType.FLOAT, 0, 2000) ui.Line(height=2, style={"color": 0xFF666666}) self._add_property(self._widget, "computed_content_width", PropertyType.FLOAT, 0, 2000) self._add_property(self._widget, "computed_content_height", PropertyType.FLOAT, 0, 2000) ui.Line(height=2, style={"color": 0xFF666666}) self._add_property(self._widget, "screen_position_x", PropertyType.FLOAT, 0, 2000) self._add_property(self._widget, "screen_position_y", PropertyType.FLOAT, 0, 2000)
2,156
Python
39.698112
96
0.667904
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/tests/test_ui.py
import omni.kit.test import omni.kit.window.inspector.inspector_window from omni.kit import ui_test class TestInspectorWindow(omni.kit.test.AsyncTestCase): @classmethod def setUpClass(cls): cls.inspector_window = omni.kit.window.inspector.inspector_window.InspectorWindow() async def setUp(self): self.window_name = self.inspector_window._window.title @classmethod def tearDownClass(cls) -> None: cls.inspector_window._window.destroy() async def test_window_list(self): ''' Check that the main combox box is doing the right thing There's a bit of an ordering assumption going on ''' ui_window = ui_test.find(self.window_name) widgets = ui_window.find_all("**/WindowListComboBox") self.assertTrue(len(widgets) == 1) combo_box = widgets[0].widget self.assertTrue(isinstance(combo_box, omni.ui.ComboBox)) # Make sure render settings is set combo_box.model.get_item_value_model(None, 0).set_value(0) window_name = combo_box.model.get_current_window() self.assertEqual(window_name, "Render Settings") # Set to Stage window combo_box.model.get_item_value_model(None, 0).set_value(1) window_name = combo_box.model.get_current_window() self.assertEqual(window_name, "Stage") await omni.kit.app.get_app().next_update_async() async def test_tree_expansion(self): # make sure render settings is the current window ui_window = ui_test.find(self.window_name) widgets = ui_window.find_all("**/WindowListComboBox") combo_box = widgets[0].widget combo_box.model.get_item_value_model(None, 0).set_value(0) widgets = ui_window.find_all("**/WidgetInspectorTree") self.assertTrue(len(widgets) == 1) tree_items = widgets[0].find_all("**") self.assertTrue(len(tree_items) == 20, f"actually was {len(tree_items)}") # Switch to Stage Window combo_box.model.get_item_value_model(None, 0).set_value(1) widgets = ui_window.find_all("**/WidgetInspectorTree") self.assertTrue(len(widgets) == 1) tree_items = widgets[0].find_all("**") self.assertTrue(len(tree_items) == 17, f"actually was {len(tree_items)}") async def test_tree_basic_content(self): # make sure render settings is the current window ui_window = ui_test.find(self.window_name) widgets = ui_window.find_all("**/WindowListComboBox") combo_box = widgets[0].widget combo_box.model.get_item_value_model(None, 0).set_value(0) widgets = ui_window.find_all("**/WidgetInspectorTree") self.assertTrue(len(widgets) == 1) tree_items = widgets[0].find_all("**") labels = [t.widget for t in tree_items if isinstance(t.widget, omni.ui.Label)] self.assertTrue(len(labels) == 2) self.assertTrue(labels[0].text == "Frame") self.assertTrue(labels[1].text == "Style") async def test_styles(self): ui_window = ui_test.find(self.window_name) buttons = ui_window.find_all("**/ToolButton[*]") # enable style for button in buttons: if button.widget.text == "Style": await button.click() await ui_test.wait_n_updates(2) trees = ui_window.find_all("**/WidgetInspectorTree") self.assertTrue(len(trees) == 1) tree_items = trees[0].find_all("**") labels = [t for t in tree_items if isinstance(t.widget, omni.ui.Label)] for label in labels: if label.widget.text == "Frame": await label.click() await ui_test.wait_n_updates(2) # check there is colorwidget widgets created colorwidgets = ui_window.find_all("**/ColorWidget[*]") self.assertTrue(len(colorwidgets) > 0)
3,881
Python
36.68932
91
0.627416
omniverse-code/kit/exts/omni.kit.documentation.builder/scripts/generate_docs_for_sphinx.py
import argparse import asyncio import logging import carb import omni.kit.app import omni.kit.documentation.builder logger = logging.getLogger(__name__) _app_ready_sub = None def main(): parser = argparse.ArgumentParser() parser.add_argument( "ext_id", help="Extension id (name-version).", ) parser.add_argument( "output_path", help="Path to output generated files to.", ) options = parser.parse_args() async def _generate_and_exit(options): # Skip 2 updates to make sure all extensions loaded and initialized await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() try: result = omni.kit.documentation.builder.generate_for_sphinx(options.ext_id, options.output_path) except Exception as e: # pylint: disable=broad-except carb.log_error(f"Failed to generate docs for sphinx: {e}") for _ in range(5): await omni.kit.app.get_app().next_update_async() returncode = 0 if result else 33 omni.kit.app.get_app().post_quit(returncode) def on_app_ready(e): global _app_ready_sub _app_ready_sub = None asyncio.ensure_future(_generate_and_exit(options)) app = omni.kit.app.get_app() if app.is_app_ready(): on_app_ready(None) else: global _app_ready_sub _app_ready_sub = app.get_startup_event_stream().create_subscription_to_pop_by_type( omni.kit.app.EVENT_APP_READY, on_app_ready, name="omni.kit.documentation.builder generate_docs_for_sphinx" ) if __name__ == "__main__": main()
1,675
Python
26.475409
118
0.628657
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_capture.py
# Copyright (c) 2018-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__ = ["DocumentationBuilderCapture"] import asyncio import omni.appwindow import omni.kit.app import omni.kit.imgui_renderer import omni.kit.renderer.bind import omni.renderer_capture import omni.ui as ui class DocumentationBuilderCapture: r""" Captures the omni.ui widgets to the image file. Works like this: with Capture("c:\temp\1.png", 600, 600): ui.Button("Hello World") """ def __init__(self, path: str, width: int, height: int, window_name: str = "Capture Window"): self._path: str = path self._dpi = ui.Workspace.get_dpi_scale() self._width: int = int(width * self._dpi) self._height: int = int(height * self._dpi) self._window_name: str = window_name # Interfaces self._app_window_factory = omni.appwindow.acquire_app_window_factory_interface() self._renderer = omni.kit.renderer.bind.acquire_renderer_interface() self._imgui_renderer = omni.kit.imgui_renderer.acquire_imgui_renderer_interface() self._renderer_capture = omni.renderer_capture.acquire_renderer_capture_interface() self._virtual_app_window = None self._window = None def __enter__(self): # Create virtual OS window self._virtual_app_window = self._app_window_factory.create_window_by_type(omni.appwindow.WindowType.VIRTUAL) self._virtual_app_window.startup_with_desc( title=self._window_name, width=self._width, height=self._height, scale_to_monitor=False, dpi_scale_override=1.0, ) self._imgui_renderer.attach_app_window(self._virtual_app_window) # Create omni.ui window self._window = ui.Window(self._window_name, flags=ui.WINDOW_FLAGS_NO_TITLE_BAR, padding_x=0, padding_y=0) self._window.move_to_app_window(self._virtual_app_window) self._window.width = self._width self._window.height = self._height # Enter the window frame self._window.frame.__enter__() def __exit__(self, exc_type, exc_val, exc_tb): # Exit the window frame self._window.frame.__exit__(exc_type, exc_val, exc_tb) # Capture and detach at the next frame asyncio.ensure_future( DocumentationBuilderCapture.__capture_detach( self._renderer_capture, self._path, self._renderer, self._virtual_app_window, self._window ) ) @staticmethod async def __capture_detach(renderer_capture, path, renderer, iappwindow, window): # The next frame await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() # Capture renderer_capture.capture_next_frame_texture(path, renderer.get_framebuffer_texture(iappwindow), iappwindow) await omni.kit.app.get_app().next_update_async() # Detach renderer.detach_app_window(iappwindow)
3,392
Python
36.7
116
0.659788
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_window.py
# Copyright (c) 2018-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__ = ["DocumentationBuilderWindow"] import weakref import carb import omni.ui as ui from omni.kit.widget.filebrowser import FileBrowserItem from omni.kit.window.filepicker import FilePickerDialog from .documentation_capture import DocumentationBuilderCapture from .documentation_catalog import DocumentationBuilderCatalog from .documentation_md import DocumentationBuilderMd from .documentation_page import DocumentationBuilderPage from .documentation_style import get_style class DocumentationBuilderWindow(ui.Window): """The window with the documentation""" def __init__(self, title: str, **kwargs): """ ### Arguments `title: str` The title of the window. `filenames: List[str]` The list of .md files to process. `show_catalog: bool` Show catalog pane (default True) """ self._pages = [] self._catalog = None self.__content_frame = None self.__content_page = None self.__source_filenames = kwargs.pop("filenames", []) self._show_catalog = kwargs.pop("show_catalog", True) if "width" not in kwargs: kwargs["width"] = 1200 if "height" not in kwargs: kwargs["height"] = 720 if "flags" not in kwargs: kwargs["flags"] = ui.WINDOW_FLAGS_NO_SCROLL_WITH_MOUSE | ui.WINDOW_FLAGS_NO_SCROLLBAR super().__init__(title, **kwargs) self._set_style() self.frame.set_build_fn(self.__build_window) self.__pick_folder_dialog = None def get_page_names(self): """Names of all the pages to use in `set_page`""" return [p.name for p in self._pages] def set_page(self, name: str = None, scroll_to: str = None): """ Set current page ### Arguments `name: str` The name of the page to switch to. If None, it will set the first page. `scroll_to: str` The name of the section to scroll to. """ if self.__content_page and self.__content_page.name == name: self.__content_page.scroll_to(scroll_to) return if name is None: page = self._pages[0] else: page = next((p for p in self._pages if p.name == name), None) if page: if self.__content_page: self.__content_page.destroy() with self.__content_frame: self.__content_page = DocumentationBuilderPage(page, scroll_to) def generate_for_sphinx(self, path: str): """ Produce the set of files and screenshots readable by Sphinx. ### Arguments `path: str` The path to produce the files. """ for page in self._pages: for code_block in page.code_blocks: image_file = f"{path}/{code_block['name']}.png" height = int(code_block["height"] or 200) with DocumentationBuilderCapture(image_file, 800, height): with ui.ZStack(): # Background ui.Rectangle(name="code_background") # The code with ui.VStack(): # flake8: noqa: PLW0212 self.__content_page._execute_code(code_block["code"]) carb.log_info(f"[omni.docs] Generated image: '{image_file}'") md_file = f"{path}/{page.name}.md" with open(md_file, "w", encoding="utf-8") as f: f.write(page.source) carb.log_info(f"[omni.docs] Generated md file: '{md_file}'") def destroy(self): if self.__pick_folder_dialog: self.__pick_folder_dialog.destroy() self.__pick_folder_dialog = None if self._catalog: self._catalog.destroy() self._catalog = None for page in self._pages: page.destroy() self._pages = [] if self.__content_page: self.__content_page.destroy() self.__content_page = None self.__content_frame = None super().destroy() @staticmethod def get_style(): """ Deprecated: use omni.kit.documentation.builder.get_style() """ return get_style() def _set_style(self): self.frame.set_style(get_style()) def __build_window(self): """Called to build the widgets of the window""" self.__reload_pages() def __on_export(self): """Open Pick Folder dialog to add compounds""" if self.__pick_folder_dialog: self.__pick_folder_dialog.destroy() self.__pick_folder_dialog = FilePickerDialog( "Pick Output Folder", apply_button_label="Use This Folder", click_apply_handler=self.__on_apply_folder, item_filter_options=["All Folders (*)"], item_filter_fn=self.__on_filter_folder, ) def __on_apply_folder(self, filename: str, root_path: str): """Called when the user press "Use This Folder" in the pick folder dialog""" self.__pick_folder_dialog.hide() self.generate_for_sphinx(root_path) @staticmethod def __on_filter_folder(item: FileBrowserItem) -> bool: """Used by pick folder dialog to hide all the files""" return item.is_folder def __reload_pages(self): """Called to reload all the pages""" # Properly destroy all the past pages for page in self._pages: page.destroy() self._pages = [] # Reload the pages at the drawing time for page_source in self.__source_filenames: if page_source.endswith(".md"): self._pages.append(DocumentationBuilderMd(page_source)) def keep_page_name(page, catalog_data): """Puts the page name to the catalog data""" for c in catalog_data: c["page"] = page keep_page_name(page, c["children"]) catalog_data = [] for page in self._pages: catalog = page.catalog keep_page_name(page.name, catalog) catalog_data += catalog # The layout with ui.HStack(): if self._show_catalog: self._catalog = DocumentationBuilderCatalog( catalog_data, weakref.ref(self), horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, width=300, settings_menu=[{"name": "Export Markdown", "clicked_fn": self.__on_export}], ) with ui.ZStack(): ui.Rectangle(name="content_background") with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style={"ScrollingFrame": {"background_color": 0x0}}, ): self.__content_frame = ui.Frame(height=1) self.set_page()
7,676
Python
33.12
97
0.563054
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/__init__.py
# Copyright (c) 2018-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__ = [ "create_docs_window", "DocumentationBuilder", "DocumentationBuilderCatalog", "DocumentationBuilderMd", "DocumentationBuilderPage", "DocumentationBuilderWindow", "generate_for_sphinx", "get_style", ] from .documentation_catalog import DocumentationBuilderCatalog from .documentation_extension import DocumentationBuilder, create_docs_window from .documentation_generate import generate_for_sphinx from .documentation_md import DocumentationBuilderMd from .documentation_page import DocumentationBuilderPage from .documentation_style import get_style from .documentation_window import DocumentationBuilderWindow
1,089
Python
37.92857
77
0.803489
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_catalog.py
# Copyright (c) 2018-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__ = ["DocumentationBuilderCatalog"] import asyncio import weakref from typing import Any, Dict, List import omni.kit.app import omni.ui as ui class _CatalogModelItem(ui.AbstractItem): def __init__(self, catalog_data): super().__init__() self.__catalog_data = catalog_data self.name_model = ui.SimpleStringModel(catalog_data["name"]) self.__children = None self.widget = None def destroy(self): for c in self.__children or []: c.destroy() self.__children = None self.__catalog_data = None self.widget = None @property def page_name(self): return self.__catalog_data["page"] @property def children(self): if self.__children is None: # Lazy initialization self.__children = [_CatalogModelItem(c) for c in self.__catalog_data.get("children", [])] return self.__children class _CatalogModel(ui.AbstractItemModel): def __init__(self, catalog_data): super().__init__() self.__root = _CatalogModelItem({"name": "Root", "children": catalog_data}) def destroy(self): self.__root.destroy() self.__root = None def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is None: return self.__root.children return item.children def get_item_value_model_count(self, item): """The number of columns""" return 1 def get_item_value_model(self, item, column_id): """ Return value model. """ return item.name_model class _CatalogDelegate(ui.AbstractItemDelegate): def destroy(self): pass def build_branch(self, model, item, column_id, level, expanded): """Create a branch widget that opens or closes subtree""" name = f"tree{level+1}" with ui.ZStack(width=(level + 1) * 20): ui.Rectangle(height=28, name=name) if level > 0: with ui.VStack(): ui.Spacer() with ui.HStack(height=10): ui.Spacer() if model.can_item_have_children(item): image = "minus" if expanded else "plus" ui.Image(name=image, width=10, height=10) ui.Spacer() def build_widget(self, model, item, column_id, level, expanded): """Create a widget per column per item""" name = f"tree{level}" label = model.get_item_value_model(item, column_id).as_string if level == 1: label = label.upper() with ui.ZStack(): ui.Rectangle(height=28, name=name) with ui.VStack(): item.widget = ui.Label(label, name=name, style_type_name_override="Text") class DocumentationBuilderCatalog: """The left panel""" def __init__(self, catalog_data, parent: weakref, **kwargs): """ `settings_menu: List[Dict[str, Any]]` List of items. [{"name": "Export", "clicked_fn": on_export}] """ width = kwargs.get("width", 200) self.__settings_menu: List[Dict[str, Any]] = kwargs.pop("settings_menu", None) self._model = _CatalogModel(catalog_data) self._delegate = _CatalogDelegate() self.__parent = parent with ui.ScrollingFrame(**kwargs): with ui.VStack(height=0): with ui.ZStack(): ui.Image(height=width, name="main_logo") if self.__settings_menu: with ui.Frame(height=16, width=16, mouse_hovered_fn=self._on_settings_hovered): self.__settings_image = ui.Image( name="settings", visible=False, mouse_pressed_fn=self._on_settings ) tree_view = ui.TreeView( self._model, name="catalog", delegate=self._delegate, root_visible=False, header_visible=False, selection_changed_fn=self.__selection_changed, ) # Generate the TreeView children ui.Inspector.get_children(tree_view) # Expand the first level for i in self._model.get_item_children(None): tree_view.set_expanded(i, True, False) self.__stop_event = asyncio.Event() self._menu = None def destroy(self): self.__settings_menu = [] self.__stop_event.set() self.__settings_image = None self._model.destroy() self._model = None self._delegate.destroy() self._delegate = None self._menu = None async def _show_settings(self, delay, event: asyncio.Event): for _i in range(delay): await omni.kit.app.get_app().next_update_async() if event.is_set(): return self.__settings_image.visible = True def _on_settings_hovered(self, hovered): self.__stop_event.set() self.__settings_image.visible = False if hovered: self.__stop_event = asyncio.Event() asyncio.ensure_future(self._show_settings(100, self.__stop_event)) def _on_settings(self, x, y, button, mod): self._menu = ui.Menu("Scene Docs Settings") with self._menu: for item in self.__settings_menu: ui.MenuItem(item["name"], triggered_fn=item["clicked_fn"]) self._menu.show() def __selection_changed(self, selection): if not selection: return self.__parent().set_page(selection[0].page_name, selection[0].name_model.as_string)
6,230
Python
32.681081
103
0.564687
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_md.py
# Copyright (c) 2018-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__ = ["DocumentationBuilderMd"] import re from enum import Enum, auto from pathlib import Path from typing import Any, Dict, List, NamedTuple, Tuple, Union import omni.client as client H1_CHECK = re.compile(r"# .*") H2_CHECK = re.compile(r"## .*") H3_CHECK = re.compile(r"### .*") PARAGRAPH_CHECK = re.compile(r"[a-zA-Z0-9].*") LIST_CHECK = re.compile(r"^[-+] [a-zA-Z0-9].*$") CODE_CHECK = re.compile(r"```.*") IMAGE_CHECK = re.compile('!\\[(?P<alt>[^\\]]*)\\]\\((?P<url>.*?)(?=\\"|\\))(?P<title>\\".*\\")?\\)') LINK_CHECK = re.compile(r"\[(.*)\]\((.*)\)") LINK_IN_LIST = re.compile(r"^[-+] \[(.*)\]\((.*)\)") TABLE_CHECK = re.compile(r"^(?:\s*\|.+)+\|\s*$") class _BlockType(Enum): H1 = auto() H2 = auto() H3 = auto() PARAGRAPH = auto() LIST = auto() CODE = auto() IMAGE = auto() LINK = auto() TABLE = auto() LINK_IN_LIST = auto() class _Block(NamedTuple): block_type: _BlockType text: Union[str, Tuple[str]] source: str metadata: Dict[str, Any] class DocumentationBuilderMd: """ The cache for .md file. It contains parsed data, catalog, links, etc... """ def __init__(self, filename: str): """ ### Arguments `filename : str` Path to .md file """ self.__filename = filename self.__blocks: List[_Block] = [] result, _, content = client.read_file(f"{filename}") if result != client.Result.OK: content = "" else: content = memoryview(content).tobytes().decode("utf-8") self._process_lines(content.splitlines()) def destroy(self): pass @property def blocks(self): return self.__blocks @property def catalog(self): """ Return the document outline in the following format: {"name": "h1", "children": []} """ result = [] blocks = [b for b in self.__blocks if b.block_type in [_BlockType.H1, _BlockType.H2, _BlockType.H3]] if blocks: self._get_catalog_recursive(blocks, result, blocks[0].block_type.value) return result @property def source(self) -> str: content = [] code_id = 0 page_name = self.name for block in self.__blocks: if block.block_type == _BlockType.CODE: content.append(self._source_code(block, page_name, code_id)) code_id += 1 else: content.append(block.source) return "\n\n".join(content) + "\n" @property def code_blocks(self) -> List[Dict[str, str]]: page_name = self.name blocks = [b for b in self.__blocks if b.block_type == _BlockType.CODE] return [ {"name": f"{page_name}_{i}", "code": block.text, "height": block.metadata["height"]} for i, block in enumerate(blocks) if block.metadata.get("code_type", None) == "execute" ] @property def image_blocks(self) -> List[Dict[str, str]]: return [ {"path": block.text, "alt": block.metadata["alt"], "title": block.metadata["title"]} for block in self.__blocks if block.block_type == _BlockType.IMAGE ] @property def name(self): first_header = next( (b for b in self.__blocks if b.block_type in [_BlockType.H1, _BlockType.H2, _BlockType.H3]), None ) return first_header.text if first_header else None def _get_catalog_recursive(self, blocks: List[_Block], children: List[Dict], level: int): while blocks: top = blocks[0] top_level = top.block_type.value if top_level == level: children.append({"name": top.text, "children": []}) blocks.pop(0) elif top_level > level: self._get_catalog_recursive(blocks, children[-1]["children"], top_level) else: # top_level < level return def _add_block(self, block_type, text, source, **kwargs): self.__blocks.append(_Block(block_type, text, source, kwargs)) def _process_lines(self, content): # Remove empty lines while True: while content and not content[0].strip(): content.pop(0) if not content: break if H1_CHECK.match(content[0]): self._process_h1(content) elif H2_CHECK.match(content[0]): self._process_h2(content) elif H3_CHECK.match(content[0]): self._process_h3(content) elif CODE_CHECK.match(content[0]): self._process_code(content) elif IMAGE_CHECK.match(content[0]): self._process_image(content) elif LINK_CHECK.match(content[0]): self._process_link(content) elif LINK_IN_LIST.match(content[0]): self._process_link_in_list(content) elif LIST_CHECK.match(content[0]): self._process_list(content) elif TABLE_CHECK.match(content[0]): self._process_table(content) else: self._process_paragraph(content) def _process_h1(self, content): text = content.pop(0) self._add_block(_BlockType.H1, text[2:], text) def _process_h2(self, content): text = content.pop(0) self._add_block(_BlockType.H2, text[3:], text) def _process_h3(self, content): text = content.pop(0) self._add_block(_BlockType.H3, text[4:], text) def _process_list(self, content: List[str]): text_lines = [] while True: current_line = content.pop(0) text_lines.append(current_line.strip()) if not content or not LIST_CHECK.match(content[0]): # The next line is not a paragraph. break self._add_block(_BlockType.LIST, tuple(text_lines), "\n".join(text_lines)) def _process_table(self, content: List[str]): text_lines = [] while True: current_line = content.pop(0) text_lines.append(current_line.strip()) if not content or not TABLE_CHECK.match(content[0]): # The next line is not a paragraph. break self._add_block(_BlockType.TABLE, tuple(text_lines), "\n".join(text_lines)) def _process_link(self, content): text = content.pop(0) self._add_block(_BlockType.LINK, text, text) def _process_link_in_list(self, content: List[str]): text_lines = [] while True: current_line = content.pop(0) text_lines.append(current_line.strip()) if not content or not LINK_CHECK.match(content[0]): # The next line is not a link in a list. break self._add_block(_BlockType.LINK_IN_LIST, tuple(text_lines), "\n".join(text_lines)) def _process_paragraph(self, content: List[str]): text_lines = [] while True: current_line = content.pop(0) text_lines.append(current_line.strip()) if current_line.endswith(" "): # To create a line break, end a line with two or more spaces. break if not content or not PARAGRAPH_CHECK.match(content[0]): # The next line is not a paragraph. break self._add_block(_BlockType.PARAGRAPH, " ".join(text_lines), "\n".join(text_lines)) def _process_code(self, content): source = [] text = content.pop(0) source.append(text) code_type = text[3:].strip().split() # Extract height if code_type and len(code_type) > 1: height = code_type[1] else: height = None if code_type: code_type = code_type[0] else: code_type = "" code_lines = [] while content and not CODE_CHECK.match(content[0]): text = content.pop(0) source.append(text) code_lines.append(text) source.append(content.pop(0)) self._add_block(_BlockType.CODE, "\n".join(code_lines), "\n".join(source), code_type=code_type, height=height) def _process_image(self, content: List[str]): text = content.pop(0) parts = IMAGE_CHECK.match(text.strip()).groupdict() path = Path(self.__filename).parent.joinpath(parts["url"]) self._add_block(_BlockType.IMAGE, f"{path}", text, alt=parts["alt"], title=parts["title"]) @staticmethod def get_clean_code(block): # Remove double-comments clean = [] skip = False for line in block.text.splitlines(): if line.lstrip().startswith("##"): skip = not skip continue if skip: continue if not clean and not line.strip(): continue clean.append(line) return "\n".join(clean) def _source_code(self, block, page_name, code_id): result = [] code_type = block.metadata.get("code_type", "") if code_type == "execute": image_name = f"{page_name}_{code_id}.png" result.append(f"![Code Result]({image_name})\n") code_type = "python" elif code_type == "execute-manual": code_type = "python" result.append(f"```{code_type}") result.append(self.get_clean_code(block)) result.append("```") return "\n".join(result)
10,066
Python
30.857595
118
0.548281
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_generate.py
# Copyright (c) 2018-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__ = ["generate_for_sphinx"] import shutil import traceback from pathlib import Path import carb import omni.kit.app import omni.ui as ui from .documentation_capture import DocumentationBuilderCapture from .documentation_md import DocumentationBuilderMd from .documentation_style import get_style PRINT_GENERATION_STATUS = True # Can be made into setting if needed def _print(message): if PRINT_GENERATION_STATUS: print(message) else: carb.log_info(message) def generate_for_sphinx(extension_id: str, path: str) -> bool: """ Produce the set of files and screenshots readable by Sphinx. ### Arguments `extension_id: str` The extension to generate documentation files `path: str` The path to produce the files. ### Return `True` if generation succeded. """ _print(f"Generating for sphinx. Ext: {extension_id}. Path: {path}") out_path = Path(path) if not out_path.is_dir(): carb.log_error(f"{path} is not a directory") return False ext_info = omni.kit.app.get_app().get_extension_manager().get_extension_dict(extension_id) if ext_info is None: carb.log_error(f"Extension id {extension_id} not found") return False if not ext_info.get("state", {}).get("enabled", False): carb.log_error(f"Extension id {extension_id} is not enabled") return False ext_path = Path(ext_info.get("path", "")) pages = ext_info.get("documentation", {}).get("pages", []) if len(pages) == 0: carb.log_error(f"Extension id {extension_id} has no pages set in [documentation] section of config.") return False for page in pages: _print(f"Processing page: '{page}'") if not page.endswith(".md"): _print(f"Not .md, skipping: '{page}'") continue page_path = Path(ext_path / page) md = DocumentationBuilderMd(str(page_path)) if md.name is None: _print(f"md is None, skipping: '{page}'") continue for code_block in md.code_blocks: image_file = out_path / f"{code_block['name']}.png" height = int(code_block["height"] or 200) with DocumentationBuilderCapture(str(image_file), 800, height): stack = ui.ZStack() stack.set_style(get_style()) with stack: # Background ui.Rectangle(name="code_background") # The code with ui.VStack(): try: _execute_code(code_block["code"]) except Exception as e: tb = traceback.format_exception(Exception, e, e.__traceback__) ui.Label( "".join(tb), name="code", style_type_name_override="Text", skip_draw_when_clipped=True ) _print(f"Generated image: '{image_file}'") for image_block in md.image_blocks: image_file = Path(image_block["path"]) image_out = out_path / image_file.relative_to(page_path.parent) image_out.parent.mkdir(parents=True, exist_ok=True) try: shutil.copyfile(image_file, image_out) except shutil.SameFileError: pass _print(f"Copied image: '{image_out}'") md_file = out_path / f"{page_path.stem}.md" with open(md_file, "w", encoding="utf-8") as f: f.write(md.source) _print(f"Generated md file: '{md_file}'") return True def _execute_code(code: str): # Wrap the code in a class to provide scoping indented = "\n".join([" " + line for line in code.splitlines()]) source = f"class Execution:\n def __init__(self):\n{indented}" locals_from_execution = {} # flake8: noqa: PLW0122 exec(source, None, locals_from_execution) locals_from_execution["Execution"]()
4,473
Python
33.953125
118
0.594232
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_extension.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import os.path import typing from functools import partial import omni.ext import omni.kit.app import omni.kit.ui from .documentation_window import DocumentationBuilderWindow class DocumentationBuilder(omni.ext.IExt): """ Extension to create a documentation window for any extension which has markdown pages defined in its extension.toml. Such pages can have inline omni.ui code blocks which are executed. For example, [documentation] pages = ["docs/Overview.md"] menu = "Help/API/omni.kit.documentation.builder" title = "Omni UI Documentation Builder" """ def __init__(self): super().__init__() # cache docs and window by extensions id self._doc_info: typing.Dict[str, _DocInfo] = {} self._editor_menu = None self._extension_enabled_hook = None self._extension_disabled_hook = None def on_startup(self, ext_id: str): self._editor_menu = omni.kit.ui.get_editor_menu() manager = omni.kit.app.get_app().get_extension_manager() # add menus for any extensions with docs that are already enabled all_exts = manager.get_extensions() for ext in all_exts: if ext.get("enabled", False): self._add_docs_menu(ext.get("id")) # hook into extension enable/disable events if extension specifies "documentation" config key hooks = manager.get_hooks() self._extension_enabled_hook = hooks.create_extension_state_change_hook( self.on_after_extension_enabled, omni.ext.ExtensionStateChangeType.AFTER_EXTENSION_ENABLE, ext_dict_path="documentation", hook_name="omni.kit.documentation.builder", ) self._extension_disabled_hook = hooks.create_extension_state_change_hook( self.on_before_extension_disabled, omni.ext.ExtensionStateChangeType.BEFORE_EXTENSION_DISABLE, ext_dict_path="documentation", hook_name="omni.kit.documentation.builder", ) def on_shutdown(self): self._extension_enabled_hook = None self._extension_disabled_hook = None for ext_id in list(self._doc_info.keys()): self._destroy_docs_window(ext_id) self._editor_menu = None def on_after_extension_enabled(self, ext_id: str, *_): self._add_docs_menu(ext_id) def on_before_extension_disabled(self, ext_id: str, *_): self._destroy_docs_window(ext_id) def _add_docs_menu(self, ext_id: str): doc_info = _get_doc_info(ext_id) if doc_info and doc_info.menu_path and self._editor_menu: doc_info.menu = self._editor_menu.add_item(doc_info.menu_path, partial(self._show_docs_window, ext_id)) self._doc_info[ext_id] = doc_info def _show_docs_window(self, ext_id: str, *_): window = self._doc_info[ext_id].window if not window: window = _create_docs_window(ext_id) self._doc_info[ext_id].window = window window.visible = True def _destroy_docs_window(self, ext_id: str): if ext_id in self._doc_info: doc_info = self._doc_info.pop(ext_id) if doc_info.window: doc_info.window.destroy() def create_docs_window(ext_name: str): """ Creates a DocumentationBuilderWindow for ext_name Returns the window, or None if no such extension is enabled and has documentation """ # fetch by name ext_versions = omni.kit.app.get_app().get_extension_manager().fetch_extension_versions(ext_name) # use latest version that is enabled for ver in ext_versions: if ver.get("enabled", False): return _create_docs_window(ver.get("id", "")) return None def _create_docs_window(ext_id: str): """ Creates a DocumentationBuilderWindow for ext_id Returns the window, or None if ext_id has no documentation """ doc_info = _get_doc_info(ext_id) if doc_info: window = DocumentationBuilderWindow(doc_info.title, filenames=doc_info.pages) return window return None class _DocInfo: def __init__(self): self.pages = [] self.menu_path = "" self.title = "" self.window = None self.menu = None def _get_doc_info(ext_id: str) -> _DocInfo: """ Returns extension documentation metadata if it exists. Returns None if exension has no documentation pages. """ ext_info = omni.kit.app.get_app().get_extension_manager().get_extension_dict(ext_id) if ext_info: ext_path = ext_info.get("path", "") doc_dict = ext_info.get("documentation", {}) doc_info = _DocInfo() doc_info.pages = doc_dict.get("pages", []) doc_info.menu_path = doc_dict.get("menu", "Help/API/" + ext_id) doc_info.title = doc_dict.get("title", ext_id) filenames = [] for page in doc_info.pages: filenames.append(page if os.path.isabs(page) else os.path.join(ext_path, page)) if filenames: doc_info.pages = filenames return doc_info return None
5,549
Python
34.806451
115
0.640115
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_page.py
# Copyright (c) 2018-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__ = ["DocumentationBuilderPage"] import re import subprocess import sys import traceback import weakref import webbrowser from functools import partial from typing import Any, Dict, List, Optional import omni.ui as ui from PIL import Image from .documentation_md import LINK_CHECK, DocumentationBuilderMd, _Block, _BlockType class DocumentationBuilderPage: """ Widget that draws .md page with the cache. """ def __init__(self, md: DocumentationBuilderMd, scroll_to: Optional[str] = None): """ ### Arguments `md : DocumentationBuilderMd` MD cache object `scroll_to : Optional[str]` The name of the section to scroll to """ self.__md = md self.__scroll_to = scroll_to self.__images: List[ui.Image] = [] self.__code_stacks: List[ui.ZStack] = [] self.__code_locals: Dict[str, Any] = {} self._copy_context_menu = None self.__bookmarks: Dict[str, ui.Widget] = {} self._dont_scale_images = False ui.Frame(build_fn=self.__build) def destroy(self): self.__bookmarks: Dict[str, ui.Widget] = {} if self._copy_context_menu: self._copy_context_menu.destroy() self._copy_context_menu = None self.__code_locals = {} for stack in self.__code_stacks: stack.destroy() self.__code_stacks = [] for image in self.__images: image.destroy() self.__images = [] @property def name(self): """The name of the page""" return self.__md.name def scroll_to(self, where: str): """Scroll to the given section""" widget = self.__bookmarks.get(where, None) if widget: widget.scroll_here() def _execute_code(self, code: str): indented = "\n".join([" " + line for line in code.splitlines()]) source = f"class Execution:\n def __init__(self):\n{indented}" locals_from_execution = {} # flake8: noqa: PLW0122 exec(source, None, locals_from_execution) self.__code_locals[code] = locals_from_execution["Execution"]() def __build(self): self.__bookmarks: Dict[str, ui.Widget] = {} with ui.HStack(): ui.Spacer(width=50) with ui.VStack(height=0): ui.Spacer(height=50) for block in self.__md.blocks: # Build sections one by one # Space between sections space = ui.Spacer(height=10) self.__bookmarks[block.text] = space if block.text == self.__scroll_to: # Scroll to this section if necessary space.scroll_here() if block.block_type == _BlockType.H1: self._build_h1(block) elif block.block_type == _BlockType.H2: self._build_h2(block) elif block.block_type == _BlockType.H3: self._build_h3(block) elif block.block_type == _BlockType.PARAGRAPH: self._build_paragraph(block) elif block.block_type == _BlockType.LIST: self._build_list(block) elif block.block_type == _BlockType.TABLE: self._build_table(block) elif block.block_type == _BlockType.LINK: self._build_link(block) elif block.block_type == _BlockType.CODE: self._build_code(block) elif block.block_type == _BlockType.IMAGE: self._build_image(block) elif block.block_type == _BlockType.LINK_IN_LIST: self._build_link_in_list(block) ui.Spacer(height=50) ui.Spacer(width=50) def _build_h1(self, block: _Block): with ui.ZStack(): ui.Rectangle(name="h1") ui.Label(block.text, name="h1", style_type_name_override="Text") def _build_h2(self, block: _Block): with ui.VStack(): ui.Line(name="h2") ui.Label(block.text, name="h2", style_type_name_override="Text") ui.Line(name="h2") def _build_h3(self, block: _Block): with ui.VStack(height=0): ui.Line(name="h3") ui.Label(block.text, name="h3", style_type_name_override="Text") ui.Line(name="h3") def _build_paragraph(self, block: _Block): ui.Label(block.text, name="paragraph", word_wrap=True, skip_draw_when_clipped=True) def _build_list(self, block: _Block): with ui.VStack(spacing=-5): for list_entry in block.text: list_entry = list_entry.lstrip("+") list_entry = list_entry.lstrip("-") with ui.HStack(spacing=0): ui.Circle( width=10, size_policy=ui.CircleSizePolicy.FIXED, alignment=ui.Alignment.LEFT_CENTER, radius=3 ) ui.Label( list_entry, alignment=ui.Alignment.LEFT_TOP, name="paragraph", word_wrap=True, skip_draw_when_clipped=True, ) # ui.Spacer(width=5) def _build_link_in_list(self, block: _Block): with ui.VStack(spacing=-5): for list_entry in block.text: list_entry = list_entry.lstrip("+") list_entry = list_entry.lstrip("-") list_entry = list_entry.lstrip() with ui.HStack(spacing=0): ui.Circle( width=10, size_policy=ui.CircleSizePolicy.FIXED, alignment=ui.Alignment.LEFT_CENTER, radius=3 ) reg = re.match(LINK_CHECK, list_entry) if reg and len(reg.groups()) == 2: self._build_link_impl(reg.group(1), reg.group(2)) def _build_link(self, block: _Block): text = block.text reg = re.match(LINK_CHECK, text) label = "" url = "" if reg and len(reg.groups()) == 2: label = reg.group(1) url = reg.group(2) self._build_link_impl(label, url) def _build_link_impl(self, label, url): def _on_clicked(a, b, c, d, url): try: webbrowser.open(url) except OSError: print("Please open a browser on: " + url) with ui.HStack(): spacer = ui.Spacer(width=5) label = ui.Label( label, style_type_name_override="url_link", name="paragraph", word_wrap=True, skip_draw_when_clipped=True, tooltip=url, ) label.set_mouse_pressed_fn(lambda a, b, c, d, u=url: _on_clicked(a, b, c, d, u)) def _build_table(self, block: _Block): cells = [] num_columns = 0 for line in block.text: cell_text_list = line.split("|") cell_text_list = [c.strip() for c in cell_text_list] cell_text_list = [c for c in cell_text_list if c] num_columns = max(num_columns, len(cell_text_list)) cells.append(cell_text_list) # Assume 2nd row is separators "|------|---|" del cells[1] frame_pixel_width = 800 grid_column_width = frame_pixel_width / num_columns frame_pixel_height = len(cells) * 20 with ui.ScrollingFrame( width=frame_pixel_width, height=frame_pixel_height, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, ): with ui.VGrid(column_width=grid_column_width, row_height=20): for i in range(len(cells)): for j in range(num_columns): with ui.ZStack(): bg_color = 0xFFCCCCCC if i == 0 else 0xFFFFFFF ui.Rectangle( style={ "border_color": 0xFF000000, "background_color": bg_color, "border_width": 1, "margin": 0, } ) cell_val = cells[i][j] if len(cell_val) > 66: cell_val = cell_val[:65] + "..." ui.Label(f"{cell_val}", style_type_name_override="table_label") def _build_code(self, block: _Block): def label_size_changed(label: ui.Label, short_frame: ui.Frame, overlay: ui.Frame): max_height = ui.Pixel(200) if label.computed_height > max_height.value: short_frame.height = max_height short_frame.vertical_clipping = True with overlay: with ui.VStack(): ui.Spacer() with ui.ZStack(): ui.Rectangle(style_type_name_override="TextOverlay") ui.InvisibleButton(clicked_fn=partial(remove_overlay, label, short_frame, overlay)) def remove_overlay(label: ui.Label, short_frame: ui.Frame, overlay: ui.Frame): short_frame.height = ui.Pixel(label.computed_height) with overlay: ui.Spacer() code_type = block.metadata.get("code_type", None) is_execute_manual = code_type == "execute-manual" is_execute = code_type == "execute" if is_execute: with ui.Frame(horizontal_clipping=True): with ui.ZStack(): # Background ui.Rectangle(name="code_background") # The code with ui.VStack(): try: self._execute_code(block.text) except Exception as e: tb = traceback.format_exception(Exception, e, e.__traceback__) ui.Label( "".join(tb), name="code", style_type_name_override="Text", skip_draw_when_clipped=True ) ui.Spacer(height=10) # Remove double-comments clean = DocumentationBuilderMd.get_clean_code(block) with ui.Frame(horizontal_clipping=True): stack = ui.ZStack(height=0) with stack: ui.Rectangle(name="code") short_frame = ui.Frame() with short_frame: label = ui.Label(clean, name="code", style_type_name_override="Text", skip_draw_when_clipped=True) overlay = ui.Frame() # Enable clipping/extending the label after we know its size label.set_computed_content_size_changed_fn(partial(label_size_changed, label, short_frame, overlay)) self.__code_stacks.append(stack) if is_execute_manual: ui.Spacer(height=4) with ui.HStack(): # ui.Spacer(height=10) def on_click(text=block.text): try: self._execute_code(block.text) except Exception as e: tb = traceback.format_exception(Exception, e, e.__traceback__) ui.Label("".join(tb), name="code", style_type_name_override="Text", skip_draw_when_clipped=True) button = ui.Button( "RUN CODE", style_type_name_override="RunButton", width=50, height=20, clicked_fn=on_click ) ui.Spacer() if sys.platform != "linux": stack.set_mouse_pressed_fn(lambda x, y, b, m, text=clean: b == 1 and self._show_copy_menu(x, y, b, m, text)) def _build_image(self, block: _Block): source_url = block.text def change_resolution_legacy(image_weak, size): """ Change the widget size proportionally to the image We set a max height of 400 for anything. """ MAX_HEIGHT = 400 image = image_weak() if not image: return width, height = size image_height = min(image.computed_content_width * height / width, MAX_HEIGHT) image.height = ui.Pixel(image_height) def change_resolution(image_weak, size): """ This leaves the image scale untouched """ image = image_weak() if not image: return width, height = size image.height = ui.Pixel(height) image.width = ui.Pixel(width) im = Image.open(source_url) image = ui.Image(source_url, height=200) # Even though the legacy behaviour is probably wrong there are extensions out there with images that are # too big, we don't want them to display differently than before if self._dont_scale_images: image.set_computed_content_size_changed_fn(partial(change_resolution, weakref.ref(image), im.size)) else: image.set_computed_content_size_changed_fn(partial(change_resolution_legacy, weakref.ref(image), im.size)) self.__images.append(image) def _show_copy_menu(self, x, y, button, modifier, text): """The context menu to copy the text""" # Display context menu only if the right button is pressed def copy_text(text_value): # we need to find a cross plartform way currently Window Only subprocess.run(["clip.exe"], input=text_value.strip().encode("utf-8"), check=True) # Reset the previous context popup self._copy_context_menu = ui.Menu("Copy Context Menu") with self._copy_context_menu: ui.MenuItem("Copy Code", triggered_fn=lambda t=text: copy_text(t)) # Show it self._copy_context_menu.show()
14,863
Python
37.015345
120
0.519545
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_style.py
# Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from pathlib import Path import omni.ui as ui from omni.ui import color as cl from omni.ui import constant as fl from omni.ui import url CURRENT_PATH = Path(__file__).parent DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data") FONTS_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("fonts") def get_style(): """ Returns the standard omni.ui style for documentation """ cl.documentation_nvidia = cl("#76b900") # Content cl.documentation_bg = cl.white cl.documentation_text = cl("#1a1a1a") cl.documentation_h1_bg = cl.black cl.documentation_h1_color = cl.documentation_nvidia cl.documentation_h2_line = cl.black cl.documentation_h2_color = cl.documentation_nvidia cl.documentation_exec_bg = cl("#454545") cl.documentation_code_bg = cl("#eeeeee") cl.documentation_code_fadeout = cl("#eeeeee01") cl.documentation_code_fadeout_selected = cl.documentation_nvidia cl.documentation_code_line = cl("#bbbbbb") fl.documentation_margin = 5 fl.documentation_code_size = 16 fl.documentation_code_radius = 2 fl.documentation_text_size = 18 fl.documentation_h1_size = 36 fl.documentation_h2_size = 28 fl.documentation_h3_size = 20 fl.documentation_line_width = 0.3 cl.url_link = cl("#3333CC") # Catalog cl.documentation_catalog_bg = cl.black cl.documentation_catalog_text = cl("#cccccc") cl.documentation_catalog_h1_bg = cl("#333333") cl.documentation_catalog_h1_color = cl.documentation_nvidia cl.documentation_catalog_h2_bg = cl("#fcfcfc") cl.documentation_catalog_h2_color = cl("#404040") cl.documentation_catalog_h3_bg = cl("#e3e3e3") cl.documentation_catalog_h3_color = cl("#404040") cl.documentation_catalog_icon_selected = cl("#333333") fl.documentation_catalog_tree1_size = 17 fl.documentation_catalog_tree1_margin = 5 fl.documentation_catalog_tree2_size = 19 fl.documentation_catalog_tree2_margin = 2 fl.documentation_catalog_tree3_size = 19 fl.documentation_catalog_tree3_margin = 2 url.documentation_logo = f"{DATA_PATH.joinpath('main_ov_logo_square.png')}" url.documentation_settings = f"{DATA_PATH.joinpath('settings.svg')}" url.documentation_plus = f"{DATA_PATH.joinpath('plus.svg')}" url.documentation_minus = f"{DATA_PATH.joinpath('minus.svg')}" url.documentation_font_regular = f"{FONTS_PATH}/DINPro-Regular.otf" url.documentation_font_regular_bold = f"{FONTS_PATH}/DINPro-Bold.otf" url.documentation_font_monospace = f"{FONTS_PATH}/DejaVuSansMono.ttf" style = { "Window": {"background_color": cl.documentation_catalog_bg, "border_width": 0, "padding": 0}, "Rectangle::content_background": {"background_color": cl.documentation_bg}, "Label::paragraph": { "color": cl.documentation_text, "font_size": fl.documentation_text_size, "margin": fl.documentation_margin, }, "Text::code": { "color": cl.documentation_text, "font": url.documentation_font_monospace, "font_size": fl.documentation_code_size, "margin": fl.documentation_margin, }, "url_link": {"color": cl.url_link, "font_size": fl.documentation_text_size}, "table_label": { "color": cl.documentation_text, "font_size": fl.documentation_text_size, "margin": 2, }, "Rectangle::code": { "background_color": cl.documentation_code_bg, "border_color": cl.documentation_code_line, "border_width": fl.documentation_line_width, "border_radius": fl.documentation_code_radius, }, "Rectangle::code_background": {"background_color": cl.documentation_exec_bg}, "Rectangle::h1": {"background_color": cl.documentation_h1_bg}, "Rectangle::tree1": {"background_color": cl.documentation_catalog_h1_bg}, "Rectangle::tree2": {"background_color": 0x0}, "Rectangle::tree2:selected": {"background_color": cl.documentation_catalog_h2_bg}, "Rectangle::tree3": {"background_color": 0x0}, "Rectangle::tree3:selected": {"background_color": cl.documentation_catalog_h3_bg}, "Text::h1": { "color": cl.documentation_h1_color, "font": url.documentation_font_regular, "font_size": fl.documentation_h1_size, "margin": fl.documentation_margin, "alignment": ui.Alignment.CENTER, }, "Text::h2": { "color": cl.documentation_h2_color, "font": url.documentation_font_regular, "font_size": fl.documentation_h2_size, "margin": fl.documentation_margin, }, "Text::h3": { "color": cl.documentation_h2_color, "font": url.documentation_font_regular, "font_size": fl.documentation_h3_size, "margin": fl.documentation_margin, }, "Text::tree1": { "color": cl.documentation_catalog_h1_color, "font": url.documentation_font_regular_bold, "font_size": fl.documentation_catalog_tree1_size, "margin": fl.documentation_catalog_tree1_margin, }, "Text::tree2": { "color": cl.documentation_catalog_text, "font": url.documentation_font_regular, "font_size": fl.documentation_catalog_tree2_size, "margin": fl.documentation_catalog_tree2_margin, }, "Text::tree2:selected": {"color": cl.documentation_catalog_h2_color}, "Text::tree3": { "color": cl.documentation_catalog_text, "font": url.documentation_font_regular, "font_size": fl.documentation_catalog_tree3_size, "margin": fl.documentation_catalog_tree3_margin, }, "Text::tree3:selected": {"color": cl.documentation_catalog_h3_color}, "Image::main_logo": {"image_url": url.documentation_logo}, "Image::settings": {"image_url": url.documentation_settings}, "Image::plus": {"image_url": url.documentation_plus}, "Image::minus": {"image_url": url.documentation_minus}, "Image::plus:selected": {"color": cl.documentation_catalog_icon_selected}, "Image::minus:selected": {"color": cl.documentation_catalog_icon_selected}, "Line::h2": {"border_width": fl.documentation_line_width}, "Line::h3": {"border_width": fl.documentation_line_width}, "TextOverlay": { "background_color": cl.documentation_bg, "background_gradient_color": cl.documentation_code_fadeout, }, "TextOverlay:hovered": {"background_color": cl.documentation_code_fadeout_selected}, "RunButton": {"background_color": cl("#76b900"), "border_radius": 2}, "RunButton.Label": {"color": 0xFF3E3E3E, "font_size": 14}, "RunButton:hovered": {"background_color": cl("#84d100")}, "RunButton:pressed": {"background_color": cl("#7bc200")}, } return style
7,491
Python
42.812865
101
0.637699
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/tests/test_documentation.py
# Copyright (c) 2019-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__ = ["TestDocumentation"] import pathlib import omni.kit.app import omni.kit.test from omni.ui.tests.test_base import OmniUiTest from ..documentation_md import DocumentationBuilderMd EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) TESTS_PATH = EXTENSION_FOLDER_PATH.joinpath("data/tests") class TestDocumentation(OmniUiTest): async def test_builder(self): builder = DocumentationBuilderMd(f"{TESTS_PATH}/test.md") self.assertEqual( builder.catalog, [{"name": "NVIDIA", "children": [{"name": "Omiverse", "children": [{"name": "Doc", "children": []}]}]}], ) self.assertEqual(builder.blocks[0].text, "NVIDIA") self.assertEqual(builder.blocks[0].block_type.name, "H1") self.assertEqual(builder.blocks[1].text, "Omiverse") self.assertEqual(builder.blocks[1].block_type.name, "H2") self.assertEqual(builder.blocks[2].text, "Doc") self.assertEqual(builder.blocks[2].block_type.name, "H3") self.assertEqual(builder.blocks[3].text, "Text") self.assertEqual(builder.blocks[3].block_type.name, "PARAGRAPH") clean = builder.get_clean_code(builder.blocks[4]) self.assertEqual(clean, 'ui.Label("Hello")') self.assertEqual(builder.blocks[4].block_type.name, "CODE") self.assertEqual(builder.blocks[5].text, ("- List1", "- List2")) self.assertEqual(builder.blocks[5].block_type.name, "LIST") self.assertEqual(builder.blocks[6].text, ("- [YOUTUBE](https://www.youtube.com)",)) self.assertEqual(builder.blocks[6].block_type.name, "LINK_IN_LIST") self.assertEqual(builder.blocks[7].text, "[NVIDIA](https://www.nvidia.com)") self.assertEqual(builder.blocks[7].block_type.name, "LINK") self.assertEqual( builder.blocks[8].text, ("| Noun | Adjective |", "| ---- | --------- |", "| Omniverse | Awesome |") ) self.assertEqual(builder.blocks[8].block_type.name, "TABLE") builder.destroy()
2,531
Python
39.838709
116
0.670881
omniverse-code/kit/exts/omni.volume/omni/volume/__init__.py
"""This module contains bindings to C++ carb::volume::IVolume interface. All the function are in omni.volume.IVolume class, to get it use get_editor_interface method, which caches acquire interface call: >>> import omni.volume >>> e = omni.volume.get_volume_interface() >>> print(f"Is UI hidden: {e.is_ui_hidden()}") """ from ._volume import * from functools import lru_cache @lru_cache() def get_volume_interface() -> IVolume: """Returns cached :class:` omni.volume.IVolume` interface""" return acquire_volume_interface()
547
Python
29.444443
106
0.702011
omniverse-code/kit/exts/omni.volume/omni/volume/tests/test_volume.py
import numpy import omni.kit.test import omni.volume class CreateFromDenseTest(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_create_from_dense(self): ivolume = omni.volume.get_volume_interface() o = numpy.array([0, 0, 0]).astype(numpy.float64) float_x = numpy.arange(30).reshape((5, 3, 2)).astype(numpy.float32) float_volume = ivolume.create_from_dense(0, float_x, 1, o, "floatTest") self.assertEqual(ivolume.get_num_grids(float_volume), 1) self.assertEqual(ivolume.get_grid_class(float_volume, 0), 0) self.assertEqual(ivolume.get_grid_type(float_volume, 0), 1) self.assertEqual(ivolume.get_short_grid_name(float_volume, 0), "floatTest") float_index_bounding_box = ivolume.get_index_bounding_box(float_volume, 0) self.assertEqual(float_index_bounding_box, [(0, 0, 0), (1, 2, 4)]) float_world_bounding_box = ivolume.get_world_bounding_box(float_volume, 0) self.assertEqual(float_world_bounding_box, [(0, 0, 0), (2, 3, 5)]) double_x = numpy.arange(30).reshape((5, 3, 2)).astype(numpy.float64) double_volume = ivolume.create_from_dense(0, double_x, 1, o, "doubleTest") self.assertEqual(ivolume.get_num_grids(double_volume), 1) self.assertEqual(ivolume.get_grid_class(double_volume, 0), 0) self.assertEqual(ivolume.get_grid_type(double_volume, 0), 2) self.assertEqual(ivolume.get_short_grid_name(double_volume, 0), "doubleTest") double_index_bounding_box = ivolume.get_index_bounding_box(double_volume, 0) self.assertEqual(double_index_bounding_box, [(0, 0, 0), (1, 2, 4)]) double_world_bounding_box = ivolume.get_world_bounding_box(double_volume, 0) self.assertEqual(double_world_bounding_box, [(0, 0, 0), (2, 3, 5)])
2,028
Python
47.309523
85
0.661736
omniverse-code/kit/exts/omni.volume/omni/volume/tests/__init__.py
from .test_volume import *
26
Python
25.999974
26
0.769231
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/open_file_addon.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui import asyncio from .activity_progress_bar import ProgressBarWidget class OpenFileAddon: def __init__(self): self._stop_event = asyncio.Event() # The progress with ui.Frame(height=355): self.activity_widget = ProgressBarWidget() def new(self, model): self.activity_widget.new(model) def __del__(self): self.activity_widget.destroy() self._stop_event.set() def mouse_pressed(self, *args): # Bind this class to the rectangle, so when Rectangle is deleted, the # class is deleted as well pass def start_timer(self): self.activity_widget.reset_timer() def stop_timer(self): self.activity_widget.stop_timer()
1,190
Python
29.538461
77
0.694118
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_tree_delegate.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ActivityTreeDelegate", "ActivityProgressTreeDelegate"] from .activity_model import SECOND_MULTIPLIER, ActivityModelItem import omni.kit.app import omni.ui as ui import pathlib from urllib.parse import unquote EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) class ActivityTreeDelegate(ui.AbstractItemDelegate): """ The delegate for the bottom TreeView that displays details of the activity. """ def __init__(self, **kwargs): super().__init__() self._on_expand = kwargs.pop("on_expand", None) self._initialize_expansion = kwargs.pop("initialize_expansion", None) 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=20 * (level + 1), height=0): ui.Spacer() if model.can_item_have_children(item): # Draw the +/- icon image_name = "Minus" if expanded else "Plus" ui.ImageWithProvider( f"{EXTENSION_FOLDER_PATH}/data/{image_name}.svg", width=10, height=10, style_type_name_override="TreeView.Label", mouse_pressed_fn=lambda x, y, b, a: self._on_expand(item) ) ui.Spacer(width=5) def _build_header(self, column_id, headers, headers_tooltips): alignment = ui.Alignment.LEFT_CENTER if column_id == 0 else ui.Alignment.RIGHT_CENTER return ui.Label( headers[column_id], height=22, alignment=alignment, style_type_name_override="TreeView.Label", tooltip=headers_tooltips[column_id]) def build_header(self, column_id: int): headers = [" Name", "Dur", "Start", "End", "Size "] headers_tooltips = ["Activity Name", "Duration (second)", "Start Time (second)", "End Time (second)", "Size (MB)"] return self._build_header(column_id, headers, headers_tooltips) def _build_name(self, text, item, model): tooltip = f"{text}" short_name = unquote(text.split("/")[-1]) children_size = len(model.get_item_children(item)) label_text = short_name if children_size == 0 else short_name + " (" + str(children_size) + ")" with ui.HStack(spacing=5): icon_name = item.icon_name if icon_name != "undefined": ui.ImageWithProvider(style_type_name_override="Icon", name=icon_name, width=16) if icon_name != "material": ui.ImageWithProvider(style_type_name_override="Icon", name="file", width=12) label_style_name = icon_name if item.ended else "unfinished" ui.Label(label_text, name=label_style_name, tooltip=tooltip) # if text == "Materials" or text == "Textures": # self._initialize_expansion(item, True) def _build_duration(self, item): duration = item.total_time / SECOND_MULTIPLIER ui.Label(f"{duration:.2f}", style_type_name_override="TreeView.Label.Right", tooltip=str(duration) + " sec") def _build_start_and_end(self, item, model, is_start): time_ranges = item.time_range if len(time_ranges) == 0: return time_begin = model.time_begin begin = (time_ranges[0].begin - time_begin) / SECOND_MULTIPLIER end = (time_ranges[-1].end - time_begin) / SECOND_MULTIPLIER if is_start: ui.Label(f"{begin:.2f}", style_type_name_override="TreeView.Label.Right", tooltip=str(begin) + " sec") else: ui.Label(f"{end:.2f}", style_type_name_override="TreeView.Label.Right", tooltip=str(end) + " sec") def _build_size(self, text, item): if text in ["Read", "Load", "Resolve"]: size = item.children_size else: size = item.size if size != 0: size *= 0.000001 ui.Label(f"{size:.2f}", style_type_name_override="TreeView.Label.Right", tooltip=str(size) + " MB") # from byte to MB def build_widget(self, model, item, column_id, level, expanded): """Create a widget per item""" if not hasattr(model, "time_begin") or not isinstance(item, ActivityModelItem): return text = model.get_item_value_model(item, column_id).get_value_as_string() with ui.VStack(height=20): if column_id == 0: self._build_name(text, item, model) elif column_id == 1: self._build_duration(item) elif column_id == 2 or column_id == 3: self._build_start_and_end(item, model, column_id == 2) elif column_id == 4: self._build_size(text, item) class ActivityProgressTreeDelegate(ActivityTreeDelegate): def __init__(self, **kwargs): super().__init__() def build_header(self, column_id: int): headers = [" Name", "Dur", "Size "] headers_tooltips = ["Activity Name", "Duration (second)", "Size (MB)"] return self._build_header(column_id, headers, headers_tooltips) def build_widget(self, model, item, column_id, level, expanded): """Create a widget per item""" if not hasattr(model, "time_begin") or not isinstance(item, ActivityModelItem): return text = model.get_item_value_model(item, column_id).get_value_as_string() with ui.VStack(height=20): if column_id == 0: self._build_name(text, item, model) elif column_id == 1: self._build_duration(item) elif column_id == 2: self._build_size(text, item)
6,242
Python
42.964788
143
0.598526
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_extension.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ActivityWindowExtension", "get_instance"] from .activity_menu import ActivityMenuOptions from .activity_model import ActivityModelDump, ActivityModelDumpForProgress, ActivityModelStageOpen, ActivityModelStageOpenForProgress from .activity_progress_model import ActivityProgressModel from .activity_progress_bar import ActivityProgressBarWindow, TIMELINE_WINDOW_NAME from .activity_window import ActivityWindow from .open_file_addon import OpenFileAddon from .activity_actions import register_actions, deregister_actions import asyncio from functools import partial import os from pathlib import Path from typing import Any from typing import Dict from typing import Optional import weakref import carb.profiler import carb.settings import carb.tokens import omni.activity.core import omni.activity.profiler import omni.ext import omni.kit.app import omni.kit.ui from omni.kit.window.file import register_open_stage_addon from omni.kit.usd.layers import get_live_syncing import omni.ui as ui import omni.usd_resolver import omni.kit.commands AUTO_SAVE_LOCATION = "/exts/omni.activity.ui/auto_save_location" STARTUP_ACTIVITY_FILENAME = "Startup" g_singleton = None def get_instance(): return g_singleton class ActivityWindowExtension(omni.ext.IExt): """The entry point for Activity Window""" PROGRESS_WINDOW_NAME = "Activity Progress" PROGRESS_MENU_PATH = f"Window/Utilities/{PROGRESS_WINDOW_NAME}" def on_startup(self, ext_id): import omni.kit.app # true when we record the activity self.__activity_started = False self._activity_profiler = omni.activity.profiler.get_activity_profiler() self._activity_profiler_capture_mask_uid = 0 # make sure the old activity widget is disabled before loading the new one ext_manager = omni.kit.app.get_app_interface().get_extension_manager() old_activity_widget = "omni.kit.activity.widget.monitor" if ext_manager.is_extension_enabled(old_activity_widget): ext_manager.set_extension_enabled_immediate(old_activity_widget, False) self._timeline_window = None self._progress_bar = None self._addon = None self._current_path = None self._data = None self.__model = None self.__progress_model= None self.__flatten_model = None self._menu_entry = None self._activity_menu_option = ActivityMenuOptions(load_data=self.load_data, get_save_data=self.get_save_data) # The ability to show up the window if the system requires it. We use it # in QuickLayout. ui.Workspace.set_show_window_fn(TIMELINE_WINDOW_NAME, partial(self.show_window, None)) ui.Workspace.set_show_window_fn( ActivityWindowExtension.PROGRESS_WINDOW_NAME, partial(self.show_progress_bar, None) ) # add actions self._ext_name = omni.ext.get_extension_name(ext_id) register_actions(self._ext_name, self) # add new menu try: import omni.kit.menu.utils from omni.kit.menu.utils import MenuItemDescription self._menu_entry = [ MenuItemDescription(name="Utilities", sub_menu= [MenuItemDescription( name=ActivityWindowExtension.PROGRESS_WINDOW_NAME, ticked=True, ticked_fn=self._is_progress_visible, onclick_action=("omni.activity.ui", "show_activity_window"), )] ) ] omni.kit.menu.utils.add_menu_items(self._menu_entry, name="Window") except (ModuleNotFoundError, AttributeError): # pragma: no cover pass # Listen for the app ready event startup_event_stream = omni.kit.app.get_app().get_startup_event_stream() self._app_ready_sub = startup_event_stream.create_subscription_to_pop_by_type( omni.kit.app.EVENT_APP_READY, self._on_app_ready, name="Omni Activity" ) # Listen to USD stage activity stage_event_stream = omni.usd.get_context().get_stage_event_stream() self._stage_event_sub = stage_event_stream.create_subscription_to_pop( self._on_stage_event, name="Omni Activity" ) self._activity_widget_subscription = register_open_stage_addon(self._open_file_addon) self._activity_widget_live_subscription = get_live_syncing().register_open_stage_addon(self._open_file_addon) # subscribe the callback to show the progress window when the prompt window disappears # self._show_window_subscription = register_open_stage_complete(self._show_progress_window) # message bus to update the status bar self.__subscription = None self.name_progress = carb.events.type_from_string("omni.kit.window.status_bar@progress") self.name_activity = carb.events.type_from_string("omni.kit.window.status_bar@activity") self.name_clicked = carb.events.type_from_string("omni.kit.window.status_bar@clicked") self.message_bus = omni.kit.app.get_app().get_message_bus_event_stream() # subscribe the callback to show the progress window when user clicks the status bar's progress area self.__statusbar_click_subscription = self.message_bus.create_subscription_to_pop_by_type( self.name_clicked, lambda e: self._show_progress_window()) # watch the commands commands = ["AddReference", "CreatePayload", "CreateSublayer", "ReplacePayload", "ReplaceReference"] self.__command_callback_ids = [ omni.kit.commands.register_callback( cb, omni.kit.commands.PRE_DO_CALLBACK, partial(ActivityWindowExtension._on_command, weakref.proxy(self), cb), ) for cb in commands ] # Set up singleton instance global g_singleton g_singleton = self def _show_progress_window(self): ui.Workspace.show_window(ActivityWindowExtension.PROGRESS_WINDOW_NAME) self._progress_bar.focus() def _on_app_ready(self, event): if not self.__activity_started: # Start an activity trace to measure the time between app ready and the first frame. # This may have already happened in _on_stage_event if an empty stage was opened at startup. self._start_activity(STARTUP_ACTIVITY_FILENAME, profiler_mask=omni.activity.profiler.CAPTURE_MASK_STARTUP) self._app_ready_sub = None rendering_event_stream = omni.usd.get_context().get_rendering_event_stream() self._new_frame_sub = rendering_event_stream.create_subscription_to_push_by_type( omni.usd.StageRenderingEventType.NEW_FRAME, self._on_new_frame, name="Omni Activity" ) def _on_new_frame(self, event): # Stop the activity trace measuring the time between app ready and the first frame. self._stop_activity(completed=True, filename=STARTUP_ACTIVITY_FILENAME) self._new_frame_sub = None def _on_stage_event(self, event): OPENING = int(omni.usd.StageEventType.OPENING) OPEN_FAILED = int(omni.usd.StageEventType.OPEN_FAILED) ASSETS_LOADED = int(omni.usd.StageEventType.ASSETS_LOADED) if event.type is OPENING: path = event.payload.get("val", None) capture_mask = omni.activity.profiler.CAPTURE_MASK_SCENE_LOADING if self._app_ready_sub != None: capture_mask |= omni.activity.profiler.CAPTURE_MASK_STARTUP path = STARTUP_ACTIVITY_FILENAME self._start_activity(path, profiler_mask=capture_mask) elif event.type is OPEN_FAILED: self._stop_activity(completed=False) elif event.type is ASSETS_LOADED: self._stop_activity(completed=True) def _model_changed(self, model, item): self.message_bus.push(self.name_activity, payload={"text": f"{model.latest_item}"}) self.message_bus.push(self.name_progress, payload={"progress": f"{model.total_progress}"}) def on_shutdown(self): global g_singleton g_singleton = None import omni.kit.commands self._app_ready_sub = None self._new_frame_sub = None self._stage_event_sub = None self._progress_menu = None self._current_path = None self.__model = None self.__progress_model= None self.__flatten_model = None # remove actions deregister_actions(self._ext_name) # remove menu try: import omni.kit.menu.utils omni.kit.menu.utils.remove_menu_items(self._menu_entry, name="Window") except (ModuleNotFoundError, AttributeError): # pragma: no cover pass self._menu_entry = None if self._timeline_window: self._timeline_window.destroy() self._timeline_window = None if self._progress_bar: self._progress_bar.destroy() self._progress_bar = None self._addon = None if self._activity_menu_option: self._activity_menu_option.destroy() # Deregister the function that shows the window from omni.ui ui.Workspace.set_show_window_fn(TIMELINE_WINDOW_NAME, None) ui.Workspace.set_show_window_fn(ActivityWindowExtension.PROGRESS_WINDOW_NAME, None) self._activity_widget_subscription = None self._activity_widget_live_subscription = None self._show_window_subscription = None for callback_id in self.__command_callback_ids: omni.kit.commands.unregister_callback(callback_id) async def _destroy_window_async(self): # wait one frame, this is due to the one frame defer # in Window::_moveToMainOSWindow() await omni.kit.app.get_app().next_update_async() if hasattr(self, '_timeline_window') and self._timeline_window: self._timeline_window.destroy() self._timeline_window = None async def _destroy_progress_window_async(self): # wait one frame, this is due to the one frame defer # in Window::_moveToMainOSWindow() await omni.kit.app.get_app().next_update_async() if self._progress_bar: self._progress_bar.destroy() self._progress_bar = None def _visiblity_changed_fn(self, visible): # Called when the user pressed "X" if not visible: # Destroy the window, since we are creating new window # in show_window asyncio.ensure_future(self._destroy_window_async()) def _progress_visiblity_changed_fn(self, visible): try: import omni.kit.menu.utils omni.kit.menu.utils.refresh_menu_items("Window") except (ModuleNotFoundError, AttributeError): # pragma: no cover pass if not visible: # Destroy the window, since we are creating new window in show_progress_bar asyncio.ensure_future(self._destroy_progress_window_async()) def _is_progress_visible(self) -> bool: return False if self._progress_bar is None else self._progress_bar.visible def show_window(self, menu, value): if value: self._timeline_window = ActivityWindow( TIMELINE_WINDOW_NAME, weakref.proxy(self.__model) if self.__model else None, activity_menu=self._activity_menu_option, ) self._timeline_window.set_visibility_changed_fn(self._visiblity_changed_fn) elif self._timeline_window: self._timeline_window.visible = False def show_progress_bar(self, menu, value): if value: self._progress_bar = ActivityProgressBarWindow( ActivityWindowExtension.PROGRESS_WINDOW_NAME, self.__flatten_model, activity_menu=self._activity_menu_option, width=415, height=355, ) self._progress_bar.set_visibility_changed_fn(self._progress_visiblity_changed_fn) elif self._progress_bar: self._progress_bar.visible = False def _open_file_addon(self): self._addon = OpenFileAddon() def get_save_data(self): """Save the current model to external file""" if not self.__model: return None return self.__model.get_data() def _save_current_activity(self, fullpath: Optional[str] = None, filename: Optional[str] = None): """ Saves current activity. If the full path is not given it takes the stage name and saves it to the auto save location from settings. It can be URL or contain tokens. """ if fullpath is None: settings = carb.settings.get_settings() auto_save_location = settings.get(AUTO_SAVE_LOCATION) if not auto_save_location: # No auto save location - nothing to do return # Resolve auto save location token = carb.tokens.get_tokens_interface() auto_save_location = token.resolve(auto_save_location) def remove_files(): # only keep the latest 20 activity files, remove the old ones if necessary file_stays = 20 sorted_files = [item for item in Path(auto_save_location).glob("*.activity")] if len(sorted_files) < file_stays: return sorted_files.sort(key=lambda item: item.stat().st_mtime) for item in sorted_files[:-file_stays]: os.remove(item) remove_files() if filename is None: # Extract filename # Current URL current_stage_url = omni.usd.get_context().get_stage_url() # Using clientlib to parse it current_stage_path = Path(omni.client.break_url(current_stage_url).path) # Some usd layers have ":" in name filename = current_stage_path.stem.split(":")[-1] # Construct the full path fullpath = omni.client.combine_urls(auto_save_location + "/", filename + ".activity") if not fullpath: return self._activity_menu_option.save(fullpath) carb.log_info(f"The activity log has been written to ${fullpath}.") def load_data(self, data): """Load the model from the data""" if self.__model: self.__flatten_model.destroy() self.__progress_model.destroy() self.__model.destroy() # Use separate models for Timeline and ProgressBar to mimic realtime model lifecycle. See _start_activity() self.__model = ActivityModelDump(data=data) self.__progress_model = ActivityModelDumpForProgress(data=data) self.__flatten_model = ActivityProgressModel(weakref.proxy(self.__progress_model)) self.__flatten_model.finished_loading() if self._timeline_window: self._timeline_window._menu_new(weakref.proxy(self.__model)) if self._progress_bar: self._progress_bar.new(self.__flatten_model) def _start_activity(self, path: Optional[str] = None, profiler_mask = 0): self.__activity_started = True self._activity_profiler_capture_mask_uid = self._activity_profiler.enable_capture_mask(profiler_mask) # reset all the windows if self.__model: self.__flatten_model.destroy() self.__progress_model.destroy() self.__model.destroy() self._current_path = None self.__model = ActivityModelStageOpen() self.__progress_model = ActivityModelStageOpenForProgress() self.__flatten_model = ActivityProgressModel(weakref.proxy(self.__progress_model)) self.__subscription = None self.clear_status_bar() if self._timeline_window: self._timeline_window._menu_new(weakref.proxy(self.__model)) if self._progress_bar: self._progress_bar.new(self.__flatten_model) if self._addon: self._addon.new(self.__flatten_model) if path: self.__subscription = self.__flatten_model.subscribe_item_changed_fn(self._model_changed) # only when we have a path, we start to record the activity self.__flatten_model.start_loading = True if self._progress_bar: self._progress_bar.start_timer() if self._addon: self._addon.start_timer() self.__model.set_path(path) self.__progress_model.set_path(path) self._current_path = path def _stop_activity(self, completed=True, filename: Optional[str] = None): # ASSETS_LOADED could be triggered by many things e.g. selection change # make sure we only enter this function once when the activity stops if not self.__activity_started: return self.__activity_started = False if self._activity_profiler_capture_mask_uid != 0: self._activity_profiler.disable_capture_mask(self._activity_profiler_capture_mask_uid) self._activity_profiler_capture_mask_uid = 0 if self.__model: self.__model.end() if self.__progress_model: self.__progress_model.end() if self._current_path: if self._progress_bar: self._progress_bar.stop_timer() if self._addon: self._addon.stop_timer() if completed: # make sure the progress is 1 when assets loaded if self.__flatten_model: self.__flatten_model.finished_loading() self.message_bus.push(self.name_progress, payload={"progress": "1.0"}) self._save_current_activity(filename = filename) self.clear_status_bar() def clear_status_bar(self): # send an empty message to status bar self.message_bus.push(self.name_activity, payload={"text": ""}) # clear the progress bar widget self.message_bus.push(self.name_progress, payload={"progress": "-1"}) def _on_command(self, command: str, kwargs: Dict[str, Any]): if command == "AddReference": path = kwargs.get("reference", None) if path: path = path.assetPath self._start_activity(path) elif command == "CreatePayload": path = kwargs.get("asset_path", None) self._start_activity(path) elif command == "CreateSublayer": path = kwargs.get("new_layer_path", None) self._start_activity(path) elif command == "ReplacePayload": path = kwargs.get("new_payload", None) if path: path = path.assetPath self._start_activity(path) elif command == "ReplaceReference": path = kwargs.get("new_reference", None) if path: path = path.assetPath self._start_activity(path)
19,658
Python
39.367556
134
0.626717
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_progress_model.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ActivityProgressModel"] import weakref from dataclasses import dataclass from typing import Dict, List, Set from functools import partial import omni.ui as ui import omni.activity.core import time from urllib.parse import unquote from .activity_model import ActivityModel, SECOND_MULTIPLIER moving_window = 20 class ActivityProgressModel(ui.AbstractItemModel): """ The model that takes the source model and filters out the items that are outside of the given time range. """ def __init__(self, source: ActivityModel, **kwargs): super().__init__() self._flattened_children = [] self._latest_item = None self.usd_loaded_sum = 0 self.usd_sum = 0 self.usd_progress = 0 self.usd_size = 0 self.usd_speed = 0 self.texture_loaded_sum = 0 self.texture_sum = 0 self.texture_progress = 0 self.texture_size = 0 self.texture_speed = 0 self.material_loaded_sum = 0 self.material_sum = 0 self.material_progress = 0 self.total_loaded_sum = 0 self.total_sum = 0 self.total_progress = 0 self.start_loading = False self.finish_loading = False self.total_duration = 0 current_time = time.time() self.prev_usd_update_time = current_time self.prev_texture_update_time = current_time self.texture_data = [(0, current_time)] self.usd_data = [(0, current_time)] self.__source: ActivityModel = source self.__subscription = self.__source.subscribe_item_changed_fn( partial(ActivityProgressModel._source_changed, weakref.proxy(self)) ) self.activity = omni.activity.core.get_instance() self._load_data_from_source(self.__source) def update_USD(self, item): self.usd_loaded_sum = item.loaded_children_num self.usd_sum = len(item.children) self.usd_progress = 0 if self.usd_sum == 0 else self.usd_loaded_sum / float(self.usd_sum) loaded_size = item.children_size * 0.000001 if loaded_size != self.usd_size: current_time = time.time() self.usd_data.append((loaded_size, current_time)) if len(self.usd_data) > moving_window: self.usd_data.pop(0) prev_size, prev_time = self.usd_data[0] self.usd_speed = (loaded_size - prev_size) / (current_time - prev_time) self.prev_usd_update_time = current_time self.usd_size = loaded_size def update_textures(self, item): self.texture_loaded_sum = item.loaded_children_num self.texture_sum = len(item.children) self.texture_progress = 0 if self.texture_sum == 0 else self.texture_loaded_sum / float(self.texture_sum) loaded_size = item.children_size * 0.000001 if loaded_size != self.texture_size: current_time = time.time() self.texture_data.append((loaded_size, current_time)) if len(self.texture_data) > moving_window: self.texture_data.pop(0) prev_size, prev_time = self.texture_data[0] if current_time == prev_time: return self.texture_speed = (loaded_size - prev_size) / (current_time - prev_time) self.prev_texture_update_time = current_time self.texture_size = loaded_size def update_materials(self, item): self.material_loaded_sum = item.loaded_children_num self.material_sum = len(item.children) self.material_progress = 0 if self.material_sum == 0 else self.material_loaded_sum / float(self.material_sum) def update_total(self): self.total_sum = self.usd_sum + self.texture_sum + self.material_sum self.total_loaded_sum = self.usd_loaded_sum + self.texture_loaded_sum + self.material_loaded_sum self.total_progress = 0 if self.total_sum == 0 else self.total_loaded_sum / float(self.total_sum) def _load_data_from_source(self, model): if not model or not model.get_item_children(None): return for child in model.get_item_children(None): name = child.name_model.as_string if name == "Materials": self.update_materials(child) elif name in ["USD", "Textures"]: items = model.get_item_children(child) for item in items: item_name = item.name_model.as_string if item_name == "Read": self.update_USD(item) elif item_name == "Load": self.update_textures(item) self.update_total() if model._time_begin and model._time_end: self.total_duration = int((model._time_end - model._time_begin) / float(SECOND_MULTIPLIER)) def _source_changed(self, model, item): name = item.name_model.as_string if name in ["Read", "Load", "Materials"]: if name == "Read": self.update_USD(item) elif name == "Load": self.update_textures(item) elif name == "Materials": self.update_materials(item) self.update_total() # telling the tree root that the list is changing self._item_changed(None) def finished_loading(self): if self.__source._time_begin and self.__source._time_end: self.total_duration = int((self.__source._time_end - self.__source._time_begin) / float(SECOND_MULTIPLIER)) else: self.total_duration = self.duration self.finish_loading = True # sometimes ASSETS_LOADED isn't called when stage is completely finished loading, # so we force progress to be 1 when we decided that it's finished loading. self.usd_loaded_sum = self.usd_sum self.usd_progress = 1 self.texture_loaded_sum = self.texture_sum self.texture_progress = 1 self.material_loaded_sum = self.material_sum self.material_progress = 1 self.total_loaded_sum = self.total_sum self.total_progress = 1 self._item_changed(None) @property def time_begin(self): return self.__source._time_begin @property def duration(self): if not self.start_loading and not self.finish_loading: return 0 elif self.finish_loading: return self.total_duration elif self.start_loading and not self.finish_loading: current_timestamp = self.activity.current_timestamp duration = (current_timestamp - self.time_begin) / float(SECOND_MULTIPLIER) return int(duration) @property def latest_item(self): if self.finish_loading: return None if hasattr(self.__source, "_flattened_children") and self.__source._flattened_children: item = self.__source._flattened_children[0] name = item.name_model.as_string short_name = unquote(name.split("/")[-1]) return short_name else: return "" def get_data(self): return self.__source.get_data() def destroy(self): self.__source = None self.__subscription = None self.texture_data = [] self.usd_data = [] def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is None and hasattr(self.__source, "_flattened_children"): return self.__source._flattened_children return [] def get_item_value_model_count(self, item): """The number of columns""" return self.__source.get_item_value_model_count(item) def get_item_value_model(self, item, column_id): """ Return value model. """ return self.__source.get_item_value_model(item, column_id)
8,354
Python
36.977273
119
0.609887
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/style.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["activity_window_style"] from omni.ui import color as cl from omni.ui import constant as fl from omni.ui import url import omni.kit.app import omni.ui as ui import pathlib EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) # Pre-defined constants. It's possible to change them runtime. cl.activity_window_attribute_bg = cl("#1f2124") cl.activity_window_attribute_fg = cl("#0f1115") cl.activity_window_hovered = cl("#FFFFFF") cl.activity_text = cl("#9e9e9e") cl.activity_green = cl("#4FA062") cl.activity_usd_blue = cl("#2091D0") cl.activity_progress_blue = cl("#4F7DA0") cl.activity_purple = cl("#8A6592") fl.activity_window_attr_hspacing = 10 fl.activity_window_attr_spacing = 1 fl.activity_window_group_spacing = 2 # The main style dict activity_window_style = { "Label::attribute_name": { "alignment": ui.Alignment.RIGHT_CENTER, "margin_height": fl.activity_window_attr_spacing, "margin_width": fl.activity_window_attr_hspacing, }, "Label::attribute_name:hovered": {"color": cl.activity_window_hovered}, "Label::collapsable_name": {"alignment": ui.Alignment.LEFT_CENTER}, "Label::time": {"font_size": 12, "color": cl.activity_text, "alignment": ui.Alignment.LEFT_CENTER}, "Label::selection_time": {"font_size": 12, "color": cl("#34C7FF")}, "Line::timeline": {"color": cl(0.22)}, "Rectangle::selected_area": {"background_color": cl(1.0, 1.0, 1.0, 0.1)}, "Slider::attribute_int:hovered": {"color": cl.activity_window_hovered}, "Slider": { "background_color": cl.activity_window_attribute_bg, "draw_mode": ui.SliderDrawMode.HANDLE, }, "Slider::attribute_float": { "draw_mode": ui.SliderDrawMode.FILLED, "secondary_color": cl.activity_window_attribute_fg, }, "Slider::attribute_float:hovered": {"color": cl.activity_window_hovered}, "Slider::attribute_vector:hovered": {"color": cl.activity_window_hovered}, "Slider::attribute_color:hovered": {"color": cl.activity_window_hovered}, "CollapsableFrame::group": {"margin_height": fl.activity_window_group_spacing}, "Button::options": {"background_color": 0x0, "margin": 0}, "Button.Image::options": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/options.svg", "color": cl.activity_text}, "RadioButton": {"background_color": cl.transparent}, "RadioButton.Label": {"font_size": 14, "color": cl("#A1A1A1")}, "RadioButton.Label:checked": {"font_size": 14, "color": cl("#34C7FF")}, "RadioButton:checked": {"background_color": cl.transparent}, "RadioButton:hovered": {"background_color": cl.transparent}, "RadioButton:pressed": {"background_color": cl.transparent}, "Rectangle::separator": {"background_color": cl("#707070"), "border_radius": 1.5}, "TreeView.Label": {"color": cl.activity_text}, "TreeView.Label.Right": {"color": cl.activity_text, "alignment": ui.Alignment.RIGHT_CENTER}, "Rectangle::spacer": {"background_color": cl("#1F2123")}, "ScrollingFrame": {"background_color": cl("#1F2123")}, "Label::USD": {"color": cl.activity_usd_blue}, "Label::progress": {"color": cl.activity_progress_blue}, "Label::material": {"color": cl.activity_purple}, "Label::undefined": {"color": cl.activity_text}, "Label::unfinished": {"color": cl.lightsalmon}, "Icon::USD": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/USD.svg"}, "Icon::progress": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/progress.svg", "color": cl.activity_progress_blue}, "Icon::material": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/Material.png"}, "Icon::texture": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/Texture.svg"}, "Icon::file": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/file.svg"}, } progress_window_style = { "RadioButton": {"background_color": cl.transparent}, "RadioButton.Label": {"font_size": 14, "color": cl("#A1A1A1")}, "RadioButton.Label:checked": {"font_size": 14, "color": cl("#34C7FF")}, "RadioButton:checked": {"background_color": cl.transparent}, "RadioButton:hovered": {"background_color": cl.transparent}, "RadioButton:pressed": {"background_color": cl.transparent}, "Rectangle::separator": {"background_color": cl("#707070"), "border_radius": 1.5}, "ProgressBar::texture": {"border_radius": 0, "color": cl.activity_green, "background_color": cl("#606060")}, "ProgressBar::USD": {"border_radius": 0, "color": cl.activity_usd_blue, "background_color": cl("#606060")}, "ProgressBar::material": {"border_radius": 0, "color": cl.activity_purple, "background_color": cl("#606060")}, "ProgressBar::progress": {"border_radius": 0, "color": cl.activity_progress_blue, "background_color": cl("#606060"), "secondary_color": cl.transparent}, "Button::options": {"background_color": 0x0, "margin": 0}, "Button.Image::options": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/options.svg", "color": cl.activity_text}, "TreeView.Label": {"color": cl.activity_text}, "TreeView.Label.Right": {"color": cl.activity_text, "alignment": ui.Alignment.RIGHT_CENTER}, "Label::USD": {"color": cl.activity_usd_blue}, "Label::progress": {"color": cl.activity_progress_blue}, "Label::material": {"color": cl.activity_purple}, "Label::undefined": {"color": cl.activity_text}, "Label::unfinished": {"color": cl.lightsalmon}, "ScrollingFrame": {"background_color": cl("#1F2123")}, "Icon::USD": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/USD.svg"}, "Icon::progress": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/progress.svg", "color": cl.activity_progress_blue}, "Icon::material": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/Material.png"}, "Icon::texture": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/Texture.svg"}, "Icon::file": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/file.svg"}, "Tree.Branch::Minus": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/Minus.svg", "color": cl("#707070")}, "Tree.Branch::Plus": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/Plus.svg", "color": cl("#707070")}, } def get_shade_from_name(name: str): #--------------------------------------- if name == "USD": return cl("#2091D0") elif name == "Read": return cl("#1A75A8") elif name == "Resolve": return cl("#16648F") elif name.endswith((".usd", ".usda", ".usdc", ".usdz")): return cl("#13567B") #--------------------------------------- elif name == "Stage": return cl("#d43838") elif name.startswith("Opening"): return cl("#A12A2A") #--------------------------------------- elif name == "Render Thread": return cl("#d98927") elif name == "Execute": return cl("#A2661E") elif name == "Post Sync": return cl("#626262") #---------------------------------------- elif name == "Textures": return cl("#4FA062") elif name == "Load": return cl("#3C784A") elif name == "Queue": return cl("#31633D") elif name.endswith(".hdr"): return cl("#34A24E") elif name.endswith(".png"): return cl("#2E9146") elif name.endswith(".jpg") or name.endswith(".JPG"): return cl("#2B8741") elif name.endswith(".ovtex"): return cl("#287F3D") elif name.endswith(".dds"): return cl("#257639") elif name.endswith(".exr"): return cl("#236E35") elif name.endswith(".wav"): return cl("#216631") elif name.endswith(".tga"): return cl("#1F5F2D") #--------------------------------------------- elif name == "Materials": return cl("#8A6592") elif name.endswith(".mdl"): return cl("#76567D") elif "instance)" in name: return cl("#694D6F") elif name == "Compile": return cl("#5D4462") elif name == "Create Shader Variations": return cl("#533D58") elif name == "Load Textures": return cl("#4A374F") #--------------------------------------------- elif name == "Meshes": return cl("#626262") #--------------------------------------------- elif name == "Ray Tracing Pipeline": return cl("#8B8000") else: return cl("#555555")
8,708
Python
43.661538
156
0.615641