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.rtx.window.settings/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``omni.rtx.window.settings`` extension.
This project adheres to `Semantic Versioning <https://semver.org/>`.
## [Unreleased]
### Added
### Changed
### Removed
## [0.6.2] - 2022-09-20
### Added
- API to switch to explicitly switch to a renderer's settings and show the window.
## [0.6.1] - 2022-02-15
### Changed
- Made test suite runnable for carb-settings paths other than 'rtx'
## [0.6.0] - 2020-11-27
### Changed
- Added RenderSettingsFactory interface as entry point for dependent extensions, and removed existing get_rtx_settings_window. This is an interface breaking change
- Cleaned up Reset Button logic so any changes to settings result in reset button status being checked
- Set an active tab when you add any Render Settings (previously wasn't set)
- Start frames collapsed, and store collapse state during session
- try and delete widgets/models etc that don't get destroyed/garbage collected when UI is rebuilt due to circular references
## [0.5.4] - 2020-11-25
### Changed
- Added Registration process
- Moved hardcoded RTX registration out
- Custom tooltips support
## [0.5.3] - 2020-11-18
### Changed
- Additional fix to make labels wider
- Additional fix to Default to centre panel when Renderer Changed
- removed IRay
## [0.5.2] - 2020-11-16
### Changed
- Made labels wider to accommodate longer label width on single line
- Changed colour of float/int drag bars
- Default to centre panel when Renderer Changed
## [0.5.1] - 2020-11-11
### Changed
- Cleaned up code - type annotations, comments etc
- Added some tests
- Added skip_draw_when_clipped=True performance optimisation
## [0.5.0] - 2020-11-04
### Changed
- initial release
| 1,729 | Markdown | 25.615384 | 163 | 0.735107 |
omniverse-code/kit/exts/omni.rtx.window.settings/docs/README.md | # The RTX Renderer Settings Window Framework [omni.rtx.window.settings]
This extensions build the Base settings window and API so different rendering extensions can register their settings
| 191 | Markdown | 37.399993 | 116 | 0.827225 |
omniverse-code/kit/exts/omni.kit.mainwindow/omni/kit/mainwindow/scripts/main_window.py | import asyncio
import carb.settings
import omni.kit.app
import omni.ui as ui
class MainWindow(object):
def __init__(self):
# Show gray color the first several frames. It will hode the windows
# that are not yet docked.
self._ui_main_window = ui.MainWindow(show_foreground=True)
# this will be False for Release
self.get_main_menu_bar().visible = False
settings = carb.settings.get_settings()
margin_width = settings.get_as_float("ext/omni.kit.mainwindow/margin/width")
margin_height = settings.get_as_float("ext/omni.kit.mainwindow/margin/height")
background_color = settings.get_as_int("ext/omni.kit.mainwindow/backgroundColor")
self._ui_main_window.main_frame.set_style(
{"margin_width": margin_width, "margin_height": margin_height, "background_color": background_color}
)
self._setup_window_task = asyncio.ensure_future(self._dock_windows())
def destroy(self):
self._ui_main_window = None
def get_main_menu_bar(self) -> ui.MenuBar:
return self._ui_main_window.main_menu_bar
def get_status_bar_frame(self) -> ui.Frame:
return self._ui_main_window.status_bar_frame
def show_hide_menu(self):
self.get_main_menu_bar().visible = not self.get_main_menu_bar().visible
def show_hide_status_bar(self):
self.get_status_bar_frame().visible = not self.get_status_bar_frame().visible
async def _dock_windows(self):
stage_win = None
viewport = None
property_win = None
toolbar = None
console = None
frames = 3
while frames > 0:
# setup the docking Space
if not stage_win:
stage_win = ui.Workspace.get_window("Stage")
if not viewport:
viewport = ui.Workspace.get_window("Viewport")
if not property_win:
property_win = ui.Workspace.get_window("Property")
if not toolbar:
toolbar = ui.Workspace.get_window("Main ToolBar")
if not console:
console = ui.Workspace.get_window("Console")
if stage_win and viewport and property_win and toolbar and console:
break # early out
frames = frames - 1
await omni.kit.app.get_app().next_update_async()
main_dockspace = ui.Workspace.get_window("DockSpace")
if viewport:
viewport.dock_in(main_dockspace, ui.DockPosition.SAME)
if stage_win:
stage_win.dock_in(viewport, ui.DockPosition.RIGHT, 0.3)
if property_win:
if stage_win:
property_win.dock_in(stage_win, ui.DockPosition.BOTTOM, 0.5)
else:
property_win.dock_in(viewport, ui.DockPosition.RIGHT, 0.3)
if console:
console.dock_in(viewport, ui.DockPosition.BOTTOM, 0.3)
if toolbar:
toolbar.dock_in(viewport, ui.DockPosition.LEFT)
self._setup_window_task = None
# Hide foreground after 5 frames. It's enough for windows to appear.
for _ in range(5):
await omni.kit.app.get_app().next_update_async()
self._ui_main_window.show_foreground = False
| 3,270 | Python | 33.431579 | 112 | 0.606422 |
omniverse-code/kit/exts/omni.kit.mainwindow/omni/kit/mainwindow/scripts/extension.py | import omni.ext
from .main_window import MainWindow
global g_main_window
g_main_window = None
def get_main_window() -> MainWindow:
global g_main_window
return g_main_window
class MainWindowExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
global g_main_window
self._main_window = MainWindow()
g_main_window = self._main_window
def on_shutdown(self):
global g_main_window
if (g_main_window):
g_main_window.destroy()
self._main_window = None
g_main_window = None
| 727 | Python | 23.266666 | 119 | 0.662999 |
omniverse-code/kit/exts/omni.kit.mainwindow/omni/kit/mainwindow/tests/test_main_window.py | ## Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from ..scripts.extension import get_main_window
from omni.ui.tests.test_base import OmniUiTest
import omni.kit.app
import omni.kit.mainwindow
import omni.kit.test
import omni.ui as ui
import carb.settings
from pathlib import Path
GOLDEN_IMAGE_PATH = Path(omni.kit.test.get_test_output_path()).resolve().absolute()
class Test(OmniUiTest):
# Before running each test
async def setUp(self):
pass
# After running each test
async def tearDown(self):
pass
async def test_dockspace(self):
"""Checking mainwindow is initialized"""
self.assertIsNotNone(get_main_window())
await omni.kit.app.get_app().next_update_async()
main_dockspace = ui.Workspace.get_window("DockSpace")
self.assertIsNotNone(main_dockspace)
async def test_windows(self):
"""Testing windows"""
await self.create_test_area()
width = ui.Workspace.get_main_window_width()
height = ui.Workspace.get_main_window_height()
window1 = ui.Window("Viewport", width=width, height=height)
window2 = ui.Window("Viewport", width=width, height=height)
window3 = ui.Window("Something Else", width=width, height=height)
with window1.frame:
ui.Rectangle(style={"background_color": ui.color.indigo})
with window2.frame:
ui.Label("NVIDIA")
for i in range(10):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=GOLDEN_IMAGE_PATH)
for i in range(3):
await omni.kit.app.get_app().next_update_async()
| 2,054 | Python | 32.688524 | 83 | 0.685492 |
omniverse-code/kit/exts/omni.kit.mainwindow/omni/kit/mainwindow/tests/__init__.py | from .test_main_window import *
| 32 | Python | 15.499992 | 31 | 0.75 |
omniverse-code/kit/exts/omni.kit.mainwindow/docs/index.rst | omni.kit.mainwindow
###########################
This class describe the MainWindow workflow, that include 3 main components
# MainMenuBar
# DockSpace
# StatusBar
Python API Reference
*********************
.. automodule:: omni.kit.mainwindow
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:imported-members:
.. toctree::
:maxdepth: 1
CHANGELOG
| 390 | reStructuredText | 16.772727 | 76 | 0.625641 |
omniverse-code/kit/exts/omni.kit.window.stats/config/extension.toml | [package]
version = "0.1.2"
category = "Core"
feature = true
[dependencies]
"omni.stats" = {}
"omni.ui" = {}
"omni.usd.libs" = {}
"omni.kit.menu.utils" = {}
[[python.module]]
name = "omni.kit.window.stats"
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window",
]
dependencies = [
"omni.kit.renderer.capture",
"omni.kit.mainwindow",
"omni.kit.ui_test",
]
| 437 | TOML | 14.642857 | 41 | 0.601831 |
omniverse-code/kit/exts/omni.kit.window.stats/omni/kit/window/stats/stats_window.py | import carb
import sys
import os
import omni.ext
import omni.ui
import omni.kit.ui
import omni.kit.app
import omni.stats
import carb.settings
WINDOW_NAME = "Statistics"
class Extension(omni.ext.IExt):
"""Statistics view extension"""
class ComboBoxItem(omni.ui.AbstractItem):
def __init__(self, text):
super().__init__()
self.model = omni.ui.SimpleStringModel(text)
class ComboBoxModel(omni.ui.AbstractItemModel):
def __init__(self):
super().__init__()
self._current_index = omni.ui.SimpleIntModel()
self._current_index.add_value_changed_fn(self._changed_model)
self._items = []
def _changed_model(self, model):
# update stats at the end of the frame instead
self._item_changed(None)
def get_item_children(self, item):
return self._items
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
def _update_scopes(self, stat_iface):
scopes = stat_iface.get_scopes()
scope_count = len(scopes)
item_count = len(self._items)
if item_count != scope_count:
selected_scope = ""
if item_count != 0:
selected_scope = self._current_index
self._items.clear()
for i in range(scope_count):
scope = scopes[i]
self._items.append(Extension.ComboBoxItem(scope["name"]))
# verify if a scope is already selected
if selected_scope == scope["name"]:
self._current_index.as_int = i
# A default selection if it is not already picked
if not selected_scope:
self._current_index.as_int = 0
# update stats
if scope_count != 0:
selected_scope_node = scopes[self._current_index.as_int]
self._item_changed(None)
return selected_scope_node
return None
def __init__(self):
self._window = None
self._app = None
self._stats_mode = None
self._scope_description = None
self._stats = None
self._stat_grid = None
self._scope_combo_model = None
self._stats_names = None
self._stats_values = None
self._stats_desc = None
self._show_names = False # Don't show names by default, just descriptions
super().__init__()
def get_name(self):
return WINDOW_NAME
def _menu_callback(self, menu, value):
self._window.visible = value
# update menu state
if self._menu:
omni.kit.ui.get_editor_menu().set_value(f"Window/{WINDOW_NAME}", value)
def on_startup(self):
self._app = omni.kit.app.get_app()
self._stats = omni.stats.get_stats_interface()
menu_path = f"Window/{WINDOW_NAME}"
self._window = omni.ui.Window(
WINDOW_NAME,
width=400,
height=600,
padding_x=10,
visible=False,
dockPreference=omni.ui.DockPreference.RIGHT_TOP,
)
self._window.deferred_dock_in("Details", omni.ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE)
with self._window.frame:
with omni.ui.VStack(height=0, spacing=8):
with omni.ui.HStack():
omni.ui.Label("Scope to display:")
self._scope_combo_model = Extension.ComboBoxModel()
self._scope_combo = omni.ui.ComboBox(self._scope_combo_model)
with omni.ui.HStack():
omni.ui.Label("Scope description:")
self._scope_description = omni.ui.Label("", word_wrap=True)
omni.ui.Line()
# green color for header
style_header = {"color": 0xFF00B976}
with omni.ui.HStack(style=style_header):
if self._show_names:
omni.ui.Label("Name", alignment=omni.ui.Alignment.LEFT)
omni.ui.Label("Description", alignment=omni.ui.Alignment.LEFT)
omni.ui.Label("Amount", alignment=omni.ui.Alignment.RIGHT)
omni.ui.Line()
# For performance, draw with two labels (per-frame update)
with omni.ui.HStack(style=style_header):
if self._show_names:
self._stats_names = omni.ui.Label("", alignment=omni.ui.Alignment.LEFT)
self._stats_desc = omni.ui.Label("", alignment=omni.ui.Alignment.LEFT)
self._stats_values = omni.ui.Label("", alignment=omni.ui.Alignment.RIGHT)
try:
editor_menu = omni.kit.ui.get_editor_menu()
self._menu = editor_menu.add_item(menu_path, self._menu_callback, toggle=True)
editor_menu.set_priority(menu_path, 15)
except:
pass
self._sub_event = self._app.get_update_event_stream().create_subscription_to_pop(
self._on_update, name="omni.stats frame statistics"
)
self._window.set_visibility_changed_fn(self._visiblity_changed_fn)
def on_shutdown(self):
self._menu = None
self._window = None
self._sub_event = None
def _visiblity_changed_fn(self, visible):
# update menu state
if self._menu:
omni.kit.ui.get_editor_menu().set_value(f"Window/{WINDOW_NAME}", visible)
carb.settings.get_settings().set("/profiler/enableDeviceUtilizationQuery", visible)
def _update_stats(self, scope_node):
stat_nodes = self._stats.get_stats(scope_node["scopeId"])
stats_names = ""
stats_values = ""
stats_descs = ""
# Sort nodes in descending order based on the alphabet
stat_nodes = sorted(stat_nodes, key=lambda node: node["description"].lower(), reverse=False)
for node in stat_nodes:
if self._show_names:
stats_names += node["name"] + "\n"
stats_descs += node["description"] + "\n"
if node["type"] == 0:
stats_values += "{:,}".format(node["value"]) + "\n"
elif node["type"] == 1:
stats_values += "{:.3f}".format(node["value"]) + "\n"
if self._show_names:
self._stats_names.text = stats_names
self._stats_values.text = stats_values
self._stats_desc.text = stats_descs
def _on_update(self, evt):
if not self._window.visible:
return
scope_node = self._scope_combo_model._update_scopes(self._stats)
if scope_node is not None:
self._scope_description.text = scope_node["description"]
self._update_stats(scope_node)
| 6,944 | Python | 37.15934 | 100 | 0.548819 |
omniverse-code/kit/exts/omni.kit.window.stats/omni/kit/window/stats/__init__.py | from .stats_window import *
| 28 | Python | 13.499993 | 27 | 0.75 |
omniverse-code/kit/exts/omni.kit.window.stats/omni/kit/window/stats/tests/__init__.py | from .test_stats import *
| 26 | Python | 12.499994 | 25 | 0.730769 |
omniverse-code/kit/exts/omni.kit.window.stats/omni/kit/window/stats/tests/test_stats.py | import asyncio
import carb
import unittest
import carb
import omni.kit.test
import omni.usd
import omni.ui as ui
from omni.kit import ui_test
class TestStats(omni.kit.test.AsyncTestCase):
async def setUp(self):
pass
async def tearDown(self):
pass
async def test_stats_window(self):
stats_window = ui_test.find("Statistics")
stats_window.widget.visible = True
await stats_window.focus()
line_count = [0, 0, 0]
for index in range(0, 3):
# can't use widget.click as open combobox has no readable size and clicks goto stage window
stats_window.find("**/ComboBox[*]").model.get_item_value_model(None, 0).set_value(index)
await ui_test.human_delay(10)
for widget in stats_window.find_all("**/Label[*]"):
line_count[index] += len(widget.widget.text.split('\n'))
self.assertNotEqual(line_count[0], 0)
self.assertNotEqual(line_count[1], 0)
self.assertNotEqual(line_count[2], 0)
| 1,031 | Python | 29.35294 | 103 | 0.634336 |
omniverse-code/kit/exts/omni.kit.manipulator.prim/omni/kit/manipulator/prim/model.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from __future__ import annotations
import asyncio
import math
import traceback
from enum import Enum, Flag, IntEnum, auto
from typing import Dict, List, Sequence, Set, Tuple, Union
import concurrent.futures
import carb
import carb.dictionary
import carb.events
import carb.profiler
import carb.settings
import omni.kit.app
from omni.kit.async_engine import run_coroutine
import omni.kit.commands
import omni.kit.undo
import omni.timeline
from omni.kit.manipulator.tool.snap import SnapProviderManager
from omni.kit.manipulator.tool.snap import settings_constants as snap_c
from omni.kit.manipulator.transform import AbstractTransformManipulatorModel, Operation
from omni.kit.manipulator.transform.gestures import (
RotateChangedGesture,
RotateDragGesturePayload,
ScaleChangedGesture,
ScaleDragGesturePayload,
TransformDragGesturePayload,
TranslateChangedGesture,
TranslateDragGesturePayload,
)
from omni.kit.manipulator.transform.settings_constants import c
from omni.kit.manipulator.transform.settings_listener import OpSettingsListener, SnapSettingsListener
from omni.ui import scene as sc
from pxr import Gf, Sdf, Tf, Usd, UsdGeom, UsdUtils
from .settings_constants import Constants as prim_c
from .utils import *
# Settings needed for zero-gravity
TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_ENABLED = "/app/transform/gizmoCustomManipulatorEnabled"
TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_PRIMS = "/app/transform/gizmoCustomManipulatorPrims"
TRANSFORM_GIZMO_IS_USING = "/app/transform/gizmoIsUsing"
TRANSFORM_GIZMO_TRANSLATE_DELTA_XYZ = "/app/transform/gizmoTranslateDeltaXYZ"
TRANSFORM_GIZMO_PIVOT_WORLD_POSITION = "/app/transform/tempPivotWorldPosition"
TRANSFORM_GIZMO_ROTATE_DELTA_XYZW = "/app/transform/gizmoRotateDeltaXYZW"
TRANSFORM_GIZMO_SCALE_DELTA_XYZ = "/app/transform/gizmoScaleDeltaXYZ"
TRANSLATE_DELAY_FRAME_SETTING = "/exts/omni.kit.manipulator.prim/visual/delayFrame"
class OpFlag(Flag):
TRANSLATE = auto()
ROTATE = auto()
SCALE = auto()
class Placement(Enum):
LAST_PRIM_PIVOT = auto()
SELECTION_CENTER = auto()
BBOX_CENTER = auto()
REF_PRIM = auto()
BBOX_BASE = auto()
class ManipulationMode(IntEnum):
PIVOT = 0 # transform around manipulator pivot
UNIFORM = 1 # set same world transform from manipulator to all prims equally
INDIVIDUAL = 2 # 2: (TODO) transform around each prim's own pivot respectively
class Viewport1WindowState:
def __init__(self):
self._focused_windows = None
focused_windows = []
try:
# For some reason is_focused may return False, when a Window is definitely in fact is the focused window!
# And there's no good solution to this when multiple Viewport-1 instances are open; so we just have to
# operate on all Viewports for a given usd_context.
import omni.kit.viewport_legacy as vp
vpi = vp.acquire_viewport_interface()
for instance in vpi.get_instance_list():
window = vpi.get_viewport_window(instance)
if not window:
continue
focused_windows.append(window)
if focused_windows:
self._focused_windows = focused_windows
for window in self._focused_windows:
# Disable the selection_rect, but enable_picking for snapping
window.disable_selection_rect(True)
# Schedule a picking request so if snap needs it later, it may arrive by the on_change event
window.request_picking()
except Exception:
pass
def get_picked_world_pos(self):
if self._focused_windows:
# Try to reduce to the focused window now after, we've had some mouse-move input
focused_windows = [window for window in self._focused_windows if window.is_focused()]
if focused_windows:
self._focused_windows = focused_windows
for window in self._focused_windows:
window.disable_selection_rect(True)
# request picking FOR NEXT FRAME
window.request_picking()
# get PREVIOUSLY picked pos, it may be None the first frame but that's fine
return window.get_picked_world_pos()
return None
def __del__(self):
self.destroy()
def destroy(self):
self._focused_windows = None
def get_usd_context_name(self):
if self._focused_windows:
return self._focused_windows[0].get_usd_context_name()
else:
return ""
class PrimTransformChangedGestureBase:
def __init__(self, usd_context_name: str = "", viewport_api=None):
self._settings = carb.settings.get_settings()
self._usd_context_name = usd_context_name
self._usd_context = omni.usd.get_context(self._usd_context_name)
self._viewport_api = viewport_api # VP2
self._vp1_window_state = None
self._stage_id = None
def on_began(self, payload_type=TransformDragGesturePayload):
self._viewport_on_began()
if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, payload_type):
return
model = self.sender.model
if not model:
return
item = self.gesture_payload.changing_item
self._current_editing_op = item.operation
# NOTE! self._begin_xform has no scale. To get the full matrix, do self._begin_scale_mtx * self._begin_xform
self._begin_xform = Gf.Matrix4d(*model.get_as_floats(model.get_item("no_scale_transform_manipulator")))
manip_scale = Gf.Vec3d(*model.get_as_floats(model.get_item("scale_manipulator")))
self._begin_scale_mtx = Gf.Matrix4d(1.0)
self._begin_scale_mtx.SetScale(manip_scale)
model.set_floats(model.get_item("viewport_fps"), [0.0])
model.on_began(self.gesture_payload)
def on_changed(self, payload_type=TransformDragGesturePayload):
if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, payload_type):
return
model = self.sender.model
if not model:
return
if self._viewport_api:
fps = self._viewport_api.frame_info.get("fps")
model.set_floats(model.get_item("viewport_fps"), [fps])
model.on_changed(self.gesture_payload)
def on_ended(self, payload_type=TransformDragGesturePayload):
self._viewport_on_ended()
if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, payload_type):
return
model = self.sender.model
if not model:
return
item = self.gesture_payload.changing_item
if item.operation != self._current_editing_op:
return
model.set_floats(model.get_item("viewport_fps"), [0.0])
model.on_ended(self.gesture_payload)
self._current_editing_op = None
def on_canceled(self, payload_type=TransformDragGesturePayload):
self._viewport_on_ended()
if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, payload_type):
return
model = self.sender.model
if not model:
return
item = self.gesture_payload.changing_item
if item.operation != self._current_editing_op:
return
model.on_canceled(self.gesture_payload)
self._current_editing_op = None
def _publish_delta(self, operation: Operation, delta: List[float]): # pragma: no cover
if operation == Operation.TRANSLATE:
self._settings.set_float_array(TRANSFORM_GIZMO_TRANSLATE_DELTA_XYZ, delta)
elif operation == Operation.ROTATE:
self._settings.set_float_array(TRANSFORM_GIZMO_ROTATE_DELTA_XYZW, delta)
elif operation == Operation.SCALE:
self._settings.set_float_array(TRANSFORM_GIZMO_SCALE_DELTA_XYZ, delta)
def __set_viewport_manipulating(self, value: int):
# Signal that user-manipulation has started for this stage
if self._stage_id is None:
self._stage_id = UsdUtils.StageCache.Get().GetId(self._usd_context.get_stage()).ToLongInt()
key = f"/app/viewport/{self._stage_id}/manipulating"
cur_value = self._settings.get(key) or 0
self._settings.set(key, cur_value + value)
def _viewport_on_began(self):
self._viewport_on_ended()
if self._viewport_api is None:
self._vp1_window_state = Viewport1WindowState()
self.__set_viewport_manipulating(1)
def _viewport_on_ended(self):
if self._vp1_window_state:
self._vp1_window_state.destroy()
self._vp1_window_state = None
if self._stage_id:
self.__set_viewport_manipulating(-1)
self._stage_id = None
class PrimTranslateChangedGesture(TranslateChangedGesture, PrimTransformChangedGestureBase):
def __init__(self, snap_manager: SnapProviderManager, **kwargs):
PrimTransformChangedGestureBase.__init__(self, **kwargs)
TranslateChangedGesture.__init__(self)
self._accumulated_translate = Gf.Vec3d(0)
self._snap_manager = snap_manager
def on_began(self):
PrimTransformChangedGestureBase.on_began(self, TranslateDragGesturePayload)
self._accumulated_translate = Gf.Vec3d(0)
model = self._get_model(TranslateDragGesturePayload)
if model and self._can_snap(model):
# TODO No need for gesture=self when VP1 has viewport_api
self._snap_manager.on_began(model.consolidated_xformable_prim_data_curr.keys(), gesture=self)
if model:
model.set_floats(model.get_item("translate_delta"), [0, 0, 0])
def on_ended(self):
PrimTransformChangedGestureBase.on_ended(self, TranslateDragGesturePayload)
model = self._get_model(TranslateDragGesturePayload)
if model and self._can_snap(model):
self._snap_manager.on_ended()
def on_canceled(self):
PrimTransformChangedGestureBase.on_canceled(self, TranslateDragGesturePayload)
model = self._get_model(TranslateDragGesturePayload)
if model and self._can_snap(model):
self._snap_manager.on_ended()
@carb.profiler.profile
def on_changed(self):
PrimTransformChangedGestureBase.on_changed(self, TranslateDragGesturePayload)
model = self._get_model(TranslateDragGesturePayload)
if not model:
return
manip_xform = Gf.Matrix4d(*model.get_as_floats(model.get_item("no_scale_transform_manipulator")))
new_manip_xform = Gf.Matrix4d(manip_xform)
rotation_mtx = manip_xform.ExtractRotationMatrix()
rotation_mtx.Orthonormalize()
translate_delta = self.gesture_payload.moved_delta
translate = self.gesture_payload.moved
axis = self.gesture_payload.axis
# slow Gf.Vec3d(*translate_delta)
translate_delta = Gf.Vec3d(translate_delta[0], translate_delta[1], translate_delta[2])
if model.op_settings_listener.translation_mode == c.TRANSFORM_MODE_LOCAL:
translate_delta = translate_delta * rotation_mtx
self._accumulated_translate += translate_delta
def apply_position(snap_world_pos=None, snap_world_orient=None, keep_spacing: bool = True):
nonlocal new_manip_xform
if self.state != sc.GestureState.CHANGED:
return
# only set translate if no snap or only snap to position
item_name = "translate"
if snap_world_pos and (
math.isfinite(snap_world_pos[0])
and math.isfinite(snap_world_pos[1])
and math.isfinite(snap_world_pos[2])
):
if snap_world_orient is None:
new_manip_xform.SetTranslateOnly(Gf.Vec3d(snap_world_pos[0], snap_world_pos[1], snap_world_pos[2]))
new_manip_xform = self._begin_scale_mtx * new_manip_xform
else:
new_manip_xform.SetTranslateOnly(Gf.Vec3d(snap_world_pos[0], snap_world_pos[1], snap_world_pos[2]))
new_manip_xform.SetRotateOnly(snap_world_orient)
# set transform if snap both position and orientation
item_name = "no_scale_transform_manipulator"
else:
new_manip_xform.SetTranslateOnly(self._begin_xform.ExtractTranslation() + self._accumulated_translate)
new_manip_xform = self._begin_scale_mtx * new_manip_xform
model.set_floats(model.get_item("translate_delta"), translate_delta)
if model.custom_manipulator_enabled:
self._publish_delta(Operation.TRANSLATE, translate_delta)
if keep_spacing is False:
mode_item = model.get_item("manipulator_mode")
prev_mode = model.get_as_ints(mode_item)
model.set_ints(mode_item, [int(ManipulationMode.UNIFORM)])
model.set_floats(model.get_item(item_name), flatten(new_manip_xform))
if keep_spacing is False:
model.set_ints(mode_item, prev_mode)
# only do snap to surface if drag the center point
if (
model.snap_settings_listener.snap_enabled
and model.snap_settings_listener.snap_provider
and axis == [1, 1, 1]
):
ndc_location = None
if self._viewport_api:
# No mouse location is available, have to convert back to NDC space
ndc_location = self.sender.transform_space(
sc.Space.WORLD, sc.Space.NDC, self.gesture_payload.ray_closest_point
)
if self._snap_manager.get_snap_pos(
new_manip_xform,
ndc_location,
self.sender.scene_view,
lambda **kwargs: apply_position(
kwargs.get("position", None), kwargs.get("orient", None), kwargs.get("keep_spacing", True)
),
):
return
apply_position()
def _get_model(self, payload_type) -> PrimTransformModel:
if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, payload_type):
return None
return self.sender.model
def _can_snap(self, model: PrimTransformModel):
axis = self.gesture_payload.axis
if (
model.snap_settings_listener.snap_enabled
and model.snap_settings_listener.snap_provider
and axis == [1, 1, 1]
):
return True
return False
class PrimRotateChangedGesture(RotateChangedGesture, PrimTransformChangedGestureBase):
def __init__(self, **kwargs):
PrimTransformChangedGestureBase.__init__(self, **kwargs)
RotateChangedGesture.__init__(self)
def on_began(self):
PrimTransformChangedGestureBase.on_began(self, RotateDragGesturePayload)
model = self.sender.model
if model:
model.set_floats(model.get_item("rotate_delta"), [0, 0, 0, 0])
def on_ended(self):
PrimTransformChangedGestureBase.on_ended(self, RotateDragGesturePayload)
def on_canceled(self):
PrimTransformChangedGestureBase.on_canceled(self, RotateDragGesturePayload)
@carb.profiler.profile
def on_changed(self):
PrimTransformChangedGestureBase.on_changed(self, RotateDragGesturePayload)
if (
not self.gesture_payload
or not self.sender
or not isinstance(self.gesture_payload, RotateDragGesturePayload)
):
return
model = self.sender.model
if not model:
return
axis = self.gesture_payload.axis
angle = self.gesture_payload.angle
angle_delta = self.gesture_payload.angle_delta
screen_space = self.gesture_payload.screen_space
free_rotation = self.gesture_payload.free_rotation
axis = Gf.Vec3d(*axis[:3])
rotate = Gf.Rotation(axis, angle)
delta_axis = Gf.Vec4d(*axis, 0.0)
rot_matrix = Gf.Matrix4d(1)
rot_matrix.SetRotate(rotate)
if free_rotation:
rotate = Gf.Rotation(axis, angle_delta)
rot_matrix = Gf.Matrix4d(1)
rot_matrix.SetRotate(rotate)
xform = Gf.Matrix4d(*model.get_as_floats(model.get_item("no_scale_transform_manipulator")))
full_xform = self._begin_scale_mtx * xform
translate = full_xform.ExtractTranslation()
no_translate_mtx = Gf.Matrix4d(full_xform)
no_translate_mtx.SetTranslateOnly(Gf.Vec3d(0))
no_translate_mtx = no_translate_mtx * rot_matrix
new_transform_matrix = no_translate_mtx.SetTranslateOnly(translate)
delta_axis = no_translate_mtx * delta_axis
elif model.op_settings_listener.rotation_mode == c.TRANSFORM_MODE_GLOBAL or screen_space:
begin_full_xform = self._begin_scale_mtx * self._begin_xform
translate = begin_full_xform.ExtractTranslation()
no_translate_mtx = Gf.Matrix4d(begin_full_xform)
no_translate_mtx.SetTranslateOnly(Gf.Vec3d(0))
no_translate_mtx = no_translate_mtx * rot_matrix
new_transform_matrix = no_translate_mtx.SetTranslateOnly(translate)
delta_axis = no_translate_mtx * delta_axis
else:
self._begin_xform = Gf.Matrix4d(*model.get_as_floats(model.get_item("no_scale_transform_manipulator")))
new_transform_matrix = self._begin_scale_mtx * rot_matrix * self._begin_xform
delta_axis.Normalize()
delta_rotate = Gf.Rotation(delta_axis[:3], angle_delta)
quat = delta_rotate.GetQuaternion()
real = quat.GetReal()
imaginary = quat.GetImaginary()
rd = [imaginary[0], imaginary[1], imaginary[2], real]
model.set_floats(model.get_item("rotate_delta"), rd)
if model.custom_manipulator_enabled:
self._publish_delta(Operation.ROTATE, rd)
model.set_floats(model.get_item("rotate"), flatten(new_transform_matrix))
class PrimScaleChangedGesture(ScaleChangedGesture, PrimTransformChangedGestureBase):
def __init__(self, **kwargs):
PrimTransformChangedGestureBase.__init__(self, **kwargs)
ScaleChangedGesture.__init__(self)
def on_began(self):
PrimTransformChangedGestureBase.on_began(self, ScaleDragGesturePayload)
model = self.sender.model
if model:
model.set_floats(model.get_item("scale_delta"), [0, 0, 0])
def on_ended(self):
PrimTransformChangedGestureBase.on_ended(self, ScaleDragGesturePayload)
def on_canceled(self):
PrimTransformChangedGestureBase.on_canceled(self, ScaleDragGesturePayload)
@carb.profiler.profile
def on_changed(self):
PrimTransformChangedGestureBase.on_changed(self, ScaleDragGesturePayload)
if not self.gesture_payload or not self.sender or not isinstance(self.gesture_payload, ScaleDragGesturePayload):
return
model = self.sender.model
if not model:
return
axis = self.gesture_payload.axis
scale = self.gesture_payload.scale
axis = Gf.Vec3d(*axis[:3])
scale_delta = scale * axis
scale_vec = Gf.Vec3d()
for i in range(3):
scale_vec[i] = scale_delta[i] if scale_delta[i] else 1
scale_matrix = Gf.Matrix4d(1.0)
scale_matrix.SetScale(scale_vec)
scale_matrix *= self._begin_scale_mtx
new_transform_matrix = scale_matrix * self._begin_xform
s = Gf.Vec3d(*model.get_as_floats(model.get_item("scale_manipulator")))
sd = [s_n / s_o for s_n, s_o in zip([scale_matrix[0][0], scale_matrix[1][1], scale_matrix[2][2]], s)]
model.set_floats(model.get_item("scale_delta"), sd)
if model.custom_manipulator_enabled:
self._publish_delta(Operation.SCALE, sd)
model.set_floats(model.get_item("scale"), flatten(new_transform_matrix))
class PrimTransformModel(AbstractTransformManipulatorModel):
def __init__(self, usd_context_name: str = "", viewport_api=None):
super().__init__()
self._transform = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1] # visual transform of manipulator
self._no_scale_transform_manipulator = Gf.Matrix4d(1.0) # transform of manipulator without scale
self._scale_manipulator = Gf.Vec3d(1.0) # scale of manipulator
self._settings = carb.settings.get_settings()
self._dict = carb.dictionary.get_dictionary()
self._timeline = omni.timeline.get_timeline_interface()
self._app = omni.kit.app.get_app()
self._usd_context_name = usd_context_name
self._usd_context = omni.usd.get_context(usd_context_name)
self._stage: Usd.Stage = None
self._enabled_hosting_widget_count: int = 0
self._stage_listener = None
self._xformable_prim_paths: List[Sdf.Path] = []
self._xformable_prim_paths_sorted: List[Sdf.Path] = []
self._xformable_prim_paths_set: Set[Sdf.Path] = set()
self._xformable_prim_paths_prefix_set: Set[Sdf.Path] = set()
self._consolidated_xformable_prim_paths: List[Sdf.Path] = []
self._pivot_prim: Usd.Prim = None
self._update_prim_xform_from_prim_task_or_future: Union[asyncio.Task, concurrent.futures.Future, None] = None
self._current_editing_op: Operation = None
self._ignore_xform_data_change = False
self._timeline_sub = None
self._pending_changed_paths: Dict[Sdf.Path, bool] = {}
self._pending_changed_paths_for_xform_data: Set[Sdf.Path] = set()
self._mode = ManipulationMode.PIVOT
self._viewport_fps: float = 0.0 # needed this as heuristic for delaying the visual update of manipulator to match rendering
self._viewport_api = viewport_api
self._delay_dirty_tasks_or_futures: Dict[int, Union[asyncio.Task, concurrent.futures.Future]] = {}
self._no_scale_transform_manipulator_item = sc.AbstractManipulatorItem()
self._items["no_scale_transform_manipulator"] = self._no_scale_transform_manipulator_item
self._scale_manipulator_item = sc.AbstractManipulatorItem()
self._items["scale_manipulator"] = self._scale_manipulator_item
self._transform_manipulator_item = sc.AbstractManipulatorItem()
self._items["transform_manipulator"] = self._transform_manipulator_item
self._manipulator_mode_item = sc.AbstractManipulatorItem()
self._items["manipulator_mode"] = self._manipulator_mode_item
self._viewport_fps_item = sc.AbstractManipulatorItem()
self._items["viewport_fps"] = self._viewport_fps_item
self._set_default_settings()
# subscribe to snap events
self._snap_settings_listener = SnapSettingsListener(
enabled_setting_path=None,
move_x_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH,
move_y_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH,
move_z_setting_path=snap_c.SNAP_TRANSLATE_SETTING_PATH,
rotate_setting_path=snap_c.SNAP_ROTATE_SETTING_PATH,
scale_setting_path=snap_c.SNAP_SCALE_SETTING_PATH,
provider_setting_path=snap_c.SNAP_PROVIDER_NAME_SETTING_PATH,
)
# subscribe to operation/mode events
self._op_settings_listener = OpSettingsListener()
self._op_settings_listener_sub = self._op_settings_listener.subscribe_listener(self._on_op_listener_changed)
self._placement_sub = self._settings.subscribe_to_node_change_events(
prim_c.MANIPULATOR_PLACEMENT_SETTING, self._on_placement_setting_changed
)
self._placement = Placement.LAST_PRIM_PIVOT
placement = self._settings.get(prim_c.MANIPULATOR_PLACEMENT_SETTING)
self._update_placement(placement)
# cache unique setting path for selection pivot position
# vp1 default
self._selection_pivot_position_path = TRANSFORM_GIZMO_PIVOT_WORLD_POSITION + "/Viewport"
# vp2
if self._viewport_api:
self._selection_pivot_position_path = (
TRANSFORM_GIZMO_PIVOT_WORLD_POSITION + "/" + self._viewport_api.id.split("/")[0]
)
# update setting with pivot placement position on init
self._update_temp_pivot_world_position()
def subscribe_to_value_and_get_current(setting_val_name: str, setting_path: str):
sub = self._settings.subscribe_to_node_change_events(
setting_path, lambda item, type: setattr(self, setting_val_name, self._dict.get(item))
)
setattr(self, setting_val_name, self._settings.get(setting_path))
return sub
# subscribe to zero-gravity settings
self._custom_manipulator_enabled_sub = subscribe_to_value_and_get_current(
"_custom_manipulator_enabled", TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_ENABLED
)
# subscribe to USD related events
self._stage_event_sub = self._usd_context.get_stage_event_stream().create_subscription_to_pop(
self._on_stage_event, name="PrimTransformModel stage event"
)
if self._usd_context.get_stage_state() == omni.usd.StageState.OPENED:
self._on_stage_opened()
self._warning_notification = None
self._selected_instance_proxy_paths = set()
def __del__(self):
self.destroy()
def destroy(self):
if self._warning_notification:
self._warning_notification.dismiss()
self._warning_notification = None
self._op_settings_listener_sub = None
if self._op_settings_listener:
self._op_settings_listener.destroy()
self._op_settings_listener = None
self._stage_event_sub = None
if self._stage_listener:
self._stage_listener.Revoke()
self._stage_listener = None
if self._usd_context.get_stage_state() == omni.usd.StageState.OPENED:
self._on_stage_closing()
self._timeline_sub = None
if self._snap_settings_listener:
self._snap_settings_listener.destroy()
self._snap_settings_listener = None
if self._custom_manipulator_enabled_sub:
self._settings.unsubscribe_to_change_events(self._custom_manipulator_enabled_sub)
self._custom_manipulator_enabled_sub = None
if self._placement_sub:
self._settings.unsubscribe_to_change_events(self._placement_sub)
self._placement_sub = None
for task_or_future in self._delay_dirty_tasks_or_futures.values():
task_or_future.cancel()
self._delay_dirty_tasks_or_futures.clear()
def set_pivot_prim_path(self, path: Sdf.Path) -> bool:
if path not in self._xformable_prim_paths_set:
carb.log_warn(f"Cannot set pivot prim path to {path}")
return False
if not self._pivot_prim or self._pivot_prim.GetPath() != path:
self._pivot_prim = self._stage.GetPrimAtPath(path)
else:
return False
if self._update_transform_from_prims():
self._item_changed(self._transform_item)
return True
def get_pivot_prim_path(self) -> Sdf.Path:
if self._pivot_prim:
return self._pivot_prim.GetPath()
return None
def on_began(self, payload):
item = payload.changing_item
self._current_editing_op = item.operation
# All selected xformable prims' transforms. Store this for when `Keep Spacing` option is off during snapping,
# because it can modify parent's and child're transform differently.
self._all_xformable_prim_data_prev: Dict[Sdf.Path, Tuple[Gf.Vec3d, Gf.Vec3d, Gf.Vec3i, Gf.Vec3d, Gf.Vec3d]] = {}
# consolidated xformable prims' transforms. If parent is in the dict, child will be excluded.
self._consolidated_xformable_prim_data_prev: Dict[Sdf.Path, Tuple[Gf.Vec3d, Gf.Vec3d, Gf.Vec3i, Gf.Vec3d]] = {}
for path in self._xformable_prim_paths:
prim = self.stage.GetPrimAtPath(path)
xform_tuple = omni.usd.get_local_transform_SRT(prim, self._get_current_time_code())
pivot = get_local_transform_pivot_inv(prim, self._get_current_time_code()).GetInverse()
self._all_xformable_prim_data_prev[path] = xform_tuple + (pivot,)
if path in self._consolidated_xformable_prim_paths:
self._consolidated_xformable_prim_data_prev[path] = xform_tuple + (pivot,)
self.all_xformable_prim_data_curr = self._all_xformable_prim_data_prev.copy()
self.consolidated_xformable_prim_data_curr = self._consolidated_xformable_prim_data_prev.copy()
self._pending_changed_paths_for_xform_data.clear()
if self.custom_manipulator_enabled:
self._settings.set(TRANSFORM_GIZMO_IS_USING, True)
def on_changed(self, payload):
# Always re-fetch the changed transform on_changed. Although it might not be manipulated by manipulator,
# prim's transform can be modified by other runtime (e.g. omnigraph), and we always want the latest.
self._update_xform_data_from_dirty_paths()
def on_ended(self, payload):
# Always re-fetch the changed transform on_changed. Although it might not be manipulated by manipulator,
# prim's transform can be modified by other runtime (e.g. omnigraph), and we always want the latest.
self._update_xform_data_from_dirty_paths()
carb.profiler.begin(1, "PrimTransformChangedGestureBase.TransformPrimSRT.all")
paths = []
new_translations = []
new_rotation_eulers = []
new_rotation_orders = []
new_scales = []
old_translations = []
old_rotation_eulers = []
old_rotation_orders = []
old_scales = []
for path, (s, r, ro, t, pivot) in self.all_xformable_prim_data_curr.items():
# Data didn't change
if self._all_xformable_prim_data_prev[path] == self.all_xformable_prim_data_curr[path]:
# carb.log_info(f"Skip {path}")
continue
(old_s, old_r, old_ro, old_t, old_pivot) = self._all_xformable_prim_data_prev[path]
paths.append(path.pathString)
new_translations += [t[0], t[1], t[2]]
new_rotation_eulers += [r[0], r[1], r[2]]
new_rotation_orders += [ro[0], ro[1], ro[2]]
new_scales += [s[0], s[1], s[2]]
old_translations += [old_t[0], old_t[1], old_t[2]]
old_rotation_eulers += [old_r[0], old_r[1], old_r[2]]
old_rotation_orders += [old_ro[0], old_ro[1], old_ro[2]]
old_scales += [old_s[0], old_s[1], old_s[2]]
self._ignore_xform_data_change = True
self._on_ended_transform(
paths,
new_translations,
new_rotation_eulers,
new_rotation_orders,
new_scales,
old_translations,
old_rotation_eulers,
old_rotation_orders,
old_scales,
)
self._ignore_xform_data_change = False
carb.profiler.end(1)
if self.custom_manipulator_enabled:
self._settings.set(TRANSFORM_GIZMO_IS_USING, False)
# if the manipulator was locked to orientation or translation,
# refresh it on_ended so the transform is up to date
mode = self._get_transform_mode_for_current_op()
if self._should_keep_manipulator_orientation_unchanged(
mode
) or self._should_keep_manipulator_translation_unchanged(mode):
# set editing op to None AFTER _should_keep_manipulator_*_unchanged but
# BEFORE self._update_transform_from_prims
self._current_editing_op = None
if self._update_transform_from_prims():
self._item_changed(self._transform_item)
self._current_editing_op = None
def _on_ended_transform(
self,
paths: List[str],
new_translations: List[float],
new_rotation_eulers: List[float],
new_rotation_orders: List[int],
new_scales: List[float],
old_translations: List[float],
old_rotation_eulers: List[float],
old_rotation_orders: List[int],
old_scales: List[float],
):
"""Function ran by on_ended(). Can be overridden to change the behavior. Do not remove this function: can be
used outside of this code"""
self._alert_if_selection_has_instance_proxies()
omni.kit.commands.execute(
"TransformMultiPrimsSRTCpp",
count=len(paths),
paths=paths,
new_translations=new_translations,
new_rotation_eulers=new_rotation_eulers,
new_rotation_orders=new_rotation_orders,
new_scales=new_scales,
old_translations=old_translations,
old_rotation_eulers=old_rotation_eulers,
old_rotation_orders=old_rotation_orders,
old_scales=old_scales,
usd_context_name=self._usd_context_name,
time_code=self._get_current_time_code().GetValue(),
)
def on_canceled(self, payload):
if self.custom_manipulator_enabled:
self._settings.set(TRANSFORM_GIZMO_IS_USING, False)
self._current_editing_op = None
def widget_enabled(self):
self._enabled_hosting_widget_count += 1
# just changed from no active widget to 1 active widget
if self._enabled_hosting_widget_count == 1:
# listener only needs to be activated if manipulator is visible
if self._consolidated_xformable_prim_paths:
assert self._stage_listener is None
self._stage_listener = Tf.Notice.Register(
Usd.Notice.ObjectsChanged, self._on_objects_changed, self._stage
)
carb.log_info("Tf.Notice.Register in PrimTransformModel")
def _clear_temp_pivot_position_setting(self):
if self._settings.get(self._selection_pivot_position_path):
self._settings.destroy_item(self._selection_pivot_position_path)
def widget_disabled(self):
self._enabled_hosting_widget_count -= 1
self._clear_temp_pivot_position_setting()
assert self._enabled_hosting_widget_count >= 0
if self._enabled_hosting_widget_count < 0:
carb.log_error(f"manipulator enabled widget tracker out of sync: {self._enabled_hosting_widget_count}")
self._enabled_hosting_widget_count = 0
# If no hosting manipulator is active, revoke the listener since there's no need to sync Transform
if self._enabled_hosting_widget_count == 0:
if self._stage_listener:
self._stage_listener.Revoke()
self._stage_listener = None
carb.log_info("Tf.Notice.Revoke in PrimTransformModel")
for task_or_future in self._delay_dirty_tasks_or_futures.values():
task_or_future.cancel()
self._delay_dirty_tasks_or_futures.clear()
def set_floats(self, item: sc.AbstractManipulatorItem, value: Sequence[float]):
if item == self._viewport_fps_item:
self._viewport_fps = value[0]
return
flag = None
if issubclass(type(item), AbstractTransformManipulatorModel.OperationItem):
if (
item.operation == Operation.TRANSLATE_DELTA
or item.operation == Operation.ROTATE_DELTA
or item.operation == Operation.SCALE_DELTA
):
return
if item.operation == Operation.TRANSLATE:
flag = OpFlag.TRANSLATE
elif item.operation == Operation.ROTATE:
flag = OpFlag.ROTATE
elif item.operation == Operation.SCALE:
flag = OpFlag.SCALE
transform = Gf.Matrix4d(*value)
elif item == self._transform_manipulator_item:
flag = OpFlag.TRANSLATE | OpFlag.ROTATE | OpFlag.SCALE
transform = Gf.Matrix4d(*value)
elif item == self._no_scale_transform_manipulator_item:
flag = OpFlag.TRANSLATE | OpFlag.ROTATE
old_manipulator_scale_mtx = Gf.Matrix4d(1.0)
old_manipulator_scale_mtx.SetScale(self._scale_manipulator)
transform = old_manipulator_scale_mtx * Gf.Matrix4d(*value)
if flag is not None:
if self._mode == ManipulationMode.PIVOT:
self._transform_selected_prims(
transform, self._no_scale_transform_manipulator, self._scale_manipulator, flag
)
elif self._mode == ManipulationMode.UNIFORM:
self._transform_all_selected_prims_to_manipulator_pivot(transform, flag)
else:
carb.log_warn(f"Unsupported item {item}")
def set_ints(self, item: sc.AbstractManipulatorItem, value: Sequence[int]):
if item == self._manipulator_mode_item:
try:
self._mode = ManipulationMode(value[0])
except:
carb.log_error(traceback.format_exc())
else:
carb.log_warn(f"unsupported item {item}")
return None
def get_as_floats(self, item: sc.AbstractManipulatorItem):
if item == self._transform_item:
return self._transform
elif item == self._no_scale_transform_manipulator_item:
return flatten(self._no_scale_transform_manipulator)
elif item == self._scale_manipulator_item:
return [self._scale_manipulator[0], self._scale_manipulator[1], self._scale_manipulator[2]]
elif item == self._transform_manipulator_item:
scale_mtx = Gf.Matrix4d(1)
scale_mtx.SetScale(self._scale_manipulator)
return flatten(scale_mtx * self._no_scale_transform_manipulator)
else:
carb.log_warn(f"unsupported item {item}")
return None
def get_as_ints(self, item: sc.AbstractManipulatorItem):
if item == self._manipulator_mode_item:
return [int(self._mode)]
else:
carb.log_warn(f"unsupported item {item}")
return None
def get_operation(self) -> Operation:
if self._op_settings_listener.selected_op == c.TRANSFORM_OP_MOVE:
return Operation.TRANSLATE
elif self._op_settings_listener.selected_op == c.TRANSFORM_OP_ROTATE:
return Operation.ROTATE
elif self._op_settings_listener.selected_op == c.TRANSFORM_OP_SCALE:
return Operation.SCALE
return Operation.NONE
def get_snap(self, item: AbstractTransformManipulatorModel.OperationItem):
if not self._snap_settings_listener.snap_enabled:
return None
if item.operation == Operation.TRANSLATE:
if self._snap_settings_listener.snap_provider:
return None
return (
self._snap_settings_listener.snap_move_x,
self._snap_settings_listener.snap_move_y,
self._snap_settings_listener.snap_move_z,
)
elif item.operation == Operation.ROTATE:
return self._snap_settings_listener.snap_rotate
elif item.operation == Operation.SCALE:
return self._snap_settings_listener.snap_scale
return None
@property
def stage(self):
return self._stage
@property
def custom_manipulator_enabled(self):
return self._custom_manipulator_enabled
@property
def snap_settings_listener(self):
return self._snap_settings_listener
@property
def op_settings_listener(self):
return self._op_settings_listener
@property
def usd_context(self) -> omni.usd.UsdContext:
return self._usd_context
@property
def xformable_prim_paths(self) -> List[Sdf.Path]:
return self._xformable_prim_paths
@carb.profiler.profile
def _update_xform_data_from_dirty_paths(self):
for p in self._pending_changed_paths_for_xform_data:
prim_path = p.GetPrimPath()
if prim_path in self.all_xformable_prim_data_curr and self._path_may_affect_transform(p):
prim = self.stage.GetPrimAtPath(prim_path)
xform_tuple = omni.usd.get_local_transform_SRT(prim, self._get_current_time_code())
pivot = get_local_transform_pivot_inv(prim, self._get_current_time_code()).GetInverse()
self.all_xformable_prim_data_curr[prim_path] = xform_tuple + (pivot,)
if prim_path in self._consolidated_xformable_prim_paths:
self.consolidated_xformable_prim_data_curr[prim_path] = xform_tuple + (pivot,)
self._pending_changed_paths_for_xform_data.clear()
@carb.profiler.profile
def _transform_selected_prims(
self,
new_manipulator_transform: Gf.Matrix4d,
old_manipulator_transform_no_scale: Gf.Matrix4d,
old_manipulator_scale: Gf.Vec3d,
dirty_ops: OpFlag,
):
carb.profiler.begin(1, "omni.kit.manipulator.prim.model._transform_selected_prims.prepare_data")
paths = []
new_translations = []
new_rotation_eulers = []
new_rotation_orders = []
new_scales = []
self._xform_cache.Clear()
# any op may trigger a translation change if multi-manipulating
should_update_translate = dirty_ops & OpFlag.TRANSLATE or len(
self._xformable_prim_paths) > 1 or self._placement != Placement.LAST_PRIM_PIVOT
should_update_rotate = dirty_ops & OpFlag.ROTATE
should_update_scale = dirty_ops & OpFlag.SCALE
old_manipulator_scale_mtx = Gf.Matrix4d(1.0)
old_manipulator_scale_mtx.SetScale(old_manipulator_scale)
old_manipulator_transform_inv = (old_manipulator_scale_mtx * old_manipulator_transform_no_scale).GetInverse()
for path in self._consolidated_xformable_prim_paths:
if self._custom_manipulator_enabled and self._should_skip_custom_manipulator_path(path.pathString):
continue
selected_prim = self._stage.GetPrimAtPath(path)
# We check whether path is in consolidated_xformable_prim_data_curr because it may have not made it the dictionary if an error occured
if not selected_prim or path not in self.consolidated_xformable_prim_data_curr:
continue
(s, r, ro, t, selected_pivot) = self.consolidated_xformable_prim_data_curr[path]
selected_pivot_inv = selected_pivot.GetInverse()
selected_local_to_world_mtx = self._xform_cache.GetLocalToWorldTransform(selected_prim)
selected_parent_to_world_mtx = self._xform_cache.GetParentToWorldTransform(selected_prim)
# Transform the prim from world space to pivot's space
# Then apply the new pivotPrim-to-world-space transform matrix
selected_local_to_world_pivot_mtx = (
selected_pivot * selected_local_to_world_mtx * old_manipulator_transform_inv * new_manipulator_transform
)
world_to_parent_mtx = selected_parent_to_world_mtx.GetInverse()
selected_local_mtx_new = selected_local_to_world_pivot_mtx * world_to_parent_mtx * selected_pivot_inv
if should_update_translate:
translation = selected_local_mtx_new.ExtractTranslation()
if should_update_rotate:
# Construct the new rotation from old scale and translation.
# Don't use Factor because it won't be able to tell if scale is positive or negative and can result in flipped rotation
old_s_mtx = Gf.Matrix4d(1.0)
old_s_mtx.SetScale(Gf.Vec3d(s))
old_t_mtx = Gf.Matrix4d(1.0)
old_t_mtx.SetTranslate(Gf.Vec3d(t))
rot_new = (old_s_mtx.GetInverse() * selected_local_mtx_new * old_t_mtx.GetInverse()).ExtractRotation()
axes = [Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()]
decomp_rot = rot_new.Decompose(axes[ro[2]], axes[ro[1]], axes[ro[0]])
index_order = Gf.Vec3i()
for i in range(3):
index_order[ro[i]] = 2 - i
rotation = Gf.Vec3d(decomp_rot[index_order[0]], decomp_rot[index_order[1]], decomp_rot[index_order[2]])
rotation = find_best_euler_angles(Gf.Vec3d(r), rotation, ro)
if should_update_scale:
# Construct the new scale from old rotation and translation.
# Don't use Factor because it won't be able to tell if scale is positive or negative and can result in flipped rotation
old_rt_mtx = compose_transform_ops_to_matrix(t, r, ro, Gf.Vec3d(1))
new_s_mtx = selected_local_mtx_new * old_rt_mtx.GetInverse()
scale = Gf.Vec3d(new_s_mtx[0][0], new_s_mtx[1][1], new_s_mtx[2][2])
translation = translation if should_update_translate else t
rotation = rotation if should_update_rotate else r
scale = scale if should_update_scale else s
paths.append(path.pathString)
new_translations += [translation[0], translation[1], translation[2]]
new_rotation_eulers += [rotation[0], rotation[1], rotation[2]]
new_rotation_orders += [ro[0], ro[1], ro[2]]
new_scales += [scale[0], scale[1], scale[2]]
xform_tuple = (scale, rotation, ro, translation, selected_pivot)
self.consolidated_xformable_prim_data_curr[path] = xform_tuple
self.all_xformable_prim_data_curr[path] = xform_tuple
carb.profiler.end(1)
self._ignore_xform_data_change = True
self._do_transform_selected_prims(paths, new_translations, new_rotation_eulers, new_rotation_orders, new_scales)
self._ignore_xform_data_change = False
def _do_transform_selected_prims(
self,
paths: List[str],
new_translations: List[float],
new_rotation_eulers: List[float],
new_rotation_orders: List[int],
new_scales: List[float],
):
"""Function ran by _transform_selected_prims(). Can be overridden to change the behavior
Do not remove this function: can be used outside of this code"""
self._alert_if_selection_has_instance_proxies()
omni.kit.commands.create(
"TransformMultiPrimsSRTCpp",
count=len(paths),
no_undo=True,
paths=paths,
new_translations=new_translations,
new_rotation_eulers=new_rotation_eulers,
new_rotation_orders=new_rotation_orders,
new_scales=new_scales,
usd_context_name=self._usd_context_name,
time_code=self._get_current_time_code().GetValue(),
).do()
@carb.profiler.profile
def _transform_all_selected_prims_to_manipulator_pivot(
self,
new_manipulator_transform: Gf.Matrix4d,
dirty_ops: OpFlag,
):
paths = []
new_translations = []
new_rotation_eulers = []
new_rotation_orders = []
new_scales = []
old_translations = []
old_rotation_eulers = []
old_rotation_orders = []
old_scales = []
self._xform_cache.Clear()
# any op may trigger a translation change if multi-manipulating
should_update_translate = dirty_ops & OpFlag.TRANSLATE or len(self._xformable_prim_paths) > 1
should_update_rotate = dirty_ops & OpFlag.ROTATE
should_update_scale = dirty_ops & OpFlag.SCALE
for path in self._xformable_prim_paths_sorted:
if self._custom_manipulator_enabled and self._should_skip_custom_manipulator_path(path.pathString):
continue
selected_prim = self._stage.GetPrimAtPath(path)
# We check whether path is in all_xformable_prim_data_curr because it may have not made it the dictionary if an error occured
if not selected_prim or path not in self.all_xformable_prim_data_curr:
continue
(s, r, ro, t, selected_pivot) = self.all_xformable_prim_data_curr[path]
selected_parent_to_world_mtx = self._xform_cache.GetParentToWorldTransform(selected_prim)
world_to_parent_mtx = selected_parent_to_world_mtx.GetInverse()
selected_local_mtx_new = new_manipulator_transform * world_to_parent_mtx * selected_pivot.GetInverse()
if should_update_translate:
translation = selected_local_mtx_new.ExtractTranslation()
if should_update_rotate:
# Construct the new rotation from old scale and translation.
# Don't use Factor because it won't be able to tell if scale is positive or negative and can result in flipped rotation
old_s_mtx = Gf.Matrix4d(1.0)
old_s_mtx.SetScale(Gf.Vec3d(s))
old_t_mtx = Gf.Matrix4d(1.0)
old_t_mtx.SetTranslate(Gf.Vec3d(t))
rot_new = (old_s_mtx.GetInverse() * selected_local_mtx_new * old_t_mtx.GetInverse()).ExtractRotation()
axes = [Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()]
decomp_rot = rot_new.Decompose(axes[ro[2]], axes[ro[1]], axes[ro[0]])
index_order = Gf.Vec3i()
for i in range(3):
index_order[ro[i]] = 2 - i
rotation = Gf.Vec3d(decomp_rot[index_order[0]], decomp_rot[index_order[1]], decomp_rot[index_order[2]])
rotation = find_best_euler_angles(Gf.Vec3d(r), rotation, ro)
if should_update_scale:
# Construct the new scale from old rotation and translation.
# Don't use Factor because it won't be able to tell if scale is positive or negative and can result in flipped rotation
old_rt_mtx = compose_transform_ops_to_matrix(t, r, ro, Gf.Vec3d(1))
new_s_mtx = selected_local_mtx_new * old_rt_mtx.GetInverse()
scale = Gf.Vec3d(new_s_mtx[0][0], new_s_mtx[1][1], new_s_mtx[2][2])
# any op may trigger a translation change if multi-manipulating
translation = translation if should_update_translate else t
rotation = rotation if should_update_rotate else r
scale = scale if should_update_scale else s
paths.append(path.pathString)
new_translations += [translation[0], translation[1], translation[2]]
new_rotation_eulers += [rotation[0], rotation[1], rotation[2]]
new_rotation_orders += [ro[0], ro[1], ro[2]]
new_scales += [scale[0], scale[1], scale[2]]
old_translations += [t[0], t[1], t[2]]
old_rotation_eulers += [r[0], r[1], r[2]]
old_rotation_orders += [ro[0], ro[1], ro[2]]
old_scales += [s[0], s[1], s[2]]
xform_tuple = (scale, rotation, ro, translation, selected_pivot)
self.all_xformable_prim_data_curr[path] = xform_tuple
if path in self.consolidated_xformable_prim_data_curr:
self.consolidated_xformable_prim_data_curr[path] = xform_tuple
self._ignore_xform_data_change = True
self._do_transform_all_selected_prims_to_manipulator_pivot(
paths, new_translations, new_rotation_eulers, new_rotation_orders, new_scales
)
self._ignore_xform_data_change = False
def _alert_if_selection_has_instance_proxies(self):
if self._selected_instance_proxy_paths and (not self._warning_notification or self._warning_notification.dismissed):
try:
import omni.kit.notification_manager as nm
self._warning_notification = nm.post_notification(
"Children of an instanced prim cannot be modified, uncheck Instanceable on the instanced prim to modify child prims.",
status=nm.NotificationStatus.WARNING
)
except ImportError:
pass
def _do_transform_all_selected_prims_to_manipulator_pivot(
self,
paths: List[str],
new_translations: List[float],
new_rotation_eulers: List[float],
new_rotation_orders: List[int],
new_scales: List[float],
):
"""Function ran by _transform_all_selected_prims_to_manipulator_pivot().
Can be overridden to change the behavior. Do not remove this function: can be used outside of this code"""
self._alert_if_selection_has_instance_proxies()
omni.kit.commands.create(
"TransformMultiPrimsSRTCpp",
count=len(paths),
no_undo=True,
paths=paths,
new_translations=new_translations,
new_rotation_eulers=new_rotation_eulers,
new_rotation_orders=new_rotation_orders,
new_scales=new_scales,
usd_context_name=self._usd_context_name,
time_code=self._get_current_time_code().GetValue(),
).do()
def _on_stage_event(self, event: carb.events.IEvent):
if event.type == int(omni.usd.StageEventType.OPENED):
self._on_stage_opened()
elif event.type == int(omni.usd.StageEventType.CLOSING):
self._on_stage_closing()
def _on_stage_opened(self):
self._stage = self._usd_context.get_stage()
self._timeline_sub = self._timeline.get_timeline_event_stream().create_subscription_to_pop(
self._on_timeline_event
)
self._current_time = self._timeline.get_current_time()
self._xform_cache = UsdGeom.XformCache(self._get_current_time_code())
def _on_stage_closing(self):
self._stage = None
self._xform_cache = None
self._xformable_prim_paths.clear()
self._xformable_prim_paths_sorted.clear()
self._xformable_prim_paths_set.clear()
self._xformable_prim_paths_prefix_set.clear()
self._consolidated_xformable_prim_paths.clear()
self._pivot_prim = None
self._timeline_sub = None
if self._stage_listener:
self._stage_listener.Revoke()
self._stage_listener = None
carb.log_info("Tf.Notice.Revoke in PrimTransformModel")
self._pending_changed_paths.clear()
if self._update_prim_xform_from_prim_task_or_future is not None:
self._update_prim_xform_from_prim_task_or_future.cancel()
self._update_prim_xform_from_prim_task_or_future = None
def on_selection_changed(self, selection: List[Sdf.Path]):
if self._update_prim_xform_from_prim_task_or_future is not None:
self._update_prim_xform_from_prim_task_or_future.cancel()
self._update_prim_xform_from_prim_task_or_future = None
self._selected_instance_proxy_paths.clear()
self._xformable_prim_paths.clear()
self._xformable_prim_paths_set.clear()
self._xformable_prim_paths_prefix_set.clear()
self._consolidated_xformable_prim_paths.clear()
self._pivot_prim = None
for sdf_path in selection:
prim = self._stage.GetPrimAtPath(sdf_path)
if prim and prim.IsA(UsdGeom.Xformable) and prim.IsActive():
self._xformable_prim_paths.append(sdf_path)
if self._xformable_prim_paths:
# Make a sorted list so parents always appears before child
self._xformable_prim_paths_sorted = self._xformable_prim_paths.copy()
self._xformable_prim_paths_sorted.sort()
# Find the most recently selected valid xformable prim as the pivot prim where the transform gizmo is located at.
self._pivot_prim = self._stage.GetPrimAtPath(self._xformable_prim_paths[-1])
# Get least common prims ancestors.
# We do this so that if one selected prim is a descendant of other selected prim, the descendant prim won't be
# transformed twice.
self._consolidated_xformable_prim_paths = Sdf.Path.RemoveDescendentPaths(self._xformable_prim_paths)
# Filter all instance proxy paths.
for path in self._consolidated_xformable_prim_paths:
prim = self._stage.GetPrimAtPath(path)
if prim.IsInstanceProxy():
self._selected_instance_proxy_paths.add(sdf_path)
self._xformable_prim_paths_set.update(self._xformable_prim_paths)
for path in self._xformable_prim_paths_set:
self._xformable_prim_paths_prefix_set.update(path.GetPrefixes())
if self._update_transform_from_prims():
self._item_changed(self._transform_item)
# Happens when host widget is already enabled and first selection in a new stage
if self._enabled_hosting_widget_count > 0 and self._stage_listener is None:
self._stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_objects_changed, self._stage)
carb.log_info("Tf.Notice.Register in PrimTransformModel")
def _should_keep_manipulator_orientation_unchanged(self, mode: str) -> bool:
# Exclude snap_to_face. During snap_to_face operation, it may modify the orientation of object to confrom to surface
# normal and the `new_manipulator_transform` param for `_transform_selected_prims` is set to the final transform
# of the manipulated prim. However, if we use old rotation in the condition below, _no_scale_transform_manipulator
# will not confrom to the new orientation, and _transform_selected_prims would double rotate the prims because it
# sees the rotation diff between the old prim orientation (captured at on_began) vs new normal orient, instead of
# current prim orientation vs new normal orientation.
# Plus, it is nice to see the normal of the object changing while snapping.
snap_provider_enabled = self.snap_settings_listener.snap_enabled and self.snap_settings_listener.snap_provider
# When the manipulator is being manipulated as local translate or scale, we do not want to change the rotation of
# the manipulator even if it's rotated, otherwise the direction of moving or scaling will change and can be very hard to control.
# It can happen when you move a prim that has a constraint on it (e.g. lookAt)
# In this case keep the rotation the same as on_began
return (
mode == c.TRANSFORM_MODE_LOCAL
and (self._current_editing_op == Operation.TRANSLATE or self._current_editing_op == Operation.SCALE)
and not snap_provider_enabled
)
def _should_keep_manipulator_translation_unchanged(self, mode: str) -> bool:
# When the pivot placement is BBOX_CENTER and multiple prims being rotated, the bbox center may shifts, and the
# rotation center will shift with them. This causes weird user experience. So we pin the rotation center until
# mouse is released.
return (
self._current_editing_op == Operation.ROTATE
and (self._placement == Placement.BBOX_CENTER or self._placement == Placement.BBOX_BASE)
)
def _get_transform_mode_for_current_op(self) -> str:
mode = c.TRANSFORM_MODE_LOCAL
if self._op_settings_listener.selected_op == c.TRANSFORM_OP_ROTATE:
mode = self._op_settings_listener.rotation_mode
elif self._op_settings_listener.selected_op == c.TRANSFORM_OP_MOVE:
mode = self._op_settings_listener.translation_mode
return mode
# Adds a delay to the visual update during translate (only) manipulation
# It's due to the renderer having a delay of rendering the mesh and the manipulator appears to drift apart.
# It's only an estimation and may varying from scene/renderer setup.
async def _delay_dirty(self, transform, id):
if self._viewport_fps:
render_frame_time = 1.0 / self._viewport_fps * self._settings.get(TRANSLATE_DELAY_FRAME_SETTING)
while True:
dt = await self._app.next_update_async()
render_frame_time -= dt
# break a frame early
if render_frame_time < dt:
break
# cancel earlier job if a later one catches up (fps suddenly changed?)
earlier_tasks_or_futures = []
for key, task_or_future in self._delay_dirty_tasks_or_futures.items():
if key < id:
earlier_tasks_or_futures.append(key)
task_or_future.cancel()
else:
break
for key in earlier_tasks_or_futures:
self._delay_dirty_tasks_or_futures.pop(key)
self._transform = transform
self._item_changed(self._transform_item)
self._delay_dirty_tasks_or_futures.pop(id)
def _update_temp_pivot_world_position(self):
if type(self._transform) is not list:
return
new_world_position = self._transform[12:15]
self._settings.set_float_array(
self._selection_pivot_position_path,
new_world_position
)
@carb.profiler.profile
def _update_transform_from_prims(self):
xform_flattened = self._calculate_transform_from_prim()
if self._transform != xform_flattened:
self._transform = xform_flattened
# update setting with new pivot placement position
self._update_temp_pivot_world_position()
return True
return False
def _calculate_transform_from_prim(self):
if not self._stage:
return False
if not self._pivot_prim:
return False
self._xform_cache.Clear()
cur_time = self._get_current_time_code()
mode = self._get_transform_mode_for_current_op()
pivot_inv = get_local_transform_pivot_inv(self._pivot_prim, cur_time)
if self._should_keep_manipulator_orientation_unchanged(mode):
pivot_prim_path = self._pivot_prim.GetPath()
(s, r, ro, t) = omni.usd.get_local_transform_SRT(self._pivot_prim, cur_time)
pivot = get_local_transform_pivot_inv(self._pivot_prim, self._get_current_time_code()).GetInverse()
self.all_xformable_prim_data_curr[pivot_prim_path] = (s, r, ro, t) + (pivot,)
# This method may be called from _on_op_listener_changed, before any gesture has started
# in which case _all_xformable_prim_data_prev would be empty
piv_xf_tuple = self._all_xformable_prim_data_prev.get(pivot_prim_path, False)
if not piv_xf_tuple:
piv_xf_tuple = omni.usd.get_local_transform_SRT(self._pivot_prim, cur_time)
pv_xf_pivot = get_local_transform_pivot_inv(
self._pivot_prim, self._get_current_time_code()
).GetInverse()
self._all_xformable_prim_data_prev[self._pivot_prim.GetPath()] = piv_xf_tuple + (pv_xf_pivot,)
(s_p, r_p, ro_p, t_p, t_piv) = piv_xf_tuple
xform = self._construct_transform_matrix_from_SRT(t, r_p, ro_p, s, pivot_inv)
parent = self._xform_cache.GetLocalToWorldTransform(self._pivot_prim.GetParent())
xform *= parent
else:
xform = self._xform_cache.GetLocalToWorldTransform(self._pivot_prim)
xform = pivot_inv.GetInverse() * xform
if self._should_keep_manipulator_translation_unchanged(mode):
xform.SetTranslateOnly((self._transform[12], self._transform[13], self._transform[14]))
else:
# if there's only one selection, we always use LAST_PRIM_PIVOT though
if (
self._placement != Placement.LAST_PRIM_PIVOT
and self._placement != Placement.REF_PRIM
):
average_translation = Gf.Vec3d(0.0)
if self._placement == Placement.BBOX_CENTER or self._placement == Placement.BBOX_BASE:
world_bound = Gf.Range3d()
def get_prim_translation(xformable):
xformable_world_mtx = self._xform_cache.GetLocalToWorldTransform(xformable)
xformable_pivot_inv = get_local_transform_pivot_inv(xformable, cur_time)
xformable_world_mtx = xformable_pivot_inv.GetInverse() * xformable_world_mtx
return xformable_world_mtx.ExtractTranslation()
for path in self._xformable_prim_paths:
xformable = self._stage.GetPrimAtPath(path)
if self._placement == Placement.SELECTION_CENTER:
average_translation += get_prim_translation(xformable)
elif self._placement == Placement.BBOX_CENTER or Placement.BBOX_BASE:
bound_range = self._usd_context.compute_path_world_bounding_box(path.pathString)
bound_range = Gf.Range3d(Gf.Vec3d(*bound_range[0]), Gf.Vec3d(*bound_range[1]))
if not bound_range.IsEmpty():
world_bound = Gf.Range3d.GetUnion(world_bound, bound_range)
else:
# extend world bound with tranlation for prims with zero bbox, e.g. Xform, Camera
prim_translation = get_prim_translation(xformable)
world_bound.UnionWith(prim_translation)
if self._placement == Placement.SELECTION_CENTER:
average_translation /= len(self._xformable_prim_paths)
elif self._placement == Placement.BBOX_CENTER:
average_translation = world_bound.GetMidpoint()
elif self._placement == Placement.BBOX_BASE:
# xform may not have bbox but its descendants may have, exclude cases that only xform are selected
if not world_bound.IsEmpty():
bbox_center = world_bound.GetMidpoint()
bbox_size = world_bound.GetSize()
if UsdGeom.GetStageUpAxis(self._stage) == UsdGeom.Tokens.y:
# Y-up world
average_translation = bbox_center - Gf.Vec3d(0.0, bbox_size[1] / 2.0, 0.0)
else:
# Z-up world
average_translation = bbox_center - Gf.Vec3d(0.0, 0.0, bbox_size[2] / 2.0)
else:
# fallback to SELECTION_CENTER
average_translation /= len(self._xformable_prim_paths)
# Only take the translate from selected prim average.
# The rotation and scale still comes from pivot prim
xform.SetTranslateOnly(average_translation)
# instead of using RemoveScaleShear, additional steps made to handle negative scale properly
scale, _, _, _ = omni.usd.get_local_transform_SRT(self._pivot_prim, cur_time)
scale_epsilon = 1e-6
for i in range(3):
if Gf.IsClose(scale[i], 0.0, scale_epsilon):
scale[i] = -scale_epsilon if scale[i] < 0 else scale_epsilon
inverse_scale = Gf.Matrix4d().SetScale(Gf.Vec3d(1.0 / scale[0], 1.0 / scale[1], 1.0 / scale[2]))
xform = inverse_scale * xform
# this is the average xform without scale
self._no_scale_transform_manipulator = Gf.Matrix4d(xform)
# store the scale separately
self._scale_manipulator = Gf.Vec3d(scale)
# Visual transform of the manipulator
xform = xform.RemoveScaleShear()
if mode == c.TRANSFORM_MODE_GLOBAL:
xform = xform.SetTranslate(xform.ExtractTranslation())
return flatten(xform)
def _construct_transform_matrix_from_SRT(
self,
translation: Gf.Vec3d,
rotation_euler: Gf.Vec3d,
rotation_order: Gf.Vec3i,
scale: Gf.Vec3d,
pivot_inv: Gf.Matrix4d,
):
trans_mtx = Gf.Matrix4d()
rot_mtx = Gf.Matrix4d()
scale_mtx = Gf.Matrix4d()
trans_mtx.SetTranslate(Gf.Vec3d(translation))
axes = [Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis()]
rotation = (
Gf.Rotation(axes[rotation_order[0]], rotation_euler[rotation_order[0]])
* Gf.Rotation(axes[rotation_order[1]], rotation_euler[rotation_order[1]])
* Gf.Rotation(axes[rotation_order[2]], rotation_euler[rotation_order[2]])
)
rot_mtx.SetRotate(rotation)
scale_mtx.SetScale(Gf.Vec3d(scale))
return pivot_inv * scale_mtx * rot_mtx * pivot_inv.GetInverse() * trans_mtx
def _on_op_listener_changed(self, type: OpSettingsListener.CallbackType, value: str):
if type == OpSettingsListener.CallbackType.OP_CHANGED:
# cancel all delayed tasks
for task_or_future in self._delay_dirty_tasks_or_futures.values():
task_or_future.cancel()
self._delay_dirty_tasks_or_futures.clear()
self._update_transform_from_prims()
self._item_changed(self._transform_item)
elif type == OpSettingsListener.CallbackType.TRANSLATION_MODE_CHANGED:
if self._op_settings_listener.selected_op == c.TRANSFORM_OP_MOVE:
if self._update_transform_from_prims():
self._item_changed(self._transform_item)
elif type == OpSettingsListener.CallbackType.ROTATION_MODE_CHANGED:
if self._op_settings_listener.selected_op == c.TRANSFORM_OP_ROTATE:
if self._update_transform_from_prims():
self._item_changed(self._transform_item)
def _update_placement(self, placement_str: str):
if placement_str == prim_c.MANIPULATOR_PLACEMENT_SELECTION_CENTER:
placement = Placement.SELECTION_CENTER
elif placement_str == prim_c.MANIPULATOR_PLACEMENT_BBOX_CENTER:
placement = Placement.BBOX_CENTER
elif placement_str == prim_c.MANIPULATOR_PLACEMENT_PICK_REF_PRIM:
placement = Placement.REF_PRIM
elif placement_str == prim_c.MANIPULATOR_PLACEMENT_BBOX_BASE:
placement = Placement.BBOX_BASE
else: # placement == prim_c.MANIPULATOR_PLACEMENT_LAST_PRIM_PIVOT or bad values
placement = Placement.LAST_PRIM_PIVOT
if placement != self._placement:
if placement == Placement.LAST_PRIM_PIVOT and self._placement == Placement.REF_PRIM:
# reset the pivot prim in case it was changed by MANIPULATOR_PLACEMENT_PICK_REF_PRIM
if self._xformable_prim_paths:
self._pivot_prim = self._stage.GetPrimAtPath(self._xformable_prim_paths[-1])
self._placement = placement
if self._update_transform_from_prims():
self._item_changed(self._transform_item)
def _on_placement_setting_changed(self, item, event_type):
placement_str = self._dict.get(item)
self._update_placement(placement_str)
def _check_update_selected_instance_proxy_list(self, path: Sdf.Path, resynced):
def track_or_remove_from_instance_proxy_list(prim):
valid_proxy = prim and prim.IsActive() and prim.IsInstanceProxy()
if valid_proxy:
self._selected_instance_proxy_paths.add(prim.GetPath())
else:
self._selected_instance_proxy_paths.discard(prim.GetPath())
prim_path = path.GetPrimPath()
changed_prim = self._stage.GetPrimAtPath(prim_path)
# Update list of instance proxy paths.
if resynced and path.IsPrimPath():
if prim_path in self._consolidated_xformable_prim_paths:
# Quick path if it's selected already.
track_or_remove_from_instance_proxy_list(changed_prim)
else:
# Slow path to verify if any of its ancestors are changed.
for path in self._consolidated_xformable_prim_paths:
if not path.HasPrefix(prim_path):
continue
prim = self._stage.GetPrimAtPath(path)
track_or_remove_from_instance_proxy_list(prim)
@carb.profiler.profile
async def _update_transform_from_prims_async(self):
try:
check_all_prims = (
self._placement != Placement.LAST_PRIM_PIVOT
and self._placement != Placement.REF_PRIM
and len(self._xformable_prim_paths) > 1
)
pivot_prim_path = self._pivot_prim.GetPath()
for p, resynced in self._pending_changed_paths.items():
self._check_update_selected_instance_proxy_list(p, resynced)
prim_path = p.GetPrimPath()
# Update either check_all_prims
# or prim_path is a prefix of pivot_prim_path (pivot prim's parent affect pivot prim transform)
# Note: If you move the manipulator and the prim flies away while manipulator stays in place, check this
# condition!
if (
# check _xformable_prim_paths_prefix_set so that if the parent path of selected prim(s) changed, it
# can still update manipulator transform
prim_path in self._xformable_prim_paths_prefix_set
if check_all_prims
else pivot_prim_path.HasPrefix(prim_path)
):
if self._path_may_affect_transform(p):
# only delay the visual update in translate mode.
should_delay_frame = self._settings.get(TRANSLATE_DELAY_FRAME_SETTING) > 0
if self._op_settings_listener.selected_op == c.TRANSFORM_OP_MOVE and should_delay_frame:
xform = self._calculate_transform_from_prim()
id = self._app.get_update_number()
self._delay_dirty_tasks_or_futures[id] = run_coroutine(self._delay_dirty(xform, id))
else:
if self._update_transform_from_prims():
self._item_changed(self._transform_item)
break
except Exception as e:
carb.log_error(traceback.format_exc())
finally:
self._pending_changed_paths.clear()
self._update_prim_xform_from_prim_task_or_future = None
@carb.profiler.profile
def _on_objects_changed(self, notice, sender):
if not self._pivot_prim:
return
# collect resynced paths so that removed/added xformOps triggers refresh
for path in notice.GetResyncedPaths():
self._pending_changed_paths[path] = True
# collect changed only paths
for path in notice.GetChangedInfoOnlyPaths():
self._pending_changed_paths[path] = False
# if an operation is in progess, record all dirty xform path
if self._current_editing_op is not None and not self._ignore_xform_data_change:
self._pending_changed_paths_for_xform_data.update(notice.GetChangedInfoOnlyPaths())
if self._update_prim_xform_from_prim_task_or_future is None or self._update_prim_xform_from_prim_task_or_future.done():
self._update_prim_xform_from_prim_task_or_future = run_coroutine(self._update_transform_from_prims_async())
def _on_timeline_event(self, e: carb.events.IEvent):
if e.type == int(omni.timeline.TimelineEventType.CURRENT_TIME_TICKED):
current_time = e.payload["currentTime"]
if current_time != self._current_time:
self._current_time = current_time
self._xform_cache.SetTime(self._get_current_time_code())
# TODO only update transform if this prim or ancestors transforms are time varying?
if self._update_transform_from_prims():
self._item_changed(self._transform_item)
def _get_current_time_code(self):
return Usd.TimeCode(omni.usd.get_frame_time_code(self._current_time, self._stage.GetTimeCodesPerSecond()))
def _set_default_settings(self):
self._settings.set_default(TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_ENABLED, False)
self._settings.set_default(TRANSFORM_GIZMO_IS_USING, False)
self._settings.set_default(TRANSFORM_GIZMO_TRANSLATE_DELTA_XYZ, [0, 0, 0])
self._settings.set_default(TRANSFORM_GIZMO_ROTATE_DELTA_XYZW, [0, 0, 0, 1])
self._settings.set_default(TRANSFORM_GIZMO_SCALE_DELTA_XYZ, [0, 0, 0])
def _should_skip_custom_manipulator_path(self, path: str) -> bool:
custom_manipulator_path_prims_settings_path = TRANSFORM_GIZMO_CUSTOM_MANIPULATOR_PRIMS + path
return self._settings.get(custom_manipulator_path_prims_settings_path)
def _path_may_affect_transform(self, path: Sdf.Path) -> bool:
# Batched changes sent in a SdfChangeBlock may not have property name but only the prim path
return not path.ContainsPropertyElements() or UsdGeom.Xformable.IsTransformationAffectedByAttrNamed(path.name)
| 78,021 | Python | 44.308943 | 146 | 0.623922 |
omniverse-code/kit/exts/omni.kit.window.inspector/config/extension.toml | [package]
title = "Inspector Window (Preview)"
description = "Inspect your UI Elements"
version = "1.0.6"
category = "Developer"
authors = ["NVIDIA"]
repository = ""
keywords = ["stage", "outliner", "scene"]
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
preview_image = "data/inspector_full.png"
icon = "data/clouseau.png"
[dependencies]
"omni.ui" = {}
"omni.ui_query" = {}
"omni.kit.widget.inspector" = {}
[[python.module]]
name = "omni.kit.window.inspector"
[settings]
exts."omni.kit.window.inspector".use_demo_window = false
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
]
stdoutFailPatterns.exclude = [
]
dependencies = [
"omni.kit.mainwindow",
"omni.kit.ui_test",
"omni.kit.window.viewport",
"omni.rtx.window.settings",
"omni.kit.window.stage"
]
[documentation]
pages = [
"docs/overview.md",
"docs/CHANGELOG.md",
]
| 923 | TOML | 18.659574 | 56 | 0.664139 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/inspector_preview.py |
__all__ = ["InspectorPreview"]
from typing import Union
import omni.ui as ui
import omni.kit.app
import carb.events
import carb
from omni.ui_query import OmniUIQuery
from omni.kit.widget.inspector import InspectorWidget, PreviewMode
class InspectorPreview:
"""The Stage widget"""
def destroy(self):
self._window = None
self._inspector = None
def __init__(self, window: ui.Window, **kwargs):
self._window = window
self._widget = window.frame if window else None
self._preview_mode = ["BOTH", "WIRE", "COLOR"]
self._preview_mode_model = None
self._inspector: Union[ui.Inspector, None] = None
self._main_stack = ui.VStack()
self._sender_id = hash("InspectorPreview") & 0xFFFFFFFF
self._build_ui()
app = omni.kit.app.get_app()
self._update_sub = app.get_message_bus_event_stream().create_subscription_to_pop(
self.on_selection_changed, name="Inspector Selection Changed"
)
def on_selection_changed(self, event: carb.events.IEvent):
if event.sender == self._sender_id:
# we don't respond to our own events
return
from .inspector_widget import INSPECTOR_ITEM_SELECTED_ID, INSPECTOR_PREVIEW_CHANGED_ID
if event.type == INSPECTOR_ITEM_SELECTED_ID:
selection = OmniUIQuery.find_widget(event.payload["item_path"])
if selection:
self.set_widget(selection)
elif event.type == INSPECTOR_PREVIEW_CHANGED_ID:
selection = OmniUIQuery.find_widget(event.payload["item_path"])
if selection:
if "window_name" in event.payload:
window_name = event.payload["window_name"]
window = ui.Workspace.get_window(window_name)
if window:
self._window = window
else:
carb.log_error(f"Failed to find {window_name}")
self.set_main_widget(selection)
def toggle_visibility(self):
self._main_stack.visible = not self._main_stack.visible
def _build_ui(self):
with self._main_stack:
ui.Spacer(height=5)
with ui.ZStack():
ui.Rectangle(name="render_background", style={"background_color": 0xFF333333})
with ui.VStack():
ui.Spacer(height=10)
with ui.ZStack():
ui.Rectangle()
with ui.HStack():
self._inspector = InspectorWidget(widget=self._widget)
def selection_changed(widget):
# Send the Selection Changed Message
from .inspector_widget import INSPECTOR_ITEM_SELECTED_ID
stream = omni.kit.app.get_app().get_message_bus_event_stream()
widget_path = OmniUIQuery.get_widget_path(self._window, widget)
if widget_path:
stream.push(
INSPECTOR_ITEM_SELECTED_ID,
sender=self._sender_id,
payload={"item_path": widget_path},
)
self._inspector.set_selected_widget_changed_fn(selection_changed)
with ui.HStack(height=0):
ui.Label("Depth", width=0)
ui.Spacer(width=4)
def value_changed_fn(model: ui.AbstractValueModel):
self._inspector.depth_scale = float(model.as_int)
model = ui.IntDrag(min=0, max=300, width=40).model
model.set_value(50)
model.add_value_changed_fn(value_changed_fn)
ui.Spacer()
# def build Preview Type Radio
with ui.HStack(width=0, style={"margin": 0, "padding_width": 6, "border_radius": 0}):
self._preview_mode_collection = ui.RadioCollection()
def preview_mode_changed(item: ui.AbstractValueModel):
index = item.as_int
if index == 0:
self._inspector.preview_mode = PreviewMode.WIREFRAME_AND_COLOR
elif index == 1:
self._inspector.preview_mode = PreviewMode.WIRE_ONLY
else:
self._inspector.preview_mode = PreviewMode.COLOR_ONLY
self._preview_mode_collection.model.add_value_changed_fn(preview_mode_changed)
for preview_mode in self._preview_mode:
style = {}
radius = 4
if preview_mode == "BOTH":
style = {"border_radius": radius, "corner_flag": ui.CornerFlag.LEFT}
if preview_mode == "COLOR":
style = {"border_radius": radius, "corner_flag": ui.CornerFlag.RIGHT}
ui.RadioButton(
width=50, style=style, text=preview_mode, radio_collection=self._preview_mode_collection
)
def preview_mode_value_changed(value):
if value == PreviewMode.WIREFRAME_AND_COLOR:
self._preview_mode_collection.model.set_value(0)
elif value == PreviewMode.WIRE_ONLY:
self._preview_mode_collection.model.set_value(1)
elif value == PreviewMode.COLOR_ONLY:
self._preview_mode_collection.model.set_value(2)
self._inspector.set_preview_mode_change_fn(preview_mode_value_changed)
ui.Spacer()
ui.Label("Range ", width=0)
def min_value_changed_fn(model: ui.AbstractValueModel):
self._inspector.start_depth = model.as_int
model = ui.IntDrag(min=0, max=20, width=50).model.add_value_changed_fn(min_value_changed_fn)
ui.Spacer(width=4)
def max_value_changed_fn(model: ui.AbstractValueModel):
self._inspector.end_depth = model.as_int
ui.IntDrag(min=0, max=6000, width=50).model.add_value_changed_fn(max_value_changed_fn)
def set_main_widget(self, widget: ui.Widget):
self._widget = widget
self._inspector.widget = widget
def set_widget(self, widget: ui.Widget):
self._inspector.selected_widget = widget
def update_window(self, window: ui.Window):
self._inspector = None
self._window = window
self._widget = window.frame
self._main_stack.clear()
self._build_ui()
| 6,936 | Python | 40.047337 | 116 | 0.523933 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/inspector_window.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
__all__ = ["InspectorWindow"]
import omni.ui as ui
import carb.events
import omni.kit.app
from typing import cast
from .tree.inspector_tree import WindowListModel, WindowItem
from .demo_window import InspectorDemoWindow
from .inspector_widget import InspectorWidget
from pathlib import Path
ICON_PATH = Path(__file__).parent.parent.parent.parent.parent.joinpath("icons")
class InspectorWindow:
"""The inspector window"""
def __init__(self):
window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR
self._window = ui.Window(
"Inspector",
width=1000,
height=800,
flags=window_flags,
dockPreference=ui.DockPreference.RIGHT_TOP,
padding_x=0,
padding_y=0,
)
# Create a Demo Window to show case the general feature
self._demo_window = None
use_demo_window = carb.settings.get_settings().get("/exts/omni.kit.window.inspector/use_demo_window")
with self._window.frame:
if use_demo_window:
self._demo_window = InspectorDemoWindow()
self._inspector_widget = InspectorWidget(self._demo_window.window)
else:
self._inspector_widget = InspectorWidget(None)
def destroy(self):
"""
Called by extension before destroying this object. It doesn't happen automatically.
Without this hot reloading doesn't work.
"""
if self._demo_window:
self._demo_window.destroy()
self._demo_window = None
self._inspector_widget.destroy()
self._inspector_widget = None
self._window = None
| 2,094 | Python | 32.790322 | 109 | 0.661891 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/inspector_tests.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
__all__ = ["test_widget_tool_button", "test_select_frame", "test_change_query", "test_menu_activation"]
from omni.ui_query import OmniUIQuery
import omni.kit.app
import asyncio
import carb
import omni.ui as ui
wait = None
def test_widget_tool_button():
preview_tool_button = OmniUIQuery.find_widget("Inspector/Frame[0]/ZStack[1]/VStack[0]/HStack[2]/ToolButton")
if preview_tool_button:
preview_tool_button.call_clicked_fn()
property_tool_button = OmniUIQuery.find_widget("Inspector/Frame[0]/ZStack[1]/VStack[0]/HStack[3]/ToolButton")
if property_tool_button:
property_tool_button.call_clicked_fn()
style_tool_button = OmniUIQuery.find_widget("Inspector/Frame[0]/ZStack[1]/VStack[0]/HStack[4]/ToolButton")
if style_tool_button:
style_tool_button.call_clicked_fn()
def test_select_frame():
global wait
from .inspector_widget import INSPECTOR_ITEM_SELECTED_ID
stream = omni.kit.app.get_app().get_message_bus_event_stream()
stream.push(INSPECTOR_ITEM_SELECTED_ID, sender=444, payload={"item_path": "DemoWindow/Frame[0]/VStack"})
async def wait_a_frame():
await omni.kit.app.get_app().next_update_async()
spacing_label_path = "Inspector/Frame[0]/ZStack[1]/VStack[2]/HStack[3]/VStack[3]/CollapsableFrame[0]/Frame[0]/VStack[1]/HStack[0]/Label"
spacing_value_path = "Inspector/Frame[0]/ZStack[1]/VStack[2]/HStack[3]/VStack[3]/CollapsableFrame[0]/Frame[0]/VStack[1]/HStack[2]/FloatDrag"
spacing_label = OmniUIQuery.find_widget(spacing_label_path)
print("spacing_label", spacing_label)
if spacing_label and isinstance(spacing_label, ui.Label):
if not spacing_label.text == "spacing":
carb.log_error(f"Failed the Frame Selection Test , Label is {spacing_label.text}")
return
spacing_value = OmniUIQuery.find_widget(spacing_value_path)
print("spacing_value", spacing_value)
if spacing_value and isinstance(spacing_value, ui.FloatDrag):
if not spacing_value.model.as_float == 0.0:
carb.log_error(f"Failed the Frame Selection Test , spacing value is {spacing_value.model.as_float}")
return
carb.log_warn("Frame Selection Test PASSED")
wait = asyncio.ensure_future(wait_a_frame())
def test_change_query():
query_field = OmniUIQuery.find_widget(
"Inspector/Frame[0]/ZStack[1]/VStack[4]/ZStack[1]/VStack[1]/HStack[2]/StringField"
)
if query_field and isinstance(query_field, ui.StringField):
response_field_path = "Inspector/Frame[0]/ZStack[1]/VStack[4]/ZStack[1]/VStack[1]/HStack[4]/StringField"
query_field.model.set_value(response_field_path)
query_field.model.end_edit()
response_field = OmniUIQuery.find_widget(response_field_path)
if not isinstance(response_field, ui.StringField):
carb.log_error(f"Faild to find the right widget at {response_field_path}")
else:
print(response_field, response_field.model.as_string)
def test_menu_activation():
menu_item = OmniUIQuery.find_menu_item("MainWindow/MenuBar[0]/Menu[14]/MenuItem")
print(menu_item)
if isinstance(menu_item, ui.MenuItem):
print(menu_item.text)
menu_item.call_triggered_fn()
| 3,737 | Python | 41 | 148 | 0.693069 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/demo_window.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
__all__ = ["InspectorDemoWindow"]
from typing import cast
from pathlib import Path
import omni.ui as ui
ICON_PATH = Path(__file__).parent.parent.parent.parent.parent.joinpath("icons")
class InspectorDemoWindow:
"""The demo window for the inspector"""
@property
def window(self) -> ui.Window:
return cast(ui.Window, self._window)
def destroy(self):
self._window = None
def __init__(self):
self._window = ui.Window("DemoWindow", width=300, height=900)
style_testing = {
"Label:hovered": {"color": 0xFF00FFFF},
"Label::title": {"font_size": 18, "color": 0xFF00EEEE, "alignment": ui.Alignment.LEFT},
"Label": {"font_size": 14, "color": 0xFFEEEEEE},
"Button.Label": {"font_size": 15, "color": 0xFF33FF33},
"Line": {"color": 0xFFFF0000},
"Slider": {"draw_mode": ui.SliderDrawMode.FILLED, "secondary_color": 0xFFAA0000},
"Stack::blue": {"stack_direction": ui.Direction.RIGHT_TO_LEFT},
"Button::green": {
"background_color": 0xFF333333,
"color": 0xFF00FFFF,
"border_width": 2,
"border_color": 0xFF00FF00,
"border_radius": 3,
"corner_flag": ui.CornerFlag.BOTTOM,
"alignment": ui.Alignment.CENTER,
},
"Button.Image::green": {
# "image_url": "c:/path/to/an/image.png",
"fill_policy": ui.FillPolicy.PRESERVE_ASPECT_FIT
},
}
self._window.frame.set_style(style_testing)
with self._window.frame:
with ui.VStack():
ui.Label("Title", height=0, name="title")
with ui.HStack(height=0):
ui.Label("THis is Cool", style={"Label": {"font_size": 12, "color": 0xFF0000FF}})
def button_fn(name: str):
print(f"Executed Button Labled {name}")
ui.Button("Button 1", name="button1", clicked_fn=lambda n="Button 1": button_fn(n))
ui.Button("Button 2", name="green", clicked_fn=lambda n="Button 2": button_fn(n))
ui.Line(height=2)
ui.Spacer(height=10)
ui.IntSlider(height=0, min=0, max=100)
ui.Spacer(height=10)
with ui.HStack(height=0):
ui.Label("Field", style={"color": 0xFF00FF00})
ui.StringField().model.set_value("This is Cool ")
with ui.HStack(height=0):
ui.Rectangle(
height=30,
style={
"backgroun_color": 0xFFAAAAAA,
"border_width": 2,
"border_radius": 3,
"border_color": 0xFFAADDAA,
},
)
with ui.Frame(height=100):
with ui.Placer(draggable=True):
ui.Rectangle(width=20, height=20, style={"background_color": 0xFF0000FF})
ui.ComboBox(1, "One", "Two", "Inspector", "Is", "Amazing", height=0)
ui.Spacer(height=10)
with ui.VGrid(height=50, column_count=5, row_height=50):
for i in range(5):
ui.Rectangle(style={"background_color": 0xFF000000})
ui.Rectangle(style={"background_color": 0xFFFFFFFF})
with ui.HGrid(height=50, column_width=30, row_count=3):
for i in range(10):
ui.Rectangle(style={"background_color": 0xFF00FFAA})
ui.Rectangle(style={"background_color": 0xFFF00FFF})
ui.Spacer(height=10)
with ui.CollapsableFrame(title="Image", height=0):
# ui.Image("/dfagnou/Desktop/omniverse_background.png", height=100)
ui.Image(f"{ICON_PATH}/sync.svg", height=100)
with ui.HStack(height=30):
ui.Triangle(height=20, style={"background_color": 0xFFAAFFAA})
ui.Circle(style={"background_color": 0xFFAAFFFF})
canvas = ui.CanvasFrame(height=20, style={"background_color": 0xFFDD00DD})
# canvas.set_pan_key_shortcut(1, carb.K)
with canvas:
# ui.Image("/dfagnou/Desktop/omniverse_background.png")
ui.Image(f"{ICON_PATH}/sync.svg", height=20)
| 4,997 | Python | 41.355932 | 103 | 0.529518 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/inspector_widget.py |
__all__ = ["InspectorWidget"]
import omni.ui as ui
from .tree.inspector_tree import InspectorTreeView
from .style.style_tree import StyleTreeView
from .property.inspector_property_widget import InspectorPropertyWidget
from .inspector_preview import InspectorPreview
from omni.ui_query import OmniUIQuery
# move the test into a menu on the top widget to experiment
from .inspector_tests import test_widget_tool_button, test_select_frame, test_change_query, test_menu_activation
from .inspector_style import INSPECTOR_STYLE
DARK_BACKGROUND = 0xFF333333
INSPECTOR_ITEM_SELECTED_ID = 427273737 # hash("INSPECTOR_ITEM_SELECTED")
INSPECTOR_PREVIEW_CHANGED_ID = 427273738 # hash("INSPECTOR_PREVIEW_CHANGED")
INSPECTOR_ITEM_EXPANDED_ID = 427273739
KIT_GREEN = 0xFF888888
class InspectorWidget:
def destroy(self):
self._tree_view.destroy()
self._tree_view = None
self._render_view.set_widget(None)
self._render_view._window = None
self._render_view = None
self._property_view.set_widget(None)
self._property_view = None
def __init__(self, window: ui.Window, **kwargs):
self._test_menu = None
self._window = window
self._render_view = None
self._main_stack = ui.ZStack(style=INSPECTOR_STYLE)
self._build_ui()
def _build_ui(self):
with self._main_stack:
ui.Rectangle(name="background")
with ui.VStack():
with ui.HStack(height=30):
bt = ui.Button("TestMenu", width=0)
def show_test_menu():
self._test_menu = ui.Menu("Test")
with self._test_menu:
ui.MenuItem("ToolButton1", triggered_fn=test_widget_tool_button)
ui.MenuItem("Select Frame", triggered_fn=test_select_frame)
ui.MenuItem("Change Query", triggered_fn=test_change_query)
ui.MenuItem("Test Menu", triggered_fn=test_menu_activation)
self._test_menu.show_at(bt.screen_position_x, bt.screen_position_y + bt.computed_height)
bt.set_clicked_fn(show_test_menu)
ui.Spacer()
# self._tree_vis_model = ui.ToolButton(text="Tree", width=100).model
self._preview_vis_model = ui.ToolButton(text="Preview", name="toolbutton", width=100).model
self._property_vis_model = ui.ToolButton(text="Property", name="toolbutton", width=100).model
self._style_vis_model = ui.ToolButton(text="Style", name="toolbutton", width=100).model
ui.Spacer()
ui.Line(height=3, name="dark_separator")
with ui.HStack():
# Build adjustable Inspector Tree Widget with "Splitter"
with ui.ZStack(width=0):
handle_width = 3
# the placer will increate the stack width
with ui.Placer(offset_x=300, draggable=True, drag_axis=ui.Axis.X):
ui.Rectangle(width=handle_width, name="splitter")
# the tree view will fit the all ZStack Width minus the Handle Width
with ui.HStack(name="tree", style={"HStack::tree": {"margin_width": 5}}):
# Extensions List Widget (on the left)
self._tree_view = InspectorTreeView(self._window, self.update_window)
ui.Spacer(width=handle_width)
# Build Inspector Preview
self._render_view = InspectorPreview(self._window)
ui.Line(alignment=ui.Alignment.H_CENTER, width=2, style={"color": 0xFF222222, "border_width": 2})
# Build Inspector Property Window
self._property_view = InspectorPropertyWidget()
ui.Line(alignment=ui.Alignment.H_CENTER, width=2, style={"color": 0xFF222222, "border_width": 2})
self._style_view = StyleTreeView()
ui.Line(height=3, style={"color": 0xFF222222, "border_width": 3})
with ui.ZStack(height=30):
ui.Rectangle(name="background")
with ui.VStack():
ui.Spacer()
with ui.HStack(height=0):
ui.Spacer(width=10)
ui.Label("Query : ", width=0)
model = ui.StringField(width=400).model
model.set_value("DemoWindow//Frame/VStack[1]/HStack[1]/Button")
ui.Spacer(width=10)
result = ui.StringField(width=200, read_only=True).model
def execute_query(model: ui.AbstractValueModel):
query = model.as_string
children = OmniUIQuery.find_widget(query)
if children:
result.set_value(children.__class__.__name__)
else:
result.set_value("NO RESULT")
if type(children) == ui.Button:
print("Has Clicked Fn", children.has_clicked_fn)
children.call_clicked_fn()
model.add_end_edit_fn(execute_query)
ui.Spacer()
def visiblity_changed_fn(w):
w.toggle_visibility()
self._preview_vis_model.set_value(True)
self._property_vis_model.set_value(True)
self._style_vis_model.set_value(True)
# self._tree_vis_model.add_value_changed_fn(lambda m, w=self._tree_view: visiblity_changed_fn(w))
self._preview_vis_model.add_value_changed_fn(lambda m, w=self._render_view: visiblity_changed_fn(w))
self._property_vis_model.add_value_changed_fn(lambda m, w=self._property_view: visiblity_changed_fn(w))
self._style_vis_model.add_value_changed_fn(lambda m, w=self._style_view: visiblity_changed_fn(w))
self._preview_vis_model.set_value(False)
self._property_vis_model.set_value(False)
self._style_vis_model.set_value(False)
def update_window(self, window: ui.Window):
self._window = window
if self._render_view:
self._render_view.update_window(window)
| 6,568 | Python | 42.503311 | 117 | 0.549635 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/extension.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ext
import omni.kit.ui
from .inspector_window import InspectorWindow
class InspectorExtension(omni.ext.IExt):
"""The entry point for Inspector Window"""
MENU_PATH = "Window/Inspector"
def on_startup(self):
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
self._menu = editor_menu.add_item(InspectorExtension.MENU_PATH, self.show_window, toggle=True, value=True)
self.show_window(None, True)
def on_shutdown(self):
self._menu = None
self._window.destroy()
self._window = None
def _visiblity_changed_fn(self, visible):
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
editor_menu.set_value(InspectorExtension.MENU_PATH, visible)
def show_window(self, menu, value):
if value:
self._window = InspectorWindow()
elif self._window:
self._window.destroy()
self._window = None
| 1,408 | Python | 31.767441 | 118 | 0.683239 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/inspector_style.py |
__all__ = ["INSPECTOR_STYLE"]
import omni.ui as ui
KIT_GREEN = 0xFF888888
DARK_BACKGROUND = 0xFF333333
INSPECTOR_STYLE = {
"Rectangle::background": {"background_color": DARK_BACKGROUND},
# toolbutton
"Button.Label::toolbutton": {"color": 0xFF7B7B7B},
"Button.Label::toolbutton:checked": {"color": 0xFFD4D4D4},
"Button::toolbutton": {"background_color": 0xFF424242, "margin": 2.0},
"Button::toolbutton:checked": {"background_color": 0xFF5D5D5D},
"CheckBox::greenCheck": {"font_size": 10, "background_color": KIT_GREEN, "color": 0xFF23211F},
"Line::dark_separator": {"color": 0xFF222222, "border_width": 3},
"Rectangle::splitter": {"background_color": 0xFF222222},
"Rectangle::splitter:hovered": {"background_color": 0xFFFFCA83},
"Tooltip": {"background_color": 0xFF000000, "color": 0xFF333333},
}
| 845 | Python | 35.782607 | 98 | 0.67574 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/style/style_model.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
__all__ = ["StyleComboValueModel", "StyleComboNameValueItem", "StyleComboItemModel", "StylePropertyType", "StyleColorComponentItem", "StyleColorModel", "StyleItem", "StyleGroupItem", "StyleModel"]
from os import remove
from typing import Callable, Union, List, cast
import omni.ui as ui
from enum import Enum
import copy, carb
StyleFloatProperty = [
"border_radius",
"border_width",
"font_size",
"margin",
"margin_width",
"margin_height",
"padding",
"padding_width",
"padding_height",
"secondary_padding",
"scrollbar_size",
]
StyleColorProperties = [
"background_color",
"background_gradient_color",
"background_selected_color",
"border_color",
"color",
"selected_color",
"secondary_color",
"secondary_selected_color",
"debug_color",
]
StyleEnumProperty = ["corner_flag", "alignment", "fill_policy", "draw_mode", "stack_direction"]
StyleStringProperty = ["image_url"]
def get_enum_class(property_name: str) -> Union[Callable, None]:
if property_name == "corner_flag":
return ui.CornerFlag
elif property_name == "alignment":
return ui.Alignment
elif property_name == "fill_policy":
return ui.FillPolicy
elif property_name == "draw_mode":
return ui.SliderDrawMode
elif property_name == "stack_direction":
return ui.Direction
else:
return None
class StyleComboValueModel(ui.AbstractValueModel):
"""
Model to store a pair (label, value of arbitrary type) for use in a ComboBox
"""
def __init__(self, key, value):
"""
Args:
value: the instance of the Style value
"""
ui.AbstractValueModel.__init__(self)
self.key = key
self.value = value
def __repr__(self):
return f'"StyleComboValueModel name:{self.key} value:{int(self.value)}"'
def get_value_as_string(self) -> str:
"""
this is called to get the label of the combo box item
"""
return self.key
def get_style_value(self) -> int:
"""
we call this to get the value of the combo box item
"""
return int(self.value)
class StyleComboNameValueItem(ui.AbstractItem):
def __init__(self, key, value):
super().__init__()
self.model = StyleComboValueModel(key, value)
def __repr__(self):
return f'"StyleComboNameValueItem {self.model}"'
class StyleComboItemModel(ui.AbstractItemModel):
"""
Model for a combo box - for each setting we have a dictionary of key, values
"""
def __init__(self, class_obj: Callable, default_value: int):
super().__init__()
self._class = class_obj
self._items = []
self._default_value = default_value
default_index = 0
current_index = 0
for key, value in class_obj.__members__.items():
if self._default_value == value:
default_index = current_index
self._items.append(StyleComboNameValueItem(key, value))
current_index += 1
self._current_index = ui.SimpleIntModel(default_index)
self._current_index.add_value_changed_fn(self._current_index_changed)
def get_current_value(self):
return self._items[self._current_index.as_int].model.get_style_value()
def _current_index_changed(self, model):
self._item_changed(None)
def get_item_children(self, item):
return self._items
def get_item_value_model(self, item, column_id: int):
if item is None:
return self._current_index
return item.model
class StylePropertyType(Enum):
ENUM = 0
COLOR = 1
FLOAT = 2
STRING = 3
def get_property_type(property_name: str) -> StylePropertyType:
if property_name in StyleStringProperty:
return StylePropertyType.STRING
elif property_name in StyleEnumProperty:
return StylePropertyType.ENUM
elif property_name in StyleColorProperties:
return StylePropertyType.COLOR
elif property_name in StyleFloatProperty:
return StylePropertyType.FLOAT
else:
return StylePropertyType.FLOAT
class StyleColorComponentItem(ui.AbstractItem):
def __init__(self, model: ui.SimpleFloatModel) -> None:
super().__init__()
self.model = model
class StyleColorModel(ui.AbstractItemModel):
""" define a model for a style color, and enable coversion from int32 etc """
def __init__(self, value: int) -> None:
super().__init__()
self._value = value
# Create root model
self._root_model = ui.SimpleIntModel()
self._root_model.add_value_changed_fn(lambda a: self._item_changed(None))
# convert Value from int
red = self._value & 255
green = (self._value >> 8) & 255
blue = (self._value >> 16) & 255
alpha = (self._value >> 24) & 255
rgba_values = [red / 255, green / 255, blue / 255, alpha / 255]
# Create three models per component
self._items: List[StyleColorComponentItem] = [
StyleColorComponentItem(ui.SimpleFloatModel(rgba_values[i])) for i in range(4)
]
for item in self._items:
item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item))
def set_value(self, value: int):
self._value = value
def set_components_values(self, values: List[float]):
if len(values) != 4:
print("Error: List need to be exactly 4 long")
return
for i in range(4):
self._items[i].model.set_value(values[i])
def set_components_values_as_int(self, values: List[int]):
if len(values) != 4:
print("Error: List need to be exactly 4 long")
return
for i in range(4):
self._items[i].model.set_value(values[i] / 255)
def get_value_as_int8s(self) -> List[int]:
result: List[int] = []
for i in range(4):
result.append(int(round(self._items[i].model.get_value_as_float() * 255)))
return result
def get_value_as_floats(self) -> List[float]:
result: List[float] = []
for i in range(4):
result.append(self._items[i].model.get_value_as_float())
return result
def get_value_as_int32(self) -> int:
red, green, blue, alpha = self.get_value_as_int8s()
# we store then in AABBGGRR
result = (alpha << 24) + (blue << 16) + (green << 8) + red
return result
def _on_value_changed(self, item):
self._item_changed(item)
def get_item_children(self, parentItem: ui.AbstractItem) -> List[StyleColorComponentItem]:
return self._items
def get_item_value_model(self, item: ui.AbstractItem, column_id: int) -> ui.AbstractValueModel:
if item is None:
return self._root_model
return item.model
def begin_edit(self, item):
"""
TODO: if we don't add this override (even without a real implementation) we get crashes
"""
pass
def end_edit(self, item):
"""
TODO: if we don't add this override (even without a real implementation) we get crashes
"""
pass
class StyleItem(ui.AbstractItem):
"""A single AbstractItemModel item that represents a single prim"""
def __init__(
self,
property_name: str,
style_type: StylePropertyType,
values: dict,
parent_model: "StyleModel",
parent_item: "StyleGroupItem",
):
super().__init__()
self.parent_item = parent_item
self.parent_model = parent_model
self.property = property_name
self.style_type = style_type
self.value = values[property_name]
self._values = values
self._model: Union[ui.AbstractValueModel, ui.AbstractItemModel, None] = None
if self.style_type == StylePropertyType.STRING:
self._model = ui.SimpleStringModel(str(self.value))
elif self.style_type == StylePropertyType.ENUM:
enum_cls = get_enum_class(property_name)
self._model = StyleComboItemModel(enum_cls, self.value)
elif self.style_type == StylePropertyType.COLOR:
self._model = StyleColorModel(int(self.value))
elif self.style_type == StylePropertyType.FLOAT:
self._model = ui.SimpleFloatModel(float(self.value))
else:
raise ValueError("The Style Type need to be either STRING, ENUM, COLOR or FLOAT")
if self.style_type in [StylePropertyType.STRING, StylePropertyType.FLOAT]:
def value_changed(model: ui.AbstractValueModel):
self._values[self.property] = model.as_float
self.parent_model.update()
self._model.add_value_changed_fn(value_changed)
elif self.style_type == StylePropertyType.COLOR:
def value_changed(model: StyleColorModel, item: ui.AbstractItem):
self._values[self.property] = model.get_value_as_int32()
self.parent_model.update()
self._model.add_item_changed_fn(value_changed)
elif self.style_type == StylePropertyType.ENUM:
def value_changed(model: StyleComboItemModel, item: ui.AbstractItem):
self._values[self.property] = model.get_current_value()
self.parent_model.update()
self._model.add_item_changed_fn(value_changed)
def delete(self):
# we simply remove the key from the referenced Value Dict
del self._values[self.property]
def get_model(self) -> Union[ui.AbstractValueModel, None]:
return self._model
def __repr__(self):
return f"<StyleItem '{self.property} . {self.style_type}'>"
def __str__(self):
return f"<StyleItem '{self.property} . {self.style_type}'>"
class StyleGroupItem(ui.AbstractItem):
"""A single AbstractItemModel item that represents a single prim"""
def __init__(self, type_name: str, style_dict: dict, parent_model: "StyleModel"):
super().__init__()
self.children = []
self.type_name = type_name
self._parent_dict = style_dict
self.style_dict = self._parent_dict[type_name]
self.parent_model = parent_model
self._name_model = ui.SimpleStringModel()
self._name_model.set_value(type_name)
def value_changed(model: ui.AbstractValueModel):
new_name = model.as_string
if new_name in self._parent_dict:
carb.log_warn(f"Entry with type {new_name} already exits, skipping")
return
self._parent_dict[new_name] = self.style_dict
del self._parent_dict[self.type_name]
self.type_name = new_name
self.parent_model.update()
self._name_model.add_value_changed_fn(value_changed)
def get_model(self):
return self._name_model
def delete_item(self, item: StyleItem):
# we call delete on the item but also make sure we clear our cach for it
self.children.remove(item)
item.delete()
def delete(self):
# we simply remove the key from the referenced Value Dict
del self._parent_dict[self.type_name]
def __repr__(self):
return f"<StyleItem '{self.type_name} . {self.style_dict}'>"
def __str__(self):
return f"<StyleItem '{self.type_name} . {self.style_dict}'>"
class StyleModel(ui.AbstractItemModel):
"""The item model that watches the stage"""
def __init__(self, treeview):
"""Flat means the root node has all the children and children of children, etc."""
super().__init__()
self._widget = None
self._style_dict: dict = {}
self._is_generic = False
self._root: List[StyleGroupItem] = []
self._treeview: "StyleTreeView" = treeview
def _update_style_dict(self, style: dict) -> dict:
style_dict = copy.copy(style)
# find if there are "Generic" entry (with no sub dictionary) and move them around
remove_keys = []
has_generic_entries = False
for key, value in style_dict.items():
if not type(value) == dict:
has_generic_entries = True
break
if has_generic_entries:
style_dict["All"] = {}
for key, value in style_dict.items():
if not type(value) == dict:
style_dict["All"][key] = value
remove_keys.append(key)
for a_key in remove_keys:
del style_dict[a_key]
return style_dict
def set_widget(self, widget: ui.Widget):
self._widget = widget
self.update_cached_style()
self._root: List[StyleGroupItem] = []
self._item_changed(None)
def update_cached_style(self):
if not self._widget.style:
style_dict = {}
else:
style_dict = cast(dict, self._widget.style)
self._style_dict = self._update_style_dict(style_dict)
# rebuild
self._item_changed(None)
def can_item_have_children(self, parentItem: Union[StyleGroupItem, StyleItem]) -> bool:
if not parentItem:
return True
if isinstance(parentItem, StyleGroupItem):
return True
return False
def get_item_children(self, item: Union[StyleGroupItem, StyleItem, None]) -> Union[None, list]:
"""Reimplemented from AbstractItemModel"""
if not item:
if not self._root:
self._root = []
for key, value in self._style_dict.items():
group_item = StyleGroupItem(key, self._style_dict, self)
self._root.append(group_item)
return self._root
if isinstance(item, StyleItem):
return []
if isinstance(item, StyleGroupItem):
children = []
for key, value in item.style_dict.items():
property_type = get_property_type(key)
# value is passed by reference and updated internally on change
style_item = StyleItem(key, property_type, item.style_dict, self, item)
children.append(style_item)
item.children = children
return item.children
# we should not get here ..
return []
def duplicate_item(self, item: StyleGroupItem):
new_item = item.type_name + "1"
self._style_dict[new_item] = copy.copy(self._style_dict[item.type_name])
new_item = StyleGroupItem(new_item, self._style_dict, self)
self._root.append(new_item)
self._item_changed(None)
self.update()
def delete_item(self, item: Union[StyleGroupItem, StyleItem]):
if isinstance(item, StyleItem):
item.parent_item.delete_item(item)
self._item_changed(item.parent_item)
self.update()
elif isinstance(item, StyleGroupItem):
item.delete()
self._root.remove(item)
self._item_changed(None)
self.update()
else:
carb.log_error("Delete_item only support Union[StyleGroupItem, StyleItem]")
def update(self):
style_dict = cast(dict, copy.copy(self._style_dict))
if "All" in style_dict:
# update Generic Entry
for key, value in style_dict["All"].items():
style_dict[key] = value
del style_dict["All"]
self._widget.set_style(style_dict)
def get_item_value_model_count(self, item):
"""Reimplemented from AbstractItemModel"""
return 1
def get_item_value_model(self, item: Union[StyleItem, StyleGroupItem], column_id: int):
"""Reimplemented from AbstractItemModel"""
if isinstance(item, StyleGroupItem):
if column_id == 0:
return item.get_model()
elif isinstance(item, StyleItem):
if column_id == 0:
return ui.SimpleStringModel(item.property)
if column_id == 1:
return item.get_model()
def destroy(self):
self._widget = None
| 16,635 | Python | 30.992308 | 196 | 0.603727 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/style/style_delegate.py |
__all__ = ["StyleTreeDelegate"]
import omni.ui as ui
from typing import Union
from .style_model import StyleGroupItem, StyleModel, StyleItem, StylePropertyType
from .widget_styles import ClassStyles
from pathlib import Path
ICON_PATH = Path(__file__).parent.parent.parent.parent.parent.parent.joinpath("icons")
LINE_COLOR = 0x00555555
STYLE_NAME_DEFAULT = {
"Colors": {
"background_color": 0xFFAAAAAA,
"color": 0xFFAAAAAA,
"secondary_color": 0xFFAAAAAA,
"selected_color": 0xFFAAAAAA,
"secondary_selected_color": 0xFFAAAAAA,
"debug_color": 0xAAAAFFAA,
},
"Border": {"border_radius": 2.0, "border_width": 1.0, "border_color": 0xFFAAFFAA, "corner_flag": ui.CornerFlag.ALL},
"Text": {"alignment": ui.Alignment.LEFT, "font_size": 16.0},
"Images": {"image_url": "", "fill_policy": ui.FillPolicy.STRETCH},
"-Margin-": {"margin": 0, "margin_width": 0, "margin_height": 0},
"-Padding-": {"padding": 0, "padding_width": 0, "padding_height": 0},
"-Misc-": {"secondary_padding": 0, "scrollbar_size": 10, "draw_mode": ui.SliderDrawMode.DRAG},
}
class StyleTreeDelegate(ui.AbstractItemDelegate):
def __init__(self, model: StyleModel):
super().__init__()
self._add_menu = None
self._model = model
self._delete_menu = None
self._delete_group_menu = None
def _show_group_menu(self, b, item: StyleGroupItem):
if not b == 1:
return
if not self._delete_group_menu:
self._delete_group_menu = ui.Menu("Delete")
self._delete_group_menu.clear()
def duplicate_item():
self._model.duplicate_item(item)
def delete_item():
self._model.delete_item(item)
with self._delete_group_menu:
ui.MenuItem("Delete", triggered_fn=delete_item)
ui.MenuItem("Duplicate", triggered_fn=duplicate_item)
self._delete_group_menu.show()
def _show_delete_menu(self, b, item: StyleItem):
if not b == 1:
return
if not self._delete_menu:
self._delete_menu = ui.Menu("Delete")
self._delete_menu.clear()
def delete_item():
self._model.delete_item(item)
with self._delete_menu:
ui.MenuItem("Delete", triggered_fn=delete_item)
self._delete_menu.show()
def _show_add_menu(self, x, y, b, m, type: str, item: StyleGroupItem):
if not self._add_menu:
self._add_menu = ui.Menu("Add")
# menu is dynamically built based on type
self._add_menu.clear()
def add_style(key, value):
# this is capture by the closure
item.style_dict[key] = value
self._model._item_changed(item)
self._model.update()
# we extact the base type
item_type = item.type_name.split(":")[0]
if "." in item_type:
item_type = item_type.split(".")[0]
filtered_style = ClassStyles.get(item_type, None)
def add_menu_item(name: str, default):
if filtered_style and name not in filtered_style:
return
ui.MenuItem(name, triggered_fn=lambda key=name, value=default: add_style(key, value))
with self._add_menu:
for category, values in STYLE_NAME_DEFAULT.items():
if category[0] == "-" or filtered_style:
ui.Separator()
for style, default in values.items():
add_menu_item(style, default)
else:
with ui.Menu(category):
for style, default in values.items():
add_menu_item(style, default)
self._add_menu.show()
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
if column_id == 0:
if isinstance(item, StyleGroupItem):
with ui.VStack(height=0):
ui.Spacer(height=10)
with ui.ZStack(width=10 * (level + 1), height=0):
ui.Rectangle(height=25)
with ui.HStack(width=10 * (level + 1)):
ui.Spacer(height=10)
ui.Spacer()
if model.can_item_have_children(item):
with ui.VStack():
ui.Spacer()
image_name = "Minus" if expanded else "Plus"
ui.Image(
f"{ICON_PATH}/{image_name}.svg",
width=10,
height=10,
style={"color": 0xFFCCCCCC},
)
ui.Spacer()
ui.Spacer(width=5)
else:
ui.Spacer(width=20)
def build_widget(self, model, item: Union[StyleGroupItem, StyleItem], column_id: int, level, expanded):
"""Create a widget per column per item"""
value_model: ui.AbstractValueModel = model.get_item_value_model(item, column_id)
# some cells are empty
if not value_model:
ui.Spacer()
return
# Group Instance = Group Title and Add Button
if isinstance(item, StyleGroupItem):
with ui.VStack():
# small Space before Group Title
ui.Spacer(height=10)
with ui.ZStack(
height=25, mouse_pressed_fn=lambda x, y, b, m, item=item: self._show_group_menu(b, item)
):
ui.Rectangle(style={"background_color": 0xFF222222})
with ui.HStack():
ui.Spacer(width=5)
with ui.VStack():
ui.Spacer()
ui.StringField(
value_model, height=20, style={"font_size": 16, "background_color": 0xFF222222}
)
ui.Spacer()
ui.Spacer(width=5)
group_type = model.get_item_value_model(item, 0).as_string
with ui.VStack(width=0):
ui.Spacer()
ui.Button(
image_url=f"{ICON_PATH}/Add.svg",
width=20,
height=20,
style={"background_color": 0xFF556655, "border_radius": 5},
mouse_pressed_fn=lambda x, y, b, m, type=group_type, item=item: self._show_add_menu(
x, y, b, m, type, item
),
)
ui.Spacer()
# Style Property Row
else:
with ui.HStack(height=25, mouse_pressed_fn=lambda x, y, b, m, item=item: self._show_delete_menu(b, item)):
ui.Spacer(width=5)
with ui.VStack():
ui.Spacer()
ui.Label(
value_model.as_string,
height=0,
style={"font_size": 14, "alignment": ui.Alignment.RIGHT_CENTER, "margin_width": 5},
)
ui.Spacer()
# Value Model for the Second Columns
value_model: ui.AbstractValueModel = model.get_item_value_model(item, 1)
with ui.VStack():
ui.Spacer()
with ui.HStack(height=0):
# key: str = model.get_item_value_model(item, 0).as_string
if item.style_type == StylePropertyType.COLOR:
# color_model = StyleColorModel(value_model.as_int)
ui.ColorWidget(value_model, width=12, height=12)
elif item.style_type == StylePropertyType.FLOAT:
ui.FloatDrag(value_model).step = 1
elif item.style_type == StylePropertyType.STRING:
ui.StringField(value_model)
elif item.style_type == StylePropertyType.ENUM:
ui.ComboBox(value_model)
ui.Spacer(width=20)
ui.Spacer()
| 8,610 | Python | 37.271111 | 120 | 0.483275 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/style/resolved_style.py |
__all__ = ["ResolvedStyleWidget"]
from typing import Union
import omni.ui as ui
from .widget_styles import ClassStyles
from .style_model import get_property_type, StylePropertyType, StyleColorModel, StyleComboItemModel, get_enum_class
class ResolvedStyleWidget:
"""The Stage widget"""
def __init__(self, **kwargs):
self._widget = None
# self._frame_widget = ui.CollapsableFrame("Resolved Styles", height=0, build_fn=self._build_ui)
# with self._frame_widget:
self._stack = ui.VStack(height=0, spacing=5)
self._class_name_mapping = {
"CollapsableFrame": "Frame",
"VStack": "Stack",
"HStack": "Stack",
"ZStack": "Stack",
"IntSlider": "AbstractSlider",
"FloatSlider": "AbstractSlider",
"IntDrag": "AbstractSlider",
"FloatDrag": "AbstractSlider",
}
def set_widget(self, widget: ui.Widget):
self._widget = widget
self._widget_type = self._widget.__class__.__name__
self._widget_type = self._class_name_mapping.get(self._widget_type, self._widget_type)
self._widget_styles = ClassStyles.get(self._widget_type, [])
self._build_ui()
def _build_ui(self):
self._stack.clear()
if not self._widget:
return
with self._stack:
ui.Label("Resolved Styles", height=0)
ui.Spacer(height=5)
for name in self._widget_styles:
with ui.HStack(height=0):
ui.Spacer(width=10)
ui.Label(name, width=150)
prop_type = get_property_type(name)
if prop_type == StylePropertyType.COLOR:
print(ui.Inspector.get_resolved_style(self._widget))
value = False
# value: Union[int, bool] = ui.Inspector.get_resolved_style(self._widget.get_resolved_style_value(name)
if value:
model = StyleColorModel(value)
color_widget = ui.ColorWidget(enabled=False)
color_widget.model = model
else:
ui.Label("Default")
elif prop_type == StylePropertyType.FLOAT:
print(ui.Inspector.get_resolved_style(self._widget))
value = False
# value: Union[float, bool] = self._widget.get_resolved_style_value(name)
if value:
field = ui.FloatField().model
field.set_value(value)
else:
ui.Label("Default")
elif prop_type == StylePropertyType.STRING:
print(ui.Inspector.get_resolved_style(self._widget))
value = False
# value: Union[str, bool] = self._widget.get_resolved_style_value(name)
if value:
ui.StringField().model.set_value(value)
else:
ui.Label("Default")
elif prop_type == StylePropertyType.ENUM:
print(ui.Inspector.get_resolved_style(self._widget))
value = False
# value: Union[int, bool] = self._widget.get_resolved_style_value(name)
if value:
enum_cls = get_enum_class(name)
self._model = StyleComboItemModel(enum_cls, value)
ui.ComboBox(self._model)
else:
ui.Label("Default")
else:
ui.Label("MISSING ... TYPE")
| 3,885 | Python | 39.905263 | 127 | 0.487259 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/style/style_tree.py |
__all__ = ["StyleTreeView"]
from typing import Dict, cast
from ..tree.inspector_tree import ICON_PATH
import omni.ui as ui
import omni.kit.app
import carb.events
from omni.ui_query import OmniUIQuery
from .style_model import StyleModel
from .style_delegate import StyleTreeDelegate
from .resolved_style import ResolvedStyleWidget
from .style_model import StyleEnumProperty, StyleColorProperties
import json
import omni.kit.clipboard
def int32_color_to_hex(value: int) -> str:
# convert Value from int
red = value & 255
green = (value >> 8) & 255
blue = (value >> 16) & 255
alpha = (value >> 24) & 255
def hex_value_only(value: int):
hex_value = f"{value:#0{4}x}"
return hex_value[2:].upper()
hex_color = f"HEX<0x{hex_value_only(alpha)}{hex_value_only(blue)}{hex_value_only(green)}{hex_value_only(red)}>HEX"
return hex_color
def int_enum_to_constant(value: int, key: str) -> str:
result = ""
if key == "corner_flag":
enum = ui.CornerFlag(value)
result = f"UI.CONSTANT<ui.CornerFlag.{enum.name}>UI.CONSTANT"
elif key == "alignment":
enum = ui.Alignment(value)
result = f"UI.CONSTANT<ui.Alignment.{enum.name}>UI.CONSTANT"
elif key == "fill_policy":
enum = ui.FillPolicy(value)
result = f"UI.CONSTANT<ui.FillPolicy.{enum.name}>UI.CONSTANT"
elif key == "draw_mode":
enum = ui.SliderDrawMode(value)
result = f"UI.CONSTANT<ui.SliderDrawMode.{enum.name}>UI.CONSTANT"
elif key == "stack_direction":
enum = ui.Direction(value)
result = f"UI.CONSTANT<ui.Direction.{enum.name}>UI.CONSTANT"
return result
class StyleTreeView:
"""The Stage widget"""
def __init__(self, **kwargs):
self._widget = None
self._model = StyleModel(self)
self._delegate = StyleTreeDelegate(self._model)
self._main_stack = ui.VStack()
self._build_ui()
app = omni.kit.app.get_app()
self._update_sub = app.get_message_bus_event_stream().create_subscription_to_pop(
self.on_selection_changed, name="Inspector Selection Changed"
)
def on_selection_changed(self, event: carb.events.IEvent):
from ..inspector_widget import INSPECTOR_ITEM_SELECTED_ID
if event.type == INSPECTOR_ITEM_SELECTED_ID:
selection = OmniUIQuery.find_widget(event.payload["item_path"])
if selection:
self.set_widget(selection)
def toggle_visibility(self):
self._main_stack.visible = not self._main_stack.visible
def set_widget(self, widget: ui.Widget):
self._widget = widget
# self._resolved_style.set_widget(widget)
self._model.set_widget(widget)
self._tree_view.set_expanded(None, True, True)
def _build_ui(self):
with self._main_stack:
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Spacer(width=10)
ui.Button(
image_url=f"{ICON_PATH}/copy.svg",
width=20,
height=20,
style={"margin": 0},
clicked_fn=self._copy_style,
)
ui.Label("Styles", height=0, style={"font_size": 16}, alignment=ui.Alignment.CENTER)
ui.Button(
image_url=f"{ICON_PATH}/Add.svg",
style={"margin": 0},
height=20,
width=20,
clicked_fn=self._add_style,
)
ui.Spacer(width=10)
ui.Spacer(height=3)
ui.Line(height=1, style={"color": 0xFF222222, "border_width": 1})
with ui.HStack():
ui.Spacer(width=5)
with ui.VStack():
# ResolvedStyleWidget: Omni.UI API is Broken
# self._resolved_style = ResolvedStyleWidget()
# ui.Spacer(height=10)
ui.Label("Local Styles", height=0)
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style_type_name_override="TreeView.ScrollingFrame",
style={"TreeView.ScrollingFrame": {"background_color": 0xFF333333}},
):
self._tree_view = ui.TreeView(
self._model,
delegate=self._delegate,
column_widths=[ui.Fraction(1), 150],
header_visible=False,
root_visible=False,
)
self._tree_view.set_expanded(None, True, True)
ui.Spacer(width=5)
def _add_style(self):
if not self._widget:
return
style = cast(dict, self._widget.style)
if not style:
style = {}
style["color"] = 0xFF000000
self._widget.set_style(style)
self._model.update_cached_style()
def _copy_style(self):
if self._widget:
style: Dict = cast(Dict, self._widget.style)
if not style:
style = {}
has_type_names = False
# convert numbers to
for key, value in style.items():
if type(value) == dict:
has_type_names = True
for name, internal_value in value.items():
if name in StyleColorProperties:
value[name] = int32_color_to_hex(internal_value)
if name in StyleEnumProperty:
value[name] = int_enum_to_constant(internal_value, name)
else:
if key in StyleColorProperties:
style[key] = int32_color_to_hex(value)
if key in StyleEnumProperty:
style[key] = int_enum_to_constant(value, key)
if has_type_names:
style_json = json.dumps(style, indent=4)
else:
style_json = json.dumps(style)
# remove HEX Markers
style_json = style_json.replace('"HEX<', "")
style_json = style_json.replace('>HEX"', "")
# remove Constant Markers
style_json = style_json.replace('"UI.CONSTANT<', "")
style_json = style_json.replace('>UI.CONSTANT"', "")
omni.kit.clipboard.copy(style_json)
| 6,562 | Python | 34.475675 | 118 | 0.535812 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/style/widget_styles.py |
__all__ = ["ClassStyles"]
ClassStyles = {
"AbstractField": ["background_selected_color", "color", "padding"],
"AbstractSlider": [
"background_color",
"border_color",
"border_radius",
"border_width",
"color",
"draw_mode",
"padding",
"secondary_color",
"secondary_selected_color",
"font_size",
],
"Button": [
"background_color",
"border_color",
"border_radius",
"border_width",
"color",
"padding",
"font_size",
"stack_direction",
],
"CanvasFrame": ["background_color"],
"CheckBox": ["background_color", "border_radius", "font_size", "color"],
"Circle": ["background_color", "border_color", "border_width"],
"ColorWidget": ["background_color", "border_color", "border_radius", "border_width", "color"],
"ComboBox": [
"font_size",
"background_color",
"border_radius",
"color",
"padding",
"padding_height",
"padding_width",
"secondary_color",
"secondary_padding",
"secondary_selected_color",
"selected_color",
],
"DockSpace": ["background_color"],
"Frame": ["padding"],
"FreeBezierCurve": ["border_width", "color"],
"Image": [
"alignment",
"border_color",
"border_radius",
"border_width",
"color",
"corner_flag",
"fill_policy",
"image_url",
],
"ImageWithProvider": [
"alignment",
"border_color",
"border_radius",
"border_width",
"color",
"corner_flag",
"fill_policy",
"image_url",
],
"Label": ["padding", "alignment", "color", "font_size"],
"Line": ["border_width", "color"],
"MainWindow": ["background_color", "Margin_height", "margin_width"],
"Menu": [
"background_color",
"BackgroundSelected_color",
"border_color",
"border_radius",
"border_width",
"color",
"padding",
"secondary_color",
],
"MenuBar": [
"background_color",
"BackgroundSelected_color",
"border_color",
"border_radius",
"border_width",
"color",
"padding",
],
"MenuItem": ["BackgroundSelected_color", "color", "secondary_color"],
"Plot": [
"background_color",
"BackgroundSelected_color",
"border_color",
"border_radius",
"border_width",
"color",
"secondary_color",
"selected_color",
],
"ProgressBar": [
"background_color",
"border_color",
"border_radius",
"border_width",
"color",
"padding",
"secondary_color",
],
"Rectangle": [
"background_color",
"BackgroundGradient_color",
"border_color",
"border_radius",
"border_width",
"corner_flag",
],
"ScrollingFrame": ["background_color", "ScrollbarSize", "secondary_color"],
"Separator": ["color"],
"Stack": ["debug_color"],
"TreeView": ["background_color", "background_selected_color", "secondary_color", "secondary_selected_color"],
"Triangle": ["background_color", "border_color", "border_width"],
"Widget": [
"background_color",
"border_color",
"border_radius",
"border_width",
"Debug_color",
"margin",
"margin_height",
"margin_width",
],
"Window": ["background_color", "border_color", "border_radius", "border_width"],
}
| 3,607 | Python | 25.725926 | 113 | 0.512337 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/tree/inspector_tree.py |
__all__ = ["WindowItem", "WindowListModel", "InspectorTreeView"]
from typing import List, cast
import asyncio
import omni.ui as ui
import omni.kit.app
import carb
import carb.events
from .inspector_tree_model import InspectorTreeModel, WidgetItem
from .inspector_tree_delegate import InspectorTreeDelegate
from omni.ui_query import OmniUIQuery
from pathlib import Path
ICON_PATH = Path(__file__).parent.parent.parent.parent.parent.parent.joinpath("icons")
DARK_BACKGROUND = 0xFF333333
class WindowItem(ui.AbstractItem):
def __init__(self, window_name: str, display_name: str = ""):
super().__init__()
self.model = ui.SimpleStringModel(display_name if display_name else window_name)
self.window_name = window_name
class WindowListModel(ui.AbstractItemModel):
def __init__(self):
super().__init__()
self._current_index = ui.SimpleIntModel()
self._current_index.add_value_changed_fn(lambda a: self._item_changed(None))
self._items = []
self._forbidden_windows = ["Inspector"]
async def refresh_later():
await omni.kit.app.get_app().next_update_async()
self.refresh()
asyncio.ensure_future(refresh_later())
def refresh(self):
self._items = []
window_list = []
for w in ui.Workspace.get_windows():
if isinstance(w, ui.Window) and not w.title in self._forbidden_windows and w.visible:
window_list.append(w)
window_list = sorted(window_list, key=lambda a: a.title)
for index, w in enumerate(window_list):
self._items.append(WindowItem(w.title))
if w.title == "DemoWindow":
self._current_index.set_value(index)
self._item_changed(None)
def get_current_window(self) -> str:
index = self.get_item_value_model(None, 0).as_int
if not self._items:
print ("no other windows available!")
return None
item = self._items[index]
return item.window_name
def get_item_children(self, item):
return self._items
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
class InspectorTreeView:
def destroy(self):
self._window = None
self._frame = None
self._model = None
self._delegate.set_window(None)
def __init__(self, window: ui.Window, update_window_cb: callable, **kwargs):
self._delegate = InspectorTreeDelegate()
self._preview_window = None
self._tree_view = None
self._model = None
self._sender_id = hash("InspectorTreeView") & 0xFFFFFFFF
self._window = window
self._frame = window.frame if window else None
self._update_window_cb = update_window_cb
self._main_stack = ui.VStack()
self._update_window(window)
self._build_ui()
app = omni.kit.app.get_app()
self._update_sub_sel = app.get_message_bus_event_stream().create_subscription_to_pop(
self.on_selection_changed, name="Inspector Selection Changed"
)
self._update_sub_exp = app.get_message_bus_event_stream().create_subscription_to_pop(
self.on_expansion_changed, name="Inspector Expand"
)
def on_expansion_changed(self, event: carb.events.IEvent):
if not self._model:
# carb.log_error("NO Model setup")
return
if event.sender == self._sender_id:
# we don't respond to our own changes
return
from ..inspector_widget import INSPECTOR_ITEM_EXPANDED_ID
def set_expansion_state(item, exp_state):
for c in item.children:
c.expanded = exp_state
set_expansion_state(c, exp_state)
if event.type == INSPECTOR_ITEM_EXPANDED_ID:
expansion_path = OmniUIQuery.find_widget(event.payload["item_path"])
expansion_item = cast(ui.AbstractItem, self._model.get_item_for_widget(expansion_path))
expand = event.payload["expand"]
self.set_expanded(expansion_item, expand, True)
expansion_item.expanded = expand
set_expansion_state(expansion_item, expand)
def on_selection_changed(self, event: carb.events.IEvent):
if not self._model:
# carb.log_error("NO Model setup")
return
if event.sender == self._sender_id:
# we don't respond to our own changes
return
from ..inspector_widget import INSPECTOR_ITEM_SELECTED_ID
if event.type == INSPECTOR_ITEM_SELECTED_ID:
selection = OmniUIQuery.find_widget(event.payload["item_path"])
if selection:
selection_item, items = cast(ui.AbstractItem, self._model.get_item_with_path_for_widget(selection))
if selection_item:
if len(self._tree_view.selection) == 1 and self._tree_view.selection[0] != selection_item:
for item in reversed(items):
self._tree_view.set_expanded(item, True, False)
self._selection = [selection_item]
self._tree_view.selection = self._selection
def _update_window(self, window: ui.Window):
self._window = window
self._frame = window.frame if window else None
if self._update_window_cb:
self._update_window_cb(window)
self._model = InspectorTreeModel(window)
self._delegate.set_window(window)
self._selection: List[WidgetItem] = []
if self._tree_view:
self._tree_view.model = self._model
def toggle_visibility(self):
self._main_stack.visible = not self._main_stack.visible
def set_expanded(self, item: WidgetItem, expanded: bool, recursive: bool = False):
"""
Sets the expansion state of the given item.
Args:
item (:obj:`WidgetItem`): The item to effect.
expanded (bool): True to expand, False to collapse.
recursive (bool): Apply state recursively to descendent nodes. Default False.
"""
if self._tree_view and item:
self._tree_view.set_expanded(item, expanded, recursive)
def _build_ui(self):
with self._main_stack:
with ui.ZStack(height=0):
ui.Rectangle(style={"background_color": DARK_BACKGROUND})
with ui.VStack():
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Spacer(width=5)
ui.Label("Windows", height=20, width=0)
ui.Spacer(width=10)
def combo_changed_fn(model: WindowListModel, item: WindowItem):
window_name = model.get_current_window()
if window_name:
window: ui.Window = ui.Workspace.get_window(window_name)
if window:
self._update_window(window)
self._window_list_model = WindowListModel()
self._window_list_model.add_item_changed_fn(combo_changed_fn)
ui.ComboBox(self._window_list_model, identifier="WindowListComboBox")
ui.Spacer(width=5)
def refresh_windows():
self._window_list_model.refresh()
ui.Button(
image_url=f"{ICON_PATH}/sync.svg",
style={"margin": 0},
width=19,
height=19,
clicked_fn=refresh_windows,
)
ui.Spacer(width=5)
ui.Spacer(height=10)
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style_type_name_override="TreeView.ScrollingFrame",
style={"TreeView.ScrollingFrame": {"background_color": 0xFF23211F}},
):
with ui.VStack():
ui.Spacer(height=5)
self._tree_view = ui.TreeView(
self._model,
delegate=self._delegate,
column_widths=[ui.Fraction(1), 40],
header_visible=False,
root_visible=False,
selection_changed_fn=self._widget_selection_changed,
identifier="WidgetInspectorTree"
)
def _widget_selection_changed(self, selection: list):
if len(selection) == 0:
self._selection = selection
return
if not selection[0]:
return
if len(self._selection) > 0 and self._selection[0] == selection[0]:
return
self._selection = selection
first_widget_path = self._selection[0].path
# Send the Selection Changed Message
from ..inspector_widget import INSPECTOR_ITEM_SELECTED_ID
stream = omni.kit.app.get_app().get_message_bus_event_stream()
stream.push(INSPECTOR_ITEM_SELECTED_ID, sender=self._sender_id, payload={"item_path": first_widget_path})
return
for a_selection in self._selection:
widget: ui.Widget = a_selection.widget
print("style", widget.get_style())
print(widget.checked)
print(widget.computed_content_width)
print(widget.computed_content_height)
print(widget.computed_height)
print(widget.computed_width)
print(widget.width)
print(widget.height)
print(widget.screen_position_x)
print(widget.screen_position_y)
properties = ["font_size", "border_width", "border_color", "alignment"]
color = widget.get_resolved_style_value("color")
if color:
print("color", hex(color))
bg_color = widget.get_resolved_style_value("background_color")
if bg_color:
print("background_color", hex(bg_color))
for a_style in properties:
print(a_style, widget.get_resolved_style_value(a_style))
# widget.set_style({"debug_color": 0x1100DD00})
| 10,521 | Python | 35.282758 | 115 | 0.564015 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/tree/inspector_tree_model.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
__all__ = ["WidgetItem", "InspectorTreeModel"]
from typing import Union
import omni.ui as ui
from omni.ui_query import OmniUIQuery
class WidgetItem(ui.AbstractItem):
"""A single AbstractItemModel item that represents a single prim"""
def __init__(self, widget: ui.Widget, path: str):
super().__init__()
self.widget = widget
self.path = path
self.children = []
# True when it's necessary to repopulate its children
self.populated = False
widget_name = path.split("/")[-1]
self._widget_name = widget_name
# Get Type
self._widget_type = str(type(widget)).split(".")[-1]
self._widget_type = self._widget_type.split("'")[0]
self.type_model = ui.SimpleStringModel(self._widget_type)
self.expanded = False
def __repr__(self):
return f"<Omni::UI Widget '{str(type(self.widget))}'>"
def __str__(self):
return f"WidgetItem: {self.widget} @ {self.path}"
class InspectorTreeModel(ui.AbstractItemModel):
"""The item model that watches the stage"""
def __init__(self, window: ui.Window):
"""Flat means the root node has all the children and children of children, etc."""
super().__init__()
self._root = None
self._frame = window.frame if window else None
self._window_name = window.title if window else ""
self._window = window
self._frame_item = WidgetItem(self._frame, f"{self._window_name}//Frame")
def get_item_for_widget(self, widget: ui.Widget) -> Union[WidgetItem, None]:
def search_for_item(item: WidgetItem, widget: ui.Widget) -> Union[WidgetItem, None]:
if item.widget == widget:
return item
if isinstance(item.widget, ui.Container) or isinstance(item.widget, ui.TreeView):
for a_child_item in self.get_item_children(item):
matched_item = search_for_item(a_child_item, widget)
if matched_item:
return matched_item
return None
return search_for_item(self._frame_item, widget)
def get_item_with_path_for_widget(self, widget: ui.Widget):
parents = []
def search_for_item(item: WidgetItem, widget: ui.Widget):
if item.widget == widget:
return item
if isinstance(item.widget, ui.Container) or isinstance(item.widget, ui.TreeView):
for a_child_item in self.get_item_children(item):
matched_item = search_for_item(a_child_item, widget)
if matched_item:
parents.append(item)
return matched_item
return None
item = search_for_item(self._frame_item, widget)
return item, parents
def can_item_have_children(self, parentItem: WidgetItem) -> bool:
if not parentItem:
return True
if not parentItem.widget:
return True
if issubclass(type(parentItem.widget), ui.Container):
return True
elif issubclass(type(parentItem.widget), ui.TreeView):
return True
else:
return False
def get_item_children(self, item: WidgetItem):
"""Reimplemented from AbstractItemModel"""
if item is None:
return [self._frame_item]
if item.populated:
return item.children
widget = item.widget
# return the children of the Container
item.children = []
index = 0
for w in ui.Inspector.get_children(widget):
widget_path = OmniUIQuery.get_widget_path(self._window, w)
if widget_path:
# TODO: There are widgets that have no paths... why?
new_item = WidgetItem(w, widget_path)
item.children.append(new_item)
item.populated = True
return item.children
def get_item_value_model_count(self, item):
"""Reimplemented from AbstractItemModel"""
return 2
def get_widget_type(self, item):
return item._widget_type
def get_widget_path(self, item):
return item.path
def get_item_value_model(self, item, column_id):
"""Reimplemented from AbstractItemModel"""
if item is None:
return ui.SimpleStringModel("Window")
if column_id == 0:
return ui.SimpleStringModel(item._widget_name)
if column_id == 1:
style = item.widget.style if item and item.widget else None
return ui.SimpleBoolModel(not style == None)
if column_id == 2:
height = item.widget.computed_height
return ui.SimpleStringModel("{:10.2f}".format(height))
| 5,207 | Python | 33.039215 | 93 | 0.604955 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/tree/inspector_tree_delegate.py |
__all__ = ["InspectorTreeDelegate"]
import os.path
import omni.ui as ui
import omni.kit.app
import carb
from .inspector_tree_model import WidgetItem, InspectorTreeModel
from pathlib import Path
ICON_PATH = Path(__file__).parent.parent.parent.parent.parent.parent.joinpath("icons")
class InspectorTreeDelegate(ui.AbstractItemDelegate):
def __init__(self):
super().__init__()
self._context_menu = None
self._window_title = None
self._icon_alternatives = {
"CollapsableFrame": "Frame",
"InvisibleButton": "Button",
"ImageWithProvider": "Image",
"FloatDrag": "FloatField",
}
def set_window(self, window: ui.Window):
if window:
self._window_title = window.title
def _copy_path(self, item: WidgetItem):
try:
import omni.kit.clipboard
omni.kit.clipboard.copy(item.path)
except ImportError:
carb.log_warn("Could not import omni.kit.clipboard.")
def _expand_nodes(self, item: WidgetItem, expand=False):
from ..inspector_widget import INSPECTOR_ITEM_EXPANDED_ID
stream = omni.kit.app.get_app().get_message_bus_event_stream()
stream.push(INSPECTOR_ITEM_EXPANDED_ID, payload={"item_path": item.path, "expand": expand})
def _show_context_menu(self, button: int, item: WidgetItem):
if not self._context_menu:
self._context_menu = ui.Menu("Context")
self._context_menu.clear()
if not button == 1:
return
def send_selected_message(item: WidgetItem):
from ..inspector_widget import INSPECTOR_PREVIEW_CHANGED_ID
stream = omni.kit.app.get_app().get_message_bus_event_stream()
stream.push(
INSPECTOR_PREVIEW_CHANGED_ID, payload={"item_path": item.path, "window_name": self._window_title}
)
with self._context_menu:
ui.MenuItem("Preview", triggered_fn=lambda item=item: send_selected_message(item))
ui.MenuItem("Copy Path", triggered_fn=lambda item=item: self._copy_path(item))
if item.expanded:
ui.MenuItem(
"Collapse All", triggered_fn=lambda item=item, expand=False: self._expand_nodes(item, expand)
)
else:
ui.MenuItem("Expand All", triggered_fn=lambda item=item, expand=True: self._expand_nodes(item, expand))
self._context_menu.show()
def build_branch(self, model: InspectorTreeModel, item: WidgetItem, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
if column_id == 0:
with ui.HStack(width=25 * (level + 1), height=0, style={"Line": {"color": 0xFFAAAAAA}}):
ui.Spacer(width=25 * level + 10)
if model.can_item_have_children(item):
# ui.Spacer()
with ui.VStack():
ui.Spacer()
image_name = "Minus" if expanded else "Plus"
ui.Image(f"{ICON_PATH}/{image_name}.svg", width=10, height=10, style={"color": 0xFFCCCCCC})
ui.Spacer()
else:
ui.Spacer(width=10)
ui.Spacer()
def build_widget(self, model: InspectorTreeModel, item: WidgetItem, column_id, level, expanded):
"""Create a widget per column per item"""
value_model: ui.AbstractValueModel = model.get_item_value_model(item, column_id)
widget_type = model.get_widget_type(item)
if column_id == 0:
with ui.HStack(height=30, mouse_pressed_fn=lambda x, y, b, m, item=item: self._show_context_menu(b, item)):
with ui.VStack(width=25):
ui.Spacer()
icon = f"{widget_type}"
if not os.path.isfile(f"{ICON_PATH}/{icon}.svg"):
if icon in self._icon_alternatives:
icon = self._icon_alternatives[icon]
else:
carb.log_warn(f"{ICON_PATH}/{icon}.svg not found")
icon = "Missing"
ui.Image(f"{ICON_PATH}/{icon}.svg", width=25, height=25)
ui.Spacer()
ui.Spacer(width=10)
with ui.VStack():
ui.Spacer()
ui.Label(
value_model.as_string,
height=0,
style={"color": 0xFFEEEEEE},
tooltip=model.get_widget_path(item),
)
ui.Spacer()
elif column_id == 1:
# does it contain a Local Style
if value_model.as_bool:
with ui.HStack():
ui.Label("Style", alignment=ui.Alignment.RIGHT)
ui.Spacer(width=5)
def build_header(self, column_id):
"""Create a widget per column per item"""
label = ""
if column_id == 0:
label = "Type"
if column_id == 1:
label = "Has Style"
ui.Label(label, alignment=ui.Alignment.CENTER)
| 5,239 | Python | 37.529411 | 119 | 0.538271 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/create_widget.py |
__all__ = ["get_property_enum_class", "PropertyType", "create_property_widget"]
from typing import Tuple, Union, Callable
import omni.ui as ui
import enum
from .widget_model import WidgetModel, WidgetComboItemModel
from .widget_builder import PropertyWidgetBuilder
def get_property_enum_class(property: str) -> Callable:
if property == "direction":
return ui.Direction
elif property == "alignment":
return ui.Alignment
elif property == "fill_policy":
return ui.FillPolicy
elif property == "arc":
return ui.Alignment
elif property == "size_policy":
return ui.CircleSizePolicy
elif property == "drag_axis":
return ui.Axis
else:
return ui.Direction
class PropertyType(enum.Enum):
FLOAT = 0
INT = 1
COLOR3 = 2
BOOL = 3
STRING = 4
DOUBLE3 = 5
INT2 = 6
DOUBLE2 = 7
ENUM = 8
# TODO: Section will be moved to some location like omni.ui.settings
# #############################################################################################
def create_property_widget(
widget: ui.Widget, property: str, property_type: PropertyType, range_from=0, range_to=0, speed=1, **kwargs
) -> Tuple[Union[ui.Widget, None], Union[ui.AbstractValueModel, None]]:
"""
Create a UI widget connected with a setting.
If ``range_from`` >= ``range_to`` there is no limit. Undo/redo operations are also supported, because changing setting
goes through the :mod:`omni.kit.commands` module, using :class:`.ChangeSettingCommand`.
Args:
setting_path: Path to the setting to show and edit.
property_type: Type of the setting to expect.
range_from: Limit setting value lower bound.
range_to: Limit setting value upper bound.
Returns:
:class:`ui.Widget` connected with the setting on the path specified.
"""
property_widget: Union[ui.Widget, None] = None
model = None
# Create widget to be used for particular type
if property_type == PropertyType.INT:
model = WidgetModel(widget, property)
property_widget = PropertyWidgetBuilder.createIntWidget(model, range_from, range_to, **kwargs)
elif property_type == PropertyType.FLOAT:
model = WidgetModel(widget, property)
property_widget = PropertyWidgetBuilder.createFloatWidget(model, range_from, range_to, **kwargs)
elif property_type == PropertyType.BOOL:
model = WidgetModel(widget, property)
property_widget = PropertyWidgetBuilder.createBoolWidget(model, **kwargs)
elif property_type == PropertyType.STRING:
model = WidgetModel(widget, property)
property_widget = ui.StringField(**kwargs)
elif property_type == PropertyType.ENUM:
enum_cls = get_property_enum_class(property)
model = WidgetComboItemModel(widget, property, enum_cls)
property_widget = ui.ComboBox(model, **kwargs)
else:
print("Couldnt find widget for ", property_type, property) # Do we have any right now?
return property_widget, None
if property_widget:
try:
property_widget.model = model
except:
print(widget, "doesn't have model")
return property_widget, model
| 3,241 | Python | 34.626373 | 122 | 0.650417 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widget_builder.py |
__all__ = ["PropertyWidgetBuilder"]
import omni.ui as ui
LABEL_HEIGHT = 18
HORIZONTAL_SPACING = 4
LABEL_WIDTH = 150
class PropertyWidgetBuilder:
@classmethod
def _build_reset_button(cls, path) -> ui.Rectangle:
with ui.VStack(width=0, height=0):
ui.Spacer()
with ui.ZStack(width=15, height=15):
with ui.HStack(style={"margin_width": 0}):
ui.Spacer()
with ui.VStack(width=0):
ui.Spacer()
ui.Rectangle(width=5, height=5, name="reset_invalid")
ui.Spacer()
ui.Spacer()
btn = ui.Rectangle(width=12, height=12, name="reset", tooltip="Click to reset value")
btn.visible = False
btn.set_mouse_pressed_fn(lambda x, y, m, w, p=path, b=btn: cls._restore_defaults(path, b))
ui.Spacer()
return btn
@staticmethod
def _create_multi_float_drag_with_labels(model, labels, comp_count, **kwargs) -> None:
RECT_WIDTH = 13
SPACING = 4
with ui.ZStack():
with ui.HStack():
ui.Spacer(width=RECT_WIDTH)
widget_kwargs = {"name": "multivalue", "h_spacing": RECT_WIDTH + SPACING}
widget_kwargs.update(kwargs)
ui.MultiFloatDragField(model, **widget_kwargs)
with ui.HStack():
for i in range(comp_count):
if i != 0:
ui.Spacer(width=SPACING)
label = labels[i]
with ui.ZStack(width=RECT_WIDTH + 1):
ui.Rectangle(name="vector_label", style={"background_color": label[1]})
ui.Label(label[0], name="vector_label", alignment=ui.Alignment.CENTER)
ui.Spacer()
@classmethod
def createColorWidget(cls, model, comp_count=3, additional_widget_kwargs=None) -> ui.HStack:
with ui.HStack(spacing=HORIZONTAL_SPACING) as widget:
widget_kwargs = {"min": 0.0, "max": 1.0}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
# TODO probably need to support "A" if comp_count is 4, but how many assumptions can we make?
with ui.HStack(spacing=4):
cls._create_multi_float_drag_with_labels(
model=model,
labels=[("R", 0xFF5555AA), ("G", 0xFF76A371), ("B", 0xFFA07D4F)],
comp_count=comp_count,
**widget_kwargs,
)
widget = ui.ColorWidget(model, width=30, height=0)
# cls._create_control_state(model)
return widget
@classmethod
def createVecWidget(cls, model, range_min, range_max, comp_count=3, additional_widget_kwargs=None):
widget_kwargs = {"min": range_min, "max": range_max}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
cls._create_multi_float_drag_with_labels(
model=model,
labels=[("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F), ("W", 0xFFFFFFFF)],
comp_count=comp_count,
**widget_kwargs,
)
return model
@staticmethod
def _create_drag_or_slider(drag_widget, slider_widget, **kwargs):
if "min" in kwargs and "max" in kwargs:
range_min = kwargs["min"]
range_max = kwargs["max"]
if range_max - range_min < 100:
return slider_widget(name="value", **kwargs)
else:
if "step" not in kwargs:
kwargs["step"] = max(0.1, (range_max - range_min) / 1000.0)
else:
if "step" not in kwargs:
kwargs["step"] = 0.1
# If range is too big or no range, don't use a slider
widget = drag_widget(name="value", **kwargs)
return widget
@classmethod
def _create_label(cls, attr_name, label_width=150, additional_label_kwargs=None):
label_kwargs = {
"name": "label",
"word_wrap": True,
"width": label_width,
"height": LABEL_HEIGHT,
"alignment": ui.Alignment.LEFT,
}
if additional_label_kwargs:
label_kwargs.update(additional_label_kwargs)
ui.Label(attr_name, **label_kwargs)
ui.Spacer(width=5)
@classmethod
def createBoolWidget(cls, model, additional_widget_kwargs=None):
widget = None
with ui.HStack():
with ui.HStack(style={"margin_width": 0}, width=10):
ui.Spacer()
widget_kwargs = {"font_size": 16, "height": 16, "width": 16, "model": model}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
widget = ui.CheckBox(**widget_kwargs, style={"color": 0xFFDDDDDD, "background_color": 0xFF666666})
ui.Spacer()
return widget
@classmethod
def createFloatWidget(cls, model, range_min, range_max, additional_widget_kwargs=None):
widget_kwargs = {"model": model}
# only set range if range is valid (min < max)
if range_min < range_max:
widget_kwargs["min"] = range_min
widget_kwargs["max"] = range_max
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
widget_kwargs.update(style={"secondary_color": 0xFF444444})
return cls._create_drag_or_slider(ui.FloatDrag, ui.FloatSlider, **widget_kwargs)
@classmethod
def createIntWidget(cls, model, range_min, range_max, additional_widget_kwargs=None):
widget_kwargs = {"model": model} # This passes the model into the widget
# only set range if range is valid (min < max)
if range_min < range_max:
widget_kwargs["min"] = range_min
widget_kwargs["max"] = range_max
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
widget_kwargs.update(style={"secondary_color": 0xFF444444})
return cls._create_drag_or_slider(ui.IntDrag, ui.IntSlider, **widget_kwargs)
| 6,266 | Python | 39.694805 | 114 | 0.555538 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widget_model.py |
__all__ = ["WidgetModel", "WidgetComboValueModel", "WidgetComboNameValueItem", "WidgetComboItemModel"]
from typing import Callable
import omni.ui as ui
class WidgetModel(ui.AbstractValueModel):
"""
Model for widget Properties
"""
def __init__(self, widget: ui.Widget, property: str, dragable=True):
"""
Args:
"""
super().__init__()
self._widget = widget
self._property = property
self.initialValue = None
self._reset_button = None
self._editing = False
# def _on_change(owner, value, event_type) -> None:
# if event_type == carb.settings.ChangeEventType.CHANGED:
# owner._on_dirty()
# if owner._editing == False:
# owner._update_reset_button()
# def begin_edit(self) -> None:
# self._editing = True
# ui.AbstractValueModel.begin_edit(self)
# self.initialValue = self._settings.get(self._path)
# def end_edit(self) -> None:
# ui.AbstractValueModel.end_edit(self)
# omni.kit.commands.execute(
# "ChangeSettingCommand", path=self._path, value=self._settings.get(self._path), prev=self.initialValue
# )
# self._update_reset_button()
# self._editing = False
def get_value_as_string(self) -> str:
return str(self._widget.__getattribute__(self._property))
def get_value_as_float(self) -> float:
return self._widget.__getattribute__(self._property)
def get_value_as_bool(self) -> bool:
return self._widget.__getattribute__(self._property)
def get_value_as_int(self) -> int:
# print("here int ")
return self._widget.__getattribute__(self._property)
def set_value(self, value):
print(type(self._widget.__getattribute__(self._property)))
if type(self._widget.__getattribute__(self._property)) == ui.Length:
print("Is Length")
self._widget.__setattr__(self._property, ui.Pixel(value))
else:
self._widget.__setattr__(self._property, value)
self._value_changed()
def destroy(self):
self._widget = None
self._reset_button = None
class WidgetComboValueModel(ui.AbstractValueModel):
"""
Model to store a pair (label, value of arbitrary type) for use in a ComboBox
"""
def __init__(self, key, value):
"""
Args:
value: the instance of the Style value
"""
ui.AbstractValueModel.__init__(self)
self.key = key
self.value = value
def __repr__(self):
return f'"WidgetComboValueModel name:{self.key} value:{int(self.value)}"'
def get_value_as_string(self) -> str:
"""
this is called to get the label of the combo box item
"""
return self.key
def get_style_value(self) -> int:
"""
we call this to get the value of the combo box item
"""
return int(self.value)
class WidgetComboNameValueItem(ui.AbstractItem):
def __init__(self, key, value):
super().__init__()
self.model = WidgetComboValueModel(key, value)
def __repr__(self):
return f'"StyleComboNameValueItem {self.model}"'
class WidgetComboItemModel(ui.AbstractItemModel):
"""
Model for a combo box - for each setting we have a dictionary of key, values
"""
def __init__(self, widget: ui.Widget, property: str, class_obj: Callable):
super().__init__()
self._widget = widget
self._property = property
self._class = class_obj
self._items = []
self._default_value = self._widget.__getattribute__(property)
default_index = 0
current_index = 0
for key, value in class_obj.__members__.items():
if self._default_value == value:
default_index = current_index
self._items.append(WidgetComboNameValueItem(key, value))
current_index += 1
self._current_index = ui.SimpleIntModel(default_index)
self._current_index.add_value_changed_fn(self._current_index_changed)
def get_current_value(self):
return self._items[self._current_index.as_int].model.get_style_value()
def _current_index_changed(self, model):
self._item_changed(None)
value = self.get_current_value()
self._widget.__setattr__(self._property, self._class(value))
def get_item_children(self, item):
return self._items
def get_item_value_model(self, item, column_id: int):
if item is None:
return self._current_index
return item.model
| 4,648 | Python | 29.993333 | 115 | 0.593589 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/inspector_property_widget.py |
__all__ = ["InspectorPropertyWidget"]
import omni.ui as ui
import carb.events
import omni.kit.app
from omni.ui_query import OmniUIQuery
from .widgets.button import ButtonPropertyFrame
from .widgets.canvas_frame import CanvasPropertyFrame
from .widgets.circle import CirclePropertyFrame
from .widgets.collapsable_frame import CollapsableFramePropertyFrame
from .widgets.combox_box import ComboBoxPropertyFrame
from .widgets.frame import FramePropertyFrame
from .widgets.grid import GridPropertyFrame
from .widgets.image import ImagePropertyFrame
from .widgets.image_with_provider import ImageWithProviderPropertyFrame
from .widgets.label import LabelPropertyFrame
from .widgets.line import LinePropertyFrame
from .widgets.placer import PlacerPropertyFrame
from .widgets.scrolling_frame import ScrollingFramePropertyFrame
from .widgets.slider import SliderPropertyFrame
from .widgets.stack import StackPropertyFrame
from .widgets.string_field import StringFieldPropertyFrame
from .widgets.tree_view import TreeViewPropertyFrame
from .widgets.triangle import TrianglePropertyFrame
from .widgets.widget import WidgetPropertyFrame
class InspectorPropertyWidget:
"""The Stage widget"""
def __init__(self, **kwargs):
self._widget = None
self._main_stack = ui.VStack(
spacing=5,
width=300,
style={
"VStack": {"margin_width": 10},
"CollapsableFrame": {"background_color": 0xFF2A2A2A, "secondary_color": 0xFF2A2A2A},
},
)
self._build_ui()
app = omni.kit.app.get_app()
self._update_sub = app.get_message_bus_event_stream().create_subscription_to_pop(
self.on_selection_changed, name="Inspector Selection Changed"
)
def on_selection_changed(self, event: carb.events.IEvent):
from ..inspector_widget import INSPECTOR_ITEM_SELECTED_ID
if event.type == INSPECTOR_ITEM_SELECTED_ID:
selection = OmniUIQuery.find_widget(event.payload["item_path"])
if selection:
self.set_widget(selection)
def toggle_visibility(self):
self._main_stack.visible = not self._main_stack.visible
def set_widget(self, widget: ui.Widget):
self._widget = widget
self._build_ui()
def _build_ui(self):
self._main_stack.clear()
with self._main_stack:
ui.Spacer(height=0)
ui.Label("Properties", height=0, style={"font_size": 16}, alignment=ui.Alignment.CENTER)
ui.Spacer(height=0)
if not self._widget:
return
if isinstance(self._widget, ui.Label):
LabelPropertyFrame("Label", self._widget)
elif isinstance(self._widget, ui.Stack):
StackPropertyFrame("Stack", self._widget)
elif isinstance(self._widget, ui.Button):
ButtonPropertyFrame("Button", self._widget)
elif isinstance(self._widget, ui.Image):
ImagePropertyFrame("Image", self._widget)
elif isinstance(self._widget, ui.CanvasFrame):
CanvasPropertyFrame("CanvasFrame", self._widget)
elif isinstance(self._widget, ui.AbstractSlider):
SliderPropertyFrame("Slider", self._widget)
elif isinstance(self._widget, ui.Circle):
CirclePropertyFrame("Circle", self._widget)
elif isinstance(self._widget, ui.ComboBox):
ComboBoxPropertyFrame("ComboBox", self._widget)
elif isinstance(self._widget, ui.ScrollingFrame):
ScrollingFramePropertyFrame("ScrollingFrame", self._widget)
FramePropertyFrame("Frame", self._widget)
elif isinstance(self._widget, ui.CollapsableFrame):
CollapsableFramePropertyFrame("CollapsableFrame", self._widget)
FramePropertyFrame("Frame", self._widget)
elif isinstance(self._widget, ui.Frame):
FramePropertyFrame("Frame", self._widget)
elif isinstance(self._widget, ui.Grid):
GridPropertyFrame("Grid", self._widget)
elif isinstance(self._widget, ui.ImageWithProvider):
ImageWithProviderPropertyFrame("ImageWithProvider", self._widget)
elif isinstance(self._widget, ui.Line):
LinePropertyFrame("Line", self._widget)
elif isinstance(self._widget, ui.Placer):
PlacerPropertyFrame("Placer", self._widget)
elif isinstance(self._widget, ui.ScrollingFrame):
ScrollingFramePropertyFrame("ScrollingFrame", self._widget)
elif isinstance(self._widget, ui.StringField):
StringFieldPropertyFrame("StringField", self._widget)
elif isinstance(self._widget, ui.TreeView):
TreeViewPropertyFrame("TreeView", self._widget)
elif isinstance(self._widget, ui.Triangle):
TrianglePropertyFrame("Triangle", self._widget)
WidgetPropertyFrame("Widget", self._widget)
| 5,087 | Python | 41.049586 | 100 | 0.653823 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/base_frame.py |
__all__ = ["WidgetCollectionFrame"]
# from typing import Union, Any
from .create_widget import PropertyType
import omni.ui as ui
from .create_widget import create_property_widget
from .widget_builder import PropertyWidgetBuilder
class WidgetCollectionFrame:
parents = {} # For later deletion of parents
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
self._models = []
self._widget = widget
self._frame_widget = ui.CollapsableFrame(frame_label, height=0, build_fn=self.build_ui)
def destroy(self):
""""""
self._frame_widget.clear()
self._frame_widget = None
def build_ui(self):
with ui.VStack(height=0, spacing=5, style={"VStack": {"margin_width": 10}}):
ui.Spacer(height=5)
self._build_ui()
ui.Spacer(height=5)
def _rebuild(self):
if self._frame_widget:
self._frame_widget.rebuild()
def _add_property(
self,
widget: ui.Widget,
property: str,
property_type: PropertyType,
range_from=0,
range_to=0,
speed=1,
has_reset=True,
tooltip="",
label_width=150,
):
with ui.HStack(skip_draw_when_clipped=True):
PropertyWidgetBuilder._create_label(property, label_width=label_width)
property_widget, model = create_property_widget(
widget, property, property_type, range_from, range_to, speed
)
self._models.append(model)
# if has_reset:
# button = PropertyWidgetBuilder._build_reset_button(path)
# model.set_reset_button(button)
return property_widget, model
# def _add_setting_combo(
# self, name: str, path: str, items: Union[list, dict], callback=None, has_reset=True, tooltip=""
# ):
# with ui.HStack(skip_draw_when_clipped=True):
# PropertyWidgetBuilder._create_label(name, path, tooltip)
# property_widget, model = create_property_widget_combo(widget, items)
# #if has_reset:
# # button = PropertyWidgetBuilder._build_reset_button(path)
# # model.set_reset_button(button)
# return property_widget
def _build_ui(self):
""" virtual function that will be called in the Collapsable frame """
pass
| 2,377 | Python | 29.883116 | 105 | 0.595709 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/button.py |
__all__ = ["ButtonPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class ButtonPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "image_url", PropertyType.STRING)
self._add_property(self._widget, "text", PropertyType.STRING)
self._add_property(self._widget, "image_width", PropertyType.FLOAT)
self._add_property(self._widget, "image_height", PropertyType.FLOAT)
self._add_property(self._widget, "spacing", PropertyType.FLOAT)
| 712 | Python | 29.999999 | 76 | 0.688202 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/canvas_frame.py |
__all__ = ["CanvasPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class CanvasPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "zoom", PropertyType.FLOAT, range_from=0)
self._add_property(self._widget, "pan_x", PropertyType.FLOAT)
self._add_property(self._widget, "pan_y", PropertyType.FLOAT)
self._add_property(self._widget, "draggable", PropertyType.BOOL)
| 636 | Python | 30.849998 | 82 | 0.685535 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/tree_view.py |
__all__ = ["TreeViewPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class TreeViewPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "columns_resizable", PropertyType.BOOL)
self._add_property(self._widget, "header_visible", PropertyType.BOOL)
self._add_property(self._widget, "root_visible", PropertyType.BOOL)
self._add_property(self._widget, "expand_on_branch_click", PropertyType.BOOL)
self._add_property(self._widget, "keep_alive", PropertyType.BOOL)
self._add_property(self._widget, "keep_expanded", PropertyType.BOOL)
self._add_property(self._widget, "drop_between_items", PropertyType.BOOL)
| 897 | Python | 39.81818 | 85 | 0.696767 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/grid.py |
__all__ = ["GridPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class GridPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "columnWidth", PropertyType.FLOAT)
self._add_property(self._widget, "rowHeight", PropertyType.FLOAT)
self._add_property(self._widget, "columnCount", PropertyType.INT, range_from=0)
self._add_property(self._widget, "rowCount", PropertyType.INT, range_from=0)
| 659 | Python | 31.999998 | 87 | 0.693475 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/slider.py |
__all__ = ["SliderPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class SliderPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "min", PropertyType.INT)
self._add_property(self._widget, "max", PropertyType.INT)
| 471 | Python | 26.764704 | 68 | 0.687898 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/frame.py |
__all__ = ["FramePropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class FramePropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "horizontal_clipping", PropertyType.BOOL)
self._add_property(self._widget, "vertical_clipping", PropertyType.BOOL)
self._add_property(self._widget, "separate_window", PropertyType.BOOL)
| 580 | Python | 31.277776 | 82 | 0.701724 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/image.py |
__all__ = ["ImagePropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class ImagePropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "source_url", PropertyType.STRING, label_width=80)
self._add_property(self._widget, "alignment", PropertyType.ENUM, label_width=80)
self._add_property(self._widget, "fill_policy", PropertyType.ENUM, label_width=80)
| 609 | Python | 32.888887 | 91 | 0.697865 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/string_field.py |
__all__ = ["StringFieldPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class StringFieldPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "password_mode", PropertyType.BOOL)
self._add_property(self._widget, "read_only", PropertyType.BOOL)
self._add_property(self._widget, "multiline", PropertyType.BOOL)
| 572 | Python | 30.833332 | 76 | 0.699301 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/collapsable_frame.py |
__all__ = ["CollapsableFramePropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class CollapsableFramePropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "collapsed", PropertyType.BOOL)
self._add_property(self._widget, "title", PropertyType.STRING)
self._add_property(self._widget, "alignment", PropertyType.ENUM)
| 576 | Python | 31.055554 | 72 | 0.704861 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/placer.py |
__all__ = ["PlacerPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class PlacerPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "offset_x", PropertyType.FLOAT)
self._add_property(self._widget, "offset_y", PropertyType.FLOAT)
self._add_property(self._widget, "draggable", PropertyType.BOOL)
self._add_property(self._widget, "drag_axis", PropertyType.ENUM)
self._add_property(self._widget, "stable_size", PropertyType.BOOL)
| 705 | Python | 36.157893 | 74 | 0.689362 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/scrolling_frame.py |
__all__ = ["ScrollingFramePropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class ScrollingFramePropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "scroll_x", PropertyType.FLOAT)
self._add_property(self._widget, "scroll_y", PropertyType.FLOAT)
self._add_property(self._widget, "horizontal_scrollbar_policy", PropertyType.ENUM)
self._add_property(self._widget, "vertical_scrollbar_policy", PropertyType.ENUM)
| 681 | Python | 34.894735 | 90 | 0.707783 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/label.py |
__all__ = ["LabelPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class LabelPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "text", PropertyType.STRING)
self._add_property(self._widget, "alignment", PropertyType.ENUM)
self._add_property(self._widget, "word_wrap", PropertyType.BOOL)
self._add_property(self._widget, "elided_text", PropertyType.BOOL)
| 628 | Python | 32.105261 | 74 | 0.68949 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/circle.py |
__all__ = ["CirclePropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class CirclePropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "radius", PropertyType.FLOAT, range_from=0)
self._add_property(self._widget, "alignment", PropertyType.ENUM)
self._add_property(self._widget, "arc", PropertyType.ENUM)
self._add_property(self._widget, "size_policy", PropertyType.ENUM)
| 640 | Python | 31.049998 | 84 | 0.689062 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/widget.py |
__all__ = ["WidgetPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class WidgetPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "width", PropertyType.FLOAT, 0, 2000)
self._add_property(self._widget, "height", PropertyType.FLOAT, 0, 2000)
self._add_property(self._widget, "tooltip_offset_x", PropertyType.FLOAT, 0, 2000)
self._add_property(self._widget, "tooltip_offset_y", PropertyType.FLOAT, 0, 2000)
ui.Line(height=2, style={"color": 0xFF666666})
self._add_property(self._widget, "name", PropertyType.STRING)
ui.Line(height=2, style={"color": 0xFF666666})
self._add_property(self._widget, "checked", PropertyType.BOOL)
self._add_property(self._widget, "enabled", PropertyType.BOOL)
self._add_property(self._widget, "selected", PropertyType.BOOL)
self._add_property(self._widget, "opaque_for_mouse_events", PropertyType.BOOL)
self._add_property(self._widget, "visible", PropertyType.BOOL)
self._add_property(self._widget, "skip_draw_when_clipped", PropertyType.BOOL)
ui.Spacer(height=10)
ui.Line(height=5, style={"color": 0xFF666666, "border_width": 5})
ui.Label("Read Only", alignment=ui.Alignment.CENTER)
self._add_property(self._widget, "computed_width", PropertyType.FLOAT, 0, 2000)
self._add_property(self._widget, "computed_height", PropertyType.FLOAT, 0, 2000)
ui.Line(height=2, style={"color": 0xFF666666})
self._add_property(self._widget, "computed_content_width", PropertyType.FLOAT, 0, 2000)
self._add_property(self._widget, "computed_content_height", PropertyType.FLOAT, 0, 2000)
ui.Line(height=2, style={"color": 0xFF666666})
self._add_property(self._widget, "screen_position_x", PropertyType.FLOAT, 0, 2000)
self._add_property(self._widget, "screen_position_y", PropertyType.FLOAT, 0, 2000)
| 2,156 | Python | 39.698112 | 96 | 0.667904 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/tests/test_ui.py | import omni.kit.test
import omni.kit.window.inspector.inspector_window
from omni.kit import ui_test
class TestInspectorWindow(omni.kit.test.AsyncTestCase):
@classmethod
def setUpClass(cls):
cls.inspector_window = omni.kit.window.inspector.inspector_window.InspectorWindow()
async def setUp(self):
self.window_name = self.inspector_window._window.title
@classmethod
def tearDownClass(cls) -> None:
cls.inspector_window._window.destroy()
async def test_window_list(self):
'''
Check that the main combox box is doing the right thing
There's a bit of an ordering assumption going on
'''
ui_window = ui_test.find(self.window_name)
widgets = ui_window.find_all("**/WindowListComboBox")
self.assertTrue(len(widgets) == 1)
combo_box = widgets[0].widget
self.assertTrue(isinstance(combo_box, omni.ui.ComboBox))
# Make sure render settings is set
combo_box.model.get_item_value_model(None, 0).set_value(0)
window_name = combo_box.model.get_current_window()
self.assertEqual(window_name, "Render Settings")
# Set to Stage window
combo_box.model.get_item_value_model(None, 0).set_value(1)
window_name = combo_box.model.get_current_window()
self.assertEqual(window_name, "Stage")
await omni.kit.app.get_app().next_update_async()
async def test_tree_expansion(self):
# make sure render settings is the current window
ui_window = ui_test.find(self.window_name)
widgets = ui_window.find_all("**/WindowListComboBox")
combo_box = widgets[0].widget
combo_box.model.get_item_value_model(None, 0).set_value(0)
widgets = ui_window.find_all("**/WidgetInspectorTree")
self.assertTrue(len(widgets) == 1)
tree_items = widgets[0].find_all("**")
self.assertTrue(len(tree_items) == 20, f"actually was {len(tree_items)}")
# Switch to Stage Window
combo_box.model.get_item_value_model(None, 0).set_value(1)
widgets = ui_window.find_all("**/WidgetInspectorTree")
self.assertTrue(len(widgets) == 1)
tree_items = widgets[0].find_all("**")
self.assertTrue(len(tree_items) == 17, f"actually was {len(tree_items)}")
async def test_tree_basic_content(self):
# make sure render settings is the current window
ui_window = ui_test.find(self.window_name)
widgets = ui_window.find_all("**/WindowListComboBox")
combo_box = widgets[0].widget
combo_box.model.get_item_value_model(None, 0).set_value(0)
widgets = ui_window.find_all("**/WidgetInspectorTree")
self.assertTrue(len(widgets) == 1)
tree_items = widgets[0].find_all("**")
labels = [t.widget for t in tree_items if isinstance(t.widget, omni.ui.Label)]
self.assertTrue(len(labels) == 2)
self.assertTrue(labels[0].text == "Frame")
self.assertTrue(labels[1].text == "Style")
async def test_styles(self):
ui_window = ui_test.find(self.window_name)
buttons = ui_window.find_all("**/ToolButton[*]")
# enable style
for button in buttons:
if button.widget.text == "Style":
await button.click()
await ui_test.wait_n_updates(2)
trees = ui_window.find_all("**/WidgetInspectorTree")
self.assertTrue(len(trees) == 1)
tree_items = trees[0].find_all("**")
labels = [t for t in tree_items if isinstance(t.widget, omni.ui.Label)]
for label in labels:
if label.widget.text == "Frame":
await label.click()
await ui_test.wait_n_updates(2)
# check there is colorwidget widgets created
colorwidgets = ui_window.find_all("**/ColorWidget[*]")
self.assertTrue(len(colorwidgets) > 0)
| 3,881 | Python | 36.68932 | 91 | 0.627416 |
omniverse-code/kit/exts/omni.kit.window.inspector/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.6] - 2022-07-05
- add test to increase the test coverage
## [1.0.5] - 2022-05-16
- start adding tests
## [1.0.4] - 2022-01-10
- support for widgets under Treeview (i.e those created by the treeview delegate)
## [1.0.3] - 2021-11-24
### Added
- expand/collapse in tree widget
## [1.0.2] - 2021-11-24
### Changes
- Fix some bugs naming paths
- startup defaults less cluttered..
## [1.0.1] - 2021-11-24
### Changes
- Update to latest omni.ui_query
## [1.0.0] -
### TODO
- Better support for ALL <Category> >> DONE
- Better list of Property for Widget >> DONE
- Contextual Styling List
-
| 702 | Markdown | 19.085714 | 81 | 0.653846 |
omniverse-code/kit/exts/omni.kit.window.inspector/docs/overview.md | # Overview
| 12 | Markdown | 3.333332 | 10 | 0.666667 |
omniverse-code/kit/exts/omni.kit.window.inspector/docs/README.md | # UI Inspector Widget [omni.kit.window.inspector]
| 52 | Markdown | 12.249997 | 49 | 0.75 |
omniverse-code/kit/exts/omni.kit.documentation.builder/scripts/generate_docs_for_sphinx.py | import argparse
import asyncio
import logging
import carb
import omni.kit.app
import omni.kit.documentation.builder
logger = logging.getLogger(__name__)
_app_ready_sub = None
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"ext_id",
help="Extension id (name-version).",
)
parser.add_argument(
"output_path",
help="Path to output generated files to.",
)
options = parser.parse_args()
async def _generate_and_exit(options):
# Skip 2 updates to make sure all extensions loaded and initialized
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
try:
result = omni.kit.documentation.builder.generate_for_sphinx(options.ext_id, options.output_path)
except Exception as e: # pylint: disable=broad-except
carb.log_error(f"Failed to generate docs for sphinx: {e}")
for _ in range(5):
await omni.kit.app.get_app().next_update_async()
returncode = 0 if result else 33
omni.kit.app.get_app().post_quit(returncode)
def on_app_ready(e):
global _app_ready_sub
_app_ready_sub = None
asyncio.ensure_future(_generate_and_exit(options))
app = omni.kit.app.get_app()
if app.is_app_ready():
on_app_ready(None)
else:
global _app_ready_sub
_app_ready_sub = app.get_startup_event_stream().create_subscription_to_pop_by_type(
omni.kit.app.EVENT_APP_READY, on_app_ready, name="omni.kit.documentation.builder generate_docs_for_sphinx"
)
if __name__ == "__main__":
main()
| 1,675 | Python | 26.475409 | 118 | 0.628657 |
omniverse-code/kit/exts/omni.kit.documentation.builder/config/extension.toml | [package]
version = "1.0.9"
authors = ["NVIDIA"]
title = "Omni.UI Documentation Builder"
description="The interactive documentation builder for omni.ui extensions"
readme = "docs/README.md"
category = "Documentation"
keywords = ["ui", "example", "docs", "documentation", "builder"]
changelog="docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
# Moved from https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-widgets
repository = ""
[dependencies]
"omni.kit.window.filepicker" = {}
[documentation]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
menu = "Help/API/omni.kit.documentation.builder"
title = "Omni UI Documentation Builder"
[[python.module]]
name = "omni.kit.documentation.builder"
[[python.scriptFolder]]
path = "scripts"
[[test]]
| 799 | TOML | 22.529411 | 82 | 0.718398 |
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_capture.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["DocumentationBuilderCapture"]
import asyncio
import omni.appwindow
import omni.kit.app
import omni.kit.imgui_renderer
import omni.kit.renderer.bind
import omni.renderer_capture
import omni.ui as ui
class DocumentationBuilderCapture:
r"""
Captures the omni.ui widgets to the image file. Works like this:
with Capture("c:\temp\1.png", 600, 600):
ui.Button("Hello World")
"""
def __init__(self, path: str, width: int, height: int, window_name: str = "Capture Window"):
self._path: str = path
self._dpi = ui.Workspace.get_dpi_scale()
self._width: int = int(width * self._dpi)
self._height: int = int(height * self._dpi)
self._window_name: str = window_name
# Interfaces
self._app_window_factory = omni.appwindow.acquire_app_window_factory_interface()
self._renderer = omni.kit.renderer.bind.acquire_renderer_interface()
self._imgui_renderer = omni.kit.imgui_renderer.acquire_imgui_renderer_interface()
self._renderer_capture = omni.renderer_capture.acquire_renderer_capture_interface()
self._virtual_app_window = None
self._window = None
def __enter__(self):
# Create virtual OS window
self._virtual_app_window = self._app_window_factory.create_window_by_type(omni.appwindow.WindowType.VIRTUAL)
self._virtual_app_window.startup_with_desc(
title=self._window_name,
width=self._width,
height=self._height,
scale_to_monitor=False,
dpi_scale_override=1.0,
)
self._imgui_renderer.attach_app_window(self._virtual_app_window)
# Create omni.ui window
self._window = ui.Window(self._window_name, flags=ui.WINDOW_FLAGS_NO_TITLE_BAR, padding_x=0, padding_y=0)
self._window.move_to_app_window(self._virtual_app_window)
self._window.width = self._width
self._window.height = self._height
# Enter the window frame
self._window.frame.__enter__()
def __exit__(self, exc_type, exc_val, exc_tb):
# Exit the window frame
self._window.frame.__exit__(exc_type, exc_val, exc_tb)
# Capture and detach at the next frame
asyncio.ensure_future(
DocumentationBuilderCapture.__capture_detach(
self._renderer_capture, self._path, self._renderer, self._virtual_app_window, self._window
)
)
@staticmethod
async def __capture_detach(renderer_capture, path, renderer, iappwindow, window):
# The next frame
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
# Capture
renderer_capture.capture_next_frame_texture(path, renderer.get_framebuffer_texture(iappwindow), iappwindow)
await omni.kit.app.get_app().next_update_async()
# Detach
renderer.detach_app_window(iappwindow)
| 3,392 | Python | 36.7 | 116 | 0.659788 |
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_window.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["DocumentationBuilderWindow"]
import weakref
import carb
import omni.ui as ui
from omni.kit.widget.filebrowser import FileBrowserItem
from omni.kit.window.filepicker import FilePickerDialog
from .documentation_capture import DocumentationBuilderCapture
from .documentation_catalog import DocumentationBuilderCatalog
from .documentation_md import DocumentationBuilderMd
from .documentation_page import DocumentationBuilderPage
from .documentation_style import get_style
class DocumentationBuilderWindow(ui.Window):
"""The window with the documentation"""
def __init__(self, title: str, **kwargs):
"""
### Arguments
`title: str`
The title of the window.
`filenames: List[str]`
The list of .md files to process.
`show_catalog: bool`
Show catalog pane (default True)
"""
self._pages = []
self._catalog = None
self.__content_frame = None
self.__content_page = None
self.__source_filenames = kwargs.pop("filenames", [])
self._show_catalog = kwargs.pop("show_catalog", True)
if "width" not in kwargs:
kwargs["width"] = 1200
if "height" not in kwargs:
kwargs["height"] = 720
if "flags" not in kwargs:
kwargs["flags"] = ui.WINDOW_FLAGS_NO_SCROLL_WITH_MOUSE | ui.WINDOW_FLAGS_NO_SCROLLBAR
super().__init__(title, **kwargs)
self._set_style()
self.frame.set_build_fn(self.__build_window)
self.__pick_folder_dialog = None
def get_page_names(self):
"""Names of all the pages to use in `set_page`"""
return [p.name for p in self._pages]
def set_page(self, name: str = None, scroll_to: str = None):
"""
Set current page
### Arguments
`name: str`
The name of the page to switch to. If None, it will set the
first page.
`scroll_to: str`
The name of the section to scroll to.
"""
if self.__content_page and self.__content_page.name == name:
self.__content_page.scroll_to(scroll_to)
return
if name is None:
page = self._pages[0]
else:
page = next((p for p in self._pages if p.name == name), None)
if page:
if self.__content_page:
self.__content_page.destroy()
with self.__content_frame:
self.__content_page = DocumentationBuilderPage(page, scroll_to)
def generate_for_sphinx(self, path: str):
"""
Produce the set of files and screenshots readable by Sphinx.
### Arguments
`path: str`
The path to produce the files.
"""
for page in self._pages:
for code_block in page.code_blocks:
image_file = f"{path}/{code_block['name']}.png"
height = int(code_block["height"] or 200)
with DocumentationBuilderCapture(image_file, 800, height):
with ui.ZStack():
# Background
ui.Rectangle(name="code_background")
# The code
with ui.VStack():
# flake8: noqa: PLW0212
self.__content_page._execute_code(code_block["code"])
carb.log_info(f"[omni.docs] Generated image: '{image_file}'")
md_file = f"{path}/{page.name}.md"
with open(md_file, "w", encoding="utf-8") as f:
f.write(page.source)
carb.log_info(f"[omni.docs] Generated md file: '{md_file}'")
def destroy(self):
if self.__pick_folder_dialog:
self.__pick_folder_dialog.destroy()
self.__pick_folder_dialog = None
if self._catalog:
self._catalog.destroy()
self._catalog = None
for page in self._pages:
page.destroy()
self._pages = []
if self.__content_page:
self.__content_page.destroy()
self.__content_page = None
self.__content_frame = None
super().destroy()
@staticmethod
def get_style():
"""
Deprecated: use omni.kit.documentation.builder.get_style()
"""
return get_style()
def _set_style(self):
self.frame.set_style(get_style())
def __build_window(self):
"""Called to build the widgets of the window"""
self.__reload_pages()
def __on_export(self):
"""Open Pick Folder dialog to add compounds"""
if self.__pick_folder_dialog:
self.__pick_folder_dialog.destroy()
self.__pick_folder_dialog = FilePickerDialog(
"Pick Output Folder",
apply_button_label="Use This Folder",
click_apply_handler=self.__on_apply_folder,
item_filter_options=["All Folders (*)"],
item_filter_fn=self.__on_filter_folder,
)
def __on_apply_folder(self, filename: str, root_path: str):
"""Called when the user press "Use This Folder" in the pick folder dialog"""
self.__pick_folder_dialog.hide()
self.generate_for_sphinx(root_path)
@staticmethod
def __on_filter_folder(item: FileBrowserItem) -> bool:
"""Used by pick folder dialog to hide all the files"""
return item.is_folder
def __reload_pages(self):
"""Called to reload all the pages"""
# Properly destroy all the past pages
for page in self._pages:
page.destroy()
self._pages = []
# Reload the pages at the drawing time
for page_source in self.__source_filenames:
if page_source.endswith(".md"):
self._pages.append(DocumentationBuilderMd(page_source))
def keep_page_name(page, catalog_data):
"""Puts the page name to the catalog data"""
for c in catalog_data:
c["page"] = page
keep_page_name(page, c["children"])
catalog_data = []
for page in self._pages:
catalog = page.catalog
keep_page_name(page.name, catalog)
catalog_data += catalog
# The layout
with ui.HStack():
if self._show_catalog:
self._catalog = DocumentationBuilderCatalog(
catalog_data,
weakref.ref(self),
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
width=300,
settings_menu=[{"name": "Export Markdown", "clicked_fn": self.__on_export}],
)
with ui.ZStack():
ui.Rectangle(name="content_background")
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style={"ScrollingFrame": {"background_color": 0x0}},
):
self.__content_frame = ui.Frame(height=1)
self.set_page()
| 7,676 | Python | 33.12 | 97 | 0.563054 |
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/__init__.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = [
"create_docs_window",
"DocumentationBuilder",
"DocumentationBuilderCatalog",
"DocumentationBuilderMd",
"DocumentationBuilderPage",
"DocumentationBuilderWindow",
"generate_for_sphinx",
"get_style",
]
from .documentation_catalog import DocumentationBuilderCatalog
from .documentation_extension import DocumentationBuilder, create_docs_window
from .documentation_generate import generate_for_sphinx
from .documentation_md import DocumentationBuilderMd
from .documentation_page import DocumentationBuilderPage
from .documentation_style import get_style
from .documentation_window import DocumentationBuilderWindow
| 1,089 | Python | 37.92857 | 77 | 0.803489 |
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_catalog.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["DocumentationBuilderCatalog"]
import asyncio
import weakref
from typing import Any, Dict, List
import omni.kit.app
import omni.ui as ui
class _CatalogModelItem(ui.AbstractItem):
def __init__(self, catalog_data):
super().__init__()
self.__catalog_data = catalog_data
self.name_model = ui.SimpleStringModel(catalog_data["name"])
self.__children = None
self.widget = None
def destroy(self):
for c in self.__children or []:
c.destroy()
self.__children = None
self.__catalog_data = None
self.widget = None
@property
def page_name(self):
return self.__catalog_data["page"]
@property
def children(self):
if self.__children is None:
# Lazy initialization
self.__children = [_CatalogModelItem(c) for c in self.__catalog_data.get("children", [])]
return self.__children
class _CatalogModel(ui.AbstractItemModel):
def __init__(self, catalog_data):
super().__init__()
self.__root = _CatalogModelItem({"name": "Root", "children": catalog_data})
def destroy(self):
self.__root.destroy()
self.__root = None
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is None:
return self.__root.children
return item.children
def get_item_value_model_count(self, item):
"""The number of columns"""
return 1
def get_item_value_model(self, item, column_id):
"""
Return value model.
"""
return item.name_model
class _CatalogDelegate(ui.AbstractItemDelegate):
def destroy(self):
pass
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
name = f"tree{level+1}"
with ui.ZStack(width=(level + 1) * 20):
ui.Rectangle(height=28, name=name)
if level > 0:
with ui.VStack():
ui.Spacer()
with ui.HStack(height=10):
ui.Spacer()
if model.can_item_have_children(item):
image = "minus" if expanded else "plus"
ui.Image(name=image, width=10, height=10)
ui.Spacer()
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per column per item"""
name = f"tree{level}"
label = model.get_item_value_model(item, column_id).as_string
if level == 1:
label = label.upper()
with ui.ZStack():
ui.Rectangle(height=28, name=name)
with ui.VStack():
item.widget = ui.Label(label, name=name, style_type_name_override="Text")
class DocumentationBuilderCatalog:
"""The left panel"""
def __init__(self, catalog_data, parent: weakref, **kwargs):
"""
`settings_menu: List[Dict[str, Any]]`
List of items. [{"name": "Export", "clicked_fn": on_export}]
"""
width = kwargs.get("width", 200)
self.__settings_menu: List[Dict[str, Any]] = kwargs.pop("settings_menu", None)
self._model = _CatalogModel(catalog_data)
self._delegate = _CatalogDelegate()
self.__parent = parent
with ui.ScrollingFrame(**kwargs):
with ui.VStack(height=0):
with ui.ZStack():
ui.Image(height=width, name="main_logo")
if self.__settings_menu:
with ui.Frame(height=16, width=16, mouse_hovered_fn=self._on_settings_hovered):
self.__settings_image = ui.Image(
name="settings", visible=False, mouse_pressed_fn=self._on_settings
)
tree_view = ui.TreeView(
self._model,
name="catalog",
delegate=self._delegate,
root_visible=False,
header_visible=False,
selection_changed_fn=self.__selection_changed,
)
# Generate the TreeView children
ui.Inspector.get_children(tree_view)
# Expand the first level
for i in self._model.get_item_children(None):
tree_view.set_expanded(i, True, False)
self.__stop_event = asyncio.Event()
self._menu = None
def destroy(self):
self.__settings_menu = []
self.__stop_event.set()
self.__settings_image = None
self._model.destroy()
self._model = None
self._delegate.destroy()
self._delegate = None
self._menu = None
async def _show_settings(self, delay, event: asyncio.Event):
for _i in range(delay):
await omni.kit.app.get_app().next_update_async()
if event.is_set():
return
self.__settings_image.visible = True
def _on_settings_hovered(self, hovered):
self.__stop_event.set()
self.__settings_image.visible = False
if hovered:
self.__stop_event = asyncio.Event()
asyncio.ensure_future(self._show_settings(100, self.__stop_event))
def _on_settings(self, x, y, button, mod):
self._menu = ui.Menu("Scene Docs Settings")
with self._menu:
for item in self.__settings_menu:
ui.MenuItem(item["name"], triggered_fn=item["clicked_fn"])
self._menu.show()
def __selection_changed(self, selection):
if not selection:
return
self.__parent().set_page(selection[0].page_name, selection[0].name_model.as_string)
| 6,230 | Python | 32.681081 | 103 | 0.564687 |
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_md.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["DocumentationBuilderMd"]
import re
from enum import Enum, auto
from pathlib import Path
from typing import Any, Dict, List, NamedTuple, Tuple, Union
import omni.client as client
H1_CHECK = re.compile(r"# .*")
H2_CHECK = re.compile(r"## .*")
H3_CHECK = re.compile(r"### .*")
PARAGRAPH_CHECK = re.compile(r"[a-zA-Z0-9].*")
LIST_CHECK = re.compile(r"^[-+] [a-zA-Z0-9].*$")
CODE_CHECK = re.compile(r"```.*")
IMAGE_CHECK = re.compile('!\\[(?P<alt>[^\\]]*)\\]\\((?P<url>.*?)(?=\\"|\\))(?P<title>\\".*\\")?\\)')
LINK_CHECK = re.compile(r"\[(.*)\]\((.*)\)")
LINK_IN_LIST = re.compile(r"^[-+] \[(.*)\]\((.*)\)")
TABLE_CHECK = re.compile(r"^(?:\s*\|.+)+\|\s*$")
class _BlockType(Enum):
H1 = auto()
H2 = auto()
H3 = auto()
PARAGRAPH = auto()
LIST = auto()
CODE = auto()
IMAGE = auto()
LINK = auto()
TABLE = auto()
LINK_IN_LIST = auto()
class _Block(NamedTuple):
block_type: _BlockType
text: Union[str, Tuple[str]]
source: str
metadata: Dict[str, Any]
class DocumentationBuilderMd:
"""
The cache for .md file.
It contains parsed data, catalog, links, etc...
"""
def __init__(self, filename: str):
"""
### Arguments
`filename : str`
Path to .md file
"""
self.__filename = filename
self.__blocks: List[_Block] = []
result, _, content = client.read_file(f"{filename}")
if result != client.Result.OK:
content = ""
else:
content = memoryview(content).tobytes().decode("utf-8")
self._process_lines(content.splitlines())
def destroy(self):
pass
@property
def blocks(self):
return self.__blocks
@property
def catalog(self):
"""
Return the document outline in the following format:
{"name": "h1", "children": []}
"""
result = []
blocks = [b for b in self.__blocks if b.block_type in [_BlockType.H1, _BlockType.H2, _BlockType.H3]]
if blocks:
self._get_catalog_recursive(blocks, result, blocks[0].block_type.value)
return result
@property
def source(self) -> str:
content = []
code_id = 0
page_name = self.name
for block in self.__blocks:
if block.block_type == _BlockType.CODE:
content.append(self._source_code(block, page_name, code_id))
code_id += 1
else:
content.append(block.source)
return "\n\n".join(content) + "\n"
@property
def code_blocks(self) -> List[Dict[str, str]]:
page_name = self.name
blocks = [b for b in self.__blocks if b.block_type == _BlockType.CODE]
return [
{"name": f"{page_name}_{i}", "code": block.text, "height": block.metadata["height"]}
for i, block in enumerate(blocks)
if block.metadata.get("code_type", None) == "execute"
]
@property
def image_blocks(self) -> List[Dict[str, str]]:
return [
{"path": block.text, "alt": block.metadata["alt"], "title": block.metadata["title"]}
for block in self.__blocks
if block.block_type == _BlockType.IMAGE
]
@property
def name(self):
first_header = next(
(b for b in self.__blocks if b.block_type in [_BlockType.H1, _BlockType.H2, _BlockType.H3]), None
)
return first_header.text if first_header else None
def _get_catalog_recursive(self, blocks: List[_Block], children: List[Dict], level: int):
while blocks:
top = blocks[0]
top_level = top.block_type.value
if top_level == level:
children.append({"name": top.text, "children": []})
blocks.pop(0)
elif top_level > level:
self._get_catalog_recursive(blocks, children[-1]["children"], top_level)
else: # top_level < level
return
def _add_block(self, block_type, text, source, **kwargs):
self.__blocks.append(_Block(block_type, text, source, kwargs))
def _process_lines(self, content):
# Remove empty lines
while True:
while content and not content[0].strip():
content.pop(0)
if not content:
break
if H1_CHECK.match(content[0]):
self._process_h1(content)
elif H2_CHECK.match(content[0]):
self._process_h2(content)
elif H3_CHECK.match(content[0]):
self._process_h3(content)
elif CODE_CHECK.match(content[0]):
self._process_code(content)
elif IMAGE_CHECK.match(content[0]):
self._process_image(content)
elif LINK_CHECK.match(content[0]):
self._process_link(content)
elif LINK_IN_LIST.match(content[0]):
self._process_link_in_list(content)
elif LIST_CHECK.match(content[0]):
self._process_list(content)
elif TABLE_CHECK.match(content[0]):
self._process_table(content)
else:
self._process_paragraph(content)
def _process_h1(self, content):
text = content.pop(0)
self._add_block(_BlockType.H1, text[2:], text)
def _process_h2(self, content):
text = content.pop(0)
self._add_block(_BlockType.H2, text[3:], text)
def _process_h3(self, content):
text = content.pop(0)
self._add_block(_BlockType.H3, text[4:], text)
def _process_list(self, content: List[str]):
text_lines = []
while True:
current_line = content.pop(0)
text_lines.append(current_line.strip())
if not content or not LIST_CHECK.match(content[0]):
# The next line is not a paragraph.
break
self._add_block(_BlockType.LIST, tuple(text_lines), "\n".join(text_lines))
def _process_table(self, content: List[str]):
text_lines = []
while True:
current_line = content.pop(0)
text_lines.append(current_line.strip())
if not content or not TABLE_CHECK.match(content[0]):
# The next line is not a paragraph.
break
self._add_block(_BlockType.TABLE, tuple(text_lines), "\n".join(text_lines))
def _process_link(self, content):
text = content.pop(0)
self._add_block(_BlockType.LINK, text, text)
def _process_link_in_list(self, content: List[str]):
text_lines = []
while True:
current_line = content.pop(0)
text_lines.append(current_line.strip())
if not content or not LINK_CHECK.match(content[0]):
# The next line is not a link in a list.
break
self._add_block(_BlockType.LINK_IN_LIST, tuple(text_lines), "\n".join(text_lines))
def _process_paragraph(self, content: List[str]):
text_lines = []
while True:
current_line = content.pop(0)
text_lines.append(current_line.strip())
if current_line.endswith(" "):
# To create a line break, end a line with two or more spaces.
break
if not content or not PARAGRAPH_CHECK.match(content[0]):
# The next line is not a paragraph.
break
self._add_block(_BlockType.PARAGRAPH, " ".join(text_lines), "\n".join(text_lines))
def _process_code(self, content):
source = []
text = content.pop(0)
source.append(text)
code_type = text[3:].strip().split()
# Extract height
if code_type and len(code_type) > 1:
height = code_type[1]
else:
height = None
if code_type:
code_type = code_type[0]
else:
code_type = ""
code_lines = []
while content and not CODE_CHECK.match(content[0]):
text = content.pop(0)
source.append(text)
code_lines.append(text)
source.append(content.pop(0))
self._add_block(_BlockType.CODE, "\n".join(code_lines), "\n".join(source), code_type=code_type, height=height)
def _process_image(self, content: List[str]):
text = content.pop(0)
parts = IMAGE_CHECK.match(text.strip()).groupdict()
path = Path(self.__filename).parent.joinpath(parts["url"])
self._add_block(_BlockType.IMAGE, f"{path}", text, alt=parts["alt"], title=parts["title"])
@staticmethod
def get_clean_code(block):
# Remove double-comments
clean = []
skip = False
for line in block.text.splitlines():
if line.lstrip().startswith("##"):
skip = not skip
continue
if skip:
continue
if not clean and not line.strip():
continue
clean.append(line)
return "\n".join(clean)
def _source_code(self, block, page_name, code_id):
result = []
code_type = block.metadata.get("code_type", "")
if code_type == "execute":
image_name = f"{page_name}_{code_id}.png"
result.append(f"\n")
code_type = "python"
elif code_type == "execute-manual":
code_type = "python"
result.append(f"```{code_type}")
result.append(self.get_clean_code(block))
result.append("```")
return "\n".join(result)
| 10,066 | Python | 30.857595 | 118 | 0.548281 |
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_generate.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["generate_for_sphinx"]
import shutil
import traceback
from pathlib import Path
import carb
import omni.kit.app
import omni.ui as ui
from .documentation_capture import DocumentationBuilderCapture
from .documentation_md import DocumentationBuilderMd
from .documentation_style import get_style
PRINT_GENERATION_STATUS = True # Can be made into setting if needed
def _print(message):
if PRINT_GENERATION_STATUS:
print(message)
else:
carb.log_info(message)
def generate_for_sphinx(extension_id: str, path: str) -> bool:
"""
Produce the set of files and screenshots readable by Sphinx.
### Arguments
`extension_id: str`
The extension to generate documentation files
`path: str`
The path to produce the files.
### Return
`True` if generation succeded.
"""
_print(f"Generating for sphinx. Ext: {extension_id}. Path: {path}")
out_path = Path(path)
if not out_path.is_dir():
carb.log_error(f"{path} is not a directory")
return False
ext_info = omni.kit.app.get_app().get_extension_manager().get_extension_dict(extension_id)
if ext_info is None:
carb.log_error(f"Extension id {extension_id} not found")
return False
if not ext_info.get("state", {}).get("enabled", False):
carb.log_error(f"Extension id {extension_id} is not enabled")
return False
ext_path = Path(ext_info.get("path", ""))
pages = ext_info.get("documentation", {}).get("pages", [])
if len(pages) == 0:
carb.log_error(f"Extension id {extension_id} has no pages set in [documentation] section of config.")
return False
for page in pages:
_print(f"Processing page: '{page}'")
if not page.endswith(".md"):
_print(f"Not .md, skipping: '{page}'")
continue
page_path = Path(ext_path / page)
md = DocumentationBuilderMd(str(page_path))
if md.name is None:
_print(f"md is None, skipping: '{page}'")
continue
for code_block in md.code_blocks:
image_file = out_path / f"{code_block['name']}.png"
height = int(code_block["height"] or 200)
with DocumentationBuilderCapture(str(image_file), 800, height):
stack = ui.ZStack()
stack.set_style(get_style())
with stack:
# Background
ui.Rectangle(name="code_background")
# The code
with ui.VStack():
try:
_execute_code(code_block["code"])
except Exception as e:
tb = traceback.format_exception(Exception, e, e.__traceback__)
ui.Label(
"".join(tb), name="code", style_type_name_override="Text", skip_draw_when_clipped=True
)
_print(f"Generated image: '{image_file}'")
for image_block in md.image_blocks:
image_file = Path(image_block["path"])
image_out = out_path / image_file.relative_to(page_path.parent)
image_out.parent.mkdir(parents=True, exist_ok=True)
try:
shutil.copyfile(image_file, image_out)
except shutil.SameFileError:
pass
_print(f"Copied image: '{image_out}'")
md_file = out_path / f"{page_path.stem}.md"
with open(md_file, "w", encoding="utf-8") as f:
f.write(md.source)
_print(f"Generated md file: '{md_file}'")
return True
def _execute_code(code: str):
# Wrap the code in a class to provide scoping
indented = "\n".join([" " + line for line in code.splitlines()])
source = f"class Execution:\n def __init__(self):\n{indented}"
locals_from_execution = {}
# flake8: noqa: PLW0122
exec(source, None, locals_from_execution)
locals_from_execution["Execution"]()
| 4,473 | Python | 33.953125 | 118 | 0.594232 |
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_extension.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import os.path
import typing
from functools import partial
import omni.ext
import omni.kit.app
import omni.kit.ui
from .documentation_window import DocumentationBuilderWindow
class DocumentationBuilder(omni.ext.IExt):
"""
Extension to create a documentation window for any extension which has
markdown pages defined in its extension.toml.
Such pages can have inline omni.ui code blocks which are executed.
For example,
[documentation]
pages = ["docs/Overview.md"]
menu = "Help/API/omni.kit.documentation.builder"
title = "Omni UI Documentation Builder"
"""
def __init__(self):
super().__init__()
# cache docs and window by extensions id
self._doc_info: typing.Dict[str, _DocInfo] = {}
self._editor_menu = None
self._extension_enabled_hook = None
self._extension_disabled_hook = None
def on_startup(self, ext_id: str):
self._editor_menu = omni.kit.ui.get_editor_menu()
manager = omni.kit.app.get_app().get_extension_manager()
# add menus for any extensions with docs that are already enabled
all_exts = manager.get_extensions()
for ext in all_exts:
if ext.get("enabled", False):
self._add_docs_menu(ext.get("id"))
# hook into extension enable/disable events if extension specifies "documentation" config key
hooks = manager.get_hooks()
self._extension_enabled_hook = hooks.create_extension_state_change_hook(
self.on_after_extension_enabled,
omni.ext.ExtensionStateChangeType.AFTER_EXTENSION_ENABLE,
ext_dict_path="documentation",
hook_name="omni.kit.documentation.builder",
)
self._extension_disabled_hook = hooks.create_extension_state_change_hook(
self.on_before_extension_disabled,
omni.ext.ExtensionStateChangeType.BEFORE_EXTENSION_DISABLE,
ext_dict_path="documentation",
hook_name="omni.kit.documentation.builder",
)
def on_shutdown(self):
self._extension_enabled_hook = None
self._extension_disabled_hook = None
for ext_id in list(self._doc_info.keys()):
self._destroy_docs_window(ext_id)
self._editor_menu = None
def on_after_extension_enabled(self, ext_id: str, *_):
self._add_docs_menu(ext_id)
def on_before_extension_disabled(self, ext_id: str, *_):
self._destroy_docs_window(ext_id)
def _add_docs_menu(self, ext_id: str):
doc_info = _get_doc_info(ext_id)
if doc_info and doc_info.menu_path and self._editor_menu:
doc_info.menu = self._editor_menu.add_item(doc_info.menu_path, partial(self._show_docs_window, ext_id))
self._doc_info[ext_id] = doc_info
def _show_docs_window(self, ext_id: str, *_):
window = self._doc_info[ext_id].window
if not window:
window = _create_docs_window(ext_id)
self._doc_info[ext_id].window = window
window.visible = True
def _destroy_docs_window(self, ext_id: str):
if ext_id in self._doc_info:
doc_info = self._doc_info.pop(ext_id)
if doc_info.window:
doc_info.window.destroy()
def create_docs_window(ext_name: str):
"""
Creates a DocumentationBuilderWindow for ext_name
Returns the window, or None if no such extension is enabled and has documentation
"""
# fetch by name
ext_versions = omni.kit.app.get_app().get_extension_manager().fetch_extension_versions(ext_name)
# use latest version that is enabled
for ver in ext_versions:
if ver.get("enabled", False):
return _create_docs_window(ver.get("id", ""))
return None
def _create_docs_window(ext_id: str):
"""
Creates a DocumentationBuilderWindow for ext_id
Returns the window, or None if ext_id has no documentation
"""
doc_info = _get_doc_info(ext_id)
if doc_info:
window = DocumentationBuilderWindow(doc_info.title, filenames=doc_info.pages)
return window
return None
class _DocInfo:
def __init__(self):
self.pages = []
self.menu_path = ""
self.title = ""
self.window = None
self.menu = None
def _get_doc_info(ext_id: str) -> _DocInfo:
"""
Returns extension documentation metadata if it exists.
Returns None if exension has no documentation pages.
"""
ext_info = omni.kit.app.get_app().get_extension_manager().get_extension_dict(ext_id)
if ext_info:
ext_path = ext_info.get("path", "")
doc_dict = ext_info.get("documentation", {})
doc_info = _DocInfo()
doc_info.pages = doc_dict.get("pages", [])
doc_info.menu_path = doc_dict.get("menu", "Help/API/" + ext_id)
doc_info.title = doc_dict.get("title", ext_id)
filenames = []
for page in doc_info.pages:
filenames.append(page if os.path.isabs(page) else os.path.join(ext_path, page))
if filenames:
doc_info.pages = filenames
return doc_info
return None
| 5,549 | Python | 34.806451 | 115 | 0.640115 |
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_page.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["DocumentationBuilderPage"]
import re
import subprocess
import sys
import traceback
import weakref
import webbrowser
from functools import partial
from typing import Any, Dict, List, Optional
import omni.ui as ui
from PIL import Image
from .documentation_md import LINK_CHECK, DocumentationBuilderMd, _Block, _BlockType
class DocumentationBuilderPage:
"""
Widget that draws .md page with the cache.
"""
def __init__(self, md: DocumentationBuilderMd, scroll_to: Optional[str] = None):
"""
### Arguments
`md : DocumentationBuilderMd`
MD cache object
`scroll_to : Optional[str]`
The name of the section to scroll to
"""
self.__md = md
self.__scroll_to = scroll_to
self.__images: List[ui.Image] = []
self.__code_stacks: List[ui.ZStack] = []
self.__code_locals: Dict[str, Any] = {}
self._copy_context_menu = None
self.__bookmarks: Dict[str, ui.Widget] = {}
self._dont_scale_images = False
ui.Frame(build_fn=self.__build)
def destroy(self):
self.__bookmarks: Dict[str, ui.Widget] = {}
if self._copy_context_menu:
self._copy_context_menu.destroy()
self._copy_context_menu = None
self.__code_locals = {}
for stack in self.__code_stacks:
stack.destroy()
self.__code_stacks = []
for image in self.__images:
image.destroy()
self.__images = []
@property
def name(self):
"""The name of the page"""
return self.__md.name
def scroll_to(self, where: str):
"""Scroll to the given section"""
widget = self.__bookmarks.get(where, None)
if widget:
widget.scroll_here()
def _execute_code(self, code: str):
indented = "\n".join([" " + line for line in code.splitlines()])
source = f"class Execution:\n def __init__(self):\n{indented}"
locals_from_execution = {}
# flake8: noqa: PLW0122
exec(source, None, locals_from_execution)
self.__code_locals[code] = locals_from_execution["Execution"]()
def __build(self):
self.__bookmarks: Dict[str, ui.Widget] = {}
with ui.HStack():
ui.Spacer(width=50)
with ui.VStack(height=0):
ui.Spacer(height=50)
for block in self.__md.blocks:
# Build sections one by one
# Space between sections
space = ui.Spacer(height=10)
self.__bookmarks[block.text] = space
if block.text == self.__scroll_to:
# Scroll to this section if necessary
space.scroll_here()
if block.block_type == _BlockType.H1:
self._build_h1(block)
elif block.block_type == _BlockType.H2:
self._build_h2(block)
elif block.block_type == _BlockType.H3:
self._build_h3(block)
elif block.block_type == _BlockType.PARAGRAPH:
self._build_paragraph(block)
elif block.block_type == _BlockType.LIST:
self._build_list(block)
elif block.block_type == _BlockType.TABLE:
self._build_table(block)
elif block.block_type == _BlockType.LINK:
self._build_link(block)
elif block.block_type == _BlockType.CODE:
self._build_code(block)
elif block.block_type == _BlockType.IMAGE:
self._build_image(block)
elif block.block_type == _BlockType.LINK_IN_LIST:
self._build_link_in_list(block)
ui.Spacer(height=50)
ui.Spacer(width=50)
def _build_h1(self, block: _Block):
with ui.ZStack():
ui.Rectangle(name="h1")
ui.Label(block.text, name="h1", style_type_name_override="Text")
def _build_h2(self, block: _Block):
with ui.VStack():
ui.Line(name="h2")
ui.Label(block.text, name="h2", style_type_name_override="Text")
ui.Line(name="h2")
def _build_h3(self, block: _Block):
with ui.VStack(height=0):
ui.Line(name="h3")
ui.Label(block.text, name="h3", style_type_name_override="Text")
ui.Line(name="h3")
def _build_paragraph(self, block: _Block):
ui.Label(block.text, name="paragraph", word_wrap=True, skip_draw_when_clipped=True)
def _build_list(self, block: _Block):
with ui.VStack(spacing=-5):
for list_entry in block.text:
list_entry = list_entry.lstrip("+")
list_entry = list_entry.lstrip("-")
with ui.HStack(spacing=0):
ui.Circle(
width=10, size_policy=ui.CircleSizePolicy.FIXED, alignment=ui.Alignment.LEFT_CENTER, radius=3
)
ui.Label(
list_entry,
alignment=ui.Alignment.LEFT_TOP,
name="paragraph",
word_wrap=True,
skip_draw_when_clipped=True,
)
# ui.Spacer(width=5)
def _build_link_in_list(self, block: _Block):
with ui.VStack(spacing=-5):
for list_entry in block.text:
list_entry = list_entry.lstrip("+")
list_entry = list_entry.lstrip("-")
list_entry = list_entry.lstrip()
with ui.HStack(spacing=0):
ui.Circle(
width=10, size_policy=ui.CircleSizePolicy.FIXED, alignment=ui.Alignment.LEFT_CENTER, radius=3
)
reg = re.match(LINK_CHECK, list_entry)
if reg and len(reg.groups()) == 2:
self._build_link_impl(reg.group(1), reg.group(2))
def _build_link(self, block: _Block):
text = block.text
reg = re.match(LINK_CHECK, text)
label = ""
url = ""
if reg and len(reg.groups()) == 2:
label = reg.group(1)
url = reg.group(2)
self._build_link_impl(label, url)
def _build_link_impl(self, label, url):
def _on_clicked(a, b, c, d, url):
try:
webbrowser.open(url)
except OSError:
print("Please open a browser on: " + url)
with ui.HStack():
spacer = ui.Spacer(width=5)
label = ui.Label(
label,
style_type_name_override="url_link",
name="paragraph",
word_wrap=True,
skip_draw_when_clipped=True,
tooltip=url,
)
label.set_mouse_pressed_fn(lambda a, b, c, d, u=url: _on_clicked(a, b, c, d, u))
def _build_table(self, block: _Block):
cells = []
num_columns = 0
for line in block.text:
cell_text_list = line.split("|")
cell_text_list = [c.strip() for c in cell_text_list]
cell_text_list = [c for c in cell_text_list if c]
num_columns = max(num_columns, len(cell_text_list))
cells.append(cell_text_list)
# Assume 2nd row is separators "|------|---|"
del cells[1]
frame_pixel_width = 800
grid_column_width = frame_pixel_width / num_columns
frame_pixel_height = len(cells) * 20
with ui.ScrollingFrame(
width=frame_pixel_width,
height=frame_pixel_height,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
):
with ui.VGrid(column_width=grid_column_width, row_height=20):
for i in range(len(cells)):
for j in range(num_columns):
with ui.ZStack():
bg_color = 0xFFCCCCCC if i == 0 else 0xFFFFFFF
ui.Rectangle(
style={
"border_color": 0xFF000000,
"background_color": bg_color,
"border_width": 1,
"margin": 0,
}
)
cell_val = cells[i][j]
if len(cell_val) > 66:
cell_val = cell_val[:65] + "..."
ui.Label(f"{cell_val}", style_type_name_override="table_label")
def _build_code(self, block: _Block):
def label_size_changed(label: ui.Label, short_frame: ui.Frame, overlay: ui.Frame):
max_height = ui.Pixel(200)
if label.computed_height > max_height.value:
short_frame.height = max_height
short_frame.vertical_clipping = True
with overlay:
with ui.VStack():
ui.Spacer()
with ui.ZStack():
ui.Rectangle(style_type_name_override="TextOverlay")
ui.InvisibleButton(clicked_fn=partial(remove_overlay, label, short_frame, overlay))
def remove_overlay(label: ui.Label, short_frame: ui.Frame, overlay: ui.Frame):
short_frame.height = ui.Pixel(label.computed_height)
with overlay:
ui.Spacer()
code_type = block.metadata.get("code_type", None)
is_execute_manual = code_type == "execute-manual"
is_execute = code_type == "execute"
if is_execute:
with ui.Frame(horizontal_clipping=True):
with ui.ZStack():
# Background
ui.Rectangle(name="code_background")
# The code
with ui.VStack():
try:
self._execute_code(block.text)
except Exception as e:
tb = traceback.format_exception(Exception, e, e.__traceback__)
ui.Label(
"".join(tb), name="code", style_type_name_override="Text", skip_draw_when_clipped=True
)
ui.Spacer(height=10)
# Remove double-comments
clean = DocumentationBuilderMd.get_clean_code(block)
with ui.Frame(horizontal_clipping=True):
stack = ui.ZStack(height=0)
with stack:
ui.Rectangle(name="code")
short_frame = ui.Frame()
with short_frame:
label = ui.Label(clean, name="code", style_type_name_override="Text", skip_draw_when_clipped=True)
overlay = ui.Frame()
# Enable clipping/extending the label after we know its size
label.set_computed_content_size_changed_fn(partial(label_size_changed, label, short_frame, overlay))
self.__code_stacks.append(stack)
if is_execute_manual:
ui.Spacer(height=4)
with ui.HStack():
# ui.Spacer(height=10)
def on_click(text=block.text):
try:
self._execute_code(block.text)
except Exception as e:
tb = traceback.format_exception(Exception, e, e.__traceback__)
ui.Label("".join(tb), name="code", style_type_name_override="Text", skip_draw_when_clipped=True)
button = ui.Button(
"RUN CODE", style_type_name_override="RunButton", width=50, height=20, clicked_fn=on_click
)
ui.Spacer()
if sys.platform != "linux":
stack.set_mouse_pressed_fn(lambda x, y, b, m, text=clean: b == 1 and self._show_copy_menu(x, y, b, m, text))
def _build_image(self, block: _Block):
source_url = block.text
def change_resolution_legacy(image_weak, size):
"""
Change the widget size proportionally to the image
We set a max height of 400 for anything.
"""
MAX_HEIGHT = 400
image = image_weak()
if not image:
return
width, height = size
image_height = min(image.computed_content_width * height / width, MAX_HEIGHT)
image.height = ui.Pixel(image_height)
def change_resolution(image_weak, size):
"""
This leaves the image scale untouched
"""
image = image_weak()
if not image:
return
width, height = size
image.height = ui.Pixel(height)
image.width = ui.Pixel(width)
im = Image.open(source_url)
image = ui.Image(source_url, height=200)
# Even though the legacy behaviour is probably wrong there are extensions out there with images that are
# too big, we don't want them to display differently than before
if self._dont_scale_images:
image.set_computed_content_size_changed_fn(partial(change_resolution, weakref.ref(image), im.size))
else:
image.set_computed_content_size_changed_fn(partial(change_resolution_legacy, weakref.ref(image), im.size))
self.__images.append(image)
def _show_copy_menu(self, x, y, button, modifier, text):
"""The context menu to copy the text"""
# Display context menu only if the right button is pressed
def copy_text(text_value):
# we need to find a cross plartform way currently Window Only
subprocess.run(["clip.exe"], input=text_value.strip().encode("utf-8"), check=True)
# Reset the previous context popup
self._copy_context_menu = ui.Menu("Copy Context Menu")
with self._copy_context_menu:
ui.MenuItem("Copy Code", triggered_fn=lambda t=text: copy_text(t))
# Show it
self._copy_context_menu.show()
| 14,863 | Python | 37.015345 | 120 | 0.519545 |
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_style.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from pathlib import Path
import omni.ui as ui
from omni.ui import color as cl
from omni.ui import constant as fl
from omni.ui import url
CURRENT_PATH = Path(__file__).parent
DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data")
FONTS_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("fonts")
def get_style():
"""
Returns the standard omni.ui style for documentation
"""
cl.documentation_nvidia = cl("#76b900")
# Content
cl.documentation_bg = cl.white
cl.documentation_text = cl("#1a1a1a")
cl.documentation_h1_bg = cl.black
cl.documentation_h1_color = cl.documentation_nvidia
cl.documentation_h2_line = cl.black
cl.documentation_h2_color = cl.documentation_nvidia
cl.documentation_exec_bg = cl("#454545")
cl.documentation_code_bg = cl("#eeeeee")
cl.documentation_code_fadeout = cl("#eeeeee01")
cl.documentation_code_fadeout_selected = cl.documentation_nvidia
cl.documentation_code_line = cl("#bbbbbb")
fl.documentation_margin = 5
fl.documentation_code_size = 16
fl.documentation_code_radius = 2
fl.documentation_text_size = 18
fl.documentation_h1_size = 36
fl.documentation_h2_size = 28
fl.documentation_h3_size = 20
fl.documentation_line_width = 0.3
cl.url_link = cl("#3333CC")
# Catalog
cl.documentation_catalog_bg = cl.black
cl.documentation_catalog_text = cl("#cccccc")
cl.documentation_catalog_h1_bg = cl("#333333")
cl.documentation_catalog_h1_color = cl.documentation_nvidia
cl.documentation_catalog_h2_bg = cl("#fcfcfc")
cl.documentation_catalog_h2_color = cl("#404040")
cl.documentation_catalog_h3_bg = cl("#e3e3e3")
cl.documentation_catalog_h3_color = cl("#404040")
cl.documentation_catalog_icon_selected = cl("#333333")
fl.documentation_catalog_tree1_size = 17
fl.documentation_catalog_tree1_margin = 5
fl.documentation_catalog_tree2_size = 19
fl.documentation_catalog_tree2_margin = 2
fl.documentation_catalog_tree3_size = 19
fl.documentation_catalog_tree3_margin = 2
url.documentation_logo = f"{DATA_PATH.joinpath('main_ov_logo_square.png')}"
url.documentation_settings = f"{DATA_PATH.joinpath('settings.svg')}"
url.documentation_plus = f"{DATA_PATH.joinpath('plus.svg')}"
url.documentation_minus = f"{DATA_PATH.joinpath('minus.svg')}"
url.documentation_font_regular = f"{FONTS_PATH}/DINPro-Regular.otf"
url.documentation_font_regular_bold = f"{FONTS_PATH}/DINPro-Bold.otf"
url.documentation_font_monospace = f"{FONTS_PATH}/DejaVuSansMono.ttf"
style = {
"Window": {"background_color": cl.documentation_catalog_bg, "border_width": 0, "padding": 0},
"Rectangle::content_background": {"background_color": cl.documentation_bg},
"Label::paragraph": {
"color": cl.documentation_text,
"font_size": fl.documentation_text_size,
"margin": fl.documentation_margin,
},
"Text::code": {
"color": cl.documentation_text,
"font": url.documentation_font_monospace,
"font_size": fl.documentation_code_size,
"margin": fl.documentation_margin,
},
"url_link": {"color": cl.url_link, "font_size": fl.documentation_text_size},
"table_label": {
"color": cl.documentation_text,
"font_size": fl.documentation_text_size,
"margin": 2,
},
"Rectangle::code": {
"background_color": cl.documentation_code_bg,
"border_color": cl.documentation_code_line,
"border_width": fl.documentation_line_width,
"border_radius": fl.documentation_code_radius,
},
"Rectangle::code_background": {"background_color": cl.documentation_exec_bg},
"Rectangle::h1": {"background_color": cl.documentation_h1_bg},
"Rectangle::tree1": {"background_color": cl.documentation_catalog_h1_bg},
"Rectangle::tree2": {"background_color": 0x0},
"Rectangle::tree2:selected": {"background_color": cl.documentation_catalog_h2_bg},
"Rectangle::tree3": {"background_color": 0x0},
"Rectangle::tree3:selected": {"background_color": cl.documentation_catalog_h3_bg},
"Text::h1": {
"color": cl.documentation_h1_color,
"font": url.documentation_font_regular,
"font_size": fl.documentation_h1_size,
"margin": fl.documentation_margin,
"alignment": ui.Alignment.CENTER,
},
"Text::h2": {
"color": cl.documentation_h2_color,
"font": url.documentation_font_regular,
"font_size": fl.documentation_h2_size,
"margin": fl.documentation_margin,
},
"Text::h3": {
"color": cl.documentation_h2_color,
"font": url.documentation_font_regular,
"font_size": fl.documentation_h3_size,
"margin": fl.documentation_margin,
},
"Text::tree1": {
"color": cl.documentation_catalog_h1_color,
"font": url.documentation_font_regular_bold,
"font_size": fl.documentation_catalog_tree1_size,
"margin": fl.documentation_catalog_tree1_margin,
},
"Text::tree2": {
"color": cl.documentation_catalog_text,
"font": url.documentation_font_regular,
"font_size": fl.documentation_catalog_tree2_size,
"margin": fl.documentation_catalog_tree2_margin,
},
"Text::tree2:selected": {"color": cl.documentation_catalog_h2_color},
"Text::tree3": {
"color": cl.documentation_catalog_text,
"font": url.documentation_font_regular,
"font_size": fl.documentation_catalog_tree3_size,
"margin": fl.documentation_catalog_tree3_margin,
},
"Text::tree3:selected": {"color": cl.documentation_catalog_h3_color},
"Image::main_logo": {"image_url": url.documentation_logo},
"Image::settings": {"image_url": url.documentation_settings},
"Image::plus": {"image_url": url.documentation_plus},
"Image::minus": {"image_url": url.documentation_minus},
"Image::plus:selected": {"color": cl.documentation_catalog_icon_selected},
"Image::minus:selected": {"color": cl.documentation_catalog_icon_selected},
"Line::h2": {"border_width": fl.documentation_line_width},
"Line::h3": {"border_width": fl.documentation_line_width},
"TextOverlay": {
"background_color": cl.documentation_bg,
"background_gradient_color": cl.documentation_code_fadeout,
},
"TextOverlay:hovered": {"background_color": cl.documentation_code_fadeout_selected},
"RunButton": {"background_color": cl("#76b900"), "border_radius": 2},
"RunButton.Label": {"color": 0xFF3E3E3E, "font_size": 14},
"RunButton:hovered": {"background_color": cl("#84d100")},
"RunButton:pressed": {"background_color": cl("#7bc200")},
}
return style
| 7,491 | Python | 42.812865 | 101 | 0.637699 |
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/tests/test_documentation.py | # Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["TestDocumentation"]
import pathlib
import omni.kit.app
import omni.kit.test
from omni.ui.tests.test_base import OmniUiTest
from ..documentation_md import DocumentationBuilderMd
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
TESTS_PATH = EXTENSION_FOLDER_PATH.joinpath("data/tests")
class TestDocumentation(OmniUiTest):
async def test_builder(self):
builder = DocumentationBuilderMd(f"{TESTS_PATH}/test.md")
self.assertEqual(
builder.catalog,
[{"name": "NVIDIA", "children": [{"name": "Omiverse", "children": [{"name": "Doc", "children": []}]}]}],
)
self.assertEqual(builder.blocks[0].text, "NVIDIA")
self.assertEqual(builder.blocks[0].block_type.name, "H1")
self.assertEqual(builder.blocks[1].text, "Omiverse")
self.assertEqual(builder.blocks[1].block_type.name, "H2")
self.assertEqual(builder.blocks[2].text, "Doc")
self.assertEqual(builder.blocks[2].block_type.name, "H3")
self.assertEqual(builder.blocks[3].text, "Text")
self.assertEqual(builder.blocks[3].block_type.name, "PARAGRAPH")
clean = builder.get_clean_code(builder.blocks[4])
self.assertEqual(clean, 'ui.Label("Hello")')
self.assertEqual(builder.blocks[4].block_type.name, "CODE")
self.assertEqual(builder.blocks[5].text, ("- List1", "- List2"))
self.assertEqual(builder.blocks[5].block_type.name, "LIST")
self.assertEqual(builder.blocks[6].text, ("- [YOUTUBE](https://www.youtube.com)",))
self.assertEqual(builder.blocks[6].block_type.name, "LINK_IN_LIST")
self.assertEqual(builder.blocks[7].text, "[NVIDIA](https://www.nvidia.com)")
self.assertEqual(builder.blocks[7].block_type.name, "LINK")
self.assertEqual(
builder.blocks[8].text, ("| Noun | Adjective |", "| ---- | --------- |", "| Omniverse | Awesome |")
)
self.assertEqual(builder.blocks[8].block_type.name, "TABLE")
builder.destroy()
| 2,531 | Python | 39.838709 | 116 | 0.670881 |
omniverse-code/kit/exts/omni.kit.documentation.builder/docs/CHANGELOG.md | # Changelog
The interactive documentation builder for omni.ui extensions
## [1.0.9] - 2022-11-16
### Changed
- Remove execute tag from Overview.md for publishing
## [1.0.8] - 2022-08-29
### Added
- List, link, and basic table support
- Show errors from code execute blocks
## [1.0.7] - 2022-06-27
### Added
- Create documentation menu automatically from extension.toml files
## [1.0.6] - 2022-06-22
### Fixed
- Allow md headers without initial H1 level
## [1.0.5] - 2022-06-14
### Added
- Use ui.Label for all text blocks
## [1.0.4] - 2022-05-09
### Fixed
- Missing import
## [1.0.3] - 2022-04-30
### Added
- Minimal test
## [1.0.2] - 2021-12-17
### Added
- `DocumentationBuilderWindow.get_style` to get the default style
## [1.0.1] - 2021-12-15
### Added
- A separate widget for the page `DocumentationBuilderPage`
## [1.0.0] - 2021-12-14
### Added
- The initial implementation
| 890 | Markdown | 18.8 | 67 | 0.669663 |
omniverse-code/kit/exts/omni.kit.documentation.builder/docs/README.md | # The documentation for omni.ui extensions
The interactive documentation builder for omni.ui extensions | 104 | Markdown | 33.999989 | 60 | 0.846154 |
omniverse-code/kit/exts/omni.kit.documentation.builder/docs/index.rst | omni.kit.documentation.builder
##############################
.. toctree::
:maxdepth: 1
CHANGELOG
| 108 | reStructuredText | 9.899999 | 30 | 0.481481 |
omniverse-code/kit/exts/omni.kit.documentation.builder/docs/Overview.md | # Omni.UI Documentation Builder
The Documentation Builder extension finds enabled extensions with a [documentation] section in their extension.toml
and adds a menu to show that documentation in a popup window. Extensions do not need to depend on
omni.kit.documentation.builder to enable this functionality.
For example:
```toml
[documentation]
pages = ["docs/Overview.md"]
menu = "Help/API/omni.kit.documentation.builder"
title = "Omni UI Documentation Builder"
```
Documentation pages may contain code blocks with omni.ui calls that will be executed and displayed inline, by using
the "execute" language tag after three backticks:
````{code-block} markdown
---
dedent: 4
---
```execute
import omni.ui as ui
ui.Label("Hello World!")
```
````
## generate_for_sphinx
omni.kit.documentation.builder.generate_for_sphinx can be called to generate documentation offline for sphinx web pages:
```python
import omni.kit.app
import omni.kit.documentation.builder as builder
manager = omni.kit.app.get_app().get_extension_manager()
all_exts = manager.get_extensions()
for ext in all_exts:
if ext.get("enabled", False):
builder.generate_for_sphinx(ext.get("id", ""), f"/docs/{ext.get('name')}")
```
## create_docs_window
Explicity create a documentation window with the omni.kit.documentation.builder.create_docs_window function:
```python
import omni.kit.documentation.builder as builder
builder.create_docs_window("omni.kit.documentation.builder")
```
| 1,482 | Markdown | 28.078431 | 120 | 0.749663 |
omniverse-code/kit/exts/omni.kit.documentation.builder/data/tests/test.md | # NVIDIA
## Omiverse
### Doc
Text
```execute
##
import omni.ui as ui
##
ui.Label("Hello")
```
- List1
- List2
[NVIDIA](https://www.nvidia.com)
| Noun | Adjective |
| ---- | --------- |
| Omniverse | Awesome |
| 214 | Markdown | 8.772727 | 32 | 0.551402 |
omniverse-code/kit/exts/omni.volume/config/extension.toml | [package]
version = "0.1.0"
title = "Volume"
category = "Internal"
[dependencies]
"omni.usd.libs" = {}
"omni.assets.plugins" = {}
"omni.kit.pip_archive" = {}
[[python.module]]
name = "omni.volume"
# numpy is used by tests
[python.pipapi]
requirements = ["numpy"]
[[native.plugin]]
path = "bin/deps/carb.volume.plugin"
| 322 | TOML | 15.149999 | 36 | 0.661491 |
omniverse-code/kit/exts/omni.volume/omni/volume/_volume.pyi | """pybind11 carb.volume bindings"""
from __future__ import annotations
import omni.volume._volume
import typing
import numpy
_Shape = typing.Tuple[int, ...]
__all__ = [
"GridData",
"IVolume",
"acquire_volume_interface"
]
class GridData():
pass
class IVolume():
def create_from_dense(self, arg0: float, arg1: buffer, arg2: float, arg3: buffer, arg4: str) -> GridData: ...
def create_from_file(self, arg0: str) -> GridData: ...
def get_grid_class(self, arg0: GridData, arg1: int) -> int: ...
def get_grid_data(self, arg0: GridData, arg1: int) -> typing.List[int]: ...
def get_grid_type(self, arg0: GridData, arg1: int) -> int: ...
def get_index_bounding_box(self, arg0: GridData, arg1: int) -> list: ...
def get_num_grids(self, arg0: GridData) -> int: ...
def get_short_grid_name(self, arg0: GridData, arg1: int) -> str: ...
def get_world_bounding_box(self, arg0: GridData, arg1: int) -> list: ...
def mesh_to_level_set(self, arg0: numpy.ndarray[numpy.float32], arg1: numpy.ndarray[numpy.int32], arg2: numpy.ndarray[numpy.int32], arg3: float, arg4: numpy.ndarray[numpy.int32]) -> GridData: ...
def save_volume(self, arg0: GridData, arg1: str) -> bool: ...
pass
def acquire_volume_interface(plugin_name: str = None, library_path: str = None) -> IVolume:
pass
| 1,327 | unknown | 40.499999 | 199 | 0.650339 |
omniverse-code/kit/exts/omni.volume/omni/volume/__init__.py | """This module contains bindings to C++ carb::volume::IVolume interface.
All the function are in omni.volume.IVolume class, to get it use get_editor_interface method, which caches
acquire interface call:
>>> import omni.volume
>>> e = omni.volume.get_volume_interface()
>>> print(f"Is UI hidden: {e.is_ui_hidden()}")
"""
from ._volume import *
from functools import lru_cache
@lru_cache()
def get_volume_interface() -> IVolume:
"""Returns cached :class:` omni.volume.IVolume` interface"""
return acquire_volume_interface()
| 547 | Python | 29.444443 | 106 | 0.702011 |
omniverse-code/kit/exts/omni.volume/omni/volume/tests/test_volume.py | import numpy
import omni.kit.test
import omni.volume
class CreateFromDenseTest(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
pass
# After running each test
async def tearDown(self):
pass
# Actual test, notice it is "async" function, so "await" can be used if needed
async def test_create_from_dense(self):
ivolume = omni.volume.get_volume_interface()
o = numpy.array([0, 0, 0]).astype(numpy.float64)
float_x = numpy.arange(30).reshape((5, 3, 2)).astype(numpy.float32)
float_volume = ivolume.create_from_dense(0, float_x, 1, o, "floatTest")
self.assertEqual(ivolume.get_num_grids(float_volume), 1)
self.assertEqual(ivolume.get_grid_class(float_volume, 0), 0)
self.assertEqual(ivolume.get_grid_type(float_volume, 0), 1)
self.assertEqual(ivolume.get_short_grid_name(float_volume, 0), "floatTest")
float_index_bounding_box = ivolume.get_index_bounding_box(float_volume, 0)
self.assertEqual(float_index_bounding_box, [(0, 0, 0), (1, 2, 4)])
float_world_bounding_box = ivolume.get_world_bounding_box(float_volume, 0)
self.assertEqual(float_world_bounding_box, [(0, 0, 0), (2, 3, 5)])
double_x = numpy.arange(30).reshape((5, 3, 2)).astype(numpy.float64)
double_volume = ivolume.create_from_dense(0, double_x, 1, o, "doubleTest")
self.assertEqual(ivolume.get_num_grids(double_volume), 1)
self.assertEqual(ivolume.get_grid_class(double_volume, 0), 0)
self.assertEqual(ivolume.get_grid_type(double_volume, 0), 2)
self.assertEqual(ivolume.get_short_grid_name(double_volume, 0), "doubleTest")
double_index_bounding_box = ivolume.get_index_bounding_box(double_volume, 0)
self.assertEqual(double_index_bounding_box, [(0, 0, 0), (1, 2, 4)])
double_world_bounding_box = ivolume.get_world_bounding_box(double_volume, 0)
self.assertEqual(double_world_bounding_box, [(0, 0, 0), (2, 3, 5)])
| 2,028 | Python | 47.309523 | 85 | 0.661736 |
omniverse-code/kit/exts/omni.volume/omni/volume/tests/__init__.py | from .test_volume import * | 26 | Python | 25.999974 | 26 | 0.769231 |
omniverse-code/kit/exts/omni.activity.ui/config/extension.toml | [package]
title = "omni.ui Window Activity"
description = "The full end to end activity of the window"
feature = true
version = "1.0.20"
category = "Activity"
authors = ["NVIDIA"]
repository = ""
keywords = ["activity", "window", "ui"]
changelog = "docs/CHANGELOG.md"
icon = "data/icon.png"
preview_image = "data/preview.png"
[dependencies]
"omni.activity.core" = {}
"omni.activity.pump" = {}
"omni.activity.usd_resolver" = {}
"omni.kit.menu.utils" = {optional=true}
"omni.ui" = {}
"omni.ui.scene" = {}
"omni.kit.window.file" = {}
[[native.library]]
path = "bin/${lib_prefix}omni.activity.ui.bar${lib_ext}"
[[python.module]]
name = "omni.activity.ui"
[settings]
exts."omni.activity.ui".auto_save_location = "${cache}/activities"
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.kit.renderer.capture",
]
[documentation]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
| 986 | TOML | 20 | 66 | 0.656187 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/open_file_addon.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
import asyncio
from .activity_progress_bar import ProgressBarWidget
class OpenFileAddon:
def __init__(self):
self._stop_event = asyncio.Event()
# The progress
with ui.Frame(height=355):
self.activity_widget = ProgressBarWidget()
def new(self, model):
self.activity_widget.new(model)
def __del__(self):
self.activity_widget.destroy()
self._stop_event.set()
def mouse_pressed(self, *args):
# Bind this class to the rectangle, so when Rectangle is deleted, the
# class is deleted as well
pass
def start_timer(self):
self.activity_widget.reset_timer()
def stop_timer(self):
self.activity_widget.stop_timer()
| 1,190 | Python | 29.538461 | 77 | 0.694118 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_tree_delegate.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ActivityTreeDelegate", "ActivityProgressTreeDelegate"]
from .activity_model import SECOND_MULTIPLIER, ActivityModelItem
import omni.kit.app
import omni.ui as ui
import pathlib
from urllib.parse import unquote
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
class ActivityTreeDelegate(ui.AbstractItemDelegate):
"""
The delegate for the bottom TreeView that displays details of the activity.
"""
def __init__(self, **kwargs):
super().__init__()
self._on_expand = kwargs.pop("on_expand", None)
self._initialize_expansion = kwargs.pop("initialize_expansion", None)
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
if column_id == 0:
with ui.HStack(width=20 * (level + 1), height=0):
ui.Spacer()
if model.can_item_have_children(item):
# Draw the +/- icon
image_name = "Minus" if expanded else "Plus"
ui.ImageWithProvider(
f"{EXTENSION_FOLDER_PATH}/data/{image_name}.svg",
width=10,
height=10,
style_type_name_override="TreeView.Label",
mouse_pressed_fn=lambda x, y, b, a: self._on_expand(item)
)
ui.Spacer(width=5)
def _build_header(self, column_id, headers, headers_tooltips):
alignment = ui.Alignment.LEFT_CENTER if column_id == 0 else ui.Alignment.RIGHT_CENTER
return ui.Label(
headers[column_id], height=22, alignment=alignment, style_type_name_override="TreeView.Label", tooltip=headers_tooltips[column_id])
def build_header(self, column_id: int):
headers = [" Name", "Dur", "Start", "End", "Size "]
headers_tooltips = ["Activity Name", "Duration (second)", "Start Time (second)", "End Time (second)", "Size (MB)"]
return self._build_header(column_id, headers, headers_tooltips)
def _build_name(self, text, item, model):
tooltip = f"{text}"
short_name = unquote(text.split("/")[-1])
children_size = len(model.get_item_children(item))
label_text = short_name if children_size == 0 else short_name + " (" + str(children_size) + ")"
with ui.HStack(spacing=5):
icon_name = item.icon_name
if icon_name != "undefined":
ui.ImageWithProvider(style_type_name_override="Icon", name=icon_name, width=16)
if icon_name != "material":
ui.ImageWithProvider(style_type_name_override="Icon", name="file", width=12)
label_style_name = icon_name if item.ended else "unfinished"
ui.Label(label_text, name=label_style_name, tooltip=tooltip)
# if text == "Materials" or text == "Textures":
# self._initialize_expansion(item, True)
def _build_duration(self, item):
duration = item.total_time / SECOND_MULTIPLIER
ui.Label(f"{duration:.2f}", style_type_name_override="TreeView.Label.Right", tooltip=str(duration) + " sec")
def _build_start_and_end(self, item, model, is_start):
time_ranges = item.time_range
if len(time_ranges) == 0:
return
time_begin = model.time_begin
begin = (time_ranges[0].begin - time_begin) / SECOND_MULTIPLIER
end = (time_ranges[-1].end - time_begin) / SECOND_MULTIPLIER
if is_start:
ui.Label(f"{begin:.2f}", style_type_name_override="TreeView.Label.Right", tooltip=str(begin) + " sec")
else:
ui.Label(f"{end:.2f}", style_type_name_override="TreeView.Label.Right", tooltip=str(end) + " sec")
def _build_size(self, text, item):
if text in ["Read", "Load", "Resolve"]:
size = item.children_size
else:
size = item.size
if size != 0:
size *= 0.000001
ui.Label(f"{size:.2f}", style_type_name_override="TreeView.Label.Right", tooltip=str(size) + " MB") # from byte to MB
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per item"""
if not hasattr(model, "time_begin") or not isinstance(item, ActivityModelItem):
return
text = model.get_item_value_model(item, column_id).get_value_as_string()
with ui.VStack(height=20):
if column_id == 0:
self._build_name(text, item, model)
elif column_id == 1:
self._build_duration(item)
elif column_id == 2 or column_id == 3:
self._build_start_and_end(item, model, column_id == 2)
elif column_id == 4:
self._build_size(text, item)
class ActivityProgressTreeDelegate(ActivityTreeDelegate):
def __init__(self, **kwargs):
super().__init__()
def build_header(self, column_id: int):
headers = [" Name", "Dur", "Size "]
headers_tooltips = ["Activity Name", "Duration (second)", "Size (MB)"]
return self._build_header(column_id, headers, headers_tooltips)
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per item"""
if not hasattr(model, "time_begin") or not isinstance(item, ActivityModelItem):
return
text = model.get_item_value_model(item, column_id).get_value_as_string()
with ui.VStack(height=20):
if column_id == 0:
self._build_name(text, item, model)
elif column_id == 1:
self._build_duration(item)
elif column_id == 2:
self._build_size(text, item)
| 6,242 | Python | 42.964788 | 143 | 0.598526 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_extension.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ActivityWindowExtension", "get_instance"]
from .activity_menu import ActivityMenuOptions
from .activity_model import ActivityModelDump, ActivityModelDumpForProgress, ActivityModelStageOpen, ActivityModelStageOpenForProgress
from .activity_progress_model import ActivityProgressModel
from .activity_progress_bar import ActivityProgressBarWindow, TIMELINE_WINDOW_NAME
from .activity_window import ActivityWindow
from .open_file_addon import OpenFileAddon
from .activity_actions import register_actions, deregister_actions
import asyncio
from functools import partial
import os
from pathlib import Path
from typing import Any
from typing import Dict
from typing import Optional
import weakref
import carb.profiler
import carb.settings
import carb.tokens
import omni.activity.core
import omni.activity.profiler
import omni.ext
import omni.kit.app
import omni.kit.ui
from omni.kit.window.file import register_open_stage_addon
from omni.kit.usd.layers import get_live_syncing
import omni.ui as ui
import omni.usd_resolver
import omni.kit.commands
AUTO_SAVE_LOCATION = "/exts/omni.activity.ui/auto_save_location"
STARTUP_ACTIVITY_FILENAME = "Startup"
g_singleton = None
def get_instance():
return g_singleton
class ActivityWindowExtension(omni.ext.IExt):
"""The entry point for Activity Window"""
PROGRESS_WINDOW_NAME = "Activity Progress"
PROGRESS_MENU_PATH = f"Window/Utilities/{PROGRESS_WINDOW_NAME}"
def on_startup(self, ext_id):
import omni.kit.app
# true when we record the activity
self.__activity_started = False
self._activity_profiler = omni.activity.profiler.get_activity_profiler()
self._activity_profiler_capture_mask_uid = 0
# make sure the old activity widget is disabled before loading the new one
ext_manager = omni.kit.app.get_app_interface().get_extension_manager()
old_activity_widget = "omni.kit.activity.widget.monitor"
if ext_manager.is_extension_enabled(old_activity_widget):
ext_manager.set_extension_enabled_immediate(old_activity_widget, False)
self._timeline_window = None
self._progress_bar = None
self._addon = None
self._current_path = None
self._data = None
self.__model = None
self.__progress_model= None
self.__flatten_model = None
self._menu_entry = None
self._activity_menu_option = ActivityMenuOptions(load_data=self.load_data, get_save_data=self.get_save_data)
# The ability to show up the window if the system requires it. We use it
# in QuickLayout.
ui.Workspace.set_show_window_fn(TIMELINE_WINDOW_NAME, partial(self.show_window, None))
ui.Workspace.set_show_window_fn(
ActivityWindowExtension.PROGRESS_WINDOW_NAME, partial(self.show_progress_bar, None)
)
# add actions
self._ext_name = omni.ext.get_extension_name(ext_id)
register_actions(self._ext_name, self)
# add new menu
try:
import omni.kit.menu.utils
from omni.kit.menu.utils import MenuItemDescription
self._menu_entry = [
MenuItemDescription(name="Utilities", sub_menu=
[MenuItemDescription(
name=ActivityWindowExtension.PROGRESS_WINDOW_NAME,
ticked=True,
ticked_fn=self._is_progress_visible,
onclick_action=("omni.activity.ui", "show_activity_window"),
)]
)
]
omni.kit.menu.utils.add_menu_items(self._menu_entry, name="Window")
except (ModuleNotFoundError, AttributeError): # pragma: no cover
pass
# Listen for the app ready event
startup_event_stream = omni.kit.app.get_app().get_startup_event_stream()
self._app_ready_sub = startup_event_stream.create_subscription_to_pop_by_type(
omni.kit.app.EVENT_APP_READY, self._on_app_ready, name="Omni Activity"
)
# Listen to USD stage activity
stage_event_stream = omni.usd.get_context().get_stage_event_stream()
self._stage_event_sub = stage_event_stream.create_subscription_to_pop(
self._on_stage_event, name="Omni Activity"
)
self._activity_widget_subscription = register_open_stage_addon(self._open_file_addon)
self._activity_widget_live_subscription = get_live_syncing().register_open_stage_addon(self._open_file_addon)
# subscribe the callback to show the progress window when the prompt window disappears
# self._show_window_subscription = register_open_stage_complete(self._show_progress_window)
# message bus to update the status bar
self.__subscription = None
self.name_progress = carb.events.type_from_string("omni.kit.window.status_bar@progress")
self.name_activity = carb.events.type_from_string("omni.kit.window.status_bar@activity")
self.name_clicked = carb.events.type_from_string("omni.kit.window.status_bar@clicked")
self.message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
# subscribe the callback to show the progress window when user clicks the status bar's progress area
self.__statusbar_click_subscription = self.message_bus.create_subscription_to_pop_by_type(
self.name_clicked, lambda e: self._show_progress_window())
# watch the commands
commands = ["AddReference", "CreatePayload", "CreateSublayer", "ReplacePayload", "ReplaceReference"]
self.__command_callback_ids = [
omni.kit.commands.register_callback(
cb,
omni.kit.commands.PRE_DO_CALLBACK,
partial(ActivityWindowExtension._on_command, weakref.proxy(self), cb),
)
for cb in commands
]
# Set up singleton instance
global g_singleton
g_singleton = self
def _show_progress_window(self):
ui.Workspace.show_window(ActivityWindowExtension.PROGRESS_WINDOW_NAME)
self._progress_bar.focus()
def _on_app_ready(self, event):
if not self.__activity_started:
# Start an activity trace to measure the time between app ready and the first frame.
# This may have already happened in _on_stage_event if an empty stage was opened at startup.
self._start_activity(STARTUP_ACTIVITY_FILENAME, profiler_mask=omni.activity.profiler.CAPTURE_MASK_STARTUP)
self._app_ready_sub = None
rendering_event_stream = omni.usd.get_context().get_rendering_event_stream()
self._new_frame_sub = rendering_event_stream.create_subscription_to_push_by_type(
omni.usd.StageRenderingEventType.NEW_FRAME, self._on_new_frame, name="Omni Activity"
)
def _on_new_frame(self, event):
# Stop the activity trace measuring the time between app ready and the first frame.
self._stop_activity(completed=True, filename=STARTUP_ACTIVITY_FILENAME)
self._new_frame_sub = None
def _on_stage_event(self, event):
OPENING = int(omni.usd.StageEventType.OPENING)
OPEN_FAILED = int(omni.usd.StageEventType.OPEN_FAILED)
ASSETS_LOADED = int(omni.usd.StageEventType.ASSETS_LOADED)
if event.type is OPENING:
path = event.payload.get("val", None)
capture_mask = omni.activity.profiler.CAPTURE_MASK_SCENE_LOADING
if self._app_ready_sub != None:
capture_mask |= omni.activity.profiler.CAPTURE_MASK_STARTUP
path = STARTUP_ACTIVITY_FILENAME
self._start_activity(path, profiler_mask=capture_mask)
elif event.type is OPEN_FAILED:
self._stop_activity(completed=False)
elif event.type is ASSETS_LOADED:
self._stop_activity(completed=True)
def _model_changed(self, model, item):
self.message_bus.push(self.name_activity, payload={"text": f"{model.latest_item}"})
self.message_bus.push(self.name_progress, payload={"progress": f"{model.total_progress}"})
def on_shutdown(self):
global g_singleton
g_singleton = None
import omni.kit.commands
self._app_ready_sub = None
self._new_frame_sub = None
self._stage_event_sub = None
self._progress_menu = None
self._current_path = None
self.__model = None
self.__progress_model= None
self.__flatten_model = None
# remove actions
deregister_actions(self._ext_name)
# remove menu
try:
import omni.kit.menu.utils
omni.kit.menu.utils.remove_menu_items(self._menu_entry, name="Window")
except (ModuleNotFoundError, AttributeError): # pragma: no cover
pass
self._menu_entry = None
if self._timeline_window:
self._timeline_window.destroy()
self._timeline_window = None
if self._progress_bar:
self._progress_bar.destroy()
self._progress_bar = None
self._addon = None
if self._activity_menu_option:
self._activity_menu_option.destroy()
# Deregister the function that shows the window from omni.ui
ui.Workspace.set_show_window_fn(TIMELINE_WINDOW_NAME, None)
ui.Workspace.set_show_window_fn(ActivityWindowExtension.PROGRESS_WINDOW_NAME, None)
self._activity_widget_subscription = None
self._activity_widget_live_subscription = None
self._show_window_subscription = None
for callback_id in self.__command_callback_ids:
omni.kit.commands.unregister_callback(callback_id)
async def _destroy_window_async(self):
# wait one frame, this is due to the one frame defer
# in Window::_moveToMainOSWindow()
await omni.kit.app.get_app().next_update_async()
if hasattr(self, '_timeline_window') and self._timeline_window:
self._timeline_window.destroy()
self._timeline_window = None
async def _destroy_progress_window_async(self):
# wait one frame, this is due to the one frame defer
# in Window::_moveToMainOSWindow()
await omni.kit.app.get_app().next_update_async()
if self._progress_bar:
self._progress_bar.destroy()
self._progress_bar = None
def _visiblity_changed_fn(self, visible):
# Called when the user pressed "X"
if not visible:
# Destroy the window, since we are creating new window
# in show_window
asyncio.ensure_future(self._destroy_window_async())
def _progress_visiblity_changed_fn(self, visible):
try:
import omni.kit.menu.utils
omni.kit.menu.utils.refresh_menu_items("Window")
except (ModuleNotFoundError, AttributeError): # pragma: no cover
pass
if not visible:
# Destroy the window, since we are creating new window in show_progress_bar
asyncio.ensure_future(self._destroy_progress_window_async())
def _is_progress_visible(self) -> bool:
return False if self._progress_bar is None else self._progress_bar.visible
def show_window(self, menu, value):
if value:
self._timeline_window = ActivityWindow(
TIMELINE_WINDOW_NAME,
weakref.proxy(self.__model) if self.__model else None,
activity_menu=self._activity_menu_option,
)
self._timeline_window.set_visibility_changed_fn(self._visiblity_changed_fn)
elif self._timeline_window:
self._timeline_window.visible = False
def show_progress_bar(self, menu, value):
if value:
self._progress_bar = ActivityProgressBarWindow(
ActivityWindowExtension.PROGRESS_WINDOW_NAME,
self.__flatten_model,
activity_menu=self._activity_menu_option,
width=415,
height=355,
)
self._progress_bar.set_visibility_changed_fn(self._progress_visiblity_changed_fn)
elif self._progress_bar:
self._progress_bar.visible = False
def _open_file_addon(self):
self._addon = OpenFileAddon()
def get_save_data(self):
"""Save the current model to external file"""
if not self.__model:
return None
return self.__model.get_data()
def _save_current_activity(self, fullpath: Optional[str] = None, filename: Optional[str] = None):
"""
Saves current activity.
If the full path is not given it takes the stage name and saves it to the
auto save location from settings. It can be URL or contain tokens.
"""
if fullpath is None:
settings = carb.settings.get_settings()
auto_save_location = settings.get(AUTO_SAVE_LOCATION)
if not auto_save_location:
# No auto save location - nothing to do
return
# Resolve auto save location
token = carb.tokens.get_tokens_interface()
auto_save_location = token.resolve(auto_save_location)
def remove_files():
# only keep the latest 20 activity files, remove the old ones if necessary
file_stays = 20
sorted_files = [item for item in Path(auto_save_location).glob("*.activity")]
if len(sorted_files) < file_stays:
return
sorted_files.sort(key=lambda item: item.stat().st_mtime)
for item in sorted_files[:-file_stays]:
os.remove(item)
remove_files()
if filename is None:
# Extract filename
# Current URL
current_stage_url = omni.usd.get_context().get_stage_url()
# Using clientlib to parse it
current_stage_path = Path(omni.client.break_url(current_stage_url).path)
# Some usd layers have ":" in name
filename = current_stage_path.stem.split(":")[-1]
# Construct the full path
fullpath = omni.client.combine_urls(auto_save_location + "/", filename + ".activity")
if not fullpath:
return
self._activity_menu_option.save(fullpath)
carb.log_info(f"The activity log has been written to ${fullpath}.")
def load_data(self, data):
"""Load the model from the data"""
if self.__model:
self.__flatten_model.destroy()
self.__progress_model.destroy()
self.__model.destroy()
# Use separate models for Timeline and ProgressBar to mimic realtime model lifecycle. See _start_activity()
self.__model = ActivityModelDump(data=data)
self.__progress_model = ActivityModelDumpForProgress(data=data)
self.__flatten_model = ActivityProgressModel(weakref.proxy(self.__progress_model))
self.__flatten_model.finished_loading()
if self._timeline_window:
self._timeline_window._menu_new(weakref.proxy(self.__model))
if self._progress_bar:
self._progress_bar.new(self.__flatten_model)
def _start_activity(self, path: Optional[str] = None, profiler_mask = 0):
self.__activity_started = True
self._activity_profiler_capture_mask_uid = self._activity_profiler.enable_capture_mask(profiler_mask)
# reset all the windows
if self.__model:
self.__flatten_model.destroy()
self.__progress_model.destroy()
self.__model.destroy()
self._current_path = None
self.__model = ActivityModelStageOpen()
self.__progress_model = ActivityModelStageOpenForProgress()
self.__flatten_model = ActivityProgressModel(weakref.proxy(self.__progress_model))
self.__subscription = None
self.clear_status_bar()
if self._timeline_window:
self._timeline_window._menu_new(weakref.proxy(self.__model))
if self._progress_bar:
self._progress_bar.new(self.__flatten_model)
if self._addon:
self._addon.new(self.__flatten_model)
if path:
self.__subscription = self.__flatten_model.subscribe_item_changed_fn(self._model_changed)
# only when we have a path, we start to record the activity
self.__flatten_model.start_loading = True
if self._progress_bar:
self._progress_bar.start_timer()
if self._addon:
self._addon.start_timer()
self.__model.set_path(path)
self.__progress_model.set_path(path)
self._current_path = path
def _stop_activity(self, completed=True, filename: Optional[str] = None):
# ASSETS_LOADED could be triggered by many things e.g. selection change
# make sure we only enter this function once when the activity stops
if not self.__activity_started:
return
self.__activity_started = False
if self._activity_profiler_capture_mask_uid != 0:
self._activity_profiler.disable_capture_mask(self._activity_profiler_capture_mask_uid)
self._activity_profiler_capture_mask_uid = 0
if self.__model:
self.__model.end()
if self.__progress_model:
self.__progress_model.end()
if self._current_path:
if self._progress_bar:
self._progress_bar.stop_timer()
if self._addon:
self._addon.stop_timer()
if completed:
# make sure the progress is 1 when assets loaded
if self.__flatten_model:
self.__flatten_model.finished_loading()
self.message_bus.push(self.name_progress, payload={"progress": "1.0"})
self._save_current_activity(filename = filename)
self.clear_status_bar()
def clear_status_bar(self):
# send an empty message to status bar
self.message_bus.push(self.name_activity, payload={"text": ""})
# clear the progress bar widget
self.message_bus.push(self.name_progress, payload={"progress": "-1"})
def _on_command(self, command: str, kwargs: Dict[str, Any]):
if command == "AddReference":
path = kwargs.get("reference", None)
if path:
path = path.assetPath
self._start_activity(path)
elif command == "CreatePayload":
path = kwargs.get("asset_path", None)
self._start_activity(path)
elif command == "CreateSublayer":
path = kwargs.get("new_layer_path", None)
self._start_activity(path)
elif command == "ReplacePayload":
path = kwargs.get("new_payload", None)
if path:
path = path.assetPath
self._start_activity(path)
elif command == "ReplaceReference":
path = kwargs.get("new_reference", None)
if path:
path = path.assetPath
self._start_activity(path)
| 19,658 | Python | 39.367556 | 134 | 0.626717 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_progress_model.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ActivityProgressModel"]
import weakref
from dataclasses import dataclass
from typing import Dict, List, Set
from functools import partial
import omni.ui as ui
import omni.activity.core
import time
from urllib.parse import unquote
from .activity_model import ActivityModel, SECOND_MULTIPLIER
moving_window = 20
class ActivityProgressModel(ui.AbstractItemModel):
"""
The model that takes the source model and filters out the items that are
outside of the given time range.
"""
def __init__(self, source: ActivityModel, **kwargs):
super().__init__()
self._flattened_children = []
self._latest_item = None
self.usd_loaded_sum = 0
self.usd_sum = 0
self.usd_progress = 0
self.usd_size = 0
self.usd_speed = 0
self.texture_loaded_sum = 0
self.texture_sum = 0
self.texture_progress = 0
self.texture_size = 0
self.texture_speed = 0
self.material_loaded_sum = 0
self.material_sum = 0
self.material_progress = 0
self.total_loaded_sum = 0
self.total_sum = 0
self.total_progress = 0
self.start_loading = False
self.finish_loading = False
self.total_duration = 0
current_time = time.time()
self.prev_usd_update_time = current_time
self.prev_texture_update_time = current_time
self.texture_data = [(0, current_time)]
self.usd_data = [(0, current_time)]
self.__source: ActivityModel = source
self.__subscription = self.__source.subscribe_item_changed_fn(
partial(ActivityProgressModel._source_changed, weakref.proxy(self))
)
self.activity = omni.activity.core.get_instance()
self._load_data_from_source(self.__source)
def update_USD(self, item):
self.usd_loaded_sum = item.loaded_children_num
self.usd_sum = len(item.children)
self.usd_progress = 0 if self.usd_sum == 0 else self.usd_loaded_sum / float(self.usd_sum)
loaded_size = item.children_size * 0.000001
if loaded_size != self.usd_size:
current_time = time.time()
self.usd_data.append((loaded_size, current_time))
if len(self.usd_data) > moving_window:
self.usd_data.pop(0)
prev_size, prev_time = self.usd_data[0]
self.usd_speed = (loaded_size - prev_size) / (current_time - prev_time)
self.prev_usd_update_time = current_time
self.usd_size = loaded_size
def update_textures(self, item):
self.texture_loaded_sum = item.loaded_children_num
self.texture_sum = len(item.children)
self.texture_progress = 0 if self.texture_sum == 0 else self.texture_loaded_sum / float(self.texture_sum)
loaded_size = item.children_size * 0.000001
if loaded_size != self.texture_size:
current_time = time.time()
self.texture_data.append((loaded_size, current_time))
if len(self.texture_data) > moving_window:
self.texture_data.pop(0)
prev_size, prev_time = self.texture_data[0]
if current_time == prev_time:
return
self.texture_speed = (loaded_size - prev_size) / (current_time - prev_time)
self.prev_texture_update_time = current_time
self.texture_size = loaded_size
def update_materials(self, item):
self.material_loaded_sum = item.loaded_children_num
self.material_sum = len(item.children)
self.material_progress = 0 if self.material_sum == 0 else self.material_loaded_sum / float(self.material_sum)
def update_total(self):
self.total_sum = self.usd_sum + self.texture_sum + self.material_sum
self.total_loaded_sum = self.usd_loaded_sum + self.texture_loaded_sum + self.material_loaded_sum
self.total_progress = 0 if self.total_sum == 0 else self.total_loaded_sum / float(self.total_sum)
def _load_data_from_source(self, model):
if not model or not model.get_item_children(None):
return
for child in model.get_item_children(None):
name = child.name_model.as_string
if name == "Materials":
self.update_materials(child)
elif name in ["USD", "Textures"]:
items = model.get_item_children(child)
for item in items:
item_name = item.name_model.as_string
if item_name == "Read":
self.update_USD(item)
elif item_name == "Load":
self.update_textures(item)
self.update_total()
if model._time_begin and model._time_end:
self.total_duration = int((model._time_end - model._time_begin) / float(SECOND_MULTIPLIER))
def _source_changed(self, model, item):
name = item.name_model.as_string
if name in ["Read", "Load", "Materials"]:
if name == "Read":
self.update_USD(item)
elif name == "Load":
self.update_textures(item)
elif name == "Materials":
self.update_materials(item)
self.update_total()
# telling the tree root that the list is changing
self._item_changed(None)
def finished_loading(self):
if self.__source._time_begin and self.__source._time_end:
self.total_duration = int((self.__source._time_end - self.__source._time_begin) / float(SECOND_MULTIPLIER))
else:
self.total_duration = self.duration
self.finish_loading = True
# sometimes ASSETS_LOADED isn't called when stage is completely finished loading,
# so we force progress to be 1 when we decided that it's finished loading.
self.usd_loaded_sum = self.usd_sum
self.usd_progress = 1
self.texture_loaded_sum = self.texture_sum
self.texture_progress = 1
self.material_loaded_sum = self.material_sum
self.material_progress = 1
self.total_loaded_sum = self.total_sum
self.total_progress = 1
self._item_changed(None)
@property
def time_begin(self):
return self.__source._time_begin
@property
def duration(self):
if not self.start_loading and not self.finish_loading:
return 0
elif self.finish_loading:
return self.total_duration
elif self.start_loading and not self.finish_loading:
current_timestamp = self.activity.current_timestamp
duration = (current_timestamp - self.time_begin) / float(SECOND_MULTIPLIER)
return int(duration)
@property
def latest_item(self):
if self.finish_loading:
return None
if hasattr(self.__source, "_flattened_children") and self.__source._flattened_children:
item = self.__source._flattened_children[0]
name = item.name_model.as_string
short_name = unquote(name.split("/")[-1])
return short_name
else:
return ""
def get_data(self):
return self.__source.get_data()
def destroy(self):
self.__source = None
self.__subscription = None
self.texture_data = []
self.usd_data = []
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is None and hasattr(self.__source, "_flattened_children"):
return self.__source._flattened_children
return []
def get_item_value_model_count(self, item):
"""The number of columns"""
return self.__source.get_item_value_model_count(item)
def get_item_value_model(self, item, column_id):
"""
Return value model.
"""
return self.__source.get_item_value_model(item, column_id)
| 8,354 | Python | 36.977273 | 119 | 0.609887 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/style.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["activity_window_style"]
from omni.ui import color as cl
from omni.ui import constant as fl
from omni.ui import url
import omni.kit.app
import omni.ui as ui
import pathlib
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
# Pre-defined constants. It's possible to change them runtime.
cl.activity_window_attribute_bg = cl("#1f2124")
cl.activity_window_attribute_fg = cl("#0f1115")
cl.activity_window_hovered = cl("#FFFFFF")
cl.activity_text = cl("#9e9e9e")
cl.activity_green = cl("#4FA062")
cl.activity_usd_blue = cl("#2091D0")
cl.activity_progress_blue = cl("#4F7DA0")
cl.activity_purple = cl("#8A6592")
fl.activity_window_attr_hspacing = 10
fl.activity_window_attr_spacing = 1
fl.activity_window_group_spacing = 2
# The main style dict
activity_window_style = {
"Label::attribute_name": {
"alignment": ui.Alignment.RIGHT_CENTER,
"margin_height": fl.activity_window_attr_spacing,
"margin_width": fl.activity_window_attr_hspacing,
},
"Label::attribute_name:hovered": {"color": cl.activity_window_hovered},
"Label::collapsable_name": {"alignment": ui.Alignment.LEFT_CENTER},
"Label::time": {"font_size": 12, "color": cl.activity_text, "alignment": ui.Alignment.LEFT_CENTER},
"Label::selection_time": {"font_size": 12, "color": cl("#34C7FF")},
"Line::timeline": {"color": cl(0.22)},
"Rectangle::selected_area": {"background_color": cl(1.0, 1.0, 1.0, 0.1)},
"Slider::attribute_int:hovered": {"color": cl.activity_window_hovered},
"Slider": {
"background_color": cl.activity_window_attribute_bg,
"draw_mode": ui.SliderDrawMode.HANDLE,
},
"Slider::attribute_float": {
"draw_mode": ui.SliderDrawMode.FILLED,
"secondary_color": cl.activity_window_attribute_fg,
},
"Slider::attribute_float:hovered": {"color": cl.activity_window_hovered},
"Slider::attribute_vector:hovered": {"color": cl.activity_window_hovered},
"Slider::attribute_color:hovered": {"color": cl.activity_window_hovered},
"CollapsableFrame::group": {"margin_height": fl.activity_window_group_spacing},
"Button::options": {"background_color": 0x0, "margin": 0},
"Button.Image::options": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/options.svg", "color": cl.activity_text},
"RadioButton": {"background_color": cl.transparent},
"RadioButton.Label": {"font_size": 14, "color": cl("#A1A1A1")},
"RadioButton.Label:checked": {"font_size": 14, "color": cl("#34C7FF")},
"RadioButton:checked": {"background_color": cl.transparent},
"RadioButton:hovered": {"background_color": cl.transparent},
"RadioButton:pressed": {"background_color": cl.transparent},
"Rectangle::separator": {"background_color": cl("#707070"), "border_radius": 1.5},
"TreeView.Label": {"color": cl.activity_text},
"TreeView.Label.Right": {"color": cl.activity_text, "alignment": ui.Alignment.RIGHT_CENTER},
"Rectangle::spacer": {"background_color": cl("#1F2123")},
"ScrollingFrame": {"background_color": cl("#1F2123")},
"Label::USD": {"color": cl.activity_usd_blue},
"Label::progress": {"color": cl.activity_progress_blue},
"Label::material": {"color": cl.activity_purple},
"Label::undefined": {"color": cl.activity_text},
"Label::unfinished": {"color": cl.lightsalmon},
"Icon::USD": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/USD.svg"},
"Icon::progress": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/progress.svg", "color": cl.activity_progress_blue},
"Icon::material": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/Material.png"},
"Icon::texture": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/Texture.svg"},
"Icon::file": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/file.svg"},
}
progress_window_style = {
"RadioButton": {"background_color": cl.transparent},
"RadioButton.Label": {"font_size": 14, "color": cl("#A1A1A1")},
"RadioButton.Label:checked": {"font_size": 14, "color": cl("#34C7FF")},
"RadioButton:checked": {"background_color": cl.transparent},
"RadioButton:hovered": {"background_color": cl.transparent},
"RadioButton:pressed": {"background_color": cl.transparent},
"Rectangle::separator": {"background_color": cl("#707070"), "border_radius": 1.5},
"ProgressBar::texture": {"border_radius": 0, "color": cl.activity_green, "background_color": cl("#606060")},
"ProgressBar::USD": {"border_radius": 0, "color": cl.activity_usd_blue, "background_color": cl("#606060")},
"ProgressBar::material": {"border_radius": 0, "color": cl.activity_purple, "background_color": cl("#606060")},
"ProgressBar::progress": {"border_radius": 0, "color": cl.activity_progress_blue, "background_color": cl("#606060"), "secondary_color": cl.transparent},
"Button::options": {"background_color": 0x0, "margin": 0},
"Button.Image::options": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/options.svg", "color": cl.activity_text},
"TreeView.Label": {"color": cl.activity_text},
"TreeView.Label.Right": {"color": cl.activity_text, "alignment": ui.Alignment.RIGHT_CENTER},
"Label::USD": {"color": cl.activity_usd_blue},
"Label::progress": {"color": cl.activity_progress_blue},
"Label::material": {"color": cl.activity_purple},
"Label::undefined": {"color": cl.activity_text},
"Label::unfinished": {"color": cl.lightsalmon},
"ScrollingFrame": {"background_color": cl("#1F2123")},
"Icon::USD": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/USD.svg"},
"Icon::progress": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/progress.svg", "color": cl.activity_progress_blue},
"Icon::material": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/Material.png"},
"Icon::texture": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/Texture.svg"},
"Icon::file": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/file.svg"},
"Tree.Branch::Minus": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/Minus.svg", "color": cl("#707070")},
"Tree.Branch::Plus": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/Plus.svg", "color": cl("#707070")},
}
def get_shade_from_name(name: str):
#---------------------------------------
if name == "USD":
return cl("#2091D0")
elif name == "Read":
return cl("#1A75A8")
elif name == "Resolve":
return cl("#16648F")
elif name.endswith((".usd", ".usda", ".usdc", ".usdz")):
return cl("#13567B")
#---------------------------------------
elif name == "Stage":
return cl("#d43838")
elif name.startswith("Opening"):
return cl("#A12A2A")
#---------------------------------------
elif name == "Render Thread":
return cl("#d98927")
elif name == "Execute":
return cl("#A2661E")
elif name == "Post Sync":
return cl("#626262")
#----------------------------------------
elif name == "Textures":
return cl("#4FA062")
elif name == "Load":
return cl("#3C784A")
elif name == "Queue":
return cl("#31633D")
elif name.endswith(".hdr"):
return cl("#34A24E")
elif name.endswith(".png"):
return cl("#2E9146")
elif name.endswith(".jpg") or name.endswith(".JPG"):
return cl("#2B8741")
elif name.endswith(".ovtex"):
return cl("#287F3D")
elif name.endswith(".dds"):
return cl("#257639")
elif name.endswith(".exr"):
return cl("#236E35")
elif name.endswith(".wav"):
return cl("#216631")
elif name.endswith(".tga"):
return cl("#1F5F2D")
#---------------------------------------------
elif name == "Materials":
return cl("#8A6592")
elif name.endswith(".mdl"):
return cl("#76567D")
elif "instance)" in name:
return cl("#694D6F")
elif name == "Compile":
return cl("#5D4462")
elif name == "Create Shader Variations":
return cl("#533D58")
elif name == "Load Textures":
return cl("#4A374F")
#---------------------------------------------
elif name == "Meshes":
return cl("#626262")
#---------------------------------------------
elif name == "Ray Tracing Pipeline":
return cl("#8B8000")
else:
return cl("#555555")
| 8,708 | Python | 43.661538 | 156 | 0.615641 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_filter_model.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ActivityFilterModel"]
import weakref
from dataclasses import dataclass
from typing import Dict, List, Set
from functools import partial
import omni.ui as ui
from .activity_model import ActivityModel
class ActivityFilterModel(ui.AbstractItemModel):
"""
The model that takes the source model and filters out the items that are
outside of the given time range.
"""
def __init__(self, source: ActivityModel, **kwargs):
super().__init__()
self.__source: ActivityModel = source
self.__subscription = self.__source.subscribe_item_changed_fn(
partial(ActivityFilterModel._source_changed, weakref.proxy(self))
)
self.__timerange_begin = None
self.__timerange_end = None
def _source_changed(self, model, item):
self._item_changed(item)
@property
def time_begin(self):
return self.__source._time_begin
@property
def timerange_begin(self):
return self.__timerange_begin
@timerange_begin.setter
def timerange_begin(self, value):
if self.__timerange_begin != value:
self.__timerange_begin = value
self._item_changed(None)
@property
def timerange_end(self):
return self.__timerange_end
@timerange_end.setter
def timerange_end(self, value):
if self.__timerange_end != value:
self.__timerange_end = value
self._item_changed(None)
def destroy(self):
self.__source = None
self.__subscription = None
self.__timerange_begin = None
self.__timerange_end = None
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if self.__source is None:
return []
children = self.__source.get_item_children(item)
if self.__timerange_begin is None or self.__timerange_end is None:
return children
result = []
for child in children:
for range in child.time_range:
if max(self.__timerange_begin, range.begin) <= min(self.__timerange_end, range.end):
result.append(child)
break
return result
def get_item_value_model_count(self, item):
"""The number of columns"""
return self.__source.get_item_value_model_count(item)
def get_item_value_model(self, item, column_id):
"""
Return value model.
"""
return self.__source.get_item_value_model(item, column_id)
| 2,975 | Python | 29.680412 | 100 | 0.636303 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_delegate.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ActivityDelegate"]
from ..bar._bar import AbstractActivityBarDelegate
from ..bar._bar import ActivityBar
from .activity_model import SECOND_MULTIPLIER
from .activity_pack_model import ActivityPackModelItem
from .activity_model import TimeRange
from functools import partial
from omni.ui import color as cl
from typing import List
import omni.ui as ui
import weakref
import carb
class ActivityBarDelegate(AbstractActivityBarDelegate):
def __init__(self, ranges: List[TimeRange], hide_label: bool = False):
super().__init__()
self._hide_label = hide_label
self._ranges = ranges
def get_label(self, index):
if self._hide_label:
# Can't return None because it's derived from C++
return ""
else:
# use short name
item = self._ranges[index].item
name = item.name_model.as_string
short_name = name.split("/")[-1]
# the number of children
children_num = len(item.children)
label_text = short_name if children_num == 0 else short_name + " (" + str(children_num) + ")"
return label_text
def get_tooltip_text(self, index):
time_range = self._ranges[index]
elapsed = time_range.end - time_range.begin
item = time_range.item
name = item.name_model.as_string
tooltip_name = time_range.metadata.get("name", None) or name
if name in ["Read", "Load", "Resolve"]:
# the size of children
size = item.children_size * 0.000001
else:
size = time_range.item.size * 0.000001
return f"{tooltip_name}\n{elapsed / SECOND_MULTIPLIER:.2f}s\n{size:.2f} MB"
class ActivityDelegate(ui.AbstractItemDelegate):
"""
The delegate for the TreeView for the activity chart. Instead of text, it
shows the activity on the timeline.
"""
def __init__(self, **kwargs):
super().__init__()
# Called to collapse/expand
self._on_expand = kwargs.pop("on_expand", None)
# Map between the range and range delegate
self._activity_bar_map = {}
self._activity_bar = None
def destroy(self):
self._activity_bar_map = {}
self._activity_bar = None
def build_branch(self, model, item, column_id, level, expanded): # pragma: no cover
"""Create a branch widget that opens or closes subtree"""
pass
def __on_double_clicked(self, weak_item, weak_range_item, x, y, button, modifier):
if button != 0:
return
if not self._on_expand:
return
item = weak_item()
if not item:
return
range_item = weak_range_item()
if not range_item:
return
# shift + double click will expand all
recursive = True if modifier & carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT else False
self._on_expand(item, range_item, recursive)
def __on_selection(self, time_range, model, item_id):
if item_id is None:
return
item = time_range[item_id].item
if not item:
return
model.selection = item
def select_range(self, item, model):
model.selection = item
if item in self._activity_bar_map:
(_activity_bar, i) = self._activity_bar_map[item]
_activity_bar.selection = i
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per item"""
if not isinstance(item, ActivityPackModelItem):
return
if column_id != 0:
return
time_range = item.time_range
if time_range:
first_range = time_range[0]
first_item = first_range.item
with ui.VStack():
if level == 1:
ui.Spacer(height=2)
_activity_bar = ActivityBar(
time_limit=(model._time_begin, model._time_end),
time_ranges=[(t.begin, t.end) for t in time_range],
colors=[t.metadata["color"] for t in time_range],
delegate=ActivityBarDelegate(time_range),
height=25,
mouse_double_clicked_fn=partial(
ActivityDelegate.__on_double_clicked,
weakref.proxy(self),
weakref.ref(item),
weakref.ref(first_item),
),
selection_changed_fn=partial(ActivityDelegate.__on_selection, weakref.proxy(self), time_range, model),
)
for i, t in enumerate(time_range):
self._activity_bar_map[t.item] = (_activity_bar, i)
| 5,190 | Python | 33.838926 | 122 | 0.587861 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_actions.py | import omni.kit.actions.core
def register_actions(extension_id, cls):
action_registry = omni.kit.actions.core.get_action_registry()
actions_tag = "Activity Actions"
action_registry.register_action(
extension_id,
"show_activity_window",
lambda: cls.show_progress_bar(None, not cls._is_progress_visible()),
display_name="Activity show/hide window",
description="Activity show/hide window",
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)
| 651 | Python | 30.047618 | 76 | 0.697389 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_pack_model.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ActivityPackModel"]
from time import time
from .activity_model import ActivityModel
from .activity_model import ActivityModelItem
from .activity_model import TimeRange
from collections import defaultdict
from functools import partial
from typing import List, Dict, Optional
import omni.ui as ui
import weakref
class ActivityPackModelItem(ui.AbstractItem):
def __init__(self, parent: "ActivityPackModelItem", parent_model: "ActivityPackModel", packed=True):
super().__init__()
self._is_packed = packed
self._time_ranges: List[TimeRange] = []
self._children: List[ActivityPackModelItem] = []
self._parent: ActivityPackModelItem = parent
self._parent_model: ActivityPackModel = parent_model
self._children_dirty = True
# Time range when the item is active
self._timerange_dirty = True
self.__total_time: int = 0
self.name_model = ui.SimpleStringModel("Empty")
def destroy(self):
for child in self._children:
child.destroy()
self._time_ranges = []
self._children = []
self._parent = None
self._parent_model = None
def extend_with_range(self, time_range: TimeRange):
if not self._add_range(time_range):
return False
self._children_dirty = True
return True
def dirty(self):
self._children_dirty = True
self._timerange_dirty = True
def get_children(self) -> List["ActivityPackModelItem"]:
self._update_children()
return self._children
@property
def time_range(self) -> List[TimeRange]:
self._update_timerange()
return self._time_ranges
@property
def total_time(self):
"""Return the time ranges when the item was active"""
if not self._timerange_dirty:
# Recache
_ = self.time_range
return self.__total_time
def _add_range(self, time_range: TimeRange):
"""
Try to fit the given range to the current item. Return true if it's
inserted.
"""
if not self._time_ranges:
self._time_ranges.append(time_range)
return True
# Check if it fits after the last
last = self._time_ranges[-1]
if last.end <= time_range.begin:
self._time_ranges.append(time_range)
return True
# Check if it fits before the first
first = self._time_ranges[0]
if time_range.end <= first.begin:
# prepend
self._time_ranges.insert(0, time_range)
return True
ranges_count = len(self._time_ranges)
if ranges_count <= 1:
# Checked all the combinations
return False
def _binary_search(array, time_range):
left = 0
right = len(array) - 1
while left <= right:
middle = left + (right - left) // 2
if array[middle].end < time_range.begin:
left = middle + 1
elif array[middle].end > time_range.begin:
right = middle - 1
else:
return middle
return left - 1
i = _binary_search(self._time_ranges, time_range) + 1
if i > 0 and i < ranges_count:
if time_range.end <= self._time_ranges[i].begin:
# Insert after i-1 or before i
self._time_ranges.insert(i, time_range)
return True
return False
def _create_child(self):
child = ActivityPackModelItem(weakref.proxy(self), self._parent_model)
self._children.append(child)
return child
def _pack_range(self, time_range: TimeRange):
if self._parent: # Don't pack items if it's not a leaf
for child in self._children:
if child.extend_with_range(time_range):
# Successfully packed
return child
# Can't be packed. Create a new one.
child = self._create_child()
child.extend_with_range(time_range)
return child
def _add_subchild(self, subchild: ActivityModelItem) -> Optional["ActivityPackModelItem"]:
child = None
if self._is_packed:
subchild_time_range = subchild.time_range
for time_range in subchild.time_range:
added_to_child = self._pack_range(time_range)
child = added_to_child
self._parent_model._index_subitem_timegrange_count[subchild] = len(subchild_time_range)
elif subchild not in self._parent_model._index_subitem_timegrange_count:
subchild_time_range = subchild.time_range
child = self._create_child()
for time_range in subchild_time_range:
child.extend_with_range(time_range)
self._parent_model._index_subitem_timegrange_count[subchild] = len(subchild_time_range)
return child
def _search_time_range(self, time_range, low, high):
# Classic binary search
if high >= low:
mid = (high + low) // 2
# If element is present at the middle itself
if self._time_ranges[mid].begin == time_range.begin:
return mid
# If element is smaller than mid, then it can only
# be present in left subarray
elif self._time_ranges[mid].begin > time_range.begin:
return self._search_time_range(time_range, low, mid - 1)
# Else the element can only be present in right subarray
else:
return self._search_time_range(time_range, mid + 1, high)
else:
# Element is not present in the array
return None
def _update_timerange(self):
if not self._parent_model:
return
if not self._timerange_dirty:
return
self._timerange_dirty = False
dirty_subitems = self._parent_model._index_dirty.pop(self, [])
for subitem in dirty_subitems:
time_range_count_done = self._parent_model._index_subitem_timegrange_count.get(subitem, 0)
subitem_time_range = subitem.time_range
# Check the last one. It could be changed
if time_range_count_done:
time_range = subitem_time_range[time_range_count_done - 1]
i = self._search_time_range(time_range, 0, len(self._time_ranges) - 1)
if i is not None and i < len(self._time_ranges) - 1:
if time_range.end > self._time_ranges[i + 1].begin:
# It's changed so it itersects the next range. Repack.
self._time_ranges.pop(i)
self._parent._pack_range(time_range)
for time_range in subitem_time_range[time_range_count_done:]:
self._parent._pack_range(time_range)
self._parent_model._index_subitem_timegrange_count[subitem] = len(subitem_time_range)
def _update_children(self):
if not self._children_dirty:
return
self._children_dirty = False
already_checked = set()
for range in self._time_ranges:
subitem = range.item
if subitem in already_checked:
continue
already_checked.add(subitem)
# Check child count
child_count_already_here = self._parent_model._index_child_count.get(subitem, 0)
subchildren = subitem.children
if subchildren:
# Don't touch already added
for subchild in subchildren[child_count_already_here:]:
child = self._add_subchild(subchild)
self._parent_model._index[subchild] = child
subchild._packItem = child
self._parent_model._index_child_count[subitem] = len(subchildren)
def __repr__(self):
return "<ActivityPackModelItem " + str(self._time_ranges) + ">"
class ActivityPackModel(ActivityModel):
"""Activity model that packs the given submodel"""
def __init__(self, submodel: ActivityModel, **kwargs):
self._submodel = submodel
self._destroy_submodel = kwargs.pop("destroy_submodel", None)
# Replace on_timeline_changed
self.__on_timeline_changed_sub = self._submodel.subscribe_timeline_changed(
partial(ActivityPackModel.__on_timeline_changed, weakref.proxy(self))
)
super().__init__(**kwargs)
self._time_begin = self._submodel._time_begin
self._time_end = self._submodel._time_end
# Index for fast access
self._index: Dict[ActivityModelItem, ActivityPackModelItem] = {}
self._index_child_count: Dict[ActivityModelItem, int] = {}
self._index_subitem_timegrange_count: Dict[ActivityModelItem, int] = {}
self._index_dirty: Dict[ActivityPackModelItem, List[ActivityModelItem]] = defaultdict(list)
self._root = ActivityPackModelItem(None, weakref.proxy(self), packed=False)
self.__subscription = self._submodel.subscribe_item_changed_fn(
partial(ActivityPackModel._subitem_changed, weakref.proxy(self))
)
def _subitem_changed(self, submodel, subitem):
item = self._index.get(subitem, None)
if item is None or item == self._root:
# Root
self._root.dirty()
self._item_changed(None)
elif item:
self._dirty_item(item, subitem)
self._item_changed(item)
def _dirty_item(self, item, subitem):
item.dirty()
self._index_dirty[item].append(subitem)
def destroy(self):
super().destroy()
self.__on_timeline_changed_sub = None
self.__on_model_changed_sub = None
self._index: Dict[ActivityModelItem, ActivityPackModelItem] = {}
self._index_child_count: Dict[ActivityModelItem, int] = {}
self._index_subitem_timegrange_count: Dict[ActivityModelItem, int] = {}
self._index_dirty: Dict[ActivityPackModelItem, List[ActivityModelItem]] = defaultdict(list)
self._root.destroy()
if self._destroy_submodel:
self._submodel.destroy()
self._submodel = None
self.__subscription = None
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if self._submodel is None:
return []
if item is None:
if not self._root.time_range:
# Add the initial timerange once we have it
self._submodel._root.update_flags()
root_time_range = self._submodel._root.time_range
if root_time_range:
self._root.extend_with_range(root_time_range[0])
self._root.dirty()
children = self._root.get_children()
else:
children = item.get_children()
return children
def __on_timeline_changed(self):
self._time_end = self._submodel._time_end
if self._on_timeline_changed:
self._on_timeline_changed()
| 11,645 | Python | 33.764179 | 104 | 0.589867 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_chart.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ActivityChart"]
from .activity_delegate import ActivityDelegate
from .activity_filter_model import ActivityFilterModel
from .activity_menu import ActivityMenuOptions
from .activity_model import SECOND_MULTIPLIER, TIMELINE_EXTEND_DELAY_SEC
from .activity_pack_model import ActivityPackModel
from .activity_tree_delegate import ActivityTreeDelegate
from functools import partial
from omni.ui import color as cl
from typing import Tuple
import carb.input
import math
import omni.appwindow
import omni.client
import omni.ui as ui
import weakref
DENSITY = [1, 2, 5]
def get_density(i):
# the density will be like this [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, ...]
level = math.floor(i / 3)
return (10**level) * DENSITY[i % 3]
def get_current_mouse_coords() -> Tuple[float, float]:
app_window = omni.appwindow.get_default_app_window()
input = carb.input.acquire_input_interface()
dpi_scale = ui.Workspace.get_dpi_scale()
pos_x, pos_y = input.get_mouse_coords_pixel(app_window.get_mouse())
return pos_x / dpi_scale, pos_y / dpi_scale
class ActivityChart:
"""The widget that represents the activity viewer"""
def __init__(self, model, activity_menu: ActivityMenuOptions = None, **kwargs):
self.__model = None
self.__packed_model = None
self.__filter_model = None
# Widgets
self.__timeline_frame = None
self.__selection_frame = None
self.__chart_graph = None
self.__chart_tree = None
self._activity_menu_option = activity_menu
# Timeline Zoom
self.__zoom_level = 100
self.__delegate = kwargs.pop("delegate", None) or ActivityDelegate(
on_expand=partial(ActivityChart.__on_timeline_expand, weakref.proxy(self)),
)
self.__tree_delegate = ActivityTreeDelegate(
on_expand=partial(ActivityChart.__on_treeview_expand, weakref.proxy(self)),
initialize_expansion=partial(ActivityChart.__initialize_expansion, weakref.proxy(self)),
)
self.density = 3
self.__frame = ui.Frame(
build_fn=partial(self.__build, model),
style={"ActivityBar": {"border_color": cl(0.25), "secondary_selected_color": cl.white, "border_width": 1}},
)
# Selection
self.__is_selection = False
self.__selection_from = None
self.__selection_to = None
# Pan/zoom
self.__pan_x_start = None
self.width = None
def destroy(self):
self.__model = None
if self.__packed_model:
self.__packed_model.destroy()
if self.__filter_model:
self.__filter_model.destroy()
if self.__delegate:
self.__delegate.destroy()
self.__delegate = None
self.__tree_delegate = None
def invalidate(self): # pragma: no cover
"""Rebuild all"""
# TODO: Do we need it?
self.__frame.rebuild()
def new(self, model=None):
"""Recreate the models and start recording"""
if self.__packed_model:
self.__packed_model.destroy()
if self.__filter_model:
self.__filter_model.destroy()
self.__model = model
if self.__model:
self.__packed_model = ActivityPackModel(
self.__model,
on_timeline_changed=partial(ActivityChart.__on_timeline_changed, weakref.proxy(self)),
on_selection_changed=partial(ActivityChart.__on_selection_changed, weakref.proxy(self)),
)
self.__filter_model = ActivityFilterModel(self.__model)
self.__apply_models()
self.__on_timeline_changed()
else:
if self.__chart_graph:
self.__chart_graph.dirty_widgets()
if self.__chart_tree:
self.__chart_tree.dirty_widgets()
def save_for_report(self):
return self.__model.get_report_data()
def __build(self, model):
"""Build the whole UI"""
if self._activity_menu_option:
self._options_menu = ui.Menu("Options")
with self._options_menu:
ui.MenuItem("Open...", triggered_fn=self._activity_menu_option.menu_open)
ui.MenuItem("Save...", triggered_fn=self._activity_menu_option.menu_save)
with ui.VStack():
self.__build_title()
self.__build_body()
self.__build_footer()
self.new(model)
def __build_title(self):
"""Build the top part of the widget"""
pass
def __zoom_horizontally(self, x: float, y: float, modifiers: int):
scale = 1.1**y
self.__zoom_level *= scale
self.__range_placer.width = ui.Percent(self.__zoom_level)
self.__timeline_placer.width = ui.Percent(self.__zoom_level)
# do an offset pan, so the zoom looks like happened at the mouse coordinate
origin = self.__range_frame.screen_position_x
pox_x, pos_y = get_current_mouse_coords()
offset = (pox_x - origin - self.__range_placer.offset_x) * (scale - 1)
self.__range_placer.offset_x -= offset
self.__timeline_placer.offset_x -= offset
if self.__relax_timeline():
self.__timeline_indicator.rebuild()
def __relax_timeline(self):
if self.width is None:
return
width = self.__timeline_placer.computed_width * self.width / get_density(self.density)
if width < 25 and self.density > 0:
self.density -= 1
return True
elif width > 50:
self.density += 1
return True
return False
def __selection_changed(self, selection):
"""
Called from treeview selection change, update the timeline selection
"""
if not selection:
return
# avoid selection loop
if self.__packed_model.selection and selection[0] == self.__packed_model.selection:
return
self.__delegate.select_range(selection[0], self.__packed_model)
self.selection_on_stage(selection[0])
def selection_on_stage(self, item):
if not item:
return
path = item.name_model.as_string
# skip the one which is cached locally
if path.startswith("file:"):
return
elif path.endswith("instance)"):
path = path.split(" ")[0]
usd_context = omni.usd.get_context()
usd_context.get_selection().set_selected_prim_paths([path], True)
def show_stack_from_idx(self, idx):
if idx == 0:
self._activity_stack.visible = False
self._timeline_stack.visible = True
elif idx == 1:
self._activity_stack.visible = True
self._timeline_stack.visible = False
def __build_body(self):
"""Build the middle part of the widget"""
self._collection = ui.RadioCollection()
with ui.VStack():
with ui.HStack(height=30):
ui.Spacer()
tab0 = ui.RadioButton(
text="Timeline",
width=0,
radio_collection=self._collection)
ui.Spacer(width=12)
with ui.VStack(width=3):
ui.Spacer()
ui.Rectangle(name="separator", height=16)
ui.Spacer()
ui.Spacer(width=12)
tab1 = ui.RadioButton(
text="Activities",
width=0,
radio_collection=self._collection)
ui.Spacer()
ui.Button(name="options", width=20, height=20, clicked_fn=lambda: self._options_menu.show())
with ui.ZStack():
self.__build_timeline_stack()
self.__build_activity_stack()
self._activity_stack.visible = False
tab0.set_clicked_fn(lambda: self.show_stack_from_idx(0))
tab1.set_clicked_fn(lambda: self.show_stack_from_idx(1))
def __timeline_right_pressed(self, x, y, button, modifier):
if button != 1:
return
# make to separate this from middle mouse selection
self.__is_selection = False
self.__pan_x_start = x
self.__pan_y_start = y
def __timeline_pan(self, x, y):
if self.__pan_x_start is None:
return
self.__pan_x_end = x
moved_x = self.__pan_x_end - self.__pan_x_start
self.__range_placer.offset_x += moved_x
self.__timeline_placer.offset_x += moved_x
self.__pan_x_start = x
self.__pan_y_end = y
moved_y = min(self.__pan_y_start - self.__pan_y_end, self.__range_frame.scroll_y_max)
self.__range_frame.scroll_y += moved_y
self.__pan_y_start = y
def __timeline_right_moved(self, x, y, modifier, button):
if button or self.__is_selection:
return
self.__timeline_pan(x, y)
def __timeline_right_released(self, x, y, button, modifier):
if button != 1 or self.__pan_x_start is None:
return
self.__timeline_pan(x, y)
self.__pan_x_start = None
def __build_timeline_stack(self):
self._timeline_stack = ui.VStack()
with self._timeline_stack:
with ui.ZStack():
with ui.VStack():
ui.Rectangle(height=36, name="spacer")
self.__range_frame = ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
mouse_wheel_fn=self.__zoom_horizontally)
with self.__range_frame:
self.__range_placer = ui.Placer()
with self.__range_placer:
# Chart view
self.__chart_graph = ui.TreeView(
self.__packed_model,
delegate=self.__delegate,
root_visible=False,
header_visible=True,
column_widths=[ui.Fraction(1), 0, 0, 0, 0]
)
with ui.HStack():
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
):
self.__timeline_placer = ui.Placer(
mouse_pressed_fn=self.__timeline_right_pressed,
mouse_released_fn=self.__timeline_right_released,
mouse_moved_fn=self.__timeline_right_moved,
)
with self.__timeline_placer:
# It's in placer to prevent the whole ZStack from changing size
self.__timeline_frame = ui.Frame(build_fn=self.__build_timeline)
# this is really a trick to show self.__range_frame's vertical scrollbar, and 12 is the
# kScrollBarWidth of scrollingFrame, so that we can pan vertically for the timeline
scrollbar_width = 12 * ui.Workspace.get_dpi_scale()
ui.Spacer(width=scrollbar_width)
def __build_activity_stack(self):
# TreeView with all the activities
self._activity_stack = ui.VStack()
with self._activity_stack:
with ui.ScrollingFrame():
self.__chart_tree = ui.TreeView(
self.__filter_model,
delegate=self.__tree_delegate,
root_visible=False,
header_visible=True,
column_widths=[ui.Fraction(1), 60, 60, 60, 60],
columns_resizable=True,
selection_changed_fn=self.__selection_changed,
)
def __build_footer(self):
"""Build the bottom part of the widget"""
pass
def __build_timeline(self):
"""Build the timeline on top of the chart"""
if self.__packed_model:
time_begin = self.__packed_model._time_begin
time_end = self.__packed_model._time_end
self.time_length = (time_end - time_begin) / SECOND_MULTIPLIER
else:
self.time_length = TIMELINE_EXTEND_DELAY_SEC
self.time_step = max(math.floor(self.time_length / 5.0), 1.0)
self.width = self.time_step / self.time_length
with ui.ZStack():
self.__timeline_indicator = ui.Frame(build_fn=self.__build_time_indicator)
self.__selection_frame = ui.Frame(
build_fn=self.__build_selection,
mouse_pressed_fn=self.__timeline_middle_pressed,
mouse_released_fn=self.__timeline_middle_released,
mouse_moved_fn=self.__timeline_middle_moved,
)
def __build_time_indicator(self):
density = get_density(self.density)
counts = math.floor(self.time_length / self.time_step) * density
# put a cap on the indicator numbers. Otherwise, it hits the imgui prims limits and cause crash
if counts > 10000:
carb.log_warn("Zoom level is too high to show the time indicator")
return
width = ui.Percent(self.width / density * 100)
with ui.VStack():
with ui.Placer(offset_x=-0.5 * width, height=0):
with ui.HStack():
for i in range(math.floor(counts / 5)):
ui.Label(f" {i * 5 * self.time_step / density} s", name="time", width=width * 5)
with ui.HStack():
for i in range(counts):
if i % 10 == 0:
height = 36
elif i % 5 == 0:
height = 24
else:
height = 12
ui.Line(alignment=ui.Alignment.LEFT, height=height, name="timeline", width=width)
def __build_selection(self):
"""Build the selection widgets on top of the chart"""
if self.__selection_from is None or self.__selection_to is None or self.__selection_from == self.__selection_to:
ui.Spacer()
return
if self.__packed_model is None:
return
time_begin = self.__packed_model._time_begin
time_end = self.__packed_model._time_end
selection_from = min(self.__selection_from, self.__selection_to)
selection_to = max(self.__selection_from, self.__selection_to)
with ui.HStack():
ui.Spacer(width=ui.Fraction(selection_from - time_begin))
with ui.ZStack(width=ui.Fraction(selection_to - selection_from)):
ui.Rectangle(name="selected_area")
ui.Label(
f"{(selection_from - time_begin) / SECOND_MULTIPLIER:.2f}",
height=0, elided_text=True, elided_text_str="", name="selection_time")
ui.Label(
f"< {(selection_to - selection_from) / SECOND_MULTIPLIER:.2f} s >",
height=0, elided_text=True, elided_text_str="", name="selection_time", alignment=ui.Alignment.CENTER)
ui.Label(
f"{(selection_to - time_begin) / SECOND_MULTIPLIER:.2f}",
width=ui.Fraction(time_end - selection_to), height=0,
elided_text=True, elided_text_str="", name="selection_time")
def __on_timeline_changed(self):
"""
Called to resubmit timeline because the global time range is
changed.
"""
if self.__chart_graph:
# Update visible widgets
self.__chart_graph.dirty_widgets()
if self.__timeline_frame:
self.__relax_timeline()
self.__timeline_frame.rebuild()
def __on_selection_changed(self):
"""
Called from timeline selection change, update the treeview selection
"""
selection = self.__packed_model.selection
self.__chart_tree.selection = [selection]
self.selection_on_stage(selection)
def __on_timeline_expand(self, item, range_item, recursive):
"""Called from the timeline when it wants to expand something"""
if self.__chart_graph:
expanded = not self.__chart_graph.is_expanded(item)
self.__chart_graph.set_expanded(item, expanded, recursive)
# Expand the bottom tree view as well.
if expanded != self.__chart_tree.is_expanded(range_item):
self.__chart_tree.set_expanded(range_item, expanded, recursive)
def __initialize_expansion(self, item, expanded):
# expand the treeview
if self.__chart_tree:
if expanded != self.__chart_tree.is_expanded(item):
self.__chart_tree.set_expanded(item, expanded, False)
# expand the timeline
if self.__chart_graph:
pack_item = item._packItem
if pack_item and expanded != self.__chart_graph.is_expanded(pack_item):
self.__chart_graph.set_expanded(pack_item, expanded, False)
def __on_treeview_expand(self, range_item):
"""Called from the treeview when it wants to expand something"""
# this callback is triggered when the branch is pressed, so the expand status will be opposite of the current
# expansion status
if self.__chart_tree:
expanded = not self.__chart_tree.is_expanded(range_item)
# expand the timeline as well
item = range_item._packItem
if item and expanded != self.__chart_graph.is_expanded(item):
self.__chart_graph.set_expanded(item, expanded, False)
def __timeline_middle_pressed(self, x, y, button, modifier):
if button != 2:
return
self.__is_selection = True
if self.__packed_model is None:
return
width = self.__selection_frame.computed_width
origin = self.__selection_frame.screen_position_x
time_begin = self.__packed_model._time_begin
time_end = self.__packed_model._time_end
self.__selection_from_pos_x = x
self.__selection_from = time_begin + (x - origin) / width * (time_end - time_begin)
self.__selection_from = max(self.__selection_from, time_begin)
self.__selection_from = min(self.__selection_from, time_end)
def __timeline_middle_moved(self, x, y, modifier, button):
if button or not self.__is_selection or self.__packed_model is None:
return
width = self.__selection_frame.computed_width
if width == 0:
return
origin = self.__selection_frame.screen_position_x
time_begin = self.__packed_model._time_begin
time_end = self.__packed_model._time_end
self.__selection_to = time_begin + (x - origin) / width * (time_end - time_begin)
self.__selection_to = max(self.__selection_to, time_begin)
self.__selection_to = min(self.__selection_to, time_end)
self.__selection_frame.rebuild()
def __timeline_middle_released(self, x, y, button, modifier):
if button != 2 or not self.__is_selection or self.__packed_model is None:
return
self.__selection_to_pos_x = x
width = self.__selection_frame.computed_width
origin = self.__selection_frame.screen_position_x
time_begin = self.__packed_model._time_begin
time_end = self.__packed_model._time_end
self.__selection_to = time_begin + (x - origin) / width * (time_end - time_begin)
self.__selection_to = max(self.__selection_to, time_begin)
self.__selection_to = min(self.__selection_to, time_end)
self.__selection_frame.rebuild()
self.__timeline_selected()
self.__is_selection = False
def __zoom_to_fit_selection(self):
time_begin = self.__packed_model._time_begin
time_end = self.__packed_model._time_end
selection_from = self.__filter_model.timerange_begin
selection_to = self.__filter_model.timerange_end
pre_zoom_level = self.__zoom_level
zoom_level = (time_end - time_begin) / float(selection_to - selection_from) * 100
# zoom
self.__zoom_level = zoom_level
self.__range_placer.width = ui.Percent(self.__zoom_level)
self.__timeline_placer.width = ui.Percent(self.__zoom_level)
# offset pan
origin = self.__selection_frame.screen_position_x
start = min(self.__selection_to_pos_x, self.__selection_from_pos_x)
offset = (start - origin) * zoom_level / float(pre_zoom_level) + self.__range_placer.offset_x
self.__range_placer.offset_x -= offset
self.__timeline_placer.offset_x -= offset
def __timeline_selected(self):
if self.__selection_from is None or self.__selection_to is None or self.__selection_from == self.__selection_to:
# Deselect
self.__filter_model.timerange_begin = None
self.__filter_model.timerange_end = None
return
self.__filter_model.timerange_begin = min(self.__selection_from, self.__selection_to)
self.__filter_model.timerange_end = max(self.__selection_from, self.__selection_to)
self.__zoom_to_fit_selection()
def __apply_models(self):
if self.__chart_graph:
self.__chart_graph.model = self.__packed_model
if self.__chart_tree:
self.__chart_tree.model = self.__filter_model
| 22,146 | Python | 38.689964 | 121 | 0.568771 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_model.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ActivityModel"]
from dataclasses import dataclass
from functools import lru_cache
from omni.ui import color as cl
from typing import Dict, List, Optional, Set
from .style import get_shade_from_name
import asyncio
import carb
import contextlib
import functools
import omni.activity.core
import omni.ui as ui
import traceback
import weakref
TIMELINE_EXTEND_DELAY_SEC = 5.0
SECOND_MULTIPLIER = 10000000
SMALL_ACTIVITY_THRESHOLD = 0.001
time_begin = 0
time_end = 0
@lru_cache()
def get_color_from_name(name: str):
return get_shade_from_name(name)
def get_default_metadata(name):
return {"name": name, "color": int(get_color_from_name(name))}
def handle_exception(func):
"""
Decorator to print exception in async functions
TODO: The alternative way would be better, but we want to use traceback.format_exc for better error message.
result = await asyncio.gather(*[func(*args)], return_exceptions=True)
"""
@functools.wraps(func)
async def wrapper(*args, **kwargs):
try:
return await func(*args, **kwargs)
except asyncio.CancelledError:
# We always cancel the task. It's not a problem.
pass
except Exception as e:
carb.log_error(f"Exception when async '{func}'")
carb.log_error(f"{e}")
carb.log_error(f"{traceback.format_exc()}")
return wrapper
async def event_wait(evt, timeout):
# Suppress TimeoutError because we'll return False in case of timeout
with contextlib.suppress(asyncio.TimeoutError):
await asyncio.wait_for(evt.wait(), timeout)
return evt.is_set()
@handle_exception
async def loop_forever_async(refresh_rate: float, stop_event: asyncio.Event, callback):
"""Forever loop with the ability to stop"""
while not await event_wait(stop_event, refresh_rate):
# Do something
callback()
@dataclass
class ActivityModelEvent:
"""Atomic event"""
type: omni.activity.core.EventType
time: int
payload: dict
@dataclass
class TimeRange:
"""Values or a timerange"""
item: ui.AbstractItem
begin: int
end: int
metadata: dict
class ActivityModelItem(ui.AbstractItem):
def __init__(self, name: str, parent):
super().__init__()
self.parent = parent
self.name_model = ui.SimpleStringModel(name)
self.events: List[ActivityModelEvent] = []
self.children: List[ActivityModelItem] = []
self.child_to_id: Dict[str, int] = {}
# We need it for hash
parent_path = parent.path if parent else ""
self.path = parent_path + "->" + name
if parent_path == "->Root->Textures->Load" or parent_path == "->Root->Textures->Queue":
self.icon_name = "texture"
elif parent_path == "->Root->Materials":
self.icon_name = "material"
elif parent_path == "->Root->USD->Read" or parent_path == "->Root->USD->Resolve":
self.icon_name = "USD"
else:
self.icon_name = "undefined"
self.max_time_cached = None
# True when ended
self.ended = True
# Time range when the item is active
self.__child_timerange_dirty = True
self.__dirty_event_id: Optional[int] = None
self.__timerange_cache: List[TimeRange] = []
self.__total_time: int = 0
self.__size = 0
self.__children_size = 0
self._packItem = None
def __hash__(self):
return hash(self.path)
def __eq__(self, other):
return self.path == other.path
def __repr__(self):
return "<ActivityModelItem '" + self.name_model.as_string + "'>"
@property
def loaded_children_num(self):
res = 0
for c in self.children:
if c.ended:
res += 1
return res
@property
def time_range(self) -> List[TimeRange]:
"""Return the time ranges when the item was active"""
if self.events:
# Check if it's not dirty and is not read from the json
if self.__dirty_event_id is None and self.__timerange_cache:
return self.__timerange_cache
dirty_event_id = self.__dirty_event_id
self.__dirty_event_id = None
if self.__timerange_cache:
time_range = self.__timerange_cache.pop(-1)
else:
time_range = None
# Iterate the new added events
for event in self.events[dirty_event_id:]:
if event.type == omni.activity.core.EventType.ENDED or event.type == omni.activity.core.EventType.UPDATED:
if time_range is None:
# Can't end or update if it's not started
continue
time_range.end = event.time
else:
if time_range and event.type == omni.activity.core.EventType.BEGAN and time_range.end != 0:
# The latest event is ended. We can add it to the cache.
self.__timerange_cache.append(time_range)
time_range = None
if time_range is None:
global time_begin
time_range = TimeRange(self, 0, 0, get_default_metadata(self.name_model.as_string))
time_range.begin = max(event.time, time_begin)
if "size" in event.payload:
prev_size = self.__size
self.__size = event.payload["size"]
loaded_size = self.__size - prev_size
if loaded_size > 0:
self.parent.__children_size += loaded_size
if time_range:
if time_range.end == 0:
# Range did not end, set to the end of the capture.
global time_end
time_range.end = max(time_end, time_range.begin)
if time_range.end < time_range.begin:
# Bad data, range ended before it began.
time_range.end = time_range.begin
self.__timerange_cache.append(time_range)
elif self.children:
# Check if it's not dirty
if not self.__child_timerange_dirty:
return self.__timerange_cache
self.__child_timerange_dirty = False
# Create ranges out of children
min_begin = None
max_end = None
for child in self.children:
time_range = child.time_range
if time_range:
if min_begin is None:
min_begin = time_range[0].begin
else:
min_begin = min(min_begin, time_range[0].begin)
if max_end is None:
max_end = time_range[-1].end
else:
max_end = max(max_end, time_range[-1].end)
if min_begin is not None and max_end is not None:
if self.__timerange_cache:
time_range_cache = self.__timerange_cache[0]
time_range_cache.begin = min_begin
time_range_cache.end = max_end
else:
time_range_cache = TimeRange(
self, min_begin, max_end, get_default_metadata(self.name_model.as_string)
)
if not self.__timerange_cache:
self.__timerange_cache.append(time_range_cache)
# TODO: optimize
self.__total_time = 0
for timerange in self.__timerange_cache:
self.__total_time += timerange.end - timerange.begin
return self.__timerange_cache
@property
def total_time(self):
"""Return the time ranges when the item was active"""
if self.__dirty_event_id is not None:
# Recache
_ = self.time_range
return self.__total_time
@property
def size(self):
"""Return the size of the item"""
return self.__size
@size.setter
def size(self, val):
self.__size = val
@property
def children_size(self):
return self.__children_size
@children_size.setter
def children_size(self, val):
self.__children_size = val
def find_or_create_child(self, node):
"""Return the child if it's exists, or creates one"""
name = node.name
child_id = self.child_to_id.get(name, None)
if child_id is None:
created = True
# Create a new item
child_item = ActivityModelItem(name, self)
child_id = len(self.children)
self.child_to_id[name] = child_id
self.children.append(child_item)
else:
created = False
child_item = self.children[child_id]
child_item._update_events(node)
return child_item, created
def _update_events(self, node: omni.activity.core.IEvent):
"""Returns true if the item is ended"""
if not node.event_count:
return
activity_events_count = node.event_count
if activity_events_count > 512:
# We have a problem with the following activities:
#
# IEventStream(RunLoop.update)::push() Event:0
# IEventStream(RunLoop.update)::push() Event:0
# IEventStream(RunLoop.update)::dispatch() Event:0
# IEventStream(RunLoop.update)::dispatch() Event:0
# IEventStream(RunLoop.postUpdate)::push() Event:0
# IEventStream(RunLoop.postUpdate)::push() Event:0
# IEventStream(RunLoop.postUpdate)::dispatch() Event:0
# IEventStream(RunLoop.postUpdate)::dispatch() Event:0
# IEventListener(omni.kit.renderer.plugin.dll!carb::events::LambdaEventListener::onEvent+0x0 at include\carb\events\EventsUtils.h:57)::onEvent
# IEventListener(omni.kit.renderer.plugin.dll!carb::events::LambdaEventListener::onEvent+0x0 at include\carb\events\EventsUtils.h:57)::onEvent
# IEventStream(RunLoop.preUpdate)::push() Event:0
# IEventStream(RunLoop.preUpdate)::push() Event:0
# IEventStream(RunLoop.preUpdate)::dispatch() Event:0
# IEventStream(RunLoop.preUpdate)::dispatch() Event:0
#
# Each of them has 300k events on Factory Explorer startup. (pairs
# of Begin-End with 0 duration). When trying to visualize 300k
# events at once on Python side it fails to do it in adequate time.
# Ignoring such activities saves 15s of startup time.
#
# TODO: But the best would be to not report such activities at all.
activity_events = [node.get_event(0), node.get_event(activity_events_count - 1)]
activity_events_count = 2
else:
activity_events = [node.get_event(e) for e in range(activity_events_count)]
activity_events_filtered = []
# TODO: Temporary. We need to do in in the core
# Filter out BEGAN+ENDED events with the same timestamp
i = 0
# The threshold is 1 ms
threshold = SECOND_MULTIPLIER * SMALL_ACTIVITY_THRESHOLD
while i < activity_events_count:
if (
i + 1 < activity_events_count
and activity_events[i].event_type == omni.activity.core.EventType.BEGAN
and activity_events[i + 1].event_type == omni.activity.core.EventType.ENDED
and activity_events[i + 1].event_timestamp - activity_events[i].event_timestamp < threshold
):
# Skip them
i += 2
elif (
i + 2 < activity_events_count
and activity_events[i].event_type == omni.activity.core.EventType.BEGAN
and activity_events[i + 1].event_type == omni.activity.core.EventType.UPDATED
and activity_events[i + 2].event_type == omni.activity.core.EventType.ENDED
and activity_events[i + 2].event_timestamp - activity_events[i].event_timestamp < threshold
):
# Skip them
i += 3
else:
activity_events_filtered.append(activity_events[i])
i += 1
if self.__dirty_event_id is None:
self.__dirty_event_id = len(self.events)
for activity_event in activity_events_filtered:
self.events.append(
ActivityModelEvent(activity_event.event_type, activity_event.event_timestamp, activity_event.payload)
)
def update_flags(self):
self.ended = not self.events or self.events[-1].type == omni.activity.core.EventType.ENDED
for c in self.children:
self.ended = self.ended and c.ended
if c.__child_timerange_dirty or self.__dirty_event_id is not None:
self.__child_timerange_dirty = True
def update_size(self):
if self.events:
for event in self.events:
if "size" in event.payload:
self.size = event.payload["size"]
def get_data(self):
children = []
for c in self.children:
children.append(c.get_data())
# Events
events = []
for e in self.events:
event = {"time": e.time, "type": e.type.name}
if "size" in e.payload:
event["size"] = self.size
events.append(event)
return {"name": self.name_model.as_string, "children": children, "events": events}
def get_report_data(self):
children = []
for c in self.children:
children.append(c.get_report_data())
data = {
"name": self.name_model.as_string,
"children": children,
"duration": self.total_time / SECOND_MULTIPLIER,
}
for e in self.events:
if "size" in e.payload:
data["size"] = self.size
return data
def set_data(self, data):
"""Recreate the item from the data"""
self.name_model = ui.SimpleStringModel(data["name"])
self.events: List[ActivityModelEvent] = []
for e in data["events"]:
event_type_str = e["type"]
if event_type_str == "BEGAN":
event_type = omni.activity.core.EventType.BEGAN
elif event_type_str == "ENDED":
event_type = omni.activity.core.EventType.ENDED
else: # event_type_str == "UPDATED":
event_type = omni.activity.core.EventType.UPDATED
payload = {}
if "size" in e:
self.size = e["size"]
payload["size"] = e["size"]
self.events.append(ActivityModelEvent(event_type, e["time"], payload))
self.children: List[ActivityModelItem] = []
self.child_to_id: Dict[str, int] = {}
for i, c in enumerate(data["children"]):
child = ActivityModelItem(c["name"], self)
child.set_data(c)
self.children.append(child)
self.child_to_id[c["name"]] = i
class ActivityModel(ui.AbstractItemModel):
"""Empty Activity model"""
class _Event(set):
"""
A list of callable objects. Calling an instance of this will cause a
call to each item in the list in ascending order by index.
"""
def __call__(self, *args, **kwargs):
"""Called when the instance is “called” as a function"""
# Call all the saved functions
for f in list(self):
f(*args, **kwargs)
def __repr__(self):
"""
Called by the repr() built-in function to compute the “official”
string representation of an object.
"""
return f"Event({set.__repr__(self)})"
class _EventSubscription:
"""
Event subscription.
_Event has callback while this object exists.
"""
def __init__(self, event, fn):
"""
Save the function, the event, and add the function to the event.
"""
self._fn = fn
self._event = event
event.add(self._fn)
def __del__(self):
"""Called by GC."""
self._event.remove(self._fn)
def __init__(self, **kwargs):
super().__init__()
self._stage_path = ""
self._root = ActivityModelItem("Root", None)
self.__selection = None
self._on_selection_changed = ActivityModel._Event()
self.__on_selection_changed_sub = self.subscribe_selection_changed(kwargs.pop("on_selection_changed", None))
self._on_timeline_changed = ActivityModel._Event()
self.__on_timeline_changed_sub = self.subscribe_timeline_changed(kwargs.pop("on_timeline_changed", None))
def destroy(self):
self._on_timeline_changed = None
self.__on_timeline_changed_sub = None
self.__selection = None
self._on_selection_changed = None
self.__on_selection_changed_sub = None
def subscribe_timeline_changed(self, fn):
if fn:
return ActivityModel._EventSubscription(self._on_timeline_changed, fn)
def subscribe_selection_changed(self, fn):
if fn:
return ActivityModel._EventSubscription(self._on_selection_changed, fn)
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is None:
return self._root.children
return item.children
def get_item_value_model_count(self, item):
"""The number of columns"""
return 5
def get_item_value_model(self, item, column_id):
"""
Return value model. It's the object that tracks the specific value.
"""
return item.name_model
def get_data(self):
return {"stage": self._stage_path, "root": self._root.get_data(), "begin": self._time_begin, "end": self._time_end}
def get_report_data(self):
return {"root": self._root.get_report_data()}
@property
def selection(self):
return self.__selection
@selection.setter
def selection(self, value):
if not self.__selection or self.__selection != value:
self.__selection = value
self._on_selection_changed()
class ActivityModelDump(ActivityModel):
"""Activity model with pre-defined data"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._data = kwargs.pop("data", [])
self._time_begin = self._data["begin"]
self._time_end = self._data["end"]
# So we can fixup time spans that started early or didn't end.
global time_begin
global time_end
time_begin = self._time_begin
time_end = self._time_end
self._root.set_data(self._data["root"])
def destroy(self):
super().destroy()
class ActivityModelDumpForProgress(ActivityModelDump):
"""Activity model for loaded data with 3 columns"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def get_item_value_model_count(self, item):
"""The number of columns"""
return 3
class ActivityModelRealtime(ActivityModel):
"""The model that accumulates all the activities"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
activity = omni.activity.core.get_instance()
self._subscription = activity.create_callback_to_pop(self._activity)
self._timeline_stop_event = asyncio.Event()
self._timeline_extend_task = asyncio.ensure_future(
loop_forever_async(
TIMELINE_EXTEND_DELAY_SEC,
self._timeline_stop_event,
functools.partial(ActivityModelRealtime.__update_timeline, weakref.proxy(self)),
)
)
self._time_begin = activity.current_timestamp
self._time_end = self._time_begin + int(TIMELINE_EXTEND_DELAY_SEC * SECOND_MULTIPLIER)
self._activity_pump = False
# So we can fixup time spans that started early or didn't end.
global time_begin
global time_end
time_begin = self._time_begin
time_end = self._time_end
def start(self):
self._activity_pump = True
def end(self):
self._activity_pump = False
activity = omni.activity.core.get_instance()
activity.remove_callback(self._subscription)
self._timeline_stop_event.set()
if self._timeline_extend_task:
self._timeline_extend_task.cancel()
self._timeline_extend_task = None
def destroy(self):
super().destroy()
self.end()
def _activity(self, node):
"""Called when the activity happened"""
if self._activity_pump:
self._update_item(self._root, node)
def __update_timeline(self):
"""
Called once a minute to extend the timeline.
"""
activity = omni.activity.core.get_instance()
self._time_end = activity.current_timestamp + int(TIMELINE_EXTEND_DELAY_SEC * SECOND_MULTIPLIER)
# So we can fixup time spans that don't end.
global time_end
time_end = self._time_end
if self._on_timeline_changed:
self._on_timeline_changed()
def _update_item(self, parent, node, depth=0):
"""
Recursively update the item with the activity. Called when the activity
passed to the UI.
"""
item, created = parent.find_or_create_child(node)
events = node.event_count
for node_id in range(node.child_count):
child_events = self._update_item(item, node.get_child(node_id), depth + 1)
# Cascading
events += child_events
item.update_flags()
# If child is created, we need to update the parent
if created:
if parent == self._root:
self._item_changed(None)
else:
self._item_changed(parent)
# If the time/size is changed, we need to update the item
if events:
self._item_changed(item)
return events
class ActivityModelStageOpen(ActivityModelRealtime):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def set_path(self, path):
self._stage_path = path
self.start()
def destroy(self):
super().destroy()
class ActivityModelStageOpenForProgress(ActivityModelStageOpen):
def __init__(self, **kwargs):
self._flattened_children = []
super().__init__(**kwargs)
def destroy(self):
super().destroy()
self._flattened_children = []
def _update_item(self, parent, node, depth=0):
"""
Recursively update the item with the activity. Called when the activity
passed to the UI.
"""
item, created = parent.find_or_create_child(node)
for node_id in range(node.child_count):
self._update_item(item, node.get_child(node_id), depth + 1)
item.update_flags()
if parent.name_model.as_string in ["Read", "Load", "Materials"]: # Should check for "USD|Read" and "Textures|Load" if possible
if not created and item in self._flattened_children:
self._flattened_children.pop(self._flattened_children.index(item))
self._flattened_children.insert(0, item)
# make sure the list only keeps the latest items, so else insert won't be too expensive
if len(self._flattened_children) > 50:
self._flattened_children.pop()
# update the item size and parent's children_size
prev_size = item.size
item.update_size()
loaded_size = item.size - prev_size
if loaded_size > 0:
parent.children_size += loaded_size
# if there is newly created items or new updated size, we update the item
if created or loaded_size > 0:
self._item_changed(parent)
def get_item_value_model_count(self, item):
"""The number of columns"""
return 3
| 24,789 | Python | 32.912449 | 154 | 0.573601 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_menu.py | import carb.input
import omni.client
from omni.kit.widget.filebrowser import FileBrowserItem
from omni.kit.window.filepicker import FilePickerDialog
import json
import os
class ActivityMenuOptions:
def __init__(self, **kwargs):
self._pick_folder_dialog = None
self._current_filename = None
self._current_dir = None
self.load_data = kwargs.pop("load_data", None)
self.get_save_data = kwargs.pop("get_save_data", None)
def destroy(self):
if self._pick_folder_dialog:
self._pick_folder_dialog.destroy()
def __menu_save_apply_filename(self, filename: str, dir: str):
"""Called when the user presses "Save" in the pick filename dialog"""
# don't accept as long as no filename is selected
if not filename or not dir:
return
if self._pick_folder_dialog:
self._pick_folder_dialog.hide()
# add the file extension if missing
extension = filename.split(".")[-1]
filter = "json" if self._pick_folder_dialog and self._pick_folder_dialog.current_filter_option else "activity"
if extension != filter:
filename = filename + "." + filter
self._current_filename = filename
self._current_dir = dir
# add a trailing slash for the client library
if dir[-1] != os.sep:
dir = dir + os.sep
current_export_path = omni.client.combine_urls(dir, filename)
self.save(current_export_path)
def __menu_open_apply_filename(self, filename: str, dir: str):
"""Called when the user presses "Open" in the pick filename dialog"""
# don't accept as long as no filename is selected
if not filename or not dir:
return
if self._pick_folder_dialog:
self._pick_folder_dialog.hide()
# add a trailing slash for the client library
if dir[-1] != os.sep:
dir = dir + os.sep
current_path = omni.client.combine_urls(dir, filename)
if omni.client.stat(current_path)[0] != omni.client.Result.OK:
# add the file extension if missing
extension = filename.split(".")[-1]
filter = "json" if self._pick_folder_dialog and self._pick_folder_dialog.current_filter_option else "activity"
if extension != filter:
filename = filename + "." + filter
current_path = omni.client.combine_urls(dir, filename)
if omni.client.stat(current_path)[0] != omni.client.Result.OK:
# Still can't find
return
self._current_filename = filename
self._current_dir = dir
self.load(current_path)
def __menu_filter_files(self, item: FileBrowserItem) -> bool:
"""Used by pick folder dialog to hide all the files"""
if not item or item.is_folder:
return True
filter = ".json" if self._pick_folder_dialog and self._pick_folder_dialog.current_filter_option else ".activity"
if item.path.endswith(filter):
return True
else:
return False
def menu_open(self):
"""Open "Open" dialog"""
if self._pick_folder_dialog:
self._pick_folder_dialog.destroy()
self._pick_folder_dialog = FilePickerDialog(
"Open...",
allow_multi_selection=False,
apply_button_label="Open",
click_apply_handler=self.__menu_open_apply_filename,
item_filter_options=["ACTIVITY file (*.activity)", "JSON file (*.json)"],
item_filter_fn=self.__menu_filter_files,
current_filename=self._current_filename,
current_directory=self._current_dir,
)
def menu_save(self):
"""Open "Save" dialog"""
if self._pick_folder_dialog:
self._pick_folder_dialog.destroy()
self._pick_folder_dialog = FilePickerDialog(
"Save As...",
allow_multi_selection=False,
apply_button_label="Save",
click_apply_handler=self.__menu_save_apply_filename,
item_filter_options=["ACTIVITY file (*.activity)", "JSON file (*.json)"],
item_filter_fn=self.__menu_filter_files,
current_filename=self._current_filename,
current_directory=self._current_dir,
)
def save(self, filename: str):
"""Save the current model to external file"""
data = self.get_save_data()
if not data:
return
payload = bytes(json.dumps(data, sort_keys=True, indent=4).encode("utf-8"))
if not payload:
return
# Save to the file
result = omni.client.write_file(filename, payload)
if result != omni.client.Result.OK:
carb.log_error(f"[omni.activity.ui] The activity cannot be written to {filename}, error code: {result}")
return
carb.log_info(f"[omni.activity.ui] The activity saved to {filename}")
def load(self, filename: str):
"""Load the model from the file"""
result, _, content = omni.client.read_file(filename)
if result != omni.client.Result.OK:
carb.log_error(f"[omni.activity.ui] Can't read the activity file {filename}, error code: {result}")
return
data = json.loads(memoryview(content).tobytes().decode("utf-8"))
self.load_data(data)
| 5,434 | Python | 35.722973 | 122 | 0.593669 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_window.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ActivityWindow"]
from .activity_chart import ActivityChart
from .style import activity_window_style
import omni.ui as ui
LABEL_WIDTH = 120
SPACING = 4
class ActivityWindow(ui.Window):
"""The class that represents the window"""
def __init__(self, title: str, model, delegate=None, activity_menu=None, **kwargs):
super().__init__(title, raster_policy=ui.RasterPolicy.NEVER, **kwargs)
self.__chart = None
# Apply the style to all the widgets of this window
self.frame.style = activity_window_style
self.deferred_dock_in("Content", ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE)
# Set the function that is called to build widgets when the window is
# visible
self.frame.set_build_fn(lambda: self.__build(model, activity_menu))
def destroy(self):
if self.__chart:
self.__chart.destroy()
# It will destroy all the children
super().destroy()
def _menu_new(self, model=None):
if self.__chart:
self.__chart.new(model)
def get_data(self):
if self.__chart:
return self.__chart.save_for_report()
return None
def __build(self, model, activity_menu):
"""
The method that is called to build all the UI once the window is
visible.
"""
self.__chart = ActivityChart(model, activity_menu)
| 1,828 | Python | 31.087719 | 87 | 0.664114 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_progress_bar.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ActivityProgressBarWindow"]
import omni.ui as ui
from omni.ui import scene as sc
import omni.kit.app
import asyncio
from functools import partial
import math
import pathlib
import weakref
from .style import progress_window_style
from .activity_tree_delegate import ActivityProgressTreeDelegate
from .activity_menu import ActivityMenuOptions
from .activity_progress_model import ActivityProgressModel
TIMELINE_WINDOW_NAME = "Activity Timeline"
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
def convert_seconds_to_hms(sec):
result = ""
rest_sec = sec
h = math.floor(rest_sec / 3600)
if h > 0:
if h < 10:
result += "0"
result += str(h) + ":"
rest_sec -= h * 3600
else:
result += "00:"
m = math.floor(rest_sec / 60)
if m > 0:
if m < 10:
result += "0"
result += str(m) + ":"
rest_sec -= m * 60
else:
result += "00:"
if rest_sec < 10:
result += "0"
result += str(rest_sec)
return result
class Spinner(sc.Manipulator):
def __init__(self, event):
super().__init__()
self.__deg = 0
self.__spinning_event = event
def on_build(self):
self.invalidate()
if self.__spinning_event.is_set():
self.__deg = self.__deg % 360
transform = sc.Matrix44.get_rotation_matrix(0, 0, -self.__deg, True)
with sc.Transform(transform=transform):
sc.Image(f"{EXTENSION_FOLDER_PATH}/data/progress.svg", width=2, height=2)
self.__deg += 3
class ProgressBarWidget:
def __init__(self, model=None, activity_menu=None):
self.__model = None
self.__subscription = None
self._finished_ui_build = False
self.__frame = ui.Frame(build_fn=partial(self.__build, model))
self.__frame.style = progress_window_style
# for the menu
self._activity_menu_option = activity_menu
# for the timer
self._start_event = asyncio.Event()
self._stop_event = asyncio.Event()
self.spinner = None
self._progress_stack = None
def reset_timer(self):
if self._finished_ui_build:
self.total_time.text = "00:00:00"
self._start_event.set()
def stop_timer(self):
self._start_event.clear()
def new(self, model=None):
"""Recreate the models and start recording"""
self.__model = model
self.__subscription = None
self._start_event.clear()
if self.__model:
self.__subscription = self.__model.subscribe_item_changed_fn(self._model_changed)
# this is for the add on widget, no need to update the model if the ui is not ready
if self._finished_ui_build:
self.update_by_model(self.__model)
self.total_time.text = convert_seconds_to_hms(model.duration)
self.__tree.model = self.__model
def destroy(self):
self.__model = None
self.__subscription = None
self.__tree_delegate = None
self.__tree = None
self.usd_number = None
self.material_number = None
self.texture_number = None
self.total_number = None
self.usd_progress = None
self.material_progress = None
self.texture_progress = None
self.total_progress = None
self.current_event = None
self.total_progress_text = None
self._stop_event.set()
def show_stack_from_idx(self, idx):
if idx == 0:
self._activity_stack.visible = False
self._progress_stack.visible = True
elif idx == 1:
self._activity_stack.visible = True
self._progress_stack.visible = False
def update_USD(self, model):
if self._progress_stack:
self.usd_number.text = str(model.usd_loaded_sum) + "/" + str(model.usd_sum)
self.usd_progress.set_value(model.usd_progress)
self.usd_size.text = str(round(model.usd_size, 2)) + " MB"
self.usd_speed.text = str(round(model.usd_speed, 2)) + " MB/sec"
def update_textures(self, model):
if self._progress_stack:
self.texture_number.text = str(model.texture_loaded_sum) + "/" + str(model.texture_sum)
self.texture_progress.set_value(model.texture_progress)
self.texture_size.text = str(round(model.texture_size, 2)) + " MB"
self.texture_speed.text = str(round(model.texture_speed, 2)) + " MB/sec"
def update_materials(self, model):
if self._progress_stack:
self.material_number.text = str(model.material_loaded_sum) + "/" + str(model.material_sum)
self.material_progress.set_value(model.material_progress)
def update_total(self, model):
if self._progress_stack:
self.total_number.text = "Total: " + str(model.total_loaded_sum) + "/" + str(model.total_sum)
self.total_progress.set_value(model.total_progress)
self.total_progress_text.text = f"{model.total_progress * 100 :.2f}%"
if model.latest_item:
self.current_event.text = "Loading " + model.latest_item
elif model.latest_item is None:
self.current_event.text = "Done"
else:
self.current_event.text = ""
def update_by_model(self, model):
self.update_USD(model)
self.update_textures(model)
self.update_materials(model)
self.update_total(model)
if self._progress_stack:
self.total_time.text = convert_seconds_to_hms(model.duration)
def _model_changed(self, model, item):
self.update_by_model(model)
def progress_stack(self):
self._progress_stack = ui.VStack()
with self._progress_stack:
ui.Spacer(height=15)
with ui.HStack():
ui.Spacer(width=20)
with ui.VStack(spacing=4):
with ui.HStack(height=30):
ui.ImageWithProvider(style_type_name_override="Icon", name="USD", width=23)
ui.Label(" USD", width=50)
ui.Spacer()
self.usd_size = ui.Label("0 MB", alignment=ui.Alignment.RIGHT_CENTER, width=120)
ui.Spacer()
self.usd_speed = ui.Label("0 MB/sec", alignment=ui.Alignment.RIGHT_CENTER, width=140)
with ui.HStack(height=22):
self.usd_number = ui.Label("0/0", width=60, alignment=ui.Alignment.RIGHT_CENTER)
ui.Spacer(width=10)
self.usd_progress = ui.ProgressBar(name="USD").model
with ui.HStack(height=30):
ui.ImageWithProvider(style_type_name_override="Icon", name="material", width=20)
ui.Label(" Material", width=50)
ui.Spacer()
self.material_size = ui.Label("", alignment=ui.Alignment.RIGHT_CENTER, width=120)
ui.Spacer()
self.material_speed = ui.Label("", alignment=ui.Alignment.RIGHT_CENTER, width=140)
with ui.HStack(height=22):
self.material_number = ui.Label("0/0", width=60, alignment=ui.Alignment.RIGHT_CENTER)
ui.Spacer(width=10)
self.material_progress = ui.ProgressBar(height=22, name="material").model
with ui.HStack(height=30):
ui.ImageWithProvider(style_type_name_override="Icon", name="texture", width=20)
ui.Label(" Texture", width=50)
ui.Spacer()
self.texture_size = ui.Label("0 MB", alignment=ui.Alignment.RIGHT_CENTER, width=120)
ui.Spacer()
self.texture_speed = ui.Label("0 MB/sec", alignment=ui.Alignment.RIGHT_CENTER, width=140)
with ui.HStack(height=22):
self.texture_number = ui.Label("0/0", width=60, alignment=ui.Alignment.RIGHT_CENTER)
ui.Spacer(width=10)
self.texture_progress = ui.ProgressBar(height=22, name="texture").model
ui.Spacer(width=20)
def activity_stack(self):
self._activity_stack = ui.VStack()
self.__tree_delegate = ActivityProgressTreeDelegate()
with self._activity_stack:
ui.Spacer(height=10)
self.__tree = ui.TreeView(
self.__model,
delegate=self.__tree_delegate,
root_visible=False,
header_visible=True,
column_widths=[ui.Fraction(1), 50, 50],
columns_resizable=True,
)
async def infloop(self):
while not self._stop_event.is_set():
await asyncio.sleep(1)
if self._stop_event.is_set():
break
if self._start_event.is_set():
# cant use duration += 1 since when the ui is stuck, the function is not called, so we will get the
# duration wrong
if self.__model:
self.total_time.text = convert_seconds_to_hms(self.__model.duration)
def __build(self, model):
"""
The method that is called to build all the UI once the window is visible.
"""
if self._activity_menu_option:
self._options_menu = ui.Menu("Options")
with self._options_menu:
ui.MenuItem("Show Timeline", triggered_fn=lambda: ui.Workspace.show_window(TIMELINE_WINDOW_NAME))
ui.Separator()
ui.MenuItem("Open...", triggered_fn=self._activity_menu_option.menu_open)
ui.MenuItem("Save...", triggered_fn=self._activity_menu_option.menu_save)
self._collection = ui.RadioCollection()
with ui.VStack():
with ui.HStack(height=30):
ui.Spacer()
tab0 = ui.RadioButton(
text="Progress Bar",
width=0,
radio_collection=self._collection)
ui.Spacer(width=12)
with ui.VStack(width=3):
ui.Spacer()
ui.Rectangle(name="separator", height=16)
ui.Spacer()
ui.Spacer(width=12)
tab1 = ui.RadioButton(
text="Activity",
width=0,
radio_collection=self._collection)
ui.Spacer()
if self._activity_menu_option:
ui.Button(name="options", width=20, height=20, clicked_fn=lambda: self._options_menu.show())
with ui.HStack():
ui.Spacer(width=3)
with ui.ScrollingFrame():
with ui.ZStack():
self.progress_stack()
self.activity_stack()
self._activity_stack.visible = False
ui.Spacer(width=3)
tab0.set_clicked_fn(lambda: self.show_stack_from_idx(0))
tab1.set_clicked_fn(lambda: self.show_stack_from_idx(1))
with ui.HStack(height=70):
ui.Spacer(width=20)
with ui.VStack(width=20):
ui.Spacer(height=12)
with sc.SceneView().scene:
self.spinner = Spinner(self._start_event)
ui.Spacer(width=10)
with ui.VStack():
with ui.HStack(height=30):
self.total_number = ui.Label("Total: 0/0")
self.total_time = ui.Label("00:00:00", width=0, alignment=ui.Alignment.RIGHT_CENTER)
with ui.ZStack(height=22):
self.total_progress = ui.ProgressBar(name="progress").model
with ui.HStack():
ui.Spacer(width=4)
self.current_event = ui.Label("", elided_text=True)
self.total_progress_text = ui.Label("0.00%", width=0, alignment=ui.Alignment.RIGHT_CENTER)
ui.Spacer(width=4)
asyncio.ensure_future(self.infloop())
ui.Spacer(width=35)
self._finished_ui_build = True
# update ui with model, so that we keep tracking of the model even when the widget is not shown
if model:
self.new(model)
if model.start_loading and not model.finish_loading:
self._start_event.set()
class ActivityProgressBarWindow(ui.Window):
"""The class that represents the window"""
def __init__(self, title: str, model, delegate=None, activity_menu=None, **kwargs):
super().__init__(title, raster_policy=ui.RasterPolicy.NEVER, **kwargs)
self.__widget = None
self.deferred_dock_in("Property", ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE)
self.frame.set_build_fn(lambda: self.__build(model, activity_menu))
def destroy(self):
if self.__widget:
self.__widget.destroy()
# It will destroy all the children
super().destroy()
def __build(self, model, activity_menu):
self.__widget = ProgressBarWidget(model, activity_menu=activity_menu)
def new(self, model):
if self.__widget:
self.__widget.new(model)
def start_timer(self):
if self.__widget:
self.__widget.reset_timer()
def stop_timer(self):
if self.__widget:
self.__widget.stop_timer()
| 14,257 | Python | 38.826816 | 118 | 0.553553 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_report.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ActivityReportWindow"]
import asyncio
import omni.kit.app
import omni.ui as ui
from omni.ui import color as cl
import math
import pathlib
from typing import Callable
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
def exec_after_redraw(callback: Callable, wait_frames: int = 2):
async def exec_after_redraw_async(callback: Callable, wait_frames: int):
# Wait some frames before executing
for _ in range(wait_frames):
await omni.kit.app.get_app().next_update_async()
callback()
asyncio.ensure_future(exec_after_redraw_async(callback, wait_frames))
class ReportItem(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, text, value, size, parent):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
self.value_model = ui.SimpleFloatModel(value)
self.size_model = ui.SimpleFloatModel(size)
self.parent = parent
self.children = []
self.filtered_children = []
class ReportModel(ui.AbstractItemModel):
"""
Represents the model for the report
"""
def __init__(self, data, treeview_size):
super().__init__()
self._children = []
self._parents = []
self.root = None
self.load(data)
self._sized_children = self._children[:treeview_size]
def destroy(self):
self._children = []
self._parents = []
self.root = None
self._sized_children = []
def load(self, data):
if data and "root" in data:
self.root = ReportItem("root", 0, 0, None)
self.set_data(data["root"], self.root)
# sort the data with duration
self._children.sort(key=lambda item: item.value_model.get_value_as_float(), reverse=True)
def set_data(self, data, parent):
parent_name = parent.name_model.as_string
for child in data["children"]:
size = child["size"] if "size" in child else 0
item = ReportItem(child["name"], child["duration"], size, parent)
# put the item we cares to the self._children
if parent_name in ["Resolve", "Read", "Meshes", "Textures", "Materials"]:
self._children.append(item)
parent.children.append(item)
self.set_data(child, item)
def get_item_children(self, item):
if item is not None:
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return.
return item.filtered_children
# clear previous results
for p in self._parents:
p.filtered_children = []
self._parents = []
for child in self._sized_children:
parent = child.parent
parent.filtered_children.append(child)
if parent not in self._parents:
self._parents.append(parent)
return self._parents
def get_item_value_model_count(self, item):
"""The number of columns"""
return 2
def get_item_value_model(self, item, column_id):
if column_id == 0:
return item.name_model
else:
return item.value_model
class ReportTreeDelegate(ui.AbstractItemDelegate):
def __init__(self):
super().__init__()
def build_branch(self, model, item, column_id, level, expanded=True):
"""Create a branch widget that opens or closes subtree"""
if column_id == 0:
with ui.HStack(width=20 * (level + 1), height=0):
ui.Spacer()
if model.can_item_have_children(item):
# Draw the +/- icon
image_name = "Minus" if expanded else "Plus"
ui.ImageWithProvider(
f"{EXTENSION_FOLDER_PATH}/data/{image_name}.svg",
width=10,
height=10,
)
ui.Spacer(width=5)
def build_header(self, column_id: int):
headers = ["Name", "Duration (HH:MM:SS)"]
return ui.Label(headers[column_id], height=22)
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per column per item"""
def convert_seconds_to_hms(sec):
result = ""
rest_sec = sec
h = math.floor(rest_sec / 3600)
if h > 0:
if h < 10:
result += "0"
result += str(h) + ":"
rest_sec -= h * 3600
else:
result += "00:"
m = math.floor(rest_sec / 60)
if m > 0:
if m < 10:
result += "0"
result += str(m) + ":"
rest_sec -= m * 60
else:
result += "00:"
if rest_sec < 10:
result += "0"
result += str(rest_sec)
return result
if column_id == 1 and level == 1:
return
value_model = model.get_item_value_model(item, column_id)
value = value_model.as_string
if column_id == 0 and level == 1:
value += " (" + str(len(model.get_item_children(item))) + ")"
elif column_id == 1:
value = convert_seconds_to_hms(value_model.as_int)
with ui.VStack(height=20):
ui.Label(value, elided_text=True)
class ActivityReportWindow(ui.Window):
"""The class that represents the window"""
def __init__(self, title: str, delegate=None, **kwargs):
super().__init__(title, raster_policy=ui.RasterPolicy.NEVER, **kwargs)
self.__expand_task = None
self._current_path = kwargs.pop("path", "")
self._data = kwargs.pop("data", "")
# Set the function that is called to build widgets when the window is visible
self.frame.set_build_fn(self.__build)
def destroy(self):
# It will destroy all the children
super().destroy()
if self.__expand_task is not None:
self.__expand_task.cancel()
self.__expand_task = None
if self._report_model:
self._report_model.destroy()
self._report_model = None
def __build(self):
"""
The method that is called to build all the UI once the window is
visible.
"""
treeview_size = 10
def set_treeview_size(model, size):
model._sized_children = model._children[:size]
model._item_changed(None)
with ui.VStack():
ui.Label(f"Report for opening {self._current_path}", height=70, alignment=ui.Alignment.CENTER)
self._report_model = ReportModel(self._data, treeview_size)
ui.Line(height=12, style={"color": cl.red})
root_children = []
if self._report_model.root:
root_children = self._report_model.root.children
file_children = []
# time
for child in root_children:
name = child.name_model.as_string
if name in ["USD", "Meshes", "Textures", "Materials"]:
file_children += [child]
with ui.HStack(height=0):
ui.Label(f"Total Time of {name}")
ui.Label(f" {child.value_model.as_string} ")
color = cl.red if child == root_children[-1] else cl.black
ui.Line(height=12, style={"color": color})
# number
for file in file_children:
with ui.HStack(height=0):
name = file.name_model.as_string.split(" ")[0]
ui.Label(f"Total Number of {name}")
ui.Label(f" {len(file.children)} ")
color = cl.red if file == file_children[-1] else cl.black
ui.Line(height=12, style={"color": color})
# size
for file in file_children:
size = 0
for c in file.children:
s = c.size_model.as_float
if s > 0:
size += s
with ui.HStack(height=0):
name = file.name_model.as_string.split(" ")[0]
ui.Label(f"Total Size of {name} (MB)")
ui.Label(f" {size * 0.000001} ")
color = cl.red if file == file_children[-1] else cl.black
ui.Line(height=12, style={"color": color})
ui.Spacer(height=10)
# field which can change the size of the treeview
with ui.HStack(height=0):
ui.Label("The top ", width=0)
field = ui.IntField(width=60)
field.model.set_value(treeview_size)
ui.Label(f" most time consuming task{'s' if treeview_size > 1 else ''}")
ui.Spacer(height=3)
# treeview
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
style={"Field": {"background_color": cl.black}},
):
self._name_value_delegate = ReportTreeDelegate()
self.treeview = ui.TreeView(
self._report_model,
delegate=self._name_value_delegate,
root_visible=False,
header_visible=True,
column_widths=[ui.Fraction(1), 130],
columns_resizable=True,
style={"TreeView.Item": {"margin": 4}},
)
field.model.add_value_changed_fn(lambda m: set_treeview_size(self._report_model, m.get_value_as_int()))
def expand_collections():
for item in self._report_model.get_item_children(None):
self.treeview.set_expanded(item, True, False)
# Finally, expand collection nodes in treeview after UI becomes ready
self.__expand_task = exec_after_redraw(expand_collections, wait_frames=2)
| 10,714 | Python | 36.465035 | 119 | 0.541628 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/tests/test_window.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["TestWindow"]
import json
import unittest
from omni.activity.ui.activity_extension import get_instance
from omni.activity.ui.activity_menu import ActivityMenuOptions
from omni.activity.ui import ActivityWindow, ActivityWindowExtension, ActivityProgressBarWindow
from omni.activity.ui.activity_model import ActivityModelRealtime, ActivityModelDumpForProgress
from omni.activity.ui.activity_progress_model import ActivityProgressModel
from omni.activity.ui.activity_report import ActivityReportWindow
from omni.ui.tests.test_base import OmniUiTest
import omni.kit.ui_test as ui_test
from omni.kit.ui_test.input import emulate_mouse, emulate_mouse_slow_move, human_delay
from omni.ui import color as cl
from ..style import get_shade_from_name
from pathlib import Path
from unittest.mock import MagicMock
import omni.client
import omni.usd
import omni.kit.app
import omni.kit.test
import math
from carb.input import KeyboardInput, MouseEventType
EXTENSION_FOLDER_PATH = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__))
TEST_DATA_PATH = EXTENSION_FOLDER_PATH.joinpath("data/tests")
TEST_FILE_NAME = "test.activity"
TEST_SMALL_FILE_NAME = "test_small.activity"
def calculate_duration(events):
duration = 0
for i in range(0, len(events), 2):
if events[i]['type'] == 'BEGAN' and events[i+1]['type'] == 'ENDED':
duration += (events[i+1]['time'] - events[i]['time']) / 10000000
return duration
def add_duration(node):
total_duration = 0
if 'children' in node:
for child in node['children']:
child_duration = add_duration(child)
total_duration += child_duration
if 'events' in child and child['events']:
event_duration = calculate_duration(child['events'])
child['duration'] = event_duration
total_duration += event_duration
node['duration'] = total_duration
return total_duration
def process_json(json_data):
add_duration(json_data['root'])
return json_data
class TestWindow(OmniUiTest):
async def load_data(self, file_name):
filename = TEST_DATA_PATH.joinpath(file_name)
result, _, content = omni.client.read_file(filename.as_posix())
self.assertEqual(result, omni.client.Result.OK)
self._data = json.loads(memoryview(content).tobytes().decode("utf-8"))
async def test_general(self):
"""Testing general look of section"""
menu = ActivityMenuOptions()
model = ActivityModelRealtime()
window = ActivityWindow("Test", model=model, activity_menu=menu)
await omni.kit.app.get_app().next_update_async()
await self.docked_test_window(
window=window,
width=300,
height=385,
)
# Wait for images
for _ in range(20):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="window.png")
self.assertIsNotNone(window.get_data())
window.destroy()
model.destroy()
menu.destroy()
async def test_activity_chart_scroll(self):
menu = ActivityMenuOptions()
model = ActivityModelRealtime()
window = ActivityWindow("Test", model=model, activity_menu=menu)
await omni.kit.app.get_app().next_update_async()
await self.docked_test_window(
window=window,
width=300,
height=385,
block_devices=False,
)
for _ in range(120):
await omni.kit.app.get_app().next_update_async()
self.assertEqual(100, math.floor(window._ActivityWindow__chart._ActivityChart__zoom_level))
await ui_test.emulate_mouse_move(ui_test.Vec2(180, 200), human_delay_speed=3)
await ui_test.emulate_mouse_scroll(ui_test.Vec2(0, 50), human_delay_speed=3)
for _ in range(20):
await omni.kit.app.get_app().next_update_async()
self.assertEqual(101, math.floor(window._ActivityWindow__chart._ActivityChart__zoom_level))
await self.finalize_test_no_image()
# Move outside the window
await ui_test.emulate_mouse_move(ui_test.Vec2(400, 400), human_delay_speed=3)
window.destroy()
model.destroy()
menu.destroy()
async def test_activity_chart_drag(self):
menu = ActivityMenuOptions()
model = ActivityModelRealtime()
window = ActivityWindow("Test", model=model, activity_menu=menu)
await omni.kit.app.get_app().next_update_async()
await self.docked_test_window(
window=window,
width=300,
height=385,
block_devices=False,
)
for _ in range(20):
await omni.kit.app.get_app().next_update_async()
start_pos = ui_test.Vec2(180, 50)
end_pos = ui_test.Vec2(230, 50)
human_delay_speed = 2
await ui_test.emulate_mouse_move(start_pos, human_delay_speed=human_delay_speed)
await emulate_mouse(MouseEventType.MIDDLE_BUTTON_DOWN)
await human_delay(human_delay_speed)
await emulate_mouse_slow_move(start_pos, end_pos, human_delay_speed=human_delay_speed)
await emulate_mouse(MouseEventType.MIDDLE_BUTTON_UP)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="test_activity_chart_drag.png")
# Move outside the window
await ui_test.emulate_mouse_move(ui_test.Vec2(400, 400), human_delay_speed=3)
window.destroy()
model.destroy()
menu.destroy()
async def test_selection(self):
menu = ActivityMenuOptions()
model = ActivityModelRealtime()
window = ActivityWindow("Test", model=model, activity_menu=menu)
await omni.kit.app.get_app().next_update_async()
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
self.assertIsNone(model.selection)
model.selection = 2
self.assertEqual(model.selection, 2)
window.destroy()
model.destroy()
menu.destroy()
async def test_activity_chart_pan(self):
menu = ActivityMenuOptions()
model = ActivityModelRealtime()
window = ActivityWindow("Test", model=model, activity_menu=menu)
await omni.kit.app.get_app().next_update_async()
await self.docked_test_window(
window=window,
width=300,
height=385,
block_devices=False,
)
for _ in range(20):
await omni.kit.app.get_app().next_update_async()
start_pos = ui_test.Vec2(180, 50)
end_pos = ui_test.Vec2(230, 50)
human_delay_speed = 2
await ui_test.emulate_mouse_move(start_pos, human_delay_speed=human_delay_speed)
await emulate_mouse(MouseEventType.RIGHT_BUTTON_DOWN)
await human_delay(human_delay_speed)
await emulate_mouse_slow_move(start_pos, end_pos, human_delay_speed=human_delay_speed)
await emulate_mouse(MouseEventType.RIGHT_BUTTON_UP)
for _ in range(20):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="test_activity_chart_pan.png")
# Move outside the window
await ui_test.emulate_mouse_move(ui_test.Vec2(400, 400), human_delay_speed=3)
window.destroy()
model.destroy()
menu.destroy()
async def test_activities_tab(self):
menu = ActivityMenuOptions()
model = ActivityModelRealtime()
window = ActivityWindow("Test", model=model, activity_menu=menu)
await omni.kit.app.get_app().next_update_async()
await self.docked_test_window(
window=window,
width=300,
height=385,
block_devices=False,
)
for _ in range(20):
await omni.kit.app.get_app().next_update_async()
human_delay_speed = 10
# Click on Activities tab
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(180, 15), human_delay_speed=2)
await human_delay(human_delay_speed)
# Click on Timeline tab
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(100, 15), human_delay_speed=2)
await human_delay(human_delay_speed)
# Click on Activities tab
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(180, 15), human_delay_speed=2)
for _ in range(20):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="test_activities_tab.png")
# Move outside the window
await ui_test.emulate_mouse_move(ui_test.Vec2(400, 400), human_delay_speed=3)
window.destroy()
model.destroy()
menu.destroy()
async def test_activity_menu_open(self):
ext = get_instance()
menu = ActivityMenuOptions(load_data=ext.load_data)
model = ActivityModelRealtime()
window = ActivityWindow("Test", model=model, activity_menu=menu)
window_width = 300
await omni.kit.app.get_app().next_update_async()
await self.docked_test_window(
window=window,
width=window_width,
height=385,
block_devices=False,
)
for _ in range(20):
await omni.kit.app.get_app().next_update_async()
human_delay_speed = 5
# Click on Activity hamburger menu
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(window_width-20, 15), human_delay_speed=2)
await human_delay(human_delay_speed)
# Click on Open menu option
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(window_width-20, 30), human_delay_speed=2)
await human_delay(human_delay_speed)
# Cancel Open dialog
await ui_test.emulate_keyboard_press(KeyboardInput.ESCAPE)
await human_delay(human_delay_speed)
# Do it all again to cover the case where it was open before, and has to be destroyed
# Click on Activity hamburger menu
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(window_width-20, 15), human_delay_speed=2)
await human_delay(human_delay_speed)
# Click on Open menu option
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(window_width-20, 30), human_delay_speed=2)
await human_delay(human_delay_speed)
# Cancel Open dialog
await ui_test.emulate_keyboard_press(KeyboardInput.ESCAPE)
await human_delay(human_delay_speed)
# simulate failure first
menu._ActivityMenuOptions__menu_open_apply_filename("broken_test", str(TEST_DATA_PATH))
await human_delay(human_delay_speed)
self.assertIsNone(menu._current_filename)
# simulate opening the file through file dialog
menu._ActivityMenuOptions__menu_open_apply_filename(TEST_SMALL_FILE_NAME, str(TEST_DATA_PATH))
await human_delay(human_delay_speed)
self.assertIsNotNone(menu._current_filename)
await self.finalize_test_no_image()
# Move outside the window
await ui_test.emulate_mouse_move(ui_test.Vec2(window_width+20, 400), human_delay_speed=3)
ext = None
window.destroy()
model.destroy()
menu.destroy()
async def test_activity_menu_save(self):
ext = get_instance()
# await self.load_data(TEST_SMALL_FILE_NAME)
menu = ActivityMenuOptions(get_save_data=ext.get_save_data)
model = ActivityModelRealtime()
window = ActivityWindow("Test", model=model, activity_menu=menu)
window_width = 300
await omni.kit.app.get_app().next_update_async()
await self.docked_test_window(
window=window,
width=window_width,
height=385,
block_devices=False,
)
for _ in range(20):
await omni.kit.app.get_app().next_update_async()
human_delay_speed = 5
# Click on Activity hamburger menu
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(window_width-20, 15), human_delay_speed=2)
await human_delay(human_delay_speed)
# Click on Save menu option
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(window_width-20, 50), human_delay_speed=2)
await human_delay(human_delay_speed)
# Cancel Open dialog
await ui_test.emulate_keyboard_press(KeyboardInput.ESCAPE)
await human_delay(human_delay_speed)
# Do it all again to cover the case where it was open before, and has to be destroyed
# Click on Activity hamburger menu
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(window_width-20, 15), human_delay_speed=2)
await human_delay(human_delay_speed)
# Click on Save menu option
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(window_width-20, 50), human_delay_speed=2)
await human_delay(human_delay_speed)
# Cancel Open dialog
await ui_test.emulate_keyboard_press(KeyboardInput.ESCAPE)
await human_delay(human_delay_speed)
# Create a mock for omni.client.write_file, so we don't have to actually write out to a file
mock_write_file = MagicMock()
# Set the return value of the mock to omni.client.Result.OK
mock_write_file.return_value = omni.client.Result.OK
# Replace the actual omni.client.write_file with the mock
omni.client.write_file = mock_write_file
# simulate opening the file through file dialog
menu._ActivityMenuOptions__menu_save_apply_filename("test", str(TEST_DATA_PATH))
await human_delay(human_delay_speed)
ext._save_current_activity()
self.assertTrue(ext._ActivityWindowExtension__model)
await self.finalize_test_no_image()
# Move outside the window
await ui_test.emulate_mouse_move(ui_test.Vec2(window_width+20, 400), human_delay_speed=3)
mock_write_file.reset_mock()
ext = None
window.destroy()
model.destroy()
menu.destroy()
async def test_activity_report(self):
"""Testing activity report window"""
await self.load_data(TEST_SMALL_FILE_NAME)
# Adding "duration" data for each child, as the test.activity files didn't already have that
self._data = process_json(self._data)
window = ActivityReportWindow("TestReport", path=TEST_SMALL_FILE_NAME, data=self._data)
await omni.kit.app.get_app().next_update_async()
await self.docked_test_window(
window=window,
width=600,
height=450,
)
# Wait for images
for _ in range(120):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="report_window.png")
window.destroy()
window = None
async def test_progress_window(self):
"""Test progress window with loaded activity"""
await self.load_data(TEST_FILE_NAME)
loaded_model = ActivityModelDumpForProgress(data=self._data)
model = ActivityProgressModel(source=loaded_model)
menu = ActivityMenuOptions()
window = ActivityProgressBarWindow(ActivityWindowExtension.PROGRESS_WINDOW_NAME, model=model, activity_menu=menu)
model.finished_loading()
await omni.kit.app.get_app().next_update_async()
await self.docked_test_window(
window=window,
width=415,
height=355,
block_devices=False,
)
# Wait for images
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
human_delay_speed = 10
window.start_timer()
await human_delay(30)
window.stop_timer()
await human_delay(5)
# Click on Activities tab
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(250, 15), human_delay_speed=2)
await human_delay(human_delay_speed)
# Click on Timeline tab
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(180, 15), human_delay_speed=2)
await human_delay(human_delay_speed)
await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="progress_window.png", threshold=.015)
self.assertIsNotNone(model.get_data())
report_data = loaded_model.get_report_data()
data = loaded_model.get_data()
self.assertIsNotNone(report_data)
self.assertGreater(len(data), len(report_data))
loaded_model.destroy()
model.destroy()
menu.destroy()
window.destroy()
async def test_chart_window_bars(self):
ext = get_instance()
ext.show_window(None, True)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
width = 415
height = 355
await self.docked_test_window(
window=ext._timeline_window,
width=width,
height=height,
block_devices=False,
)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
ext._timeline_window._ActivityWindow__chart._activity_menu_option._ActivityMenuOptions__menu_open_apply_filename(TEST_FILE_NAME, str(TEST_DATA_PATH))
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="chart_window_bars.png")
ext.show_window(None, False)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
ext = None
async def test_chart_window_activities(self):
ext = get_instance()
ext.show_window(None, True)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
width = 415
height = 355
await self.docked_test_window(
window=ext._timeline_window,
width=width,
height=height,
block_devices=False,
)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
ext._timeline_window._ActivityWindow__chart._activity_menu_option._ActivityMenuOptions__menu_open_apply_filename(TEST_FILE_NAME, str(TEST_DATA_PATH))
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
# Click on Activities tab
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(240, 15), human_delay_speed=2)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="chart_window_activities.png")
ext.show_window(None, False)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
ext = None
async def test_extension_start_stop(self):
# Disabling this part in case it is causing crashing in 105.1
# ext = get_instance()
# ext.show_window(None, True)
# for _ in range(10):
# await omni.kit.app.get_app().next_update_async()
manager = omni.kit.app.get_app().get_extension_manager()
ext_id = "omni.activity.ui"
self.assertTrue(ext_id)
self.assertTrue(manager.is_extension_enabled(ext_id))
# ext = None
manager.set_extension_enabled(ext_id, False)
for _ in range(5):
await omni.kit.app.get_app().next_update_async()
self.assertTrue(not manager.is_extension_enabled(ext_id))
manager.set_extension_enabled(ext_id, True)
for _ in range(5):
await omni.kit.app.get_app().next_update_async()
self.assertTrue(manager.is_extension_enabled(ext_id))
async def test_extension_level_progress_bar(self):
ext = get_instance()
ext._show_progress_window()
await human_delay(5)
ext.show_progress_bar(None, False)
await human_delay(5)
ext.show_progress_bar(None, True)
await human_delay(5)
self.assertTrue(ext._is_progress_visible())
ext.show_progress_bar(None, False)
ext = None
async def test_extension_level_window(self):
ext = get_instance()
await human_delay(5)
ext.show_window(None, False)
await human_delay(5)
ext.show_window(None, True)
await human_delay(5)
self.assertTrue(ext._timeline_window.visible)
ext.show_window(None, False)
ext = None
@unittest.skip("Not working in 105.1 as it tests code that is not available there.")
async def test_extension_level_commands(self):
await self.create_test_area(width=350, height=300)
ext = get_instance()
await human_delay(5)
ext._on_command("AddReference", kwargs={})
await human_delay(5)
ext._on_command("CreatePayload", kwargs={})
await human_delay(5)
ext._on_command("CreateSublayer", kwargs={})
await human_delay(5)
ext._on_command("ReplacePayload", kwargs={})
await human_delay(5)
ext._on_command("ReplaceReference", kwargs={})
await human_delay(5)
self.assertTrue(ext._ActivityWindowExtension__activity_started)
# Create a mock event object
event = MagicMock()
event.type = int(omni.usd.StageEventType.ASSETS_LOADED)
ext._on_stage_event(event)
self.assertFalse(ext._ActivityWindowExtension__activity_started)
event.type = int(omni.usd.StageEventType.OPENING)
ext._on_stage_event(event)
self.assertTrue(ext._ActivityWindowExtension__activity_started)
event.type = int(omni.usd.StageEventType.OPEN_FAILED)
ext._on_stage_event(event)
self.assertFalse(ext._ActivityWindowExtension__activity_started)
# This method doesn't exist in 105.1
ext.show_asset_load_prompt()
await human_delay(20)
self.assertTrue(ext._asset_prompt.is_visible())
ext._asset_prompt.set_text("Testing, testing")
await human_delay(20)
await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="asset_load_prompt.png")
ext.hide_asset_load_prompt()
event.reset_mock()
ext = None
async def test_styles(self):
# full name comparisons
self.assertEqual(get_shade_from_name("USD"), cl("#2091D0"))
self.assertEqual(get_shade_from_name("Read"), cl("#1A75A8"))
self.assertEqual(get_shade_from_name("Resolve"), cl("#16648F"))
self.assertEqual(get_shade_from_name("Stage"), cl("#d43838"))
self.assertEqual(get_shade_from_name("Render Thread"), cl("#d98927"))
self.assertEqual(get_shade_from_name("Execute"), cl("#A2661E"))
self.assertEqual(get_shade_from_name("Post Sync"), cl("#626262"))
self.assertEqual(get_shade_from_name("Textures"), cl("#4FA062"))
self.assertEqual(get_shade_from_name("Load"), cl("#3C784A"))
self.assertEqual(get_shade_from_name("Queue"), cl("#31633D"))
self.assertEqual(get_shade_from_name("Materials"), cl("#8A6592"))
self.assertEqual(get_shade_from_name("Compile"), cl("#5D4462"))
self.assertEqual(get_shade_from_name("Create Shader Variations"), cl("#533D58"))
self.assertEqual(get_shade_from_name("Load Textures"), cl("#4A374F"))
self.assertEqual(get_shade_from_name("Meshes"), cl("#626262"))
self.assertEqual(get_shade_from_name("Ray Tracing Pipeline"), cl("#8B8000"))
# startswith comparisons
self.assertEqual(get_shade_from_name("Opening_test"), cl("#A12A2A"))
# endswith comparisons
self.assertEqual(get_shade_from_name("test.usda"), cl("#13567B"))
self.assertEqual(get_shade_from_name("test.hdr"), cl("#34A24E"))
self.assertEqual(get_shade_from_name("test.png"), cl("#2E9146"))
self.assertEqual(get_shade_from_name("test.jpg"), cl("#2B8741"))
self.assertEqual(get_shade_from_name("test.JPG"), cl("#2B8741"))
self.assertEqual(get_shade_from_name("test.ovtex"), cl("#287F3D"))
self.assertEqual(get_shade_from_name("test.dds"), cl("#257639"))
self.assertEqual(get_shade_from_name("test.exr"), cl("#236E35"))
self.assertEqual(get_shade_from_name("test.wav"), cl("#216631"))
self.assertEqual(get_shade_from_name("test.tga"), cl("#1F5F2D"))
self.assertEqual(get_shade_from_name("test.mdl"), cl("#76567D"))
# "in" comparisons
self.assertEqual(get_shade_from_name('(test instance) 5'), cl("#694D6F"))
# anything else
self.assertEqual(get_shade_from_name("random_test_name"), cl("#555555"))
| 25,414 | Python | 36.989537 | 157 | 0.635831 |
omniverse-code/kit/exts/omni.activity.ui/docs/CHANGELOG.md | # Changelog
## [1.0.20] - 2023-02-08
### Fixed
- total duration not correct in progress window
## [1.0.19] - 2023-01-05
### Fixed
- merge issue caused by the diff between the cherry pick MR (https://gitlab-master.nvidia.com/omniverse/kit/-/merge_requests/21206) and the original MR (https://gitlab-master.nvidia.com/omniverse/kit/-/merge_requests/21171)
## [1.0.18] - 2022-12-08
### Fixed
- try to open non-exsited URL, the spinner is always rotationg by using OPEN_FAILED event (OM-73934)
## [1.0.17] - 2022-12-05
### Changed
- Fixed pinwheel slightly offset from loading bar (OM-74619)
- Added padding on the tree view header (OM-74828)
## [1.0.16] - 2022-11-30
### Fixed
- Updated to use omni.kit.menu.utils
## [1.0.15] - 2022-11-25
### Fixed
- when new stage is created or new stage is loading, the previous stage data should be cleared
## [1.0.14] - 2022-11-23
### Fixed
- try to open non-exsited URL, the spinner is always rotationg (OM-73934)
- force loading completion in the model rather than in the widget in case widget is not available (OM-73085)
## [1.0.13] - 2022-11-22
### Changed
- Make the pinwheel invisible when it's not loading
## [1.0.12] - 2022-11-18
### Changed
- Fixed the performance issue when ASSETS_LOADED is triggered by selection change
- Changed visibility of the progress bar window, instead of poping up when the prompt window is done we show the window when user clicks the status bar's progress area
## [1.0.11] - 2022-11-21
### Changed
- fixed performance issue caused by __extend_unfinished
- create ActivityModelStageOpenForProgress model for progress bar window to solve the performance issue of progress bar
## [1.0.10] - 2022-11-16
### Added
- informative text on the total progress bar showing the activity event happening (OM-72502)
- docs for the extension (OM-52478)
## [1.0.9] - 2022-11-10
### Changed
- clear the status bar instead of sending progress as 0% when new stage is created
- also clear the status bar when the stage is loaded so it's not stuck at 100%
## [1.0.8] - 2022-11-08
### Changed
- Don't use usd_resolver python callbacks
## [1.0.7] - 2022-11-07
### Changed
- using spinner instead of the ping-pong rectangle for the floating window
## [1.0.6] - 2022-11-04
### Changed
- make sure the activity progress window is shown and on focus when open stage is triggered
## [1.0.5] - 2022-10-28
### Changed
- fix the test with a threshold
## [1.0.4] - 2022-10-26
### Changed
- Stop the timeline view when asset_loaded
- Move the Activity Window menu item under Utilities
- Disable the menu button in the floating window
- Rename windows to Activity Progress and Activity Timeline
- Removed Timeline window menu entry and only make accessible through main Activity window
- Fixed resizing issue in the Activity Progress Treeview - resizing second column resizer breaks the view
- Make the spinner active during opening stage
- Remove the material progress bar size and speed for now
- Set the Activty window invisible by default (fix OM-67358)
- Update the preview image
## [1.0.3] - 2022-10-20
### Changed
- create ActivityModelStageOpen which inherits from ActivityModelRealtime, so to move the stage_path and _flattened_children out from the ActivityModelRealtime mode
## [1.0.2] - 2022-10-18
### Changed
- Fix the auto save to be window irrelevant (when progress bar window or timeline window is closed, still working), save to "${cache}/activities", and auto delete the old files, at the moment we keep 20 of them
- Add file numbers to timeline view when necessary
- Add size to the parent time range in the tooltip of timeline view when make sense
- Force progress to 1 when assets loaded
- Fix the issue of middle and right clicked is triggered unnecessarily, e.g., mouse movement in viewport
- Add timeline view selection callback to usd stage prim selection
## [1.0.1] - 2022-10-13
### Fixed
- test failure due to self._addon is None
## [1.0.0] - 2022-06-05
### Added
- Initial window
| 3,970 | Markdown | 36.462264 | 223 | 0.734509 |
omniverse-code/kit/exts/omni.activity.ui/docs/Overview.md | # Overview
omni.activity.ui is an extension created to display progress and activities. This is the new generation of the activity monitor which replaces the old version of omni.kit.activity.widget.monitor extension since the old activity monitor has limited information on activities and doesn't always provide accurate information about the progress.
Current work of omni.activity.ui focuses on loading activities but the solution is in general and will be extended to unload and frame activities in the future.
There are currently two visual presentations for the activities. The main one is the Activity Progress window which can be manually enabled from menu: Window->Utilities->Activity Progress:

It can also be shown when user clicks the status bar's progress area at the bottom right of the app. The Activity Progress window will be docked and on focus as a standard window.

The other window: Activity Timeline window can be enabled through the drop-down menu: Show Timeline, by clicking the hamburger button on the top right corner from Activity Progress window.

Here is an example showing the Activity Progress window on the bottom right and Activity Timeline window on the bottom left.

Closing any window shouldn't affect the activities. When the window is re-enabled, the data will pick up from the model to show the current progress.
## Activity Progress Window
The Activity Progress window shows a simplified user interface about activity information that can be easily understood and displayed. There are two tabs in the Activity Progress window: Progress Bar and Activity. They share the same data model and present the data in two ways.
The Activity Progress window shows the total loading file number and total time at the bottom. The rotating spinner indicates the loading is in progress or not. The total progress bar shows the current loading activity and the overall progress of the loading. The overall progress is linked to the progress of the status bar.

### Progress Bar Tab
The Progress Bar Tab focuses on the overall progress on the loading of USD, Material and Texture which are normally the top time-consuming activities. We display the total loading size and speed to each category. The user can easily see how many of the files have been loaded vs the total numbers we've traced. All these numbers are dynamically updated when the data model changes.
### Activity Tab
The activity tab displays loading activities in the order of the most recent update. It is essentially a flattened treeview. It details the file name, loading duration and file size if relevant. When the user hover over onto each tree item, you will see more detailed information about the file path, duration and size.

## Activity Timeline Window
The Activity Timeline window gives advanced users (mostly developers) more details to explore. It currently shows 6 threads: Stage, USD, Textures, Render Thread, Meshes and Materials. It also contains two tabs: Timeline and Activities. They share the same data model but have two different data presentations which help users to understand the information from different perspectives.
### Timeline Tab
In the Timeline Tab, each thread is shown as a growing rectangle bar on their own lane, but the SubActivities for those are "bin packed" to use as few lanes as possible even when they are on many threads. Each timeline block represents an activity, whose width shows the duration of the activity. Different activities are color coded to provide better visual results to help users understand the data more intuitively. When users hover onto each item, it will give more detailed information about the path, duration and size.
Users can double click to see what's happening in each activity, double click with shift will expand/collapse all.
Right mouse move can pan the timeline view vertically and horizontally.
Middle mouse scrolling can zoom in/out the timeline ranges. Users can also use middle mouse click (twice) to select a time range, which will zoom to fit the Timeline window. This will filter the activities treeview under the Activities Tab to only show the items which are within the selected time range.
Here is an image showing a time range selection:

### Activities Tab
The data is presented in a regular treeview with the root item as the 6 threads. Each thread activity shows its direct subActivities. Users can also see the duration, start time, end time and size information about each activity. When users hover onto each item, it will give more detailed information.
The expansion and selection status are synced between the Timeline Tab and Activities Tab.
## Save and Load Activity Log
Both Activity Progress Window and Activity Timeline Window have a hamburger button on the top right corner where you can save or choose to open an .activity or .json log file. The saved log file has the same data from both windows and it records all the activities happening for a certain stage. When you open the same .activity file from different windows, you get a different visual representation of the data.
A typical activity entry looks like this:
```python
{
"children": [],
"events": [
{
"size": 2184029,
"time": 133129969539325474,
"type": "BEGAN"
},
{
"size": 2184029,
"time": 133129969540887869,
"type": "ENDED"
}
],
"name": "omniverse://ov-content/NVIDIA/Samples/Marbles/assets/standalone/SM_board_4/SM_board_4.usd"
},
```
This is really useful to send to people for debug purposes, e.g find the performance bottleneck of the stage loading or spot problematic texture and so on.
## Dependencies
This extension depends on two core activity extensions omni.activity.core and omni.activity.pump. omni.activity.core is the core activity progress processor which defines the activity and event structure and provides APIs to subscribe to the events dispatching on the stream. omni.activity.pump makes sure the activity and the progress gets pumped every frame. | 6,230 | Markdown | 72.305882 | 525 | 0.781059 |
omniverse-code/kit/exts/omni.kit.window.filepicker/scripts/demo_filepicker.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 omni.ui as ui
from omni.kit.window.filepicker import FilePickerDialog
from omni.kit.widget.filebrowser import FileBrowserItem
def options_pane_build_fn(selected_items):
with ui.CollapsableFrame("Reference Options"):
with ui.HStack(height=0, spacing=2):
ui.Label("Prim Path", width=0)
return True
def on_filter_item(dialog: FilePickerDialog, item: FileBrowserItem) -> bool:
if not item or item.is_folder:
return True
if dialog.current_filter_option == 0:
# Show only files with listed extensions
_, ext = os.path.splitext(item.path)
if ext in [".usd", ".usda", ".usdc", ".usdz"]:
return True
else:
return False
else:
# Show All Files (*)
return True
def on_click_open(dialog: FilePickerDialog, 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.
"""
# Normally, you'd want to hide the dialog
# dialog.hide()
dirname = dirname.strip()
if dirname and not dirname.endswith("/"):
dirname += "/"
fullpath = f"{dirname}{filename}"
print(f"Opened file '{fullpath}'.")
if __name__ == "__main__":
item_filter_options = ["USD Files (*.usd, *.usda, *.usdc, *.usdz)", "All Files (*)"]
dialog = FilePickerDialog(
"Demo Filepicker",
apply_button_label="Open",
click_apply_handler=lambda filename, dirname: on_click_open(dialog, filename, dirname),
item_filter_options=item_filter_options,
item_filter_fn=lambda item: on_filter_item(dialog, item),
options_pane_build_fn=options_pane_build_fn,
)
dialog.add_connections({"ov-content": "omniverse://ov-content", "ov-rc": "omniverse://ov-rc"})
# Display dialog at pre-determined path
dialog.show(path="omniverse://ov-content/NVIDIA/Samples/Astronaut/Astronaut.usd")
| 2,545 | Python | 36.999999 | 98 | 0.677014 |
omniverse-code/kit/exts/omni.kit.window.filepicker/config/extension.toml | [package]
title = "Kit Filepicker Window"
version = "2.7.15"
category = "Internal"
description = "Filepicker popup dialog and embeddable widget"
authors = ["NVIDIA"]
slackids = ["UQY4RMR3N"]
repository = ""
keywords = ["kit", "ui"]
readme = "docs/README.md"
changelog = "docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[dependencies]
"omni.ui" = {}
"omni.usd" = {optional=true}
"omni.client" = {}
"omni.kit.notification_manager" = {}
"omni.kit.pip_archive" = {} # Pull in pip_archive to make sure psutil is found and not installed
"omni.kit.widget.filebrowser" = {}
"omni.kit.widget.browser_bar" = {}
"omni.kit.window.popup_dialog" = {}
"omni.kit.widget.versioning" = {}
"omni.kit.search_core" = {}
"omni.kit.widget.nucleus_connector" = {}
[[python.module]]
name = "omni.kit.window.filepicker"
[[python.scriptFolder]]
path = "scripts"
[python.pipapi]
requirements = ["psutil", "pyperclip"]
[settings]
exts."omni.kit.window.filepicker".timeout = 10.0
persistent.exts."omni.kit.window.filepicker".window_split = 306
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.kit.ui_test",
]
pythonTests.unreliable = [
"*test_search_returns_expected*", # OM-75424
"*test_changing_directory_while_searching*", # OM-75424
]
| 1,355 | TOML | 23.214285 | 96 | 0.681181 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/search_delegate.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 abc
import omni.ui as ui
from typing import Dict
from omni.kit.widget.filebrowser import FileBrowserModel, FileBrowserItem, find_thumbnails_for_files_async
from omni.kit.search_core import AbstractSearchModel, AbstractSearchItem
class SearchDelegate:
def __init__(self, **kwargs):
self._search_dir = None
@property
def visible(self):
return True
@property
def enabled(self):
"""Enable/disable Widget"""
return True
@property
def search_dir(self):
return self._search_dir
@search_dir.setter
def search_dir(self, search_dir: str):
self._search_dir = search_dir
@abc.abstractmethod
def build_ui(self):
pass
@abc.abstractmethod
def destroy(self):
pass
class SearchResultsItem(FileBrowserItem):
class _RedirectModel(ui.AbstractValueModel):
def __init__(self, search_model, field):
super().__init__()
self._search_model = search_model
self._field = field
def get_value_as_string(self):
return str(self._search_model[self._field])
def set_value(self, value):
pass
def __init__(self, search_item: AbstractSearchItem):
super().__init__(search_item.path, search_item)
self.search_item = search_item
self._is_folder = self.search_item.is_folder
self._models = (
self._RedirectModel(self.search_item, "name"),
self._RedirectModel(self.search_item, "date"),
self._RedirectModel(self.search_item, "size"),
)
@property
def icon(self) -> str:
"""str: Gets/sets path to icon file."""
return self.search_item.icon
@icon.setter
def icon(self, icon: str):
pass
class SearchResultsModel(FileBrowserModel):
def __init__(self, search_model: AbstractSearchModel, **kwargs):
super().__init__(**kwargs)
self._search_model = search_model
# Circular dependency
self._dirty_item_subscription = self._search_model.subscribe_item_changed(self.__on_item_changed)
self._children = []
self._thumbnail_dict: Dict = {}
def destroy(self):
# Remove circular dependency
self._dirty_item_subscription = None
if self._search_model:
self._search_model.destroy()
self._search_model = None
def get_item_children(self, item: FileBrowserItem) -> [FileBrowserItem]:
"""Converts AbstractSearchItem to FileBrowserItem"""
if self._search_model is None or item is not None:
return []
search_items = self._search_model.items or []
self._children = [SearchResultsItem(search_item) for search_item in search_items]
if self._filter_fn:
return list(filter(self._filter_fn, self._children))
else:
return self._children
def __on_item_changed(self, item):
if item is None:
self._children = []
self._item_changed(item)
async def get_custom_thumbnails_for_folder_async(self, _: SearchResultsItem) -> Dict:
"""
Returns a dictionary of thumbnails for the given search results.
Args:
item (:obj:`FileBrowseritem`): Ignored, should be set to None.
Returns:
dict: With item name as key, and fullpath to thumbnail file as value.
"""
# Files in the root folder only
file_urls = []
for item in self.get_item_children(None):
if item.is_folder or item.path in self._thumbnail_dict:
# Skip if folder or thumbnail previously found
pass
else:
file_urls.append(item.path)
thumbnail_dict = await find_thumbnails_for_files_async(file_urls)
for url, thumbnail_url in thumbnail_dict.items():
if url and thumbnail_url:
self._thumbnail_dict[url] = thumbnail_url
return self._thumbnail_dict
| 4,440 | Python | 30.496454 | 106 | 0.626126 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/item_deletion_dialog.py | # Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from typing import Callable
from typing import List
from omni.kit.widget.filebrowser import FileBrowserItem
from omni.kit.window.popup_dialog.dialog import PopupDialog
import omni.ui as ui
from .item_deletion_model import ConfirmItemDeletionListModel
from .style import get_style
class ConfirmItemDeletionDialog(PopupDialog):
"""Dialog prompting the User to confirm the deletion of the provided list of files and folders."""
def __init__(
self,
items: List[FileBrowserItem],
title: str="Confirm File Deletion",
message: str="You are about to delete",
message_fn: Callable[[None], None]=None,
parent: ui.Widget=None, # OBSOLETE
width: int=500,
ok_handler: Callable[[PopupDialog], None]=None,
cancel_handler: Callable[[PopupDialog], None]=None,
):
"""
Dialog prompting the User to confirm the deletion of the provided list of files and folders.
Args:
items ([FileBrowserItem]): List of files and folders to delete.
title (str): Title of the dialog. Default "Confirm File Deletion".
message (str): Basic message. Default "You are about to delete".
message_fn (Callable[[None], None]): Message build function.
parent (:obj:`omni.ui.Widget`): OBSOLETE. If specified, the dialog position is relative to this widget. Default `None`.
width (int): Dialog width. Default `500`.
ok_handler (Callable): Function to execute upon clicking the "Yes" button. Function signature:
void ok_handler(dialog: :obj:`PopupDialog`)
cancel_handler (Callable): Function to execute upon clicking the "No" button. Function signature:
void cancel_handler(dialog: :obj:`PopupDialog`)
"""
super().__init__(
width=width,
title=title,
ok_handler=ok_handler,
ok_label="Yes",
cancel_handler=cancel_handler,
cancel_label="No",
)
self._items = items
self._message = message
self._message_fn = message_fn
self._list_model = ConfirmItemDeletionListModel(items)
self._tree_view = None
self._build_ui()
self.hide()
def _build_ui(self) -> None:
with self._window.frame:
with ui.ZStack(style=get_style()):
ui.Rectangle(style_type_name_override="Background")
with ui.VStack(style_type_name_override="Dialog", spacing=6):
if self._message_fn:
self._message_fn()
else:
prefix_message = self._message + " this item:" if len(self._items) == 1 else f"these {len(self._items)} items:"
ui.Label(prefix_message)
scrolling_frame = ui.ScrollingFrame(
height=150,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
)
with scrolling_frame:
self._tree_view = ui.TreeView(
self._list_model,
root_visible=False,
header_visible=False,
style={"TreeView.Item": {"margin": 4}},
)
ui.Label("Are you sure you wish to proceed?")
self._build_ok_cancel_buttons()
def destroy(self) -> None:
"""Destructor."""
if self._list_model:
self._list_model = None
if self._tree_view:
self._tree_view = None
self._window = None
def rebuild_ui(self, message_fn: Callable[[None], None]) -> None:
"""
Rebuild ui widgets with new message
Args:
message_fn (Callable[[None], None]): Message build function.
"""
self._message_fn = message_fn
# Reset window or new height with new message
self._window.height = 0
self._window.frame.clear()
self._build_ui()
| 4,701 | Python | 40.610619 | 135 | 0.577962 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/view.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
import platform
import omni.kit.app
import omni.client
import carb.settings
from typing import Callable, List, Optional
from carb import events, log_warn
from omni.kit.widget.filebrowser import (
FileBrowserWidget,
FileBrowserModel,
FileBrowserItem,
FileSystemModel,
NucleusModel,
NucleusConnectionItem,
LAYOUT_DEFAULT,
TREEVIEW_PANE,
LISTVIEW_PANE,
CONNECTION_ERROR_EVENT
)
from omni.kit.widget.nucleus_connector import get_nucleus_connector, NUCLEUS_CONNECTION_SUCCEEDED_EVENT
from .model import FilePickerModel
from .bookmark_model import BookmarkItem, BookmarkModel
from .utils import exec_after_redraw, get_user_folders_dict
from .style import ICON_PATH
import carb.events
BOOKMARK_ADDED_EVENT: int = carb.events.type_from_string("omni.kit.window.filepicker.BOOKMARK_ADDED")
BOOKMARK_DELETED_EVENT: int = carb.events.type_from_string("omni.kit.window.filepicker.BOOKMARK_DELETED")
BOOKMARK_RENAMED_EVENT: int = carb.events.type_from_string("omni.kit.window.filepicker.BOOKMARK_RENAMED")
NUCLEUS_SERVER_ADDED_EVENT: int = carb.events.type_from_string("omni.kit.window.filepicker.NUCLEUS_SERVER_ADDED")
NUCLEUS_SERVER_DELETED_EVENT: int = carb.events.type_from_string("omni.kit.window.filepicker.NUCLEUS_SERVER_DELETED")
NUCLEUS_SERVER_RENAMED_EVENT: int = carb.events.type_from_string("omni.kit.window.filepicker.NUCLEUS_SERVER_RENAMED")
class FilePickerView:
"""
An embeddable UI component for browsing the filesystem. This widget is more full-functioned
than :obj:`FileBrowserWidget` but less so than :obj:`FilePickerWidget`. More specifically, this is one of
the 3 sub-components of its namesake :obj:`FilePickerWidget`. The difference is it doesn't have the Browser Bar
(at top) or the File Bar (at bottom). This gives users the flexibility to substitute in other surrounding
components instead.
Args:
title (str): Widget title. Default None.
Keyword Args:
layout (int): The overall layout of the window, one of: {LAYOUT_SPLIT_PANES, LAYOUT_SINGLE_PANE_SLIM,
LAYOUT_SINGLE_PANE_WIDE, LAYOUT_DEFAULT}. Default LAYOUT_SPLIT_PANES.
splitter_offset (int): Position of vertical splitter bar. Default 300.
show_grid_view (bool): Display grid view in the intial layout. Default True.
show_recycle_widget (bool): Display recycle widget in the intial layout. Default False.
grid_view_scale (int): Scales grid view, ranges from 0-5. Default 2.
on_toggle_grid_view_fn (Callable): Callback after toggle grid view is executed. Default None.
on_scale_grid_view_fn (Callable): Callback after scale grid view is executed. Default None.
show_only_collections (list[str]): List of collections to display, any combination of ["bookmarks",
"omniverse", "my-computer"]. If None, then all are displayed. Default None.
tooltip (bool): Display tooltips when hovering over items. Default True.
allow_multi_selection (bool): Allow multiple items to be selected at once. Default False.
mouse_pressed_fn (Callable): Function called on mouse press. Function signature:
void mouse_pressed_fn(pane: int, button: int, key_mode: int, item: :obj:`FileBrowserItem`)
mouse_double_clicked_fn (Callable): Function called on mouse double click. Function signature:
void mouse_double_clicked_fn(pane: int, button: int, key_mode: int, item: :obj:`FileBrowserItem`)
selection_changed_fn (Callable): Function called when selection changed. Function signature:
void selection_changed_fn(pane: int, selections: list[:obj:`FileBrowserItem`])
drop_handler (Callable): Function called to handle drag-n-drops.
Function signature: void drop_fn(dst_item: :obj:`FileBrowserItem`, src_paths: [str])
item_filter_fn (Callable): This handler should return True if the given tree view item is visible,
False otherwise. Function signature: bool item_filter_fn(item: :obj:`FileBrowserItem`)
thumbnail_provider (Callable): This callback returns the path to the item's thumbnail. If not specified,
then a default thumbnail is used. Signature: str thumbnail_provider(item: :obj:`FileBrowserItem`).
icon_provider (Callable): This callback provides an icon to replace the default in the tree view.
Signature str icon_provider(item: :obj:`FileBrowserItem`)
badges_provider (Callable): This callback provides the list of badges to layer atop the thumbnail
in the grid view. Callback signature: [str] badges_provider(item: :obj:`FileBrowserItem`)
treeview_identifier (str): widget identifier for treeview, only used by tests.
enable_zoombar (bool): Enables/disables zoombar. Default True.
"""
# Singleton placeholder item in the tree view
__placeholder_model = None
# use class attribute to store connected server's url
# it could shared between different file dialog (OMFP-2569)
__connected_servers = set()
def __init__(self, title: str, **kwargs):
self._title = title
self._filebrowser = None
self._layout = kwargs.get("layout", LAYOUT_DEFAULT)
self._splitter_offset = kwargs.get("splitter_offset", 300)
self._show_grid_view = kwargs.get("show_grid_view", True)
self._show_recycle_widget = kwargs.get("show_recycle_widget", False)
self._grid_view_scale = kwargs.get("grid_view_scale", 2)
# OM-66270: Add callback to record show grid view settings in between sessions
self._on_toggle_grid_view_fn = kwargs.get("on_toggle_grid_view_fn", None)
self._on_scale_grid_view_fn = kwargs.get("on_scale_grid_view_fn", None)
self._show_only_collections = kwargs.get("show_only_collections", None)
self._tooltip = kwargs.get("tooltip", True)
self._allow_multi_selection = kwargs.get("allow_multi_selection", False)
self._mouse_pressed_fn = kwargs.get("mouse_pressed_fn", None)
self._mouse_double_clicked_fn = kwargs.get("mouse_double_clicked_fn", None)
self._selection_changed_fn = kwargs.get("selection_changed_fn", None)
self._drop_handler = kwargs.get("drop_handler", None)
self._item_filter_fn = kwargs.get("item_filter_fn", None)
self._icon_provider = kwargs.get("icon_provider", None)
self._thumbnail_provider = kwargs.get("thumbnail_provider", None)
self._treeview_identifier = kwargs.get('treeview_identifier', None)
self._enable_zoombar = kwargs.get("enable_zoombar", True)
self._badges_provider = kwargs.get("badges_provider", None)
self._collections = {}
self._bookmark_model = None
self._show_add_new_connection = carb.settings.get_settings().get_as_bool("/exts/omni.kit.window.filepicker/show_add_new_connection")
if not FilePickerView.__placeholder_model:
FilePickerView.__placeholder_model = FileBrowserModel(name="Add New Connection ...")
FilePickerView.__placeholder_model.root.icon = f"{ICON_PATH}/hdd_plus.svg"
self.__expand_task = None
self._connection_failed_event_sub = None
self._connection_succeeded_event_sub = None
self._connection_status_sub = None
self._build_ui()
@property
def filebrowser(self):
return self._filebrowser
def destroy(self):
if self.__expand_task is not None:
self.__expand_task.cancel()
self.__expand_task = None
if self._filebrowser:
self._filebrowser.destroy()
self._filebrowser = None
self._mouse_pressed_fn = None
self._mouse_double_clicked_fn = None
self._selection_changed_fn = None
self._drop_handler = None
self._item_filter_fn = None
self._icon_provider = None
self._thumbnail_provider = None
self._badges_provider = None
self._collections = None
self._bookmark_model = None
self._connection_failed_event_sub = None
self._connection_succeeded_event_sub = None
self._connection_status_sub = None
@property
def show_udim_sequence(self):
return self._filebrowser.show_udim_sequence
@show_udim_sequence.setter
def show_udim_sequence(self, value: bool):
self._filebrowser.show_udim_sequence = value
@property
def notification_frame(self):
return self._filebrowser._notification_frame
def _build_ui(self):
""" """
def on_mouse_pressed(pane: int, button: int, key_mod: int, item: FileBrowserItem, x: float = 0, y: float = 0):
if button == 0 and self._is_placeholder(item):
# Left mouse button: add new connection
self.show_connect_dialog()
if self._mouse_pressed_fn and not self._is_placeholder(item):
self._mouse_pressed_fn(pane, button, key_mod, item)
def on_mouse_double_clicked(pane: int, button: int, key_mod: int, item: FileBrowserItem, x: float = 0, y: float = 0):
if self._is_placeholder(item):
return
if item and item.is_folder:
# In the special case where item errored out previously, try reconnecting the host.
broken_url = omni.client.break_url(item.path)
if broken_url.host:
def on_host_found(host: FileBrowserItem):
if host and host.alert:
self.reconnect_server(host)
try:
self._find_item_with_callback(
omni.client.make_url(scheme=broken_url.scheme, host=broken_url.host), on_host_found)
except Exception as e:
log_warn(str(e))
if self._mouse_double_clicked_fn:
self._mouse_double_clicked_fn(pane, button, key_mod, item)
def on_selection_changed(pane: int, selected: [FileBrowserItem]):
# Filter out placeholder item
selected = list(filter(lambda i: not self._is_placeholder(i), selected))
if self._selection_changed_fn:
self._selection_changed_fn(pane, selected)
self._filebrowser = FileBrowserWidget(
"All",
tree_root_visible=False,
layout=self._layout,
splitter_offset=self._splitter_offset,
show_grid_view=self._show_grid_view,
show_recycle_widget=self._show_recycle_widget,
grid_view_scale=self._grid_view_scale,
on_toggle_grid_view_fn=self._on_toggle_grid_view_fn,
on_scale_grid_view_fn=self._on_scale_grid_view_fn,
tooltip=self._tooltip,
allow_multi_selection=self._allow_multi_selection,
mouse_pressed_fn=on_mouse_pressed,
mouse_double_clicked_fn=on_mouse_double_clicked,
selection_changed_fn=on_selection_changed,
drop_fn=self._drop_handler,
filter_fn=self._item_filter_fn,
icon_provider=self._icon_provider,
thumbnail_provider=self._thumbnail_provider,
badges_provider=self._badges_provider,
treeview_identifier=self._treeview_identifier,
enable_zoombar=self._enable_zoombar
)
# Listen for connections errors that may occur during navigation
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
self._connection_failed_event_sub =\
event_stream.create_subscription_to_pop_by_type(CONNECTION_ERROR_EVENT, self._on_connection_failed)
self._connection_succeeded_event_sub = \
event_stream.create_subscription_to_pop_by_type(NUCLEUS_CONNECTION_SUCCEEDED_EVENT, self._on_connection_succeeded)
self._connection_status_sub = omni.client.register_connection_status_callback(self._server_status_changed)
self._build_bookmarks_collection()
self._build_omniverse_collection()
self._build_computer_collection()
def expand_collections():
for collection in self._collections.values():
self._filebrowser.set_expanded(collection, expanded=True, recursive=False)
# Finally, expand collection nodes in treeview after UI becomes ready
self.__expand_task = exec_after_redraw(expand_collections, wait_frames=6)
def _build_bookmarks_collection(self):
collection_id = "bookmarks"
if self._show_only_collections and collection_id not in self._show_only_collections:
return
if not self._bookmark_model:
self._bookmark_model = BookmarkModel("Bookmarks", f"{collection_id}://")
self._filebrowser.add_model_as_subtree(self._bookmark_model)
self._collections[collection_id] = self._bookmark_model.root
def _build_omniverse_collection(self):
collection_id = "omniverse"
if self._show_only_collections and collection_id not in self._show_only_collections:
return
collection = self._filebrowser.create_grouping_item("Omniverse", f"{collection_id}://", parent=None)
collection.icon = f"{ICON_PATH}/omniverse_logo_64.png"
self._collections[collection_id] = collection
# Create a placeholder item for adding new connections
if self._show_add_new_connection:
self._filebrowser.add_model_as_subtree(FilePickerView.__placeholder_model, parent=collection)
def _build_computer_collection(self):
collection_id = "my-computer"
if self._show_only_collections and collection_id not in self._show_only_collections:
return
collection = self._collections.get(collection_id, None)
if collection is None:
collection = self._filebrowser.create_grouping_item("My Computer", f"{collection_id}://", parent=None)
collection.icon = f"{ICON_PATH}/my_computer.svg"
self._collections[collection_id] = collection
try:
if platform.system().lower() == "linux":
import psutil
partitions = psutil.disk_partitions(all=True)
# OM-76424: Pre-filter some of the local directories that are of interest for users
filtered_partitions = []
for partition in partitions:
if any(x in partition.opts for x in ('nodev', 'nosuid', 'noexec')):
continue
if partition.fstype in ('tmpfs', 'proc', 'devpts', 'sysfs', 'nsfs', 'autofs', 'cgroup'):
continue
filtered_partitions.append(partition)
partitions = filtered_partitions
# OM-76424: Ensure that "/" is always there, because disk_partitions() will ignore it sometimes.
if not any(p.mountpoint == "/" for p in partitions):
from types import SimpleNamespace
e = SimpleNamespace()
e.mountpoint = "/"
e.opts = "fixed"
partitions.insert(0, e) # first entry
elif platform.system().lower() == "windows":
from ctypes import windll
# GetLocalDrives returns a bitmask with with bit i set meaning that
# the logical drive 'A' + i is available on the system.
logicalDriveBitMask = windll.kernel32.GetLogicalDrives()
from types import SimpleNamespace
partitions = list()
# iterate over all letters in the latin alphabet
for bit in range(0, (ord('Z') - ord('A') + 1)):
if logicalDriveBitMask & (1 << bit):
e = SimpleNamespace()
e.mountpoint = chr(ord('A') + bit) + ":"
e.opts = "fixed"
partitions.append(e)
else:
import psutil
partitions = psutil.disk_partitions(all=True)
except Exception:
log_warn("Warning: Could not import psutil")
return
else:
# OM-51243: Show OV Drive (O: drive) after refresh in Create
user_folders = get_user_folders_dict()
# we should remove all old Drive at first, but keep the user folder
for name in collection.children:
if name not in user_folders:
self._filebrowser.delete_child_by_name(name, collection)
# then add current Drive
for p in partitions:
if any(x in p.opts for x in ["removable", "fixed", "rw", "ro", "remote"]):
mountpoint = p.mountpoint.rstrip("\\")
item_model = FileSystemModel(mountpoint, mountpoint)
self._filebrowser.add_model_as_subtree(item_model, parent=collection)
@property
def collections(self):
"""dict: Dictionary of collections, e.g. 'bookmarks', 'omniverse', 'my-computer'."""
return self._collections
def get_root(self, pane: int = None) -> FileBrowserItem:
"""
Returns the root item of the specified pane.
Args:
pane (int): One of {TREEVIEW_PANE, LISTVIEW_PANE}.
"""
if self._filebrowser:
return self._filebrowser.get_root(pane)
return None
def all_collection_items(self, collection: str = None) -> List[FileBrowserItem]:
"""
Returns all connections as items for the specified collection. If collection is 'None', then return connections
from all collections.
Args:
collection (str): One of ['bookmarks', 'omniverse', 'my-computer']. Default None.
Returns:
List[FileBrowserItem]: All connections found.
"""
collections = [self._collections.get(collection)] if collection else self._collections.values()
connections = []
for coll in collections:
# Note: We know that collections are initally expanded so we can safely retrieve its children
# here without worrying about async delay.
if coll and coll.children:
for _, conn in coll.children.items():
if not self._is_placeholder(conn):
connections.append(conn)
return connections
def is_collection_root(self, url: str = None) -> bool:
"""
Returns True if the given url is a collection root url.
Args:
url (str): The url to query. Default None.
Returns:
bool: The result.
"""
if not url:
return False
for col in self._collections.values():
if col.path == url:
return True
# click the path field root always renturn "omniverse:///"
if url.rstrip("/") == "omniverse:":
return True
return False
def has_connection_with_name(self, name: str, collection: str = None) -> bool:
"""
Returns True if named connection exists within the collection.
Args:
name (str): name (could be aliased name) of connection
collection (str): One of {'bookmarks', 'omniverse', 'my-computer'}. Default None.
Returns:
bool
"""
connections = [i.name for i in self.all_collection_items(collection)]
return name in connections
def get_connection_with_url(self, url: str) -> Optional[NucleusConnectionItem]:
"""
Gets the connection item with the given url.
Args:
name (str): name (could be aliased name) of connection
Returns:
NucleusConnectionItem
"""
for item in self.all_collection_items(collection="omniverse"):
if item.path == url:
return item
return None
def set_item_filter_fn(self, item_filter_fn: Callable[[str], bool]):
"""
Sets the item filter function.
Args:
item_filter_fn (Callable): Signature is bool fn(item: FileBrowserItem)
"""
self._item_filter_fn = item_filter_fn
if self._filebrowser and self._filebrowser._listview_model:
self._filebrowser._listview_model.set_filter_fn(self._item_filter_fn)
def set_selections(self, selections: List[FileBrowserItem], pane: int = TREEVIEW_PANE):
"""
Selected given items in given pane.
ARGS:
selections (list[:obj:`FileBrowserItem`]): list of selections.
pane (int): One of TREEVIEW_PANE, LISTVIEW_PANE, or None for both. Default None.
"""
if self._filebrowser:
self._filebrowser.set_selections(selections, pane)
def get_selections(self, pane: int = LISTVIEW_PANE) -> List[FileBrowserItem]:
"""
Returns list of currently selected items.
Args:
pane (int): One of {TREEVIEW_PANE, LISTVIEW_PANE}.
Returns:
list[:obj:`FileBrowserItem`]
"""
if self._filebrowser:
return [sel for sel in self._filebrowser.get_selections(pane) if not self._is_placeholder(sel)]
return []
def refresh_ui(self, item: FileBrowserItem = None):
"""
Redraws the subtree rooted at the given item. If item is None, then redraws entire tree.
Args:
item (:obj:`FileBrowserItem`): Root of subtree to redraw. Default None, i.e. root.
"""
self._build_computer_collection()
if item:
item.populated = False
if self._filebrowser:
self._filebrowser.refresh_ui(item)
def is_connection_point(self, item: FileBrowserItem) -> bool:
"""
Returns true if given item is a direct child of a collection node.
Args:
item (:obj:`FileBrowserItem`): Item in question.
Returns:
bool
"""
return item in self.all_collection_items("omniverse")
def is_bookmark(self, item: FileBrowserItem, path: Optional[str] = None) -> bool:
"""
Returns true if given item is a bookmarked item, or if a given path is bookmarked.
Args:
item (:obj:`FileBrowserItem`): Item in question.
path (Optional[str]): Path in question.
Returns:
bool
"""
if path:
for item in self.all_collection_items("bookmarks"):
# compare the bookmark path with the formatted file path
if item.path == item.format_bookmark_path(path):
return True
return False
# if path is not given, check item type directly
return isinstance(item, BookmarkItem)
def is_collection_node(self, item: FileBrowserItem) -> bool:
"""
Returns true if given item is a collection node.
Args:
item (:obj:`FileBrowserItem`): Item in question.
Returns:
bool
"""
for value in self.collections.values():
if value.name == item.name:
return True
return False
def select_and_center(self, item: FileBrowserItem):
"""
Selects and centers the view on the given item, expanding the tree if needed.
Args:
item (:obj:`FileBrowserItem`): The selected item.
"""
if not self._filebrowser:
return
if (item and item.is_folder) or not item:
self._filebrowser.select_and_center(item, pane=TREEVIEW_PANE)
else:
self._filebrowser.select_and_center(item.parent, pane=TREEVIEW_PANE)
exec_after_redraw(lambda item=item: self._filebrowser.select_and_center(item, pane=LISTVIEW_PANE))
def show_model(self, model: FileBrowserModel):
"""Displays the model on the right side of the split pane"""
self._filebrowser.show_model(model)
def show_connect_dialog(self):
"""Displays the add connection dialog."""
nucleus_connector = get_nucleus_connector()
if nucleus_connector:
nucleus_connector.connect_with_dialog(on_success_fn=self.add_server)
def add_server(self, name: str, path: str, publish_event: bool = True) -> FileBrowserModel:
"""
Creates a :obj:`FileBrowserModel` rooted at the given path, and connects its subtree to the
tree view.
Args:
name (str): Name, label really, of the connection.
path (str): Fullpath of the connection, e.g. "omniverse://ov-content". Paths to
Omniverse servers should contain the prefix, "omniverse://".
publish_event (bool): If True, push a notification to the event stream.
Returns:
:obj:`FileBrowserModel`
Raises:
:obj:`RuntimeWarning`: If unable to add server.
"""
if not (name and path):
raise RuntimeWarning(f"Error adding server, invalid name: '{path}', path: '{path}'.")
collection = self._collections.get("omniverse", None)
if not collection:
return None
# First, remove the placeholder model
if self._show_add_new_connection:
self._filebrowser.delete_child(FilePickerView.__placeholder_model.root, parent=collection)
# Append the new model of desired server type
server = NucleusModel(name, path)
self._filebrowser.add_model_as_subtree(server, parent=collection)
# Finally, re-append the placeholder
if self._show_add_new_connection:
self._filebrowser.add_model_as_subtree(FilePickerView.__placeholder_model, parent=collection)
if publish_event:
# Push a notification event to the event stream
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
event_stream.push(NUCLEUS_SERVER_ADDED_EVENT, payload={"name": name, "url": path})
return server
def _on_connection_failed(self, event: events.IEvent):
if event.type == CONNECTION_ERROR_EVENT:
def set_item_warning(item: FileBrowserItem, msg: str):
if item and not self._is_placeholder(item):
self.filebrowser.set_item_warning(item, msg)
try:
broken_url = omni.client.break_url(event.payload.get('url', ""))
except Exception:
return
if broken_url.scheme == "omniverse" and broken_url.host:
url = omni.client.make_url(scheme=broken_url.scheme, host=broken_url.host)
msg = "Unable to access this server. Please double-click this item or right-click, then 'reconnect server' to refresh the connection."
self._find_item_with_callback(url, lambda item: set_item_warning(item, msg))
def _on_connection_succeeded(self, event: events.IEvent):
if event.type == NUCLEUS_CONNECTION_SUCCEEDED_EVENT:
try:
url = event.payload.get('url', "")
except Exception:
return
else:
return
def refresh_connection(item: FileBrowserItem):
if self._filebrowser:
# Clear alerts, if any
self._filebrowser.clear_item_alert(item)
self.refresh_ui(item)
self._find_item_with_callback(url, refresh_connection)
def delete_server(self, item: FileBrowserItem, publish_event: bool = True):
"""
Disconnects the subtree rooted at the given item.
Args:
item (:obj:`FileBrowserItem`): Root of subtree to disconnect.
publish_event (bool): If True, push a notification to the event stream.
"""
if not item or not self.is_connection_point(item) or self._is_placeholder(item):
return
nucleus_connector = get_nucleus_connector()
if nucleus_connector:
nucleus_connector.disconnect(item.path)
self._filebrowser.delete_child(item, parent=item.parent)
if publish_event:
# Push a notification event to the event stream
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
event_stream.push(NUCLEUS_SERVER_DELETED_EVENT, payload={"name": item.name, "url": item.path})
def rename_server(self, item: FileBrowserItem, new_name: str, publish_event: bool = True):
"""
Renames the connection item. Note: doesn't change the connection itself, only how it's labeled
in the tree view.
Args:
item (:obj:`FileBrowserItem`): Root of subtree to disconnect.
new_name (str): New name.
publish_event (bool): If True, push a notification to the event stream.
"""
if not item or not self.is_connection_point(item) or self._is_placeholder(item):
return
elif new_name == item.name:
return
old_name, server_url = item.name, item.path
self._filebrowser.delete_child(item, parent=item.parent)
self.add_server(new_name, server_url, publish_event=False)
if publish_event:
# Push a notification event to the event stream
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
event_stream.push(NUCLEUS_SERVER_RENAMED_EVENT, payload={"old_name": old_name, "new_name": new_name, "url": server_url})
def reconnect_server(self, item: FileBrowserItem):
"""
Reconnects the server at the given path. Clears out any cached authentication tokens to force the action.
Args:
item (:obj:`FileBrowserItem`): Connection item.
"""
broken_url = omni.client.break_url(item.path)
if broken_url.scheme != 'omniverse':
return
if self.is_connection_point(item):
nucleus_connector = get_nucleus_connector()
if nucleus_connector:
nucleus_connector.reconnect(item.path)
def log_out_server(self, item: NucleusConnectionItem):
"""
Log out from the server at the given path.
Args:
item (:obj:`NucleusConnectionItem`): Connection item.
"""
if not isinstance(item, NucleusConnectionItem):
return
broken_url = omni.client.break_url(item.path)
if broken_url.scheme != 'omniverse':
return
omni.client.sign_out(item.path)
def add_bookmark(self, name: str, path: str, is_folder: bool = True, publish_event: bool = True) -> BookmarkItem:
"""
Creates a :obj:`FileBrowserModel` rooted at the given path, and connects its subtree to the
tree view.
Args:
name (str): Name of the bookmark.
path (str): Fullpath of the connection, e.g. "omniverse://ov-content". Paths to
Omniverse servers should contain the prefix, "omniverse://".
is_folder (bool): If the item to be bookmarked is a folder or not. Default to True.
publish_event (bool): If True, push a notification to the event stream.
Returns:
:obj:`BookmarkItem`
"""
bookmark = None
if not (name and path):
return None
if not self._collections.get("bookmarks", None):
return None
if self._bookmark_model:
bookmark = self._bookmark_model.add_bookmark(name, path, is_folder=is_folder)
self._filebrowser.refresh_ui(self._bookmark_model.root)
if bookmark and publish_event:
# Push a notification event to the event stream
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
event_stream.push(BOOKMARK_ADDED_EVENT, payload={"name": bookmark.name, "url": bookmark.path})
return bookmark
def delete_bookmark(self, item: BookmarkItem, publish_event: bool = True):
"""
Deletes the given bookmark.
Args:
item (:obj:`FileBrowserItem`): Bookmark item.
publish_event (bool): If True, push a notification to the event stream.
"""
if not item or not self.is_bookmark(item):
return
bookmark = None
if self._bookmark_model:
bookmark = {"name": item.name, "url": item.path}
self._bookmark_model.delete_bookmark(item)
self._filebrowser.refresh_ui(self._bookmark_model.root)
if bookmark and publish_event:
# Push a notification event to the event stream
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
event_stream.push(BOOKMARK_DELETED_EVENT, payload=bookmark)
def rename_bookmark(self, item: BookmarkItem, new_name: str, new_url: str, publish_event: bool = True):
"""
Renames the bookmark item. Note: doesn't change the connection itself, only how it's labeled
in the tree view.
Args:
item (:obj:`FileBrowserItem`): Bookmark item.
new_name (str): New name.
new_url (str): New url address.
publish_event (bool): If True, push a notification to the event stream.
"""
if not item or not self.is_bookmark(item):
return
elif new_name == item.name and new_url == item.path:
return
old_name, is_folder = item.name, item.is_folder
self.delete_bookmark(item, publish_event=False)
self.add_bookmark(new_name, new_url, is_folder=is_folder, publish_event=False)
item.set_bookmark_path(new_url)
if publish_event:
# Push a notification event to the event stream
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
event_stream.push(BOOKMARK_RENAMED_EVENT, payload={"old_name": old_name, "new_name": new_name, "url": new_url})
def mount_user_folders(self, folders: dict):
"""
Mounts given set of user folders under the local collection.
Args:
folders (dict): Name, path pairs.
"""
if not folders:
return
collection = self._collections.get("my-computer", None)
if not collection:
return
for name, path in folders.items():
if os.path.exists(path):
self._filebrowser.add_model_as_subtree(FileSystemModel(name, path), parent=collection)
def _is_placeholder(self, item: FileBrowserItem) -> bool:
"""
Returns True if given item is the placeholder item.
Returns:
bool
"""
if item and self.__placeholder_model:
return item == self.__placeholder_model.root
return False
def toggle_grid_view(self, show_grid_view: bool):
"""
Toggles file picker between grid and list view.
Args:
show_grid_view (bool): True to show grid view, False to show list view.
"""
self._filebrowser.toggle_grid_view(show_grid_view)
@property
def show_grid_view(self):
"""
Gets file picker stage of grid or list view.
Returns:
bool: True if grid view shown or False if list view shown.
"""
return self._filebrowser.show_grid_view
def scale_grid_view(self, scale: float):
"""
Scale file picker's grid view icon size.
Args:
scale (float): Scale of the icon.
"""
self._filebrowser.scale_grid_view(scale)
def show_notification(self):
"""Utility to show the notification frame."""
self._filebrowser.show_notification()
def hide_notification(self):
"""Utility to hide the notification frame."""
self._filebrowser.hide_notification()
def _find_item_with_callback(self, path: str, callback: Callable):
"""
Wrapper around FilePickerModel.find_item_with_callback. This is a workaround for accessing the
model's class method, which in hindsight should've been made a utility function.
"""
model = FilePickerModel()
model.collections = self.collections
model.find_item_with_callback(path, callback)
def _server_status_changed(self, url: str, status: omni.client.ConnectionStatus) -> None:
"""Updates NucleuseConnectionItem signed in status based upon server status changed."""
item = self.get_connection_with_url(url)
if item:
if status == omni.client.ConnectionStatus.CONNECTED:
item.signed_in = True
FilePickerView.__connected_servers.add(url)
elif status == omni.client.ConnectionStatus.SIGNED_OUT:
item.signed_in = False
if url in FilePickerView.__connected_servers:
FilePickerView.__connected_servers.remove(url)
@staticmethod
def is_connected(url: str) -> bool:
return url in FilePickerView.__connected_servers
| 37,500 | Python | 40.667778 | 150 | 0.617867 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/style.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb
import omni.ui as ui
from pathlib import Path
try:
THEME = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle")
except Exception:
THEME = None
finally:
THEME = THEME or "NvidiaDark"
CURRENT_PATH = Path(__file__).parent.absolute()
ICON_ROOT = CURRENT_PATH.parent.parent.parent.parent.joinpath("icons/")
ICON_PATH = ICON_ROOT.joinpath(THEME)
THUMBNAIL_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data").joinpath("thumbnails")
def get_style():
if THEME == "NvidiaLight":
BACKGROUND_COLOR = 0xFF535354
BACKGROUND_SELECTED_COLOR = 0xFF6E6E6E
BACKGROUND_HOVERED_COLOR = 0xFF6E6E6E
SECONDARY_COLOR = 0xFFE0E0E0
BORDER_COLOR = 0xFF707070
MENU_BACKGROUND_COLOR = 0xFF343432
MENU_SEPARATOR_COLOR = 0x449E9E9E
PROGRESS_BACKGROUND = 0xFF606060
PROGRESS_BORDER = 0xFF323434
PROGRESS_BAR = 0xFFC9974C
PROGRESS_TEXT_COLOR = 0xFFD8D8D8
TITLE_COLOR = 0xFF707070
TEXT_COLOR = 0xFF8D760D
TEXT_HINT_COLOR = 0xFFD6D6D6
SPLITTER_HOVER_COLOR = 0xFFB0703B
else:
BACKGROUND_COLOR = 0xFF23211F
BACKGROUND_SELECTED_COLOR = 0xFF8A8777
BACKGROUND_HOVERED_COLOR = 0xFF3A3A3A
SECONDARY_COLOR = 0xFF9E9E9E
BORDER_COLOR = 0xFF8A8777
MENU_BACKGROUND_COLOR = 0xFF343432
MENU_SEPARATOR_COLOR = 0x449E9E9E
PROGRESS_BACKGROUND = 0xFF606060
PROGRESS_BORDER = 0xFF323434
PROGRESS_BAR = 0xFFC9974C
PROGRESS_TEXT_COLOR = 0xFFD8D8D8
TITLE_COLOR = 0xFFCECECE
TEXT_COLOR = 0xFF9E9E9E
TEXT_HINT_COLOR = 0xFF4A4A4A
SPLITTER_HOVER_COLOR = 0xFFB0703B
style = {
"Button": {
"background_color": BACKGROUND_COLOR,
"selected_color": BACKGROUND_SELECTED_COLOR,
"color": TEXT_COLOR,
"margin": 0,
"padding": 0
},
"Button:hovered": {"background_color": BACKGROUND_HOVERED_COLOR},
"Button.Label": {"color": TEXT_COLOR},
"Button.Label:disabled": {"color": BACKGROUND_HOVERED_COLOR},
"ComboBox": {
"background_color": BACKGROUND_COLOR,
"selected_color": BACKGROUND_SELECTED_COLOR,
"color": TEXT_COLOR,
},
"ComboBox:hovered": {"background_color": BACKGROUND_HOVERED_COLOR},
"ComboBox:selected": {"background_color": BACKGROUND_SELECTED_COLOR},
"ComboBox.Button": {
"background_color": BACKGROUND_COLOR,
"selected_color": BACKGROUND_SELECTED_COLOR,
"color": TEXT_COLOR,
"margin_width": 0,
"padding": 0,
},
"ComboBox.Button:hovered": {"background_color": BACKGROUND_HOVERED_COLOR},
"ComboBox.Button.Label": {"color": TEXT_COLOR, "alignment": ui.Alignment.LEFT_CENTER},
"ComboBox.Button.Glyph": {"color": 0xFFFFFFFF},
"ComboBox.Menu": {
"background_color": 0x0,
"margin": 0,
"padding": 0,
},
"ComboBox.Menu.Frame": {
"background_color": 0xFF343432,
"border_color": BORDER_COLOR,
"border_width": 0,
"border_radius": 4,
"margin": 2,
"padding": 0,
},
"ComboBox.Menu.Background": {
"background_color": 0xFF343432,
"border_color": BORDER_COLOR,
"border_width": 0,
"border_radius": 4,
"margin": 0,
"padding": 0,
},
"ComboBox.Menu.Item": {"background_color": 0x0, "color": TEXT_COLOR},
"ComboBox.Menu.Item:hovered": {"background_color": BACKGROUND_SELECTED_COLOR},
"ComboBox.Menu.Item:selected": {"background_color": BACKGROUND_SELECTED_COLOR},
"ComboBox.Menu.Item::left": {"color": TEXT_COLOR, "alignment": ui.Alignment.LEFT_CENTER},
"ComboBox.Menu.Item::right": {"color": TEXT_COLOR, "alignment": ui.Alignment.RIGHT_CENTER},
"Field": {"background_color": 0x0, "selected_color": BACKGROUND_SELECTED_COLOR, "color": TEXT_COLOR, "alignment": ui.Alignment.LEFT_CENTER},
"Label": {"background_color": 0x0, "color": TEXT_COLOR},
"Menu": {"background_color": MENU_BACKGROUND_COLOR, "color": TEXT_COLOR, "border_radius": 2},
"Menu.Item": {"background_color": 0x0, "margin": 0},
"Menu.Separator": {"background_color": 0x0, "color": MENU_SEPARATOR_COLOR},
"Rectangle": {"background_color": 0x0},
"FileBar": {"background_color": BACKGROUND_COLOR, "color": TEXT_COLOR},
"FileBar.Label": {"background_color": 0x0, "color": TEXT_COLOR, "alignment": ui.Alignment.LEFT_CENTER, "margin_width": 4, "margin_height": 0},
"FileBar.Label:disabled": {"color": TEXT_HINT_COLOR},
"DetailView": {"background_color": BACKGROUND_COLOR, "color": TEXT_COLOR, "margin": 0, "padding": 0},
"DetailView.ScrollingFrame": {"background_color": BACKGROUND_COLOR, "secondary_color": SECONDARY_COLOR},
"DetailFrame": {
"background_color": BACKGROUND_COLOR,
"secondary_color": 0xFF0000FF,
"color": TEXT_COLOR,
"border_radius": 1,
"border_color": 0xFF535354,
"margin_width": 4,
"margin_height": 1.5,
"padding": 0
},
"DetailFrame.Header.Label": {"color": TITLE_COLOR},
"DetailFrame.Header.Icon": {"color": 0xFFFFFFFF, "padding": 0, "alignment": ui.Alignment.LEFT_CENTER},
"DetailFrame.Body": {"margin_height": 2, "padding": 0},
"DetailFrame.Separator": {"background_color": TEXT_HINT_COLOR},
"DetailFrame.LineItem::left_aligned": {"alignment": ui.Alignment.LEFT_CENTER},
"DetailFrame.LineItem::right_aligned": {"alignment": ui.Alignment.RIGHT_CENTER},
"ProgressBar": {
"background_color": PROGRESS_BACKGROUND,
"border_width": 2,
"border_radius": 0,
"border_color": PROGRESS_BORDER,
"color": PROGRESS_BAR,
"secondary_color": PROGRESS_TEXT_COLOR,
"margin": 0,
"padding": 0,
"alignment": ui.Alignment.LEFT_CENTER,
},
"ProgressBar.Frame": {"background_color": BACKGROUND_COLOR, "margin": 0, "padding": 0},
"ProgressBar.Puck": {"background_color": PROGRESS_BAR, "margin": 2},
"ToolBar": {"alignment": ui.Alignment.CENTER, "margin_height": 2},
"ToolBar.Button": {"background_color": 0x0, "color": TEXT_COLOR, "margin_width": 2, "padding": 2},
"ToolBar.Button.Label": {"color": TEXT_COLOR, "alignment": ui.Alignment.LEFT_CENTER},
"ToolBar.Button.Image": {"background_color": 0x0, "color": 0xFFFFFFFF, "alignment": ui.Alignment.CENTER},
"ToolBar.Button:hovered": {"background_color": 0xFF6E6E6E},
"ToolBar.Field": {"background_color": BACKGROUND_COLOR, "color": TEXT_COLOR, "margin": 0, "padding": 0},
"Splitter": {"background_color": 0x0, "margin_width": 0},
"Splitter:hovered": {"background_color": SPLITTER_HOVER_COLOR},
"Splitter:pressed": {"background_color": SPLITTER_HOVER_COLOR},
"LoadingPane.Bg": {"background_color": BACKGROUND_COLOR},
"LoadingPane.Button": {
"background_color": BACKGROUND_HOVERED_COLOR,
"selected_color": BACKGROUND_SELECTED_COLOR,
"color": TEXT_COLOR,
},
"LoadingPane.Button:hovered": {"background_color": BACKGROUND_SELECTED_COLOR},
}
return style
| 7,983 | Python | 45.418604 | 150 | 0.613429 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/timestamp.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.
#
__all__ = ["TimestampWidget"]
import datetime
import omni.ui as ui
from .datetime import DateWidget, TimeWidget, TimezoneWidget
from typing import List
from .style import get_style
class TimestampWidget:
def __init__(self, **kwargs):
"""
Timestamp Widget.
"""
self._url = None
self._on_check_changed_fn = []
self._checkpoint_widget = None
self._frame = None
self._timestamp_checkbox = None
self._datetime_stack = None
self._desc_text = None
self._date = None
self._time = None
self._timezone = None
self._selection_changed_fn = kwargs.get("selection_changed_fn", None)
self._frame = ui.Frame(visible=True, height=100, style=get_style())
self._frame.set_build_fn(self._build_ui)
self._frame.rebuild()
def __del__(self):
self.destroy()
def destroy(self):
self._on_check_changed_fn.clear()
self._checkpoint_widget = None
self._selection_changed_fn = None
if self._timestamp_checkbox:
self._timestamp_checkbox.model.remove_value_changed_fn(self._checkbox_fn_id)
self._timestamp_checkbox = None
self._datetime_stack = None
self._frame = None
if self._date:
self._date.model.remove_value_changed_fn(self._date_fn_id)
self._date.destroy()
self._date = None
if self._time:
self._time.model.remove_value_changed_fn(self._time_fn_id)
self._time.destroy()
self._time = None
if self._timezone:
self._timezone.model.remove_value_changed_fn(self._timezone_fn_id)
self._timezone.destroy()
self._timezone = None
def rebuild(self, selected: List[str]):
self._frame.rebuild()
def _build_ui(self):
with ui.ZStack(height=32, width=0):
self._datetime_stack = ui.VStack(visible=False)
with self._datetime_stack:
with ui.HStack(height=0, spacing=6):
self._timestamp_checkbox = ui.CheckBox(width=0)
self._checkbox_fn_id = self._timestamp_checkbox.model.add_value_changed_fn(self._on_timestamp_checked)
ui.Label("Resolve with")
with ui.HStack(height=0, spacing=0):
ui.Label("Date:", width=0)
self._date = DateWidget()
self._date_fn_id = self._date.model.add_value_changed_fn(self._on_timestamp_changed)
ui.Label("Time:", width=0)
self._time = TimeWidget()
self._time_fn_id = self._time.model.add_value_changed_fn(self._on_timestamp_changed)
self._timezone = TimezoneWidget()
self._timezone_fn_id = self._timezone.model.add_value_changed_fn(self._on_timestamp_changed)
self._desc_text = ui.Label("does not support")
@staticmethod
def create_timestamp_widget() -> 'TimestampWidget':
widget = TimestampWidget()
return widget
@staticmethod
def delete_timestamp_widget(widget: 'TimestampWidget'):
if widget:
widget.destroy()
@staticmethod
def on_selection_changed(widget: 'TimestampWidget', selected: List[str]):
if not widget:
return
if selected:
widget.set_url(selected[-1] or None)
else:
widget.set_url(None)
# show timestamp status according to the checkpoint_widget status
def set_checkpoint_widget(self, widget):
self._checkpoint_widget = widget
def on_list_checkpoint(self, select):
# Fix OM-85963: It seems this called without UI (not builded or destory?) in some test
if self._datetime_stack:
has_checkpoint = self._checkpoint_widget is not None and not self._checkpoint_widget.empty()
self._datetime_stack.visible = has_checkpoint
self._desc_text.visible = not has_checkpoint
def set_url(self, url):
self._url = url
def get_timestamp_url(self, url):
if url and url != self._url:
return url
if not self._timestamp_checkbox.model.as_bool:
return self._url
dt = datetime.datetime(
self._date.model.year,
self._date.model.month,
self._date.model.day,
self._time.model.hour,
self._time.model.minute,
self._time.model.second,
tzinfo=self._timezone.model.timezone,
)
full_url = f"{self._url}?×tamp={int(dt.timestamp())}"
return full_url
def add_on_check_changed_fn(self, fn):
self._on_check_changed_fn.append(fn)
def _on_timestamp_checked(self, model):
full_url = self.get_timestamp_url(None)
for fn in self._on_check_changed_fn:
fn(full_url)
def _on_timestamp_changed(self, model):
if self._timestamp_checkbox.model.as_bool:
self._on_timestamp_checked(None)
@property
def check(self):
if self._timestamp_checkbox:
return self._timestamp_checkbox.model.as_bool
return False
@check.setter
def check(self, value: bool):
if self._timestamp_checkbox:
self._timestamp_checkbox.model.set_value(value)
| 5,838 | Python | 34.822086 | 122 | 0.595923 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.