file_path
stringlengths 21
202
| content
stringlengths 12
1.02M
| size
int64 12
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 3.33
100
| max_line_length
int64 10
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_present.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.
##
from .test_base import OmniUiTest
from functools import partial
import asyncio
import carb.settings
import csv
import omni.appwindow
import omni.kit.app
import omni.kit.renderer
import omni.ui as ui
import os
color = 0xFF123456
color_settings_path = "/exts/omni.kit.renderer.core/imgui/csvDump/vertexColor"
dump_settings_path = "/exts/omni.kit.renderer.core/imgui/csvDump/path"
enabled_settings_path = "/exts/omni.kit.renderer.core/present/enabled"
present_settings_path = "/app/runLoops/present/rateLimitFrequency"
main_settings_path = "/app/runLoops/main/rateLimitFrequency"
busy_present_settings_path = "/app/runLoops/present/rateLimitUseBusyLoop"
busy_main_settings_path = "/app/runLoops/main/rateLimitUseBusyLoop"
sync_settings_path = "/app/runLoops/main/syncToPresent"
global_sync_settings_path = "/app/runLoopsGlobal/syncToPresent"
async def _moving_rect(window, description: str):
"""
Setups moving rect in the given window. Setups csv dump from imgui. Reads
the dump and returns computed FPS for the current (from ImGui renderer point
of view present) and the main thread.
"""
rect_size = 50
speed = 0.02
max_counter = 1.0
settings = carb.settings.get_settings()
# Get a path to dump csv in the _testoutput directory
temp_path = os.path.join(omni.kit.test.get_test_output_path(), f"moving_rect-{description}.csv")
# remove any existing file (it's creation will be waited on below)
try:
os.remove(temp_path)
except FileNotFoundError:
pass
# pre-roll some frames for UI (to deal with test window resizing)
for _ in range(90):
await omni.kit.app.get_app().next_update_async()
with window.frame:
with ui.VStack():
ui.Spacer()
with ui.HStack(height=rect_size):
left = ui.Spacer(width=0)
ui.Rectangle(width=rect_size, style={"background_color": color})
right = ui.Spacer()
ui.Spacer()
# pre-roll even more frames after the UI was built
for _ in range(90):
await omni.kit.app.get_app().next_update_async()
settings.set(color_settings_path, color)
settings.set(dump_settings_path, temp_path)
# Move the rect
counter = 0.0
while counter <= max_counter:
await omni.kit.app.get_app().next_update_async()
counter += speed
normalized = counter % 2.0
if normalized > 1.0:
normalized = 2.0 - normalized
left.width = ui.Fraction(normalized)
right.width = ui.Fraction(1.0 - normalized)
# this is actually going to trigger the dump to temp_path
settings.set(dump_settings_path, "")
# now wait for temp_path to be generated
while not os.path.isfile(temp_path):
await omni.kit.app.get_app().next_update_async()
# file should be atomically swapped into place fully written
# but wait one frame before reading just in case
await omni.kit.app.get_app().next_update_async()
with open(temp_path, "r") as f:
reader = csv.reader(f)
data = [row for row in reader]
keys, values = zip(*data)
min_key = int(keys[0])
keys = [float((int(x) - min_key) / 10000) for x in keys]
values = [float(x) for x in values]
time_delta = [keys[i] - keys[i - 1] for i in range(1, len(keys))]
values = [values[i] - values[i - 1] for i in range(1, len(values))]
keys = keys[1:]
min_value, max_value = min(values), max(values)
margin = (max_value - min_value) * 0.1
min_value -= margin
max_value += margin
min_time = min(time_delta)
max_time = max(time_delta)
fps_current = 1000.0 / (sum(time_delta) / len(time_delta))
fps_main = 1000.0 / (keys[-1] / (max_counter / speed))
return fps_current, fps_main
def _on_present(future: asyncio.Future, counter, frames_to_wait, event):
"""
Sets result of the future after `frames_to_wait` calls.
"""
if not future.done():
if counter[0] < frames_to_wait:
counter[0] += 1
else:
future.set_result(True)
async def next_update_present_async(frames_to_wait):
"""
Warms up the present thread because it takes long time to enable it the
first time. It enables it and waits `frames_to_wait` frames of present
thread. `next_update_async` doesn't work here because it's related to the
main thread.
"""
_app_window_factory = omni.appwindow.acquire_app_window_factory_interface()
_app_window = _app_window_factory.get_windows()[0]
_renderer = omni.kit.renderer.bind.acquire_renderer_interface()
_stream = _renderer.get_post_present_frame_buffer_event_stream(_app_window)
counter = [0]
f = asyncio.Future()
_subscription = _stream.create_subscription_to_push(
partial(_on_present, f, counter, frames_to_wait), 0, "omni.ui Test"
)
await f
await omni.kit.app.get_app().next_update_async()
class TestPresent(OmniUiTest):
"""
Testing how the present thread works and how main thread is synchronized to
the present thread.
"""
async def setup_fps_test(
self, set_main: float, set_present: float, expect_main: float, expect_present: float, threshold: float = 0.1
):
"""
Set environment and fps for present and main thread and runs the
rectangle test. Compares the computed FPS with the given values.
Threshold is the number FPS can be different from expected.
"""
window = await self.create_test_window()
# Save the environment
settings = carb.settings.get_settings()
buffer_enabled = settings.get(enabled_settings_path)
buffer_present_fps = settings.get(present_settings_path)
buffer_main_fps = settings.get(main_settings_path)
buffer_present_busy = settings.get(busy_present_settings_path)
buffer_main_busy = settings.get(busy_main_settings_path)
buffer_sync = settings.get(sync_settings_path)
buffer_global_sync = settings.get(global_sync_settings_path)
finalized = False
try:
# Modify the environment
settings.set(present_settings_path, set_present)
settings.set(main_settings_path, set_main)
settings.set(busy_present_settings_path, True)
settings.set(busy_main_settings_path, True)
settings.set(sync_settings_path, True)
settings.set(global_sync_settings_path, True)
settings.set(enabled_settings_path, True)
for _ in range(2):
await omni.kit.app.get_app().next_update_async()
await next_update_present_async(10)
fps_current, fps_main = await _moving_rect(
window, f"{set_main}-{set_present}-{expect_main}-{expect_present}"
)
await self.finalize_test_no_image()
finalized = True
for _ in range(2):
await omni.kit.app.get_app().next_update_async()
# Check the result
self.assertTrue(abs(1.0 - expect_present / fps_current) < threshold)
self.assertTrue(abs(1.0 - expect_main / fps_main) < threshold)
finally:
# Restore the environment
settings.set(present_settings_path, buffer_present_fps)
settings.set(main_settings_path, buffer_main_fps)
settings.set(busy_present_settings_path, buffer_present_busy)
settings.set(busy_main_settings_path, buffer_main_busy)
settings.set(sync_settings_path, buffer_sync)
settings.set(global_sync_settings_path, buffer_global_sync)
settings.set(enabled_settings_path, buffer_enabled)
settings.set(dump_settings_path, "")
settings.set(color_settings_path, "")
if not finalized:
await self.finalize_test_no_image()
async def test_general_30_30(self):
# Set main 30; present: 30
# Expect after sync: main 30; present: 30
await self.setup_fps_test(30.0, 30.0, 30.0, 30.0)
async def test_general_60_30(self):
# Set main 60; present: 30
# Expect after sync: main 60; present: 30
await self.setup_fps_test(60.0, 30.0, 60.0, 30.0)
async def test_general_40_30(self):
# Set main 40; present: 30
# Expect after sync: main 60; present: 30
await self.setup_fps_test(40.0, 30.0, 30.0, 30.0)
async def test_general_20_30(self):
# Set main 20; present: 30
# Expect after sync: main 30; present: 30
await self.setup_fps_test(20.0, 30.0, 15.0, 30.0)
| 9,059 |
Python
| 36.28395 | 116 | 0.645546 |
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_shadows.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.
##
__all__ = ["TestShadows"]
import omni.kit.test
from .test_base import OmniUiTest
import omni.ui as ui
from omni.ui import color as cl
class TestShadows(OmniUiTest):
"""Testing shadow for ui.Shape"""
async def test_rectangle(self):
"""Testing rectangle shadow"""
window = await self.create_test_window()
with window.frame:
with ui.HStack():
ui.Spacer()
with ui.VStack():
ui.Spacer()
ui.Rectangle(
width=100,
height=100,
style={
"background_color": cl.transparent,
"shadow_flag": 1, "shadow_color": cl.blue,
"shadow_thickness": 20,
"shadow_offset_x": 3,
"shadow_offset_y": 3,
"border_width": 0,
"border_color": 0x22FFFF00,
"border_radius": 20,
"corner_flag": ui.CornerFlag.RIGHT})
ui.Spacer()
ui.Spacer()
await self.finalize_test()
async def test_circle(self):
"""Testing circle shadow"""
window = await self.create_test_window()
with window.frame:
with ui.HStack():
ui.Spacer()
with ui.VStack():
ui.Spacer()
ui.Circle(
width=60,
height=70,
alignment=ui.Alignment.RIGHT_BOTTOM,
style={
"background_color": cl.yellow,
"shadow_color": cl.blue,
"shadow_thickness": 20,
"shadow_offset_x": 6,
"shadow_offset_y": -6,
"border_width": 20,
"border_color": cl.blue})
ui.Spacer()
ui.Spacer()
await self.finalize_test()
async def test_triangle(self):
"""Testing triangle shadow"""
window = await self.create_test_window()
with window.frame:
with ui.HStack():
ui.Spacer()
with ui.VStack():
ui.Spacer()
ui.Triangle(
width=100,
height=80,
alignment=ui.Alignment.RIGHT_TOP,
style={
"background_color": cl.red,
"shadow_color": cl.blue,
"shadow_thickness": 10,
"shadow_offset_x": -8,
"shadow_offset_y": 5})
ui.Spacer()
ui.Spacer()
await self.finalize_test()
async def test_line(self):
"""Testing line shadow"""
window = await self.create_test_window()
with window.frame:
with ui.HStack():
ui.Spacer()
with ui.VStack():
ui.Spacer()
ui.Line(
alignment=ui.Alignment.LEFT,
style={
"color": cl.red,
"shadow_color": cl.green,
"shadow_thickness": 15,
"shadow_offset_x": 3,
"shadow_offset_y": 3,
"border_width": 10})
ui.Spacer()
ui.Spacer()
await self.finalize_test()
async def test_ellipse(self):
"""Testing ellipse shadow"""
window = await self.create_test_window()
with window.frame:
with ui.HStack():
ui.Spacer(width=15)
with ui.VStack():
ui.Spacer(height=35)
ui.Ellipse(
style={
"background_color": cl.green,
"shadow_color": cl.red,
"shadow_thickness": 20,
"shadow_offset_x": 5,
"shadow_offset_y": -5,
"border_width": 5,
"border_color": cl.blue})
ui.Spacer(height=35)
ui.Spacer(width=15)
await self.finalize_test()
async def test_freeshape(self):
"""Testing freeshap with shadow"""
window = await self.create_test_window()
with window.frame:
with ui.ZStack():
# 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)
with ui.Placer(draggable=True, offset_x=150, offset_y=150):
control2 = ui.Circle(width=10, height=10)
# The rectangle that fits to the control points
ui.FreeRectangle(
control1,
control2,
style={
"background_color": cl(0.6),
"border_color": cl(0.1),
"border_width": 1.0,
"border_radius": 8.0,
"shadow_color": cl.red,
"shadow_thickness": 20,
"shadow_offset_x": 5,
"shadow_offset_y": 5})
await self.finalize_test()
async def test_buttons(self):
"""Testing button with shadow"""
window = await self.create_test_window()
with window.frame:
with ui.VStack(spacing=10):
ui.Button(
"One",
height=30,
style={
"shadow_flag": 1,
"shadow_color": cl.blue,
"shadow_thickness": 13,
"shadow_offset_x": 3,
"shadow_offset_y": 3,
"border_width": 3,
"border_color": cl.green,
"border_radius": 3})
ui.Button(
"Two",
height=30,
style={
"shadow_flag": 1,
"shadow_color": cl.red,
"shadow_thickness": 10,
"shadow_offset_x": 2,
"shadow_offset_y": 2,
"border_radius": 3})
ui.Button(
"Three",
height=30,
style={
"shadow_flag": 1,
"shadow_color": cl.green,
"shadow_thickness": 5,
"shadow_offset_x": 4,
"shadow_offset_y": 4})
await self.finalize_test()
| 7,607 |
Python
| 35.932039 | 77 | 0.411989 |
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_label.py
|
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from .test_base import OmniUiTest
import omni.kit.app
import omni.ui as ui
class TestLabel(OmniUiTest):
"""Testing ui.Label"""
async def test_general(self):
"""Testing general properties of ui.Label"""
window = await self.create_test_window()
with window.frame:
with ui.VStack(height=0):
# Simple text
ui.Label("Hello world")
# Word wrap
ui.Label(
"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.",
word_wrap=True,
)
# Computing text size
with ui.HStack(width=0):
ui.Label("A")
ui.Label("BC")
ui.Label("DEF")
ui.Label("GHIjk")
ui.Label("lmnopq")
ui.Label("rstuvwxyz")
# Styling
ui.Label("Red", style={"color": 0xFF0000FF})
ui.Label("Green", style={"Label": {"color": 0xFF00FF00}})
ui.Label("Blue", style_type_name_override="TreeView", style={"TreeView": {"color": 0xFFFF0000}})
await self.finalize_test()
async def test_alignment(self):
"""Testing alignment of ui.Label"""
window = await self.create_test_window()
with window.frame:
with ui.ZStack():
ui.Label("Left Top", alignment=ui.Alignment.LEFT_TOP)
ui.Label("Center Top", alignment=ui.Alignment.CENTER_TOP)
ui.Label("Right Top", alignment=ui.Alignment.RIGHT_TOP)
ui.Label("Left Center", alignment=ui.Alignment.LEFT_CENTER)
ui.Label("Center", alignment=ui.Alignment.CENTER)
ui.Label("Right Center", alignment=ui.Alignment.RIGHT_CENTER)
ui.Label("Left Bottom", alignment=ui.Alignment.LEFT_BOTTOM)
ui.Label("Center Bottom", alignment=ui.Alignment.CENTER_BOTTOM)
ui.Label("Right Bottom", alignment=ui.Alignment.RIGHT_BOTTOM)
await self.finalize_test()
async def test_wrap_alignment(self):
"""Testing alignment of ui.Label with word_wrap"""
window = await self.create_test_window()
with window.frame:
ui.Label(
"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.",
word_wrap=True,
style={"Label": {"alignment": ui.Alignment.CENTER}},
)
await self.finalize_test()
async def test_elide(self):
"""Testing ui.Label with elided_text"""
window = await self.create_test_window()
with window.frame:
with ui.VStack():
ui.Label(
"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.",
elided_text=True,
height=0,
)
ui.Label(
"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.",
word_wrap=True,
elided_text=True,
)
ui.Label(
"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.",
alignment=ui.Alignment.CENTER,
word_wrap=True,
elided_text=True,
)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_change_size(self):
"""Testing how ui.Label dynamically changes size"""
window = await self.create_test_window()
with window.frame:
with ui.VStack(style={"Rectangle": {"background_color": 0xFFFFFFFF}}):
with ui.HStack(height=0):
with ui.Frame(width=0):
line1 = ui.Label("Test")
ui.Rectangle()
with ui.HStack(height=0):
with ui.Frame(width=0):
line2 = ui.Label("Test")
ui.Rectangle()
with ui.Frame(height=0):
line3 = ui.Label("Test", word_wrap=True)
ui.Rectangle()
for i in range(2):
await omni.kit.app.get_app().next_update_async()
# Change the text
line1.text = "Bigger than before"
line2.text = "a"
line3.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."
)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_font(self):
window = await self.create_test_window()
with window.frame:
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,
)
await self.finalize_test()
async def test_invalid_font(self):
window = await self.create_test_window()
with window.frame:
ui.Label(
"The quick brown fox jumps over the lazy dog",
style={"font_size": 55, "font": "${fonts}/IDoNotExist.ttf", "alignment": ui.Alignment.CENTER},
word_wrap=True,
)
await self.finalize_test()
async def test_mouse_released_fn(self):
"""Test mouse_released_fn only triggers on widget which was pressed"""
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
release_count = [0, 0]
def release(i):
release_count[i] += 1
with window.frame:
with ui.VStack():
label1 = ui.Label("1", mouse_released_fn=lambda *_: release(0))
label2 = ui.Label("2", mouse_released_fn=lambda *_: release(1))
try:
await omni.kit.app.get_app().next_update_async()
refLabel1 = ui_test.WidgetRef(label1, "")
refLabel2 = ui_test.WidgetRef(label2, "")
await omni.kit.app.get_app().next_update_async()
# Left button
await ui_test.emulate_mouse_drag_and_drop(refLabel1.center, refLabel2.center)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(release_count[0], 1)
self.assertEqual(release_count[1], 0)
# Right button
release_count = [0, 0]
await ui_test.emulate_mouse_drag_and_drop(refLabel1.center, refLabel2.center, right_click=True)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(release_count[0], 1)
self.assertEqual(release_count[1], 0)
finally:
await self.finalize_test_no_image()
async def test_exact_content_size(self):
"""Test the exact content width/height properties"""
CHAR_WIDTH = 7
CHAR_HEIGHT = 14
window = await self.create_test_window()
with window.frame:
with ui.VStack(height=0):
with ui.HStack():
label1 = ui.Label("1")
label10 = ui.Label("10")
label1234 = ui.Label("1234")
label_wrap = ui.Label(
"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.",
word_wrap=True,
)
label_elided = ui.Label(
"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.",
elided_text=True,
)
await omni.kit.app.get_app().next_update_async()
# Verify width of text
self.assertEqual(label1.exact_content_width, CHAR_WIDTH)
self.assertEqual(label10.exact_content_width, CHAR_WIDTH*2)
self.assertEqual(label1234.exact_content_width, CHAR_WIDTH*4)
self.assertEqual(label_wrap.exact_content_width, CHAR_WIDTH*35)
self.assertAlmostEqual(label_elided.computed_content_width, 248.0, 3)
# Verify height
self.assertEqual(label1.exact_content_height, CHAR_HEIGHT)
self.assertEqual(label10.exact_content_height, CHAR_HEIGHT)
self.assertEqual(label1234.exact_content_height, CHAR_HEIGHT)
self.assertEqual(label_wrap.exact_content_height, CHAR_HEIGHT*11)
self.assertEqual(label_elided.exact_content_height, CHAR_HEIGHT)
# Change the text
label1.text = "12345"
await omni.kit.app.get_app().next_update_async()
self.assertEqual(label1.exact_content_width, CHAR_WIDTH*5)
self.assertEqual(label1.exact_content_height, CHAR_HEIGHT)
# Change text (no word wrap), should just resize the label
label10.text = (
"1234567890"
"1234567890"
"1234567890"
)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(label10.exact_content_width, CHAR_WIDTH*30)
self.assertEqual(label10.exact_content_height, CHAR_HEIGHT)
await self.finalize_test_no_image()
| 13,358 |
Python
| 45.224913 | 117 | 0.592679 |
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_raster.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.
##
from functools import partial
from .test_base import OmniUiTest
import omni.ui as ui
import omni.kit.app
class TestRaster(OmniUiTest):
"""Testing ui.Frame"""
async def test_general(self):
import omni.kit.ui_test as ui_test
from carb.input import MouseEventType
window = await self.create_test_window(block_devices=False)
with window.frame:
with ui.HStack():
left_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
right_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
with left_frame:
ui.Rectangle(style={"background_color": ui.color.grey})
with right_frame:
ui.Rectangle(style={"background_color": ui.color.grey})
left_frame_ref = ui_test.WidgetRef(left_frame, "")
right_frame_ref = ui_test.WidgetRef(right_frame, "")
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse_move(right_frame_ref.center)
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse_move(left_frame_ref.center)
await ui_test.input.wait_n_updates_internal()
await self.finalize_test()
async def test_edit(self):
import omni.kit.ui_test as ui_test
from carb.input import MouseEventType
window = await self.create_test_window(block_devices=False)
with window.frame:
with ui.HStack():
left_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
right_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
with left_frame:
ui.Rectangle(style={"background_color": ui.color.grey})
with right_frame:
with ui.ZStack():
ui.Rectangle(style={"background_color": ui.color.grey})
with ui.VStack():
ui.Spacer()
field = ui.StringField(height=0)
ui.Spacer()
left_frame_ref = ui_test.WidgetRef(left_frame, "")
field_ref = ui_test.WidgetRef(field, "")
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse_move_and_click(field_ref.center)
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse_move(left_frame_ref.center)
await ui_test.input.wait_n_updates_internal()
await self.finalize_test()
async def test_dnd(self):
import omni.kit.ui_test as ui_test
from carb.input import MouseEventType
window = await self.create_test_window(
block_devices=False,
window_flags=ui.WINDOW_FLAGS_NO_SCROLLBAR
| ui.WINDOW_FLAGS_NO_TITLE_BAR
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_MOVE,
)
with window.frame:
with ui.HStack():
left_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
right_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
with left_frame:
ui.Rectangle(style={"background_color": ui.color.grey})
with right_frame:
ui.Rectangle(style={"background_color": ui.color.grey})
left_frame_ref = ui_test.WidgetRef(left_frame, "")
right_frame_ref = ui_test.WidgetRef(right_frame, "")
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse(MouseEventType.MOVE, left_frame_ref.center)
await ui_test.input.emulate_mouse(MouseEventType.LEFT_BUTTON_DOWN)
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse_slow_move(left_frame_ref.center, right_frame_ref.center)
await self.finalize_test()
await ui_test.input.emulate_mouse(MouseEventType.LEFT_BUTTON_UP)
async def test_update(self):
import omni.kit.ui_test as ui_test
from carb.input import MouseEventType
window = await self.create_test_window(block_devices=False)
with window.frame:
with ui.HStack():
left_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
right_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
with left_frame:
ui.Rectangle(style={"background_color": ui.color.grey})
with right_frame:
ui.Rectangle(style={"background_color": ui.color.grey})
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse_move(ui_test.input.Vec2(0, 0))
with right_frame:
ui.Rectangle(style={"background_color": ui.color.beige})
await ui_test.input.wait_n_updates_internal(update_count=4)
await self.finalize_test()
async def test_model(self):
import omni.kit.ui_test as ui_test
from carb.input import MouseEventType
window = await self.create_test_window(block_devices=False)
with window.frame:
with ui.HStack():
left_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
right_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
with left_frame:
ui.Rectangle(style={"background_color": ui.color.grey})
with right_frame:
with ui.ZStack():
ui.Rectangle(style={"background_color": ui.color.grey})
with ui.VStack():
ui.Spacer()
field = ui.StringField(height=0)
ui.Spacer()
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse_move(ui_test.input.Vec2(0, 0))
field.model.as_string = "NVIDIA"
await ui_test.input.wait_n_updates_internal(update_count=4)
await self.finalize_test()
async def test_on_demand(self):
import omni.kit.ui_test as ui_test
from carb.input import MouseEventType
window = await self.create_test_window(block_devices=False)
with window.frame:
with ui.HStack():
right_frame = ui.Frame(raster_policy=ui.RasterPolicy.ON_DEMAND)
with right_frame:
with ui.ZStack():
ui.Rectangle(style={"background_color": ui.color.grey})
with ui.VStack():
ui.Spacer()
field = ui.StringField(height=0)
ui.Spacer()
right_frame_ref = ui_test.WidgetRef(right_frame, "")
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse_move(right_frame_ref.center)
field.model.as_string = "NVIDIA"
await ui_test.input.wait_n_updates_internal(update_count=4)
await self.finalize_test()
async def test_on_demand_invalidate(self):
import omni.kit.ui_test as ui_test
from carb.input import MouseEventType
window = await self.create_test_window(block_devices=False)
with window.frame:
with ui.HStack():
right_frame = ui.Frame(raster_policy=ui.RasterPolicy.ON_DEMAND)
with right_frame:
with ui.ZStack():
ui.Rectangle(style={"background_color": ui.color.grey})
with ui.VStack():
ui.Spacer()
field = ui.StringField(height=0)
ui.Spacer()
right_frame_ref = ui_test.WidgetRef(right_frame, "")
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse_move(right_frame_ref.center)
field.model.as_string = "NVIDIA"
await ui_test.input.wait_n_updates_internal(update_count=4)
right_frame.invalidate_raster()
await ui_test.input.wait_n_updates_internal(update_count=4)
await self.finalize_test()
async def test_child_window(self):
"""Testing rasterization when mouse hovers child window"""
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
small_window = ui.Window("small", width=100, height=100, position_x=0, position_y=0)
with small_window.frame:
with ui.VStack():
with ui.Frame(raster_policy=ui.RasterPolicy.AUTO):
with ui.VStack():
ui.Label("NVIDIA")
with ui.Frame(raster_policy=ui.RasterPolicy.AUTO):
with ui.VStack():
ui.Spacer()
combo = ui.ComboBox(1, "one", "two", "three", "four", height=0)
await ui_test.input.wait_n_updates_internal(update_count=2)
# Clicking the combo box in the small window
combo_ref = ui_test.WidgetRef(combo, "")
await ui_test.input.emulate_mouse_move_and_click(combo_ref.center)
await ui_test.input.wait_n_updates_internal(update_count=2)
# Moving the mouse over the combo box and outside the window
await ui_test.input.emulate_mouse_move(ui_test.input.Vec2(combo_ref.center.x, combo_ref.center.y + 80))
await ui_test.input.wait_n_updates_internal(update_count=6)
await self.finalize_test()
async def test_label(self):
import omni.kit.ui_test as ui_test
window = await self.create_test_window()
with window.frame:
with ui.HStack():
left_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
right_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
with left_frame:
l = ui.Label("Left")
with right_frame:
r = ui.Label("Right")
await ui_test.input.wait_n_updates_internal()
l.text = "NVIDIA"
r.text = "Omniverse"
await ui_test.input.wait_n_updates_internal(update_count=4)
await self.finalize_test()
async def test_canvasframe_lod(self):
import omni.kit.ui_test as ui_test
window = await self.create_test_window()
with window.frame:
with ui.Frame(raster_policy=ui.RasterPolicy.AUTO):
canvas = ui.CanvasFrame()
with canvas:
with ui.ZStack():
p1 = ui.Placer(stable_size=1, draggable=1)
with p1:
with ui.Frame(raster_policy=ui.RasterPolicy.AUTO):
ui.Rectangle(style={"background_color": ui.color.blue}, visible_min=0.5)
p2 = ui.Placer(stable_size=1, draggable=1)
with p2:
with ui.Frame(raster_policy=ui.RasterPolicy.AUTO):
ui.Rectangle(style={"background_color": ui.color.green}, visible_max=0.5)
await ui_test.input.wait_n_updates_internal(update_count=4)
canvas.zoom = 0.25
await ui_test.input.wait_n_updates_internal(update_count=4)
canvas.zoom = 1.0
await ui_test.input.wait_n_updates_internal(update_count=4)
p2.offset_x = 300
p2.offset_y = 300
await ui_test.input.wait_n_updates_internal(update_count=4)
canvas.zoom = 0.25
await ui_test.input.wait_n_updates_internal(update_count=4)
await self.finalize_test()
| 11,688 |
Python
| 34.637195 | 111 | 0.603867 |
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_placer.py
|
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from .test_base import OmniUiTest
import omni.ui as ui
import omni.kit.app
RECT_SIZE = 10
RECT_STYLE = {"background_color": 0xFFFFFFFF}
RECT_TRANSPARENT_STYLE = {"background_color": 0x66FFFFFF, "border_color": 0xFFFFFFFF, "border_width": 1}
class TestPlacer(OmniUiTest):
"""Testing ui.Placer"""
async def test_general(self):
"""Testing general properties of ui.Placer"""
window = await self.create_test_window()
with window.frame:
with ui.ZStack():
with ui.Placer(offset_x=10, offset_y=10):
ui.Rectangle(width=RECT_SIZE, height=RECT_SIZE, style=RECT_STYLE)
with ui.Placer(offset_x=90, offset_y=10):
ui.Rectangle(width=RECT_SIZE, height=RECT_SIZE, style=RECT_STYLE)
with ui.Placer(offset_x=90, offset_y=90):
ui.Rectangle(width=RECT_SIZE, height=RECT_SIZE, style=RECT_STYLE)
with ui.Placer(offset_x=10, offset_y=90):
ui.Rectangle(width=RECT_SIZE, height=RECT_SIZE, style=RECT_STYLE)
await self.finalize_test()
async def test_percents(self):
"""Testing ability to offset in percents of ui.Placer"""
window = await self.create_test_window()
with window.frame:
with ui.ZStack():
with ui.Placer(offset_x=ui.Percent(10), offset_y=ui.Percent(10)):
ui.Rectangle(width=RECT_SIZE, height=RECT_SIZE, style=RECT_STYLE)
with ui.Placer(offset_x=ui.Percent(90), offset_y=ui.Percent(10)):
ui.Rectangle(width=RECT_SIZE, height=RECT_SIZE, style=RECT_STYLE)
with ui.Placer(offset_x=ui.Percent(90), offset_y=ui.Percent(90)):
ui.Rectangle(width=RECT_SIZE, height=RECT_SIZE, style=RECT_STYLE)
with ui.Placer(offset_x=ui.Percent(10), offset_y=ui.Percent(90)):
ui.Rectangle(width=RECT_SIZE, height=RECT_SIZE, style=RECT_STYLE)
await self.finalize_test()
async def test_child_percents(self):
"""Testing ability to offset in percents of ui.Placer"""
window = await self.create_test_window()
with window.frame:
with ui.ZStack():
with ui.Placer(offset_x=ui.Percent(10), offset_y=ui.Percent(10)):
ui.Rectangle(width=ui.Percent(80), height=ui.Percent(80), style=RECT_TRANSPARENT_STYLE)
with ui.Placer(offset_x=ui.Percent(50), offset_y=ui.Percent(50)):
ui.Rectangle(width=ui.Percent(50), height=ui.Percent(50), style=RECT_TRANSPARENT_STYLE)
await self.finalize_test()
async def test_resize(self):
window = await self.create_test_window()
with window.frame:
placer = ui.Placer(width=200)
with placer:
ui.Rectangle(height=100, style={"background_color": omni.ui.color.red})
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
placer.width = ui.Percent(5)
await self.finalize_test()
| 3,574 |
Python
| 41.559523 | 107 | 0.629547 |
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_window.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.
##
from .test_base import OmniUiTest
import omni.ui as ui
import omni.kit.app
from functools import partial
import omni.kit.test
WINDOW_STYLE = {"Window": {"background_color": 0xFF303030, "border_color": 0x0, "border_width": 0, "border_radius": 0}}
MODAL_WINDOW_STYLE = {
"Window": {
"background_color": 0xFFFF0000,
"border_color": 0x0,
"border_width": 0,
"border_radius": 0,
"secondary_background_color": 0,
}
}
class TestWindow(OmniUiTest):
"""Testing ui.Window"""
async def test_general(self):
"""Testing general properties of ui.Windows"""
window = await self.create_test_window()
# Empty window
window1 = ui.Window(
"Test1", width=100, height=100, position_x=10, position_y=10, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR
)
window1.frame.set_style(WINDOW_STYLE)
# Window with Label
window2 = ui.Window(
"Test2", width=100, height=100, position_x=120, position_y=10, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR
)
window2.frame.set_style(WINDOW_STYLE)
with window2.frame:
ui.Label("Hello world")
# Window with layout
window3 = ui.Window(
"Test3", width=100, height=100, position_x=10, position_y=120, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR
)
window3.frame.set_style(WINDOW_STYLE)
with window3.frame:
with ui.VStack():
ui.Spacer()
with ui.HStack(height=0):
ui.Spacer()
ui.Label("Hello world", width=0)
await self.finalize_test()
async def test_imgui_visibility(self):
"""Testing general properties of ui.Windows"""
window = await self.create_test_window()
# Empty window
window1 = ui.Window("Test1", width=100, height=100, position_x=10, position_y=10)
window1.frame.set_style(WINDOW_STYLE)
await omni.kit.app.get_app().next_update_async()
# Remove window
window1 = None
await omni.kit.app.get_app().next_update_async()
# It's still at ImGui cache
window1 = ui.Workspace.get_window("Test1")
window1.visible = False
await omni.kit.app.get_app().next_update_async()
# Create another one
window1 = ui.Window("Test1", width=100, height=100, position_x=10, position_y=10)
window1.frame.set_style(WINDOW_STYLE)
with window1.frame:
ui.Label("Hello world")
await omni.kit.app.get_app().next_update_async()
# It should be visible
await self.finalize_test()
async def test_overlay(self):
"""Testing the ability to overlay of ui.Windows"""
window = await self.create_test_window()
# Creating to windows with the same title. It should be displayed as
# one window with the elements of both windows.
window1 = ui.Window("Test", width=100, height=100, position_x=10, position_y=10)
window1.frame.set_style(WINDOW_STYLE)
with window1.frame:
with ui.VStack():
ui.Label("Hello world", height=0)
window3 = ui.Window("Test")
window3.frame.set_style(WINDOW_STYLE)
with window3.frame:
with ui.VStack():
ui.Spacer()
ui.Label("Hello world", height=0)
await self.finalize_test()
async def test_popup1(self):
"""Testing WINDOW_FLAGS_POPUP"""
window = await self.create_test_window()
# General popup
window1 = ui.Window(
"test_popup1",
width=100,
height=100,
position_x=10,
position_y=10,
flags=ui.WINDOW_FLAGS_POPUP | ui.WINDOW_FLAGS_NO_TITLE_BAR,
)
window1.frame.set_style(WINDOW_STYLE)
with window1.frame:
with ui.VStack():
ui.Label("Hello world", height=0)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_popup2(self):
"""Testing WINDOW_FLAGS_POPUP"""
window = await self.create_test_window()
# Two popups
window1 = ui.Window(
"test_popup2_0",
width=100,
height=100,
position_x=10,
position_y=10,
flags=ui.WINDOW_FLAGS_POPUP | ui.WINDOW_FLAGS_NO_TITLE_BAR,
)
window1.frame.set_style(WINDOW_STYLE)
with window1.frame:
with ui.VStack():
ui.Label("Hello world", height=0)
# Wait one frame and create second window.
await omni.kit.app.get_app().next_update_async()
window2 = ui.Window(
"test_popup2_1",
position_x=10,
position_y=10,
auto_resize=True,
flags=ui.WINDOW_FLAGS_POPUP | ui.WINDOW_FLAGS_NO_TITLE_BAR,
)
window2.frame.set_style(WINDOW_STYLE)
with window2.frame:
with ui.VStack():
ui.Label("Second popup", height=0)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_popup3(self):
"""Testing WINDOW_FLAGS_POPUP"""
window = await self.create_test_window()
with window.frame:
with ui.VStack():
field = ui.StringField(style={"background_color": 0x0})
field.model.set_value("This is StringField")
# General popup
window1 = ui.Window(
"test_popup3",
width=100,
height=100,
position_x=10,
position_y=10,
flags=ui.WINDOW_FLAGS_POPUP | ui.WINDOW_FLAGS_NO_TITLE_BAR,
)
window1.frame.set_style(WINDOW_STYLE)
with window1.frame:
with ui.VStack():
ui.Label("Hello world", height=0)
# Wait one frame and focus field
await omni.kit.app.get_app().next_update_async()
field.focus_keyboard()
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_modal1(self):
"""Testing WINDOW_FLAGS_MODAL"""
window = await self.create_test_window()
# General popup
window1 = ui.Window(
"test_modal1",
width=100,
height=100,
position_x=10,
position_y=10,
flags=ui.WINDOW_FLAGS_MODAL | ui.WINDOW_FLAGS_NO_TITLE_BAR,
)
window1.frame.set_style(WINDOW_STYLE)
with window1.frame:
with ui.VStack():
ui.Label("Hello world", height=0)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_modal2(self):
"""Testing WINDOW_FLAGS_MODAL with transparent dim background"""
window = await self.create_test_window()
# General popup
window1 = ui.Window(
"test_modal2",
width=100,
height=100,
position_x=10,
position_y=10,
flags=ui.WINDOW_FLAGS_MODAL | ui.WINDOW_FLAGS_NO_TITLE_BAR,
)
window1.frame.set_style(MODAL_WINDOW_STYLE)
with window1.frame:
with ui.VStack():
ui.Label("Hello world", height=0)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_menubar(self):
"""Testing general properties of ui.MenuBar"""
window = await self.create_test_window()
# Empty window
window1 = ui.Window(
"Test1",
width=100,
height=100,
position_x=10,
position_y=10,
flags=ui.WINDOW_FLAGS_MENU_BAR | ui.WINDOW_FLAGS_NO_SCROLLBAR,
)
window1.frame.set_style(WINDOW_STYLE)
with window1.menu_bar:
with ui.Menu("File"):
ui.MenuItem("Open")
with window1.frame:
ui.Label("Hello world")
# Window with Label
window2 = ui.Window(
"Test2",
width=100,
height=100,
position_x=120,
position_y=10,
flags=ui.WINDOW_FLAGS_MENU_BAR | ui.WINDOW_FLAGS_NO_SCROLLBAR,
)
window2.frame.set_style(WINDOW_STYLE)
window2.menu_bar.style = {"MenuBar": {"background_color": 0xFFEDB51A}}
with window2.menu_bar:
with ui.Menu("File"):
ui.MenuItem("Open")
with window2.frame:
ui.Label("Hello world")
# Window with layout
window3 = ui.Window(
"Test3",
width=100,
height=100,
position_x=10,
position_y=120,
flags=ui.WINDOW_FLAGS_MENU_BAR | ui.WINDOW_FLAGS_NO_SCROLLBAR,
)
window3.frame.style = {**WINDOW_STYLE, **{"Window": {"background_color": 0xFFEDB51A}}}
with window3.menu_bar:
with ui.Menu("File"):
ui.MenuItem("Open")
with window3.frame:
ui.Label("Hello world")
await self.finalize_test()
async def test_docked(self):
ui_main_window = ui.MainWindow()
win = ui.Window("first", width=100, height=100)
await omni.kit.app.get_app().next_update_async()
self.assertFalse(win.docked)
main_dockspace = ui.Workspace.get_window("DockSpace")
win.dock_in(main_dockspace, ui.DockPosition.SAME)
await omni.kit.app.get_app().next_update_async()
self.assertTrue(win.docked)
async def test_is_selected_in_dock(self):
ui_main_window = ui.MainWindow()
window1 = ui.Window("First", width=100, height=100)
window2 = ui.Window("Second", width=100, height=100)
window3 = ui.Window("Thrid", width=100, height=100)
await omni.kit.app.get_app().next_update_async()
main_dockspace = ui.Workspace.get_window("DockSpace")
window1.dock_in(main_dockspace, ui.DockPosition.SAME)
window2.dock_in(main_dockspace, ui.DockPosition.SAME)
window3.dock_in(main_dockspace, ui.DockPosition.SAME)
await omni.kit.app.get_app().next_update_async()
window2.focus()
await omni.kit.app.get_app().next_update_async()
self.assertFalse(window1.is_selected_in_dock())
self.assertTrue(window2.is_selected_in_dock())
self.assertFalse(window3.is_selected_in_dock())
async def test_mainwindow_resize(self):
"""Testing resizing of mainwindow"""
await self.create_test_area(128, 128)
main_window = ui.MainWindow()
main_window.main_menu_bar.clear()
main_window.main_menu_bar.visible = True
main_window.main_menu_bar.menu_compatibility = False
with main_window.main_menu_bar:
with ui.Menu("NVIDIA"):
ui.MenuItem("Item 1")
ui.MenuItem("Item 2")
ui.MenuItem("Item 3")
ui.Spacer()
with ui.Menu("Omniverse"):
ui.MenuItem("Item 1")
ui.MenuItem("Item 2")
ui.MenuItem("Item 3")
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
main_dockspace = ui.Workspace.get_window("DockSpace")
window1 = ui.Window("Viewport")
with window1.frame:
ui.Label("Window", alignment=ui.Alignment.CENTER)
await omni.kit.app.get_app().next_update_async()
window1.dock_in(main_dockspace, ui.DockPosition.SAME)
await omni.kit.app.get_app().next_update_async()
window1.dock_tab_bar_enabled = False
app_window = omni.appwindow.get_default_app_window()
app_window.resize(256, 128)
for i in range(2):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
main_window = None
window1.dock_tab_bar_enabled = True # Turn back on for other tests
for i in range(2):
await omni.kit.app.get_app().next_update_async()
class WindowCallbacks(OmniUiTest):
def _focus_callback(self, state_dict, name, focus_state: bool) -> None:
state_dict[name] = focus_state
async def test_window_focus_callback(self):
"""test window focus callback"""
focus_values = {}
window1 = ui.Window("First", width=100, height=100)
window1.set_focused_changed_fn(partial(self._focus_callback, focus_values, "window1"))
window2 = ui.Window("Second", width=100, height=100)
window1.set_focused_changed_fn(partial(self._focus_callback, focus_values, "window2"))
await omni.kit.app.get_app().next_update_async()
#Looks like setting focus on 1 window doesn't set if off on the others?
window1.focus()
self.assertTrue(focus_values['window1']==True)
await omni.kit.app.get_app().next_update_async()
window2.focus()
self.assertTrue(focus_values['window2']==True)
async def __test_window_focus_policy(self, focus_policy: ui.FocusPolicy, mouse_event: str, focus_changes: bool = True):
import omni.kit.ui_test as ui_test
from carb.input import MouseEventType
width, height = 100, 100
start_pos = ui_test.Vec2(width, height)
window0_center = ui_test.Vec2(width/2, height/2)
window1_center = window0_center + ui_test.Vec2(width, 0)
mouse_types = {
"left": (MouseEventType.LEFT_BUTTON_DOWN, MouseEventType.LEFT_BUTTON_UP),
"middle": (MouseEventType.MIDDLE_BUTTON_DOWN, MouseEventType.MIDDLE_BUTTON_UP),
"right": (MouseEventType.RIGHT_BUTTON_DOWN, MouseEventType.RIGHT_BUTTON_UP),
}.get(mouse_event)
# Get the list of expected eulsts based on FocusPolicy
if focus_changes:
if focus_policy != ui.FocusPolicy.FOCUS_ON_HOVER:
focus_tests = [
(False, True), # Initial state
(False, True), # After mouse move to window 0
(False, True), # After mouse move to window 1
(True, False), # After mouse click in window 0
(False, True), # After mouse click in window 1
]
else:
focus_tests = [
(False, True), # Initial state
(True, False), # After mouse move to window 0
(False, True), # After mouse move to window 1
(True, False), # After mouse click in window 0
(False, True), # After mouse click in window 1
]
else:
# Default focus test that never changes focus
focus_tests = [
(False, True), # Initial state
(False, True), # After mouse move to window 0
(False, True), # After mouse move to window 1
(False, True), # After mouse click in window 0
(False, True), # After mouse click in window 1
]
await self.create_test_area(width*2, height, block_devices=False)
window0 = ui.Window("0", width=width, height=height, position_y=0, position_x=0)
window1 = ui.Window("1", width=width, height=height, position_y=0, position_x=width)
# Test initial focus state
if focus_policy != ui.FocusPolicy.DEFAULT:
self.assertNotEqual(window0.focus_policy, focus_policy)
window0.focus_policy = focus_policy
self.assertNotEqual(window1.focus_policy, focus_policy)
window1.focus_policy = focus_policy
self.assertEqual(window0.focus_policy, focus_policy)
self.assertEqual(window1.focus_policy, focus_policy)
# Test the individual focus state and move to next state test
focus_test_idx = 0
async def test_focused_windows():
nonlocal focus_test_idx
expected_focus_state = focus_tests[focus_test_idx]
focus_test_idx = focus_test_idx + 1
window0_focused, window1_focused = window0.focused, window1.focused
expected_window0_focus, expected_window1_focus = expected_focus_state[0], expected_focus_state[1]
# Build a more specifc failure message
fail_msg = f"Testing {focus_policy} with mouse '{mouse_event}' (focus_test_idx: {focus_test_idx-1})"
fail_msg_0 = f"{fail_msg}: Window 0 expected focus: {expected_window0_focus}, had focus {window0_focused}."
fail_msg_1 = f"{fail_msg}: Window 1 expected focus: {expected_window1_focus}, had focus {window1_focused}."
self.assertEqual(expected_window0_focus, window0_focused, msg=fail_msg_0)
self.assertEqual(expected_window1_focus, window1_focused, msg=fail_msg_1)
# Move mouse
await ui_test.input.emulate_mouse_move(start_pos)
# Test the current focus state
await test_focused_windows()
# Move mouse
await ui_test.input.emulate_mouse_move(window0_center)
# Test the current focus state on both windows
await test_focused_windows()
# Move mouse
await ui_test.input.emulate_mouse_move(window1_center)
# Test the current focus state on both windows
await test_focused_windows()
# Move mouse to Window 0
await ui_test.emulate_mouse_move(window0_center)
# Do mouse click: down and up event
await ui_test.input.emulate_mouse(mouse_types[0])
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse(mouse_types[1])
await ui_test.input.wait_n_updates_internal()
# Test the current focus state on both windows
await test_focused_windows()
# Move mouse to Window 1
await ui_test.emulate_mouse_move(window1_center)
# Do mouse click: down and up event
await ui_test.input.emulate_mouse(mouse_types[0])
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse(mouse_types[1])
await ui_test.input.wait_n_updates_internal()
# Test the current focus state on both windows
await test_focused_windows()
async def test_window_focus_policy_left_mouse(self):
"""test Window focus policy based on mouse events on left click"""
# Left click should change focus
await self.__test_window_focus_policy(ui.FocusPolicy.FOCUS_ON_LEFT_MOUSE_DOWN, "left")
# Middle click should not change focus
await self.__test_window_focus_policy(ui.FocusPolicy.FOCUS_ON_LEFT_MOUSE_DOWN, "middle", False)
# Right click should not change focus
await self.__test_window_focus_policy(ui.FocusPolicy.FOCUS_ON_LEFT_MOUSE_DOWN, "right", False)
async def test_window_focus_policy_any_mouse(self):
"""test Window focus policy based on mouse events on any click"""
# Left click should change focus
await self.__test_window_focus_policy(ui.FocusPolicy.FOCUS_ON_ANY_MOUSE_DOWN, "left")
# Middle click should change focus
await self.__test_window_focus_policy(ui.FocusPolicy.FOCUS_ON_ANY_MOUSE_DOWN, "middle")
# Right click should change focus
await self.__test_window_focus_policy(ui.FocusPolicy.FOCUS_ON_ANY_MOUSE_DOWN, "right")
async def test_window_focus_policy_hover_mouse(self):
"""test Window focus policy based on mouse events hover"""
# Left click should change focus
await self.__test_window_focus_policy(ui.FocusPolicy.FOCUS_ON_HOVER, "left")
# Middle click should not change focus
await self.__test_window_focus_policy(ui.FocusPolicy.FOCUS_ON_HOVER, "middle")
# Right click should not change focus
await self.__test_window_focus_policy(ui.FocusPolicy.FOCUS_ON_HOVER, "right")
| 20,373 |
Python
| 36.246801 | 123 | 0.595396 |
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_image.py
|
## Copyright (c) 2019-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
from .test_base import OmniUiTest
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from functools import partial
from pathlib import Path
import asyncio
import carb
import omni.kit.app
import omni.ui as ui
import os
import unittest
CURRENT_PATH = Path(__file__).parent
DATA_PATH = CURRENT_PATH.parent.parent.parent.joinpath("data")
class TestImage(OmniUiTest):
"""Testing ui.Image"""
async def test_general(self):
"""Testing general properties of ui.Image"""
window = await self.create_test_window()
f = asyncio.Future()
def on_image_progress(future: asyncio.Future, progress):
if progress >= 1:
if not future.done():
future.set_result(None)
with window.frame:
ui.Image(f"{DATA_PATH}/tests/red.png", progress_changed_fn=partial(on_image_progress, f))
# Wait the image to be loaded
await f
await self.finalize_test()
async def test_broken_svg(self):
"""Testing ui.Image doesn't crash when the image is broken."""
window = await self.create_test_window()
def build():
ui.Image(f"{DATA_PATH}/tests/broken.svg")
window.frame.set_build_fn(build)
# Call build
await omni.kit.app.get_app().next_update_async()
# Attempts to load the broken file. The error message is "Failed to load the texture:"
await omni.kit.app.get_app().next_update_async()
# Recall build
window.frame.rebuild()
await omni.kit.app.get_app().next_update_async()
# Second attempt to load the broken file. Second error message is expected.
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_imagewithprovider(self):
# Because PIL works differently in Windows and Liniux.
# TODO: Use something else for the rasterization of the text
return
"""Testing ui.Image doesn't crash when the image is broken."""
window = await self.create_test_window()
image_width = 256
image_height = 256
upscale = 2
black = (0, 0, 0, 255)
white = (255, 255, 255, 255)
font_path = os.path.normpath(
carb.tokens.get_tokens_interface().resolve("${kit}/resources/fonts/roboto_medium.ttf")
)
font_size = 25
font = ImageFont.truetype(font_path, font_size)
image = Image.new("RGBA", (image_width * upscale, image_height * upscale), white)
draw = ImageDraw.Draw(image)
# draw.fontmode = "RGB"
draw.text(
(0, image_height),
"The quick brown fox jumps over the lazy dog",
fill=black,
font=font,
)
# Convert image to Image Provider
pixels = [int(c) for p in image.getdata() for c in p]
image_provider = ui.ByteImageProvider()
image_provider.set_bytes_data(pixels, [image_width * upscale, image_height * upscale])
with window.frame:
with ui.HStack():
ui.Spacer(width=0.5)
ui.ImageWithProvider(
image_provider,
fill_policy=ui.IwpFillPolicy.IWP_STRETCH,
width=image_width,
height=image_height,
pixel_aligned=True,
)
# Second attempt to load the broken file. Second error message is expected.
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_imagewithprovider_with_no_valid_style(self):
"""This is to test ImageWithProvider is not crash when style is not defined and image_url is not defined"""
window = await self.create_test_window()
with window.frame:
ui.ImageWithProvider(
height=200,
width=200,
fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT,
style_type_name_override="Graph.Node.Port")
for _ in range(2):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test_no_image()
async def test_destroy(self):
"""Testing creating and destroying ui.Image"""
window = await self.create_test_window()
with window.frame:
ui.Image(f"{DATA_PATH}/tests/red.png")
# It will immediately kill ui.Image
ui.Spacer()
# Several frames to make sure it doesn't crash
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
# Another way to destroy it
with window.frame:
# The image is destroyed, but we hold it to make sure it doesn't
# crash
ui.Image(f"{DATA_PATH}/tests/red.png").destroy()
# Several frames to make sure it doesn't crash
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test_no_image()
async def test_byteimageprovider(self):
"""Testing creating ui.ByteImageProvider"""
window = await self.create_test_window()
bytes = [0, 0, 0, 255, 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255]
resolution = [2, 2]
with window.frame:
ui.ImageWithProvider(
ui.ByteImageProvider(bytes, resolution),
fill_policy=ui.IwpFillPolicy.IWP_STRETCH,
)
await self.finalize_test()
async def test_dynamictextureprovider(self):
"""Testing creating ui.DynamicTextureProvider"""
window = await self.create_test_window()
bytes = [0, 0, 0, 255, 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255]
resolution = [2, 2]
textureprovider = ui.DynamicTextureProvider("textureX")
textureprovider.set_bytes_data(bytes, resolution)
with window.frame:
ui.ImageWithProvider(
textureprovider,
fill_policy=ui.IwpFillPolicy.IWP_STRETCH,
)
resource = textureprovider.get_managed_resource()
self.assertIsNotNone(resource)
await self.finalize_test()
def _warpAvailable():
try:
import warp as wp
return True
except ModuleNotFoundError:
return False
@unittest.skipIf(not _warpAvailable(), "warp module not found")
async def test_byteimageprovider_from_warp(self):
"""Testing creating ui.ByteImageProvider with bytes from gpu"""
window = await self.create_test_window()
import warp as wp
@wp.kernel
def checkerboard(pixels: wp.array(dtype=wp.uint8, ndim=3), size_x: wp.int32, size_y: wp.int32, num_channels: wp.int32):
x, y, c = wp.tid()
value = wp.uint8(0)
if (x / 4) % 2 == (y / 4) % 2:
value = wp.uint8(255)
pixels[x, y, c] = value
size_x = 256
size_y = 256
num_channels = 4
texture_array = wp.zeros(shape=(size_x, size_y, num_channels), dtype=wp.uint8)
wp.launch(kernel=checkerboard, dim=(size_x, size_y, num_channels), inputs=[texture_array, size_x, size_y, num_channels])
provider = ui.ByteImageProvider()
# Test switching between host and gpu source data
provider.set_bytes_data([128 for _ in range(size_x * size_y * num_channels)], [size_x, size_y])
provider.set_bytes_data_from_gpu(texture_array.ptr, [size_x, size_y])
with window.frame:
ui.ImageWithProvider(
provider,
fill_policy=ui.IwpFillPolicy.IWP_STRETCH,
)
await self.finalize_test()
async def test_imageprovider_single_channel(self):
"""Test single channel image with attempt to use unsupported mipmapping"""
window = await self.create_test_window()
provider = ui.RasterImageProvider()
provider.source_url = DATA_PATH.joinpath("tests", "single_channel.jpg").as_posix()
provider.max_mip_levels = 2
with window.frame:
ui.ImageWithProvider(
provider,
fill_policy=ui.IwpFillPolicy.IWP_STRETCH,
)
# wait for image to load
await asyncio.sleep(2)
await self.finalize_test()
async def test_image_rasterization(self):
"""Testing ui.Image while rasterization is turned on"""
window = await self.create_test_window()
f = asyncio.Future()
def on_image_progress(future: asyncio.Future, progress):
if progress >= 1:
if not future.done():
future.set_result(None)
with window.frame:
with ui.Frame(raster_policy=ui.RasterPolicy.AUTO):
ui.Image(f"{DATA_PATH}/tests/red.png", progress_changed_fn=partial(on_image_progress, f))
# Wait the image to be loaded
await f
await self.finalize_test()
| 9,464 |
Python
| 33.046762 | 128 | 0.600803 |
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_configuration.py
|
import glob, os
import omni.kit.test
import omni.kit.app
class ConfigurationTest(omni.kit.test.AsyncTestCase):
async def test_pyi_file_present(self):
# Check that omni.ui extension has _ui.pyi file generated
manager = omni.kit.app.get_app().get_extension_manager()
ext_id = manager.get_enabled_extension_id("omni.ui")
self.assertIsNotNone(ext_id)
ext_path = manager.get_extension_path(ext_id)
self.assertIsNotNone(ext_path)
pyi_files = list(glob.glob(ext_path + "/**/_ui.pyi", recursive=True))
self.assertEqual(len(pyi_files), 1)
| 601 |
Python
| 34.411763 | 77 | 0.672213 |
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_collapsableframe.py
|
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from .test_base import OmniUiTest
import omni.ui as ui
import omni.kit.app
STYLE = {
"CollapsableFrame": {
"background_color": 0xFF383838,
"secondary_color": 0xFF4D4D4D,
"color": 0xFFFFFFFF,
"border_radius": 3,
"margin": 1,
"padding": 3,
}
}
class TestCollapsableFrame(OmniUiTest):
"""Testing ui.CollapsableFrame"""
async def test_general(self):
"""Testing general properties of ui.CollapsableFrame"""
window = await self.create_test_window()
with window.frame:
with ui.VStack(style=STYLE, height=0, spacing=3):
with ui.CollapsableFrame("Frame1"):
ui.Label("Label in CollapsableFrame")
with ui.CollapsableFrame("Frame2"):
ui.Label("First label, should not be displayed")
ui.Label("Second label, should be displayed")
with ui.CollapsableFrame("Frame3"):
ui.Label("Long Label in CollapsableFrame. " * 9, word_wrap=True)
await self.finalize_test()
async def test_collapsing(self):
"""Testing the collapsing behaviour of ui.CollapsableFrame"""
window = await self.create_test_window()
with window.frame:
with ui.VStack(style=STYLE, height=0, spacing=3):
frame1 = ui.CollapsableFrame("Frame1")
with frame1:
ui.Label("Label in CollapsableFrame")
frame2 = ui.CollapsableFrame("Frame2")
with frame2:
ui.Label("Label in CollapsableFrame")
frame3 = ui.CollapsableFrame("Frame3")
with frame3:
ui.Label("Label in CollapsableFrame")
frame4 = ui.CollapsableFrame("Frame4", collapsed=True)
with frame4:
ui.Label("Label in CollapsableFrame")
frame5 = ui.CollapsableFrame("Frame5")
with frame5:
ui.Label("Label in CollapsableFrame")
frame1.collapsed = True
await omni.kit.app.get_app().next_update_async()
frame2.collapsed = True
frame3.collapsed = True
await omni.kit.app.get_app().next_update_async()
frame3.collapsed = False
await self.finalize_test()
async def test_collapsing_build_fn(self):
"""Testing the collapsing behaviour of ui.CollapsableFrame and delayed ui.Frame"""
window = await self.create_test_window()
def content():
ui.Label("Label in CollapsableFrame")
with window.frame:
with ui.VStack(style=STYLE, height=0, spacing=3):
frame1 = ui.CollapsableFrame("Frame1")
with frame1:
ui.Frame(build_fn=content)
frame2 = ui.CollapsableFrame("Frame2")
with frame2:
ui.Frame(build_fn=content)
frame3 = ui.CollapsableFrame("Frame3")
with frame3:
ui.Frame(build_fn=content)
frame4 = ui.CollapsableFrame("Frame4", collapsed=True)
with frame4:
ui.Frame(build_fn=content)
frame5 = ui.CollapsableFrame("Frame5")
with frame5:
ui.Frame(build_fn=content)
frame1.collapsed = True
await omni.kit.app.get_app().next_update_async()
frame2.collapsed = True
frame3.collapsed = True
await omni.kit.app.get_app().next_update_async()
frame3.collapsed = False
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_nested(self):
"""Testing the collapsing behaviour of nested ui.CollapsableFrame"""
window = await self.create_test_window()
with window.frame:
with ui.VStack(style=STYLE, height=0, spacing=3):
frame1 = ui.CollapsableFrame("Frame1")
with frame1:
with ui.VStack(height=0, spacing=3):
ui.Label("Label in CollapsableFrame 1")
frame2 = ui.CollapsableFrame("Frame2")
with frame2:
with ui.VStack(height=0, spacing=3):
ui.Label("Label in CollapsableFrame 2")
frame3 = ui.CollapsableFrame("Frame3")
with frame3:
ui.Label("Label in CollapsableFrame 3")
frame4 = ui.CollapsableFrame("Frame4", collapsed=True)
with frame4:
with ui.VStack(height=0, spacing=3):
ui.Label("Label in CollapsableFrame 4")
frame5 = ui.CollapsableFrame("Frame5")
with frame5:
ui.Label("Label in CollapsableFrame 5")
frame6 = ui.CollapsableFrame("Frame6", collapsed=True)
with frame6:
ui.Label("Label in CollapsableFrame 6")
frame7 = ui.CollapsableFrame("Frame7")
with frame7:
ui.Label("Label in CollapsableFrame 7")
frame1.collapsed = True
frame6.collapsed = False
frame7.collapsed = True
await omni.kit.app.get_app().next_update_async()
frame1.collapsed = False
frame2.collapsed = True
frame3.collapsed = True
frame4.collapsed = False
frame5.collapsed = True
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
| 6,215 |
Python
| 34.930636 | 90 | 0.555591 |
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_grid.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.
##
from unittest import skip
import omni.kit.test
import omni.ui as ui
from .test_base import OmniUiTest
import omni.kit.app
class TestGrid(OmniUiTest):
"""Testing ui.HGrid and ui.VGrid"""
async def test_v_size(self):
"""Testing fixed width of ui.VGrid"""
window = await self.create_test_window()
with window.frame:
with ui.VGrid(column_width=20, row_height=20):
for i in range(200):
ui.Label(f"{i}", style={"color": 0xFFFFFFFF})
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_v_number(self):
"""Testing varying width of ui.VGrid"""
window = await self.create_test_window()
with window.frame:
with ui.VGrid(column_count=10, row_height=20):
for i in range(200):
ui.Label(f"{i}", style={"color": 0xFFFFFFFF})
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_v_length(self):
"""Testing varying height of ui.VGrid"""
window = await self.create_test_window()
with window.frame:
with ui.VGrid(column_width=30):
for i in range(200):
if i == 50:
ui.Label(f"{i}", style={"color": 0xFF0033FF, "font_size": 22}, alignment=ui.Alignment.CENTER)
else:
ui.Label(f"{i}", style={"color": 0xFFFFFFFF}, alignment=ui.Alignment.CENTER)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_length_resize(self):
"""Testing varying height of ui.VGrid"""
window = await self.create_test_window()
with window.frame:
grid = ui.VGrid(column_width=64)
with grid:
for i in range(300):
with ui.Frame(height=16):
with ui.HStack():
with ui.VStack():
ui.Spacer()
ui.Rectangle(style={"background_color": ui.color.white})
with ui.VStack():
ui.Rectangle(style={"background_color": ui.color.white})
ui.Spacer()
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
grid.column_width = 16
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_h_size(self):
"""Testing fixed height of ui.HGrid"""
window = await self.create_test_window()
with window.frame:
with ui.HGrid(column_width=20, row_height=20):
for i in range(200):
ui.Label(f"{i}", style={"color": 0xFFFFFFFF})
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_h_number(self):
"""Testing varying height of ui.VGrid"""
window = await self.create_test_window()
with window.frame:
with ui.HGrid(row_count=10, column_width=20):
for i in range(200):
ui.Label(f"{i}", style={"color": 0xFFFFFFFF})
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_h_length(self):
"""Testing varying height of ui.VGrid"""
window = await self.create_test_window()
with window.frame:
with ui.HGrid(row_height=30):
for i in range(200):
if i == 50:
ui.Label(
f"{i}",
style={"color": 0xFF0033FF, "font_size": 22, "margin": 3},
alignment=ui.Alignment.CENTER,
)
else:
ui.Label(f"{i}", style={"color": 0xFFFFFFFF, "margin": 3}, alignment=ui.Alignment.CENTER)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_v_inspector(self):
"""Testing how inspector opens nested frames"""
window = await self.create_test_window()
with window.frame:
with ui.VGrid(column_width=30):
for i in range(200):
ui.Frame(
build_fn=lambda i=i: ui.Label(f"{i}", style={"color": 0xFFFFFFFF}, alignment=ui.Alignment.CENTER)
)
grid = ui.Inspector.get_children(window.frame)[0]
self.assertIsInstance(grid, ui.VGrid)
counter = 0
frames = ui.Inspector.get_children(grid)
for frame in frames:
self.assertIsInstance(frame, ui.Frame)
label = ui.Inspector.get_children(frame)[0]
self.assertIsInstance(label, ui.Label)
self.assertEqual(label.text, f"{counter}")
counter += 1
self.assertEqual(counter, 200)
await self.finalize_test()
@skip("TC crash on this test in linux")
async def test_nested_grid(self):
"""Testing nested grid without setting height and width and not crash (OM-70184)"""
window = await self.create_test_window()
with window.frame:
with ui.VGrid():
with ui.CollapsableFrame("Main Frame"):
with ui.VGrid():
ui.CollapsableFrame("Sub Frame")
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
| 6,144 |
Python
| 33.914773 | 121 | 0.551921 |
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_base.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.
##
__all__ = ["OmniUiTest"]
"""The base class for all the visual tests in omni.ui"""
from .compare_utils import capture_and_compare, CompareMetric
import carb
import carb.input
import carb.windowing
import omni.appwindow
import omni.kit.test
import omni.ui as ui
import pathlib
from carb.input import MouseEventType
DEVICE_TO_BLOCK = [carb.input.DeviceType.GAMEPAD, carb.input.DeviceType.KEYBOARD, carb.input.DeviceType.MOUSE]
async def next_resize_async():
"""
Wait for the next event in the resize event stream of IAppWindow::getWindowResizeEventStream.
We need it because the window resize event stream is independent of IApp::getUpdateEventStream. Without this
function it's possible that resize happens several updates after. It's reproducible on Linux Release build.
"""
return await omni.appwindow.get_default_app_window().get_window_resize_event_stream().next_event()
class OmniUiTest(omni.kit.test.AsyncTestCase):
"""
Base class for testing Omni::UI.
Has methods to initialize/return window and compare images.
"""
# Maximum allowed difference when comparing two images, default compare metric is mean error.
# Set a default threshold that is enough to filter out the artifacts of antialiasing on the different systems.
MEAN_ERROR_THRESHOLD = 0.01
MEAN_ERROR_SQUARED_THRESHOLD = 1e-5
THRESHOLD = MEAN_ERROR_THRESHOLD # default threshold
def __init__(self, tests=()):
super().__init__(tests)
self._saved_width = None
self._saved_height = None
self._restore_window = None
self._restore_position = None
self._restore_dock_window = None
self._need_finalize = False
self.__device_state = [None for _ in DEVICE_TO_BLOCK]
async def setUp(self):
"""Before running each test"""
self._need_finalize = False
async def tearDown(self):
"""After running each test"""
if self._need_finalize: # keep track of whether we get our closing finalize function
carb.log_warn(
"After a create_test_area, create_test_window, or docked_test_window call, finish the test with a finalize_test or finalize_test_no_image "
"call, to restore the window and settings."
)
self._need_finalize = False
async def wait_n_updates(self, n_frames: int = 3):
app = omni.kit.app.get_app()
for _ in range(n_frames):
await app.next_update_async()
@property
def __test_name(self) -> str:
"""
The full name of the test.
It has the name of the module, class and the current test function
"""
return f"{self.__module__}.{self.__class__.__name__}.{self._testMethodName}"
def __get_golden_img_name(self, golden_img_name: str, golden_img_dir: str, test_name: str):
if not golden_img_name:
golden_img_name = f"{test_name}.png"
# Test name includes a module, which makes it long. Filepath length can exceed path limit on windows.
# We want to trim it, but for backward compatibility by default keep golden image name the same. But when
# golden image does not exist and generated first time use shorter name.
if golden_img_dir and not golden_img_dir.joinpath(golden_img_name).exists():
# Example: omni.example.ui.tests.example_ui_test.TestExampleUi.test_ScrollingFrame -> test_ScrollingFrame
pos = test_name.rfind(".test_")
if pos > 0:
test_name = test_name[(pos + 1) :]
golden_img_name = f"{test_name}.png"
return golden_img_name
def __block_devices(self, app_window):
# Save the state
self.__device_state = [app_window.get_input_blocking_state(device) for device in DEVICE_TO_BLOCK]
# Set the new state
for device in DEVICE_TO_BLOCK:
app_window.set_input_blocking_state(device, True)
def __restore_devices(self, app_window):
for device, state in zip(DEVICE_TO_BLOCK, self.__device_state):
if state is not None:
app_window.set_input_blocking_state(device, state)
self.__device_state = [None for _ in DEVICE_TO_BLOCK]
async def create_test_area(
self,
width: int = 256,
height: int = 256,
block_devices: bool = True,
):
"""Resize the main window"""
app_window = omni.appwindow.get_default_app_window()
dpi_scale = ui.Workspace.get_dpi_scale()
# requested size scaled with dpi
width_with_dpi = int(width * dpi_scale)
height_with_dpi = int(height * dpi_scale)
# Current main window size
current_width = app_window.get_width()
current_height = app_window.get_height()
# If the main window is already has requested size, do nothing
if width_with_dpi == current_width and height_with_dpi == current_height:
self._saved_width = None
self._saved_height = None
else:
# Save the size of the main window to be able to restore it at the end of the test
self._saved_width = current_width
self._saved_height = current_height
app_window.resize(width_with_dpi, height_with_dpi)
# Wait for getWindowResizeEventStream
await next_resize_async()
windowing = carb.windowing.acquire_windowing_interface()
os_window = app_window.get_window()
# Move the cursor away to avoid hovering on element and trigger tooltips that break the tests
if block_devices:
input_provider = carb.input.acquire_input_provider()
mouse = app_window.get_mouse()
input_provider.buffer_mouse_event(mouse, MouseEventType.MOVE, (0, 0), 0, (0, 0))
windowing.set_cursor_position(os_window, (0, 0))
# One frame to move mouse cursor
await omni.kit.app.get_app().next_update_async()
if block_devices:
self.__block_devices(app_window)
self._restore_window = None
self._restore_position = None
self._restore_dock_window = None
self._need_finalize = True # keep track of whether we get our closing finalize function
async def create_test_window(
self, width: int = 256, height: int = 256, block_devices: bool = True, window_flags=None
) -> ui.Window:
"""
Resize the main window and create a window with the given resolution.
Returns:
ui.Window with black background, expended to fill full main window and ready for testing.
"""
await self.create_test_area(width, height, block_devices=block_devices)
if window_flags is None:
window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE
window = ui.Window(
f"{self.__test_name} Test",
dockPreference=ui.DockPreference.DISABLED,
flags=window_flags,
width=width,
height=height,
position_x=0,
position_y=0,
)
# Override default background
window.frame.set_style({"Window": {"background_color": 0xFF000000, "border_color": 0x0, "border_radius": 0}})
return window
async def docked_test_window(
self,
window: ui.Window,
width: int = 256,
height: int = 256,
restore_window: ui.Window = None,
restore_position: ui.DockPosition = ui.DockPosition.SAME,
block_devices: bool = True,
) -> None:
"""
Resize the main window and use docked window with the given resolution.
"""
window.undock()
# Wait for the window to be undocked
await omni.kit.app.get_app().next_update_async()
window.focus()
app_window = omni.appwindow.get_default_app_window()
dpi_scale = ui.Workspace.get_dpi_scale()
# requested size scaled with dpi
width_with_dpi = int(width * dpi_scale)
height_with_dpi = int(height * dpi_scale)
# Current main window size
current_width = app_window.get_width()
current_height = app_window.get_height()
# If the main window is already has requested size, do nothing
if width_with_dpi == current_width and height_with_dpi == current_height:
self._saved_width = None
self._saved_height = None
else:
# Save the size of the main window to be able to restore it at the end of the test
self._saved_width = current_width
self._saved_height = current_height
app_window.resize(width_with_dpi, height_with_dpi)
# Wait for getWindowResizeEventStream
await app_window.get_window_resize_event_stream().next_event()
if isinstance(window, ui.Window):
window.flags = ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE
window.width = width
window.height = height
window.position_x = 0
window.position_y = 0
windowing = carb.windowing.acquire_windowing_interface()
os_window = app_window.get_window()
# Move the cursor away to avoid hovering on element and trigger tooltips that break the tests
if block_devices:
input_provider = carb.input.acquire_input_provider()
mouse = app_window.get_mouse()
input_provider.buffer_mouse_event(mouse, MouseEventType.MOVE, (0, 0), 0, (0, 0))
windowing.set_cursor_position(os_window, (0, 0))
# One frame to move mouse cursor
await omni.kit.app.get_app().next_update_async()
if block_devices:
self.__block_devices(app_window)
self._restore_dock_window = window
self._restore_window = restore_window
self._restore_position = restore_position
self._need_finalize = True # keep track of whether we get our closing finalize function
async def finalize_test_no_image(self):
"""Restores the main window once a test is complete."""
# Restore main window resolution if it was saved
if self._saved_width is not None and self._saved_height is not None:
app_window = omni.appwindow.get_default_app_window()
app_window.resize(self._saved_width, self._saved_height)
# Wait for getWindowResizeEventStream
await next_resize_async()
if self._restore_dock_window and self._restore_window:
self._restore_dock_window.dock_in(self._restore_window, self._restore_position)
self._restore_window = None
self._restore_position = None
self._restore_dock_window = None
app_window = omni.appwindow.get_default_app_window()
self.__restore_devices(app_window)
self._need_finalize = False
async def capture_and_compare(
self,
threshold=None,
golden_img_dir: pathlib.Path = None,
golden_img_name=None,
use_log: bool = True,
cmp_metric=CompareMetric.MEAN_ERROR,
test_name: str = None,
hide_menu_bar: bool = True
):
"""Capture current frame and compare it with the golden image. Assert if the diff is more than given threshold."""
test_name = test_name or f"{self.__test_name}"
golden_img_name = self.__get_golden_img_name(golden_img_name, golden_img_dir, test_name)
menu_bar = None
old_visible = None
try:
try:
from omni.kit.mainwindow import get_main_window
main_window = get_main_window()
menu_bar = main_window.get_main_menu_bar()
old_visible = menu_bar.visible
if hide_menu_bar:
menu_bar.visible = False
except ImportError:
pass
# set default threshold for each compare metric
if threshold is None:
if cmp_metric == CompareMetric.MEAN_ERROR:
threshold = self.MEAN_ERROR_THRESHOLD
elif cmp_metric == CompareMetric.MEAN_ERROR_SQUARED:
threshold = self.MEAN_ERROR_SQUARED_THRESHOLD
elif cmp_metric == CompareMetric.PIXEL_COUNT:
threshold = 10 # arbitrary number
diff = await capture_and_compare(
golden_img_name, threshold, golden_img_dir, use_log=use_log, cmp_metric=cmp_metric
)
if diff != 0:
carb.log_warn(f"[{test_name}] the generated image has difference {diff}")
self.assertTrue(
(diff is not None and diff < threshold),
msg=f"The image for test '{test_name}' doesn't match the golden one. Difference of {diff} is is not less than threshold of {threshold}.",
)
finally:
if menu_bar:
menu_bar.visible = old_visible
async def finalize_test(
self,
threshold=None,
golden_img_dir: pathlib.Path = None,
golden_img_name=None,
use_log: bool = True,
cmp_metric=CompareMetric.MEAN_ERROR,
test_name: str = None,
hide_menu_bar: bool = True
):
try:
test_name = test_name or f"{self.__test_name}"
golden_img_name = self.__get_golden_img_name(golden_img_name, golden_img_dir, test_name)
await self.capture_and_compare(threshold,
golden_img_dir,
golden_img_name,
use_log,
cmp_metric,
test_name,
hide_menu_bar)
finally:
await self.finalize_test_no_image()
| 14,402 |
Python
| 39.119777 | 155 | 0.608735 |
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_layout.py
|
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from .test_base import OmniUiTest
import omni.kit.app
import omni.ui as ui
class TestLayout(OmniUiTest):
"""Testing the layout"""
async def test_general(self):
"""Testing general layout and number of calls of setComputedWidth"""
window = await self.create_test_window()
with window.frame:
with ui.VStack():
with ui.HStack():
ui.Button("NVIDIA")
ui.Button("Omniverse")
bottom_stack = ui.HStack()
with bottom_stack:
ui.Button("omni")
button = ui.Button("ui")
await omni.kit.app.get_app().next_update_async()
# 21 is because the window looks like this:
# MenuBar
# Frame
# VStack
# HStack
# Button
# Stack
# Label
# Rectangle
# Button
# Stack
# Label
# Rectangle
# HStack
# Button
# Stack
# Label
# Rectangle
# Button
# Stack
# Label
# Rectangle
should_be_called = [21] + [0] * 20
for i in should_be_called:
ui.Inspector.begin_computed_width_metric()
ui.Inspector.begin_computed_height_metric()
await omni.kit.app.get_app().next_update_async()
width_calls = ui.Inspector.end_computed_width_metric()
height_calls = ui.Inspector.end_computed_height_metric()
self.assertEqual(width_calls, i)
self.assertEqual(height_calls, i)
button.height = ui.Pixel(25)
# 11 becuse we changed the height of the button and this is the list of
# changed widgets:
# 4 Button
# 4 Neighbour button because it's Fraction(1)
# 1 HStack becuase min size could change
# 1 VStack becuase min size could change
# 1 Frame becuase min size could change
should_be_called = [11] + [0] * 20
for i in range(10):
ui.Inspector.begin_computed_width_metric()
ui.Inspector.begin_computed_height_metric()
await omni.kit.app.get_app().next_update_async()
width_calls = ui.Inspector.end_computed_width_metric()
height_calls = ui.Inspector.end_computed_height_metric()
bottom_stack.height = ui.Pixel(50)
# 16 because 20 (total wingets minus MenuBar) - 4 (Button is in pixels,
# the size of pixels don't change if parent changes) and we only changed
# heights and width should not be called
should_be_called = [16] + [0] * 20
for i in should_be_called:
ui.Inspector.begin_computed_width_metric()
ui.Inspector.begin_computed_height_metric()
await omni.kit.app.get_app().next_update_async()
width_calls = ui.Inspector.end_computed_width_metric()
height_calls = ui.Inspector.end_computed_height_metric()
self.assertEqual(width_calls, 0)
self.assertEqual(height_calls, i)
button.width = ui.Pixel(25)
# 20 because everything except MenuBar could change:
# Neighbour button is changed
# Stack could change if button.width is very big
# Neighbour stack could change if current stack is changed
# Parent stack
# Root frame
#
# Height shouldn't change
should_be_called = [20] + [0] * 20
for i in should_be_called:
ui.Inspector.begin_computed_width_metric()
ui.Inspector.begin_computed_height_metric()
await omni.kit.app.get_app().next_update_async()
width_calls = ui.Inspector.end_computed_width_metric()
height_calls = ui.Inspector.end_computed_height_metric()
self.assertEqual(width_calls, i)
self.assertEqual(height_calls, 0)
await self.finalize_test()
async def test_send_mouse_events_to_back(self):
"""Testing send_mouse_events_to_back of ui.ZStack"""
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
clicked = [0, 0]
def clicked_fn(i):
clicked[i] += 1
with window.frame:
stack = ui.ZStack()
with stack:
ui.Button(clicked_fn=lambda: clicked_fn(0))
button = ui.Button(clicked_fn=lambda: clicked_fn(1))
await omni.kit.app.get_app().next_update_async()
refButton = ui_test.WidgetRef(button, "")
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move_and_click(refButton.center)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(clicked[0], 1)
stack.send_mouse_events_to_back = False
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move_and_click(refButton.center)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(clicked[1], 1)
await self.finalize_test_no_image()
async def test_visibility(self):
window = await self.create_test_window()
with window.frame:
with ui.HStack(height=32):
with ui.VStack(width=80):
ui.Spacer(height=10)
c1 = ui.ComboBox(0, "NVIDIA", "OMNIVERSE", width=100)
with ui.VStack(width=80):
ui.Spacer(height=10)
ui.ComboBox(0, "NVIDIA", "OMNIVERSE", width=100)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
c1.visible = not c1.visible
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
c1.visible = not c1.visible
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
| 6,774 |
Python
| 34.471204 | 80 | 0.566873 |
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_workspace.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.
##
from .test_base import OmniUiTest
import carb.settings
import omni.appwindow
import omni.kit.app
import omni.kit.renderer
import omni.kit.test
import omni.ui as ui
class TestWorkspace(OmniUiTest):
"""Testing ui.Workspace"""
async def test_window_selection(self):
"""Testing window selection callback"""
ui.Workspace.clear()
self.text = "null"
def update_selection(selected):
self.text = "Selected" if selected else "UnSelected"
ui_main_window = ui.MainWindow()
window1 = ui.Window("First Selection", width=100, height=100)
window2 = ui.Window("Second Selection", width=100, height=100)
window3 = ui.Window("Third Selection", width=100, height=100)
await omni.kit.app.get_app().next_update_async()
main_dockspace = ui.Workspace.get_window("DockSpace")
window1.dock_in(main_dockspace, ui.DockPosition.SAME)
window2.dock_in(main_dockspace, ui.DockPosition.SAME)
window3.dock_in(main_dockspace, ui.DockPosition.SAME)
await omni.kit.app.get_app().next_update_async()
# add callback function to window2 to subscribe selection change in windows
window2.set_selected_in_dock_changed_fn(lambda value: update_selection(value))
await omni.kit.app.get_app().next_update_async()
# select window2 to check if the callback is triggered
window2.focus()
await omni.kit.app.get_app().next_update_async()
self.assertEqual(self.text, "Selected")
await omni.kit.app.get_app().next_update_async()
# select window1 to check if the callback is triggered
window1.focus()
await omni.kit.app.get_app().next_update_async()
self.assertEqual(self.text, "UnSelected")
async def test_workspace_nohide(self):
"""Testing window layout without hiding the windows"""
ui.Workspace.clear()
await self.create_test_area(256, 256)
ui_main_window = ui.MainWindow()
ui_main_window.main_menu_bar.visible = False
window1 = ui.Window("First", width=100, height=100)
window2 = ui.Window("Second", width=100, height=100)
await omni.kit.app.get_app().next_update_async()
main_dockspace = ui.Workspace.get_window("DockSpace")
window1.dock_in(main_dockspace, ui.DockPosition.SAME)
window2.dock_in(window1, ui.DockPosition.BOTTOM)
await omni.kit.app.get_app().next_update_async()
# Save the layout
layout = ui.Workspace.dump_workspace()
# Reference. Don't check directly because `dock_id` is random.
# [
# {
# "dock_id": 3358485147,
# "children": [
# {
# "dock_id": 1,
# "position": "TOP",
# "children": [
# {
# "title": "First",
# "width": 100.0,
# "height": 100.0,
# "position_x": 78.0,
# "position_y": 78.0,
# "dock_id": 1,
# "visible": True,
# "selected_in_dock": False,
# }
# ],
# },
# {
# "dock_id": 2,
# "position": "BOTTOM",
# "children": [
# {
# "title": "Second",
# "width": 100.0,
# "height": 100.0,
# "position_x": 78.0,
# "position_y": 78.0,
# "dock_id": 2,
# "visible": True,
# "selected_in_dock": False,
# }
# ],
# },
# ],
# }
# ]
self.assertEqual(layout[0]["children"][0]["children"][0]["title"], "First")
self.assertEqual(layout[0]["children"][1]["children"][0]["title"], "Second")
window3 = ui.Window("Third", width=100, height=100)
await omni.kit.app.get_app().next_update_async()
window3.dock_in(window1, ui.DockPosition.LEFT)
ui.Workspace.restore_workspace(layout, True)
window3.position_x = 78
window3.position_y = 78
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_workspace_nohide_invisible(self):
"""Testing window layout without hiding the windows"""
ui.Workspace.clear()
await self.create_test_area(256, 256)
ui_main_window = ui.MainWindow()
ui_main_window.main_menu_bar.visible = False
window1 = ui.Window(
"First Vis", width=100, height=100, position_x=0, position_y=0, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR
)
window2 = ui.Window(
"Second Invis", width=100, height=100, position_x=100, position_y=0, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR
)
await omni.kit.app.get_app().next_update_async()
window2.visible = False
await omni.kit.app.get_app().next_update_async()
# Save the layout
layout = ui.Workspace.dump_workspace()
# We have first window visible, the second is not visible
window3 = ui.Window("Third Absent", width=100, height=100, position_x=0, position_y=100)
await omni.kit.app.get_app().next_update_async()
ui.Workspace.restore_workspace(layout, True)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_dock_node_size(self):
ui.Workspace.clear()
await self.create_test_area(256, 256)
ui_main_window = ui.MainWindow()
ui_main_window.main_menu_bar.visible = False
window1 = ui.Window("1", width=100, height=100)
window2 = ui.Window("2", width=100, height=100)
window3 = ui.Window("3", width=100, height=100)
window4 = ui.Window("4", width=100, height=100)
await omni.kit.app.get_app().next_update_async()
main_dockspace = ui.Workspace.get_window("DockSpace")
window1.dock_in(main_dockspace, ui.DockPosition.SAME)
window2.dock_in(window1, ui.DockPosition.RIGHT)
window3.dock_in(window1, ui.DockPosition.BOTTOM)
window4.dock_in(window2, ui.DockPosition.BOTTOM)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(ui.Workspace.get_dock_id_width(window1.dock_id), 126)
self.assertEqual(ui.Workspace.get_dock_id_width(window2.dock_id), 126)
self.assertEqual(ui.Workspace.get_dock_id_width(window3.dock_id), 126)
self.assertEqual(ui.Workspace.get_dock_id_width(window4.dock_id), 126)
self.assertEqual(ui.Workspace.get_dock_id_height(window1.dock_id), 124)
self.assertEqual(ui.Workspace.get_dock_id_height(window2.dock_id), 124)
self.assertEqual(ui.Workspace.get_dock_id_height(window3.dock_id), 124)
self.assertEqual(ui.Workspace.get_dock_id_height(window4.dock_id), 124)
ui.Workspace.set_dock_id_width(window1.dock_id, 50)
ui.Workspace.set_dock_id_height(window1.dock_id, 50)
ui.Workspace.set_dock_id_height(window4.dock_id, 50)
await self.finalize_test()
ui.Workspace.clear()
def _window_visibility_callback(self, title, visible) -> None:
self._visibility_changed_window_title = title
self._visibility_changed_window_visible = visible
def _window_visibility_callback2(self, title, visible) -> None:
self._visibility_changed_window_title2 = title
self._visibility_changed_window_visible2 = visible
def _window_visibility_callback3(self, title, visible) -> None:
self._visibility_changed_window_title3 = title
self._visibility_changed_window_visible3 = visible
async def test_workspace_window_visibility_callback(self):
"""Testing window visibility changed callback"""
# test window create
ui.Workspace.clear()
self._visibility_changed_window_title = None
self._visibility_changed_window_visible = False
self._visibility_changed_window_title2 = None
self._visibility_changed_window_visible2 = False
self._visibility_changed_window_title3 = None
self._visibility_changed_window_visible3 = False
id1 = ui.Workspace.set_window_visibility_changed_callback(self._window_visibility_callback)
id2 = ui.Workspace.set_window_visibility_changed_callback(self._window_visibility_callback2)
id3 = ui.Workspace.set_window_visibility_changed_callback(self._window_visibility_callback3)
window2 = ui.Window("visible_change", width=100, height=100)
self.assertTrue(self._visibility_changed_window_title=="visible_change")
self.assertTrue(self._visibility_changed_window_visible==True)
# test window visible change to False
self._visibility_changed_window_title = None
self._visibility_changed_window_visible = True
window2.visible = False
await omni.kit.app.get_app().next_update_async()
self.assertTrue(self._visibility_changed_window_title=="visible_change")
self.assertTrue(self._visibility_changed_window_visible==False)
# test window visible change to true
self._visibility_changed_window_title = None
self._visibility_changed_window_visible = False
window2.visible = True
await omni.kit.app.get_app().next_update_async()
self.assertTrue(self._visibility_changed_window_title=="visible_change")
self.assertTrue(self._visibility_changed_window_visible==True)
# test another callback function change to false
self._visibility_changed_window_title2 = None
self._visibility_changed_window_visible2 = True
window2.visible = False
await omni.kit.app.get_app().next_update_async()
self.assertTrue(self._visibility_changed_window_title2=="visible_change")
self.assertTrue(self._visibility_changed_window_visible2==False)
# test another callback function change change to true
self._visibility_changed_window_title2 = None
self._visibility_changed_window_visible2 = False
window2.visible = True
await omni.kit.app.get_app().next_update_async()
self.assertTrue(self._visibility_changed_window_title2=="visible_change")
self.assertTrue(self._visibility_changed_window_visible2==True)
# Add more window visible change to true and wait more frames
self._visibility_changed_window_title = None
self._visibility_changed_window_visible = False
window3 = ui.Window("visible_change3", width=100, height=100)
for i in range(10):
await omni.kit.app.get_app().next_update_async()
self.assertTrue(self._visibility_changed_window_title=="visible_change3")
self.assertTrue(self._visibility_changed_window_visible==True)
# Add more window visible change to False
self._visibility_changed_window_title = None
self._visibility_changed_window_visible = False
window3.visible = False
for i in range(10):
await omni.kit.app.get_app().next_update_async()
self.assertTrue(self._visibility_changed_window_title=="visible_change3")
self.assertTrue(self._visibility_changed_window_visible==False)
# test remove_window_visibility_changed_callback
self._visibility_changed_window_title = None
self._visibility_changed_window_visible = True
self._visibility_changed_window_title2 = None
self._visibility_changed_window_visible2 = True
ui.Workspace.remove_window_visibility_changed_callback(id1)
window2.visible = False
await omni.kit.app.get_app().next_update_async()
self.assertTrue(self._visibility_changed_window_title==None)
self.assertTrue(self._visibility_changed_window_visible==True)
self.assertTrue(self._visibility_changed_window_title2=="visible_change")
self.assertTrue(self._visibility_changed_window_visible2==False)
# OM-60640: Notice that remove one change callback not effect other callbacks
self._visibility_changed_window_visible = False
self._visibility_changed_window_title2 = None
self._visibility_changed_window_visible2 = False
self._visibility_changed_window_title3 = None
self._visibility_changed_window_visible3 = False
window2.visible = True
await omni.kit.app.get_app().next_update_async()
self.assertTrue(self._visibility_changed_window_title==None)
self.assertTrue(self._visibility_changed_window_visible==False)
self.assertTrue(self._visibility_changed_window_title2=="visible_change")
self.assertTrue(self._visibility_changed_window_visible2==True)
self.assertTrue(self._visibility_changed_window_title3=="visible_change")
self.assertTrue(self._visibility_changed_window_visible3==True)
ui.Workspace.remove_window_visibility_changed_callback(id2)
ui.Workspace.remove_window_visibility_changed_callback(id3)
async def test_workspace_deferred_dock_in(self):
"""Testing window layout without hiding the windows"""
ui.Workspace.clear()
await self.create_test_area(256, 256)
ui_main_window = ui.MainWindow()
ui_main_window.main_menu_bar.visible = False
window1 = ui.Window("First", width=100, height=100)
window2 = ui.Window("Second", width=100, height=100)
await omni.kit.app.get_app().next_update_async()
main_dockspace = ui.Workspace.get_window("DockSpace")
window1.dock_in(main_dockspace, ui.DockPosition.SAME)
window2.dock_in(window1, ui.DockPosition.BOTTOM)
await omni.kit.app.get_app().next_update_async()
# Save the layout
layout = ui.Workspace.dump_workspace()
window2.deferred_dock_in("First")
# Restore_workspace should reset deferred_dock_in
ui.Workspace.restore_workspace(layout, True)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_freeze(self):
PRESENT_THREAD = "/exts/omni.kit.renderer.core/present/enabled"
settings = carb.settings.get_settings()
present_thread_enabled = settings.get(PRESENT_THREAD)
settings.set(PRESENT_THREAD, True)
window = await self.create_test_window()
with window.frame:
ui.Label("NVIDIA Omniverse")
# Get IRenderer
renderer = omni.kit.renderer.bind.get_renderer_interface()
# Get default IAppWindow
app_window_factory = omni.appwindow.acquire_app_window_factory_interface()
app_window = app_window_factory.get_app_window()
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
# Draw freeze the window
renderer.draw_freeze_app_window(app_window, True)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
with window.frame:
ui.Label("Something Else")
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
renderer.draw_freeze_app_window(app_window, False)
await omni.kit.app.get_app().next_update_async()
settings.set(PRESENT_THREAD, present_thread_enabled)
await omni.kit.app.get_app().next_update_async()
class WorkspaceCallbacks(omni.kit.test.AsyncTestCase):
def _window_created_callback(self, w) -> None:
self._created = w
async def test_window_creation_callback(self):
"""Testing window creation callback"""
self._created = None
ui.Workspace.set_window_created_callback(self._window_created_callback)
window1 = ui.Window("First", width=100, height=100)
await omni.kit.app.get_app().next_update_async()
self.assertTrue(self._created == window1)
| 16,910 |
Python
| 41.704545 | 115 | 0.626316 |
omniverse-code/kit/exts/omni.ui/omni/ui/tests/compare_utils.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.
##
"""The utilities for image comparison"""
from pathlib import Path
import os
import platform
import carb
import carb.tokens
import sys
import traceback
import omni.kit.test
from omni.kit.test.teamcity import teamcity_publish_image_artifact
OUTPUTS_DIR = Path(omni.kit.test.get_test_output_path())
KIT_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${kit}")).parent.parent.parent
GOLDEN_DIR = KIT_ROOT.joinpath("data/tests/omni.ui.tests")
def Singleton(class_):
"""
A singleton decorator.
TODO: It's also available in omni.kit.widget.stage. Do we have a utility extension where we can put the utilities
like this?
"""
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
class CompareError(Exception):
pass
class CompareMetric:
MEAN_ERROR = "mean_error"
MEAN_ERROR_SQUARED = "mean_error_squared"
PIXEL_COUNT = "pixel_count"
def compare(image1: Path, image2: Path, image_diffmap: Path, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR):
"""
Compares two images and return a value that indicates the difference based on the metric used.
Types of comparison: mean error (default), mean error squared, and pixel count.
Mean Error (mean absolute error):
Average pixel level for each channel in the image, return a number between [0, 255]
This is the default method in UI compare tests - it gives a nice range of numbers.
Mean Error Squared (mean squared error):
Measures the average of the squares of the errors, return a number between [0, 1]
This is the default method used in Kit Rendering, see `meanErrorSquaredMetric`
Pixel Count:
Return the number of pixels that are different
It uses Pillow for image read.
Args:
image1, image2: images to compare
image_diffmap: the difference map image will be saved if there is any difference between given images
threshold: the threshold value (int or float)
cmp_metric: comparison method
"""
if not image1.exists():
raise CompareError(f"File image1 {image1} does not exist")
if not image2.exists():
raise CompareError(f"File image2 {image2} does not exist")
# OMFP-1891: Cease use of pip install
if "PIL" not in sys.modules.keys():
raise CompareError("Cannot import PIL from Pillow, image comparison failed.")
from PIL import Image, ImageChops, ImageStat
original = Image.open(str(image1))
contrast = Image.open(str(image2))
if original.size != contrast.size:
raise CompareError(
f"[omni.ui.test] Can't compare different resolutions\n\n"
f"{image1} {original.size[0]}x{original.size[1]}\n"
f"{image2} {contrast.size[0]}x{contrast.size[1]}\n\n"
f"It's possible that your monitor DPI is not 100%.\n\n"
)
if original.mode != contrast.mode:
raise CompareError(
f"[omni.ui.test] Can't compare images with different mode (channels).\n\n"
f"{image1} {original.mode}\n"
f"{image2} {contrast.mode}\n\n"
)
img_diff = ImageChops.difference(original, contrast)
stat = ImageStat.Stat(img_diff)
if cmp_metric == CompareMetric.MEAN_ERROR:
# Calculate average difference between two images
diff = sum(stat.mean) / len(stat.mean)
elif cmp_metric == CompareMetric.MEAN_ERROR_SQUARED:
# Measure the average of the squares of the errors between two images
# Errors are calculated from 0 to 255 (squared), divide by 255^2 to have a range between [0, 1]
errors = [x / stat.count[i] for i, x in enumerate(stat.sum2)]
diff = sum(errors) / len(stat.sum2) / 255**2
elif cmp_metric == CompareMetric.PIXEL_COUNT:
# Count of different pixels - on single channel image the value of getpixel is an int instead of a tuple
if isinstance(img_diff.getpixel((0, 0)), int):
diff = sum([img_diff.getpixel((j, i)) > 0 for i in range(img_diff.height) for j in range(img_diff.width)])
else:
diff = sum(
[sum(img_diff.getpixel((j, i))) > 0 for i in range(img_diff.height) for j in range(img_diff.width)]
)
# only save image diff if needed (2 order of magnitude near threshold)
if diff > 0 and threshold and diff > threshold / 100:
# Images are different
# Multiply image by 255
img_diff = img_diff.convert("RGB").point(lambda i: min(i * 255, 255))
img_diff.save(str(image_diffmap))
return diff
async def capture_and_compare(
image_name: str,
threshold,
golden_img_dir: Path = None,
use_log: bool = True,
cmp_metric=CompareMetric.MEAN_ERROR,
):
"""
Captures frame and compares it with the golden image.
Args:
image_name: the image name of the image and golden image.
threshold: the max threshold to collect TC artifacts.
golden_img_dir: the directory path that stores the golden image. Leave it to None to use default dir.
cmp_metric: comparison metric (mean error, mean error squared, pixel count)
Returns:
A diff value based on the comparison metric used.
"""
if not golden_img_dir:
golden_img_dir = GOLDEN_DIR
image1 = OUTPUTS_DIR.joinpath(image_name)
image2 = golden_img_dir.joinpath(image_name)
image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image_name).stem}.diffmap.png")
alt_image2 = golden_img_dir.joinpath(f"{platform.system().lower()}/{image_name}")
if os.path.exists(alt_image2):
image2 = alt_image2
if use_log:
carb.log_info(f"[omni.ui.tests.compare] Capturing {image1} and comparing with {image2}.")
import omni.renderer_capture
capture_next_frame = omni.renderer_capture.acquire_renderer_capture_interface().capture_next_frame_swapchain
wait_async_capture = omni.renderer_capture.acquire_renderer_capture_interface().wait_async_capture
capture_next_frame(str(image1))
await omni.kit.app.get_app().next_update_async()
wait_async_capture()
try:
diff = compare(image1, image2, image_diffmap, threshold, cmp_metric)
if diff >= threshold:
golden_path = Path("golden").joinpath(OUTPUTS_DIR.name)
results_path = Path("results").joinpath(OUTPUTS_DIR.name)
teamcity_publish_image_artifact(image2, golden_path, "Reference")
teamcity_publish_image_artifact(image1, results_path, "Generated")
teamcity_publish_image_artifact(image_diffmap, results_path, "Diff")
return diff
except CompareError as e:
carb.log_error(f"[omni.ui.tests.compare] Failed to compare images for {image_name}. Error: {e}")
carb.log_error(f"[omni.ui.tests.compare] Traceback:\n{traceback.format_exc()}")
| 7,390 |
Python
| 37.295337 | 118 | 0.672936 |
omniverse-code/kit/exts/omni.kit.property.skel/config/extension.toml
|
[package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.1"
category = "Internal"
feature = true
# 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 = "Skeleton Animation Property Widget"
description="View and Edit Skeleton Animation Property Values"
# URL of the extension source repository.
repository = ""
# Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file).
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# Keywords for the extension
keywords = ["kit", "usd", "property", "skel", "skeleton", "animation"]
# 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"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
[dependencies]
"omni.usd" = {}
"omni.ui" = {}
"omni.kit.window.property" = {}
"omni.kit.property.usd" = {}
"omni.kit.commands" = {}
"omni.kit.usd_undo" = {}
[[python.module]]
name = "omni.kit.property.skel"
[[test]]
args = [
"--/renderer/enabled=pxr",
"--/renderer/active=pxr",
"--/renderer/multiGpu/enabled=false",
"--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611
"--/renderer/multiGpu/maxGpuCount=1",
"--/app/asyncRendering=false",
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.hydra.pxr",
"omni.kit.renderer.capture",
"omni.kit.mainwindow",
"omni.kit.ui_test",
"omni.kit.test_suite.helpers"
]
stdoutFailPatterns.exclude = [
"*HydraRenderer failed to render this frame*", # Can drop a frame or two rendering with OpenGL interop
"*Failed to acquire interface*while unloading all plugins*",
"*Cannot use omni.hydra.pxr without OpenGL interop*" # Linux TC configs with multi-GPU might not have OpenGL available
]
| 2,206 |
TOML
| 30.084507 | 122 | 0.703989 |
omniverse-code/kit/exts/omni.kit.property.skel/omni/kit/property/skel/scripts/skel_animation_widget.py
|
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
import omni.usd
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidget
from omni.kit.property.usd.prim_selection_payload import PrimSelectionPayload
from pxr import Sdf, Usd, UsdSkel
from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutProperty
from .command import *
class SkelAnimationAttributesWidget(UsdPropertiesWidget):
def __init__(self, title: str):
super().__init__(title, collapsed=False)
self._title = title
from omni.kit.property.usd import PrimPathWidget
self._add_button_menus = []
self._add_button_menus.append(
PrimPathWidget.add_button_menu_entry(
"Animation/Skeletal Animation",
show_fn=self.on_show,
onclick_fn=self.on_click
)
)
def destroy(self):
for menu_entry in self._add_button_menus:
PrimPathWidget.remove_button_menu_entry(menu_entry)
def on_show(self, objects: dict):
if "prim_list" not in objects or "stage" not in objects:
return False
stage = objects["stage"]
if not stage:
return False
prim_list = objects["prim_list"]
if len(prim_list) < 1:
return False
for item in prim_list:
if isinstance(item, Sdf.Path):
prim = stage.GetPrimAtPath(item)
elif isinstance(item, Usd.Prim):
prim = item
if not prim.HasAPI(UsdSkel.BindingAPI) and prim.IsA(UsdSkel.Skeleton):
return True
return False
def on_click(self, payload: PrimSelectionPayload):
if payload is None:
return Sdf.Path.emptyPath
payload_paths = payload.get_paths()
omni.kit.commands.execute("ApplySkelBindingAPICommand", paths=payload_paths)
def on_new_payload(self, payload):
if not super().on_new_payload(payload):
return False
if not self._payload or len(self._payload) == 0:
return False
for prim_path in payload:
prim = self._get_prim(prim_path)
if not prim:
return False
if prim.HasAPI(UsdSkel.BindingAPI) and (prim.IsA(UsdSkel.Skeleton) or prim.IsA(UsdSkel.Root)):
return True
return False
def _filter_props_to_build(self, props):
return [prop for prop in props if prop.GetName() == "skel:animationSource"]
def _customize_props_layout(self, props):
frame = CustomLayoutFrame(hide_extra=True)
def spacer_build_fn(*args):
ui.Spacer(height=2)
with frame:
CustomLayoutProperty("skel:animationSource", "Animation Source")
CustomLayoutProperty(None, None, build_fn=spacer_build_fn)
return frame.apply(props)
def get_additional_kwargs(self, ui_attr):
random_prim = Usd.Prim()
prim_same_type = True
if self._payload:
prim_paths = self._payload.get_paths()
for prim_path in prim_paths:
prim = self._get_prim(prim_path)
if not prim:
continue
if not random_prim:
random_prim = prim
elif random_prim.GetTypeName() != prim.GetTypeName():
prim_same_type = False
break
if ui_attr.prop_name == "skel:animationSource" and prim_same_type and random_prim and (random_prim.IsA(UsdSkel.Skeleton) or random_prim.IsA(UsdSkel.Root)):
return None, {"target_picker_filter_type_list": [UsdSkel.Animation], "targets_limit": 1}
return None, {"targets_limit": 0}
| 4,140 |
Python
| 38.066037 | 163 | 0.622947 |
omniverse-code/kit/exts/omni.kit.property.skel/omni/kit/property/skel/scripts/extension.py
|
import omni.ext
from .skel_animation_widget import SkelAnimationAttributesWidget
from .mesh_skel_binding_widget import MeshSkelBindingAttributesWidget
class SkelPropertyExtension(omni.ext.IExt):
def __init__(self):
self._skel_widget = None
def on_startup(self, ext_id):
import omni.kit.window.property as p
self._skel_animation_widget = SkelAnimationAttributesWidget("Skeletal Animation")
self._mesh_skel_binding_widget = MeshSkelBindingAttributesWidget("Skeletal Binding")
w = p.get_window()
if w:
w.register_widget("prim", "skel_animation", self._skel_animation_widget)
w.register_widget("prim", "mesh_skel_binding", self._mesh_skel_binding_widget)
def on_shutdown(self):
if self._skel_widget is not None:
import omni.kit.window.property as p
w = p.get_window()
if w:
w.unregister_widget("prim", "skel_animation")
w.unregister_widget("prim", "mesh_skel_binding")
self._skel_animation_widget.destroy()
self._skel_animation_widget = None
self._mesh_skel_binding_widget.destroy()
self._mesh_skel_binding_widget = None
| 1,229 |
Python
| 39.999999 | 92 | 0.644426 |
omniverse-code/kit/exts/omni.kit.property.skel/omni/kit/property/skel/scripts/__init__.py
|
from .extension import *
from .command import *
| 48 |
Python
| 15.333328 | 24 | 0.75 |
omniverse-code/kit/exts/omni.kit.property.skel/omni/kit/property/skel/scripts/mesh_skel_binding_widget.py
|
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
import omni.usd
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidget, UsdPropertyUiEntry
from omni.kit.property.usd.prim_selection_payload import PrimSelectionPayload
from pxr import Usd, UsdSkel, UsdGeom
from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty
from .command import *
MESH_ATTRS = ["skel:skeleton", "skel:skinningMethod", "skel:blendShapeTargets"]
class MeshSkelBindingAttributesWidget(UsdPropertiesWidget):
def __init__(self, title: str):
super().__init__(title, collapsed=False)
self._title = title
def destroy(self):
pass
def on_new_payload(self, payload):
if not super().on_new_payload(payload):
return False
if not self._payload or len(self._payload) == 0:
return False
for prim_path in payload:
prim = self._get_prim(prim_path)
if not prim:
return False
if prim.HasAPI(UsdSkel.BindingAPI) and prim.IsA(UsdGeom.Mesh):
return True
return False
def _filter_props_to_build(self, props):
return [prop for prop in props if prop.GetName() in MESH_ATTRS]
def _customize_props_layout(self, props):
frame = CustomLayoutFrame(hide_extra=True)
def spacer_build_fn(*args):
ui.Spacer(height=10)
with frame:
CustomLayoutProperty("skel:skeleton", "Skeleton")
CustomLayoutProperty(None, None, build_fn=spacer_build_fn)
CustomLayoutProperty("skel:skinningMethod", "Skinning Method")
CustomLayoutProperty(None, None, build_fn=spacer_build_fn)
CustomLayoutProperty("skel:blendShapeTargets", "Blendshape Targets")
return frame.apply(props)
def get_additional_kwargs(self, ui_attr):
random_prim = Usd.Prim()
prim_same_type = True
if self._payload:
prim_paths = self._payload.get_paths()
for prim_path in prim_paths:
prim = self._get_prim(prim_path)
if not prim:
continue
if not random_prim:
random_prim = prim
elif random_prim.GetTypeName() != prim.GetTypeName():
prim_same_type = False
break
if ui_attr.prop_name == "skel:skeleton" and prim_same_type and random_prim and random_prim.IsA(UsdGeom.Mesh):
return None, {"target_picker_filter_type_list": [UsdSkel.Skeleton], "targets_limit": 1}
elif ui_attr.prop_name == "skel:blendShapeTargets" and prim_same_type and random_prim and random_prim.IsA(UsdGeom.Mesh):
return None, {"target_picker_filter_type_list": [UsdSkel.BlendShape], "targets_limit": 0}
return None, {"targets_limit": 0}
| 3,301 |
Python
| 40.274999 | 128 | 0.653135 |
omniverse-code/kit/exts/omni.kit.property.skel/omni/kit/property/skel/scripts/command.py
|
import carb
import omni
import omni.kit.commands
from pxr import Sdf, UsdGeom, Usd, UsdSkel
from omni.kit.usd_undo import UsdLayerUndo
from typing import List
class ApplySkelBindingAPICommand(omni.kit.commands.Command):
def __init__(
self,
layer: Sdf.Layer = None,
paths: List[Sdf.Path] = []
):
self._usd_undo = None
self._layer = layer
self._paths = paths
def do(self):
stage = omni.usd.get_context().get_stage()
if self._layer is None:
self._layer = stage.GetEditTarget().GetLayer()
self._usd_undo = UsdLayerUndo(self._layer)
for path in self._paths:
prim = stage.GetPrimAtPath(path)
if not prim.HasAPI(UsdSkel.BindingAPI):
self._usd_undo.reserve(path)
UsdSkel.BindingAPI.Apply(prim)
def undo(self):
if self._usd_undo is not None:
self._usd_undo.undo()
omni.kit.commands.register(ApplySkelBindingAPICommand)
| 1,012 |
Python
| 27.138888 | 60 | 0.606719 |
omniverse-code/kit/exts/omni.kit.property.skel/omni/kit/property/skel/tests/__init__.py
|
from .test_skel import *
| 25 |
Python
| 11.999994 | 24 | 0.72 |
omniverse-code/kit/exts/omni.kit.property.skel/omni/kit/property/skel/tests/test_skel.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.ui.tests.test_base import OmniUiTest
from omni.kit import ui_test
from omni.kit.test_suite.helpers import wait_stage_loading
from pxr import Kind, Sdf, Gf
class TestSkeletonWidget(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")
self._usd_path = pathlib.Path(ext_path).joinpath("data/tests/")
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_skeleton_ui(self):
usd_context = omni.usd.get_context()
await self.docked_test_window(
window=self._w._window,
width=450,
height=650,
restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position = ui.DockPosition.BOTTOM)
test_file_path = self._usd_path.joinpath("boy_skel.usd").absolute()
await usd_context.open_stage_async(str(test_file_path))
await wait_stage_loading()
# Select the prim.
usd_context.get_selection().set_selected_prim_paths(["/Root/SkelRoot/Head_old"], 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_skeleton_ui.png")
| 2,284 |
Python
| 36.459016 | 109 | 0.688704 |
omniverse-code/kit/exts/omni.kit.property.skel/docs/CHANGELOG.md
|
# Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2021-05-31
### Changes
- Created
## [1.0.1] - 2022-01-18
### Changes
- Switch some API from AnimationSchema to RetargetingSchema
| 237 |
Markdown
| 20.636362 | 80 | 0.683544 |
omniverse-code/kit/exts/omni.kit.property.skel/docs/README.md
|
# omni.kit.property.skel
## Introduction
Property window extensions are for viewing and editing Usd Prim Attributes
## This extension supports editing of these Usd Types;
- UsdSkel.Root
- UsdSkel.Skeleton
- UsdSkel.SkelAnimation
- UsdSkel.BlendShape
### and supports editing of these Usd APIs;
- UsdSkel.BindingAPI
| 322 |
Markdown
| 16.944444 | 74 | 0.776398 |
omniverse-code/kit/exts/omni.kit.property.skel/docs/index.rst
|
omni.kit.property.skel
###########################
Property Skeleton Animation Values
.. toctree::
:maxdepth: 1
CHANGELOG
| 133 |
reStructuredText
| 10.166666 | 34 | 0.56391 |
omniverse-code/kit/exts/omni.kit.viewport.docs/config/extension.toml
|
[package]
version = "104.0.2"
authors = ["NVIDIA"]
title = "omni.kit Viewport API Documentation"
description="The documentation for the next Viewport API in Kit "
readme = "docs/README.md"
repository = ""
category = "Documentation"
keywords = ["ui", "example", "viewport", "renderer", "docs", "documentation"]
changelog="docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[dependencies]
"omni.ui" = {}
"omni.kit.documentation.builder" = {}
[[python.module]]
name = "omni.kit.viewport.docs"
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--/app/window/width=640",
"--/app/window/height=480",
"--no-window"
]
dependencies = [
"omni.kit.mainwindow",
"omni.kit.ui_test"
]
[documentation]
pages = [
"docs/overview.md",
"docs/camera_manipulator.md",
"docs/capture.md",
"docs/viewport_api.md",
"docs/widget.md",
"docs/window.md",
"docs/CHANGELOG.md",
]
| 981 |
TOML
| 21.318181 | 77 | 0.649337 |
omniverse-code/kit/exts/omni.kit.viewport.docs/omni/kit/viewport/docs/extension.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.
#
import omni.ext
from .window import ViewportDocsWindow
__all__ = ["ViewportDocsExtension"]
class ViewportDocsExtension(omni.ext.IExt):
def on_startup(self, ext_id):
self._window = ViewportDocsWindow("Viewport Doc")
def on_shutdown(self):
self._window.destroy()
self._window = None
| 751 |
Python
| 31.695651 | 76 | 0.753662 |
omniverse-code/kit/exts/omni.kit.viewport.docs/omni/kit/viewport/docs/__init__.py
|
from .extension import ViewportDocsExtension
| 45 |
Python
| 21.999989 | 44 | 0.888889 |
omniverse-code/kit/exts/omni.kit.viewport.docs/omni/kit/viewport/docs/window.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 omni.kit.documentation.builder import DocumentationBuilderWindow
from pathlib import Path
__all__ = ["ViewportDocsWindow"]
class ViewportDocsWindow(DocumentationBuilderWindow):
"""The window with the documentation"""
def __init__(self, title: str, **kwargs):
module_root = Path(__file__).parent
docs_root = module_root.parent.parent.parent.parent.joinpath("docs")
pages = ['overview.md', 'window.md', 'widget.md', 'viewport_api.md', 'capture.md', 'camera_manipulator.md']
filenames = [f'{docs_root.joinpath(page_source)}' for page_source in pages]
super().__init__(title, filenames=filenames, **kwargs)
| 1,095 |
Python
| 41.153845 | 115 | 0.73242 |
omniverse-code/kit/exts/omni.kit.viewport.docs/omni/kit/viewport/docs/tests/__init__.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
from omni.ui.tests.test_base import OmniUiTest
import omni.kit.ui_test
class TestViewportDocsWindow(OmniUiTest):
async def setUp(self):
await super().setUp()
async def tearDown(self):
await super().tearDown()
async def test_just_opened(self):
win = omni.kit.ui_test.find("Viewport Doc")
self.assertIsNotNone(win)
| 819 |
Python
| 31.799999 | 77 | 0.741148 |
omniverse-code/kit/exts/omni.kit.viewport.docs/docs/camera_manipulator.md
|
# Camera Manipulator
Mouse interaction with the Viewport is handled with classes from `omni.kit.manipulator.camera`, which is built on top of the `omni.ui.scene` framework.
We've created an `omni.ui.scene.SceneView` to host the manipulator, and by simply assigning the camera manipulators model
into the SceneView's model, all of the edits to the Camera's transform will be pushed through to the `SceneView`.
```
# And finally add the camera-manipulator into that view
with self.__scene_view.scene:
self.__camera_manip = ViewportCameraManipulator(self.viewport_api)
# Push the camera manipulator's model into the SceneView so it'lll auto-update
self.__scene_view.model = self.__camera_manip.model
```
The `omni.ui.scene.SceneView` only understands two values: 'view' and 'projection'. Our CameraManipulator's model will push
out those values as edits are made; however, it supports a larger set of values to control the manipulator itself.
## Operations and Values
The CameraManipulator model store's the amount of movement according to three modes, applied in this order:
1. Tumble
2. Look
3. Move (Pan)
4. Fly (FlightMode / WASD navigation)
### tumble
Tumble values are specified in degrees as the amount to rotate around the current up-axis.
These values should be pre-scaled with any speed before setting into the model.
This allows for different manipulators/gestures to interpret speed differently, rather than lock to a constant speed.
```python
# Tumble by 180 degrees around Y (as a movement across ui X would cause)
model.set_floats('tumble', [0, 180, 0])
```
### look
Look values are specified in degrees as the amount to rotate around the current up-axis.
These values should be pre-scaled with any speed before setting into the model.
This allows for different manipulators/gestures to interpret speed differently, rather than lock to a constant speed.
```python
# Look by 90 degrees around X (as a movement across ui Y would cause)
# i.e Look straight up
model.set_floats('look', [90, 0, 0])
```
### move
Move values are specified in world units and the amount to move the camera by.
Move is applied after rotation, so the X, Y, Z are essentially left, right, back.
These values should be pre-scaled with any speed before setting into the model.
This allows for different manipulators/gestures to interpret speed differently, rather than lock to a constant speed.
```python
# Move left by 30 units, up by 60 and back by 90
model.set_floats('move', [30, 60, 90])
```
### fly
Fly values are the direction of flight in X, Y, Z.
Fly is applied after rotation, so the X, Y, Z are essentially left, right, back.
These values will be scaled with `fly_speed` before aplication.
Because fly is a direction with `fly_speed` automatically applied, if a gesture/manipulator wants to fly slower
without changing `fly_speed` globally, it must apply whatever factor is required before setting.
```python
# Move left
model.set_floats('fly', [1, 0, 0])
# Move up
model.set_floats('fly', [0, 1, 0])
```
## Speed
By default the Camera manipulator will map a full mouse move across the viewport as follows:
- Pan: A full translation of the center-of-interest across the Viewport.
- Tumble: A 180 degree rotation across X or Y.
- Look: A 180 degree rotation across X and a 90 degree rotation across Y.
These speed can be adjusted by setting float values into the model.
### world_speed
The Pan and Zoom speed can be adjusted with three floats set into the model as 'world_speed'.
```python
# Half the movement speed for both Pan and Zoom
pan_speed_x = 0.5, pan_speed_y = 0.5, zoom_speed_z = 0.5
model.set_floats('world_speed', [pan_speed_x, pan_speed_y, zoom_speed_z])
```
### rotation_speed
The Tumble and Look speed can be adjusted with either a scalar value for all rotation axes or per component.
```python
# Half the rotation speed for both Tumble and Look
rot_speed_both = 0.5
model.set_floats('rotation_speed', [rot_speed_both])
# Half the rotation speed for both Tumble and Look in X and quarter if for Y
rot_speed_x = 0.5, rot_speed_y = 0.25
model.set_floats('rotation_speed', [rot_speed_x, rot_speed_y])
```
### tumble_speed
Tumble can be adjusted separately with either a scalar value for all rotation axes or per component.
The final speed of Tumble operation is `rotation_speed * tumble_speed`
```python
# Half the rotation speed for Tumble
rot_speed_both = 0.5
model.set_floats('tumble_speed', [rot_speed_both])
# Half the rotation speed for Tumble in X and quarter if for Y
rot_speed_x = 0.5, rot_speed_y = 0.25
model.set_floats('tumble_speed', [rot_speed_x, rot_speed_y])
```
### look_speed
Look can be adjusted separately with either a scalar value for all rotation axes or per component.
The final speed of a Look operation is `rotation_speed * tumble_speed`
```python
# Half the rotation speed for Look
rot_speed_both = 0.5
model.set_floats('look_speed', [rot_speed_both])
# Half the rotation speed for Tumble in X and quarter if for Y
rot_speed_x = 0.5, rot_speed_y = 0.25
model.set_floats('look_speed', [rot_speed_x, rot_speed_y])
```
### fly_speed
The speed at which FlightMode (WASD navigation) will fly through the scene.
FlightMode speed can be adjusted separately with either a scalar value for all axes or per component.
```python
# Half the speed in all directions
fly_speed = 0.5
model.set_floats('fly_speed', [fly_speed])
# Half the speed when moving in X or Y, but double it moving in Z
fly_speed_x_y = 0.5, fly_speed_z = 2
model.set_floats('fly_speed', [fly_speed_x_y, fly_speed_x_y, fly_speed_z])
```
## Undo
Because we're operating on a unique `omni.usd.UsdContext` we don't want movement in the preview-window to affect the undo-stack.
To accomplish that, we'll set the 'disable_undo' value to an array of 1 int; essentially saying `disable_undo=True`.
```python
# Let's disable any undo for these movements as we're a preview-window
model.set_ints('disable_undo', [1])
```
## Disabling operations
By default the manipulator will allow Pan, Zoom, Tumble, and Look operations on a perspective camera, but only allow
Pan and Zoom on an orthographic one. If we want to explicitly disable any operations again we set int values as booleans
into the model.
### disable_tumble
```python
# Disable the Tumble manipulation
model.set_ints('disable_tumble', [1])
```
### disable_look
```python
# Disable the Look manipulation
model.set_ints('disable_look', [1])
```
### disable_pan
```python
# Disable the Pan manipulation.
model.set_ints('disable_pan', [1])
```
### disable_zoom
```python
# Disable the Zoom manipulation.
model.set_ints('disable_zoom', [1])
```
| 6,646 |
Markdown
| 35.927778 | 151 | 0.7418 |
omniverse-code/kit/exts/omni.kit.viewport.docs/docs/widget.md
|
# Stage Preview Widget
The `StagePreviewWidget` is comprised of a few `omni.ui` objects which are stacked on top of one-another.
So first an `omni.ui.ZStack` container is instantiated and using the `omni.ui` with syntax, the remaining objects
are created in its scope:
```python
self.__ui_container = ui.ZStack()
with self.__ui_container:
```
## Background
First we create an `omni.ui.Rectangle` that will fill the entire frame with a constant color, using black as the default.
We add a few additional style arguments so that the background color can be controlled easily from calling code.
```python
# Add a background Rectangle that is black by default, but can change with a set_style
ui.Rectangle(style_type_name_override='ViewportBackgroundColor', style={'ViewportBackgroundColor': {'background_color': 0xff000000}})
```
## ViewportWidget
Next the `omni.kit.widget.viewport.ViewportWidget` is created, directly above the background Rectangle.
In the `stage_preview` example, the `ViewportWidget` is actually created to always fill the parent frame by
passing `resolution='fill_frame'`, which will essentially make it so the black background never seen.
If a constant resolution was requested by passing a tuple `resolution=(640, 480)`; however, the rendered image would be
locked to that resolution and causing the background rect to be seen if the Widget was wider or taller than the texture's
resolution.
```python
self.__vp_widget = ViewportWidget(usd_context_name=usd_context_name, camera_path=camera_path, resolution=resolution, *ui_args, **ui_kw_args)
```
## SceneView
The final `omni.ui` element we are going to create is an `omni.ui.scene.SceneView`. We are creating it primarily to
host our camera-manipulators which are written for the `omni.ui.scene` framework, but it could also be used to insert
additional drawing on top of the `ViewportWidget` in 3D space.
```python
# Add the omni.ui.scene.SceneView that is going to host the camera-manipulator
self.__scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.STRETCH)
# And finally add the camera-manipulator into that view
with self.__scene_view.scene:
```
## Full code
```python
class StagePreviewWidget:
def __init__(self, usd_context_name: str = '', camera_path: str = None, resolution: Union[tuple, str] = None, *ui_args ,**ui_kw_args):
"""StagePreviewWidget contructor
Args:
usd_context_name (str): The name of a UsdContext the Viewport will be viewing.
camera_path (str): The path of the initial camera to render to.
resolution (x, y): The resolution of the backing texture, or 'fill_frame' to match the widget's ui-size
*ui_args, **ui_kw_args: Additional arguments to pass to the ViewportWidget's parent frame
"""
# Put the Viewport in a ZStack so that a background rectangle can be added underneath
self.__ui_container = ui.ZStack()
with self.__ui_container:
# Add a background Rectangle that is black by default, but can change with a set_style
ui.Rectangle(style_type_name_override='ViewportBackgroundColor', style={'ViewportBackgroundColor': {'background_color': 0xff000000}})
# Create the ViewportWidget, forwarding all of the arguments to this constructor
self.__vp_widget = ViewportWidget(usd_context_name=usd_context_name, camera_path=camera_path, resolution=resolution, *ui_args, **ui_kw_args)
# Add the omni.ui.scene.SceneView that is going to host the camera-manipulator
self.__scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.STRETCH)
# And finally add the camera-manipulator into that view
with self.__scene_view.scene:
self.__camera_manip = ViewportCameraManipulator(self.viewport_api)
model = self.__camera_manip.model
# Let's disable any undo for these movements as we're a preview-window
model.set_ints('disable_undo', [1])
# We'll also let the Viewport automatically push view and projection changes into our scene-view
self.viewport_api.add_scene_view(self.__scene_view)
def __del__(self):
self.destroy()
def destroy(self):
self.__view_change_sub = None
if self.__camera_manip:
self.__camera_manip.destroy()
self.__camera_manip = None
if self.__scene_view:
self.__scene_view.destroy()
self.__scene_view = None
if self.__vp_widget:
self.__vp_widget.destroy()
self.__vp_widget = None
if self.__ui_container:
self.__ui_container.destroy()
self.__ui_container = None
@property
def viewport_api(self):
# Access to the underying ViewportAPI object to control renderer, resolution
return self.__vp_widget.viewport_api
@property
def scene_view(self):
# Access to the omni.ui.scene.SceneView
return self.__scene_view
def set_style(self, *args, **kwargs):
# Give some styling access
self.__ui_container.set_style(*args, **kwargs)
```
| 5,212 |
Markdown
| 43.555555 | 152 | 0.683615 |
omniverse-code/kit/exts/omni.kit.viewport.docs/docs/CHANGELOG.md
|
# Changelog
Documentation for the next Viewport
## [104.0.2] - 2022-05-04
### Changed
- Imported to kit repro and bump version to match Kit SDK
## [1.0.2] - 2022-02-09
### Changed
- Updated documentation to include latest changes and Viewport capturing
## [1.0.1] - 2021-12-22
### Changed
- Add documentation for add_scene_view and remove_scene_view methods.
## [1.0.0] - 2021-12-20
### Changed
- Initial release
| 418 |
Markdown
| 19.949999 | 72 | 0.696172 |
omniverse-code/kit/exts/omni.kit.viewport.docs/docs/overview.md
|
# Overview
Viewport Next is a preview of the next generation of Kit's Viewport. It was
designed to be as light as possible, providing a way to isolate features and
compose them as needed to create unique experiences.
This documentation will walk through a few simple examples using this technology,
as well as how it can be used in tandem with the `omni.ui.scene` framework.
## What is a Viewport
Exactly what a viewport is can be a bit ill-defined and dependent on what you are
trying to accomplish, so it's best to define some terms up front and explain what
this documentation is targeting.

At a very high level a Viewport is a way for a user to visualize (and often
interact with) a Renderer's output of a scene. When you create a "Viewport Next"
instance via Kit's Window menu, you are actually creating a hierarchy of objects.

The three objects of interest in this hierarchy are:
1. The `ViewportWindow`, which we will be re-implementing as `StagePreviewWindow`
2. The `ViewportWidget`, one of which we will be instantiating.
3. The `ViewportTexture`, which is created and owned by the `ViewportWidget`.
While we will be using (or re-implementing) all three of those objects, this documentation is primarily
targeted towards understanding the `ViewportWidget` and it's usage in the `omni.kit.viewport.stage_preview`.
After creating a Window and instance of a `ViewportWidget`, we will finally add a camera manipulator built
with `omni.ui.scene` to interact with the `Usd.Stage`, as well as control aspects of the
Renderer's output to the underlying `ViewportTexture`.
Even though the `ViewportWidget` is our main focus, it is good to understand the backing `ViewportTexture` is independent
of the `ViewportWidget`, and that a texture's resolution may not neccessarily match the size of the `ViewportWidget`
it is contained in. This is particularly import for world-space queries or other advanced usage.
## Enabling the extension
To enable the extension and open a "Viewport Next" window, go to the "Extensions" tab
and enable the "Viewport Window" extension (`omni.kit.viewport.window`).

## Simplest example
The `omni.kit.viewport.stage_preview` adds additional features that make may make a first read of the code a bit harder.
So before stepping through that example, lets take a moment to reduce it to an even simpler case where we create
a single Window and add only a Viewport which is tied to the default `UsdContext` and `Usd.Stage`.
We won't be able to interact with the Viewport other than through Python, but because we are associated with the
default `UsdContext`: any changes in the `Usd.Stage` (from navigation or editing in another Viewport or adding a `Usd.Prim`
from the Create menu) will be reflected in our new view.
```python
from omni.kit.widget.viewport import ViewportWidget
viewport_window = omni.ui.Window('SimpleViewport', width=1280, height=720+20) # Add 20 for the title-bar
with viewport_window.frame:
viewport_widget = ViewportWidget(resolution = (1280, 720))
# Control of the ViewportTexture happens through the object held in the viewport_api property
viewport_api = viewport_widget.viewport_api
# We can reduce the resolution of the render easily
viewport_api.resolution = (640, 480)
# We can also switch to a different camera if we know the path to one that exists
viewport_api.camera_path = '/World/Camera'
# And inspect
print(viewport_api.projection)
print(viewport_api.transform)
# Don't forget to destroy the objects when done with them
# viewport_widget.destroy()
# viewport_window.destroy()
# viewport_window, viewport_widget = None, None
```

| 3,733 |
Markdown
| 42.929411 | 123 | 0.776855 |
omniverse-code/kit/exts/omni.kit.viewport.docs/docs/window.md
|
# Stage Preview Window
In order to display the Renderer's output, we'll need to have an `omni.ui.window`
that will host our widget. We're interested in this level primarily to demonstrate the
ability to create a `ViewportWidget` that isn't tied to the application's main `UsdContext`;
rather you can provide a usd_context_name string argument and the `StagePreviewWindow` will
either reuse an existing `UsdContext` with that name, or create a new one.
Keep in mind a `ViewportWidget` is currently tied to exactly one `UsdContext` for its lifetime.
If you wanted to change the `UsdContext` you are viewing, you would need to hide and show a new `ViewportWidget` based
on which context you want to be displayed.

## Context creation
The first step we take is to check whether the named `UsdContext` exists, and if not, create it.
```python
# We may be given an already valid context, or we'll be creating and managing it ourselves
usd_context = omni.usd.get_context(usd_context_name)
if not usd_context:
self.__usd_context_name = usd_context_name
self.__usd_context = omni.usd.create_context(usd_context_name)
else:
self.__usd_context_name = None
self.__usd_context = None
```
## Viewport creation
Once we know a valid context with usd_context_name exists, we create the `omni.ui.Window` passing along
the window size and window flags. The `omni.ui` documentation has more in depth description of what an `omni.ui.Window`
is and the arguments for it's creation.
After the `omni.ui.Window` has been created, we'll finally be able to create the `StagePreviewWidget`, passing along
the `usd_context_name`. We do this within the context of the `omni.ui.Window.frame` property, and forward any
additional arguments to the `StagePreviewWidget` constructor.
```python
super().__init__(title, width=window_width, height=window_height, flags=flags)
with self.frame:
self.__preview_viewport = StagePreviewWidget(usd_context_name, *vp_args, **vp_kw_args)
```
## Full code
```python
class StagePreviewWindow(ui.Window):
def __init__(self, title: str, usd_context_name: str = '', window_width: int = 1280, window_height: int = 720 + 20, flags: int = ui.WINDOW_FLAGS_NO_SCROLLBAR, *vp_args, **vp_kw_args):
"""StagePreviewWindow contructor
Args:
title (str): The name of the Window.
usd_context_name (str): The name of a UsdContext this Viewport will be viewing.
window_width(int): The width of the Window.
window_height(int): The height of the Window.
flags(int): ui.WINDOW flags to use for the Window.
*vp_args, **vp_kw_args: Additional arguments to pass to the StagePreviewWidget
"""
# We may be given an already valid context, or we'll be creating and managing it ourselves
usd_context = omni.usd.get_context(usd_context_name)
if not usd_context:
self.__usd_context_name = usd_context_name
self.__usd_context = omni.usd.create_context(usd_context_name)
else:
self.__usd_context_name = None
self.__usd_context = None
super().__init__(title, width=window_width, height=window_height, flags=flags)
with self.frame:
self.__preview_viewport = StagePreviewWidget(usd_context_name, *vp_args, **vp_kw_args)
def __del__(self):
self.destroy()
@property
def preview_viewport(self):
return self.__preview_viewport
def open_stage(self, file_path: str):
# Reach into the StagePreviewWidget and get the viewport where we can retrieve the usd_context or usd_context_name
self.__preview_viewport.viewport_api.usd_context.open_stage(file_path)
# the Viewport doesn't have any idea of omni.ui.scene so give the models a sync after open (camera may have changed)
self.__preview_viewport.sync_models()
def destroy(self):
if self.__preview_viewport:
self.__preview_viewport.destroy()
self.__preview_viewport = None
if self.__usd_context:
# We can't fully tear down everything yet, so just clear out any active stage
self.__usd_context.remove_all_hydra_engines()
# self.__usd_context = None
# omni.usd.destroy_context(self.__usd_context_name)
super().destroy()
```
| 4,376 |
Markdown
| 43.663265 | 187 | 0.684186 |
omniverse-code/kit/exts/omni.kit.viewport.docs/docs/viewport_api.md
|
# Viewport API
The ViewportAPI object is used to access and control aspects of the render, who will then push images into the backing texture.
It is accessed via the `ViewportWidget.viewport_api` property which returns a Python `weakref.proxy` object.
The use of a weakref is done in order to make sure that a Renderer and Texture aren't kept alive because client code
is keeping a reference to one of these objects. That is: the lifetime of a Viewport is controlled by the creator of the Viewport and
cannot be extended beyond the usage they expect.
With our simple `omni.kit.viewport.stage_preview` example, we'll now run through some cases of directly controlling the render,
similar to what the Content context-menu does.
```python
from omni.kit.viewport.stage_preview.window import StagePreviewWindow
# Viewport widget can be setup to fill the frame with 'fill_frame', or to a constant resolution (x, y).
resolution = 'fill_frame' or (640, 480) # Will use 'fill_frame'
# Give the Window a unique name, the window-size, and forward the resolution to the Viewport itself
preview_window = StagePreviewWindow('My Stage Preview', usd_context_name='MyStagePreviewWindowContext',
window_width=640, window_height=480, resolution=resolution)
# Open a USD file in the UsdContext that the preview_window is using
preview_window.open_stage('http://omniverse-content-production.s3-us-west-2.amazonaws.com/Samples/Astronaut/Astronaut.usd')
# Save an easy-to-use reference to the ViewportAPI object
viewport_api = preview_window.preview_viewport.viewport_api
```
## Camera
The camera being used to render the image is controlled with the `camera_path` property.
It will return and is settable with a an `Sdf.Path`.
The property will also accept a string, but it is slightly more efficient to set with an `Sdf.Path` if you have one available.
```python
print(viewport_api.camera_path)
# => '/Root/LongView'
# Change the camera to view through the implicit Top camera
viewport_api.camera_path = '/OmniverseKit_Front'
# Change the camera to view through the implicit Perspective camera
viewport_api.camera_path = '/OmniverseKit_Persp'
```
## Filling the canvas
Control whether the texture-resolution should be adjusted based on the parent objects ui-size with the `fill_frame` property.
It will return and is settable with a bool.
```python
print('viewport_api.fill_frame)
# => True
# Disable the automatic resolution
viewport_api.fill_frame = False
# And give it an explicit resolution
viewport_api.resolution = (640, 480)
```
## Resolution
Resolution of the underlying `ViewportTexture` can be queried and set via the `resolution` property.
It will return and is settable with a tuple representing the (x, y) resolution of the rendered image.
```python
print(viewport_api.resolution)
# => (640, 480)
# Change the render output resolution to a 512 x 512 texture
viewport_api.resolution = (512, 512)
```
## SceneView
For simplicity, the ViewportAPI can push both view and projection matrices into an `omni.ui.scene.SceneView.model`.
The use of these methods are not required, rather provided a convenient way to
auto-manage their relationship (particularly for stage independent camera, resolution, and widget size changes),
while also providing room for future expansion where a `SceneView` may be locked
to last delivered rendered frame versus the current implementation that pushes changes
into the Renderer and the `SceneView` simultaneously.
### add_scene_view
Add an `omni.ui.scene.SceneView` to the list of models that the Viewport will notify with changes to view and projection matrices.
The Viewport will only retain a weak-reference to the provided `SceneView` to avoid extending the lifetime of the `SceneView` itself.
A `remove_scene_view` is available if the need to dynamically change the list of models to be notified is necessary.
```python
scene_view = omni.ui.scene.SceneView()
# Pass the real object, as a weak-reference will be retained
viewport_api.add_scene_view(scene_view)
```
### remove_scene_view
Remove the `omni.ui.scene.SceneView` from the list of models that the Viewport will notify from changes to view and projection matrices.
Because the Viewport only retains a weak-reference to the `SceneView`, calling this explicitly isn't mandatory, but can be
used to dynamically change the list of `SceneView` objects whose model should be updated.
```python
viewport_api.remove_scene_view(scene_view)
```
## Additional Accessors
The `ViewportAPI` provides a few additional read-only accessors for convenience:
### usd_context_name
```python
viewport_api.usd_context_name => str
# Returns the name of the UsdContext the Viewport is bound to.
```
### usd_context
```python
viewport_api.usd_context => omni.usd.UsdContext
# Returns the actual UsdContext the Viewport is bound to, essentially `omni.usd.get_context(self.usd_context_name)`.
```
### stage
```python
viewport_api.stage => Usd.Stage
# Returns the `Usd.Stage` the ViewportAPI is bound to, essentially: `omni.usd.get_context(self.usd_context_name).get_stage()`.
```
### projection
```python
viewport_api.projection=> Gf.Matrix4d
# Returns the Gf.Matrix4d of the projection. This may differ than the projection of the `Usd.Camera` based on how the Viewport is placed in the parent widget.
```
### transform
```python
viewport_api.transform => Gf.Matrix4d
# Return the Gf.Matrix4d of the transform for the `Usd.Camera` in world-space.
```
### view
```python
viewport_api.view => Gf.Matrix4d
# Return the Gf.Matrix4d of the inverse-transform for the `Usd.Camera` in world-space.
```
### time
```python
viewport_api.time => Usd.TimeCode
# Return the Usd.TimeCode that the Viewport is using.
```
## Space Mapping
The `ViewportAPI` natively uses NDC coordinates to interop with the payloads from `omni.ui.scene` gestures.
To understand where these coordinates are in 3D-space for the `ViewportTexture`, two properties will
can be used to get a `Gf.Matrix4d` to convert to and from NDC-space to World-space.
```python
origin = (0, 0, 0)
origin_screen = viewport_api.world_to_ndc.Transform(origin)
print('Origin is at {origin_screen}, in screen-space')
origin = viewport_api.ndc_to_world.Transform(origin_screen)
print('Converted back to world-space, origin is {origin}')
```
### world_to_ndc
```python
viewport_api.world_to_ndc => Gf.Matrix4d
# Returns a Gf.Matrix4d to move from World/Scene space into NDC space
```
### ndc_to_world
```python
viewport_api.ndc_to_world => Gf.Matrix4d
# Returns a Gf.Matrix4d to move from NDC space into World/Scene space
```
## World queries
While it is useful being able to move through these spaces is useful, for the most part what we'll be more interested
in using this to inspect the scene that is being rendered. What that means is that we'll need to move from an NDC coordinate
into pixel-space of our rendered image.
A quick breakdown of the three spaces in use:
The native NDC space that works with `omni.ui.scene` gestures can be thought of as a cartesian space centered on the rendered image.

We can easily move to a 0.0 - 1.0 uv space on the rendered image.

And finally expand that 0.0 - 1.0 uv space into pixel space.

Now that we know how to map between the ui and texture space, we can use it to convert between screen and 3D-space.
More importantly, we can use it to actually query the backing `ViewportTexture` about objects and locations in the scene.
### request_query
```python
viewport_api.request_query(pixel_coordinate: (x, y), query_completed: callable) => None
# Query a pixel co-ordinate with a callback to be executed when the query completes
# Get the mouse position from within an omni.ui.scene gesture
mouse_ndc = self.sender.gesture_payload.mouse
# Convert the ndc-mouse to pixel-space in our ViewportTexture
mouse, in_viewport = viewport_api.map_ndc_to_texture_pixel(mouse_ndc)
# We know immediately if the mapping is outside the ViewportTexture
if not in_viewport:
return
# Inside the ViewportTexture, create a callback and query the 3D world
def query_completed(path, pos, *args):
if not path:
print('No object')
else:
print(f"Object '{path}' hit at {pos}")
viewport_api.request_query(mouse, query_completed)
```
## Asynchronous waiting
Some properties and API calls of the Viewport won't take effect immediately after control-flow has returned to the caller.
For example, setting the camera-path or resolution won't immediately deliver frames from that Camera at the new resolution.
There are two methods available to asynchrnously wait for the changes to make their way through the pipeline.
### wait_for_render_settings_change
Asynchronously wait until a render-settings change has been ansorbed by the backend.
This can be useful after changing the camera, resolution, or render-product.
```python
my_custom_product = '/Render/CutomRenderProduct'
viewport_api.render_product_path = my_custom_product
settings_changed = await viewport_api.wait_for_render_settings_change()
print('settings_changed', settings_changed)
```
### wait_for_rendered_frames
Asynchronously wait until a number of frames have been delivered.
Default behavior is to wait for deivery of 1 frame, but the function accepts an optional argument for an additional number of frames to wait on.
```python
await viewport_api.wait_for_rendered_frames(10)
print('Waited for 10 frames')
```
## Capturing Viewport frames
To access the state of the Viewport's next frame and any AOVs it may be rendering, you can schedule a capture with the `schedule_capture` method.
There are a variety of default Capturing delegates in the `omni.kit.widget.viewport.capture` that can handle writing to disk or accesing the AOV's buffer.
Because capture is asynchronous, it will likely not have occured when control-flow has returned to the caller of `schedule_capture`.
To wait until it has completed, the returned object has a `wait_for_result` method that can be used.
### schedule_capture
```python
viewport_api.schedule_capture(capture_delegate: Capture): -> Capture
```
```python
from omni.kit.widget.viewport.capture import FileCapture
capture = viewport_api.schedule_capture(FileCapture(image_path))
captured_aovs = await capture.wait_for_result()
if captured_aovs:
print(f'AOV "{captured_aovs[0]}" was written to "{image_path}"')
else:
print(f'No image was written to "{image_path}"')
```
| 10,506 |
Markdown
| 37.346715 | 159 | 0.762136 |
omniverse-code/kit/exts/omni.kit.viewport.docs/docs/capture.md
|
# Capture
`omni.kit.widget.viewport.capture` is the interface to a capture a Viewport's state and AOVs.
It provides a few convenient implementations that will write AOV(s) to disk or pass CPU buffers for pixel access.
## FileCapture
A simple delegate to capture a single AOV to a single file.
It can be used as is, or subclassed to access additional information/meta-data to be written.
By default it will capture a color AOV, but accepts an explicit AOV-name to capture instead.
```python
from omni.kit.widget.viewport.capture import FileCapture
capture = viewport_api.schedule_capture(FileCapture(image_path))
captured_aovs = await capture.wait_for_result()
if captured_aovs:
print(f'AOV "{captured_aovs[0]}" was written to "{image_path}"')
else:
print(f'No image was written to "{image_path}"')
```
A sample subclass implementation to write additional data.
```python
from omni.kit.widget.viewport.capture import FileCapture
SideCarWriter(FileCapture):
def __init__(self, image_path, aov_name=''):
super().__init__(image_path, aov_name)
def capture_aov(self, file_path, aov):
# Call the default file-saver
self.save_aov_to_file(file_path, aov)
# Possibly append data to a custom image
print(f'Wrote AOV "{aov['name']}" to "{file_path}")
print(f' with view: {self.view}")
print(f' with projection: {self.projection}")
capture = viewport_api.schedule_capture(SideCarWriter(image_path))
captured_aovs = await capture.wait_for_result()
if captured_aovs:
print(f'AOV "{captured_aovs[0]}" was written to "{image_path}"')
else:
print(f'No image was written to "{image_path}"')
```
## ByteCapture
A simple delegate to capture a single AOV and deliver it as CPU pixel data.
It can be used as is with a free-standing function, or subclassed to access additional information/meta-data.
By default it will capture a color AOV, but accepts an explicit AOV-name to capture instead.
```python
from omni.kit.widget.viewport.capture import ByteCapture
def on_capture_completed(buffer, buffer_size, width, height, format):
print(f'PixelData resolution: {width} x {height}')
print(f'PixelData format: {format}')
capture = viewport_api.schedule_capture(ByteCapture(on_capture_completed))
captured_aovs = await capture.wait_for_result()
if captured_aovs:
print(f'AOV "{captured_aovs[0]}" was written to "{image_path}"')
print(f'It had a camera view of {capture.view}')
else:
print(f'No image was written to "{image_path}"')
```
A sample subclass implementation to write additional data.
```python
from omni.kit.widget.viewport.capture import ByteCapture
SideCarData(ByteCapture):
def __init__(self, image_path, aov_name=''):
super().__init__(image_path, aov_name)
def on_capture_completed(self, buffer, buffer_size, width, height, format):
print(f'PixelData resolution: {width} x {height}')
print(f'PixelData format: {format}')
print(f'PixelData has a camera view of {self.view}')
capture = viewport_api.schedule_capture(SideCarData(image_path))
captured_aovs = await capture.wait_for_result()
if captured_aovs:
print(f'AOV "{captured_aovs[0]}" was written to "{image_path}"')
else:
print(f'No image was written to "{image_path}"')
```
| 3,284 |
Markdown
| 34.32258 | 113 | 0.714677 |
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/scripts/create_actions.py
|
import omni.usd
import omni.kit.actions.core
from pxr import Usd, UsdGeom, UsdLux, OmniAudioSchema
def get_action_name(name):
return name.lower().replace('-', '_').replace(' ', '_')
def get_geometry_standard_prim_list(usd_context=None):
if not usd_context:
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
if stage:
meters_per_unit = UsdGeom.GetStageMetersPerUnit(stage)
else:
meters_per_unit = 0.01
geom_base = 0.5 / meters_per_unit
geom_base_double = geom_base * 2
geom_base_half = geom_base / 2
all_shapes = sorted([
(
"Cube",
{
UsdGeom.Tokens.size: geom_base_double,
UsdGeom.Tokens.extent: [(-geom_base, -geom_base, -geom_base), (geom_base, geom_base, geom_base)],
},
),
(
"Sphere",
{
UsdGeom.Tokens.radius: geom_base,
UsdGeom.Tokens.extent: [(-geom_base, -geom_base, -geom_base), (geom_base, geom_base, geom_base)],
},
),
(
"Cylinder",
{
UsdGeom.Tokens.radius: geom_base,
UsdGeom.Tokens.height: geom_base_double,
UsdGeom.Tokens.extent: [(-geom_base, -geom_base, -geom_base), (geom_base, geom_base, geom_base)],
},
),
(
"Capsule",
{
UsdGeom.Tokens.radius: geom_base_half,
UsdGeom.Tokens.height: geom_base,
# Create extent with command dynamically since it's different in different up-axis.
},
),
(
"Cone",
{
UsdGeom.Tokens.radius: geom_base,
UsdGeom.Tokens.height: geom_base_double,
UsdGeom.Tokens.extent: [(-geom_base, -geom_base, -geom_base), (geom_base, geom_base, geom_base)],
},
),
])
shape_attrs = {}
for name, attrs in all_shapes:
shape_attrs[name] = attrs
return shape_attrs
def get_audio_prim_list():
return [
("Spatial Sound", "OmniSound", {}),
(
"Non-Spatial Sound",
"OmniSound",
{OmniAudioSchema.Tokens.auralMode: OmniAudioSchema.Tokens.nonSpatial}
),
("Listener", "OmniListener", {})
]
def get_light_prim_list(usd_context=None):
if not usd_context:
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
if stage:
meters_per_unit = UsdGeom.GetStageMetersPerUnit(stage)
else:
meters_per_unit = 0.01
geom_base = 0.5 / meters_per_unit
geom_base_double = geom_base * 2
# https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7
if hasattr(UsdLux.Tokens, 'inputsIntensity'):
return sorted([
("Distant Light", "DistantLight", {UsdLux.Tokens.inputsAngle: 1.0, UsdLux.Tokens.inputsIntensity: 3000}),
("Sphere Light", "SphereLight", {UsdLux.Tokens.inputsRadius: geom_base, UsdLux.Tokens.inputsIntensity: 30000}),
(
"Rect Light",
"RectLight",
{
UsdLux.Tokens.inputsWidth: geom_base_double,
UsdLux.Tokens.inputsHeight: geom_base_double,
UsdLux.Tokens.inputsIntensity: 15000,
},
),
("Disk Light", "DiskLight", {UsdLux.Tokens.inputsRadius: geom_base, UsdLux.Tokens.inputsIntensity: 60000}),
(
"Cylinder Light",
"CylinderLight",
{UsdLux.Tokens.inputsLength: geom_base_double, UsdLux.Tokens.inputsRadius: 5, UsdLux.Tokens.inputsIntensity: 30000},
),
(
"Dome Light",
"DomeLight",
{UsdLux.Tokens.inputsIntensity: 1000, UsdLux.Tokens.inputsTextureFormat: UsdLux.Tokens.latlong},
),
])
return sorted([
("Distant Light", "DistantLight", {UsdLux.Tokens.angle: 1.0, UsdLux.Tokens.intensity: 3000}),
("Sphere Light", "SphereLight", {UsdLux.Tokens.radius: geom_base, UsdLux.Tokens.intensity: 30000}),
(
"Rect Light",
"RectLight",
{
UsdLux.Tokens.width: geom_base_double,
UsdLux.Tokens.height: geom_base_double,
UsdLux.Tokens.intensity: 15000,
},
),
("Disk Light", "DiskLight", {UsdLux.Tokens.radius: geom_base, UsdLux.Tokens.intensity: 60000}),
(
"Cylinder Light",
"CylinderLight",
{UsdLux.Tokens.length: geom_base_double, UsdLux.Tokens.radius: 5, UsdLux.Tokens.intensity: 30000},
),
(
"Dome Light",
"DomeLight",
{UsdLux.Tokens.intensity: 1000, UsdLux.Tokens.textureFormat: UsdLux.Tokens.latlong},
),
])
def register_actions(extension_id, cls, get_self_fn):
actions_tag = "Create Menu Actions"
# actions
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
"create_prim",
cls.on_create_prim,
display_name="Create->Create Prim",
description="Create Prim",
tag=actions_tag
)
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
"create_prim_camera",
lambda: cls.on_create_prim("Camera", {}),
display_name="Create->Create Camera Prim",
description="Create Camera Prim",
tag=actions_tag
)
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
"create_prim_scope",
lambda: cls.on_create_prim("Scope", {}),
display_name="Create->Create Scope",
description="Create Scope",
tag=actions_tag
)
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
"create_prim_xform",
lambda: cls.on_create_prim("Xform", {}),
display_name="Create->Create Xform",
description="Create Xform",
tag=actions_tag
)
def on_create_shape(shape_name):
shape_attrs = get_geometry_standard_prim_list()
cls.on_create_prim(shape_name, shape_attrs[shape_name])
for prim in get_geometry_standard_prim_list().keys():
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
f"create_prim_{prim.lower()}",
lambda p=prim: on_create_shape(p),
display_name=f"Create->Create Prim {prim}",
description=f"Create Prim {prim}",
tag=actions_tag
)
for name, prim, attrs in get_light_prim_list():
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
f"create_prim_{get_action_name(name)}",
lambda p=prim, a=attrs: cls.on_create_light(p, a),
display_name=f"Create->Create Prim {name}",
description=f"Create Prim {name}",
tag=actions_tag
)
for name, prim, attrs in get_audio_prim_list():
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
f"create_prim_{get_action_name(name)}",
lambda p=prim, a=attrs: cls.on_create_prim(p, a),
display_name=f"Create->Create Prim {name}",
description=f"Create Prim {name}",
tag=actions_tag
)
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
"high_quality_option_toggle",
get_self_fn()._high_quality_option_toggle,
display_name="Create->High Quality Option Toggle",
description="Create High Quality Option Toggle",
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)
| 8,014 |
Python
| 32.67647 | 132 | 0.564387 |
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/scripts/__init__.py
|
from .create import *
| 22 |
Python
| 10.499995 | 21 | 0.727273 |
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/scripts/create.py
|
import os
import functools
import carb.input
import omni.ext
import omni.kit.ui
import omni.kit.menu.utils
from functools import partial
from omni.kit.menu.utils import MenuItemDescription, MenuItemOrder
from .create_actions import register_actions, deregister_actions, get_action_name, get_geometry_standard_prim_list, get_audio_prim_list, get_light_prim_list
_extension_instance = None
_extension_path = None
PERSISTENT_SETTINGS_PREFIX = "/persistent"
class CreateMenuExtension(omni.ext.IExt):
def __init__(self):
super().__init__()
omni.kit.menu.utils.set_default_menu_proirity("Create", -8)
def on_startup(self, ext_id):
global _extension_instance
_extension_instance = self
global _extension_path
_extension_path = omni.kit.app.get_app_interface().get_extension_manager().get_extension_path(ext_id)
self._settings = carb.settings.get_settings()
self._settings.set_default_bool(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality", True)
self._create_menu_list = None
self._build_create_menu()
self._ext_name = omni.ext.get_extension_name(ext_id)
register_actions(self._ext_name, CreateMenuExtension, lambda: _extension_instance)
def on_shutdown(self):
global _extension_instance
deregister_actions(self._ext_name)
_extension_instance = None
omni.kit.menu.utils.remove_menu_items(self._create_menu_list, "Create")
def _rebuild_menus(self):
omni.kit.menu.utils.remove_menu_items(self._create_menu_list, "Create")
self._build_create_menu()
def _high_quality_option_toggle(self):
enabled = self._settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality")
self._settings.set(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality", not enabled)
def _build_create_menu(self):
def is_create_type_enabled(type: str):
settings = carb.settings.get_settings()
if type == "Shape":
if settings.get("/app/primCreation/hideShapes") == True or \
settings.get("/app/primCreation/enableMenuShape") == False:
return False
return True
enabled = settings.get(f"/app/primCreation/enableMenu{type}")
if enabled == True or enabled == False:
return enabled
return True
# setup menus
self._create_menu_list = []
# Shapes
if is_create_type_enabled("Shape"):
sub_menu = []
for prim in get_geometry_standard_prim_list().keys():
sub_menu.append(
MenuItemDescription(name=prim, onclick_action=("omni.kit.menu.create", f"create_prim_{prim.lower()}"))
)
def on_high_quality_option_select():
enabled = self._settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality")
self._settings.set(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality", not enabled)
def on_high_quality_option_checked():
enabled = self._settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality")
return enabled
sub_menu.append(MenuItemDescription())
sub_menu.append(
MenuItemDescription(
name="High Quality",
onclick_action=("omni.kit.menu.create", "high_quality_option_toggle"),
ticked_fn=lambda: on_high_quality_option_checked()
)
)
self._create_menu_list.append(
MenuItemDescription(name="Shape", glyph="menu_prim.svg", appear_after=["Mesh", MenuItemOrder.FIRST], sub_menu=sub_menu)
)
# Lights
if is_create_type_enabled("Light"):
sub_menu = []
for name, prim, attrs in get_light_prim_list():
sub_menu.append(
MenuItemDescription(name=name, onclick_action=("omni.kit.menu.create", f"create_prim_{get_action_name(name)}")
)
)
if is_create_type_enabled("Shape"):
appear_after="Shape"
else:
appear_after="Mesh"
self._create_menu_list.append(
MenuItemDescription(name="Light", glyph="menu_light.svg", appear_after=appear_after, sub_menu=sub_menu)
)
# Audio
if is_create_type_enabled("Audio"):
sub_menu = []
for name, prim, attrs in get_audio_prim_list():
sub_menu.append(
MenuItemDescription(
name=name, onclick_action=("omni.kit.menu.create", f"create_prim_{get_action_name(name)}")
)
)
self._create_menu_list.append(
MenuItemDescription(name="Audio", glyph="menu_audio.svg", appear_after="Light", sub_menu=sub_menu)
)
# Camera
if is_create_type_enabled("Camera"):
self._create_menu_list.append(
MenuItemDescription(
name="Camera",
glyph="menu_camera.svg",
appear_after="Audio",
onclick_action=("omni.kit.menu.create", "create_prim_camera"),
)
)
# Scope
if is_create_type_enabled("Scope"):
self._create_menu_list.append(
MenuItemDescription(
name="Scope",
glyph="menu_scope.svg",
appear_after="Camera",
onclick_action=("omni.kit.menu.create", "create_prim_scope"),
)
)
# Xform
if is_create_type_enabled("Xform"):
self._create_menu_list.append(
MenuItemDescription(
name="Xform",
glyph="menu_xform.svg",
appear_after="Scope",
onclick_action=("omni.kit.menu.create", "create_prim_xform"),
)
)
if self._create_menu_list:
omni.kit.menu.utils.add_menu_items(self._create_menu_list, "Create", -8)
def on_create_prim(prim_type, attributes, use_settings: bool = False):
usd_context = omni.usd.get_context()
with omni.kit.usd.layers.active_authoring_layer_context(usd_context):
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type=prim_type, attributes=attributes)
def on_create_light(light_type, attributes):
usd_context = omni.usd.get_context()
with omni.kit.usd.layers.active_authoring_layer_context(usd_context):
omni.kit.commands.execute("CreatePrim", prim_type=light_type, attributes=attributes)
def on_create_prims():
usd_context = omni.usd.get_context()
with omni.kit.usd.layers.active_authoring_layer_context(usd_context):
omni.kit.commands.execute("CreatePrims", prim_types=["Cone", "Cylinder", "Cone"])
def get_extension_path(sub_directory):
global _extension_path
path = _extension_path
if sub_directory:
path = os.path.normpath(os.path.join(path, sub_directory))
return path
def rebuild_menus():
if _extension_instance:
_extension_instance._rebuild_menus()
| 7,415 |
Python
| 37.827225 | 156 | 0.582333 |
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/tests/test_func_create_prims.py
|
import asyncio
import os
import carb
import omni.usd
import omni.ui as ui
from omni.kit import ui_test
from omni.kit.menu.utils import MenuItemDescription, MenuLayout
from omni.kit.test_suite.helpers import get_test_data_path, wait_stage_loading, get_prims, select_prims, wait_for_window
from omni.kit.material.library.test_helper import MaterialLibraryTestHelper
from pxr import Sdf, UsdShade
PERSISTENT_SETTINGS_PREFIX = "/persistent"
async def create_test_func_create_camera(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Camera")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Camera'])
# Test creation with typed-defaults
settings = carb.settings.get_settings()
try:
focal_len_key = '/persistent/app/primCreation/typedDefaults/camera/focalLength'
settings.set(focal_len_key, 48)
await ui_test.menu_click("Create/Camera")
cam_prim = omni.usd.get_context().get_stage().GetPrimAtPath('/Camera_01')
tester.assertIsNotNone(cam_prim)
tester.assertEqual(cam_prim.GetAttribute('focalLength').Get(), 48)
finally:
# Delete the change now for any other tests
settings.destroy_item(focal_len_key)
async def create_test_func_create_scope(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Scope")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Scope'])
async def create_test_func_create_xform(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Xform")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Xform'])
async def create_test_func_create_shape_capsule(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Shape/Capsule")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Capsule'])
async def create_test_func_create_shape_cone(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Shape/Cone")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Cone'])
async def create_test_func_create_shape_cube(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Shape/Cube")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Cube'])
async def create_test_func_create_shape_cylinder(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Shape/Cylinder")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Cylinder'])
async def create_test_func_create_shape_sphere(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Shape/Sphere")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Sphere'])
async def create_test_func_create_shape_high_quality(tester, menu_item: MenuItemDescription):
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality", False)
# use menu
await ui_test.menu_click("Create/Shape/High Quality")
# verify
tester.assertTrue(carb.settings.get_settings().get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality"))
async def create_test_func_create_light_cylinder_light(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Light/Cylinder Light")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/CylinderLight'])
async def create_test_func_create_light_disk_light(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Light/Disk Light")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/DiskLight'])
async def create_test_func_create_light_distant_light(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Light/Distant Light")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/DistantLight'])
async def create_test_func_create_light_dome_light(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Light/Dome Light")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/DomeLight'])
async def create_test_func_create_light_rect_light(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Light/Rect Light")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/RectLight'])
async def create_test_func_create_light_sphere_light(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Light/Sphere Light")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/SphereLight'])
async def create_test_func_create_audio_spatial_sound(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Audio/Spatial Sound")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/OmniSound'])
async def create_test_func_create_audio_non_spatial_sound(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Audio/Non-Spatial Sound")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/OmniSound'])
async def create_test_func_create_audio_listener(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Audio/Listener")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/OmniListener'])
async def create_test_func_create_mesh_cone(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Cone")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Cone'])
async def create_test_func_create_mesh_cube(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Cube")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Cube'])
async def create_test_func_create_mesh_cylinder(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Cylinder")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Cylinder'])
async def create_test_func_create_mesh_disk(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Disk")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Disk'])
async def create_test_func_create_mesh_plane(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Plane")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Plane'])
async def create_test_func_create_mesh_sphere(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Sphere")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Sphere'])
async def create_test_func_create_mesh_torus(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Torus")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Torus'])
async def create_test_func_create_mesh_settings(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Settings")
await wait_for_window("Mesh Generation Settings")
ui_test.find("Mesh Generation Settings").widget.visible = False
async def create_test_func_create_material(tester, material_name: str):
mdl_name = material_name.split('/')[-1].replace(" ", "_")
stage = omni.usd.get_context().get_stage()
if mdl_name == "Add_MDL_File":
# click on menu item
await ui_test.menu_click(material_name)
await ui_test.human_delay()
# use add material dialog
async with MaterialLibraryTestHelper() as material_test_helper:
await material_test_helper.handle_add_material_dialog(get_test_data_path(__name__, "mdl/TESTEXPORT.mdl"), "TESTEXPORT.mdl")
# wait for material to load & UI to refresh
await wait_stage_loading()
# verify
shader = UsdShade.Shader(stage.GetPrimAtPath("/Looks/Material/Shader"))
identifier = shader.GetSourceAssetSubIdentifier("mdl")
tester.assertTrue(identifier == "Material")
return
if mdl_name == "USD_Preview_Surface":
await ui_test.menu_click(material_name)
tester.assertTrue(tester.get_stage_prims() == ['/Looks', '/Looks/PreviewSurface', '/Looks/PreviewSurface/Shader'])
elif mdl_name == "USD_Preview_Surface_Texture":
await ui_test.menu_click(material_name)
tester.assertTrue(tester.get_stage_prims() == ['/Looks', '/Looks/PreviewSurfaceTexture', '/Looks/PreviewSurfaceTexture/PreviewSurfaceTexture', '/Looks/PreviewSurfaceTexture/st', '/Looks/PreviewSurfaceTexture/diffuseColorTex', '/Looks/PreviewSurfaceTexture/metallicTex', '/Looks/PreviewSurfaceTexture/roughnessTex', '/Looks/PreviewSurfaceTexture/normalTex'])
else:
# create sphere, select & create material
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
await select_prims(["/Sphere"])
await ui_test.menu_click(material_name)
# verify material is created
tester.assertTrue(tester.get_stage_prims() == ["/Sphere", "/Looks", f"/Looks/{mdl_name}", f"/Looks/{mdl_name}/Shader"])
prim = stage.GetPrimAtPath(f"/Looks/{mdl_name}/Shader")
asset_path = prim.GetAttribute("info:mdl:sourceAsset").Get()
tester.assertFalse(os.path.isabs(asset_path.path))
tester.assertTrue(os.path.isabs(asset_path.resolvedPath))
# verify /Sphere is bound to material
prim = stage.GetPrimAtPath("/Sphere")
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
tester.assertEqual(bound_material.GetPath().pathString, f"/Looks/{mdl_name}")
| 9,882 |
Python
| 34.046099 | 365 | 0.699757 |
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/tests/__init__.py
|
from .create_tests import *
from .test_enable_menu import *
| 60 |
Python
| 19.333327 | 31 | 0.75 |
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/tests/create_tests.py
|
import sys
import re
import asyncio
import unittest
import carb
import omni.kit.test
from .test_func_create_prims import *
class TestMenuCreate(omni.kit.test.AsyncTestCase):
async def setUp(self):
pass
async def tearDown(self):
pass
async def test_create_menus(self):
import omni.kit.material.library
# 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()
material_list = []
menus = omni.kit.menu.utils.get_merged_menus()
prefix = "create_test"
to_test = []
this_module = sys.modules[__name__]
for key in menus.keys():
# create menu only
if key.startswith("Create"):
for item in menus[key]['items']:
if item.name != "" and item.has_action():
key_name = re.sub('\W|^(?=\d)','_', key.lower())
func_name = re.sub('\W|^(?=\d)','_', item.name.replace("${kit}/", "").lower())
while key_name and key_name[-1] == "_":
key_name = key_name[:-1]
while func_name and func_name[-1] == "_":
func_name = func_name[:-1]
test_fn = f"{prefix}_func_{key_name}_{func_name}"
try:
to_call = getattr(this_module, test_fn)
to_test.append((to_call, test_fn, item))
except AttributeError:
if test_fn.startswith("create_test_func_create_material_"):
material_list.append(f"{key.replace('_', '/')}/{item.name}")
else:
carb.log_error(f"test function \"{test_fn}\" not found")
if item.original_menu_item and item.original_menu_item.hotkey:
test_fn = f"{prefix}_hotkey_func_{key_name}_{func_name}"
try:
to_call = getattr(this_module, test_fn)
to_test.append((to_call, test_fn, item.original_menu_item))
except AttributeError:
carb.log_error(f"test function \"{test_fn}\" not found")
for to_call, test_fn, menu_item in to_test:
await omni.usd.get_context().new_stage_async()
omni.kit.menu.utils.refresh_menu_items("Create")
await ui_test.human_delay()
print(f"Running test {test_fn}")
try:
await to_call(self, menu_item)
except Exception as exc:
carb.log_error(f"error {test_fn} failed - {exc}")
import traceback
traceback.print_exc(file=sys.stdout)
for material_name in material_list:
await omni.usd.get_context().new_stage_async()
omni.kit.menu.utils.refresh_menu_items("Create")
await ui_test.human_delay()
print(f"Running test create_test_func_create_material {material_name}")
try:
await create_test_func_create_material(self, material_name)
except Exception as exc:
carb.log_error(f"error create_test_func_create_material failed - {exc}")
import traceback
traceback.print_exc(file=sys.stdout)
def get_stage_prims(self):
stage = omni.usd.get_context().get_stage()
return [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)]
| 3,757 |
Python
| 42.697674 | 111 | 0.51424 |
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/tests/test_enable_menu.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 carb
import omni.kit.app
import omni.kit.test
import omni.usd
import omni.ui as ui
from omni.ui.tests.test_base import OmniUiTest
from omni.kit import ui_test
from omni.kit.test_suite.helpers import wait_stage_loading, arrange_windows
class TestEnableCreateMenu(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
await omni.usd.get_context().new_stage_async()
await wait_stage_loading()
# Test(s)
async def test_enable_create_menu(self):
settings = carb.settings.get_settings()
def reset_prim_creation():
settings.set("/app/primCreation/hideShapes", False)
settings.set("/app/primCreation/enableMenuShape", True)
settings.set("/app/primCreation/enableMenuLight", True)
settings.set("/app/primCreation/enableMenuAudio", True)
settings.set("/app/primCreation/enableMenuCamera", True)
settings.set("/app/primCreation/enableMenuScope", True)
settings.set("/app/primCreation/enableMenuXform", True)
def verify_menu(mesh:bool, shape:bool, light:bool, audio:bool, camera:bool, scope:bool, xform:bool):
menu_widget = ui_test.get_menubar()
menu_widgets = []
for w in menu_widget.find_all("**/"):
if isinstance(w.widget, (ui.Menu, ui.MenuItem)) and w.widget.text.strip() != "placeholder":
menu_widgets.append(w.widget.text)
self.assertEqual("Mesh" in menu_widgets, mesh)
self.assertEqual("Shape" in menu_widgets, shape)
self.assertEqual("Light" in menu_widgets, light)
self.assertEqual("Audio" in menu_widgets, audio)
self.assertEqual("Camera" in menu_widgets, camera)
self.assertEqual("Scope" in menu_widgets, scope)
self.assertEqual("Xform" in menu_widgets, xform)
async def test_menu(mesh:bool, shape:bool, light:bool, audio:bool, camera:bool, scope:bool, xform:bool):
omni.kit.menu.create.rebuild_menus()
verify_menu(mesh, shape, light, audio, camera, scope, xform)
try:
# verify default
reset_prim_creation()
await test_menu(mesh=True, shape=True, light=True, audio=True, camera=True, scope=True, xform=True)
# verify hide shapes
reset_prim_creation()
settings.set("/app/primCreation/hideShapes", True)
await test_menu(mesh=True, shape=False, light=True, audio=True, camera=True, scope=True, xform=True)
reset_prim_creation()
settings.set("/app/primCreation/enableMenuShape", False)
await test_menu(mesh=True, shape=False, light=True, audio=True, camera=True, scope=True, xform=True)
# verify hide light
reset_prim_creation()
settings.set("/app/primCreation/enableMenuLight", False)
await test_menu(mesh=True, shape=True, light=False, audio=True, camera=True, scope=True, xform=True)
# verify hide audio
reset_prim_creation()
settings.set("/app/primCreation/enableMenuAudio", False)
await test_menu(mesh=True, shape=True, light=True, audio=False, camera=True, scope=True, xform=True)
# verify hide camera
reset_prim_creation()
settings.set("/app/primCreation/enableMenuCamera", False)
await test_menu(mesh=True, shape=True, light=True, audio=True, camera=False, scope=True, xform=True)
# verify hide scope
reset_prim_creation()
settings.set("/app/primCreation/enableMenuScope", False)
await test_menu(mesh=True, shape=True, light=True, audio=True, camera=True, scope=False, xform=True)
# verify hide xform
reset_prim_creation()
settings.set("/app/primCreation/enableMenuXform", False)
await test_menu(mesh=True, shape=True, light=True, audio=True, camera=True, scope=True, xform=False)
finally:
reset_prim_creation()
| 4,545 |
Python
| 45.865979 | 112 | 0.649725 |
omniverse-code/kit/exts/omni.kit.window.file_exporter/scripts/demo_file_exporter.py
|
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
import asyncio
import omni.ui as ui
from typing import List
from omni.kit.window.file_exporter import get_file_exporter, ExportOptionsDelegate
# BEGIN-DOC-export_options
class MyExportOptionsDelegate(ExportOptionsDelegate):
def __init__(self):
super().__init__(build_fn=self._build_ui_impl, destroy_fn=self._destroy_impl)
self._widget = None
def _build_ui_impl(self):
self._widget = ui.Frame()
with self._widget:
with ui.VStack(style={"background_color": 0xFF23211F}):
ui.Label("Checkpoint Description", alignment=ui.Alignment.CENTER)
ui.Separator(height=5)
model = ui.StringField(multiline=True, height=80).model
model.set_value("This is my new checkpoint.")
def _destroy_impl(self, _):
if self._widget:
self._widget.destroy()
self._widget = None
# END-DOC-export_options
# BEGIN-DOC-tagging_options
class MyTaggingOptionsDelegate(ExportOptionsDelegate):
def __init__(self):
super().__init__(
build_fn=self._build_ui_impl,
filename_changed_fn=self._filename_changed_impl,
selection_changed_fn=self._selection_changed_impl,
destroy_fn=self._destroy_impl
)
self._widget = None
def _build_ui_impl(self, file_type: str=''):
self._widget = ui.Frame()
with self._widget:
with ui.VStack():
ui.Button(f"Tags for {file_type or 'unknown'} type", height=24)
def _filename_changed_impl(self, filename: str):
if filename:
_, ext = os.path.splitext(filename)
self._build_ui_impl(file_type=ext)
def _selection_changed_impl(self, selections: List[str]):
if len(selections) == 1:
_, ext = os.path.splitext(selections[0])
self._build_ui_impl(file_type=ext)
def _destroy_impl(self, _):
if self._widget:
self._widget.destroy()
self._widget = None
# END-DOC-tagging_options
class DemoFileExporterDialog:
"""
Example that demonstrates how to invoke the file exporter dialog.
"""
def __init__(self):
self._app_window: ui.Window = None
self._export_options = ExportOptionsDelegate = None
self._tag_options = ExportOptionsDelegate = None
self.build_ui()
def build_ui(self):
""" """
window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR
self._app_window = ui.Window("File Exporter", width=1000, height=500, flags=window_flags)
with self._app_window.frame:
with ui.VStack(spacing=10):
with ui.HStack(height=30):
ui.Spacer()
button = ui.RadioButton(text="Export File", width=120)
button.set_clicked_fn(self._show_dialog)
ui.Spacer()
asyncio.ensure_future(self._dock_window("File Exporter", ui.DockPosition.TOP))
def _show_dialog(self):
# BEGIN-DOC-get_instance
# Get the singleton extension object, but as weakref to guard against the extension being removed.
file_exporter = get_file_exporter()
if not file_exporter:
return
# END-DOC-get_instance
# BEGIN-DOC-show_window
file_exporter.show_window(
title="Export As ...",
export_button_label="Save",
export_handler=self.export_handler,
filename_url="omniverse://ov-rc/NVIDIA/Samples/Marbles/foo",
show_only_folders=True,
enable_filename_input=False,
)
# END-DOC-show_window
# BEGIN-DOC-add_tagging_options
self._tagging_options = MyTaggingOptionsDelegate()
file_exporter.add_export_options_frame("Tagging Options", self._tagging_options)
# END-DOC-add_tagging_options
# BEGIN-DOC-add_export_options
self._export_options = MyExportOptionsDelegate()
file_exporter.add_export_options_frame("Export Options", self._export_options)
# END-DOC-add_export_options
def _hide_dialog(self):
# Get the Content extension object. Same as: omni.kit.window.file_exporter.get_extension()
# Keep as weakref to guard against the extension being removed at any time. If it is removed,
# then invoke appropriate handler; in this case the destroy method.
file_exporter = get_file_exporter()
if file_exporter:
file_exporter.hide()
# BEGIN-DOC-export_handler
def export_handler(self, filename: str, dirname: str, extension: str = "", selections: List[str] = []):
# NOTE: Get user inputs from self._export_options, if needed.
print(f"> Export As '{filename}{extension}' to '{dirname}' with additional selections '{selections}'")
# END-DOC-export_handler
async def _dock_window(self, window_title: str, position: ui.DockPosition, ratio: float = 1.0):
frames = 3
while frames > 0:
if ui.Workspace.get_window(window_title):
break
frames = frames - 1
await omni.kit.app.get_app().next_update_async()
window = ui.Workspace.get_window(window_title)
dockspace = ui.Workspace.get_window("DockSpace")
if window and dockspace:
window.dock_in(dockspace, position, ratio=ratio)
window.dock_tab_bar_visible = False
def destroy(self):
if self._app_window:
self._app_window.destroy()
self._app_window = None
if __name__ == "__main__":
view = DemoFileExporterDialog()
| 6,054 |
Python
| 36.376543 | 110 | 0.623059 |
omniverse-code/kit/exts/omni.kit.window.file_exporter/config/extension.toml
|
[package]
title = "File Exporter"
version = "1.0.10"
category = "core"
feature = true
description = "A dialog for exporting files"
authors = ["NVIDIA"]
slackids = ["UQY4RMR3N"]
repository = ""
keywords = ["kit", "ui"]
readme = "docs/README.md"
changelog = "docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[dependencies]
"omni.ui" = {}
"omni.usd" = {}
"omni.kit.window.filepicker" = {}
[[python.module]]
name = "omni.kit.window.file_exporter"
[settings]
exts."omni.kit.window.file_exporter".appSettings = "/persistent/app/file_exporter"
[[python.scriptFolder]]
path = "scripts"
[[test]]
dependencies = [
"omni.kit.renderer.core"
]
[documentation]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
| 747 |
TOML
| 17.7 | 82 | 0.672021 |
omniverse-code/kit/exts/omni.kit.window.file_exporter/omni/kit/window/file_exporter/extension.py
|
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
import asyncio
import omni.ext
import omni.kit.app
import carb.settings
import carb.windowing
from typing import List, Tuple, Callable, Dict
from functools import partial
from carb import log_warn, events
from omni.kit.window.filepicker import FilePickerDialog, UI_READY_EVENT
from omni.kit.widget.filebrowser import FileBrowserItem
from . import ExportOptionsDelegate
g_singleton = None
WINDOW_NAME = "File Exporter"
# BEGIN-DOC-file_postfix_options
DEFAULT_FILE_POSTFIX_OPTIONS = [
None,
"anim",
"cache",
"curveanim",
"geo",
"material",
"project",
"seq",
"skel",
"skelanim",
]
# END-DOC-file_postfix_options
# BEGIN-DOC-file_extension_types
DEFAULT_FILE_EXTENSION_TYPES = [
("*.usd", "Can be Binary or Ascii"),
("*.usda", "Human-readable text format"),
("*.usdc", "Binary format"),
]
# END-DOC-file_extension_types
def on_filter_item(dialog: FilePickerDialog, show_only_folders: True, item: FileBrowserItem) -> bool:
if item and not item.is_folder:
if show_only_folders:
return False
else:
return file_filter_handler(item.path or '', dialog.get_file_postfix(), dialog.get_file_extension())
return True
def on_export(
export_fn: Callable[[str, str, str, List[str]], None],
dialog: FilePickerDialog,
filename: str,
dirname: str,
should_validate: bool = False,
):
# OM-64312: should only perform validation when specified, default to not validate
if should_validate:
# OM-58150: should not allow saving with a empty filename
if not _filename_validation_handler(filename):
return
file_postfix = dialog.get_file_postfix()
file_extension = dialog.get_file_extension()
_save_default_settings({'directory': dirname})
selections = dialog.get_current_selections() or []
dialog.hide()
def normalize_filename_parts(filename, file_postfix, file_extension) -> Tuple[str, str]:
splits = filename.split('.')
keep = len(splits) - 1
# leaving the dynamic writable usd file exts strip logic here, in case writable exts are loaded at runtime
try:
import omni.usd
if keep > 0 and splits[keep] in omni.usd.writable_usd_file_exts():
keep -= 1
except Exception:
pass
# OM-84454: strip out file extensions from filename if the current filename ends with any of the file extensions
# available in the current instance of dialog
available_options = [item.lstrip("*.") for item, _ in dialog.get_file_extension_options()]
if keep > 0 and splits[keep] in available_options:
keep -= 1
# strip out postfix from filename
if keep > 0 and splits[keep] in dialog.get_file_postfix_options():
keep -= 1
basename = '.'.join(splits[:keep+1]) if keep >= 0 else ""
extension = ""
if file_postfix:
extension += f".{file_postfix}"
if file_extension:
extension += f"{file_extension.strip('*')}"
return basename, extension
if export_fn:
basename, extension = normalize_filename_parts(filename, file_postfix, file_extension)
export_fn(basename, dirname, extension=extension, selections=selections)
def file_filter_handler(filename: str, filter_postfix: str, filter_ext: str) -> bool:
if not filename:
return True
if not filter_ext:
return True
filter_ext = filter_ext.replace('*', '')
# Show only files whose names end with: *<postfix>.<ext>
if not filter_ext:
filename = os.path.splitext(filename)[0]
elif filename.endswith(filter_ext):
filename = filename[:-len(filter_ext)].strip('.')
else:
return False
if not filter_postfix or filename.endswith(filter_postfix):
return True
return False
def _save_default_settings(default_settings: Dict):
settings = carb.settings.get_settings()
default_settings_path = settings.get_as_string("/exts/omni.kit.window.file_exporter/appSettings")
settings.set_string(f"{default_settings_path}/directory", default_settings['directory'] or "")
def _filename_validation_handler(filename):
"""Validates the filename being exported. Currently only checking if it's empty."""
if not filename:
msg = "Filename is empty! Please specify the filename first."
try:
import omni.kit.notification_manager as nm
nm.post_notification(msg, status=nm.NotificationStatus.WARNING)
except ModuleNotFoundError:
import carb
carb.log_warn(msg)
return False
return True
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class FileExporterExtension(omni.ext.IExt):
"""A Standardized file export dialog."""
def __init__(self):
super().__init__()
self._dialog = None
self._title = None
self._ui_ready = False
self._ui_ready_event_sub = None
def on_startup(self, ext_id):
# Save away this instance as singleton for the editor window
global g_singleton
g_singleton = self
# Listen for filepicker events
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
self._ui_ready_event_sub = event_stream.create_subscription_to_pop_by_type(UI_READY_EVENT, self._on_ui_ready)
self._destroy_dialog_task = None
def show_window(
self,
title: str = None,
width: int = 1080,
height: int = 450,
show_only_collections: List[str] = None,
show_only_folders: bool = False,
file_postfix_options: List[str] = None,
file_extension_types: List[Tuple[str, str]] = None,
export_button_label: str = "Export",
export_handler: Callable[[str, str, str, List[str]], None] = None,
filename_url: str = None,
file_postfix: str = None,
file_extension: str = None,
should_validate: bool = False,
enable_filename_input: bool = True,
focus_filename_input: bool = True, # OM-91056: file exporter should focus filename input field
):
"""
Displays the export dialog with the specified settings.
Keyword Args:
title (str): The name of the dialog
width (int): Width of the window (Default=1250)
height (int): Height of the window (Default=450)
show_only_collections (List[str]): Which of these collections, ["bookmarks", "omniverse", "my-computer"] to display.
show_only_folders (bool): Show only folders in the list view.
file_postfix_options (List[str]): A list of filename postfix options. Nvidia defaults.
file_extension_types (List[Tuple[str, str]]): A list of filename extension options. Each list
element is a (extension name, description) pair, e.g. (".usdc", "Binary format"). Nvidia defaults.
export_button_label (str): Label for the export button (Default="Export")
export_handler (Callable): The callback to handle the export. Function signature is
export_handler(filename: str, dirname: str, extension: str, selections: List[str]) -> None
filename_url (str): Url of the target file, excluding filename extension.
file_postfix (str): Sets selected postfix to this value if specified.
file_extension (str): Sets selected extension to this value if specified.
should_validate (bool): Whether filename validation should be performed.
enable_filename_input (bool): Whether filename field input is enabled, default to True.
"""
if self._dialog:
self.destroy_dialog()
# Load saved settings as defaults
default_settings = self._load_default_settings()
basename = ""
directory = default_settings.get('directory')
if filename_url:
dirname, filename = os.path.split(filename_url)
basename = os.path.basename(filename)
# override directory name only if explicitly given from filename_url
if dirname:
directory = dirname
file_postfix_options = file_postfix_options or DEFAULT_FILE_POSTFIX_OPTIONS
file_extension_types = file_extension_types or DEFAULT_FILE_EXTENSION_TYPES
self._title = title or WINDOW_NAME
self._dialog = FilePickerDialog(
self._title,
width=width,
height=height,
splitter_offset=260,
enable_file_bar=True,
enable_filename_input=enable_filename_input,
enable_checkpoints=False,
show_detail_view=True,
show_only_collections=show_only_collections or [],
file_postfix_options=file_postfix_options,
file_extension_options=file_extension_types,
filename_changed_handler=partial(self._on_filename_changed, show_only_folders=show_only_folders),
apply_button_label=export_button_label,
current_directory=directory,
current_filename=basename,
current_file_postfix=file_postfix,
current_file_extension=file_extension,
focus_filename_input=focus_filename_input,
)
self._dialog.set_item_filter_fn(partial(on_filter_item, self._dialog, show_only_folders))
self._dialog.set_click_apply_handler(
partial(on_export, export_handler, self._dialog, should_validate=should_validate)
)
self._dialog.set_visibility_changed_listener(self._visibility_changed_fn)
# don't disable apply button if we are showing folders only
self._dialog._widget.file_bar.enable_apply_button(enable=show_only_folders)
self._dialog.show()
def _visibility_changed_fn(self, visible: bool):
async def destroy_dialog_async():
# wait one frame, this is due to the one frame defer
# in Window::_moveToMainOSWindow()
try:
await omni.kit.app.get_app().next_update_async()
if self._dialog:
self._dialog.destroy()
self._dialog = None
finally:
self._destroy_dialog_task = None
if not visible:
# Destroy the window, since we are creating new window in show_window
if not self._destroy_dialog_task or self._destroy_dialog_task.done():
self._destroy_dialog_task = asyncio.ensure_future(
destroy_dialog_async()
)
def _load_default_settings(self) -> Dict:
settings = carb.settings.get_settings()
default_settings_path = settings.get_as_string("/exts/omni.kit.window.file_exporter/appSettings")
default_settings = {}
default_settings['directory'] = settings.get_as_string(f"{default_settings_path}/directory")
return default_settings
def _on_filename_changed(self, filename, show_only_folders=False):
# OM-78341: Disable apply button if no file is selected, if we are not showing only folders
if self._dialog and self._dialog._widget and not show_only_folders:
self._dialog._widget.file_bar.enable_apply_button(enable=bool(filename))
def _on_ui_ready(self, event: events.IEvent):
try:
payload = event.payload.get_dict()
title = payload.get('title', None)
except Exception:
return
if event.type == UI_READY_EVENT and title == self._title:
self._ui_ready = True
@property
def is_ui_ready(self) -> bool:
return self._ui_ready
@property
def is_window_visible(self) -> bool:
if self._dialog and self._dialog._window:
return self._dialog._window.visible
return False
def hide_window(self):
"""Hides and destroys the dialog window."""
self.destroy_dialog()
def add_export_options_frame(self, name: str, delegate: ExportOptionsDelegate):
"""
Adds a set of export options to the dialog. Should be called after show_window.
Args:
name (str): Title of the options box.
delegate (ExportOptionsDelegate): Subclasses specified delegate and overrides the
_build_ui_impl method to provide a custom widget for getting user input.
"""
if self._dialog:
self._dialog.add_detail_frame_from_controller(name, delegate)
def click_apply(self, filename_url: str = None, postfix: str = None, extension: str = None):
"""Helper function to progammatically execute the apply callback. Useful in unittests"""
if self._dialog:
if filename_url:
dirname, filename = os.path.split(filename_url)
self._dialog.set_current_directory(dirname)
self._dialog.set_filename(filename)
if postfix:
self._dialog.set_file_postfix(postfix)
if extension:
self._dialog.self_file_extension(extension)
self._dialog._widget._file_bar._on_apply()
def click_cancel(self, cancel_handler: Callable[[str, str], None] = None):
"""Helper function to progammatically execute the cancel callback. Useful in unittests"""
if cancel_handler:
self._dialog._widget._file_bar._click_cancel_handler = cancel_handler
self._dialog._widget._file_bar._on_cancel()
async def select_items_async(self, url: str, filenames: List[str] = []) -> List[FileBrowserItem]:
"""Helper function to programatically select multiple items in filepicker. Useful in unittests."""
if self._dialog:
return await self._dialog._widget.api.select_items_async(url, filenames=filenames)
return []
def detach_from_main_window(self):
"""Detach the current file importer dialog from main window."""
if self._dialog:
self._dialog._window.move_to_new_os_window()
def destroy_dialog(self):
# handles the case for detached window
if self._dialog and self._dialog._window:
carb.windowing.acquire_windowing_interface().hide_window(self._dialog._window.app_window.get_window())
if self._dialog:
self._dialog.destroy()
self._dialog = None
self._ui_ready = False
if self._destroy_dialog_task:
self._destroy_dialog_task.cancel()
self._destroy_dialog_task = None
def on_shutdown(self):
self.destroy_dialog()
self._ui_ready_event_sub = None
global g_singleton
g_singleton = None
def get_instance():
return g_singleton
| 15,396 |
Python
| 39.518421 | 128 | 0.637178 |
omniverse-code/kit/exts/omni.kit.window.file_exporter/omni/kit/window/file_exporter/__init__.py
|
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""A standardized dialog for exporting files"""
__all__ = ['FileExporterExtension', 'get_file_exporter']
from carb import log_warn
from omni.kit.window.filepicker import DetailFrameController as ExportOptionsDelegate
from .extension import FileExporterExtension, get_instance
def get_file_exporter() -> FileExporterExtension:
"""Returns the singleton file_exporter extension instance"""
instance = get_instance()
if instance is None:
log_warn("File exporter extension is no longer alive.")
return instance
| 966 |
Python
| 41.043476 | 85 | 0.779503 |
omniverse-code/kit/exts/omni.kit.window.file_exporter/omni/kit/window/file_exporter/test_helper.py
|
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import asyncio
import omni.kit.app
import omni.kit.ui_test as ui_test
from .extension import get_instance
from typing import List, Callable
from omni.kit.widget.filebrowser import FileBrowserItem, LISTVIEW_PANE, TREEVIEW_PANE
class FileExporterTestHelper:
"""Test helper for the file export dialog"""
# NOTE Since the file dialog is a singleton, use an async lock to ensure mutex access in unit tests.
# During run-time, this is not a issue because the dialog is effectively modal.
__async_lock = asyncio.Lock()
async def __aenter__(self):
await self.__async_lock.acquire()
return self
async def __aexit__(self, *args):
self.__async_lock.release()
async def wait_for_popup(self, timeout_frames: int = 20):
"""Waits for dialog to be ready"""
file_exporter = get_instance()
if file_exporter:
for _ in range(timeout_frames):
if file_exporter.is_ui_ready:
for _ in range(4):
# Wait a few extra frames to settle before returning
await omni.kit.app.get_app().next_update_async()
return
await omni.kit.app.get_app().next_update_async()
raise Exception("Error: The file export window did not open.")
async def click_apply_async(self, filename_url: str = None):
"""Helper function to progammatically execute the apply callback. Useful in unittests"""
file_exporter = get_instance()
if file_exporter:
file_exporter.click_apply(filename_url=filename_url)
await omni.kit.app.get_app().next_update_async()
async def click_cancel_async(self, cancel_handler: Callable[[str, str], None] = None):
"""Helper function to progammatically execute the cancel callback. Useful in unittests"""
file_exporter = get_instance()
if file_exporter:
file_exporter.click_cancel(cancel_handler=cancel_handler)
await omni.kit.app.get_app().next_update_async()
async def select_items_async(self, dir_url: str, names: List[str]) -> List[FileBrowserItem]:
file_exporter = get_instance()
selections = []
if file_exporter:
selections = await file_exporter.select_items_async(dir_url, names)
return selections
async def get_item_async(self, treeview_identifier: str, name: str, pane: int = LISTVIEW_PANE):
# Return item from the specified pane, handles both tree and grid views
file_exporter = get_instance()
if not file_exporter:
return
if name:
pane_widget = None
if pane == TREEVIEW_PANE:
pane_widget = ui_test.find_all(f"{file_exporter._title}//Frame/**/TreeView[*].identifier=='{treeview_identifier}_folder_view'")
elif file_exporter._dialog._widget._view.filebrowser.show_grid_view:
# LISTVIEW selected + showing grid view
pane_widget = ui_test.find_all(f"{file_exporter._title}//Frame/**/VGrid[*].identifier=='{treeview_identifier}_grid_view'")
else:
# LISTVIEW selected + showing tree view
pane_widget = ui_test.find_all(f"{file_exporter._title}//Frame/**/TreeView[*].identifier=='{treeview_identifier}'")
if pane_widget:
widget = pane_widget[0].find(f"**/Label[*].text=='{name}'")
if widget:
widget.widget.scroll_here(0.5, 0.5)
await ui_test.human_delay(4)
return widget
return None
| 4,054 |
Python
| 44.561797 | 143 | 0.633202 |
omniverse-code/kit/exts/omni.kit.window.file_exporter/omni/kit/window/file_exporter/tests/test_extension.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 os
import omni.kit.test
import omni.kit.ui_test as ui_test
import asyncio
import omni.appwindow
from unittest.mock import Mock, patch, ANY
from carb.settings import ISettings
from omni.kit.window.filepicker import FilePickerDialog
from omni.kit.test_suite.helpers import get_test_data_path
from .. import get_file_exporter
from ..test_helper import FileExporterTestHelper
from ..extension import on_export, file_filter_handler, DEFAULT_FILE_POSTFIX_OPTIONS
class TestFileExporter(omni.kit.test.AsyncTestCase):
"""
Testing omni.kit.window.file_exporter extension. NOTE that since the dialog is a singleton, we use an async
lock to ensure that only one test runs at a time. In practice, this is not a issue because only one extension
is accessing the dialog at any given time.
"""
__lock = asyncio.Lock()
async def setUp(self):
self._settings_path = "my_settings"
self._test_settings = {
"/exts/omni.kit.window.file_exporter/appSettings": self._settings_path,
f"{self._settings_path}/directory": "C:/temp/folder",
f"{self._settings_path}/filename": "my-file",
}
async def tearDown(self):
pass
def _mock_settings_get_string_impl(self, name: str) -> str:
return self._test_settings.get(name)
def _mock_settings_set_string_impl(self, name: str, value: str):
self._test_settings[name] = value
async def test_show_window_destroys_previous(self):
"""Testing show_window destroys previously allocated dialog"""
async with self.__lock:
under_test = get_file_exporter()
with patch.object(FilePickerDialog, "destroy", autospec=True) as mock_destroy_dialog,\
patch("carb.windowing.IWindowing.hide_window"):
under_test.show_window(title="first")
under_test.show_window(title="second")
mock_destroy_dialog.assert_called()
dialog = mock_destroy_dialog.call_args[0][0]
self.assertEqual(str(dialog._window), "first")
async def test_hide_window_destroys_it(self):
"""Testing that hiding the window destroys it"""
async with self.__lock:
under_test = get_file_exporter()
with patch.object(FilePickerDialog, "destroy", autospec=True) as mock_destroy_dialog:
under_test.show_window(title="test")
under_test._dialog.hide()
# Dialog is destroyed after a couple frames
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
mock_destroy_dialog.assert_called()
dialog = mock_destroy_dialog.call_args[0][0]
self.assertEqual(str(dialog._window), "test")
async def test_hide_window_destroys_detached_window(self):
"""Testing that hiding the window destroys detached window."""
async with self.__lock:
under_test = get_file_exporter()
with patch.object(FilePickerDialog, "destroy", autospec=True) as mock_destroy_dialog:
under_test.show_window(title="test_detached")
await omni.kit.app.get_app().next_update_async()
under_test.detach_from_main_window()
main_window = omni.appwindow.get_default_app_window().get_window()
self.assertFalse(main_window is under_test._dialog._window.app_window.get_window())
under_test.hide_window()
# Dialog is destroyed after a couple frames
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
mock_destroy_dialog.assert_called()
dialog = mock_destroy_dialog.call_args[0][0]
self.assertEqual(str(dialog._window), "test_detached")
async def test_load_default_settings(self):
"""Testing that dialog applies saved settings"""
async with self.__lock:
under_test = get_file_exporter()
with patch('omni.kit.window.file_exporter.extension.FilePickerDialog') as mock_dialog,\
patch.object(ISettings, "get_as_string", side_effect=self._mock_settings_get_string_impl):
under_test.show_window(title="test_dialog")
# Retrieve keyword args for the constructor (first call), and confirm called with expected values
constructor_kwargs = mock_dialog.call_args_list[0][1]
self.assertEqual(constructor_kwargs['current_directory'], self._test_settings[f"{self._settings_path}/directory"])
self.assertEqual(constructor_kwargs['current_filename'], "")
async def test_override_default_settings(self):
"""Testing that user values override default settings"""
async with self.__lock:
test_url = "Omniverse://ov-test/my-folder/my-file.usd"
under_test = get_file_exporter()
with patch('omni.kit.window.file_exporter.extension.FilePickerDialog') as mock_dialog,\
patch.object(ISettings, "get_as_string", side_effect=self._mock_settings_get_string_impl),\
patch("carb.windowing.IWindowing.hide_window"):
under_test.show_window(title="test_dialog", filename_url=test_url)
# Retrieve keyword args for the constructor (first call), and confirm called with expected values
constructor_kwargs = mock_dialog.call_args_list[0][1]
dirname, filename = os.path.split(test_url)
self.assertEqual(constructor_kwargs['current_directory'], dirname)
self.assertEqual(constructor_kwargs['current_filename'], filename)
async def test_save_settings_on_export(self):
"""Testing that settings are saved on export"""
my_settings = {
'filename': "my-file",
'directory': "Omniverse://ov-test/my-folder",
}
mock_dialog = Mock()
with patch.object(ISettings, "get_as_string", side_effect=self._mock_settings_get_string_impl),\
patch.object(ISettings, "set_string", side_effect=self._mock_settings_set_string_impl):
on_export(None, mock_dialog, my_settings['filename'], my_settings['directory'])
# Retrieve keyword args for the constructor (first call), and confirm called with expected values
self.assertEqual(my_settings['filename'], self._test_settings[f"{self._settings_path}/filename"])
self.assertEqual(my_settings['directory'], self._test_settings[f"{self._settings_path}/directory"])
async def test_show_only_folders(self):
"""Testing show only folders option."""
mock_handler = Mock()
async with self.__lock:
under_test = get_file_exporter()
test_path = get_test_data_path(__name__).replace("\\", '/')
async with FileExporterTestHelper() as helper:
with patch("carb.windowing.IWindowing.hide_window"):
# under normal circumstance, files will be shown and could be selected.
# under_test.show_window(title="test", filename_url=test_path)
under_test.show_window(title="test", filename_url=test_path + "/")
await ui_test.human_delay(10)
item = await helper.get_item_async(None, "dummy.usd")
self.assertIsNotNone(item)
# apply button should be disabled
self.assertFalse(under_test._dialog._widget.file_bar._apply_button.enabled)
await helper.click_cancel_async()
# if shown with show_only_folders, files will not be shown
under_test.show_window(title="test", show_only_folders=True, export_handler=mock_handler)
await ui_test.human_delay(10)
item = await helper.get_item_async(None, "dummy.usd")
self.assertIsNone(item)
# try selecting a folder
selections = await under_test.select_items_async(test_path, filenames=['folder'])
self.assertEqual(len(selections), 1)
selected = selections[0]
# apply button should not be disabled
self.assertTrue(under_test._dialog._widget.file_bar._apply_button.enabled)
await ui_test.human_delay()
await helper.click_apply_async()
mock_handler.assert_called_once_with('', selected.path + "/", extension=".usd", selections=[selected.path])
async def test_cancel_handler(self):
"""Testing cancel handler."""
mock_handler = Mock()
async with self.__lock:
under_test = get_file_exporter()
test_path = get_test_data_path(__name__).replace("\\", '/')
async with FileExporterTestHelper() as helper:
under_test.show_window("test_cancel_handler", filename_url=test_path + "/")
await helper.wait_for_popup()
await ui_test.human_delay(10)
await helper.click_cancel_async(cancel_handler=mock_handler)
await ui_test.human_delay(10)
mock_handler.assert_called_once()
class TestFileFilterHandler(omni.kit.test.AsyncTestCase):
"""Testing default_file_filter_handler correctly shows/hides files."""
async def setUp(self):
ext_type = {
'usd': "*.usd",
'usda': "*.usda",
'usdc': "*.usdc",
'usdz': "*.usdz",
}
self.test_filenames = [
("test.anim.usd", "anim", ext_type['usd'], True),
("test.anim.usdz", "anim", ext_type['usdz'], True),
("test.anim.usdc", "anim", ext_type['usdz'], False),
("test.anim.usda", None, ext_type['usda'], True),
("test.material.", None, ext_type['usda'], False),
("test.materials.usd", "material", ext_type['usd'], False),
]
async def tearDown(self):
pass
async def test_file_filter_handler(self):
"""Testing file filter handler"""
for test_filename in self.test_filenames:
filename, postfix, ext, expected = test_filename
result = file_filter_handler(filename, postfix, ext)
self.assertEqual(result, expected)
class TestOnExport(omni.kit.test.AsyncTestCase):
"""Testing on_export function correctly parses filename parts from dialog."""
async def setUp(self):
self.test_sets = [
("test", "anim", "*.usdc", "test", ".anim.usdc"),
("test.usd", "anim", "*.usdc", "test", ".anim.usdc"),
("test.cache.usdc", "geo", "*.usdz", "test", ".geo.usdz"),
("test.cache.any", "geo", "*.usd", "test.cache.any", ".geo.usd"),
("test.geo.usd", None, "*.usda", "test", ".usda"),
("test.png", "anim", "*.jpg", "test", ".anim.jpg"),
]
async def tearDown(self):
pass
async def test_on_export(self):
"""Testing file filter handler"""
mock_callback = Mock()
mock_dialog = Mock()
mock_extension_options = [
('*.usd', 'Can be Binary or Ascii'),
('*.usda', 'Human-readable text format'),
('*.usdc', 'Binary format'),
('*.png', 'test'),
('*.jpg', 'another test')
]
for test_set in self.test_sets:
filename = test_set[0]
mock_dialog.get_file_postfix.return_value = test_set[1]
mock_dialog.get_file_extension.return_value = test_set[2]
mock_dialog.get_file_postfix_options.return_value = DEFAULT_FILE_POSTFIX_OPTIONS
mock_dialog.get_file_extension_options.return_value = mock_extension_options
mock_dialog.get_current_selections.return_value = []
on_export(mock_callback, mock_dialog, filename, "C:/temp/test/")
expected_basename = test_set[3]
expected_extension = test_set[4]
mock_callback.assert_called_with(expected_basename, "C:/temp/test/", extension=expected_extension, selections=ANY)
async def test_export_filename_validation(self):
"""Test export with and without validation."""
mock_callback = Mock()
mock_dialog = Mock()
mock_dialog.get_file_postfix.return_value = None
mock_dialog.get_file_extension.return_value = ".usd"
mock_dialog.get_file_extension_options.return_value = [('*.usd', 'Can be Binary or Ascii')]
on_export(mock_callback, mock_dialog, "", "", should_validate=True)
mock_callback.assert_not_called()
on_export(mock_callback, mock_dialog, "", "C:/temp/test/", should_validate=False)
mock_callback.assert_called_once()
| 13,329 |
Python
| 47.827839 | 127 | 0.607998 |
omniverse-code/kit/exts/omni.kit.window.file_exporter/docs/CHANGELOG.md
|
# Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.10] - 2022-11-14
### Changed
- Updated the docs.
## [1.0.9] - 2022-10-21
### Changed
- Add flag for show_window if file name input should be enabled.
## [1.0.8] - 2022-10-01
### Changed
- Add flag for if file name validation should be performed.
## [1.0.7] - 2022-09-19
### Added
- Added file name validation for file exports, do not allow empty filenames when exporting.
## [1.0.6] - 2022-07-07
### Added
- Added test helper function that waits for UI to be ready.
## [1.0.5] - 2022-06-15
### Added
- Adds test helper.
## [1.0.4] - 2022-04-06
### Added
- Disable unittests from loading at startup.
## [1.0.3] - 2022-03-17
### Added
- Disabled checkpoints.
## [1.0.2] - 2022-02-09
### Added
- Adds click_apply and click_cancel methods.
## [1.0.1] - 2022-02-02
### Added
- Adds postfix and extension options.
## [1.0.0] - 2021-11-05
### Added
- Initial add.
| 970 |
Markdown
| 19.229166 | 91 | 0.645361 |
omniverse-code/kit/exts/omni.kit.window.file_exporter/docs/README.md
|
# Kit File Exporter Extension [omni.kit.window.file_exporter]
The File Exporter extension
| 91 |
Markdown
| 21.999995 | 61 | 0.802198 |
omniverse-code/kit/exts/omni.kit.window.file_exporter/docs/Overview.md
|
# Overview
The file_exporter extension provides a standardized dialog for exporting files. It is a wrapper around the {obj}`FilePickerDialog`,
but with reasonable defaults for common settings, so it's a higher-level entry point to that interface.
Nevertheless, users will still have the ability to customize some parts but we've boiled them down to just the essential ones.
Why you should use this extension:
* Present a consistent file export experience across the app.
* Customize only the essential parts while inheriting sensible defaults elsewhere.
* Reduce boilerplate code.
* Inherit future improvements.
* Checkpoints fully supported if available on the server.
```{image} ../../../../source/extensions/omni.kit.window.file_exporter/data/preview.png
---
align: center
---
```
## Quickstart
You can pop-up a dialog in just 2 steps. First, retrieve the extension.
```{literalinclude} ../../../../source/extensions/omni.kit.window.file_exporter/scripts/demo_file_exporter.py
---
language: python
start-after: BEGIN-DOC-get_instance
end-before: END-DOC-get_instance
dedent: 8
---
```
Then, invoke its show_window method.
```{literalinclude} ../../../../source/extensions/omni.kit.window.file_exporter/scripts/demo_file_exporter.py
---
language: python
start-after: BEGIN-DOC-show_window
end-before: END-DOC-show_window
dedent: 8
---
```
Note that the extension is a singleton, meaning there's only one instance of it throughout the app. Basically, we are assuming that you'd
never open more than one instance of the dialog at any one time. The advantage is that we can channel any development through this
single extension and all users will inherit the same changes.
## Customizing the Dialog
You can customize these parts of the dialog.
* Title - The title of the dialog.
* Collections - Which of these collections, ["bookmarks", "omniverse", "my-computer"] to display.
* Filename Url - Url to open the dialog with.
* Postfix options - List of content labels appended to the filename.
* Extension options - List of filename extensions.
* Export options - Options to apply during the export process.
* Export label - Label for the export button.
* Export handler - User provided callback to handle the export process.
Note that these settings are applied when you show the window. Therefore, each time it's displayed, the dialog can be tailored
to the use case.
## Filename postfix options
Users might want to set up data libraries of just animations, materials, etc. However, one challenge of working in Omniverse is that
everything is a USD file. To facilitate this workflow, we suggest adding a postfix to the filename, e.g. "file.animation.usd". The
file bar contains a dropdown that lists the postfix labels. A default list is provided but you can also provide your own.
```{literalinclude} ../../../../source/extensions/omni.kit.window.file_exporter/omni/kit/window/file_exporter/extension.py
---
language: python
start-after: BEGIN-DOC-file_postfix_options
end-before: END-DOC-file_postfix_options
dedent: 0
---
```
A list of file extensions, furthermore, allows the user to specify what flavor of USD to export.
```{literalinclude} ../../../../source/extensions/omni.kit.window.file_exporter/omni/kit/window/file_exporter/extension.py
---
language: python
start-after: BEGIN-DOC-file_extension_types
end-before: END-DOC-file_extension_types
dedent: 0
---
```
When the user selects a combination of postfix and extension types, the file view will filter out all other file types, leaving only
the matching ones.
## Export options
A common need is to provide user options for the export process. You create the widget for accepting those inputs,
then add it to the details pane of the dialog. Do this by subclassing from {obj}`ExportOptionsDelegate`
and overriding the methods, :meth:`ExportOptionsDelegate._build_ui_impl` and (optionally) :meth:`ExportOptionsDelegate._destroy_impl`.
```{literalinclude} ../../../../source/extensions/omni.kit.window.file_exporter/scripts/demo_file_exporter.py
---
language: python
start-after: BEGIN-DOC-export_options
end-before: END-DOC-export_options
dedent: 0
---
```
Then provide the controller to the file picker for display.
```{literalinclude} ../../../../source/extensions/omni.kit.window.file_exporter/scripts/demo_file_exporter.py
---
language: python
start-after: BEGIN-DOC-add_export_options
end-before: END-DOC-add_export_options
dedent: 8
---
```
## Export handler
Pprovide a handler for when the Export button is clicked. In additon to :attr:`filename` and :attr:`dirname`, the handler
should expect a list of :attr:`selections` made from the UI.
```{literalinclude} ../../../../source/extensions/omni.kit.window.file_exporter/scripts/demo_file_exporter.py
---
language: python
start-after: BEGIN-DOC-export_handler
end-before: END-DOC-export_handler
dedent: 4
---
```
## Demo app
A complete demo, that includes the code snippets above, is included with this extension at "scripts/demo_file_exporter.py".
| 5,021 |
Markdown
| 35.92647 | 139 | 0.756622 |
omniverse-code/kit/exts/omni.kit.property.bundle/omni/kit/property/bundle/widgets.py
|
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb
import omni.usd
from pathlib import Path
from .geom_scheme_delegate import GeomPrimSchemeDelegate
from .path_scheme_delegate import PathPrimSchemeDelegate
from .material_scheme_delegate import MaterialPrimSchemeDelegate, ShaderPrimSchemeDelegate
TEST_DATA_PATH = ""
class BundlePropertyWidgets(omni.ext.IExt):
def __init__(self):
self._registered = False
super().__init__()
def on_startup(self, ext_id):
self._register_widget()
manager = omni.kit.app.get_app().get_extension_manager()
extension_path = manager.get_extension_path(ext_id)
global TEST_DATA_PATH
TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests")
def on_shutdown(self):
self._unregister_widget()
def _register_widget(self):
import omni.kit.window.property as p
w = p.get_window()
w.register_scheme_delegate("prim", "xformable_prim", GeomPrimSchemeDelegate())
w.register_scheme_delegate("prim", "path_prim", PathPrimSchemeDelegate())
w.register_scheme_delegate("prim", "material_prim", MaterialPrimSchemeDelegate())
w.register_scheme_delegate("prim", "shade_prim", ShaderPrimSchemeDelegate())
physics_widgets = [
"physics_components",
"physics_prim",
"joint_prim",
"vehicle_prim",
"physics_material",
"custom_properties",
]
anim_graph_widgets = ["anim_graph", "anim_graph_node"]
w.set_scheme_delegate_layout(
"prim",
[
"path_prim",
"basis_curves_prim",
"point_instancer_prim",
"material_prim",
"xformable_prim",
"shade_prim",
"audio_settings",
]
+ physics_widgets
+ anim_graph_widgets,
)
def _unregister_widget(self):
import omni.kit.window.property as p
w = p.get_window()
w.reset_scheme_delegate_layout("prim")
w.unregister_scheme_delegate("prim", "xformable_prim")
w.unregister_scheme_delegate("prim", "path_prim")
w.unregister_scheme_delegate("prim", "material_prim")
w.unregister_scheme_delegate("prim", "shade_prim")
| 2,730 |
Python
| 34.467532 | 90 | 0.632234 |
omniverse-code/kit/exts/omni.kit.property.bundle/omni/kit/property/bundle/material_scheme_delegate.py
|
import carb
import omni.usd
from pxr import Sdf, UsdShade
from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate
class MaterialPrimSchemeDelegate(PropertySchemeDelegate):
def get_widgets(self, payload):
widgets_to_build = []
if self._should_enable_delegate(payload):
widgets_to_build.append("path")
widgets_to_build.append("material")
return widgets_to_build
def get_unwanted_widgets(self, payload):
unwanted_widgets_to_build = []
if self._should_enable_delegate(payload):
unwanted_widgets_to_build.append("transform")
return unwanted_widgets_to_build
def _should_enable_delegate(self, payload):
stage = payload.get_stage()
if stage:
for prim_path in payload:
prim = stage.GetPrimAtPath(prim_path)
if prim:
if not prim.IsA(UsdShade.Material):
return False
return True
return False
class ShaderPrimSchemeDelegate(PropertySchemeDelegate):
def get_widgets(self, payload):
widgets_to_build = []
if self._should_enable_delegate(payload):
widgets_to_build.append("path")
widgets_to_build.append("shader")
return widgets_to_build
def get_unwanted_widgets(self, payload):
unwanted_widgets_to_build = []
if self._should_enable_delegate(payload):
unwanted_widgets_to_build.append("transform")
return unwanted_widgets_to_build
def _should_enable_delegate(self, payload):
stage = payload.get_stage()
if stage:
for prim_path in payload:
prim = stage.GetPrimAtPath(prim_path)
if prim:
if not prim.IsA(UsdShade.Shader):
return False
return True
return False
| 1,922 |
Python
| 32.155172 | 84 | 0.60666 |
omniverse-code/kit/exts/omni.kit.property.bundle/omni/kit/property/bundle/path_scheme_delegate.py
|
import carb
import omni.usd
from pxr import Sdf, UsdGeom
from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate
class PathPrimSchemeDelegate(PropertySchemeDelegate):
def get_widgets(self, payload):
widgets_to_build = []
if len(payload):
widgets_to_build.append("path")
return widgets_to_build
| 367 |
Python
| 23.533332 | 84 | 0.719346 |
omniverse-code/kit/exts/omni.kit.property.bundle/omni/kit/property/bundle/geom_scheme_delegate.py
|
import carb
import omni.usd
from pxr import Sdf, UsdMedia, OmniAudioSchema, UsdGeom, UsdLux, UsdSkel
from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate
class GeomPrimSchemeDelegate(PropertySchemeDelegate):
def get_widgets(self, payload):
widgets_to_build = []
anchor_prim = None
stage = payload.get_stage()
if stage:
for prim_path in payload:
prim = stage.GetPrimAtPath(prim_path)
if prim:
if not prim.IsA(UsdGeom.Imageable):
return widgets_to_build
anchor_prim = prim
if anchor_prim is None:
return widgets_to_build
if (
anchor_prim
and anchor_prim.IsA(UsdMedia.SpatialAudio)
or anchor_prim.IsA(OmniAudioSchema.OmniSound)
or anchor_prim.IsA(OmniAudioSchema.OmniListener)
):
widgets_to_build.append("path")
widgets_to_build.append("transform")
widgets_to_build.append("media")
widgets_to_build.append("audio_sound")
widgets_to_build.append("audio_listener")
widgets_to_build.append("audio_settings")
widgets_to_build.append("kind")
elif anchor_prim and anchor_prim.IsA(UsdSkel.Root): # pragma: no cover
widgets_to_build.append("path")
widgets_to_build.append("transform")
widgets_to_build.append("character_api")
widgets_to_build.append("anim_graph_api")
widgets_to_build.append("omni_graph_api")
widgets_to_build.append("kind")
elif anchor_prim.IsA(UsdSkel.Skeleton): # pragma: no cover
widgets_to_build.append("path")
widgets_to_build.append("transform")
widgets_to_build.append("control_rig")
widgets_to_build.append("skel_animation")
elif anchor_prim and anchor_prim.IsA(UsdGeom.Camera):
widgets_to_build.append("path")
widgets_to_build.append("transform")
widgets_to_build.append("camera")
widgets_to_build.append("geometry_imageable")
widgets_to_build.append("kind")
# https://github.com/PixarAnimationStudios/USD/commit/7540fdf3b2aa6b6faa0fce8e7b4c72b756286f51
elif anchor_prim and ((hasattr(UsdLux, 'LightAPI') and anchor_prim.HasAPI(UsdLux.LightAPI)) or ((hasattr(UsdLux, 'Light') and anchor_prim.IsA(UsdLux.Light)))):
widgets_to_build.append("path")
widgets_to_build.append("transform")
widgets_to_build.append("light")
widgets_to_build.append("geometry_imageable")
widgets_to_build.append("kind")
elif anchor_prim and anchor_prim.IsA(UsdGeom.Scope):
widgets_to_build.append("path")
widgets_to_build.append("geometry_imageable")
widgets_to_build.append("character_motion_library")
widgets_to_build.append("kind")
elif anchor_prim and anchor_prim.IsA(UsdGeom.Mesh):
widgets_to_build.append("path")
widgets_to_build.append("transform")
widgets_to_build.append("material_binding")
widgets_to_build.append("geometry")
widgets_to_build.append("geometry_imageable")
widgets_to_build.append("character_interactive_object_api")
widgets_to_build.append("mesh_skel_binding")
widgets_to_build.append("kind")
elif anchor_prim and anchor_prim.IsA(UsdGeom.Xform):
widgets_to_build.append("path")
widgets_to_build.append("transform")
widgets_to_build.append("material_binding")
widgets_to_build.append("geometry_imageable")
widgets_to_build.append("kind")
elif anchor_prim and anchor_prim.IsA(UsdGeom.Xformable):
widgets_to_build.append("path")
widgets_to_build.append("transform")
widgets_to_build.append("material_binding")
widgets_to_build.append("geometry")
widgets_to_build.append("geometry_imageable")
widgets_to_build.append("character_interactive_object_api")
widgets_to_build.append("kind")
return widgets_to_build
def get_unwanted_widgets(self, payload):
unwanted_widgets_to_build = []
anchor_prim = None
stage = payload.get_stage()
if stage:
for prim_path in payload:
prim = stage.GetPrimAtPath(prim_path)
if prim:
if not prim.IsA(UsdGeom.Imageable):
return unwanted_widgets_to_build
anchor_prim = prim
if anchor_prim is None:
return unwanted_widgets_to_build
if anchor_prim and anchor_prim.IsA(UsdGeom.Scope):
unwanted_widgets_to_build.append("transform")
unwanted_widgets_to_build.append("geometry")
unwanted_widgets_to_build.append("kind")
# https://github.com/PixarAnimationStudios/USD/commit/7540fdf3b2aa6b6faa0fce8e7b4c72b756286f51
elif anchor_prim and ((hasattr(UsdLux, 'LightAPI') and anchor_prim.HasAPI(UsdLux.LightAPI)) or ((hasattr(UsdLux, 'Light') and anchor_prim.IsA(UsdLux.Light)))):
unwanted_widgets_to_build.append("geometry")
elif (
anchor_prim
and anchor_prim.IsA(UsdMedia.SpatialAudio)
or anchor_prim.IsA(OmniAudioSchema.Sound)
or anchor_prim.IsA(OmniAudioSchema.Listener)
):
unwanted_widgets_to_build.append("geometry_imageable")
elif anchor_prim and anchor_prim.IsA(UsdSkel.Skeleton) or anchor_prim.IsA(UsdSkel.Root):
unwanted_widgets_to_build.append("geometry")
unwanted_widgets_to_build.append("geometry_imageable")
return unwanted_widgets_to_build
| 5,906 |
Python
| 41.496403 | 167 | 0.614968 |
omniverse-code/kit/exts/omni.kit.property.bundle/omni/kit/property/bundle/tests/test_bundle.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 platform
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.ui.tests.test_base import OmniUiTest
from omni.kit import ui_test
from omni.kit.test_suite.helpers import arrange_windows, wait_stage_loading, get_prims
from pxr import Kind, Sdf, Gf
import pathlib
class TestBundleWidget(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
await arrange_windows()
from omni.kit.property.bundle.widgets import TEST_DATA_PATH
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute()
self._usd_path = TEST_DATA_PATH.absolute()
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_bundle_ui(self):
usd_context = omni.usd.get_context()
test_file_path = self._usd_path.joinpath("bundle.usda").absolute()
await usd_context.open_stage_async(str(test_file_path))
await wait_stage_loading()
stage = usd_context.get_stage()
for prim_path in ['/World/Cube', '/World/Cone', '/World/OmniSound', '/World/Camera', '/World/DomeLight', '/World/Scope', '/World/Xform']:
await self.docked_test_window(
window=self._w._window,
width=450,
height=995,
restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position = ui.DockPosition.BOTTOM)
# Select the prim.
usd_context.get_selection().set_selected_prim_paths([prim_path], True)
prim = stage.GetPrimAtPath(prim_path)
type = prim.GetTypeName().lower()
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(10)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=f"test_bundle_ui_{type}.png")
# allow window to be restored to full size
await ui_test.human_delay(50)
| 2,673 |
Python
| 37.199999 | 145 | 0.66517 |
omniverse-code/kit/exts/omni.kit.property.bundle/docs/CHANGELOG.md
|
# Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.2.6] - 2022-05-13
### Changes
- Update test golden image
## [1.2.5] - 2022-05-05
### Changes
- Update test golden image
## [1.2.4] - 2021-04-15
### Changes
- Changed how material input is populated.
## [1.2.3] - 2021-02-19
### Changes
- Added UI test
## [1.2.2] - 2020-12-09
### Changes
- Added extension icon
- Added readme
- Updated preview image
## [1.2.1] - 2020-11-10
### Changes
- Added layer widget to ordering
## [1.2.0] - 2020-10-27
### Changes
- Added physics widgets to ordering
## [1.1.0] - 2020-10-21
### Changes
- Property schemas moved into bundle
## [1.0.3] - 2020-10-19
### Changes
- Loads property.transform
## [1.0.2] - 2020-10-13
### Changes
- Loads property.audio
## [1.0.1] - 2020-10-09
### Changes
- created
- Loads property.geometry
## [1.0.0] - 2020-09-23
### Changes
- created
- Loads property.camera, property.light, property.material & property.usd
| 989 |
Markdown
| 16.678571 | 80 | 0.645096 |
omniverse-code/kit/exts/omni.kit.property.bundle/docs/README.md
|
# omni.kit.property.bundle
## Introduction
Property window extensions are for viewing and editing Usd Prim Attributes
## This extension loads;
- omni.kit.window.property
- omni.kit.property.camera
- omni.kit.property.light
- omni.kit.property.material
- omni.kit.property.usd
- omni.kit.property.geometry
- omni.kit.property.audio
- omni.kit.property.transform
## so is a convenient way to load all the property extensions.
## This is also controls what properties are shown and in what order
| 500 |
Markdown
| 21.772726 | 74 | 0.774 |
omniverse-code/kit/exts/omni.kit.property.bundle/docs/index.rst
|
omni.kit.property.bundle
###########################
Property Widget Loader
.. toctree::
:maxdepth: 1
CHANGELOG
| 123 |
reStructuredText
| 9.333333 | 27 | 0.536585 |
omniverse-code/kit/exts/omni.kit.exec.debug/omni/kit/exec/debug/execution_debug_page.py
|
"""EF Execution Debugging Page"""
import omni.ui as ui
from omni.kit.exec.core.unstable import dump_graph_topology
from omni.kit.window.preferences import PreferenceBuilder, SettingType
class ExecutionDebugPage(PreferenceBuilder):
"""EF Execution Debugging Page"""
def __init__(self):
super().__init__("Execution")
# Setting keys. When changing, make sure to update ExecutionController.cpp as well.
self.serial_eg = "/app/execution/debug/forceSerial"
self.parallel_eg = "/app/execution/debug/forceParallel"
# ID counter for file path write-out.
self.id = 0
self.file_name = "ExecutionGraph_"
def build(self):
"""Build the EF execution debugging page"""
with ui.VStack(height=0):
with self.add_frame("Execution Debugging"):
with ui.VStack():
dump_graph_topology_button = ui.Button("Dump execution graph", width=24)
dump_graph_topology_button.set_clicked_fn(self._dump_graph_topology)
dump_graph_topology_button.set_tooltip(
"Writes the execution graph topology out as a GraphViz (.dot) file. File location\n"
+ "will differ depending on the kit app being run, whether the button was pressed\n"
+ "in a unit test, etc., but typically it can be found under something like\n"
+ "kit/_compiler/omni.app.dev; if not, then just search for .dot files containing\n"
+ "the name ExecutionGraph in the kit directory.\n"
)
self.create_setting_widget("Force serial execution", self.serial_eg, SettingType.BOOL)
self.create_setting_widget("Force parallel execution", self.parallel_eg, SettingType.BOOL)
def _dump_graph_topology(self):
"""Dump graph topology with incremented file"""
dump_graph_topology(self.file_name + str(self.id))
self.id += 1
| 2,021 |
Python
| 46.023255 | 110 | 0.617516 |
omniverse-code/kit/exts/omni.kit.exec.debug/omni/kit/exec/debug/extension.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.ext
from omni.kit.window.preferences import register_page, unregister_page
from .execution_debug_page import ExecutionDebugPage
class ExecutionDebugExtension(omni.ext.IExt):
# The entry point for this extension (generates a page within the Preferences
# tab with debugging flags for the Execution Framework).
def on_startup(self):
self.execution_debug_page = ExecutionDebugPage()
register_page(self.execution_debug_page)
def on_shutdown(self):
unregister_page(self.execution_debug_page)
| 970 |
Python
| 39.458332 | 81 | 0.778351 |
omniverse-code/kit/exts/omni.kit.exec.debug/omni/kit/exec/debug/tests/test_exec_debug.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 carb.settings
import omni.kit.test
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
import omni.kit.app
import omni.kit.window.preferences as preferences
from omni.kit.viewport.window import ViewportWindow
import omni.ui as ui
CURRENT_PATH = Path(__file__).parent
TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests")
TEST_WIDTH, TEST_HEIGHT = 1280, 600
class TestExecutionDebugWindow(OmniUiTest):
"""Test the EF Debugging Page"""
async def setUp(self):
"""Test set-up before running each test"""
await super().setUp()
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute()
await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT)
self._vw = ViewportWindow("TestWindow", width=TEST_WIDTH, height=TEST_HEIGHT)
async def tearDown(self):
"""Test tear-down after running each test"""
await super().tearDown()
async def test_execution_page(self):
"""Test the EF Debugging Page"""
title = "Execution"
for page in preferences.get_page_list():
if page.get_title() == title:
# Setting keys for the test. Flag some stuff to be true to make sure toggles work.
carb.settings.get_settings().set(page.serial_eg, False)
carb.settings.get_settings().set(page.parallel_eg, True)
preferences.select_page(page)
preferences.show_preferences_window()
await omni.kit.app.get_app().next_update_async()
pref_window = ui.Workspace.get_window("Preferences")
await self.docked_test_window(
window=pref_window,
width=TEST_WIDTH,
height=TEST_HEIGHT,
)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=f"{title}.png")
| 2,383 |
Python
| 36.841269 | 101 | 0.68569 |
omniverse-code/kit/exts/omni.kit.exec.debug/docs/index.rst
|
omni.kit.exec.debug
###########################
.. toctree::
:maxdepth: 1
CHANGELOG
| 94 |
reStructuredText
| 8.499999 | 27 | 0.43617 |
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/welcome_page_item.py
|
from typing import Callable
import carb
import omni.kit.app
import omni.ui as ui
class WelcomePageItem(ui.AbstractItem):
def __init__(self, raw_data: dict):
super().__init__()
self.text = raw_data.get("text", "")
self.icon = raw_data.get("icon", "")
self.active_icon = raw_data.get("active_icon", self.icon)
self.extension_id = raw_data.get("extension_id")
self.order = raw_data.get("order", 0xFFFFFFFF)
self.build_fn: Callable[[None], None] = None
carb.log_info(f"Register welcome page: {self}")
def build_ui(self) -> None:
# Enable page extension and call build_ui
manager = omni.kit.app.get_app().get_extension_manager()
manager.set_extension_enabled_immediate(self.extension_id, True)
try:
if self.build_fn:
self.build_fn()
else:
carb.log_error(f"Failed to build page for `{self.text}` because build entry point not defined!")
except Exception as e:
carb.log_error(f"Failed to build page for `{self.text}`: {e}")
def __repr__(self):
return f"{self.text}:{self.extension_id}"
| 1,175 |
Python
| 35.749999 | 112 | 0.6 |
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/welcome_window.py
|
from typing import Dict, List, Optional
import carb.settings
import omni.ui as ui
from omni.ui import constant as fl
from .style import WELCOME_STYLE
from .welcome_model import WelcomeModel
from .welcome_page_item import WelcomePageItem
SETTING_SHOW_AT_STARTUP = "/persistent/exts/omni.kit.welcome.window/visible_at_startup"
SETTING_SHOW_SAS_CHECKBOX = "/exts/omni.kit.welcome.window/show_sas_checkbox"
class WelcomeWindow(ui.Window):
"""
Window to show welcome content.
Args:
visible (bool): If visible when window created.
"""
def __init__(self, model: WelcomeModel, visible: bool=True):
self._model = model
self._delegates: List[WelcomePageItem] = []
self.__page_frames: Dict[WelcomePageItem, ui.Frame] = {}
self.__page_buttons: Dict[WelcomePageItem, ui.Button] = {}
self.__selected_page: Optional[WelcomePageItem] = None
# TODO: model window?
# If model window and open extensions manager, new extensions window unavailable
# And if model window, checkpoing combobox does not pop up droplist because it is a popup window
flags = (ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_MODAL)
super().__init__("Welcome Screen", flags=flags, width=1380, height=780, padding_x=2, padding_y=2, visible=visible)
self.frame.set_build_fn(self._build_ui)
self.frame.set_style(WELCOME_STYLE)
def destroy(self) -> None:
super().destroy()
self.__page_frames = {}
self.visible = False
self.__sub_show_at_startup = None
def _build_ui(self):
self._pages = self._model.get_item_children(None)
button_height = fl._find("welcome_page_button_height")
with self.frame:
with ui.HStack():
# Left for buttons to switch different pages
with ui.VStack(width=250, spacing=0):
for page in self._pages:
self.__page_buttons[page] = ui.Button(
page.text.upper(),
height=button_height,
image_width=button_height,
image_height=button_height,
spacing=4,
image_url=page.icon,
clicked_fn=lambda d=page: self.__show_page(d), style_type_name_override="Page.Button"
)
ui.Spacer()
self.__build_show_at_startup()
# Right for page content
with ui.ZStack():
for page in self._pages:
self.__page_frames[page] = ui.Frame(build_fn=lambda p=page: p.build_ui(), visible=False)
# Default always show first page
self.__show_page(self._pages[0])
def __build_show_at_startup(self) -> None:
settings = carb.settings.get_settings()
self.__show_at_startup_model = ui.SimpleBoolModel(settings.get(SETTING_SHOW_AT_STARTUP))
def __on_show_at_startup_changed(model: ui.SimpleBoolModel):
settings.set(SETTING_SHOW_AT_STARTUP, model.as_bool)
self.__sub_show_at_startup = self.__show_at_startup_model.subscribe_value_changed_fn(__on_show_at_startup_changed)
if settings.get_as_bool(SETTING_SHOW_SAS_CHECKBOX):
with ui.HStack(height=0, spacing=5):
ui.Spacer(width=5)
ui.CheckBox(self.__show_at_startup_model, width=0)
ui.Label("Show at Startup", width=0)
ui.Spacer(height=5)
def __show_page(self, page: WelcomePageItem):
if self.__selected_page:
self.__page_frames[self.__selected_page].visible = False
self.__page_buttons[self.__selected_page].selected = False
self.__page_buttons[self.__selected_page].image_url = self.__selected_page.icon
if page:
self.__page_frames[page].visible = True
self.__page_buttons[page].selected = True
self.__page_buttons[page].image_url = page.active_icon
self.__selected_page = page
| 4,148 |
Python
| 42.21875 | 122 | 0.592575 |
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/style.py
|
from pathlib import Path
import omni.ui as ui
from omni.ui import color as cl
from omni.ui import constant as fl
CURRENT_PATH = Path(__file__).parent
ICON_PATH = CURRENT_PATH.parent.parent.parent.joinpath("data/icons")
cl.welcome_window_background = cl.shade(cl("#363636"))
cl.welcome_content_background = cl.shade(cl("#1F2123"))
cl.welcome_button_text = cl.shade(cl("#979797"))
cl.welcome_button_text_selected = cl.shade(cl("#E3E3E3"))
cl.welcome_label = cl.shade(cl("#A1A1A1"))
cl.welcome_label_selected = cl.shade(cl("#34C7FF"))
fl.welcome_page_button_size = 24
fl.welcome_title_font_size = 18
fl.welcome_page_button_height = 80
fl.welcome_page_title_height = fl._find("welcome_page_button_height") + 8
fl.welcome_content_padding_x = 10
fl.welcome_content_padding_y = 10
WELCOME_STYLE = {
"Window": {
"background_color": cl.welcome_window_background,
"border_width": 0,
"padding": 0,
"marging" : 0,
"padding_width": 0,
"margin_width": 0,
},
"Page.Button": {
"background_color": cl.welcome_window_background,
"stack_direction": ui.Direction.LEFT_TO_RIGHT,
"padding_x": 10,
"margin": 0,
},
"Page.Button:hovered": {
"background_color": cl.welcome_content_background,
},
"Page.Button:pressed": {
"background_color": cl.welcome_content_background,
},
"Page.Button:selected": {
"background_color": cl.welcome_content_background,
},
"Page.Button.Label": {
"font_size": fl.welcome_page_button_size,
"alignment": ui.Alignment.LEFT_CENTER,
"color": cl.welcome_button_text,
},
"Page.Button.Label:selected": {
"color": cl.welcome_button_text_selected,
},
"Content": {
"background_color": cl.welcome_content_background,
},
"Title.Button": {
"background_color": cl.transparent,
"stack_direction": ui.Direction.RIGHT_TO_LEFT,
},
"Title.Button.Label": {
"font_size": fl.welcome_title_font_size,
},
"Title.Button.Image": {
"color": cl.welcome_label_selected,
"alignment": ui.Alignment.LEFT_CENTER,
},
"Doc.Background": {"background_color": cl.white},
"CheckBox": {
"background_color": cl.welcome_button_text,
"border_radius": 0,
},
"Label": {"color": cl.welcome_button_text},
}
| 2,375 |
Python
| 29.075949 | 73 | 0.622737 |
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/extension.py
|
import asyncio
from typing import Callable, Optional
import carb
import carb.settings
import omni.ext
import omni.kit.app
import omni.kit.menu.utils
import omni.kit.ui
import omni.ui as ui
from omni.kit.menu.utils import MenuItemDescription
from .actions import deregister_actions, register_actions
from .welcome_model import WelcomeModel
from .welcome_window import WelcomeWindow
WELCOME_MENU_ROOT = "File"
_extension_instance = None
class WelcomeExtension(omni.ext.IExt):
def on_startup(self, ext_id):
self._ext_name = omni.ext.get_extension_name(ext_id)
self.__stage_opened = False
# Window
self._model = WelcomeModel()
visible = carb.settings.get_settings().get("/persistent/exts/omni.kit.welcome.window/visible_at_startup")
self._window = WelcomeWindow(self._model, visible=visible)
self._window.set_visibility_changed_fn(self.__on_visibility_changed)
if visible:
self.__center_window()
else:
# Listen for the app ready event
def _on_app_ready(event):
self.__on_close()
self._app_ready_sub = None
startup_event_stream = omni.kit.app.get_app().get_startup_event_stream()
self._app_ready_sub = startup_event_stream.create_subscription_to_pop_by_type(
omni.kit.app.EVENT_APP_READY, _on_app_ready, name="Welcome window"
)
# Menu item
self._register_menuitem()
global _extension_instance
_extension_instance = self
# Action
register_actions(self._ext_name, _extension_instance)
def on_shutdown(self):
self._hooks = None
self._app_ready_sub = None
deregister_actions(self._ext_name)
self._model = None
if self._menu_list is not None:
omni.kit.menu.utils.remove_menu_items(self._menu_list, WELCOME_MENU_ROOT)
self._menu_list = None
if self._window is not None:
self._window.destroy()
self._window = None
global _extension_instance
_extension_instance = self
def toggle_window(self):
self._window.visible = not self._window.visible
def _register_menuitem(self):
self._menu_list = [
MenuItemDescription(
name="Welcome",
glyph="none.svg",
ticked=True,
ticked_fn=self._on_tick,
onclick_action=(self._ext_name, "toggle_window"),
appear_after="Open",
)
]
omni.kit.menu.utils.add_menu_items(self._menu_list, WELCOME_MENU_ROOT)
def _on_tick(self):
if self._window:
return self._window.visible
else:
return False
def _on_click(self, *args):
self._window.visible = not self._window.visible
def __on_visibility_changed(self, visible: bool):
omni.kit.menu.utils.refresh_menu_items(WELCOME_MENU_ROOT)
if visible:
# Always center. Cannot use layout file to change window position because window may be invisible when startup
self.__center_window()
return
self.__on_close()
def __open_default_stage(self):
self.__execute_action("omni.kit.stage.templates", "create_new_stage_empty")
def __on_close(self):
# When welcome window is closed, setup the Viewport to a complete state
settings = carb.settings.get_settings()
if settings.get("/exts/omni.kit.welcome.window/autoSetupOnClose"):
self.__execute_action("omni.app.setup", "enable_viewport_rendering")
# Do not open default stage if stage already opened
if not self.__stage_opened and not omni.usd.get_context().get_stage():
self.__open_default_stage()
workflow = settings.get("/exts/omni.kit.welcome.window/default_workflow")
if workflow:
self.__active_workflow(workflow)
def __active_workflow(self, workflow: str):
carb.log_info(f"Trying to active workflow '{workflow}'...")
self.__execute_action("omni.app.setup", "active_workflow", workflow)
def __center_window(self):
async def __delay_center():
await omni.kit.app.get_app().next_update_async()
app_width = ui.Workspace.get_main_window_width()
app_height = ui.Workspace.get_main_window_height()
self._window.position_x = (app_width - self._window.frame.computed_width) / 2
self._window.position_y = (app_height - self._window.frame.computed_height) / 2
asyncio.ensure_future(__delay_center())
def __execute_action(self, ext_id: str, action_id: str, *args, **kwargs):
try:
import omni.kit.actions.core
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.execute_action(ext_id, action_id, *args, **kwargs)
except Exception as e:
carb.log_error(f"Failed to execute action '{ext_id}::{action_id}': {e}")
def register_page(self, ext_id: str, build_fn: Callable[[None], None]) -> bool:
return self._model.register_page(ext_id, build_fn)
def show_window(self, visible: bool = True, stage_opened: bool = False) -> None:
self.__stage_opened = stage_opened or self.__stage_opened
self._window.visible = visible
def register_page(ext_id: str, build_fn: Callable[[None], None]) -> bool:
if _extension_instance:
return _extension_instance.register_page(ext_id, build_fn)
else:
return False
def show_window(visible: bool = True, stage_opened: bool = False) -> None:
if _extension_instance:
_extension_instance.show_window(visible=visible, stage_opened=stage_opened)
| 5,793 |
Python
| 35.670886 | 122 | 0.619886 |
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/welcome_model.py
|
from typing import Callable, List, Optional
import carb
import carb.settings
import omni.ui as ui
from .welcome_page_item import WelcomePageItem
SETTING_WELCOME_PAGES = "/app/welcome/page"
class WelcomeModel(ui.AbstractItemModel):
def __init__(self):
super().__init__()
self.__settings = carb.settings.get_settings()
self._items = [WelcomePageItem(page) for page in self.__settings.get(SETTING_WELCOME_PAGES)]
self._items.sort(key=lambda item: item.order)
def get_item_children(self, item: Optional[WelcomePageItem]) -> List[WelcomePageItem]:
return self._items
def register_page(self, ext_id: str, build_fn: Callable[[None], None]) -> bool:
for item in self._items:
if item.extension_id == ext_id:
item.build_fn = build_fn
return True
carb.log_warn(f"Extension {ext_id} not defined in welcome window.")
return False
| 945 |
Python
| 30.533332 | 100 | 0.65291 |
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/actions.py
|
def register_actions(extension_id, extension_inst):
try:
import omni.kit.actions.core
action_registry = omni.kit.actions.core.get_action_registry()
actions_tag = "Welcome"
action_registry.register_action(
extension_id,
"toggle_window",
extension_inst.toggle_window,
display_name="File->Welcome",
description="Show/Hide welcome window",
tag=actions_tag,
)
except ImportError:
pass
def deregister_actions(extension_id):
try:
import omni.kit.actions.core
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.deregister_all_actions_for_extension(extension_id)
except ImportError:
pass
| 777 |
Python
| 28.923076 | 74 | 0.622909 |
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/tests/__init__.py
|
from .test_window import *
| 26 |
Python
| 25.999974 | 26 | 0.769231 |
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/tests/test_window.py
|
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
import omni.ui as ui
from ..extension import register_page, _extension_instance as welcome_instance
CURRENT_PATH = Path(__file__).parent
TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests")
class TestWelcomeWindow(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute()
# Register page build function
register_page("omni.kit.welcome.window", self.__build_ui)
# Show window
self._window = welcome_instance._window
self._window.visible = True
# After running each test
async def tearDown(self):
await super().tearDown()
async def test_window(self):
await self.docked_test_window(window=self._window, width=1280, height=720, block_devices=False)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="window.png")
def __build_ui(self):
with ui.VStack():
ui.Label("PLACE PAGE WIDGETS HERE!", height=0)
| 1,186 |
Python
| 32.914285 | 103 | 0.680438 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/config/extension.toml
|
[package]
version = "1.1.3"
title = "Live Session Management Widgets"
category = "Internal"
description = "This extension includes shared live session widgets used by other extentions to re-use widgets for session management."
keywords = ["Live Session", "Layers", "Widget"]
changelog = "docs/CHANGELOG.md"
authors = ["NVIDIA"]
repository = ""
[dependencies]
"omni.ui" = {}
"omni.client" = {}
"omni.kit.usd.layers" = {}
"omni.kit.widget.prompt" = {}
"omni.kit.window.filepicker" = {}
"omni.kit.notification_manager" = {}
"omni.kit.collaboration.channel_manager" = {}
"omni.kit.window.file" = {}
[[python.module]]
name = "omni.kit.widget.live_session_management"
[[test]]
waiver = "Tests covered in omni.kit.widget.layers"
| 725 |
TOML
| 26.923076 | 134 | 0.704828 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/share_session_link_window.py
|
import carb
import omni.kit.usd.layers as layers
import omni.ui as ui
import omni.kit.clipboard
from .live_session_model import LiveSessionModel
from .layer_icons import LayerIcons
class ShareSessionLinkWindow:
def __init__(self, layers_interface: layers.Layers, layer_identifier):
self._window = None
self._layers_interface = layers_interface
self._base_layer_identifier = layer_identifier
self._buttons = []
self._existing_sessions_combo = None
self._existing_sessions_model = LiveSessionModel(self._layers_interface, layer_identifier, False)
self._key_functions = {
int(carb.input.KeyboardInput.ENTER): self._on_ok_button_fn,
int(carb.input.KeyboardInput.ESCAPE): self._on_cancel_button_fn
}
self._build_ui()
def _on_layer_event(event: carb.events.IEvent):
payload = layers.get_layer_event_payload(event)
if payload.event_type == layers.LayerEventType.LIVE_SESSION_LIST_CHANGED:
if self._base_layer_identifier not in payload.identifiers_or_spec_paths:
return
self._existing_sessions_model.refresh_sessions(force=True)
self._update_dialog_states()
self._layers_event_subscription = layers_interface.get_event_stream().create_subscription_to_pop(
_on_layer_event, name="Session Start Window Events"
)
def destroy(self):
self._layers_interface = None
for button in self._buttons:
button.set_clicked_fn(None)
self._buttons.clear()
if self._window:
self._window.visible = False
self._window = None
if self._existing_sessions_model:
self._existing_sessions_model.destroy()
self._existing_sessions_model = None
self._layers_event_subscription = None
self._existing_sessions_combo = None
self._existing_sessions_empty_hint = None
self._error_label = None
@property
def visible(self):
return self._window and self._window.visible
@visible.setter
def visible(self, value):
if self._window:
self._window.visible = value
if not self._window.visible:
self._existing_sessions_model.stop_channel()
def _on_ok_button_fn(self):
current_session = self._existing_sessions_model.current_session
if not current_session or self._existing_sessions_model.empty():
self._error_label.text = "No Valid Session Selected."
return
omni.kit.clipboard.copy(current_session.shared_link)
self._error_label.text = ""
self.visible = False
def _on_cancel_button_fn(self):
self.visible = False
def _on_key_pressed_fn(self, key, mod, pressed):
if not pressed:
return
func = self._key_functions.get(key)
if func:
func()
def _update_dialog_states(self):
if self._existing_sessions_model.empty():
self._existing_sessions_empty_hint.visible = True
else:
self._existing_sessions_empty_hint.visible = False
self._error_label.text = ""
def _build_ui(self):
"""Construct the window based on the current parameters"""
self._window = ui.Window(
"SHARE LIVE SESSION LINK", visible=False, height=0,
auto_resize=True, dockPreference=ui.DockPreference.DISABLED
)
self._window.flags = (
ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_SCROLLBAR |
ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE
)
self._window.set_key_pressed_fn(self._on_key_pressed_fn)
self._window.flags = self._window.flags | ui.WINDOW_FLAGS_MODAL
self._existing_sessions_model.refresh_sessions(True)
STYLES = {
"Button.Image::confirm_button": {
"image_url": LayerIcons.get("link"), "alignment" : ui.Alignment.RIGHT_CENTER
},
"Label::copy_link": {"font_size": 14},
"Rectangle::hovering": {"border_radius": 2, "margin": 0, "padding": 0},
"Rectangle::hovering:hovered": {"background_color": 0xCC9E9E9E},
}
with self._window.frame:
with ui.VStack(height=0, style=STYLES):
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer(width=20)
self._error_label = ui.Label(
"", name="error_label", style={"color": 0xFF0000CC},
alignment=ui.Alignment.LEFT, word_wrap=True
)
ui.Spacer(width=20)
ui.Spacer(width=0, height=5)
with ui.HStack(height=0):
ui.Spacer(width=20)
with ui.ZStack(height=0):
self._existing_sessions_combo = ui.ComboBox(
self._existing_sessions_model, width=self._window.width - 40, height=0
)
self._existing_sessions_empty_hint = ui.Label(
" No Existing Sessions", alignment=ui.Alignment.LEFT_CENTER, style={"color": 0xFF3F3F3F}
)
ui.Spacer(width=20)
ui.Spacer(width=0, height=30)
with ui.HStack(height=0):
ui.Spacer()
with ui.ZStack(width=120, height=30):
ui.Rectangle(name="hovering")
with ui.HStack():
ui.Spacer()
ui.Label("Copy Link", width=0, name="copy_link")
ui.Spacer(width=8)
ui.Image(LayerIcons.get("link"), width=20)
ui.Spacer()
ok_button = ui.InvisibleButton(name="confirm_button")
ok_button.set_clicked_fn(self._on_ok_button_fn)
self._buttons.append(ok_button)
ui.Spacer()
ui.Spacer(width=0, height=20)
self._update_dialog_states()
| 6,306 |
Python
| 38.41875 | 116 | 0.550428 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/layer_icons.py
|
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from pathlib import Path
class LayerIcons:
"""A singleton that scans the icon folder and returns the icon depending on the type"""
_icons = {}
@staticmethod
def on_startup(extension_path):
current_path = Path(extension_path)
icon_path = current_path.joinpath("icons")
# Read all the svg files in the directory
LayerIcons._icons = {icon.stem: icon for icon in icon_path.glob("*.svg")}
@staticmethod
def get(name, default=None):
"""Checks the icon cache and returns the icon if exists"""
found = LayerIcons._icons.get(name)
if not found and default:
found = LayerIcons._icons.get(default)
if found:
return str(found)
return None
| 1,194 |
Python
| 34.147058 | 91 | 0.688442 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/live_session_user_list.py
|
__all__ = ["LiveSessionUserList"]
import carb
import omni.usd
import omni.client.utils as clientutils
import omni.ui as ui
import omni.kit.usd.layers as layers
import omni.kit.collaboration.presence_layer as pl
from .utils import build_live_session_user_layout, is_extension_loaded
from omni.ui import color as cl
TOOLTIP_STYLE = {
"color": cl("#979797"),
"Tooltip": {"background_color": 0xEE222222}
}
PRESENTER_STYLE = {"background_color": 0xff2032dc} # blue alternative: 0xffff851a
class LiveSessionUserList:
"""Widget to build an user list to show all live session users of interested layer."""
def __init__(self, usd_context: omni.usd.UsdContext, base_layer_identifier: str, **kwargs):
"""
Constructor.
Args:
usd_context (omni.usd.UsdContext): USD Context instance.
base_layer_identifier (str): Interested layer to listen to.
follow_user_with_double_click (bool): Whether to enable follow user function of double click.
Kwargs:
icon_size (int): The width and height of the user icon. 16 pixel by default.
spacing (int): The horizonal spacing between two icons. 2 pixel by default.
show_myself (int): Whether to show local user or not. True by default
show_myself_to_leftmost (bool): Whether to show local user to the left most, or right most otherwise.
True by default.
maximum_users (int): The maximum users to show, and show others with overflow. Unlimited by default.
prim_path (Sdf.Path): Track Live Session for this prim only.
"""
self.__icon_size = kwargs.get("icon_size", 16)
self.__spacing = kwargs.get("spacing", 2)
self.__show_myself = kwargs.get("show_myself", True)
self.__show_myself_to_leftmost = kwargs.get("show_myself_to_leftmost", True)
self.__maximum_count = kwargs.get("maximum_users", None)
self.__follow_user_with_double_click = kwargs.get("follow_user_with_double_click", False)
timeline_ext_loaded = is_extension_loaded("omni.timeline.live_session")
self.__allow_timeline_settings = kwargs.get("allow_timeline_settings", False) and timeline_ext_loaded
self.__prim_path = kwargs.get("prim_path", None)
self.__base_layer_identifier = base_layer_identifier
self.__usd_context = usd_context
self.__layers = layers.get_layers(usd_context)
self.__live_syncing = layers.get_live_syncing()
self.__layers_event_subscriptions = []
self.__main_layout: ui.HStack = ui.HStack(width=0, height=0)
self.__all_user_layouts = {}
self.__overflow = None
self.__overflow_button = None
self.__initialize()
@property
def layout(self) -> ui.HStack:
return self.__main_layout
def track_layer(self, layer_identifier):
"""Switches the base layer to listen to."""
if self.__base_layer_identifier != layer_identifier:
self.__base_layer_identifier = layer_identifier
self.__initialize()
def empty(self):
return len(self.__all_user_layouts) == 0
def __initialize(self):
if not clientutils.is_local_url(self.__base_layer_identifier):
for event in [
layers.LayerEventType.LIVE_SESSION_STATE_CHANGED,
layers.LayerEventType.LIVE_SESSION_USER_JOINED,
layers.LayerEventType.LIVE_SESSION_USER_LEFT,
]:
layers_event_subscription = self.__layers.get_event_stream().create_subscription_to_pop_by_type(
event, self.__on_layers_event,
name=f"omni.kit.widget.live_session_management.LiveSessionUserList {str(event)}"
)
self.__layers_event_subscriptions.append(layers_event_subscription)
else:
self.__layers_event_subscriptions = []
self.__build_ui()
def __is_in_session(self):
if self.__prim_path:
return self.__live_syncing.is_prim_in_live_session(self.__prim_path, self.__base_layer_identifier)
else:
return self.__live_syncing.is_layer_in_live_session(self.__base_layer_identifier)
def __build_myself(self):
current_live_session = self.__live_syncing.get_current_live_session(self.__base_layer_identifier)
if not current_live_session:
return
logged_user = current_live_session.logged_user
with ui.ZStack(width=0, height=0):
with ui.HStack():
ui.Spacer()
self.__build_user_layout_or_overflow(current_live_session, logged_user, True, spacing=0)
ui.Spacer()
if self.__is_presenting(logged_user):
with ui.VStack():
ui.Spacer()
with ui.HStack(height=2, width=24):
ui.Rectangle(
height=2, width=12, alignment=ui.Alignment.BOTTOM, style={"background_color": 0xff00b86b}
)
ui.Rectangle(
height=2, width=12, alignment=ui.Alignment.BOTTOM, style=PRESENTER_STYLE
)
else:
with ui.VStack():
ui.Spacer()
ui.Rectangle(
height=2, width=24, alignment=ui.Alignment.BOTTOM, style={"background_color": 0xff00b86b}
)
def __build_ui(self):
# Destroyed
if not self.__main_layout:
return
self.__overflow = False
self.__main_layout.clear()
self.__all_user_layouts.clear()
self.__overflow_button = None
if not self.__is_in_session():
return
current_live_session = self.__live_syncing.get_current_live_session(self.__base_layer_identifier)
with self.__main_layout:
if self.__show_myself and self.__show_myself_to_leftmost:
self.__build_myself()
for peer_user in current_live_session.peer_users:
self.__build_user_layout_or_overflow(current_live_session, peer_user, False, self.__spacing)
if self.__overflow:
break
if self.__show_myself and not self.__show_myself_to_leftmost:
ui.Spacer(self.__spacing)
self.__build_myself()
if self.empty():
self.__main_layout.visible = False
else:
self.__main_layout.visible = True
@carb.profiler.profile
def __on_layers_event(self, event):
payload = layers.get_layer_event_payload(event)
if payload.event_type == layers.LayerEventType.LIVE_SESSION_STATE_CHANGED:
if not payload.is_layer_influenced(self.__base_layer_identifier):
return
if self.__allow_timeline_settings:
import omni.timeline.live_session
timeline_session = omni.timeline.live_session.get_timeline_session()
if timeline_session is not None:
timeline_session.add_presenter_changed_fn(self.__on_presenter_changed)
self.__build_ui()
elif (
payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_JOINED or
payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_LEFT
):
if not payload.is_layer_influenced(self.__base_layer_identifier):
return
if not self.__is_in_session():
return
current_live_session = self.__live_syncing.get_current_live_session(self.__base_layer_identifier)
user_id = payload.user_id
if payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_LEFT:
self.__all_user_layouts.pop(user_id, None)
# FIXME: omni.ui does not support to remove single child.
self.__build_ui()
else:
if user_id in self.__all_user_layouts or self.__overflow:
# OMFP-2909: Refresh overflow button to rebuild tooltip.
if self.__overflow and self.__overflow_button:
self.__overflow_button.set_tooltip_fn(self.__build_tooltip)
return
user_info = current_live_session.get_peer_user_info(user_id)
if not user_info:
return
self.__main_layout.add_child(
self.__build_user_layout_or_overflow(current_live_session, user_info, False, self.__spacing)
)
def destroy(self): # pragma: no cover
self.__overflow_button = None
self.__main_layout = None
self.__layers_event_subscriptions = []
self.__layers = None
self.__live_syncing = None
self.__user_menu = None
self.__all_user_layouts.clear()
def __on_follow_user(
self, x : float, y : float, button : int, modifier, user_info: layers.LiveSessionUser
):
if button != int(carb.input.MouseInput.LEFT_BUTTON): # only left MB click
return
current_live_session = self.__live_syncing.get_current_live_session(self.__base_layer_identifier)
if not current_live_session or current_live_session.logged_user_id == user_info.user_id:
return
presence_layer = pl.get_presence_layer_interface(self.__usd_context)
if presence_layer:
presence_layer.enter_follow_mode(user_info.user_id)
def __on_mouse_clicked(
self, x : float, y : float, button : int, modifier, user_info: layers.LiveSessionUser
):
if button == int(carb.input.MouseInput.RIGHT_BUTTON): # right click to open menu
import omni.timeline.live_session
timeline_session = omni.timeline.live_session.get_timeline_session()
if timeline_session is not None and timeline_session.am_i_owner():
self.__user_menu = ui.Menu("global_live_timeline_user")
show = False
with self.__user_menu:
if timeline_session.is_presenter(user_info) and not timeline_session.is_owner(user_info):
ui.MenuItem(
"Withdraw Timeline Presenter",
triggered_fn=lambda *args: self.__set_presenter(timeline_session, timeline_session.owner)
)
show = True
elif not timeline_session.is_presenter(user_info):
ui.MenuItem(
"Set as Timeline Presenter",
triggered_fn=lambda *args: self.__set_presenter(timeline_session, user_info)
)
show = True
if show:
self.__user_menu.show()
def __set_presenter(self, timeline_session, user_info: layers.LiveSessionUser):
timeline_session.presenter = user_info
def __is_presenting(self, user_info: layers.LiveSessionUser) -> bool:
if not self.__allow_timeline_settings:
return False
timeline_session = omni.timeline.live_session.get_timeline_session()
return timeline_session.is_presenter(user_info) if timeline_session is not None else False
def __on_presenter_changed(self, _):
self.__build_ui()
def __build_user_layout(
self, live_session: layers.LiveSession, user_info: layers.LiveSessionUser, me: bool, spacing=2
):
if me:
tooltip = f"{user_info.user_name} - Me"
if live_session.merge_permission:
tooltip += " (owner)"
else:
tooltip = f"{user_info.user_name} ({user_info.from_app})"
if not live_session.merge_permission and live_session.owner == user_info.user_name:
tooltip += " - owner"
layout = ui.ZStack(width=0, height=0)
with layout:
with ui.HStack():
ui.Spacer(width=spacing)
user_layout = build_live_session_user_layout(
user_info, self.__icon_size, tooltip, self.__on_follow_user if self.__follow_user_with_double_click else None,
self.__on_mouse_clicked if self.__allow_timeline_settings else None
)
user_layout.set_style(TOOLTIP_STYLE)
current_live_session = self.__live_syncing.get_current_live_session(self.__base_layer_identifier)
logged_user = current_live_session.logged_user
if logged_user.user_id != user_info.user_id and self.__is_presenting(user_info):
with ui.VStack():
ui.Spacer()
ui.Rectangle(
height=2, width=24, alignment=ui.Alignment.BOTTOM, style=PRESENTER_STYLE
)
return layout
def __build_tooltip(self): # pragma: no cover
live_session = self.__live_syncing.get_current_live_session(self.__base_layer_identifier)
if not live_session:
return
total_users = len(live_session.peer_users)
if self.__show_myself:
total_users += 1
with ui.VStack():
with ui.HStack(style={"color": cl("#757575")}):
ui.Spacer()
ui.Label(f"{total_users} Users Connected", style={"font_size": 12})
ui.Spacer()
ui.Spacer(height=0)
ui.Separator(style={"color": cl("#4f4f4f")})
ui.Spacer(height=4)
all_users = []
if self.__show_myself:
all_users = [live_session.logged_user]
all_users.extend(live_session.peer_users)
for user in all_users:
item_title = f"{user.user_name} ({user.from_app})"
if live_session.owner == user.user_name:
item_title += " - owner"
with ui.HStack():
build_live_session_user_layout(
user, self.__icon_size, "", self.__on_follow_user if self.__follow_user_with_double_click else None,
self.__on_mouse_clicked if self.__allow_timeline_settings else None
)
ui.Spacer(width=4)
ui.Label(item_title, style={"font_size": 14})
ui.Spacer(height=2)
@carb.profiler.profile
def __build_user_layout_or_overflow(
self, live_session: layers.LiveSession, user_info: layers.LiveSessionUser, me: bool, spacing=2
): # pragma: no cover
current_count = len(self.__all_user_layouts)
if self.__overflow:
return None
if self.__maximum_count is not None and current_count >= self.__maximum_count:
layout = ui.HStack(width=0)
with layout:
ui.Spacer(width=4)
with ui.ZStack():
ui.Label("...", style={"font_size": 16}, aligment=ui.Alignment.V_CENTER)
self.__overflow_button = ui.InvisibleButton(style=TOOLTIP_STYLE)
self.__overflow_button.set_tooltip_fn(self.__build_tooltip)
self.__overflow = True
else:
layout = self.__build_user_layout(live_session, user_info, me, spacing)
self.__all_user_layouts[user_info.user_id] = layout
self.__main_layout.visible = True
self.__overflow_button = None
return layout
| 15,529 |
Python
| 42.379888 | 130 | 0.57267 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/live_session_preferences.py
|
from .utils import QUICK_JOIN_ENABLED
from .utils import SESSION_LIST_SELECT, SESSION_LIST_SELECT_DEFAULT_SESSION, SESSION_LIST_SELECT_LAST_SESSION
import carb.settings
import omni.ui as ui
from omni.kit.widget.settings import SettingType
from omni.kit.window.preferences import PreferenceBuilder
class LiveSessionPreferences(PreferenceBuilder):
SETTING_PAGE_NAME = "Live"
def __init__(self):
super().__init__(LiveSessionPreferences.SETTING_PAGE_NAME)
self._settings = carb.settings.get_settings()
self._checkbox_quick_join_enabled = None
self._combobox_session_list_select = None
def destroy(self):
self._settings = None
self._checkbox_quick_join_enabled = None
self._combobox_session_list_select = None
def build(self):
self._checkbox_quick_join_enabled = None
self._combobox_session_list_select = None
with ui.VStack(height=0):
with self.add_frame("Join"):
with ui.VStack():
checkbox = self.create_setting_widget(
"Quick Join Enabled",
QUICK_JOIN_ENABLED,
SettingType.BOOL,
tooltip="Quick Join, creates and joins a Default session and bypasses dialogs."
)
self._checkbox_quick_join_enabled = checkbox
ui.Spacer()
combo = self.create_setting_widget_combo(
"Session List Select",
SESSION_LIST_SELECT,
[SESSION_LIST_SELECT_DEFAULT_SESSION, SESSION_LIST_SELECT_LAST_SESSION]
)
self._combobox_session_list_select = combo
ui.Spacer()
ui.Spacer(height=10)
| 1,823 |
Python
| 37.80851 | 109 | 0.582556 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/extension.py
|
__all__ = ["stop_or_show_live_session_widget", "LiveSessionWidgetExtension"]
import asyncio
import os
import carb
import omni.ext
import omni.kit.app
import omni.usd
import omni.client
import omni.ui as ui
import omni.kit.notification_manager as nm
import omni.kit.usd.layers as layers
import omni.kit.clipboard
from typing import Union
from enum import Enum
from omni.kit.widget.prompt import PromptButtonInfo, PromptManager
from .layer_icons import LayerIcons
from .live_session_start_window import LiveSessionStartWindow
from .live_session_end_window import LiveSessionEndWindow
from .utils import is_extension_loaded, join_live_session, is_viewer_only_mode, is_quick_join_enabled
from .join_with_session_link_window import JoinWithSessionLinkWindow
from .share_session_link_window import ShareSessionLinkWindow
from pxr import Sdf
from .live_style import Styles
_extension_instance = None
_debugCollaborationWindow = None
class LiveSessionMenuOptions(Enum):
QUIT_ONLY = 0
MERGE_AND_QUIT = 1
class LiveSessionWidgetExtension(omni.ext.IExt):
def on_startup(self, ext_id):
global _extension_instance
_extension_instance = self
extension_path = omni.kit.app.get_app_interface().get_extension_manager().get_extension_path(ext_id)
self._settings = None
LayerIcons.on_startup(extension_path)
self._live_session_end_window = None
self._live_session_start_window = None
self._join_with_session_link_window = None
self._share_session_link_window = None
self._live_session_menu = None
self._app = omni.kit.app.get_app()
try:
from omni.kit.window.preferences import register_page
from .live_session_preferences import LiveSessionPreferences
self._settings = register_page(LiveSessionPreferences())
except ImportError: # pragma: no cover
pass
Styles.on_startup()
def on_shutdown(self):
global _extension_instance
_extension_instance = None
self._live_session_menu = None
if self._live_session_end_window:
self._live_session_end_window.destroy()
self._live_session_end_window = None
if self._live_session_start_window:
self._live_session_start_window.destroy()
self._live_session_start_window = None
if self._join_with_session_link_window:
self._join_with_session_link_window.destroy()
self._join_with_session_link_window = None
if self._share_session_link_window:
self._share_session_link_window.destroy()
self._share_session_link_window = None
if self._settings:
try:
from omni.kit.window.preferences import unregister_page
unregister_page(self._settings)
except ImportError:
pass
self._settings = None
@staticmethod
def get_instance():
global _extension_instance
return _extension_instance
def _show_live_session_end_window(self, layers_interface: layers.Layers, layer_identifier):
if self._live_session_end_window:
self._live_session_end_window.destroy()
async def show_dialog():
self._live_session_end_window = LiveSessionEndWindow(layers_interface, layer_identifier)
async with self._live_session_end_window:
pass
asyncio.ensure_future(show_dialog())
def _show_join_with_session_link_window(self, layers_interface):
current_session_link = None
# Destroys it to center the window.
if self._join_with_session_link_window:
current_session_link = self._join_with_session_link_window.current_session_link
self._join_with_session_link_window.destroy()
self._join_with_session_link_window = JoinWithSessionLinkWindow(layers_interface)
self._join_with_session_link_window.visible = True
if current_session_link:
self._join_with_session_link_window.current_session_link = current_session_link
def _show_share_session_link_window(self, layers_interface, layer_identifier):
# Destroys it to center the window.
if self._share_session_link_window:
self._share_session_link_window.destroy()
self._share_session_link_window = ShareSessionLinkWindow(layers_interface, layer_identifier)
self._share_session_link_window.visible = True
def _show_live_session_menu_options(self, layers_interface, layer_identifier, is_stage_session, prim_path=None):
live_syncing = layers_interface.get_live_syncing()
current_session = live_syncing.get_current_live_session(layer_identifier)
self._live_session_menu = ui.Menu("global_live_update")
is_omniverse_stage = layer_identifier.startswith("omniverse://")
is_live_prim = prim_path or live_syncing.is_layer_in_live_session(layer_identifier, live_prim_only=True)
with self._live_session_menu:
if is_omniverse_stage:
if current_session:
# If layer is in the live session already, showing `leave` and `end and merge`
ui.MenuItem(
"Leave Session",
triggered_fn=lambda *args: self._on_leave_live_session_menu_options(
layers_interface, LiveSessionMenuOptions.QUIT_ONLY, layer_identifier
),
)
if not is_viewer_only_mode():
ui.MenuItem(
"End and Merge",
triggered_fn=lambda *args: self._on_leave_live_session_menu_options(
layers_interface, LiveSessionMenuOptions.MERGE_AND_QUIT, layer_identifier
),
)
ui.Separator()
else:
# If it's not in the live session, show `join` and `create`.
ui.MenuItem(
"Join Session",
triggered_fn=lambda *args: self._show_live_session_start_window(
layers_interface, layer_identifier, True, prim_path
),
)
ui.MenuItem(
"Create Session",
triggered_fn=lambda *args: self._show_live_session_start_window(
layers_interface, layer_identifier, False, prim_path
),
)
# Don't show those options for live prim
if not is_live_prim:
# If layer_identifier is given, it's to show menu options for sublayer.
# Show `copy` to copy session link. Otherwise, show share session dialog
# to choose session to share.
if is_stage_session:
ui.Separator()
ui.MenuItem(
"Share Session Link",
triggered_fn=lambda *args: self._show_share_session_link_window(
layers_interface, layer_identifier
),
)
elif current_session:
ui.Separator()
ui.MenuItem(
"Copy Session Link",
triggered_fn=lambda *args: self._copy_session_link(layers_interface),
)
# If layer identifier is gven, it will not show `join with session link` menu option.
if is_stage_session and not is_live_prim:
ui.MenuItem(
"Join With Session Link",
triggered_fn=lambda *args: self._show_join_with_session_link_window(layers_interface),
)
if is_extension_loaded("omni.kit.collaboration.debug_options"): # pragma: no cover
ui.Separator()
ui.MenuItem(
"Open Debug Window",
triggered_fn=lambda *args: self._on_open_debug_window(),
)
if is_omniverse_stage and current_session and is_extension_loaded("omni.timeline.live_session"):
ui.Separator()
import omni.timeline.live_session
timeline_session = omni.timeline.live_session.get_timeline_session()
if timeline_session is not None:
session_window = omni.timeline.live_session.get_session_window()
ui.MenuItem(
"Synchronize Timeline",
triggered_fn=lambda *args: self._on_timeline_sync_triggered(
layers_interface, layer_identifier, timeline_session
),
checkable=True,
checked=timeline_session.is_sync_enabled()
)
if timeline_session.am_i_owner():
ui.MenuItem(
"Set Timeline Owner",
triggered_fn=lambda *args: self._on_open_timeline_session_window(
layers_interface, layer_identifier, timeline_session, session_window
),
)
elif not timeline_session.am_i_presenter():
if not self._requested_timeline_control(timeline_session):
ui.MenuItem(
"Request Timeline Ownership",
triggered_fn=lambda *args: self._on_request_timeline_control(timeline_session),
)
else:
ui.MenuItem(
"Withdraw Timeline Ownership Request",
triggered_fn=lambda *args: self._on_withdraw_timeline_control(timeline_session),
)
self._live_session_menu.show()
def _show_live_session_start_window(self, layers_interface, layer_identifier, join_session=None, prim_path=None):
if self._live_session_start_window:
self._live_session_start_window.destroy()
self._live_session_start_window = LiveSessionStartWindow(layers_interface, layer_identifier, prim_path)
self._live_session_start_window.visible = True
if join_session is not None:
self._live_session_start_window.set_focus(join_session)
def _show_session_start_window_or_menu(
self, layers_interface: layers.Layers, show_join_options, layer_identifier, is_stage_session, join_session=None, prim_path=None
):
if show_join_options:
return self._show_live_session_menu_options(
layers_interface, layer_identifier, is_stage_session, prim_path
)
else:
self._show_live_session_start_window(layers_interface, layer_identifier, join_session, prim_path)
return None
def _requested_timeline_control(self, timeline_session) -> bool:
return timeline_session is not None and\
timeline_session.live_session_user in timeline_session.get_request_controls()
def _on_request_timeline_control(self, timeline_session):
if timeline_session is not None:
timeline_session.request_control(True)
def _on_withdraw_timeline_control(self, timeline_session):
if timeline_session is not None:
timeline_session.request_control(False)
def _on_timeline_sync_triggered(
self, layers_interface: layers.Layers,
layer_identifier: str,
timeline_session
):
timeline_session.enable_sync(not timeline_session.is_sync_enabled())
def _on_open_timeline_session_window(
self, layers_interface: layers.Layers,
layer_identifier: str,
timeline_session,
session_window,
):
session_window.show()
def _on_open_debug_window(
self,
): # pragma: no cover
import omni.kit.collaboration.debug_options
from omni.kit.collaboration.debug_options import CollaborationWindow
global _debugCollaborationWindow
if _debugCollaborationWindow is None :
_debugCollaborationWindow = CollaborationWindow(width=480, height=320)
_debugCollaborationWindow.visible = True
def _on_leave_live_session_menu_options(
self, layers_interface: layers.Layers,
options: LiveSessionMenuOptions,
layer_identifier: str,
):
live_syncing = layers_interface.get_live_syncing()
current_session = live_syncing.get_current_live_session(layer_identifier)
if current_session:
if options == LiveSessionMenuOptions.QUIT_ONLY:
if self._can_quit_session_directly(live_syncing, layer_identifier):
live_syncing.stop_live_session(layer_identifier)
else:
PromptManager.post_simple_prompt(
"Leave Session",
f"You are about to leave '{current_session.name}' session.",
PromptButtonInfo("LEAVE", lambda: live_syncing.stop_live_session(layer_identifier)),
PromptButtonInfo("CANCEL")
)
elif options == LiveSessionMenuOptions.MERGE_AND_QUIT:
layers_state = layers_interface.get_layers_state()
is_read_only_on_disk = layers_state.is_layer_readonly_on_disk(layer_identifier)
if current_session.merge_permission and not is_read_only_on_disk:
self._show_live_session_end_window(layers_interface, layer_identifier)
else:
if is_read_only_on_disk:
owner = layers_state.get_layer_owner(layer_identifier)
else:
owner = current_session.owner
logged_user_name = current_session.logged_user_name
if logged_user_name == owner and current_session.merge_permission:
message = f"You currently do not have merge privileges as base layer is read-only on disk."\
" Do you want to quit this live session?"
else:
if is_read_only_on_disk:
message = f"You currently do not have merge privileges as base layer is read-only on disk."\
f" Please contact '{owner}' to grant you write access. Do you want to quit this live session?"
else:
message = f"You currently do not have merge privileges, please contact '{owner}'"\
" to merge any changes from the live session. Do you want to quit this live session?"
PromptManager.post_simple_prompt(
"Permission Denied",
message,
PromptButtonInfo("YES", lambda: live_syncing.stop_live_session(layer_identifier)),
PromptButtonInfo("NO")
)
def _can_quit_session_directly(self, live_syncing: layers.LiveSyncing, layer_identifier):
current_live_session = live_syncing.get_current_live_session(layer_identifier)
if current_live_session:
if current_live_session.peer_users:
return False
layer = Sdf.Find(current_live_session.root)
if layer and len(layer.rootPrims) > 0:
return False
return True
def _copy_session_link(self, layers_interface):
live_syncing = layers_interface.get_live_syncing()
current_session = live_syncing.get_current_live_session()
if not current_session:
return
omni.kit.clipboard.copy(current_session.shared_link)
def _stop_or_show_live_session_widget_internal(
self, layers_interface: layers.Layers,
stop_session_only,
stop_session_forcely,
show_join_options,
layer_identifier,
quick_join="",
prim_path=None
):
usd_context = layers_interface.usd_context
stage = usd_context.get_stage()
# Skips it if stage is not opened.
if not stage:
return None
# By default, it will join live session of tht root layer.
if not layer_identifier:
# If layer identifier is not provided, it's to show global
# menu that includes share sesison link and join session with link.
# Otherwise, it will show menu for the sublayer session only.
is_stage_session = True
root_layer = stage.GetRootLayer()
layer_identifier = root_layer.identifier
else:
is_stage_session = False
layer_handle = Sdf.Find(layer_identifier)
if (
not layer_handle or
(not prim_path and not stage.HasLocalLayer(layer_handle)) or
(prim_path and layer_handle not in stage.GetUsedLayers())
):
nm.post_notification(
"Only a layer opened in the current stage can start a live-sync session.",
status=nm.NotificationStatus.WARNING
)
return None
if not layer_identifier.startswith("omniverse://"):
if is_stage_session and not prim_path:
return self._show_live_session_menu_options(layers_interface, layer_identifier, is_stage_session)
else:
nm.post_notification(
"Only a layer in Nucleus can start a live-sync session.",
status=nm.NotificationStatus.WARNING
)
return None
live_syncing = layers_interface.get_live_syncing()
if not live_syncing.is_layer_in_live_session(layer_identifier):
if not quick_join and not show_join_options:
quick_join = "Default"
elif quick_join and show_join_options:
show_join_options = False
if quick_join:
# This runs when the main live button is pressed.
live_syncing = layers_interface.get_live_syncing()
quick_session = live_syncing.find_live_session_by_name(layer_identifier, quick_join)
if is_quick_join_enabled():
if not quick_session:
quick_session = live_syncing.create_live_session(
layer_identifier=layer_identifier,
name=quick_join
)
if not quick_session:
nm.post_notification(
"Cannot create a Live session on a read only location. Please\n"
"save root file in a writable location.",
status=nm.NotificationStatus.WARNING
)
return None
join_live_session(
layers_interface, layer_identifier, quick_session, prim_path,
is_viewer_only_mode()
)
return None
else:
join_session = True if quick_session is not None else False
return self._show_session_start_window_or_menu(
layers_interface, False, layer_identifier, False, join_session, prim_path
)
else:
return self._show_session_start_window_or_menu(
layers_interface, show_join_options, layer_identifier, is_stage_session, prim_path
)
elif stop_session_forcely:
live_syncing.stop_live_session(layer_identifier)
elif stop_session_only:
self._on_leave_live_session_menu_options(
layers_interface, LiveSessionMenuOptions.QUIT_ONLY, layer_identifier
)
else:
return self._show_live_session_menu_options(layers_interface, layer_identifier, is_stage_session, prim_path)
return None
def stop_or_show_live_session_widget(
usd_context: Union[str, omni.usd.UsdContext] = "",
stop_session_only: bool = False,
stop_session_forcely: bool = False,
show_join_options: bool = True,
layer_identifier: str = None,
quick_join: str = False,
prim_path: Union[str, Sdf.Path] = None,
):
"""Stops current live session or shows widget to join/leave session. If current session is empty, it will show
the session start dialog. If current session is not empty, it will stop session directly or show stop session menu.
Args:
usd_context: The current usd context to operate on.
stop_session_only: If it's true, it will ask user to stop session if session is not empty without showing merge options.
If it's false, it will show both leave and merge session options.
stop_session_forcely: If it's true, it will stop session forcely even if current sesison is not empty.
Otherwise, it will show leave session or both leave and merge options that's dependent on
if stop_session_only is true or false.
show_join_options: If it's true, it will show menu options.
If it's false, it will show session dialog directly.
This option is only used when layer is not in a live session. If both quick_join and
this param have the same value, it will do quick join.
layer_identifier: By default, it will join/stop the live session of the root layer.
If layer_identifier is not None, it will join/stop the live session for the specific sublayer.
quick_join: Quick Join / Leave a session without bringing up a dialog.
This option is only used when layer is not in a live session. If both show_join_options and
this param have the same value, this param will be True.
prim_path: If prim path is specified, it will join live session for the prim instead of sublayers. Only prim with
references or payloads supports to join a live session. Prim path is not needed when it's to
stop a live session.
Returns:
It will return the menu widgets created if it needs to create options menu. Otherwise, it will return None.
"""
instance = LiveSessionWidgetExtension.get_instance()
if not instance: # pragma: no cover
carb.log_error("omni.kit.widget.live_session_management extension must be enabled.")
return
layers_interface = layers.get_layers(usd_context)
return instance._stop_or_show_live_session_widget_internal(
layers_interface,
stop_session_only,
stop_session_forcely,
show_join_options,
layer_identifier,
quick_join=quick_join,
prim_path=prim_path
)
| 23,531 |
Python
| 44.34104 | 135 | 0.576984 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/__init__.py
|
from .extension import *
from .utils import *
from .live_session_user_list import *
from .live_session_model import *
from .live_session_camera_follower_list import *
| 166 |
Python
| 32.399994 | 48 | 0.771084 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/file_picker.py
|
import omni
import carb
import os
import omni.client
import omni.kit.notification_manager as nm
from omni.kit.widget.prompt import PromptButtonInfo, PromptManager
from .filebrowser import FileBrowserMode, FileBrowserSelectionType, FileBrowserUI
class FilePicker:
def __init__(self, title, mode, file_type, filter_options, save_extensions=None):
self._mode = mode
self._ui_handler = None
self._app = omni.kit.app.get_app()
self._open_handler = None
self._cancel_handler = None
self._save_extensions = save_extensions
self._ui_handler = FileBrowserUI(
title, mode, file_type, filter_options, enable_versioning_pane=(mode == FileBrowserMode.OPEN)
)
def _show_prompt(self, file_path, file_save_handler):
def _on_file_save():
if file_save_handler:
file_save_handler(file_path, True)
PromptManager.post_simple_prompt(
f'{omni.kit.ui.get_custom_glyph_code("${glyphs}/exclamation.svg")} Overwrite',
f"File {os.path.basename(file_path)} already exists, do you want to overwrite it?",
ok_button_info=PromptButtonInfo("YES", _on_file_save),
cancel_button_info=PromptButtonInfo("NO")
)
def _save_and_prompt_if_exists(self, file_path, file_save_handler=None):
result, _ = omni.client.stat(file_path)
if result == omni.client.Result.OK:
self._show_prompt(file_path, file_save_handler)
elif file_save_handler:
file_save_handler(file_path, False)
def _on_file_open(self, path, filter_index=-1):
if self._mode == FileBrowserMode.SAVE:
_, ext = os.path.splitext(path)
if (
filter_index >= 0
and self._save_extensions
and filter_index < len(self._save_extensions)
and ext not in self._save_extensions
):
path += self._save_extensions[filter_index]
self._save_and_prompt_if_exists(path, self._open_handler)
elif self._open_handler:
self._open_handler(path, False)
def _on_cancel_open(self):
if self._cancel_handler:
self._cancel_handler()
def set_file_selected_fn(self, file_open_handler):
self._open_handler = file_open_handler
def set_cancel_fn(self, cancel_handler):
self._cancel_handler = cancel_handler
def show(self, dir=None, filename=None):
if self._ui_handler:
if dir:
self._ui_handler.set_current_directory(dir)
if filename:
self._ui_handler.set_current_filename(filename)
self._ui_handler.open(self._on_file_open, self._on_cancel_open)
def hide(self):
if self._ui_handler:
self._ui_handler.hide()
def set_current_directory(self, dir):
if self._ui_handler:
self._ui_handler.set_current_directory(dir)
def set_current_filename(self, filename):
if self._ui_handler:
self._ui_handler.set_current_filename(filename)
def get_current_filename(self):
if self._ui_handler:
return self._ui_handler.get_current_filename()
return None
def destroy(self):
if self._ui_handler:
self._ui_handler.destroy()
self._ui_handler = None
| 3,413 |
Python
| 33.836734 | 105 | 0.600938 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/utils.py
|
__all__ = ["build_live_session_user_layout", "is_viewer_only_mode", "VIEWER_ONLY_MODE_SETTING"]
import asyncio
import carb
import os
import omni.usd
import omni.kit.app
import omni.ui as ui
import omni.kit.usd.layers as layers
from omni.kit.async_engine import run_coroutine
from omni.kit.widget.prompt import PromptManager, PromptButtonInfo
from pxr import Sdf
from typing import Union, List
# When this setting is True, it will following the rules:
# * When joining a live session, if the user has unsaved changes,
# skip the dialog and automatically reload the stage, then join the session.
# * When creating a live session, if the user has unsaved changes,
# skip the dialog and automatically reload the stage, then create the session.
# * When leaving a live session, do not offer to merge changes,
# instead reload the stage to its original state
VIEWER_ONLY_MODE_SETTING = "/exts/omni.kit.widget.live_session_management/viewer_only_mode"
# When this setting is True, it will show the Join/Create Session dialog wqhen the quick live button is pressed.
# When this setting if False, it will auto Create Session or Join with no dialog shown.
QUICK_JOIN_ENABLED = "/exts/omni.kit.widget.live_session_management/quick_join_enabled"
SESSION_LIST_SELECT = "/exts/omni.kit.widget.live_session_management/session_list_select"
SESSION_LIST_SELECT_DEFAULT_SESSION = "DefaultSession"
SESSION_LIST_SELECT_LAST_SESSION = "LastSession"
def is_viewer_only_mode():
return carb.settings.get_settings().get(VIEWER_ONLY_MODE_SETTING) or False
def is_quick_join_enabled():
return carb.settings.get_settings().get(QUICK_JOIN_ENABLED) or False
def get_session_list_select():
return carb.settings.get_settings().get(SESSION_LIST_SELECT)
def join_live_session(layers_interface, layer_identifier, current_session, prim_path=None, force_reload=False):
layers_state = layers_interface.get_layers_state()
live_syncing = layers_interface.get_live_syncing()
layer_handle = Sdf.Find(layer_identifier)
def fetch_and_join(layer_identifier):
with Sdf.ChangeBlock():
layer = Sdf.Find(layer_identifier)
if layer:
layer.Reload(True)
if layers_state.is_auto_reload_layer(layer_identifier):
layers_state.remove_auto_reload_layer(layer_identifier)
return live_syncing.join_live_session(current_session, prim_path)
async def post_simple_prompt(title, text, ok_button_info, cancel_button_info):
await omni.kit.app.get_app().next_update_async()
PromptManager.post_simple_prompt(
title, text,
ok_button_info=ok_button_info,
cancel_button_info=cancel_button_info
)
is_outdated = layers_state.is_layer_outdated(layer_identifier)
if force_reload and (is_outdated or layer_handle.dirty):
fetch_and_join(layer_identifier)
elif is_outdated:
asyncio.ensure_future(
post_simple_prompt(
"Join Session",
"The file you would like to go live on is not up to date, "
"a newer version must be fetched for joining a live session. "
"Press Fetch to get the most recent version or use Cancel "
"if you would like to save a copy first.",
ok_button_info=PromptButtonInfo(
"Fetch",
lambda: fetch_and_join(layer_identifier)
),
cancel_button_info=PromptButtonInfo("Cancel")
)
)
elif layer_handle.dirty:
asyncio.ensure_future(
post_simple_prompt(
"Join Session",
"There are unsaved changes to your file. Joining this live session will discard any unsaved changes.",
ok_button_info=PromptButtonInfo(
"Join",
lambda: fetch_and_join(layer_identifier)
),
cancel_button_info=PromptButtonInfo("Cancel")
)
)
else:
if layers_state.is_auto_reload_layer(layer_identifier):
layers_state.remove_auto_reload_layer(layer_identifier)
return live_syncing.join_live_session(current_session, prim_path)
return True
def is_extension_loaded(extansion_name: str) -> bool:
"""
Returns True if the extension with the given name is loaded.
"""
def is_ext(id: str, extension_name: str) -> bool:
id_name = id.split("-")[0]
return id_name == extension_name
app = omni.kit.app.get_app_interface()
ext_manager = app.get_extension_manager()
extensions = ext_manager.get_extensions()
loaded = next((ext for ext in extensions if is_ext(ext["id"], extansion_name) and ext["enabled"]), None)
return not not loaded
def build_live_session_user_layout(user_info: layers.LiveSessionUser, size=16, tooltip = "", on_double_click_fn: callable = None, on_mouse_click_fn: callable = None) -> ui.ZStack:
"""Builds user icon."""
user_layout = ui.ZStack(width=size, height=size)
with user_layout:
circle = ui.Circle(
style={"background_color": ui.color(*user_info.user_color)}
)
if on_double_click_fn:
circle.set_mouse_double_clicked_fn(lambda x, y, b, m, user_info_t=user_info: on_double_click_fn( x, y, b, m, user_info_t))
if on_mouse_click_fn:
circle.set_mouse_pressed_fn(lambda x, y, b, m, user_info_t=user_info: on_mouse_click_fn( x, y, b, m, user_info_t))
ui.Label(
layers.get_short_user_name(user_info.user_name), style={"font_size": size - 5, "color": 0xFFFFFFFF},
alignment=ui.Alignment.CENTER
)
if tooltip:
user_layout.set_tooltip(tooltip)
return user_layout
def reload_outdated_layers(
layer_identifiers: Union[str, List[str]], usd_context_name_or_instance: Union[str, omni.usd.UsdContext] = None
) -> None:
"""Reloads outdated layer. It will show prompt to user if layer is in a Live Session."""
if isinstance(usd_context_name_or_instance, str):
usd_context = omni.usd.get_context(usd_context_name_or_instance)
elif isinstance(usd_context_name_or_instance, omni.usd.UsdContext):
usd_context = usd_context_name_or_instance
elif not usd_context_name_or_instance:
usd_context = omni.usd.get_context()
if not usd_context:
carb.log_error("Failed to reload layer as usd context is not invalid.")
return
if isinstance(layer_identifiers, str):
layer_identifiers = [layer_identifiers]
live_syncing = layers.get_live_syncing(usd_context)
layers_state = layers.get_layers_state(usd_context)
all_layer_ids = layers_state.get_all_outdated_layer_identifiers()
if not all_layer_ids:
return
layer_identifiers = [layer_id for layer_id in layer_identifiers if layer_id in all_layer_ids]
if not layer_identifiers:
return
count = 0
for layer_identifier in layer_identifiers:
if live_syncing.is_layer_in_live_session(layer_identifier):
count += 1
if count == 1:
title = f"{os.path.basename(layer_identifier)} is in a Live Session"
else:
title = "Reload Layers In Live Session"
def reload_layers(layer_identifiers):
async def reload(layer_identifiers):
layers.LayerUtils.reload_all_layers(layer_identifiers)
run_coroutine(reload(layer_identifiers))
if count != 0:
PromptManager.post_simple_prompt(
title,
"Reloading live layers has performance implications and some live edits may be lost - OK to proceed?",
PromptButtonInfo("YES", lambda: reload_layers(layer_identifiers)),
PromptButtonInfo("NO")
)
else:
reload_layers(layer_identifiers)
| 7,853 |
Python
| 36.4 | 179 | 0.657328 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/join_with_session_link_window.py
|
__all__ = ["JoinWithSessionLinkWindow"]
import asyncio
import carb
import omni.kit.usd.layers as layers
import omni.ui as ui
import omni.kit.notification_manager as nm
import omni.kit.app
import omni.kit.clipboard
from pxr import Usd
from .layer_icons import LayerIcons
class JoinWithSessionLinkWindow:
def __init__(self, layers_interface: layers.Layers):
self._window = None
self._layers_interface = layers_interface
self._buttons = []
self._session_link_input_field = None
self._session_link_input_hint = None
self._error_label = None
self._session_link_begin_edit_cb = None
self._session_link_end_edit_cb = None
self._session_link_edit_cb = None
self._key_functions = {
int(carb.input.KeyboardInput.ENTER): self._on_ok_button_fn,
int(carb.input.KeyboardInput.ESCAPE): self._on_cancel_button_fn
}
self._build_ui()
def destroy(self):
self._layers_interface = None
for button in self._buttons:
button.set_clicked_fn(None)
self._buttons.clear()
if self._window:
self._window.visible = False
self._window = None
self._session_link_input_hint = None
self._session_link_input_field = None
self._session_link_begin_edit_cb = None
self._session_link_end_edit_cb = None
self._session_link_edit_cb = None
self._error_label = None
@property
def visible(self):
return self._window and self._window.visible
@visible.setter
def visible(self, value):
if self._window:
self._window.visible = value
if value:
async def focus_field():
await omni.kit.app.get_app().next_update_async()
if self._session_link_input_field:
self._session_link_input_field.focus_keyboard()
asyncio.ensure_future(focus_field())
@property
def current_session_link(self):
if self._session_link_input_field:
return self._session_link_input_field.model.get_value_as_string()
return ""
@current_session_link.setter
def current_session_link(self, value):
if self._session_link_input_field:
self._session_link_input_field.model.set_value(value)
def _validate_session_link(self, str):
return str and Usd.Stage.IsSupportedFile(str)
def _on_ok_button_fn(self):
if not self._update_button_status():
return
self._error_label.text = ""
self.visible = False
session_link = self._session_link_input_field.model.get_value_as_string()
session_link = session_link.strip()
live_syncing = self._layers_interface.get_live_syncing()
async def open_stage_with_live_session(live_syncing, session_link):
(success, error) = await live_syncing.open_stage_with_live_session_async(session_link)
if not success:
nm.post_notification(f"Failed to open stage {session_link} with live session: {error}.")
asyncio.ensure_future(open_stage_with_live_session(live_syncing, session_link))
def _on_cancel_button_fn(self):
self.visible = False
def _on_key_pressed_fn(self, key, mod, pressed):
if not pressed:
return
func = self._key_functions.get(key)
if func:
func()
def _update_button_status(self):
if not self._session_link_input_field:
return False
session_link = self._session_link_input_field.model.get_value_as_string()
session_link = session_link.strip()
join_button = self._buttons[0]
if not self._validate_session_link(session_link):
if session_link:
self._error_label.text = "The link is not supported for USD."
else:
self._error_label.text = ""
join_button.enabled = False
else:
self._error_label.text = ""
join_button.enabled = True
if not session_link:
self._session_link_input_hint.visible = True
else:
self._session_link_input_hint.visible = False
return join_button.enabled
def _on_session_link_begin_edit(self, model):
self._update_button_status()
def _on_session_link_end_edit(self, model):
self._update_button_status()
def _on_session_link_edit(self, model):
self._update_button_status()
def _on_paste_link_fn(self):
link = omni.kit.clipboard.paste()
if link:
self._session_link_input_field.model.set_value(link)
def _build_ui(self):
"""Construct the window based on the current parameters"""
self._window = ui.Window(
"JOIN LIVE SESSION WITH LINK", visible=False, width=500, height=0,
auto_resize=True, dockPreference=ui.DockPreference.DISABLED
)
self._window.flags = (
ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_SCROLLBAR |
ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE
)
self._window.set_key_pressed_fn(self._on_key_pressed_fn)
self._window.flags = self._window.flags | ui.WINDOW_FLAGS_MODAL
STYLES = {
"Rectangle::hovering": {"background_color": 0x0, "border_radius": 2, "margin": 0, "padding": 0},
"Rectangle::hovering:hovered": {"background_color": 0xFF9E9E9E},
"Button.Image::paste_button": {"image_url": LayerIcons().get("paste"), "color": 0xFFD0D0D0},
"Button::paste_button": {"background_color": 0x0, "margin": 0},
"Button::paste_button:checked": {"background_color": 0x0},
"Button::paste_button:hovered": {"background_color": 0x0},
"Button::paste_button:pressed": {"background_color": 0x0},
}
with self._window.frame:
with ui.VStack(height=0, style=STYLES):
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer(width=20)
self._error_label = ui.Label("", name="error_label", style={"color": 0xFF0000CC}, alignment=ui.Alignment.LEFT, word_wrap=True)
ui.Spacer(width=20)
ui.Spacer(width=0, height=5)
with ui.ZStack(height=0):
with ui.HStack(height=0):
ui.Spacer(width=20)
with ui.ZStack(width=20, height=20):
ui.Rectangle(name="hovering")
paste_link_button = ui.ToolButton(name="paste_button", image_width=20, image_height=20)
paste_link_button.set_clicked_fn(self._on_paste_link_fn)
ui.Spacer(width=4)
with ui.VStack():
ui.Spacer()
with ui.ZStack(height=0):
self._session_link_input_field = ui.StringField(
name="new_session_link_field", width=self._window.width - 40, height=0
)
self._session_link_input_hint = ui.Label(
" Paste Live Session Link Here", alignment=ui.Alignment.LEFT_CENTER,
style={"color": 0xFF3F3F3F}
)
self._session_link_begin_edit_cb = self._session_link_input_field.model.subscribe_begin_edit_fn(
self._on_session_link_begin_edit
)
self._session_link_end_edit_cb = self._session_link_input_field.model.subscribe_end_edit_fn(
self._on_session_link_end_edit
)
self._session_link_edit_cb = self._session_link_input_field.model.subscribe_value_changed_fn(
self._on_session_link_edit
)
ui.Spacer()
ui.Spacer(width=20)
ui.Spacer(width=0, height=30)
with ui.HStack(height=0):
ui.Spacer(height=0)
ok_button = ui.Button("JOIN", name="confirm_button", width=120, height=0)
ok_button.set_clicked_fn(self._on_ok_button_fn)
cancel_button = ui.Button("CANCEL", name="cancel_button", width=120, height=0)
cancel_button.set_clicked_fn(self._on_cancel_button_fn)
self._buttons.append(ok_button)
self._buttons.append(cancel_button)
ui.Spacer(height=0, width=20)
ui.Spacer(width=0, height=20)
# 0 for ok button, 0 for cancel button and appends paste link button at last
self._buttons.append(paste_link_button)
self._update_button_status()
| 9,226 |
Python
| 40.008889 | 146 | 0.54574 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/reload_widget.py
|
__all__ = ["build_reload_widget"]
import carb
import omni.usd
import omni.kit.app
import omni.ui as ui
import omni.kit.usd.layers as layers
import weakref
from functools import partial
from typing import Union
from .live_style import Styles
from .layer_icons import LayerIcons
from .utils import reload_outdated_layers
from omni.kit.async_engine import run_coroutine
class ReloadWidgetWrapper(ui.ZStack):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.auto_reload_menu = None
def __del__(self):
if self.auto_reload_menu:
self.auto_reload_menu.hide()
self.auto_reload_menu = None
def show_reload_menu(layer_identifier, usd_context, widget, button, global_auto):
"""Creates and shows a reload menu relative to widget position"""
layers_state = layers.get_layers_state(usd_context)
live_syncing = layers.get_live_syncing()
is_outdated = layers_state.is_layer_outdated(layer_identifier)
in_session = live_syncing.is_layer_in_live_session(layer_identifier)
def toggle_auto_reload(layer_identifier, widget):
async def toggle(layer_identifier):
is_auto = layers_state.is_auto_reload_layer(layer_identifier)
if not is_auto:
layers_state.add_auto_reload_layer(layer_identifier)
widget.set_style(Styles.RELOAD_AUTO)
button.tooltip = "Auto Reload Enabled"
else:
layers_state.remove_auto_reload_layer(layer_identifier)
widget.set_style(Styles.RELOAD_BTN)
button.tooltip = "Reload"
run_coroutine(toggle(layer_identifier))
def reload_layer(layer_identifier):
reload_outdated_layers(layer_identifier, layers_state._usd_context)
auto_reload_menu = ui.Menu("auto_reload_menu")
with auto_reload_menu:
ui.MenuItem(
"Reload Layer",
triggered_fn=lambda *args: reload_layer(layer_identifier),
enabled=is_outdated,
visible=not global_auto
)
ui.MenuItem(
"Auto Reload",
triggered_fn=lambda *args: toggle_auto_reload(layer_identifier, widget),
checkable=True,
checked=layers_state.is_auto_reload_layer(layer_identifier),
visible=not global_auto,
enabled=not in_session
)
_x = widget.screen_position_x
_y = widget.screen_position_y
_h = widget.computed_height
auto_reload_menu.show_at(_x - 95, _y + _h / 2 + 2)
return auto_reload_menu
def build_reload_widget(
layer_identifier: str,
usd_context_name_or_instance: Union[str, omni.usd.UsdContext] = None,
is_outdated=False,
is_auto=False,
global_auto=False
) -> None:
"""Builds reload widget."""
if isinstance(usd_context_name_or_instance, str):
usd_context = omni.usd.get_context(usd_context_name_or_instance)
elif isinstance(usd_context_name_or_instance, omni.usd.UsdContext):
usd_context = usd_context_name_or_instance
elif not usd_context_name_or_instance:
usd_context = omni.usd.get_context()
if not usd_context:
carb.log_error("Failed to reload layer as usd context is not invalid.")
return
reload_stack = ReloadWidgetWrapper(width=0, height=0)
if global_auto:
is_auto = global_auto
reload_stack.name = "reload-auto" if is_auto else "reload-outd" if is_outdated else "reload"
reload_stack.set_style(Styles.RELOAD_AUTO if is_auto and not is_outdated else Styles.RELOAD_OTD if is_outdated else Styles.RELOAD_BTN)
with reload_stack:
with ui.VStack(width=0, height=0):
ui.Spacer(width=22, height=12)
with ui.HStack(width=0):
ui.Spacer(width=16)
ui.Image(
LayerIcons.get("drop_down"),
width=6, height=6, alignment=ui.Alignment.RIGHT_BOTTOM,
name="drop_down"
)
ui.Image(LayerIcons.get("reload"), width=20, name="reload")
tooltip = "Auto Reload All Enabled" if global_auto else "Auto Reload Enabled" if is_auto else "Reload"
if is_outdated:
tooltip = "Reload Outdated"
reload_button = ui.InvisibleButton(width=20, tooltip=tooltip)
def on_reload_clicked(layout_weakref, x, y, b, m):
if (b == 0):
reload_outdated_layers(layer_identifier, usd_context)
return
auto_reload_menu = show_reload_menu(layer_identifier, usd_context, reload_stack, reload_button, global_auto)
if layout_weakref():
# Hold the menu handle to release it along with the stack.
layout_weakref().auto_reload_menu = auto_reload_menu
layout_weakref = weakref.ref(reload_stack)
reload_button.set_mouse_pressed_fn(partial(on_reload_clicked, layout_weakref))
return reload_stack
| 4,919 |
Python
| 34.142857 | 138 | 0.639561 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/live_session_start_window.py
|
import asyncio
import carb
import omni.kit.app
import omni.kit.usd.layers as layers
import omni.ui as ui
import re
from .layer_icons import LayerIcons
from .utils import join_live_session, is_viewer_only_mode, get_session_list_select, SESSION_LIST_SELECT_DEFAULT_SESSION
from omni.kit.widget.prompt import PromptButtonInfo, PromptManager
from pxr import Sdf
from .live_session_model import LiveSessionModel
class LiveSessionStartWindow:
def __init__(self, layers_interface: layers.Layers, layer_identifier, prim_path):
self._window = None
self._layers_interface = layers_interface
self._base_layer_identifier = layer_identifier
self._live_prim_path = prim_path
self._buttons = []
self._existing_sessions_combo = None
self._session_name_input_field = None
self._session_name_input_hint = None
self._error_label = None
self._session_name_begin_edit_cb = None
self._session_name_end_edit_cb = None
self._session_name_edit_cb = None
self._existing_sessions_model = LiveSessionModel(self._layers_interface, layer_identifier)
self._participants_list = None
self._participants_layout = None
self._existing_sessions_model.set_user_update_callback(self._on_channel_users_update)
self._existing_sessions_model.add_value_changed(self._on_session_list_changed)
self._update_user_list_task: asyncio.Future = None
self._join_create_radios = None
self._key_functions = {
int(carb.input.KeyboardInput.ENTER): self._on_ok_button_fn,
int(carb.input.KeyboardInput.ESCAPE): self._on_cancel_button_fn
}
self._build_ui()
def _on_layer_event(event: carb.events.IEvent):
payload = layers.get_layer_event_payload(event)
if payload.event_type == layers.LayerEventType.LIVE_SESSION_LIST_CHANGED:
if self._base_layer_identifier not in payload.identifiers_or_spec_paths:
return
self._existing_sessions_model.refresh_sessions(force=True)
self._update_dialog_states()
self._layers_event_subscription = layers_interface.get_event_stream().create_subscription_to_pop(
_on_layer_event, name="Session Start Window Events"
)
def destroy(self):
self._layers_interface = None
for button in self._buttons:
button.set_clicked_fn(None)
self._buttons.clear()
self._participants_list = None
if self._window:
self._window.visible = False
self._window = None
if self._existing_sessions_model:
self._existing_sessions_model.set_user_update_callback(None)
self._existing_sessions_model.destroy()
self._existing_sessions_model = None
self._participants_layout = None
self._layers_event_subscription = None
self._existing_sessions_combo = None
self._existing_sessions_empty_hint = None
self._join_create_radios = None
self._session_name_input_hint = None
self._session_name_input_field = None
self._session_name_begin_edit_cb = None
self._session_name_end_edit_cb = None
self._session_name_edit_cb = None
self._error_label = None
if self._update_user_list_task:
try:
self._update_user_list_task.cancel()
except Exception:
pass
self._update_user_list_task = None
@property
def visible(self):
return self._window and self._window.visible
@visible.setter
def visible(self, value):
if self._window:
self._window.visible = value
if not self._window.visible:
if self._update_user_list_task:
try:
self._update_user_list_task.cancel()
except Exception:
pass
self._update_user_list_task = None
self._existing_sessions_model.stop_channel()
def set_focus(self, join_session):
if not self._join_create_radios:
return
if join_session:
self._join_create_radios.model.set_value(0)
if get_session_list_select() == SESSION_LIST_SELECT_DEFAULT_SESSION:
self._existing_sessions_model.select_default_session()
else:
self._join_create_radios.model.set_value(1)
async def async_focus_keyboard():
await omni.kit.app.get_app().next_update_async()
self._session_name_input_field.focus_keyboard()
omni.kit.async_engine.run_coroutine(async_focus_keyboard())
def _on_channel_users_update(self):
async def _update_users():
all_users = self._existing_sessions_model.all_users
current_session = self._existing_sessions_model.current_session
if not current_session:
return
self._participants_list.clear()
with self._participants_list:
if len(all_users) > 0:
for _, user in all_users.items():
is_owner = current_session.owner == user.user_name
with ui.VStack(height=0):
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Spacer(width=10)
if is_owner:
ui.Label(f"{user.user_name} - {user.from_app} (owner)", style={"color": 0xFF808080})
else:
ui.Label(f"{user.user_name} - {user.from_app}", style={"color": 0xFF808080})
else:
self._build_empty_participants_list()
if not self._update_user_list_task or self._update_user_list_task.done():
self._update_user_list_task = asyncio.ensure_future(_update_users())
def _validate_session_name(self, str):
if re.match(r'^[a-zA-Z][a-zA-Z0-9-_]*$', str):
return True
return False
def _on_join_session(self, current_session):
layer_identifier = self._base_layer_identifier
layers_interface = self._layers_interface
prim_path = self._live_prim_path
return join_live_session(
layers_interface, layer_identifier, current_session, prim_path, is_viewer_only_mode()
)
def _on_ok_button_fn(self): # pragma: no cover
live_syncing = self._layers_interface.get_live_syncing()
current_option = self._join_create_radios.model.as_int
join_session = current_option == 0
if join_session:
current_session = self._existing_sessions_model.current_session
if not current_session:
self._error_label.text = "No Valid Session Selected"
self._error_label.visible = True
elif self._on_join_session(current_session):
self._error_label.text = ""
self._error_label.visible = False
self.visible = False
else:
self._error_label.text = "Failed to join session, please check console for more details."
self._error_label.visible = True
else:
session_name = self._session_name_input_field.model.get_value_as_string()
session_name = session_name.strip()
if not session_name or not self._validate_session_name(session_name):
self._update_button_status(session_name)
self._error_label.text = "Session name must be given."
self._error_label.visible = True
else:
session = live_syncing.create_live_session(layer_identifier=self._base_layer_identifier, name=session_name)
if not session:
self._error_label.text = "Failed to create session, please check console for more details."
self._error_label.visible = True
elif not self._on_join_session(session):
self._error_label.text = "Failed to join session, please check console for more details."
self._error_label.visible = True
else:
self._error_label.text = ""
self._error_label.visible = False
self.visible = False
def _on_cancel_button_fn(self):
self.visible = False
def _on_key_pressed_fn(self, key, mod, pressed):
if not pressed:
return
func = self._key_functions.get(key)
if func:
func()
def _build_option_checkbox(self, name, text, default_value, tooltip=""): # pragma: no cover
with ui.HStack(height=0, width=0):
checkbox = ui.CheckBox(width=20, name=name)
checkbox.model.set_value(default_value)
label = ui.Label(text, alignment=ui.Alignment.LEFT)
if tooltip:
label.set_tooltip(tooltip)
return checkbox, label
def _build_option_radio(self, collection, name, text, tooltip=""):
style = {
"": {"background_color": 0x0, "image_url": LayerIcons.get("radio_off")},
":checked": {"image_url": LayerIcons.get("radio_on")},
}
with ui.HStack(height=0, width=0):
radio = ui.RadioButton(radio_collection=collection, width=28, height=28, name=name, style=style)
ui.Spacer(width=4)
label = ui.Label(text, alignment=ui.Alignment.LEFT_CENTER)
if tooltip:
label.set_tooltip(tooltip)
return radio
def _update_button_status(self, session_name):
join_button = self._buttons[0]
if session_name and not self._validate_session_name(session_name):
if not str.isalpha(session_name[0]):
self._error_label.text = "Session name must be prefixed with letters."
else:
self._error_label.text = "Only alphanumeric letters, hyphens, or underscores are supported."
self._error_label.visible = True
join_button.enabled = False
else:
self._error_label.text = ""
self._error_label.visible = False
join_button.enabled = True
def _on_session_name_begin_edit(self, model):
self._session_name_input_hint.visible = False
session_name = model.get_value_as_string().strip()
self._update_button_status(session_name)
def _on_session_name_end_edit(self, model):
if len(model.get_value_as_string()) == 0:
self._session_name_input_hint.visible = True
session_name = model.get_value_as_string().strip()
self._update_button_status(session_name)
def _on_session_name_edit(self, model):
session_name = model.get_value_as_string().strip()
self._update_button_status(session_name)
def _update_dialog_states(self):
self._error_label.text = ""
current_option = self._join_create_radios.model.as_int
show_join_session = current_option == 0
join_button = self._buttons[0]
if show_join_session:
self._existing_sessions_combo.visible = True
self._session_name_input_field.visible = False
self._session_name_input_hint.visible = False
self._participants_layout.visible = True
self._existing_sessions_model.refresh_sessions()
if self._existing_sessions_model.empty():
self._existing_sessions_empty_hint.visible = True
else:
self._existing_sessions_empty_hint.visible = False
join_button.text = "JOIN"
else:
self._participants_layout.visible = False
self._existing_sessions_combo.visible = False
self._session_name_input_field.visible = True
self._session_name_input_hint.visible = False
self._existing_sessions_empty_hint.visible = False
self._existing_sessions_model.clear()
join_button.text = "CREATE"
new_session_name = self._existing_sessions_model.create_new_session_name()
self._session_name_input_field.model.set_value(new_session_name)
self._session_name_input_field.focus_keyboard()
def _on_radios_changed_fn(self, model):
self._update_dialog_states()
self._on_checkbox_changed_called = False
def _on_session_list_changed(self, model):
if self._participants_list:
self._participants_list.clear()
def _build_ui(self):
"""Construct the window based on the current parameters"""
self._window = ui.Window("Live Session", visible=False, height=0, auto_resize=True, dockPreference=ui.DockPreference.DISABLED)
self._window.flags = (
ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_SCROLLBAR |
ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE
)
self._window.set_key_pressed_fn(self._on_key_pressed_fn)
self._window.flags = self._window.flags | ui.WINDOW_FLAGS_MODAL
self._existing_sessions_model.refresh_sessions()
empty_sessions = self._existing_sessions_model.empty()
with self._window.frame:
with ui.VStack(height=0):
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer()
self._join_create_radios = ui.RadioCollection()
self._build_option_radio(self._join_create_radios, "join_session_radio_button", "Join Session")
ui.Spacer(width=20)
self._build_option_radio(self._join_create_radios, "create_session_radio_button", "Create Session")
ui.Spacer()
self._join_create_radios.model.add_value_changed_fn(lambda _: self._update_dialog_states())
ui.Spacer(width=0, height=15)
with ui.HStack(height=0):
ui.Spacer(width=20)
self._error_label = ui.Label("", name="error_label", style={"color": 0xFF0000CC}, alignment=ui.Alignment.LEFT, word_wrap=True)
ui.Spacer(width=20)
ui.Spacer(width=0, height=5)
with ui.ZStack(height=0):
with ui.HStack(height=0):
ui.Spacer(width=20)
with ui.ZStack(height=0):
self._session_name_input_field = ui.StringField(
name="new_session_name_field", width=self._window.width - 40, height=0
)
self._session_name_input_hint = ui.Label(
" New Session Name", alignment=ui.Alignment.LEFT_CENTER, style={"color": 0xFF3F3F3F}
)
self._session_name_begin_edit_cb = self._session_name_input_field.model.subscribe_begin_edit_fn(
self._on_session_name_begin_edit
)
self._session_name_end_edit_cb = self._session_name_input_field.model.subscribe_end_edit_fn(
self._on_session_name_end_edit
)
self._session_name_edit_cb = self._session_name_input_field.model.subscribe_value_changed_fn(
self._on_session_name_edit
)
ui.Spacer(width=20)
with ui.HStack(height=0):
ui.Spacer(width=20)
with ui.ZStack(height=0):
self._existing_sessions_combo = ui.ComboBox(
self._existing_sessions_model, width=self._window.width - 40, height=0
)
self._existing_sessions_empty_hint = ui.Label(
" No Existing Sessions", alignment=ui.Alignment.LEFT_CENTER, style={"color": 0xFF3F3F3F}
)
ui.Spacer(width=20)
ui.Spacer(width=0, height=10)
self._participants_layout = ui.VStack(height=0)
with self._participants_layout:
with ui.HStack(height=0):
ui.Spacer(width=20)
with ui.VStack(height=0, width=0):
with ui.HStack(height=0, width=0):
ui.Label("Participants: ", alignment=ui.Alignment.CENTER)
with ui.HStack():
ui.Spacer()
ui.Image(LayerIcons.get("participants"), width=28, height=28)
ui.Spacer()
ui.Spacer(width=0, height=5)
with ui.HStack(height=0):
with ui.ScrollingFrame(height=120, style={"background_color": 0xFF24211F}):
self._participants_list = ui.VStack(height=0)
with self._participants_list:
self._build_empty_participants_list()
ui.Spacer(width=20)
ui.Spacer(width=0, height=30)
with ui.HStack(height=0):
ui.Spacer(height=0)
ok_button = ui.Button("JOIN", name="confirm_button", width=120, height=0)
ok_button.set_clicked_fn(self._on_ok_button_fn)
cancel_button = ui.Button("CANCEL", name="cancel_button", width=120, height=0)
cancel_button.set_clicked_fn(self._on_cancel_button_fn)
self._buttons.append(ok_button)
self._buttons.append(cancel_button)
ui.Spacer(height=0, width=20)
ui.Spacer(width=0, height=20)
if empty_sessions:
self._join_create_radios.model.set_value(1)
else:
self._update_dialog_states()
def _build_empty_participants_list(self):
with ui.VStack(height=0):
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Spacer(width=10)
ui.Label("No users currently in session.", style={"color": 0xFF808080})
| 18,527 |
Python
| 44.635468 | 146 | 0.559454 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/live_session_end_window.py
|
import carb
import asyncio
import omni.ui as ui
import omni.kit.app
import omni.kit.usd.layers as layers
import omni.kit.notification_manager as nm
from omni.kit.widget.prompt import PromptManager
from pxr import Sdf
from .file_picker import FilePicker, FileBrowserMode, FileBrowserSelectionType
class LiveSessionEndWindow:
def __init__(self, layers_interface: layers.Layers, layer_identifier):
self._window = None
self._live_syncing = layers_interface.get_live_syncing()
self._base_layer_identifier = layer_identifier
self._buttons = []
self._options_combo = None
self._file_picker = None
self._key_functions = {
int(carb.input.KeyboardInput.ENTER): self._on_ok_button_fn,
int(carb.input.KeyboardInput.ESCAPE): self._on_cancel_button_fn
}
self._build_ui()
def destroy(self):
for button in self._buttons:
button.set_clicked_fn(None)
self._buttons.clear()
if self._window:
self._window.visible = False
self._window = None
self._options_combo = None
if self._file_picker:
self._file_picker.destroy()
self._file_picker = None
async def __aenter__(self):
await self._live_syncing.broadcast_merge_started_message_async(self._base_layer_identifier)
self.visible = True
# Wait until dialog disappears
while self.visible:
await asyncio.sleep(0.1)
async def __aexit__(self, exc_type, exc, tb):
self.visible = False
@property
def visible(self):
return self._window and self._window.visible
@visible.setter
def visible(self, value):
if self._window:
self._window.visible = value
def _on_ok_button_fn(self):
self.visible = False
if not self._live_syncing.is_layer_in_live_session(self._base_layer_identifier):
return
prompt = None
async def pre_merge(current_session):
nonlocal prompt
app = omni.kit.app.get_app()
await app.next_update_async()
await app.next_update_async()
prompt = PromptManager.post_simple_prompt(
"Merging",
"Merging live layers into base layers...",
None,
shortcut_keys=False
)
async def post_merge(success):
nonlocal prompt
if prompt:
prompt.destroy()
prompt = None
if success:
await self._live_syncing.broadcast_merge_done_message_async(
layer_identifier=self._base_layer_identifier
)
current_session = self._live_syncing.get_current_live_session(self._base_layer_identifier)
comment = self._description_field.model.get_value_as_string()
option = self._options_combo.model.get_item_value_model().as_int
if option == 1:
def save_model(file_path: str, overwrite_existing: bool):
layer = Sdf.Layer.FindOrOpen(file_path)
if not layer:
layer = Sdf.Layer.CreateNew(file_path)
if not layer:
error = f"Failed to save live changes to layer {file_path} as it's not writable."
carb.log_error(error)
nm.post_notification(error, status=nm.NotificationStatus.WARNING)
return
asyncio.ensure_future(
self._live_syncing.merge_and_stop_live_session_async(
file_path, comment, pre_merge=pre_merge, post_merge=post_merge,
layer_identifier=self._base_layer_identifier
)
)
usd_context = self._live_syncing.usd_context
stage = usd_context.get_stage()
root_layer_identifier = stage.GetRootLayer().identifier
root_layer_name = current_session.name
self._show_file_picker(save_model, root_layer_identifier, root_layer_name)
elif option == 0:
asyncio.ensure_future(
self._live_syncing.merge_and_stop_live_session_async(
comment=comment, pre_merge=pre_merge, post_merge=post_merge,
layer_identifier=self._base_layer_identifier
)
)
def _on_cancel_button_fn(self):
self.visible = False
def _on_key_pressed_fn(self, key, mod, pressed):
if not pressed:
return
func = self._key_functions.get(key)
if func:
func()
def _create_file_picker(self):
filter_options = [
(r"^(?=.*.usd$)((?!.*\.(sublayer)\.usd).)*$", "USD File (*.usd)"),
(r"^(?=.*.usda$)((?!.*\.(sublayer)\.usda).)*$", "USDA File (*.usda)"),
(r"^(?=.*.usdc$)((?!.*\.(sublayer)\.usdc).)*$", "USDC File (*.usdc)"),
("(.*?)", "All Files (*.*)"),
]
layer_file_picker = FilePicker(
"Save Live Changes",
FileBrowserMode.SAVE,
FileBrowserSelectionType.FILE_ONLY,
filter_options,
[".usd", ".usda", ".usdc", ".usd"],
)
return layer_file_picker
def _show_file_picker(self, file_handler, default_location=None, default_filename=None):
if not self._file_picker:
self._file_picker = self._create_file_picker()
self._file_picker.set_file_selected_fn(file_handler)
self._file_picker.show(default_location, default_filename)
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 _build_ui(self):
"""Construct the window based on the current parameters"""
self._window = ui.Window("Merge Options", visible=False, height=0, dockPreference=ui.DockPreference.DISABLED)
self._window.flags = (
ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_SCROLLBAR |
ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE
)
self._window.set_key_pressed_fn(self._on_key_pressed_fn)
self._window.flags = self._window.flags | ui.WINDOW_FLAGS_MODAL
current_session = self._live_syncing.get_current_live_session(self._base_layer_identifier)
with self._window.frame:
with ui.VStack(height=0):
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer()
ui.Label(
"Live Session is ending.", word_wrap=True, alignment=ui.Alignment.CENTER, width=self._window.width - 80, height=0
)
ui.Spacer()
with ui.HStack(height=0):
ui.Spacer()
ui.Label(
f"How do you want to merge changes from '{current_session.name}' session?",
alignment=ui.Alignment.CENTER, word_wrap=True, width=self._window.width - 80, height=0
)
ui.Spacer()
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer()
self._options_combo = ui.ComboBox(
0, "Merge to corresponding layers", "Merge to a new layer",
word_wrap=True, width=self._window.width - 80, height=0
)
ui.Spacer()
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer(width=40)
self._checkpoint_comment_frame = ui.Frame()
with self._checkpoint_comment_frame:
with ui.VStack(height=0, spacing=5):
ui.Label("Checkpoint Description")
with ui.ZStack():
self._description_field = ui.StringField(multiline=True, height=80)
self._description_field_hint_label = ui.Label(
" Description", alignment=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
)
ui.Spacer(width=40)
ui.Spacer(width=0, height=30)
with ui.HStack(height=0):
ui.Spacer(height=0)
ok_button = ui.Button("CONTINUE", name="confirm_button", width=120, height=0)
ok_button.set_clicked_fn(self._on_ok_button_fn)
cancel_button = ui.Button("CANCEL", name="cancel_button", width=120, height=0)
cancel_button.set_clicked_fn(self._on_cancel_button_fn)
self._buttons.append(ok_button)
self._buttons.append(cancel_button)
ui.Spacer(height=0)
ui.Spacer(width=0, height=10)
| 9,633 |
Python
| 39.649789 | 137 | 0.534517 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/live_style.py
|
class Styles:
RELOAD_BTN = None
RELOAD_AUTO = None
RELOAD_OTD = None
LIVE_TOOL_TIP = None
@staticmethod
def on_startup():
# from .layer_icons import LayerIcons as li
from omni.ui import color as cl
c_otd = cl("#eb9d00")
c_otdh = cl("#ffaa00")
c_live = cl("#76B900")
c_liveh = cl("#9bf400")
c_lived = cl("#76B900")
c_auto = cl("#34C7FF")
c_autoh = cl("#82dcff")
c_white = cl("#ffffff")
c_rel = cl("#888888")
c_relh = cl("#BBBBBB")
c_disabled = cl("#555555")
Styles.LIVE_TOOL_TIP = {"background_color": 0xEE222222, "color": 0x33333333}
Styles.LIVE_GREEN = {"color": c_live, "Tooltip": Styles.LIVE_TOOL_TIP}
Styles.LIVE_SEL = {"color": c_liveh, "Tooltip": Styles.LIVE_TOOL_TIP}
Styles.LIVE_GREEN_DARKER = {"color": c_lived, "Tooltip": Styles.LIVE_TOOL_TIP}
Styles.RELOAD_BTN = {
"color": c_rel,
":hovered": {"color": c_relh},
":pressed": {"color": c_white},
":disabled": {"color": c_disabled},
}
Styles.RELOAD_AUTO = {
"color": c_auto, "Tooltip": Styles.LIVE_TOOL_TIP,
":hovered": {"color": c_autoh},
":pressed": {"color": c_white},
":disabled": {"color": c_disabled},
}
Styles.RELOAD_OTD = {
"color": c_otd, "Tooltip": Styles.LIVE_TOOL_TIP,
":hovered": {"color": c_otdh},
":pressed": {"color": c_white},
":disabled": {"color": c_disabled},
}
| 1,602 |
Python
| 29.245282 | 86 | 0.500624 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/live_session_model.py
|
__all__ = ["LiveSessionItem", "LiveSessionModel"]
import asyncio
import omni.kit.usd.layers as layers
import omni.ui as ui
from typing import Callable
import itertools
_last_sessions = {}
class LiveSessionItem(ui.AbstractItem):
def __init__(self, session: layers.LiveSession) -> None:
super().__init__()
self._session = session
self.model = ui.SimpleStringModel(session.name)
@property
def session(self):
return self._session
def __str__(self) -> str:
return self._session.name
class LiveSessionModel(ui.AbstractItemModel):
def __init__(self, layers_interface: layers.Layers, layer_identifier, update_users=True) -> None:
super().__init__()
self._layers_interface = layers_interface
self._base_layer_identifier = layer_identifier
self._current_index = ui.SimpleIntModel()
self._current_index.set_value(-1)
id = self._current_index.add_value_changed_fn(self._value_changed_fn)
self._items = []
self._current_session = None
self._current_session_channel = None
self._channel_subscriber = None
self._join_channel_task = None
self._all_users = {}
self._user_update_callback: Callable[[], None] = None
self._all_value_changed_fns = [id]
self._update_users = update_users
self._refreshing_item = False
self._is_default_session_selected = False
def __del__(self):
self.destroy()
@property
def all_users(self):
return self._all_users
@property
def is_default_session_selected(self):
return self._is_default_session_selected
def set_user_update_callback(self, callback: Callable[[], None]):
self._user_update_callback = callback
def stop_channel(self):
self._cancel_current_task()
def _join_current_channel(self):
if not self._current_session or not self._update_users:
return
try:
# OM-108516: Make channel_manager optional
import omni.kit.collaboration.channel_manager as cm
except ImportError:
return
if not self._current_session_channel or self._current_session_channel.url != self._current_session.url:
self._cancel_current_task()
async def join_stage_async(url):
self._current_session_channel = await cm.join_channel_async(url, True)
if not self._current_session_channel:
return
self._channel_subscriber = self._current_session_channel.add_subscriber(self._on_channel_message)
self._join_channel_task = asyncio.ensure_future(join_stage_async(self._current_session.channel_url))
def _on_channel_message(self, message):
try:
# OM-108516: Make channel_manager optional
import omni.kit.collaboration.channel_manager as cm
except ImportError:
return
user = message.from_user
if message.message_type == cm.MessageType.LEFT and user.user_id in self._all_users:
self._all_users.pop(user.user_id, None)
changed = True
elif user.user_id not in self._all_users:
self._all_users[user.user_id] = user
changed = True
else:
changed = False
if changed and self._user_update_callback:
self._user_update_callback()
def _cancel_current_task(self):
if self._join_channel_task and not self._join_channel_task.done():
try:
self._join_channel_task.cancel()
except Exception:
pass
if self._current_session_channel:
self._current_session_channel.stop()
self._current_session_channel = None
self._join_channel_task = None
self._channel_subscriber = None
def add_value_changed(self, fn):
if self._current_index:
id = self._current_index.add_value_changed_fn(fn)
self._all_value_changed_fns.append(id)
def _value_changed_fn(self, model):
if self._refreshing_item:
return
global _last_sessions
index = self._current_index.as_int
if index < 0 or index >= len(self._items):
return
self._current_session = self._items[index].session
self._is_default_session_selected = (self._current_session and self._current_index.as_int == 0)
_last_sessions[self._base_layer_identifier] = self._current_session.url
self._all_users.clear()
if self._user_update_callback:
self._user_update_callback()
self._join_current_channel()
self._refreshing_item = True
self._item_changed(None)
self._refreshing_item = False
def destroy(self):
self._user_update_callback = None
self._cancel_current_task()
if self._current_index:
for fn in self._all_value_changed_fns:
self._current_index.remove_value_changed_fn(fn)
self._all_value_changed_fns.clear()
self._current_index = None
self._layers_interface = None
self._current_session = None
self._items = []
self._all_users = {}
self._layers_event_subscription = None
def clear(self):
self._items = []
self._current_session = None
self._current_index.set_value(-1)
def empty(self):
return len(self._items) == 0
def get_item_children(self, item):
return self._items
@property
def current_session(self):
return self._current_session
def refresh_sessions(self, force=False):
global _last_sessions
live_syncing = self._layers_interface.get_live_syncing()
current_live_session = live_syncing.get_current_live_session(self._base_layer_identifier)
live_sessions = live_syncing.get_all_live_sessions(self._base_layer_identifier)
live_sessions.sort(key=lambda s: s.get_last_modified_time(), reverse=True)
identifier = self._base_layer_identifier
pre_sort = []
for session in live_sessions:
if session.name == "Default":
pre_sort.insert(0, session)
else:
pre_sort.append(session)
self._items.clear()
index = 0 if live_sessions else -1
for i, session in enumerate(pre_sort):
item = LiveSessionItem(session)
if current_live_session and current_live_session.url == session.url:
index = i
elif identifier in _last_sessions and _last_sessions[identifier] == session.url:
index = i
self._items.append(item)
current_index = self._current_index.as_int
if current_index != index:
self._current_index.set_value(index)
elif force:
self._item_changed(None)
self._is_default_session_selected = (self._current_session and self._current_index.as_int == 0)
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
def select_default_session(self):
live_syncing = self._layers_interface.get_live_syncing()
live_sessions = live_syncing.get_all_live_sessions(self._base_layer_identifier)
if live_sessions and self._current_index.as_int != 0:
self._current_index.set_value(0)
self._item_changed(None)
return
def create_new_session_name(self) -> str:
live_syncing = self._layers_interface.get_live_syncing()
live_sessions = live_syncing.get_all_live_sessions(self._base_layer_identifier)
# first we attempt creating a "Default" as the first new session.
default_session_name = "Default"
if not live_syncing.find_live_session_by_name(self._base_layer_identifier, default_session_name):
return default_session_name
# if there already is a `Default`, then we use <username>_01, <username>_02, ...
layers_instance = live_syncing._layers_instance
live_syncing_interface = live_syncing._live_syncing_interface
logged_user_name = live_syncing_interface.get_logged_in_user_name_for_layer(layers_instance, self._base_layer_identifier)
if "@" in logged_user_name:
logged_user_name = logged_user_name.split('@')[0]
for i in itertools.count(start=1):
user_session_name = "{}_{:02d}".format(logged_user_name, i)
if not live_syncing.find_live_session_by_name(self._base_layer_identifier, user_session_name):
return user_session_name
| 8,699 |
Python
| 35.708861 | 129 | 0.613174 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/live_session_camera_follower_list.py
|
__all__ = ["LiveSessionCameraFollowerList"]
import carb
import omni.usd
import omni.client.utils as clientutils
import omni.ui as ui
import omni.kit.usd.layers as layers
import omni.kit.collaboration.presence_layer as pl
from .utils import build_live_session_user_layout
from pxr import Sdf
from omni.ui import color as cl
TOOLTIP_STYLE = {
"color": cl("#979797"),
"Tooltip": {"background_color": 0xEE222222}
}
class LiveSessionCameraFollowerList:
"""Widget to build an user list to show all followers to the specific camera."""
def __init__(self, usd_context: omni.usd.UsdContext, camera_path: Sdf.Path, **kwargs):
"""
Constructor.
Args:
usd_context (omni.usd.UsdContext): USD Context instance.
camera_path (str): Interested camera.
Kwargs:
icon_size (int): The width and height of the user icon. 16 pixel by default.
spacing (int): The horizonal spacing between two icons. 2 pixel by default.
maximum_users (int): The maximum users to show, and show others with overflow.
show_my_following_users (bool): Whether it should show the users that are following me or not.
"""
self.__icon_size = kwargs.get("icon_size", 16)
self.__spacing = kwargs.get("spacing", 2)
self.__maximum_count = kwargs.get("maximum_users", 3)
self.__show_my_following_users = kwargs.get("show_my_following_users", True)
self.__camera_path = camera_path
self.__usd_context = usd_context
self.__presence_layer = pl.get_presence_layer_interface(self.__usd_context)
self.__layers = layers.get_layers(usd_context)
self.__live_syncing = layers.get_live_syncing()
self.__layers_event_subscriptions = []
self.__main_layout: ui.HStack = ui.HStack(width=0, height=0)
self.__all_user_layouts = {}
self.__initialize()
self.__overflow = False
self.__overflow_button = None
@property
def layout(self) -> ui.HStack:
return self.__main_layout
def empty(self):
return len(self.__all_user_layouts) == 0
def track_camera(self, camera_path: Sdf.Path):
"""Switches the camera path to listen to."""
if self.__camera_path != camera_path:
self.__camera_path = camera_path
self.__initialize()
def __initialize(self):
layer_identifier = self.__usd_context.get_stage_url()
if self.__camera_path and not clientutils.is_local_url(layer_identifier):
for event in [
layers.LayerEventType.LIVE_SESSION_STATE_CHANGED,
layers.LayerEventType.LIVE_SESSION_USER_JOINED,
layers.LayerEventType.LIVE_SESSION_USER_LEFT,
pl.PresenceLayerEventType.BOUND_CAMERA_CHANGED
]:
layers_event_subscription = self.__layers.get_event_stream().create_subscription_to_pop_by_type(
event, self.__on_layers_event,
name=f"omni.kit.widget.live_session_management.LiveSessionCameraFollowerList {str(event)}"
)
self.__layers_event_subscriptions.append(layers_event_subscription)
else:
self.__layers_event_subscriptions = []
self.__build_ui()
def __build_ui(self):
# Destroyed
if not self.__main_layout:
return
self.__main_layout.clear()
self.__all_user_layouts.clear()
self.__overflow = False
self.__overflow_button = None
current_live_session = self.__live_syncing.get_current_live_session()
if not current_live_session or not self.__camera_path:
return
with self.__main_layout:
for peer_user in current_live_session.peer_users:
self.__add_user(current_live_session, peer_user.user_id, False)
if self.__overflow:
break
if self.empty():
self.__main_layout.visible = False
else:
self.__main_layout.visible = True
def __build_tooltip(self): # pragma: no cover
live_session = self.__live_syncing.get_current_live_session(self.__base_layer_identifier)
if not live_session:
return
with ui.VStack():
with ui.HStack(style={"color": cl("#757575")}):
ui.Spacer()
title_label = ui.Label(
"Following by 0 Users", style={"font_size": 12}, width=0
)
ui.Spacer()
ui.Spacer(height=0)
ui.Separator(style={"color": cl("#4f4f4f")})
ui.Spacer(height=4)
valid_users = 0
for user in live_session.peer_users:
if not self.__show_my_following_users:
following_user_id = self.__presence_layer.get_following_user_id(user.user_id)
if following_user_id == live_session.logged_user_id:
continue
bound_camera_prim = self.__presence_layer.get_bound_camera_prim(user.user_id)
if not bound_camera_prim or bound_camera_prim.GetPath() != self.__camera_path:
continue
valid_users += 1
item_title = f"{user.user_name} ({user.from_app})"
with ui.HStack():
build_live_session_user_layout(user, self.__icon_size, "")
ui.Spacer(width=4)
ui.Label(item_title, style={"font_size": 14})
ui.Spacer(height=2)
title_label.text = f"Following by {valid_users} Users"
@carb.profiler.profile
def __add_user(self, current_live_session, user_id, add_child=False):
bound_camera_prim = self.__presence_layer.get_bound_camera_prim(user_id)
if not bound_camera_prim:
return False
if bound_camera_prim.GetPath() == self.__camera_path:
user_info = current_live_session.get_peer_user_info(user_id)
if not user_info:
return False
if not self.__show_my_following_users:
following_user_id = self.__presence_layer.get_following_user_id(user_id)
if following_user_id == current_live_session.logged_user_id:
return False
if user_id not in self.__all_user_layouts:
current_count = len(self.__all_user_layouts)
if current_count > self.__maximum_count or self.__overflow:
# OMFP-2909: Refresh overflow button to rebuild tooltip.
if self.__overflow and self.__overflow_button:
self.__overflow_button.set_tooltip_fn(self.__build_tooltip)
return True
elif current_count == self.__maximum_count:
self.__overflow = True
layout = ui.HStack(width=0)
with layout:
ui.Spacer(width=4)
with ui.ZStack():
ui.Label("...", style={"font_size": 16}, aligment=ui.Alignment.V_CENTER)
self.__overflow_button = ui.InvisibleButton(style=TOOLTIP_STYLE)
self.__overflow_button.set_tooltip_fn(self.__build_tooltip)
if add_child:
self.__main_layout.add_child(layout)
else:
if self.empty():
spacer = 0
else:
spacer = self.__spacing
layout = self.__build_user_layout(user_info, spacer)
if add_child:
self.__main_layout.add_child(layout)
self.__main_layout.visible = True
self.__all_user_layouts[user_id] = layout
return True
return False
@carb.profiler.profile
def __on_layers_event(self, event):
payload = layers.get_layer_event_payload(event)
stage_url = self.__usd_context.get_stage_url()
if payload.event_type == layers.LayerEventType.LIVE_SESSION_STATE_CHANGED:
if stage_url not in payload.identifiers_or_spec_paths:
return
self.__build_ui()
elif (
payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_JOINED or
payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_LEFT
):
if stage_url != payload.layer_identifier:
return
current_live_session = self.__live_syncing.get_current_live_session()
if not current_live_session:
self.__build_ui()
return
user_id = payload.user_id
if payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_LEFT:
user = self.__all_user_layouts.pop(user_id, None)
if user:
# FIXME: omni.ui does not support to remove single child.
self.__build_ui()
else:
self.__add_user(current_live_session, user_id, True)
else:
current_live_session = self.__live_syncing.get_current_live_session()
if not current_live_session:
return
payload = pl.get_presence_layer_event_payload(event)
if not payload or not payload.event_type:
return
if payload.event_type == pl.PresenceLayerEventType.BOUND_CAMERA_CHANGED:
changed_user_ids = payload.changed_user_ids
needs_rebuild = False
for user_id in changed_user_ids:
if not self.__add_user(current_live_session, user_id, True):
# It's not bound to this camera already.
needs_rebuild = user_id in self.__all_user_layouts
break
if needs_rebuild:
self.__build_ui()
def destroy(self): # pragma: no cover
self.__main_layout = None
self.__layers_event_subscriptions = []
self.__layers = None
self.__live_syncing = None
self.__all_user_layouts.clear()
self.__overflow_button = None
def __build_user_layout(self, user_info: layers.LiveSessionUser, spacing=2):
tooltip = f"{user_info.user_name} ({user_info.from_app})"
layout = ui.HStack()
with layout:
ui.Spacer(width=spacing)
build_live_session_user_layout(user_info, self.__icon_size, tooltip)
return layout
| 10,669 |
Python
| 39.264151 | 112 | 0.556472 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/filebrowser/__init__.py
|
from .app_filebrowser import FileBrowserUI, FileBrowserSelectionType, FileBrowserMode
| 85 |
Python
| 84.999915 | 85 | 0.894118 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/filebrowser/app_filebrowser.py
|
import asyncio
import re
import omni.client
import omni.client.utils as clientutils
from omni.kit.window.filepicker import FilePickerDialog
from omni.kit.widget.filebrowser import FileBrowserItem
from typing import Iterable, Tuple, Union
class FileBrowserSelectionType:
FILE_ONLY = 0
DIRECTORY_ONLY = 1
ALL = 2
class FileBrowserMode:
OPEN = 0
SAVE = 1
class FileBrowserUI:
def __init__(self, title, mode, selection_type, filter_options, **kwargs):
if mode == FileBrowserMode.OPEN:
confirm_text = "Open"
else:
confirm_text = "Save"
self._file_picker = FilePickerApp(title, confirm_text, selection_type, filter_options, **kwargs)
def set_current_directory(self, dir):
self._file_picker.set_current_directory(dir)
def set_current_filename(self, filename):
self._file_picker.set_current_filename(filename)
def get_current_filename(self):
return self._file_picker.get_current_filename()
def open(self, select_fn, cancel_fn):
self._file_picker.set_custom_fn(select_fn, cancel_fn)
self._file_picker.show_dialog()
def destroy(self):
self._file_picker.set_custom_fn(None, None)
self._file_picker = None
def hide(self):
self._file_picker.hide_dialog()
class FilePickerApp:
"""
Standalone app to demonstrate the use of the FilePicker dialog.
Args:
title (str): Title of the window.
apply_button_name (str): Name of the confirm button.
selection_type (FileBrowserSelectionType): The file type that confirm event will respond to.
item_filter_options (list): Array of filter options. Element of array
is a tuple that first element of this tuple is the regex string for filtering,
and second element of this tuple is the descriptions, like ("*.*", "All Files").
By default, it will list all files.
kwargs: additional keyword arguments to be passed to FilePickerDialog.
"""
def __init__(
self,
title: str,
apply_button_name: str,
selection_type: FileBrowserSelectionType = FileBrowserSelectionType.ALL,
item_filter_options: Iterable[Tuple[Union[re.Pattern, str], str]] = ((
re.compile(".*"), "All Files (*.*)")),
**kwargs,
):
self._title = title
self._filepicker = None
self._selection_type = selection_type
self._custom_select_fn = None
self._custom_cancel_fn = None
self._apply_button_name = apply_button_name
self._filter_regexes = []
self._filter_descriptions = []
self._current_directory = None
for regex, desc in item_filter_options:
if not isinstance(regex, re.Pattern):
regex = re.compile(regex, re.IGNORECASE)
self._filter_regexes.append(regex)
self._filter_descriptions.append(desc)
self._build_ui(**kwargs)
def set_custom_fn(self, select_fn, cancel_fn):
self._custom_select_fn = select_fn
self._custom_cancel_fn = cancel_fn
def show_dialog(self):
self._filepicker.show(self._current_directory)
self._current_directory = None
def hide_dialog(self):
self._filepicker.hide()
def set_current_directory(self, dir: str):
self._current_directory = dir
if not self._current_directory.endswith("/"):
self._current_directory += "/"
def set_current_filename(self, filename: str):
self._filepicker.set_filename(filename)
def get_current_filename(self):
return self._filepicker.get_filename()
def _build_ui(self, **kwargs):
on_click_open = lambda f, d: asyncio.ensure_future(self._on_click_open(f, d))
on_click_cancel = lambda f, d: asyncio.ensure_future(self._on_click_cancel(f, d))
# Create the dialog
self._filepicker = FilePickerDialog(
self._title,
allow_multi_selection=False,
apply_button_label=self._apply_button_name,
click_apply_handler=on_click_open,
click_cancel_handler=on_click_cancel,
item_filter_options=self._filter_descriptions,
item_filter_fn=lambda item: self._on_filter_item(item),
error_handler=lambda m: self._on_error(m),
**kwargs,
)
# Start off hidden
self.hide_dialog()
def _on_filter_item(self, item: FileBrowserItem) -> bool:
if not item or item.is_folder:
return True
if self._filepicker.current_filter_option >= len(self._filter_regexes):
return False
regex = self._filter_regexes[self._filepicker.current_filter_option]
if regex.match(item.path):
return True
else:
return False
def _on_error(self, msg: str):
"""
Demonstrates error handling. Instead of just printing to the shell, the App can
display the error message to a console window.
"""
print(msg)
async def _on_click_open(self, filename: str, dirname: str):
"""
The meat of the App is done in this callback when the user clicks 'Accept'. This is
a potentially costly operation so we implement it as an async operation. The inputs
are the filename and directory name. Together they form the fullpath to the selected
file.
"""
dirname = dirname.strip()
if dirname and not dirname.endswith("/"):
dirname += "/"
fullpath = clientutils.make_absolute_url_if_possible(dirname, filename)
result, entry = omni.client.stat(fullpath)
if result == omni.client.Result.OK and entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN:
is_folder = True
else:
is_folder = False
if not is_folder and self._selection_type == FileBrowserSelectionType.DIRECTORY_ONLY:
return
self.hide_dialog()
await omni.kit.app.get_app().next_update_async()
if self._custom_select_fn:
self._custom_select_fn(fullpath, self._filepicker.current_filter_option)
async def _on_click_cancel(self, filename: str, dirname: str):
"""
This function is called when the user clicks 'Cancel'.
"""
self.hide_dialog()
await omni.kit.app.get_app().next_update_async()
if self._custom_cancel_fn:
self._custom_cancel_fn()
| 6,490 |
Python
| 33.343915 | 104 | 0.623729 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/tests/mock_utils.py
|
import carb
import asyncio
import os
import functools
import uuid
import omni.usd
import omni.client
import omni.kit.usd.layers as layers
from typing import Callable, Awaitable
from omni.kit.collaboration.channel_manager.types import PeerUser
from omni.kit.usd.layers import LayersState, LiveSyncing, LiveSession
from ..live_session_model import LiveSessionModel
from ..file_picker import FilePicker
from omni.kit.usd.layers._omni_kit_usd_layers import IWorkflowLiveSyncing
from unittest.mock import Mock, MagicMock
from pxr import Sdf, Usd
_mock_sdf_save_layer_api = None
_mock_layer_states_get_all_outdated_layer_identifiers_api = None
_mock_live_session_model_all_users_api = None
_mock_live_syncing_merge_and_stop_live_session_async_api = None
_mock_filepicker_show_api = None
_mock_filepicker_set_file_selected_fn_api = None
_mock_outdated_layers = []
file_save_handler = None
merge_and_stop_live_session_async_called = False
def append_outdated_layers(layer_id):
global _mock_outdated_layers
_mock_outdated_layers.append(layer_id)
def clear_outdated_layers():
global _mock_outdated_layers
_mock_outdated_layers = []
def get_merge_and_stop_live_session_async_called():
global merge_and_stop_live_session_async_called
return merge_and_stop_live_session_async_called
def _start_mock_api_for_live_session_management():
carb.log_info("Start mock api for live session management...")
def __mock_sdf_save_layer(force):
pass
global _mock_sdf_save_layer_api
_mock_sdf_save_layer_api = Sdf.Layer.Save
Sdf.Layer.Save = Mock(side_effect=__mock_sdf_save_layer)
def __mock_layer_states_get_all_outdated_layer_identifiers_():
global _mock_outdated_layers
return _mock_outdated_layers
global _mock_layer_states_get_all_outdated_layer_identifiers_api
_mock_layer_states_get_all_outdated_layer_identifiers_api = LayersState.get_all_outdated_layer_identifiers
LayersState.get_all_outdated_layer_identifiers = Mock(side_effect=__mock_layer_states_get_all_outdated_layer_identifiers_)
global _mock_live_session_model_all_users_api
_mock_live_session_model_all_users_api = LiveSessionModel.all_users
LiveSessionModel.all_users = {f"user_{i}": PeerUser(f"user_{i}", f"user_{i}", "Kit") for i in range(3)}
async def __mock_live_syncing_merge_and_stop_live_session_async(
self, target_layer: str = None, comment="",
pre_merge: Callable[[LiveSession], Awaitable] = None,
post_merge: Callable[[bool], Awaitable] = None,
layer_identifier: str = None
) -> bool:
global merge_and_stop_live_session_async_called
merge_and_stop_live_session_async_called = True
return True
global _mock_live_syncing_merge_and_stop_live_session_async_api
_mock_live_syncing_merge_and_stop_live_session_async_api = LiveSyncing.merge_and_stop_live_session_async
LiveSyncing.merge_and_stop_live_session_async = Mock(side_effect=__mock_live_syncing_merge_and_stop_live_session_async)
def __mock_filepicker_show(dummy1, dummy2):
global file_save_handler
if file_save_handler:
file_save_handler(dummy1, False)
global _mock_filepicker_show_api
_mock_filepicker_show_api = FilePicker.show
FilePicker.show = Mock(side_effect=__mock_filepicker_show)
def __mock_filepicker_set_file_selected_fn(fn):
global file_save_handler
file_save_handler = fn
global _mock_filepicker_set_file_selected_fn_api
_mock_filepicker_set_file_selected_fn_api = FilePicker.set_file_selected_fn
FilePicker.set_file_selected_fn = Mock(side_effect=__mock_filepicker_set_file_selected_fn)
def _end_mock_api_for_live_session_management():
carb.log_info("Start mock api for live session management...")
global _mock_sdf_save_layer_api
Sdf.Layer.Save = _mock_sdf_save_layer_api
_mock_sdf_save_layer_api = None
global _mock_layer_states_get_all_outdated_layer_identifiers_api
LayersState.get_all_outdated_layer_identifiers = _mock_layer_states_get_all_outdated_layer_identifiers_api
_mock_layer_states_get_all_outdated_layer_identifiers_api = None
global _mock_live_session_model_all_users_api
LiveSessionModel.all_users = _mock_live_session_model_all_users_api
_mock_live_session_model_all_users_api = None
global _mock_live_syncing_merge_and_stop_live_session_async_api
LiveSyncing.merge_and_stop_live_session_async = _mock_live_syncing_merge_and_stop_live_session_async_api
_mock_live_syncing_merge_and_stop_live_session_async_api = None
global _mock_filepicker_show_api
FilePicker.show = _mock_filepicker_show_api
_mock_filepicker_show_api = None
global _mock_filepicker_set_file_selected_fn_api
FilePicker.set_file_selected_fn = _mock_filepicker_set_file_selected_fn_api
_mock_filepicker_set_file_selected_fn_api = None
global merge_and_stop_live_session_async_called
merge_and_stop_live_session_async_called = False
def MockApiForLiveSessionManagement(*args, **kwargs):
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
func = args[0]
args = args[1:]
else:
func = None
def wrapper(func):
@functools.wraps(func)
def wrapper_api(*args, **kwargs):
try:
_start_mock_api_for_live_session_management()
return func(*args, **kwargs)
finally:
_end_mock_api_for_live_session_management()
@functools.wraps(func)
async def wrapper_api_async(*args, **kwargs):
try:
_start_mock_api_for_live_session_management()
return await func(*args, **kwargs)
finally:
_end_mock_api_for_live_session_management()
if asyncio.iscoroutinefunction(func):
return wrapper_api_async
else:
return wrapper_api
if func:
return wrapper(func)
else:
return wrapper
| 5,995 |
Python
| 37.435897 | 126 | 0.69975 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/tests/__init__.py
|
from .test_live_session_management import *
| 43 |
Python
| 42.999957 | 43 | 0.813953 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/tests/test_live_session_management.py
|
import os
import carb
import omni.usd
import omni.kit.ui_test as ui_test
import omni.ui as ui
import omni.kit.usd.layers as layers
import omni.timeline.live_session
import omni.kit.collaboration.presence_layer as pl
import omni.kit.collaboration.presence_layer.utils as pl_utils
import unittest
import tempfile
import random
import uuid
from omni.kit.test import AsyncTestCase
from omni.kit.window.preferences import register_page, unregister_page
from pxr import Sdf, Usd
from omni.kit.usd.layers.tests.mock_utils import MockLiveSyncingApi, join_new_simulated_user, quit_simulated_user, forbid_session_merge
from ..extension import LiveSessionWidgetExtension, stop_or_show_live_session_widget
from ..live_session_camera_follower_list import LiveSessionCameraFollowerList
from ..live_session_user_list import LiveSessionUserList
from ..file_picker import FilePicker, FileBrowserMode, FileBrowserSelectionType
from ..live_session_preferences import LiveSessionPreferences
from ..reload_widget import build_reload_widget
from ..live_session_start_window import LiveSessionStartWindow
from .mock_utils import (
MockApiForLiveSessionManagement,
append_outdated_layers,
clear_outdated_layers,
get_merge_and_stop_live_session_async_called
)
TEST_URL = "omniverse://__omni.kit.widget.live_session_management__/tests/"
LIVE_SESSION_CONFIRM_BUTTON_PATH = "Live Session//Frame/**/Button[*].name=='confirm_button'"
LIVE_SESSION_CANCEL_BUTTON_PATH = "Live Session//Frame/**/Button[*].name=='cancel_button'"
LEAVE_SESSION_CONFIRM_BUTTON_PATH = "Leave Session//Frame/**/Button[*].name=='confirm_button'"
JOIN_LIVE_SESSION_WITH_LINK_CANCEL_BUTTON_PATH = "JOIN LIVE SESSION WITH LINK//Frame/**/Button[*].name=='cancel_button'"
SHARE_LIVE_SESSION_LINK_COMBO_BOX_PATH = "SHARE LIVE SESSION LINK//Frame/**/ComboBox[0]"
SHARE_LIVE_SESSION_LINK_CONFIRM_BUTTON_PATH = "SHARE LIVE SESSION LINK//Frame/**/InvisibleButton[*].name=='confirm_button'"
MERGE_OPTIONS_CONFIRM_BUTTON_PATH = "Merge Options//Frame/**/Button[*].name=='confirm_button'"
MERGE_OPTIONS_COMBO_BOX_PATH = "Merge Options//Frame/**/ComboBox[0]"
MERGE_PROMPT_LEAVE_BUTTON_PATH = "Permission Denied//Frame/**/Button[*].name=='confirm_button'"
QUICK_JOIN_ENABLED = "/exts/omni.kit.widget.live_session_management/quick_join_enabled"
def _menu_items_as_string_list(items):
return [i.text for i in items]
def _find_menu_item(items, text):
for i in items:
if i.text == text:
return i
return None
def enable_server_tests():
settings = carb.settings.get_settings()
return True or settings.get_as_bool("/exts/omni.kit.widget.live_session_management/enable_server_tests")
class TestLiveSessionManagement(AsyncTestCase):
def get_live_syncing(self):
usd_context = omni.usd.get_context()
self.assertIsNotNone(layers.get_layers(usd_context))
self.assertIsNotNone(layers.get_layers(usd_context).get_live_syncing())
return layers.get_layers(usd_context).get_live_syncing()
async def setUp(self):
self._instance = LiveSessionWidgetExtension.get_instance()
self.assertIsNotNone(self._instance)
self.assertFalse(self.get_live_syncing().is_stage_in_live_session())
pass
async def _close_case(self):
if omni.usd.get_context().get_stage():
live_syncing = self.get_live_syncing()
if live_syncing:
if live_syncing.is_stage_in_live_session():
await self._leave_current_session()
live_syncing.stop_all_live_sessions()
await omni.usd.get_context().close_stage_async()
await ui_test.human_delay(6)
async def _click_menu_item(self, item, right_click=False):
offset = ui_test.Vec2(5, 5)
pos = ui_test.Vec2(item.screen_position_x, item.screen_position_y) + offset
await ui_test.emulate_mouse_move(pos, 4)
await ui_test.human_delay(6)
await ui_test.emulate_mouse_click(right_click=right_click)
await ui_test.human_delay(6)
async def _create_test_usd(self, filename = 'test'):
await omni.client.delete_async(TEST_URL)
stage_url = TEST_URL + f"{filename}.usd"
layer = Sdf.Layer.CreateNew(stage_url)
stage = Usd.Stage.Open(layer.identifier)
self.assertIsNotNone(stage)
return stage
async def _create_test_sublayer_usd(self, filename = 'sublayer'):
layer_url = TEST_URL + f"{filename}.usd"
layer = Sdf.Layer.CreateNew(layer_url)
return layer
async def _expand_live_session_menu(self,
layer_identifier: str=None,
quick_join: str=None):
stop_or_show_live_session_widget(layer_identifier=layer_identifier, quick_join=quick_join)
await ui_test.human_delay(6)
menu = self._instance._live_session_menu
self.assertIsNotNone(menu)
items = ui.Inspector.get_children(menu)
await ui_test.human_delay(6)
return items
def _get_current_menu_item_string_list(self):
menu = ui.Menu.get_current()
self.assertIsNotNone(menu)
items = ui.Inspector.get_children(menu)
return _menu_items_as_string_list(items)
async def _click_on_current_menu(self, text: str):
menu = ui.Menu.get_current()
self.assertIsNotNone(menu)
items = ui.Inspector.get_children(menu)
item_str_list = self._get_current_menu_item_string_list()
self.assertIn(text, item_str_list)
item = _find_menu_item(items, text)
self.assertIsNotNone(item)
await self._click_menu_item(item)
await ui_test.human_delay(6)
async def _click_live_session_menu_item(self,
text: str, layer_identifier = None,
quick_join: str = None):
items = await self._expand_live_session_menu(layer_identifier, quick_join)
self.assertTrue(len(items) > 0)
item_str_list = _menu_items_as_string_list(items)
self.assertIn(text, item_str_list)
item = _find_menu_item(items, text)
self.assertIsNotNone(item)
await self._click_menu_item(item)
await ui_test.human_delay(6)
@MockLiveSyncingApi
async def test_create_session_dialog(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._click_live_session_menu_item("Create Session")
frame = ui_test.find("Live Session")
self.assertIsNotNone(frame)
cancal_button = ui_test.find(LIVE_SESSION_CANCEL_BUTTON_PATH)
self.assertIsNotNone(cancal_button)
await cancal_button.click()
await self._close_case()
async def _create_session(self, session_name: str=None):
await self._click_live_session_menu_item("Create Session")
frame = ui_test.find("Live Session")
self.assertIsNotNone(frame)
if session_name:
name_field = ui_test.find("Live Session//Frame/**/StringField[0]")
self.assertIsNotNone(name_field)
name_field.model.set_value(session_name)
ok_button = ui_test.find(LIVE_SESSION_CONFIRM_BUTTON_PATH)
self.assertIsNotNone(ok_button)
await ok_button.click()
await ui_test.human_delay(6)
async def _create_session_then_leave(self, session_name: str):
self.assertFalse(self.get_live_syncing().is_stage_in_live_session())
await self._create_session(session_name)
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
await self._leave_current_session()
self.assertFalse(self.get_live_syncing().is_stage_in_live_session())
async def _leave_current_session(self):
await self._click_live_session_menu_item("Leave Session")
if ui_test.find("Leave Session"):
button = ui_test.find(LEAVE_SESSION_CONFIRM_BUTTON_PATH)
self.assertIsNotNone(button)
await button.click()
await ui_test.human_delay(6)
@MockLiveSyncingApi
async def test_create_session(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test")
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
self.get_live_syncing().stop_all_live_sessions()
self.assertFalse(self.get_live_syncing().is_stage_in_live_session())
await self._close_case()
@MockLiveSyncingApi
async def test_leave_session(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._close_case()
@MockLiveSyncingApi
async def test_join_session(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session_then_leave("test")
await self._click_live_session_menu_item("Join Session")
frame = ui_test.find("Live Session")
self.assertIsNotNone(frame)
ok_button = ui_test.find(LIVE_SESSION_CONFIRM_BUTTON_PATH)
self.assertIsNotNone(ok_button)
await ok_button.click()
await ui_test.human_delay(6)
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
await self._close_case()
@MockLiveSyncingApi
@MockApiForLiveSessionManagement
async def test_join_session_participants(self):
stage = await self._create_test_usd("test")
await omni.usd.get_context().attach_stage_async(stage)
live_session_start_window = LiveSessionStartWindow(layers.get_layers(),
stage.GetRootLayer().identifier,
None)
await self._create_session("test")
live_session_start_window.visible = True
live_session_start_window.set_focus(True)
await ui_test.human_delay(6)
live_session_start_window.visible = False
await self._close_case()
@MockLiveSyncingApi
async def test_join_session_quick(self):
settings = carb.settings.get_settings()
before = settings.get_as_bool(QUICK_JOIN_ENABLED)
settings.set(QUICK_JOIN_ENABLED, True)
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session_then_leave("test")
await self._expand_live_session_menu(quick_join="test")
self.assertEqual("test", self.get_live_syncing().get_current_live_session().name)
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
settings.set(QUICK_JOIN_ENABLED, before)
await self._close_case()
@MockLiveSyncingApi
async def test_join_session_quick_create(self):
settings = carb.settings.get_settings()
before = settings.get_as_bool(QUICK_JOIN_ENABLED)
settings.set(QUICK_JOIN_ENABLED, True)
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._expand_live_session_menu(quick_join="test")
self.assertEqual("test", self.get_live_syncing().get_current_live_session().name)
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
settings.set(QUICK_JOIN_ENABLED, before)
await self._close_case()
@MockLiveSyncingApi
async def test_join_session_options(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session_then_leave(None)
await self._create_session_then_leave(None)
for i in range(3):
await self._create_session_then_leave(f"test_{i}")
await self._click_live_session_menu_item("Join Session")
frame = ui_test.find("Live Session")
self.assertIsNotNone(frame)
combo_box = ui_test.find("Live Session//Frame/**/ComboBox[0]")
items = combo_box.model.get_item_children(None)
names = [i.session.name for i in items]
carb.log_warn(names)
self.assertIn("Default", names)
self.assertIn("simulated_user_name___01", names)
for i in range(3):
self.assertIn(f"test_{i}", names)
index_of_second_test_usd = names.index('test_1')
self.assertTrue(index_of_second_test_usd > -1)
combo_box.model.get_item_value_model(None, 0).set_value(index_of_second_test_usd)
await ui_test.human_delay(6)
ok_button = ui_test.find(LIVE_SESSION_CONFIRM_BUTTON_PATH)
self.assertIsNotNone(ok_button)
await ok_button.click()
await ui_test.human_delay(6)
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
self.assertEqual("test_1", self.get_live_syncing().get_current_live_session().name)
await self._close_case()
@MockLiveSyncingApi
async def test_menu_item_join_with_session_link_without_stage(self):
self.assertIsNone(stop_or_show_live_session_widget())
await self._close_case()
@MockLiveSyncingApi
async def test_menu_item_join_with_session_link_dialog(self):
await omni.usd.get_context().new_stage_async()
await self._click_live_session_menu_item("Join With Session Link")
frame = ui_test.find("JOIN LIVE SESSION WITH LINK")
self.assertIsNotNone(frame)
cancal_button = ui_test.find(JOIN_LIVE_SESSION_WITH_LINK_CANCEL_BUTTON_PATH)
self.assertIsNotNone(cancal_button)
await cancal_button.click()
await self._close_case()
@MockLiveSyncingApi
async def test_menu_item_copy_session_link(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test")
layer = stage.GetRootLayer()
await self._click_live_session_menu_item("Copy Session Link", layer.identifier)
current_session = self.get_live_syncing().get_current_live_session()
live_session_link = omni.kit.clipboard.paste()
self.assertEqual(live_session_link, current_session.shared_link)
await self._close_case()
@MockLiveSyncingApi
async def test_menu_item_share_session_link(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
for i in range(3):
await self._create_session_then_leave(f"test_{i}")
await self._click_live_session_menu_item("Share Session Link")
frame = ui_test.find("SHARE LIVE SESSION LINK")
self.assertIsNotNone(frame)
combo_box = ui_test.find(SHARE_LIVE_SESSION_LINK_COMBO_BOX_PATH)
items = combo_box.model.get_item_children(None)
names = [i.session.name for i in items]
index_of_second_test_usd = -1
for i in range(3):
self.assertIn(f"test_{i}", names)
if names[i] == "test_1":
index_of_second_test_usd = i
self.assertTrue(index_of_second_test_usd > -1)
combo_box.model.get_item_value_model(None, 0).set_value(index_of_second_test_usd)
await ui_test.human_delay(6)
confirm_button = ui_test.find(SHARE_LIVE_SESSION_LINK_CONFIRM_BUTTON_PATH)
await confirm_button.click()
live_session_link = omni.kit.clipboard.paste()
self.assertEqual(live_session_link, items[index_of_second_test_usd].session.shared_link)
await self._close_case()
def _create_test_camera(self, name: str='camera'):
camera_path = f"/{name}"
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Camera", prim_path=camera_path)
return Sdf.Path(camera_path)
async def _setup_camera_follower_list(self, camera_path, maximum_users=3):
camera = omni.usd.get_context().get_stage().GetPrimAtPath(camera_path)
self.assertIsNotNone(camera)
return LiveSessionCameraFollowerList(omni.usd.get_context(), camera_path, maximum_users=maximum_users)
@MockLiveSyncingApi
async def test_live_session_camera_follower_list(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
camera_path = self._create_test_camera()
camera_follower_list = await self._setup_camera_follower_list(camera_path)
await self._close_case()
async def _bound_camera(self, shared_stage: Usd.Stage, user_id: str, camera_path: Sdf.Path):
if not camera_path:
camera_path = Sdf.Path.emptyPath
camera_path = Sdf.Path(camera_path)
bound_camera_property_path = pl_utils.get_bound_camera_property_path(user_id)
property_spec = pl_utils.get_or_create_property_spec(
shared_stage.GetRootLayer(), bound_camera_property_path,
Sdf.ValueTypeNames.String
)
builtin_camera_name = pl_utils.is_local_builtin_camera(camera_path)
if not builtin_camera_name:
property_spec.default = str(camera_path)
else:
property_spec.default = builtin_camera_name
if builtin_camera_name:
persp_camera = pl_utils.get_user_shared_root_path(user_id).AppendChild(builtin_camera_name)
camera_prim = shared_stage.DefinePrim(persp_camera, "Camera")
await ui_test.human_delay(12)
def _get_shared_stage(self, current_session: layers.LiveSession):
shared_data_stage_url = current_session.url + "/shared_data/users.live"
layer = Sdf.Layer.FindOrOpen(shared_data_stage_url)
if not layer:
layer = Sdf.Layer.CreateNew(shared_data_stage_url)
return Usd.Stage.Open(layer)
async def _follow_user(
self, shared_stage: Usd.Stage, user_id: str, following_user_id: str
):
following_user_property_path = pl_utils.get_following_user_property_path(user_id)
property_spec = pl_utils.get_or_create_property_spec(
shared_stage.GetRootLayer(), following_user_property_path,
Sdf.ValueTypeNames.String
)
property_spec.default = following_user_id
await ui_test.human_delay(6)
def _create_shared_stage(self):
current_session = self.get_live_syncing().get_current_live_session()
self.assertIsNotNone(current_session)
shared_stage = self._get_shared_stage(current_session)
self.assertIsNotNone(shared_stage)
return shared_stage
def _create_users(self, count):
return [f"user_{i}" for i in range(count)]
@MockLiveSyncingApi
async def test_live_session_camera_follower_list_user_join(self):
stage = await self._create_test_usd("test_camera")
usd_context = omni.usd.get_context()
presence_layer = pl.get_presence_layer_interface(usd_context)
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test_camera")
stage_url = usd_context.get_stage_url()
presence_layer = pl.get_presence_layer_interface(usd_context)
shared_stage = self._create_shared_stage()
camera_path = self._create_test_camera()
camera_follower_list = await self._setup_camera_follower_list(camera_path)
user_list = LiveSessionUserList(usd_context, stage_url)
users = self._create_users(3)
await self._bound_camera(shared_stage, users[0], camera_path)
for user_id in users:
join_new_simulated_user(user_id, user_id)
await ui_test.human_delay(6)
self.assertIsNotNone(presence_layer.get_bound_camera_prim(users[0]))
user_0 = self._get_user_in_session(users[0])
user_list._LiveSessionUserList__on_follow_user(
0.0,
0.0,
int(carb.input.MouseInput.LEFT_BUTTON),
None,
user_0
)
await ui_test.human_delay(6)
async def right_click_on(user):
user_list._LiveSessionUserList__on_mouse_clicked(
0.0,
0.0,
int(carb.input.MouseInput.RIGHT_BUTTON),
None,
user
)
await ui_test.human_delay(6)
timeline_session = omni.timeline.live_session.get_timeline_session()
self.assertFalse(timeline_session.is_presenter(user_0))
await right_click_on(user_0)
await self._click_on_current_menu("Set as Timeline Presenter")
self.assertTrue(timeline_session.is_presenter(user_0))
await right_click_on(user_0)
await self._click_on_current_menu("Withdraw Timeline Presenter")
self.assertFalse(timeline_session.is_presenter(user_0))
self.assertEqual(users[0], presence_layer.get_following_user_id())
await ui_test.human_delay(600)
for user_id in users:
quit_simulated_user(user_id)
await ui_test.human_delay(6)
await self._close_case()
@MockLiveSyncingApi
async def test_live_session_camera_follower_list_bound_change(self):
stage = await self._create_test_usd("test_camera")
usd_context = omni.usd.get_context()
presence_layer = pl.get_presence_layer_interface(usd_context)
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test_camera")
stage_url = usd_context.get_stage_url()
presence_layer = pl.get_presence_layer_interface(usd_context)
shared_stage = self._create_shared_stage()
camera_path_1 = self._create_test_camera("camera1")
camera_path_2 = self._create_test_camera("camera2")
camera_follower_list = await self._setup_camera_follower_list(camera_path_1)
user_list = LiveSessionUserList(usd_context, stage_url)
users = self._create_users(2)
for user_id in users:
join_new_simulated_user(user_id, user_id)
await ui_test.human_delay(6)
await self._bound_camera(shared_stage, users[0], camera_path_1)
await self._bound_camera(shared_stage, users[1], camera_path_2)
await self._bound_camera(shared_stage, users[0], camera_path_2)
await self._bound_camera(shared_stage, users[1], camera_path_1)
for user_id in users:
quit_simulated_user(user_id)
await ui_test.human_delay(6)
await self._close_case()
@MockLiveSyncingApi
async def test_live_session_camera_follower_list_user_join_exceed_maximum(self):
stage = await self._create_test_usd("test_camera")
usd_context = omni.usd.get_context()
presence_layer = pl.get_presence_layer_interface(usd_context)
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test_camera")
UI_MAXIMUM_USERS = 3
stage_url = usd_context.get_stage_url()
presence_layer = pl.get_presence_layer_interface(usd_context)
shared_stage = self._create_shared_stage()
camera_path = self._create_test_camera()
camera_follower_list = await self._setup_camera_follower_list(camera_path, maximum_users=UI_MAXIMUM_USERS)
user_list = LiveSessionUserList(usd_context, stage_url)
users = self._create_users(UI_MAXIMUM_USERS + 1)
for user in users:
await self._bound_camera(shared_stage, user, camera_path)
for user_id in users:
join_new_simulated_user(user_id, user_id)
await ui_test.human_delay(6)
for user_id in users:
quit_simulated_user(user_id)
await ui_test.human_delay(6)
await self._close_case()
@MockLiveSyncingApi
async def test_end_and_merge(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test")
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
await self._click_live_session_menu_item("End and Merge")
frame = ui_test.find("Merge Options")
self.assertIsNotNone(frame)
combo = ui_test.find(MERGE_OPTIONS_COMBO_BOX_PATH)
combo.model.get_item_value_model(None, 0).set_value(0)
ok_button = ui_test.find(MERGE_OPTIONS_CONFIRM_BUTTON_PATH)
self.assertIsNotNone(ok_button)
await ok_button.click()
await ui_test.human_delay(6)
await self._close_case()
@MockLiveSyncingApi
@MockApiForLiveSessionManagement
async def test_end_and_merge_save_file(self):
self.assertFalse(get_merge_and_stop_live_session_async_called())
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test")
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
await self._click_live_session_menu_item("End and Merge")
frame = ui_test.find("Merge Options")
self.assertIsNotNone(frame)
combo = ui_test.find(MERGE_OPTIONS_COMBO_BOX_PATH)
combo.model.get_item_value_model(None, 0).set_value(1)
ok_button = ui_test.find(MERGE_OPTIONS_CONFIRM_BUTTON_PATH)
self.assertIsNotNone(ok_button)
await ok_button.click()
await ui_test.human_delay(6)
self.assertTrue(get_merge_and_stop_live_session_async_called())
await self._close_case()
@MockLiveSyncingApi
async def test_end_and_merge_without_permission(self):
stage = await self._create_test_usd()
await omni.usd.get_context().attach_stage_async(stage)
await self._create_session("test")
current_session = self.get_live_syncing().get_current_live_session()
forbid_session_merge(current_session)
self.assertTrue(self.get_live_syncing().is_stage_in_live_session())
await self._click_live_session_menu_item("End and Merge")
frame = ui_test.find("Permission Denied")
self.assertIsNotNone(frame)
ok_button = ui_test.find(MERGE_PROMPT_LEAVE_BUTTON_PATH)
self.assertIsNotNone(ok_button)
await ok_button.click()
await ui_test.human_delay(6)
await self._close_case()
@MockLiveSyncingApi
async def test_reload_widget_on_layer(self):
stage = await self._create_test_usd("test")
usd_context = omni.usd.get_context()
await usd_context.attach_stage_async(stage)
await self._create_session("test")
layer = stage.GetSessionLayer()
window = omni.ui.Window(title='test_reload')
with window.frame:
reload_widget = build_reload_widget(layer.identifier, usd_context, True, True, False)
self.assertIsNotNone(reload_widget)
reload_widget.visible = True
await ui_test.human_delay(10)
window.width, window.height = 50, 50
reload_button = ui_test.find("test_reload//Frame/**/InvisibleButton[0]")
self.assertIsNotNone(reload_button)
await reload_button.click(right_click=True)
await ui_test.human_delay(6)
item_str_list = self._get_current_menu_item_string_list()
self.assertIn("Auto Reload", item_str_list)
self.assertIn("Reload Layer", item_str_list)
self.assertFalse(layers.get_layers_state(usd_context).is_auto_reload_layer(layer.identifier))
await self._click_on_current_menu("Auto Reload")
self.assertTrue(layers.get_layers_state(usd_context).is_auto_reload_layer(layer.identifier))
await reload_button.click(right_click=True)
await ui_test.human_delay(6)
await self._click_on_current_menu("Auto Reload")
self.assertFalse(layers.get_layers_state(usd_context).is_auto_reload_layer(layer.identifier))
await reload_button.click()
await ui_test.human_delay(6)
await self._close_case()
@MockLiveSyncingApi
@MockApiForLiveSessionManagement
async def test_reload_widget_on_outdated_layer(self):
stage = await self._create_test_usd("test")
usd_context = omni.usd.get_context()
await usd_context.attach_stage_async(stage)
await self._create_session("test")
all_layers = []
for i in range(3):
layer = await self._create_test_sublayer_usd(f"layer_{i}")
self.assertIsNotNone(layer)
all_layers.append(layer)
stage.GetRootLayer().subLayerPaths.append(layer.identifier)
window = omni.ui.Window(title='test_reload')
with window.frame:
reload_widget = build_reload_widget(all_layers[0].identifier, usd_context, True, True, False)
self.assertIsNotNone(reload_widget)
reload_widget.visible = True
await ui_test.human_delay(10)
window.width, window.height = 50, 50
reload_button = ui_test.find("test_reload//Frame/**/InvisibleButton[0]")
self.assertIsNotNone(reload_button)
layer = all_layers[0]
custom_data = layer.customLayerData
custom_data['test'] = random.randint(0, 10000000)
layer.customLayerData = custom_data
layer.Save(True)
await ui_test.human_delay(6)
append_outdated_layers(all_layers[0].identifier)
await reload_button.click()
await ui_test.human_delay(6)
clear_outdated_layers()
await self._close_case()
async def test_live_session_preferences(self):
preferences = register_page(LiveSessionPreferences())
omni.kit.window.preferences.show_preferences_window()
await ui_test.human_delay(6)
label = ui_test.find("Preferences//Frame/**/ScrollingFrame[0]/TreeView[0]/Label[*].text=='Live'")
await label.click()
await ui_test.human_delay(6)
self.assertIsNotNone(preferences._checkbox_quick_join_enabled)
self.assertIsNotNone(preferences._combobox_session_list_select)
await ui_test.human_delay(6)
omni.kit.window.preferences.hide_preferences_window()
unregister_page(preferences)
def _get_user_in_session(self, user_id):
current_session = self.get_live_syncing().get_current_live_session()
session_channel = current_session._session_channel()
return session_channel._peer_users.get(user_id, None)
@MockLiveSyncingApi
async def test_file_picker(self):
temp_dir = tempfile.TemporaryDirectory()
def file_save_handler(file_path: str, overwrite_existing: bool):
prefix = "file:/"
self.assertTrue(file_path.startswith(prefix))
nonlocal called
called = True
def file_open_handler(file_path: str, overwrite_existing: bool):
nonlocal called
called = True
filter_options = [
("(.*?)", "All Files (*.*)"),
]
FILE_PICKER_DIALOG_TITLE = "test file picker"
file_picker = FilePicker(
FILE_PICKER_DIALOG_TITLE,
FileBrowserMode.SAVE,
FileBrowserSelectionType.FILE_ONLY,
filter_options,
)
called = False
file_picker.set_file_selected_fn(file_save_handler)
file_picker.show(temp_dir.name, 'test_file_picker')
await ui_test.human_delay(6)
button = ui_test.find(f"{FILE_PICKER_DIALOG_TITLE}//Frame/**/Button[*].text=='Save'")
self.assertIsNotNone(button)
await button.click()
await ui_test.human_delay(6)
self.assertTrue(called)
file_picker = FilePicker(
FILE_PICKER_DIALOG_TITLE,
FileBrowserMode.OPEN,
FileBrowserSelectionType.FILE_ONLY,
filter_options,
)
called = False
file_picker.set_file_selected_fn(file_open_handler)
file_picker.show(temp_dir.name)
await ui_test.human_delay(6)
button = ui_test.find(f"{FILE_PICKER_DIALOG_TITLE}//Frame/**/Button[*].text=='Open'")
self.assertIsNotNone(button)
await button.click()
await ui_test.human_delay(6)
self.assertTrue(called)
| 32,194 |
Python
| 38.024242 | 135 | 0.647139 |
omniverse-code/kit/exts/omni.kit.widget.live_session_management/docs/CHANGELOG.md
|
# Changelog
Omniverse Kit Shared Live Session Widgets
## [1.1.3] - 2022-11-21
### Changed
- Prompt if layer is outdate or dirty before live.
## [1.1.2] - 2022-10-27
### Changed
- Fix deprecated API warnings.
## [1.1.1] - 2022-10-15
### Changed
- Fix issue to refresh session list.
## [1.1.0] - 2022-09-29
### Changed
- Supports sublayer live session workflow.
## [1.0.6] - 2022-09-02
### Changed
- Add name validator for session name input.
## [1.0.5] - 2022-08-30
### Changed
- Show menu options for join.
## [1.0.4] - 2022-08-25
### Changed
- Notifications for read-only stage.
## [1.0.3] - 2022-08-09
### Changed
- Notify user before quitting application that session is live still.
## [1.0.2] - 2022-07-19
### Changed
- Shows menu still even session is empty when it's not forcely quit.
## [1.0.1] - 2022-06-29
### Changed
- Supports more options to control session menus.
## [1.0.0] - 2022-06-15
### Fixed
- Initialize extension.
| 946 |
Markdown
| 19.148936 | 69 | 0.657505 |
omniverse-code/kit/exts/omni.kit.property.camera/omni/kit/property/camera/scripts/camera_properties.py
|
import os
import carb
import omni.ext
from typing import List
from pathlib import Path
from pxr import Kind, Sdf, Usd, UsdGeom, Vt
from omni.kit.property.usd.usd_property_widget import MultiSchemaPropertiesWidget, UsdPropertyUiEntry
from omni.kit.property.usd.usd_property_widget import create_primspec_token, create_primspec_float, create_primspec_bool, create_primspec_string
TEST_DATA_PATH = ""
class CameraPropertyExtension(omni.ext.IExt):
def __init__(self):
self._registered = False
super().__init__()
def on_startup(self, ext_id):
self._register_widget()
manager = omni.kit.app.get_app().get_extension_manager()
extension_path = manager.get_extension_path(ext_id)
global TEST_DATA_PATH
TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests")
def on_shutdown(self):
if self._registered:
self._unregister_widget()
def _register_widget(self):
import omni.kit.window.property as p
from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate
from . import CameraSchemaAttributesWidget
w = p.get_window()
if w:
w.register_widget(
"prim",
"camera",
CameraSchemaAttributesWidget(
"Camera",
UsdGeom.Camera,
[],
[
"cameraProjectionType",
"fthetaWidth",
"fthetaHeight",
"fthetaCx",
"fthetaCy",
"fthetaMaxFov",
"fthetaPolyA",
"fthetaPolyB",
"fthetaPolyC",
"fthetaPolyD",
"fthetaPolyE",
"fthetaPolyF",
"p0",
"p1",
"s0",
"s1",
"s2",
"s3",
"fisheyeResolutionBudget",
"fisheyeFrontFaceResolutionScale",
"interpupillaryDistance", # Only required for 'omniDirectionalStereo'
"isLeftEye", # Only required for 'omniDirectionalStereo'
"cameraSensorType",
"sensorModelPluginName",
"sensorModelConfig",
"sensorModelSignals",
"crossCameraReferenceName"
],
[],
),
)
self._registered = True
def _unregister_widget(self):
import omni.kit.window.property as p
w = p.get_window()
if w:
w.unregister_widget("prim", "camera")
self._registered = False
class CameraSchemaAttributesWidget(MultiSchemaPropertiesWidget):
def __init__(self, title: str, schema, schema_subclasses: list, include_list: list = [], exclude_list: list = []):
"""
Constructor.
Args:
title (str): Title of the widgets on the Collapsable Frame.
schema: The USD IsA schema or applied API schema to filter attributes.
schema_subclasses (list): list of subclasses
include_list (list): list of additional schema named to add
exclude_list (list): list of additional schema named to remove
"""
super().__init__(title, schema, schema_subclasses, include_list, exclude_list)
# custom attributes
cpt_tokens = Vt.TokenArray(9, ("pinhole", "fisheyeOrthographic", "fisheyeEquidistant", "fisheyeEquisolid", "fisheyePolynomial", "fisheyeSpherical", "fisheyeKannalaBrandtK3", "fisheyeRadTanThinPrism", "omniDirectionalStereo"))
cst_tokens = Vt.TokenArray(4, ("camera", "radar", "lidar", "rtxsensor"))
self.add_custom_schema_attribute("cameraProjectionType", lambda p: p.IsA(UsdGeom.Camera), None, "Projection Type", create_primspec_token(cpt_tokens, "pinhole"))
self.add_custom_schema_attribute("fthetaWidth", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(1936.0))
self.add_custom_schema_attribute("fthetaHeight", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(1216.0))
self.add_custom_schema_attribute("fthetaCx", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(970.942444))
self.add_custom_schema_attribute("fthetaCy", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(600.374817))
self.add_custom_schema_attribute("fthetaMaxFov", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(200.0))
self.add_custom_schema_attribute("fthetaPolyA", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(0.0))
self.add_custom_schema_attribute("fthetaPolyB", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(2.45417095720768e-3))
self.add_custom_schema_attribute("fthetaPolyC", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(3.72747912535942e-8))
self.add_custom_schema_attribute("fthetaPolyD", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(-1.43520517692508e-9))
self.add_custom_schema_attribute("fthetaPolyE", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(9.76061787817672e-13))
self.add_custom_schema_attribute("fthetaPolyF", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(0.0))
self.add_custom_schema_attribute("p0", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(-0.0003672190538065101))
self.add_custom_schema_attribute("p1", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(-0.0007413905358394097))
self.add_custom_schema_attribute("s0", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(-0.0005839984838196491))
self.add_custom_schema_attribute("s1", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(-0.0002193412417918993))
self.add_custom_schema_attribute("s2", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(0.0001936268547567258))
self.add_custom_schema_attribute("s3", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(-0.0002042473404798113))
self.add_custom_schema_attribute("fisheyeResolutionBudget", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(1.5))
self.add_custom_schema_attribute("fisheyeFrontFaceResolutionScale", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(1.0))
self.add_custom_schema_attribute("interpupillaryDistance", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_float(6.4))
self.add_custom_schema_attribute("isLeftEye", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_bool(False))
self.add_custom_schema_attribute("sensorModelPluginName", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_string())
self.add_custom_schema_attribute("sensorModelConfig", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_string())
self.add_custom_schema_attribute("sensorModelSignals", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_string())
self.add_custom_schema_attribute("crossCameraReferenceName", lambda p: p.IsA(UsdGeom.Camera), None, "", create_primspec_string())
self.add_custom_schema_attribute("cameraSensorType", lambda p: p.IsA(UsdGeom.Camera), None, "Sensor Type", create_primspec_token(cst_tokens, "camera"))
def on_new_payload(self, payload):
"""
See PropertyWidget.on_new_payload
"""
if not super().on_new_payload(payload):
return False
if not self._payload or len(self._payload) == 0:
return False
used = []
for prim_path in self._payload:
prim = self._get_prim(prim_path)
if not prim or not prim.IsA(self._schema):
return False
used += [attr for attr in prim.GetAttributes() if attr.GetName() in self._schema_attr_names and not attr.IsHidden()]
camProjTypeAttr = prim.GetAttribute("cameraProjectionType")
if prim.IsA(UsdGeom.Camera) and camProjTypeAttr.GetTypeName() == Sdf.ValueTypeNames.Token:
tokens = camProjTypeAttr.GetMetadata("allowedTokens")
if not tokens:
camProjTypeAttr.SetMetadata("allowedTokens", ["pinhole", "fisheyeOrthographic", "fisheyeEquidistant", "fisheyeEquisolid", "fisheyePolynomial", "fisheyeSpherical", "fisheyeKannalaBrandtK3", "fisheyeRadTanThinPrism", "omniDirectionalStereo"])
if self.is_custom_schema_attribute_used(prim):
used.append(None)
camSensorTypeAttr = prim.GetAttribute("cameraSensorType")
if prim.IsA(UsdGeom.Camera) and camSensorTypeAttr.GetTypeName() == Sdf.ValueTypeNames.Token:
tokens = camSensorTypeAttr.GetMetadata("allowedTokens")
if not tokens:
camSensorTypeAttr.SetMetadata("allowedTokens", ["camera", "radar", "lidar", "rtxsensor"])
return used
def _customize_props_layout(self, attrs):
from omni.kit.property.usd.custom_layout_helper import (
CustomLayoutFrame,
CustomLayoutGroup,
CustomLayoutProperty,
)
from omni.kit.window.property.templates import (
SimplePropertyWidget,
LABEL_WIDTH,
LABEL_HEIGHT,
HORIZONTAL_SPACING,
)
self.add_custom_schema_attributes_to_props(attrs)
anchor_prim = self._get_prim(self._payload[-1])
frame = CustomLayoutFrame(hide_extra=False)
with frame:
with CustomLayoutGroup("Lens"):
CustomLayoutProperty("focalLength", "Focal Length")
CustomLayoutProperty("focusDistance", "Focus Distance")
CustomLayoutProperty("fStop", "fStop")
CustomLayoutProperty("projection", "Projection")
CustomLayoutProperty("stereoRole", "Stereo Role")
with CustomLayoutGroup("Horizontal Aperture"):
CustomLayoutProperty("horizontalAperture", "Aperture")
CustomLayoutProperty("horizontalApertureOffset", "Offset")
with CustomLayoutGroup("Vertical Aperture"):
CustomLayoutProperty("verticalAperture", "Aperture")
CustomLayoutProperty("verticalApertureOffset", "Offset")
with CustomLayoutGroup("Clipping"):
CustomLayoutProperty("clippingPlanes", "Clipping Planes")
CustomLayoutProperty("clippingRange", "Clipping Range")
with CustomLayoutGroup("Fisheye Lens", collapsed=True):
CustomLayoutProperty("cameraProjectionType", "Projection Type")
CustomLayoutProperty("fthetaWidth", "Nominal Width")
CustomLayoutProperty("fthetaHeight", "Nominal Height")
CustomLayoutProperty("fthetaCx", "Optical Center X")
CustomLayoutProperty("fthetaCy", "Optical Center Y")
CustomLayoutProperty("fthetaMaxFov", "Max FOV")
CustomLayoutProperty("fthetaPolyA", "Poly k0")
CustomLayoutProperty("fthetaPolyB", "Poly k1")
CustomLayoutProperty("fthetaPolyC", "Poly k2")
CustomLayoutProperty("fthetaPolyD", "Poly k3")
CustomLayoutProperty("fthetaPolyE", "Poly k4")
CustomLayoutProperty("fthetaPolyF", "Poly k5")
CustomLayoutProperty("p0", "p0")
CustomLayoutProperty("p1", "p1")
CustomLayoutProperty("s0", "s0")
CustomLayoutProperty("s1", "s1")
CustomLayoutProperty("s2", "s2")
CustomLayoutProperty("s3", "s3")
CustomLayoutProperty("fisheyeResolutionBudget", "Max Fisheye Resolution (% of Viewport Resolution")
CustomLayoutProperty("fisheyeFrontFaceResolutionScale", "Front Face Resolution Scale")
CustomLayoutProperty("interpupillaryDistance", "Interpupillary Distance (cm)")
CustomLayoutProperty("isLeftEye", "Is left eye")
with CustomLayoutGroup("Shutter", collapsed=True):
CustomLayoutProperty("shutter:open", "Open")
CustomLayoutProperty("shutter:close", "Close")
with CustomLayoutGroup("Sensor Model", collapsed=True):
CustomLayoutProperty("cameraSensorType", "Sensor Type")
CustomLayoutProperty("sensorModelPluginName", "Sensor Plugin Name")
CustomLayoutProperty("sensorModelConfig", "Sensor Config")
CustomLayoutProperty("sensorModelSignals", "Sensor Signals")
with CustomLayoutGroup("Synthetic Data Generation", collapsed=True):
CustomLayoutProperty("crossCameraReferenceName", "Cross Camera Reference")
return frame.apply(attrs)
def get_additional_kwargs(self, ui_prop: UsdPropertyUiEntry):
"""
Override this function if you want to supply additional arguments when building the label or ui widget.
"""
additional_widget_kwargs = None
if ui_prop.prop_name == "fisheyeResolutionBudget":
additional_widget_kwargs = {"min": 0, "max": 10}
if ui_prop.prop_name == "fisheyeFrontFaceResolutionScale":
additional_widget_kwargs = {"min": 0, "max": 10}
return None, additional_widget_kwargs
| 14,637 |
Python
| 57.087301 | 260 | 0.581813 |
omniverse-code/kit/exts/omni.kit.property.camera/omni/kit/property/camera/scripts/__init__.py
|
from .camera_properties import *
| 33 |
Python
| 15.999992 | 32 | 0.787879 |
omniverse-code/kit/exts/omni.kit.property.camera/omni/kit/property/camera/tests/__init__.py
|
from .test_camera import *
from .test_prim_edits_and_auto_target import *
| 74 |
Python
| 23.999992 | 46 | 0.756757 |
omniverse-code/kit/exts/omni.kit.property.camera/omni/kit/property/camera/tests/test_prim_edits_and_auto_target.py
|
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import carb
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.ui.tests.test_base import OmniUiTest
from pxr import Kind, Sdf, Gf, Usd
class TestPrimEditsAndAutoTarget(omni.kit.test.AsyncTestCase):
def __init__(self, tests=()):
super().__init__(tests)
# Before running each test
async def setUp(self):
self._usd_context = omni.usd.get_context()
await self._usd_context.new_stage_async()
self._stage = self._usd_context.get_stage()
from omni.kit.test_suite.helpers import arrange_windows
await arrange_windows(topleft_window="Property", topleft_height=64, topleft_width=800.0)
await self.wait()
# After running each test
async def tearDown(self):
from omni.kit.test_suite.helpers import wait_stage_loading
await wait_stage_loading()
async def wait(self, updates=3):
for i in range(updates):
await omni.kit.app.get_app().next_update_async()
async def test_built_in_camera_editing(self):
from omni.kit.test_suite.helpers import select_prims, wait_stage_loading
from omni.kit import ui_test
# wait for material to load & UI to refresh
await wait_stage_loading()
prim_path = "/OmniverseKit_Persp"
await select_prims([prim_path])
# Loading all inputs
await self.wait()
all_widgets = ui_test.find_all("Property//Frame/**/.identifier!=''")
self.assertNotEqual(all_widgets, [])
for w in all_widgets:
id = w.widget.identifier
if id.startswith("float_slider_"):
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
await w.input(str(0.3456))
await ui_test.human_delay()
elif id.startswith("integer_slider_"):
w.widget.scroll_here_y(0.5)
attr = self._stage.GetPrimAtPath(prim_path).GetAttribute(id[15:])
await ui_test.human_delay()
old_value = attr.Get()
new_value = old_value + 1
await w.input(str(new_value))
await ui_test.human_delay()
elif id.startswith("drag_per_channel_int"):
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
sub_widgets = w.find_all("**/IntSlider[*]")
if sub_widgets == []:
sub_widgets = w.find_all("**/IntDrag[*]")
self.assertNotEqual(sub_widgets, [])
for child in sub_widgets:
child.model.set_value(0)
await child.input("9999")
await ui_test.human_delay()
elif id.startswith("drag_per_channel_"):
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
sub_widgets = w.find_all("**/FloatSlider[*]")
if sub_widgets == []:
sub_widgets = w.find_all("**/FloatDrag[*]")
self.assertNotEqual(sub_widgets, [])
for child in sub_widgets:
await child.input("0.12345")
await self.wait()
elif id.startswith("bool_"):
w.widget.scroll_here_y(0.5)
attr = self._stage.GetPrimAtPath(prim_path).GetAttribute(id[5:])
await ui_test.human_delay()
old_value = attr.Get()
new_value = not old_value
w.widget.model.set_value(new_value)
elif id.startswith("sdf_asset_"):
w.widget.scroll_here_y(0.5)
await ui_test.human_delay()
new_value = "testpath/abc.png"
w.widget.model.set_value(new_value)
await ui_test.human_delay()
# All property edits to built-in cameras should be retargeted into session layer.
root_layer = self._stage.GetRootLayer()
prim_spec = root_layer.GetPrimAtPath("/OmniverseKit_Persp")
self.assertTrue(bool(prim_spec))
| 4,561 |
Python
| 39.371681 | 96 | 0.578163 |
omniverse-code/kit/exts/omni.kit.property.camera/omni/kit/property/camera/tests/test_camera.py
|
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.kit import ui_test
from omni.ui.tests.test_base import OmniUiTest
from pxr import Kind, Sdf, Gf
import pathlib
class TestCameraWidget(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
from omni.kit.property.camera.scripts.camera_properties import TEST_DATA_PATH
self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute()
self._usd_path = TEST_DATA_PATH.absolute()
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()
async def test_camera_ui(self):
usd_context = omni.usd.get_context()
await self.docked_test_window(
window=self._w._window,
width=450,
height=675,
restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position = ui.DockPosition.BOTTOM)
test_file_path = self._usd_path.joinpath("camera_test.usda").absolute()
await usd_context.open_stage_async(str(test_file_path))
await omni.kit.app.get_app().next_update_async()
# Select the prim.
usd_context.get_selection().set_selected_prim_paths(["/World/Camera"], True)
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(10)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_camera_ui.png")
| 2,162 |
Python
| 35.661016 | 107 | 0.691489 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.