file_path
stringlengths 21
202
| content
stringlengths 19
1.02M
| size
int64 19
1.02M
| lang
stringclasses 8
values | avg_line_length
float64 5.88
100
| max_line_length
int64 12
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/transform_mode_model.py | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
import carb
import carb.dictionary
import carb.settings
class TransformModeModel(ui.AbstractValueModel):
"""The value model that is reimplemented in Python to watch the prim select mode"""
TRANSFORM_OP_SETTING = "/app/transform/operation"
TRANSFORM_OP_SELECT = "select"
TRANSFORM_OP_MOVE = "move"
TRANSFORM_OP_ROTATE = "rotate"
TRANSFORM_OP_SCALE = "scale"
def __init__(self, op):
super().__init__()
self._op = op
self._settings = carb.settings.get_settings()
self._settings.set_default_string(self.TRANSFORM_OP_SETTING, self.TRANSFORM_OP_MOVE)
self._dict = carb.dictionary.get_dictionary()
self._op_sub = self._settings.subscribe_to_node_change_events(self.TRANSFORM_OP_SETTING, self._on_op_change)
self._selected_op = self._settings.get(self.TRANSFORM_OP_SETTING)
def clean(self):
self._settings.unsubscribe_to_change_events(self._op_sub)
def _on_op_change(self, item, event_type):
self._selected_op = self._dict.get(item)
self._value_changed()
def _on_op_space_changed(self, item, event_type): # pragma: no cover (Seems to never be used, is overwritten in the inherited model where it is used.)
self._op_space = self._dict.get(item)
self._value_changed()
def get_value_as_bool(self):
return self._selected_op == self._op
def set_value(self, value):
"""Reimplemented set bool"""
if value:
self._settings.set(self.TRANSFORM_OP_SETTING, self._op)
class LocalGlobalTransformModeModel(TransformModeModel):
TRANSFORM_MODE_GLOBAL = "global"
TRANSFORM_MODE_LOCAL = "local"
def __init__(self, op, op_space_setting_path):
super().__init__(op=op)
self._setting_path = op_space_setting_path
self._op_space_sub = self._settings.subscribe_to_node_change_events(
self._setting_path, self._on_op_space_changed
)
self._op_space = self._settings.get(self._setting_path)
def clean(self):
self._settings.unsubscribe_to_change_events(self._op_space_sub)
super().clean()
def _on_op_space_changed(self, item, event_type):
self._op_space = self._dict.get(item)
self._value_changed()
def get_op_space_mode(self):
return self._op_space
def set_value(self, value):
if not value:
self._settings.set(
self._setting_path,
self.TRANSFORM_MODE_LOCAL
if self._op_space == self.TRANSFORM_MODE_GLOBAL
else self.TRANSFORM_MODE_GLOBAL,
)
super().set_value(value)
| 3,104 | Python | 33.5 | 155 | 0.653351 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/setting_model.py | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
import carb
import carb.dictionary
import carb.settings
class BoolSettingModel(ui.AbstractValueModel):
"""The value model that is reimplemented in Python to watch a bool setting path"""
def __init__(self, setting_path, inverted):
super().__init__()
self._setting_path = setting_path
self._inverted = inverted
self._settings = carb.settings.get_settings()
self._dict = carb.dictionary.get_dictionary()
self._subscription = self._settings.subscribe_to_node_change_events(self._setting_path, self._on_change)
self._value = self._settings.get(self._setting_path)
if self._inverted:
self._value = not self._value
def clean(self):
self._settings.unsubscribe_to_change_events(self._subscription)
def _on_change(self, item, event_type):
self._value = self._dict.get(item)
if self._inverted:
self._value = not self._value
self._value_changed()
def get_value_as_bool(self):
return self._value
def set_value(self, value):
"""Reimplemented set bool"""
if self._inverted:
value = not value
self._settings.set(self._setting_path, value)
if self._inverted:
self._value = value
class FloatSettingModel(ui.AbstractValueModel):
"""The value model that is reimplemented in Python to watch a float setting path"""
def __init__(self, setting_path):
super().__init__()
self._setting_path = setting_path
self._settings = carb.settings.get_settings()
self._dict = carb.dictionary.get_dictionary()
self._subscription = self._settings.subscribe_to_node_change_events(self._setting_path, self._on_change)
self._value = self._settings.get(self._setting_path)
def clean(self):
self._settings.unsubscribe_to_change_events(self._subscription)
def _on_change(self, item, event_type):
self._value = self._dict.get(item)
self._value_changed()
def get_value_as_float(self):
return self._value
def set_value(self, value):
"""Reimplemented set float"""
self._settings.set(self._setting_path, value)
| 2,654 | Python | 34.4 | 112 | 0.662773 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/timeline_model.py | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
import carb
import omni.timeline
from omni.kit.commands import execute
class TimelinePlayPauseModel(ui.AbstractValueModel):
"""The value model that is reimplemented in Python to watch a bool setting path"""
def __init__(self):
super().__init__()
self._timeline = omni.timeline.get_timeline_interface()
self._is_playing = self._timeline.is_playing()
self._is_stopped = self._timeline.is_stopped()
stream = self._timeline.get_timeline_event_stream()
self._sub = stream.create_subscription_to_pop(self._on_timeline_event)
def clean(self):
self._sub = None
def get_value_as_bool(self):
return self._is_playing and not self._is_stopped
def set_value(self, value):
"""Reimplemented set bool"""
if value:
execute("ToolbarPlayButtonClicked")
else:
execute("ToolbarPauseButtonClicked")
def _on_timeline_event(self, e):
is_playing = self._timeline.is_playing()
is_stopped = self._timeline.is_stopped()
if is_playing != self._is_playing or is_stopped != self._is_stopped:
self._is_playing = self._timeline.is_playing()
self._is_stopped = self._timeline.is_stopped()
self._value_changed()
| 1,732 | Python | 34.367346 | 86 | 0.67552 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/select_mode_model.py | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
import carb
import carb.dictionary
import carb.settings
class SelectModeModel(ui.AbstractValueModel):
"""The value model that is reimplemented in Python to watch the prim select mode"""
PICKING_MODE_SETTING = "/persistent/app/viewport/pickingMode"
PICKING_MODE_MODELS = "kind:model.ALL"
PICKING_MODE_PRIMS = "type:ALL"
# new default
PICKING_MODE_DEFAULT = PICKING_MODE_PRIMS
def __init__(self):
super().__init__()
self._settings = carb.settings.get_settings()
self._settings.set_default_string(self.PICKING_MODE_SETTING, self.PICKING_MODE_DEFAULT)
self._dict = carb.dictionary.get_dictionary()
self._subscription = self._settings.subscribe_to_node_change_events(self.PICKING_MODE_SETTING, self._on_change)
self.set_value(self._settings.get(self.PICKING_MODE_SETTING))
def clean(self):
self._settings.unsubscribe_to_change_events(self._subscription)
def _on_change(self, item, event_type):
self._mode = self._dict.get(item)
self._value_changed()
def get_value_as_bool(self):
return self._mode == self.PICKING_MODE_PRIMS
def get_value_as_string(self):
return self._mode
def set_value(self, value):
if isinstance(value, bool):
if value:
self._mode = self.PICKING_MODE_PRIMS
else:
self._mode = self.PICKING_MODE_MODELS
else:
self._mode = value
self._settings.set(self.PICKING_MODE_SETTING, self._mode)
| 1,993 | Python | 32.79661 | 119 | 0.67988 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/select_no_kinds_model.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
import carb
import carb.dictionary
import carb.settings
class SelectNoKindsModel(ui.AbstractValueModel):
"""The value model that is reimplemented in Python to watch the prim select mode"""
PICKING_MODE_NO_KINDS_SETTING = "/persistent/app/viewport/pickingModeNoKinds"
# new default
PICKING_MODE_NO_KINDS_DEFAULT = True
def __init__(self):
super().__init__()
self._settings = carb.settings.get_settings()
self._settings.set_default_bool(self.PICKING_MODE_NO_KINDS_SETTING, self.PICKING_MODE_NO_KINDS_DEFAULT)
self._dict = carb.dictionary.get_dictionary()
self._subscription = self._settings.subscribe_to_node_change_events(self.PICKING_MODE_NO_KINDS_SETTING, self._on_change)
self.set_value(self._settings.get(self.PICKING_MODE_NO_KINDS_SETTING))
def clean(self):
self._settings.unsubscribe_to_change_events(self._subscription)
def _on_change(self, item, event_type):
self._mode = self._dict.get(item)
self._value_changed()
def get_value_as_bool(self):
return self._mode
def set_value(self, value):
self._mode = value
self._settings.set(self.PICKING_MODE_NO_KINDS_SETTING, self._mode)
| 1,680 | Python | 34.765957 | 128 | 0.713095 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/tests/helpers.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb.settings
def reset_toolbar_settings():
settings = carb.settings.get_settings()
vals = {
"/app/transform/operation": "move",
"/persistent/app/viewport/pickingMode": "type:ALL",
"/app/viewport/snapEnabled": False,
}
for key, val in vals.items():
settings.set(key, val)
| 759 | Python | 32.043477 | 76 | 0.724638 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/tests/test_api.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import carb.settings
import omni.appwindow
import omni.kit.app
import omni.kit.test
import omni.timeline
import omni.kit.ui_test as ui_test
import omni.kit.widget.toolbar
import omni.kit.context_menu
import omni.kit.hotkeys.core
import omni.ui as ui
from carb.input import KeyboardInput as Key
from carb.input import KEYBOARD_MODIFIER_FLAG_SHIFT
from omni.kit.ui_test import Vec2
from omni.kit.widget.toolbar import Hotkey, SimpleToolButton, Toolbar, WidgetGroup, get_instance
from .helpers import reset_toolbar_settings
test_message_queue = []
class TestSimpleToolButton(SimpleToolButton):
"""
Test of how to use SimpleToolButton
"""
def __init__(self, icon_path):
def on_toggled(c):
test_message_queue.append(f"Test button toggled {c}")
super().__init__(
name="test_simple_tool_button",
tooltip="Test Simple ToolButton",
icon_path=f"{icon_path}/plus.svg",
icon_checked_path=f"{icon_path}/plus.svg",
hotkey=Key.U,
toggled_fn=on_toggled,
additional_style={"Button": { "color": 0xffffffff }}
)
class TestToolButtonGroup(WidgetGroup):
"""
Test of how to create two ToolButton in one WidgetGroup
"""
def __init__(self, icon_path):
super().__init__()
self._icon_path = icon_path
def clean(self):
self._sub1 = None
self._sub2 = None
self._hotkey.clean()
self._hotkey = None
super().clean()
def get_style(self):
style = {
"Button.Image::test1": {"image_url": f"{self._icon_path}/plus.svg"},
"Button.Image::test1:checked": {"image_url": f"{self._icon_path}/minus.svg"},
"Button.Image::test2": {"image_url": f"{self._icon_path}/minus.svg"},
"Button.Image::test2:checked": {"image_url": f"{self._icon_path}/plus.svg"},
}
return style
def create(self, default_size):
def on_value_changed(index, model):
if model.get_value_as_bool():
self._acquire_toolbar_context()
else:
self._release_toolbar_context()
test_message_queue.append(f"Group button {index} clicked")
self._menu1 = omni.kit.context_menu.add_menu({ "name": "Test 1", "onclick_fn": None }, "test1", "omni.kit.widget.toolbar")
self._menu2 = omni.kit.context_menu.add_menu({ "name": "Test 2", "onclick_fn": None }, "test1", "omni.kit.widget.toolbar")
button1 = ui.ToolButton(
name="test1",
width=default_size,
height=default_size,
mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "test1"),
mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b),
)
self._sub1 = button1.model.subscribe_value_changed_fn(lambda model, index=1: on_value_changed(index, model))
button2 = ui.ToolButton(
name="test2",
width=default_size,
height=default_size,
)
self._sub2 = button2.model.subscribe_value_changed_fn(lambda model, index=2: on_value_changed(index, model))
self._hotkey = Hotkey(
"toolbar::test2",
Key.K,
lambda: button2.model.set_value(not button2.model.get_value_as_bool()),
lambda: self._is_in_context(),
)
# return a dictionary of name -> widget if you want to expose it to other widget_group
return {"test1": button1, "test2": button2}
_MAIN_WINDOW_INSTANCE = None
class ToolbarApiTest(omni.kit.test.AsyncTestCase):
WINDOW_NAME = "Main Toolbar Test"
async def setUp(self):
reset_toolbar_settings()
self._icon_path = omni.kit.widget.toolbar.get_data_path().absolute().joinpath("icon").absolute()
self._app = omni.kit.app.get_app()
test_message_queue.clear()
# If the instance doesn't exist, we need to create it for the test
# Create a tmp window with the widget inside, Y axis because the tests are in the Y axis
global _MAIN_WINDOW_INSTANCE
if _MAIN_WINDOW_INSTANCE is None:
_MAIN_WINDOW_INSTANCE = ui.ToolBar(
self.WINDOW_NAME, noTabBar=False, padding_x=3, padding_y=3, margin=5, axis=ui.ToolBarAxis.Y
)
self._widget = get_instance()
self._widget.set_axis(ui.ToolBarAxis.Y)
self._widget.rebuild_toolbar(root_frame=_MAIN_WINDOW_INSTANCE.frame)
await self._app.next_update_async()
await self._app.next_update_async()
self._main_dockspace = ui.Workspace.get_window("DockSpace")
self._toolbar_handle = ui.Workspace.get_window(self.WINDOW_NAME)
self._toolbar_handle.undock()
await self._app.next_update_async()
self._toolbar_handle.dock_in(self._main_dockspace, ui.DockPosition.LEFT)
await self._app.next_update_async()
async def test_api(self):
toolbar: Toolbar = omni.kit.widget.toolbar.get_instance()
widget_simple = TestSimpleToolButton(self._icon_path)
widget = TestToolButtonGroup(self._icon_path)
toolbar.add_widget(widget, -100)
toolbar.add_widget(widget_simple, -200)
await self._app.next_update_async()
self.assertIsNotNone(widget_simple.get_tool_button())
# Check widgets are added and can be fetched
self.assertIsNotNone(toolbar.get_widget("test_simple_tool_button"))
self.assertIsNotNone(toolbar.get_widget("test1"))
self.assertIsNotNone(toolbar.get_widget("test2"))
await self._app.next_update_async()
await self._app.next_update_async()
await self._app.next_update_async()
await self._app.next_update_async()
await self._app.next_update_async()
manager = omni.kit.app.get_app().get_extension_manager()
extension_name = omni.ext.get_extension_name(manager.get_extension_id_by_module(__name__))
hotkey_registry = omni.kit.hotkeys.core.get_hotkey_registry()
hotkey = self._get_hotkey('test_simple_tool_button::hotkey')
self.assertIsNotNone(hotkey)
hotkey_registry.edit_hotkey(hotkey, omni.kit.hotkeys.core.KeyCombination(Key.U, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None)
tool_test_simple_pos = self._get_widget_center(toolbar, "test_simple_tool_button")
tool_test1_pos = self._get_widget_center(toolbar, "test1")
tool_test2_pos = self._get_widget_center(toolbar, "test2")
# Test click on first simple button
await self._emulate_click(tool_test_simple_pos)
await self._app.next_update_async()
# Test hot key on first simple button
await self._emulate_keyboard_press(Key.U, KEYBOARD_MODIFIER_FLAG_SHIFT)
await self._app.next_update_async()
# Test click on 1/2 group button
await self._emulate_click(tool_test1_pos)
await self._app.next_update_async()
# Test click on 2/2 group button
await self._emulate_click(tool_test2_pos)
await self._app.next_update_async()
# Test click on 2/2 group button again
await self._emulate_click(tool_test2_pos)
await self._app.next_update_async()
self.assertIsNone(ui.Menu.get_current())
# Test right click on 1/2 group button
await self._emulate_click(tool_test1_pos, right_click=True)
await self._app.next_update_async()
self.assertIsNotNone(ui.Menu.get_current())
# Test left click on 1/2 group button to close the menu
await self._emulate_click(tool_test1_pos, right_click=False)
await self._app.next_update_async()
self.assertIsNone(ui.Menu.get_current())
# Test hold-left-click click on 1/2 group button
await ui_test.input.emulate_mouse(ui_test.input.MouseEventType.MOVE, Vec2(*tool_test1_pos))
await ui_test.input.emulate_mouse(ui_test.input.MouseEventType.LEFT_BUTTON_DOWN)
await self._app.next_update_async()
await asyncio.sleep(0.4)
await ui_test.input.emulate_mouse(ui_test.input.MouseEventType.LEFT_BUTTON_UP)
await self._app.next_update_async()
self.assertIsNotNone(ui.Menu.get_current())
# Test left click on 1/2 group button to close the menu
await self._emulate_click(tool_test1_pos)
await self._app.next_update_async()
self.assertIsNone(ui.Menu.get_current())
# Making sure all button are triggered by checking the message queue
expected_messages = [
"Test button toggled True",
"Test button toggled False",
"Group button 1 clicked",
"Group button 2 clicked",
"Group button 2 clicked",
]
self.assertEqual(expected_messages, test_message_queue)
test_message_queue.clear()
hotkey_registry.edit_hotkey(hotkey, omni.kit.hotkeys.core.KeyCombination(Key.U, modifiers=0), None)
toolbar.remove_widget(widget)
toolbar.remove_widget(widget_simple)
widget.clean()
widget_simple.clean()
await self._app.next_update_async()
# Check widgets are cleared
self.assertIsNone(toolbar.get_widget("test_simple_tool_button"))
self.assertIsNone(toolbar.get_widget("test1"))
self.assertIsNone(toolbar.get_widget("test2"))
# Change the Hotkey for the Play button
play_hotkey = self._get_hotkey('toolbar::play')
self.assertIsNotNone(play_hotkey)
hotkey_registry.edit_hotkey(play_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.SPACE, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None)
await self._app.next_update_async()
tooltip_after_change = toolbar.get_widget('play').tooltip
hotkey_registry.edit_hotkey(play_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.SPACE, modifiers=0), None)
await self._app.next_update_async()
tooltip_after_revert = toolbar.get_widget('play').tooltip
self.assertEqual(tooltip_after_change, "Play (SHIFT + SPACE)")
self.assertEqual(tooltip_after_revert, "Play (SPACE)")
# Change the Hotkey for the Select Mode button
select_mode_hotkey = self._get_hotkey('toolbar::select_mode')
self.assertIsNotNone(select_mode_hotkey)
hotkey_registry.edit_hotkey(select_mode_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.T, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None)
await self._app.next_update_async()
tooltip_after_change = toolbar.get_widget('select_mode').tooltip
hotkey_registry.edit_hotkey(select_mode_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.T, modifiers=0), None)
await self._app.next_update_async()
tooltip_after_revert = toolbar.get_widget('select_mode').tooltip
self.assertEqual(tooltip_after_change, "All Prim Types (SHIFT + T)")
self.assertEqual(tooltip_after_revert, "All Prim Types (T)")
# Change the Hotkey for the Move button
move_op_hotkey = self._get_hotkey('toolbar::move')
self.assertIsNotNone(move_op_hotkey)
hotkey_registry.edit_hotkey(move_op_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.W, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None)
await self._app.next_update_async()
tooltip_after_change = toolbar.get_widget('move_op').tooltip
hotkey_registry.edit_hotkey(move_op_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.W, modifiers=0), None)
await self._app.next_update_async()
tooltip_after_revert = toolbar.get_widget('move_op').tooltip
from ..builtin_tools.transform_button_group import MOVE_TOOL_NAME
self.assertEqual(tooltip_after_change, f"{MOVE_TOOL_NAME} (SHIFT + W)")
self.assertEqual(tooltip_after_revert, f"{MOVE_TOOL_NAME} (W)")
# Test the Select Mode hotkey button
settings = carb.settings.get_settings()
from ..builtin_tools.models.select_mode_model import SelectModeModel
self.assertEqual(settings.get(SelectModeModel.PICKING_MODE_SETTING), SelectModeModel.PICKING_MODE_PRIMS)
await self._emulate_keyboard_press(Key.T)
await self._app.next_update_async()
self.assertEqual(settings.get(SelectModeModel.PICKING_MODE_SETTING), SelectModeModel.PICKING_MODE_MODELS)
await self._emulate_keyboard_press(Key.T)
await self._app.next_update_async()
self.assertEqual(settings.get(SelectModeModel.PICKING_MODE_SETTING), SelectModeModel.PICKING_MODE_PRIMS)
# Test changing the Select hotkey
select_hotkey = self._get_hotkey('toolbar::select')
self.assertIsNotNone(select_hotkey)
hotkey_registry.edit_hotkey(select_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.Q, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None)
await self._app.next_update_async()
hotkey_registry.edit_hotkey(select_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.Q, modifiers=0), None)
await self._app.next_update_async()
async def test_context(self):
toolbar = omni.kit.widget.toolbar.get_instance()
widget_simple = TestSimpleToolButton(self._icon_path)
widget = TestToolButtonGroup(self._icon_path)
test_context = "test_context"
toolbar.add_widget(widget, -100)
toolbar.add_widget(widget_simple, -200, test_context)
await self._app.next_update_async()
await self._app.next_update_async()
await self._app.next_update_async()
await self._app.next_update_async()
await self._app.next_update_async()
tool_test_simple_pos = self._get_widget_center(toolbar, "test_simple_tool_button")
tool_test1_pos = self._get_widget_center(toolbar, "test1")
# Test click on first simple button
# Add "Test button toggled True" to queue
await self._emulate_click(tool_test_simple_pos)
await self._app.next_update_async()
self.assertEqual(toolbar.get_context(), test_context)
# Test hot key on 2/2 group button
# It should have no effect since it's not "in context"
# Add nothing to queue
await self._emulate_keyboard_press(Key.K)
await self._app.next_update_async()
# Test click on first simple button again, should exit context
# Add "Test button toggled False" to queue
await self._emulate_click(tool_test_simple_pos)
await self._app.next_update_async()
self.assertEqual(toolbar.get_context(), Toolbar.DEFAULT_CONTEXT)
# Test hot key on 2/2 group button again
# It should have effect because it's in default context
# Add "Group button 2 clicked" to queue
await self._emulate_keyboard_press(Key.K)
await self._app.next_update_async()
# Test click on first simple button again
# Add "Test button toggled True" to queue
await self._emulate_click(tool_test_simple_pos)
await self._app.next_update_async()
self.assertEqual(toolbar.get_context(), test_context)
# Test click on 1/2 group button so it takes context by force.
# Add "Group button 1 clicked" to queue
await self._emulate_click(tool_test1_pos)
await self._app.next_update_async()
self.assertEqual(toolbar.get_context(), Toolbar.DEFAULT_CONTEXT)
# Test hot key on first simple button, it should still work on default context.
# Releasing an expired context.
# Add "Test button toggled False" to queue
await self._emulate_keyboard_press(Key.U)
await self._app.next_update_async()
self.assertEqual(toolbar.get_context(), Toolbar.DEFAULT_CONTEXT)
# Test hot key on first simple button, it should still work on default context.
# Add "Test button toggled True" to queue
await self._emulate_keyboard_press(Key.U)
await self._app.next_update_async()
self.assertEqual(toolbar.get_context(), test_context)
expected_messages = [
"Test button toggled True",
"Test button toggled False",
"Group button 2 clicked",
"Test button toggled True",
"Group button 1 clicked",
"Test button toggled False",
"Test button toggled True",
]
self.assertEqual(expected_messages, test_message_queue)
toolbar.remove_widget(widget)
toolbar.remove_widget(widget_simple)
widget.clean()
widget_simple.clean()
await self._app.next_update_async()
def _get_widget_center(self, toolbar, id: str):
return (
toolbar.get_widget(id).screen_position_x + toolbar.get_widget(id).width / 2,
toolbar.get_widget(id).screen_position_y + toolbar.get_widget(id).height / 2,
)
def _get_hotkey(self, action_id: str):
manager = omni.kit.app.get_app().get_extension_manager()
extension_name = omni.ext.get_extension_name(manager.get_extension_id_by_module(__name__))
hotkey_registry = omni.kit.hotkeys.core.get_hotkey_registry()
for hotkey in hotkey_registry.get_all_hotkeys_for_extension(extension_name):
if hotkey.action_id == action_id:
return hotkey
async def _emulate_click(self, pos, right_click: bool = False):
await ui_test.emulate_mouse_move_and_click(Vec2(*pos), right_click=right_click)
async def _emulate_keyboard_press(self, key: Key, modifier: int = 0):
await ui_test.emulate_keyboard_press(key, modifier)
async def test_custom_select_types(self):
toolbar: Toolbar = omni.kit.widget.toolbar.get_instance()
entry_name = 'TestType'
toolbar.add_custom_select_type(entry_name, ['test_type'])
menu_dict = omni.kit.context_menu.get_menu_dict("select_mode", "omni.kit.widget.toolbar")
self.assertIn(entry_name, [item['name'] for item in menu_dict])
toolbar.remove_custom_select(entry_name)
menu_dict = omni.kit.context_menu.get_menu_dict("select_mode", "omni.kit.widget.toolbar")
self.assertNotIn(entry_name, [item['name'] for item in menu_dict])
async def test_toolbar_methods(self):
from ..context_menu import ContextMenu
toolbar: Toolbar = omni.kit.widget.toolbar.get_instance()
self.assertIsInstance(toolbar.context_menu, ContextMenu)
toolbar.set_axis(ui.ToolBarAxis.X)
toolbar.rebuild_toolbar()
await ui_test.human_delay()
toolbar.set_axis(ui.ToolBarAxis.Y)
toolbar.rebuild_toolbar()
await ui_test.human_delay()
toolbar.subscribe_grab_mouse_pressed(None)
async def test_toolbar_play_stop_button(self):
toolbar: Toolbar = omni.kit.widget.toolbar.get_instance()
timeline = omni.timeline.get_timeline_interface()
# Click the stop button
toolbar.get_widget("stop").call_clicked_fn()
await ui_test.human_delay()
self.assertTrue(timeline.is_stopped())
| 19,485 | Python | 39.17732 | 146 | 0.651014 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/tests/__init__.py | from .test_api import *
from .test_models import * | 50 | Python | 24.499988 | 26 | 0.74 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/tests/test_models.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.kit.app
import omni.kit.test
import omni.timeline
import carb.settings
import omni.kit.commands
from omni.kit import ui_test
class ToolbarTestModels(omni.kit.test.AsyncTestCase):
async def test_setting_pass_through(self):
from ..builtin_tools.builtin_tools import LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW, LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET
settings = carb.settings.get_settings()
orig_value = settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET)
settings.set_bool(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW, True)
self.assertEqual(settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW), settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET))
settings.set_bool(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW, False)
self.assertEqual(settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW), settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET))
settings.set_bool(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET, orig_value)
async def test_select_include_ref_model(self):
from ..builtin_tools.models.select_include_ref_model import SelectIncludeRefModel
model = SelectIncludeRefModel()
orig_value = model.get_value_as_bool()
model.set_value(not orig_value)
self.assertEqual(model.get_value_as_bool(), not orig_value)
model.set_value(orig_value)
async def test_select_mode_model(self):
from ..builtin_tools.models.select_mode_model import SelectModeModel
model = SelectModeModel()
orig_value = model.get_value_as_string()
model.set_value(True)
self.assertEqual(model.get_value_as_string(), SelectModeModel.PICKING_MODE_PRIMS)
model.set_value(False)
self.assertEqual(model.get_value_as_string(), SelectModeModel.PICKING_MODE_MODELS)
model.set_value(SelectModeModel.PICKING_MODE_PRIMS)
self.assertEqual(model.get_value_as_string(), SelectModeModel.PICKING_MODE_PRIMS)
model.set_value(orig_value)
async def test_select_no_kinds_model(self):
from ..builtin_tools.models.select_no_kinds_model import SelectNoKindsModel
model = SelectNoKindsModel()
orig_value = model.get_value_as_bool()
model.set_value(not orig_value)
self.assertEqual(model.get_value_as_bool(), not orig_value)
model.set_value(orig_value)
async def test_setting_model(self):
from ..builtin_tools.models.setting_model import BoolSettingModel, FloatSettingModel
settings = carb.settings.get_settings()
bool_setting_path = '/exts/omni.kit.widget.toolbar/test/boolSetting'
float_setting_path = '/exts/omni.kit.widget.toolbar/test/floatSetting'
bool_model = BoolSettingModel(bool_setting_path, False)
bool_model.set_value(True)
self.assertEqual(bool_model.get_value_as_bool(), True)
self.assertEqual(settings.get(bool_setting_path), True)
bool_model.set_value(False)
self.assertEqual(bool_model.get_value_as_bool(), False)
self.assertEqual(settings.get(bool_setting_path), False)
inverted_bool_model = BoolSettingModel(bool_setting_path, True)
inverted_bool_model.set_value(True)
self.assertEqual(inverted_bool_model.get_value_as_bool(), not True)
self.assertEqual(settings.get(bool_setting_path), not True)
inverted_bool_model.set_value(False)
self.assertEqual(inverted_bool_model.get_value_as_bool(), not False)
self.assertEqual(settings.get(bool_setting_path), not False)
float_model = FloatSettingModel(float_setting_path)
float_model.set_value(42.0)
self.assertEqual(float_model.get_value_as_float(), 42.0)
self.assertEqual(settings.get(float_setting_path), 42.0)
float_model.set_value(21.0)
self.assertEqual(float_model.get_value_as_float(), 21.0)
self.assertEqual(settings.get(float_setting_path), 21.0)
async def test_timeline_model(self):
from ..builtin_tools.models.timeline_model import TimelinePlayPauseModel
model = TimelinePlayPauseModel()
model.set_value(True)
await ui_test.human_delay()
self.assertTrue(model.get_value_as_bool())
model.set_value(False)
await ui_test.human_delay()
self.assertFalse(model.get_value_as_bool())
async def test_transform_mode_model(self):
from ..builtin_tools.models.transform_mode_model import TransformModeModel, LocalGlobalTransformModeModel
model = TransformModeModel(TransformModeModel.TRANSFORM_OP_MOVE)
model.set_value(True)
self.assertTrue(model.get_value_as_bool())
settings = carb.settings.get_settings()
setting_path = '/exts/omni.kit.widget.toolbar/test/localGlobalTransformOp'
settings.set(setting_path, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL)
model = LocalGlobalTransformModeModel(TransformModeModel.TRANSFORM_OP_MOVE, setting_path)
model.set_value(False)
self.assertTrue(model.get_op_space_mode() == LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL)
model.set_value(False)
self.assertTrue(model.get_op_space_mode() == LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL)
async def test_play_pause_stop_commands(self):
timeline = omni.timeline.get_timeline_interface()
omni.kit.commands.execute("ToolbarPlayButtonClicked")
await ui_test.human_delay()
self.assertTrue(timeline.is_playing())
omni.kit.commands.execute("ToolbarPauseButtonClicked")
await ui_test.human_delay()
self.assertFalse(timeline.is_playing())
omni.kit.commands.execute("ToolbarStopButtonClicked")
await ui_test.human_delay()
self.assertTrue(timeline.is_stopped())
settings = carb.settings.get_settings()
setting_path = '/exts/omni.kit.widget.toolbar/test/playFilter'
omni.kit.commands.execute("ToolbarPlayFilterChecked", setting_path=setting_path, enabled=True)
self.assertTrue(settings.get(setting_path))
| 6,629 | Python | 43.496644 | 148 | 0.706291 |
omniverse-code/kit/exts/omni.kit.window.file/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.3.32"
category = "Internal"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarily for displaying extension info in UI
title = "USD File UI"
description="Provides utility functions to new/open/save/close USD files"
# URL of the extension source repository.
repository = ""
# Keywords for the extension
keywords = ["kit", "usd", "ui"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog = "docs/CHANGELOG.md"
[dependencies]
"omni.client" = {}
"omni.usd" = {}
"omni.kit.stage_templates" = {}
"omni.ui" = {}
"omni.kit.pip_archive" = {} # Pull in pip_archive to make sure psutil is found and not installed
"omni.kit.window.file_importer" = {}
"omni.kit.window.file_exporter" = {}
"omni.kit.widget.versioning" = {}
"omni.kit.widget.nucleus_connector" = {}
"omni.kit.actions.core" = {}
[python.pipapi]
requirements = ["psutil"]
[[python.module]]
name = "omni.kit.window.file"
[settings]
exts."omni.kit.window.file".enable_versioning = true
[[test]]
args = [
"--/renderer/enabled=pxr",
"--/renderer/active=pxr",
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--/app/file/ignoreUnsavedOnExit=true",
"--/persistent/app/omniverse/filepicker/options_menu/show_details=false",
"--no-window"
]
dependencies = [
"omni.hydra.pxr",
"omni.physx.bundle",
"omni.timeline",
"omni.kit.mainwindow",
"omni.kit.menu.file",
"omni.kit.ui_test",
"omni.kit.test_suite.helpers",
]
| 1,741 | TOML | 25.8 | 96 | 0.687536 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/prompt_ui.py | import urllib
import carb
import carb.settings
import omni.ui as ui
from typing import List
class Prompt:
def __init__(
self, title: str, text: str, button_text: list, button_fn: list, modal: bool = False,
callback_addons: List = [], callback_destroy: List = [], decode_text: bool = True
):
self._title = title
self._text = urllib.parse.unquote(text) if decode_text else text
self._button_list = []
self._modal = modal
self._callback_addons = callback_addons
self._callback_destroy = callback_destroy
self._buttons = []
for name, fn in zip(button_text, button_fn):
self._button_list.append((name, fn))
self._build_ui()
def destroy(self):
self._cancel_button_fn = None
self._ok_button_fn = None
self._button_list = []
if self._window:
self._window.destroy()
del self._window
self._window = None
for button in self._buttons:
button.set_clicked_fn(None)
self._buttons.clear()
self._callback_addons = []
for callback in self._callback_destroy:
if callback and callable(callback):
callback()
self._callback_destroy = []
def __del__(self):
self.destroy()
def __enter__(self):
self.show()
if self._modal:
settings = carb.settings.get_settings()
# Only use first word as a reason (e.g. "Creating, Openning"). URL won't work as a setting key.
operation = self._text.split(" ")[0].lower()
self._hang_detector_disable_key = "/app/hangDetector/disableReasons/{0}".format(operation)
settings.set(self._hang_detector_disable_key, "1")
settings.set("/crashreporter/data/appState", operation)
return self
def __exit__(self, type, value, trace):
self.hide()
if self._modal:
settings = carb.settings.get_settings()
settings.destroy_item(self._hang_detector_disable_key)
settings.set("/crashreporter/data/appState", "started")
def show(self):
self._window.visible = True
def hide(self):
self._window.visible = False
def is_visible(self):
return self._window.visible
def set_text(self, text):
self._text_label.text = text
def _build_ui(self):
self._window = ui.Window(
self._title, visible=False, height=0, dockPreference=ui.DockPreference.DISABLED, raster_policy=ui.RasterPolicy.NEVER
)
self._window.flags = (
ui.WINDOW_FLAGS_NO_COLLAPSE
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_SCROLLBAR
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_MOVE
| ui.WINDOW_FLAGS_NO_CLOSE
)
if self._modal:
self._window.flags |= ui.WINDOW_FLAGS_MODAL
with self._window.frame:
with ui.VStack(height=0):
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer(widht=10, height=0)
self._text_label = ui.Label(
self._text,
width=ui.Percent(100),
height=0,
word_wrap=True,
alignment=ui.Alignment.CENTER,
)
ui.Spacer(widht=10, height=0)
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer(height=0)
for name, fn in self._button_list:
if name:
button = ui.Button(name)
if fn:
button.set_clicked_fn(lambda on_fn=fn: (self.hide(), on_fn()))
else:
button.set_clicked_fn(lambda: self.hide())
self._buttons.append(button)
ui.Spacer(height=0)
ui.Spacer(width=0, height=10)
for callback in self._callback_addons:
if callback and callable(callback):
callback()
| 4,295 | Python | 32.302325 | 128 | 0.518743 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/share_window.py | import carb
import omni.ui as ui
class ShareWindow(ui.Window):
def __init__(self, copy_button_text="Copy Path to Clipboard", copy_button_fn=None, modal=True, url=None):
self._title = "Share Omniverse USD Path"
self._copy_button_text = copy_button_text
self._copy_button_fn = copy_button_fn
self._status_text = "Copy and paste this path to another user to share the location of this USD file."
self._stage_url = url
self._stage_string_box = None
super().__init__(self._title, visible=url is not None, width=600, height=140, dockPreference=ui.DockPreference.DISABLED)
self.flags = (
ui.WINDOW_FLAGS_NO_COLLAPSE
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_SCROLLBAR
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_MOVE
)
if modal:
self.flags = self.flags | ui.WINDOW_FLAGS_MODAL
self.frame.set_build_fn(self._build_ui)
def _build_ui(self):
with self.frame:
with ui.VStack():
ui.Spacer(height=10)
with ui.HStack(height=0):
ui.Spacer()
self._status_label = ui.Label(self._status_text, width=0)
ui.Spacer()
ui.Spacer(height=10)
with ui.HStack(height=0):
ui.Spacer()
self._stage_string_box = ui.StringField(width=550)
self._stage_string_box.model.set_value(self._stage_url)
ui.Spacer()
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Spacer()
copy_button = ui.Button(self._copy_button_text, width=165)
copy_button.set_clicked_fn(self._on_copy_button_fn)
ui.Spacer()
ui.Spacer(height=10)
def _on_copy_button_fn(self):
self.visible = False
if self._stage_string_box:
try:
import omni.kit.clipboard # type: ignore
try:
omni.kit.clipboard.copy(self._stage_string_box.model.as_string)
except:
carb.log_warn("clipboard copy failed")
except ImportError:
carb.log_warn("Could not import omni.kit.clipboard. Cannot copy scene URL to the clipboard.")
@property
def url(self):
return self._stage_url
@url.setter
def url(self, value: str) -> None:
self._stage_url = value
if self._stage_string_box:
self._stage_string_box.model.set_value(value)
self.visible = True
| 2,688 | Python | 37.971014 | 128 | 0.541295 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/save_stage_ui.py | import asyncio
import weakref
import urllib
import carb.settings
import omni.client
import omni.ui
from omni.kit.widget.versioning import CheckpointHelper
class CheckBoxStatus:
def __init__(self, checkbox, layer_identifier, layer_is_writable):
self.checkbox = checkbox
self.layer_identifier = layer_identifier
self.layer_is_writable = layer_is_writable
self.is_checking = False
class StageSaveDialog:
WINDOW_WIDTH = 580
MAX_VISIBLE_LAYER_COUNT = 10
def __init__(self, on_save_fn=None, on_dont_save_fn=None, on_cancel_fn=None, enable_dont_save=False):
self._usd_context = omni.usd.get_context()
self._save_fn = on_save_fn
self._dont_save_fn = on_dont_save_fn
self._cancel_fn = on_cancel_fn
self._checkboxes_status = []
self._select_all_checkbox_is_checking = False
self._selected_layers = []
self._checkpoint_marks = {}
flags = (
omni.ui.WINDOW_FLAGS_NO_COLLAPSE
| omni.ui.WINDOW_FLAGS_NO_SCROLLBAR
| omni.ui.WINDOW_FLAGS_MODAL
)
self._window = omni.ui.Window(
"Select Files to Save##file.py",
visible=False,
width=0,
height=0,
flags=flags,
auto_resize=True,
padding_x=10,
dockPreference=omni.ui.DockPreference.DISABLED,
)
with self._window.frame:
with omni.ui.VStack(height=0, width=StageSaveDialog.WINDOW_WIDTH):
self._layers_scroll_frame = omni.ui.ScrollingFrame(height=160)
omni.ui.Spacer(width=0, height=10)
self._checkpoint_comment_frame = omni.ui.Frame()
with self._checkpoint_comment_frame:
with omni.ui.VStack(height=0, spacing=5):
omni.ui.Label("*) File(s) that will be Checkpointed with a comment.")
with omni.ui.ZStack():
self._description_field = omni.ui.StringField(multiline=True, height=60)
self._description_field_hint_label = omni.ui.Label(
" Description", alignment=omni.ui.Alignment.LEFT_TOP, style={"color": 0xFF3F3F3F}
)
self._description_begin_edit_sub = self._description_field.model.subscribe_begin_edit_fn(
self._on_description_begin_edit
)
self._description_end_edit_sub = self._description_field.model.subscribe_end_edit_fn(
self._on_description_end_edit
)
self._checkpoint_comment_spacer = omni.ui.Spacer(width=0, height=10)
with omni.ui.HStack(height=0):
omni.ui.Spacer(height=0)
self._save_selected_button = omni.ui.Button("Save Selected", width=0, height=0)
self._save_selected_button.set_clicked_fn(self._on_save_fn)
omni.ui.Spacer(width=5, height=0)
if enable_dont_save:
self._dont_save_button = omni.ui.Button("Don't Save", width=0, height=0)
self._dont_save_button.set_clicked_fn(self._on_dont_save_fn)
omni.ui.Spacer(width=5, height=0)
self._cancel_button = omni.ui.Button("Cancel", width=0, height=0)
self._cancel_button.set_clicked_fn(self._on_cancel_fn)
omni.ui.Spacer(height=0)
omni.ui.Spacer(height=5)
def destroy(self):
self._usd_context = None
self._save_fn = None
self._dont_save_fn = None
self._cancel_fn = None
self._checkboxes_status = None
self._selected_layers = None
self._checkpoint_marks = None
if self._window:
del self._window
self._window = None
def __del__(self):
self.destroy()
def _on_save_fn(self):
if self._save_fn:
self._save_fn(
self._selected_layers,
comment=self._description_field.model.get_value_as_string()
if self._checkpoint_comment_frame.visible
else "",
)
self._window.visible = False
self._selected_layers = []
def _on_dont_save_fn(self):
if self._dont_save_fn:
self._dont_save_fn(self._description_field.model.get_value_as_string())
self._window.visible = False
self._selected_layers = []
def _on_cancel_fn(self):
if self._cancel_fn:
self._cancel_fn(self._description_field.model.get_value_as_string())
self._window.visible = False
self._selected_layers = []
def _on_select_all_fn(self, model):
if self._select_all_checkbox_is_checking:
return
self._select_all_checkbox_is_checking = True
if model.get_value_as_bool():
for checkbox_status in self._checkboxes_status:
checkbox_status.checkbox.model.set_value(True)
else:
for checkbox_status in self._checkboxes_status:
checkbox_status.checkbox.model.set_value(False)
self._select_all_checkbox_is_checking = False
def _check_and_select_all(self, select_all_check_box):
select_all = True
for checkbox_status in self._checkboxes_status:
if checkbox_status.layer_is_writable and not checkbox_status.checkbox.model.get_value_as_bool():
select_all = False
break
if select_all:
self._select_all_checkbox_is_checking = True
select_all_check_box.model.set_value(True)
self._select_all_checkbox_is_checking = False
def _on_checkbox_fn(self, model, check_box_index, select_all_check_box):
check_box_status = self._checkboxes_status[check_box_index]
if check_box_status.is_checking:
return
check_box_status.is_checking = True
if not check_box_status.layer_is_writable:
model.set_value(False)
elif model.get_value_as_bool():
self._selected_layers.append(check_box_status.layer_identifier)
self._check_and_select_all(select_all_check_box)
else:
self._selected_layers.remove(check_box_status.layer_identifier)
self._select_all_checkbox_is_checking = True
select_all_check_box.model.set_value(False)
self._select_all_checkbox_is_checking = False
check_box_status.is_checking = False
def show(self, layer_identifiers=None):
self._layers_scroll_frame.clear()
self._checkpoint_marks.clear()
self._checkpoint_comment_frame.visible = False
self._checkpoint_comment_spacer.visible = False
settings = carb.settings.get_settings()
enable_versioning = settings.get_as_bool("exts/omni.kit.window.file/enable_versioning") or False
# make a copy
self._selected_layers.extend(layer_identifiers)
self._checkboxes_status = []
#build layers_scroll_frame
self._first_item_stack = None
with self._layers_scroll_frame:
with omni.ui.VStack(height=0):
omni.ui.Spacer(width=0, height=10)
with omni.ui.HStack(height=0):
omni.ui.Spacer(width=20, height=0)
self._select_all_checkbox = omni.ui.CheckBox(width=20, style={"font_size": 16})
self._select_all_checkbox.model.set_value(True)
omni.ui.Label("File Name", alignment=omni.ui.Alignment.LEFT)
omni.ui.Spacer(width=20, height=0)
omni.ui.Spacer(width=0, height=10)
with omni.ui.HStack(height=0):
omni.ui.Spacer(width=20, height=0)
omni.ui.Separator(height=0, style={"color": 0xFF808080})
omni.ui.Spacer(width=20, height=0)
omni.ui.Spacer(width=0, height=5)
for i in range(len(layer_identifiers)):
layer_identifier = layer_identifiers[i]
# TODO Move version related code
if enable_versioning:
# Check if the server support checkpoint
self._check_checkpoint_enabled(layer_identifier)
style = {}
layer_is_writable = omni.usd.is_layer_writable(layer_identifier)
layer_is_locked = omni.usd.is_layer_locked(self._usd_context, layer_identifier)
if not layer_is_writable or layer_is_locked:
self._selected_layers.remove(layer_identifier)
style = {"background_color": 0xFF808080, "color": 0xFF808080}
label_text = urllib.parse.unquote(layer_identifier).replace("\\", "/")
if not layer_is_writable or layer_is_locked:
label_text += " (Read-Only)"
omni.ui.Spacer(width=0, height=5)
stack = omni.ui.HStack(height=0, style=style)
if self._first_item_stack is None:
self._first_item_stack = stack
with stack:
omni.ui.Spacer(width=20, height=0)
checkbox = omni.ui.CheckBox(width=20, style={"font_size": 16})
checkbox.model.set_value(True)
omni.ui.Label(label_text, word_wrap=False, elided_text=True, alignment=omni.ui.Alignment.LEFT)
check_point_label = omni.ui.Label("*", width=3, alignment=omni.ui.Alignment.LEFT, visible=False)
omni.ui.Spacer(width=20, height=0)
self._checkpoint_marks[layer_identifier] = check_point_label
checkbox.model.add_value_changed_fn(
lambda a, b=i, c=self._select_all_checkbox: self._on_checkbox_fn(a, b, c)
)
self._checkboxes_status.append(CheckBoxStatus(checkbox, layer_identifier, layer_is_writable))
self._select_all_checkbox.model.add_value_changed_fn(lambda a: self._on_select_all_fn(a))
self._window.visible = True
async def __delay_adjust_window_size(weak_self):
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
__self = weak_self()
if not __self:
return
y0 = __self._layers_scroll_frame.screen_position_y
y1 = __self._first_item_stack.screen_position_y
fixed_height = y1 - y0 + 5
item_height = __self._first_item_stack.computed_content_height + 5
count = min(StageSaveDialog.MAX_VISIBLE_LAYER_COUNT, len(__self._checkpoint_marks))
scroll_frame_new_height = fixed_height + count * item_height
__self._layers_scroll_frame.height = omni.ui.Pixel(scroll_frame_new_height)
if len(layer_identifiers) > 0:
asyncio.ensure_future(__delay_adjust_window_size(weakref.ref(self)))
def is_visible(self):
return self._window.visible
def _on_description_begin_edit(self, model):
self._description_field_hint_label.visible = False
def _on_description_end_edit(self, model):
if len(model.get_value_as_string()) == 0:
self._description_field_hint_label.visible = True
def _check_checkpoint_enabled(self, url):
async def check_server_support(weak_self, url):
_self = weak_self()
if not _self:
return
if await CheckpointHelper.is_checkpoint_enabled_async(url):
_self._checkpoint_comment_frame.visible = True
_self._checkpoint_comment_spacer.visible = True
label = _self._checkpoint_marks.get(url, None)
if label:
label.visible = True
asyncio.ensure_future(check_server_support(weakref.ref(self), url))
| 12,233 | Python | 43.813187 | 120 | 0.563803 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/style.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb
import omni.ui as ui
try:
THEME = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle")
except Exception:
THEME = None
finally:
THEME = THEME or "NvidiaDark"
def get_style():
if THEME == "NvidiaLight": # pragma: no cover
BACKGROUND_COLOR = 0xFF535354
BACKGROUND_SELECTED_COLOR = 0xFF6E6E6E
BACKGROUND_HOVERED_COLOR = 0xFF6E6E6E
FIELD_BACKGROUND_COLOR = 0xFF1F2124
SECONDARY_COLOR = 0xFFE0E0E0
BORDER_COLOR = 0xFF707070
TITLE_COLOR = 0xFF707070
TEXT_COLOR = 0xFF8D760D
TEXT_HINT_COLOR = 0xFFD6D6D6
else:
BACKGROUND_COLOR = 0xFF23211F
BACKGROUND_SELECTED_COLOR = 0xFF8A8777
BACKGROUND_HOVERED_COLOR = 0xFF3A3A3A
SECONDARY_COLOR = 0xFF9E9E9E
BORDER_COLOR = 0xFF8A8777
TITLE_COLOR = 0xFFCECECE
TEXT_COLOR = 0xFF9E9E9E
TEXT_HINT_COLOR = 0xFF7A7A7A
style = {
"Button": {
"background_color": BACKGROUND_COLOR,
"selected_color": BACKGROUND_SELECTED_COLOR,
"color": TEXT_COLOR,
"margin": 0,
"padding": 0
},
"Button:hovered": {"background_color": BACKGROUND_HOVERED_COLOR},
"Button.Label": {"color": TEXT_COLOR},
"Field": {"background_color": BACKGROUND_COLOR, "selected_color": BACKGROUND_SELECTED_COLOR, "color": TEXT_COLOR, "alignment": ui.Alignment.LEFT_CENTER},
"Field.Hint": {"background_color": 0x0, "color": TEXT_HINT_COLOR, "margin_width": 4},
"Label": {"background_color": 0x0, "color": TEXT_COLOR},
"CheckBox": {"alignment": ui.Alignment.CENTER},
}
return style
| 2,126 | Python | 36.982142 | 161 | 0.659454 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/__init__.py | from .file_window import *
| 27 | Python | 12.999994 | 26 | 0.740741 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/file_actions.py | import omni.kit.actions.core
from .app_ui import AppUI, DialogOptions
def register_actions(extension_id):
import omni.kit.window.file
action_registry = omni.kit.actions.core.get_action_registry()
actions_tag = "File Actions"
action_registry.register_action(
extension_id,
"new",
omni.kit.window.file.new,
display_name="File->New",
description="Create a new USD stage.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"open",
omni.kit.window.file.open,
display_name="File->Open",
description="Open an existing USD stage.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"open_stage",
omni.kit.window.file.open_stage,
display_name="File->Open Stage",
description="Open an named USD stage.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"reopen",
omni.kit.window.file.reopen,
display_name="File->Reopen",
description="Reopen the currently opened USD stage.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"open_with_new_edit_layer",
omni.kit.window.file.open_with_new_edit_layer,
display_name="File->Open With New Edit Layer",
description="Open an existing USD stage with a new edit layer.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"share",
omni.kit.window.file.share,
display_name="File->Share",
description="Share the currently open USD stage.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"save",
lambda: omni.kit.window.file.save(dialog_options=DialogOptions.HIDE),
display_name="File->Save",
description="Save the currently opened USD stage to file.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"save_with_options",
lambda: omni.kit.window.file.save(dialog_options=DialogOptions.NONE),
display_name="File->Save With Options",
description="Save the currently opened USD stage to file.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"save_as",
lambda: omni.kit.window.file.save_as(False),
display_name="File->Save As",
description="Save the currently opened USD stage to a new file.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"save_as_flattened",
lambda: omni.kit.window.file.save_as(True),
display_name="File->Save As Flattened",
description="Save the currently opened USD stage to a new flattened file.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"add_reference",
lambda: omni.kit.window.file.add_reference(is_payload=False),
display_name="File->Add Reference",
description="Add a reference to a file.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"add_payload",
lambda: omni.kit.window.file.add_reference(is_payload=True),
display_name="File->Add Payload",
description="Add a payload to a file.",
tag=actions_tag,
)
def deregister_actions(extension_id):
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.deregister_all_actions_for_extension(extension_id)
| 3,626 | Python | 31.383928 | 83 | 0.621897 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/file_window.py | """USD File interaction for Omniverse Kit.
:mod:`omni.kit.window.file` provides util functions to new/open/save/close USD files. It handles file picking dialog and prompt for unsaved stage.
"""
import os
import time
import traceback
import asyncio
from typing import Awaitable, Callable, List
import carb
import omni.ext
import omni.usd
import omni.kit.app
import omni.kit.helper.file_utils as file_utils
from pathlib import Path
from functools import partial
from omni.kit.helper.file_utils import asset_types
import omni.kit.usd.layers as layers
from omni.kit.window.file_importer import get_file_importer
from omni.kit.window.file_exporter import get_file_exporter
from omni.kit.widget.nucleus_connector import get_nucleus_connector
from .prompt_ui import Prompt
from .read_only_options_window import ReadOnlyOptionsWindow
from .share_window import ShareWindow
from .app_ui import AppUI, DialogOptions, SaveOptionsDelegate, OpenOptionsDelegate
from .file_actions import register_actions, deregister_actions
from pxr import Tf, Sdf, Usd, UsdGeom, UsdUtils
_extension_instance = None
TEST_DATA_PATH = ""
IGNORE_UNSAVED_ON_EXIT_PATH = "/app/file/ignoreUnsavedOnExit"
IGNORE_UNSAVED_STAGE = "/app/file/ignoreUnsavedStage"
LAST_OPENED_DIRECTORY = "/persistent/app/omniverse/lastOpenDirectory"
SHOW_UNSAVED_LAYERS_DIALOG = "/persistent/app/file/save/showUnsavedLayersDialog"
class _CheckpointCommentContext:
def __init__(self, comment: str):
self._comment = comment
def __enter__(self):
try:
import omni.usd_resolver
omni.usd_resolver.set_checkpoint_message(self._comment)
except Exception as e:
carb.log_error(f"Failed to import omni.usd_resolver: {str(e)}.")
return self
def __exit__(self, type, value, trace):
try:
import omni.usd_resolver
omni.usd_resolver.set_checkpoint_message("")
except Exception:
pass
class _CallbackRegistrySubscription:
"""
Simple subscription.
_Event has callback while this object exists.
"""
def __init__(self, callback_list: List, callback: Callable):
"""
Save the callback in the given list.
"""
self.__callback_list: List = callback_list
self.__callback = callback
callback_list.append(callback)
def __del__(self):
"""Called by GC."""
self.__callback_list.remove(self.__callback)
class FileWindowExtension(omni.ext.IExt):
def on_startup(self, ext_id):
global _extension_instance
_extension_instance = self
self._open_stage_callbacks: List = []
self._open_stage_complete_callbacks: List = []
self.ui_handler = None
self._task = None
self._unsaved_stage_prompt = None
self._file_existed_prompt = None
self._open_readonly_usd_prompt = None
self._app = omni.kit.app.get_app()
self._settings = carb.settings.get_settings()
self._settings.set_default_bool(IGNORE_UNSAVED_ON_EXIT_PATH, False)
self.ui_handler = AppUI()
self._save_options = None
self._open_options = None
self._share_window = None
manager = omni.kit.app.get_app().get_extension_manager()
extension_path = manager.get_extension_path(ext_id)
global TEST_DATA_PATH
TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests")
def on_event(e: carb.events.IEvent):
if e.type == omni.kit.app.POST_QUIT_EVENT_TYPE:
ignore_unsaved_file_on_exit = self._settings.get(IGNORE_UNSAVED_ON_EXIT_PATH)
usd_context = omni.usd.get_context()
if not ignore_unsaved_file_on_exit and usd_context.can_close_stage() and usd_context.has_pending_edit():
self._app.try_cancel_shutdown("Interrupting shutdown - closing stage first")
# OM-52366: fast shutdown will not close stage but post quit directly.
fast_shutdown = carb.settings.get_settings().get("/app/fastShutdown")
self.close(lambda *args: omni.kit.app.get_app().post_quit(), fast_shutdown=fast_shutdown)
self._shutdown_subs = self._app.get_shutdown_event_stream().create_subscription_to_pop(
on_event, name="window.file shutdown hook", order=0
)
self._ext_name = omni.ext.get_extension_name(ext_id)
register_actions(self._ext_name)
def on_shutdown(self):
deregister_actions(self._ext_name)
self._shutdown_subs = None
self._save_options = None
self._open_options = None
if self._task:
self._task.cancel()
self._task = None
if self._unsaved_stage_prompt:
self._unsaved_stage_prompt.destroy()
self._unsaved_stage_prompt = None
if self._file_existed_prompt:
self._file_existed_prompt.destroy()
self._file_existed_prompt = None
if self._open_readonly_usd_prompt:
self._open_readonly_usd_prompt.destroy()
self._open_readonly_usd_prompt = None
global _extension_instance
_extension_instance = None
if self.ui_handler:
self.ui_handler.destroy()
self.ui_handler = None
def stop_timeline(self):
try:
import omni.timeline
timeline = omni.timeline.get_timeline_interface()
if timeline:
timeline.stop()
else:
carb.log_warn(f"Failed to stop timeline, get_timeline_interface() return None")
except ModuleNotFoundError:
carb.log_warn(f"Failed to stop timeline, omni.timeline not loaded")
def new(self, template=None):
"""Create a new USD stage. If currently opened stage is dirty, a prompt will show to let you save it."""
self.stop_timeline()
async def new_stage_job():
# FIXME: Delay two frames to center prompt.
await self._app.next_update_async()
await self._app.next_update_async()
with Prompt("Please Wait", "Creating new stage...", [], [], True):
await self._app.next_update_async() # Making sure prompt shows
await omni.kit.stage_templates.new_stage_async(template=template)
await self._app.next_update_async() # Wait anther frame for StageEvent.OPENED to be handled
self.prompt_if_unsaved_stage(lambda *_: self._exclusive_task_wrapper(new_stage_job))
def open(self, open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL):
"""Bring up a file picker to choose a USD file to open. If currently opened stage is dirty, a prompt will show to let you save it."""
self.stop_timeline()
def open_handler(loadset: int, filename: str, dirname: str, selections: List[str]):
if ':/' in filename or filename.startswith('\\\\'):
# Filename is a pasted fullpath. The first test finds paths that start with 'C:/' or 'omniverse://';
# the second finds MS network paths that start like '\\analogfs\VENDORS\...'
path = filename
else:
path = f"{dirname or ''}/{filename}"
if not omni.usd.is_usd_readable_filetype(path):
FileWindowExtension.post_notification(f"Cannot open {path}. No valid stage")
return
result, entry = omni.client.stat(path)
if result != omni.client.Result.OK:
carb.log_warn(f"Failed to stat '{path}', attempting to open in read-only mode.")
read_only = True
else:
# https://nvidia-omniverse.atlassian.net/browse/OM-45124
read_only = entry.access & omni.client.AccessFlags.WRITE == 0
if read_only:
def _open_with_edit_layer():
self.open_with_new_edit_layer(path, open_loadset)
def _open_original_stage():
self.open_stage(path, open_loadset, open_options=self._open_options)
self._show_readonly_usd_prompt(_open_with_edit_layer, _open_original_stage)
else:
self.open_stage(path, open_loadset=loadset, open_options=self._open_options)
file_importer = get_file_importer()
if file_importer:
file_importer.show_window(
title="Open File",
import_button_label="Open File",
import_handler=partial(open_handler, open_loadset),
)
if self._open_options is None:
self._open_options = OpenOptionsDelegate()
file_importer.add_import_options_frame("Options", self._open_options)
def open_stage(self, path, open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL, open_options: OpenOptionsDelegate=None, callback: callable=None):
"""open stage. If the current stage is dirty, a prompt will show to let you save it."""
if not omni.usd.is_usd_readable_filetype(path):
FileWindowExtension.post_notification(f"Cannot open {path}. No valid stage")
if callback:
callback(False)
return
self.stop_timeline()
ui_handler = self.ui_handler
self._settings.set(LAST_OPENED_DIRECTORY, os.path.dirname(path))
checkbox = None
if open_options:
checkbox = open_options.should_load_payload()
if not checkbox: # open with payloads disabled
open_loadset = omni.usd.UsdContextInitialLoadSet.LOAD_NONE
async def open_stage_job():
# FIXME: Delay two frames to center prompt.
await self._app.next_update_async()
await self._app.next_update_async()
prompt = Prompt("Please Wait", f"Opening {path}...", [], [], True, self._open_stage_callbacks, self._open_stage_complete_callbacks)
prompt._window.width = 415
with prompt:
context = omni.usd.get_context()
start_time = time.time()
result, err = await context.open_stage_async(path, open_loadset)
success = True
if not result or context.get_stage_state() != omni.usd.StageState.OPENED:
success = False
carb.log_error(f"Failed to open stage {path}: {err}")
ui_handler.show_open_stage_failed_prompt(path)
else:
stage = context.get_stage()
identifier = stage.GetRootLayer().identifier
if not stage.GetRootLayer().anonymous:
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
message_bus.push(file_utils.FILE_OPENED_EVENT, payload=file_utils.FileEventModel(url=identifier).dict())
open_duration = time.time() - start_time
omni.kit.app.send_telemetry_event("omni.kit.window.file@open_stage", duration=open_duration, data1=path, value1=float(success))
if callback:
callback(False)
async def open_stage_async():
result, _ = await omni.client.stat_async(path)
if result == omni.client.Result.OK:
FileWindowExtension._exclusive_task_wrapper(open_stage_job)
return
# Attempt to connect to nucleus server
broken_url = omni.client.break_url(path)
if broken_url.scheme == 'omniverse':
server_url = omni.client.make_url(scheme='omniverse', host=broken_url.host)
nucleus_connector = get_nucleus_connector()
if nucleus_connector:
nucleus_connector.connect(broken_url.host, server_url,
on_success_fn=lambda *_: FileWindowExtension._exclusive_task_wrapper(open_stage_job),
on_failed_fn=lambda *_: carb.log_error(f"Invalid stage URL: {path}")
)
else:
carb.log_error(f"Invalid stage URL: {path}")
self.prompt_if_unsaved_stage(lambda *_: asyncio.ensure_future(open_stage_async()))
def _show_readonly_usd_prompt(self, ok_fn, middle_fn):
if self._open_readonly_usd_prompt:
self._open_readonly_usd_prompt.destroy()
self._open_readonly_usd_prompt = ReadOnlyOptionsWindow(ok_fn, middle_fn)
self._open_readonly_usd_prompt.show()
def _show_file_existed_prompt(self, path, on_confirm_fn, on_cancel_fn=None):
file_name = os.path.basename(path)
if self._file_existed_prompt:
self._file_existed_prompt.destroy()
self._file_existed_prompt = Prompt(
f'{omni.kit.ui.get_custom_glyph_code("${glyphs}/exclamation.svg")} Overwrite',
f"File {file_name} already exists, do you want to overwrite it?",
["OK", "Cancel"],
[on_confirm_fn, None],
False,
)
self._file_existed_prompt.show()
def open_with_new_edit_layer(self, path: str, open_loadset: int = omni.usd.UsdContextInitialLoadSet.LOAD_ALL, callback: Callable = None):
if not omni.usd.is_usd_readable_filetype(path):
FileWindowExtension.post_notification(f"Cannot open {path}. No valid stage")
return
self.stop_timeline()
def create_handler(stage_path: str, callback: Callable, filename: str, dirname: str,
extension: str = None, selections: List[str] = []):
# Allow incoming directory as /path/to/dir or /path/to/dir/
dirname = dirname.rstrip('/')
edit_layer_path = f"{dirname}/{filename}{extension}"
self.create_stage(edit_layer_path, stage_path, callback=callback)
def create_edit_layer(stage_path: str, callback: Callable):
file_exporter = get_file_exporter()
if file_exporter:
dirname = os.path.dirname(stage_path)
if Sdf.Layer.IsAnonymousLayerIdentifier(stage_path):
basename = Sdf.Layer.GetDisplayNameFromIdentifier(stage_path)
else:
basename = os.path.basename(stage_path)
edit_layer_path = f"{dirname}/{os.path.splitext(basename)[0]}_edit"
file_exporter.show_window(
title="Create Edit Layer",
export_button_label="Save",
export_handler=partial(create_handler, stage_path, callback),
filename_url=edit_layer_path,
)
self.prompt_if_unsaved_stage(lambda: create_edit_layer(path, callback))
def create_stage(self, edit_layer_path: str, file_path: str, callback: Callable = None):
self.stop_timeline()
async def create_stage_async(edit_layer_path: str, stage_path: str, callback: Callable):
edit_layer = Sdf.Layer.FindOrOpen(edit_layer_path)
if edit_layer:
edit_layer.Clear()
else:
edit_layer = Sdf.Layer.CreateNew(edit_layer_path)
if not edit_layer:
carb.log_error(f"open_with_new_edit_layer: failed to create edit layer {edit_layer_path}")
return
# FIXME: Delay two frames to center prompt.
await self._app.next_update_async()
await self._app.next_update_async()
with Prompt("Please Wait", "Creating new stage...", [], [], True):
await self._app.next_update_async() # Making sure prompt shows
root_layer = Sdf.Layer.CreateAnonymous()
root_layer.subLayerPaths.insert(0, file_path)
root_layer.subLayerPaths.insert(0, edit_layer_path)
# Copy all meta
base_layer = Sdf.Layer.FindOrOpen(file_path)
UsdUtils.CopyLayerMetadata(base_layer, root_layer, True)
omni.usd.resolve_paths(base_layer.identifier, root_layer.identifier, False, True)
# Set edit target
stage = Usd.Stage.Open(root_layer)
edit_target = Usd.EditTarget(edit_layer)
stage.SetEditTarget(edit_target)
await omni.usd.get_context().attach_stage_async(stage)
await self._app.next_update_async() # Wait anther frame for StageEvent.OPENED to be handled
if callback:
callback()
async def create_stage_prompt_if_exists(edit_layer_path: str, file_path: str, callback: Callable):
result, _ = await omni.client.stat_async(edit_layer_path)
# File is existed already.
if result == omni.client.Result.OK:
self._show_file_existed_prompt(
edit_layer_path,
lambda: FileWindowExtension._exclusive_task_wrapper(
create_stage_async, edit_layer_path, file_path, callback
)
)
else:
await create_stage_async(edit_layer_path, file_path, callback)
asyncio.ensure_future(create_stage_prompt_if_exists(edit_layer_path, file_path, callback))
def reopen(self):
"""Reopen currently opened stage. If the stage is dirty, a prompt will show to let you save it."""
self.stop_timeline()
async def reopen_stage_job():
context = omni.usd.get_context()
path = context.get_stage_url()
# FIXME: Delay two frames to center prompt.
await self._app.next_update_async()
await self._app.next_update_async()
with Prompt("Please Wait", f"Reopening {path}...", [], [], True):
await self._app.next_update_async() # Making sure prompt shows
result, err = await context.reopen_stage_async()
await self._app.next_update_async() # Wait anther frame for StageEvent.OPENED to be handled
if not result or context.get_stage_state() != omni.usd.StageState.OPENED:
carb.log_error(f"Failed to reopen stage {path}: {err}")
self.ui_handler.show_open_stage_failed_prompt(path)
if not (omni.usd.get_context().get_stage_state() == omni.usd.StageState.OPENED and not omni.usd.get_context().is_new_stage()):
FileWindowExtension.post_notification("Cannot Reopen. No valid stage")
return
self.prompt_if_unsaved_stage(lambda *_: FileWindowExtension._exclusive_task_wrapper(reopen_stage_job))
def share(self):
context = omni.usd.get_context()
if context.get_stage_url().startswith("omniverse://"):
layers_interface = layers.get_layers(context)
live_syncing = layers_interface.get_live_syncing()
current_session = live_syncing.get_current_live_session()
if not current_session:
url = context.get_stage_url()
else:
url = current_session.shared_link
self._share_window = ShareWindow(url=url)
def save(self, callback: Callable, allow_skip_sublayers: bool = False):
"""Save currently opened stage to file. Will call Save As for a newly created stage"""
# Syncs render settings to stage before save so stage could
# get the correct edit state if render settings are changed.
if omni.usd.get_context().get_stage_state() != omni.usd.StageState.OPENED:
FileWindowExtension.post_notification("Cannot Save. No valid stage")
return
self.stop_timeline()
async def save_async(callback: Callable, allow_skip_sublayers: bool):
is_new_stage = omni.usd.get_context().is_new_stage() or \
omni.usd.get_context().get_stage_state() != omni.usd.StageState.OPENED
is_writeable = False
try:
filename_url = omni.usd.get_context().get_stage().GetRootLayer().identifier
result, stat = await omni.client.stat_async(filename_url)
except Exception:
pass
else:
if result == omni.client.Result.OK:
is_writeable = stat.flags & omni.client.ItemFlags.WRITEABLE_FILE
# OM-47514 When saving a checkpoint or read-only file, use save_as instead
if is_new_stage or not is_writeable:
self.save_as(False, callback, allow_skip_sublayers=allow_skip_sublayers)
else:
stage = omni.usd.get_context().get_stage()
dirty_layer_identifiers = omni.usd.get_dirty_layers(stage, True)
self.ui_handler.save_root_and_sublayers("", dirty_layer_identifiers, on_save_done=callback, allow_skip_sublayers=allow_skip_sublayers)
asyncio.ensure_future(save_async(callback, allow_skip_sublayers))
def save_as(self, flatten: bool, callback: Callable, allow_skip_sublayers: bool = False):
"""Bring up a file picker to choose a file to save current stage to."""
self.stop_timeline()
def save_handler(callback: Callable, flatten: bool, filename: str, dirname: str, extension: str = '', selections: List[str] = []):
path = f"{dirname}/{filename}{extension}"
self.save_stage(path, callback=callback, flatten=flatten, save_options=self._save_options, allow_skip_sublayers=allow_skip_sublayers)
if omni.usd.get_context().get_stage_state() != omni.usd.StageState.OPENED:
FileWindowExtension.post_notification("Cannot Save As. No valid stage")
return
file_exporter = get_file_exporter()
if file_exporter:
# OM-48033: Save as should open to latest opened stage path. Solution also covers ...
# OM-58150: Save as should pass in the current file name as default value.
filename_url = file_utils.get_last_url_visited(asset_type=asset_types.ASSET_TYPE_USD)
if filename_url:
# OM-91056: File Save As should not prefill the file name
filename_url = os.path.dirname(filename_url) + "/"
file_exporter.show_window(
title="Save File As...",
export_button_label="Save",
export_handler=partial(save_handler, callback, flatten),
filename_url=filename_url,
# OM-64312: Set save-as dialog to validate file names in file exporter
should_validate=True,
)
if self._save_options is None:
self._save_options = SaveOptionsDelegate()
file_exporter.add_export_options_frame("Save Options", self._save_options)
# OM-55838: Don't show "include sesson layer" for non-flatten save-as.
self._save_options.show_include_session_layer_option = flatten
def save_stage(self, path: str, callback: Callable = None, flatten: bool=False, save_options: SaveOptionsDelegate=None, allow_skip_sublayers: bool=False):
self.stop_timeline()
stage = omni.usd.get_context().get_stage()
save_comment = ""
if save_options:
save_comment = save_options.get_comment()
include_session_layer = False
if save_options and flatten:
include_session_layer = save_options.include_session_layer()
if flatten:
path = path or stage.GetRootLayer().identifier
# TODO: Currently, it's implemented differently for export w/o session layer as
# flatten is a simple operation and we don't want to break the ABI of omni.usd.
if include_session_layer:
omni.usd.get_context().export_as_stage_with_callback(path, callback)
else:
async def flatten_stage_without_session_layer(path, callback):
await self._app.next_update_async()
await self._app.next_update_async()
with Prompt("Please Wait", "Exporting flattened stage...", [], [], True):
await self._app.next_update_async()
usd_context = omni.usd.get_context()
if usd_context.can_save_stage():
stage = usd_context.get_stage()
# Creates empty anon layer.
anon_layer = Sdf.Layer.CreateAnonymous()
temp_stage = Usd.Stage.Open(stage.GetRootLayer(), anon_layer)
success = temp_stage.Export(path)
if callback:
if success:
callback(True, "")
else:
callback(False, f"Error exporting flattened stage to path: {path}.")
else:
error = "Stage busy or another saving task is in progress!!"
CARB_LOG_ERROR(error)
if callback:
callback(False, error)
asyncio.ensure_future(flatten_stage_without_session_layer(path, callback))
else:
async def save_stage_async(path: str, callback: Callable):
if path == stage.GetRootLayer().identifier:
dirty_layer_identifiers = omni.usd.get_dirty_layers(stage, True)
self.ui_handler.save_root_and_sublayers(
"", dirty_layer_identifiers, on_save_done=callback, save_comment=save_comment, allow_skip_sublayers=allow_skip_sublayers)
else:
path = path or stage.GetRootLayer().identifier
dirty_layer_identifiers = omni.usd.get_dirty_layers(stage, False)
save_fn = lambda: self.ui_handler.save_root_and_sublayers(
path, dirty_layer_identifiers, on_save_done=callback, save_comment=save_comment, allow_skip_sublayers=allow_skip_sublayers)
cancel_fn = lambda: self.ui_handler.save_root_and_sublayers(
"", dirty_layer_identifiers, on_save_done=callback, save_comment=save_comment, allow_skip_sublayers=allow_skip_sublayers)
result, _ = await omni.client.stat_async(path)
if result == omni.client.Result.OK:
# Path already exists, prompt to overwrite
self._show_file_existed_prompt(path, save_fn, on_cancel_fn=cancel_fn)
else:
save_fn()
asyncio.ensure_future(save_stage_async(path, callback))
def close(self, on_closed, fast_shutdown=False):
"""Check if current stage is dirty. If it's dirty, it will ask if to save the file, then close stage."""
self.stop_timeline()
async def close_stage_job():
if not fast_shutdown:
# FIXME: Delay two frames to center prompt.
await self._app.next_update_async()
await self._app.next_update_async()
with Prompt("Please Wait", "Closing stage...", [], [], True):
await self._app.next_update_async() # Making sure prompt shows
await omni.usd.get_context().close_stage_async()
await self._app.next_update_async() # Wait anther frame for StageEvent.CLOSED to be handled
else:
# Clear dirty state to allow quit fastly.
omni.usd.get_context().set_pending_edit(False)
if on_closed:
on_closed()
self.prompt_if_unsaved_stage(lambda *_: self._exclusive_task_wrapper(close_stage_job))
def save_layers(self, new_root_path, dirty_layers, on_save_done, create_checkpoint=True, checkpoint_comment=""):
"""Save current layers"""
# Skips if it has no real layers to be saved.
self.stop_timeline()
# It's possible that all layers are not dirty but it has pending edits to be saved,
# like render settings, which needs to be saved into root layer during save.
usd_context = omni.usd.get_context()
has_pending_edit = usd_context.has_pending_edit()
if not new_root_path and not dirty_layers and not has_pending_edit:
if on_save_done:
on_save_done(True, "")
return
try:
async def save_layers_job(*_):
# FIXME: Delay two frames to center prompt.
await self._app.next_update_async()
await self._app.next_update_async()
with Prompt("Please Wait", "Saving layers...", [], [], True):
await self._app.next_update_async() # Making sure prompt shows
await self._app.next_update_async() # Need 2 frames since save happens on mainthread
with _CheckpointCommentContext(checkpoint_comment):
result, err, saved_layers = await usd_context.save_layers_async(new_root_path, dirty_layers)
await self._app.next_update_async() # Wait anther frame for StageEvent.SAVED to be handled
# Clear unique task since it's possible that
# post-call to on_save_done needs to create unique
# instance also.
if _extension_instance and _extension_instance._task:
_extension_instance._task = None
if on_save_done:
on_save_done(result, err)
if result:
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
message_bus.push(file_utils.FILE_SAVED_EVENT, payload=file_utils.FileEventModel(url=new_root_path).dict())
else:
self.ui_handler.show_save_layers_failed_prompt()
FileWindowExtension._exclusive_task_wrapper(save_layers_job)
except Exception as exc:
carb.log_error(f"save error {exc}")
traceback.print_exc()
def prompt_if_unsaved_stage(self, callback: Callable):
"""Check if current stage is dirty. If it's dirty, ask to save the file, then execute callback. Otherwise runs callback directly."""
def should_show_stage_save_dialog():
# Use settings to control if it needs to show stage save dialog for layers save.
# For application that uses kit and does not want this, it can disable this.
settings = carb.settings.get_settings()
settings.set_default_bool(SHOW_UNSAVED_LAYERS_DIALOG, True)
show_stage_save_dialog = settings.get(SHOW_UNSAVED_LAYERS_DIALOG)
return show_stage_save_dialog
ignore_unsaved = self._settings.get(IGNORE_UNSAVED_STAGE)
if omni.usd.get_context().has_pending_edit() and not ignore_unsaved:
if omni.usd.get_context().is_new_stage() or should_show_stage_save_dialog():
if self._unsaved_stage_prompt:
self._unsaved_stage_prompt.destroy()
self._unsaved_stage_prompt = Prompt(
f'{omni.kit.ui.get_custom_glyph_code("${glyphs}/exclamation.svg")}',
"Would you like to save this stage?",
["Save", "Don't Save", "Cancel"],
[lambda *_: self.save(callback, allow_skip_sublayers=True), lambda *_: callback() if callback else None, None],
modal=True)
self._unsaved_stage_prompt.show()
else:
self.save(callback, allow_skip_sublayers=True)
else:
if callback:
callback()
def add_reference(self, is_payload=False):
self.stop_timeline()
def on_file_picked(is_payload: bool, filename: str, dirname: str, selections: List[str]):
if ':/' in filename or filename.startswith('\\\\'):
# Filename is a pasted fullpath. The first test finds paths that start with 'C:/' or 'omniverse://';
# the second finds MS network paths that start like '\\analogfs\VENDORS\...'
reference_path = filename
else:
reference_path = f"{dirname or ''}/{filename}"
name = os.path.splitext(os.path.basename(reference_path))[0]
stage = omni.usd.get_context().get_stage()
if stage.HasDefaultPrim():
prim_path = omni.usd.get_stage_next_free_path(
stage, stage.GetDefaultPrim().GetPath().pathString + "/" + Tf.MakeValidIdentifier(name), False
)
else:
prim_path = omni.usd.get_stage_next_free_path(stage, "/" + Tf.MakeValidIdentifier(name), False)
if is_payload:
omni.kit.commands.execute(
"CreatePayload", usd_context=omni.usd.get_context(), path_to=prim_path, asset_path=reference_path, instanceable=False
)
else:
omni.kit.commands.execute(
"CreateReference", usd_context=omni.usd.get_context(), path_to=prim_path, asset_path=reference_path, instanceable=False
)
file_importer = get_file_importer()
if file_importer:
file_importer.show_window(
title="Select File",
import_button_label="Add Reference" if not is_payload else "Add Payload",
import_handler=partial(on_file_picked, is_payload))
def register_open_stage_addon(self, callback):
return _CallbackRegistrySubscription(self._open_stage_callbacks, callback)
def register_open_stage_complete(self, callback):
return _CallbackRegistrySubscription(self._open_stage_complete_callbacks, callback)
@staticmethod
def _exclusive_task_wrapper(job: Awaitable, *args):
# Only allow one task to be run
if _extension_instance._task:
carb.log_info("_exclusive_task_wrapper already running. Cancelling")
_extension_instance._task.cancel()
_extension_instance._task = None
async def exclusive_task():
await job(*args)
_extension_instance._task = None
_extension_instance._task = asyncio.ensure_future(exclusive_task())
def post_notification(message: str, info: bool = False, duration: int = 3):
try:
import omni.kit.notification_manager as nm
if info:
type = nm.NotificationStatus.INFO
else:
type = nm.NotificationStatus.WARNING
nm.post_notification(message, status=type, duration=duration)
except ModuleNotFoundError:
carb.log_warn(message)
def get_instance():
return _extension_instance
def new(template=None):
file_window = get_instance()
if file_window:
file_window.new(template)
def open(open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL):
file_window = get_instance()
if file_window:
file_window.open(open_loadset)
def open_stage(path, open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL, callback: callable=None):
file_window = get_instance()
if file_window:
file_window.open_stage(path, open_loadset=open_loadset, callback=callback)
def open_with_new_edit_layer(path, open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL, callback=None):
file_window = get_instance()
if file_window:
file_window.open_with_new_edit_layer(path, open_loadset, callback)
def reopen():
file_window = get_instance()
if file_window:
file_window.reopen()
def share():
file_window = get_instance()
if file_window:
file_window.share()
def save(on_save_done=None, exit=False, dialog_options=DialogOptions.NONE):
file_window = get_instance()
if file_window:
file_window.save(on_save_done)
def save_as(flatten, on_save_done=None):
file_window = get_instance()
if file_window:
file_window.save_as(flatten, on_save_done)
def close(on_closed=None):
file_window = get_instance()
if file_window:
file_window.close(on_closed)
def save_layers(new_root_path, dirty_layers, on_save_done, create_checkpoint=True, checkpoint_comment=""):
file_window = get_instance()
if file_window:
file_window.save_layers(new_root_path, dirty_layers, on_save_done, create_checkpoint, checkpoint_comment)
def prompt_if_unsaved_stage(job):
file_window = get_instance()
if file_window:
file_window.prompt_if_unsaved_stage(job)
def add_reference(is_payload=False):
file_window = get_instance()
if file_window:
file_window.add_reference(is_payload=is_payload)
def register_open_stage_addon(callback):
file_window = get_instance()
if file_window:
return file_window.register_open_stage_addon(callback)
def register_open_stage_complete(callback):
file_window = get_instance()
if file_window:
return file_window.register_open_stage_complete(callback)
| 37,160 | Python | 45.048327 | 158 | 0.598681 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/app_ui.py | """USD File interaction for Omniverse Kit.
:mod:`omni.kit.window.file` provides util functions to new/open/save/close USD files. It handles file picking dialog and prompt
for unsaved stage.
"""
import os
import carb.settings
import omni.ui as ui
import omni.kit.ui
from enum import Enum
from typing import List, Callable
from omni.kit.window.file_exporter import get_file_exporter, ExportOptionsDelegate
from omni.kit.window.file_importer import ImportOptionsDelegate
from omni.kit.widget.versioning import CheckpointHelper
from .prompt_ui import Prompt
from .save_stage_ui import StageSaveDialog
from .style import get_style
class DialogOptions(Enum):
NONE = 0, 'Show dialog using is-required logic'
FORCE = 1, 'Force dialog to show and ignore is-required logic'
HIDE = 2, 'Never show dialog'
class SaveOptionsDelegate(ExportOptionsDelegate):
def __init__(self):
super().__init__(
build_fn=self._build_ui_impl,
selection_changed_fn=lambda *_: self._build_ui_impl(),
filename_changed_fn=lambda *_: self._build_ui_impl(),
destroy_fn=self._destroy_impl
)
self._widget = None
self._comment_model = ui.SimpleStringModel()
self._include_session_layer_checkbox = None
self._hint_container = None
self._sub_begin_edit = None
self._sub_end_edit = None
self._show_include_session_layer_option = False
self._other_options_widget = None
settings = carb.settings.get_settings()
self._versioning_enabled = settings.get_as_bool("exts/omni.kit.window.file/enable_versioning") or False
def get_comment(self):
if self._comment_model:
return self._comment_model.get_value_as_string()
return ""
def include_session_layer(self):
"""
When doing save-as or save-flattened-as, this option
can tell if it needs to keep session layers's change or
flatten session layer's change also.
"""
if self._include_session_layer_checkbox:
return self._include_session_layer_checkbox.model.get_value_as_bool()
return True
@property
def show_include_session_layer_option(self):
return self._show_include_session_layer_option
@show_include_session_layer_option.setter
def show_include_session_layer_option(self, value):
self._show_include_session_layer_option = value
if self._other_options_widget:
self._other_options_widget.visible = value
def _build_ui_impl(self):
if not self._versioning_enabled:
return
folder_url = ""
file_exporter = get_file_exporter()
if file_exporter and file_exporter._dialog:
folder_url = file_exporter._dialog.get_current_directory()
self._widget = ui.Frame()
CheckpointHelper.is_checkpoint_enabled_with_callback(folder_url, self._build_options_box)
def _build_option_checkbox(self, text, default_value, tooltip, identifier):
with ui.VStack():
ui.Spacer()
with ui.HStack(height=0):
checkbox = ui.CheckBox(width=14, height=14, style={"font_size": 16}, identifier=identifier)
checkbox.model.set_value(default_value)
ui.Spacer(width=4)
label = ui.Label(text, alignment=ui.Alignment.LEFT)
label.set_tooltip(tooltip)
ui.Spacer()
return checkbox
def _build_options_box(self, server_url: str, checkpoint_enabled: bool):
with self._widget:
with ui.VStack(height=0, style=get_style()):
if checkpoint_enabled:
ui.Label("Checkpoint comments:", height=20, alignment=ui.Alignment.LEFT_CENTER)
ui.Separator(height=5)
ui.Spacer(height=2)
with ui.ZStack():
with ui.HStack():
ui.StringField(self._comment_model, multiline=True, height=64, style_type_name_override="Field")
self._hint_container = ui.VStack()
with self._hint_container:
with ui.HStack():
ui.Label("Add checkpoint comments here.", height=20, style_type_name_override="Field.Hint")
ui.Spacer()
self._hint_container.visible = False
self._sub_begin_edit = self._comment_model.subscribe_begin_edit_fn(self._on_begin_edit)
self._sub_end_edit = self._comment_model.subscribe_end_edit_fn(self._on_end_edit)
else:
ui.Label("This server does not support checkpoints.", height=20, alignment=ui.Alignment.CENTER, word_wrap=True)
# OM-55838: Add option to support excluding session layer from flattening.
self._other_options_widget = ui.VStack(height=0)
with self._other_options_widget:
ui.Spacer(height=5)
ui.Separator(height=5)
ui.Label("Other Options:", height=20, alignment=ui.Alignment.LEFT_CENTER)
ui.Spacer(height=5)
self._include_session_layer_checkbox = self._build_option_checkbox(
"Include Session Layer", False,
"When this option is checked, it means it will include content\n"
"of session layer into the flattened stage.",
"include_session_layer"
)
self._other_options_widget.visible = self.show_include_session_layer_option
def _on_begin_edit(self, model):
self._hint_container.visible = False
def _on_end_edit(self, model: ui.AbstractValueModel):
if self.get_comment():
self._hint_container.visible = False
else:
self._hint_container.visible = True
def _destroy_impl(self, _):
self._comment_model = None
self._hint_container = None
self._widget = None
self._sub_begin_edit = None
self._sub_end_edit = None
self._include_session_layer_checkbox = None
class OpenOptionsDelegate(ImportOptionsDelegate):
def __init__(self):
super().__init__(
build_fn=self._build_ui_impl,
destroy_fn=self._destroy_impl
)
self._widget = None
self._load_payload_checkbox = None
def should_load_payload(self):
if self._load_payload_checkbox:
return self._load_payload_checkbox.model.get_value_as_bool()
def _build_ui_impl(self):
self._widget = ui.Frame()
with self._widget:
with ui.VStack(height=0, style=get_style()):
ui.Separator(height=5)
ui.Spacer(height=2)
with ui.HStack():
ui.Spacer(width=2)
self._load_payload_checkbox = ui.CheckBox(width=20, style_type_name_override="CheckBox")
self._load_payload_checkbox.model.set_value(True)
ui.Spacer(width=4)
ui.Label("Open Payloads", width=0, height=20, style_type_name_override="Label")
ui.Spacer()
def _destroy_impl(self, _):
self._load_payload_checkbox = None
self._widget = None
class AppUI:
def __init__(self):
self._open_stage_failed_prompt = None
self._save_layers_failed_prompt = None
self._save_stage_prompt = None
def destroy(self):
if self._open_stage_failed_prompt:
self._open_stage_failed_prompt.destroy()
self._open_stage_failed_prompt = None
if self._save_layers_failed_prompt:
self._save_layers_failed_prompt.destroy()
self._save_layers_failed_prompt = None
if self._save_stage_prompt:
self._save_stage_prompt.destroy()
self._save_stage_prompt = None
def save_root_and_sublayers(
self, new_root_path: str,
dirty_sublayers: List[str],
on_save_done: Callable = None,
dialog_options: int = DialogOptions.NONE,
save_comment: str = "",
allow_skip_sublayers: bool = False):
stage = omni.usd.get_context().get_stage()
if not stage:
return
if dialog_options == DialogOptions.HIDE:
self._save_layers(new_root_path, dirty_sublayers, on_save_done=on_save_done)
return
if len(dirty_sublayers) > 0 or dialog_options == DialogOptions.FORCE:
if self._save_stage_prompt:
self._save_stage_prompt.destroy()
self._save_stage_prompt = StageSaveDialog(
enable_dont_save=allow_skip_sublayers,
on_save_fn=lambda layers, comment: self._save_layers(
new_root_path, layers, on_save_done=on_save_done, checkpoint_comment=comment),
on_dont_save_fn=lambda comment: self._dont_save_layers(
new_root_path, on_save_done=on_save_done, checkpoint_comment=comment),
on_cancel_fn=lambda comment: self._cancel_save(new_root_path, checkpoint_comment=comment),
)
self._save_stage_prompt.show(dirty_sublayers)
else:
self._save_layers(new_root_path, [], on_save_done=on_save_done, checkpoint_comment=save_comment)
def _save_layers(
self, new_root_path, dirty_layers, on_save_done=None, create_checkpoint=True, checkpoint_comment=""
):
settings = carb.settings.get_settings()
versioning_enabled = settings.get_as_bool("exts/omni.kit.window.file/enable_versioning") or False
if versioning_enabled and create_checkpoint:
omni.client.create_checkpoint(new_root_path, checkpoint_comment)
def save_done_fn(result, err):
if result:
if versioning_enabled and create_checkpoint:
omni.client.create_checkpoint(new_root_path, checkpoint_comment)
if on_save_done:
on_save_done(result, err)
omni.kit.window.file.save_layers(
new_root_path, dirty_layers, save_done_fn, create_checkpoint, checkpoint_comment
)
def _dont_save_layers(self, new_root_path, on_save_done=None, checkpoint_comment=""):
if new_root_path:
self._save_layers(new_root_path, [], on_save_done=on_save_done, checkpoint_comment=checkpoint_comment)
elif on_save_done:
on_save_done(True, "")
def _cancel_save(self, new_root_path, checkpoint_comment=""):
if new_root_path:
self._save_layers(new_root_path, [], None, checkpoint_comment=checkpoint_comment)
def show_open_stage_failed_prompt(self, path):
if not self._open_stage_failed_prompt:
self._open_stage_failed_prompt = Prompt(
f'{omni.kit.ui.get_custom_glyph_code("${glyphs}/exclamation.svg")} Open Stage Failed',
"",
["OK"],
[None],
)
self._open_stage_failed_prompt.set_text(
f"Failed to open stage {os.path.basename(path)}. Please check console for error."
)
self._open_stage_failed_prompt.show()
return self._open_stage_failed_prompt
def show_save_layers_failed_prompt(self):
if not self._save_layers_failed_prompt:
self._save_layers_failed_prompt = Prompt(
f'{omni.kit.ui.get_custom_glyph_code("${glyphs}/exclamation.svg")} Save Layer(s) Failed',
"Failed to save layers. Please check console for error.",
["OK"],
[None],
)
self._save_layers_failed_prompt.show()
return self._save_layers_failed_prompt
| 11,906 | Python | 40.34375 | 131 | 0.592474 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/read_only_options_window.py | import carb
import omni.usd
import omni.ui as ui
from pathlib import Path
CURRENT_PATH = Path(__file__).parent.absolute()
ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("icons")
class ReadOnlyOptionsWindow:
def __init__(self, open_with_new_edit_fn, open_original_fn, modal=False):
self._title = "Opening a Read Only File"
self._modal = modal
self._buttons = []
self._content_buttons = [
("Open With New Edit Layer", "open_edit_layer.svg", open_with_new_edit_fn),
("Open Original File", "pencil.svg", open_original_fn),
]
self._build_ui()
def destroy(self):
for button in self._buttons:
button.set_clicked_fn(None)
self._buttons.clear()
def show(self):
self._window.visible = True
def hide(self):
self._window.visible = False
def is_visible(self):
return self._window.visible
def _build_ui(self):
self._window = ui.Window(
self._title, visible=False, height=0, dockPreference=ui.DockPreference.DISABLED
)
self._window.flags = (
ui.WINDOW_FLAGS_NO_COLLAPSE
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_SCROLLBAR
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_MOVE
)
if self._modal:
self._window.flags = self._window.flags | ui.WINDOW_FLAGS_MODAL
button_style = {
"Button": {"stack_direction": ui.Direction.LEFT_TO_RIGHT},
"Button.Image": {"alignment": ui.Alignment.CENTER},
"Button.Label": {"alignment": ui.Alignment.LEFT_CENTER}
}
def button_cliked_fn(button_fn):
if button_fn:
button_fn()
self.hide()
with self._window.frame:
with ui.VStack(height=0):
ui.Spacer(width=0, height=10)
with ui.VStack(height=0):
ui.Spacer(height=0)
for button in self._content_buttons:
(button_text, button_icon, button_fn) = button
with ui.HStack():
ui.Spacer(width=40)
ui_button = ui.Button(
" " + button_text,
image_url=f"{ICON_PATH}/{button_icon}",
image_width=24,
height=40,
clicked_fn=lambda a=button_fn: button_cliked_fn(a),
style=button_style
)
ui.Spacer(width=40)
ui.Spacer(height=5)
self._buttons.append(ui_button)
ui.Spacer(height=5)
with ui.HStack():
ui.Spacer()
cancel_button = ui.Button("Cancel", width=80, height=0)
cancel_button.set_clicked_fn(lambda: self.hide())
self._buttons.append(cancel_button)
ui.Spacer(width=40)
ui.Spacer(height=0)
ui.Spacer(width=0, height=10)
| 3,269 | Python | 34.543478 | 91 | 0.492199 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_stop_animation.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import platform
import unittest
import os
import pathlib
import asyncio
import shutil
import tempfile
import omni.kit.app
import omni.usd
import omni.timeline
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows
from omni.kit.window.file_exporter.test_helper import FileExporterTestHelper
class FileWindowStopAnimation(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
# wait for material to be preloaded so create menu is complete & menus don't rebuild during tests
await omni.kit.material.library.get_mdl_list_async()
await ui_test.human_delay()
# load stage
await open_stage(get_test_data_path(__name__, "physics_animation.usda"))
# setup events
self._future_test = None
self._required_stage_event = -1
self._stage_event_sub = omni.usd.get_context().get_stage_event_stream().create_subscription_to_pop(self._on_stage_event, name="omni.usd.window.file")
# After running each test
async def tearDown(self):
# free events
self._future_test = None
self._required_stage_event = -1
self._stage_event_sub = None
await wait_stage_loading()
await omni.usd.get_context().new_stage_async()
def _on_stage_event(self, event):
if self._future_test and int(self._required_stage_event) == int(event.type) and not self._future_test.done():
self._future_test.set_result(event.type)
async def reset_stage_event(self, stage_event):
self._required_stage_event = stage_event
self._future_test = asyncio.Future()
async def wait_for_stage_event(self):
async def wait_for_event():
await self._future_test
try:
await asyncio.wait_for(wait_for_event(), timeout=30.0)
except asyncio.TimeoutError:
carb.log_error(f"wait_for_stage_event timeout waiting for {self._required_stage_event}")
self._future_test = None
self._required_stage_event = -1
async def test_l1_stop_animation_save(self):
def get_box_pos():
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath("/World/boxActor")
attr = prim.GetAttribute("xformOp:translate")
return attr.Get()
def play_anim():
timeline = omni.timeline.get_timeline_interface()
if timeline:
timeline.play()
# setup
orig_pos = get_box_pos()
tmpdir = tempfile.mkdtemp()
orig_file = get_test_data_path(__name__, "physics_animation.usda").replace("\\", "/")
new_file = f"{tmpdir}/physics_animation.usd".replace("\\", "/")
# play anim
play_anim()
await ui_test.human_delay(100)
# save as
await self.reset_stage_event(omni.usd.StageEventType.SAVED)
omni.kit.actions.core.get_action_registry().get_action("omni.kit.window.file", "save_as").execute()
await ui_test.human_delay(10)
async with FileExporterTestHelper() as file_export_helper:
await file_export_helper.click_apply_async(filename_url=new_file)
await self.wait_for_stage_event()
# play anim
play_anim()
await ui_test.human_delay(100)
# save
await self.reset_stage_event(omni.usd.StageEventType.SAVED)
omni.kit.actions.core.get_action_registry().get_action("omni.kit.window.file", "save").execute()
await ui_test.human_delay(10)
# check _check_and_select_all and _on_select_all_fn for StageSaveDialog
check_box = ui_test.find("Select Files to Save##file.py//Frame/VStack[0]/ScrollingFrame[0]/VStack[0]/HStack[0]/CheckBox[0]")
await check_box.click(human_delay_speed=10)
await check_box.click(human_delay_speed=10)
await ui_test.human_delay()
await ui_test.find("Select Files to Save##file.py//Frame/**/Button[*].text=='Save Selected'").click()
await ui_test.human_delay()
await self.wait_for_stage_event()
# load saved file
await open_stage(new_file)
# verify boxActor is in same place
new_pos = get_box_pos()
self.assertAlmostEqual(orig_pos[0], new_pos[0], places=5)
self.assertAlmostEqual(orig_pos[1], new_pos[1], places=5)
self.assertAlmostEqual(orig_pos[2], new_pos[2], places=5)
| 5,013 | Python | 37.56923 | 157 | 0.655496 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_file_save.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import carb
import os
import tempfile
import shutil
import omni.kit.app
import omni.kit.commands
import omni.kit.test
from pathlib import Path
from unittest.mock import Mock, patch
from omni.kit.window.file_exporter.test_helper import FileExporterTestHelper
from .. import FileWindowExtension, get_instance as get_window_file
from .test_base import TestFileBase
from pxr import Usd
import unittest
class TestFileSave(TestFileBase):
async def setUp(self):
await super().setUp()
async def tearDown(self):
await super().tearDown()
async def test_file_save(self):
"""Testing that save should write to stage url"""
omni.usd.get_context().new_stage()
omni.usd.get_context().set_pending_edit(False)
test_file = "test_file.usda"
temp_path = os.path.join(tempfile.gettempdir(), test_file)
shutil.copyfile(os.path.join(self._usd_path, test_file), temp_path)
omni.kit.window.file.open_stage(temp_path)
await self.wait_for_update()
mock_callback = Mock()
omni.kit.window.file.save(mock_callback)
await self.wait_for_update()
self.assertEqual(omni.usd.get_context().get_stage_url(), temp_path.replace("\\", "/"))
self.assertTrue(os.path.isfile(temp_path))
mock_callback.assert_called_once()
self.remove_file(temp_path)
async def test_file_save_with_render_setting_changes_only(self):
usd_context = omni.usd.get_context()
await usd_context.new_stage_async()
self.assertFalse(usd_context.has_pending_edit())
with tempfile.TemporaryDirectory() as tmp_dir_name:
await omni.kit.app.get_app().next_update_async()
# save
tmp_file_path = Path(tmp_dir_name) / "tmp.usda"
result = usd_context.save_as_stage(str(tmp_file_path))
self.assertTrue(result)
self.assertFalse(usd_context.has_pending_edit())
# save the file with customized key value
settings = carb.settings.get_settings()
setting_key_ao = "/rtx/post/aa/op"
settings.set_int(setting_key_ao, 3)
await omni.kit.app.get_app().next_update_async()
# After changing render settings, it will be dirty.
self.assertTrue(usd_context.has_pending_edit())
# Saves stage, although no layers are dirty except render settings.
omni.kit.window.file.save(None)
# Waiting for save to be done as it's asynchronous.
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
# Making sure that render settings are saved into root layer.
self.assertFalse(usd_context.has_pending_edit())
# Reloading stage will reload the settings also.
await usd_context.reopen_stage_async()
await omni.kit.app.get_app().next_update_async()
self.assertFalse(usd_context.has_pending_edit())
setting_value_ao = settings.get(setting_key_ao)
self.assertEqual(setting_value_ao, 3)
# New stage to release temp file.
await usd_context.new_stage_async()
async def test_file_save_read_only_file(self):
"""Test saving read-only file calls save_as instead"""
omni.usd.get_context().new_stage()
omni.usd.get_context().set_pending_edit(False)
test_file = "test_file.usda"
temp_path = os.path.join(tempfile.gettempdir(), test_file)
shutil.copyfile(os.path.join(self._usd_path, test_file), temp_path)
omni.kit.window.file.open_stage(temp_path)
await self.wait_for_update()
class ListEntry:
def __init__(self) -> None:
self.flags = 0
mock_callback = Mock()
with patch.object(omni.usd.UsdContext, 'is_new_stage', return_value=False),\
patch.object(omni.client, "stat_async", return_value=(omni.client.Result.OK, ListEntry())),\
patch.object(FileWindowExtension, "save_as") as mock_save_as:
omni.kit.window.file.save(mock_callback)
await self.wait_for_update()
mock_save_as.assert_called_once_with(False, mock_callback, allow_skip_sublayers=False)
self.remove_file(temp_path)
async def test_file_saveas(self):
"""Testing save as"""
omni.usd.get_context().new_stage()
omni.usd.get_context().set_pending_edit(False)
temp_path = self._temp_path.replace('.usda', '.usd')
mock_callback = Mock()
async with FileExporterTestHelper() as file_export_helper:
with patch.object(omni.usd.UsdContext, 'is_new_stage', return_value=False):
omni.kit.window.file.save_as(False, mock_callback)
await self.wait_for_update()
await file_export_helper.click_apply_async(filename_url=temp_path)
await self.wait_for_update()
mock_callback.assert_called_once()
self.assertTrue(os.path.isfile(temp_path))
self.remove_file(temp_path)
async def _test_file_saveas_with_empty_filename(self): # pragma: no cover
"""Testing save as with an empty filename, should not allow saving."""
omni.usd.get_context().new_stage()
omni.usd.get_context().set_pending_edit(False)
temp_path = self._temp_path.replace('.usda', '.usd')
mock_callback = Mock()
async with FileExporterTestHelper() as file_export_helper:
with patch.object(omni.usd.UsdContext, 'is_new_stage', return_value=False):
omni.kit.window.file.save_as(False, mock_callback)
await self.wait_for_update()
await file_export_helper.click_apply_async()
await self.wait_for_update()
mock_callback.assert_not_called()
self.assertFalse(os.path.isfile(temp_path))
async def _test_file_saveas_flattened_internal(self, include_session_layer):
"""Testing save as flatten"""
omni.usd.get_context().new_stage()
omni.usd.get_context().set_pending_edit(False)
mock_callback = Mock()
base, ext = os.path.splitext(self._temp_path)
temp_path = base + str(include_session_layer) + ext
temp_path = self._temp_path.replace('.usda', '.usd')
async with FileExporterTestHelper() as file_export_helper:
with patch.object(omni.usd.UsdContext, 'is_new_stage', return_value=False):
omni.kit.window.file.save_as(True, mock_callback)
await self.wait_for_update()
import omni.kit.ui_test as ui_test
file_picker = ui_test.find("Save File As...")
self.assertTrue(file_picker)
await file_picker.focus()
include_session_layer_checkbox = file_picker.find(
"**/CheckBox[*].identifier=='include_session_layer'"
)
self.assertTrue(include_session_layer_checkbox)
include_session_layer_checkbox.model.set_value(include_session_layer)
await file_export_helper.click_apply_async(filename_url=temp_path)
await self.wait_for_update()
stage = Usd.Stage.Open(temp_path)
prim = stage.GetPrimAtPath("/OmniverseKit_Persp")
if include_session_layer:
self.assertTrue(prim)
else:
self.assertFalse(prim)
stage = None
mock_callback.assert_called_once()
self.assertTrue(os.path.isfile(temp_path))
self.remove_file(temp_path)
@unittest.skip("A.B. temp disable, omni.physx.bundle extension causes issues")
async def test_file_saveas_flattened_with_session_layer(self):
await self._test_file_saveas_flattened_internal(True)
async def test_file_saveas_flattened_without_session_layer(self):
await self._test_file_saveas_flattened_internal(False)
async def test_show_save_layers_failed_prompt(self):
omni.usd.get_context().new_stage()
prompt = get_window_file().ui_handler.show_save_layers_failed_prompt()
await self.wait_for_update()
prompt.hide()
async def test_file_saveas_existed_filename(self):
"""Testing save as with a filename which is already existed, should not allow saving."""
# create an empty stage
await omni.usd.get_context().new_stage_async()
omni.usd.get_context().set_pending_edit(False)
file_name = f"4Lights.usda"
temp_path = os.path.join(tempfile.gettempdir(), file_name)
shutil.copyfile(os.path.join(self._usd_path, file_name), temp_path)
# save the current stage to the temp path where the file name already exists
async with FileExporterTestHelper() as file_export_helper:
with patch.object(omni.usd.UsdContext, 'is_new_stage', return_value=False):
omni.kit.window.file.save_as(False, Mock())
await self.wait_for_update()
await file_export_helper.click_apply_async(filename_url=temp_path)
await self.wait_for_update()
# check 4Lights.usda is not empty, which means saveas didn't happen
stage = Usd.Stage.Open(str(temp_path))
await self.wait_for_update()
prim = stage.GetPrimAtPath("/Stage/SphereLight_01")
self.assertTrue(prim)
self.remove_file(temp_path)
async def test_invalid_save(self):
"""Test no valid stage save"""
if omni.usd.get_context().get_stage():
await omni.usd.get_context().close_stage_async()
mock_callback = Mock()
omni.kit.window.file.save(mock_callback)
mock_callback.assert_not_called()
| 10,185 | Python | 39.420635 | 104 | 0.633873 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_file_window.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.window.file
from .test_base import TestFileBase
from unittest.mock import Mock
from omni.kit import ui_test
from omni.kit.window.file import ReadOnlyOptionsWindow
from omni.kit.window.file import register_open_stage_addon, register_open_stage_complete
from omni.kit.window.file_importer import get_file_importer
class TestFileWindow(TestFileBase):
async def setUp(self):
await super().setUp()
# After running each test
async def tearDown(self):
await super().tearDown()
async def test_read_only_options_window(self):
"""Testing read only options window"""
self._readonly_window = ReadOnlyOptionsWindow(None, None, True)
self._readonly_window.show()
self.assertTrue(self._readonly_window.is_visible)
self._readonly_window.destroy()
async def test_stage_register(self):
"""Testing register_open_stage_addon and register_open_stage_complete subscription"""
mock_callback1 = Mock()
mock_callback2 = Mock()
self._addon_subscription = register_open_stage_addon(mock_callback1)
self._complete_subscription = register_open_stage_complete(mock_callback2)
omni.kit.window.file.open_stage(f"{self._usd_path}/test_file.usda")
await self.wait_for_update()
mock_callback1.assert_called_once()
mock_callback2.assert_called_once()
async def test_add_reference(self):
omni.kit.window.file.add_reference(is_payload=False)
await ui_test.human_delay()
file_importer = get_file_importer()
self.assertTrue(file_importer.is_window_visible)
file_importer.click_cancel()
| 2,103 | Python | 35.91228 | 93 | 0.717071 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/__init__.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from .test_file_new import *
from .test_file_open import *
from .test_file_save import *
from .test_prompt_unsaved import *
from .test_stop_animation import *
from .test_file_window import *
from .test_loadstage import *
| 657 | Python | 40.124997 | 77 | 0.7793 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_file_new.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import omni.usd
import omni.kit.window
from unittest.mock import patch
from .test_base import TestFileBase
class TestFileNew(TestFileBase):
async def setUp(self):
await super().setUp()
# After running each test
async def tearDown(self):
await super().tearDown()
async def test_file_new(self):
"""Testing file new"""
omni.kit.window.file.new()
await self.wait_for_update()
# verify new layer has non-Null identifier
self.assertTrue(bool(omni.usd.get_context().get_stage().GetRootLayer().identifier))
| 1,033 | Python | 32.354838 | 91 | 0.724105 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_loadstage.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import asyncio
import omni.ui as ui
import omni.kit.app
import omni.kit.test
import omni.kit.ui_test as ui_test
from omni.ui.tests.test_base import OmniUiTest
from omni.kit.test_suite.helpers import get_test_data_path, wait_stage_loading
from omni.kit import ui_test
class TestOpenStage(OmniUiTest):
"""Testing omni.usd.core"""
async def setUp(self):
await super().setUp()
await wait_stage_loading()
self._future_test = None
self._required_stage_event = -1
self._stage_event_sub = omni.usd.get_context().get_stage_event_stream().create_subscription_to_pop(self._on_stage_event, name="omni.usd.menu.file")
# After running each test
async def tearDown(self):
await super().tearDown()
def _on_stage_event(self, event):
if self._future_test and int(self._required_stage_event) == int(event.type) and not self._future_test.done():
self._future_test.set_result(event.type)
async def reset_stage_event(self, stage_event):
self._required_stage_event = stage_event
self._future_test = asyncio.Future()
async def wait_for_stage_event(self):
async def wait_for_event():
await self._future_test
try:
await asyncio.wait_for(wait_for_event(), timeout=30.0)
except asyncio.TimeoutError:
carb.log_error(f"wait_for_stage_event timeout waiting for {self._required_stage_event}")
self._future_test = None
self._required_stage_event = -1
async def test_open_stage(self):
def on_load_complete(success):
if not success:
if self._future_test:
self._future_test.set_result(False)
usd_context = omni.usd.get_context()
# test file not found
stage = omni.usd.get_context().get_stage()
await self.reset_stage_event(omni.usd.StageEventType.OPENED)
omni.kit.window.file.open_stage("missing file", callback=on_load_complete)
await self.wait_for_stage_event()
stage = omni.usd.get_context().get_stage()
self.assertEqual(stage, omni.usd.get_context().get_stage())
await ui_test.human_delay(50)
# load valid stage
stage = omni.usd.get_context().get_stage()
await self.reset_stage_event(omni.usd.StageEventType.OPENED)
omni.kit.window.file.open_stage(get_test_data_path(__name__, "4Lights.usda"), callback=on_load_complete)
await self.wait_for_stage_event()
self.assertNotEqual(stage, omni.usd.get_context().get_stage())
await ui_test.human_delay(50)
# create new stage
await usd_context.new_stage_async()
await ui_test.human_delay(50)
# load a material as usd file
stage = omni.usd.get_context().get_stage()
await self.reset_stage_event(omni.usd.StageEventType.OPENED)
success = omni.kit.window.file.open_stage(get_test_data_path(__name__, "anno_material.mdl"), callback=on_load_complete)
await self.wait_for_stage_event()
self.assertEqual(stage, omni.usd.get_context().get_stage())
await ui_test.human_delay(50)
| 3,594 | Python | 38.076087 | 155 | 0.663884 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_prompt_unsaved.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import omni.usd
import omni.kit.window
from unittest.mock import Mock, patch
from omni.usd import UsdContext
from carb.settings import ISettings
from .test_base import TestFileBase
from .. import FileWindowExtension
# run tests last as it doesn't cleanup modela dialogs
class zzTestPromptIfUnsavedStage(TestFileBase):
async def setUp(self):
await super().setUp()
self._show_unsaved_layers_dialog = False
self._ignore_unsaved_stage = False
# After running each test
async def tearDown(self):
await super().tearDown()
def _mock_get_carb_setting(self, setting: str):
from ..scripts.file_window import SHOW_UNSAVED_LAYERS_DIALOG, IGNORE_UNSAVED_STAGE
if setting == SHOW_UNSAVED_LAYERS_DIALOG:
return self._show_unsaved_layers_dialog
elif setting == IGNORE_UNSAVED_STAGE:
return self._ignore_unsaved_stage
return False
async def test_save_unsaved_stage(self):
"""Testing click save when prompted to save unsaved stage"""
self._ignore_unsaved_stage = False
self._show_unsaved_layers_dialog = True
mock_callback = Mock()
with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting),\
patch.object(UsdContext, "has_pending_edit", return_value=True),\
patch.object(UsdContext, "is_new_stage", return_value=True),\
patch.object(FileWindowExtension, "save") as mock_file_save:
# Show prompt and click Save
omni.kit.window.file.prompt_if_unsaved_stage(mock_callback)
await self.click_unsaved_stage_prompt(button=0)
mock_file_save.assert_called_once_with(mock_callback, allow_skip_sublayers=True)
async def test_dont_save_unsaved_stage(self):
"""Testing click don't save when prompted to save unsaved stage"""
self._ignore_unsaved_stage = False
self._show_unsaved_layers_dialog = True
mock_callback = Mock()
with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting),\
patch.object(UsdContext, "has_pending_edit", return_value=True),\
patch.object(UsdContext, "is_new_stage", return_value=True),\
patch.object(FileWindowExtension, "save") as mock_file_save:
# Show prompt and click Don't Save
omni.kit.window.file.prompt_if_unsaved_stage(mock_callback)
await self.click_unsaved_stage_prompt(button=1)
mock_file_save.assert_not_called()
mock_callback.assert_called_once()
async def test_cancel_unsaved_stage(self):
"""Testing click cancel when prompted to save unsaved stage"""
self._ignore_unsaved_stage = False
self._show_unsaved_layers_dialog = True
mock_callback = Mock()
with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting),\
patch.object(UsdContext, "has_pending_edit", return_value=True),\
patch.object(UsdContext, "is_new_stage", return_value=True),\
patch.object(FileWindowExtension, "save") as mock_file_save:
# Show prompt and click Don't Save
omni.kit.window.file.prompt_if_unsaved_stage(mock_callback)
await self.click_unsaved_stage_prompt(button=2)
mock_file_save.assert_not_called()
mock_callback.assert_not_called()
async def test_no_prompt(self):
"""Testing unsaved stage prompt not shown"""
self._ignore_unsaved_stage = False
self._show_unsaved_layers_dialog = False
mock_callback = Mock()
with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting),\
patch.object(UsdContext, "has_pending_edit", return_value=True),\
patch.object(UsdContext, "is_new_stage", return_value=False),\
patch.object(FileWindowExtension, "save") as mock_file_save:
omni.kit.window.file.prompt_if_unsaved_stage(mock_callback)
mock_file_save.assert_called_once_with(mock_callback, allow_skip_sublayers=True)
async def test_ignore_unsaved(self):
"""Testing ignore unsaved setting set to True"""
self._ignore_unsaved_stage = True
mock_callback = Mock()
with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting),\
patch.object(UsdContext, "has_pending_edit", return_value=True),\
patch.object(FileWindowExtension, "save") as mock_file_save:
omni.kit.window.file.prompt_if_unsaved_stage(mock_callback)
mock_file_save.assert_not_called()
mock_callback.assert_called_once()
async def test_no_pending_edit(self):
"""Testing stage with no pending edit"""
self._ignore_unsaved_stage = False
mock_callback = Mock()
with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting),\
patch.object(UsdContext, "has_pending_edit", return_value=False),\
patch.object(FileWindowExtension, "save") as mock_file_save:
omni.kit.window.file.prompt_if_unsaved_stage(mock_callback)
mock_file_save.assert_not_called()
mock_callback.assert_called_once()
| 5,662 | Python | 43.590551 | 90 | 0.668492 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_base.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import random
import string
import carb
import omni.kit.app
import omni.usd
import asyncio
import omni.kit.ui_test as ui_test
from omni.ui.tests.test_base import OmniUiTest
from .. import get_instance as get_window_file
class TestFileBase(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
from omni.kit.window.file.scripts.file_window import TEST_DATA_PATH
self._usd_path = TEST_DATA_PATH.absolute()
token = carb.tokens.get_tokens_interface()
temp_dir = token.resolve("${temp}")
def get_random_string():
return "".join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))
self._temp_path = os.path.join(temp_dir, get_random_string(), "test.usda").replace("\\", "/")
self._temp_edit_path = os.path.join(temp_dir, get_random_string(), "test_edit.usda").replace("\\", "/")
self._dirname = os.path.dirname(self._temp_path).replace("\\", "/")
self._filename = os.path.basename(self._temp_path)
# After running each test
async def tearDown(self):
await super().tearDown()
async def wait_for_update(self, usd_context=omni.usd.get_context(), wait_frames=20):
max_loops = 0
while max_loops < wait_frames:
_, files_loaded, total_files = usd_context.get_stage_loading_status()
await omni.kit.app.get_app().next_update_async()
if files_loaded or total_files:
continue
max_loops = max_loops + 1
def remove_file(self, full_path: str):
import stat
try:
os.chmod(full_path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777
os.remove(full_path)
except Exception:
# Don't know what's causing these errors: "PermissionError: [WinError 5] Access is denied", but don't want
# to fail tests for this reason.
pass
async def click_file_existed_prompt(self, accept: bool = True):
dialog = get_window_file()._file_existed_prompt
button = 0 if accept else 1
if dialog and dialog._button_list[button][1]:
# If file exists, click accept at the prompt to continue
dialog._button_list[button][1]()
await self.wait_for_update()
async def click_save_stage_prompt(self, button: int = 0):
dialog = get_window_file().ui_handler._save_stage_prompt
if button == 0:
dialog._on_save_fn()
elif button == 1:
dialog._on_dont_save_fn()
elif button == 2:
dialog._on_cacnel_fn()
async def click_unsaved_stage_prompt(self, button: int = 0):
dialog = get_window_file()._unsaved_stage_prompt
_, click_fn = dialog._button_list[button]
if click_fn:
click_fn()
await self.wait_for_update()
| 3,325 | Python | 37.229885 | 118 | 0.633383 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_file_open.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import tempfile
import shutil
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import unittest
from unittest.mock import Mock, patch
from carb.settings import ISettings
from omni.kit.window.file_exporter.test_helper import FileExporterTestHelper
from omni.kit.window.file_importer.test_helper import FileImporterTestHelper
from pxr import Sdf
from omni.kit.widget.nucleus_connector import NucleusConnectorExtension
from .. import get_instance as get_window_file
from .test_base import TestFileBase
class TestFileOpen(TestFileBase):
async def setUp(self):
await super().setUp()
# After running each test
async def tearDown(self):
await super().tearDown()
def _mock_get_carb_setting(self, setting: str):
from ..scripts.file_window import SHOW_UNSAVED_LAYERS_DIALOG, IGNORE_UNSAVED_STAGE
if setting == SHOW_UNSAVED_LAYERS_DIALOG:
return True
elif setting == IGNORE_UNSAVED_STAGE:
return True
return False
async def test_file_open(self):
"""Testing file open"""
omni.usd.get_context().new_stage()
omni.usd.get_context().set_pending_edit(False)
omni.kit.window.file.open_stage(f"{self._usd_path}/test_file.usda")
await self.wait_for_update()
# check file is loaded
stage = omni.usd.get_context().get_stage()
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)]
self.assertEquals(prim_list, ['/World', '/World/defaultLight'])
async def test_open(self):
"""Test omni.kit.window.file.open"""
async with FileImporterTestHelper() as file_importer_helper:
omni.kit.window.file.open()
from omni.kit.window.file_importer import get_file_importer
file_importer = get_file_importer()
self.assertTrue(file_importer.is_window_visible)
async def test_file_open_with_new_edit_layer(self):
"""Testing that open with new edit layer executes the callback upon success"""
omni.usd.get_context().new_stage()
omni.usd.get_context().set_pending_edit(False)
layer = Sdf.Layer.CreateNew(self._temp_path)
self.assertTrue(layer, f"Failed to create temp layer {self._temp_path}.")
layer.Save()
layer = None
mock_callback = Mock()
async with FileExporterTestHelper() as file_export_helper:
omni.kit.window.file.open_with_new_edit_layer(self._temp_path, callback=mock_callback)
await self.wait_for_update()
await file_export_helper.click_apply_async()
await self.wait_for_update()
mock_callback.assert_called_once()
@unittest.skip("Crashes when run in random order") # OM-77535
async def test_file_open_with_new_edit_layer_overwrites_existing_file(self):
"""Testing that open with new edit layer overwrites existing file"""
layer = Sdf.Layer.CreateNew(self._temp_path)
self.assertTrue(layer, f"Failed to create temp layer {self._temp_path}.")
layer.Save()
layer = None
layer = Sdf.Layer.CreateNew(self._temp_edit_path)
self.assertTrue(layer, f"Failed to create temp layer {self._temp_edit_path}.")
layer.Save()
layer = None
async def open_with_new_edit_layer(path):
async with FileExporterTestHelper() as file_export_helper:
omni.kit.window.file.open_with_new_edit_layer(path)
await self.wait_for_update()
await file_export_helper.click_apply_async()
await self.wait_for_update()
await self.click_file_existed_prompt(accept=True)
current_stage = omni.usd.get_context().get_stage()
self.assertTrue(current_stage)
name, _ = os.path.splitext(path)
expected_layer_name = f"{name}_edit"
self.assertTrue(current_stage.GetRootLayer().anonymous)
self.assertEqual(len(current_stage.GetRootLayer().subLayerPaths), 2)
sublayer0 = current_stage.GetRootLayer().subLayerPaths[0]
sublayer1 = current_stage.GetRootLayer().subLayerPaths[1]
file_name, _ = os.path.splitext(sublayer0)
self.assertEqual(file_name, expected_layer_name)
self.assertEqual(os.path.normpath(sublayer1), os.path.normpath(path))
# First time, creates new edit layer
await open_with_new_edit_layer(self._temp_path)
# Second time, creates the same name to make sure it correctly overwrites.
await omni.usd.get_context().close_stage_async()
await open_with_new_edit_layer(self._temp_path)
async def test_file_reopen(self):
"""Testing file reopen"""
await omni.usd.get_context().new_stage_async()
omni.usd.get_context().set_pending_edit(False)
omni.kit.window.file.open_stage(f"{self._usd_path}/4Lights.usda")
await self.wait_for_update()
# verify its a unmodified stage
self.assertFalse(omni.kit.undo.can_undo())
## create prim
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
# verify its a modified stage
self.assertTrue(omni.kit.undo.can_undo())
# Skip unsaved stage prompt
with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting):
omni.kit.window.file.reopen()
await self.wait_for_update()
# verify its a unmodified stage
self.assertFalse(omni.kit.undo.can_undo())
async def test_file_reopen_with_new_edit_layer(self):
temp_dir = tempfile.mkdtemp()
omni.usd.get_context().new_stage()
omni.usd.get_context().set_pending_edit(False)
omni.kit.window.file.open_stage(f"{self._usd_path}/4Lights.usda")
await self.wait_for_update()
async with FileExporterTestHelper() as file_export_helper:
stage = omni.usd.get_context().get_stage()
stage_url = stage.GetRootLayer().identifier
# Re-open with edit layer
omni.kit.window.file.open_with_new_edit_layer(stage_url)
await self.wait_for_update()
# Save edit layer to temp dir
temp_url = f"{temp_dir}/4Lights_layer.usd".replace("\\", "/")
await file_export_helper.click_apply_async(filename_url=temp_url)
await self.wait_for_update()
layer = omni.usd.get_context().get_stage().GetRootLayer()
expected = [temp_url, stage_url.replace("\\", "/")]
self.assertTrue(layer.anonymous)
self.assertTrue(len(layer.subLayerPaths) == 2)
self.assertEqual(layer.subLayerPaths[0], expected[0])
self.assertEqual(layer.subLayerPaths[1], expected[1])
# cleanup
shutil.rmtree(temp_dir, ignore_errors=True)
async def test_show_open_stage_failed_prompt(self):
"""Testing show_open_stage_failed_prompt"""
omni.usd.get_context().new_stage()
prompt = get_window_file().ui_handler.show_open_stage_failed_prompt("Test Window File Show Open Stage Failed Prompt")
await self.wait_for_update()
prompt.hide()
async def test_connect_nucleus_when_opening_unreachable_file(self):
"""Testing that when opening an unreachable file, will try to auto-connect to Nucleus server"""
omni.usd.get_context().new_stage()
omni.usd.get_context().set_pending_edit(False)
test_host = "ov-unconnected"
test_url = f"omniverse://{test_host}/test_file.usda"
async def mock_stat_async(url: str):
return (omni.client.Result.ERROR_CONNECTION, None)
with patch("omni.client.stat_async", side_effect=mock_stat_async),\
patch.object(NucleusConnectorExtension, "connect") as mock_nucleus_connect:
omni.kit.window.file.open_stage(test_url)
await self.wait_for_update()
# Confirm attempt to connect to Nucleus server
self.assertEqual(mock_nucleus_connect.call_args[0], (test_host, f"omniverse://{test_host}"))
async def test_file_close(self):
"""Testing try to close a file which has been modified"""
await omni.usd.get_context().new_stage_async()
omni.usd.get_context().set_pending_edit(False)
omni.kit.window.file.open_stage(f"{self._usd_path}/4Lights.usda")
await self.wait_for_update()
# modify the stage
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
# try to close a modified stage
mock_callback = Mock()
with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting):
omni.kit.window.file.close(mock_callback)
await self.wait_for_update()
mock_callback.assert_called_once()
| 9,309 | Python | 40.377778 | 125 | 0.653883 |
omniverse-code/kit/exts/omni.kit.window.file/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.3.32] - 2023-01-13
## Changed
- Remove render settings save as it's driven by events already.
## [1.3.31] - 2023-01-04
## Changed
- skipping test_file_open_with_new_edit_layer_overwrites_existing_file which crashes when run in random order.
## [1.3.30] - 2022-11-04
## Added
- open stage complete callback register for the use of e.g. Activiy window
## [1.3.29] - 2022-10-28
## Changed
- When opening a stage, auto-connect to nucleus.
## [1.3.28] - 2022-10-01
## Changed
- Do not pass in a default filename for new stage for save-as;
- Explicitly set file exporter to validate filename for save-as;
## [1.3.27] - 2022-09-21
## Changed
- When saving a checkpoint or read-only file, use save_as instead.
## [1.3.26] - 2022-09-14
## Changed
- Pass in default file url to file exporter for save-as option.
## [1.3.25] - 2022-09-05
## Changed
- Supports to flatten stage without session layer.
## [1.3.24] - 2022-07-22
## Changed
- Fixed checkpoint comments with latet omni.usd_resolver.
## [1.3.23] - 2022-07-19
## Changed
- As menus no longer use contextual greying
- Improved error handing for actions & notifications
## [1.3.22] - 2022-07-19
## Changed
- Fixes comment field in save-as option
## [1.3.21] - 2022-06-27
## Changed
- Fixed save actions
## [1.3.20] - 2022-05-30
## Changed
- Added action "open_stage"
- Added action "save_with_options"
- Added action "save_as_flattened"
- Added action "add_payload"
## [1.3.19] - 2022-06-15
## Changed
- Updated unittests.
## [1.3.18] - 2022-05-30
## Changed
- "Select Files to Save" window expands with length of filenames
- Decoded URL in Opening URL popup window
## [1.3.17] - 2022-05-19
## Changed
- Fixed file export prompt when quitting an unsaved stage.
## [1.3.16] - 2022-05-05
## Changed
- Updated unittests.
## [1.3.15] - 2022-03-21
## Changed
- Disable checkpoint comments in save as dialog if server doesn't support checkpoints.
## [1.3.14] - 2022-03-21
## Changed
- Open payloads in file dialog.
## [1.3.13] - 2022-03-17
## Changed
- Fixed typo in the previous merge.
## [1.3.12] - 2022-03-17
## Changed
- Fixed UX flow for saving unsaved stage.
## [1.3.11] - 2022-03-08
## Changed
- Fixes Unsaved Layers dialog sometimes not enabling `Dont Save` flag.
## [1.3.10] - 2022-03-10
## Changed
- Pop up read only options dialog for read-only stage to keep consistent behavior as content browser.
## [1.3.9] - 2022-02-09
## Changed
- Refactor to use file_importer and file_exporter rather than FilePickerDialog.
## [1.3.8] - 2021-12-21
## Changed
- More fixes to `open_with_new_edit_layer` and tests added.
- Fix memory leak caused by prompt.
## [1.3.7] - 2021-12-17
## Changed
- Fixed `open_with_new_edit_layer` function
## [1.3.6] - 2021-11-10
## Changed
- Cleans up on shutdown, including releasing handle to FilePickerDialog.
## [1.3.5] - 2021-11-02
## Changed
- Add open stage callback register for the use of e.g. Activiy window
## [1.3.4] - 2021-10-20
## Changed
- Don't return windows slashes in paths
## [1.3.3] - 2021-08-04
## Changed
- Fixed leak in popup modal dialog
## [1.3.2] - 2021-07-29
## Changed
- Added LoadSet flags to open_file, open_stage
- Fixed Create Reference/Payload to use commands to they are undoable
- Create Reference/Payload now uses correct rotation when created
## [1.3.1] - 2021-06-25
## Changed
- "Would you like to save this stage?" is modal
## [1.3.0] - 2021-06-08
## Changed
- Added checkpoint description to `Save As` file picker
## [1.2.2] - 2021-05-05
## Changed
- Updated Save so can either have no UI or UI
## [1.2.1] - 2021-04-08
## Changed
= Removed versioning pane from `Save As` file picker
## [1.2.0] - 2021-03-22
## Changed
= Unified `Save` and `Save with Comment` user interface.
## [1.1.1] - 2021-03-02
- Added test
- Fixed leaks
## [1.1.0] - 2021-02-09
### Changes
- Changed checkpoint comment message:
- When using Save As to save a new file and overwriting an existing file: "Replaced with new file"
- When using Save As to save an existing file and overwriting an existing file: "Replaced with [the path of the file]"
## [1.0.2] - 2021-02-10
- Updated StyleUI handling
## [1.0.1] - 2020-08-28
### Changes
- added add_reference function
## [1.0.0] - 2020-08-28
### Changes
- converted to extension 2.0
| 4,357 | Markdown | 23.483146 | 120 | 0.683957 |
omniverse-code/kit/exts/omni.kit.window.file/docs/index.rst | omni.kit.window.file
###########################
Provides utility functions to new/open/save/close USD files
.. toctree::
:maxdepth: 1
CHANGELOG
.. automodule:: omni.kit.window.file
:platform: Windows-x86_64, Linux-x86_64, Linux-aarch64
:members:
:undoc-members:
:imported-members:
:exclude-members: partial
:noindex: pathlib
| 362 | reStructuredText | 17.149999 | 59 | 0.635359 |
omniverse-code/kit/exts/omni.hydra.engine.stats/omni/hydra/engine/stats/__init__.py | from ._stats import *
| 22 | Python | 10.499995 | 21 | 0.681818 |
omniverse-code/kit/exts/omni.hydra.engine.stats/omni/hydra/engine/stats/tests/test_bindings.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
__all__ = ['TestStatsBindings']
import omni.kit.test
from omni.kit.test import AsyncTestCase
import omni.hydra.engine.stats as engine_stats
class TestStatsBindings(AsyncTestCase):
'''Simple test against the interfaces of the bindings to fail if they change'''
def setUp(self):
super().setUp()
# After running each test
def tearDown(self):
super().tearDown()
def assertItemIsIndexable(self, item):
self.assertTrue(hasattr(item, '__getitem__'))
async def test_mem_stats(self):
mem_stats = engine_stats.get_mem_stats()
# Item should be indexable
self.assertItemIsIndexable(mem_stats)
# Items should have a caetgory field
self.assertIsNotNone(mem_stats[0].get('category'))
async def test_mem_stats_detailed(self):
mem_stats_detailed = engine_stats.get_mem_stats(detailed=True)
# Item should be indexable
self.assertItemIsIndexable(mem_stats_detailed)
# Items should have a caetgory field
self.assertIsNotNone(mem_stats_detailed[0].get('category'))
async def test_device_info(self):
all_devices = engine_stats.get_device_info()
# Item should be indexable
self.assertItemIsIndexable(all_devices)
# Test getting info on individual devices
for i in range(len(all_devices)):
cur_device = engine_stats.get_device_info(i)
self.assertEqual(cur_device['description'], all_devices[i]['description'])
self.assertTrue(cur_device, all_devices[i])
async def test_active_engine_stats(self):
hd_stats = engine_stats.HydraEngineStats()
a = hd_stats.get_nested_gpu_profiler_result()
self.assertItemIsIndexable(a)
b = hd_stats.get_gpu_profiler_result()
self.assertItemIsIndexable(b)
c = hd_stats.reset_gpu_profiler_containers()
self.assertTrue(c)
self.assertIsNotNone(hd_stats.save_gpu_profiler_result_to_json)
async def test_specific_engine_stats(self):
hd_stats = engine_stats.HydraEngineStats(usd_context_name='', hydra_engine_name='')
a = hd_stats.get_nested_gpu_profiler_result()
self.assertItemIsIndexable(a)
b = hd_stats.get_gpu_profiler_result()
self.assertItemIsIndexable(b)
c = hd_stats.reset_gpu_profiler_containers()
self.assertTrue(c)
self.assertIsNotNone(hd_stats.save_gpu_profiler_result_to_json)
| 2,895 | Python | 33.891566 | 91 | 0.683247 |
omniverse-code/kit/exts/omni.hydra.engine.stats/omni/hydra/engine/stats/tests/__init__.py | from .test_bindings import *
| 29 | Python | 13.999993 | 28 | 0.758621 |
omniverse-code/kit/exts/omni.kit.debug.vscode/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "0.1.0"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarily for displaying extension info in UI
title = "Kit Debug VSCode"
description = "VSCode python debugger support window."
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Internal"
feature = true
# Keywords for the extension
keywords = ["kit"]
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
[dependencies]
"omni.ui" = {}
"omni.kit.commands" = {}
"omni.usd.libs" = {}
"omni.kit.debug.python" = {}
[[python.module]]
name = "omni.kit.debug.vscode_debugger"
[[test]]
pyCoverageEnabled = false
waiver = "Ultrasmall UI on top of omni.kit.debug.vscode." # OM-48108
| 968 | TOML | 22.071428 | 84 | 0.716942 |
omniverse-code/kit/exts/omni.kit.debug.vscode/omni/kit/debug/vscode_debugger.py | import omni.ext
import omni.kit.commands
import omni.kit.ui
import omni.kit.debug.python
EXTENSION_NAME = "VS Code Link"
class DebugBreak(omni.kit.commands.Command):
def do(self):
omni.kit.debug.python.breakpoint()
def toColor01(color):
return tuple(c / 255.0 for c in color) + (1,)
class Extension(omni.ext.IExt):
"""
Extension to enable connection of VS Code python debugger. It enables it using python ptvsd module and shows status.
"""
def on_startup(self):
self._window = omni.kit.ui.Window(EXTENSION_NAME, 300, 150)
layout = self._window.layout
row_layout = layout.add_child(omni.kit.ui.RowLayout())
# Status label
row_layout.add_child(omni.kit.ui.Label("Status:"))
self._status_label = row_layout.add_child(omni.kit.ui.Label())
wait_info = omni.kit.debug.python.get_listen_address()
info_label = layout.add_child(omni.kit.ui.Label())
info_label.text = f"Address: {wait_info}" if wait_info else "Error"
# Break button
self._break_button = layout.add_child(omni.kit.ui.Button("Break"))
def on_click(*x):
omni.kit.commands.execute("DebugBreak")
self._break_button.set_clicked_fn(on_click)
# Monitor for attachment
self._attached = None
self._set_attached(False)
def on_update(dt):
self._set_attached(omni.kit.debug.python.is_attached())
self._window.set_update_fn(on_update)
def _set_attached(self, attached):
if self._attached != attached:
ATTACH_DISPLAY = {
True: ("VS Code Debugger Attached", (0, 255, 255)),
False: ("VS Code Debugger Unattached", (255, 0, 0)),
}
self._attached = attached
self._break_button.enabled = attached
self._status_label.text = ATTACH_DISPLAY[self._attached][0]
self._status_label.set_text_color(toColor01(ATTACH_DISPLAY[self._attached][1]))
| 2,011 | Python | 29.484848 | 120 | 0.6181 |
omniverse-code/kit/exts/omni.kit.property.tagging/omni/kit/property/tagging/scripts/tagging_attributes_widget.py | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.kit.window.property.templates import SimplePropertyWidget, LABEL_WIDTH, LABEL_HEIGHT
from omni.kit.tagging import OmniKitTaggingDelegate, get_tagging_instance
from pxr import UsdShade, UsdUI
import os.path
import carb
import carb.settings
import omni.ui as ui
import omni.kit.app
import omni.kit.commands
import omni.client
EXCLUDED_NAMESPACE = "excluded"
GENERATED_NAMESPACE = "generated"
DOT_EXCLUDED_NAMESPACE = ".excluded"
DOT_GENERATED_NAMESPACE = ".generated"
EMPTY_NAMESPACE_DISPLAY_VALUE = "<empty namespace>"
SPACING = 5
class TaggingAttributesWidget(SimplePropertyWidget, OmniKitTaggingDelegate):
def __init__(self, style):
super().__init__(title="Tagging", collapsed=False)
self._style = style
self._tagging = get_tagging_instance()
self._tagging.set_delegate(self)
self._advanced_view = False
self._refresh_tags = True
self._selected_asset = None
self._path_names = []
self._current_tags = {}
self._configured_namespaces = ["appearance"]
self._init_settings()
self._read_settings()
def on_new_payload(self, payload):
self._selected_asset = None
self._refresh_tags = True
# redraw if rebuild flag is true, or we have a new payload
if not super().on_new_payload(payload):
return False
# exclude material/shaders
for prim_path in self._payload:
prim = self._get_prim(prim_path)
if prim and (prim.IsA(UsdShade.Material) or
prim.IsA(UsdShade.Shader) or
prim.IsA(UsdShade.NodeGraph) or
prim.IsA(UsdUI.Backdrop)):
return False
return payload is not None and len(payload) > 0
def clean(self):
"""Inherited function from subclass
"""
self._tag_event_sub = None
self._selected_asset = None
self._sub_show_advanced_view = None
self._sub_hidden_tags = None
self._sub_mod_hidden_tags = None
self._stage_event = None
self._tagging.set_delegate(None)
self._tagging = None
def _get_prim(self, prim_path):
if prim_path:
stage = self._payload.get_stage()
if stage:
return stage.GetPrimAtPath(prim_path)
return None
def _init_settings(self):
settings = carb.settings.get_settings()
self._sub_show_advanced_view = omni.kit.app.SettingChangeSubscription(
"/persistent/exts/omni.kit.property.tagging/showAdvancedTagView", lambda *_: self._on_settings_change()
)
self._sub_hidden_tags = omni.kit.app.SettingChangeSubscription(
"/persistent/exts/omni.kit.property.tagging/showHiddenTags", lambda *_: self._on_settings_change()
)
self._sub_mod_hidden_tags = omni.kit.app.SettingChangeSubscription(
"/persistent/exts/omni.kit.property.tagging/modifyHiddenTags", lambda *_: self._on_settings_change()
)
def _read_settings(self):
settings = carb.settings.get_settings()
self._allow_advanced_view = settings.get("/persistent/exts/omni.kit.property.tagging/showAdvancedTagView")
self._show_hidden_tags = settings.get("/persistent/exts/omni.kit.property.tagging/showHiddenTags")
self._modify_hidden_tags = settings.get("/persistent/exts/omni.kit.property.tagging/modifyHiddenTags")
self._show_and_modify_hidden_tags = self._show_hidden_tags and self._modify_hidden_tags
def _on_settings_change(self):
self._read_settings()
self.request_rebuild()
def _get_tags_callback(self):
self.request_rebuild()
def updated_tags_for_url(self, url):
if url in self._path_names:
self._refresh_tags = True
self.request_rebuild()
def _get_prim_paths(self, payload):
"""Get the absolute paths of the full prim stack of the payload.
"""
stage = payload.get_stage()
if stage is None:
return [], []
prims = []
path_names = []
for path in payload:
prim = stage.GetPrimAtPath(path)
if prim:
for prim_spec in prim.GetPrimStack():
identifier = prim_spec.layer.identifier
broken_url = omni.client.break_url(identifier)
if broken_url.scheme == "omniverse" and identifier not in path_names:
path_names.append(identifier)
prims.append(prim)
return prims, path_names
def _prim_selection_view(self):
"""Build the combo box that can select the absolute path of the asset whose tags we will display
"""
with ui.HStack():
ui.Label("Reference(s):", name="label", word_wrap=True, width=LABEL_WIDTH, height=LABEL_HEIGHT)
with ui.VStack(spacing=SPACING):
def current_index_changed(model, _index):
index = model.get_item_value_model().get_value_as_int()
self._selected_asset = self._path_names[index]
self._refresh_tags = True
self.request_rebuild()
if self._selected_asset is None and len(self._path_names) > 0:
# default - choose last asset path
self._selected_asset = self._path_names[-1]
index = self._path_names.index(self._selected_asset)
# parse identifiers and create short readable names
shorter_path_names = []
for path in self._path_names:
broken_url = omni.client.break_url(path)
if broken_url.path not in shorter_path_names:
shorter_path_names.append(os.path.basename(broken_url.path))
if len(shorter_path_names) < len(self._path_names):
shorter_path_names = self._path_names
model = ui.ComboBox(index, *shorter_path_names).model
model.add_item_changed_fn(lambda m, i: current_index_changed(m, i))
return shorter_path_names[index], index
def _advanced_view_toggle(self):
if self._allow_advanced_view:
def toggle_advanced_view(model):
val = model.get_value_as_bool()
model.set_value(val)
self._advanced_view = val
self.request_rebuild()
with ui.HStack(width=0, spacing=SPACING):
ui.Label("Advanced view", name="label", word_wrap=True, width=LABEL_WIDTH, height=LABEL_HEIGHT)
with ui.VStack(width=10):
ui.Spacer()
bool_check = ui.CheckBox(width=10, height=0, name="greenCheck")
bool_check.model.set_value(self._advanced_view)
bool_check.model.add_value_changed_fn(toggle_advanced_view)
ui.Spacer()
else:
self._advanced_view = False
def build_items(self):
"""Main function that builds the tagging ui
"""
self._sub_to_prim = None
if len(self._payload) == 0:
return
with ui.VStack(spacing=SPACING, height=0):
prims, path_names = self._get_prim_paths(self._payload)
self._path_names = path_names
if len(prims) == 0 or not prims[0].GetPath():
ui.Label("Nothing taggable selected")
return
if len(self._path_names) == 0:
ui.Label("No asset paths found.", name="label", alignment=ui.Alignment.LEFT_TOP)
return
if len(self._path_names) == 0:
with ui.VStack(height=0, spacing=SPACING):
ui.Label(
"No tagging service found", name="label", word_wrap=True, width=LABEL_WIDTH, height=LABEL_HEIGHT
)
return
if self._refresh_tags:
# send a tag query to the tagging service asyncronously
self._tagging.get_tags(self._path_names, self._get_tags_callback)
self._refresh_tags = False
path_tags = {}
for path in self._path_names:
# get the tags already cached from the tagging service
results = self._tagging.tags_for_url(path)
if results is None:
results = []
path_tags[path] = self._tagging.unpack_raw_tags(results)
# prim selection combo box
selected_name, selected_index = self._prim_selection_view()
# checkbox that enables advanced view (if enabled in preferences)
self._advanced_view_toggle()
if self._selected_asset is None or self._selected_asset not in path_tags:
return
self._current_tags = path_tags[self._selected_asset]
if not self._current_tags:
self._current_tags = {}
for namespace in self._configured_namespaces:
if namespace not in self._current_tags:
self._current_tags[namespace] = {}
# sort by namespace
sorted_tags = [t for t in self._current_tags]
sorted_tags = sorted(sorted_tags)
if "" in sorted_tags:
sorted_tags = sorted_tags[1:] + [""]
with ui.CollapsableFrame(title=f"Tags for {selected_name}", name="groupFrame"):
with ui.VStack(spacing=SPACING, height=0):
for namespace in sorted_tags:
if self._advanced_view:
self._create_advanced_view(namespace)
else:
self._create_default_view(namespace)
def _advanced_tag_row(self, namespace, hidden_label, key, value, editable):
"""Show one tag in advanced view along with buttons.
A user tag will be an editable text field.
A generated tag will be either hidden, non-editable, or editable, depending on preferences.
"""
full_tag = self._tagging.pack_tag(namespace, hidden_label, key=key, value=value)
if not editable:
with ui.HStack(spacing=SPACING, width=ui.Percent(100)):
ui.Label(full_tag, name="hidden", style=self._style)
return
# remove a tag or revert (after an update) a change.
def revert_tag(field, remove_btn):
field.model.set_value(remove_btn.name)
remove_btn.set_tooltip("Remove")
# toggle revert and update buttons
def on_tag_changed(field, update_btn, remove_btn, value):
old_value = remove_btn.name
valid = self._tagging.validate_tag(value, self._show_and_modify_hidden_tags)
changed = value != old_value and valid
if not valid:
remove_btn.set_clicked_fn(lambda f=field, rb=remove_btn: revert_tag(f, rb))
remove_btn.set_tooltip("Revert")
remove_btn.enabled = True
update_btn.visible = False
elif changed:
remove_btn.set_clicked_fn(lambda f=field, rb=remove_btn: revert_tag(f, rb))
remove_btn.set_tooltip("Revert")
remove_btn.enabled = True
update_btn.visible = True
elif not changed:
remove_btn.set_tooltip("Remove")
remove_btn.set_clicked_fn(lambda f=field, rb=remove_btn: remove_tag(f, rb))
remove_btn.enabled = True
update_btn.visible = False
# update a tag via changing text field and clicking "update" button.
def update_value(field, update_button, remove_button):
full_tag = field.model.get_value_as_string()
if self._tagging.validate_tag(full_tag, self._show_and_modify_hidden_tags):
old_value = remove_button.name
omni.kit.commands.execute(
"UpdateTag", asset_path=self._selected_asset, old_tag=old_value, new_tag=full_tag
)
update_button.visible = False
# update names so we know when the value changes
remove_button.name = full_tag
# remove a tag or revert (after an update) a change.
def remove_tag(field, remove_btn):
full_tag = remove_btn.name
if self._tagging.validate_tag(full_tag, self._show_and_modify_hidden_tags):
omni.kit.commands.execute("RemoveTag", asset_path=self._selected_asset, tag=full_tag)
field.visible = False
remove_btn.visible = False
with ui.HStack(spacing=SPACING, width=ui.Percent(100)):
field = ui.StringField()
update_button = ui.Button(
tooltip="Update",
style=self._style["check"],
image_height=self._style["check"]["height"],
image_width=self._style["check"]["width"],
width=1,
)
remove_button = ui.Button(
tooltip="Remove",
style=self._style["remove"],
image_height=self._style["remove"]["height"],
image_width=self._style["remove"]["width"],
width=1,
name=full_tag,
)
ui.Spacer(width=2)
remove_button.set_clicked_fn(lambda f=field, rb=remove_button: remove_tag(f, rb))
update_button.set_clicked_fn(lambda f=field, ub=update_button, rb=remove_button: update_value(f, ub, rb))
update_button.visible = False
field.model.set_value(full_tag)
field.model.add_value_changed_fn(
lambda m, f=field, ub=update_button, rb=remove_button: on_tag_changed(
f, ub, rb, m.get_value_as_string()
)
)
def _advanced_new_tag_row(self, namespace):
"""This allows adding a new tag, but the text box must include the namespace (unlike in default view).
For example: appearance.user.car
"""
# add a new tag (must be valid)
def add_tag(model):
full_tag = model.get_value_as_string()
if self._tagging.validate_tag(full_tag, self._show_and_modify_hidden_tags):
omni.kit.commands.execute("AddTag", asset_path=self._selected_asset, tag=full_tag)
model.set_value("")
# toggle add button enabled
def on_new_tag_changed(btn, value):
valid = self._tagging.validate_tag(value, self._show_and_modify_hidden_tags)
if valid:
btn.enabled = True
else:
btn.enabled = False
with ui.HStack(spacing=SPACING, width=ui.Percent(100)):
model = ui.StringField(name="new_tag:" + namespace).model
b = ui.Button(
"Add",
tooltip="Add new tag",
style=self._style["plus"],
image_height=self._style["plus"]["height"],
image_width=self._style["plus"]["height"],
width=60,
clicked_fn=lambda m=model: add_tag(m),
)
b.enabled = False
model.add_value_changed_fn(lambda m, btn=b: on_new_tag_changed(btn, m.get_value_as_string()))
def _create_advanced_view(self, namespace):
"""Create the full advanced view for each namespace.
"""
namespace_name = namespace or EMPTY_NAMESPACE_DISPLAY_VALUE
with ui.CollapsableFrame(title=f"Advanced tag view: {namespace_name}", name="subFrame"):
with ui.VStack(spacing=SPACING, height=0):
# show non-hidden tags first
for key in self._current_tags[namespace]:
if not key[0] == ".":
value = self._current_tags[namespace][key]
self._advanced_tag_row(namespace, None, key, value, True)
# show hidden tags
if self._show_hidden_tags:
for hidden_label in self._current_tags[namespace]:
if hidden_label[0] == ".":
for key, value in self._current_tags[namespace][hidden_label].items():
self._advanced_tag_row(
namespace, hidden_label[1:], key, value, self._modify_hidden_tags
)
self._advanced_new_tag_row(namespace)
def _default_user_tag_row(self, namespace, key, generated_tags):
"""Show a user created tag and the button to remove it.
"""
with ui.HStack(spacing=SPACING):
ui.Label(key, name="label")
ui.Spacer()
if namespace == "":
full_tag = key
else:
full_tag = ".".join([namespace, key])
with ui.HStack(width=60):
ui.Spacer(width=2)
if key in generated_tags:
if namespace == "":
excluded_tag = "." + ".".join([EXCLUDED_NAMESPACE, key])
else:
excluded_tag = "." + ".".join([namespace, EXCLUDED_NAMESPACE, key])
b = ui.Button(
style=self._style["remove"],
width=1,
image_height=self._style["remove"]["height"],
image_width=self._style["remove"]["width"],
tooltip="Reject",
clicked_fn=lambda t=full_tag, ap=self._selected_asset: omni.kit.commands.execute(
"AddTag", asset_path=ap, tag=excluded_tag, excluded=t
),
)
else:
b = ui.Button(
style=self._style["remove"],
width=1,
image_height=self._style["remove"]["height"],
image_width=self._style["remove"]["width"],
tooltip="Remove",
clicked_fn=lambda t=full_tag, ap=self._selected_asset: omni.kit.commands.execute(
"RemoveTag", asset_path=ap, tag=t
),
)
ui.Spacer(width=2)
def _default_generated_tag_row(self, namespace, key):
"""Show a generated created tag and the buttons to confirm it or reject it.
"""
with ui.HStack(spacing=SPACING):
ui.Label(key, name="generated", style=self._style)
ui.Spacer()
if namespace == "":
user_tag = key
exclude_tag = "." + ".".join([EXCLUDED_NAMESPACE, key])
else:
user_tag = ".".join([namespace, key])
exclude_tag = "." + ".".join([namespace, EXCLUDED_NAMESPACE, key])
with ui.HStack(width=60):
ui.Spacer(width=2)
a = ui.Button(
width=1,
style=self._style["check"],
tooltip="Confirm",
image_height=self._style["check"]["height"],
image_width=self._style["check"]["width"],
clicked_fn=lambda t=user_tag, ap=self._selected_asset: omni.kit.commands.execute(
"AddTag", asset_path=ap, tag=t
),
)
ui.Spacer(width=15)
b = ui.Button(
width=1,
style=self._style["remove"],
tooltip="Reject",
image_height=self._style["remove"]["height"],
image_width=self._style["remove"]["width"],
clicked_fn=lambda t=exclude_tag, ap=self._selected_asset: omni.kit.commands.execute(
"AddTag", asset_path=ap, tag=t
),
)
ui.Spacer(width=2)
def _default_new_tag_row(self, namespace):
"""Show a text box and button to create a new user tag in the given namespace.
"""
def add_tag(namespace, model):
value = model.get_value_as_string()
if namespace == "":
full_tag = value
else:
full_tag = ".".join([namespace, value])
# if the tag we are adding is excluded, we want to remove the exclusion (this is undoable)
excluded = ""
if (
namespace in self._current_tags
and DOT_EXCLUDED_NAMESPACE in self._current_tags[namespace]
and value in self._current_tags[namespace][DOT_EXCLUDED_NAMESPACE]
):
if namespace == "":
excluded = "." + ".".join([EXCLUDED_NAMESPACE, value])
else:
excluded = "." + ".".join([namespace, EXCLUDED_NAMESPACE, value])
if self._tagging.validate_tag(full_tag, self._show_and_modify_hidden_tags):
omni.kit.commands.execute(
"AddTag", asset_path=self._selected_asset, tag=full_tag, excluded=excluded
)
model.set_value("")
def on_new_tag_changed(btn, value):
if not namespace == "":
value = ".".join([namespace, value])
valid = self._tagging.validate_tag(value, self._show_and_modify_hidden_tags)
if valid:
btn.enabled = True
else:
btn.enabled = False
with ui.HStack(spacing=SPACING, width=ui.Percent(100)):
field = ui.StringField(name="new_tag:" + namespace)
model = field.model
with ui.HStack(spacing=SPACING, width=60):
b = ui.Button(
"Add",
style=self._style["plus"],
image_height=self._style["plus"]["height"],
image_width=self._style["plus"]["height"],
tooltip="Add new tag",
width=60,
clicked_fn=lambda m=model, n=namespace: add_tag(n, m),
)
b.enabled = False
model.add_value_changed_fn(lambda m, btn=b: on_new_tag_changed(btn, m.get_value_as_string()))
def _create_default_view(self, namespace):
""" This is the default tag view, which shows tags both added by the user and generated hidden tags.
When generated tags are "removed" we actually do not delete them, but add another tag with
the namespace ".excluded" instead of ".generated"
"""
def safe_int(value):
try:
return int(value)
except ValueError:
return 0
# populate special namespaces
user_tags = {}
excluded_tags = []
generated_tags = {}
if namespace in self._current_tags:
user_tags = {n: self._current_tags[namespace][n] for n in self._current_tags[namespace] if n[0] != "."}
if DOT_EXCLUDED_NAMESPACE in self._current_tags[namespace]:
excluded_tags = self._current_tags[namespace][DOT_EXCLUDED_NAMESPACE]
if DOT_GENERATED_NAMESPACE in self._current_tags[namespace]:
generated_tags = {
key: safe_int(value)
for key, value in self._current_tags[namespace][DOT_GENERATED_NAMESPACE].items()
if key not in excluded_tags
}
sorted_by_confidence = [key for key in generated_tags]
sorted_by_confidence.sort(key=lambda x: -generated_tags[x])
# skip empty blocks unless they are "appearance"
if len(user_tags) == 0 and len(sorted_by_confidence) == 0 and namespace not in self._configured_namespaces:
return
namespace_name = namespace or EMPTY_NAMESPACE_DISPLAY_VALUE
with ui.CollapsableFrame(title=f"Tags for {namespace_name}", name="subFrame"):
with ui.VStack(spacing=SPACING):
# first list user added tags (non-hidden tags)
for key, _ in user_tags.items():
self._default_user_tag_row(namespace, key, generated_tags)
# generated tags
if sorted_by_confidence and len(sorted_by_confidence) > 0:
for key in sorted_by_confidence:
if key in user_tags or key in excluded_tags:
continue
self._default_generated_tag_row(namespace, key)
self._default_new_tag_row(namespace)
| 25,219 | Python | 41.673435 | 120 | 0.543558 |
omniverse-code/kit/exts/omni.kit.property.tagging/omni/kit/property/tagging/scripts/style.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
from pathlib import Path
UI_STYLES = {}
UI_STYLES["NvidiaLight"] = {
"Label::generated": {"color": 0xFF777777, "font_size": 14},
"Label::hidden": {"color": 0xFF777777, "font_size": 14},
"check": {
"width": 15,
"height": 15,
"Button.Image": {"color": 0xFF75A270},
"Button": {"background_color": 0xFFD6D6D6},
},
"remove": {
"width": 15,
"height": 15,
"Button.Image": {"color": 0xFF3333AA},
"Button": {"background_color": 0xFFD6D6D6},
},
"plus": {
"Button.Label": {"color": 0xFF333333},
"Button.Label:disabled": {"color": 0xFF666666},
"width": 15,
"height": 15,
"Button.Image": {"color": 0xFF75A270},
"Button.Image:disabled": {"color": 0xFF666666},
"stack_direction": ui.Direction.LEFT_TO_RIGHT,
},
}
UI_STYLES["NvidiaDark"] = {
"Label::generated": {"color": 0xFF777777, "font_size": 14},
"Label::hidden": {"color": 0xFF777777, "font_size": 14},
"check": {"width": 15, "height": 15, "Button.Image": {"color": 0xFF75A270}, "Button": {"background_color": 0x0}},
"remove": {"width": 15, "height": 15, "Button.Image": {"color": 0xFF3333AA}, "Button": {"background_color": 0x0}},
"plus": {
"Button.Label": {"color": 0xFFCCCCCC},
"Button.Label:disabled": {"color": 0xFF666666},
"width": 15,
"height": 15,
"Button.Image": {"color": 0xFF75A270},
"Button.Image:disabled": {"color": 0xFF666666},
"stack_direction": ui.Direction.LEFT_TO_RIGHT,
},
}
| 2,024 | Python | 35.818181 | 118 | 0.606719 |
omniverse-code/kit/exts/omni.kit.property.tagging/omni/kit/property/tagging/scripts/tagging_commands.py | import omni.kit.commands
import omni.kit.tagging
import omni.client
class AddTagCommand(omni.kit.commands.Command):
"""
Add a tag to an asset **Command**.
Fails if we are not connected to the tagging server.
Args:
asset_path (str): Path to the asset. Should start with omniverse: or it will just return
tag (str): packed string tag, such as appearance.Car, or .appearance.generated.Truck=99
excluded (str): excluded version of the tag (or empty string) to remove if present
"""
def __init__(self, asset_path: str, tag: str, excluded: str = ""):
self._asset_path = asset_path
self._tag = tag
self._excluded = excluded
def do(self):
broken_url = omni.client.break_url(self._asset_path)
if broken_url.scheme != "omniverse":
return
tagging = omni.kit.tagging.get_tagging_instance()
tagging.tags_action(self._asset_path, self._tag, action="add")
if self._excluded:
tagging.tags_action(self._asset_path, self._excluded, action="remove")
def undo(self):
broken_url = omni.client.break_url(self._asset_path)
if broken_url.scheme != "omniverse":
return
tagging = omni.kit.tagging.get_tagging_instance()
tagging.tags_action(self._asset_path, self._tag, action="remove")
if self._excluded:
tagging.tags_action(self._asset_path, self._excluded, action="add")
class RemoveTagCommand(omni.kit.commands.Command):
"""
Remove a tag to an asset **Command**.
Fails if we are not connected to the tagging server.
Args:
asset_path (str): Path to the asset. Should start with omniverse: or it will just return
tag (str): packed string tag, such as appearance.Car, or .appearance.generated.Truck=99
"""
def __init__(self, asset_path: str, tag: str):
self._asset_path = asset_path
self._tag = tag
def do(self):
broken_url = omni.client.break_url(self._asset_path)
if broken_url.scheme != "omniverse":
return
tagging = omni.kit.tagging.get_tagging_instance()
tagging.tags_action(self._asset_path, self._tag, action="remove")
def undo(self):
broken_url = omni.client.break_url(self._asset_path)
if broken_url.scheme != "omniverse":
return
tagging = omni.kit.tagging.get_tagging_instance()
tagging.tags_action(self._asset_path, self._tag, action="add")
class UpdateTagCommand(omni.kit.commands.Command):
"""
Remove a tag to an asset **Command**.
Fails if we are not connected to the tagging server.
Args:
asset_path (str): Path to the asset. Should start with omniverse: or it will just return
old_tag (str): packed string tag, such as appearance.Car, or .appearance.generated.Truck=99
new_tag (str): packed string tag, such as appearance.Car, or .appearance.generated.Truck=99
"""
def __init__(self, asset_path: str, old_tag: str, new_tag):
self._asset_path = asset_path
self._old_tag = old_tag
self._new_tag = new_tag
def do(self):
broken_url = omni.client.break_url(self._asset_path)
if broken_url.scheme != "omniverse":
return
tagging = omni.kit.tagging.get_tagging_instance()
tagging.tags_action(self._asset_path, old_tag=self._old_tag, action="update", new_tag=self._new_tag)
def undo(self):
broken_url = omni.client.break_url(self._asset_path)
if broken_url.scheme != "omniverse":
return
tagging = omni.kit.tagging.get_tagging_instance()
tagging.tags_action(self._asset_path, old_tag=self._new_tag, action="update", new_tag=self._old_tag)
omni.kit.commands.register_all_commands_in_module(__name__)
| 3,827 | Python | 36.529411 | 108 | 0.634962 |
omniverse-code/kit/exts/omni.kit.property.tagging/omni/kit/property/tagging/scripts/__init__.py | from .tagging_properties import *
from .tagging_commands import *
| 66 | Python | 21.333326 | 33 | 0.787879 |
omniverse-code/kit/exts/omni.kit.property.tagging/omni/kit/property/tagging/scripts/tagging_properties.py | import os
import carb
import omni.ext
from pxr import Sdf, UsdShade
from pathlib import Path
from .style import UI_STYLES
class TaggingPropertyExtension(omni.ext.IExt):
def __init__(self):
self._registered = False
self._icon_path = ""
super().__init__()
def on_startup(self, ext_id):
manager = omni.kit.app.get_app().get_extension_manager()
extension_path = manager.get_extension_path(ext_id)
self._icon_path = Path(extension_path).joinpath("data").joinpath("icons")
self._hooks = manager.subscribe_to_extension_enable(
on_enable_fn=lambda _: self._register_widget(),
on_disable_fn=lambda _: self._unregister_widget(),
ext_name="omni.kit.window.property",
hook_name="omni.kit.window.property listener",
)
def destroy(self):
if self._registered:
self._unregister_widget()
def on_shutdown(self):
self._hooks = None
if self._registered:
self._unregister_widget()
def _register_widget(self):
theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
style = UI_STYLES[theme]
# update icon paths
style["check"]["image_url"] = str(self._icon_path.joinpath("check.svg"))
style["remove"]["image_url"] = str(self._icon_path.joinpath("remove.svg"))
style["plus"]["image_url"] = str(self._icon_path.joinpath("plus.svg"))
try:
import omni.kit.window.property as p
from .tagging_attributes_widget import TaggingAttributesWidget
w = p.get_window()
if w:
w.register_widget("prim", "tagging", TaggingAttributesWidget(style))
self._registered = True
except Exception as exc:
carb.log_error(f"Error registering tagging widget {exc}")
def _unregister_widget(self):
try:
import omni.kit.window.property as p
w = p.get_window()
if w:
w.unregister_widget("prim", "tagging")
self._registered = False
except Exception as e:
carb.log_warn(f"Unable to unregister 'tagging:/attributes': {e}")
| 2,256 | Python | 33.723076 | 108 | 0.595301 |
omniverse-code/kit/exts/omni.kit.property.tagging/omni/kit/property/tagging/tests/test_tagging.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 pathlib
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.kit import ui_test
from omni.ui.tests.test_base import OmniUiTest
from pxr import Kind, Sdf, Gf
class TestTaggingWidget(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
ext_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
self._golden_img_dir = pathlib.Path(ext_path).joinpath("data/tests/golden_img")
from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget
import omni.kit.window.property as p
self._w = p.get_window()
# After running each test
async def tearDown(self):
await super().tearDown()
# Test(s)
async def test_tagging_ui(self):
usd_context = omni.usd.get_context()
await self.docked_test_window(
window=self._w._window,
width=450,
height=250,
restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position = ui.DockPosition.BOTTOM)
# new stage
await omni.usd.get_context().new_stage_async()
stage = omni.usd.get_context().get_stage()
## create prim
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
# verify one prim
prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll() if prim.GetPath().pathString not in ['/Render', '/Render/Vars']]
self.assertTrue(prim_list == ['/Sphere'])
# Select the prim.
usd_context.get_selection().set_selected_prim_paths(["/Sphere"], True)
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(10)
# verify image
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_tagging_ui.png")
| 2,414 | Python | 35.590909 | 143 | 0.676056 |
omniverse-code/kit/exts/omni.kit.property.tagging/omni/kit/property/tagging/tests/__init__.py | from .test_tagging import *
| 28 | Python | 13.499993 | 27 | 0.75 |
omniverse-code/kit/exts/omni.kit.property.tagging/docs/index.rst | omni.kit.property.tagging
###########################
Property Tagging Values
.. toctree::
:maxdepth: 1
CHANGELOG
| 125 | reStructuredText | 9.499999 | 27 | 0.544 |
omniverse-code/kit/exts/omni.example.ui/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.2.3"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarly for displaying extension info in UI
title = "Omni UI Documentation"
description="Examples for using omni.ui library"
category = "Example"
# URL of the extension source repository.
repository = ""
# Keywords for the extension
keywords = ["kit", "example", "ui"]
changelog="docs/CHANGELOG.md"
[ui]
name = "Omni UI Documentation"
[dependencies]
"omni.kit.commands" = {}
"omni.kit.documentation.builder" = {}
"omni.ui" = {}
"omni.usd" = {}
[[python.module]]
name = "omni.example.ui"
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--/app/menu/legacy_mode=false", # needed for golden images to match
"--no-window",
]
dependencies = [
"omni.kit.mainwindow",
"omni.kit.renderer.capture",
]
| 995 | TOML | 20.652173 | 83 | 0.687437 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/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.
#
"""The documentation of the omni.ui aka UI Framework"""
from .scripts.ui_doc import UIDoc
from functools import partial
import asyncio
import carb
import carb.settings
import omni.ext
import omni.kit.app
import omni.ui as ui
EXTENSION_NAME = "Omni.UI Documentation"
class ExampleExtension(omni.ext.IExt):
"""The Demo extension"""
WINDOW_NAME = "Omni::UI Doc"
_ui_doc = None
def __init__(self):
super().__init__()
@staticmethod
def ui_doc():
return ExampleExtension._ui_doc
def get_name(self):
"""Return the name of the extension"""
return EXTENSION_NAME
def on_startup(self, ext_id):
"""Caled to load the extension"""
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id)
ExampleExtension._ui_doc = UIDoc(extension_path)
ui.Workspace.set_show_window_fn(
ExampleExtension.WINDOW_NAME,
lambda show: show and ExampleExtension._ui_doc.build_window(ExampleExtension.WINDOW_NAME),
)
ui.Workspace.show_window(ExampleExtension.WINDOW_NAME)
# Dock this extension into mainwindow if running as standalone
settings = carb.settings.get_settings()
standalone_mode = settings.get_as_bool("app/settings/standalone_mode")
if standalone_mode:
asyncio.ensure_future(self._dock_window(ExampleExtension.WINDOW_NAME, omni.ui.DockPosition.SAME))
def on_shutdown(self):
"""Called when the extesion us unloaded"""
ExampleExtension._ui_doc.shutdown()
ExampleExtension._ui_doc = None
ui.Workspace.set_show_window_fn(ExampleExtension.WINDOW_NAME, None)
async def _dock_window(self, window_title: str, position: omni.ui.DockPosition, ratio: float = 1.0):
frames = 3
while frames > 0:
if omni.ui.Workspace.get_window(window_title):
break
frames = frames - 1
await omni.kit.app.get_app().next_update_async()
window = omni.ui.Workspace.get_window(window_title)
dockspace = omni.ui.Workspace.get_window("DockSpace")
if window and dockspace:
window.dock_in(dockspace, position, ratio=ratio)
window.dock_tab_bar_visible = False
| 2,717 | Python | 33.405063 | 109 | 0.676849 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/__init__.py | # NOTE: all imported classes must have different class names
from .extension import *
| 86 | Python | 27.999991 | 60 | 0.790698 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/ui_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation of the omni.ui aka UI Framework"""
from .abstract_model_doc import AbstractModelDoc
from .attribute_editor_demo import AttributeEditorWindow
from .canvas_frame_doc import CanvasFrameDoc
from .checkbox_doc import CheckBoxDoc
from .colorwidget_doc import ColorWidgetDoc
from .combobox_doc import ComboBoxDoc
from .custom_window_example import BrickSunStudyWindow
from .dnd_doc import DNDDoc
from .doc_page import DocPage
from .field_doc import FieldDoc
from .image_doc import ImageDoc
from .layout_doc import LayoutDoc
from .length_doc import LengthDoc
from .md_doc import MdDoc
from .menu_bar_doc import MenuBarDoc
from .menu_doc import MenuDoc
from .multifield_doc import MultiFieldDoc
from .plot_doc import PlotDoc
from .progressbar_doc import ProgressBarDoc
from .scrolling_frame_doc import ScrollingFrameDoc
from .shape_doc import ShapeDoc
from .slider_doc import SliderDoc
from .styling_doc import StylingDoc
from .treeview_doc import TreeViewDoc
from .widget_doc import WidgetDoc
from .window_doc import WindowDoc
from .workspace_doc import WorkspaceDoc
from omni.kit.documentation.builder import DocumentationBuilderWindow
from omni.kit.documentation.builder import DocumentationBuilderMd
from omni.ui import color as cl
from omni.ui import constant as fl
from pathlib import Path
import omni.kit.app as app
import omni.ui as ui
EXTENSION_NAME = "OMNI.UI Demo"
SPACING = 5
CURRENT_PATH = Path(__file__).parent
DOCS_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("docs")
MVD_PAGES = ["overview.md", "model.md", "delegate.md"]
class UIDoc(DocPage):
"""UI Doc Class"""
def __init__(self, extension_path):
super().__init__(extension_path)
self.omniverse_version, _, _ = app.get_app_interface().get_build_version().partition("-")
self.vertical_scrollbar_on = True
self._extension_path = extension_path
self._style_system = {
"Button": {
"background_color": 0xFFE1E1E1,
"border_color": 0xFFADADAD,
"border_width": 0.5,
"border_radius": 0.0,
"margin": 5.0,
"padding": 5.0,
},
"Button.Label": {"color": 0xFF000000},
"Button:hovered": {"background_color": 0xFFFBF1E5, "border_color": 0xFFD77800},
"Button:pressed": {"background_color": 0xFFF7E4CC, "border_color": 0xFF995400, "border_width": 1.0},
}
self._example_windows = {}
self._window_list = [["Attribute Editor", AttributeEditorWindow()], ["Custom Window", BrickSunStudyWindow()]]
self._mvd_pages = [DocumentationBuilderMd(DOCS_PATH.joinpath(filename)) for filename in MVD_PAGES]
self.index_list = [
["LAYOUT"],
[
"Arrangement of elements",
LayoutDoc(extension_path),
[
"HStack",
"VStack",
"ZStack",
"Spacing",
"Frame",
"VGrid",
"HGrid",
"CollapsableFrame",
"Placer",
"Visibility",
"Direction",
],
],
["Lengths", LengthDoc(extension_path), ["Pixel", "Percent", "Fraction"]],
["WIDGETS"],
["Styling", StylingDoc(extension_path), ["The Style Sheet Syntax", "Shades", "URL Shades", "Font Size"]],
[
"Base Widgets",
WidgetDoc(extension_path),
["Button", "RadioButton", "Label", "Tooltip", "Debug Color", "Font"],
],
["Menu", MenuDoc(extension_path), []],
["ScrollingFrame", ScrollingFrameDoc(extension_path), []],
["CanvasFrame", CanvasFrameDoc(extension_path), []],
["Image", ImageDoc(extension_path), []],
["CheckBox", CheckBoxDoc(extension_path), []],
["AbstractValueModel", AbstractModelDoc(extension_path), []],
["ComboBox", ComboBoxDoc(extension_path), []],
["ColorWidget", ColorWidgetDoc(extension_path), []],
["MultiField", MultiFieldDoc(extension_path), []],
["TreeView", TreeViewDoc(extension_path), []],
[
"Shapes",
ShapeDoc(extension_path),
["Rectangle", "Circle", "Triangle", "Line", "FreeRectangle", "FreeBezierCurve"],
],
["Fields", FieldDoc(extension_path), ["StringField"]],
["Sliders", SliderDoc(extension_path), ["FloatSlider", "IntSlider", "FloatDrag", "IntDrag"]],
["ProgressBar", ProgressBarDoc(extension_path), []],
["Plot", PlotDoc(extension_path), []],
["Drag and Drop", DNDDoc(extension_path), ["Minimal Example", "Styling and Tooltips"]],
]
# Add .md files here
self.index_list.append(["MODEL-DELEGATE-VIEW"])
for page in self._mvd_pages:
catalog = page.catalog
topic = catalog[0]["name"]
sub_topics = [c["name"] for c in catalog[0]["children"]]
self.index_list.append([topic, MdDoc(extension_path, page), sub_topics])
self.index_list += [
["WINDOWING SYSTEM"],
[
"Windows",
WindowDoc(extension_path),
["Window", "ToolBar", "Multiple Modal Windows", "Overlay Other Windows", "Workspace", "Popup"],
],
["MenuBar", MenuBarDoc(extension_path), ["MenuBar"]],
["Workspace", WorkspaceDoc(extension_path), ["Controlling Windows", "Capture Layout"]],
]
try:
# TODO(vyudin): can we remove?
import omni.kit.widget.webview
webview_enabled = True
except:
webview_enabled = False
if webview_enabled:
from .web_doc import WebViewWidgetDoc
web_view_widget_doc = WebViewWidgetDoc()
self.index_list += [
["WEB WIDGETS"],
["WebViewWidget", web_view_widget_doc, web_view_widget_doc.get_sections()],
]
def get_style(self):
cl.ui_docs_nvidia = cl("#76b900")
# Content
cl.ui_docs_bg = cl.white
cl.ui_docs_text = cl("#1a1a1a")
cl.ui_docs_h1_bg = cl.black
cl.ui_docs_code_bg = cl("#eeeeee")
cl.ui_docs_code_line = cl("#bbbbbb")
fl.ui_docs_code_radius = 2
fl.ui_docs_text_size = 18
# Catalog
cl.ui_docs_catalog_bg = cl.black
cl.ui_docs_catalog_hovered = cl("#1b1f20")
style = DocumentationBuilderWindow.get_style()
style.update({
"Button::placed:hovered": {"background_color": 0xFF1111FF, "border_color": 0xFFFF0000, "border_width": 2},
"CanvasFrame": {"background_color": 0xFFDDDDDD},
"Circle::blue": {"background_color": 0xFFFF1111, "border_color": 0xFF0000CC, "border_width": 2},
"Circle::default": {"background_color": 0xFF000000, "border_color": 0xFFFFFFFF, "border_width": 1},
"Circle::placed:pressed": {"background_color": 0xFF1111FF, "border_color": 0xFFFF0000, "border_width": 2},
"Circle::red": {"background_color": 0xFF1111FF, "border_color": 0xFFFF0000, "border_width": 2},
"Image::index_h2": {"color": 0xFF484849, "image_url": f"{self._extension_path}/icons/plus.svg"},
"Image::index_h2:selected": {"color": 0xFF5D5D5D, "image_url": f"{self._extension_path}/icons/minus.svg"},
"Image::omniverse_image": {"image_url": "resources/icons/ov_logo_square.png", "margin": 5},
"Label::caption": {"color": 0xFFFFFFFF, "font_size": 22.0, "margin_width": 10, "margin_height": 4},
"Label::code": {"color": cl.ui_docs_text},
"Label::index_h1": {
"color": cl.ui_docs_nvidia,
"font_size": 16.0,
"margin_height": 5,
"margin_width": 20,
},
"Label::index_h2": {"color": 0xFFD9D9D9, "font_size": 16.0, "margin_height": 5, "margin_width": 5},
"Label::index_h2:selected": {"color": 0xFF404040},
"Label::index_h3": {"color": 0xFF404040, "font_size": 16.0, "margin_height": 5, "margin_width": 30},
"Label::omniverse_version": {"font_size": 16.0, "color": 0xFF4D4D4D, "margin": 10},
"Label::section": {
"color": cl.ui_docs_nvidia,
"font_size": 22.0,
"margin_width": 10,
"margin_height": 4,
},
"Label::text": {"color": cl.ui_docs_text, "font_size": fl.ui_docs_text_size},
"Line::default": {"color": 0xFF000000, "border_width": 1},
"Line::demo": {"color": 0xFF555500, "border_width": 3},
"Line::separator": {"color": 0xFF111111, "border_width": 2},
"Line::underline": {"color": 0xFF444444, "border_width": 2},
"Rectangle::caption": {"background_color": cl.ui_docs_nvidia},
"Rectangle::code": {
"background_color": cl.ui_docs_code_bg,
"border_color": cl.ui_docs_code_line,
"border_width": 1.0,
"border_radius": fl.ui_docs_code_radius,
},
"Rectangle::placed:hovered": {
"background_color": 0xFFFF6E00,
"border_color": 0xFF111111,
"border_width": 2,
},
"Rectangle::section": {"background_color": cl.ui_docs_h1_bg},
"Rectangle::selection_h2": {"background_color": cl.ui_docs_catalog_bg},
"Rectangle::selection_h2:hovered": {"background_color": 0xFF4A4A4E},
"Rectangle::selection_h2:pressed": {"background_color": 0xFFB98029},
"Rectangle::selection_h2:selected": {"background_color": 0xFFFCFCFC},
"Rectangle::selection_h3": {"background_color": 0xFFE3E3E3},
"Rectangle::selection_h3:hovered": {"background_color": 0xFFD6D6D6},
"Rectangle::table": {"background_color": 0x0, "border_color": 0xFFCCCCCC, "border_width": 0.25},
"ScrollingFrame::canvas": {"background_color": cl.ui_docs_bg},
"Triangle::default": {"background_color": 0xFF00FF00, "border_color": 0xFFFFFFFF, "border_width": 1},
"Triangle::orientation": {"background_color": 0xFF444444, "border_color": 0xFFFFFFFF, "border_width": 3},
"VStack::layout": {"margin": 50},
"VStack::layout_md": {"margin": 1},
})
return style
def build_window(self, title):
"""Caled to load the extension"""
self._window = ui.Window(title, width=1000, height=600, dockPreference=ui.DockPreference.LEFT_BOTTOM)
# Populate UI once the window is visible
self._window.frame.set_build_fn(self.build_window_content)
# Dock it to the same space where Layers is docked
if ui.Workspace.get_window("Content"):
self._window.deferred_dock_in("Content")
def rebuild(self):
"""Rebuild all the content"""
self._window.frame.rebuild()
def build_window_content(self):
global_style = self.get_style()
with ui.HStack():
# Side panel with the table of contents
with ui.ScrollingFrame(
width=250,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
):
with ui.ZStack(height=0):
ui.Rectangle(style={"background_color": 0xFF313134})
with ui.VStack(style=global_style, height=0):
# Omniverse logo and version
with ui.ZStack():
ui.Rectangle(style={"background_color": 0xFF000000})
with ui.VStack(style=global_style, height=0):
ui.Image(height=250, alignment=ui.Alignment.CENTER, name="omniverse_image")
# Cut the end of the version. It's enough to print:
# "Omniverse Version: 103.0+master..."
text = f"Omniverse Version: {self.omniverse_version}"
if len(text) > 32:
text = text[:32] + "..."
ui.Label(
text,
alignment=ui.Alignment.CENTER,
name="omniverse_version",
tooltip=self.omniverse_version,
# elided_text=True,
content_clipping=True,
)
# The table of contents
with ui.VStack():
for entry in self.index_list:
if len(entry) == 1:
# If entry has nothing, it's a h1 title
ui.Label(entry[0], name="index_h1")
else:
# Otherwise it's h2 title and it has h3 subtitles
title = entry[0]
sub_titles = entry[2]
if len(entry) < 4:
entry.append(None)
entry.append(None)
# Draw h2 title
stack = ui.ZStack()
entry[3] = stack
with stack:
ui.Rectangle(
name="selection_h2",
mouse_pressed_fn=lambda x, y, b, a, e=entry: self.show_a_doc(e),
)
with ui.HStack():
ui.Spacer(width=10)
with ui.VStack(width=0):
ui.Spacer()
ui.Image(name="index_h2", width=10, height=10)
ui.Spacer()
ui.Label(title, name="index_h2")
# Draw h3 titles, they appear only if h2 is selected
stack = ui.VStack(visible=False)
entry[4] = stack
with stack:
for sub in sub_titles:
with ui.ZStack():
ui.Rectangle(
name="selection_h3",
mouse_pressed_fn=lambda x, y, b, a, e=entry, n=sub: self.show_a_doc(
e, n
),
)
ui.Label(sub, name="index_h3")
ui.Label("WINDOW EXAMPLES", name="index_h1")
with ui.VStack():
for entry in self._window_list:
with ui.ZStack():
ui.Rectangle(
name="selection_h2",
mouse_pressed_fn=lambda x, y, b, a, n=entry[0], w=entry[1]: self._show_a_window(
n, w
),
)
with ui.HStack():
ui.Spacer(width=20)
ui.Label(entry[0], name="index_h2")
ui.Spacer(height=10)
# The document
if self.vertical_scrollbar_on:
vertical_scrollbar_policy = ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON
else:
vertical_scrollbar_policy = ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF
self._doc_scrolling_frame = ui.ScrollingFrame(
style=global_style,
name="canvas",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=vertical_scrollbar_policy,
)
self._add_all_docs()
def clean_entries(self):
"""Should be called when the extesion is reloaded to destroy the items, that can't be auto destroyed."""
for entry in self.index_list:
if len(entry) > 1 and entry[1]:
entry[1].clean()
def shutdown(self):
"""Should be called when the extesion us unloaded"""
# Unfortunatley, the member variables are not destroyed when the extension is unloaded. We need to do it
# automatically. Usually, it's OK because the Python garbage collector will eventually destroy everythigng. But
# we need the images to be destroyed right now because Kit know nothing about Python garbage collector and it
# will fire warning that texture is not destroyed.
for page in self._mvd_pages:
page.destroy()
self._mvd_pages = []
self.clean_entries()
self._window = None
def show_a_doc(self, entry, navigate_to=None):
""" show a single doc """
# Unselect/uncheck everything on the side panel
for index_entry in self.index_list:
if len(index_entry) == 5:
_, _, _, item, sub_items = index_entry
item.selected = False
sub_items.visible = False
self.clean_entries()
# Select and show the given title
_, doc, _, item, sub_items = entry
item.selected = True
sub_items.visible = True
if isinstance(doc, MdDoc):
style = "layout_md"
else:
style = "layout"
with self._doc_scrolling_frame: # The page itself
with ui.VStack(height=0, spacing=20, name=style):
doc.create_doc(navigate_to)
if not navigate_to:
# Scroll up if there is nothing to jump to because scrolling frame remembers the scrolling position of
# the previous page
self._doc_scrolling_frame.scroll_y = 0
def _show_a_window(self, name, window_class):
""" window an example window """
if name not in self._example_windows:
self._example_windows[name] = window_class.build_window()
self._example_windows[name].visible = True
def _add_all_docs(self):
"""The body of the document"""
self.clean_entries()
with self._doc_scrolling_frame: # The page itself
with ui.VStack(height=0, spacing=20, name="layout"):
self._section_title("What is Omni::UI?")
self._text(
"Omni::UI is Omniverse's UI toolkit for creating beautiful and flexible graphical user interfaces "
"in the Kit extensions. Omni::UI provides the basic types necessary to create rich extensions with "
"a fluid and dynamic user interface in Omniverse Kit. It gives a layout system and includes "
"widgets for creating visual components, receiving user input, and creating data models. It allows "
"user interface components to be built around their behavior and enables a declarative flavor of "
"describing the layout of the application. Omni::UI gives a very flexible styling system that "
"allows for deep customizing of the final look of the application."
)
for entry in self.index_list:
if len(entry) > 1 and entry[1] is not None:
entry[1].create_doc()
| 20,840 | Python | 46.151584 | 120 | 0.518042 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/workspace_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation for Workspaces"""
from omni import ui
from .doc_page import DocPage
import json
SPACING = 5
class WorkspaceDoc(DocPage):
"""document Workspace class"""
def _undock(self, selection):
if not selection:
return
for item in selection:
item.window.undock()
def _dock(self, left, right, position):
if not left or not right:
return
target = right[0].window
for item in left:
item.window.dock_in(target, position)
def _left(self, selection):
if not selection:
return
for item in selection:
item.window.position_x -= 100
def _right(self, selection):
if not selection:
return
for item in selection:
item.window.position_x += 100
def _set_visibility(self, selection, visible):
if not selection:
return
for item in selection:
if visible is not None:
item.window.visible = visible
else:
item.window.visible = not item.window.visible
def _dock_reorder(self, selection):
if not selection:
return
docking_groups = [ui.Workspace.get_docked_neighbours(item.window) for item in selection]
for group in docking_groups:
# Reverse order
for i, window in enumerate(reversed(group)):
window.dock_order = i
def _tabs(self, selection, visible):
if not selection:
return
for item in selection:
item.window.dock_tab_bar_visible = visible
def _focus(self, selection):
if not selection:
return
for item in selection:
item.window.focus()
break
def create_doc(self, navigate_to=None):
self._section_title("Workspace")
self._caption("Controlling Windows", navigate_to)
class WindowItem(ui.AbstractItem):
def __init__(self, window):
super().__init__()
# Don't keep the window because it prevents the window from closing.
self._window_title = window.title
self.title_model = ui.SimpleStringModel(self._window_title)
self.type_model = ui.SimpleStringModel(type(window).__name__)
@property
def window(self):
return ui.Workspace.get_window(self._window_title)
class WindowModel(ui.AbstractItemModel):
def __init__(self):
super().__init__()
self._root = ui.SimpleStringModel("Windows")
self.update()
def update(self):
self._children = [WindowItem(i) for i in ui.Workspace.get_windows()]
self._item_changed(None)
def get_item_children(self, item):
if item is not None:
return []
return self._children
def get_item_value_model_count(self, item):
return 2
def get_item_value_model(self, item, column_id):
if item is None:
return self._root
if column_id == 0:
return item.title_model
if column_id == 1:
return item.type_model
self._window_model = WindowModel()
self._tree_left = None
self._tree_right = None
with ui.VStack(style=self._style_system):
ui.Button("Refresh", clicked_fn=lambda: self._window_model.update())
with ui.HStack():
ui.Button("Clear", clicked_fn=ui.Workspace.clear)
ui.Button("Focus", clicked_fn=lambda: self._focus(self._tree_left.selection))
with ui.HStack():
ui.Button("Visibile", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, True))
ui.Button("Invisibile", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, False))
ui.Button("Toggle Visibility", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, None))
with ui.HStack():
ui.Button(
"Dock Right",
clicked_fn=lambda: self._dock(
self._tree_left.selection, self._tree_right.selection, ui.DockPosition.RIGHT
),
)
ui.Button(
"Dock Left",
clicked_fn=lambda: self._dock(
self._tree_left.selection, self._tree_right.selection, ui.DockPosition.LEFT
),
)
ui.Button(
"Dock Top",
clicked_fn=lambda: self._dock(
self._tree_left.selection, self._tree_right.selection, ui.DockPosition.TOP
),
)
ui.Button(
"Dock Bottom",
clicked_fn=lambda: self._dock(
self._tree_left.selection, self._tree_right.selection, ui.DockPosition.BOTTOM
),
)
ui.Button(
"Dock Same",
clicked_fn=lambda: self._dock(
self._tree_left.selection, self._tree_right.selection, ui.DockPosition.SAME
),
)
ui.Button("Undock", clicked_fn=lambda: self._undock(self._tree_left.selection))
with ui.HStack():
ui.Button("Move Left", clicked_fn=lambda: self._left(self._tree_left.selection))
ui.Button("MoveRight", clicked_fn=lambda: self._right(self._tree_left.selection))
with ui.HStack():
ui.Button(
"Reverse Docking Tabs of Neighbours",
clicked_fn=lambda: self._dock_reorder(self._tree_left.selection),
)
ui.Button("Hide Tabs", clicked_fn=lambda: self._tabs(self._tree_left.selection, False))
ui.Button("Show Tabs", clicked_fn=lambda: self._tabs(self._tree_left.selection, True))
with ui.HStack(height=400):
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
):
self._tree_left = ui.TreeView(self._window_model, column_widths=[ui.Fraction(1), 80])
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
):
self._tree_right = ui.TreeView(self._window_model, column_widths=[ui.Fraction(1), 80])
self._caption("Capture Layout", navigate_to)
def generate(label):
dump = ui.Workspace.dump_workspace()
label.text = json.dumps(dump, sort_keys=True, indent=4)
def restore(label):
dump = label.text
ui.Workspace.restore_workspace(json.loads(dump))
with ui.HStack(style=self._style_system):
ui.Button("Generate", clicked_fn=lambda: generate(self._label))
ui.Button("Restore", clicked_fn=lambda: restore(self._label))
self._label = self._code("Press Generate to dump layout")
# some padding at the bottom
ui.Spacer(height=100)
| 8,098 | Python | 35.813636 | 120 | 0.551988 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/menu_bar_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation for the MenuBar"""
from omni import ui
from .doc_page import DocPage
SPACING = 5
class MenuBarDoc(DocPage):
""" document MenuBar classes"""
def __init__(self, extension_path):
super().__init__(extension_path)
self._window_menu_example = None
def create_and_show_window_with_menu(self):
if not self._window_menu_example:
self._window_menu_example = ui.Window(
"Window Menu Example",
width=300,
height=300,
flags=ui.WINDOW_FLAGS_MENU_BAR | ui.WINDOW_FLAGS_NO_BACKGROUND,
)
menu_bar = self._window_menu_example.menu_bar
with menu_bar:
with ui.Menu("File"):
ui.MenuItem("Load")
ui.MenuItem("Save")
ui.MenuItem("Export")
with ui.Menu("Window"):
ui.MenuItem("Hide")
with self._window_menu_example.frame:
with ui.VStack():
ui.Button("This Window has a Menu")
def show_hide_menu(menubar):
menubar.visible = not menubar.visible
ui.Button("Click here to show/hide Menu", clicked_fn=lambda m=menu_bar: show_hide_menu(m))
def add_menu(menubar):
with menubar:
with ui.Menu("New Menu"):
ui.MenuItem("I don't do anything")
ui.Button("Add New Menu", clicked_fn=lambda m=menu_bar: add_menu(m))
self._window_menu_example.visible = True
def create_doc(self, navigate_to=None):
self._section_title("MenuBar")
self._text(
"All the Windows in Omni.UI can have a MenuBar. To add a MenuBar to your window add this flag to your "
"constructor - omni.ui.Window(flags=ui.WINDOW_FLAGS_MENU_BAR). The MenuBar object can then be accessed "
"through the menu_bar read-only property on your window\n"
"A MenuBar is a container so it is built like a Frame or Stack but only takes Menu objects as children. "
"You can leverage the 'priority' property on the Menu to order them. They will automatically be sorted "
"when they are added, but if you change the priority of an item then you need to explicitly call sort()."
)
self._caption("MenuBar", navigate_to)
self._text("This class is used to construct a MenuBar for the Window")
with ui.HStack(width=0):
ui.Button("window with MenuBar Example", width=180, clicked_fn=self.create_and_show_window_with_menu)
ui.Label("this populates the menuBar", name="text", width=180, style={"margin_width": 10})
| 3,237 | Python | 41.051948 | 117 | 0.599629 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/checkbox_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation for CheckBox"""
from omni import ui
from .doc_page import DocPage
SPACING = 5
class CheckBoxDoc(DocPage):
""" document for CheckBox"""
def create_doc(self, navigate_to=None):
self._section_title("CheckBox")
self._text(
"A CheckBox is an option button that can be switched on (checked) or off (unchecked). Checkboxes are "
"typically used to represent features in an application that can be enabled or disabled without affecting "
"others."
)
self._text(
"The checkbox is implemented using the model-delegate-view pattern. The model is the central component of this "
"system. It is the application's dynamic data structure independent of the widget. It directly manages the "
"data, logic, and rules of the checkbox. If the model is not specified, the simple one is created "
"automatically when the object is constructed."
)
self._text(
"In the following example, the models of two checkboxes are connected, and if one checkbox is changed, it "
"makes another checkbox be changed as well."
)
with ui.HStack(width=0, spacing=SPACING):
# Create two checkboxes
first = ui.CheckBox()
second = ui.CheckBox()
# Connect one to another
first.model.add_value_changed_fn(lambda a, b=second: b.model.set_value(not a.get_value_as_bool()))
second.model.add_value_changed_fn(lambda a, b=first: b.model.set_value(not a.get_value_as_bool()))
# Set the first one to True
first.model.set_value(True)
self._text("One of two")
self._code(
"""
# Create two checkboxes
first = ui.CheckBox()
second = ui.CheckBox()
# Connect one to another
first.model.add_value_changed_fn(
lambda a, b=second: b.model.set_value(not a.get_value_as_bool()))
second.model.add_value_changed_fn(
lambda a, b=first: b.model.set_value(not a.get_value_as_bool()))
"""
)
self._text("In the following example, that is a bit more complicated, only one checkbox can be enabled.")
with ui.HStack(width=0, spacing=SPACING):
# Create two checkboxes
first = ui.CheckBox()
second = ui.CheckBox()
third = ui.CheckBox()
def like_radio(model, first, second):
"""Turn on the model and turn off two checkboxes"""
if model.get_value_as_bool():
model.set_value(True)
first.model.set_value(False)
second.model.set_value(False)
# Connect one to another
first.model.add_value_changed_fn(lambda a, b=second, c=third: like_radio(a, b, c))
second.model.add_value_changed_fn(lambda a, b=first, c=third: like_radio(a, b, c))
third.model.add_value_changed_fn(lambda a, b=first, c=second: like_radio(a, b, c))
# Set the first one to True
first.model.set_value(True)
self._text("Almost like radio box")
self._code(
"""
# Create two checkboxes
first = ui.CheckBox()
second = ui.CheckBox()
third = ui.CheckBox()
def like_radio(model, first, second):
'''Turn on the model and turn off two checkboxes'''
if model.get_value_as_bool():
model.set_value(True)
first.model.set_value(False)
second.model.set_value(False)
# Connect one to another
first.model.add_value_changed_fn(
lambda a, b=second, c=third: like_radio(a, b, c))
second.model.add_value_changed_fn(
lambda a, b=first, c=third: like_radio(a, b, c))
third.model.add_value_changed_fn(
lambda a, b=first, c=second: like_radio(a, b, c))
"""
)
with ui.HStack(width=0, spacing=SPACING):
ui.CheckBox(enabled=False).model.set_value(True)
ui.CheckBox(enabled=False)
self._text("Disabled")
self._code(
"""
ui.CheckBox(enabled=False).model.set_value(True)
ui.CheckBox(enabled=False)
"""
)
ui.Spacer(height=10)
| 4,949 | Python | 36.786259 | 124 | 0.578299 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/combobox_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation for ComboBox"""
from omni import ui
from .doc_page import DocPage
class ComboBoxDoc(DocPage):
""" document for ComboBox"""
def create_doc(self, navigate_to=None):
self._section_title("ComboBox")
self._text("The ComboBox widget is a combined button and a drop-down list.")
self._text(
"A combo box is a selection widget that displays the current item and can pop up a list of selectable "
"items."
)
self._exec_code(
"""
ui.ComboBox(1, "Option 1", "Option 2", "Option 3")
"""
)
self._text("The following example demonstrates how to add items to the combo box.")
self._exec_code(
"""
editable_combo = ui.ComboBox()
ui.Button(
"Add item to combo",
clicked_fn=lambda m=editable_combo.model: m.append_child_item(
None, ui.SimpleStringModel("Hello World")),
)
"""
)
self._text("The minimal model implementation. It requires to hold the value models and reimplement two methods.")
self._exec_code(
"""
class MinimalItem(ui.AbstractItem):
def __init__(self, text):
super().__init__()
self.model = ui.SimpleStringModel(text)
class MinimalModel(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 = [
MinimalItem(text)
for text in ["Option 1", "Option 2"]
]
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
self._minimal_model = MinimalModel()
ui.ComboBox(self._minimal_model, style={"font_size": 22})
"""
)
self._text(
"The example of communication between widgets. Type anything in the field and it will appear in the combo "
"box."
)
self._exec_code(
"""
editable_combo = None
class StringModel(ui.SimpleStringModel):
'''
String Model activated when editing is finished.
Adds item to combo box.
'''
def __init__(self):
super().__init__("")
def end_edit(self):
combo_model = editable_combo.model
# Get all the options ad list of strings
all_options = [
combo_model.get_item_value_model(child).as_string
for child in combo_model.get_item_children()
]
# Get the current string of this model
fieldString = self.as_string
if fieldString:
if fieldString in all_options:
index = all_options.index(fieldString)
else:
# It's a new string in the combo box
combo_model.append_child_item(
None,
ui.SimpleStringModel(fieldString)
)
index = len(all_options)
combo_model.get_item_value_model().set_value(index)
self._field_model = StringModel()
def combo_changed(combo_model, item):
all_options = [
combo_model.get_item_value_model(child).as_string
for child in combo_model.get_item_children()
]
current_index = combo_model.get_item_value_model().as_int
self._field_model.as_string = all_options[current_index]
with ui.HStack():
ui.StringField(self._field_model)
editable_combo = ui.ComboBox(width=0, arrow_only=True)
editable_combo.model.add_item_changed_fn(combo_changed)
"""
)
ui.Spacer(height=10)
# TODO omni.ui: restore functionality for Kit Next
if True:
return
self._text("The USD example. It tracks the stage cameras and can assign the current camera.")
self._exec_code(
"""
class CamerasItem(ui.AbstractItem):
def __init__(self, model):
super().__init__()
self.model = model
class CamerasModel(ui.AbstractItemModel):
def __init__(self):
super().__init__()
# Omniverse interfaces
self._viewport = omni.kit.viewport.utility.get_active_viewport()
self._stage_update = \\
omni.stageupdate.get_stage_update_interface()
self._usd_context = omni.usd.get_context()
self._stage_subscription = \\
self._stage_update.create_stage_update_node(
"CamerasModel",
None,
None,
None,
self._on_prim_created,
None,
self._on_prim_removed
)
# The list of the cameras is here
self._cameras = []
# The current index of the editable_combo box
self._current_index = ui.SimpleIntModel()
self._current_index.add_value_changed_fn(
self._current_index_changed)
# Iterate the stage and get all the cameras
stage = self._usd_context.get_stage()
for prim in Usd.PrimRange(stage.GetPseudoRoot()):
if prim.IsA(UsdGeom.Camera):
self._cameras.append(
CamerasItem(
ui.SimpleStringModel(
prim.GetPath().pathString)))
def get_item_children(self, item):
return self._cameras
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
def _on_prim_created(self, path):
self._cameras.append(
CamerasItem(ui.SimpleStringModel(path)))
self._item_changed(None)
def _on_prim_removed(self, path):
cameras = [cam.model.as_string for cam in self._cameras]
if path in cameras:
index = cameras.index(path)
del self._cameras[index]
self._current_index.as_int = 0
self._item_changed(None)
def _current_index_changed(self, model):
index = model.as_int
self.self._viewport.camera_path = self._cameras[index].model.as_string
self._item_changed(None)
self._combo_model = CamerasModel()
ui.ComboBox(self._combo_model)
"""
)
| 7,786 | Python | 34.076576 | 121 | 0.509504 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/slider_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation for Sliders"""
from omni import ui
from omni.ui import color as cl
from .doc_page import DocPage
import re
SPACING = 5
class SliderDoc(DocPage):
""" document for Slider"""
def create_doc(self, navigate_to=None):
self._section_title("Drag & Slider")
self._text(
"There are 2 main kind of Sliders, <Type>Slider and <Type>Drag. The Sliders are more like traditionalal "
"slider that can be drag and snap where you click, the value can be shown on the slider or not but can not "
"be edited directly by double clicking"
)
self._text(
"The Drags are more like Field in the way that they behave like a Field, you can double clic to edit the "
"value but they also have a mean to be 'Dragged' to increase / decrease the value"
)
self._text(
"They currently support minimal styling, simple background color (background_color) and text color (color)."
)
self._caption("FloatSlider", navigate_to)
def build_slider_table(label, slider_command):
def mystrip(line: str, number: int) -> str:
"""Remove `number` spaces from the begin of the line"""
n = 0
l = len(line)
while n < number and n < l and line[n] == " ":
n += 1
return line[n:]
# Remove whitespaces from the command but keep the newline symbols
code = "\n".join(mystrip(line, 16) for line in slider_command.split("\n") if line)
with ui.HStack():
with ui.ZStack(width=130):
ui.Rectangle(name="table")
ui.Label(label, name="text", alignment=ui.Alignment.RIGHT, style={"margin": SPACING})
with ui.ZStack():
ui.Rectangle(name="table")
with ui.HStack(name="margin", style={"HStack::margin": {"margin": SPACING / 2}}, spacing=SPACING):
exec(code)
with ui.ZStack(width=ui.Fraction(2)):
ui.Rectangle(name="table")
with ui.ZStack(name="margin", style={"ZStack::margin": {"margin": SPACING / 2}}):
ui.Rectangle(name="code")
ui.Label(code, name="code")
with ui.VStack():
build_slider_table(
"Default",
"""
ui.FloatSlider()
""",
)
build_slider_table(
"Min/Max",
"""
ui.FloatSlider(min=0, max=10)
""",
)
build_slider_table(
"Hard Min/Max",
"""
model = ui.SimpleFloatModel(1.0, min=0, max=100)
ui.FloatSlider(model, min=0, max=10)
""",
)
build_slider_table(
"With Style",
"""
ui.FloatSlider(
min=-180,
max=180,
style={
"draw_mode": ui.SliderDrawMode.HANDLE,
"background_color": cl("#BBBBBB"),
"color": cl.black
}
)
""",
)
build_slider_table(
"Transparent bg",
"""
ui.FloatSlider(
min=-180,
max=180,
style={
"draw_mode": ui.SliderDrawMode.HANDLE,
"background_color": cl.transparent,
"color": cl.black,
"font_size":20.0
}
)
""",
)
build_slider_table(
"different slider color",
"""
ui.FloatSlider(
min=0,
max=1,
style={
"draw_mode": ui.SliderDrawMode.HANDLE,
"background_color": cl.transparent,
"color": cl.black,
"font_size":20.0,
"secondary_color": cl.red,
"secondary_selected_color": cl("#FF00FF")
}
)
""",
)
build_slider_table(
"Field & Slider",
"""
field = ui.FloatField(height=15, width=50)
ui.FloatSlider(
min=0,
max=20,
step=.1,
model=field.model,
style={"color":cl.transparent}
)
# default value
field.model.set_value(12.0)
""",
)
build_slider_table(
"Filled Mode Slider",
"""
ui.FloatSlider(
height=20,
style={"background_color": cl("#DDDDDD"),
"secondary_color": cl("#AAAAAA"),
"color": cl("#111111")}
).model.set_value(0.5)
""",
)
build_slider_table(
"Rounded Slider",
"""
ui.FloatSlider(
height=20,
style={"border_radius": 20,
"background_color": cl.black,
"secondary_color": cl("#DDDDDD"),
"color": cl("#AAAAAA")}
).model.set_value(0.5)
""",
)
build_slider_table(
"Slider Step",
"""
slider = ui.FloatSlider(
step=0.25,
height=0,
style={"border_radius": 20,
"background_color": cl.black,
"secondary_color": cl("#DDDDDD"),
"color": cl("#AAAAAA")})
slider.model.set_value(0.5)
""",
)
build_slider_table(
"Handle Step",
"""
slider = ui.FloatSlider(
step=0.2,
height=0,
style={"draw_mode": ui.SliderDrawMode.HANDLE})
slider.model.set_value(0.4)
""",
)
self._caption("IntSlider", navigate_to)
with ui.VStack():
build_slider_table(
"Default",
"""
ui.IntSlider()
""",
)
build_slider_table(
"Min/Max",
"""
ui.IntSlider(min=0, max=20)
""",
)
build_slider_table(
"With Style",
"""
ui.IntSlider(
min=0,
max=20,
style={
"draw_mode": ui.SliderDrawMode.HANDLE,
"background_color": cl("#BBFFBB"),
"color": cl("#FF00FF"),
"font_size": 14.0
}
)
""",
)
self._caption("FloatDrag", navigate_to)
with ui.VStack():
build_slider_table("Default", "ui.FloatDrag()")
build_slider_table("Min/Max", "ui.FloatDrag(min=-10, max=10, step=0.01)")
self._caption("IntDrag", navigate_to)
with ui.VStack():
build_slider_table("Default", "ui.IntDrag()")
build_slider_table("Min/Max", "ui.IntDrag(min=0, max=50)")
ui.Spacer(height=10)
| 8,360 | Python | 33.407407 | 120 | 0.417105 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/length_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation for Length"""
from omni import ui
from .doc_page import DocPage
SPACING = 5
class LengthDoc(DocPage):
""" document for Length classes"""
def create_doc(self, navigate_to=None):
self._section_title("Lengths")
self._text(
"The Framework UI offers several different units for expressing length: Pixel, Percent and Fraction."
)
self._text("There is no restriction on which units can be used where.")
self._caption("Pixel", navigate_to)
self._text("Pixel is the size in pixels and scaled with the HiDPI scale factor.")
with ui.HStack():
ui.Button("40px", width=ui.Pixel(40))
ui.Button("60px", width=ui.Pixel(60))
ui.Button("100px", width=100)
ui.Button("120px", width=120)
ui.Button("150px", width=150)
self._code(
"""
with ui.HStack():
ui.Button("40px", width=ui.Pixel(40))
ui.Button("60px", width=ui.Pixel(60))
ui.Button("100px", width=100)
ui.Button("120px", width=120)
ui.Button("150px", width=150)
"""
)
self._caption("Percent", navigate_to)
self._text("Percent and Fraction units make it possible to specify sizes relative to the parent size.")
self._text("Percent is 1/100th of the parent size.")
with ui.HStack():
ui.Button("5%", width=ui.Percent(5))
ui.Button("10%", width=ui.Percent(10))
ui.Button("15%", width=ui.Percent(15))
ui.Button("20%", width=ui.Percent(20))
ui.Button("25%", width=ui.Percent(25))
self._code(
"""
with ui.HStack():
ui.Button("5%", width=ui.Percent(5))
ui.Button("10%", width=ui.Percent(10))
ui.Button("15%", width=ui.Percent(15))
ui.Button("20%", width=ui.Percent(20))
ui.Button("25%", width=ui.Percent(25))
"""
)
self._caption("Fraction", navigate_to)
self._text(
"Fraction length is made to take the available space of the parent widget and then divide it among all the "
"child widgets with Fraction length in proportion to their Fraction factor."
)
with ui.HStack():
ui.Button("One", width=ui.Fraction(1))
ui.Button("Two", width=ui.Fraction(2))
ui.Button("Three", width=ui.Fraction(3))
ui.Button("Four", width=ui.Fraction(4))
ui.Button("Five", width=ui.Fraction(5))
self._code(
"""
with ui.HStack():
ui.Button("One", width=ui.Fraction(1))
ui.Button("Two", width=ui.Fraction(2))
ui.Button("Three", width=ui.Fraction(3))
ui.Button("Four", width=ui.Fraction(4))
ui.Button("Five", width=ui.Fraction(5))
"""
)
ui.Spacer(height=10)
| 3,405 | Python | 34.479166 | 120 | 0.576799 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/shape_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation for Shapes"""
from omni import ui
from omni.ui import color as cl
from .doc_page import DocPage
import inspect
SPACING = 5
def editable_curve():
with ui.ZStack(height=400):
# The Bezier tangents
tangents = [(50, 50), (-50, -50)]
# Four draggable rectangles that represent the control points
placer1 = ui.Placer(draggable=True, offset_x=0, offset_y=0)
with placer1:
rect1 = ui.Rectangle(width=20, height=20)
placer2 = ui.Placer(draggable=True, offset_x=50, offset_y=50)
with placer2:
rect2 = ui.Rectangle(width=20, height=20)
placer3 = ui.Placer(draggable=True, offset_x=100, offset_y=100)
with placer3:
rect3 = ui.Rectangle(width=20, height=20)
placer4 = ui.Placer(draggable=True, offset_x=150, offset_y=150)
with placer4:
rect4 = ui.Rectangle(width=20, height=20)
# The bezier curve
curve = ui.FreeBezierCurve(rect1, rect4)
curve.start_tangent_width = ui.Pixel(tangents[0][0])
curve.start_tangent_height = ui.Pixel(tangents[0][1])
curve.end_tangent_width = ui.Pixel(tangents[1][0])
curve.end_tangent_height = ui.Pixel(tangents[1][1])
# The logic of moving the control points
def left_moved(_):
x = placer1.offset_x
y = placer1.offset_y
tangent = tangents[0]
placer2.offset_x = x + tangent[0]
placer2.offset_y = y + tangent[1]
def right_moved(_):
x = placer4.offset_x
y = placer4.offset_y
tangent = tangents[1]
placer3.offset_x = x + tangent[0]
placer3.offset_y = y + tangent[1]
def left_tangent_moved(_):
x1 = placer1.offset_x
y1 = placer1.offset_y
x2 = placer2.offset_x
y2 = placer2.offset_y
tangent = (x2 - x1, y2 - y1)
tangents[0] = tangent
curve.start_tangent_width = ui.Pixel(tangent[0])
curve.start_tangent_height = ui.Pixel(tangent[1])
def right_tangent_moved(_):
x1 = placer4.offset_x
y1 = placer4.offset_y
x2 = placer3.offset_x
y2 = placer3.offset_y
tangent = (x2 - x1, y2 - y1)
tangents[1] = tangent
curve.end_tangent_width = ui.Pixel(tangent[0])
curve.end_tangent_height = ui.Pixel(tangent[1])
# Callback for moving the control points
placer1.set_offset_x_changed_fn(left_moved)
placer1.set_offset_y_changed_fn(left_moved)
placer2.set_offset_x_changed_fn(left_tangent_moved)
placer2.set_offset_y_changed_fn(left_tangent_moved)
placer3.set_offset_x_changed_fn(right_tangent_moved)
placer3.set_offset_y_changed_fn(right_tangent_moved)
placer4.set_offset_x_changed_fn(right_moved)
placer4.set_offset_y_changed_fn(right_moved)
def editable_rect():
with ui.ZStack(height=200):
# Four draggable rectangles that represent the control points
with ui.Placer(draggable=True, offset_x=0, offset_y=0):
control1 = ui.Circle(width=10, height=10, name="default")
with ui.Placer(draggable=True, offset_x=150, offset_y=150):
control2 = ui.Circle(width=10, height=10, name="default")
# The rectangle that fits to the control points
ui.FreeRectangle(control1, control2)
class ShapeDoc(DocPage):
""" document for Shapes"""
def create_doc(self, navigate_to=None):
""" descriptions for the shapes widgets"""
self._section_title("Shape")
self._text("Shape enable you to build custom widget with specific look")
self._text("There are many shape you can use, Rectangle, Circle, Triangle, Line, etc")
self._text(
"In most case those Shape will fit into the Widget size and scale accoringly to the layout they are in "
"For some of them you can fix the size to enable to have more precise control over they size"
)
self._caption("Rectangle", navigate_to)
self._text(
"You can use Rectable to draw rectangle shape, you can have backgroundColor, borderColor, "
"borderWidth, border_radius. mixed it with other controls using ZStack to create advance look"
)
with ui.VStack():
self._shape_table(f"""ui.Rectangle(name="default")""", "(Default) The rectangle is scaled to fit")
self._shape_table(
"""ui.Rectangle(
style={"background_color": cl("#888888"),
"border_color": cl("#222222"),
"border_width": 2.0,
"border_radius": 5.0} )""",
"this rectangle use its own style to control colors and shape",
)
self._shape_table(
"""ui.Rectangle( width=20, height=20,
style={"background_color": cl("#888888"),
"border_color": cl("#222222")} )""",
"using fixed width and height",
)
self._shape_table(
"""with ui.ZStack(height=20):
ui.Rectangle(height=20,
style={"background_color": cl("#888888"),
"border_color": cl("#111111"),
"border_width": .5,
"border_radius": 8.0} )
with ui.HStack():
ui.Spacer(width=10)
ui.Image(
"resources/icons/Cloud.png",
width=20,
height=20
)
ui.Label(
"Search Field",
style={"color": cl("#DDDDDD")}
)""",
"Compose with ZStack for advanced control",
)
self._text("Support for specific Rounded Corner")
corner_flags = {
"NONE": ui.CornerFlag.NONE,
"TOP_LEFT": ui.CornerFlag.TOP_LEFT,
"TOP_RIGHT": ui.CornerFlag.TOP_RIGHT,
"BOTTOM_LEFT": ui.CornerFlag.BOTTOM_LEFT,
"BOTTOM_RIGHT": ui.CornerFlag.BOTTOM_RIGHT,
"TOP": ui.CornerFlag.TOP,
"BOTTOM": ui.CornerFlag.BOTTOM,
"LEFT": ui.CornerFlag.LEFT,
"RIGHT": ui.CornerFlag.RIGHT,
"ALL": ui.CornerFlag.ALL,
}
with ui.ScrollingFrame(
height=100,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style={"ScrollingFrame": {"background_color": cl.transparent}},
):
with ui.HStack():
for key, value in corner_flags.items():
with ui.ZStack():
ui.Rectangle(name="table")
with ui.VStack(style={"VStack": {"margin": SPACING * 2}}):
ui.Rectangle(
style={"background_color": cl("#AA4444"), "border_radius": 20.0, "corner_flag": value}
)
ui.Spacer(height=10)
ui.Label(key, style={"color": cl.black, "font_size": 8}, alignment=ui.Alignment.CENTER)
self._caption("Circle", navigate_to)
self._text("You can use Circle to draw circular shape, you can have backgroundColor, borderColor, borderWidth")
with ui.VStack():
self._shape_table(
f"""ui.Circle(name="default")""", "(Default) The circle is scaled to fit, the alignment is centered"
)
self._shape_table(
f"""ui.Circle(name="default")""", "This circle, is scaled to Fit too with the Row 100 height", 100
)
self._shape_table(
f"""ui.Circle(
name="blue",
radius=20,
size_policy=ui.CircleSizePolicy.FIXED,
alignment=ui.Alignment.LEFT_CENTER)""",
"This circle has a fixed radius of 20, the alignment is LEFT_CENTER",
)
self._shape_table(
f"""ui.Circle(
name="red",
radius=10,
size_policy=ui.CircleSizePolicy.FIXED,
alignment=ui.Alignment.RIGHT_CENTER)""",
"This circle has a fixed radius of 10, the alignment is RIGHT_CENTER",
)
self._shape_table(
"""ui.Circle(
style={"background_color": cl("#00FFFF"),},
size_policy=ui.CircleSizePolicy.STRETCH,
alignment=ui.Alignment.CENTER_TOP)""",
"This circle has a radius to fill the bound, with an alignment is CENTER_TOP",
)
self._shape_table(
"""ui.Circle(
style={"background_color": cl.green,
"border_color": cl.blue,
"border_width": 5},
radius=10,
size_policy=ui.CircleSizePolicy.FIXED,
alignment=ui.Alignment.CENTER_BOTTOM)""",
"This circle has a fixed radius of 5, the alignment is CENTER_BOTTOM, and a custom style ",
)
self._text("Supported Alignment value for the Circle")
alignments = {
"CENTER": ui.Alignment.CENTER,
"LEFT_TOP": ui.Alignment.LEFT_TOP,
"LEFT_CENTER": ui.Alignment.LEFT_CENTER,
"LEFT_BOTTOM": ui.Alignment.LEFT_BOTTOM,
"CENTER_TOP": ui.Alignment.CENTER_TOP,
"CENTER_BOTTOM": ui.Alignment.CENTER_BOTTOM,
"RIGHT_TOP": ui.Alignment.RIGHT_TOP,
"RIGHT_CENTER": ui.Alignment.RIGHT_CENTER,
"RIGHT_BOTTOM": ui.Alignment.RIGHT_BOTTOM,
}
with ui.ScrollingFrame(
height=150,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style={"ScrollingFrame": {"background_color": cl.transparent}},
):
with ui.HStack():
for key, value in alignments.items():
with ui.ZStack():
ui.Rectangle(name="table")
with ui.VStack(style={"VStack": {"margin": SPACING * 2}}, spacing=SPACING * 2):
with ui.ZStack():
ui.Rectangle(name="table")
ui.Circle(
radius=10,
size_policy=ui.CircleSizePolicy.FIXED,
name="orientation",
alignment=value,
style={"background_color": cl("#AA4444")},
)
ui.Label(key, style={"color": cl.black, "font_size": 8}, alignment=ui.Alignment.CENTER)
self._caption("Triangle", navigate_to)
self._text(
"You can use Triangle to draw Triangle shape, you can have backgroundColor, borderColor, borderWidth"
)
with ui.VStack():
self._shape_table(
f"""ui.Triangle(name="default")""",
"(Default) The triange is scaled to fit, base on the left and tip on the center right",
100,
)
self._shape_table(
"""ui.Triangle(
style={"border_color": cl.black,
"border_width": 2},
alignment=ui.Alignment.CENTER_TOP)""",
"Default triange with custom color and border",
100,
)
self._text("the Alignment define where is the Tip of the Triangle, base will be at the oposite side")
alignments = {
"LEFT_TOP": ui.Alignment.LEFT_TOP,
"LEFT_CENTER": ui.Alignment.LEFT_CENTER,
"LEFT_BOTTOM": ui.Alignment.LEFT_BOTTOM,
"CENTER_TOP": ui.Alignment.CENTER_TOP,
"CENTER_BOTTOM": ui.Alignment.CENTER_BOTTOM,
"RIGHT_TOP": ui.Alignment.RIGHT_TOP,
"RIGHT_CENTER": ui.Alignment.RIGHT_CENTER,
"RIGHT_BOTTOM": ui.Alignment.RIGHT_BOTTOM,
}
colors = [cl.red, cl("#FFFF00"), cl("#FF00FF"), cl("#FF0FF0"), cl.green, cl("#F00FFF"), cl("#FFF000"), cl("#AA3333")]
index = 0
with ui.ScrollingFrame(
height=100,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style={"ScrollingFrame": {"background_color": cl.transparent}},
):
with ui.HStack():
for key, value in alignments.items():
with ui.ZStack():
ui.Rectangle(name="table")
with ui.VStack(style={"VStack": {"margin": SPACING * 2}}, spacing=SPACING * 2):
color = colors[index]
index = index + 1
ui.Triangle(name="orientation", alignment=value, style={"background_color": color})
ui.Label(key, style={"color": cl.black, "font_size": 8}, alignment=ui.Alignment.CENTER)
self._caption("Line", navigate_to)
self._text("You can use Line to draw Line shape, you can use color, border_width")
with ui.VStack():
self._shape_table(
f"""ui.Line(name="default")""",
"(Default) The Line is scaled to fit, base on the left and tip on the center right",
100,
)
self._shape_table(
"""ui.Line(name="default",
alignment=ui.Alignment.H_CENTER,
style={"border_width":1, "color": cl.blue})""",
"The Line is scaled to fit, centered top to bottom, color red and line width 1",
100,
)
self._shape_table(
"""ui.Line(name="default",
alignment=ui.Alignment.LEFT,
style={"border_width":5, "color": cl("#880088")})""",
"The Line is scaled to fit, Aligned Left , color purple and line width 5",
100,
)
self._text("the Alignment define where is the line is in the Widget, always fit")
alignments = {
"LEFT": ui.Alignment.LEFT,
"RIGHT": ui.Alignment.RIGHT,
"H_CENTER": ui.Alignment.H_CENTER,
"TOP": ui.Alignment.TOP,
"BOTTOM": ui.Alignment.BOTTOM,
"V_CENTER": ui.Alignment.V_CENTER,
}
with ui.ScrollingFrame(
height=100,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style={"ScrollingFrame": {"background_color": cl.transparent}},
):
with ui.HStack(height=100):
for key, value in alignments.items():
with ui.ZStack():
ui.Rectangle(name="table")
with ui.VStack(style={"VStack": {"margin": SPACING * 2}}, spacing=SPACING * 2):
ui.Line(name="demo", alignment=value)
ui.Label(key, style={"color": cl.black, "font_size": 8}, alignment=ui.Alignment.CENTER)
self._caption("FreeRectangle", navigate_to)
self._text(
"The free widget is the widget that is independent of the layout. It means it can be stuck to other "
"widgets."
)
editable_rect()
self._code(inspect.getsource(editable_rect).split("\n", 1)[-1])
self._caption("FreeBezierCurve", navigate_to)
self._text("Bezier curves are used to model smooth curves that can be scaled infinitely.")
self._text(
"FreeBezierCurve is using two widgets to get the position of the curve ends. It means it's possible to "
"stick the curve to the layout's widgets, and the curve will follow the changes of the layout "
"automatically."
)
editable_curve()
self._code(inspect.getsource(editable_curve).split("\n", 1)[-1])
ui.Spacer(height=10)
| 16,893 | Python | 41.661616 | 125 | 0.524063 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/scrolling_frame_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation for Scrolling Frame"""
from omni import ui
from .doc_page import DocPage
SPACING = 5
class ScrollingFrameDoc(DocPage):
""" document for Menu"""
def create_doc(self, navigate_to=None):
self._section_title("ScrollingFrame")
self._text(
"The ScrollingFrame class provides the ability to scroll onto another widget. ScrollingFrame is used to "
"display the contents of a child widget within a frame. If the widget exceeds the size of the frame, the "
"frame can provide scroll bars so that the entire area of the child widget can be viewed."
)
with ui.HStack(style=self._style_system):
left_frame = ui.ScrollingFrame(
height=250,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with left_frame:
with ui.VStack(height=0):
for i in range(20):
ui.Button(f"Button Left {i}")
right_frame = ui.ScrollingFrame(
height=250,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with right_frame:
with ui.VStack(height=0):
for i in range(20):
ui.Button(f"Button Right {i}")
# Synchronize the scroll position of two frames
def set_scroll_y(frame, y):
frame.scroll_y = y
left_frame.set_scroll_y_changed_fn(lambda y, frame=right_frame: set_scroll_y(frame, y))
right_frame.set_scroll_y_changed_fn(lambda y, frame=left_frame: set_scroll_y(frame, y))
self._code(
"""
with ui.HStack(style=style_system):
left_frame = ui.ScrollingFrame(
height=250,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with left_frame:
with ui.VStack(height=0):
for i in range(20):
ui.Button(f"Button Left {i}")
right_frame = ui.ScrollingFrame(
height=250,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with right_frame:
with ui.VStack(height=0):
for i in range(20):
ui.Button(f"Button Right {i}")
# Synchronize the scroll position of two frames
def set_scroll_y(frame, y):
frame.scroll_y = y
left_frame.set_scroll_y_changed_fn(
lambda y, frame=right_frame: set_scroll_y(frame, y))
right_frame.set_scroll_y_changed_fn(
lambda y, frame=left_frame: set_scroll_y(frame, y)
"""
)
ui.Spacer(height=10)
| 3,595 | Python | 38.086956 | 118 | 0.596106 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/treeview_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation for Widget"""
from .doc_page import DocPage
from pathlib import Path
import asyncio
import omni.ui as ui
import time
class TreeViewDoc(DocPage):
"""Document for TreeView"""
def __init__(self, extension_path):
super().__init__(extension_path)
self._selection = None
self._model = None
def clean(self):
"""Should be called when the extesion us unloaded or reloaded"""
# Unfortunatley, the member variables are not destroyed when the extension is unloaded. We need to do it
# automatically. Usually, it's OK because the Python garbage collector will eventually destroy everythigng. But
# we need the images to be destroyed right now because Kit know nothing about Python garbage collector and it
# will fire warning that texture is not destroyed.
if self._selection:
self._selection._stage_event_sub = None
self._selection._tree_view = None
self._selection = None
if self._model:
self._model.stage_subscription = None
self._model = None
self._command_model = None
self._list_model = None
self._name_value_model = None
self._name_value_delegate = None
def create_doc(self, navigate_to=None):
self._section_title("TreeView")
self._text(
"TreeView is a widget that presents a hierarchical view of information. Each item can have a number of "
"subitems. An indentation often visualizes this in a list. An item can be expanded to reveal subitems, if "
"any exist, and collapsed to hide subitems."
)
self._text(
"TreeView can be used in file manager applications, where it allows the user to navigate the file system "
"directories. They are also used to present hierarchical data, such as the scene object hierarchy."
)
self._text(
"TreeView uses a model-delegate-view pattern to manage the relationship between data and the way it is presented. "
"The separation of functionality gives developers greater flexibility to customize the presentation of "
"items and provides a standard interface to allow a wide range of data sources to be used with other "
"widgets."
)
self._text("The following example demonstrates how to make a single level tree appear like a simple list.")
class CommandItem(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, text):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
class CommandModel(ui.AbstractItemModel):
"""
Represents the list of commands registered in Kit.
It is used to make a single level tree appear like a simple list.
"""
def __init__(self):
super().__init__()
self._commands = []
try:
import omni.kit.commands
except ModuleNotFoundError:
return
omni.kit.commands.subscribe_on_change(self._commands_changed)
self._commands_changed()
def _commands_changed(self):
"""Called by subscribe_on_change"""
self._commands = []
import omni.kit.commands
for cmd_list in omni.kit.commands.get_commands().values():
for k in cmd_list.values():
self._commands.append(CommandItem(k.__name__))
self._item_changed(None)
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return.
return []
return self._commands
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.
It's the object that tracks the specific value.
In our case we use ui.SimpleStringModel.
"""
if item and isinstance(item, CommandItem):
return item.name_model
with ui.ScrollingFrame(
height=400,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
):
self._command_model = CommandModel()
tree_view = ui.TreeView(
self._command_model, root_visible=False, header_visible=False, style={"TreeView.Item": {"margin": 4}}
)
self._text("The following example demonstrates reordering with drag and drop.")
class ListItem(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, text):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
def __repr__(self):
return f'"{self.name_model.as_string}"'
class ListModel(ui.AbstractItemModel):
"""
Represents the model for lists. It's very easy to initialize it
with any string list:
string_list = ["Hello", "World"]
model = ListModel(*string_list)
ui.TreeView(model)
"""
def __init__(self, *args):
super().__init__()
self._children = [ListItem(t) for t in args]
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return.
return []
return self._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.
It's the object that tracks the specific value.
In our case we use ui.SimpleStringModel.
"""
return item.name_model
class ListModelWithReordering(ListModel):
"""
Represents the model for the list with the ability to reorder the
list with drag and drop.
"""
def __init__(self, *args):
super().__init__(*args)
def get_drag_mime_data(self, item):
"""Returns Multipurpose Internet Mail Extensions (MIME) data for be able to drop this item somewhere"""
# As we don't do Drag and Drop to the operating system, we return the string.
return item.name_model.as_string
def drop_accepted(self, target_item, source, drop_location=-1):
"""Reimplemented from AbstractItemModel. Called to highlight target when drag and drop."""
# If target_item is None, it's the drop to root. Since it's
# list model, we support reorganizetion of root only and we
# don't want to create tree.
return not target_item and drop_location >= 0
def drop(self, target_item, source, drop_location=-1):
"""Reimplemented from AbstractItemModel. Called when dropping something to the item."""
try:
source_id = self._children.index(source)
except ValueError:
# Not in the list. This is the source from another model.
return
if source_id == drop_location:
# Nothing to do
return
self._children.remove(source)
if drop_location > len(self._children):
# Drop it to the end
self._children.append(source)
else:
if source_id < drop_location:
# Becase when we removed source, the array became shorter
drop_location = drop_location - 1
self._children.insert(drop_location, source)
self._item_changed(None)
with ui.ScrollingFrame(
height=400,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
):
self._list_model = ListModelWithReordering("Simplest", "List", "Model", "With", "Reordering")
tree_view = ui.TreeView(
self._list_model,
root_visible=False,
header_visible=False,
style={"TreeView.Item": {"margin": 4}},
drop_between_items=True,
)
self._text("The following example demonstrates the ability to edit TreeView items.")
class FloatModel(ui.AbstractValueModel):
"""An example of custom float model that can be used for formatted string output"""
def __init__(self, value: float):
super().__init__()
self._value = value
def get_value_as_float(self):
"""Reimplemented get float"""
return self._value or 0.0
def get_value_as_string(self):
"""Reimplemented get string"""
# This string gors to the field.
if self._value is None:
return ""
# General format. This prints the number as a fixed-point
# number, unless the number is too large, in which case it
# switches to 'e' exponent notation.
return "{0:g}".format(self._value)
def set_value(self, value):
"""Reimplemented set"""
try:
value = float(value)
except ValueError:
value = None
if value != self._value:
# Tell the widget that the model is changed
self._value = value
self._value_changed()
class NameValueItem(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, text, value):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
self.value_model = FloatModel(value)
def __repr__(self):
return f'"{self.name_model.as_string} {self.value_model.as_string}"'
class NameValueModel(ui.AbstractItemModel):
"""
Represents the model for name-value table. It's very easy to initialize it
with any string-float list:
my_list = ["Hello", 1.0, "World", 2.0]
model = NameValueModel(*my_list)
ui.TreeView(model)
"""
def __init__(self, *args):
super().__init__()
# ["Hello", 1.0, "World", 2.0"] -> [("Hello", 1.0), ("World", 2.0)]
regrouped = zip(*(iter(args),) * 2)
self._children = [NameValueItem(*t) for t in regrouped]
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return.
return []
return self._children
def get_item_value_model_count(self, item):
"""The number of columns"""
return 2
def get_item_value_model(self, item, column_id):
"""
Return value model.
It's the object that tracks the specific value.
In our case we use ui.SimpleStringModel for the first column
and SimpleFloatModel for the second column.
"""
return item.value_model if column_id == 1 else item.name_model
class EditableDelegate(ui.AbstractItemDelegate):
"""
Delegate is the representation layer. TreeView calls the methods
of the delegate to create custom widgets for each item.
"""
def __init__(self):
super().__init__()
self.subscription = None
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
pass
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per column per item"""
stack = ui.ZStack(height=20)
with stack:
value_model = model.get_item_value_model(item, column_id)
label = ui.Label(value_model.as_string)
if column_id == 1:
field = ui.FloatField(value_model, visible=False)
else:
field = ui.StringField(value_model, visible=False)
# Start editing when double clicked
stack.set_mouse_double_clicked_fn(lambda x, y, b, m, f=field, l=label: self.on_double_click(b, f, l))
def on_double_click(self, button, field, label):
"""Called when the user double-clicked the item in TreeView"""
if button != 0:
return
# Make Field visible when double clicked
field.visible = True
field.focus_keyboard()
# When editing is finished (enter pressed of mouse clicked outside of the viewport)
self.subscription = field.model.subscribe_end_edit_fn(
lambda m, f=field, l=label: self.on_end_edit(m, f, l)
)
def on_end_edit(self, model, field, label):
"""Called when the user is editing the item and pressed Enter or clicked outside of the item"""
field.visible = False
label.text = model.as_string
self.subscription = None
with ui.ScrollingFrame(
height=400,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
style={"Field": {"background_color": 0xFF000000}},
):
self._name_value_model = NameValueModel("First", 0.2, "Second", 0.3, "Last", 0.4)
self._name_value_delegate = EditableDelegate()
tree_view = ui.TreeView(
self._name_value_model,
delegate=self._name_value_delegate,
root_visible=False,
header_visible=False,
style={"TreeView.Item": {"margin": 4}},
)
class AsyncQueryModel(ListModel):
"""
This is an example of async filling the TreeView model. It's
collecting only as many as it's possible of USD prims for 0.016s
and waits for the next frame, so the UI is not locked even if the
USD Stage is extremely big.
"""
def __init__(self):
super().__init__()
self._stop_event = None
def destroy(self):
self.stop()
def stop(self):
"""Stop traversing the stage"""
if self._stop_event:
self._stop_event.set()
def reset(self):
"""Traverse the stage and keep materials"""
self.stop()
self._stop_event = asyncio.Event()
self._children.clear()
self._item_changed(None)
asyncio.ensure_future(self.__get_all(self._stop_event))
def __push_collected(self, collected):
"""Add given array to the model"""
for c in collected:
self._children.append(c)
self._item_changed(None)
async def __get_all(self, stop_event):
"""Traverse the stage portion at time, so it doesn't freeze"""
stop_event.clear()
start_time = time.time()
# The widget will be updated not faster than 60 times a second
update_every = 1.0 / 60.0
import omni.usd
from pxr import Usd
from pxr import UsdShade
context = omni.usd.get_context()
stage = context.get_stage()
if not stage:
return
# Buffer to keep the portion of the items before sending to the
# widget
collected = []
for p in stage.Traverse(
Usd.TraverseInstanceProxies(Usd.PrimIsActive and Usd.PrimIsDefined and Usd.PrimIsLoaded)
):
if stop_event.is_set():
break
if p.IsA(UsdShade.Material):
# Collect materials only
collected.append(ListItem(str(p.GetPath())))
elapsed_time = time.time()
# Loop some amount of time so fps will be about 60FPS
if elapsed_time - start_time > update_every:
start_time = elapsed_time
# Append the portion and update the widget
if collected:
self.__push_collected(collected)
collected = []
# Wait one frame to let other tasks go
await omni.kit.app.get_app().next_update_async()
self.__push_collected(collected)
try:
import omni.usd
from pxr import Usd
usd_available = True
except ModuleNotFoundError:
usd_available = False
if usd_available:
self._text(
"This is an example of async filling the TreeView model. It's collecting only as many as it's possible "
"of USD prims for 0.016s and waits for the next frame, so the UI is not locked even if the USD Stage "
"is extremely big."
)
with ui.ScrollingFrame(
height=400,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
style={"Field": {"background_color": 0xFF000000}},
):
self._async_query_model = AsyncQueryModel()
ui.TreeView(
self._async_query_model,
root_visible=False,
header_visible=False,
style={"TreeView.Item": {"margin": 4}},
)
self._loaded_label = ui.Label("Press Button to Load Materials", name="text")
with ui.HStack():
ui.Button("Traverse All", clicked_fn=self._async_query_model.reset)
ui.Button("Stop Traversing", clicked_fn=self._async_query_model.stop)
def _item_changed(model, item):
if item is None:
count = len(model._children)
self._loaded_label.text = f"{count} Materials Traversed"
self._async_query_sub = self._async_query_model.subscribe_item_changed_fn(_item_changed)
self._text("For the example code please see the following file:")
current_file_name = Path(__file__).resolve()
self._code(f"{current_file_name}", elided_text=True)
ui.Spacer(height=10)
| 20,987 | Python | 39.130019 | 127 | 0.532377 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/dnd_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation of the omni.ui aka UI Framework"""
from omni import ui
from omni.ui import color as cl
from .doc_page import DocPage
import inspect
def simple_dnd():
def drag(url):
"""Called for the drag operation. Returns drag data."""
return url
def drop_accept(url):
"""Called to check the drag data is acceptable."""
return True
def drop(widget, event):
"""Called when dropping the data."""
widget.source_url = event.mime_data
def drag_area(url):
"""Create a draggable image."""
image = ui.Image(url, width=64, height=64)
image.set_drag_fn(lambda: drag(url))
def drop_area():
"""A drop area that shows image when drop."""
with ui.ZStack(width=64, height=64):
ui.Rectangle()
image = ui.Image()
image.set_accept_drop_fn(drop_accept)
image.set_drop_fn(lambda a, w=image: drop(w, a))
with ui.HStack():
drag_area("resources/icons/Nav_Flymode.png")
drag_area("resources/icons/Move_64.png")
ui.Spacer(width=64)
drop_area()
def complex_dnd():
def drag(url):
# Draw the image and the image name in the drag tooltip
with ui.VStack():
ui.Image(url, width=32, height=32)
ui.Label(url)
return url
def drop_accept(url, ext):
# Accept drops of specific extension only
return url.endswith(ext)
def drop(widget, event):
widget.source_url = event.mime_data
def drag_area(url):
image = ui.Image(url, width=64, height=64)
image.set_drag_fn(lambda: drag(url))
def drop_area(ext):
# If drop is acceptable, the rectangle is blue
style = {}
style["Rectangle"] = {"background_color": cl("#999999")}
style["Rectangle:drop"] = {"background_color": cl("#004499")}
stack = ui.ZStack(width=64, height=64)
with stack:
ui.Rectangle(style=style)
ui.Label(f"Accepts {ext}")
image = ui.Image(style={"margin": 2})
stack.set_accept_drop_fn(lambda d, e=ext: drop_accept(d, e))
stack.set_drop_fn(lambda a, w=image: drop(w, a))
with ui.HStack():
drag_area("resources/icons/sound.png")
drag_area("resources/icons/stage.png")
drag_area("resources/glyphs/menu_audio.svg")
drag_area("resources/glyphs/menu_camera.svg")
ui.Spacer(width=64)
drop_area(".png")
ui.Spacer(width=64)
drop_area(".svg")
class DNDDoc(DocPage):
"""The document for Drag and Drop"""
def create_doc(self, navigate_to=None):
self._section_title("Drag and Drop")
self._caption("Minimal Example", navigate_to)
self._text(
"Omni::UI includes methods to perform Drag and Drop operations quickly. Drag and Drop with Omni::UI is "
"straightforward."
)
self._text(
"A drag and drop operation consists of three parts: the drag, accept the drop, and the drop. For drag, "
"Widget has a single callback drag_fn. By adding this function to a widget, you set the callback attached "
"to the drag operation. The function should return the string data to drag."
)
self._text(
"To accept the drop Widget has a callback accept_drop_fn. It's called when the mouse enters the widget "
"area. It takes the drag string data and should return either the widget can accept this data for the "
"drop."
)
self._text(
"For the drop part, Widget has a callback drop_fn. With this method, we specify if Widget accepts drops. "
"And it's called when the user drops the string data to the widget."
)
simple_dnd()
self._code(inspect.getsource(simple_dnd).split("\n", 1)[-1])
self._caption("Styling and Tooltips", navigate_to)
self._text("It's possible to customize the drag tooltip with creating widgets in drag_fn.")
self._text(
"To show the drop widget accepts drops visually, there is a style 'drop', and it's propagated to the "
"children widgets."
)
complex_dnd()
self._code(inspect.getsource(complex_dnd).split("\n", 1)[-1])
ui.Spacer(height=10)
| 4,786 | Python | 32.711267 | 119 | 0.616172 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/web_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation for Web features such as WebViewWidget implementations"""
from .doc_page import DocPage
from typing import List
import json
import omni.kit.widget.webview as webview
import omni.ui as ui
_BASE_STYLE = {
"WebViewWidget": {"border_width": 0.5, "margin": 5.0, "padding": 5.0, "border_color": 0xFFFD761D},
"Label": {"color": 0xFF000000, "margin": 5.0},
"CheckBox": {"margin": 5.0},
}
class WebViewWidgetDoc(DocPage):
""" Document for WebViewWidget"""
def __init__(self):
self._sections = [
("Displaying an url", self.create_displaying_an_url),
("Styling", self.create_styling),
("Content loading", self.create_content_loading),
("Non-opaque contents", self.create_non_opaque_contents),
("Communication", self.create_js_host_communication),
("Web page debugging", self.create_web_page_debugging),
]
def get_sections(self) -> List[str]:
return [t for (t, _) in self._sections]
def create_doc(self, navigate_to=None):
self._section_title("WebViewWidget")
for (title, create_func) in self._sections:
self._caption(title, navigate_to)
create_func()
def create_displaying_an_url(self):
self._text(
"""The WebViewWidget type displays web pages.
The url can be loaded with 'load_url()'.
The load progress can be observed with 'loading_changed_fn' and 'progress_changed_fn' as well as the WebViewWidget properties 'loading' and 'progress'.
"""
)
with ui.VStack(style=_BASE_STYLE):
loading_label = ui.Label("Load label")
def update_progress(progress: float):
loading_label.text = f"Loading {(progress * 100.0):.0f}% ..."
def update_loading(loading: bool):
if not loading:
loading_label.text = "Loading done."
web_view = webview.WebViewWidget(
width=ui.Percent(100),
height=ui.Pixel(500),
loading_changed_fn=update_loading,
progress_changed_fn=update_progress,
)
urls = ["https://www.nvidia.com", "https://news.ycombinator.com", "http://google.com"]
web_view.load_url(urls[0])
def change_url(model, _item):
url = urls[model.get_item_value_model().as_int]
web_view.load_url(url)
url_selector = ui.ComboBox(0, *urls)
url_selector.model.add_item_changed_fn(change_url)
def create_styling(self):
self._text(
"""The WebViewWidget can be styled normally.
Here we create a web view with rounded corners and wider borders.
In this example, we also use 'url' constructor property to start the load."""
)
style = {
"WebViewWidget": {
"border_width": 3,
"border_radius": 7,
"margin": 5.0,
"padding": 5.0,
"border_color": 0xFFFD761D,
}
}
with ui.VStack(style=_BASE_STYLE):
webview.WebViewWidget(width=ui.Percent(100), height=ui.Pixel(500), url="https://www.google.com")
def create_content_loading(self):
self._text(
"""The WebViewWidget can be populated with static html with the 'html' constructor property.
In this case, the 'url' property describes the base url of the document."""
)
style = {"WebViewWidget": {"border_width": 0.5, "margin": 5.0, "padding": 5.0, "border_color": 0xFFFD761D}}
with ui.VStack(style=style):
webview.WebViewWidget(
width=ui.Percent(100),
height=ui.Pixel(500),
html='<body><h1>Hello from web page</h1><p>This is web content. Here\'s a link <a href="http://wwf.org">into the wild.</a></p></body>',
url="http://example.com/content_loading",
)
def create_non_opaque_contents(self):
self._text(
"""The WebViewWidget can be marked non-opaque so transparent or translucent contents work.
The magenta circles are omni.ui widgets and can be seen beneath and on top of the WebViewWidget.
The web page is marked as transparent with 'contents_is_opaque=False' and then with HTML body css property 'background: transparent'.
"""
)
html = """<body style="background: transparent">
<h3 style="background: rgba(255, 0, 0, 0.4)">Web page input</h3>
<input type="text" value="..text 1.." /> <br/>
<input type="text" value="..text 2.." style="background: rgba(255,255,255,0.5)"/> <br/>
<input type="text" value="..text 3.." /> <br/>
<input type="text" value="..text 4.." style="background: rgba(255,255,255,0.5)"/> <br/>
<input type="text" value="..text last.." /> <br/>
</body>
"""
with ui.VStack(style=_BASE_STYLE):
ui.Circle(
radius=100,
size_policy=ui.CircleSizePolicy.FIXED,
alignment=ui.Alignment.LEFT_BOTTOM,
style={"background_color": 0xDDFF00AA},
)
webview.WebViewWidget(
width=ui.Percent(100),
height=ui.Pixel(200),
contents_is_opaque=False,
html=html,
url="http://example.com/non_opaque_contents",
style={"background_color": 0},
)
ui.Circle(
radius=100,
size_policy=ui.CircleSizePolicy.FIXED,
alignment=ui.Alignment.LEFT_TOP,
style={"background_color": 0xDDFFAAAA},
)
def create_js_host_communication(self):
self._text(
"""The WebViewWidget can control the JavaScript application by using WebViewWidget.evaluate_javascript.
The JavaScript application can send data to the host application by using window.nvwebview.messageHandlers.<name>.postMessage("msg").
"""
)
html = """<body>
<script>
function sendToHost() {
var v = document.getElementById("toHost");
window.nvwebview.messageHandlers.hostApp.postMessage(v.value);
}
function receiveFromHost(data)
{
document.getElementById('fromHost').value = data;
}
</script>
<h3>From JS application to host application</h3>
Text to send: <input id="toHost" type="text" value="Hello from "JS" application" size="75" /> <br/>
<input type="button" value="Send message to host application" onclick="javascript: sendToHost();" /> <br/>
<h3>From host application to JS application</h3>
<input id="fromHost" type="text" value="Message from host application comes here" readonly size="75"/> <br/>
</body>
"""
message_to_send = 'Hello from "host" application \U0001f600.'
webview_widget = None
message_from_js_label = None
send_to_js_button = None
with ui.VStack(style=_BASE_STYLE):
send_to_js_button = ui.Button("Send hello to JS application", width=0)
message_from_js_label = ui.Label("Message from JS application comes here")
webview_widget = webview.WebViewWidget(width=ui.Percent(100), height=ui.Pixel(300))
def send_to_js():
webview_widget.evaluate_javascript(f"receiveFromHost({json.dumps(message_to_send)})")
send_to_js_button.set_clicked_fn(send_to_js)
def update_message_from_js_label(msg: str):
message_from_js_label.text = msg
webview_widget.set_user_script_message_handler_fn("hostApp", update_message_from_js_label)
webview_widget.load_html_from_url(html, "https://example.com/js_host_communication")
def create_web_page_debugging(self):
self._text(
"""The WebViewWidget.set_remote_web_page_debugging_enabled(true) can be used to enable Chrome Web Inspector debugging for all the WebViewWidget instances.
Enable the web page debugging below. Using the desktop Chrome browser, navigate to chrome://inspect to see list of WebViewWidget instances in the process.
"""
)
webview.WebViewWidget.set_remote_web_page_debugging_enabled(False)
checkbox = None
def update_remote_debugging(value_model):
webview.WebViewWidget.set_remote_web_page_debugging_enabled(value_model.get_value_as_bool())
with ui.HStack(style=_BASE_STYLE):
ui.Label("Remote web page debugging enabled", width=0, style={"color": 0xFF000000})
checkbox = ui.CheckBox()
checkbox.model.add_value_changed_fn(update_remote_debugging)
with ui.VStack():
ui.Spacer()
ui.Spacer()
| 9,073 | Python | 39.150442 | 166 | 0.616665 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/attribute_editor_demo.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""an example of creating a custom attribute Editor window"""
from omni import ui
from pathlib import Path
ICON_PATH = Path(__file__).parent.parent.joinpath("icons")
LIGHT_WINDOW_STYLE = {
# main frame style
"ScrollingFrame::canvas": {"background_color": 0xFFCACACA},
"Frame::main_frame": {"background_color": 0xFFCACACA},
# title bar style
"Label::title": {"color": 0xFF777777, "font_size": 16.0},
"Rectangle::titleBar": {"background_color": 0xFFCACACA},
"Rectangle::timeSelection": {"background_color": 0xFF888888, "border_radius": 5.0},
"Triangle::timeArrows": {"background_color": 0xFFCACACA},
"Label::timeLabel": {"color": 0xFFDDDDDD, "font_size": 16.0},
# custom widget slider
"Rectangle::sunStudySliderBackground": {
"background_color": 0xFFBBBBBB,
"border_color": 0xFF888888,
"border_width": 1.0,
"border_radius": 10.0,
},
"Rectangle::sunStudySliderForground": {"background_color": 0xFF888888},
"Circle::slider": {"background_color": 0xFFBBBBBB},
"Circle::slider:hovered": {"background_color": 0xFFCCCCCC},
"Circle::slider:pressed": {"background_color": 0xFFAAAAAA},
"Triangle::selector": {"background_color": 0xFF888888},
"Triangle::selector:hovered": {"background_color": 0xFF999999},
"Triangle::selector:pressed": {"background_color": 0xFF777777},
# toolbar
"Triangle::play_button": {"background_color": 0xFF6E6E6E},
}
KIT_GREEN = 0xFF8A8777
LABEL_PADDING = 120
DARK_WINDOW_STYLE = {
"Window": {"background_color": 0xFF444444},
"Button": {"background_color": 0xFF292929, "margin": 3, "padding": 3, "border_radius": 2},
"Button.Label": {"color": 0xFFCCCCCC},
"Button:hovered": {"background_color": 0xFF9E9E9E},
"Button:pressed": {"background_color": 0xC22A8778},
"VStack::main_v_stack": {"secondary_color": 0x0, "margin_width": 10, "margin_height": 0},
"VStack::frame_v_stack": {"margin_width": 15},
"Rectangle::frame_background": {"background_color": 0xFF343432, "border_radius": 5},
"Field::models": {"background_color": 0xFF23211F, "font_size": 14, "color": 0xFFAAAAAA, "border_radius": 4.0},
"Frame": {"background_color": 0xFFAAAAAA},
"Label::transform": {"font_size": 12, "color": 0xFF8A8777},
"Circle::transform": {"background_color": 0x558A8777},
"Field::transform": {
"background_color": 0xFF23211F,
"border_radius": 3,
"corner_flag": ui.CornerFlag.RIGHT,
"font_size": 12,
},
"Slider::transform": {
"background_color": 0xFF23211F,
"border_radius": 3,
"draw_mode": ui.SliderDrawMode.DRAG,
"corner_flag": ui.CornerFlag.RIGHT,
"font_size": 14,
},
"Label::transform_label": {"font_size": 12, "color": 0xFFDDDDDD},
"Label": {"font_size": 12, "color": 0xFF8A8777},
"Label::label": {"font_size": 14, "color": 0xFF8A8777},
"Label::title": {"font_size": 14, "color": 0xFFAAAAAA},
"Triangle::title": {"background_color": 0xFFAAAAAA},
"ComboBox::path": {"font_size": 12, "secondary_color": 0xFF23211F, "color": 0xFFAAAAAA},
"ComboBox::choices": {
"font_size": 12,
"color": 0xFFAAAAAA,
"background_color": 0xFF23211F,
"secondary_color": 0xFF23211F,
},
"ComboBox:hovered:choices": {"background_color": 0xFF33312F, "secondary_color": 0xFF33312F},
"Slider::value_less": {
"font_size": 12,
"color": 0x0,
"border_radius": 5,
"background_color": 0xFF23211F,
"secondary_color": KIT_GREEN,
"border_color": 0xFFAAFFFF,
"border_width": 0,
},
"Slider::value": {
"font_size": 14,
"color": 0xFFAAAAAA,
"border_radius": 5,
"background_color": 0xFF23211F,
"secondary_color": KIT_GREEN,
},
"Rectangle::add": {"background_color": 0xFF23211F},
"Rectangle:hovered:add": {"background_color": 0xFF73414F},
"CheckBox::greenCheck": {"font_size": 10, "background_color": KIT_GREEN, "color": 0xFF23211F},
"CheckBox::whiteCheck": {"font_size": 10, "background_color": 0xFFDDDDDD, "color": 0xFF23211F},
"Slider::colorField": {"background_color": 0xFF23211F, "font_size": 14, "color": 0xFF8A8777},
# Frame
"CollapsableFrame::standard_collapsable": {
"background_color": 0xFF343432,
"secondary_color": 0xFF343432,
"font_size": 16,
"border_radius": 2.0,
"border_color": 0x0,
"border_width": 0,
},
"CollapsableFrame:hovered:standard_collapsable": {"secondary_color": 0xFFFBF1E5},
"CollapsableFrame:pressed:standard_collapsable": {"secondary_color": 0xFFF7E4CC},
}
CollapsableFrame_style = {
"CollapsableFrame": {
"background_color": 0xFF343432,
"secondary_color": 0xFF343432,
"color": 0xFFAAAAAA,
"border_radius": 4.0,
"border_color": 0x0,
"border_width": 0,
"font_size": 14,
"padding": 0,
},
"HStack::header": {"margin": 5},
"CollapsableFrame:hovered": {"secondary_color": 0xFF3A3A3A},
"CollapsableFrame:pressed": {"secondary_color": 0xFF343432},
}
class AttributeEditorWindow:
""" example of an Attribute Editor Window using Omni::UI """
def __init__(self):
self._editor_window = None
self._window_Frame = None
def set_style_light(self, button):
""" """
self._window_Frame.set_style(LIGHT_WINDOW_STYLE)
def set_style_dark(self, button):
""" """
self._window_Frame.set_style(DARK_WINDOW_STYLE)
def shutdown(self):
"""Should be called when the extesion us unloaded"""
# Unfortunatley, the member variables are not destroyed when the extension is unloaded. We need to do it
# automatically. Usually, it's OK because the Python garbage collector will eventually destroy everythigng. But
# we need the images to be destroyed right now because Kit know nothing about Python garbage collector and it
# will fire warning that texture is not destroyed.
self._editor_window = None
def _create_object_selection_frame(self):
with ui.Frame():
with ui.ZStack():
ui.Rectangle(name="frame_background")
with ui.VStack(spacing=5, name="this", style={"VStack::this": {"margin": 5, "margin_width": 15}}):
with ui.HStack(height=0):
ui.StringField(name="models").model.set_value("(9 models selected)")
with ui.VStack(width=0, height=0):
ui.Spacer(width=0, height=3)
ui.Image(
"resources/glyphs/lock_open.svg",
width=25,
height=12,
style={"color": KIT_GREEN, "marging_width": 5},
)
ui.Spacer(width=0)
with ui.VStack(width=0, height=0):
ui.Spacer(width=0, height=3)
ui.Image("resources/glyphs/settings.svg", width=25, height=12, style={"color": KIT_GREEN})
ui.Spacer(width=0)
with ui.HStack(height=0):
with ui.ZStack(width=60):
ui.Image(f"{ICON_PATH}/Add.svg", width=60, height=30)
with ui.HStack(name="this", style={"HStack::this": {"margin_height": 0}}):
ui.Spacer(width=15)
ui.Label("Add", style={"font_size": 16, "color": 0xFFAAAAAA, "margin_width": 10})
ui.Spacer(width=50)
with ui.ZStack():
ui.Rectangle(style={"background_color": 0xFF23211F, "border_radius": 4.0})
with ui.HStack():
with ui.VStack(width=0):
ui.Spacer(width=0)
ui.Image("resources/glyphs/sync.svg", width=25, height=12)
ui.Spacer(width=0)
ui.StringField(name="models").model.set_value("Search")
def _create_control_state(self, state=0):
control_type = [
f"{ICON_PATH}/Expression.svg",
f"{ICON_PATH}/Mute Channel.svg",
f"{ICON_PATH}/mixed properties.svg",
f"{ICON_PATH}/Default value.svg",
f"{ICON_PATH}/Changed value.svg",
f"{ICON_PATH}/Animation Curve.svg",
f"{ICON_PATH}/Animation Key.svg",
]
if state == 0:
ui.Circle(name="transform", width=20, radius=3.5, size_policy=ui.CircleSizePolicy.FIXED)
else:
with ui.VStack(width=0):
ui.Spacer()
ui.Image(control_type[state - 1], width=20, height=12)
ui.Spacer()
def _create_checkbox_control(self, name, value, label_width=100, line_width=ui.Fraction(1)):
with ui.HStack():
ui.Label(name, name="label", width=0)
ui.Spacer(width=10)
ui.Line(style={"color": 0x338A8777}, width=line_width)
ui.Spacer(width=5)
with ui.VStack(width=10):
ui.Spacer()
ui.CheckBox(width=10, height=0, name="greenCheck").model.set_value(value)
ui.Spacer()
self._create_control_state(0)
def _create_path_combo(self, name, paths):
with ui.HStack():
ui.Label(name, name="label", width=LABEL_PADDING)
with ui.ZStack():
ui.StringField(name="models").model.set_value(paths)
with ui.HStack():
ui.Spacer()
ui.Circle(width=10, height=20, style={"background_color": 0xFF555555})
ui.ComboBox(0, paths, paths, name="path", width=0, height=0, arrow_only=True)
ui.Spacer(width=5)
ui.Image("resources/icons/folder.png", width=15)
ui.Spacer(width=5)
ui.Image("resources/icons/find.png", width=15)
self._create_control_state(2)
def _build_transform_frame(self):
# Transform Frame
with ui.CollapsableFrame(title="Transform", style=CollapsableFrame_style):
with ui.VStack(spacing=8, name="frame_v_stack"):
ui.Spacer(height=0)
components = ["Position", "Rotation", "Scale"]
for component in components:
with ui.HStack():
with ui.HStack(width=LABEL_PADDING):
ui.Label(component, name="transform", width=50)
self._create_control_state()
ui.Spacer()
# Field (X)
all_axis = ["X", "Y", "Z"]
colors = {"X": 0xFF5555AA, "Y": 0xFF76A371, "Z": 0xFFA07D4F}
for axis in all_axis:
with ui.HStack():
with ui.ZStack(width=15):
ui.Rectangle(
width=15,
height=20,
style={
"background_color": colors[axis],
"border_radius": 3,
"corner_flag": ui.CornerFlag.LEFT,
},
)
ui.Label(axis, name="transform_label", alignment=ui.Alignment.CENTER)
ui.FloatDrag(name="transform", min=-1000000, max=1000000, step=0.01)
self._create_control_state(0)
ui.Spacer(height=0)
def _build_checked_header(self, collapsed, title):
triangle_alignment = ui.Alignment.RIGHT_CENTER
if not collapsed:
triangle_alignment = ui.Alignment.CENTER_BOTTOM
with ui.HStack(style={"HStack": {"margin_width": 15, "margin_height": 5}}):
with ui.VStack(width=20):
ui.Spacer()
ui.Triangle(
alignment=triangle_alignment,
name="title",
width=8,
height=8,
style={"background_color": 0xFFCCCCCC},
)
ui.Spacer()
ui.Label(title, name="title", width=0)
ui.Spacer()
ui.CheckBox(width=10, name="whiteCheck").model.set_value(True)
self._create_control_state()
def _build_custom_callapsable_frame(self):
with ui.CollapsableFrame(
title="Light Property", style=CollapsableFrame_style, build_header_fn=self._build_checked_header
):
with ui.VStack(spacing=12, name="frame_v_stack"):
ui.Spacer(height=5)
with ui.HStack():
ui.Label("Slider", name="label", width=LABEL_PADDING)
ui.IntSlider(name="value_less", min=0, max=100, usingGauge=True).model.set_value(30)
self._create_control_state()
self._create_checkbox_control("Great UI", True)
self._create_checkbox_control("Hard To Build", False)
self._create_checkbox_control("Support very very very long checkbox label", True)
ui.Spacer(height=0)
def _build_dropdown_frame(self):
with ui.Frame():
with ui.ZStack():
ui.Rectangle(name="frame_background")
with ui.VStack(height=0, spacing=10, name="frame_v_stack"):
ui.Spacer(height=5)
for index in range(3):
with ui.HStack():
ui.Label("Drop Down", name="label", width=LABEL_PADDING)
ui.ComboBox(0, "Choice 1", "Choice 2", "Choice 3", height=10, name="choices")
self._create_control_state()
self._create_checkbox_control("Check Box", False)
ui.Spacer(height=0)
def _build_scale_and_bias_frame(self):
with ui.CollapsableFrame(title="Scale And Bias Output", collapsed=False, style=CollapsableFrame_style):
with ui.VStack(name="frame_v_stack"):
with ui.HStack():
ui.Spacer(width=100)
ui.Label("Scale", name="label", alignment=ui.Alignment.CENTER)
ui.Spacer(width=10)
ui.Label("Bias", name="label", alignment=ui.Alignment.CENTER)
with ui.VStack(spacing=8):
colors = ["Red", "Green", "Blue", "Alpha"]
for color in colors:
with ui.HStack():
ui.Label(color, name="label", width=LABEL_PADDING)
ui.FloatSlider(name="value", min=0, max=2).model.set_value(1.0)
self._create_control_state(6)
ui.Spacer(width=20)
ui.FloatSlider(name="value", min=-1.0, max=1.0).model.set_value(0.0)
state = None
if color == "Red":
state = 2
elif color == "Blue":
state = 5
else:
state = 3
self._create_control_state(state)
ui.Spacer(height=0)
ui.Spacer(height=5)
with ui.VStack(spacing=14):
self._create_checkbox_control("Warp to Output Range", True)
ui.Line(style={"color": KIT_GREEN})
self._create_checkbox_control("Border Color", True)
self._create_checkbox_control("Zero Alpha Border", False)
with ui.HStack():
self._create_checkbox_control("Cutout Alpha", False, label_width=20, line_width=20)
self._create_checkbox_control("Scale Alpha For Mi Pmap Coverage", True)
self._create_checkbox_control("Border Color", True)
ui.Spacer(height=0)
def _build_color_picker_frame(self):
def color_drag(args):
with ui.HStack(spacing=2):
color_model = ui.MultiFloatDragField(
args[0], args[1], args[2], width=200, h_spacing=5, name="colorField"
).model
ui.ColorWidget(color_model, width=10, height=10)
def color4_drag(args):
with ui.HStack(spacing=2):
color_model = ui.MultiFloatDragField(
args[0],
args[1],
args[2],
args[3],
width=200,
h_spacing=5,
style={"color": 0xFFAAAAAA, "background_color": 0xFF000000, "draw_mode": ui.SliderDrawMode.HANDLE},
).model
ui.ColorWidget(color_model, width=10, height=10)
with ui.CollapsableFrame(title="Color Controls", collapsed=False, style=CollapsableFrame_style):
with ui.VStack(name="frame_v_stack"):
with ui.VStack(spacing=8):
colors = [("Red", [1.0, 0.0, 0.0]), ("Green", [0.0, 1.0, 0.0]), ("Blue", [0.0, 0.0, 1.0])]
for color in colors:
with ui.HStack():
ui.Label(color[0], name="label", width=LABEL_PADDING)
if len(color[1]) == 4:
color4_drag(color[1])
else:
color_drag(color[1])
self._create_control_state(0)
ui.Line(style={"color": 0x338A8777})
color = ("RGBA", [1.0, 0.0, 1.0, 0.5])
with ui.HStack():
ui.Label(color[0], name="label", width=LABEL_PADDING)
color4_drag(color[1])
self._create_control_state(0)
ui.Spacer(height=0)
def _build_frame_with_radio_button(self):
with ui.CollapsableFrame(title="Compression Quality", collapsed=False, style=CollapsableFrame_style):
with ui.VStack(spacing=8, name="frame_v_stack"):
ui.Spacer(height=5)
with ui.HStack():
with ui.VStack(width=LABEL_PADDING):
ui.Label(" Select One...", name="label", width=100, height=0)
ui.Spacer(width=100)
with ui.VStack(spacing=10):
values = ["Faster", "Normal", "Production", "Highest"]
for value in values:
with ui.HStack():
with ui.ZStack(width=20):
outer_style = {
"border_width": 1,
"border_color": KIT_GREEN,
"background_color": 0x0,
"border_radius": 2,
}
ui.Rectangle(width=12, height=12, style=outer_style)
if value == "Faster":
outer_style = {"background_color": KIT_GREEN, "border_radius": 2}
with ui.Placer(offset_x=3, offset_y=3):
ui.Rectangle(width=10, height=10, style=outer_style)
ui.Label(value, name="label", aligment=ui.Alignment.LEFT)
ui.Spacer(height=0)
def build_window(self):
""" build the window for the Class"""
self._editor_window = ui.Window("Attribute Editor", width=450, height=800)
self._editor_window.deferred_dock_in("Layers")
self._editor_window.setPosition(0, 0)
self._editor_window.frame.set_style(DARK_WINDOW_STYLE)
with self._editor_window.frame:
with ui.VStack():
with ui.HStack(height=20):
ui.Label("Styling : ", alignment=ui.Alignment.RIGHT_CENTER)
ui.Button("Light Mode", clicked_fn=lambda b=None: self.set_style_light(b))
ui.Button("Dark Mode", clicked_fn=lambda b=None: self.set_style_dark(b))
ui.Spacer()
ui.Spacer(height=10)
self._window_Frame = ui.ScrollingFrame(
name="canvas",
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
)
with self._window_Frame:
with ui.VStack(height=0, name="main_v_stack", spacing=6):
# create object selection Frame
self._create_object_selection_frame()
# create build transform Frame
self._build_transform_frame()
# DropDown Frame
self._build_dropdown_frame()
# Custom Collapsable Frame
self._build_custom_callapsable_frame()
# Custom Collapsable Frame
with ui.CollapsableFrame(title="Files", style=CollapsableFrame_style):
with ui.VStack(spacing=10, name="frame_v_stack"):
ui.Spacer(height=0)
self._create_path_combo("UI Path", "omni:/Project/Cool_ui.usd")
self._create_path_combo("Texture Path", "omni:/Project/cool_texture.png")
ui.Spacer(height=0)
# Custom Collapsable Frame
with ui.CollapsableFrame(title="Images Options", collapsed=True, style=CollapsableFrame_style):
with ui.VStack(spacing=10, name="frame_v_stack"):
self._create_path_combo("Images Path", "omni:/Library/Images/")
ui.Spacer(height=0)
# Custom Collapsable Frame
self._build_frame_with_radio_button()
# Scale And Bias
self._build_scale_and_bias_frame()
# Color Pickrs
self._build_color_picker_frame()
return self._editor_window
| 23,430 | Python | 45.582505 | 119 | 0.509902 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/progressbar_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation for ProgressBar"""
from omni import ui
from omni.ui import color as cl
from .doc_page import DocPage
SPACING = 5
class CustomProgressValueModel(ui.AbstractValueModel):
"""An example of custom float model that can be used for progress bar"""
def __init__(self, value: float):
super().__init__()
self._value = value
def set_value(self, value):
"""Reimplemented set"""
try:
value = float(value)
except ValueError:
value = None
if value != self._value:
# Tell the widget that the model is changed
self._value = value
self._value_changed()
def get_value_as_float(self):
return self._value
def get_value_as_string(self):
return "Custom Overlay"
class ProgressBarDoc(DocPage):
""" document for ProgressBar"""
def create_doc(self, navigate_to=None):
self._section_title("ProgressBar")
self._text("A progressbar is widget that indicates the progress of an operation.")
self._text("In the following example, it shows how to use progress bar and override the overlay text.")
with ui.VStack(spacing=SPACING):
# Create progressbars
first = ui.ProgressBar()
# Range is [0.0, 1.0]
first.model.set_value(0.5)
second = ui.ProgressBar()
second.model.set_value(1.0)
# Overrides the overlay of progressbar
model = CustomProgressValueModel(0.8)
third = ui.ProgressBar(model)
third.model.set_value(0.1)
# Styling its color
fourth = ui.ProgressBar(style={"color": cl("#0000DD")})
fourth.model.set_value(0.3)
# Styling its border width
ui.ProgressBar(style={"border_width": 2, "color": cl("#0000DD")}).model.set_value(0.7)
# Styling its border radius
ui.ProgressBar(style={"border_radius": 100, "color": cl("#0000DD")}).model.set_value(0.6)
# Styling its background color
ui.ProgressBar(style={"border_radius": 100, "background_color": cl("#0000DD")}).model.set_value(0.6)
# Styling the text color
ui.ProgressBar(style={"border_radius": 100, "secondary_color": cl("#00DDDD")}).model.set_value(0.6)
# Two progress bars in a row with padding
with ui.HStack():
ui.ProgressBar(style={"color": cl("#0000DD"), "padding": 100}).model.set_value(1.0)
ui.ProgressBar().model.set_value(0.0)
self._code(
"""
# Create progressbars
first = ui.ProgressBar()
# Range is [0.0, 1.0]
first.model.set_value(0.5)
second = ui.ProgressBar()
second.model.set_value(1.0)
# Overrides the overlay of progressbar
model = CustomProgressValueModel(0.8)
third = ui.ProgressBar(model)
third.model.set_value(0.1)
# Styling its color
fourth = ui.ProgressBar(style={"color": cl("#0000DD")})
fourth.model.set_value(0.3)
# Styling its border width
ui.ProgressBar(style={"border_width": 2, "color": cl("#0000DD")}).model.set_value(0.7)
# Styling its border radius
ui.ProgressBar(style={"border_radius": 100, "color": cl("#0000DD")}).model.set_value(0.6)
# Styling its background color
ui.ProgressBar(style={"border_radius": 100, "background_color": cl("#0000DD")}).model.set_value(0.6)
# Styling the text color
ui.ProgressBar(style={"border_radius": 100, "secondary_color": cl("#00DDDD")}).model.set_value(0.6)
# Two progress bars in a row with padding
with ui.HStack():
ui.ProgressBar(style={"color": cl("#0000DD"), "padding": 100}).model.set_value(1.0)
ui.ProgressBar().model.set_value(0.0)
"""
)
ui.Spacer(height=10)
| 4,492 | Python | 34.377952 | 112 | 0.592164 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/menu_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation for Menu"""
from omni import ui
from .doc_page import DocPage
class MenuDoc(DocPage):
""" document for Menu"""
def __init__(self, extension_path):
super().__init__(extension_path)
self._context_menu = ui.Menu(
"Context menu",
name="this",
style={
"Menu": {"background_color": 0xFFAA0000, "color": 0xFFFFFFFF, "background_selected_color": 0xFF00AA00},
"MenuItem": {"color": 0xFFFFFFFF, "background_selected_color": 0xFF00AA00},
"Separator": {"color": 0xFFFFFFFF},
},
)
self._pushed_menu = ui.Menu(
"Pushed menu",
style={
"Menu": {"background_color": 0xFF000000, "color": 0xFFFFFFFF, "background_selected_color": 0xFFAAAAAA},
"MenuItem": {"color": 0xFFFFFFFF, "background_selected_color": 0xFFAAAAAA},
},
)
def _show_context_menu(self, x, y, button, modifier):
"""The context menu example"""
# Display context menu only if the right button is pressed
if button != 1:
return
# Reset the previous context popup
self._context_menu.clear()
with self._context_menu:
ui.MenuItem("Delete Shot")
ui.Separator()
ui.MenuItem("Attach Selected Camera")
with ui.Menu("Sub-menu"):
ui.MenuItem("One")
ui.MenuItem("Two")
ui.MenuItem("Three")
ui.Separator()
ui.MenuItem("Four")
with ui.Menu("Five"):
ui.MenuItem("Six")
ui.MenuItem("Seven")
# Show it
self._context_menu.show()
def _show_pushed_menu(self, x, y, button, modifier, widget):
"""The Pushed menu example"""
# Display context menu only if the left mouse button is pressed
if button != 0:
return
# Reset the previous context popup
self._pushed_menu.clear()
with self._pushed_menu:
ui.MenuItem("Camera 1")
ui.MenuItem("Camera 2")
ui.MenuItem("Camera 3")
ui.Separator()
with ui.Menu("More Cameras"):
ui.MenuItem("This Menu is Pushed")
ui.MenuItem("and Aligned with a widget")
# Show it
self._pushed_menu.show_at(
(int)(widget.screen_position_x), (int)(widget.screen_position_y + widget.computed_content_height)
)
def create_doc(self, navigate_to=None):
self._section_title("Menu")
self._text(
"The Menu class provides a menu widget for use in menu bars, context menus, and other popup menus. It can "
"be either a pull-down menu in a menu bar or a standalone context menu. Pull-down menus are shown by the "
"menu bar when the user clicks on the respective item. Context menus are usually invoked by some special "
"keyboard key or by right-clicking."
)
with ui.HStack(style=self._style_system):
ui.Button("Right click to context menu", width=0, mouse_pressed_fn=self._show_context_menu)
self._code(
"""
def _on_startup(self):
....
with ui.HStack(style=style_system):
ui.Button(
"Right click to context menu",
width=0,
mouse_pressed_fn=self._show_context_menu
)
....
def _show_context_menu(self, x, y, button, modifier):
# Display context menu only if the right button is pressed
if button != 1:
return
# Reset the previous context popup
self._context_menu.clear()
with self._context_menu:
with ui.Menu("Sub-menu"):
ui.MenuItem("One")
ui.MenuItem("Two")
ui.MenuItem("Three")
ui.MenuItem("Four")
with ui.Menu("Five"):
ui.MenuItem("Six")
ui.MenuItem("Seven")
ui.MenuItem("Delete Shot")
ui.MenuItem("Attach Selected Camera")
"""
)
with ui.HStack(style=self._style_system):
bt = ui.Button("Pushed Button Menu", width=0, style={"background_color": 0xFF000000, "color": 0xFFFFFFFF})
bt.set_mouse_pressed_fn(lambda x, y, b, m, widget=bt: self._show_pushed_menu(x, y, b, m, widget))
ui.Spacer(height=100)
| 5,068 | Python | 36 | 119 | 0.547948 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/md_doc.py | # Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .doc_page import DocPage
from omni.kit.documentation.builder import DocumentationBuilderMd
from omni.kit.documentation.builder import DocumentationBuilderPage
class MdDoc(DocPage):
def __init__(self, extension_path, md: DocumentationBuilderMd):
super().__init__(extension_path)
self.__md = md
self.__page = None
def clean(self):
"""Should be called when the extesion us unloaded or reloaded"""
if self.__page:
self.__page.destroy()
self.__page = None
def create_doc(self, navigate_to=None):
"""Issue the UI"""
self.__page = DocumentationBuilderPage(self.__md, navigate_to)
| 1,108 | Python | 35.966665 | 76 | 0.710289 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/abstract_model_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation for Abstract Model """
from omni import ui
from pxr import UsdGeom
import omni.kit.commands
import omni.usd
from .doc_page import DocPage
SPACING = 5
class VisibilityWatchModel(ui.AbstractValueModel):
"""The value model that is reimplemented in Python to watch the visibility of the selection"""
def __init__(self):
super(VisibilityWatchModel, self).__init__()
self._usd_context = omni.usd.get_context()
self._selection = None
self._events = None
self._stage_event_sub = None
if self._usd_context is not None:
self._selection = self._usd_context.get_selection()
self._events = self._usd_context.get_stage_event_stream()
self._stage_event_sub = self._events.create_subscription_to_pop(
self._on_stage_event, name="omni.example.ui abstract model stage update"
)
self.prim = None
def clean(self):
"""Should be called when the extesion us unloaded or reloaded"""
self._usd_context = None
self._selection = None
self._events = None
self._stage_event_sub = None
self.prim = None
def _on_stage_event(self, event):
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
self._on_selection_changed()
def _on_selection_changed(self):
selection = self._selection.get_selected_prim_paths()
stage = self._usd_context.get_stage()
# When TC runs tests, it's possible that stage is None
if selection and stage:
self.prim = stage.GetPrimAtPath(selection[0])
# Say to the widgets that the model value is changed
self._value_changed()
def get_value_as_bool(self):
"""Reimplemented get bool"""
if self.prim:
if self.prim.HasAttribute(UsdGeom.Tokens.visibility):
attribute = self.prim.GetAttribute(UsdGeom.Tokens.visibility)
if attribute:
return attribute.Get() == UsdGeom.Tokens.inherited
def set_value(self, value):
"""Reimplemented set bool"""
if self.prim:
omni.kit.commands.execute("ToggleVisibilitySelectedPrims", selected_paths=[self.prim.GetPath()])
# Say to the widgets that the model value is changed
self._value_changed()
class AbstractModelDoc(DocPage):
""" document for CheckBox"""
def __init__(self, extension_path):
super().__init__(extension_path)
self._visibility_model = VisibilityWatchModel()
def clean(self):
"""Should be called when the extesion us unloaded or reloaded"""
# Unfortunatley, the member variables are not destroyed when the extension is unloaded. We need to do it
# automatically. Usually, it's OK because the Python garbage collector will eventually destroy everythigng. But
# we need the images to be destroyed right now because Kit know nothing about Python garbage collector and it
# will fire warning that texture is not destroyed.
if self._visibility_model:
self._visibility_model.clean()
self._visibility_model = None
def create_doc(self, navigate_to=None):
self._section_title("AbstractValueModel")
self._text(
"The AbstractValueModel class provides an abstract interface for the model that holds a single value. It's "
"a central component of the model-delegate-view pattern used in many widgets like CheckBox, StringField(TODO), "
"Slider(TODO), RadioBox(TODO). It's a dynamic data structure independent of the widget implementation. And "
"it holds the data, logic, and rules of the widgets and defines the standard interface that widgets must "
"use to be able to interoperate with the data model. It is not supposed to be instantiated directly. "
"Instead, the user should subclass it to create new models."
)
self._text(
"In the next example, AbstractValueModel class is reimplemented to provide control over the visibility of "
"the selected object."
)
with ui.HStack(width=0, spacing=SPACING):
ui.CheckBox(self._visibility_model)
self._text("Visibility of Selected Prim")
self._code(
"""
class VisibilityWatchModel(ui.AbstractValueModel):
'''
The value model that is reimplemented in Python
to watch the visibility of the selection.
'''
def __init__(self):
super(VisibilityWatchModel, self).__init__()
self._usd_context = omni.usd.get_context()
self._selection = self._usd_context.get_selection()
self._events = self._usd_context.get_stage_event_stream()
self._stage_event_sub = \\
self._events.create_subscription_to_pop(
self._on_stage_event, name="omni.example.ui visibilitywatch stage update")
self.prim = None
def _on_stage_event(self, event):
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
self._on_selection_changed()
def _on_selection_changed(self):
selection = self._selection.get_selected_prim_paths()
stage = self._usd_context.get_stage()
if selection and stage:
self.prim = stage.GetPrimAtPath(selection[0])
# Say to the widgets that the model value is changed
self._value_changed()
def get_value_as_bool(self):
'''Reimplemented get bool'''
if self.prim:
attribute = \\
UsdGeom.Imageable(self.prim).GetVisibilityAttr()
inherited = \\
attribute.Get() == UsdGeom.Tokens.inherited
return inherited if attribute else False
def set_value(self, value):
'''Reimplemented set bool'''
if self.prim:
omni.kit.commands.execute(
"ToggleVisibilitySelectedPrims",
selected_paths=[self.prim.GetPath()])
# Say to the widgets that the model value is changed
self._value_changed()
"""
)
ui.Spacer(height=10)
| 6,940 | Python | 41.32317 | 124 | 0.610375 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/field_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation for Field """
from .doc_page import DocPage
from omni import ui
import inspect
SPACING = 5
def field_callbacks():
def on_value(label):
label.text = "Value is changed"
def on_begin(label):
label.text = "Editing is started"
def on_end(label):
label.text = "Editing is finished"
label = ui.Label("Nothing happened", name="text")
model = ui.StringField().model
model.add_value_changed_fn(lambda m, l=label: on_value(l))
model.add_begin_edit_fn(lambda m, l=label: on_begin(l))
model.add_end_edit_fn(lambda m, l=label: on_end(l))
def multiline_field():
initial_text = inspect.getsource(field_callbacks)
model = ui.SimpleStringModel(initial_text)
field = ui.StringField(model, multiline=True)
class FieldDoc(DocPage):
""" document for Field"""
def create_doc(self, navigate_to=None):
self._section_title("Field")
self._caption("StringField", navigate_to)
self._text(
"The StringField widget is a one-line text editor. A field allows the user to enter and edit a single line "
"of plain text. It's implemented using the model-delegate-view pattern and uses AbstractValueModel as the central "
"component of the system."
)
self._text("The following example demonstrates the way how to connect a StringField and a Label.")
field_style = {
"Field": {
"background_color": 0xFFFFFFFF,
"background_selected_color": 0xFFD77800,
"border_color": 0xFF444444,
"border_radius": 1,
"border_width": 0.5,
"color": 0xFF444444,
"font_size": 16.0,
},
"Field:hovered": {"border_color": 0xFF000000},
"Field:pressed": {"background_color": 0xFFFFFFFF, "border_color": 0xFF995400, "border_width": 0.75},
}
def setText(label, text):
"""Sets text on the label"""
# This function exists because lambda cannot contain assignment
label.text = f"You wrote '{text}'"
with ui.HStack():
field = ui.StringField(style=field_style)
ui.Spacer(width=SPACING)
label = ui.Label("", name="text")
field.model.add_value_changed_fn(lambda m, label=label: setText(label, m.get_value_as_string()))
self._code(
"""
def setText(label, text):
'''Sets text on the label'''
# This function exists because lambda cannot contain assignment
label.text = f"You wrote '{text}'"
with ui.HStack():
field = ui.StringField(style=field_style)
label = ui.Label("")
field.model.add_value_changed_fn(
lambda m, label=label: setText(label, m.get_value_as_string()))
"""
)
self._text(
"The following example demonstrates that the model decides the content of the field. The field can have "
"only one of two options, either 'True' or 'False' because the model supports only those two possibilities."
)
with ui.HStack():
checkbox = ui.CheckBox(width=0)
field = ui.StringField()
field.model = checkbox.model
self._code(
"""
with ui.HStack():
checkbox = ui.CheckBox(width=0)
field = ui.StringField()
field.model = checkbox.model
"""
)
self._text(
"In this example, the field can have anything because the model accepts any string, but the model returns "
"bool for checkbox, and the checkbox is off when the string is empty or 'False'."
)
with ui.HStack():
checkbox = ui.CheckBox(width=0)
field = ui.StringField()
checkbox.model = field.model
self._code(
"""
with ui.HStack():
checkbox = ui.CheckBox(width=0)
field = ui.StringField()
checkbox.model = field.model
"""
)
self._caption("FloatField and IntField", navigate_to)
self._text(
"There are fields for string, float and int models. The following example shows how they interact with "
"each other:"
)
self._text("All three fields share the same SimpleFloatModel:")
with ui.HStack():
self._text("FloatField")
self._text("IntField")
self._text("StringField")
with ui.HStack():
left = ui.FloatField()
center = ui.IntField()
right = ui.StringField()
center.model = left.model
right.model = left.model
self._text("All three fields share the same SimpleIntModel:")
with ui.HStack():
self._text("FloatField")
self._text("IntField")
self._text("StringField")
with ui.HStack():
left = ui.FloatField()
center = ui.IntField()
right = ui.StringField()
left.model = center.model
right.model = center.model
self._text("All three fields share the same SimpleStringModel:")
with ui.HStack():
self._text("FloatField")
self._text("IntField")
self._text("StringField")
with ui.HStack():
left = ui.FloatField()
center = ui.IntField()
right = ui.StringField()
left.model = right.model
center.model = right.model
self._text(
"The widget doesn't keep the data due to the model-delegate-view pattern. However, there are two ways to track the "
"state of the widget. It's possible to reimplement AbstractValueModel, for details see the chapter "
"`AbstractValueModel`. The second way is using the callbacks of the model. This is a minimal example "
"of callbacks."
)
field_callbacks()
self._code(inspect.getsource(field_callbacks).split("\n", 1)[-1])
self._caption("Multiline StringField", navigate_to)
self._text(
"Property `multiline` of `StringField` allows to press enter and create a new line. It's possible to "
"finish editing with Ctrl-Enter."
)
with ui.Frame(style=field_style, height=300):
multiline_field()
self._code(inspect.getsource(multiline_field).split("\n", 1)[-1])
ui.Spacer(height=10)
| 7,030 | Python | 34.155 | 128 | 0.582077 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/multifield_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation for Shapes"""
from omni import ui
from .doc_page import DocPage
import inspect
import omni.usd
from .colorwidget_doc import USDColorModel
SPACING = 5
def simplest_field():
ui.MultiIntField(0, 0, 0, 0)
def simplest_drag():
ui.MultiFloatDragField(0.0, 0.0, 0.0, 0.0)
def matrix_field():
args = [1.0 if i % 5 == 0 else 0.0 for i in range(16)]
ui.MultiFloatField(*args, width=ui.Percent(50), h_spacing=5, v_spacing=2)
def usd_field():
with ui.HStack(spacing=SPACING):
model = USDColorModel()
ui.ColorWidget(model, width=0)
ui.MultiFloatField(model)
def usd_drag():
with ui.HStack(spacing=SPACING):
model = USDColorModel()
ui.ColorWidget(model, width=0)
ui.MultiFloatDragField(model, min=0.0, max=2.0)
class MultiFieldDoc(DocPage):
"""Document for MultiField"""
def create_doc(self, navigate_to=None):
"""Descriptions for MultiField"""
self._section_title("MultiField")
self._text(
"MultiField widget groups are the widgets that have multiple similar widgets to represent each item in the "
"model. It's handy to use them for arrays and multi-component data like float3, matrix, and color."
)
simplest_field()
self._code(inspect.getsource(simplest_field).split("\n", 1)[-1])
simplest_drag()
self._code(inspect.getsource(simplest_drag).split("\n", 1)[-1])
matrix_field()
self._code(inspect.getsource(matrix_field).split("\n", 1)[-1])
# TODO omni.ui: restore functionality for Kit Next
if False:
usd_field()
self._code(inspect.getsource(usd_field).split("\n", 1)[-1])
usd_drag()
self._code(inspect.getsource(usd_drag).split("\n", 1)[-1])
| 2,255 | Python | 28.68421 | 120 | 0.659867 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/colorwidget_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation for ColorWidget"""
from .doc_page import DocPage
from omni import ui
from pxr import Gf
from pxr import UsdGeom
from typing import Any
import inspect
import omni.kit.commands
import omni.usd
import weakref
SPACING = 5
class SetDisplayColorCommand(omni.kit.commands.Command):
"""
Change prim display color undoable **Command**. Unlike ChangePropertyCommand, it can undo property creation.
Args:
gprim (Gprim): Prim to change display color on.
value: Value to change to.
value: Value to undo to.
"""
def __init__(self, gprim: UsdGeom.Gprim, color: Any, prev: Any):
self._gprim = gprim
self._color = color
self._prev = prev
def do(self):
color_attr = self._gprim.CreateDisplayColorAttr()
color_attr.Set([self._color])
def undo(self):
color_attr = self._gprim.GetDisplayColorAttr()
if self._prev is None:
color_attr.Clear()
else:
color_attr.Set([self._prev])
class FloatModel(ui.SimpleFloatModel):
def __init__(self, parent):
super().__init__()
self._parent = weakref.ref(parent)
def begin_edit(self):
parent = self._parent()
parent.begin_edit(None)
def end_edit(self):
parent = self._parent()
parent.end_edit(None)
class USDColorItem(ui.AbstractItem):
def __init__(self, model):
super().__init__()
self.model = model
class USDColorModel(ui.AbstractItemModel):
def __init__(self):
super().__init__()
# Create root model
self._root_model = ui.SimpleIntModel()
self._root_model.add_value_changed_fn(lambda a: self._item_changed(None))
# Create three models per component
self._items = [USDColorItem(FloatModel(self)) for i in range(3)]
for item in self._items:
item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item))
# Omniverse contexts
self._usd_context = omni.usd.get_context()
self._selection = self._usd_context.get_selection()
self._events = self._usd_context.get_stage_event_stream()
self._stage_event_sub = self._events.create_subscription_to_pop(
self._on_stage_event, name="omni.example.ui colorwidget stage update"
)
# Privates
self._subscription = None
self._gprim = None
self._prev_color = None
self._edit_mode_counter = 0
def _on_stage_event(self, event):
"""Called with subscription to pop"""
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
self._on_selection_changed()
def _on_selection_changed(self):
"""Called when the user changes the selection"""
selection = self._selection.get_selected_prim_paths()
stage = self._usd_context.get_stage()
self._subscription = None
self._gprim = None
# When TC runs tests, it's possible that stage is None
if selection and stage:
self._gprim = UsdGeom.Gprim.Get(stage, selection[0])
if self._gprim:
color_attr = self._gprim.GetDisplayColorAttr()
usd_watcher = omni.usd.get_watcher()
self._subscription = usd_watcher.subscribe_to_change_info_path(
color_attr.GetPath(), self._on_usd_changed
)
# Change the widget color
self._on_usd_changed()
def _on_value_changed(self, item):
"""Called when the submodel is chaged"""
if not self._gprim:
return
if self._edit_mode_counter > 0:
# Change USD only if we are in the edit mode.
color_attr = self._gprim.CreateDisplayColorAttr()
color = Gf.Vec3f(
self._items[0].model.get_value_as_float(),
self._items[1].model.get_value_as_float(),
self._items[2].model.get_value_as_float(),
)
color_attr.Set([color])
self._item_changed(item)
def _on_usd_changed(self, path=None):
"""Called with UsdWatcher when something in USD is changed"""
color = self._get_current_color() or Gf.Vec3f(0.0)
for i in range(len(self._items)):
self._items[i].model.set_value(color[i])
def _get_current_color(self):
"""Returns color of the current object"""
if self._gprim:
color_attr = self._gprim.GetDisplayColorAttr()
if color_attr:
color_array = color_attr.Get()
if color_array:
return color_array[0]
def get_item_children(self, item):
"""Reimplemented from the base class"""
return self._items
def get_item_value_model(self, item, column_id):
"""Reimplemented from the base class"""
if item is None:
return self._root_model
return item.model
def begin_edit(self, item):
"""
Reimplemented from the base class.
Called when the user starts editing.
"""
if self._edit_mode_counter == 0:
self._prev_color = self._get_current_color()
self._edit_mode_counter += 1
def end_edit(self, item):
"""
Reimplemented from the base class.
Called when the user finishes editing.
"""
self._edit_mode_counter -= 1
if not self._gprim or self._edit_mode_counter > 0:
return
color = Gf.Vec3f(
self._items[0].model.get_value_as_float(),
self._items[1].model.get_value_as_float(),
self._items[2].model.get_value_as_float(),
)
omni.kit.commands.execute("SetDisplayColor", gprim=self._gprim, color=color, prev=self._prev_color)
def color_field():
with ui.HStack(spacing=SPACING):
color_model = ui.ColorWidget(width=0, height=0).model
for item in color_model.get_item_children():
component = color_model.get_item_value_model(item)
ui.FloatField(component)
def color_drag():
with ui.HStack(spacing=SPACING):
color_model = ui.ColorWidget(0.125, 0.25, 0.5, width=0, height=0).model
for item in color_model.get_item_children():
component = color_model.get_item_value_model(item)
ui.FloatDrag(component)
def color_combo():
with ui.HStack(spacing=SPACING):
color_model = ui.ColorWidget(width=0, height=0).model
ui.ComboBox(color_model)
def two_usd_color_boxes():
with ui.HStack(spacing=SPACING):
ui.ColorWidget(USDColorModel(), width=0)
ui.Label("First ColorWidget", name="text")
with ui.HStack(spacing=SPACING):
ui.ColorWidget(USDColorModel(), width=0)
ui.Label("Second ColorWidget has independed model", name="text")
class ColorWidgetDoc(DocPage):
"""Document for ColorWidget"""
def create_doc(self, navigate_to=None):
self._section_title("ColorWidget")
self._text(
"The ColorWidget widget is a button that displays the color from the item model and can open a picker "
"window. The color dialog's function is to allow users to choose colors."
)
self._text("Fields connected to the color model")
color_field()
self._code(inspect.getsource(color_field).split("\n", 1)[-1])
self._text("Drags connected to the color model")
color_drag()
self._code(inspect.getsource(color_drag).split("\n", 1)[-1])
self._text("ComboBox connected to the color model.")
color_combo()
self._code(inspect.getsource(color_combo).split("\n", 1)[-1])
# TODO omni.ui: restore functionality for Kit Next
if False:
self._text("Two different models that watch USD Stage. Undo/Redo example.")
two_usd_color_boxes()
with ui.ScrollingFrame(height=250, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON):
self._code(
inspect.getsource(FloatModel)
+ "\n"
+ inspect.getsource(USDColorItem)
+ "\n"
+ inspect.getsource(USDColorModel)
+ "\n"
+ inspect.getsource(two_usd_color_boxes)
)
ui.Spacer(height=20)
| 8,824 | Python | 31.806691 | 115 | 0.600748 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/widget_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation for Widget"""
from .doc_page import DocPage
from omni import ui
from omni.ui import color as cl
from pathlib import Path
import inspect
import random
SPACING = 5
def tooltip_fixed_position():
ui.Button("Fixed-position Tooltip", width=200, tooltip="Hello World", tooltip_offset_y=22)
def tooltip_random_position():
button = ui.Button("Random-position Tooltip", width=200, tooltip_offset_y=22)
def create_tooltip(button=button):
button.tooltip_offset_x = random.randint(0, 200)
ui.Label("Hello World")
button.set_tooltip_fn(create_tooltip)
def image_button():
style = {
"Button": {"stack_direction": ui.Direction.TOP_TO_BOTTOM},
"Button.Image": {
"color": cl("#99CCFF"),
"image_url": "resources/icons/Learn_128.png",
"alignment": ui.Alignment.CENTER,
},
"Button.Label": {"alignment": ui.Alignment.CENTER},
}
def direction(model, button, style=style):
value = model.get_item_value_model().get_value_as_int()
direction = (
ui.Direction.TOP_TO_BOTTOM,
ui.Direction.BOTTOM_TO_TOP,
ui.Direction.LEFT_TO_RIGHT,
ui.Direction.RIGHT_TO_LEFT,
ui.Direction.BACK_TO_FRONT,
ui.Direction.FRONT_TO_BACK,
)[value]
style["Button"]["stack_direction"] = direction
button.set_style(style)
def align(model, button, image, style=style):
value = model.get_item_value_model().get_value_as_int()
alignment = (
ui.Alignment.LEFT_TOP,
ui.Alignment.LEFT_CENTER,
ui.Alignment.LEFT_BOTTOM,
ui.Alignment.CENTER_TOP,
ui.Alignment.CENTER,
ui.Alignment.CENTER_BOTTOM,
ui.Alignment.RIGHT_TOP,
ui.Alignment.RIGHT_CENTER,
ui.Alignment.RIGHT_BOTTOM,
)[value]
if image:
style["Button.Image"]["alignment"] = alignment
else:
style["Button.Label"]["alignment"] = alignment
button.set_style(style)
def layout(model, button, padding, style=style):
padding = "padding" if padding else "margin"
style["Button"][padding] = model.get_value_as_float()
button.set_style(style)
def spacing(model, button):
button.spacing = model.get_value_as_float()
button = ui.Button("Label", style=style, width=64, height=64)
with ui.HStack(width=ui.Percent(50)):
ui.Label('"Button": {"stack_direction"}', name="text")
options = (
0,
"TOP_TO_BOTTOM",
"BOTTOM_TO_TOP",
"LEFT_TO_RIGHT",
"RIGHT_TO_LEFT",
"BACK_TO_FRONT",
"FRONT_TO_BACK",
)
model = ui.ComboBox(*options).model
model.add_item_changed_fn(lambda m, i, b=button: direction(m, b))
alignment = (
4,
"LEFT_TOP",
"LEFT_CENTER",
"LEFT_BOTTOM",
"CENTER_TOP",
"CENTER",
"CENTER_BOTTOM",
"RIGHT_TOP",
"RIGHT_CENTER",
"RIGHT_BOTTOM",
)
with ui.HStack(width=ui.Percent(50)):
ui.Label('"Button.Image": {"alignment"}', name="text")
model = ui.ComboBox(*alignment).model
model.add_item_changed_fn(lambda m, i, b=button: align(m, b, 1))
with ui.HStack(width=ui.Percent(50)):
ui.Label('"Button.Label": {"alignment"}', name="text")
model = ui.ComboBox(*alignment).model
model.add_item_changed_fn(lambda m, i, b=button: align(m, b, 0))
with ui.HStack(width=ui.Percent(50)):
ui.Label("padding", name="text")
model = ui.FloatSlider(min=0, max=500).model
model.add_value_changed_fn(lambda m, b=button: layout(m, b, 1))
with ui.HStack(width=ui.Percent(50)):
ui.Label("margin", name="text")
model = ui.FloatSlider(min=0, max=500).model
model.add_value_changed_fn(lambda m, b=button: layout(m, b, 0))
with ui.HStack(width=ui.Percent(50)):
ui.Label("Button.spacing", name="text")
model = ui.FloatSlider(min=0, max=50).model
model.add_value_changed_fn(lambda m, b=button: spacing(m, b))
class WidgetDoc(DocPage):
""" document for Widget"""
def radio_button(self):
style = {
"": {"background_color": cl.transparent, "image_url": f"{self._extension_path}/icons/radio_off.svg"},
":checked": {"image_url": f"{self._extension_path}/icons/radio_on.svg"},
}
collection = ui.RadioCollection()
for i in range(5):
with ui.HStack(style=style):
ui.RadioButton(radio_collection=collection, width=30, height=30)
ui.Label(f"Option {i}", name="text")
ui.IntSlider(collection.model, min=0, max=4)
def create_doc(self, navigate_to=None):
self._section_title("Widgets")
self._text(
"The widget provides all the base functionality for most ui elements" "There is a lot of default feature "
)
self._caption("Button", navigate_to)
self._text(
"The Button widget provides a command button. The command button, is perhaps the most commonly used widget "
"in any graphical user interface. Click a button to execute a command. It is rectangular and typically "
"displays a text label describing its action."
)
def make_longer_text(button):
"""Set the text of the button longer"""
button.text = "Longer " + button.text
def make_shorter_text(button):
"""Set the text of the button shorter"""
splitted = button.text.split(" ", 1)
button.text = splitted[1] if len(splitted) > 1 else splitted[0]
with ui.HStack(style=self._style_system):
btn_with_text = ui.Button("Text", width=0)
ui.Button("Press me", width=0, clicked_fn=lambda b=btn_with_text: make_longer_text(b))
btn_with_text.set_clicked_fn(lambda b=btn_with_text: make_shorter_text(b))
self._code(
"""
def make_longer_text(button):
'''Set the text of the button longer'''
button.text = "Longer " + button.text
def make_shorter_text(button):
'''Set the text of the button shorter'''
splitted = button.text.split(" ", 1)
button.text = \\
splitted[1] if len(splitted) > 1 else splitted[0]
with ui.HStack(style=style_system):
btn_with_text = ui.Button("Text", width=0)
ui.Button(
"Press me",
width=0,
clicked_fn=lambda b=btn_with_text: make_longer_text(b)
)
btn_with_text.set_clicked_fn(
lambda b=btn_with_text: make_shorter_text(b))
"""
)
image_button()
self._code(inspect.getsource(image_button).split("\n", 1)[-1])
self._caption("RadioButton", navigate_to)
self._text(
"RadioButton is the widget that allows the user to choose only one of a predefined set of mutually "
"exclusive options."
)
self._text(
"RadioButtons are arranged in collections of two or more with the class RadioGroup, which is the central "
"component of the system and controls the behavior of all the RadioButtons in the collection."
)
self.radio_button()
self._code(inspect.getsource(self.radio_button).split("\n", 1)[-1])
self._caption("Label", navigate_to)
self._text(
"Labels are used everywhere in omni.ui. They are text-only objects, and don't have a background color"
"But you can control the color, font_size and alignment in the styling."
)
self._exec_code(
"""
ui.Label("this is a simple label", style={"color": cl.black})
"""
)
self._exec_code(
"""
ui.Label("label with aligment", style={"color": cl.black}, alignment=ui.Alignment.CENTER)
"""
)
self._exec_code(
"""
label_style = {"Label": {"font_size": 16, "color": cl.blue, "alignment":ui.Alignment.RIGHT }}
ui.Label("Label with style", style=label_style)
"""
)
self._exec_code(
"""
ui.Label(
"Label can be elided: Lorem ipsum dolor "
"sit amet, consectetur adipiscing elit, sed do "
"eiusmod tempor incididunt ut labore et dolore "
"magna aliqua. Ut enim ad minim veniam, quis "
"nostrud exercitation ullamco laboris nisi ut "
"aliquip ex ea commodo consequat. Duis aute irure "
"dolor in reprehenderit in voluptate velit esse "
"cillum dolore eu fugiat nulla pariatur. Excepteur "
"sint occaecat cupidatat non proident, sunt in "
"culpa qui officia deserunt mollit anim id est "
"laborum.",
style={"color":cl.black},
elided_text=True,
)
"""
)
self._caption("Tooltip", navigate_to)
self._text(
"All Widget can be augmented with a tooltip, it can take 2 forms, either a simple ui.Label or a callback"
"when using the callback, tooltip_fn= or widget.set_tooltip_fn() you can create virtually any widget for "
"the tooltip"
)
self._exec_code(
"""
tooltip_style = {
"Tooltip": {"background_color": cl("#DDDD00"), "color": cl("#333333"), "margin_width": 3 ,
"margin_height": 2 , "border_width":3, "border_color": cl.red }}
ui.Button("Simple Label Tooltip", name="tooltip", width=200,
tooltip=" I am a text ToolTip ", style=tooltip_style)
"""
)
self._exec_code(
"""
def create_tooltip():
with ui.VStack(width=200, style=tooltip_style):
with ui.HStack():
ui.Label("Fancy tooltip", width=150)
ui.IntField().model.set_value(12)
ui.Line(height=2, style={"color": cl.white})
with ui.HStack():
ui.Label("Anything is possible", width=150)
ui.StringField().model.set_value("you bet")
image_source = "resources/desktop-icons/omniverse_512.png"
ui.Image(
image_source,
width=200,
height=200,
alignment=ui.Alignment.CENTER,
style={"margin": 0},
)
tooltip_style = {
"Tooltip": {"background_color": cl("#444444"), "border_width":2, "border_radius":5},
}
ui.Button("Callback function Tooltip", width=200, style=tooltip_style, tooltip_fn=create_tooltip)
"""
)
tooltip_fixed_position()
self._code(inspect.getsource(tooltip_fixed_position).split("\n", 1)[-1])
tooltip_random_position()
self._code(inspect.getsource(tooltip_random_position).split("\n", 1)[-1])
ui.Spacer(height=50)
self._caption("Debug Color", navigate_to)
self._text("All Widget can be styled to use a debug color that enable you to visualize their frame")
self._exec_code(
"""
style = {"background_color": cl("#DDDD00"),
"color": cl("#333333"),
"debug_color": cl("#FF000022") }
ui.Label("Label with Debug", width=200, style=style)
"""
)
self._exec_code(
"""
style = {":hovered": {"debug_color": cl("#00FFFF22") },
"Label": {"padding": 3,
"background_color": cl("#DDDD00"),
"color": cl("#333333"),
"debug_color": cl("#0000FF22") }}
with ui.HStack(width=500, style=style):
ui.Label("Label 1", width=50)
ui.Label("Label 2")
ui.Label("Label 3",
width=100,
alignment=ui.Alignment.CENTER)
ui.Spacer()
ui.Label("Label 3", width=50)
"""
)
self._caption("Font", navigate_to)
self._text(
"It's possible to set the font of the label using styles. The style key 'font' should point to the font "
"file, which allows packaging of the font to the extension. We support both TTF and OTF formats. "
"All text-based widgets support custom fonts."
)
self._exec_code(
"""
ui.Label(
"The quick brown fox jumps over the lazy dog",
style={
"font_size": 55,
"font": "${fonts}/OpenSans-SemiBold.ttf",
"alignment": ui.Alignment.CENTER
},
word_wrap=True,
)
"""
)
ui.Spacer(height=10)
| 13,547 | Python | 34.465968 | 120 | 0.552668 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/plot_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation for Menu"""
from omni import ui
from omni.ui import color as cl
from .doc_page import DocPage
import math
class PlotDoc(DocPage):
""" document for Plot"""
def __init__(self, extension_path):
super().__init__(extension_path)
self._data = []
for i in range(360):
self._data.append(math.cos(math.radians(i)))
def create_doc(self, navigate_to=None):
self._section_title("Plot")
self._text("The Plot class displayes a line or histogram image.")
self._text("The data of image is specified as a data array or a provider function.")
ui.Plot(ui.Type.LINE, -1.0, 1.0, *self._data, width=360, height=100, style={"color": cl.red})
self._code(
"""
self._data = []
for i in range(360):
self._data.append(math.cos(math.radians(i)))
ui.Plot(ui.Type.LINE, -1.0, 1.0, *self._data, width=360, height=100, style={"color": cl.red})
"""
)
plot = ui.Plot(
ui.Type.HISTOGRAM,
-1.0,
1.0,
self._on_data_provider,
360,
width=360,
height=100,
style={"color": cl.blue},
)
plot.value_stride = 6
self._code(
"""
def _on_data_provider(self, index):
return math.sin(math.radians(index))
plot = ui.Plot(ui.Type.HISTOGRAM, -1.0, 1.0, self._on_data_provider, 360, width=360, height=100, style={"color": cl.blue})
plot.value_stride = 6
"""
)
ui.Spacer(height=100)
def _on_data_provider(self, index):
return math.sin(math.radians(index))
| 2,140 | Python | 29.585714 | 130 | 0.590187 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/styling_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation for Styling"""
from .doc_page import DocPage
from functools import partial
from omni import ui
from omni.ui import color as cl
from omni.ui import constant as fl
from omni.ui import url
import inspect
SPACING = 5
def named_shades():
def set_color(color):
cl.example_color = color
def set_width(value):
fl.example_width = value
cl.example_color = cl.green
fl.example_width = 1.0
with ui.HStack(height=100, spacing=5):
with ui.ZStack():
ui.Rectangle(
style={
"background_color": cl.shade(
"aqua",
orange=cl.orange,
another=cl.example_color,
transparent=cl.transparent,
black=cl.black,
),
"border_width": fl.shade(1, orange=4, another=8),
"border_radius": fl.one,
"border_color": cl.black,
},
)
ui.Label(
"ui.Rectangle(\n"
"\tstyle={\n"
'\t\t"background_color":\n'
"\t\t\tcl.shade(\n"
'\t\t\t\t"aqua",\n'
"\t\t\t\torange=cl(1, 0.5, 0),\n"
"\t\t\t\tanother=cl.example_color),\n"
'\t\t"border_width":\n'
"\t\t\tfl.shade(1, orange=4, another=8)})",
alignment=ui.Alignment.CENTER,
word_wrap=True,
style={"color": cl.black, "margin": 15},
)
with ui.ZStack():
ui.Rectangle(
style={
"background_color": cl.example_color,
"border_width": fl.example_width,
"border_radius": fl.one,
"border_color": cl.black,
}
)
ui.Label(
"ui.Rectangle(\n"
"\tstyle={\n"
'\t\t"background_color": cl.example_color,\n'
'\t\t"border_width": fl.example_width)})',
alignment=ui.Alignment.CENTER,
word_wrap=True,
style={"color": cl.black, "margin": 15},
)
with ui.HStack():
ui.Button("ui.set_shade()", clicked_fn=partial(ui.set_shade, ""))
ui.Button('ui.set_shade("orange")', clicked_fn=partial(ui.set_shade, "orange"))
ui.Button('ui.set_shade("another")', clicked_fn=partial(ui.set_shade, "another"))
with ui.HStack():
ui.Button("fl.example_width = 1", clicked_fn=partial(set_width, 1))
ui.Button("fl.example_width = 4", clicked_fn=partial(set_width, 4))
with ui.HStack():
ui.Button('cl.example_color = "green"', clicked_fn=partial(set_color, "green"))
ui.Button("cl.example_color = cl(0.8)", clicked_fn=partial(set_color, cl(0.8)))
def url_shades():
def set_url(url_path: str):
url.example_url = url_path
walk = "resources/icons/Nav_Walkmode.png"
fly = "resources/icons/Nav_Flymode.png"
url.example_url = walk
with ui.HStack(height=100, spacing=5):
with ui.ZStack():
ui.Image(style={"image_url": url.example_url})
ui.Label(
'ui.Image(\n\tstyle={"image_url": cl.example_url})\n',
alignment=ui.Alignment.CENTER,
word_wrap=True,
style={"color": cl.black, "margin": 15},
)
with ui.ZStack():
ui.ImageWithProvider(
style={
"image_url": url.shade(
"resources/icons/Move_local_64.png",
another="resources/icons/Move_64.png",
orange="resources/icons/Rotate_local_64.png",
)
}
)
ui.Label(
"ui.ImageWithProvider(\n"
"\tstyle={\n"
'\t\t"image_url":\n'
"\t\t\tst.shade(\n"
'\t\t\t\t"Move_local_64.png",\n'
'\t\t\t\tanother="Move_64.png")})\n',
alignment=ui.Alignment.CENTER,
word_wrap=True,
style={"color": cl.black, "margin": 15},
)
with ui.HStack():
ui.Button("ui.set_shade()", clicked_fn=partial(ui.set_shade, ""))
ui.Button('ui.set_shade("another")', clicked_fn=partial(ui.set_shade, "another"))
with ui.HStack():
ui.Button("url.example_url = Nav_Walkmode.png", clicked_fn=partial(set_url, walk))
ui.Button("url.example_url = Nav_Flymode.png", clicked_fn=partial(set_url, fly))
def font_size():
def value_changed(label, value):
label.style = {"color": ui.color(0), "font_size": value.as_float}
slider = ui.FloatSlider(min=1.0, max=150.0)
slider.model.as_float = 10.0
label = ui.Label("Omniverse", style={"color": ui.color(0), "font_size": 7.0})
slider.model.add_value_changed_fn(partial(value_changed, label))
class StylingDoc(DocPage):
""" document for Styling workflow"""
def create_doc(self, navigate_to=None):
self._section_title("Styling")
self._caption("The Style Sheet Syntax", navigate_to)
self._text(
"OMNI.UI Style Sheet rules are almost identical to those of HTML CSS. Style sheets consist of a sequence "
"of style rules. A style rule is made up of a selector and a declaration. The selector specifies which "
"widgets are affected by the rule; the declaration specifies which properties should be set on the widget. "
"For example:"
)
with ui.VStack(width=0, style={"Button": {"background_color": cl("#097EFF")}}):
ui.Button("Style Example")
self._code(
"""
with ui.VStack(width=0, style={"Button": {"background_color": cl("#097EFF")}}):
ui.Button("Style Example")
"""
)
self._text(
'In the above style rule, Button is the selector, and { "background_color": cl("#097EFF") } is the '
"declaration. The rule specifies that Button should use blue as its background color."
)
with ui.VStack():
self._table("Selector", "Example", "Explanation", cl.black)
self._table("Type Selector", "Button", "Matches instances of Button.")
self._table(
"Name Selector", "Button::okButton", "Matches all Button instances whose object name is okButton."
)
self._table(
"State Selector",
"Button:hovered",
"Matches all Button instances whose state is hovered. It means the mouse should be in the widget area. "
"Pseudo-states appear at the end of the selector, with a colon (:) in between. The supported states are "
"hovered and pressed.",
)
self._text("It's possible to omit the selector and override the property in all the widget types:")
with ui.VStack(width=0, style={"background_color": cl("#097EFF")}):
ui.Button("Style Example")
self._code(
"""
with ui.VStack(width=0, style={"background_color": cl("#097EFF")}):
ui.Button("Style Example")
"""
)
self._text(
"The difference with the previous button is that all the colors, including pressed color and hovered "
"color, are overridden."
)
style1 = {
"Button": {"border_width": 0.5, "border_radius": 0.0, "margin": 5.0, "padding": 5.0},
"Button::one": {
"background_color": cl("#097EFF"),
"background_gradient_color": cl("#6DB2FA"),
"border_color": cl("#1D76FD"),
},
"Button.Label::one": {"color": cl.white},
"Button::one:hovered": {"background_color": cl("#006EFF"), "background_gradient_color": cl("#5AAEFF")},
"Button::one:pressed": {"background_color": cl("#6DB2FA"), "background_gradient_color": cl("#097EFF")},
"Button::two": {"background_color": cl.white, "border_color": cl("#B1B1B1")},
"Button.Label::two": {"color": cl("#272727")},
"Button::three:hovered": {
"background_color": cl("#006EFF"),
"background_gradient_color": cl("#5AAEFF"),
"border_color": cl("#1D76FD"),
},
"Button::four:pressed": {
"background_color": cl("#6DB2FA"),
"background_gradient_color": cl("#097EFF"),
"border_color": cl("#1D76FD"),
},
}
with ui.HStack(style=style1):
ui.Button("One", name="one")
ui.Button("Two", name="two")
ui.Button("Three", name="three")
ui.Button("Four", name="four")
ui.Button("Five", name="five")
self._code(
"""
style1 = {
"Button": {
"border_width": 0.5,
"border_radius": 0.0,
"margin": 5.0,
"padding": 5.0
},
"Button::one": {
"background_color": cl("#097EFF"),
"background_gradient_color": cl("#6DB2FA"),
"border_color": cl("#1D76FD"),
},
"Button.Label::one": {
"color": cl.white,
},
"Button::one:hovered": {
"background_color": cl("#006EFF"),
"background_gradient_color": cl("#5AAEFF")
},
"Button::one:pressed": {
"background_color": cl("#6DB2FA"),
"background_gradient_color": cl("#097EFF")
},
"Button::two": {
"background_color": cl.white,
"border_color": cl("#B1B1B1")
},
"Button.Label::two": {
"color": cl("#272727")
},
"Button::three:hovered": {
"background_color": cl("#006EFF"),
"background_gradient_color": cl("#5AAEFF"),
"border_color": cl("#1D76FD"),
},
"Button::four:pressed": {
"background_color": cl("#6DB2FA"),
"background_gradient_color": cl("#097EFF"),
"border_color": cl("#1D76FD"),
},
}
with ui.HStack(style=style1):
ui.Button("One", name="one")
ui.Button("Two", name="two")
ui.Button("Three", name="three")
ui.Button("Four", name="four")
ui.Button("Five", name="five")
"""
)
self._text(
"It's possible to assign any style override to any level of the widget. It can be assigned to both parents "
"and children at the same time."
)
with ui.HStack(style=self._style_system):
ui.Button("One")
ui.Button("Two", style={"color": cl("#AAAAAA")})
ui.Button("Three", style={"background_color": cl("#097EFF"), "background_gradient_color": cl("#6DB2FA")})
ui.Button(
"Four", style={":hovered": {"background_color": cl("#006EFF"), "background_gradient_color": cl("#5AAEFF")}}
)
ui.Button(
"Five",
style={"Button:pressed": {"background_color": cl("#6DB2FA"), "background_gradient_color": cl("#097EFF")}},
)
self._code(
"""
style_system = {
"Button": {
"background_color": cl("#E1E1E1"),
"border_color": cl("#ADADAD"),
"border_width": 0.5,
"border_radius": 0.0,
"margin": 5.0,
"padding": 5.0,
},
"Button.Label": {
"color": cl.black,
},
"Button:hovered": {
"background_color": cl("#E5F1FB"),
"border_color": cl("#0078D7")
},
"Button:pressed": {
"background_color": cl("#CCE4F7"),
"border_color": cl("#005499"),
"border_width": 1.0
},
}
with ui.HStack(style=style_system):
ui.Button("One")
ui.Button("Two", style={"color": cl("#AAAAAA")})
ui.Button("Three", style={
"background_color": cl("#097EFF"),
"background_gradient_color": cl("#6DB2FA")}
)
ui.Button(
"Four", style={
":hovered": {
"background_color": cl("#006EFF"),
"background_gradient_color": cl("#5AAEFF")
}
}
)
ui.Button(
"Five",
style={
"Button:pressed": {
"background_color": cl("#6DB2FA"),
"background_gradient_color": cl("#097EFF")
}
},
)
"""
)
self._caption("Color Syntax", navigate_to)
self._text(
"There are many ways that colors can be described with omni.ui.color. If alpha is not specified, it is assumed to be 255 or 1.0."
)
self._code(
"""
from omni.ui import color as cl
cl("#CCCCCC") # RGB
cl("#CCCCCCFF") # RGBA
cl(128, 128, 128) # RGB
cl(0.5, 0.5, 0.5) # RGB
cl(128, 128, 128, 255) # RGBA
cl(0.5, 0.5, 0.5, 1.0) # RGBA
cl(128) # RGB all the same
cl(0.5) # RGB all the same
cl.blue
"""
)
self._text(
"Note: You may see something like this syntax in older code, but that syntax is not suggested anymore:"
)
self._code('"background_color": 0xFF886644 # Same as cl("#446688FF")')
self._text(
"Because of the way bytes are packed with little-endian format in that syntax, the color components appear to be backwards (ABGR). "
"Going forward only omni.ui.color syntax should be used."
)
self._caption("Shades", navigate_to)
self._text(
"Shades are used to have multiple named color palettes with the ability to runtime switch. The shade can "
"be defined with the following code:"
)
self._code('cl.shade(cl("#0066FF"), red=cl.red, green=cl("#00FF66"))')
self._text(
"It can be assigned to the color style. It's possible to switch the color with the following command "
"globally:"
)
self._code('cl.set_shade("red")')
named_shades()
self._code(inspect.getsource(named_shades).split("\n", 1)[-1])
self._caption("URL Shades", navigate_to)
self._text("It's also possible to use shades for specifying shortcuts to the images and style-based paths.")
url_shades()
self._code(inspect.getsource(url_shades).split("\n", 1)[-1])
self._caption("Font Size", navigate_to)
self._text("It's possible to set the font size with the style:")
font_size()
self._code(inspect.getsource(font_size).split("\n", 1)[-1])
ui.Spacer(height=10)
| 15,870 | Python | 35.823666 | 144 | 0.497669 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/custom_window_example.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""an example of creating a custom with shapes and drags window"""
# TODO : This need clean up for full documentation
from omni import ui
EXTENSION_NAME = "Brick Demo Window"
LIGHT_WINDOW_STYLE = {
# main frame style
"ScrollingFrame::canvas": {"background_color": 0xFFCACACA},
"Frame::main_frame": {"background_color": 0xFFCACACA},
# title bar style
"Label::title": {"color": 0xFF777777, "font_size": 16.0},
"Rectangle::titleBar": {"background_color": 0xFFCACACA},
"Rectangle::timeSelection": {"background_color": 0xFF888888, "border_radius": 5.0},
"Triangle::timeArrows": {"background_color": 0xFFCACACA},
"Label::timeLabel": {"color": 0xFFDDDDDD, "font_size": 16.0},
# custom widget slider
"Rectangle::sunStudySliderBackground": {
"background_color": 0xFFBBBBBB,
"border_color": 0xFF888888,
"border_width": 1.0,
"border_radius": 10.0,
},
"Rectangle::sunStudySliderForground": {"background_color": 0xFF888888},
"Circle::slider": {"background_color": 0xFFBBBBBB},
"Circle::slider:hovered": {"background_color": 0xFFCCCCCC},
"Circle::slider:pressed": {"background_color": 0xFFAAAAAA},
"Triangle::selector": {"background_color": 0xFF888888},
"Triangle::selector:hovered": {"background_color": 0xFF999999},
"Triangle::selector:pressed": {"background_color": 0xFF777777},
# toolbar
"Triangle::play_button": {"background_color": 0xFF6E6E6E},
}
DARK_WINDOW_STYLE = {
# main frame style
"ScrollingFrame::canvas": {"background_color": 0xFF454545},
"Frame::main_frame": {"background_color": 0xFF454545},
# title bar style
"Label::title": {"color": 0xFF777777, "font_size": 16.0},
"Rectangle::titleBar": {"background_color": 0xFF454545},
"Rectangle::timeSelection": {"background_color": 0xFF888888, "border_radius": 5.0},
"Triangle::timeArrows": {"background_color": 0xFF454545},
"Label::timeLabel": {"color": 0xFF454545, "font_size": 16.0},
# custom widget slider
"Rectangle::sunStudySliderBackground": {
"background_color": 0xFF666666,
"border_color": 0xFF333333,
"border_width": 1.0,
"border_radius": 10.0,
},
"Rectangle::sunStudySliderForground": {"background_color": 0xFF333333},
"Circle::slider": {"background_color": 0xFF888888},
"Triangle::selector": {"background_color": 0xFF888888},
# toolbar
"Triangle::play_button": {"background_color": 0xFF6E6E6E},
}
class BrickSunStudyWindow:
""" example of sun study window using Omni::UI """
def __init__(self):
self._is_playing = False
self._window_Frame = None
self._time_selector_left_spacer = None
self._slider_spacer = None
self._slider_spacer_width = [200]
self._start_time_offset = [200]
self._start_time_label = None
self._start_time = "8:00 AM"
self._end_time_offset = [600]
self._end_time_label = None
self._end_time = "6:00 PM"
self._time_of_day_offset = [200]
self._mouse_press_position = [0, 0]
def _play_pause_fn(self, x, y):
""" """
self._is_playing = not self._is_playing
self._play_button.visible = not self._is_playing
self._pause_button.visible = self._is_playing
def _on_object_mouse_pressed(self, position, x, y):
position[0] = x
position[1] = y
def on_placer_mouse_moved_both(self, placer, offset, position, x, y):
# TODO: DPI is the problem we need to solve
offset[0] += x - position[0]
offset[1] += y - position[1]
placer.offset_x = max(offset[0], 0)
placer.offset_y = offset[1]
self._on_object_mouse_pressed(position, x, y)
def on_time_placer_mouse_moved_X(self, placer, offset, position, x, y):
# TODO: DPI is the problem we need to solve
offset[0] += x - position[0]
offset[0] = max(offset[0], 0)
placer.offset_x = offset[0]
# this is not very correct but serve ok for this demo
hours = int(offset[0] / 800 * 24)
time = "AM"
if hours > 12:
hours = hours - 12
time = "PM"
self._current_time_label.text = f"{hours}:00 {time}"
self._on_object_mouse_pressed(position, x, 0)
def on_start_placer_mouse_moved_X(self, placer, offset, position, x, y):
# TODO: DPI is the problem we need to solve
offset[0] += x - position[0]
offset[0] = max(offset[0], 0)
placer.offset_x = offset[0]
self._time_range_placer.offset_x = offset[0] + 50
self._time_range_rectangle.width = ui.Pixel(self._end_time_offset[0] - self._start_time_offset[0] + 3)
# this is not very correct but serve ok for this demo
hours = int(offset[0] / 800 * 24)
time = "AM"
if hours > 12:
hours = hours - 12
time = "PM"
self._start_time_label.text = f"{hours}:00 {time}"
self._on_object_mouse_pressed(position, x, 0)
def on_end_placer_mouse_moved_X(self, placer, offset, position, x, y):
# TODO: DPI is the problem we need to solve
offset[0] += x - position[0]
offset[0] = max(offset[0], 0)
placer.offset_x = offset[0]
self._time_range_rectangle.width = ui.Pixel(self._end_time_offset[0] - self._start_time_offset[0] + 3)
# this is not very correct but serve ok for this demo
hours = int(offset[0] / 800 * 24)
time = "AM"
if hours > 12:
hours = hours - 12
time = "PM"
self._end_time_label.text = f"{hours}:00 {time}"
self._on_object_mouse_pressed(position, x, 0)
def set_style_light(self, button):
""" """
self._window_Frame.set_style(LIGHT_WINDOW_STYLE)
def set_style_dark(self, button):
""" """
self._window_Frame.set_style(DARK_WINDOW_STYLE)
def _build_title_bar(self):
""" return the title bar stack"""
with ui.VStack():
with ui.ZStack(height=30):
ui.Rectangle(name="titleBar")
# Title Bar
with ui.HStack():
ui.Spacer(width=10, height=0)
with ui.VStack(width=0):
ui.Spacer(width=0, height=8)
ui.Label("Sun Study", name="title", width=0, alignment=ui.Alignment.LEFT)
ui.Spacer(width=0, height=ui.Fraction(1))
ui.Spacer(width=ui.Fraction(1))
with ui.VStack(width=0):
ui.Spacer(height=5)
with ui.HStack():
ui.Spacer(width=10, height=0)
ui.Image("resources/icons/[email protected]", width=20, height=20)
ui.Spacer(width=10)
ui.Image("resources/icons/[email protected]", width=20, height=20)
ui.Spacer(width=5)
ui.Spacer(height=5)
# Shadow
ui.Image("resources/icons/TitleBarShadow_wAlpha_v2.png", fill_policy=ui.FillPolicy.STRETCH, height=20)
def _build_time_arrow(self, arrowAlignment):
with ui.VStack(width=0): # remove spacer with Fraction Padding
ui.Spacer()
ui.Triangle(name="timeArrows", width=12, height=12, alignment=arrowAlignment)
ui.Spacer()
def _build_start_time_selector(self):
""" """
selector_placer = ui.Placer(offset_x=self._start_time_offset[0])
with selector_placer:
with ui.VStack(
width=80,
mouse_pressed_fn=lambda x, y, b, a, c=self._mouse_press_position: self._on_object_mouse_pressed(
c, x, y
),
mouse_moved_fn=lambda x, y, b, a: self.on_start_placer_mouse_moved_X(
selector_placer, self._start_time_offset, self._mouse_press_position, x, y
),
opaque_for_mouse_events=True,
): # SELECTOR START
self._start_time_selector_stack = ui.ZStack()
with self._start_time_selector_stack:
ui.Rectangle(height=25, name="timeSelection")
with ui.HStack(height=25): # remove spacer with Padding
ui.Spacer(width=5)
self._build_time_arrow(ui.Alignment.LEFT_CENTER)
ui.Spacer(width=5)
self._start_time_label = ui.Label(
self._start_time, name="timeLabel", alignment=ui.Alignment.RIGHT_CENTER
)
ui.Spacer(width=5)
with ui.HStack(height=20): # Selector tip, Spacer will be removed wiht Padding
ui.Spacer()
def show_hide_start_time_selector():
self._start_time_selector_stack.visible = not self._start_time_selector_stack.visible
ui.Triangle(
width=10,
height=17,
name="selector",
alignment=ui.Alignment.CENTER_BOTTOM,
mouse_pressed_fn=lambda x, y, b, a: show_hide_start_time_selector(),
)
ui.Spacer()
def _build_end_time_selector(self):
self._end_time_placer = ui.Placer(offset_x=self._end_time_offset[0])
with self._end_time_placer:
with ui.VStack(
width=80,
mouse_pressed_fn=lambda x, y, b, a: self._on_object_mouse_pressed(
self._mouse_press_position, x, y
),
mouse_moved_fn=lambda x, y, b, a: self.on_end_placer_mouse_moved_X(
self._end_time_placer, self._end_time_offset, self._mouse_press_position, x, y
),
opaque_for_mouse_events=True,
): # SELECTOR END
self._end_time_selector_stack = ui.ZStack()
with self._end_time_selector_stack:
ui.Rectangle(height=25, name="timeSelection")
with ui.HStack(height=25):
ui.Spacer(width=5)
self._end_time_label = ui.Label(
self._end_time, name="timeLabel", widthalignment=ui.Alignment.RIGHT_CENTER
)
ui.Spacer(width=5)
self._build_time_arrow(ui.Alignment.RIGHT_CENTER)
ui.Spacer(width=5)
def show_hide_end_time_selector():
self._end_time_selector_stack.visible = not self._end_time_selector_stack.visible
with ui.HStack(height=20):
ui.Spacer()
ui.Triangle(
width=10,
height=17,
name="selector",
alignment=ui.Alignment.CENTER_BOTTOM,
mouse_pressed_fn=lambda x, y, b, a: show_hide_end_time_selector(),
)
ui.Spacer()
def _build_central_slider(self):
""" """
# custom slider Widget
with ui.VStack(height=70):
ui.Spacer(height=40)
with ui.HStack():
with ui.ZStack(height=20):
ui.Rectangle(name="sunStudySliderBackground")
self._time_range_placer = ui.Placer(offset_x=self._start_time_offset[0])
with self._time_range_placer:
self._time_range_rectangle = ui.Rectangle(name="sunStudySliderForground", width=500, height=30)
circle_placer = ui.Placer(offset_x=self._time_of_day_offset[0])
with circle_placer:
ui.Circle(
name="slider",
width=30,
height=30,
radius=10,
mouse_pressed_fn=lambda x, y, b, a: self._on_object_mouse_pressed(
self._mouse_press_position, x, y
),
mouse_moved_fn=lambda x, y, b, a: self.on_time_placer_mouse_moved_X(
circle_placer, self._time_of_day_offset, self._mouse_press_position, x, y
),
opaque_for_mouse_events=True,
)
def _build_custom_slider(self):
""" return the slider stack"""
side_padding = 50
with ui.HStack(height=70):
ui.Spacer(width=side_padding) # from Padding (will be removed by Padding on the HStack)
with ui.ZStack():
self._build_central_slider()
# Selectors
with ui.ZStack(height=40): # Selector Height
self._build_start_time_selector()
self._build_end_time_selector()
ui.Spacer(width=side_padding)
def _build_control_bar(self):
""" """
with ui.HStack(height=40):
ui.Spacer(width=50)
ui.Image("resources/icons/[email protected]", width=25)
ui.Spacer(width=10)
ui.Image("resources/icons/[email protected]", width=20)
ui.Spacer(width=10)
ui.Image("resources/icons/[email protected]", width=20)
ui.Spacer(width=ui.Fraction(2))
# with ui.ZStack():
self._play_button = ui.Image(
"resources/icons/[email protected]",
height=30,
width=30,
mouse_pressed_fn=lambda x, y, button, modifier: self._play_pause_fn(x, y),
)
self._pause_button = ui.Image(
"resources/icons/[email protected]",
height=30,
width=30,
mouse_pressed_fn=lambda x, y, button, modifier: self._play_pause_fn(x, y),
)
self._pause_button.visible = False
ui.Spacer(width=ui.Fraction(1))
with ui.HStack(width=120):
self._current_time_label = ui.Label("9:30 AM", name="title")
ui.Label(" October 21, 2019", name="title")
ui.Spacer(width=30)
def build_window(self):
""" build the window for the Class"""
self._window = ui.Window("Brick Sun Study", width=800, height=250, flags=ui.WINDOW_FLAGS_NO_TITLE_BAR)
with self._window.frame:
with ui.VStack():
with ui.HStack(height=20):
ui.Label("Styling : ", alignment=ui.Alignment.RIGHT_CENTER)
ui.Button("Light Mode", clicked_fn=lambda b=None: self.set_style_light(b))
ui.Button("Dark Mode", clicked_fn=lambda b=None: self.set_style_dark(b))
ui.Spacer()
ui.Spacer(height=10)
self._window_Frame = ui.ScrollingFrame(
style=LIGHT_WINDOW_STYLE,
name="canvas",
height=200,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
)
with self._window_Frame:
with ui.VStack(height=0):
# Build the toolbar for the window
self._build_title_bar()
ui.Spacer(height=10)
# build the custom slider
self._build_custom_slider()
ui.Spacer(height=10)
self._build_control_bar()
# botton Padding
ui.Spacer(height=10)
return self._window
| 16,391 | Python | 40.498734 | 119 | 0.532426 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/window_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation for Windows"""
from .doc_page import DocPage
from omni import ui
from omni.ui import color as cl
import inspect
import json
import carb.settings
SPACING = 5
def popup_example(self):
class StrModel(ui.AbstractValueModel):
def __init__(self, **kwargs):
super().__init__()
self.__str = ""
self.__parent = None
self.__window = None
self.__frame = None
self.__tooltips = ["Hello", "World", "Hello World"]
self.__kwargs = kwargs
def set_parent(self, parent):
self.__parent = parent
def set_value(self, value):
self.__str = str(value)
self._value_changed()
self._set_tips()
def get_value_as_string(self):
return self.__str
def begin_edit(self):
if self.__window and self.__window.visible:
return
# Create and show the window with field and list of tips
self.__window = ui.Window("0", **self.__kwargs)
with self.__window.frame:
with ui.VStack(width=0, height=0):
width = self.__parent.computed_content_width
# Field with the same model
field = ui.StringField(self, width=width)
field.focus_keyboard()
self.__frame = ui.Frame()
self.__window.position_x = self.__parent.screen_position_x
self.__window.position_y = self.__parent.screen_position_y
self._set_tips()
def _set_tips(self):
"""Generates list of tips"""
if not self.__frame:
return
found = False
with self.__frame:
with ui.VStack():
for t in self.__tooltips:
if self.__str and self.__str in t:
ui.Button(t)
found = True
if not found:
for t in self.__tooltips:
ui.Button(t)
def destroy(self):
self.__parent = None
self.__frame = None
self.__window = None
window_args = {
"flags": ui.WINDOW_FLAGS_POPUP | ui.WINDOW_FLAGS_NO_TITLE_BAR,
"auto_resize": True,
"padding_x": 0,
"padding_y": 0,
}
self._model = StrModel(**window_args)
self._field = ui.StringField(self._model)
self._model.set_parent(self._field)
class WindowDoc(DocPage):
""" document Windows classes"""
def __init__(self, extension_path):
super().__init__(extension_path)
self._window_example = None
self._modal_window_example = None
self._no_close_window_example = None
self._style_window_example = None
self._simple_toolbar = None
self._rotating_toolbar = None
self._toolbar_rotation = ui.DockPosition.BOTTOM
self._modal_test = []
self._model = None
def clean(self):
self._model = None
def build_toolbar(self):
"""Caled to load the extension"""
def top_toolbar_changeAxis(frame, axis):
with frame:
stack = None
if axis == ui.ToolBarAxis.X:
stack = ui.HStack(spacing=15, height=24)
else:
stack = ui.VStack(spacing=15, height=24)
with stack:
ui.Spacer()
ui.Image("resources/icons/Select_model_64.png", width=24, height=24)
ui.Image("resources/icons/Move_64.png", width=24, height=24)
ui.Image("resources/icons/Rotate_global.png", width=24, height=24)
ui.Image("resources/icons/Scale_64.png", width=24, height=24)
ui.Image("resources/icons/Snap_64.png", width=24, height=24)
ui.Spacer()
self._top_toolbar = ui.ToolBar("UI ToolBar", noTabBar=False, padding_x=0, padding_y=0)
self._top_toolbar.set_axis_changed_fn(
lambda axis, frame=self._top_toolbar.frame: top_toolbar_changeAxis(frame, axis)
)
top_toolbar_changeAxis(self._top_toolbar.frame, ui.ToolBarAxis.X)
self._right_toolbar = ui.ToolBar("Right Size ToolBar", noTabBar=True, padding_x=5, padding_y=0)
with self._right_toolbar.frame:
with ui.VStack(spacing=15, width=25):
ui.Spacer(height=1)
ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20)
ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20)
ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20)
ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20)
ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20)
ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20)
ui.Image("resources/icons/SunStudy_64.png", width=20, height=20)
ui.Spacer()
self._left_toolbar = ui.ToolBar("Left Size ToolBar", noTabBar=True, padding_x=5, padding_y=0)
with self._left_toolbar.frame:
with ui.VStack(spacing=0):
ui.Spacer(height=10)
ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20)
ui.Spacer()
self._bottom_toolbar = ui.ToolBar("Bottom ToolBar", noTabBar=True, padding_x=0, padding_y=0)
with self._bottom_toolbar.frame:
with ui.HStack(height=18):
ui.Spacer()
with ui.ZStack(width=200, height=15):
ui.Rectangle(
width=120,
style={"background_color": cl("#809EAB"), "corner_flag": ui.CornerFlag.LEFT, "border_radius": 2},
)
ui.Rectangle(
width=200,
style={
"background_color": cl.transparent,
"border_color": cl("#222222"),
"border_width": 1.0,
"border_radius": 2,
},
)
ui.Label("FPS 30", style={"color": cl.white, "margin_width": 10, "font_size": 8})
ui.Spacer()
self._bottom_toolbar.dock_in_window("Viewport", ui.DockPosition.BOTTOM)
self._top_toolbar.dock_in_window("Viewport", ui.DockPosition.TOP)
self._left_toolbar.dock_in_window("Viewport", ui.DockPosition.LEFT)
self._right_toolbar.dock_in_window("Viewport", ui.DockPosition.RIGHT)
# TODO omni.ui: restore functionality for Kit Next
self._settings = carb.settings.get_settings()
self._settings.set("/app/docks/autoHideTabBar", True)
self._settings.set("/app/docks/noWindowMenuButton", False)
self._settings.set("app/window/showStatusBar", False)
self._settings.set("app/window/showStatusBar", False)
self._settings.set("/app/viewport/showSettingsMenu", True)
self._settings.set("/app/viewport/showCameraMenu", False)
self._settings.set("/app/viewport/showRendererMenu", True)
self._settings.set("/app/viewport/showHideMenu", True)
self._settings.set("/app/viewport/showLayerMenu", False)
def create_and_show_window(self):
if not self._window_example:
self._window_example = ui.Window("Example Window", width=300, height=300)
button_size = None
button_dock = None
with self._window_example.frame:
with ui.VStack():
ui.Button("click me")
button_size = ui.Button("")
def move_me(window):
window.setPosition(200, 200)
def size_me(window):
window.width = 300
window.height = 300
ui.Button("move to 200,200", clicked_fn=lambda w=self._window_example: move_me(w))
ui.Button("set size 300,300", clicked_fn=lambda w=self._window_example: size_me(w))
button_dock = ui.Button("Undocked")
def update_button(window, button):
computed_width = (int)(button.computed_width)
computed_height = (int)(button.computed_height)
button.text = (
"Window size is {:.1f} x {:.1f}\n".format(window.width, window.height)
+ "Window position is {:.1f} x {:.1f}\n".format(window.position_x, window.position_y)
+ "Button size is {:.1f} x {:.1f}".format(computed_width, computed_height)
)
def update_docking(docked, button):
button.text = "Docked" if docked else "Undocked"
for fn in [
self._window_example.set_width_changed_fn,
self._window_example.set_height_changed_fn,
self._window_example.set_position_x_changed_fn,
self._window_example.set_position_y_changed_fn,
]:
fn(lambda value, b=button_size, w=self._window_example: update_button(w, b))
self._window_example.set_docked_changed_fn(lambda value, b=button_dock: update_docking(value, b))
self._window_example.visible = True
def close_modal_window_me(self):
if self._modal_window_example:
self._modal_window_example.visible = False
def create_and_show_modal_window(self):
if not self._modal_window_example:
window_flags = ui.WINDOW_FLAGS_NO_RESIZE
window_flags |= ui.WINDOW_FLAGS_NO_SCROLLBAR
window_flags |= ui.WINDOW_FLAGS_MODAL
self._modal_window_example = ui.Window("Example Modal Window", width=200, height=200, flags=window_flags)
with self._modal_window_example.frame:
with ui.VStack():
ui.Button("I am Modal")
ui.Button("You Can't Click outsite ")
ui.Button("click here to close me", height=100, clicked_fn=self.close_modal_window_me)
self._modal_window_example.visible = True
def create_and_show_window_no_close(self):
if not self._no_close_window_example:
window_flags = ui.WINDOW_FLAGS_NO_CLOSE
self._no_close_window_example = ui.Window(
"Example Modal Window",
width=400,
height=200,
flags=window_flags,
visibility_changed_fn=self._update_window_visible,
)
with self._no_close_window_example.frame:
with ui.VStack():
ui.Button("I dont have Close button")
ui.Button("my Size is 400x200 ")
def close_me(window):
if window:
window.visible = False
ui.Button(
"click here to close me",
height=100,
clicked_fn=lambda w=self._no_close_window_example: close_me(w),
)
self._no_close_window_example.visible = True
def create_styled_window(self):
if not self._style_window_example:
self._style_window_example = ui.Window("Styled Window Example", width=300, height=300)
self._style_window_example.frame.set_style(
{
"Window": {
"background_color": cl.blue,
"border_radius": 10,
"border_width": 5,
"border_color": cl.red,
}
}
)
with self._style_window_example.frame:
with ui.VStack():
ui.Button("I am a Styled Window")
ui.Spacer(height=10)
ui.Button(
"""Style is attached to 'Window'
{"Window": {"background_color": cl.blue,
"border_radius": 10,
"border_width": 5,
"border_color": cl.red}""",
height=200,
)
self._style_window_example.visible = True
def _update_window_visible(self, value):
self._window_checkbox.model.set_value(value)
def create_simple_toolbar(self):
if self._simple_toolbar:
self._simple_toolbar.visible = not self._simple_toolbar.visible
else:
self._simple_toolbar = ui.ToolBar("simple toolbar", noTabBar=True)
with self._simple_toolbar.frame:
with ui.HStack(spacing=15, height=28):
ui.Spacer()
ui.Image("resources/icons/Select_model_64.png", width=24, height=24)
ui.Image("resources/icons/Move_64.png", width=24, height=24)
ui.Image("resources/icons/Rotate_global.png", width=24, height=24)
ui.Image("resources/icons/Scale_64.png", width=24, height=24)
ui.Image("resources/icons/Snap_64.png", width=24, height=24)
ui.Spacer()
self._simple_toolbar.dock_in_window("Viewport", ui.DockPosition.TOP)
self._simple_toolbar.frame.set_style({"Window": {"background_color": cl("#DDDDDD")}})
def create_rotating_toolbar(self):
if not self._rotating_toolbar:
def toolbar_changeAxis(frame, axis):
with frame:
stack = None
if axis == ui.ToolBarAxis.X:
stack = ui.HStack(spacing=15, height=30)
else:
stack = ui.VStack(spacing=15, width=30)
with stack:
ui.Spacer()
ui.Image("resources/icons/Select_model_64.png", width=24, height=24)
ui.Image("resources/icons/Move_64.png", width=24, height=24)
ui.Image("resources/icons/Rotate_global.png", width=24, height=24)
ui.Image("resources/icons/Scale_64.png", width=24, height=24)
ui.Image("resources/icons/Snap_64.png", width=24, height=24)
ui.Spacer()
self._rotating_toolbar = ui.ToolBar("Rotating ToolBar", noTabBar=False, padding_x=5, padding_y=5, margin=5)
self._rotating_toolbar.set_axis_changed_fn(
lambda axis, frame=self._rotating_toolbar.frame: toolbar_changeAxis(frame, axis)
)
toolbar_changeAxis(self._rotating_toolbar.frame, ui.ToolBarAxis.X)
if self._toolbar_rotation == ui.DockPosition.RIGHT:
self._toolbar_rotation = ui.DockPosition.BOTTOM
else:
self._toolbar_rotation = ui.DockPosition.RIGHT
self._rotating_toolbar.dock_in_window("Viewport", self._toolbar_rotation)
def create_doc(self, navigate_to=None):
self._section_title("Windows")
self._text(
"With omni ui you can create a varierty of Window type and style"
" the main Window type are floating window that can optionally be docked into the Main Window.\n"
"There are also other type of window like ToolBar, DialogBox, Etc that you can use"
)
self._caption("Window", navigate_to)
self._text("This class is used to construct a regular Window")
with ui.ScrollingFrame(height=350, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF):
with ui.VStack(height=0):
with ui.HStack(width=0):
ui.Button("click for window Example", width=180, clicked_fn=self.create_and_show_window)
ui.Label("this create a regular Window", name="text", width=180, style={"margin_width": 10})
ui.Label(
"""
ui.Window("Example Window",
position_x=100,
position_y=100)""",
name="text",
)
with ui.HStack(width=0):
ui.Button("Window without close", width=180, clicked_fn=self.create_and_show_window_no_close)
self._window_checkbox = ui.CheckBox(style={"margin": 5})
# this Tie the window visibility with the checkox
def update_check_box(value, self):
self._no_close_window_example.visible = value
self._window_checkbox.model.add_value_changed_fn(
lambda a, this=self: update_check_box(a.get_value_as_bool(), self)
)
ui.Label("this create a regular Window", name="text", width=150, style={"margin_width": 10})
ui.Label('ui.Window("Example Window", )', name="text")
# Modal example is off because there are few issue but this MR need to go in
with ui.HStack(width=0):
ui.Button("click for Custom Window", width=180, clicked_fn=self.create_and_show_modal_window)
ui.Label("this create a custom Window", name="text", width=180, style={"margin_width": 10})
ui.Label(
"window_flags = ui.WINDOW_FLAGS_NO_COLLAPSE\n"
"window_flags |= ui.WINDOW_FLAGS_NO_RESIZE\n"
"window_flags |= ui.WINDOW_FLAGS_NO_CLOSE\n"
"window_flags |= ui.WINDOW_FLAGS_NO_SCROLLBAR\n"
"window_flags |= ui.WINDOW_FLAGS_NO_TITLE_BAR\n\n"
"ui.Window('Example Window', flags=window_flags",
name="text",
)
with ui.HStack(width=0):
ui.Button("click for Styled Window", width=180, clicked_fn=self.create_styled_window)
ui.Spacer(width=20)
ui.Label(
"""
self._style_window_example = ui.Window("Styled Window Example", width=300, height=300)
self._style_window_example.frame.set_style({"Window": {"background_color": cl.blue,
"border_radius": 10,
"border_width": 5,
"border_color": cl.red})
with self._style_window_example.frame:
with ui.VStack():
ui.Button("I am a Styled Window")
ui.Button("Style is attached to 'Window'", height=200)""",
name="text",
)
self._text("All the Window Flags")
self._text(
""" WINDOW_FLAGS_NONE
WINDOW_FLAGS_NO_TITLE_BAR
WINDOW_FLAGS_NO_RESIZE
WINDOW_FLAGS_NO_MOVE
WINDOW_FLAGS_NO_SCROLLBAR
WINDOW_FLAGS_NO_COLLAPSE
WINDOW_FLAGS_NO_SAVED_SETTINGS
WINDOW_FLAGS_SHOW_HORIZONTAL_SCROLLBAR
WINDOW_FLAGS_FORCE_VERTICAL_SCROLLBAR
WINDOW_FLAGS_FORCE_HORIZONTAL_SCROLLBAR
WINDOW_FLAGS_NO_FOCUS_ON_APPEARING
WINDOW_FLAGS_NO_CLOSE
"""
)
self._text("Available Window Properties, call can be used in the constructor")
self._text(
""" title : set the title for the window
visible: set the window to be visible or not
frame: read only property to get the frame of the window
padding_x: padding on the window around the Frame
padding_y: padding on the window around the Frame
flags: the window flags, not that you can pass then on the constructor but also change them after !
"""
)
self._caption("ToolBar", navigate_to)
with ui.ScrollingFrame(height=60, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF):
with ui.VStack(height=0):
with ui.HStack(width=0):
ui.Button("ToolBar Example", width=180, clicked_fn=self.create_simple_toolbar)
ui.Label("this create a ToolBar Docked at the top", name="text", width=280)
ui.Label("""ui.ToolBar("Awesome ToolBar", noTabBar=True)""", name="text")
with ui.HStack(width=0):
ui.Button("Axis changing ToolBar Example", width=180, clicked_fn=self.create_rotating_toolbar)
ui.Label("see how the orientation of the toolbar can change", name="text", width=280)
ui.Label("""ui.ToolBar("Awesome ToolBar")""", name="text")
self._text(
"This file contain a very complete example of many type of toolbar\n" "location is " + __file__ + "\n"
)
self._caption("Multiple Modal Windows", navigate_to)
self._text(
"Omni::UI supports the conception of multiple modal windows. When the new modal window is created, it "
"makes other modal windows inactive. And when it's destroyed, the previous modal window becomes active, "
"blocking all other windows."
)
ui.Button("Multiple Modal Windows", clicked_fn=self._on_modal_in_modal_clicked)
self._caption("Overlay Other Windows", navigate_to)
self._text(
"When creating two windows with the same title, only one window will be displayed, and it will contain "
"the widgets from both windows. This ability allows for overlaying omni.ui Widgets to any ImGui window. "
"For example, it's possible to add a button to the viewport with creating a new window with the title "
'"Viewport".'
)
def overlay_viewport(self):
self._overlay_window = None
def create_overlay_window(self):
if self._overlay_window:
self._overlay_window = None
else:
self._overlay_window = ui.Window("Viewport")
with self._overlay_window.frame:
with ui.HStack():
ui.Spacer()
ui.Label("Hello World", width=0)
ui.Spacer()
self._overaly_button = ui.Button(
"Create or Remove Viewport Label",
style=self._style_system,
clicked_fn=lambda: create_overlay_window(self),
)
overlay_viewport(self)
self._code(inspect.getsource(overlay_viewport).split("\n", 1)[-1])
self._caption("Workspace", navigate_to)
class WindowItem(ui.AbstractItem):
def __init__(self, window):
super().__init__()
# Don't keep the window because it prevents the window from closing.
self._window_title = window.title
self.title_model = ui.SimpleStringModel(self._window_title)
self.type_model = ui.SimpleStringModel(type(window).__name__)
@property
def window(self):
return ui.Workspace.get_window(self._window_title)
class WindowModel(ui.AbstractItemModel):
def __init__(self):
super().__init__()
self._root = ui.SimpleStringModel("Windows")
self.update()
def update(self):
self._children = [WindowItem(i) for i in ui.Workspace.get_windows()]
self._item_changed(None)
def get_item_children(self, item):
if item is not None:
return []
return self._children
def get_item_value_model_count(self, item):
return 2
def get_item_value_model(self, item, column_id):
if item is None:
return self._root
if column_id == 0:
return item.title_model
if column_id == 1:
return item.type_model
self._window_model = WindowModel()
self._tree_left = None
self._tree_right = None
with ui.VStack(style=self._style_system):
ui.Button("Refresh", clicked_fn=lambda: self._window_model.update())
with ui.HStack():
ui.Button("Clear", clicked_fn=ui.Workspace.clear)
ui.Button("Focus", clicked_fn=lambda: self._focus(self._tree_left.selection))
with ui.HStack():
ui.Button("Visibile", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, True))
ui.Button("Invisibile", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, False))
ui.Button("Toggle Visibility", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, None))
with ui.HStack():
ui.Button(
"Dock Right",
clicked_fn=lambda: self._dock(
self._tree_left.selection, self._tree_right.selection, ui.DockPosition.RIGHT
),
)
ui.Button(
"Dock Left",
clicked_fn=lambda: self._dock(
self._tree_left.selection, self._tree_right.selection, ui.DockPosition.LEFT
),
)
ui.Button(
"Dock Top",
clicked_fn=lambda: self._dock(
self._tree_left.selection, self._tree_right.selection, ui.DockPosition.TOP
),
)
ui.Button(
"Dock Bottom",
clicked_fn=lambda: self._dock(
self._tree_left.selection, self._tree_right.selection, ui.DockPosition.BOTTOM
),
)
ui.Button(
"Dock Same",
clicked_fn=lambda: self._dock(
self._tree_left.selection, self._tree_right.selection, ui.DockPosition.SAME
),
)
ui.Button("Undock", clicked_fn=lambda: self._undock(self._tree_left.selection))
with ui.HStack():
ui.Button("Move Left", clicked_fn=lambda: self._left(self._tree_left.selection))
ui.Button("MoveRight", clicked_fn=lambda: self._right(self._tree_left.selection))
with ui.HStack():
ui.Button(
"Reverse Docking Tabs of Neighbours",
clicked_fn=lambda: self._dock_reorder(self._tree_left.selection),
)
ui.Button("Hide Tabs", clicked_fn=lambda: self._tabs(self._tree_left.selection, False))
ui.Button("Show Tabs", clicked_fn=lambda: self._tabs(self._tree_left.selection, True))
with ui.HStack(height=400):
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
):
self._tree_left = ui.TreeView(self._window_model, column_widths=[ui.Fraction(1), 80])
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
):
self._tree_right = ui.TreeView(self._window_model, column_widths=[ui.Fraction(1), 80])
self._caption("Popup", navigate_to)
self._text(
"The Popup window is a window that disappears when the user clicks outside of the window. To create a popup "
"window, it's necessary to use the flag ui.WINDOW_FLAGS_POPUP. It's very useful for creating a menu with "
"custom widgets inside."
)
self._text("Start typing for popup")
popup_example(self)
self._code(inspect.getsource(popup_example).split("\n", 1)[-1])
# some padding at the bottom
ui.Spacer(height=100)
def _undock(self, selection):
if not selection:
return
for item in selection:
item.window.undock()
def _dock(self, left, right, position):
if not left or not right:
return
target = right[0].window
for item in left:
item.window.dock_in(target, position)
def _left(self, selection):
if not selection:
return
for item in selection:
item.window.position_x -= 100
def _right(self, selection):
if not selection:
return
for item in selection:
item.window.position_x += 100
def _set_visibility(self, selection, visible):
if not selection:
return
for item in selection:
if visible is not None:
item.window.visible = visible
else:
item.window.visible = not item.window.visible
def _dock_reorder(self, selection):
if not selection:
return
docking_groups = [ui.Workspace.get_docked_neighbours(item.window) for item in selection]
for group in docking_groups:
# Reverse order
for i, window in enumerate(reversed(group)):
window.dock_order = i
def _on_modal_in_modal_clicked(self):
def close_me(id):
self._modal_test[id].visible = False
def put_on_front(id):
if not self._modal_test[id]:
return
self._modal_test[id].set_top_modal()
def toggle(id):
if not self._modal_test[id]:
return
self._modal_test[id].visible = not self._modal_test[id].visible
window_id = len(self._modal_test)
prev_id = max(0, window_id - 1)
window_flags = ui.WINDOW_FLAGS_NO_RESIZE
window_flags |= ui.WINDOW_FLAGS_NO_SCROLLBAR
window_flags |= ui.WINDOW_FLAGS_MODAL
modal_window = ui.Window(f"Modal Window #{window_id}", width=200, height=200, flags=window_flags)
self._modal_test.append(modal_window)
with modal_window.frame:
with ui.VStack(height=0):
ui.Label(f"This is the window #{window_id}")
ui.Button("One Modal More", clicked_fn=self._on_modal_in_modal_clicked)
ui.Button(f"Bring #{prev_id} To Top", clicked_fn=lambda id=prev_id: put_on_front(id))
ui.Button(f"Toggle visibility of #{prev_id}", clicked_fn=lambda id=prev_id: toggle(id))
ui.Button("Close", clicked_fn=lambda id=window_id: close_me(id))
| 31,379 | Python | 40.618037 | 121 | 0.541445 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/image_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation for Images"""
from omni import ui
from .doc_page import DocPage
import inspect
SPACING = 5
def image_hot_switch():
styles = [
{
"": {"image_url": "resources/icons/Nav_Walkmode.png"},
":hovered": {"image_url": "resources/icons/Nav_Flymode.png"},
},
{
"": {"image_url": "resources/icons/Move_local_64.png"},
":hovered": {"image_url": "resources/icons/Move_64.png"},
},
{
"": {"image_url": "resources/icons/Rotate_local_64.png"},
":hovered": {"image_url": "resources/icons/Rotate_global.png"},
},
]
def set_image(model, image):
value = model.get_item_value_model().get_value_as_int()
image.set_style(styles[value])
image = ui.Image(width=64, height=64, style=styles[0])
with ui.HStack(width=ui.Percent(50)):
ui.Label("Select a texture to display", name="text")
model = ui.ComboBox(0, "Navigation", "Move", "Rotate").model
model.add_item_changed_fn(lambda m, i, im=image: set_image(m, im))
class ImageDoc(DocPage):
""" document for Image"""
def create_doc(self, navigate_to=None):
self._section_title("Image")
self._text("The Image type displays an image.")
self._text("The source of the image is specified as a URL using the source property.")
self._text(
"By default, specifying the width and height of the item causes the image to be scaled to that size. This "
"behavior can be changed by setting the fill_mode property, allowing the image to be stretched or scaled "
"instead. The property alignment controls where to align the scaled image."
)
code_width = 320
image_source = "resources/desktop-icons/omniverse_512.png"
with ui.VStack():
self._image_table(
f"""ui.Image(
'{image_source}',
fill_policy=ui.FillPolicy.STRETCH)""",
"(Default) The image is scaled to fit, the alignment is ignored",
code_width=code_width,
)
self._image_table(
f"""ui.Image(
'{image_source}',
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
alignment=ui.Alignment.LEFT_CENTER)""",
"The image is scaled uniformly to fit without cropping and aligned to the left",
code_width=code_width,
)
self._image_table(
f"""ui.Image(
'{image_source}',
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
alignment=ui.Alignment.CENTER)""",
"The image is scaled uniformly to fit without cropping and aligned to the center",
code_width=code_width,
)
self._image_table(
f"""ui.Image(
'{image_source}',
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
alignment=ui.Alignment.RIGHT_CENTER)""",
"The image is scaled uniformly to fit without croppingt and aligned to right",
code_width=code_width,
)
self._image_table(
f"""ui.Image(
'{image_source}',
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP,
alignment=ui.Alignment.CENTER_TOP)""",
"The image is scaled uniformly to fill, cropping if necessary and aligned to the top",
code_width=code_width,
)
self._image_table(
f"""ui.Image(
'{image_source}',
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP,
alignment=ui.Alignment.CENTER)""",
"The image is scaled uniformly to fill, cropping if necessary and centered",
code_width=code_width,
)
self._image_table(
f"""ui.Image(
'{image_source}',
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP,
alignment=ui.Alignment.CENTER_BOTTOM)""",
"The image is scaled uniformly to fill, cropping if necessary and aligned to the bottom",
code_width=code_width,
)
self._image_table(
f"""ui.Image(
'{image_source}',
fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT,
alignment=ui.Alignment.CENTER,
style={{'border_radius': 10}})""",
"The image has rounded corners",
code_width=code_width,
)
ui.Spacer(height=20)
ui.Line()
ui.Spacer(height=10)
self._text("The Image can use style image_url")
ui.Spacer(height=10)
ui.Line()
ui.Spacer(height=20)
code_width = 470
self._image_table(
f"""ui.Image(style={{'image_url': 'resources/desktop-icons/omniverse_128.png'}})""",
"The image has a styled URL",
code_width=code_width,
)
self._image_table(
f"""with ui.HStack(spacing =5,
style={{"Image":{{'image_url': 'resources/desktop-icons/omniverse_128.png'}}}}):
ui.Image()
ui.Image()
ui.Image()
""",
"The image has a styled URL",
code_width=code_width,
)
self._image_table(
f"""ui.Image(style={{
'image_url': 'resources/desktop-icons/omniverse_128.png',
'alignment': ui.Alignment.RIGHT_CENTER}})""",
"The image has styled Alignment",
code_width=code_width,
)
self._image_table(
f"""ui.Image(style={{
'image_url': 'resources/desktop-icons/omniverse_256.png',
'fill_policy': ui.FillPolicy.PRESERVE_ASPECT_CROP,
'alignment': ui.Alignment.RIGHT_CENTER}})""",
"The image has styled fill_policy",
code_width=code_width,
)
self._text(
"It's possible to set a different image per style state. And switch them depending on the mouse hovering, "
"selection state, etc."
)
image_hot_switch()
self._code(inspect.getsource(image_hot_switch).split("\n", 1)[-1])
ui.Spacer(height=10)
| 7,160 | Python | 39.005586 | 119 | 0.525978 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/layout_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation for Layouts"""
from omni import ui
from omni.ui import color as cl
from .doc_page import DocPage
import inspect
import asyncio
import omni.kit.app
SPACING = 5
def collapsable_simple():
with ui.CollapsableFrame("Header"):
with ui.VStack(height=0):
ui.Button("Hello World")
ui.Button("Hello World")
def collapsable_custom(style_system):
def custom_header(collapsed, title):
with ui.HStack(style=style_system):
with ui.ZStack(width=30):
ui.Circle(name="title")
with ui.HStack():
ui.Spacer()
align = ui.Alignment.V_CENTER
ui.Line(name="title", width=6, alignment=align)
ui.Spacer()
if collapsed:
with ui.VStack():
ui.Spacer()
align = ui.Alignment.H_CENTER
ui.Line(name="title", height=6, alignment=align)
ui.Spacer()
ui.Label(title, name="title")
style = {
"CollapsableFrame": {
"background_color": cl.transparent,
"secondary_color": cl.transparent,
"border_radius": 0,
"border_color": cl("#B2B2B2"),
"border_width": 0.5,
},
"CollapsableFrame:hovered": {"secondary_color": cl("#E5F1FB")},
"CollapsableFrame:pressed": {"secondary_color": cl("#CCE4F7")},
"Label::title": {"color": cl.black},
"Circle::title": {
"color": cl.black,
"background_color": cl.transparent,
"border_color": cl("#B2B2B2"),
"border_width": 0.75,
},
"Line::title": {"color": cl("#666666"), "border_width": 1},
}
style.update(style_system)
with ui.CollapsableFrame("Header", build_header_fn=custom_header, style=style):
with ui.VStack(height=0):
ui.Button("Hello World")
ui.Button("Hello World")
def collapsable_layout(style_system):
style = {
"CollapsableFrame": {
"border_color": cl("#005B96"),
"border_radius": 4,
"border_width": 2,
"padding": 0,
"margin": 0,
}
}
frame = ui.CollapsableFrame("Header", style=style)
with frame:
with ui.VStack(height=0):
ui.Button("Hello World")
ui.Button("Hello World")
def set_style(field, model, style=style, frame=frame):
frame_style = style["CollapsableFrame"]
frame_style[field] = model.get_value_as_float()
frame.set_style(style)
with ui.HStack():
ui.Label("Padding:", width=ui.Percent(10), name="text")
model = ui.FloatSlider(min=0, max=50).model
model.add_value_changed_fn(lambda m: set_style("padding", m))
with ui.HStack():
ui.Label("Margin:", width=ui.Percent(10), name="text")
model = ui.FloatSlider(min=0, max=50).model
model.add_value_changed_fn(lambda m: set_style("margin", m))
def direction():
def rotate(dirs, stack, label):
dirs[0] = (dirs[0] + 1) % len(dirs[1])
stack.direction = dirs[1][dirs[0]]
label.text = str(stack.direction)
dirs = [
0,
[
ui.Direction.LEFT_TO_RIGHT,
ui.Direction.RIGHT_TO_LEFT,
ui.Direction.TOP_TO_BOTTOM,
ui.Direction.BOTTOM_TO_TOP,
],
]
stack = ui.Stack(ui.Direction.LEFT_TO_RIGHT, width=0, height=0)
with stack:
for name in ["One", "Two", "Three", "Four"]:
ui.Button(name)
with ui.HStack():
with ui.HStack():
ui.Label("Current direcion is ", name="text", width=0)
label = ui.Label("", name="text")
button = ui.Button("Change")
button.set_clicked_fn(lambda d=dirs, s=stack, l=label: rotate(d, s, l))
rotate(dirs, stack, label)
def recreate(self):
self._recreate_ui = ui.Frame(height=40)
def changed(model, recreate_ui=self._recreate_ui):
with recreate_ui:
with ui.HStack():
for i in range(model.get_value_as_int()):
ui.Button(f"Button #{i}")
model = ui.IntDrag(min=0, max=10).model
self._sub_recreate = model.subscribe_value_changed_fn(changed)
def clipping(self):
self._clipping_frame = ui.Frame()
with self._clipping_frame:
ui.Button("Hello World")
def set_width(model):
self._clipping_frame.width = ui.Pixel(model.as_float)
def set_height(model):
self._clipping_frame.height = ui.Pixel(model.as_float)
def set_hclipping(model):
self._clipping_frame.horizontal_clipping = model.as_bool
def set_vclipping(model):
self._clipping_frame.horizontal_clipping = model.as_bool
width = ui.FloatDrag(min=50, max=1000).model
height = ui.FloatDrag(min=50, max=1000).model
hclipping = ui.ToolButton(text="HClipping").model
vclipping = ui.ToolButton(text="VClipping").model
self._width = width.subscribe_value_changed_fn(set_width)
self._height = height.subscribe_value_changed_fn(set_height)
self._hclipping = hclipping.subscribe_value_changed_fn(set_hclipping)
self._vclipping = vclipping.subscribe_value_changed_fn(set_vclipping)
width.set_value(100)
height.set_value(100)
def visibility():
def invisible(button):
button.visible = False
def visible(buttons):
for button in buttons:
button.visible = True
buttons = []
with ui.HStack():
for n in ["One", "Two", "Three", "Four", "Five"]:
button = ui.Button(n, width=0)
button.set_clicked_fn(lambda b=button: invisible(b))
buttons.append(button)
ui.Spacer()
button = ui.Button("Visible all", width=0)
button.set_clicked_fn(lambda b=buttons: visible(b))
def vgrid():
with ui.ScrollingFrame(
height=425,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
):
with ui.VGrid(column_width=100, row_height=100):
for i in range(100):
with ui.ZStack():
ui.Rectangle(
style={
"border_color": cl.black,
"background_color": cl.white,
"border_width": 1,
"margin": 0,
}
)
ui.Label(f"{i}", style={"margin": 5})
def hgrid():
with ui.ScrollingFrame(
height=425,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
):
with ui.HGrid(column_width=100, row_height=100):
for i in range(100):
with ui.ZStack():
ui.Rectangle(
style={
"border_color": cl.black,
"background_color": cl.white,
"border_width": 1,
"margin": 0,
}
)
ui.Label(f"{i}", style={"margin": 5})
def placer_track(self, id):
# Initial size
BEGIN = 50 + 100 * id
END = 120 + 100 * id
HANDLE_WIDTH = 10
class EditScope:
"""The class to avoid circular event calling"""
def __init__(self):
self.active = False
def __enter__(self):
self.active = True
def __exit__(self, type, value, traceback):
self.active = False
def __bool__(self):
return not self.active
class DoLater:
"""A helper to collect data and process it one frame later"""
def __init__(self):
self.__task = None
self.__data = []
def do(self, data):
# Collect data
self.__data.append(data)
# Update in the next frame. We need it because we want to accumulate the affected prims
if self.__task is None or self.__task.done():
self.__task = asyncio.ensure_future(self.__delayed_do())
async def __delayed_do(self):
# Wait one frame
await omni.kit.app.get_app().next_update_async()
print(f"In the previous frame the user clicked the rectangles: {self.__data}")
self.__data.clear()
self.edit = EditScope()
self.dolater = DoLater()
def start_moved(start, body, end):
if not self.edit:
# Something already edits it
return
with self.edit:
body.offset_x = start.offset_x
rect.width = ui.Pixel(end.offset_x - start.offset_x + HANDLE_WIDTH)
def body_moved(start, body, end, rect):
if not self.edit:
# Something already edits it
return
with self.edit:
start.offset_x = body.offset_x
end.offset_x = body.offset_x + rect.width.value - HANDLE_WIDTH
def end_moved(start, body, end, rect):
if not self.edit:
# Something already edits it
return
with self.edit:
body.offset_x = start.offset_x
rect.width = ui.Pixel(end.offset_x - start.offset_x + HANDLE_WIDTH)
with ui.ZStack(height=30):
# Body
body = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=BEGIN)
with body:
rect = ui.Rectangle(width=END - BEGIN + HANDLE_WIDTH)
rect.set_mouse_pressed_fn(lambda x, y, b, m, id=id: self.dolater.do(id))
# Left handle
start = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=BEGIN)
with start:
ui.Rectangle(width=HANDLE_WIDTH, style={"background_color": cl("#FF660099")})
# Right handle
end = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=END)
with end:
ui.Rectangle(width=HANDLE_WIDTH, style={"background_color": cl("#FF660099")})
# Connect them together
start.set_offset_x_changed_fn(lambda _, s=start, b=body, e=end: start_moved(s, b, e))
body.set_offset_x_changed_fn(lambda _, s=start, b=body, e=end, r=rect: body_moved(s, b, e, r))
end.set_offset_x_changed_fn(lambda _, s=start, b=body, e=end, r=rect: end_moved(s, b, e, r))
def placer_percents(self):
# The size of the rectangle
SIZE = 20.0
with ui.ZStack(height=300):
# Background
ui.Rectangle(style={"background_color": cl("#999999")})
# Small rectangle
p = ui.Percent(50)
placer = ui.Placer(draggable=True, offset_x=p, offset_y=p)
with placer:
ui.Rectangle(width=SIZE, height=SIZE)
def clamp_x(offset):
if offset.value < 0:
placer.offset_x = ui.Percent(0)
max_per = 100.0 - SIZE / placer.computed_width * 100.0
if offset.value > max_per:
placer.offset_x = ui.Percent(max_per)
def clamp_y(offset):
if offset.value < 0:
placer.offset_y = ui.Percent(0)
max_per = 100.0 - SIZE / placer.computed_height * 100.0
if offset.value > max_per:
placer.offset_y = ui.Percent(max_per)
# Calbacks
placer.set_offset_x_changed_fn(clamp_x)
placer.set_offset_y_changed_fn(clamp_y)
class LayoutDoc(DocPage):
""" document Layout classes"""
def create_doc(self, navigate_to=None):
self._section_title("Layout")
self._text("We have three main components: VStack, HStack, and ZStack.")
self._caption("HStack", navigate_to)
self._text("This class is used to construct horizontal layout objects.")
with ui.HStack():
ui.Button("One")
ui.Button("Two")
ui.Button("Three")
ui.Button("Four")
ui.Button("Five")
self._text("The simplest use of the class is like this:")
self._code(
"""
with ui.HStack():
ui.Button("One")
ui.Button("Two")
ui.Button("Three")
ui.Button("Four")
ui.Button("Five")
"""
)
self._caption("VStack", navigate_to)
self._text("The VStack class lines up widgets vertically.")
with ui.VStack(width=100.0):
with ui.VStack():
ui.Button("One")
ui.Button("Two")
ui.Button("Three")
ui.Button("Four")
ui.Button("Five")
self._text("The simplest use of the class is like this:")
self._code(
"""
with ui.VStack():
ui.Button("One")
ui.Button("Two")
ui.Button("Three")
ui.Button("Four")
ui.Button("Five")
"""
)
self._caption("ZStack", navigate_to)
self._text("A view that overlays its children, aligning them on top of each other.")
with ui.VStack(width=100.0):
with ui.ZStack():
ui.Button("Very Long Text to See How Big it Can Be", height=0)
ui.Button("Another\nMultiline\nButton", width=0)
self._code(
"""
with ui.ZStack():
ui.Button("Very Long Text to See How Big it Can Be", height=0)
ui.Button("Another\\nMultiline\\nButton", width=0)
"""
)
self._caption("Spacing", navigate_to)
self._text("Spacing is a non-stretchable space in pixels between child items of the layout.")
def set_spacing(stack, spacing):
stack.spacing = spacing
spacing_stack = ui.HStack(style={"margin": 0})
with spacing_stack:
for name in ["One", "Two", "Three", "Four"]:
ui.Button(name)
with ui.HStack(spacing=SPACING):
with ui.HStack(width=100):
ui.Spacer()
ui.Label("spacing", width=0, name="text")
with ui.HStack(width=ui.Percent(20)):
field = ui.FloatField(width=50)
slider = ui.FloatSlider(min=0, max=50, style={"color": cl.transparent})
# Link them together
slider.model = field.model
slider.model.add_value_changed_fn(lambda m, s=spacing_stack: set_spacing(s, m.get_value_as_float()))
self._code(
"""
def set_spacing(stack, spacing):
stack.spacing = spacing
ui.Spacer(height=SPACING)
spacing_stack = ui.HStack(style={"margin": 0})
with spacing_stack:
for name in ["One", "Two", "Three", "Four"]:
ui.Button(name)
ui.Spacer(height=SPACING)
with ui.HStack(spacing=SPACING):
with ui.HStack(width=100):
ui.Spacer()
ui.Label("spacing", width=0, name="text")
with ui.HStack(width=ui.Percent(20)):
field = ui.FloatField(width=50)
slider = ui.FloatSlider(min=0, max=50, style={"color": cl.transparent})
# Link them together
slider.model = field.model
slider.model.add_value_changed_fn(
lambda m, s=spacing_stack: set_spacing(s, m.get_value_as_float()))
"""
)
self._caption("VGrid", navigate_to)
self._text(
"Grid is a container that arranges its child views in a grid. The grid vertical/horizontal direction is "
"the direction the grid size growing with creating more children."
)
self._text("It has two modes for cell width.")
self._text(" - If the user set column_count, the column width is computed from the grid width.")
self._text(" - If the user sets column_width, the column count is computed.")
self._text("It also has two modes for height.")
self._text(
" - If the user sets row_height, VGrid uses it to set the height for all the cells. It's the fast mode "
"because it's considered that the cell height never changes. VGrid easily predict which cells are visible."
)
self._text(
" - If the user sets nothing, VGrid computes the size of the children. This mode is slower than the "
"previous one, but the advantage is that all the rows can be different custom sizes. VGrid still draws "
"only visible items, but to predict it, it uses cache, which can be big if VGrid has hundreds of "
"thousands of items."
)
vgrid()
self._code(inspect.getsource(vgrid).split("\n", 1)[-1])
self._caption("HGrid", navigate_to)
self._text("HGrid works exactly like VGrid, but with swapped width and height..")
hgrid()
self._code(inspect.getsource(hgrid).split("\n", 1)[-1])
self._caption("Frame", navigate_to)
self._text(
"Frame is a container that can keep only one child. Each child added to Frame overrides the previous one. "
"This feature is used for creating dynamic layouts. The whole layout can be easily recreated with a "
"simple callback. In the following example, the buttons are recreated each time the slider changes."
)
recreate(self)
self._code(inspect.getsource(recreate).split("\n", 1)[-1])
self._text(
"Another feature of Frame is the ability to clip its child. When the content of Frame is bigger than "
"Frame itself, the exceeding part is not drawn if the clipping is on."
)
clipping(self)
self._code(inspect.getsource(clipping).split("\n", 1)[-1])
self._caption("CollapsableFrame", navigate_to)
self._text(
"CollapsableFrame is a frame widget that can hide or show its content. It has two states expanded and "
"collapsed. When it's collapsed, it looks like a button. If it's expanded, it looks like a button and a "
"frame with the content. It's handy to group properties, and temporarily hide them to get more space for "
"something else."
)
collapsable_simple()
self._code(inspect.getsource(collapsable_simple).split("\n", 1)[-1])
self._text("It's possible to use a custom header.")
collapsable_custom(self._style_system)
self._code(inspect.getsource(collapsable_custom).split("\n", 1)[-1])
self._text("The next example demonstrates how padding and margin work in the collapsable frame.")
collapsable_layout(self._style_system)
self._code(inspect.getsource(collapsable_layout).split("\n", 1)[-1])
self._caption("Examples", navigate_to)
with ui.VStack(style=self._style_system):
for i in range(2):
with ui.HStack():
ui.Spacer(width=50)
with ui.VStack(height=0):
ui.Button("Left {}".format(i), height=0)
ui.Button("Vertical {}".format(i), height=50)
with ui.HStack(width=ui.Fraction(2)):
ui.Button("Right {}".format(i))
ui.Button("Horizontal {}".format(i), width=ui.Fraction(2))
ui.Spacer(width=50)
self._code(
"""
with ui.VStack():
for i in range(2):
with ui.HStack():
ui.Spacer()
with ui.VStack(height=0):
ui.Button("Left {}".format(i), height=0)
ui.Button("Vertical {}".format(i), height=50)
with ui.HStack(width=ui.Fraction(2)):
ui.Button("Right {}".format(i))
ui.Button("Horizontal {}".format(i), width=ui.Fraction(2))
ui.Spacer()
"""
)
self._caption("Placer", navigate_to)
self._text(
"Enable you to place a widget presisely with offset. Placer's property `draggable` allows changing "
"the position of the child widget with dragging it with the mouse."
)
with ui.ScrollingFrame(
height=170,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
):
with ui.ZStack():
with ui.HStack():
for index in range(60):
ui.Line(width=10, style={"color": cl.black, "border_width": 0.5}, alignment=ui.Alignment.LEFT)
with ui.VStack():
ui.Line(
height=10,
width=600,
style={"color": cl.black, "border_width": 0.5},
alignment=ui.Alignment.TOP,
)
for index in range(15):
ui.Line(
height=10,
width=600,
style={"color": cl.black, "border_width": 0.5},
alignment=ui.Alignment.TOP,
)
ui.Line(
height=10,
width=600,
style={"color": cl.black, "border_width": 0.5},
alignment=ui.Alignment.TOP,
)
with ui.Placer(offset_x=100, offset_y=10):
ui.Button("moved 100px in X, and 10px in Y", width=0, height=20, name="placed")
with ui.Placer(offset_x=200, offset_y=50):
ui.Button("moved 200px X , and 50 Y", width=0, height=0)
def set_text(widget, text):
widget.text = text
with ui.Placer(draggable=True, offset_x=300, offset_y=100):
ui.Circle(radius=50, width=50, height=50, size_policy=ui.CircleSizePolicy.STRETCH, name="placed")
placer = ui.Placer(draggable=True, drag_axis=ui.Axis.Y, offset_x=400, offset_y=120)
with placer:
with ui.ZStack(width=150, height=40):
ui.Rectangle(name="placed")
with ui.HStack(spacing=5):
ui.Circle(
radius=3,
width=15,
size_policy=ui.CircleSizePolicy.FIXED,
style={"background_color": cl.white},
)
ui.Label("UP / Down", style={"color": cl.white, "font_size": 16.0})
offset_label = ui.Label("120", style={"color": cl.white})
placer.set_offset_y_changed_fn(lambda o: set_text(offset_label, str(o)))
self._code(
"""
with ui.Placer(
draggable=True, offset_x=300, offset_y=100):
ui.Circle(
radius=50,
width=50,
height=50,
size_policy=ui.CircleSizePolicy.STRETCH,
name="placed"
)
placer = ui.Placer(
draggable=True,
drag_axis=ui.Axis.Y,
offset_x=400,
offset_y=120)
with placer:
with ui.ZStack(
width=150,
height=40,
):
ui.Rectangle(name="placed")
with ui.HStack(spacing=5):
ui.Circle(
radius=3,
width=15,
size_policy=ui.CircleSizePolicy.FIXED,
style={"background_color": cl.white},
)
ui.Label(
"UP / Down",
style={
"color": cl.white,
"font_size": 16.0
}
)
offset_label = ui.Label(
"120", style={"color": cl.white})
placer.set_offset_y_changed_fn(
lambda o: set_text(offset_label, str(o)))
"""
)
self._text(
"The following example shows the way to interact between three Placers to create a resizable rectangle. "
"The rectangle can be moved on X-axis and can be resized with small side handles."
)
self._text(
"When multiple widgets fire the callbacks simultaneously, it's possible to collect the event data and "
"process them one frame later using asyncio."
)
with ui.ZStack():
placer_track(self, 0)
placer_track(self, 1)
self._code(inspect.getsource(placer_track).split("\n", 1)[-1])
self._text(
"It's possible to set `offset_x` and `offset_y` in percents. It allows stacking the children to the "
"proportions of the parent widget. If the parent size is changed, then the offset is updated accordingly."
)
placer_percents(self)
self._code(inspect.getsource(placer_percents).split("\n", 1)[-1])
self._caption("Visibility", navigate_to)
self._text(
"This property holds whether the widget is visible. Invisible widget is not rendered, and it doesn't take "
"part in the layout. The layout skips it."
)
self._text("In the following example click the button to hide it.")
visibility()
self._code(inspect.getsource(visibility).split("\n", 1)[-1])
self._caption("Direction", navigate_to)
self._text(
"It's possible to determine the direction of a stack with the property direction. The stack is able to "
"change its direction dynamically."
)
direction()
self._code(inspect.getsource(direction).split("\n", 1)[-1])
ui.Spacer(height=50)
| 26,307 | Python | 34.647696 | 119 | 0.541415 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/canvas_frame_doc.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation for Scrolling Frame"""
from omni import ui
from .doc_page import DocPage
import inspect
SPACING = 5
TEXT = (
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut "
"labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco "
"laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in "
"voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat "
"non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
)
def simple_canvasframe():
IMAGE = "resources/icons/ov_logo_square.png"
with ui.CanvasFrame(height=256):
with ui.VStack(height=0, spacing=10):
ui.Label(TEXT, name="text", word_wrap=True)
ui.Button("Button")
ui.Image(IMAGE, width=128, height=128)
class CanvasFrameDoc(DocPage):
""" document for Menu"""
def create_doc(self, navigate_to=None):
self._section_title("CanvasFrame")
self._text(
"CanvasFrame is the widget that allows the user to pan and zoom its children with a mouse. It has the layout "
"that can be infinitely moved in any direction."
)
with ui.Frame(style=self._style_system):
simple_canvasframe()
self._code(inspect.getsource(simple_canvasframe).split("\n", 1)[-1])
ui.Spacer(height=10)
| 1,903 | Python | 35.615384 | 122 | 0.705202 |
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/doc_page.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The documentation of the omni.ui aka UI Framework"""
# Add imports here that are needed in the _exec_code calls.
from omni import ui
from omni.ui import color as cl
import omni.usd
from pxr import Usd
from pxr import UsdGeom
import subprocess
import sys
SPACING = 5
class DocPage:
"""The Demo extension"""
def __init__(self, extension_path):
self._extension_path = extension_path
self._style_system = {
"Button": {
"background_color": 0xFFE1E1E1,
"border_color": 0xFFADADAD,
"border_width": 0.5,
"border_radius": 0.0,
"margin": 5.0,
"padding": 5.0,
},
"Button.Label": {"color": 0xFF000000},
"Button:hovered": {"background_color": 0xFFFBF1E5, "border_color": 0xFFD77800},
"Button:pressed": {"background_color": 0xFFF7E4CC, "border_color": 0xFF995400, "border_width": 1.0},
}
self._copy_context_menu = ui.Menu("Copy Context menu", name="this")
def clean(self):
"""Should be called when the extesion us unloaded or reloaded"""
pass
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
if button != 1:
return
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.clear()
with self._copy_context_menu:
ui.MenuItem("Copy Code", triggered_fn=lambda t=text: copy_text(t))
# Show it
self._copy_context_menu.show()
def create_doc(self, navigate_to=None):
"""
Class should overide this methods.
Args:
navigate_to: The chapter it's necessary to navigate the scrollbar.
"""
pass
def _text(self, text):
"""Create a formated paragraph of the text"""
ui.Label(text, name="text", word_wrap=True, skip_draw_when_clipped=True)
def _section_title(self, text):
"""Create a title separator"""
with ui.ZStack():
ui.Rectangle(name="section")
ui.Label(text, name="section", alignment=ui.Alignment.CENTER)
def _caption(self, text, navigate_to=None):
"""Create a formated heading"""
with ui.ZStack():
background = ui.Rectangle(name="caption")
if navigate_to == text:
background.scroll_here_y(0.0)
ui.Label(text, name="caption", alignment=ui.Alignment.LEFT_CENTER)
def _code(self, text, elided_text=False):
"""Create a code snippet"""
stack = ui.ZStack()
with stack:
ui.Rectangle(name="code")
label = ui.Label(text, name="code", skip_draw_when_clipped=True, elided_text=elided_text)
if not sys.platform == "linux":
stack.set_mouse_pressed_fn(lambda x, y, b, m, text=text: self._show_copy_menu(x, y, b, m, text))
return label
def _exec_code(self, code):
"""Execute the code and create a snippet"""
# Python magic to capture output of exec
locals_from_execution = {}
exec(f"class Execution():\n def __init__(self):\n{code}", None, locals_from_execution)
self._first = locals_from_execution["Execution"]()
self._code(code)
def _image_table(self, code, description, description_width=ui.Fraction(1), code_width=ui.Fraction(1)):
"""Create a row of the table that demostrates images"""
# TODO: We need to use style padding instead of thousands of spacers
with ui.HStack():
with ui.ZStack(width=140):
ui.Rectangle(name="table")
with ui.HStack():
ui.Spacer(width=SPACING / 2)
with ui.VStack():
ui.Spacer(height=SPACING / 2)
# Execute the provided code
exec(code)
ui.Spacer(height=SPACING / 2)
ui.Spacer(width=SPACING / 2)
with ui.ZStack(width=description_width):
ui.Rectangle(name="table")
with ui.HStack():
ui.Spacer(width=SPACING / 2)
ui.Label(description, style={"margin": 5}, name="text", word_wrap=True)
ui.Spacer(width=SPACING / 2)
with ui.ZStack(width=code_width):
ui.Rectangle(name="table")
with ui.HStack():
ui.Spacer(width=SPACING / 2)
with ui.VStack():
ui.Spacer(height=SPACING / 2)
with ui.ZStack():
ui.Rectangle(name="code")
ui.Label(f"\n\t{code}\n\n", name="code")
ui.Spacer(height=SPACING / 2)
ui.Spacer(width=SPACING / 2)
def _shape_table(self, code, description, row_height=0):
"""Create a row of the table that demostrates images"""
# TODO: We need to use style padding instead of thousands of spacers
with ui.HStack(height=row_height):
with ui.ZStack():
ui.Rectangle(name="table")
# Execute the provided code
with ui.ZStack(name="margin", style={"ZStack::margin": {"margin": SPACING * 2}}):
ui.Rectangle(name="code")
exec(code)
with ui.ZStack(width=ui.Fraction(2)):
ui.Rectangle(name="table")
ui.Label(description, name="text", style={"margin": SPACING}, word_wrap=True)
with ui.ZStack(width=300):
ui.Rectangle(name="table")
with ui.ZStack(name="margin", style={"ZStack::margin": {"margin": SPACING / 2}}):
ui.Rectangle(name="code")
ui.Label(f"\n\t{code}\n\n", name="code")
def _table(self, selector, example, explanatoin, color=None):
"""Create a one row of a table"""
localStyle = {}
if color is not None:
localStyle = {"color": color}
# TODO: We need to use style padding instead of thousands of spacers
with ui.HStack(height=0, style=localStyle):
with ui.ZStack(width=100):
ui.Rectangle(name="table")
with ui.HStack(height=0):
ui.Spacer(width=SPACING)
ui.Label(selector, name="text")
ui.Spacer(width=SPACING)
with ui.ZStack(width=120):
ui.Rectangle(name="table")
with ui.HStack(height=0):
ui.Spacer(width=SPACING)
ui.Label(example, name="text")
ui.Spacer(width=SPACING)
with ui.ZStack():
ui.Rectangle(name="table")
with ui.HStack(height=0):
ui.Spacer(width=SPACING)
ui.Label(explanatoin, name="text", word_wrap=True)
ui.Spacer(width=SPACING)
| 7,721 | Python | 39.857143 | 112 | 0.553685 |
omniverse-code/kit/exts/omni.example.ui/docs/model.md | # Model
The central component of the TreeView widget. It is the application's dynamic
data structure, independent of the user interface, and it directly manages the
nested data. It follows the Model-Dlegate-View pattern closely. It's abstract,
and it defines the standard interface to be able to interoperate with the
components of the model-view architecture. It is not supposed to be instantiated
directly. Instead, the user should subclass it to create a new model.
The item model doesn't return the data itself. Instead, it returns the value
model that can contain any data type and supports callbacks. Thus, the model
client can track the changes in both the item model and any value it holds.
The item model can get both the value model and the nested items from any item.
Therefore, the model is flexible to represent anything from color to complicated
tree-table construction.
## Item
Item is the object that is associated with the data entity of the model.
The item should be created and stored by the model implementation. And can
contain any data in it. Another option would be to use it as a raw pointer to
the data. In any case, it's the choice of the model how to manage this class.
## Hierarchial Model
Usually, the model is a hierarchical system where the item can have any number
of child items. The model can be populated at the moment the user expands the
item to save resources. The following example demonstrates that the model can be
infinitely long.
```execute 200
class Item(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, text):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
self.children = None
class Model(ui.AbstractItemModel):
def __init__(self, *args):
super().__init__()
self._children = [Item(t) for t in args]
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
if not item.children:
item.children = [Item(f"Child #{i}") for i in range(5)]
return item.children
return self._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.
It's the object that tracks the specific value.
In our case we use ui.SimpleStringModel.
"""
return item.name_model
with ui.ScrollingFrame(
height=200,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
):
self._model = Model("Root", "Items")
ui.TreeView(self._model, root_visible=False, style={"margin": 0.5})
```
## Nested Model
Since the model doesn't keep any data and serves as an API protocol, sometimes
it's very helpful to merge multiple models into one single model. The parent
model should redirect the calls to the children.
In the following example, three different models are merged into one.
```execute 200
class Item(ui.AbstractItem):
def __init__(self, text, name, d=5):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
self.children = [Item(f"Child {name}{i}", name, d - 1) for i in range(d)]
class Model(ui.AbstractItemModel):
def __init__(self, name):
super().__init__()
self._children = [Item(f"Model {name}", name)]
def get_item_children(self, item):
return item.children if item else self._children
def get_item_value_model_count(self, item):
return 1
def get_item_value_model(self, item, column_id):
return item.name_model
class NestedItem(ui.AbstractItem):
def __init__(self, source_item, source_model):
super().__init__()
self.source = source_item
self.model = source_model
self.children = None
class NestedModel(ui.AbstractItemModel):
def __init__(self):
super().__init__()
models = [Model("A"), Model("B"), Model("C")]
self.children = [
NestedItem(i, m) for m in models for i in m.get_item_children(None)]
def get_item_children(self, item):
if item is None:
return self.children
if item.children is None:
m = item.model
item.children = [
NestedItem(i, m) for i in m.get_item_children(item.source)]
return item.children
def get_item_value_model_count(self, item):
return 1
def get_item_value_model(self, item, column_id):
return item.model.get_item_value_model(item.source, column_id)
with ui.ScrollingFrame(
height=200,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
):
self._model = NestedModel()
ui.TreeView(self._model, root_visible=False, style={"margin": 0.5})
```
## Drag and Drop
### Drag
If the model has the item to drag, the method `get_drag_mime_data` should be
reimplemented. This method should return the string with the drag and drop
payload. This data can be dropped to any model or to any `omni.ui` widget that
accepts this data.
```
def get_drag_mime_data(self, item):
```
### Drop
The model supports drag and drop. The drag source can be an item from any model
or any draggable data from omni.ui. When the cursor with draggable data enters
the area of the model's item, the method `drop_accepted` is called where the
model needs to decide if the data is compatible with the model. If the model can
accept the drop, it should return `True`. After that if the user drops the data
to the item, the method `drop` will be called.
```
def drop_accepted(self, target_item, source):
```
```
def drop(self, target_item, source):
```
```execute 200
class Item(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, text):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
def __repr__(self):
return self.name_model.as_string
class Model(ui.AbstractItemModel):
def __init__(self, label, *args):
super().__init__()
self._children = [Item(t) for t in args]
self._label = label
def get_item_children(self, item):
if item is not None:
return []
return self._children
def get_item_value_model_count(self, item):
return 1
def get_item_value_model(self, item, column_id):
return item.name_model
def get_drag_mime_data(self, item):
"""Returns data for be able to drop this item somewhere"""
return item.name_model.as_string
def drop_accepted(self, target_item, source):
"""Return true to accept the current drop"""
# Accept anything
return True
def drop(self, target_item, source):
"""Called when the user releases the mouse"""
# Change text on the label
self._label.text = f"Dropped {source} to {target_item}"
label = ui.Label("Drop something to the following TreeView")
with ui.ScrollingFrame(
height=200,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
):
self._model = Model(label, *[f"Item #{i}" for i in range(50)])
ui.TreeView(self._model, root_visible=False, style={"margin": 0.5})
```
| 7,577 | Markdown | 31.805195 | 81 | 0.671902 |
omniverse-code/kit/exts/omni.example.ui/docs/CHANGELOG.md | # Changelog
The documentation for omni.example.ui
## [1.2.3] - 2023-01-27
### Fixed
- Fixed config. Removed "omni.example.ui.tests"
## [1.2.2] - 2022-10-18
### Added
- A note about color syntax
### Changed
- Old hex color syntax to new omni.ui.color syntax
## [1.2.1] - 2022-06-27
### Added
- A small note about fonts
## [1.2.0] - 2021-12-17
### Added
- Dependency to `omni.kit.documentation.builder` to show md files
- Model-Delegate-View docs
## [1.1.1] - 2021-12-06
### Fixed
- The bug in the logo alignment
- Removed a warning of AbstractValueModel
### Changed
- Color scheme
| 586 | Markdown | 18.566666 | 65 | 0.672355 |
omniverse-code/kit/exts/omni.example.ui/docs/overview.md | # Overview
MDV (Model-Delegate-View) is a pattern commonly used in `omni.ui` to implement
user interfaces with data-controlling logic. It highlights a separation between
the data and the display logic. This separation of concepts provides for better
maintenance of the code.
It closely follows the MVC pattern with a slightly different separation of
components. Unlike MVC, the View component of MDV takes responsibility of
Controller, takes control of the layout, and routes the Delegate component that
controls the look.
The three parts of the MDV software-design pattern can be described as follows:
1. Model: The central component of the system. Manages data and logic. It
creates items that are used as pointers to the specific parts of the data
layer.
2. Delegate: Creates widgets and defines the look.
3. View: Handles layout, holds the widgets, and coordinates Model and Delegate.
## Model-Delegate-View in TreeView
TreeView is the MDV widget that takes advantage of the MDV pattern. For
simplicity, this document describes how the pattern applies to TreeView, and it
can be similarly applied to any MDV-based widget. The three parts are needed to
create a nice TreeView.

1. Model: it's necessary to reimplement the class `ui.AbstractItemModel`.
2. Delegate: it's necessary to reimplement the class `ui.AbstractItemDelegate`.
3. View: it's necessary to provide the model and the delegate components
to `ui.TreeView`. There is no way to reimplement it.
## MDV pipeline in Stage Widget
To describe the MDV pipeline in production, let's focus on the "visibility"
button of Stage Widget. Stage Widget is a part of the extension `omni.kit.widget.stage`.
It uses a model that is watching the stage, the delegate that is written to
match the design document, and a standard TreeView that coordinates the model
and the delegate.

The main idea is that the model doesn't keep the data (visibility value). The
model is an API protocol that is the bridge between UsdStage and TreeView. When
the user changes the visibility, the model changes it in UsdStage, which
triggers UsdNotice. And if something is changed in UsdStage, UsdNotice makes the
model dirty. When TreeView recognizes the model is dirty, it calls the delegate
to recreate the specific piece of layout. And the delegate creates a new widget
and queries the model for visibility, and the model queries it from UsdStage.
| 2,458 | Markdown | 42.910714 | 88 | 0.78926 |
omniverse-code/kit/exts/omni.example.ui/docs/delegate.md | # Delegate
Delegate is the representation layer. Delegate is called by the view to create a
specific piece of the user interface. TreeView calls the delegate to create the
widgets for the header and per item in the column.
To
## Item

Each row in TreeView is the representation of the model's item.
## Column

Each model's item can have multiple data fields. To display them, TreeView uses
columns.
## Level

The level is the number of parent items for the given item.
## Branch Widget Header

The branch is the widget that makes TreeView expand or collapse the current
item.
## Example
To reimplement a delegate, it's necessary to reimplement the following methods
of `ui.AbstractItemDelegate`:
```
def build_branch(self, model, item, column_id, level, expanded):
```
```
def build_widget(self, model, item, column_id, level, expanded):
```
```
def build_header(self, column_id):
```
```execute 200
##
class Item(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, text):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
self.children = None
class Model(ui.AbstractItemModel):
def __init__(self, *args):
super().__init__()
self._children = [Item(t) for t in args]
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
if not item.children:
item.children = [Item(f"Child #{i}") for i in range(5)]
return item.children
return self._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.
It's the object that tracks the specific value.
In our case we use ui.SimpleStringModel.
"""
return item.name_model
##
class Delegate(ui.AbstractItemDelegate):
"""
Delegate is the representation layer. TreeView calls the methods
of the delegate to create custom widgets for each item.
"""
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
# Offset depents on level
text = " " * (level + 1)
# > and v symbols depending on the expanded state
if expanded:
text += "v "
else:
text += "> "
ui.Label(text, height=22, alignment=ui.Alignment.CENTER, tooltip="Branch")
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per column per item"""
ui.Label(
model.get_item_value_model(item, column_id).as_string,
tooltip="Widget"
)
def build_header(self, column_id):
"""Build the header"""
ui.Label("Header", tooltip="Header", height=25)
with ui.ScrollingFrame(
height=200,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
):
self._model = Model("Root", "Items")
self._delegate = Delegate()
ui.TreeView(
self._model, delegate=self._delegate, root_visible=False, header_visible=True
)
```
| 3,476 | Markdown | 25.746154 | 85 | 0.638953 |
omniverse-code/kit/exts/omni.kit.window.commands/config/extension.toml | [package]
version = "0.2.4"
category = "Core"
authors = ["NVIDIA"]
title = "Commands Utils"
description="Commands history viewer, commands execution script generator and registered commands viewer"
repository = ""
keywords = ["kit", "commands"]
changelog = "docs/CHANGELOG.md"
[dependencies]
"omni.kit.clipboard" = {}
"omni.kit.commands" = {}
"omni.kit.pip_archive" = {}
"omni.ui" = {}
"omni.kit.menu.utils" = {}
[[python.module]]
name = "omni.kit.window.commands"
[settings]
exts."omni.kit.window.commands".windowOpenByDefault = false
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.kit.renderer.capture"
]
| 715 | TOML | 19.457142 | 105 | 0.678322 |
omniverse-code/kit/exts/omni.kit.window.commands/omni/kit/window/commands/main.py | from collections import defaultdict
from inspect import isclass
from functools import partial
import omni.kit.commands
import omni.kit.undo
from omni import ui
from .history import HistoryModel, HistoryDelegate, MainItem
from .search import SearchModel, SearchDelegate, CommandItem, Columns
class Window:
def __init__(self, title, menu_path):
self._menu_path = menu_path
self._win_history = ui.Window(title, width=700, height=500)
self._win_history.set_visibility_changed_fn(self._on_visibility_changed)
self._win_search = None
self._search_frame = None
self._doc_frame = None
self._history_delegate = HistoryDelegate()
self._search_delegate = SearchDelegate()
self._build_ui()
omni.kit.commands.subscribe_on_change(self._update_ui)
self._update_ui()
def on_shutdown(self):
self._win_history = None
self._win_search = None
self._search_frame = None
self._doc_frame = None
self._history_delegate = None
self._search_delegate = None
omni.kit.commands.unsubscribe_on_change(self._update_ui)
def show(self):
self._win_history.visible = True
self._win_history.focus()
def hide(self):
self._win_history.visible = False
if self._win_search is not None:
self._win_search.visible = False
def _on_visibility_changed(self, visible):
if not visible:
omni.kit.ui.get_editor_menu().set_value(self._menu_path, False)
if self._win_search is not None:
self._win_search.visible = False
def _build_ui(self):
with self._win_history.frame:
with ui.VStack():
with ui.HStack(height=20):
ui.Button("Clear history", width=60, clicked_fn=self._clear_history)
ui.Button("Search commands", width=60, clicked_fn=self._show_registered)
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
style_type_name_override="TreeView",
):
self._history_model = HistoryModel()
self._history_tree_view = ui.TreeView(
self._history_model,
delegate=self._history_delegate,
root_visible=False,
style={"TreeView.Item::error": {"color": 0xFF0000BB}},
column_widths=[ui.Fraction(1)],
)
self._history_tree_view.set_mouse_double_clicked_fn(self._on_double_click)
with ui.HStack(height=20):
ui.Label("Generate script to clipboard from:", width=0)
ui.Button("Top-level commands", width=60, clicked_fn=partial(self._copy_to_clipboard, False))
ui.Button("Selected commands", width=60, clicked_fn=partial(self._copy_to_clipboard, True))
def _on_double_click(self, x, y, b, m):
if len(self._history_tree_view.selection) <= 0:
return
item = self._history_tree_view.selection[0]
if isinstance(item, MainItem):
self._history_tree_view.set_expanded(item, not self._history_tree_view.is_expanded(item), False)
def _copy_to_clipboard(self, only_selected):
omni.kit.clipboard.copy(self._generate_command_script(only_selected))
def _clear_history(self):
omni.kit.undo.clear_history()
self._history_model._commands_changed()
def _show_registered(self):
if self._win_search is None:
self._win_search = ui.Window(
"Search Commands", width=700, height=500, dockPreference=ui.DockPreference.MAIN
)
with self._win_search.frame:
with ui.VStack():
with ui.HStack(height=20):
ui.Label("Find: ", width=0)
self._search_field = ui.StringField()
self._search_field.model.add_value_changed_fn(lambda _: self._refresh_list())
with ui.HStack(height=300):
self._search_frame = ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
style_type_name_override="TreeView",
)
with self._search_frame:
self._search_tree_model = SearchModel()
self._search_tree_view = ui.TreeView(
self._search_tree_model,
delegate=self._search_delegate,
selection_changed_fn=self._on_selection_changed,
root_visible=False,
header_visible=True,
columns_resizable=True,
column_widths=[x.width for x in Columns.ORDER],
)
self._doc_frame = ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
)
self._refresh_list()
self._win_search.visible = True
self._win_search.focus()
def _on_selection_changed(self, selected_items):
with self._doc_frame:
with ui.VStack(height=40):
for item in selected_items:
if isinstance(item, CommandItem):
ui.Label(f"{item.command_model.as_string}{item.class_sig}", height=30)
ui.Label(f"Documentation:", height=30)
if item.doc is None or item.doc == omni.kit.commands.Command.__doc__:
ui.Label("\n\t<None>")
else:
ui.Label(item.doc.strip())
def _update_ui(self):
self._history_model._commands_changed()
self._refresh_list() # TODO: check if this is called too much
def _refresh_list(self):
if self._search_frame is None:
return
search_str = self._search_field.model.get_value_as_string().lower().strip()
self._search_tree_model._clear_commands()
commands = omni.kit.commands.get_commands()
for cmd_list in commands.values():
for command in cmd_list.values():
if search_str == "" or command.__name__.lower().find(search_str) != -1:
if self._search_tree_model:
class_sig = omni.kit.commands.get_command_class_signature(command.__name__)
self._search_tree_model._add_command(CommandItem(command, class_sig))
self._search_tree_view.clear_selection()
self._search_tree_model._commands_changed()
def _generate_command_script(self, only_selected):
history = omni.kit.undo.get_history().values()
imports = "import omni.kit.commands\n"
code_str = ""
arg_imports = defaultdict(set)
def parse_module_name(name):
if name == "builtins":
return
nonlocal imports
lst = name.split(".")
if len(lst) == 1:
imports += "import " + name + "\n"
else:
arg_imports[lst[0]].add(".".join(lst[1:]))
def arg_import(val):
if isclass(val):
parse_module_name(val.__module__)
else:
parse_module_name(val.__class__.__module__)
return val
def gen_cmd_str(cmd):
if len(cmd.kwargs.items()) > 0:
args = ",\n\t".join(["{}={!r}".format(k, arg_import(v)) for k, v in cmd.kwargs.items()])
return f"\nomni.kit.commands.execute('{cmd.name}',\n\t{args})\n"
else:
return f"\nomni.kit.commands.execute('{cmd.name}')\n"
# generate a script executing top-level commands or all selected commands
if only_selected:
for item in self._history_tree_view.selection:
if isinstance(item, MainItem):
code_str += gen_cmd_str(item._data)
else:
for cmd in history:
if cmd.level == 0:
code_str += gen_cmd_str(cmd)
for k, v in arg_imports.items():
imports += f"from {k} import " + ", ".join(v) + "\n"
return imports + code_str
| 8,837 | Python | 41.085714 | 113 | 0.539097 |
omniverse-code/kit/exts/omni.kit.window.commands/omni/kit/window/commands/search.py | import inspect
from pathlib import Path
import carb.settings
import omni.ext
import omni.kit.app
from omni import ui
class SearchModel(ui.AbstractItemModel):
"""
Represents the list of commands registered in Kit.
It is used to make a single level tree appear like a simple list.
"""
def __init__(self):
super().__init__()
self._commands = []
def _clear_commands(self):
self._commands = []
def _commands_changed(self):
self._item_changed(None)
def _add_command(self, item):
if item and isinstance(item, CommandItem):
self._commands.append(item)
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is None:
return self._commands
return item.children
def get_item_value_model_count(self, item):
"""The number of columns"""
return Columns.get_count()
def get_item_value_model(self, item, column_id):
"""Return value model."""
if item and isinstance(item, CommandItem):
return Columns.get_model(item, column_id)
class SearchDelegate(ui.AbstractItemDelegate):
def __init__(self):
super().__init__()
self._icon_path = Path(__file__).parent.parent.parent.parent.parent.joinpath("icons")
self._style = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
# Read all the svg files in the directory
self._icons = {icon.stem: icon for icon in self._icon_path.joinpath(self._style).glob("*.svg")}
def build_widget(self, model, item, column_id, level, expanded):
value_model = model.get_item_value_model(item, column_id)
text = value_model.as_string
ui.Label(text, style_type_name_override="TreeView.Item")
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
if column_id == 0:
with ui.HStack(width=16 * (level + 2), height=0):
ui.Spacer()
if model.can_item_have_children(item):
# Draw the +/- icon
image_name = "Minus" if expanded else "Plus"
ui.Image(
str(self._icons.get(image_name)), width=10, height=10, style_type_name_override="TreeView.Item"
)
ui.Spacer(width=4)
def build_header(self, column_id):
label = Columns.get_label(column_id)
ui.Label(label, height=30, width=20)
class CommandItem(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, command, class_sig):
super().__init__()
self.command_model = ui.SimpleStringModel(command.__name__)
manager = omni.kit.app.get_app().get_extension_manager()
ext_id = manager.get_extension_id_by_module(command.__module__)
ext_name = omni.ext.get_extension_name(ext_id) if ext_id else "Unknown"
self.extension_model = ui.SimpleStringModel(ext_name)
self.undo_model = ui.SimpleBoolModel(hasattr(command, "undo") and inspect.isfunction(command.undo))
self.doc = command.__doc__ or (command.__init__ is not None and command.__init__.__doc__)
self.class_sig = class_sig
self.children = []
# uncomment these lines if child items are needed later on
# if doc is not None:
# self.children.append(CommandChildItem(doc))
class CommandChildItem(CommandItem):
def __init__(self, arg):
super().__init__(str(arg))
self.children = []
class Columns:
"""
Store UI info about the columns in one place so it's easier to keep in
"""
class ColumnData:
def __init__(self, label, column, width, attrib_name):
self.label = label
self.column = column
self.width = width
self.attrib_name = attrib_name
Command = ColumnData("Command", 0, ui.Fraction(1), "command_model")
Extension = ColumnData("Extension", 1, ui.Pixel(200), "extension_model")
CanUndo = ColumnData("Can Undo", 2, ui.Pixel(80), "undo_model")
ORDER = [Command, Extension, CanUndo]
@classmethod
def get_count(cls):
return len(cls.ORDER)
@classmethod
def get_label(cls, index):
return cls.ORDER[index].label
@classmethod
def get_model(cls, entry: CommandItem, index):
return getattr(entry, cls.ORDER[index].attrib_name)
| 4,521 | Python | 33.519084 | 119 | 0.610263 |
omniverse-code/kit/exts/omni.kit.window.commands/omni/kit/window/commands/extension.py | import carb.settings
import omni.ext
import omni.kit.ui
from .main import Window
EXTENSION_NAME = "Commands"
class Extension(omni.ext.IExt):
def on_startup(self):
self._menu_path = f"Window/{EXTENSION_NAME}"
self._window = None
open_by_default = carb.settings.get_settings().get("exts/omni.kit.window.commands/windowOpenByDefault")
self._menu = omni.kit.ui.get_editor_menu().add_item(
self._menu_path, self._on_menu_click, True, value=open_by_default
)
if open_by_default:
self._on_menu_click(None, True)
def on_shutdown(self):
if self._window is not None:
self._window.on_shutdown()
self._menu = None
self._window = None
def _on_menu_click(self, menu, toggled):
if toggled:
if self._window is None:
self._window = Window(EXTENSION_NAME, self._menu_path)
else:
self._window.show()
else:
if self._window is not None:
self._window.hide()
| 1,062 | Python | 28.527777 | 111 | 0.582863 |
omniverse-code/kit/exts/omni.kit.window.commands/omni/kit/window/commands/history.py | from pathlib import Path
import carb.settings
from omni import ui
import omni.kit.undo
class HistoryData:
def __init__(self):
self._data = omni.kit.undo.get_history()
if len(self._data):
self._curr = next(iter(self._data))
self._last = next(reversed(self._data))
else:
self._curr = 0
self._last = -1
def is_not_empty(self):
return self._curr <= self._last
def get_next(self):
self._curr += 1
return self._data[self._curr - 1]
def is_next_lower(self, level):
return self._data[self._curr].level > level
class HistoryModel(ui.AbstractItemModel):
def __init__(self):
super().__init__()
self._root = MainItem(None, HistoryData())
def _commands_changed(self):
self._root = MainItem(None, HistoryData())
self._item_changed(None)
def get_item_children(self, item):
if item is None:
return self._root.children
return item.children
def get_item_value_model_count(self, item):
return 1
def get_item_value_model(self, item, column_id):
if column_id == 0:
return item.name_model
class HistoryDelegate(ui.AbstractItemDelegate):
def __init__(self):
super().__init__()
self._icon_path = Path(__file__).parent.parent.parent.parent.parent.joinpath("icons")
self._style = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
# Read all the svg files in the directory
self._icons = {icon.stem: icon for icon in self._icon_path.joinpath(self._style).glob("*.svg")}
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per column per item"""
value_model = model.get_item_value_model(item, column_id)
# call out commands that had errors
text = value_model.as_string
name = ""
if hasattr(item, "_data") and hasattr(item._data, "error") and item._data.error:
text = "[ERROR] " + text
name = "error"
ui.Label(text, name=name, style_type_name_override="TreeView.Item")
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
if column_id == 0:
with ui.HStack(width=16 * (level + 2), height=0):
ui.Spacer()
if model.can_item_have_children(item):
# Draw the +/- icon
image_name = "Minus" if expanded else "Plus"
ui.Image(
str(self._icons.get(image_name)), width=10, height=10, style_type_name_override="TreeView.Item"
)
ui.Spacer(width=4)
def build_header(self, column_id):
pass
class MainItem(ui.AbstractItem):
def __init__(self, command_data, history):
super().__init__()
self._data = command_data
if command_data is None:
self._create_root(history)
else:
self._create_node(history)
def _create_root(self, history):
self.children = []
while history.is_not_empty():
self.children.append(MainItem(history.get_next(), history))
def _create_node(self, history):
self.name_model = ui.SimpleStringModel(self._data.name)
self.children = [ParamItem(arg, val) for arg, val in self._data.kwargs.items()]
while history.is_not_empty() and history.is_next_lower(self._data.level):
next_command = history.get_next()
self.children.append(MainItem(next_command, history))
class ParamItem(ui.AbstractItem):
def __init__(self, arg, val):
super().__init__()
self.name_model = ui.SimpleStringModel(str(arg) + "=" + str(val))
self.children = []
| 3,889 | Python | 32.534482 | 119 | 0.580869 |
omniverse-code/kit/exts/omni.kit.window.commands/omni/kit/window/commands/tests/test_extension.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import re
from pathlib import Path
import omni.kit.app
import omni.kit.commands
import omni.kit.undo
from omni.kit.window.commands import Window
from omni.ui.tests.test_base import OmniUiTest
_result = []
class TestAppendCommand(omni.kit.commands.Command):
def __init__(self, x, y):
self._x = x
self._y = y
def do(self):
global _result
_result.append(self._x)
_result.append(self._y)
def undo(self):
global _result
del _result[-1]
del _result[-1]
class TestCommandsWindow(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
self._golden_img_dir = Path(extension_path).joinpath("data").joinpath("tests").absolute()
# make sure we are starting from a clean state
omni.kit.undo.clear_stack()
# Register all commands
omni.kit.commands.register(TestAppendCommand)
# After running each test
async def tearDown(self):
# Unregister all commands
omni.kit.commands.unregister(TestAppendCommand)
await super().tearDown()
async def test_simple_command(self):
window = await self.create_test_window(1000, 600)
with window.frame:
win = Window("Commands", "Commands")
win.show()
global _result
# Execute and undo
_result = []
omni.kit.commands.execute("TestAppend", x=1, y=2)
self.assertListEqual(_result, [1, 2])
omni.kit.undo.undo()
self.assertListEqual(_result, [])
script = """import omni.kit.commands
omni.kit.commands.execute('TestAppend',
x=1,
y=2)
omni.kit.commands.execute('Undo')"""
result = win._generate_command_script(False)
# strip all whitespaces to ease our comparison
s = re.sub("[\s+]", "", script)
r = re.sub("[\s+]", "", result)
# test script
self.assertEqual(s, r)
for i in range(50):
await omni.kit.app.get_app().next_update_async()
# test image
await self.finalize_test(
golden_img_dir=self._golden_img_dir, golden_img_name="test_simple_command.png", use_log=False
)
| 2,862 | Python | 28.822916 | 110 | 0.620196 |
omniverse-code/kit/exts/omni.kit.window.commands/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [0.2.4] - 2022-11-17
### Changes
- Switched out pyperclip for linux-friendly copy & paste
## [0.2.3] - 2022-09-22
### Fixes
- Make test pass again by allowing more time for SVG load.
## [0.2.2] - 2022-06-07
### Fixes
- Get extension name from the extension manager.
## [0.2.1] - 2022-05-09
### Changes
- Added tests
## [0.2.0] - 2021-12-16
### Changes
- New TreeView for the search window that provide more details
## [0.1.1] - 2021-02-10
### Changes
- Updated StyleUI handling
## [0.1.0] - 2020-07-30
### Added
- initial implementation
| 641 | Markdown | 19.062499 | 80 | 0.656786 |
omniverse-code/kit/exts/omni.kit.window.commands/docs/index.rst | omni.kit.window.commands
###########################
* Commands history view.
* Script generator for the execution of top-level or selected commands.
* Full-text search in names of all currently registered commands.
.. toctree::
:maxdepth: 1
CHANGELOG | 272 | reStructuredText | 23.81818 | 75 | 0.647059 |
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/renderer_capture/__init__.py | from omni.kit.renderer_capture import *
| 40 | Python | 19.49999 | 39 | 0.8 |
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer/capture/scripts/extension.py | import carb.settings
import omni.ext
import omni.kit.renderer_capture
class Extension(omni.ext.IExt):
def __init__(self):
omni.ext.IExt.__init__(self)
pass
def on_startup(self):
self._settings = carb.settings.get_settings()
self._settings.set_default_bool("/exts/omni.kit.renderer.capture/autostartCapture", True)
self._autostart = self._settings.get("/exts/omni.kit.renderer.capture/autostartCapture")
if self._autostart:
self._renderer_capture = omni.kit.renderer_capture.acquire_renderer_capture_interface()
self._renderer_capture.startup()
def on_shutdown(self):
if self._autostart:
self._renderer_capture.shutdown()
self._renderer_capture = None
| 772 | Python | 31.208332 | 99 | 0.65544 |
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer/capture/tests/__init__.py | from .test_renderer_capture import *
| 37 | Python | 17.999991 | 36 | 0.783784 |
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer/capture/tests/test_renderer_capture.py | import os
import sys
import inspect
import pathlib
import importlib
import carb
import carb.dictionary
import carb.settings
import carb.tokens
import omni.appwindow
import omni.kit.app
import omni.kit.test
import omni.kit.renderer.bind
import omni.kit.renderer_capture
import omni.kit.renderer_capture_test
OUTPUTS_DIR = omni.kit.test.get_test_output_path()
USE_TUPLES = True
# Ancient hack coming from dark times
SET_ALPHA_TO_1_SETTING_PATH = "/app/captureFrame/setAlphaTo1"
class RendererCaptureTest(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._settings = carb.settings.get_settings()
self._dict = carb.dictionary.acquire_dictionary_interface()
self._app_window_factory = omni.appwindow.acquire_app_window_factory_interface()
self._renderer = omni.kit.renderer.bind.acquire_renderer_interface()
self._renderer_capture = omni.kit.renderer_capture.acquire_renderer_capture_interface()
self._renderer_capture_test = omni.kit.renderer_capture_test.acquire_renderer_capture_test_interface()
self._renderer.startup()
self._renderer_capture.startup()
self._renderer_capture_test.startup()
def __test_name(self) -> str:
return f"{self.__class__.__name__}.{inspect.stack()[1][3]}"
async def tearDown(self):
self._renderer_capture_test.shutdown()
self._renderer_capture.shutdown()
self._renderer.shutdown()
self._renderer_capture_test = None
self._renderer_capture = None
self._renderer = None
self._app_window_factory = None
self._settings = None
def _create_and_attach_window(self, w, h, window_type):
app_window = self._app_window_factory.create_window_by_type(window_type)
app_window.startup_with_desc(
title="Renderer capture test OS window",
width=w,
height=h,
x=omni.appwindow.POSITION_CENTERED,
y=omni.appwindow.POSITION_CENTERED,
decorations=True,
resize=True,
always_on_top=False,
scale_to_monitor=False,
dpi_scale_override=1.0
)
self._app_window_factory.set_default_window(app_window)
self._renderer.attach_app_window(app_window)
return app_window
def _detach_and_destroy_window(self, app_window):
self._app_window_factory.set_default_window(None)
self._renderer.detach_app_window(app_window)
app_window.shutdown()
def _capture_callback(self, buf, buf_size, w, h, fmt):
if USE_TUPLES:
self._captured_buffer = omni.kit.renderer_capture.convert_raw_bytes_to_rgba_tuples(buf, buf_size, w, h, fmt)
else:
self._captured_buffer = omni.kit.renderer_capture.convert_raw_bytes_to_list(buf, buf_size, w, h, fmt)
self._captured_buffer_w = w
self._captured_buffer_h = h
self._captured_buffer_fmt = fmt
def _get_pil_image_from_captured_data(self):
from PIL import Image
image = Image.new('RGBA', [self._captured_buffer_w, self._captured_buffer_h])
if USE_TUPLES:
image.putdata(self._captured_buffer)
else:
buf_channel_it = iter(self._captured_buffer)
captured_buffer_tuples = list(zip(buf_channel_it, buf_channel_it, buf_channel_it, buf_channel_it))
image.putdata(captured_buffer_tuples)
return image
def _get_pil_image_size_data(self, path):
from PIL import Image
image = Image.open(path)
image_data = list(image.getdata())
image_w, image_h = image.size
image.close()
return image_w, image_h, image_data
def _disable_alpha_to_1(self):
self._settings.set_default(SET_ALPHA_TO_1_SETTING_PATH, False)
self._setAlphaTo1 = self._settings.get(SET_ALPHA_TO_1_SETTING_PATH)
self._settings.set(SET_ALPHA_TO_1_SETTING_PATH, False)
def _restore_alpha_to_1(self):
self._settings.set(SET_ALPHA_TO_1_SETTING_PATH, self._setAlphaTo1)
async def test_0001_capture_swapchain_to_file(self):
test_name = self.__test_name()
TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png")
TEST_IMG_W = 8
TEST_IMG_H = 8
TEST_COLOR = (255, 0, 0, 255)
app_window = self._create_and_attach_window(TEST_IMG_W, TEST_IMG_H, omni.appwindow.WindowType.VIRTUAL)
test_color_unit = tuple(c / 255.0 for c in TEST_COLOR)
self._renderer.set_clear_color(app_window, test_color_unit)
self._renderer_capture.capture_next_frame_swapchain(TEST_IMG_PATH, app_window)
await omni.kit.app.get_app().next_update_async()
self._renderer_capture.wait_async_capture(app_window)
image_size_data = self._get_pil_image_size_data(TEST_IMG_PATH)
self.assertEqual(len(image_size_data), 3)
self.assertEqual(image_size_data[0], TEST_IMG_W)
self.assertEqual(image_size_data[1], TEST_IMG_H)
self.assertEqual(image_size_data[2][0], TEST_COLOR)
self._detach_and_destroy_window(app_window)
app_window = None
async def test_0002_capture_swapchain_callback(self):
test_name = self.__test_name()
TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png")
TEST_IMG_W = 16
TEST_IMG_H = 16
TEST_COLOR = (0, 255, 255, 255)
app_window = self._create_and_attach_window(TEST_IMG_W, TEST_IMG_H, omni.appwindow.WindowType.VIRTUAL)
test_color_unit = tuple(c / 255.0 for c in TEST_COLOR)
self._renderer.set_clear_color(app_window, test_color_unit)
self._renderer_capture.capture_next_frame_swapchain_callback(self._capture_callback, app_window)
await omni.kit.app.get_app().next_update_async()
self._renderer_capture.wait_async_capture(app_window)
image = self._get_pil_image_from_captured_data()
image.save(TEST_IMG_PATH)
self.assertEqual(self._captured_buffer_w, TEST_IMG_W)
self.assertEqual(self._captured_buffer_h, TEST_IMG_H)
if USE_TUPLES:
self.assertEqual(self._captured_buffer[0], TEST_COLOR)
else:
self.assertEqual(self._captured_buffer[0], TEST_COLOR[0])
self.assertEqual(self._captured_buffer[1], TEST_COLOR[1])
self.assertEqual(self._captured_buffer[2], TEST_COLOR[2])
self.assertEqual(self._captured_buffer[3], TEST_COLOR[3])
self._detach_and_destroy_window(app_window)
app_window = None
async def test_0003_capture_texture_to_file(self):
test_name = self.__test_name()
TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png")
TEST_IMG_W = 4
TEST_IMG_H = 4
TEST_COLOR = (255, 255, 0, 255)
app_window = self._create_and_attach_window(12, 12, omni.appwindow.WindowType.VIRTUAL)
test_color_unit = tuple(c / 255.0 for c in TEST_COLOR)
texture = self._renderer_capture_test.create_solid_color_texture(test_color_unit, TEST_IMG_W, TEST_IMG_H)
self._renderer_capture.capture_next_frame_texture(TEST_IMG_PATH, texture)
await omni.kit.app.get_app().next_update_async()
self._renderer_capture.wait_async_capture(app_window)
image_size_data = self._get_pil_image_size_data(TEST_IMG_PATH)
self.assertEqual(len(image_size_data), 3)
self.assertEqual(image_size_data[0], TEST_IMG_W)
self.assertEqual(image_size_data[1], TEST_IMG_H)
self.assertEqual(image_size_data[2][0], TEST_COLOR)
self._renderer_capture_test.cleanup_gpu_resources()
self._detach_and_destroy_window(app_window)
app_window = None
async def test_0004_capture_texture_callback(self):
test_name = self.__test_name()
TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png")
TEST_IMG_W = 6
TEST_IMG_H = 6
TEST_COLOR = (255, 0, 255, 255)
app_window = self._create_and_attach_window(12, 12, omni.appwindow.WindowType.VIRTUAL)
test_color_unit = tuple(c / 255.0 for c in TEST_COLOR)
texture = self._renderer_capture_test.create_solid_color_texture(test_color_unit, TEST_IMG_W, TEST_IMG_H)
self._renderer_capture.capture_next_frame_texture_callback(self._capture_callback, texture)
await omni.kit.app.get_app().next_update_async()
self._renderer_capture.wait_async_capture(app_window)
image = self._get_pil_image_from_captured_data()
image.save(TEST_IMG_PATH)
self.assertEqual(self._captured_buffer_w, TEST_IMG_W)
self.assertEqual(self._captured_buffer_h, TEST_IMG_H)
if USE_TUPLES:
self.assertEqual(self._captured_buffer[0], TEST_COLOR)
else:
self.assertEqual(self._captured_buffer[0], TEST_COLOR[0])
self.assertEqual(self._captured_buffer[1], TEST_COLOR[1])
self.assertEqual(self._captured_buffer[2], TEST_COLOR[2])
self.assertEqual(self._captured_buffer[3], TEST_COLOR[3])
self._renderer_capture_test.cleanup_gpu_resources()
self._detach_and_destroy_window(app_window)
app_window = None
async def test_0005_capture_rp_resource_to_file(self):
test_name = self.__test_name()
TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png")
TEST_IMG_W = 5
TEST_IMG_H = 5
TEST_COLOR = (0, 255, 0, 255)
app_window = self._create_and_attach_window(12, 12, omni.appwindow.WindowType.VIRTUAL)
test_color_unit = tuple(c / 255.0 for c in TEST_COLOR)
rp_resource = self._renderer_capture_test.create_solid_color_rp_resource(test_color_unit, TEST_IMG_W, TEST_IMG_H)
self._renderer_capture.capture_next_frame_rp_resource(TEST_IMG_PATH, rp_resource)
await omni.kit.app.get_app().next_update_async()
self._renderer_capture.wait_async_capture(app_window)
image_size_data = self._get_pil_image_size_data(TEST_IMG_PATH)
self.assertEqual(len(image_size_data), 3)
self.assertEqual(image_size_data[0], TEST_IMG_W)
self.assertEqual(image_size_data[1], TEST_IMG_H)
self.assertEqual(image_size_data[2][0], TEST_COLOR)
self._renderer_capture_test.cleanup_gpu_resources()
self._detach_and_destroy_window(app_window)
app_window = None
async def test_0006_capture_rp_resource_callback(self):
test_name = self.__test_name()
TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png")
TEST_IMG_W = 6
TEST_IMG_H = 6
TEST_COLOR = (0, 0, 255, 255)
app_window = self._create_and_attach_window(12, 12, omni.appwindow.WindowType.VIRTUAL)
test_color_unit = tuple(c / 255.0 for c in TEST_COLOR)
rp_resource = self._renderer_capture_test.create_solid_color_rp_resource(test_color_unit, TEST_IMG_W, TEST_IMG_H)
self._renderer_capture.capture_next_frame_rp_resource_callback(self._capture_callback, rp_resource)
await omni.kit.app.get_app().next_update_async()
self._renderer_capture.wait_async_capture(app_window)
image = self._get_pil_image_from_captured_data()
image.save(TEST_IMG_PATH)
self.assertEqual(self._captured_buffer_w, TEST_IMG_W)
self.assertEqual(self._captured_buffer_h, TEST_IMG_H)
if USE_TUPLES:
self.assertEqual(self._captured_buffer[0], TEST_COLOR)
else:
self.assertEqual(self._captured_buffer[0], TEST_COLOR[0])
self.assertEqual(self._captured_buffer[1], TEST_COLOR[1])
self.assertEqual(self._captured_buffer[2], TEST_COLOR[2])
self.assertEqual(self._captured_buffer[3], TEST_COLOR[3])
self._renderer_capture_test.cleanup_gpu_resources()
self._detach_and_destroy_window(app_window)
app_window = None
async def test_0007_capture_os_swapchain_to_file(self):
test_name = self.__test_name()
TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png")
TEST_IMG_W = 256
TEST_IMG_H = 32
TEST_COLOR = (255, 128, 0, 255)
app_window = self._create_and_attach_window(TEST_IMG_W, TEST_IMG_H, omni.appwindow.WindowType.OS)
test_color_unit = tuple(c / 255.0 for c in TEST_COLOR)
self._renderer.set_clear_color(app_window, test_color_unit)
self._renderer_capture.capture_next_frame_swapchain(TEST_IMG_PATH, app_window)
await omni.kit.app.get_app().next_update_async()
self._renderer_capture.wait_async_capture(app_window)
image_size_data = self._get_pil_image_size_data(TEST_IMG_PATH)
self.assertEqual(len(image_size_data), 3)
self.assertEqual(image_size_data[0], TEST_IMG_W)
self.assertEqual(image_size_data[1], TEST_IMG_H)
self.assertEqual(image_size_data[2][0], TEST_COLOR)
self._detach_and_destroy_window(app_window)
app_window = None
async def test_0008_capture_transparent_swapchain_to_file(self):
self._disable_alpha_to_1()
test_name = self.__test_name()
TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png")
TEST_IMG_W = 8
TEST_IMG_H = 8
TEST_COLOR = (255, 0, 0, 0)
app_window = self._create_and_attach_window(TEST_IMG_W, TEST_IMG_H, omni.appwindow.WindowType.VIRTUAL)
test_color_unit = tuple(c / 255.0 for c in TEST_COLOR)
self._renderer.set_clear_color(app_window, test_color_unit)
self._renderer_capture.capture_next_frame_swapchain(TEST_IMG_PATH, app_window)
await omni.kit.app.get_app().next_update_async()
self._renderer_capture.wait_async_capture(app_window)
image_size_data = self._get_pil_image_size_data(TEST_IMG_PATH)
self.assertEqual(len(image_size_data), 3)
self.assertEqual(image_size_data[0], TEST_IMG_W)
self.assertEqual(image_size_data[1], TEST_IMG_H)
self.assertEqual(image_size_data[2][0], TEST_COLOR)
self._detach_and_destroy_window(app_window)
app_window = None
self._restore_alpha_to_1()
async def test_0009_capture_transparent_swapchain_callback(self):
self._disable_alpha_to_1()
test_name = self.__test_name()
TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png")
TEST_IMG_W = 16
TEST_IMG_H = 16
TEST_COLOR = (0, 255, 255, 0)
app_window = self._create_and_attach_window(TEST_IMG_W, TEST_IMG_H, omni.appwindow.WindowType.VIRTUAL)
test_color_unit = tuple(c / 255.0 for c in TEST_COLOR)
self._renderer.set_clear_color(app_window, test_color_unit)
self._renderer_capture.capture_next_frame_swapchain_callback(self._capture_callback, app_window)
await omni.kit.app.get_app().next_update_async()
self._renderer_capture.wait_async_capture(app_window)
image = self._get_pil_image_from_captured_data()
image.save(TEST_IMG_PATH)
self.assertEqual(self._captured_buffer_w, TEST_IMG_W)
self.assertEqual(self._captured_buffer_h, TEST_IMG_H)
if USE_TUPLES:
self.assertEqual(self._captured_buffer[0], TEST_COLOR)
else:
self.assertEqual(self._captured_buffer[0], TEST_COLOR[0])
self.assertEqual(self._captured_buffer[1], TEST_COLOR[1])
self.assertEqual(self._captured_buffer[2], TEST_COLOR[2])
self.assertEqual(self._captured_buffer[3], TEST_COLOR[3])
self._detach_and_destroy_window(app_window)
app_window = None
self._restore_alpha_to_1()
async def __test_capture_rp_resource_with_format(self, format_desc_item):
test_name = self.__test_name()
TEST_IMG_PATH_NOEXT = os.path.join(OUTPUTS_DIR, test_name)
TEST_IMG_W = 15
TEST_IMG_H = 15
TEST_COLOR = (12.34, 34.56, 67.89, 128.0)
app_window = self._create_and_attach_window(12, 12, omni.appwindow.WindowType.VIRTUAL)
files = {}
format_desc_item["format"] = "exr"
rp_resource = self._renderer_capture_test.create_solid_color_rp_resource_hdr(TEST_COLOR, TEST_IMG_W, TEST_IMG_H)
async def capture():
filename = TEST_IMG_PATH_NOEXT + "_" + format_desc_item["compression"] + ".exr"
files[format_desc_item["compression"]] = filename
self._renderer_capture.capture_next_frame_rp_resource_to_file(filename, rp_resource, None, format_desc_item)
await omni.kit.app.get_app().next_update_async()
self._renderer_capture.wait_async_capture(app_window)
format_desc_item["compression"] = "none"
await capture()
format_desc_item["compression"] = "rle"
await capture()
format_desc_item["compression"] = "b44"
await capture()
file_sizes = {}
for file_key, file_path in files.items():
file_sizes[file_key] = os.path.getsize(file_path)
self.assertNotEqual(file_sizes["none"], file_sizes["rle"])
self.assertNotEqual(file_sizes["none"], file_sizes["b44"])
self.assertNotEqual(file_sizes["rle"], file_sizes["b44"])
self._renderer_capture_test.cleanup_gpu_resources()
self._detach_and_destroy_window(app_window)
app_window = None
async def test_0010_capture_rp_resource_hdr_to_file_carb_dict(self):
format_desc_item = self._dict.create_item(None, "", carb.dictionary.ItemType.DICTIONARY)
await self.__test_capture_rp_resource_with_format(format_desc_item)
async def test_0010_capture_rp_resource_hdr_to_file_py_dict(self):
format_desc_item = {}
await self.__test_capture_rp_resource_with_format(format_desc_item)
| 17,721 | Python | 39.277273 | 121 | 0.639806 |
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer_capture_test/__init__.py | import functools
from ._renderer_capture_test import *
# Cached interface instance pointer
@functools.lru_cache()
def get_renderer_capture_test_interface() -> IRendererCaptureTest:
if not hasattr(get_renderer_capture_test_interface, "renderer_capture_test"):
get_renderer_capture_test_interface.renderer_capture_test = acquire_renderer_capture_test_interface()
return get_renderer_capture_test_interface.renderer_capture_test
| 444 | Python | 39.454542 | 109 | 0.783784 |
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer_capture/_renderer_capture.pyi | from __future__ import annotations
import omni.kit.renderer_capture._renderer_capture
import typing
import omni.appwindow._appwindow
import omni.gpu_foundation_factory._gpu_foundation_factory
__all__ = [
"IRendererCapture",
"Metadata",
"acquire_renderer_capture_interface",
"convert_raw_bytes_to_list",
"convert_raw_bytes_to_rgba_tuples"
]
class IRendererCapture():
def capture_next_frame_rp_resource(self, filepath: str, resource: omni.gpu_foundation_factory._gpu_foundation_factory.RpResource, app_window: omni.appwindow._appwindow.IAppWindow = None, metadata: Metadata = None) -> None:
"""
Request capture RTX resource manager RpResource and save to a file.
"""
def capture_next_frame_rp_resource_callback(self, callback: typing.Callable[[capsule, int, int, int, omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat], None], resource: omni.gpu_foundation_factory._gpu_foundation_factory.RpResource, app_window: omni.appwindow._appwindow.IAppWindow = None, metadata: Metadata = None) -> None:
"""
Request capture RTX resource manager RpResource and trigger a callback when capture buffer is available.
"""
def capture_next_frame_rp_resource_list_callback(self, callback: typing.Callable[[typing.List[int], int, int, int, omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat], None], resource: omni.gpu_foundation_factory._gpu_foundation_factory.RpResource, app_window: omni.appwindow._appwindow.IAppWindow = None, metadata: Metadata = None) -> None:
"""
Request capture RTX resource manager RpResource and trigger a callback when capture buffer is available.
"""
def capture_next_frame_rp_resource_to_file(self, filepath: str, resource: omni.gpu_foundation_factory._gpu_foundation_factory.RpResource, app_window: omni.appwindow._appwindow.IAppWindow = None, format_desc: object = None, metadata: Metadata = None) -> None:
"""
Request capture RTX resource manager RpResource and save to a file.
"""
def capture_next_frame_swapchain(self, filepath: str, app_window: omni.appwindow._appwindow.IAppWindow = None, metadata: Metadata = None) -> None:
"""
Request capture swapchain and save to a file.
"""
def capture_next_frame_swapchain_callback(self, callback: typing.Callable[[capsule, int, int, int, omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat], None], app_window: omni.appwindow._appwindow.IAppWindow = None, metadata: Metadata = None) -> None:
"""
Request capture swapchain and trigger a callback when capture buffer is available.
"""
def capture_next_frame_swapchain_to_file(self, filepath: str, app_window: omni.appwindow._appwindow.IAppWindow = None, format_desc: object = None, metadata: Metadata = None) -> None:
"""
Request capture swapchain and save to a file.
"""
def capture_next_frame_texture(self, filepath: str, texture: omni.gpu_foundation_factory._gpu_foundation_factory.Texture = None, app_window: omni.appwindow._appwindow.IAppWindow = None, metadata: Metadata = None) -> None:
"""
Request capture texture and save to a file.
"""
def capture_next_frame_texture_callback(self, callback: typing.Callable[[capsule, int, int, int, omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat], None], texture: omni.gpu_foundation_factory._gpu_foundation_factory.Texture = None, app_window: omni.appwindow._appwindow.IAppWindow = None, metadata: Metadata = None) -> None:
"""
Request capture texture and trigger a callback when capture buffer is available.
"""
def capture_next_frame_texture_to_file(self, filepath: str, texture: omni.gpu_foundation_factory._gpu_foundation_factory.Texture = None, app_window: omni.appwindow._appwindow.IAppWindow = None, format_desc: object = None, metadata: Metadata = None) -> None:
"""
Request capture texture and save to a file.
"""
def capture_next_frame_using_render_product(self, viewport_handle: int, filepath: str, render_product: str) -> None:
"""
Request capture of all resources in render product
"""
def request_callback_memory_ownership(self) -> bool:
"""
Request memory ownership of a buffer passed into callback. Should be called from within a callback.
"""
def set_capture_sync(self, sync: bool, app_window: omni.appwindow._appwindow.IAppWindow = None) -> bool:
"""
Set synchronous capture mode.
"""
def shutdown(self) -> bool:
"""
Internal function. Shuts down capture interface.
"""
def start_frame_updates(self, app_window: omni.appwindow._appwindow.IAppWindow = None) -> bool:
"""
Starts per frame updates to collect capturing related data during each frame, such as FPS.
"""
def startup(self) -> bool:
"""
Internal function. Starts up capture interface.
"""
def wait_async_capture(self, app_window: omni.appwindow._appwindow.IAppWindow = None) -> None:
"""
Wait for asynchronous capture to complete.
"""
pass
class Metadata():
pass
def acquire_renderer_capture_interface(*args, **kwargs) -> typing.Any:
pass
def convert_raw_bytes_to_list(arg0: capsule, arg1: int, arg2: int, arg3: int, arg4: omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat) -> typing.List[int]:
pass
def convert_raw_bytes_to_rgba_tuples(arg0: capsule, arg1: int, arg2: int, arg3: int, arg4: omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat) -> typing.List[tuple]:
pass
| 5,729 | unknown | 59.957446 | 361 | 0.692617 |
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer_capture/__init__.py | from ._renderer_capture import *
| 33 | Python | 15.999992 | 32 | 0.757576 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdTextureToLinearArray.rst | .. _omni_syntheticdata_SdTextureToLinearArray_1:
.. _omni_syntheticdata_SdTextureToLinearArray:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Texture To Linear Array
:keywords: lang-en omnigraph node internal syntheticdata sd-texture-to-linear-array
Sd Texture To Linear Array
==========================
.. <description>
SyntheticData node to copy the input texture into a linear array buffer
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:cudaMipmappedArray", "``uint64``", "Pointer to the CUDA Mipmapped Array", "0"
"inputs:format", "``uint64``", "Format", "0"
"inputs:height", "``uint``", "Height", "0"
"inputs:hydraTime", "``double``", "Hydra time in stage", "0.0"
"inputs:mipCount", "``uint``", "Mip Count", "0"
"inputs:outputHeight", "``uint``", "Requested output height", "0"
"inputs:outputWidth", "``uint``", "Requested output width", "0"
"inputs:simTime", "``double``", "Simulation time", "0.0"
"inputs:stream", "``uint64``", "Pointer to the CUDA Stream", "0"
"inputs:width", "``uint``", "Width", "0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:data", "``float[4][]``", "Buffer array data", "[]"
"outputs:height", "``uint``", "Buffer array height", "None"
"outputs:hydraTime", "``double``", "Hydra time in stage", "None"
"outputs:simTime", "``double``", "Simulation time", "None"
"outputs:stream", "``uint64``", "Pointer to the CUDA Stream", "None"
"outputs:width", "``uint``", "Buffer array width", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdTextureToLinearArray"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "tests"
"Categories", "internal"
"Generated Class Name", "OgnSdTextureToLinearArrayDatabase"
"Python Module", "omni.syntheticdata"
| 2,479 | reStructuredText | 29.617284 | 99 | 0.578459 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdLinearArrayToTexture.rst | .. _omni_syntheticdata_SdLinearArrayToTexture_1:
.. _omni_syntheticdata_SdLinearArrayToTexture:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Linear Array To Texture
:keywords: lang-en omnigraph node graph:action syntheticdata sd-linear-array-to-texture
Sd Linear Array To Texture
==========================
.. <description>
Synthetic Data node to copy the input buffer array into a texture for visualization
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:data", "``float[4][]``", "Buffer array data", "[]"
"inputs:exec", "``execution``", "Trigger", "None"
"inputs:height", "``uint``", "Buffer array height", "0"
"inputs:sdDisplayCudaMipmappedArray", "``uint64``", "Visualization texture CUDA mipmapped array pointer", "0"
"inputs:sdDisplayFormat", "``uint64``", "Visualization texture format", "0"
"inputs:sdDisplayHeight", "``uint``", "Visualization texture Height", "0"
"inputs:sdDisplayStream", "``uint64``", "Visualization texture CUDA stream pointer", "0"
"inputs:sdDisplayWidth", "``uint``", "Visualization texture width", "0"
"inputs:stream", "``uint64``", "Pointer to the CUDA Stream", "0"
"inputs:width", "``uint``", "Buffer array width", "0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:cudaPtr", "``uint64``", "Display texture CUDA pointer", "None"
"Received (*outputs:exec*)", "``execution``", "Executes when the event is received", "None"
"outputs:format", "``uint64``", "Display texture format", "None"
"outputs:handlePtr", "``uint64``", "Display texture handle reference", "None"
"outputs:height", "``uint``", "Display texture height", "None"
"outputs:stream", "``uint64``", "Output texture CUDA stream pointer", "None"
"outputs:width", "``uint``", "Display texture width", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdLinearArrayToTexture"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "tests"
"Categories", "graph:action"
"Generated Class Name", "OgnSdLinearArrayToTextureDatabase"
"Python Module", "omni.syntheticdata"
| 2,767 | reStructuredText | 32.756097 | 113 | 0.606072 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdSemanticFilter.rst | .. _omni_syntheticdata_SdSemanticFilter_1:
.. _omni_syntheticdata_SdSemanticFilter:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Semantic Filter
:keywords: lang-en omnigraph node graph:simulation syntheticdata sd-semantic-filter
Sd Semantic Filter
==================
.. <description>
Synthetic Data node to declare a semantic filter.
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:exec", "``execution``", "Dependency", "None"
"inputs:hierarchicalLabels", "``bool``", "If true the filter consider all labels in the semantic hierarchy above the prims", "False"
"inputs:matchingLabels", "``bool``", "If true output only the labels matching the filter (if false keep all labels of the matching prims)", "True"
"inputs:name", "``token``", "Filter unique identifier [if empty, use the normalized predicate as an identifier]", ""
"inputs:predicate", "``token``", "The semantic filter specification : a disjunctive normal form of semantic type and label", ""
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:exec", "``execution``", "Trigger", "None"
"outputs:name", "``token``", "The semantic filter name identifier", ""
"outputs:predicate", "``token``", "The semantic filter predicate in normalized form", ""
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdSemanticFilter"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"Categories", "graph:simulation"
"Generated Class Name", "OgnSdSemanticFilterDatabase"
"Python Module", "omni.syntheticdata"
| 2,224 | reStructuredText | 29.479452 | 150 | 0.609712 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdTestStageSynchronization.rst | .. _omni_syntheticdata_SdTestStageSynchronization_1:
.. _omni_syntheticdata_SdTestStageSynchronization:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Test Stage Synchronization
:keywords: lang-en omnigraph node graph:simulation,graph:postRender,graph:action,internal:test syntheticdata sd-test-stage-synchronization
Sd Test Stage Synchronization
=============================
.. <description>
Synthetic Data node to test the pipeline stage synchronization
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:exec", "``execution``", "OnDemand connection : trigger", "None"
"gpuFoundations (*inputs:gpu*)", "``uint64``", "PostRender connection : pointer to shared context containing gpu foundations", "0"
"inputs:randomMaxProcessingTimeUs", "``uint``", "Maximum number of micro-seconds to randomly (uniformely) wait for in order to simulate varying workload", "0"
"inputs:randomSeed", "``uint``", "Random seed for the randomization", "0"
"inputs:renderResults", "``uint64``", "OnDemand connection : pointer to render product results", "0"
"renderProduct (*inputs:rp*)", "``uint64``", "PostRender connection : pointer to render product for this view", "0"
"inputs:swhFrameNumber", "``uint64``", "Fabric frame number", "0"
"inputs:tag", "``token``", "A tag to identify the node", ""
"inputs:traceError", "``bool``", "If true print an error message when the frame numbers are out-of-sync", "False"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:exec", "``execution``", "OnDemand connection : trigger", "None"
"outputs:fabricSWHFrameNumber", "``uint64``", "Fabric frame number from the fabric", "None"
"outputs:swhFrameNumber", "``uint64``", "Fabric frame number", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdTestStageSynchronization"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "tests"
"Categories", "graph:simulation,graph:postRender,graph:action,internal:test"
"Generated Class Name", "OgnSdTestStageSynchronizationDatabase"
"Python Module", "omni.syntheticdata"
| 2,765 | reStructuredText | 34.922077 | 162 | 0.633273 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdTestInstanceMapping.rst | .. _omni_syntheticdata_SdTestInstanceMapping_1:
.. _omni_syntheticdata_SdTestInstanceMapping:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Test Instance Mapping
:keywords: lang-en omnigraph node graph:simulation,graph:postRender,graph:action,internal:test syntheticdata sd-test-instance-mapping
Sd Test Instance Mapping
========================
.. <description>
Synthetic Data node to test the instance mapping pipeline
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:exec", "``execution``", "Trigger", "None"
"inputs:instanceMapPtr", "``uint64``", "Array pointer of numInstances uint16_t containing the semantic index of the instance prim first semantic prim parent", "0"
"inputs:instancePrimPathPtr", "``uint64``", "Array pointer of numInstances uint64_t containing the prim path tokens for every instance prims", "0"
"inputs:minInstanceIndex", "``uint``", "Instance index of the first instance prim in the instance arrays", "0"
"inputs:minSemanticIndex", "``uint``", "Semantic index of the first semantic prim in the semantic arrays", "0"
"inputs:numInstances", "``uint``", "Number of instances prim in the instance arrays", "0"
"inputs:numSemantics", "``uint``", "Number of semantic prim in the semantic arrays", "0"
"inputs:semanticLabelTokenPtrs", "``uint64[]``", "Array containing for every input semantic filters the corresponding array pointer of numSemantics uint64_t representing the semantic label of the semantic prim", "[]"
"inputs:semanticLocalTransformPtr", "``uint64``", "Array pointer of numSemantics 4x4 float matrices containing the transform from world to object space for every semantic prims", "0"
"inputs:semanticMapPtr", "``uint64``", "Array pointer of numSemantics uint16_t containing the semantic index of the semantic prim first semantic prim parent", "0"
"inputs:semanticPrimPathPtr", "``uint64``", "Array pointer of numSemantics uint32_t containing the prim part of the prim path tokens for every semantic prims", "0"
"inputs:semanticWorldTransformPtr", "``uint64``", "Array pointer of numSemantics 4x4 float matrices containing the transform from local to world space for every semantic entity", "0"
"inputs:stage", "``token``", "Stage in {simulation, postrender, ondemand}", ""
"inputs:swhFrameNumber", "``uint64``", "Fabric frame number", "0"
"inputs:testCaseIndex", "``int``", "Test case index", "-1"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Received (*outputs:exec*)", "``execution``", "Executes when the event is received", "None"
"outputs:semanticFilterPredicate", "``token``", "The semantic filter predicate : a disjunctive normal form of semantic type and label", "None"
"outputs:success", "``bool``", "Test value : false if failed", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdTestInstanceMapping"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"__tokens", "[""simulation"", ""postRender"", ""onDemand""]"
"Categories", "graph:simulation,graph:postRender,graph:action,internal:test"
"Generated Class Name", "OgnSdTestInstanceMappingDatabase"
"Python Module", "omni.syntheticdata"
| 3,860 | reStructuredText | 44.964285 | 220 | 0.664508 |
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdPostSemanticBoundingBox.rst | .. _omni_syntheticdata_SdPostSemanticBoundingBox_1:
.. _omni_syntheticdata_SdPostSemanticBoundingBox:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sd Post Semantic Bounding Box
:keywords: lang-en omnigraph node graph:postRender,rendering syntheticdata sd-post-semantic-bounding-box
Sd Post Semantic Bounding Box
=============================
.. <description>
Synthetic Data node to compute the bounding boxes of the scene semantic entities.
.. </description>
Installation
------------
To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:exec", "``execution``", "Trigger", "None"
"gpuFoundations (*inputs:gpu*)", "``uint64``", "Pointer to shared context containing gpu foundations", "0"
"inputs:instanceMapSDCudaPtr", "``uint64``", "cuda uint16_t buffer pointer of size numInstances containing the instance parent semantic index", "0"
"inputs:instanceMappingInfoSDPtr", "``uint64``", "uint buffer pointer containing the following information : [numInstances, minInstanceId, numSemantics, minSemanticId, numProtoSemantic]", "0"
"inputs:renderProductResolution", "``int[2]``", "RenderProduct resolution", "[0, 0]"
"inputs:renderVar", "``token``", "Name of the BoundingBox RenderVar to process", ""
"renderProduct (*inputs:rp*)", "``uint64``", "Pointer to render product for this view", "0"
"inputs:semanticLocalTransformSDCudaPtr", "``uint64``", "cuda float44 buffer pointer of size numSemantics containing the local semantic transform", "0"
"inputs:semanticMapSDCudaPtr", "``uint64``", "cuda uint16_t buffer pointer of size numSemantics containing the semantic parent semantic index", "0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:exec", "``execution``", "Trigger", "None"
"outputs:sdSemBBoxExtentCudaPtr", "``uint64``", "Cuda buffer containing the extent of the bounding boxes as a float4=(u_min,v_min,u_max,v_max) for 2D or a float6=(xmin,ymin,zmin,xmax,ymax,zmax) in object space for 3D", "None"
"outputs:sdSemBBoxInfosCudaPtr", "``uint64``", "Cuda buffer containing valid bounding boxes infos", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.syntheticdata.SdPostSemanticBoundingBox"
"Version", "1"
"Extension", "omni.syntheticdata"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"__tokens", "[""BoundingBox2DLooseSD"", ""BoundingBox2DTightSD"", ""SemanticBoundingBox2DExtentLooseSD"", ""SemanticBoundingBox2DInfosLooseSD"", ""SemanticBoundingBox2DExtentTightSD"", ""SemanticBoundingBox2DInfosTightSD"", ""BoundingBox3DSD"", ""SemanticBoundingBox3DExtentSD"", ""SemanticBoundingBox3DInfosSD""]"
"Categories", "graph:postRender,rendering"
"Generated Class Name", "OgnSdPostSemanticBoundingBoxDatabase"
"Python Module", "omni.syntheticdata"
| 3,344 | reStructuredText | 41.884615 | 318 | 0.664773 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.