file_path
stringlengths 21
202
| content
stringlengths 19
1.02M
| size
int64 19
1.02M
| lang
stringclasses 8
values | avg_line_length
float64 5.88
100
| max_line_length
int64 12
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.kit.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 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/about_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 omni.kit.window.popup_dialog.dialog import PopupDialog
import omni.ui as ui
from .style import get_style, ICON_PATH
class AboutDialog(PopupDialog):
"""Dialog to show the omniverse server info."""
def __init__(
self,
server_info,
):
"""
Args:
server_info ([FileBrowserItem]): server's information.
title (str): Title of the dialog. Default "Confirm File Deletion".
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`)
"""
super().__init__(
width=400,
title="About",
ok_handler=lambda self: self.hide(),
ok_label="Close",
modal=True,
)
self._server_info = server_info
self._build_ui()
def _build_ui(self) -> None:
with self._window.frame:
with ui.ZStack(style=get_style(),spacing=6):
ui.Rectangle(style_type_name_override="Background")
with ui.VStack(style_type_name_override="Dialog", spacing=6):
ui.Spacer(height=25)
with ui.HStack(style_type_name_override="Dialog", spacing=6, height=60):
ui.Spacer(width=15)
ui.Image(
f"{ICON_PATH}/omniverse_logo_64.png",
width=50,
height=50,
alignment=ui.Alignment.CENTER
)
ui.Spacer(width=5)
with ui.VStack(style_type_name_override="Dialog"):
ui.Spacer(height=10)
ui.Label("Nucleus", style={"font_size": 20})
ui.Label(self._server_info.version)
ui.Spacer(height=5)
with ui.HStack(style_type_name_override="Dialog"):
ui.Spacer(width=15)
with ui.VStack(style_type_name_override="Dialog"):
ui.Label("Services", style={"font_size": 20})
self._build_info_item(True, "Discovery")
# OM-94622: what it this auth for? seems token is not correct
self._build_info_item(True, "Auth 1.4.5+tag-" + self._server_info.auth_token[:8])
has_tagging = False
try:
# TODO: how to check the tagging is exist? how to get it's version?
import omni.tagging_client
has_tagging = True
except ImportError:
pass
self._build_info_item(has_tagging, "Tagging")
# there always has search service in content browser
self._build_info_item(True, "NGSearch")
self._build_info_item(True, "Search")
ui.Label("Features", style={"font_size": 20})
self._build_info_item(True, "Versioning")
self._build_info_item(self._server_info.checkpoints_enabled, "Atomic checkpoints")
self._build_info_item(self._server_info.omniojects_enabled, "Omni-objects V2")
self._build_ok_cancel_buttons(disable_cancel_button=True)
def _build_info_item(self, supported: bool, info: str):
with ui.HStack(style_type_name_override="Dialog", spacing=6):
ui.Spacer(width=5)
if supported:
ui.Image(
"resources/icons/Ok_64.png",
width=20,
height=20,
alignment=ui.Alignment.CENTER
)
else:
ui.Image(
"resources/icons/Cancel_64.png",
width=20,
height=20,
alignment=ui.Alignment.CENTER
)
ui.Label(info)
ui.Spacer()
def destroy(self) -> None:
"""Destructor."""
self._window = None
| 4,829 | Python | 43.722222 | 110 | 0.502174 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/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.app
import omni.client
from carb import events, log_warn
from .utils import exec_after_redraw
from .view import (
BOOKMARK_ADDED_EVENT, BOOKMARK_DELETED_EVENT, BOOKMARK_RENAMED_EVENT,
NUCLEUS_SERVER_ADDED_EVENT, NUCLEUS_SERVER_DELETED_EVENT, NUCLEUS_SERVER_RENAMED_EVENT
)
g_singleton = None
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class FilePickerExtension(omni.ext.IExt):
"""
The filepicker extension is not necessarily integral to using the widget. However, it is useful for handling
singleton tasks for the class.
"""
def on_startup(self, ext_id):
# Save away this instance as singleton
global g_singleton
g_singleton = self
# Listen for bookmark and server connection events in order to update persistent settings
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
self._event_stream_subscriptions = [
event_stream.create_subscription_to_pop_by_type(BOOKMARK_ADDED_EVENT, self._update_persistent_bookmarks),
event_stream.create_subscription_to_pop_by_type(BOOKMARK_DELETED_EVENT, self._update_persistent_bookmarks),
event_stream.create_subscription_to_pop_by_type(BOOKMARK_RENAMED_EVENT, self._update_persistent_bookmarks),
event_stream.create_subscription_to_pop_by_type(NUCLEUS_SERVER_ADDED_EVENT, self._update_persistent_bookmarks),
event_stream.create_subscription_to_pop_by_type(NUCLEUS_SERVER_DELETED_EVENT, self._update_persistent_bookmarks),
event_stream.create_subscription_to_pop_by_type(NUCLEUS_SERVER_RENAMED_EVENT, self._update_persistent_bookmarks),
]
def _update_persistent_bookmarks(self, event: events.IEvent):
"""When a bookmark is updated or deleted, update persistent settings"""
try:
payload = event.payload.get_dict()
except Exception as e:
log_warn(f"Failed to add omni.client bookmark: {str(e)}")
return
if event.type in [BOOKMARK_ADDED_EVENT, NUCLEUS_SERVER_ADDED_EVENT]:
name = payload.get('name')
url = payload.get('url')
if name and url:
omni.client.add_bookmark(name, url)
elif event.type in [BOOKMARK_DELETED_EVENT, NUCLEUS_SERVER_DELETED_EVENT]:
name = payload.get('name')
if name:
omni.client.remove_bookmark(name)
elif event.type in [BOOKMARK_RENAMED_EVENT, NUCLEUS_SERVER_RENAMED_EVENT]:
old_name = payload.get('old_name')
new_name = payload.get('new_name')
url = payload.get('url')
if old_name and new_name and url:
omni.client.add_bookmark(new_name, url)
if old_name != new_name:
# Wait a few frames for next update to avoid race condition
exec_after_redraw(lambda: omni.client.remove_bookmark(old_name), wait_frames=6)
def on_shutdown(self):
# Clears the auth callback
self._event_stream_subscriptions.clear()
global g_singleton
g_singleton = None
def get_instance():
return g_singleton | 3,845 | Python | 44.785714 | 125 | 0.681144 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/detail_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 omni.ui as ui
import asyncio
import omni.client
from omni.kit.async_engine import run_coroutine
from typing import Callable, List
from collections import namedtuple
from collections import OrderedDict
from carb import log_warn
from datetime import datetime
from omni.kit.helper.file_utils import asset_types
from omni.kit.widget.filebrowser import FileBrowserItem
from .style import get_style, ICON_PATH
class DetailFrameController:
def __init__(self,
glyph: str = None,
build_fn: Callable[[], None] = None,
selection_changed_fn: Callable[[List[str]], None] = None,
filename_changed_fn: Callable[[str], None] = None,
destroy_fn: Callable[[], None] = None,
**kwargs
):
self._frame = None
self._glyph = glyph
self._build_fn = build_fn
self._selection_changed_fn = selection_changed_fn
self._filename_changed_fn = filename_changed_fn
self._destroy_fn = destroy_fn
self._mouse_pressed_fn = kwargs.get("mouse_pressed_fn", None)
self._mouse_double_clicked_fn = kwargs.get("mouse_double_clicked_fn", None)
def build_header(self, collapsed: bool, title: str):
with ui.HStack():
if collapsed:
ui.ImageWithProvider(f"{ICON_PATH}/arrow_right.svg", width=20, height=20)
else:
ui.ImageWithProvider(f"{ICON_PATH}/arrow_down.svg", width=20, height=20)
ui.Label(title.capitalize(), style_type_name_override="DetailFrame.Header.Label")
def build_ui(self, frame: ui.Frame):
if not frame:
return
self._frame = frame
with self._frame:
try:
self._build_fn()
except Exception as e:
log_warn(f"Error detail frame build_ui: {str(e)}")
def on_selection_changed(self, selected: List[str] = []):
if self._frame and self._selection_changed_fn:
self._frame.set_build_fn(lambda: self._selection_changed_fn(selected))
self._frame.rebuild()
def on_filename_changed(self, filename: str):
if self._frame and self._filename_changed_fn:
self._frame.set_build_fn(lambda: self._filename_changed_fn(filename))
self._frame.rebuild()
def destroy(self):
try:
self._destroy_fn()
except Exception:
pass
# NOTE: DO NOT dereference callbacks so that we can rebuild this object if desired.
self._frame = None
class ExtendedFileInfo(DetailFrameController):
MockListEntry = namedtuple("MockListEntry", "relative_path modified_time created_by modified_by size")
_empty_list_entry = MockListEntry("File info", datetime.now(), "", "", 0)
def __init__(self):
super().__init__(
build_fn=self._build_ui_impl,
selection_changed_fn=self._on_selection_changed_impl,
destroy_fn=self._destroy_impl)
self._widget = None
self._current_url = ""
self._resolve_subscription = None
self._time_label = None
self._created_by_label = None
self._modified_by_label = None
self._size_label = None
def build_header(self, collapsed: bool, title: str):
with ui.HStack(style_type_name_override="DetailFrame.Header"):
if collapsed:
ui.ImageWithProvider(f"{ICON_PATH}/arrow_right.svg", width=20, height=20)
else:
ui.ImageWithProvider(f"{ICON_PATH}/arrow_down.svg", width=20, height=20)
icon = asset_types.get_icon(title)
if icon is not None:
ui.ImageWithProvider(icon, width=18, style_type_name_override="DetailFrame.Header.Icon")
ui.Spacer(width=4)
ui.Label(title, elided_text=True, tooltip=title, style_type_name_override="DetailFrame.Header.Label")
def _build_ui_impl(self, selected: List[str] = []):
self._widget = ui.Frame()
run_coroutine(self._build_ui_async(selected))
async def _build_ui_async(self, selected: List[str] = []):
entry = None
if len(selected) == 0:
self._frame.title = "No files selected"
elif len(selected) > 1:
self._frame.title = "Multiple files selected"
else:
result, entry = await omni.client.stat_async(selected[-1])
if result == omni.client.Result.OK and entry:
self._frame.title = entry.relative_path or os.path.basename(selected[-1])
if self._current_url != selected[-1]:
self._current_url = selected[-1]
self._resolve_subscription = omni.client.resolve_subscribe_with_callback(
self._current_url, [self._current_url], None,
lambda result, event, entry, url: self._on_file_change_event(result, entry))
else:
self._frame.title = os.path.basename(selected[-1])
entry = None
entry = entry or self._empty_list_entry
with self._widget:
with ui.ZStack():
ui.Rectangle()
with ui.VStack():
ui.Rectangle(height=2, style_type_name_override="DetailFrame.Separator")
with ui.VStack(style_type_name_override="DetailFrame.Body"):
with ui.HStack(style_type_name_override="DetailFrame.LineItem", spacing=3):
ui.Label("Date Modified", width=0, name="left_aligned")
self._time_label = ui.Label(
FileBrowserItem.datetime_as_string(entry.modified_time),
elided_text=True,
alignment=ui.Alignment.RIGHT_CENTER,
name="right_aligned"
)
with ui.HStack(style_type_name_override="DetailFrame.LineItem", spacing=3):
ui.Label("Created by", width=0, name="left_aligned")
self._created_by_label = ui.Label(entry.created_by,
elided_text=True,
alignment=ui.Alignment.RIGHT_CENTER,
name="right_aligned"
)
with ui.HStack(style_type_name_override="DetailFrame.LineItem", spacing=3):
ui.Label("Modified by", width=0, name="left_aligned")
self._modified_by_label = ui.Label(
entry.modified_by,
elided_text=True,
alignment=ui.Alignment.RIGHT_CENTER,
name="right_aligned"
)
with ui.HStack(style_type_name_override="DetailFrame.LineItem", spacing=3):
ui.Label("File size", width=0, name="left_aligned")
self._size_label = ui.Label(
FileBrowserItem.size_as_string(entry.size),
elided_text=True,
alignment=ui.Alignment.RIGHT_CENTER,
name="right_aligned"
)
def _on_file_change_event(self, result: omni.client.Result, entry: omni.client.ListEntry):
if result == omni.client.Result.OK and self._current_url:
self._time_label.text = FileBrowserItem.datetime_as_string(entry.modified_time)
self._created_by_label.text = entry.created_by
self._modified_by_label.text = entry.modified_by
self._size_label.text = FileBrowserItem.size_as_string(entry.size)
def _on_selection_changed_impl(self, selected: List[str] = []):
self._build_ui_impl(selected)
def _destroy_impl(self, _):
if self._widget:
self._widget.destroy()
self._widget = None
self._resolve_subscription = None
class DetailView:
def __init__(self, **kwargs):
self._widget: ui.Widget = None
self._view: ui.Widget = None
self._file_info = None
self._detail_frames: OrderedDict[str, DetailFrameController] = OrderedDict()
self._build_ui()
def _build_ui(self):
self._widget = ui.Frame()
with self._widget:
with ui.ZStack(style=get_style()):
ui.Rectangle(style_type_name_override="DetailView")
self._view = ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
style_type_name_override="DetailView.ScrollingFrame"
)
self._build_detail_frames()
def _build_detail_frames(self):
async def build_frame_async(frame: ui.Frame, detail_frame: DetailFrameController):
detail_frame.build_ui(frame)
with self._view:
with ui.VStack():
self._file_info = ExtendedFileInfo()
frame = ui.CollapsableFrame(title="File info", height=0, build_header_fn=self._file_info.build_header, style_type_name_override="DetailFrame")
run_coroutine(build_frame_async(frame, self._file_info))
for name, detail_frame in reversed(self._detail_frames.items()):
frame = ui.CollapsableFrame(title=name.capitalize(), height=0, build_header_fn=detail_frame.build_header, style_type_name_override="DetailFrame")
run_coroutine(build_frame_async(frame, detail_frame))
def get_detail_frame(self, name: str) -> DetailFrameController:
if name:
return self._detail_frames.get(name, None)
return None
def add_detail_frame(self,
name: str, glyph: str,
build_fn: Callable[[], ui.Widget],
selection_changed_fn: Callable[[List[str]], None] = None,
filename_changed_fn: Callable[[str], None] = None,
destroy_fn: Callable[[ui.Widget], None] = None):
"""
Adds sub-frame to the detail view, and populates it with a custom built widget.
Args:
name (str): Name of the widget sub-section, this name must be unique over all detail sub-sections.
glyph (str): Associated glyph to display for this subj-section
build_fn (Callable): This callback function builds the widget.
Keyword Args:
selection_changed_fn (Callable): This callback is invoked to handle selection changes.
filename_changed_fn (Callable): This callback is invoked when filename is changed.
destroy_fn (Callable): Cleanup function called when destroyed.
"""
if not name:
return
elif name in self._detail_frames.keys():
# Reject duplicates
log_warn(f"Unable to add detail widget '{name}': already exists.")
return
detail_frame = DetailFrameController(
glyph=glyph,
build_fn=build_fn,
selection_changed_fn=selection_changed_fn,
filename_changed_fn=filename_changed_fn,
destroy_fn=destroy_fn,
)
self.add_detail_frame_from_controller(name, detail_frame)
def add_detail_frame_from_controller(self, name: str, detail_frame: DetailFrameController = None):
"""
Adds sub-frame to the detail view, and populates it with a custom built widget.
Args:
name (str): Name of the widget sub-section, this name must be unique over all detail sub-sections.
controller (:obj:`DetailFrameController`): Controller object that encapsulates all aspects of creating,
updating, and deleting a detail frame widget.
"""
if not name:
return
elif name in self._detail_frames.keys():
# Reject duplicates
log_warn(f"Unable to add detail widget '{name}': already exists.")
return
if detail_frame:
self._detail_frames[name] = detail_frame
self._build_detail_frames()
def delete_detail_frame(self, name: str):
"""
Deletes the specified detail frame.
Args:
name (str): Name of the detail frame.
"""
if name in self._detail_frames.keys():
del self._detail_frames[name]
self._build_detail_frames()
def on_selection_changed(self, selected: List[FileBrowserItem] = []):
"""
When the user changes their filebrowser selection(s), invokes the callbacks for the detail frames.
Args:
selected (:obj:`FileBrowserItem`): List of new selections.
"""
selected_paths = [sel.path for sel in selected if sel]
if self._file_info:
self._file_info.on_selection_changed(selected_paths)
for _, detail_frame in self._detail_frames.items():
detail_frame.on_selection_changed(selected_paths)
def on_filename_changed(self, filename: str = ''):
"""
When the user edits the filename, invokes the callbacks for the detail frames.
Args:
filename (str): Current filename.
"""
for _, detail_frame in self._detail_frames.items():
detail_frame.on_filename_changed(filename)
def destroy(self):
for _, detail_frame in self._detail_frames.items():
detail_frame.destroy()
self._detail_frames.clear()
self._widget = None
self._view = None | 14,144 | Python | 42.523077 | 165 | 0.583498 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/__init__.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""
This Kit extension provides both a popup dialog as well as an embeddable widget that
you can add to your code for browsing the filesystem. Incorporates
:obj:`BrowserBarWidget` and :obj:`FileBrowserWidget` into a general-purpose utility.
The filesystem can either be from your local machine or the Omniverse server.
Example:
With just a few lines of code, you can create a ready-made dialog window. Then,
customize it by setting any number of attributes.
filepicker = FilePickerDialog(
"my-filepicker",
apply_button_label="Open",
click_apply_handler=on_click_open,
click_cancel_handler=on_click_cancel )
filepicker.show()
.. _Google Python Style Guide:
http://google.github.io/styleguide/pyguide.html
"""
import carb.events
UI_READY_EVENT: int = carb.events.type_from_string("omni.kit.window.filepicker.UI_READY")
SETTING_ROOT = "/exts/omni.kit.window.filepicker/"
SETTING_PERSISTENT_ROOT = "/persistent" + SETTING_ROOT
SETTING_PERSISTENT_SHOW_GRID_VIEW = SETTING_PERSISTENT_ROOT + "show_grid_view"
SETTING_PERSISTENT_GRID_VIEW_SCALE = SETTING_PERSISTENT_ROOT + "grid_view_scale"
from .extension import FilePickerExtension
from .dialog import FilePickerDialog
from .widget import FilePickerWidget
from .view import FilePickerView
from .model import FilePickerModel
from .api import FilePickerAPI
from .context_menu import (
BaseContextMenu,
ContextMenu,
CollectionContextMenu,
BookmarkContextMenu,
UdimContextMenu
)
from .detail_view import DetailView, DetailFrameController
from .tool_bar import ToolBar
from .timestamp import TimestampWidget
from omni.kit.widget.search_delegate import SearchDelegate, SearchResultsModel, SearchResultsItem
| 2,183 | Python | 37.315789 | 97 | 0.770499 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/bookmark_model.py | # Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["BookmarkItem", "BookmarkItemFactory", "BookmarkModel"]
import re
import omni.client
from typing import Dict
from datetime import datetime
from omni import ui
from omni.kit.widget.filebrowser import FileBrowserItem, FileBrowserModel, find_thumbnails_for_files_async
from omni.kit.widget.filebrowser.model import FileBrowserItemFields
from .style import ICON_PATH
class BookmarkItem(FileBrowserItem):
_thumbnail_dict: Dict = {}
def __init__(self, path: str, fields: FileBrowserItemFields, is_folder: bool = True):
super().__init__(path, fields, is_folder=is_folder)
self._path = self.format_bookmark_path(path)
self._expandable = False
def on_list_change_event(self, event: omni.client.ListEvent, entry: omni.client.ListEntry) -> bool:
"""
Handles ListEvent changes, should update this item's children list with the corresponding ListEntry.
Args:
event (:obj:`omni.client.ListEvent`): One of of {UNKNOWN, CREATED, UPDATED, DELETED, METADATA, LOCKED, UNLOCKED}.
entry (:obj:`omni.client.ListEntry`): Updated entry as defined by omni.client.
"""
# bookmark item doesn't need to populate children, so always return False indicating item is
# not changed
return False
def set_bookmark_path(self, path : str) -> None:
"""Sets the bookmark item path"""
self._path = path
@property
def readable(self) -> bool:
return (self._fields.permissions & omni.client.AccessFlags.READ) > 0
@property
def writeable(self) -> bool:
return (self._fields.permissions & omni.client.AccessFlags.WRITE) > 0
@property
def expandable(self) -> bool:
return self._expandable
@expandable.setter
def expandable(self, value: bool):
self._expandable = value
@property
def hideable(self) -> bool:
return False
def format_bookmark_path(self, path: str):
"""Helper method to generate a bookmark path from the given path."""
# OM-66726: Content Browser should edit bookmarks similar to Navigator
if self.is_local_path(path) and not path.startswith("file://"):
# Need to prefix "file://" for local path, so that local bookmark works in Navigator
path = "file://" + path
# make sure folder path ends with "/" so Navigator would recognize it as a directory
if self._is_folder:
path = path.rstrip("/") + "/"
return path
@staticmethod
def is_bookmark_folder(path: str):
"""Helper method to check if a given path is a bookmark of a folder."""
return path.endswith("/")
@staticmethod
def is_local_path(path: str) -> bool:
"""Returns True if given path is a local path"""
broken_url = omni.client.break_url(path)
if broken_url.scheme == "file":
return True
elif broken_url.scheme == "omniverse":
return False
# Return True if root directory looks like beginning of a Linux or Windows path
root_name = broken_url.path.split("/")[0]
return not root_name or re.match(r"[A-Za-z]:", root_name) is not None
async def get_custom_thumbnails_for_folder_async(self) -> Dict:
"""
Returns the thumbnail dictionary for this (folder) item.
Returns:
Dict: With children url's as keys, and url's to thumbnail files as values.
"""
if not self.is_folder:
return {}
# Files in the root folder only
file_urls = []
for _, item in self.children.items():
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
class BookmarkItemFactory:
@staticmethod
def create_bookmark_item(name: str, path: str, is_folder: bool = True) -> BookmarkItem:
if not name:
return None
access = omni.client.AccessFlags.READ | omni.client.AccessFlags.WRITE
fields = FileBrowserItemFields(name, datetime.now(), 0, access)
item = BookmarkItem(path, fields, is_folder=is_folder)
item._models = (ui.SimpleStringModel(item.name), datetime.now(), ui.SimpleStringModel(""))
return item
@staticmethod
def create_group_item(name: str, path: str) -> BookmarkItem:
item = BookmarkItemFactory.create_bookmark_item(name, path, is_folder=True)
item.icon = f"{ICON_PATH}/bookmark.svg"
item.populated = True
item.expandable = True
return item
class BookmarkModel(FileBrowserModel):
"""
A Bookmark model class for grouping bookmarks.
Args:
name (str): Name of root item.
root_path (str): Root path.
"""
def __init__(self, name: str, root_path: str, **kwargs):
super().__init__(**kwargs)
self._root = BookmarkItemFactory.create_group_item(name, root_path)
def add_bookmark(self, name: str, path: str, is_folder: bool = True) -> BookmarkItem:
if name and path:
item = BookmarkItemFactory.create_bookmark_item(name, path, is_folder=is_folder)
else:
return None
self._root.add_child(item)
self._item_changed(self._root)
return item
def delete_bookmark(self, item: BookmarkItem):
if item:
self._root.del_child(item.name)
self._item_changed(self._root)
| 6,219 | Python | 35.16279 | 125 | 0.6411 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/dialog.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 typing import List, Callable, Tuple
from omni.kit.widget.filebrowser import FileBrowserModel
from omni.kit.widget.search_delegate import SearchDelegate
from .widget import FilePickerWidget
from .detail_view import DetailFrameController
from .utils import exec_after_redraw
class FilePickerDialog:
"""
A popup window for browsing the filesystem and taking action on a selected file.
Includes a browser bar for keyboard input with auto-completion for navigation of the tree
view. For similar but different options, see also :obj:`FilePickerWidget` and :obj:`FilePickerView`.
Args:
title (str): Window title. Default None.
Keyword Args:
width (int): Window width. Default 1000.
height (int): Window height. Default 600.
click_apply_handler (Callable): Function that will be called when the user accepts
the selection. Function signature:
void apply_handler(file_name: str, dir_name: str).
click_cancel_handler (Callable): Function that will be called when the user clicks
the cancel button. Function signature:
void cancel_handler(file_name: str, dir_name: str).
other: Additional args listed for :obj:`FilePickerWidget`
"""
def __init__(self, title: str, **kwargs):
self._window = None
self._widget = None
self._width = kwargs.get("width", 1000)
self._height = kwargs.get("height", 600)
self._click_cancel_handler = kwargs.get("click_cancel_handler", None)
self._click_apply_handler = kwargs.get("click_apply_handler")
self.__show_task = None
self._key_functions = {
int(carb.input.KeyboardInput.ESCAPE): self._click_cancel_handler,
# OM-79404: Add enter key press handler
int(carb.input.KeyboardInput.ENTER): self._click_apply_handler,
}
self._build_ui(title, **kwargs)
def _build_ui(self, title: str, **kwargs):
window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_DOCKING
self._window = ui.Window(title, width=self._width, height=self._height, flags=window_flags)
self._window.set_key_pressed_fn(self._on_key_pressed)
def on_cancel(*args):
if self._click_cancel_handler:
self._click_cancel_handler(*args)
else:
self._window.visible = False
with self._window.frame:
kwargs["click_cancel_handler"] = on_cancel
self._key_functions[int(carb.input.KeyboardInput.ESCAPE)] = on_cancel
self._widget = FilePickerWidget(title, window=self._window, **kwargs)
self._window.set_width_changed_fn(self._widget._on_window_width_changed)
def _on_key_pressed(self, key, mod, pressed):
if not pressed:
return
func = self._key_functions.get(key)
if func and mod in (0, ui.Widget.FLAG_WANT_CAPTURE_KEYBOARD):
filename, dirname = self._widget.get_selected_filename_and_directory()
func(filename, dirname)
def set_visibility_changed_listener(self, listener: Callable[[bool], None]):
"""
Call the given handler when window visibility is changed.
Args:
listener (Callable): Handler with signature listener[visible: bool).
"""
if self._window:
self._window.set_visibility_changed_fn(listener)
def add_connections(self, connections: dict):
"""
Adds specified server connections to the browser.
Args:
connections (dict): A dictionary of name, path pairs. For example:
{"C:": "C:", "ov-content": "omniverse://ov-content"}. Paths to Omniverse servers
should be prefixed with "omniverse://".
"""
self._widget.api.add_connections(connections)
def set_current_directory(self, path: str):
"""
Procedurally sets the current directory path.
Args:
path (str): The full path name of the folder, e.g. "omniverse://ov-content/Users/me.
Raises:
:obj:`RuntimeWarning`: If path doesn't exist or is unreachable.
"""
self._widget.api.set_current_directory(path)
def get_current_directory(self) -> str:
"""
Returns the current directory from the browser bar.
Returns:
str: The system path, which may be different from the displayed path.
"""
return self._widget.api.get_current_directory()
def get_current_selections(self, pane: int = 2) -> List[str]:
"""
Returns current selected as list of system path names.
Args:
pane (int): Specifies pane to retrieve selections from, one of {TREEVIEW_PANE = 1, LISTVIEW_PANE = 2,
BOTH = None}. Default LISTVIEW_PANE.
Returns:
[str]: List of system paths (which may be different from displayed paths, e.g. bookmarks)
"""
return self._widget.api.get_current_selections(pane)
def set_filename(self, filename: str):
"""
Sets the filename in the file bar, at bottom of the dialog.
Args:
filename (str): The filename only (and not the fullpath), e.g. "myfile.usd".
"""
self._widget.api.set_filename(filename)
def get_filename(self) -> str:
"""
Returns:
str: Currently selected filename.
"""
return self._widget.api.get_filename()
def get_file_postfix(self) -> str:
"""
Returns:
str: Currently selected postfix.
"""
return self._widget.file_bar.selected_postfix
def set_file_postfix(self, postfix: str):
"""Sets the file postfix in the file bar."""
self._widget.file_bar.set_postfix(postfix)
def get_file_postfix_options(self) -> List[str]:
"""
Returns:
List[str]: List of all postfix strings.
"""
return self._widget.file_bar.postfix_options
def get_file_extension(self) -> str:
"""
Returns:
str: Currently selected filename extension.
"""
return self._widget.file_bar.selected_extension
def set_file_extension(self, extension: str):
"""Sets the file extension in the file bar."""
self._widget.file_bar.set_extension(extension)
def get_file_extension_options(self) -> List[Tuple[str, str]]:
"""
Returns:
List[str]: List of all extension options strings.
"""
return self._widget.file_bar.extension_options
def set_filebar_label_name(self, name: str):
"""
Sets the text of the name label for filebar, at the bottom of dialog.
Args:
name (str): By default, it's "File name" if it's not set. For some senarios that,
it only allows to choose folder, it can be configured with this API for better UX.
"""
self._widget.file_bar.label_name = name
def get_filebar_label_name(self) -> str:
"""
Returns:
str: Currently text of name label for file bar.
"""
return self._widget.file_bar.label_name
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._widget.set_item_filter_fn(item_filter_fn)
def set_click_apply_handler(self, click_apply_handler: Callable[[str, str], None]):
"""
Sets the function to execute upon clicking apply.
Args:
click_apply_handler (Callable): Signature is void fn(filename: str, dirname: str)
"""
self._widget.set_click_apply_handler(click_apply_handler)
# OM-79404: update key func for ENTER key when reseting click apply handler
self._key_functions[int(carb.input.KeyboardInput.ENTER)] = click_apply_handler
def navigate_to(self, path: str):
"""
Navigates to a path, i.e. the path's parent directory will be expanded and leaf selected.
Args:
path (str): The path to navigate to.
"""
self._widget.api.navigate_to(path)
def toggle_bookmark_from_path(self, name: str, path: str, is_bookmark: bool, is_folder: bool = True):
"""
Adds/deletes the given bookmark with the specified path. If deleting, then the path argument
is optional.
Args:
name (str): Name to call the bookmark or existing name if delete.
path (str): Path to the bookmark.
is_bookmark (bool): True to add, False to delete.
is_folder (bool): Whether the item to be bookmarked is a folder.
"""
self._widget.api.toggle_bookmark_from_path(name, path, is_bookmark, is_folder=is_folder)
def refresh_current_directory(self):
"""Refreshes the current directory set in the browser bar."""
self._widget.api.refresh_current_directory()
@property
def current_filter_option(self):
"""int: Index of current filter option, range 0 .. num_filter_options."""
return self._widget.current_filter_option
def add_detail_frame_from_controller(self, name: str, controller: DetailFrameController):
"""
Adds subsection to the detail view, and populate it with a custom built widget.
Args:
name (str): Name of the widget sub-section, this name must be unique over all detail sub-sections.
controller (:obj:`DetailFrameController`): Controller object that encapsulates all aspects of creating,
updating, and deleting a detail frame widget.
Returns:
ui.Widget: Handle to created widget.
"""
self._widget.api.add_detail_frame_from_controller(name, controller)
def delete_detail_frame(self, name: str):
"""
Deletes the named detail frame.
Args:
name (str): Name of the frame.
"""
self._widget.api.delete_detail_frame(name)
def set_search_delegate(self, delegate: SearchDelegate):
"""
Sets a custom search delegate for the tool bar.
Args:
delegate (:obj:`SearchDelegate`): Object that creates the search widget.
"""
self._widget.api.set_search_delegate(delegate)
def show_model(self, model: FileBrowserModel):
"""
Displays the given model in the list view, overriding the default model. For example, this model
might be the result of a search.
Args:
model (:obj:`FileBrowserModel`): Model to display.
"""
self._widget.api.show_model(model)
def show(self, path: str = None):
"""
Shows this dialog. Currently pops up atop all other windows but is not completely
modal, i.e. does not take over input focus.
Args:
path (str): If optional path is specified, then navigates to it upon startup.
"""
self._window.visible = True
if path:
if self.__show_task:
self.__show_task.cancel()
self.__show_task = exec_after_redraw(lambda path=path: self.navigate_to(path), 6)
def hide(self):
"""
Hides this dialog. Automatically called when "Cancel" buttons is clicked.
"""
self._window.visible = False
def destroy(self):
"""Destructor."""
if self.__show_task:
self.__show_task.cancel()
self.__show_task = None
if self._widget is not None:
self._widget.destroy()
self._widget = None
if self._window:
self.set_visibility_changed_listener(None)
self._window.destroy()
self._window = None
| 12,357 | Python | 34.409742 | 115 | 0.616655 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/asset_types.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb.settings
from typing import Dict
from collections import namedtuple
from .style import ICON_PATH, THUMBNAIL_PATH
AssetTypeDef = namedtuple("AssetTypeDef", "glyph thumbnail matching_exts")
# The known list of asset types, stored in this singleton variable
_known_asset_types: Dict = None
# Default Asset types
ASSET_TYPE_ANIM_USD = "anim_usd"
ASSET_TYPE_CACHE_USD = "cache_usd"
ASSET_TYPE_CURVE_ANIM_USD = "curve_anim_usd"
ASSET_TYPE_GEO_USD = "geo_usd"
ASSET_TYPE_MATERIAL_USD = "material_usd"
ASSET_TYPE_PROJECT_USD = "project_usd"
ASSET_TYPE_SEQ_USD = "seq_usd"
ASSET_TYPE_SKEL_USD = "skel_usd"
ASSET_TYPE_SKEL_ANIM_USD = "skel_anim_usd"
ASSET_TYPE_USD_SETTINGS = "settings_usd"
ASSET_TYPE_USD = "usd"
ASSET_TYPE_FBX = "fbx"
ASSET_TYPE_OBJ = "obj"
ASSET_TYPE_MATERIAL = "material"
ASSET_TYPE_IMAGE = "image"
ASSET_TYPE_SOUND = "sound"
ASSET_TYPE_SCRIPT = "script"
ASSET_TYPE_VOLUME = "volume"
ASSET_TYPE_FOLDER = "folder"
ASSET_TYPE_ICON = "icon"
ASSET_TYPE_HIDDEN = "hidden"
ASSET_TYPE_UNKNOWN = "unknown"
def _init_asset_types():
global _known_asset_types
_known_asset_types = {}
_known_asset_types[ASSET_TYPE_USD_SETTINGS] = AssetTypeDef(
f"{ICON_PATH}/settings_usd.svg",
f"{THUMBNAIL_PATH}/settings_usd_256.png",
[".settings.usd", ".settings.usda", ".settings.usdc", ".settings.usdz"],
)
_known_asset_types[ASSET_TYPE_ANIM_USD] = AssetTypeDef(
f"{ICON_PATH}/anim_usd.svg",
f"{THUMBNAIL_PATH}/anim_usd_256.png",
[".anim.usd", ".anim.usda", ".anim.usdc", ".anim.usdz"],
)
_known_asset_types[ASSET_TYPE_CACHE_USD] = AssetTypeDef(
f"{ICON_PATH}/cache_usd.svg",
f"{THUMBNAIL_PATH}/cache_usd_256.png",
[".cache.usd", ".cache.usda", ".cache.usdc", ".cache.usdz"],
)
_known_asset_types[ASSET_TYPE_CURVE_ANIM_USD] = AssetTypeDef(
f"{ICON_PATH}/anim_usd.svg",
f"{THUMBNAIL_PATH}/curve_anim_usd_256.png",
[".curveanim.usd", ".curveanim.usda", ".curveanim.usdc", ".curveanim.usdz"],
)
_known_asset_types[ASSET_TYPE_GEO_USD] = AssetTypeDef(
f"{ICON_PATH}/geo_usd.svg",
f"{THUMBNAIL_PATH}/geo_usd_256.png",
[".geo.usd", ".geo.usda", ".geo.usdc", ".geo.usdz"],
)
_known_asset_types[ASSET_TYPE_MATERIAL_USD] = AssetTypeDef(
f"{ICON_PATH}/material_usd.png",
f"{THUMBNAIL_PATH}/material_usd_256.png",
[".material.usd", ".material.usda", ".material.usdc", ".material.usdz"],
)
_known_asset_types[ASSET_TYPE_PROJECT_USD] = AssetTypeDef(
f"{ICON_PATH}/project_usd.svg",
f"{THUMBNAIL_PATH}/project_usd_256.png",
[".project.usd", ".project.usda", ".project.usdc", ".project.usdz"],
)
_known_asset_types[ASSET_TYPE_SEQ_USD] = AssetTypeDef(
f"{ICON_PATH}/sequence_usd.svg",
f"{THUMBNAIL_PATH}/sequence_usd_256.png",
[".seq.usd", ".seq.usda", ".seq.usdc", ".seq.usdz"],
)
_known_asset_types[ASSET_TYPE_SKEL_USD] = AssetTypeDef(
f"{ICON_PATH}/skel_usd.svg",
f"{THUMBNAIL_PATH}/skel_usd_256.png",
[".skel.usd", ".skel.usda", ".skel.usdc", ".skel.usdz"],
)
_known_asset_types[ASSET_TYPE_SKEL_ANIM_USD] = AssetTypeDef(
f"{ICON_PATH}/anim_usd.svg",
f"{THUMBNAIL_PATH}/skel_anim_usd_256.png",
[".skelanim.usd", ".skelanim.usda", ".skelanim.usdc", ".skelanim.usdz"],
)
_known_asset_types[ASSET_TYPE_FBX] = AssetTypeDef(
f"{ICON_PATH}/usd_stage.svg", f"{THUMBNAIL_PATH}/fbx_256.png", [".fbx"]
)
_known_asset_types[ASSET_TYPE_OBJ] = AssetTypeDef(
f"{ICON_PATH}/usd_stage.svg", f"{THUMBNAIL_PATH}/obj_256.png", [".obj"]
)
_known_asset_types[ASSET_TYPE_MATERIAL] = AssetTypeDef(
f"{ICON_PATH}/mdl.svg", f"{THUMBNAIL_PATH}/mdl_256.png", [".mdl", ".mtlx"]
)
_known_asset_types[ASSET_TYPE_IMAGE] = AssetTypeDef(
f"{ICON_PATH}/image.svg",
f"{THUMBNAIL_PATH}/image_256.png",
[".bmp", ".gif", ".jpg", ".jpeg", ".png", ".tga", ".tif", ".tiff", ".hdr", ".dds", ".exr", ".psd", ".ies", ".tx"],
)
_known_asset_types[ASSET_TYPE_SOUND] = AssetTypeDef(
f"{ICON_PATH}/sound.svg",
f"{THUMBNAIL_PATH}/sound_256.png",
[".wav", ".wave", ".ogg", ".oga", ".flac", ".fla", ".mp3", ".m4a", ".spx", ".opus", ".adpcm"],
)
_known_asset_types[ASSET_TYPE_SCRIPT] = AssetTypeDef(
f"{ICON_PATH}/script.svg", f"{THUMBNAIL_PATH}/script_256.png", [".py"]
)
_known_asset_types[ASSET_TYPE_VOLUME] = AssetTypeDef(
f"{ICON_PATH}/volume.svg",
f"{THUMBNAIL_PATH}/volume_256.png",
[".nvdb", ".vdb"],
)
_known_asset_types[ASSET_TYPE_ICON] = AssetTypeDef(None, None, [".svg"])
_known_asset_types[ASSET_TYPE_HIDDEN] = AssetTypeDef(None, None, [".thumbs"])
try:
# avoid dependency on USD in this extension and only use it when available
import omni.usd
except ImportError:
pass
else:
# readable_usd_dotted_file_exts() is auto-generated by querying USD;
# however, it includes some items that we've assigned more specific
# roles (ie, .mdl). So do this last, and subtract out any already-
# known types.
known_exts = set()
for asset_type_def in _known_asset_types.values():
known_exts.update(asset_type_def.matching_exts)
usd_exts = [
x for x in omni.usd.readable_usd_dotted_file_exts()
if x not in known_exts
]
_known_asset_types[ASSET_TYPE_USD] = AssetTypeDef(
f"{ICON_PATH}/usd_stage.svg",
f"{THUMBNAIL_PATH}/usd_stage_256.png",
usd_exts,
)
if _known_asset_types is None:
_init_asset_types()
def register_file_extensions(asset_type: str, exts: [str], replace: bool = False):
"""
Adds an asset type to the recognized list.
Args:
asset_type (str): Name of asset type.
exts ([str]): List of extensions to associate with this asset type, e.g. [".usd", ".usda"].
replace (bool): If True, replaces extensions in the existing definition. Otherwise, append
to the existing list.
"""
if not asset_type or exts == None:
return
global _known_asset_types
if asset_type in _known_asset_types:
glyph = _known_asset_types[asset_type].glyph
thumbnail = _known_asset_types[asset_type].thumbnail
if replace:
_known_asset_types[asset_type] = AssetTypeDef(glyph, thumbnail, exts)
else:
exts.extend(_known_asset_types[asset_type].matching_exts)
_known_asset_types[asset_type] = AssetTypeDef(glyph, thumbnail, exts)
else:
_known_asset_types[asset_type] = AssetTypeDef(None, None, exts)
def is_asset_type(filename: str, asset_type: str) -> bool:
"""
Returns True if given filename is of specified type.
Args:
filename (str)
asset_type (str): Tested type name.
Returns:
bool
"""
global _known_asset_types
if not (filename and asset_type):
return False
elif asset_type not in _known_asset_types:
return False
return any([filename.lower().endswith(ext.lower()) for ext in _known_asset_types[asset_type].matching_exts])
def get_asset_type(filename: str) -> str:
"""
Returns asset type, based on extension of given filename.
Args:
filename (str)
Returns:
str
"""
if not filename:
return None
global _known_asset_types
for asset_type in _known_asset_types:
if is_asset_type(filename, asset_type):
return asset_type
return ASSET_TYPE_UNKNOWN
def get_icon(filename: str) -> str:
"""
Returns icon for specified file.
Args:
filename (str)
Returns:
str: Fullpath to the icon file, None if not found.
"""
if not filename:
return None
icon = None
asset_type = get_asset_type(filename)
global _known_asset_types
if asset_type in _known_asset_types:
icon = _known_asset_types[asset_type].glyph
return icon
def get_thumbnail(filename: str) -> str:
"""
Returns thumbnail for specified file.
Args:
filename (str)
Returns:
str: Fullpath to the thumbnail file, None if not found.
"""
if not filename:
return None
thumbnail = None
asset_type = get_asset_type(filename)
global _known_asset_types
if asset_type == ASSET_TYPE_ICON:
thumbnail = filename
else:
if asset_type in _known_asset_types:
thumbnail = _known_asset_types[asset_type].thumbnail
return thumbnail or f"{THUMBNAIL_PATH}/unknown_file_256.png"
| 9,145 | Python | 33.254682 | 122 | 0.621432 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/test_helper.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from typing import List
from omni.kit import ui_test
from omni.kit.widget.filebrowser import TREEVIEW_PANE, LISTVIEW_PANE, FileBrowserItem
from .widget import FilePickerWidget
class FilePickerTestHelper:
def __init__(self, widget: FilePickerWidget):
self._widget = widget
async def __aenter__(self):
return self
async def __aexit__(self, *args):
pass
@property
def filepicker(self):
return self._widget
async def toggle_grid_view_async(self, show_grid_view: bool):
if self.filepicker and self.filepicker._view:
self.filepicker._view.toggle_grid_view(show_grid_view)
await ui_test.human_delay(10)
async def get_item_async(self, treeview_identifier: str, name: str, pane: int = LISTVIEW_PANE):
# Return item from the specified pane, handles both tree and grid views
if not self.filepicker:
return
if name:
pane_widget = None
if pane == TREEVIEW_PANE:
pane_widget = ui_test.find_all(f"{self.filepicker._title}//Frame/**/TreeView[*].identifier=='{treeview_identifier}_folder_view'")
elif self.filepicker._view.filebrowser.show_grid_view:
# LISTVIEW selected + showing grid view
pane_widget = ui_test.find_all(f"{self.filepicker._title}//Frame/**/VGrid[*].identifier=='{treeview_identifier}_grid_view'")
else:
# LISTVIEW selected + showing tree view
pane_widget = ui_test.find_all(f"{self.filepicker._title}//Frame/**/TreeView[*].identifier=='{treeview_identifier}'")
if pane_widget:
widget = pane_widget[0].find_all(f"**/Label[*].text=='{name}'")[0]
if widget:
widget.widget.scroll_here(0.5, 0.5)
await ui_test.human_delay(4)
return widget
return None
async def select_items_async(self, url: str, filenames: List[str] = []) -> List[FileBrowserItem]:
"""Helper function to programatically select multiple items in filepicker. Useful in unittests."""
if not self.filepicker:
return []
await self.filepicker.api.navigate_to_async(url)
return await self.filepicker.api.select_items_async(url, filenames=filenames)
async def get_pane_async(self, treeview_identifier: str, pane: int = LISTVIEW_PANE):
# Return the specified pane widget, handles both tree and grid views
if not self.filepicker:
return
pane_widget = None
if pane == TREEVIEW_PANE:
pane_widget = ui_test.find_all(f"{self.filepicker._title}//Frame/**/TreeView[*].identifier=='{treeview_identifier}_folder_view'")
elif self.filepicker._view.filebrowser.show_grid_view:
# LISTVIEW selected + showing grid view
pane_widget = ui_test.find_all(f"{self.filepicker._title}//Frame/**/VGrid[*].identifier=='{treeview_identifier}_grid_view'")
else:
# LISTVIEW selected + showing tree view
pane_widget = ui_test.find_all(f"{self.filepicker._title}//Frame/**/TreeView[*].identifier=='{treeview_identifier}'")
if pane_widget:
await ui_test.human_delay(4)
return pane_widget[0]
return None | 3,751 | Python | 45.320987 | 145 | 0.640896 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/context_menu.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import os
import omni.ui as ui
from functools import partial
from typing import Callable
from omni.kit.widget.filebrowser import FileBrowserItem
from omni.kit.widget.versioning import CheckpointWidget
from .view import FilePickerView
from .file_ops import *
from .style import get_style
class BaseContextMenu:
"""
Base class popup menu for the hovered FileBrowserItem. Provides API for users to add menu items.
"""
def __init__(self, title: str = None, **kwargs):
self._title: str = title
self._view: FilePickerView = kwargs.get("view", None)
self._checkpoint: CheckpointWidget = kwargs.get("checkpoint", None)
self._context_menu: ui.Menu = None
self._menu_dict: list = []
self._menu_items: list = []
self._context: dict = None
@property
def menu(self) -> ui.Menu:
""":obj:`omni.ui.Menu` The menu widget"""
return self._context_menu
@property
def context(self) -> dict:
"""dict: Provides data to the callback. Available keys are {'item', 'selected'}"""
return self._context
def show(
self,
item: FileBrowserItem,
selected: List[FileBrowserItem] = [],
):
"""
Creates the popup menu from definition for immediate display. Receives as input, information about the
item. These values are made available to the callback via the 'context' dictionary.
Args:
item (FileBrowseritem): Item for which to create menu.,
selected ([FileBrowserItem]): List of currently selected items. Default [].
"""
self._context = {}
self._context["item"] = item
self._context["selected"] = selected
self._context_menu = ui.Menu(self._title, style=get_style(), style_type_name_override="Menu")
menu_entry_built = False
with self._context_menu:
prev_entry = None
for i, menu_entry in enumerate(self._menu_dict):
if i == len(self._menu_dict) - 1 and not menu_entry.get("name"):
# Don't draw separator as last item
break
if menu_entry.get("name") or (prev_entry and prev_entry.get("name")):
# Don't draw 2 separators in a row
entry_built = self._build_menu(menu_entry, self._context)
if entry_built:
# only proceed prev_entry if the current entry is built, so that if we have menu items that
# are not built in between 2 separators, the 2nd separator will not build
prev_entry = menu_entry
menu_entry_built |= entry_built
# Show it (if there's at least one menu entry built)
if len(self._menu_dict) > 0 and menu_entry_built:
self._context_menu.show()
def hide(self):
self._context_menu.hide()
def add_menu_item(self, name: str, glyph: str, onclick_fn: Callable, show_fn: Callable, index: int = -1, separator_name: Optional[str] = None) -> str:
"""
Adds menu item, with corresponding callbacks, to this context menu.
Args:
name (str): Name of the menu item (e.g. 'Open'), this name must be unique across the context menu.
glyph (str): Associated glyph to display for this menu item.
onclick_fn (Callable): This callback function is executed when the menu item is clicked. Function signature:
void fn(context: Dict)
show_fn (Callable): Returns True to display this menu item. Function signature: bool fn(context: Dict).
For example, test filename extension to decide whether to display a 'Play Sound' action.
index (int): The position that this menu item will be inserted to.
separator_name (str): The separator name of the separator menu item. Default to '_placeholder_'. When the
index is not explicitly set, or if the index is out of range, this will be used to locate where to add
the menu item; if specified, the index passed in will be counted from the saparator with the provided
name. This is for OM-86768 as part of the effort to match Navigator and Kit UX for Filepicker/Content Browser for context menus.
Returns:
str: Name of menu item if successful, None otherwise.
"""
if not name:
return None
elif name in [item.get("name", None) for item in self._menu_dict]:
# Reject duplicates
return None
menu_item = {"name": name, "glyph": glyph or ""}
if onclick_fn:
menu_item["onclick_fn"] = lambda context, name=name: onclick_fn(name, context["item"].path)
if show_fn:
menu_item["show_fn"] = lambda context: show_fn(context["item"].path)
if index >= 0 and index <= len(self._menu_dict) and separator_name is None:
pass
else:
if separator_name is None:
separator_name = "_placeholder_"
placeholder_index = (i for i, item in enumerate(self._menu_dict) if separator_name in item)
matched = next(placeholder_index, len(self._menu_dict))
index = max(min(matched + index, len(self._menu_dict)), 0)
self._menu_dict.insert(index, menu_item)
return name
def delete_menu_item(self, name: str):
"""
Deletes the menu item, with the given name, from this context menu.
Args:
name (str): Name of the menu item (e.g. 'Open').
"""
if not name:
return
found = (i for i, item in enumerate(self._menu_dict) if name == item.get("name", None))
for j in sorted([i for i in found], reverse=True):
del self._menu_dict[j]
def _build_menu(self, menu_entry, context):
menu_entry_built = False
from omni.kit.ui import get_custom_glyph_code
if "name" in menu_entry and isinstance(menu_entry["name"], dict):
sub_menu = copy.copy(menu_entry["name"])
icon = "plus.svg"
if "glyph" in sub_menu:
icon = sub_menu["glyph"]
del sub_menu["glyph"]
gylph_char = get_custom_glyph_code("${glyphs}/" + icon)
for item in sub_menu:
menu_item = ui.Menu(f" {gylph_char} {item}")
with menu_item:
for menu_entry in sub_menu[item]:
self._build_menu(menu_entry, context)
menu_entry_built = True
self._menu_items.append(menu_item)
return menu_entry_built
if not self._get_fn_result(menu_entry, "show_fn", context):
return False
if "populate_fn" in menu_entry:
menu_item = menu_entry["populate_fn"](context)
self._menu_items.append(menu_item)
return True
if menu_entry["name"] == "":
menu_item = ui.Separator(style_type_name_override="Menu.Separator")
else:
menu_name = ""
if "glyph" in menu_entry:
menu_name = " " + get_custom_glyph_code("${glyphs}/" + menu_entry["glyph"]) + " "
if "onclick_fn" in menu_entry and menu_entry["onclick_fn"] is not None:
enabled = self._get_fn_result(menu_entry, "enabled_fn", context)
menu_item = ui.MenuItem(
menu_name + menu_entry["name"],
triggered_fn=partial(menu_entry["onclick_fn"], context),
enabled=enabled,
style_type_name_override="Menu.Item",
)
else:
menu_item = ui.MenuItem(menu_name + menu_entry["name"], enabled=False, style_type_name_override="Menu.Item")
if "show_fn_async" in menu_entry:
menu_item.visible = False
async def _delay_update_menu_item():
await menu_entry["show_fn_async"](context, menu_item)
# update menu item visiblity after the show fn result is returned
self._update_menu_item_visibility()
asyncio.ensure_future(_delay_update_menu_item())
# FIXME: in the case of when there's only one menu entry and it's show_fn_async returned false, this result will
# be wrong
self._menu_items.append(menu_item)
return True
def _get_fn_result(self, menu_entry, name, context):
if not name in menu_entry:
return True
if menu_entry[name] is None:
return True
if isinstance(menu_entry[name], list):
for show_fn in menu_entry[name]:
if not show_fn(context):
return False
else:
if not menu_entry[name](context):
return False
return True
def _update_menu_item_visibility(self):
"""
Utility to update menu item visiblity.
Mainly to eliminate the case where 2 separators are shown next to each other because of the menu items in
between them are async and made the menu items invisible.
"""
if not self._context_menu:
return
last_visible_item = None
for item in self._menu_items:
if not item.visible:
continue
# if the current item is a separator, check that the previous visible menu item is not separator to avoid
# having 2 continuous separators
if isinstance(item, ui.Separator) and last_visible_item and isinstance(last_visible_item, ui.Separator) and\
last_visible_item.visible:
item.visible = False
last_visible_item = item
self._context_menu.show()
def destroy(self):
self._context_menu = None
self._menu_dict = None
self._context = None
self._menu_items.clear()
class ContextMenu(BaseContextMenu):
"""
Creates popup menu for the hovered FileBrowserItem. In addition to the set of default actions below,
users can add more via the add_menu_item API.
"""
def __init__(self, **kwargs):
super().__init__(title="Context menu", **kwargs)
self._menu_dict = [
{
"name": "Open in File Browser",
"glyph": "folder_open.svg",
"onclick_fn": lambda context: open_in_file_browser(context["item"]),
"show_fn": [lambda context: os.path.exists(context["item"].path)],
},
{
"name": "New USD File",
"glyph": "file.svg",
"onclick_fn": lambda context: create_usd_file(context["item"]),
"show_fn": [
lambda context: context["item"].is_folder,
lambda _: is_usd_supported(),
# OM-72882: should not allow creating folder/file in read-only directory
lambda context: context["item"].writeable,
lambda context: len(context["selected"]) <= 1,
lambda context: not context["item"] in self._view.all_collection_items(collection="omniverse"),
]
},
{
"name": "Restore",
"glyph": "restore.svg",
"onclick_fn": lambda context: restore_items(context["selected"], self._view),
"show_fn": [
# OM-72882: should not allow deleting folder/file in read-only directory
lambda context: context["item"].writeable,
lambda context: context["item"].is_deleted,
],
},
{
"name": "Refresh",
"glyph": "menu_refresh.svg",
"onclick_fn": lambda context: refresh_item(context["item"], self._view),
"show_fn": [lambda context: len(context["selected"]) <= 1,]
},
{
"name": "",
"_add_on_begin_separator_": "",
},
{
"name": "",
"_add_on_end_separator_": "",
},
{
"name": "New Folder",
"glyph": "menu_plus.svg",
"onclick_fn": lambda context: create_folder(context["item"]),
"show_fn": [
lambda context: context["item"].is_folder,
# OM-72882: should not allow creating folder/file in read-only directory
lambda context: context["item"].writeable,
lambda context: len(context["selected"]) <= 1,
# TODO: Can we create any folder in the omniverer server's root folder?
#lambda context: not(context["item"].parent and \
# context["item"].parent.path == "omniverse://"),
],
},
{
"name": "",
},
{
"name": "Create Checkpoint",
"glyph": "database.svg",
"onclick_fn": lambda context: checkpoint_items(context["selected"], self._checkpoint),
"show_fn": [
lambda context: not context["item"].is_folder,
lambda context: len(context["selected"]) == 1,
],
"show_fn_async": is_item_checkpointable,
},
{
"name": "",
},
{
"name": "Rename",
"glyph": "pencil.svg",
"onclick_fn": lambda context: rename_item(context["item"], self._view),
"show_fn": [
lambda context: len(context["selected"]) == 1,
lambda context: context["item"].writeable,
]
},
{
"name": "Delete",
"glyph": "menu_delete.svg",
"onclick_fn": lambda context: delete_items(context["selected"]),
"show_fn": [
# OM-72882: should not allow deleting folder/file in read-only directory
lambda context: context["item"].writeable,
lambda context: not context["item"].is_deleted,
# OM-94626: we couldn't delete when select nothing
lambda context: len(context["selected"]) >= 1,
],
},
{
"name": "",
"_placeholder_": ""
},
{
"name": "Add Bookmark",
"glyph": "bookmark.svg",
"onclick_fn": lambda context: add_bookmark(context["item"], self._view),
"show_fn": [lambda context: len(context["selected"]) <= 1,]
},
{
"name": "Copy URL Link",
"glyph": "share.svg",
"onclick_fn": lambda context: copy_to_clipboard(context["item"]),
"show_fn": [lambda context: len(context["selected"]) <= 1,]
},
{
"name": "Obliterate",
"glyph": "menu_delete.svg",
"onclick_fn": lambda context: obliterate_items(context["selected"], self._view),
"show_fn": [
# OM-72882: should not allow deleting folder/file in read-only directory
lambda context: context["item"].writeable,
lambda context: context["item"].is_deleted,
],
},
]
class UdimContextMenu(BaseContextMenu):
"""Creates popup menu for the hovered FileBrowserItem that are Udim nodes."""
def __init__(self, **kwargs):
super().__init__(title="Udim menu", **kwargs)
self._menu_dict = [
{
"name": "Add Bookmark",
"glyph": "bookmark.svg",
"onclick_fn": lambda context: add_bookmark(context["item"], self._view),
},
]
class CollectionContextMenu(BaseContextMenu):
"""Creates popup menu for the hovered FileBrowserItem that are collection nodes."""
def __init__(self, **kwargs):
super().__init__(title="Collection menu", **kwargs)
# OM-75883: override menu dict for "Omniverse" collection node, there should be only
# one menu entry, matching Navigator UX
self._menu_dict = [
{
"name": "Add Server",
"glyph": "menu_plus.svg",
"onclick_fn": lambda context: add_connection(self._view),
"show_fn": [
lambda context: context['item'].name == "Omniverse",
lambda context: carb.settings.get_settings().get_as_bool("/exts/omni.kit.window.filepicker/show_add_new_connection"),
],
},
]
class ConnectionContextMenu(BaseContextMenu):
"""Creates popup menu for the server connection FileBrowserItem grouped under Omniverse collection node."""
def __init__(self, **kwargs):
super().__init__(title="Connection menu", **kwargs)
# OM-86768: matching context menu with Navigator UX for server connection
# TODO: Add API Tokens and Clear Cached Folders once API is exposed in omni.client
self._menu_dict = [
{
"name": "New Folder",
"glyph": "menu_plus.svg",
"onclick_fn": lambda context: create_folder(context["item"]),
"show_fn": [
# OM-72882: should not allow creating folder/file in read-only directory
lambda context: context["item"].writeable,
lambda context: len(context["selected"]) == 1,
],
},
{
"name": "Reconnect Server",
"glyph": "menu_refresh.svg",
"onclick_fn": lambda context: refresh_connection(context["item"], self._view),
},
{
"name": "",
},
{
"name": "Rename",
"glyph": "pencil.svg",
"onclick_fn": lambda context: rename_item(context["item"], self._view),
"show_fn": [
lambda context: len(context["selected"]) == 1,
]
},
{
"name": "",
},
{
"name": "Log In",
"glyph": "user.svg",
"onclick_fn": lambda context: refresh_connection(context["item"], self._view),
"show_fn": [
lambda context: not FilePickerView.is_connected(context["item"].path),
],
},
{
"name": "Log Out",
"glyph": "user.svg",
"onclick_fn": lambda context: log_out_from_connection(context["item"], self._view),
"show_fn": [
lambda context: FilePickerView.is_connected(context["item"].path),
],
},
{
"name": "",
},
{
"name": "About",
"glyph": "question.svg",
"onclick_fn": lambda context: about_connection(context["item"]),
},
{
"name": "Remove Server",
"glyph": "menu_delete.svg",
"onclick_fn": lambda context: remove_connection(context["item"], self._view),
},
]
class BookmarkContextMenu(BaseContextMenu):
"""Creates popup menu for BookmarkItems."""
def __init__(self, **kwargs):
super().__init__(title="Bookmark menu", **kwargs)
# OM-66726: Edit bookmark similar to Navigator
self._menu_dict = [
{
"name": "Edit",
"glyph": "pencil.svg",
"onclick_fn": lambda context: edit_bookmark(context['item'], self._view),
},
{
"name": "Delete",
"glyph": "menu_delete.svg",
"onclick_fn": lambda context: delete_bookmark(context['item'], self._view),
},
]
| 20,783 | Python | 40.075099 | 154 | 0.523745 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/utils.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
import asyncio
import omni.kit.app
import omni.ui as ui
from omni.ui import scene as sc
from typing import Callable, Coroutine, Any
from carb import log_warn, log_info
from .style import get_style, ICON_ROOT
def exec_after_redraw(callback: Callable, wait_frames: int = 2):
async def exec_after_redraw_async(callback: Callable, wait_frames: int):
try:
# Wait a few frames before executing
for _ in range(wait_frames):
await omni.kit.app.get_app().next_update_async()
callback()
except asyncio.CancelledError:
return
except Exception as e:
# Catches exceptions from this delayed function call; often raised by unit tests where the dialog is being rapidly
# created and destroyed. In this case, it's not worth the effort to relay the exception and have it caught, so better
# warn and carry on.
log_warn(f"Warning: Ignoring a minor exception: {str(e)}")
return asyncio.ensure_future(exec_after_redraw_async(callback, wait_frames))
def get_user_folders_dict() -> dict:
"""Returns dictionary of user folders as name, path pairs"""
from pathlib import Path
user_folders = {}
subfolders = ["Desktop", "Documents", "Downloads", "Pictures"]
for subfolder in subfolders:
path = os.path.join(Path.home(), subfolder)
if os.path.exists(path):
user_folders[subfolder] = path.replace("\\", "/")
return user_folders
class SingletonTask:
def __init__(self):
self._task = None
def destroy(self):
self.cancel_task()
def __del__(self):
self.destroy()
async def run_task(self, task: Coroutine) -> Any:
if self._task:
self.cancel_task()
await omni.kit.app.get_app().next_update_async()
self._task = asyncio.create_task(task)
try:
return await self._task
except asyncio.CancelledError:
log_info(f"Cancelling task ... {self._task}")
raise
except Exception as e:
raise
finally:
self._task = None
def cancel_task(self):
if self._task is not None:
self._task.cancel()
self._task = None
class Spinner(sc.Manipulator):
def __init__(self, rotation_speed: int = 2):
super().__init__()
self.__deg = 0
self.__rotation_speed = rotation_speed
def on_build(self):
self.invalidate()
self.__deg = self.__deg % 360
transform = sc.Matrix44.get_rotation_matrix(0, 0, -self.__deg, True)
with sc.Transform(transform=transform):
sc.Image(f"{ICON_ROOT}/ov_logo.png", width=1.5, height=1.5)
self.__deg += self.__rotation_speed
class AnimatedDots():
def __init__(self, period : int = 30, phase : int = 3, width : int = 10, height : int = 20):
self._period = period
self._phase = phase
self._stop_event = asyncio.Event()
self._build_ui(width=width, height=height)
def _build_ui(self, width : int = 0, height: int = 0):
self._label = ui.Label("...", width=width, height=height)
asyncio.ensure_future(self._inf_loop())
async def _inf_loop(self):
counter = 0
while not self._stop_event.is_set():
await omni.kit.app.get_app().next_update_async()
if self._stop_event.is_set():
break
# Animate text
phase = counter // self._period % self._phase + 1
self._label.text = phase * "."
counter += 1
def __del__(self):
self._stop_event.set()
class LoadingPane(SingletonTask):
def __init__(self, frame):
super().__init__()
self._frame = frame
self._scene_view = None
self._spinner = None
self._build_ui()
def _build_ui(self):
with self._frame:
with ui.ZStack(style=get_style()):
ui.Rectangle(style_type_name_override="LoadingPane.Bg")
with ui.VStack(style=get_style(), spacing=5):
ui.Spacer(height=ui.Percent(10))
with ui.HStack(height=ui.Percent(50)):
ui.Spacer()
self._scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT)
with self._scene_view.scene:
self._spinner = Spinner()
ui.Spacer()
with ui.HStack(spacing=0):
ui.Spacer()
ui.Label("Changing Directory", height=20, width=0)
AnimatedDots()
ui.Spacer()
with ui.HStack(height=ui.Percent(20)):
ui.Spacer()
ui.Button(
"Cancel",
width=100, height=20,
clicked_fn=lambda: self.hide(),
style_type_name_override="LoadingPane.Button",
alignment=ui.Alignment.CENTER,
identifier="LoadingPaneCancel"
)
ui.Spacer()
ui.Spacer(height=ui.Percent(10))
def show(self):
self._frame.visible = True
def hide(self):
self.cancel_task()
self._frame.visible = False
def destroy(self):
if self._spinner:
self._spinner.invalidate()
self._spinner = None
if self._scene_view:
self._scene_view.destroy()
self._scene_view = None
if self._frame:
self._frame.visible = False
self._frame.destroy()
self._frame = None
super().destroy()
| 6,298 | Python | 33.60989 | 130 | 0.555414 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/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.
#
import asyncio
import re
import urllib
import omni.client
from carb import log_warn
from typing import Callable, List, Tuple
from omni.kit.helper.file_utils import asset_types
from omni.kit.widget.filebrowser import FileBrowserItem
from .style import ICON_PATH, THUMBNAIL_PATH
class FilePickerModel:
"""The model class for :obj:`FilePickerWidget`."""
def __init__(self, **kwargs):
self._collections = {}
@property
def collections(self) -> dict:
"""[:obj:`FileBrowseItem`]: The collections loaded for this widget"""
return self._collections
@collections.setter
def collections(self, collections: dict):
self._collections = collections
def get_icon(self, item: FileBrowserItem, expanded: bool) -> str:
"""
Returns fullpath to icon for given item. Override this method to implement custom icons.
Args:
item (:obj:`FileBrowseritem`): Item in question.
expanded (bool): True if item is expanded.
Returns:
str
"""
if not item or item.is_folder:
return None
return asset_types.get_icon(item.path)
def get_thumbnail(self, item: FileBrowserItem) -> str:
"""
Returns fullpath to thumbnail for given item.
Args:
item (:obj:`FileBrowseritem`): Item in question.
Returns:
str: Fullpath to the thumbnail file, None if not found.
"""
thumbnail = None
if not item:
return None
parent = item.parent
if parent in self._collections.values() and parent.path.startswith("omniverse"):
if item.icon.endswith("hdd_plus.svg"):
# Add connection item
thumbnail = f"{THUMBNAIL_PATH}/add_mount_drive_256.png"
else:
thumbnail = f"{THUMBNAIL_PATH}/mount_drive_256.png"
elif parent in self._collections.values() and parent.path.startswith("my-computer"):
thumbnail = f"{THUMBNAIL_PATH}/local_drive_256.png"
elif item.is_folder:
thumbnail = f"{THUMBNAIL_PATH}/folder_256.png"
else:
thumbnail = asset_types.get_thumbnail(item.path)
return thumbnail or f"{THUMBNAIL_PATH}/unknown_file_256.png"
def get_badges(self, item: FileBrowserItem) -> List[Tuple[str, str]]:
"""
Returns fullpaths to badges for given item. Override this method to implement custom badges.
Args:
item (:obj:`FileBrowseritem`): Item in question.
Returns:
List[Tuple[str, str]]: Where each tuple is an (icon path, tooltip string) pair.
"""
if not item:
return None
badges = []
if not item.writeable:
badges.append((f"{ICON_PATH}/lock.svg", ""))
if item.is_deleted:
badges.append((f"{ICON_PATH}/trash_grey.svg", ""))
return badges
def find_item_with_callback(self, url: str, callback: Callable = None):
"""
Searches filebrowser model for the item with the given url. Executes callback on found item.
Args:
url (str): Url of item to search for.
callback (Callable): Invokes this callback on found item or None if not found. Function signature is
void callback(item: FileBrowserItem)
"""
asyncio.ensure_future(self.find_item_async(url, callback))
async def find_item_async(self, url: str, callback: Callable = None) -> FileBrowserItem:
"""
Searches model for the given path and executes callback on found item.
Args:
url (str): Url of item to search for.
callback (Callable): Invokes this callback on found item or None if not found. Function signature is
void callback(item: FileBrowserItem)
"""
if not url:
return None
url = omni.client.normalize_url(url)
broken_url = omni.client.break_url(url)
path, collection = None, None
if broken_url.scheme == 'omniverse':
collection = self._collections.get('omniverse')
path = self.sanitize_path(broken_url.path).strip('/')
if path:
path = f"{broken_url.host}/{path}"
else:
path = broken_url.host
elif broken_url.scheme in ['file', None]:
collection = self._collections.get('my-computer')
path = self.sanitize_path(broken_url.path).rstrip('/')
item = None
if path:
try:
item = await self.find_item_in_subtree_async(collection, path)
except asyncio.CancelledError:
raise
except Exception:
pass
if not item and broken_url.scheme == 'omniverse' and collection:
# Haven't found the item but we need to try again for connection names that are aliased; for example, a connection
# with the url "omniverse://ov-content" but renamed to "my-server".
server = None
for _, child in collection.children.items():
if ("omniverse://" + path).startswith(child.path):
server = child
break
if server:
splits = path.split("/", 1)
sub_path = splits[1] if len(splits) > 1 else ""
try:
item = await self.find_item_in_subtree_async(server, sub_path)
except asyncio.CancelledError:
raise
except Exception:
pass
else:
item = collection
if item is None:
log_warn(f"Failed to find item at '{url}'")
if callback:
callback(item)
return item
async def find_item_in_subtree_async(self, root: FileBrowserItem, path: str) -> FileBrowserItem:
if not root:
# Item not found!
raise RuntimeWarning(f"Path not found: '{path}'")
item, sub_path = root, path
while item:
if not sub_path:
# Item found
return item
# Populate current folder before searching it
try:
result = await item.populate_async(item.on_populated_async)
except asyncio.CancelledError:
raise
if isinstance(result, Exception):
raise result
elif sub_path[0] == "/":
name = "/"
sub_path = sub_path[1:]
else:
splits = sub_path.split("/", 1)
name = splits[0]
sub_path = splits[1] if len(splits) > 1 else ""
match = (child for _, child in item.children.items() if child.name == name)
try:
item = next(match)
except StopIteration:
break
# Item not found!
raise RuntimeWarning(f"Path not found: '{path}'")
@staticmethod
def is_local_path(path: str) -> bool:
"""Returns True if given path is a local path"""
broken_url = omni.client.break_url(path)
if broken_url.scheme == "file":
return True
elif broken_url.scheme == "omniverse":
return False
# Return True if root directory looks like beginning of a Linux or Windows path
root_name = broken_url.path.split("/")[0]
return not root_name or re.match(r"[A-Za-z]:", root_name) != None
def _correct_filename_case(self, file: str) -> str:
"""
Helper function to workaround problem of windows paths getting lowercased
Args:
path (str): Raw path
Returns:
str
"""
try:
import platform, glob, re
if platform.system().lower() == "windows":
# get correct case filename
ondisk = glob.glob(re.sub(r'([^:/\\])(?=[/\\]|$)|\[', r'[\g<0>]', file))[0].replace("\\", "/")
# correct drive letter case
if ondisk[0].islower() and ondisk[1] == ":":
ondisk = ondisk[0].upper() + ondisk[1:]
# has only case changed
if ondisk.lower() == file.lower():
return ondisk
except Exception as exc:
pass
return file
def sanitize_path(self, path: str) -> str:
"""
Helper function for normalizing a path that may have been copied and pasted int to browser
bar. This makes the tool more resiliant to user inputs from other apps.
Args:
path (str): Raw path
Returns:
str
"""
# Strip out surrounding white spaces
path = path.strip() if path else ""
if not path:
return path
path = omni.client.normalize_url(path)
path = urllib.parse.unquote(path).replace("\\", "/")
return self._correct_filename_case(path)
def destroy(self):
self._collections = None
| 9,600 | Python | 34.040146 | 130 | 0.561354 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/api.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
import asyncio
import omni.kit.app
import omni.client
from typing import List, Callable, Dict
from carb import log_warn, log_info
from omni.kit.helper.file_utils import asset_types
from omni.kit.widget.filebrowser import FileBrowserModel, FileBrowserItem, FileBrowserUdimItem, TREEVIEW_PANE, LISTVIEW_PANE
from omni.kit.widget.browser_bar import BrowserBar
from omni.kit.widget.nucleus_connector import get_nucleus_connector
from omni.kit.widget.search_delegate import SearchDelegate
from .model import FilePickerModel
from .bookmark_model import BookmarkItem
from .view import FilePickerView
from .context_menu import ContextMenu
from .file_bar import FileBar
from .detail_view import DetailView, DetailFrameController
from .utils import LoadingPane
class FilePickerAPI:
"""This class defines the API methods for :obj:`FilePickerWidget`."""
def __init__(self, model: FilePickerModel = None, view: FilePickerView = None):
self.model = model
self.view = view
self.tool_bar: BrowserBar = None
self.file_view: FileBar = None
self.context_menu: ContextMenu = None
self.listview_menu: ContextMenu = None
self.detail_view: DetailView = None
self.error_handler: Callable = None
self._loading_pane: LoadingPane = None
self._fallback_search_delegate = None
self._client_bookmarks_changed_subscription = None
self._filename = None
def add_connections(self, connections: dict):
"""
Adds specified server connections to the tree browser. To facilitate quick startup time, doesn't check
whether the connection is actually valid.
Args:
connections (dict): A dictionary of name, path pairs. For example:
{"C:": "C:", "ov-content": "omniverse://ov-content"}. Paths to Omniverse servers
should be prefixed with "omniverse://".
"""
if not connections:
return
for name, path in connections.items():
if not self.view.has_connection_with_name(name, "omniverse"):
try:
self.view.add_server(name, path)
except Exception as e:
self._warn(str(e))
# Update the UI
self.view.refresh_ui()
def set_current_directory(self, path: str):
"""
Procedurally sets the current directory. Use this method to set the path in the browser bar.
Args:
path (str): The full path name of the folder, e.g. "omniverse://ov-content/Users/me.
"""
if path and self.tool_bar:
self.tool_bar.set_path(path.replace("\\", "/"))
def get_current_directory(self) -> str:
"""
Returns the current directory fom the browser bar.
Returns:
str: The system path, which may be different from the displayed path.
"""
# Return the directory from set_current_directory call first, then fall back to root
if self.tool_bar:
path = self.tool_bar.path
if path:
return path.replace("\\", "/")
item = self.view.get_root(LISTVIEW_PANE)
return item.path if item else None
def get_current_selections(self, pane: int = LISTVIEW_PANE) -> List[str]:
"""
Returns current selected as list of system path names.
Args:
pane (int): Specifies pane to retrieve selections from, one of {TREEVIEW_PANE = 1, LISTVIEW_PANE = 2,
BOTH = None}. Default LISTVIEW_PANE.
Returns:
[str]: List of system paths (which may be different from displayed paths, e.g. bookmarks)
"""
if self.view:
selections = self.view.get_selections(pane)
return [sel.path for sel in selections]
return None
def set_filename(self, filename: str):
"""
Sets the filename in the file bar, at bottom of the dialog. The file is not
required to already exist.
Args:
filename (str): The filename only (and not the fullpath), e.g. "myfile.usd".
"""
if self.file_view:
dirname = self.get_current_directory()
if dirname and filename:
filename = filename.replace('\\', '/')
if filename.startswith(dirname):
# Strip directory prefix.
filename = filename[len(dirname):]
# Also strip any leading and trailing slashes.
filename = filename.strip('/')
if self.file_view._focus_filename_input:
self.file_view.focus_filename_input()
self.file_view.filename = filename
self._filename = filename
def get_filename(self) -> str:
"""
Returns:
str: Currently selected filename.
"""
if self.file_view:
return self.file_view.filename
return self._filename
def navigate_to(self, url: str, callback: Callable = None):
"""
Navigates to the given url, expanding all parent directories in the path.
Args:
url (str): The url to navigate to.
callback (Callable): On successfully finding the item, executes this callback. Function signature:
void callback(item: FileBrowserItem)
"""
asyncio.ensure_future(self.navigate_to_async(url, callback))
async def navigate_to_async(self, url: str, callback: Callable = None):
"""
Asynchronously navigates to the given url, expanding the all parent directories in the path.
Args:
url (str): The url to navigate to.
callback (Callable): On successfully finding the item, executes this callback. Function signature:
void callback(item: FileBrowserItem)
"""
if not url:
if self.file_view and self.file_view._focus_filename_input:
self.file_view.focus_filename_input()
return
async def navigate_to_url_async(url: str, callback: Callable) -> bool:
result = False
if self._loading_pane is None and self.view:
self._loading_pane = LoadingPane(self.view.notification_frame)
# Check that file is udim sequnece as those files don't exist on media
if asset_types.is_udim_sequence(url):
stat_result = omni.client.Result.OK
else:
# Check that file exists before navigating to it.
stat_result, _ = await omni.client.stat_async(url)
if stat_result == omni.client.Result.OK:
item = None
if self.view and self._loading_pane:
self.view.show_notification()
try:
# Set a very long timeout; instead, display an in-progress indicator with a cancel button.
item = await self._loading_pane.run_task(self.model.find_item_async(url))
except asyncio.CancelledError:
raise asyncio.CancelledError
finally:
if self.view:
self.view.hide_notification()
if item:
result = True
# doesn't always get set 1st time when changing directories
if self.view:
self.view.select_and_center(item)
if item.is_folder:
self.set_filename("")
else:
self.set_filename(os.path.basename(item.path))
if callback:
callback(item)
else:
self._warn(f"Uh-oh! item at '{url}' not found.")
else:
self._warn(f"No item exists with url '{url}'.")
# OM-99312: Hide the loading pane when no item exists
if self._loading_pane and not result:
self._loading_pane.hide()
return result
# if you navigate to URL with valid path but invalid filename, users gets empty window.
async def try_to_navigate_async(url, callback):
try:
result = await navigate_to_url_async(url, callback)
if not result:
# navigate_to_url_async failed, try without filename
client_url = omni.client.break_url(url)
base_path = omni.client.make_url(
scheme=client_url.scheme,
user=client_url.user,
host=client_url.host,
port=client_url.port,
path=os.path.dirname(client_url.path),
query=None,
fragment=client_url.fragment,
)
if base_path != url:
result = await navigate_to_url_async(base_path, callback)
except asyncio.CancelledError:
return
url = omni.client.normalize_url(url.strip())
broken_url = omni.client.break_url(url)
server_url = omni.client.make_url(scheme='omniverse', host=broken_url.host)
# OM-92223: we don't support to navigate to http item now
if broken_url.scheme in ['https', 'http']:
return
if broken_url.scheme == 'omniverse' and not self.view.get_connection_with_url(server_url):
# If server is not connected, then first auto-connect.
self.connect_server(server_url, callback=lambda *_: asyncio.ensure_future(try_to_navigate_async(url, callback)))
else:
await try_to_navigate_async(url, callback)
def connect_server(self, url: str, callback: Callable = None):
"""
Connects the server for given url.
Args:
url (str): Given url.
callback (Callable): On successfully connecting the server, executes this callback. Function signature:
void callback(name: str, server_url: str)
"""
def on_success(name: str, url: str):
# OM-94973: Guard against early destruction of view when this is executed async
if not self.view:
return
if not self.view.get_connection_with_url(url):
self.view.add_server(name, url)
if callback:
callback()
if url:
broken_url = omni.client.break_url(url)
if broken_url.scheme == 'omniverse':
server_url = omni.client.make_url(scheme='omniverse', host=broken_url.host)
nucleus_connector = get_nucleus_connector()
if nucleus_connector:
nucleus_connector.connect(broken_url.host, server_url, on_success_fn=on_success)
def find_subdirs_with_callback(self, url: str, callback: Callable):
"""
Executes callback on list of subdirectories at given url.
Args:
url (str): Url.
callback (Callable): On success executes this callback with the list of subdir names. Function
signature: void callback(subdirs: List[str])
"""
asyncio.ensure_future(self.find_subdirs_async(url, callback))
async def find_subdirs_async(self, url: str, callback: Callable) -> List[str]:
"""
Asynchronously executes callback on list of subdirectories at given url.
Args:
url (str): Url.
callback (Callable): On success executes this callback with the list of subdir names. Function
signature: void callback(subdirs: List[str])
"""
item, subdirs = None, []
if not url:
# For empty url, returns all connections
for collection in ['omniverse', 'my-computer']:
subdirs.extend([i.path for i in self.view.all_collection_items(collection)])
else:
item = await self.model.find_item_async(url)
if item:
result = await item.populate_async(None)
if isinstance(result, Exception):
pass
else:
subdirs = [c.name for _, c in item.children.items() if c.is_folder and not self.view._is_placeholder(c)]
# No item found for pathq
if callback:
callback(subdirs)
async def select_items_async(self, url: str, filenames: List[str] = []) -> List[FileBrowserItem]:
if not url:
return
item = await self.model.find_item_async(url)
if not item:
return
self.view.select_and_center(item)
for _ in range(4):
await omni.kit.app.get_app().next_update_async()
if item.is_folder and filenames:
result = await item.populate_async(None)
if not isinstance(result, Exception):
if isinstance(filenames, str) and filenames == "*":
listview_model = self.view._filebrowser._listview_model
selections = listview_model.filter_items([c for _, c in item.children.items()])
else:
selections = [c for _, c in item.children.items() if c.name in filenames]
self.view.set_selections(selections, pane=LISTVIEW_PANE)
await omni.kit.app.get_app().next_update_async()
return self.view.get_selections(pane=LISTVIEW_PANE)
def add_context_menu(self, name: str, glyph: str, click_fn: Callable, show_fn: Callable, index: int = -1, separator_name="_add_on_end_separator_") -> str:
"""
Adds menu item, with corresponding callbacks, to the context menu.
Args:
name (str): Name of the menu item (e.g. 'Open'), this name must be unique across the context menu.
glyph (str): Associated glyph to display for this menu item.
click_fn (Callable): This callback function is executed when the menu item is clicked. Function signature:
void fn(name: str, path: str), where name is menu name and path is absolute path to clicked item.
show_fn (Callable): Returns True to display this menu item. Function signature: bool fn(path: str).
For example, test filename extension to decide whether to display a 'Play Sound' action.
index (int): The postion that this menu item will be inserted to.
separator_name (str): The separator name of the separator menu item. Default to '_placeholder_'. When the
index is not explicitly set, or if the index is out of range, this will be used to locate where to add
the menu item; if specified, the index passed in will be counted from the saparator with the provided
name. This is for OM-86768 as part of the effort to match Navigator and Kit UX for Filepicker/Content Browser for context menus.
Returns:
str: Name of menu item if successful, None otherwise.
"""
if self.context_menu:
return self.context_menu.add_menu_item(name, glyph, click_fn, show_fn, index, separator_name=separator_name)
return None
def delete_context_menu(self, name: str):
"""
Deletes the menu item, with the given name, from the context menu.
Args:
name (str): Name of the menu item (e.g. 'Open').
"""
if self.context_menu:
self.context_menu.delete_menu_item(name)
def add_listview_menu(self, name: str, glyph: str, click_fn: Callable, show_fn: Callable, index: int = -1) -> str:
"""
Adds menu item, with corresponding callbacks, to the list view menu.
Args:
name (str): Name of the menu item (e.g. 'Open'), this name must be unique across the list view menu.
glyph (str): Associated glyph to display for this menu item.
click_fn (Callable): This callback function is executed when the menu item is clicked. Function signature:
void fn(name: str, path: str), where name is menu name and path is absolute path to clicked item.
show_fn (Callable): Returns True to display this menu item. Function signature: bool fn(path: str).
For example, test filename extension to decide whether to display a 'Play Sound' action.
index (int): The postion that this menu item will be inserted to.
Returns:
str: Name of menu item if successful, None otherwise.
"""
if self.listview_menu:
return self.listview_menu.add_menu_item(name, glyph, click_fn, show_fn, index)
return None
def delete_listview_menu(self, name: str):
"""
Deletes the menu item, with the given name, from the list view menu.
Args:
name (str): Name of the menu item (e.g. 'Open').
"""
if self.listview_menu:
self.listview_menu.delete_menu_item(name)
def add_detail_frame(self, name: str, glyph: str,
build_fn: Callable[[], None],
selection_changed_fn: Callable[[List[str]], None] = None,
filename_changed_fn: Callable[[str], None] = None,
destroy_fn: Callable[[], None] = None):
"""
Adds sub-frame to the detail view, and populates it with a custom built widget.
Args:
name (str): Name of the widget sub-section, this name must be unique over all detail sub-sections.
glyph (str): Associated glyph to display for this subj-section
build_fn (Callable): This callback function builds the widget.
Keyword Args:
selection_changed_fn (Callable): This callback is invoked to handle selection changes.
filename_changed_fn (Callable): This callback is invoked when filename is changed.
destroy_fn (Callable): Cleanup function called when destroyed.
"""
if self.detail_view:
self.detail_view.add_detail_frame(name, glyph, build_fn,
selection_changed_fn=selection_changed_fn, filename_changed_fn=filename_changed_fn, destroy_fn=destroy_fn)
def add_detail_frame_from_controller(self, name: str, controller: DetailFrameController):
"""
Adds sub-frame to the detail view, and populates it with a custom built widget.
Args:
name (str): Name of the widget sub-section, this name must be unique over all detail sub-sections.
controller (:obj:`DetailFrameController`): Controller object that encapsulates all aspects of creating,
updating, and deleting a detail frame widget.
"""
if self.detail_view:
self.detail_view.add_detail_frame_from_controller(name, controller)
def delete_detail_frame(self, name: str):
"""
Deletes the specified detail subsection.
Args:
name (str): Name previously assigned to the detail frame.
"""
if self.detail_view:
self.detail_view.delete_detail_frame(name)
def set_search_delegate(self, delegate: SearchDelegate):
"""
Sets a custom search delegate for the tool bar.
Args:
delegate (:obj:`SearchDelegate`): Object that creates the search widget.
"""
if self.tool_bar:
if delegate is None:
self.tool_bar.set_search_delegate(self._fallback_search_delegate)
else:
self.tool_bar.set_search_delegate(delegate)
def show_model(self, model: FileBrowserModel):
"""
Displays the given model in the list view, overriding the default model. For example, this model
might be the result of a search.
Args:
model (:obj:`FileBrowserModel`): Model to display.
"""
self.view.show_model(model)
def refresh_current_directory(self):
"""Refreshes the current directory set in the browser bar."""
item = self.view.get_root(LISTVIEW_PANE)
if item:
self.view.refresh_ui(item)
def toggle_bookmark_from_path(self, name: str, path: str, is_bookmark: bool, is_folder: bool = True):
"""
Adds/deletes the given bookmark with the specified path. If deleting, then the path argument
is optional.
Args:
name (str): Name to call the bookmark or existing name if delete.
path (str): Path to the bookmark.
is_bookmark (bool): True to add, False to delete.
is_folder (bool): Whether the item to be bookmarked is a folder.
"""
if is_bookmark:
self.view.add_bookmark(name, path, is_folder=is_folder)
else:
for bookmark in self.view.all_collection_items("bookmarks"):
if name == bookmark.name:
self.view.delete_bookmark(bookmark)
break
def subscribe_client_bookmarks_changed(self):
"""Subscribe to omni.client bookmark changes."""
def on_client_bookmarks_changed(client_bookmarks: Dict):
self._update_bookmarks(client_bookmarks)
self._update_nucleus_servers(client_bookmarks)
self._client_bookmarks_changed_subscription = omni.client.list_bookmarks_with_callback(on_client_bookmarks_changed)
def hide_loading_pane(self):
"""
Hide the loading icon if it exist.
"""
if self._loading_pane:
self._loading_pane.hide()
def _update_nucleus_servers(self, client_bookmarks: Dict):
new_servers = {name: url for name, url in client_bookmarks.items() if self._is_nucleus_server_url(url)}
current_servers = self.view.all_collection_items("omniverse")
# Update server list but don't push a notification event; otherwise, will repeat the update loop.
for item in current_servers:
if item.name not in new_servers or item.path != new_servers[item.name]:
self.view.delete_server(item, publish_event=False)
for name, path in new_servers.items():
if name not in [item.name for item in current_servers]:
if self.view:
self.view.add_server(name, path, publish_event=False)
def _update_bookmarks(self, client_bookmarks: Dict):
new_bookmarks = {name: url for name, url in client_bookmarks.items() if not self._is_nucleus_server_url(url)}
current_bookmarks = []
if self.view:
current_bookmarks = self.view.all_collection_items("bookmarks")
# Update bookmarks but don't push a notification event; otherwise, will repeat the update loop.
for item in current_bookmarks:
if item.name not in new_bookmarks:
if self.view:
self.view.delete_bookmark(item, publish_event=False)
for name, path in new_bookmarks.items():
if name not in [item.name for item in current_bookmarks]:
if self.view:
self.view.add_bookmark(
name, path, publish_event=False, is_folder=BookmarkItem.is_bookmark_folder(path))
def _is_nucleus_server_url(self, url: str):
if not url:
return False
broken_url = omni.client.break_url(url)
if broken_url.scheme == "omniverse" and broken_url.path == "/" and broken_url.host is not None:
# Url of the form "omniverse://server_name/" should be recognized as server connection
return True
return False
def _info(self, msg: str):
log_info(msg)
def _warn(self, msg: str):
log_warn(msg)
if self.error_handler:
self.error_handler(msg)
def destroy(self):
self.model = None
self.view = None
self.tool_bar = None
self.file_view = None
self.context_menu = None
self.listview_menu = None
self.detail_view = None
self.error_handler = None
if self._loading_pane:
self._loading_pane.destroy()
self._loading_pane = None
self._fallback_search_delegate = None
self._client_bookmarks_changed_subscription = None
| 24,729 | Python | 41.057823 | 158 | 0.598528 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/option_box.py | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
from typing import Callable, List
from .style import get_style
class OptionBox:
def __init__(self, build_fn: Callable, **kwargs):
"""
Option box.
"""
self._frame = None
self._build_fn = build_fn
self._selection_changed_fn = kwargs.get("selection_changed_fn", None)
self._mouse_pressed_fn = kwargs.get("mouse_pressed_fn", None)
self._mouse_double_clicked_fn = kwargs.get("mouse_double_clicked_fn", None)
self._build_ui()
def _build_ui(self):
self._frame = ui.Frame(visible=True, height=100, style=get_style())
def rebuild(self, selected: List[str]):
if self._frame:
self._frame.clear()
with self._frame:
self._build_fn(selected)
def destroy(self):
self._build_fn = None
self._selection_changed_fn = None
self._mouse_pressed_fn = None
self._mouse_double_clicked_fn = None
self._frame = None
@staticmethod
def create_option_box(build_fn: Callable) -> 'OptionBox':
widget = OptionBox(build_fn)
return widget
@staticmethod
def on_selection_changed(widget: 'OptionBox', selected: List[str]):
if widget:
widget.rebuild(selected)
@staticmethod
def delete_option_box(widget: 'OptionBox'):
if widget:
widget.destroy()
| 1,831 | Python | 30.586206 | 83 | 0.643364 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/tool_bar.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 carb.settings
from omni.kit.widget.browser_bar import BrowserBar
from omni.kit.window.popup_dialog import InputDialog, MessageDialog, OptionsMenu, FormDialog
from omni.kit.widget.filebrowser import FileBrowserItem
from omni.kit.widget.search_delegate import SearchDelegate
from carb import log_warn
from .style import get_style, ICON_PATH
class ToolBar:
SAVED_SETTINGS_OPTIONS_MENU = "/persistent/app/omniverse/filepicker/options_menu"
def __init__(self, **kwargs):
self._browser_bar: BrowserBar = None
self._bookmark_button: ui.Button = None
self._bookmarked: bool = False
self._config_button: ui.Button = None
self._config_menu: OptionsMenu = None
self._current_directory_provider = kwargs.get("current_directory_provider", None)
self._branching_options_handler = kwargs.get("branching_options_handler", None)
self._apply_path_handler = kwargs.get("apply_path_handler", None)
self._toggle_bookmark_handler = kwargs.get("toggle_bookmark_handler", None)
self._config_values_changed_handler = kwargs.get("config_values_changed_handler", None)
self._begin_edit_handler = kwargs.get("begin_edit_handler", None)
self._prefix_separator = kwargs.get("prefix_separator", None)
self._enable_soft_delete = kwargs.get("enable_soft_delete", False)
self._search_delegate: SearchDelegate = kwargs.get("search_delegate", None)
self._modal = kwargs.get("modal", False)
self._build_ui()
def _build_ui(self):
with ui.HStack(height=0, style=get_style(), style_type_name_override="ToolBar"):
with ui.ZStack():
with ui.HStack():
ui.Spacer(width=48)
ui.Rectangle(style_type_name_override="ToolBar.Field")
with ui.HStack():
with ui.VStack():
ui.Spacer()
self._browser_bar = BrowserBar(
visited_history_size=20,
branching_options_handler=self._branching_options_handler,
apply_path_handler=self._apply_path_handler,
prefix_separator=self._prefix_separator,
modal=self._modal,
begin_edit_handler=self._begin_edit_handler,
)
ui.Spacer()
with ui.VStack(width=20):
ui.Spacer()
self._bookmark_button = ui.Button(
image_url=f"{ICON_PATH}/bookmark_grey.svg",
image_width=18,
image_height=18,
height=18,
style_type_name_override="ToolBar.Button",
clicked_fn=lambda: self._on_toggle_bookmark(self._current_directory_provider()),
)
ui.Spacer()
if self._search_delegate:
ui.Spacer(width=2)
with ui.HStack(width=300):
self._search_frame = ui.Frame()
with self._search_frame:
self._search_delegate.build_ui()
self._build_widgets()
with ui.VStack(width=24):
ui.Spacer()
self._config_button = ui.Button(
image_url=f"{ICON_PATH}/settings.svg",
image_width=14,
height=24,
style_type_name_override="ToolBar.Button",
identifier="settings_icon"
)
self._config_button.set_clicked_fn(
lambda: self._config_menu.show(parent=self._config_button, offset_x=-1, offset_y=24, recreate_window=True))
ui.Spacer()
self._build_config_menu()
def _build_widgets(self):
# For Content window to build filter button
pass
def _build_config_menu(self):
def on_value_changed(menu: OptionsMenu, _):
carb.settings.get_settings().set(self.SAVED_SETTINGS_OPTIONS_MENU, menu.get_values())
if self._config_values_changed_handler:
self._config_values_changed_handler(menu.get_values())
def get_default_value(name, default):
menu_settings = carb.settings.get_settings().get_settings_dictionary(self.SAVED_SETTINGS_OPTIONS_MENU)
if menu_settings and name in menu_settings:
return menu_settings[name]
return default
field_defs = [
OptionsMenu.FieldDef("hide_unknown", "Hide Unknown File Types", None, get_default_value("hide_unknown", False)),
OptionsMenu.FieldDef("hide_thumbnails", "Hide Thumbnails Folders", None, get_default_value("hide_thumbnails", True)),
OptionsMenu.FieldDef("show_details", "Show Details", None, get_default_value("show_details", False)),
OptionsMenu.FieldDef("show_udim_sequence", "Display UDIM Sequence", None, get_default_value("show_udim_sequence", False)),
]
if self._enable_soft_delete:
field_defs.append(OptionsMenu.FieldDef("show_deleted", "Show Deleted", None, get_default_value("show_deleted", False)))
self._config_menu = OptionsMenu(
title="Options", field_defs=[i for i in field_defs if i is not None], width=220, value_changed_fn=on_value_changed
)
self._config_menu.hide()
def _on_toggle_bookmark(self, item: FileBrowserItem):
if not item:
return
def on_okay_clicked(dialog: InputDialog, item: FileBrowserItem, is_bookmark: bool):
if self._toggle_bookmark_handler:
if is_bookmark:
name = dialog.get_value("name")
url = dialog.get_value("address")
else:
name = item.name
url = item.path
self._toggle_bookmark_handler(name, url, is_bookmark, is_folder=item.is_folder)
dialog.hide()
if self._bookmarked:
dialog = MessageDialog(
title="Delete bookmark",
width=400,
message=f"Are you sure about deleting the bookmark '{item.path}'?",
ok_handler=lambda dialog, item=item: on_okay_clicked(dialog, item, False),
ok_label="Yes",
cancel_label="No",
)
else:
default_name = (item.path or "").rstrip("/").rsplit("/")[-1]
field_defs = [
FormDialog.FieldDef("name", "Name: ", ui.StringField, default_name, True),
FormDialog.FieldDef("address", "Address: ", ui.StringField, item.path),
]
dialog = FormDialog(
title="Add bookmark",
width=400,
ok_handler=lambda dialog, item=item: on_okay_clicked(dialog, item, True),
field_defs=field_defs,
)
dialog.show(offset_x=-1, offset_y=24, parent=self._bookmark_button)
@property
def config_values(self):
if self._config_menu:
return self._config_menu.get_values()
else:
return {}
def set_config_value(self, name: str, value: bool):
if self._config_menu:
self._config_menu.set_value(name, value)
@property
def path(self) -> str:
if self._browser_bar:
return self._browser_bar.path
return None
def set_path(self, path: str):
if self._browser_bar:
self._browser_bar.set_path(path)
path = self._browser_bar.path # In case browser bar modifies the path str in any way
if self._search_delegate:
self._search_delegate.search_dir = path
@property
def bookmarked(self) -> bool:
return self._bookmarked
def set_bookmarked(self, true_false: bool):
self._bookmarked = true_false
if self._bookmarked:
self._bookmark_button.image_url = f"{ICON_PATH}/bookmark.svg"
else:
self._bookmark_button.image_url = f"{ICON_PATH}/bookmark_grey.svg"
def set_search_delegate(self, delegate: SearchDelegate):
"""
Sets a custom search delegate for the tool bar.
Args:
delegate (:obj:`SearchDelegate`): Object that creates the search widget.
"""
if delegate is None:
self._search_frame.visible = False
else:
with self._search_frame:
try:
delegate.build_ui()
delegate.search_dir = self._browser_bar.path if self._browser_bar else None
self._search_delegate = delegate
self._search_frame.visible = True
except Exception:
log_warn("Failed to build search widget")
def destroy(self):
if self._browser_bar:
self._browser_bar.destroy()
self._browser_bar = None
# NOTE: Dereference but do not call destroy on the search delegate because we don't own the object.
self._search_delegate = None
self._search_frame = None
if self._config_menu:
self._config_menu.destroy()
self._config_menu = None
self._config_button = None
self._bookmark_button = None
self._current_directory_provider = None
self._branching_options_handler = None
self._apply_path_handler = None
self._toggle_bookmark_handler = None
self._config_values_changed_handler = None
self._begin_edit_handler = None
| 10,203 | Python | 41.69456 | 134 | 0.571891 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/versioning_helper.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import asyncio
import omni.client
class VersioningHelper:
server_info_cache = {}
@staticmethod
def is_versioning_enabled():
try:
import omni.kit.widget.versioning
enable_versioning = True
except:
enable_versioning = False
return enable_versioning
@staticmethod
def extract_server_from_url(url):
client_url = omni.client.break_url(url)
server_url = omni.client.make_url(scheme=client_url.scheme, host=client_url.host, port=client_url.port)
return server_url
@staticmethod
async def check_server_checkpoint_support_async(server: str):
if not server:
return False
server_info = await VersioningHelper.get_server_info_async(server)
support_checkpoint = server_info and server_info.checkpoints_enabled
return support_checkpoint
@staticmethod
async def get_server_info_async(server: str):
if not server:
return None
if server in VersioningHelper.server_info_cache:
return VersioningHelper.server_info_cache[server]
result, server_info = await omni.client.get_server_info_async(server)
if result:
VersioningHelper.server_info_cache[server] = server_info
return server_info
else:
return None
@staticmethod
def menu_checkpoint_dialog(ok_fn: callable, cancel_fn: callable):
import omni.ui as ui
import carb.input
window = ui.Window(
"Checkpoint Name",
width=200,
height=0,
flags = (
omni.ui.WINDOW_FLAGS_NO_COLLAPSE |
omni.ui.WINDOW_FLAGS_NO_RESIZE |
omni.ui.WINDOW_FLAGS_NO_SCROLLBAR |
omni.ui.WINDOW_FLAGS_NO_RESIZE |
omni.ui.WINDOW_FLAGS_MODAL
)
)
with window.frame:
with ui.VStack(
height=0,
spacing=5,
name="top_level_stack",
style={"VStack::top_level_stack": {"margin": 5}, "Button": {"margin": 0}},
):
async def focus(field):
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
field.focus_keyboard()
with omni.ui.ZStack():
new_name_widget = omni.ui.StringField(multiline=True, height=60)
new_name_widget_hint_label = omni.ui.StringField(alignment=omni.ui.Alignment.LEFT_TOP, style={"color": 0xFF3F3F3F})
new_name_widget.model.set_value("")
new_name_widget_hint_label.model.set_value("Description....")
new_name_widget_hint_label.enabled=False
ui.Spacer(width=5, height=5)
with ui.HStack(spacing=5):
def ok_clicked():
window.visible = False
if ok_fn:
ok_fn(new_name_widget.model.get_value_as_string())
def cancel_clicked():
window.visible = False
if cancel_fn:
cancel_fn()
ui.Button("Ok", clicked_fn=ok_clicked)
ui.Button("Cancel", clicked_fn=cancel_clicked)
editing_started = False
def on_begin(model):
nonlocal editing_started
editing_started = True
def on_end(model):
nonlocal editing_started
editing_started = False
def window_pressed_key(key_index, key_flags, key_down):
nonlocal editing_started
new_name_widget_hint_label.visible = not bool(new_name_widget.model.get_value_as_string())
key_mod = key_flags & ~ui.Widget.FLAG_WANT_CAPTURE_KEYBOARD
if (
carb.input.KeyboardInput(key_index) in [carb.input.KeyboardInput.ENTER, carb.input.KeyboardInput.NUMPAD_ENTER]
and key_mod == 0 and key_down and editing_started
):
on_end(None)
ok_clicked()
new_name_widget.model.add_begin_edit_fn(on_begin)
new_name_widget.model.add_end_edit_fn(on_end)
window.set_key_pressed_fn(window_pressed_key)
asyncio.ensure_future(focus(new_name_widget))
return window
| 5,133 | Python | 36.474452 | 138 | 0.547828 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/widget.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
import asyncio
import omni.kit.app
import omni.ui as ui
import carb.settings
from functools import partial
from carb import log_warn
from omni.kit.widget.filebrowser import (
FileBrowserItem,
FileBrowserUdimItem,
LAYOUT_SPLIT_PANES,
TREEVIEW_PANE,
LISTVIEW_PANE,
)
from omni.kit.widget.versioning import CheckpointWidget, CheckpointItem
from omni.kit.widget.search_delegate import SearchField, SearchResultsModel
from typing import List, Tuple, Dict, Callable
from .api import FilePickerAPI
from .context_menu import ContextMenu, CollectionContextMenu, BookmarkContextMenu, UdimContextMenu, ConnectionContextMenu
from .tool_bar import ToolBar
from .file_bar import FileBar
from .model import FilePickerModel
from .style import get_style
from .utils import exec_after_redraw, get_user_folders_dict, SingletonTask
from .detail_view import DetailView
from .option_box import OptionBox
from .view import FilePickerView
from .timestamp import TimestampWidget
from . import UI_READY_EVENT, SETTING_ROOT
SHOW_ONLY_COLLECTIONS = "/exts/omni.kit.window.filepicker/show_only_collections"
class FilePickerWidget:
"""
An embeddable UI widget for browsing the filesystem and taking action on a selected file.
Includes a browser bar for keyboard input with auto-completion for navigation of the tree
view. For similar but different options, see also :obj:`FilePickerDialog` and :obj:`FilePickerView`.
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.
current_directory (str): View is set to display this directory. Default None.
current_filename (str): Filename is set to this value. Default None.
splitter_offset (int): Position of vertical splitter bar. Default 300.
show_grid_view (bool): Displays grid view in the intial layout. Default True.
grid_view_scale (int): Scales grid view, ranges from 0-5. Default 2.
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.
allow_multi_selection (bool): Allows multiple selections. Default False.
click_apply_handler (Callable): Function that will be called when the user accepts
the selection. Function signature:
void apply_handler(file_name: str, dir_name: str).
click_cancel_handler (Callable): Function that will be called when the user clicks
the cancel button. Function signature:
void cancel_handler(file_name: str, dir_name: str).
apply_button_label (str): Alternative label for the apply button. Default "Okay".
cancel_button_label (str): Alternative label for the cancel button. Default "Cancel".
enable_file_bar (bool): Enables/disables file bar. Default True.
enable_filename_input (bool): Enables/disables filename input. Default True.
file_postfix_options (List[str]): A list of filename postfix options. Default [].
file_extension_options (List[Tuple[str, str]]): A list of filename extension options. Each list
element is an (extension name, description) pair, e.g. (".usdc", "Binary format"). Default [].
item_filter_options (List[str]): OBSOLETE. Use file_postfix_options & file_extension_options instead.
A list of filter options to determine which files should be listed. For example: ['usd', 'wav']. Default None.
item_filter_fn (Callable): This user function should return True if the given tree view
item is visible, False otherwise. To base the decision on which filter option is
currently chosen, use the attribute filepicker.current_filter_option. Function
signature: bool item_filter_fn(item: :obj:`FileBrowserItem`)
error_handler (Callable): OBSOLETE. This function is called with error messages when appropriate.
It provides the calling app a way to display errors on top of writing them to the
console window. Function signature: void error_handler(message: str).
show_detail_view (bool): Display the details pane.
enable_versioning_pane (bool): OBSOLETE. Use enable_checkpoints instead.
enable_checkpoints (bool): Whether the checkpoints, a.k.a. versioning pane should be displayed. Default False.
enable_timestamp (bool): Whether the show timestamp panel. need show with checkpoint, Default False.
options_pane_build_fn (Callable[[List[FileBrowserItem]], bool]): OBSOLETE, add options in a detail frame instead.
options_pane_width (Union[int, omni.ui.Percent]): OBSOLETE.
selection_changed_fn (Callable[[List[FileBrowserItem]]]): Selections has changed.
treeview_identifier (str): widget identifier for treeview, only used by tests.
enable_tool_bar (bool): Enables/disables tool bar. Default True.
enable_zoombar (bool): Enables/disables filename input. Default True.
save_grid_view (bool): Save grid view mode if toggled. Default True.
"""
def __init__(self, title: str, **kwargs):
self._title = title
self._api = None
self._view = None
self._tool_bar = None
self._file_bar = None
self._detail_pane = None
self._detail_view = None
self._detail_splitter = None
self._context_menus = dict()
self._checkpoint_widget = None
self._option_box = None # OBSOLETE. Provided for backward compatibility
self._timestamp_widget = None
settings = carb.settings.get_settings()
self._layout = kwargs.get("layout", LAYOUT_SPLIT_PANES)
self._current_directory = kwargs.get("current_directory", None)
self._current_filename = kwargs.get("current_filename", None)
# OM-66270: Record show grid view and grid view scale settings in between sessions
self._settings_root = kwargs.get("settings_root", SETTING_ROOT)
show_grid_view = settings.get(f"/persistent{self._settings_root}show_grid_view")
grid_view_scale = settings.get(f"/persistent{self._settings_root}grid_view_scale")
if show_grid_view is None:
show_grid_view = settings.get_as_bool(f"{self._settings_root}/show_grid_view") or True
if grid_view_scale is None:
grid_view_scale = 2
self._show_grid_view = kwargs.get("show_grid_view", show_grid_view)
self._grid_view_scale = kwargs.get("grid_view_scale", grid_view_scale)
self._save_grid_view = kwargs.get("save_grid_view", True)
self._show_only_collections = kwargs.get("show_only_collections", None)
if not self._show_only_collections:
settings = carb.settings.get_settings()
# If not set show_only_collections, use the setting value instead
self._show_only_collections = settings.get(SHOW_ONLY_COLLECTIONS)
self._allow_multi_selection = kwargs.get("allow_multi_selection", False)
self._apply_button_label = kwargs.get("apply_button_label", "Okay")
self._click_apply_handler = kwargs.get("click_apply_handler", None)
self._cancel_button_label = kwargs.get("cancel_button_label", "Cancel")
self._click_cancel_handler = kwargs.get("click_cancel_handler", None)
self._enable_file_bar = kwargs.get("enable_file_bar", True)
self._enable_tool_bar = kwargs.get("enable_tool_bar", True)
self._enable_zoombar = kwargs.get("enable_zoombar", True)
self._enable_filename_input = kwargs.get("enable_filename_input", True)
self._focus_filename_input = kwargs.get("focus_filename_input", False)
self._file_postfix_options = kwargs.get("file_postfix_options", [])
self._current_file_postfix = kwargs.get("current_file_postfix", None)
self._file_extension_options = kwargs.get("file_extension_options", [])
self._filename_changed_handler = kwargs.get("filename_changed_handler", None)
self._current_file_extension = kwargs.get("current_file_extension", None)
self._item_filter_options = kwargs.get("item_filter_options", None)
self._item_filter_fn = kwargs.get("item_filter_fn", None)
self._show_detail_view = kwargs.get("show_detail_view", True)
self._enable_checkpoints = kwargs.get("enable_checkpoints", False) or kwargs.get("enable_versioning_pane", False)
self._enable_timestamp = kwargs.get("enable_timestamp", False) and self._enable_checkpoints
self._options_pane_build_fn = kwargs.get("options_pane_build_fn", None)
self._selection_changed_fn = kwargs.get("selection_changed_fn", None)
self._treeview_identifier = kwargs.get("treeview_identifier", None)
self._drop_handler = kwargs.get("drop_handler", None)
self._enable_soft_delete = kwargs.get("enable_soft_delete", False)
self._modal = kwargs.get("modal", False)
self._default_search_delegate = SearchField(self._on_search)
self._init_view_task = None
self._show_unknown_asset_types = False
self._show_thumbnails_folders = False
window = kwargs.get("window", None)
if window:
self._window_size = (window.width, window.height)
else:
self._window_size = (1000, 600) # Set to default window size if window not specified
self._splitter_offset = (kwargs.get("splitter_offset", 300), 236)
self._model = kwargs.get("model", FilePickerModel())
self._api = kwargs.get("api", FilePickerAPI())
self._build_ui()
@property
def api(self) -> FilePickerAPI:
""":obj:`FilePickerAPI`: Provides API methods to this widget."""
return self._api
@property
def model(self):
return self._model
@property
def file_bar(self) -> FileBar:
""":obj:`FileBar`: Returns the file bar widget."""
return self._file_bar
@property
def current_filter_option(self) -> int:
"""OBSOLETE int: Index of current filter option, range 0 .. num_filter_options."""
return self._file_bar.current_filter_option if self._file_bar else -1
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
def set_click_apply_handler(self, click_apply_handler: Callable[[str, str], None]):
"""
Sets the function to execute upon clicking apply.
Args:
click_apply_handler (Callable): Signature is void fn(filename: str, dirname: str)
"""
self._click_apply_handler = click_apply_handler
if self._file_bar:
self._file_bar.set_click_apply_handler(self._click_apply_handler)
def get_selected_filename_and_directory(self) -> Tuple[str, str]:
""" Get the current directory and filename that has been selected or entered into the filename field"""
if self._file_bar:
return self._file_bar.filename, self._file_bar.directory
return "", ""
def destroy(self):
"""Destructor."""
self._selection_changed_fn = None
self._options_pane_build_fn = None
self._filename_changed_handler = None
if self._init_view_task:
self._init_view_task.cancel()
self._init_view_task = None
if self._initial_navigation_task:
self._initial_navigation_task.cancel()
self._initial_navigation_task = None
if self._api:
self._api.destroy()
self._api = None
if self._tool_bar:
self._tool_bar.destroy()
self._tool_bar = None
if self._file_bar:
self._file_bar.destroy()
self._file_bar = None
if self._detail_view:
self._detail_view.destroy()
self._detail_view = None
self._detail_pane = None
self._detail_splitter = None
if self._model:
self._model.destroy()
self._model = None
if self._view:
self._view.destroy()
self._view = None
if self._context_menus:
self._context_menus.clear()
if self._checkpoint_widget:
self._checkpoint_widget.destroy()
self._checkpoint_widget = None
if self._option_box:
self._option_box.destroy()
self._option_box = None
if self._timestamp_widget:
self._timestamp_widget.destroy()
self._timestamp_widget = None
self._item_filter_fn = None
self._click_apply_handler = None
self._click_cancel_handler = None
self._window = None
self._ui_ready_event_sub = None
def _build_ui(self):
with ui.VStack(spacing=2, style=get_style()):
if self._enable_tool_bar:
self._build_tool_bar()
with ui.HStack():
with ui.ZStack():
with ui.HStack():
self._build_filepicker_view()
ui.Spacer(width=2)
self._detail_splitter = ui.Placer(
offset_x=self._window_size[0]-self._splitter_offset[1],
drag_axis=ui.Axis.X,
draggable=True,
)
with self._detail_splitter:
ui.Rectangle(width=4, style_type_name_override="Splitter")
self._detail_splitter.set_offset_x_changed_fn(self._on_detail_splitter_dragged)
# Right panel
self._detail_pane = ui.VStack()
with self._detail_pane:
self._build_detail_view()
if self._enable_file_bar:
self._build_file_bar()
# Create context menus
self._build_context_menus()
# The API object encapsulates the API methods.
self._api.model = self._model
self._api.view = self._view
self._api.tool_bar = self._tool_bar
self._api.file_view = self._file_bar
self._api.detail_view = self._detail_view
self._api.context_menu = self._context_menus.get('item')
self._api.listview_menu = self._context_menus.get('list_view')
if self._show_detail_view and self._tool_bar:
self._tool_bar.set_config_value("show_details", True)
self._init_view_task = exec_after_redraw(lambda d=self._current_directory, f=self._current_filename: self._init_view(d, f))
self._initial_navigation_task = None
# Listen for ui ready event
self._ui_ready = False
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
self._ui_ready_event_sub = event_stream.create_subscription_to_pop_by_type(UI_READY_EVENT, self._on_ui_ready)
def _build_filepicker_view(self):
self._view = FilePickerView(
"filepicker",
layout=self._layout,
splitter_offset=self._splitter_offset[0],
show_grid_view=self._show_grid_view,
show_recycle_widget=self._enable_soft_delete,
grid_view_scale=self._grid_view_scale,
on_toggle_grid_view_fn=self._on_toggle_grid_view if self._save_grid_view else None,
on_scale_grid_view_fn=self._on_scale_grid_view,
show_only_collections=self._show_only_collections,
tooltip=True,
allow_multi_selection=self._allow_multi_selection,
mouse_pressed_fn=self._on_mouse_pressed,
mouse_double_clicked_fn=self._on_mouse_double_clicked,
selection_changed_fn=self._on_selection_changed,
drop_handler=self._drop_handler,
item_filter_fn=self._item_filter_handler,
icon_provider=self._model.get_icon,
thumbnail_provider=self._model.get_thumbnail,
badges_provider=self._model.get_badges,
treeview_identifier=self._treeview_identifier,
enable_zoombar=self._enable_zoombar,
)
self._model.collections = self._view.collections
def _build_tool_bar(self):
self._tool_bar = ToolBar(
visited_history_size=20,
current_directory_provider=lambda: self._view.get_root(LISTVIEW_PANE),
branching_options_handler=self._api.find_subdirs_with_callback,
apply_path_handler=self._api.navigate_to,
toggle_bookmark_handler=self._api.toggle_bookmark_from_path,
config_values_changed_handler=lambda _: self._apply_config_options(),
begin_edit_handler=self._on_begin_edit,
prefix_separator="://",
search_delegate=self._default_search_delegate,
enable_soft_delete=self._enable_soft_delete,
modal=self._modal,
)
def _build_detail_view(self):
self._detail_view = DetailView()
if self._options_pane_build_fn:
# NOTE: DEPRECATED - Left here for backwards compatibility
def build_option_box(build_fn: Callable):
self._option_box = OptionBox.create_option_box(build_fn)
self._detail_view.add_detail_frame(
"Options", None,
partial(build_option_box, self._options_pane_build_fn),
selection_changed_fn=lambda selected: OptionBox.on_selection_changed(self._option_box, selected),
destroy_fn=lambda selected: OptionBox.delete_option_box(self._option_box, selected)
)
if self._enable_checkpoints:
self._detail_view.add_detail_frame(
"Checkpoints", None,
self._build_checkpoint_widget,
selection_changed_fn=lambda selected: CheckpointWidget.on_model_url_changed(self._checkpoint_widget, selected),
destroy_fn=lambda: CheckpointWidget.delete_checkpoint_widget(self._checkpoint_widget))
if self._enable_timestamp:
def on_timestamp_check_changed(full_url: str):
self._api.set_filename(full_url)
def build_timestamp_widget():
self._timestamp_widget = TimestampWidget.create_timestamp_widget()
self._timestamp_widget.add_on_check_changed_fn(on_timestamp_check_changed)
self._detail_view.add_detail_frame(
"TimeStamp", None,
build_timestamp_widget,
selection_changed_fn=lambda selected: TimestampWidget.on_selection_changed(self._timestamp_widget, selected),
destroy_fn=lambda: TimestampWidget.delete_timestamp_widget(self._timestamp_widget))
def _build_checkpoint_widget(self):
def on_checkpoint_selection_changed(cp: CheckpointItem):
if cp:
self._api.set_filename(cp.get_full_url())
if self._timestamp_widget:
self._timestamp_widget.check = False
self._checkpoint_widget = CheckpointWidget.create_checkpoint_widget()
self._checkpoint_widget.add_on_selection_changed_fn(on_checkpoint_selection_changed)
if self._timestamp_widget:
self._checkpoint_widget.set_on_list_checkpoint_fn(self._timestamp_widget.on_list_checkpoint)
self._timestamp_widget.set_checkpoint_widget(self._checkpoint_widget)
# Add context menu to checkpoints
def on_copy_url(cp: CheckpointItem):
omni.kit.clipboard.copy(cp.get_full_url() if cp else "")
def on_copy_version(cp: CheckpointItem):
omni.kit.clipboard.copy(cp.comment or "")
self._checkpoint_widget.add_context_menu(
"Copy URL",
"copy.svg",
lambda menu, cp: on_copy_url(cp),
None
)
self._checkpoint_widget.add_context_menu(
"Copy Description",
"copy.svg",
lambda menu, cp: on_copy_version(cp),
lambda menu, cp: 1 if (cp and cp.get_relative_path()) else 0,
)
def _build_file_bar(self):
self._file_bar = FileBar(
style=get_style(),
enable_filename_input=self._enable_filename_input,
filename_changed_handler=self._on_filename_changed,
file_postfix_options=self._file_postfix_options,
file_postfix=self._current_file_postfix,
file_extension_options=self._file_extension_options,
file_extension=self._current_file_extension,
item_filter_options=self._item_filter_options,
filter_option_changed_handler=self._refresh_ui,
current_directory_provider=self._api.get_current_directory,
apply_button_label=self._apply_button_label,
click_apply_handler=self._click_apply_handler,
cancel_button_label=self._cancel_button_label,
click_cancel_handler=self._click_cancel_handler,
focus_filename_input=self._focus_filename_input,
)
def _build_context_menus(self):
# Build context menus
self._context_menus = dict()
self._context_menus['item'] = ContextMenu(view=self._view, checkpoint=self._checkpoint_widget)
self._context_menus['list_view'] = ContextMenu(view=self._view, checkpoint=self._checkpoint_widget)
self._context_menus['collection'] = CollectionContextMenu(view=self._view)
self._context_menus['connection'] = ConnectionContextMenu(view=self._view)
self._context_menus['bookmark'] = BookmarkContextMenu(view=self._view)
self._context_menus['udim'] = UdimContextMenu(view=self._view)
def _init_view(self, current_directory: str, current_filename: str):
"""Initialize the view, runs after the view is ready."""
# Mount servers
mounted_servers, make_connection = self._get_mounted_servers()
if mounted_servers:
self._api.add_connections(mounted_servers)
if make_connection:
# OM-71835: Auto-connect specified server specified in the setting (to facilitate the streaming workflows).
# Also, because we can only connect one server at a time, and it's done asynchronously, we do only the first
# in the list.
server_url = list(mounted_servers.values())[0]
self._api.connect_server(server_url)
# Mount local user folders
user_folders = get_user_folders_dict()
if user_folders:
self._view.mount_user_folders(user_folders)
self._api.subscribe_client_bookmarks_changed()
self._apply_config_options()
# Emit UI ready event
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
event_stream.push(UI_READY_EVENT, payload={'title': self._title})
async def _initial_navigation_async(self, current_directory: str, current_filename: str):
url = None
if current_directory:
url = current_directory.rstrip('/')
if current_filename:
url += '/' + current_filename
try:
await self._api.navigate_to_async(url)
if current_directory and self._api:
self._api.set_current_directory(current_directory)
if current_filename and self._api:
self._api.set_filename(current_filename)
except Exception as e:
log_warn(f"Directory {current_directory} not reachable: {str(e)}")
# For file importers or cases where we are creating a non-existing file, the navigation would fail so we need to
# set the current directory and filename regardless
finally:
self._initial_navigation_task = None
def _on_ui_ready(self, event):
# make sure this is only executed once
if self._ui_ready:
return
try:
payload = event.payload.get_dict()
title = payload.get('title', None)
except Exception:
return
if event.type == UI_READY_EVENT and title == self._title:
self._ui_ready = True
# OM-49484: Create a cancellable task for initial navigation, and cancel if user browsed to a directory
if not self._initial_navigation_task or self._initial_navigation_task.done():
self._initial_navigation_task = asyncio.ensure_future(
self._initial_navigation_async(self._current_directory, self._current_filename)
)
def _on_begin_edit(self):
# OM-49484: cancel initial navigation upon user edit for tool bar path field
self._cancel_initial_navigation()
def _cancel_initial_navigation(self):
if self._ui_ready and self._initial_navigation_task:
self._initial_navigation_task.cancel()
self._initial_navigation_task = None
def _get_mounted_servers(self) -> Dict:
"""returns mounted server dict from settings"""
settings = carb.settings.get_settings()
mounted_servers = {}
try:
mounted_servers = settings.get_settings_dictionary("exts/omni.kit.window.filepicker/mounted_servers").get_dict()
except AttributeError:
pass
return mounted_servers, False
def _on_window_width_changed(self, new_width: int):
self._window_size = (new_width, self._window_size[1])
self._detail_splitter.offset_x = self._window_size[0] - self._splitter_offset[1]
def _on_detail_splitter_dragged(self, position_x: int):
new_offset = self._window_size[0] - position_x
# Limit how far offset can move, otherwise will break
self._splitter_offset = (self._splitter_offset[0], max(24, min(350, new_offset)))
self._detail_splitter.offset_x = self._window_size[0] - self._splitter_offset[1]
def _on_toggle_grid_view(self, show_grid_view):
settings = carb.settings.get_settings()
settings.set(f"/persistent{self._settings_root}show_grid_view", show_grid_view)
def _on_scale_grid_view(self, scale_level):
if scale_level is not None:
settings = carb.settings.get_settings()
settings.set(f"/persistent{self._settings_root}grid_view_scale", scale_level)
def _on_mouse_pressed(self, pane: int, button: int, key_mod: int, item: FileBrowserItem):
if button == 1:
# Right mouse button: display context menu
if item:
# Mimics the behavior of Windows file explorer: On right mouse click, if item already
# selected, then apply action to all selections; else, make item the sole selection.
selected = self._view.get_selections(pane=pane)
selected = selected if item in selected else [item]
if self._view.is_collection_node(item):
# OM-75883: Show context menu for collection nodes
self._context_menus.get('collection').show(item)
elif self._view.is_bookmark(item):
# OM-66726: Edit bookmarks similar to Navigator
self._context_menus.get('bookmark').show(item)
elif isinstance(item, FileBrowserUdimItem):
self._context_menus.get('udim').show(item)
elif self._view.is_connection_point(item):
self._context_menus.get('connection').show(item, selected=selected)
else:
self._context_menus.get('item').show(
item,
selected=selected,
)
else:
item = self._view.get_root(pane)
if item:
if pane == TREEVIEW_PANE:
# Skip treeview menu.
pass
elif pane == LISTVIEW_PANE:
self._context_menus.get('list_view').show(
item,
selected=self._view.get_selections(pane=LISTVIEW_PANE),
)
def _on_mouse_double_clicked(self, pane: int, button: int, key_mod: int, item: FileBrowserItem):
if not item:
return
if button == 0 and not item.is_folder:
if self._click_apply_handler:
if self._timestamp_widget:
url = self._timestamp_widget.get_timestamp_url(item.path)
else:
url = item.path
dirname = os.path.dirname(item.path).rstrip("/").rstrip("\\")
filename = os.path.basename(url)
self._click_apply_handler(filename, dirname.replace("\\", "/") if dirname else None)
def _on_selection_changed(self, pane: int, selected: List[FileBrowserItem] = []):
if not selected:
return
# OM-49484: Create a cancellable task for initial navigation, and cancel if user browsed to a directory
self._cancel_initial_navigation()
# OMFP-649: Need hide the loading icon when selection changed to make it clean and consistent.
self.api.hide_loading_pane()
item = selected[-1] or self._view.get_root()
# Note: Below results in None when it's a search item
# OM-66726: Content Browser should edit bookmarks similar to Navigator
if self._view.is_bookmark(item):
self._current_directory = os.path.dirname(item.path)
def set_bookmark(path, _):
# we cannot directly check is_bookmark(item.parent) because item.parent is a FS item, but
# bookmark items are NucleusItem, so had to check path explicitly
self._tool_bar.set_bookmarked(self._view.is_bookmark(None, path=path))
self.api.navigate_to(item.path, callback=partial(set_bookmark, self._current_directory))
dir_item = item if item.is_folder else item.parent
if dir_item:
self._api.set_current_directory(dir_item.path)
self._tool_bar.set_bookmarked(self._view.is_bookmark(dir_item, path=dir_item.path))
self._current_directory = dir_item.path
if not item.is_folder:
self._api.set_filename(item.path)
if self._detail_view:
self._detail_view.on_selection_changed(selected)
if self._selection_changed_fn:
self._selection_changed_fn(selected)
def _on_filename_changed(self, filename: str):
if self._detail_view:
self._detail_view.on_filename_changed(filename)
if self._filename_changed_handler:
self._filename_changed_handler(filename)
def _on_search(self, search_model: SearchResultsModel):
if self._view:
exec_after_redraw(lambda: self._view.show_model(search_model))
def _apply_config_options(self):
settings = self._tool_bar.config_values if self._tool_bar else {}
self._show_unknown_asset_types = not settings.get("hide_unknown")
self._show_thumbnails_folders = not settings.get("hide_thumbnails")
self._view.show_udim_sequence = settings.get("show_udim_sequence")
self._show_deleted = settings.get("show_deleted")
if self._detail_pane:
self._detail_pane.visible = settings.get("show_details", True)
if self._detail_splitter:
self._detail_splitter.visible = settings.get("show_details", True)
self._refresh_ui()
def _item_filter_handler(self, item: FileBrowserItem) -> bool:
"""
Item filter handler, wrapper for the custom handler if specified. Returns True if the item is visible.
Args:
item (:obj:`FileBrowseritem`): Item in question.
Returns:
bool
"""
if not item:
return False
if item.is_deleted:
if not self._show_deleted:
return False
# Does item belongs to the thumbnails folder?
if item.is_folder:
return self._show_thumbnails_folders if item.name == ".thumbs" else True
elif not self._show_thumbnails_folders and "/.thumbs/" in item.path:
return False
# Run custom filter if specified, else the default filter
if self._item_filter_fn:
return self._item_filter_fn(item)
return True
def _refresh_ui(self, item: FileBrowserItem = None):
if not self._view:
return
self._view.refresh_ui(item)
| 33,194 | Python | 46.151989 | 131 | 0.624059 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/file_bar.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 omni.kit.app
from typing import List, Tuple, Callable, Union, Optional
from functools import partial
from .style import get_style, ICON_PATH
from omni.kit.async_engine import run_coroutine
class ComboBoxMenu:
def __init__(self, menu_options: List, **kwargs):
self._window: ui.Window = None
self._parent: ui.Widget = kwargs.get("parent", None)
self._width: int = kwargs.get("width", 210)
self._height: int = kwargs.get("height", 140)
self._selection_changed_fn: Callable = kwargs.get("selection_changed_fn", None)
self._build_ui(menu_options)
def _build_ui(self, menu_options: List):
window_flags = (
ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_POPUP
| ui.WINDOW_FLAGS_NO_TITLE_BAR
| ui.WINDOW_FLAGS_NO_BACKGROUND
| ui.WINDOW_FLAGS_NO_MOVE
| ui.WINDOW_FLAGS_NO_SCROLLBAR
)
self._window = ui.Window("ComboBoxMenu", width=self._width, height=self._height, flags=window_flags)
with self._window.frame:
with ui.ZStack(height=self._height-15, style=get_style()):
ui.Rectangle(style_type_name_override="ComboBox.Menu.Background")
with ui.HStack():
ui.Spacer(width=4)
ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
style_type_name_override="ComboBox.Menu.Frame",
build_fn=partial(self._frame_build_fn, menu_options),
)
def _frame_build_fn(self, menu_options: List):
def on_select_menu(menu: int):
self.hide()
if self._selection_changed_fn:
self._selection_changed_fn(menu)
with ui.ZStack(height=0, style=get_style()):
with ui.VStack(style_type_name_override="ComboBox.Menu"):
for index, menu_option in enumerate(menu_options):
with ui.ZStack():
button = ui.Button(" ", clicked_fn=self.hide, style_type_name_override="ComboBox.Menu.Item")
with ui.HStack(height=16):
if type(menu_option) is tuple:
name, label = menu_option
ui.Label(name, width=0, style_type_name_override="ComboBox.Menu.Item", name="left")
ui.Spacer()
ui.Label(label[:40], width=0, style_type_name_override="ComboBox.Menu.Item", name="right")
else:
name = menu_option
ui.Label(name or "none", width=0, style_type_name_override="ComboBox.Menu.Item")
ui.Spacer()
button.set_clicked_fn(lambda menu=index: on_select_menu(menu))
def show(self, offset_x: int = 0, offset_y: int =0):
if self._parent:
self._window.position_x = self._parent.screen_position_x + offset_x
self._window.position_y = self._parent.screen_position_y + offset_y
elif offset_x != 0 or offset_y != 0:
self._window.position_x = offset_x
self._window.position_y = offset_y
self._window.visible = True
def hide(self):
self._window.visible = False
class ComboBox:
def __init__(self, options: List, **kwargs):
import carb.settings
settings = carb.settings.get_settings()
self._width = kwargs.get("width", 200)
self._selection = kwargs.get("selection", 0)
self._selection_changed_fn: Callable = kwargs.get("selection_changed_fn", None)
self._menu_options = options
self._button = None
self._label = None
self._build_ui(options)
def _build_ui(self, menu_options: List):
if not menu_options:
return None
with ui.ZStack(width=self._width):
self._button = ui.Button(" ", clicked_fn=self.show_menu, style_type_name_override="ComboBox.Button")
with ui.HStack():
ui.Spacer(width=8)
self._label = ui.Label("", style_type_name_override="ComboBox.Button")
ui.Spacer()
ui.ImageWithProvider(f"{ICON_PATH}/dropdown.svg", width=20,
style_type_name_override="ComboBox.Button.Glyph")
self._label.text = self.get_selection_as_string(self._selection)
@property
def selection(self) -> int:
return self._selection
def get_selection_as_string(self, selection: int) -> str:
s = ""
if selection < len(self._menu_options):
menu_option = self._menu_options[selection]
if type(menu_option) is tuple:
s = menu_option[0]
else:
s = menu_option
s = "" + (s or "none")
return s
def show_menu(self):
menu = ComboBoxMenu(self._menu_options, parent=self._button, width=self._width,
selection_changed_fn=self._on_selection_changed
)
menu.show(offset_x=0, offset_y=20)
def _on_selection_changed(self, option: int):
self._selection = option
self._label.text = self.get_selection_as_string(self._selection)
if self._selection_changed_fn:
self._selection_changed_fn()
class FileBar:
def __init__(self, **kwargs):
self._field = None
self._field_label = None
self._hint_text_label = None
self._sub_field_edit = None
self._enable_filename_input = kwargs.get("enable_filename_input", True)
self._focus_filename_input = kwargs.get("focus_filename_input", False)
self._filename_changed_handler = kwargs.get("filename_changed_handler", None)
# OBSOLETE item_filter_options. Prefer to use file_postfix_options + file_extension_options instead.
self._item_filter_options: List[str] = kwargs.get("item_filter_options", None)
self._item_filter_menu: ui.ComboBox = None
self._current_filter_option: int = 0
self._file_postfix_options: List[str] = kwargs.get("file_postfix_options", None)
self._file_postfix: str = kwargs.get("file_postfix", None)
self._file_postfix_menu: ComboBox = None
self._file_extension_options: List[Tuple[str, str]] = kwargs.get("file_extension_options", None)
self._file_extension: str = kwargs.get("file_extension", None)
self._file_extension_menu: ComboBox = None
self._filter_option_changed_handler = kwargs.get("filter_option_changed_handler", None)
self._current_directory_provider = kwargs.get("current_directory_provider", None)
self._apply_button_label = kwargs.get("apply_button_label", "Okay")
self._cancel_button_label = kwargs.get("cancel_button_label", "Cancel")
self._apply_button: ui.Button = None
self._cancel_button: ui.Button = None
self._click_apply_handler = kwargs.get("click_apply_handler", None)
self._click_cancel_handler = kwargs.get("click_cancel_handler", None)
self._file_name_model = None
self._build_ui()
def destroy(self):
self._file_name_model = None
self._current_directory_provider = None
self._filter_option_changed_handler = None
self._file_extension_menu = None
self._file_postfix_menu = None
self._filename_changed_handler = None
self._field_label = None
self._hint_text_label = None
self._item_filter_menu = None
self._field = None
self._sub_field_edit = None
self._click_apply_handler = None
self._click_cancel_handler = None
self._apply_button = None
self._cancel_button = None
@property
def current_filter_option(self) -> int:
return self._current_filter_option
@property
def label_name(self):
if self._field_label:
return self._field_label.text
return None
@label_name.setter
def label_name(self, name):
if name and self._field_label:
self._field_label.text = (f"{name}:")
@property
def filename(self):
if self._enable_filename_input:
return self._file_name_model.get_value_as_string()
return self._hint_text_label.text
@property
def directory(self):
return self._current_directory_provider() if self._current_directory_provider else "."
@filename.setter
def filename(self, filename):
if filename and self._file_name_model:
self._file_name_model.set_value(filename)
if not self._enable_filename_input:
self._hint_text_label.text = filename
@property
def selected_postfix(self):
postfix = None
if self._file_postfix_options and self._file_postfix_menu:
postfix = self._file_postfix_options[self._file_postfix_menu.selection]
return postfix
@property
def postfix_options(self):
return self._file_postfix_options
@property
def selected_extension(self):
extension = None
if self._file_extension_options and self._file_extension_menu:
extension, _ = self._file_extension_options[self._file_extension_menu.selection]
return extension
@property
def extension_options(self):
return self._file_extension_options
def set_postfix(self, postfix: str):
if not postfix:
return
if self._file_postfix_options and self._file_postfix_menu:
if postfix in self._file_postfix_options:
index = self._file_postfix_options.index(postfix)
self._file_postfix_menu._selection = index
self._file_postfix_menu._on_selection_changed(index)
def set_extension(self, extension: str):
if not extension:
return
if self._file_extension_options and self._file_extension_menu:
extension_names = [name for name, _ in self._file_extension_options]
if extension in extension_names:
index = extension_names.index(extension)
self._file_extension_menu._selection = index
self._file_extension_menu._on_selection_changed(index)
def set_click_apply_handler(self, click_apply_handler: Callable[[str, str], None]):
"""
Sets the function to execute upon clicking apply.
Args:
click_apply_handler (Callable): Signature is void fn(filename: str, dirname: str)
"""
self._click_apply_handler = click_apply_handler
def enable_apply_button(self, enable: bool =True):
"""
Enable/disable the apply button for FileBar.
Args:
enable (bool): enable or disable the apply button.
"""
self._apply_button.enabled = enable
def focus_filename_input(self):
"""Utility to help focusing the filename input field."""
if self._field:
self._field.focus_keyboard()
def _build_ui(self):
with ui.HStack(height=24, spacing=2, style=get_style()):
if self._enable_filename_input:
with ui.ZStack():
ui.Rectangle(style_type_name_override="FileBar")
with ui.HStack():
self._field_label = ui.Label(f"File name: ", width=0, style_type_name_override="FileBar.Label")
with ui.Placer(stable_size=True, offset_y=1.5):
self._field = ui.StringField(style_type_name_override="Field")
self._file_name_model = self._field.model
self._sub_field_edit = self._field.model.subscribe_value_changed_fn(self._on_filename_changed)
if self._file_postfix_options:
try:
selection = self._file_postfix_options.index(self._file_postfix)
except Exception:
selection = 0
self._file_postfix_menu = ComboBox(
self._file_postfix_options, selection=selection, selection_changed_fn=self._on_menu_selection_changed, width=117)
if self._file_extension_options:
selection = 0
if self._file_extension:
for index, option in enumerate(self._file_extension_options):
if self._file_extension == option[0]:
selection = index
self._file_extension_menu = ComboBox(
self._file_extension_options, selection=selection, selection_changed_fn=self._on_menu_selection_changed, width=300)
if self._item_filter_options:
# OBSOLETE item_filter_options. This code block is left her for backwards compatibility.
self._item_filter_menu = self._build_filter_combo_box()
else:
# OM-99158: Add hint text display if filename input is disabled
with ui.ZStack():
ui.Rectangle(style_type_name_override="FileBar")
with ui.HStack():
self._field_label = ui.Label(
f"File name: ", width=0, style_type_name_override="FileBar.Label", enabled=False)
self._hint_text_label = ui.Label(
"", width=0, style_type_name_override="FileBar.Label", enabled=False)
self._apply_button = ui.Button(self._apply_button_label, width=117, clicked_fn=lambda: self._on_apply(),
style_type_name_override="Button")
self._cancel_button = ui.Button(self._cancel_button_label, width=117, clicked_fn=lambda: self._on_cancel(),
style_type_name_override="Button")
def _build_filter_combo_box(self) -> ui.ComboBox:
# OBSOLETE This function is left here for backwards compatibility.
args = [self._current_filter_option]
args.extend(self._item_filter_options or [])
with ui.ZStack(width=0):
ui.Rectangle(style_type_name_override="FileBar")
combo_box = ui.ComboBox(*args, width=300, style_type_name_override="ComboBox")
combo_box.model.add_item_changed_fn(lambda m, _: self._on_menu_selection_changed(model=m))
return combo_box
def _on_filename_changed(self, search_words) -> bool:
if self._filename_changed_handler is not None:
self._filename_changed_handler(self.filename)
def _on_menu_selection_changed(self, model: Optional[ui.AbstractItemModel] = None):
if self._file_extension_menu:
postfix_option = 0
if self._file_postfix_menu:
postfix_option = self._file_postfix_menu.selection
extension_option = self._file_extension_menu.selection
if self._filter_option_changed_handler:
self._filter_option_changed_handler()
elif self._item_filter_menu:
# OBSOLETE This case is left here for backwards compatibility.
index = model.get_item_value_model(None, 0)
self._current_filter_option = index.get_value_as_int()
if self._filter_option_changed_handler:
self._filter_option_changed_handler()
def _on_apply(self):
if self._click_apply_handler:
self._click_apply_handler(self.filename, self.directory.replace("\\", "/") if self.directory else None)
def _on_cancel(self):
if self._click_cancel_handler:
self._click_cancel_handler(self.filename, self.directory.replace("\\", "/") if self.directory else None)
| 16,371 | Python | 43.010753 | 139 | 0.592022 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/item_deletion_model.py | # Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
from omni.kit.widget.filebrowser import FileBrowserItem
class ConfirmItemDeletionListItem(ui.AbstractItem):
"""Single item of the list of `FileBrowserItem`s to delete."""
def __init__(self, item: FileBrowserItem):
"""
Single item of the list of `FileBrowserItem`s to delete.
Args:
item (FileBrowserItem): The item of the File Browser which should be deleted.
"""
super().__init__()
self.path_model = ui.SimpleStringModel(item.path)
class ConfirmItemDeletionListModel(ui.AbstractItemModel):
"""Model representing a list of `FileBrowserItem`s to delete."""
def __init__(self, items: [FileBrowserItem]):
"""
Model representing a list of `FileBrowserItem`s to delete.
Args:
items ([FileBrowserItem]): List of File Browser items which should be deleted.
"""
super().__init__()
self._children = [ConfirmItemDeletionListItem(item) for item in items]
def get_item_children(self, item: ConfirmItemDeletionListItem) -> [ConfirmItemDeletionListItem]:
"""
Return the list of all children of the given item to present to the display widget.
Args:
item (ConfirmItemDeletionListItem): Item of the model.
Returns:
[ConfirmItemDeletionListItem]: The list of all children of the given item to present to the display widget.
"""
if item is not None:
# Since we are doing a flat list, we only return the list of items at the root-level.
return []
return self._children
def get_item_value_model_count(self, item: ConfirmItemDeletionListItem) -> int:
"""
Return the number of columns to display.
Args:
item (ConfirmItemDeletionListItem): Item of the model.
Returns:
int: The number of columns to display.
"""
return 1
def get_item_value_model(self, item: ConfirmItemDeletionListItem, column_id: int) -> ui.SimpleStringModel:
"""
Return the value model for the given item at the given column index.
Args:
item (ConfirmItemDeletionListItem): Item of the model for which to return the model.
column_id (int): Index of the column for which to return the model.
Returns:
ui.SimpleStringModel: The model for the given item at the given column index.
"""
if item and isinstance(item, ConfirmItemDeletionListItem) and column_id == 0:
return item.path_model
return None
| 3,045 | Python | 33.613636 | 119 | 0.661741 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/file_ops.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
import sys
import subprocess
import asyncio
import omni.client
import carb.settings
import omni.kit.notification_manager
import omni.kit.app
import omni.ui as ui
from datetime import datetime
from carb import log_warn
from typing import Callable, List, Optional
from functools import partial
from omni.kit.widget.filebrowser import FileBrowserItem, NucleusConnectionItem
from omni.kit.widget.filebrowser.model import FileBrowserItemFields
from omni.kit.notification_manager.notification_info import NotificationStatus
from omni.kit.window.popup_dialog import InputDialog, MessageDialog, FormDialog
from omni.kit.widget.versioning import CheckpointWidget
from .view import FilePickerView
from .bookmark_model import BookmarkItem
from .versioning_helper import VersioningHelper
from .item_deletion_dialog import ConfirmItemDeletionDialog
from .about_dialog import AboutDialog
async def _check_paths_exist_async(paths: List[str]) -> List[str]:
"""Check if paths already exist."""
paths_already_exist = []
for path in paths:
result, _ = await omni.client.stat_async(path)
if result == omni.client.Result.OK:
paths_already_exist.append(path)
return paths_already_exist
def is_usd_supported():
try:
from pxr import Usd, Sdf, UsdGeom
except Exception:
return False
return True
async def is_item_checkpointable(context, menu_item: ui.MenuItem):
if "item" in context:
path = context["item"].path
if VersioningHelper.is_versioning_enabled():
if await VersioningHelper.check_server_checkpoint_support_async(
VersioningHelper.extract_server_from_url(path)
):
menu_item.visible = True
def add_bookmark(item: FileBrowserItem, view: FilePickerView):
def on_okay(dialog: InputDialog, item: FileBrowserItem, view: FilePickerView):
name = dialog.get_value("name")
url = dialog.get_value("address")
try:
view.add_bookmark(name, url, is_folder=item.is_folder)
except Exception as e:
log_warn(f"Error encountered while adding bookmark: {str(e)}")
finally:
dialog.hide()
field_defs = [
FormDialog.FieldDef("name", "Name: ", ui.StringField, item.name, True),
FormDialog.FieldDef("address", "Address: ", ui.StringField, item.path),
]
dialog = FormDialog(
title="Add Bookmark",
width=400,
ok_handler=lambda dialog: on_okay(dialog, item, view),
field_defs=field_defs,
)
dialog.show()
def edit_bookmark(item: BookmarkItem, view: FilePickerView):
def on_okay_clicked(dialog: FormDialog, item: BookmarkItem, view: FilePickerView):
name = dialog.get_value("name")
url = dialog.get_value("address")
try:
assert(isinstance(item, BookmarkItem))
view.rename_bookmark(item, name, url)
except Exception as e:
log_warn(f"Error encountered while editing bookmark: {str(e)}")
finally:
dialog.hide()
field_defs = [
FormDialog.FieldDef("name", "Name: ", ui.StringField, item.name, True),
FormDialog.FieldDef("address", "Address: ", ui.StringField, item.path),
]
dialog = FormDialog(
title="Edit Bookmark",
width=400,
ok_handler=lambda dialog: on_okay_clicked(dialog, item, view),
field_defs=field_defs,
)
dialog.show()
def delete_bookmark(item: BookmarkItem, view: FilePickerView):
def on_okay_clicked(dialog: MessageDialog, item: BookmarkItem, view: FilePickerView):
try:
assert(isinstance(item, BookmarkItem))
view.delete_bookmark(item)
except Exception as e:
log_warn(f"Error encountered while deleting bookmark: {str(e)}")
finally:
dialog.hide()
message = f"Are you sure about deleting the bookmark '{item.name}'?"
dialog = MessageDialog(
title="Delete Bookmark",
width=400,
message=message,
ok_handler=lambda dialog: on_okay_clicked(dialog, item, view),
ok_label="Yes",
cancel_label="No",
)
dialog.show()
def refresh_item(item: FileBrowserItem, view: FilePickerView):
try:
view.refresh_ui(item)
except Exception as e:
log_warn(f"Error refreshing the UI: {str(e)}")
def rename_item(item: FileBrowserItem, view: FilePickerView):
def on_okay(dialog: InputDialog, item: FileBrowserItem, view: FilePickerView):
new_name = dialog.get_value()
try:
if view.is_connection_point(item):
view.rename_server(item, new_name)
else:
rename_file(item, view, new_name)
except Exception as e:
log_warn(f"Error encountered while renaming item: {str(e)}")
finally:
dialog.hide()
# OM-52387: warn user if we are renaming a file or folder, since it may remove all checkpoints permanently for
# the orignal file or folder (similar to what we have in Navigator)
if view.is_connection_point(item):
dialog = InputDialog(
title=f"Rename {item.name}",
width=300,
pre_label="New Name: ",
ok_handler=lambda dialog, item=item: on_okay(dialog, item, view),
)
else:
warning_msg = f"Do you really want to rename \"{item.name}\"?\n\nThis action cannot be undone.\n" + \
"The folder and the checkpoints will be permanently deleted."
dialog = InputDialog(
title=f"Rename {item.name}",
width=450,
warning_message=warning_msg,
ok_handler=lambda dialog, item=item: on_okay(dialog, item, view),
ok_label="Confirm",
message="New name:",
default_value=item.name
)
dialog.show()
def rename_file(item: FileBrowserItem, view: FilePickerView, new_name: str):
if not (item and new_name):
return
try:
def on_moved(item: FileBrowserItem, view: FilePickerView, results):
for result in results:
if isinstance(result, Exception):
asyncio.ensure_future(_display_notification_message(
f"Error renaming file. Failed with error {str(result)}",
NotificationStatus.WARNING
))
# refresh the parent folder UI to immediately display the renamed item
refresh_item(item.parent, view)
new_name = new_name.lstrip("/")
src_root = os.path.dirname(item.path)
dst_path = f"{src_root}/{new_name}"
asyncio.ensure_future(rename_file_async(item.path, dst_path, callback=partial(on_moved, item, view)))
except Exception as e:
log_warn(f"Error encountered during move: {str(e)}")
async def rename_file_async(src_path: str, dst_path: str, callback: Callable = None):
"""
Rename item. Upon success, executes the given callback.
Args:
src_path (str): Path of item to rename.
dst_path (str): Destination path to rename to.
callback (func): Callback to execute upon success. Function signature is void callback([str]).
Raises:
:obj:`Exception`
"""
if not (dst_path and src_path):
return
# don't rename if src and dst is the same
if dst_path == src_path:
return
async def _rename_path(src_path, dst_path):
try:
results = await move_item_async(src_path, dst_path, is_rename=True)
except Exception:
raise
else:
if callback:
callback(results)
src_path = src_path.rstrip("/")
# check destination existence in batch and ask user for overwrite permission before appending move task
paths_already_exist = await _check_paths_exist_async([dst_path])
if paths_already_exist:
def apply_callback(src_path, dst_path, dialog):
dialog.hide()
asyncio.ensure_future(_rename_path(src_path, dst_path))
_prompt_confirm_items_deletion_dialog(paths_already_exist, partial(apply_callback, src_path, dst_path))
else:
await _rename_path(src_path, dst_path)
def add_connection(view: FilePickerView):
try:
view.show_connect_dialog()
except Exception:
pass
def refresh_connection(item: FileBrowserItem, view: FilePickerView):
try:
view.reconnect_server(item)
except Exception:
pass
def log_out_from_connection(item: NucleusConnectionItem, view: FilePickerView):
try:
view.log_out_server(item)
except Exception:
pass
def remove_connection(item: FileBrowserItem, view: FilePickerView):
def on_okay(dialog: MessageDialog, item: FileBrowserItem, view: FilePickerView):
try:
view.delete_server(item)
except Exception as e:
log_warn(f"Error encountered while removing connection: {str(e)}")
finally:
dialog.hide()
message = f"Are you sure about removing the connection for '{item.name}'?"
dialog = MessageDialog(
title="Remove connection",
width=400,
message=message,
ok_handler=lambda dialog, item=item: on_okay(dialog, item, view),
ok_label="Yes",
cancel_label="No",
)
dialog.show()
def about_connection(item: FileBrowserItem):
if not item:
return
async def show_dialog():
server_info = await VersioningHelper.get_server_info_async(item.path)
if server_info:
dialog = AboutDialog(
server_info=server_info,
)
dialog.show()
asyncio.ensure_future(show_dialog())
def create_folder(item: FileBrowserItem):
"""
Creates folder under given item.
Args:
item (:obj:`FileBrowserItem`): Item under which to create the folder.
"""
def on_okay(dialog: InputDialog, item: FileBrowserItem):
try:
assert(item.is_folder)
item_path = item.path.rstrip("/").rstrip("\\")
folder_name = dialog.get_value()
asyncio.ensure_future(omni.client.create_folder_async(f"{item_path}/{folder_name}"))
except Exception as e:
log_warn(f"Error encountered while creating folder: {str(e)}")
finally:
dialog.hide()
dialog = InputDialog(
title="Create folder",
width=300,
pre_label="Name: ",
ok_handler=lambda dialog, item=item: on_okay(dialog, item),
)
dialog.show()
def delete_items(items: List[FileBrowserItem]):
"""
Deletes given items. Upon success, executes the given callback.
Args:
items ([:obj:`FileBrowserItem`]): Items to delete.
callback (Callable): Callback to execute upon success. Function signature is void callback([str]).
Raises:
:obj:`Exception`
"""
if not items:
return
def on_delete_clicked(dialog: ConfirmItemDeletionDialog, items: List[FileBrowserItem]):
if not items:
return
tasks = []
for item in items:
item_path = item.path.rstrip("/").rstrip("\\")
tasks.append(omni.client.delete_async(item_path))
try:
asyncio.ensure_future(exec_tasks_async(tasks))
except Exception as e:
log_warn(f"Error encountered during delete: {str(e)}")
finally:
dialog.hide()
# OMFP-2152: To display dialog in external window, must create window immediately
# And change message later if necessary
dialog = ConfirmItemDeletionDialog(
items=items,
ok_handler=lambda dialog, items=items: on_delete_clicked(dialog, items),
)
async def show_dialog():
checkpoint_support = False
is_folder = False
for item in items:
if item.is_folder:
is_folder = True
if await VersioningHelper.check_server_checkpoint_support_async(item.path):
checkpoint_support = True
if checkpoint_support:
if len(items) > 1:
msg = f"Do you really want to delete these items - including Checkpoints?\n\nThis action cannot be undone. The items and any checkpoints will be permanently deleted."
elif is_folder:
name = os.path.basename(items[0].path)
msg = f"Do you really want to delete \"{name}\" folder and all of its contents - including files and their Checkpoints?\n\nThis action cannot be undone. The folder and all its contents will be permanently deleted."
else:
name = os.path.basename(items[0].path)
msg = f"Do you really want to delete \"{name}\" and all of its checkpoints?\n\nThis action cannot be undone. The file and the checkpoints will be permanently deleted."
def build_msg():
with ui.ZStack(height=0):
ui.Rectangle(style={"background_color": 0xFFCCCCFF}, height=ui.Percent(100), width=ui.Percent(100))
ui.Label(msg, word_wrap=True, style={"margin": 5, "color": 0xFF6D6DD5, "font_size": 16})
dialog.rebuild_ui(build_msg)
dialog.show()
asyncio.ensure_future(show_dialog())
def move_items(dst_item: FileBrowserItem, src_paths: List[str], dst_name: Optional[str] = None, callback: Callable = None):
if not dst_item:
return
try:
from omni.kit.notification_manager import post_notification
except Exception:
post_notification = log_warn
if dst_item and src_paths:
try:
def on_moved(results, callback=None):
for result in results:
if isinstance(result, Exception):
post_notification(str(result))
if callback:
callback()
asyncio.ensure_future(
move_items_async(src_paths, dst_item.path, callback=partial(on_moved, callback=callback)))
except Exception as e:
log_warn(f"Error encountered during move: {str(e)}")
async def move_items_async(src_paths: List[str], dst_path: str, callback: Callable = None):
"""
Moves items. Upon success, executes the given callback.
Args:
src_paths ([str]): Paths of items to move.
dst_path (str): Destination folder.
callback (func): Callback to execute upon success. Function signature is void callback([str]).
Raises:
:obj:`Exception`
"""
if not (dst_path and src_paths):
return
dst_paths = []
for src_path in src_paths:
# use the src_path basename and construct the dst path result
src_name = os.path.basename(src_path.rstrip("/"))
dst_paths.append(f"{dst_path}/{src_name}")
async def _move_paths(src_paths, dst_paths):
tasks = []
for src_path, dst_path in zip(src_paths, dst_paths):
tasks.append(move_item_async(src_path, dst_path))
try:
await exec_tasks_async(tasks, callback=callback)
except Exception:
raise
# check destination existence in batch and ask user for overwrite permission before appending move task
paths_already_exist = await _check_paths_exist_async(dst_paths)
if paths_already_exist:
def apply_callback(src_paths, dst_paths, dialog):
dialog.hide()
asyncio.ensure_future(_move_paths(src_paths, dst_paths))
_prompt_confirm_items_deletion_dialog(paths_already_exist, partial(apply_callback, src_paths, dst_paths))
else:
await _move_paths(src_paths, dst_paths)
async def move_item_async(src_path: str, dst_path: str, timeout: float = 300.0, is_rename: bool = False) -> str:
"""
Async function that moves item (recursively) from one path to another.
Note: this function simply uses the move function from omni.client and makes no attempt to optimize for
moving from one Omniverse server to another.
Example usage:
await move_item_async("C:/tmp/my_file.usd", "omniverse://ov-content/Users/me/moved.usd")
Args:
src_root (str): Source path to item being copied.
dst_root (str): Destination path to move the item.
timeout (float): Number of seconds to try before erroring out. Default 10.
Returns:
str: Destination path name
Raises:
:obj:`RuntimeWarning`: If error or timeout.
"""
timeout = max(300, timeout)
try:
# OM-54464: add source url in moved/renamed item checkpoint
src_checkpoint = None
result, entries = await omni.client.list_checkpoints_async(src_path)
if result == omni.client.Result.OK and entries:
src_checkpoint = entries[-1].relative_path
op_str = "Moved"
if is_rename:
op_str = "Renamed"
checkpoint_msg = f"{op_str} from {src_path}"
if src_checkpoint:
checkpoint_msg = f"{checkpoint_msg}?{src_checkpoint}"
result, _ = await asyncio.wait_for(
omni.client.move_async(src_path, dst_path, behavior=omni.client.CopyBehavior.OVERWRITE, message=checkpoint_msg),
timeout=timeout
)
except asyncio.TimeoutError:
raise RuntimeWarning(f"Error unable to move '{src_path}' to '{dst_path}': Timed out after {timeout} secs.")
except Exception as e:
raise RuntimeWarning(f"Error moving '{src_path}' to '{dst_path}': {e}")
if result != omni.client.Result.OK:
raise RuntimeWarning(f"Error moving '{src_path}' to '{dst_path}': {result}")
return dst_path
async def obliterate_item_async(path: str, timeout: float = 10.0) -> str:
"""
Async function. obliterates the item at the given path name.
Args:
path (str): The full path name of a file or folder, e.g. "omniverse://ov-content/Users/me".
timeout (float): Number of seconds to try before erroring out. Default 10.
Returns:
str: obliterated path name
Raises:
:obj:`RuntimeWarning`: If error or timeout.
"""
try:
path = path.replace("\\", "/")
result = await asyncio.wait_for(omni.client.obliterate_async(path, True), timeout=timeout)
print(result)
except asyncio.TimeoutError:
raise RuntimeWarning(f"Error obliterating item '{path}': Timed out after {timeout} secs.")
except Exception as e:
raise RuntimeWarning(f"Error obliterating item '{path}': {e}")
if result != omni.client.Result.OK:
raise RuntimeWarning(f"Error obliterating item '{path}': {result}")
return path
def obliterate_items(items: [FileBrowserItem], view: FilePickerView):
"""
Obliterate given items. Upon success, executes the given callback.
Args:
items ([:obj:`FileBrowserItem`]): Items to obliterate.
callback (Callable): Callback to execute upon success. Function signature is void callback([str]).
Raises:
:obj:`Exception`
"""
if not items:
return
def on_obliterated(item: FileBrowserItem, view: FilePickerView, results):
for result in results:
if isinstance(result, Exception):
asyncio.ensure_future(_display_notification_message(
f"Error oblitereate file. Failed with error {str(result)}",
NotificationStatus.WARNING
))
# refresh the parent folder UI to immediately display the renamed item
refresh_item(item.parent, view)
def on_obliterate_clicked(dialog: ConfirmItemDeletionDialog, items: List[FileBrowserItem]):
if not items:
return
tasks = []
for item in items:
item_path = item.path.rstrip("/").rstrip("\\")
tasks.append(obliterate_item_async(item_path))
try:
asyncio.ensure_future(exec_tasks_async(tasks, callback=partial(on_obliterated, items[0], view)))
except Exception as e:
log_warn(f"Error encountered during obliterate: {str(e)}")
finally:
dialog.hide()
async def show_dialog():
checkpoint_support = False
is_folder = False
for item in items:
if item.is_folder:
is_folder = True
if await VersioningHelper.check_server_checkpoint_support_async(item.path):
checkpoint_support = True
if checkpoint_support:
if len(items) > 1:
msg = f"Do you really want to obliterate these items - including Checkpoints?\n\nThis action cannot be undone. The items and any checkpoints will be permanently deleted."
elif is_folder:
name = os.path.basename(items[0].path)
msg = f"Do you really want to obliterate \"{name}\" folder and all of it contents - including files and their Checkpoints?\n\nThis action cannot be undone. The folder and all its contents will be permanently deleted."
else:
name = os.path.basename(items[0].path)
msg = f"Do you really want to obliterate \"{name}\" and all of its checkpoints?\n\nThis action cannot be undone. The file and the checkpoints will be permanently deleted."
def build_msg():
with ui.ZStack(height=0):
ui.Rectangle(style={"background_color": 0xFFCCCCFF}, height=ui.Percent(100), width=ui.Percent(100))
ui.Label(msg, word_wrap=True, style={"margin": 5, "color": 0xFF6D6DD5, "font_size": 16})
dialog = ConfirmItemDeletionDialog(
items=items,
message_fn=build_msg,
ok_handler=lambda dialog, items=items: on_obliterate_clicked(dialog, items),
)
else:
dialog = ConfirmItemDeletionDialog(
items=items,
ok_handler=lambda dialog, items=items: on_obliterate_clicked(dialog, items),
)
dialog.show()
asyncio.ensure_future(show_dialog())
async def restore_item_async(path: str, timeout: float = 10.0) -> str:
"""
Async function. restore the item at the given path name.
Args:
path (str): The full path name of a file or folder, e.g. "omniverse://ov-content/Users/me".
timeout (float): Number of seconds to try before erroring out. Default 10.
Returns:
str: restore path name
Raises:
:obj:`RuntimeWarning`: If error or timeout.
"""
try:
path = path.replace("\\", "/")
result = await asyncio.wait_for(omni.client.undelete_async(path), timeout=timeout)
except asyncio.TimeoutError:
raise RuntimeWarning(f"Error restoring item '{path}': Timed out after {timeout} secs.")
except Exception as e:
raise RuntimeWarning(f"Error restoring item '{path}': {e}")
if result != omni.client.Result.OK:
raise RuntimeWarning(f"Error restoring item '{path}': {result}")
return path
def restore_items(items: [FileBrowserItem], view: FilePickerView):
"""
Restore given items. Upon success, executes the given callback.
Args:
items ([:obj:`FileBrowserItem`]): Items to restore.
callback (Callable): Callback to execute upon success. Function signature is void callback([str]).
Raises:
:obj:`Exception`
"""
def on_restored(item: FileBrowserItem, view: FilePickerView, results):
for result in results:
if isinstance(result, Exception):
asyncio.ensure_future(_display_notification_message(
f"Error restore file. Failed with error {str(result)}",
NotificationStatus.WARNING
))
# refresh the parent folder UI to immediately display the renamed item
refresh_item(item.parent, view)
if items:
tasks = []
for item in items:
if item.is_deleted:
item_path = item.path.rstrip("/").rstrip("\\")
if item.is_folder:
item_path = item_path + "/"
tasks.append(restore_item_async(item_path))
asyncio.ensure_future(exec_tasks_async(tasks, callback=partial(on_restored, items[0], view)))
def _prompt_confirm_items_deletion_dialog(dst_paths, apply_callback):
"""Checks dst_paths existence and prompt user to confirm deletion."""
items = []
for dst_path in dst_paths:
dst_name = os.path.basename(dst_path)
items.append(
FileBrowserItem(dst_path, FileBrowserItemFields(dst_name, datetime.now(), 0, 0), is_folder=False))
dialog = ConfirmItemDeletionDialog(
title="Confirm File Overwrite",
message="You are about to overwrite",
items=items,
ok_handler=lambda dialog: apply_callback(dialog),
)
dialog.show()
def checkpoint_items(items: List[FileBrowserItem], checkpoint_widget: CheckpointWidget):
if not items:
return
paths = [item.path if not item.is_folder else "" for item in items]
async def checkpoint_items_async(checkpoint_comment: str, checkpoint_widget: CheckpointWidget):
for path in paths:
if path and await VersioningHelper.check_server_checkpoint_support_async(
VersioningHelper.extract_server_from_url(path)
):
result, entry = await omni.client.create_checkpoint_async(path, checkpoint_comment, True)
if result != omni.client.Result.OK:
await _display_notification_message(
f"Error creating checkpoint for {path}. Failed with error {result}",
NotificationStatus.WARNING
)
elif checkpoint_widget:
checkpoint_widget._model.list_checkpoint()
def on_ok(checkpoint_comment):
asyncio.ensure_future(checkpoint_items_async(checkpoint_comment, checkpoint_widget))
VersioningHelper.menu_checkpoint_dialog(ok_fn=on_ok, cancel_fn=None)
def copy_to_clipboard(item: FileBrowserItem):
try:
import omni.kit.clipboard
omni.kit.clipboard.copy(item.path)
except ImportError:
log_warn("Warning: Could not import omni.kit.clipboard.")
def open_in_file_browser(item: FileBrowserItem):
"""
Open the given file item in the OS's native file browser.
Args:
item (FileBrowserItem): Selected item of the Content Browser.
Returns:
None
"""
# NOTE: Providing this normalized path as an argument to `subprocess.Popen()` will properly handle the case of
# the given path containing spaces, and avoids having to parse and surround inputs with double quotation marks.
normalized_item_path = os.path.normpath(item.path)
if sys.platform == "win32":
# On Windows, open the File Explorer view at the parent-level of the given path, with the given file
# selected. This provides a view similar to what is displayed in the Content browser, and avoids Windows'
# behavior of either opening the File Explorer *in* the given folder path, or its parent when opening a
# file.
#
# NOTE: The trailing comma character (",") is intentional (see https://ss64.com/nt/explorer.html).
subprocess.Popen(["explorer", "/select,", normalized_item_path])
elif sys.platform == "darwin":
subprocess.Popen(["open", normalized_item_path])
else:
subprocess.Popen(["xdg-open", normalized_item_path])
def create_usd_file(item: FileBrowserItem):
"""
Action executed upon clicking the "New USD File" contextual menu item.
Args:
item (FileBrowserItem): Directory item of the File Browser where to create the new USD file.
Returns:
None
"""
async def create_empty_usd_file(usd_file_basename: str) -> None:
if is_usd_supported():
from pxr import Usd, Sdf, UsdGeom
else:
await _display_notification_message(f"Failed to import USD library.", NotificationStatus.WARNING)
return
absolute_usd_file_path = os.path.join(item.path, f"{usd_file_basename}.usd").replace("\\", "/")
if not await _validate_usd_file_creation(usd_file_basename, absolute_usd_file_path):
return
layer = Sdf.Layer.CreateNew(absolute_usd_file_path)
if not layer:
await _display_notification_message(
f"Unable to create USD file at location \"{absolute_usd_file_path}\".",
NotificationStatus.WARNING)
return
stage = Usd.Stage.Open(layer)
upAxis = carb.settings.get_settings().get_as_string("/persistent/app/stage/upAxis") or ""
if upAxis == "Z":
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.z)
else:
UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y)
stage.Save()
def on_okay_clicked(dialog: InputDialog, item: FileBrowserItem) -> None:
asyncio.ensure_future(create_empty_usd_file(dialog.get_value()))
dialog.hide()
dialog = InputDialog(
title="New USD",
message="New USD File",
pre_label="File Name: ",
post_label=".usd",
default_value="new_file",
ok_handler=lambda dialog, item=item: on_okay_clicked(dialog, item),
ok_label="Create",
)
dialog.show()
async def _validate_usd_file_creation(usd_filename: str, absolute_usd_file_path: str) -> bool:
"""
Check if the given absolute file path for a USD file can be created, based on:
* Whether or not the given file name is empty.
* Whether or not the given file path already exists.
Args:
usd_filename (str): The name of the USD file to create, as provided by the User (without extension).
absolute_usd_file_path (str): The absolute file path of a USD file to create.
Returns:
bool: `True` if the given absolute file path for a USD file can be created, `False` otherwise.
"""
# No desired filename was submitted:
if len(usd_filename) == 0:
await _display_notification_message("Please provide a name for the USD file.")
return False
# A file with the same name already exists:
usd_file_basename = os.path.basename(absolute_usd_file_path)
result, _ = await omni.client.stat_async(absolute_usd_file_path)
if result == omni.client.Result.OK:
await _display_notification_message(
f"A file with the same name \"{usd_file_basename}\" already exists in this location.",
NotificationStatus.WARNING
)
return False
return True
async def _display_notification_message(
message: str,
status: NotificationStatus = NotificationStatus.INFO,
) -> None:
"""
Display the given notification message to the User, using the given status.
Args:
message (str): Message to display in the notification.
status (NotificationStatus): Status of the notification (default: `NotificationStatus.INFO`).
Returns:
None
"""
try:
await omni.kit.app.get_app().next_update_async()
omni.kit.notification_manager.post_notification(
text=message,
status=status,
hide_after_timeout=False,
)
except:
if status == NotificationStatus.WARNING:
carb.log_warn(message)
else:
carb.log_info(message)
async def exec_tasks_async(tasks, callback: Callable = None):
"""
Helper function to execute a given list of tasks concurrently. When done, invokes the callback with the
list of results. Results can include an exceptions if appropriate.
Args:
tasks ([]:obj:`Task`]): List of tasks to execute.
callback (Callable): Invokes this callback when all tasks are finished. Function signature is
void callback(results: List[Union[str, Exception]])
"""
try:
results = await asyncio.gather(*tasks, return_exceptions=True)
except asyncio.CancelledError:
return
except Exception:
# Since we're returning exceptions, we should never hit this case
return
else:
if callback:
callback(results)
| 32,689 | Python | 35.443701 | 233 | 0.629386 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/datetime/style.py | from omni.ui import color as cl
cl.datetime_bg = cl('#242424')
cl.datetime_fg = cl('#545454')
cl.datetime_fg2 = cl('#848484')
cl.blue_light = cl('#3c63d3')
default_datetime_window_style = {
"Window": {"background_color": cl.transparent},
"Button": {"margin_height": 0.5, "margin_width": 0.5, },
"Button::day:selected": {"background_color": cl.datetime_fg},
"ComboBox::year": {"background_color": cl.datetime_bg},
"ComboBox::timezone": {"secondary_color": cl.datetime_bg},
"Rectangle::blank": {"background_color": cl.transparent},
"Label::number": {"font_size": 32},
"Label::morning": {"font_size": 14},
"Label::week": {"font_size": 16},
"Triangle::spinner": {"background_color": cl.datetime_fg2, "border_width": 0},
"Triangle::spinner:hovered": {"background_color": cl.datetime_fg},
"Triangle::spinner:pressed": {"background_color": cl.datetime_fg},
"Circle::clock": {"background_color": cl.datetime_fg2, "border_width": 0},
"Circle::day": {
"background_color": cl.transparent,
"border_color": cl.transparent,
"border_width": 2,
"margin": 2
},
"Circle::day:hovered": {"border_color": cl.blue_light},
}
select_circle_style = {"border_color": cl.blue_light}
unselect_circle_style = {"border_color": cl.transparent} | 1,312 | Python | 38.787878 | 82 | 0.633384 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/datetime/clock.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
from .models import TimeModel
class ClockWidget:
"""
Represents a clock to show hour minute and second
Keyword Args:
model (TimeModel): Widget model.
width (int): Widget width. Default 160.
height (int): Widget height. Default 32.
"""
def __init__(
self,
model: TimeModel,
width: int = 160,
height: int = 32,
):
self._model = model
self._time_changing = False
with ui.HStack(width=width, height=height, spacing=2):
self._hour_0 = ui.Label("0", name="number", width=0, height=0)
self._hour_1 = ui.Label("0", name="number", width=0, height=0)
# Spin for hour
with ui.VStack():
ui.Spacer()
self._hour_up = ui.Triangle(
name="spinner",
width=14,
height=10,
alignment=ui.Alignment.CENTER_TOP,
mouse_pressed_fn=(lambda x, y, key, m: self._on_hour_clicked(key, 1)),
)
ui.Spacer(height=6)
self._hour_down = ui.Triangle(
name="spinner",
width=14,
height=10,
alignment=ui.Alignment.CENTER_BOTTOM,
mouse_pressed_fn=(lambda x, y, key, m: self._on_hour_clicked(key, -1)),
)
ui.Spacer()
ui.Spacer(width=4)
# Colon between hour and minute
with ui.VStack(width=8):
ui.Spacer()
ui.Circle(name="clock", width=4, height=4)
ui.Spacer()
ui.Circle(name="clock", width=4, height=4)
ui.Spacer()
# 2 digits for minute
self._minute_0 = ui.Label("0", name="number", width=0, height=0)
self._minute_1 = ui.Label("0", name="number", width=0, height=0)
# Spin for minute
with ui.VStack():
ui.Spacer()
self._minute_up = ui.Triangle(
name="spinner",
width=14,
height=10,
alignment=ui.Alignment.CENTER_TOP,
mouse_pressed_fn=(lambda x, y, key, m: self._on_minute_clicked(key, 1)),
)
ui.Spacer(height=6)
self._minute_down = ui.Triangle(
name="spinner",
width=14,
height=10,
alignment=ui.Alignment.CENTER_BOTTOM,
mouse_pressed_fn=(lambda x, y, key, m: self._on_minute_clicked(key, -1)),
)
ui.Spacer()
# Lable for half-day
with ui.VStack():
ui.Spacer(height=ui.Percent(50))
self._half_day = ui.Label("PM", name="morning", width=0)
# Spin for half-day
with ui.VStack():
ui.Spacer(height=ui.Percent(50))
ui.Spacer(height=3)
self._day_down = ui.Triangle(
name="spinner",
width=14,
height=10,
alignment=ui.Alignment.CENTER_BOTTOM,
mouse_pressed_fn=(lambda x, y, key, m: self._on_half_day_clicked(key)),
)
self._on_time_changed(None)
self._model.add_value_changed_fn(self._on_time_changed)
def __del__(self):
self.destroy()
def destroy(self):
self._model = None
def _on_hour_clicked(self, key, step):
if key == 0:
self._model.hour += step
def _on_minute_clicked(self, key, step):
if key == 0:
self._model.minute += step
def _on_half_day_clicked(self, key):
if key != 0:
return
hour = self._model.hour
if hour < 12:
hour += 12
else:
hour -= 12
self._model.hour = hour
@property
def model(self):
return self._model
def _on_time_changed(self, model):
if self._time_changing:
return
self._time_changing = True
self._hour_0.text = str(self._model.hour // 10)
self._hour_1.text = str(self._model.hour % 10)
self._minute_0.text = str(self._model.minute // 10)
self._minute_1.text = str(self._model.minute % 10)
self._half_day.text = "AM" if self._model.hour < 12 else "PM"
self._time_changing = False
| 4,981 | Python | 32.662162 | 93 | 0.500301 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/datetime/__init__.py | from .calendar import CalendarWidget
from .clock import ClockWidget
from .date_widget import DateWidget
from .time_widget import TimeWidget
from .timezone_widget import TimezoneWidget | 183 | Python | 35.799993 | 43 | 0.852459 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/datetime/timezone_widget.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
from .models import ZoneModel
class TimezoneWidget:
"""
a combox for common timezones.
Keyword Args:
model (ZoneModel): Widget model.
width (int): Widget width. Default 80.
"""
def __init__(self, model: ZoneModel = None, **kwargs):
if model:
self._model = model
else:
self._model = ZoneModel()
width = kwargs.get("width", 80)
self._timezones = self._get_pytz_timezones()
self._timezone_combo = ui.ComboBox(0, *self._timezones, name="timezone", width=width)
self._on_zone_changed(None)
self._model.add_value_changed_fn(self._on_zone_changed)
self._timezone_combo.model.add_item_changed_fn(self._on_combo_selected)
def __del__(self):
self.destroy()
def destroy(self):
self._model = None
self._timezone_combo = None
@property
def model(self):
return self._model
def _on_zone_changed(self, model):
index = self._timezones.index(str(self._model.timezone))
self._timezone_combo.model.get_item_value_model().set_value(index)
def _on_combo_selected(self, model, item):
index = model.get_item_value_model().as_int
self._set_timezone(index)
def _get_pytz_timezones(self):
try:
import pytz
return pytz.common_timezones
except Exception:
return ["UTC"]
def _set_timezone(self, index):
try:
import pytz
self._model.set_value(pytz.timezone(self._timezones[index]))
except Exception:
return | 2,058 | Python | 31.171875 | 93 | 0.635083 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/datetime/calendar.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import calendar
import omni.ui as ui
from .models import DateModel
from .style import select_circle_style, unselect_circle_style
class CalendarWidget:
"""
Represents a calendar to show year month and day
Keyword Args:
model (DateModel): Widget model.
width (int): Widget width. Default 160.
height (int): Widget height. Default 140.
year_min (int): min year in year combobox. default 2000,
year_max (int): max year in year combobox. default 2050,
"""
def __init__(
self,
model: DateModel,
width: int = 175,
height: int = 195,
year_min: int = 2000,
year_max: int = 2050
):
self._model = model
self._year_min = year_min
self._year_max = year_max
self._year_list = [str(year) for year in range(year_min, year_max)]
self._month_list = calendar.month_name[1:]
self._calendar = calendar.Calendar(calendar.SUNDAY)
self._day_buttons = []
self._week_days = None
self._date_changing = False
combox_height = 20
self._cell_width = width / 7
self._cell_height = (height - combox_height) / 7
with ui.VStack(width=width, height=height, spacing=0):
# Month and Year
with ui.HStack(height=combox_height):
self._month_combo = ui.ComboBox(0, *self._month_list, name="month", width=85)
ui.Spacer()
self._year_combo = ui.ComboBox(0, *self._year_list, name="year", width=60)
self._month_combo.model.add_item_changed_fn(self._on_month_changed)
self._year_combo.model.add_item_changed_fn(self._on_year_changed)
# Week days
self._week_days = ui.Frame()
self._week_days.set_build_fn(self._build_week_days)
self._on_date_changed(None)
self._model.add_value_changed_fn(self._on_date_changed)
def __del__(self):
self.destroy()
def destroy(self):
self._model = None
self._week_days = None
self._day_buttons.clear()
def _build_week_days(self):
self._day_buttons.clear()
# add None for day 0, so the N day's button is buttons[N]
self._day_buttons.append(None)
with ui.VGrid(column_count=7, row_height=self._cell_height):
week_day = ["S", "M", "T", "W", "T", "F", "S"]
for i in range(7):
ui.Label(week_day[i], name="week", alignment=ui.Alignment.CENTER)
for day in self._calendar.itermonthdays(self._model.year, self._model.month):
if day > 0:
with ui.ZStack(alignment=ui.Alignment.CENTER):
button = ui.Circle(
name="day",
alignment=ui.Alignment.CENTER,
mouse_released_fn=lambda x, y, b, f, d=day: self._on_day_changed(b, d)
)
ui.Label(str(day), name="week", alignment=ui.Alignment.CENTER)
self._day_buttons.append(button)
else:
ui.Spacer()
self._day_buttons[self._model.day].set_style(select_circle_style)
def _on_month_changed(self, model, item):
selected_month = model.get_item_value_model().as_int + 1
if self._model.month == selected_month:
return
self._model.month = selected_month
self._week_days.rebuild()
def _on_year_changed(self, model, item):
selected_year = model.get_item_value_model().as_int + self._year_min
if self._model.year == selected_year:
return
self._model.year = selected_year
self._week_days.rebuild()
def _on_day_changed(self, b, day: int):
if b != 0:
return
if self._model.day == day:
return
self._day_buttons[self._model.day].set_style(unselect_circle_style)
self._day_buttons[day].set_style(select_circle_style)
self._model.day = day
@property
def model(self):
return self._model
def _on_date_changed(self, model):
if self._date_changing:
return
self._date_changing = True
if self._model.year > self._year_max:
self._model.year = self._year_max
if self._model.year < self._year_min:
self._model.year = self._year_min
self._month_combo.model.get_item_value_model().set_value(self._model.month - 1)
self._year_combo.model.get_item_value_model().set_value(self._model.year - self._year_min)
self._week_days.rebuild()
self._date_changing = False
| 5,125 | Python | 36.691176 | 98 | 0.580098 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/datetime/time_widget.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import omni.kit.app
import omni.ui as ui
from .clock import ClockWidget
from .models import TimeModel
from .style import default_datetime_window_style
class TimeWidget:
def __init__(self, model: TimeModel = None, **kwargs):
"""
Time Widget.
Keyword Args:
model (TimeModel): Widget model.
width (int): Input field width of widget. Default 60.
style (dict): Widget style.
"""
if model:
self._model = model
else:
self._model = TimeModel()
width = kwargs.get("width", 60)
self._style = kwargs.get("style", {})
self._time_field = ui.StringField(self._model, width=width)
self._model.add_begin_edit_fn(self._on_begin_edit)
self._window = None
self._clock = None
def __del__(self):
self.destroy()
def destroy(self):
self._model = None
self._time_field = None
if self._window:
self._window.destroy()
self._window = None
if self._clock:
self._clock.destroy()
self._clock = None
@property
def model(self):
return self._model
def _on_begin_edit(self, model):
if self._window and self._window.visible:
return
# Create and show the window with fields and calendar
flags = ui.WINDOW_FLAGS_POPUP | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_MOVE | ui.WINDOW_FLAGS_NO_RESIZE
self._window = ui.Window(
"Clock",
flags=flags,
auto_resize=True,
padding_x=0,
padding_y=0,
)
self._window.frame.style = default_datetime_window_style
with self._window.frame:
with ui.VStack(style=self._style):
with ui.HStack(height=0):
time_field = ui.StringField(self._model, width=self._time_field.computed_content_width)
time_field.focus_keyboard()
blank_area = ui.Rectangle(name="blank")
blank_area.set_mouse_pressed_fn(self._on_blank_clicked)
ui.Spacer(height=4)
with ui.ZStack():
ui.Rectangle()
self._clock = ClockWidget(self._model)
self._window.position_x = self._time_field.screen_position_x
self._window.position_y = self._time_field.screen_position_y
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 self._clock:
self._clock.destroy()
self._clock = None
if self._window:
self._window.destroy()
self._window = None
def _on_blank_clicked(self, x, y, b, m):
self._window.visible = False
asyncio.ensure_future(self._destroy_window_async())
| 3,397 | Python | 34.030927 | 122 | 0.591993 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/datetime/models.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import datetime
import calendar
import omni.ui as ui
from dateutil import parser
class DateModel(ui.AbstractValueModel):
def __init__(self, _datetime: datetime.datetime = None):
super().__init__()
if _datetime:
self._datetime = _datetime
else:
self._datetime = datetime.datetime.today()
def set_value(self, dt_string: str):
try:
datetime = parser.parse(dt_string)
except Exception:
return
self._datetime = self._datetime.replace(year=datetime.year, month=datetime.month, day=datetime.day)
self._value_changed()
def get_value_as_string(self):
return self._datetime.strftime("%Y-%m-%d")
@property
def year(self):
return self._datetime.year
@year.setter
def year(self, value):
day = self._adjust_day(value, self._datetime.month)
self._datetime = self._datetime.replace(year=value, day=day)
self._value_changed()
@property
def month(self):
return self._datetime.month
@month.setter
def month(self, value):
day = self._adjust_day(self._datetime.year, value)
self._datetime = self._datetime.replace(month=value, day=day)
self._value_changed()
@property
def day(self):
return self._datetime.day
@day.setter
def day(self, value):
self._datetime = self._datetime.replace(day=value)
self._value_changed()
def _adjust_day(self, year, month):
_, lastday = calendar.monthrange(year, month)
cur_day = self._datetime.day
return lastday if cur_day > lastday else cur_day
class TimeModel(ui.AbstractValueModel):
def __init__(self, _datetime: datetime.datetime = None):
super().__init__()
if _datetime:
self._datetime = _datetime
else:
self._datetime = datetime.datetime.now()
def set_value(self, dt_string: str):
try:
datetime = parser.parse(dt_string)
except Exception:
return
self._datetime = self._datetime.replace(hour=datetime.hour, minute=datetime.minute, second=datetime.second)
self._value_changed()
def get_value_as_string(self):
return self._datetime.strftime("%H:%M:%S")
@property
def hour(self):
return self._datetime.hour
@hour.setter
def hour(self, value):
if value < 0:
value = 23
if value > 23:
value = 0
self._datetime = self._datetime.replace(hour=value)
self._value_changed()
@property
def minute(self):
return self._datetime.minute
@minute.setter
def minute(self, value):
if value < 0:
value = 59
if value > 59:
value = 0
self._datetime = self._datetime.replace(minute=value)
self._value_changed()
@property
def second(self):
return self._datetime.second
@second.setter
def second(self, value):
if value < 0:
value = 59
if value > 59:
value = 0
self._datetime = self._datetime.replace(second=value)
self._value_changed()
class ZoneModel(ui.AbstractValueModel):
def __init__(self, _datetime: datetime.datetime = None):
super().__init__()
if _datetime:
self._datetime = _datetime
else:
self._datetime = datetime.datetime.now(tz=datetime.timezone.utc)
def set_value(self, tz: datetime.timezone):
self._datetime = self._datetime.astimezone(tz=tz)
self._value_changed()
def get_value_as_string(self):
return self._datetime.tzname()
@property
def timezone(self):
return self._datetime.tzinfo
| 4,198 | Python | 27.181208 | 115 | 0.61172 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/datetime/date_widget.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import omni.kit.app
import omni.ui as ui
from .calendar import CalendarWidget
from .models import DateModel
from .style import default_datetime_window_style
class DateWidget:
def __init__(self, model: DateModel = None, **kwargs):
"""
Date Widget.
Keyword Args:
model (DateModel): Widget model.
width (int): Input field width of widget. Default 80.
style (dict): Widget style.
"""
if model:
self._model = model
else:
self._model = DateModel()
width = kwargs.get("width", 80)
self._style = kwargs.get("style", {})
self._date_field = ui.StringField(self._model, width=width)
self._model.add_begin_edit_fn(self._on_begin_edit)
self._window = None
self._calendar = None
def __del__(self):
self.destroy()
def destroy(self):
self._model = None
self._date_field = None
if self._window:
self._window.destroy()
self._window = None
if self._calendar:
self._calendar.destroy()
self._calendar = None
@property
def model(self):
return self._model
def _on_begin_edit(self, model):
if self._window and self._window.visible:
return
flags = ui.WINDOW_FLAGS_POPUP | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_MOVE | ui.WINDOW_FLAGS_NO_RESIZE
# Create and show the window with fields and calendar
self._window = ui.Window(
"Calendar",
flags=flags,
auto_resize=True,
padding_x=0,
padding_y=0,
)
self._window.frame.style = default_datetime_window_style
with self._window.frame:
with ui.VStack(style=self._style):
with ui.HStack(height=0):
date_field = ui.StringField(self._model, width=self._date_field.computed_content_width)
date_field.focus_keyboard()
blank_area = ui.Rectangle(name="blank")
blank_area.set_mouse_pressed_fn(self._on_blank_clicked)
ui.Spacer(height=2)
with ui.ZStack(height=0):
ui.Rectangle()
self._calendar = CalendarWidget(self._model)
self._window.position_x = self._date_field.screen_position_x
self._window.position_y = self._date_field.screen_position_y
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 self._calendar:
self._calendar.destroy()
self._calendar = None
if self._window:
self._window.destroy()
self._window = None
def _on_blank_clicked(self, x, y, b, m):
self._window.visible = False
asyncio.ensure_future(self._destroy_window_async())
| 3,441 | Python | 34.484536 | 122 | 0.596919 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/tests/test_file_ops.py | import os
import omni.kit.test
from pathlib import Path
from omni.kit import ui_test
from typing import List
from ..dialog import FilePickerDialog
from tempfile import TemporaryDirectory, NamedTemporaryFile, gettempprefix
from ..test_helper import FilePickerTestHelper
from ..file_ops import move_items, delete_items, obliterate_items, restore_items, about_connection, checkpoint_items
from omni.kit.widget.filebrowser import TREEVIEW_PANE, LISTVIEW_PANE
import omni.ui as ui
import time
from unittest.mock import patch, Mock
import random
import omni.client
from..versioning_helper import VersioningHelper
class TestFileOps(omni.kit.test.AsyncTestCase):
"""Testing omni.kit.window.filepicker.file_ops"""
async def setUp(self):
# Because tests are run in async, queries could have access the wrong window
# using the same name
self._dialog = FilePickerDialog(
f"test_file_ops_{time.time()}",
treeview_identifier="FilePicker"
)
self._tmpdir_fd = TemporaryDirectory()
self._tmpdir = Path(self._tmpdir_fd.name).resolve()
self._temp_fd = NamedTemporaryFile(dir=self._tmpdir, suffix=".mdl", delete=False)
self._temp_fd.close()
_, self._filename = os.path.split(self._temp_fd.name)
self._filepicker_helper = FilePickerTestHelper(self._dialog._widget)
async def tearDown(self):
self._dialog.destroy()
self._tmpdir_fd.cleanup()
async def _select_item_and_menu(self, item_filename, menu_name):
await self._filepicker_helper.select_items_async(str(self._tmpdir), [item_filename])
await ui_test.human_delay(10)
item = await self._filepicker_helper.get_item_async("FilePicker", item_filename, pane=LISTVIEW_PANE)
await item.right_click(human_delay_speed=10)
menu = ui_test.WidgetRef(ui.Menu.get_current(), "")
# file picker menu still uses icons as glyphs embedded inside text, so we can't match the whole string
menu_item = menu.find(f"MenuItem[*].text.endswith('{menu_name}')")
await ui_test.emulate_mouse_move_and_click(menu_item.center)
async def _wait_for_window(self, title, updates=10):
window = None
for _ in range(updates):
window = ui_test.find(title)
if window is not None:
break
await omni.kit.app.get_app().next_update_async()
self.assertIsNotNone(window)
return window
async def test_rename(self):
# rename
await self._select_item_and_menu(self._filename, "Rename")
rename_dialog = await self._wait_for_window(f"Rename {self._filename}")
field = rename_dialog.find("**/StringField[*]")
self.assertEqual(field.widget.model.get_value_as_string(), self._filename)
new_filename = gettempprefix() + ".mdl"
field.widget.model.set_value(new_filename)
ok_button = rename_dialog.find("**/Button[*].text=='Confirm'")
await ok_button.click()
self._filename = os.path.join(self._tmpdir, new_filename)
self.assertTrue(os.path.exists(self._filename))
async def test_delete(self):
# delete
await self._select_item_and_menu(self._filename, "Delete")
delete_dialog = None
for _ in range(10):
for window in ui.Workspace.get_windows():
if window.title == "Confirm File Deletion" and\
ui_test.WindowRef(window, "").find("**/Label[*].text.find('delete') >= 0"):
delete_dialog = ui_test.WindowRef(window, "")
break
if delete_dialog is not None:
break
await omni.kit.app.get_app().next_update_async()
self.assertIsNotNone(delete_dialog)
yes_button = delete_dialog.find("**/Button[*].text=='Yes'")
await yes_button.click()
self.assertFalse(os.path.exists(self._filename))
async def test_new_folder(self):
with TemporaryDirectory(dir=self._tmpdir) as tmpdir_fd:
tmpdir = Path(tmpdir_fd).resolve()
await self._select_item_and_menu(os.path.basename(tmpdir), "New Folder")
new_dialog = await self._wait_for_window("Create folder")
self.assertIsNotNone(new_dialog)
field = new_dialog.find("**/StringField[*]")
new_folder_name = gettempprefix()
field.widget.model.set_value(new_folder_name)
ok_button = new_dialog.find("**/Button[*].text=='Ok'")
await ok_button.click()
self.assertTrue(os.path.exists(os.path.join(tmpdir, new_folder_name)))
async def test_move_items(self):
with TemporaryDirectory(dir=self._tmpdir) as tmpdir_fd:
tmpdir = Path(tmpdir_fd).resolve()
item = Mock()
item.path = tmpdir
item.parent = None
item.is_folder = True
move_items(item, [self._temp_fd.name])
await ui_test.human_delay(10)
self.assertTrue(os.path.exists(os.path.join(tmpdir, self._filename)))
async def test_obliterate(self):
with patch("omni.client.get_server_info_async") as mock_get_server_info_async,\
patch(f"omni.client.obliterate_async") as mock_obliterate_async:
mock_server_info = Mock()
mock_server_info.checkpoints_enabled = True
mock_get_server_info_async.return_value = (True, mock_server_info)
item = Mock()
item.path = self._temp_fd.name
item.parent = None
item.is_folder = False
obliterate_items([item], self._dialog._widget._view)
await ui_test.human_delay(10)
delete_dialog = None
for _ in range(10):
for window in ui.Workspace.get_windows():
if window.title == "Confirm File Deletion" and\
ui_test.WindowRef(window, "").find("**/Label[*].text.find('obliterate') >= 0"):
delete_dialog = ui_test.WindowRef(window, "")
break
if delete_dialog is not None:
break
await omni.kit.app.get_app().next_update_async()
self.assertIsNotNone(delete_dialog)
yes_button = delete_dialog.find("**/Button[*].text=='Yes'")
await yes_button.click()
await ui_test.human_delay(10)
mock_obliterate_async.assert_awaited_once_with(item.path.replace("\\", "/"), True)
async def test_restore(self):
with patch("omni.client.undelete_async") as mock_undelete_async:
item = Mock()
item.path = self._temp_fd.name
item.parent = None
item.is_folder = False
item.is_deleted = True
restore_items([item], self._dialog._widget._view)
await ui_test.human_delay(10)
mock_undelete_async.assert_awaited_once_with(item.path.replace("\\", "/"))
async def test_checkpoint(self):
with patch.object(VersioningHelper, "check_server_checkpoint_support_async") as mock_check_server,\
patch(f"omni.client.create_checkpoint_async") as mock_create_checkpoint:
item = Mock()
item.path = self._temp_fd.name
item.parent = None
item.is_folder = False
mock_check_server.return_value = True
mock_create_checkpoint.return_value = (omni.client.Result.OK, None)
checkpoint_items([item], self._dialog._widget._checkpoint_widget)
checkpoint_dialog = await self._wait_for_window("Checkpoint Name")
field = checkpoint_dialog.find("**/StringField[*].multiline==True")
field.widget.model.set_value("new_checkpoint")
ok_button = checkpoint_dialog.find("**/Button[*].text=='Ok'")
await ok_button.click()
await ui_test.human_delay(10)
mock_check_server.assert_awaited_once()
mock_create_checkpoint.assert_awaited_once_with(item.path, "new_checkpoint", True)
async def test_new_usd_file(self):
with TemporaryDirectory(dir=self._tmpdir) as tmpdir_fd:
tmpdir = Path(tmpdir_fd).resolve()
await self._select_item_and_menu(os.path.basename(tmpdir), "New USD File")
new_dialog = await self._wait_for_window("New USD")
field = new_dialog.find("**/StringField[*]")
new_filename = gettempprefix()
field.widget.model.set_value(new_filename)
create_button = new_dialog.find("**/Button[*].text=='Create'")
await create_button.click()
self.assertTrue(os.path.exists(os.path.join(tmpdir, new_filename + '.usd')))
async def test_about_connection(self):
with patch("omni.client.get_server_info_async") as mock_get_server_info_async:
mock_server_info = Mock()
mock_server_info.version = "1.0"
mock_server_info.auth_token = "xxxxxxxx"
mock_server_info.checkpoints_enabled =True
mock_server_info.omniojects_enabled = True
mock_get_server_info_async.return_value = (True, mock_server_info)
item = Mock()
item.path = self._temp_fd.name
item.parent = None
item.is_folder = False
about_connection(item)
await ui_test.human_delay(10)
about_dialog = await self._wait_for_window("About")
close_button = about_dialog.find("**/Button[*].text=='Close'")
await close_button.click()
await ui_test.human_delay(10)
self.assertFalse(about_dialog._window.visible) | 9,725 | Python | 44.448598 | 116 | 0.605656 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/tests/test_dialog.py | ## Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from unittest.mock import Mock, patch
import asyncio
from typing import Callable
import carb.input
import omni.kit.test
from omni.kit import ui_test
from omni.kit.widget.filebrowser import TREEVIEW_PANE, FileBrowserItem, FileBrowserItemFactory
from ..dialog import FilePickerDialog
from ..api import FilePickerAPI
from ..test_helper import FilePickerTestHelper
import omni.client
from tempfile import TemporaryDirectory, NamedTemporaryFile
from pathlib import Path
import os
import random
class TestDialog(omni.kit.test.AsyncTestCase):
"""Testing the Filepicker Dialog."""
async def setUp(self):
self.previous_retry_values = omni.client.set_retries(0, 0, 0)
self.test_listings = {
"omniverse://": ["omniverse://ov-sandbox", "omniverse://ov-test"],
"omniverse://ov-test": ["Lib", "NVIDIA", "Projects", "Users"],
"omniverse://ov-test/NVIDIA": ["Assets", "Materials", "Samples"],
"omniverse://ov-test/NVIDIA/Samples": ["Astronaut", "Flight", "Marbles", "Attic"],
"omniverse://ov-test/NVIDIA/Samples/Astronaut": ["Astronaut.usd", "Materials", "Props"],
"my-computer://": ["/", "Desktop", "Documents", "Downloads"],
"/": ["bin", "etc", "home", "lib", "tmp"],
"/home": ["jack", "jill"],
"/home/jack": ["Desktop", "Documents", "Downloads"],
"/home/jack/Documents": ["test.usd"],
}
async def tearDown(self):
omni.client.set_retries(*self.previous_retry_values)
@staticmethod
async def _mock_stat_async_succeeds(url: str):
return omni.client.Result.OK, None
async def _mock_populate_async_impl(self, item: FileBrowserItem, callback_async: Callable, timeout: float = 10.0):
if not item.populated:
if item.path in self.test_listings:
subdirs = self.test_listings[item.path]
else:
subdirs = []
for subdir in subdirs:
if item.path.endswith("://"):
path = subdir
elif item.path == "/":
path = f"/{subdir}"
else:
path = f"{item.path}/{subdir}"
item.add_child(FileBrowserItemFactory.create_group_item(subdir, path))
item.populated = True
return None
async def test_key_funcs(self):
"""Testing key functions"""
mock_apply = Mock()
mock_cancel = Mock()
dialog = FilePickerDialog("test_apply", click_cancel_handler=mock_cancel, click_apply_handler=mock_apply,
treeview_identifier="FilePicker")
await ui_test.human_delay(10)
dialog.show()
await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.ENTER)
await ui_test.human_delay()
mock_apply.assert_called_once()
await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.ESCAPE)
await ui_test.human_delay()
mock_cancel.assert_called_once()
# test update apply handler updates key press func
mock_apply.reset_mock()
another_mock_apply = Mock()
dialog.set_click_apply_handler(another_mock_apply)
await ui_test.emulate_keyboard_press(carb.input.KeyboardInput.ENTER)
await ui_test.human_delay()
another_mock_apply.assert_called_once()
mock_apply.assert_not_called()
async def test_initial_navigation(self):
"""Testing that the initial navigation executed."""
self.initial_navigation_finished = False
async def _mock_navigation(*args, **kwargs):
self.initial_navigation_finished = True
with patch.object(FilePickerAPI, "navigate_to_async", side_effect=_mock_navigation), \
patch("omni.client.stat_async", side_effect=self._mock_stat_async_succeeds):
# make sure that when no interaction happens, initial navigation happens correctly
dialog = FilePickerDialog(
"test_cancel_initial_navigation", current_directory="omniverse://foo", current_filename="bar.usd",
treeview_identifier="FilePicker")
await ui_test.human_delay(10)
dialog.show()
await ui_test.human_delay(10)
self.assertTrue(self.initial_navigation_finished)
self.assertEqual(dialog.get_current_directory(), "omniverse://foo/")
self.assertEqual(dialog.get_filename(), "bar.usd")
dialog.hide()
dialog.destroy()
async def test_selection_cancels_initial_navigation(self):
"""Testing that the initial navigation is cancelled by user selection."""
self.initial_navigation_finished = False
async def _mock_navigation(*args, **kwargs):
await asyncio.sleep(2)
self.initial_navigation_finished = True
with patch.object(FilePickerAPI, "navigate_to_async", side_effect=_mock_navigation), \
patch("omni.client.stat_async", side_effect=self._mock_stat_async_succeeds), \
patch.object(FileBrowserItem, "populate_async", side_effect=self._mock_populate_async_impl, autospec=True):
# check that user selection of an item cancels initial navigation
dialog = FilePickerDialog(
"test_cancel_by_selection", current_directory="omniverse://foo", current_filename="bar.usd",
treeview_identifier="FilePicker")
await ui_test.human_delay(10)
dialog.add_connections({"ov-test": "omniverse://ov-test"})
await ui_test.human_delay(10)
dialog.show()
await ui_test.human_delay()
async with FilePickerTestHelper(dialog._widget) as filepicker_helper:
item = await filepicker_helper.get_item_async("FilePicker", "ov-test", pane=TREEVIEW_PANE)
self.assertTrue(bool(item))
await item.click()
# this should have cancelled the initial navigation
await asyncio.sleep(2)
self.assertFalse(self.initial_navigation_finished)
dialog.hide()
async def test_typing_in_pathfield_cancels_initial_navigation(self):
"""Testing that the initial navigation is cancelled by typing in pathfield."""
self.initial_navigation_finished = False
async def _mock_navigation(*args, **kwargs):
await asyncio.sleep(2)
self.initial_navigation_finished = True
with patch.object(FilePickerAPI, "navigate_to_async", side_effect=_mock_navigation), \
patch("omni.client.stat_async", side_effect=self._mock_stat_async_succeeds):
# check that user typing in path field cancels initial navigation
dialog = FilePickerDialog(
"test_cancel_by_typing", current_directory="omniverse://foo", current_filename="bar.usd",
treeview_identifier="FilePicker")
await ui_test.human_delay(10)
dialog.show()
await ui_test.human_delay()
# clicking in will trigger begin edit for path field, thus cancel the initial navigation
path_field = ui_test.find_all("test_cancel_by_typing//Frame/**/ComboBox[*]")[0]
await path_field.click()
await asyncio.sleep(2)
self.assertFalse(self.initial_navigation_finished)
dialog.hide()
async def test_file_bar(self):
extension_options = [
('*.usd', 'Can be Binary or Ascii'),
('*.usda', 'Human-readable text format'),
('*.usdc', 'Binary format'),
('*.png', 'test'),
('*.jpg', 'another test')
]
postfix_options = [
"anim",
"cache",
"curveanim",
"geo",
"material",
"project",
"seq",
"skel",
"skelanim"
]
mock_handler = Mock()
dialog = FilePickerDialog("test_file_bar",
treeview_identifier="FilePicker",
file_extension_options=extension_options,
file_postfix_options=postfix_options,
click_apply_handler=mock_handler,
click_cancel_handler=mock_handler
)
# basic checks, for an actual use case check file picker use cases such as importer and exporter
dialog.set_filebar_label_name('Temp file name')
self.assertEqual('Temp file name:', dialog.get_filebar_label_name())
(choice, _) = random.choice(extension_options)
dialog.set_file_extension(choice)
self.assertEqual(choice, dialog.get_file_extension())
choice_index = random.randint(0, len(extension_options))
combo_box_button = ui_test.WidgetRef(dialog._widget._file_bar._file_extension_menu._button, "", dialog._window)
await combo_box_button.click()
combo_box_menu = None
for _ in range(10):
combo_box_menu = ui_test.find("ComboBoxMenu")
if combo_box_menu is not None:
break
await omni.kit.app.get_app().next_update_async()
self.assertIsNotNone(combo_box_menu)
extension_button = combo_box_menu.find(f"**/ZStack[{choice_index}]/Button[0]")
await extension_button.click()
self.assertEqual(extension_options[choice_index][0], dialog.get_file_extension())
choice = random.choice(postfix_options)
dialog.set_file_postfix(choice)
self.assertEqual(choice, dialog.get_file_postfix())
with TemporaryDirectory() as tmpdir_fd:
tmpdir = Path(tmpdir_fd).resolve()
temp_fd = NamedTemporaryFile(dir=tmpdir, suffix=".mdl", delete=False)
temp_fd.close()
_, filename = os.path.split(temp_fd.name)
async with FilePickerTestHelper(dialog._widget) as filepicker_helper:
await filepicker_helper.toggle_grid_view_async(True)
await filepicker_helper.select_items_async(str(tmpdir), [filename])
await ui_test.human_delay()
apply_button = ui_test.WidgetRef(dialog._widget._file_bar._apply_button, "", dialog._window)
await apply_button.click()
mock_handler.assert_called_with(filename, os.path.dirname(temp_fd.name).replace("\\", "/") + "/")
cancel_button = ui_test.WidgetRef(dialog._widget._file_bar._cancel_button, "", dialog._window)
await cancel_button.click()
mock_handler.assert_called_with(filename, os.path.dirname(temp_fd.name).replace("\\", "/") + "/") | 11,157 | Python | 44.729508 | 123 | 0.61029 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/tests/test_api.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import omni.kit.app
import omni.client
import tempfile
from unittest.mock import Mock, patch, ANY
from ..dialog import FilePickerDialog
from ..view import FilePickerView
from ..model import FilePickerModel
class TestFilePickerDialog(omni.kit.test.AsyncTestCase):
"""Testing FilePickerDialog properly executes API endpoints."""
async def setUp(self):
pass
async def wait_for_update(self, wait_frames=20):
for _ in range(wait_frames):
await omni.kit.app.get_app().next_update_async()
async def tearDown(self):
pass
async def test_add_connections_succeeds(self):
"""Testing happy path for adding connections"""
with patch.object(FilePickerView, "add_server") as mock_add_server:
# Create the widget and add multiple connections
under_test = FilePickerDialog("test")
connections = {"C:": "C:"}
mock_add_server.reset_mock()
under_test.add_connections(connections)
# Check that all specified connections were attempted
assert mock_add_server.call_count == len(connections.items())
for name, path in connections.items():
mock_add_server.assert_any_call(name, path)
async def test_set_search_delegate(self):
"""Testing that hiding the window destroys it"""
mock_search_delegate = Mock()
under_test = FilePickerDialog("test")
await self.wait_for_update()
under_test.set_search_delegate(mock_search_delegate)
mock_search_delegate.build_ui.assert_called_once()
async def test_set_filename(self):
with tempfile.TemporaryDirectory() as tmp_dirname:
under_test = FilePickerDialog("test", current_directory=tmp_dirname)
for _ in range(6):
await omni.kit.app.get_app().next_update_async()
# Confirm current directory
self.assertEqual(under_test.get_current_directory().rstrip('/'), tmp_dirname.replace('\\', '/'))
# Set simple filename
test_filename = "file.usd"
under_test.set_filename(f"{tmp_dirname}/{test_filename}")
self.assertEqual(under_test.get_filename(), test_filename)
# Set filename to full path that descends from current directory
test_filename = "path/to/test/file.usd"
under_test.set_filename(f"{tmp_dirname}/{test_filename}")
self.assertEqual(under_test.get_filename(), test_filename)
# Set filename to full path that doesn't relate to current directory
test_filename = "C:/unrelated/path/to/test/file.usd"
under_test.set_filename(test_filename)
self.assertEqual(under_test.get_filename(), test_filename)
async def test_resilience_to_fast_destruction(self):
"""Testing that the extension is resilient to fast destruction."""
async def side_effect(*args, **kwargs):
# fake a long find item period to have the loading pane present on destruction
import asyncio
await asyncio.sleep(1)
async def mock_stat(*args, **kwargs):
return omni.client.Result.OK, None
with patch.object(FilePickerModel, "find_item_async", side_effect=side_effect), patch("omni.client.stat_async", side_effect=mock_stat):
for i in range(5):
under_test = FilePickerDialog("test")
under_test.show()
under_test.navigate_to("dummy/file/path.usd")
await self.wait_for_update(wait_frames=i)
under_test.hide()
await self.wait_for_update(wait_frames=i)
under_test.destroy()
| 4,179 | Python | 41.653061 | 143 | 0.648959 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/tests/test_search_delegate.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import asyncio
import omni.kit.test
import omni.client
from unittest.mock import patch, Mock
from ..search_delegate import SearchResultsModel
class TestSearchResultsModel(omni.kit.test.AsyncTestCase):
async def setUp(self):
pass
async def tearDown(self):
pass
| 739 | Python | 29.833332 | 77 | 0.775372 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/tests/__init__.py | ## Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from .test_test_helper import *
from .test_api import *
from .test_navigate import *
from .test_connections import *
from .test_bookmarks import *
from .test_asset_types import *
from .test_auto_refresh import *
from .test_search_field import *
from .test_context_menu import *
from .test_timestamp import *
from .test_dialog import *
from .test_datetime import *
from .test_file_ops import *
from .test_file_info import *
| 865 | Python | 35.083332 | 77 | 0.772254 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/tests/test_search_field.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, shutil
import random
import omni.kit.test
import omni.appwindow
import omni.kit.app
from typing import List
from omni.kit import ui_test
from omni.ui.tests.test_base import OmniUiTest
from omni.kit.search_core import SearchEngineRegistry, AbstractSearchModel, AbstractSearchItem
from ..dialog import FilePickerDialog
class MockSearchItem(AbstractSearchItem):
def __init__(self, name: str, path: str):
self._name = name
self._path = path
@property
def name(self):
return self._name
@property
def path(self):
return self._path
class MockSearchModel(AbstractSearchModel):
"""SearchModel class for the mock search engine."""
def __init__(self, **kwargs):
super().__init__()
self._items = []
search_text = kwargs['search_text']
current_dir = kwargs['current_dir']
with os.scandir(current_dir) as it:
for entry in it:
if search_text in entry.name:
self._items.append(MockSearchItem(entry.name, entry.path))
def destroy(self):
self._items = []
@property
def items(self):
return self._items
class TestSearchField(omni.kit.test.AsyncTestCase):
"""Testing omni.kit.window.filepicker.SearchField"""
async def setUp(self):
self._search_engine = "mock_search_model"
self._search_sub = SearchEngineRegistry().register_search_model(self._search_engine, MockSearchModel)
async def tearDown(self):
self._search_sub = None
def _create_test_dir(self, temp_files: List[str] = []):
# Create test dir in temp area
temp_path = os.path.join(omni.kit.test.get_test_output_path(), f"tmp{random.randint(0, int('0xffff', 16))}")
temp_path = temp_path.replace("\\", "/")
if os.path.exists(temp_path):
os.rmdir(temp_path)
os.mkdir(temp_path)
for temp_file in temp_files:
with open(f'{temp_path}/{temp_file}', 'w') as fp:
pass
return temp_path
async def test_search_returns_expected(self):
"""Testing SearchField returns expected results"""
# Create test dir and populate with test files
temp_files = ["foo.usd", "foo.mdl", "foo_2.usd", "bar.usd", "bar.png", "foo_3.usd", "baz.png"]
temp_path = self._create_test_dir(temp_files=temp_files)
await ui_test.human_delay(2)
# Create dialog and navigate to to test dir
under_test = FilePickerDialog(
"test_search_returns_expected",
current_directory=temp_path,
show_grid_view=True,
show_only_collections=["my-computer"])
await ui_test.human_delay(10)
# Search for files using the search text, update the grid view.
search_delegate = under_test._widget._default_search_delegate
search_delegate._search_engine = self._search_engine
search_text = "foo"
search_delegate._search_field.model.set_value(search_text)
search_delegate._on_end_edit(search_delegate._search_field.model)
await ui_test.human_delay(20)
# Confirm number of found files (should == 4)
expected_result = [f for f in temp_files if search_text in f]
search_model = under_test._widget._view._filebrowser._currently_visible_model
self.assertEqual(len(expected_result), len(search_model.get_item_children(None)))
# Cleanup
shutil.rmtree(temp_path)
async def test_changing_directory_while_searching(self):
"""Testing SearchField updates results when changing directory"""
# Create test dirs
temp_files = ["foo.usd", "foo.mdl", "foo_2.usd", "bar.usd", "bar.png", "foo_3.usd", "baz.png"]
temp_path = self._create_test_dir(temp_files=temp_files)
temp_path2 = self._create_test_dir(temp_files=[])
await ui_test.human_delay(2)
# Create dialog and navigate to to test dir
under_test = FilePickerDialog(
"test_changing_directory_while_searching",
current_directory=temp_path,
show_grid_view=True,
show_only_collections=["my-computer"])
await ui_test.human_delay(10)
# Search for files using the search text, update the view.
search_delegate = under_test._widget._default_search_delegate
search_delegate._search_engine = self._search_engine
search_text = "foo"
search_delegate._on_begin_edit(search_delegate._search_field.model)
search_delegate._search_field.model.set_value(search_text)
search_delegate._on_text_edit(search_delegate._search_field.model)
await ui_test.human_delay(20)
# Confirm number of found files (should == 4).
expected_result = [f for f in temp_files if search_text in f]
search_model = under_test._widget._view._filebrowser._currently_visible_model
self.assertEqual(len(expected_result), len(search_model.get_item_children(None)))
# Change to second directory. Wait a few frames, then confirm that search results have changed (0)
under_test.set_current_directory(temp_path2)
await ui_test.human_delay(20)
search_model = under_test._widget._view._filebrowser._currently_visible_model
self.assertEqual(0, len(search_model.get_item_children(None)))
# Change back to first directory. Wait a few frames, then confirm search results again.
under_test.set_current_directory(temp_path)
await ui_test.human_delay(20)
search_model = under_test._widget._view._filebrowser._currently_visible_model
self.assertEqual(len(expected_result), len(search_model.get_item_children(None)))
# Cleanup
shutil.rmtree(temp_path)
shutil.rmtree(temp_path2)
| 6,255 | Python | 38.847134 | 116 | 0.654836 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/tests/test_connections.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import omni.kit.app
import carb.settings
from unittest.mock import patch, Mock
from omni.kit import ui_test
from omni.kit.widget.filebrowser import TREEVIEW_PANE, LISTVIEW_PANE
from omni.kit.widget.nucleus_connector import NucleusConnectorExtension
from ..dialog import FilePickerDialog
from ..widget import FilePickerWidget
from ..api import FilePickerAPI
from ..view import FilePickerView
from ..model import FilePickerModel
from ..test_helper import FilePickerTestHelper
import omni.client
class TestAddDeleteRenameServer(omni.kit.test.AsyncTestCase):
"""Testing FilePickerView.*server* methods"""
async def setUp(self):
self.previous_retry_values = omni.client.set_retries(0, 0, 0)
# OM-78933: Init_view mounts localhost, which emits a BOOKMARK_ADDED_EVENT. This corrupts the event stream
# and subsequently adds unaccounted calls to mock_add_bookmark below. The simple fix is to add a few frames
# here in order to steer clear of the initialization step.
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
async def tearDown(self):
omni.client.set_retries(*self.previous_retry_values)
async def test_add_server(self):
"""Testing FilePickerView.add_server adds the server"""
with patch("omni.client.add_bookmark") as mock_add_bookmark:
test_name, test_path = "ov-added", "omniverse://ov-added"
under_test = FilePickerView("test-view")
self.assertFalse(under_test.has_connection_with_name(test_name, collection="omniverse"))
under_test.add_server(test_name, test_path)
self.assertTrue(under_test.has_connection_with_name(test_name, collection="omniverse"))
await omni.kit.app.get_app().next_update_async()
mock_add_bookmark.assert_called_with(test_name, test_path)
async def test_delete_server(self):
"""Testing FilePickerView.delete_server deletes the server"""
with patch("omni.client.remove_bookmark") as mock_remove_bookmark:
test_name, test_path = "ov-test", "omniverse://ov-test"
under_test = FilePickerView("test-view")
self.assertFalse(under_test.has_connection_with_name(test_name, collection="omniverse"))
model = under_test.add_server(test_name, test_path)
self.assertTrue(under_test.has_connection_with_name(test_name, collection="omniverse"))
# Confirm that after being deleted, test_path is no longer in the connections liset
under_test.delete_server(model.root)
self.assertFalse(under_test.has_connection_with_name(test_name, collection="omniverse"))
await omni.kit.app.get_app().next_update_async()
mock_remove_bookmark.assert_called_with(test_name)
async def test_rename_server(self):
"""Testing FilePickerView.rename_server renames the server"""
with patch("omni.client.add_bookmark") as mock_add_bookmark,\
patch("omni.client.remove_bookmark") as mock_remove_bookmark:
test_name, test_path, test_rename = "ov-test", "omniverse://ov-test", "ov-renamed"
under_test = FilePickerView("test-view")
model = under_test.add_server(test_name, test_path)
self.assertTrue(under_test.has_connection_with_name(test_name, collection="omniverse"))
await omni.kit.app.get_app().next_update_async()
under_test.rename_server(model.root, test_rename)
self.assertFalse(under_test.has_connection_with_name(test_name, collection="omniverse"))
self.assertTrue(under_test.has_connection_with_name(test_rename, collection="omniverse"))
# Confirm that previous name deleted, then new name added
for _ in range(8):
await omni.kit.app.get_app().next_update_async()
mock_remove_bookmark.assert_called_with(test_name)
mock_add_bookmark.assert_called_with(test_rename, test_path)
async def test_log_out_server(self):
"""Testing FilePickerView.log_out_server logs out the server"""
with patch("omni.client.sign_out") as mock_sign_out:
test_name, test_path = "ov-test", "omniverse://ov-test"
under_test = FilePickerView("test-view")
self.assertFalse(under_test.has_connection_with_name(test_name, collection="omniverse"))
under_test.add_server(test_name, test_path)
self.assertTrue(under_test.has_connection_with_name(test_name, collection="omniverse"))
# Confirm that sign out is correctly called
model = under_test.get_connection_with_url(test_path)
under_test.log_out_server(model)
await omni.kit.app.get_app().next_update_async()
mock_sign_out.assert_called_with(test_path)
class TestUpdateConnectionsFromApi(omni.kit.test.AsyncTestCase):
"""Testing FilePickerAPI.*connections* methods"""
async def setUp(self):
self.previous_retry_values = omni.client.set_retries(0, 0, 0)
# OM-78933: Init_view mounts localhost, which emits a BOOKMARK_ADDED_EVENT. This corrupts the event stream
# and subsequently adds unaccounted calls to mock_add_bookmark below. The simple fix is to add a few frames
# here in order to steer clear of the initialization step.
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
async def tearDown(self):
omni.client.set_retries(*self.previous_retry_values)
async def test_add_connections(self):
"""Testing FilePickerAPI.add_connections writes new connection to persistent settings"""
with patch("omni.client.add_bookmark") as mock_add_bookmark:
test_name, test_path = "ov-test", "omniverse://ov-test"
test_view = FilePickerView("test-view")
under_test = FilePickerAPI(FilePickerModel(), test_view)
self.assertFalse(test_view.has_connection_with_name(test_name, collection="omniverse"))
under_test.add_connections({test_name: test_path})
self.assertTrue(test_view.has_connection_with_name(test_name, collection="omniverse"))
await omni.kit.app.get_app().next_update_async()
mock_add_bookmark.assert_called_with(test_name, test_path)
async def test_update_connections_when_settings_changed(self):
"""Testing FilePickerAPI.subscribe_client_bookmarks_changed updates connections in view when bookmarks changed"""
test_view = FilePickerView("test-view")
under_test = FilePickerAPI(FilePickerModel(), test_view)
under_test.subscribe_client_bookmarks_changed()
# Assert connection not initially in the view
test_name, test_path = "ov-ax98zjbm", "omniverse://ov-ax98zjbm"
self.assertFalse(test_view.has_connection_with_name(test_name, collection="omniverse"))
# Confirm that when an external source adds a bookmark, the view updates appropriately
omni.client.add_bookmark(test_name, test_path)
await ui_test.human_delay(10)
self.assertTrue(test_view.has_connection_with_name(test_name, collection="omniverse"))
# Confirm that after deleting connection from settings, the view updates appropriately
success = False
for attempt in range(200):
omni.client.remove_bookmark(test_name)
await ui_test.human_delay(10)
if not test_view.has_connection_with_name(test_name, collection="omniverse"):
success = True
break
self.assertTrue(success)
class TestAddNewConnectionUI(omni.kit.test.AsyncTestCase):
"""Testing UX fr adding new connections"""
async def setUp(self):
self.previous_retry_values = omni.client.set_retries(0, 0, 0)
async def tearDown(self):
omni.client.set_retries(*self.previous_retry_values)
async def test_treeview_add_new_connection_clicked(self):
"""Testing that when 'Add New Connection ...' item in treeview is clicked, launches connection flow"""
dialog = FilePickerDialog("test_treeview_add_new_connection_clicked", treeview_identifier="FilePicker")
await ui_test.human_delay(10)
async with FilePickerTestHelper(dialog._widget) as filepicker_helper:
with patch.object(NucleusConnectorExtension, "connect_with_dialog") as mock_connector:
item = await filepicker_helper.get_item_async("FilePicker", "Add New Connection ...", pane=TREEVIEW_PANE)
await item.click()
await ui_test.human_delay(10)
mock_connector.assert_called_once()
async def test_gridview_add_new_connection_clicked(self):
"""Testing that when 'Add New Connection ...' item in gridview is clicked, launches connection flow"""
dialog = FilePickerDialog("test_gridview_add_new_connection_clicked", treeview_identifier="FilePicker")
await ui_test.human_delay(10)
async with FilePickerTestHelper(dialog._widget) as filepicker_helper:
with patch.object(NucleusConnectorExtension, "connect_with_dialog") as mock_connector:
item = await filepicker_helper.get_item_async("FilePicker", "Omniverse", pane=TREEVIEW_PANE)
await item.click()
await ui_test.human_delay(10)
item = await filepicker_helper.get_item_async("FilePicker", "Add New Connection ...", pane=LISTVIEW_PANE)
await item.click()
await ui_test.human_delay(10)
mock_connector.assert_called_once()
async def test_not_has_default_localhost(self):
"""Testing that there is no default localhost server in filepicker dialog"""
# TODO: some test machine has the localhost bookmark stored in omniverse.toml
# and the omni client's remove_bookmark is not time stable, so it cause flaky failed
# comment his until find a better test solution
return
omni.client.remove_bookmark("localhost")
await ui_test.human_delay(100)
dialog = FilePickerDialog("test_not_has_default_localhost", treeview_identifier="FilePicker")
await ui_test.human_delay(10)
test_view = dialog._widget._view
self.assertFalse(test_view.has_connection_with_name("localhost", collection="omniverse"))
async def test_default_connection_setting(self):
"""Testing that default connection setting is working as expect"""
test_connections = {
"ov-test": "omniverse://ov-test",
"test": "omniverse://ov-test",
}
old_setting_value = carb.settings.get_settings().get("exts/omni.kit.window.filepicker/mounted_servers")
carb.settings.get_settings().set("exts/omni.kit.window.filepicker/mounted_servers", test_connections)
await ui_test.human_delay(30)
widget = FilePickerWidget("test_default_connection_setting")
await ui_test.human_delay(30)
test_view = widget._view
for test_name in test_connections.keys():
success = False
for attempt in range(100):
await ui_test.human_delay(10)
if test_view.has_connection_with_name(test_name, collection="omniverse"):
success = True
break
self.assertTrue(success)
await ui_test.human_delay(10)
carb.settings.get_settings().set("exts/omni.kit.window.filepicker/mounted_servers", old_setting_value)
for test_name in test_connections.keys():
# Confirm that after deleting connection from settings, the view updates appropriately
omni.client.remove_bookmark(test_name)
success = False
for attempt in range(100):
await ui_test.human_delay(10)
if not test_view.has_connection_with_name(test_name, collection="omniverse"):
success = True
break
self.assertTrue(success)
widget.destroy()
async def test_show_add_new_connection_setting(self):
"""Testing that show add new connection setting is working as expect"""
old_setting_value = carb.settings.get_settings().get("exts/omni.kit.window.filepicker/show_add_new_connection")
carb.settings.get_settings().set("exts/omni.kit.window.filepicker/show_add_new_connection", True)
await ui_test.human_delay(30)
widget = FilePickerWidget("test_show_add_new_connection_setting")
await ui_test.human_delay(30)
test_view = widget._view
mock_handle = Mock()
collections = test_view._collections.values()
for coll in collections:
if coll and coll.children:
for name, conn in coll.children.items():
if test_view._is_placeholder(conn):
self.assertEqual(name, "Add New Connection ...")
mock_handle()
mock_handle.assert_called_once()
widget.destroy()
mock_handle.reset_mock()
await ui_test.human_delay(10)
carb.settings.get_settings().set("exts/omni.kit.window.filepicker/show_add_new_connection", False)
widget = FilePickerWidget("test_not_show_add_new_connection_setting")
await ui_test.human_delay(30)
test_view = widget._view
mock_handle = Mock()
collections = test_view._collections.values()
for coll in collections:
if coll and coll.children:
for name, conn in coll.children.items():
if test_view._is_placeholder(conn):
mock_handle()
mock_handle.assert_not_called()
widget.destroy()
carb.settings.get_settings().set("exts/omni.kit.window.filepicker/show_add_new_connection", old_setting_value)
await ui_test.human_delay(30)
| 14,427 | Python | 50.345196 | 121 | 0.660706 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/tests/test_auto_refresh.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 threading
import asyncio
import time
import tempfile
import random
import omni.kit.app
import omni.kit.test
from omni.kit import ui_test
from ..dialog import FilePickerDialog
class CreateDummyFileThread(threading.Thread):
def __init__(self, dir: str, max_size: int = 1000, max_duration: int = 5, thread: int = 0):
super().__init__()
self._name = "Dummy"
self._dir = dir
self._max_size = max_size
self._max_duration = max_duration
self._thread = thread
@property
def name(self):
return self._name
def run(self):
time.sleep(random.randrange(self._max_duration))
with tempfile.NamedTemporaryFile(dir=self._dir, delete=False) as fp:
fp.write(os.urandom(random.randint(1, self._max_size)))
self._name = fp.name
# print(f"THREAD-{self._thread} Created: ", self._name)
class DeleteDummyFileThread(threading.Thread):
def __init__(self, name: str, max_duration: int = 5, thread: int = 0):
super().__init__()
self._name = name
self._max_duration = max_duration
self._thread = thread
def run(self):
time.sleep(random.randrange(self._max_duration))
try:
os.remove(self._name)
except FileNotFoundError as e:
pass
# print(f"THREAD-{self._thread} Deleted: ", self._name)
class TestAutoRefresh(omni.kit.test.AsyncTestCase):
"""Testing ui.TreeView"""
__async_lock = asyncio.Lock()
async def setUp(self):
self.num_files = 30
self.max_file_size = 1e2
self.max_stagger = 6
async def _test_auto_refresh_common_async(self, title: str, show_grid_view: bool = True):
"""Testing that updates to the filesystem updates the list view"""
# Create test dir in temp area
temp_path = os.path.join(omni.kit.test.get_test_output_path(), f"tmp{random.randint(0, int('0xffff', 16))}")
temp_path = temp_path.replace("\\", "/")
if os.path.exists(temp_path):
os.rmdir(temp_path)
os.mkdir(temp_path)
# Navigate to test dir, need to wait a few frames before and after for proper redraw
under_test = FilePickerDialog(
title,
current_directory=temp_path,
show_grid_view=show_grid_view,
show_only_collections=["my-computer"])
await ui_test.human_delay(10)
# Create files in concurrent threads to check that the UI keeps up with the updates
threads = []
for i in range(self.num_files):
thread = CreateDummyFileThread(temp_path, self.max_file_size, max_duration=self.max_stagger, thread=i)
thread.start()
threads.append(thread)
done = False
while not done:
# Loop until all threads are done
await ui_test.human_delay(1)
done = not any([thread.is_alive() for thread in threads])
# Confirm the temp folder in the filesystem model has been populated
await ui_test.human_delay(10)
temp_dir = await under_test._widget._model.find_item_async(temp_path)
self.assertTrue(bool(temp_dir))
self.assertEqual(len(temp_dir.children), self.num_files)
# Delete files in concurrent threads to check that the UI keeps up with the updates
filenames = [thread.name for thread in threads]
for i, filename in enumerate(filenames):
thread = DeleteDummyFileThread(filename, max_duration=self.max_stagger, thread=i)
thread.start()
threads.append(thread)
done = False
while not done:
# Loop until all threads are done
await ui_test.human_delay(1)
done = not any([thread.is_alive() for thread in threads])
# Confirm the temp folder in the filesystem model has been emptied
await ui_test.human_delay(10)
self.assertEqual(len(temp_dir.children), 0)
# Cleanup
os.rmdir(temp_path)
async def test_auto_refresh_grid_view(self):
"""Testing that updates to the filesystem updates the grid view"""
async with self.__async_lock:
await self._test_auto_refresh_common_async("test_auto_refresh_grid_view", show_grid_view=True)
async def test_auto_refresh_list_view(self):
"""Testing that updates to the filesystem updates the tree view"""
async with self.__async_lock:
await self._test_auto_refresh_common_async("test_auto_refresh_list_view", show_grid_view=False)
| 5,017 | Python | 36.729323 | 116 | 0.638429 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/tests/test_context_menu.py | import os
from pathlib import Path
from tempfile import TemporaryDirectory, NamedTemporaryFile
import omni.kit.test
from omni.kit import ui_test
from omni.kit.widget.filebrowser import TREEVIEW_PANE, LISTVIEW_PANE
from omni import ui
from ..test_helper import FilePickerTestHelper
from ..dialog import FilePickerDialog
from ..context_menu import BaseContextMenu
import omni.client
class TestContexMenu(omni.kit.test.AsyncTestCase):
"""Testing that the context menu system works as expected."""
async def setUp(self):
self.previous_retry_values = omni.client.set_retries(0, 0, 0)
self._window = ui.Window("test_context_menu")
async def tearDown(self):
omni.client.set_retries(*self.previous_retry_values)
ui.Workspace.show_window(self._window.title)
self._window = None
async def test_context_menu_built_correctly(self):
"""Testing that menu items built from menu dict are correct."""
class _MockContextMenu(BaseContextMenu):
def __init__(self, **kwargs):
super().__init__(title="Mock Context menu", **kwargs)
self._menu_dict = [
{
"name": "",
},
{
"name": "Item01_disabled",
"show_fn": [lambda context: True,]
},
{
"name": "",
},
{
"name": "Item02_invisible",
"show_fn": [lambda context: False,]
},
{
"name": "",
},
{
"name": "Item03_show",
"onclick_fn": lambda context: print(context),
"show_fn": [lambda context: True,]
},
{
"name": "",
},
]
with self._window.frame:
context_menu = _MockContextMenu()
await ui_test.human_delay()
context_menu.show(None, [])
await ui_test.human_delay()
menu_root = ui.Menu.get_current()
menu_items = ui.Inspector.get_children(menu_root)
# separator should not be built if it is the first/last element
self.assertNotIsInstance(menu_items[0], ui.Separator)
self.assertNotIsInstance(menu_items[-1], ui.Separator)
# 2 separators should not be built next to each other
# because the second item is invisbile, separator 0 and 1 are now next to each other, but we shoud only have
# one separator built after item 01
# the result of the built items are: [item 01(disabled), separator, item03]
self.assertEqual(len(menu_items), 3)
self.assertEqual(menu_items[0].text, "Item01_disabled")
self.assertFalse(menu_items[0].enabled)
self.assertIsInstance(menu_items[1], ui.Separator)
self.assertEqual(menu_items[2].text, "Item03_show")
self.assertTrue(menu_items[2].enabled)
async def test_add_context_menu(self):
"""Testing the add_context_menu API."""
class _MockContextMenu(BaseContextMenu):
def __init__(self, **kwargs):
super().__init__(title="Mock Context menu", **kwargs)
self._menu_dict = [
{
"name": "Item01",
"onclick_fn": lambda context: print(context),
"show_fn": [lambda context: True,]
},
{
"name": "",
"_separator_test_add_": ""
},
{
"name": "Item02",
"onclick_fn": lambda context: print(context),
"show_fn": [lambda context: True,]
},
{
"name": "Item03",
"onclick_fn": lambda context: print(context),
"show_fn": [lambda context: True,]
},
]
def _get_menu_names(menu_dict):
names = []
for item in menu_dict:
names.append(item.get("name"))
return names
# test adding by explicit index (regardless of separator anchor position)
context_menu = _MockContextMenu()
original_names = _get_menu_names(context_menu._menu_dict)
context_menu.add_menu_item("Item00", "", None, None, index=0)
context_menu.add_menu_item("Item2.5", "", None, None, index=4)
self.assertEqual(_get_menu_names(context_menu._menu_dict),
['Item00', 'Item01', '', 'Item02', 'Item2.5', 'Item03'])
# test adding by explicit index out of range
context_menu.add_menu_item("Item-100", "", None, None, index=-100)
context_menu.add_menu_item("Item999", "", None, None, index=999)
self.assertEqual(_get_menu_names(context_menu._menu_dict),
['Item-100', 'Item00', 'Item01', '', 'Item02', 'Item2.5', 'Item03', 'Item999'])
# test add by separator name anchor
context_menu.add_menu_item("before separator", "", None, None, index=0, separator_name="_separator_test_add_")
context_menu.add_menu_item("first", "", None, None, index=-10, separator_name="_separator_test_add_")
context_menu.add_menu_item("after separator", "", None, None, index=3, separator_name="_separator_test_add_")
context_menu.add_menu_item("last", "", None, None, index=100, separator_name="_separator_test_add_")
print(_get_menu_names(context_menu._menu_dict))
self.assertEqual(_get_menu_names(context_menu._menu_dict),
['first', 'Item-100', 'Item00', 'Item01', 'before separator', '', 'Item02', 'Item2.5',
'after separator', 'Item03', 'Item999', 'last'])
# test add by non-existent separator name default to add to last
context_menu.add_menu_item("non existent", "", None, None, index=1, separator_name="_dummy_")
self.assertEqual(_get_menu_names(context_menu._menu_dict),
['first', 'Item-100', 'Item00', 'Item01', 'before separator', '', 'Item02', 'Item2.5',
'after separator', 'Item03', 'Item999', 'last', 'non existent'])
# test delete
context_menu.delete_menu_item("Item2.5")
self.assertEqual(_get_menu_names(context_menu._menu_dict),
['first', 'Item-100', 'Item00', 'Item01', 'before separator', '', 'Item02',
'after separator', 'Item03', 'Item999', 'last', 'non existent'])
async def test_context_menu_async_show_fn(self):
"""Testing that with async show fn menu item visibility updates correctly."""
async def _async_show(context, menu_item):
await ui_test.human_delay(8)
menu_item.visible = True
async def _async_hide(context, menu_item):
await ui_test.human_delay(8)
menu_item.visible = False
class _MockAsyncShownFn(BaseContextMenu):
def __init__(self, **kwargs):
super().__init__(title="Mock Async Shown Fn", **kwargs)
self._menu_dict = [
{
"name": "Item01_show",
"onclick_fn": lambda context: print(context),
"show_fn": [lambda context: True,]
},
{
"name": "",
},
{
"name": "Item02_async_show",
"onclick_fn": lambda context: print(context),
"show_fn": [lambda context: True,],
"show_fn_async": _async_show,
},
{
"name": "",
},
{
"name": "Item03_async_hide",
"onclick_fn": lambda context: print(context),
"show_fn": [lambda context: True,],
"show_fn_async": _async_hide,
},
{
"name": "",
},
{
"name": "Item04_show",
"onclick_fn": lambda context: print(context),
"show_fn": [lambda context: True,]
},
]
with self._window.frame:
context_menu = _MockAsyncShownFn()
await ui_test.human_delay()
context_menu.show(None, [])
await ui_test.human_delay()
menu_root = ui.Menu.get_current()
menu_items = ui.Inspector.get_children(menu_root)
# check that items are built for each menu entry
self.assertEqual(len(context_menu._menu_dict), len(menu_items))
# before the aysnc shown fn finishes, all the 2 async items should be invisble
async_show_item = menu_items[2]
async_hide_item = menu_items[4]
for item in (async_show_item, async_hide_item):
self.assertFalse(item.visible)
# by default, the separator after the async hide item will be built and will be visible
separator_to_update = menu_items[5]
self.assertTrue(separator_to_update.visible)
await ui_test.human_delay(10)
# after async fn finishes, visibility of menu item should be updated
self.assertTrue(async_show_item.visible)
self.assertFalse(async_hide_item.visible)
# 2 separators should not be shown next to each other
# since async_hide_item is now confirmed invisible, the separator after it should be updated to invisble
self.assertFalse(separator_to_update.visible)
class TestMenuOptions(omni.kit.test.AsyncTestCase):
"""Testing the context menu's options"""
async def setUp(self):
self.previous_retry_values = omni.client.set_retries(0, 0, 0)
async def tearDown(self):
omni.client.set_retries(*self.previous_retry_values)
async def test_Options_availablity(self):
"""Testing the context menu show up options correctly under different circumstances."""
dialog = FilePickerDialog("test_rename_availablity", treeview_identifier="FilePicker")
await ui_test.human_delay(10)
dialog.add_connections({"ov-test": "omniverse://ov-test"})
await ui_test.human_delay(10)
with TemporaryDirectory() as tmpdir_fd:
tmpdir = Path(tmpdir_fd).resolve()
temp_fd = NamedTemporaryFile(dir=tmpdir, suffix=".mdl", delete=False)
temp_fd.close()
_, filename = os.path.split(temp_fd.name)
async with FilePickerTestHelper(dialog._widget) as filepicker_helper:
# rename should appear when connection is selected
item = await filepicker_helper.get_item_async("FilePicker", "ov-test", pane=TREEVIEW_PANE)
await item.right_click()
context_menu = await ui_test.get_context_menu()
context_options = context_menu["_"]
self.assertTrue("Rename" in context_options)
# rename should not appear when a file item is selected
await filepicker_helper.select_items_async(str(tmpdir), [filename])
item = await filepicker_helper.get_item_async("FilePicker", filename, pane=LISTVIEW_PANE)
await ui_test.human_delay()
await item.right_click()
context_menu = await ui_test.get_context_menu()
context_options = context_menu["_"]
self.assertTrue("Rename" in context_options)
pane = await filepicker_helper.get_pane_async("FilePicker", pane=LISTVIEW_PANE)
await pane.right_click()
context_menu = await ui_test.get_context_menu()
context_options = context_menu["_"]
# OM-104870: Also need check other menu options
self.assertTrue("New USD File" in context_options)
self.assertTrue("Refresh" in context_options)
self.assertTrue("Add Bookmark" in context_options)
self.assertTrue("Copy URL Link" in context_options)
# OMFP-2569: make sure login/logout menuitem is keep consisitent with the item's connect status
async def test_LogIn_LogOut_availablity(self):
"""Testing the context menu show up LogIn/LogOut correctly under different circumstances."""
dialog = FilePickerDialog("test_login_logout_availablity", treeview_identifier="FilePicker")
await ui_test.human_delay(10)
dialog.add_connections({"ov-test": "omniverse://ov-test"})
await ui_test.human_delay(10)
async with FilePickerTestHelper(dialog._widget) as filepicker_helper:
# login should appear when connection is selected
item = await filepicker_helper.get_item_async("FilePicker", "ov-test", pane=TREEVIEW_PANE)
# simulate connected status
dialog._widget._view._server_status_changed("omniverse://ov-test", omni.client.ConnectionStatus.CONNECTED)
await ui_test.human_delay(30)
await item.right_click()
context_menu = await ui_test.get_context_menu()
context_options = context_menu["_"]
self.assertFalse("Log In" in context_options)
self.assertTrue("Log Out" in context_options)
# simulate disconnected status
dialog._widget._view._server_status_changed("omniverse://ov-test", omni.client.ConnectionStatus.SIGNED_OUT)
await ui_test.human_delay(30)
await item.right_click()
context_menu = await ui_test.get_context_menu()
context_options = context_menu["_"]
self.assertTrue("Log In" in context_options)
self.assertFalse("Log Out" in context_options)
| 14,229 | Python | 45.05178 | 119 | 0.547263 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/tests/test_file_info.py | ## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import omni.kit.app
import omni.client
from datetime import datetime
from unittest.mock import patch
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit.test_suite.helpers import get_test_data_path
from ..dialog import FilePickerDialog
from ..detail_view import ExtendedFileInfo
class MockServer:
def __init__(self, cache_enabled=False, checkpoints_enabled=False, omniojects_enabled=False, username="", version=""):
self.cache_enabled = cache_enabled
self.checkpoints_enabled = checkpoints_enabled
self.omniojects_enabled = omniojects_enabled
self.username = username
self.version = version
class MockFileEntry:
def __init__(self, relative_path="", access="", flags="", size=0, modified_time="", created_time="", modified_by="", created_by="", version=""):
self.relative_path = relative_path
self.access = access
self.flags = flags
self.size = size
self.modified_time = modified_time
self.created_time = created_time
self.modified_by = modified_by
self.created_by = created_by
self.version = version
self.comment = "<Test Node>"
class TestFileInfo(AsyncTestCase):
# Before running each test
async def setUp(self):
self._mock_server = MockServer(
cache_enabled=False,
checkpoints_enabled=True,
omniojects_enabled=True,
username="[email protected]",
version="TestServer"
)
self._mock_file_entry_0 = MockFileEntry(
access=1,
created_by="[email protected]",
created_time=datetime.now(),
flags=513,
modified_by="[email protected]",
modified_time=datetime.now(),
relative_path="&FakeCheckpoint",
size=16070,
version=12023408
)
# After running each test
async def tearDown(self):
pass
async def _mock_get_server_info_async(self, url: str):
return omni.client.Result.OK, self._mock_server
def _mock_on_file_change(self, result, entry):
pass
def _mock_resolve_subscribe(self, url, urls, cb1, cb2):
cb2(omni.client.Result.OK, None, self._mock_file_entry_0, None)
async def test_file_info(self):
with patch("omni.client.get_server_info_async", side_effect=self._mock_get_server_info_async),\
patch("omni.client.resolve_subscribe_with_callback", side_effect=self._mock_resolve_subscribe),\
patch.object(ExtendedFileInfo, "_on_file_change_event", side_effect=self._mock_on_file_change) as _mock_file_change:
test_path = get_test_data_path(__name__, "../icon.png")
under_test = FilePickerDialog(
"test_resolve_timestamp",
current_directory=test_path,
)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
test_path2 = get_test_data_path(__name__, "../preview.png")
await under_test._widget.api.select_items_async(test_path2)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
_mock_file_change.assert_called()
| 3,736 | Python | 37.132653 | 148 | 0.638116 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/tests/test_bookmarks.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import asyncio
from unittest.mock import patch
from ..api import FilePickerAPI
from ..model import FilePickerModel
from ..view import FilePickerView
from ..file_ops import add_bookmark, edit_bookmark, delete_bookmark
from unittest.mock import Mock
import omni.kit.ui_test as ui_test
import omni.client
class TestAddDeleteRenameBookmark(omni.kit.test.AsyncTestCase):
"""Testing FilePickerView.*bookmark* methods"""
async def setUp(self):
self.previous_retry_values = omni.client.set_retries(0, 0, 0)
# OM-78933: Init_view mounts localhost, which emits a BOOKMARK_ADDED_EVENT. This corrupts the event stream
# and subsequently adds unaccounted calls to mock_add_bookmark below. The simple fix is to add a few frames
# here in order to steer clear of the initialization step.
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
async def tearDown(self):
omni.client.set_retries(*self.previous_retry_values)
async def _wait_for_window(self, title, updates=10):
window = None
for _ in range(updates):
window = ui_test.find(title)
if window is not None:
break
await omni.kit.app.get_app().next_update_async()
self.assertIsNotNone(window)
return window
async def test_add_bookmark(self):
"""Testing FilePickerView.add_bookmark adds the bookmark and stores as persistent setting"""
with patch("omni.client.add_bookmark") as mock_add_bookmark:
test_name, test_path = "added", "omniverse://ov-added"
under_test = FilePickerView("test-view")
self.assertFalse(under_test.has_connection_with_name(test_name, collection="bookmarks"))
mock_add_bookmark.reset_mock()
under_test.add_bookmark(test_name, test_path)
self.assertTrue(under_test.has_connection_with_name(test_name, collection="bookmarks"))
await omni.kit.app.get_app().next_update_async()
mock_add_bookmark.assert_called_once_with(test_name, test_path + "/")
# test add bookmark for local path
test_name, test_path = "local bookmark", "C:/foo/bar.pref"
under_test = FilePickerView("test-view")
self.assertFalse(under_test.has_connection_with_name(test_name, collection="bookmarks"))
# Add bookmark while testing dialogs
item = Mock()
item.name = test_name
item.path = test_path
add_bookmark(item, under_test)
add_dialog = await self._wait_for_window("Add Bookmark")
self.assertIsNotNone(add_dialog)
ok_button = add_dialog.find("**/Button[*].text=='Ok'")
await ok_button.click()
self.assertTrue(under_test.has_connection_with_name(test_name, collection="bookmarks"))
await omni.kit.app.get_app().next_update_async()
mock_add_bookmark.assert_called_with(test_name, "file://" + test_path + "/")
async def test_delete_bookmark_with_callback(self):
"""Testing FilePickerView.delete_bookmark deletes the bookmark and updates the persistent setting"""
with patch("omni.client.remove_bookmark") as mock_remove_bookmark:
test_name, test_path = "test", "omniverse://ov-test"
under_test = FilePickerView("test-view")
self.assertFalse(under_test.has_connection_with_name(test_name, collection="bookmarks"))
bookmark = under_test.add_bookmark(test_name, test_path)
self.assertTrue(under_test.has_connection_with_name(test_name, collection="bookmarks"))
# Confirm that after being deleted, test_name is no longer in the bookmarks liset
delete_bookmark(bookmark, under_test)
delete_dialog = await self._wait_for_window("Delete Bookmark")
yes_button = delete_dialog.find("**/Button[*].text=='Yes'")
await yes_button.click()
self.assertFalse(under_test.has_connection_with_name(test_name, collection="bookmarks"))
await omni.kit.app.get_app().next_update_async()
mock_remove_bookmark.assert_called_with(test_name)
async def test_rename_bookmark_with_callback(self):
"""Testing FilePickerView.rename_bookmark renames the bookmark and updates the persistent setting"""
with patch("omni.client.add_bookmark") as mock_add_bookmark,\
patch("omni.client.remove_bookmark") as mock_remove_bookmark:
test_name, test_path, test_rename = "ov-test", "omniverse://ov-test", "ov-renamed"
under_test = FilePickerView("test-view")
bookmark = under_test.add_bookmark(test_name, test_path)
self.assertTrue(under_test.has_connection_with_name(test_name, collection="bookmarks"))
# test rename name
await omni.kit.app.get_app().next_update_async()
edit_bookmark(bookmark, under_test)
edit_dialog = await self._wait_for_window("Edit Bookmark")
self.assertIsNotNone(edit_dialog)
field = edit_dialog.find(f"**/StringField[*].model.get_value_as_string() == '{test_name}'")
field.widget.model.set_value(test_rename)
ok_button = edit_dialog.find("**/Button[*].text=='Ok'")
await ok_button.click()
self.assertFalse(under_test.has_connection_with_name(test_name, collection="bookmarks"))
self.assertTrue(under_test.has_connection_with_name(test_rename, collection="bookmarks"))
# Confirm that previous name deleted, then new name added; delete bookmark is executed with delay so wait here
for _ in range(8):
await omni.kit.app.get_app().next_update_async()
mock_remove_bookmark.assert_called_with(test_name)
mock_add_bookmark.assert_called_with(test_rename, test_path + "/")
# test rename only url
await omni.kit.app.get_app().next_update_async()
under_test.rename_bookmark(bookmark, test_rename, "omniverse://dummy")
self.assertTrue(under_test.has_connection_with_name(test_rename, collection="bookmarks"))
await omni.kit.app.get_app().next_update_async()
mock_add_bookmark.assert_called_with(test_rename, "omniverse://dummy")
class TestUpdateBookmarksFromApi(omni.kit.test.AsyncTestCase):
"""Testing FilePickerAPI.*bookmarks* methods"""
async def setUp(self):
self.previous_retry_values = omni.client.set_retries(0, 0, 0)
# OM-78933: Init_view mounts localhost, which emits a BOOKMARK_ADDED_EVENT. This corrupts the event stream
# and subsequently adds unaccounted calls to mock_add_bookmark below. The simple fix is to add a few frames
# here in order to steer clear of the initialization step.
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
async def tearDown(self):
omni.client.set_retries(*self.previous_retry_values)
async def test_add_delete_bookmark(self):
"""Testing FilePickerAPI.toggle_bookmark_from_path updates persistent settings"""
with patch("omni.client.add_bookmark") as mock_add_bookmark,\
patch("omni.client.remove_bookmark") as mock_remove_bookmark:
test_name, test_path = "zXuo24Qjb", "omniverse://ov-zXuo24Qjb/bookmarked_dir"
test_view = FilePickerView("test-view")
under_test = FilePickerAPI(FilePickerModel(), test_view)
# Test adding new bookmark
self.assertFalse(test_view.has_connection_with_name(test_name, collection="bookmarks"))
under_test.toggle_bookmark_from_path(test_name, test_path, True)
self.assertTrue(test_view.has_connection_with_name(test_name, collection="bookmarks"))
await omni.kit.app.get_app().next_update_async()
mock_add_bookmark.assert_called_with(test_name, test_path + "/")
# Test deleting bookmark
under_test.toggle_bookmark_from_path(test_name, test_path, False)
self.assertFalse(test_view.has_connection_with_name(test_name, collection="bookmarks"))
await omni.kit.app.get_app().next_update_async()
mock_remove_bookmark.assert_called_with(test_name)
async def test_update_bookmarks_when_settings_changed(self):
"""Testing FilePickerAPI.subscribe_client_bookmarks_changed updates bookmarks in view when settings changed"""
test_view = FilePickerView("test-view")
under_test = FilePickerAPI(FilePickerModel(), test_view)
under_test.subscribe_client_bookmarks_changed()
# Assert bookmark not initially in the view
test_name, test_path = "b0azwuYvz", "omniverse://ov-b0azwuYvz/bookmarked_dir"
self.assertFalse(test_view.has_connection_with_name(test_name, collection="bookmarks"))
# Confirm that after adding bookmark to settings, the view updates appropriately
omni.client.add_bookmark(test_name, test_path)
# bookmark refreshing has a 1 second "debounce" time, so wait for longer than that
await asyncio.sleep(1.5)
self.assertTrue(test_view.has_connection_with_name(test_name, collection="bookmarks"))
# Confirm that after deleting bookmark from settings, the view updates appropriately
omni.client.remove_bookmark(test_name)
# bookmark refreshing has a 1 second "debounce" time, so wait for longer than that
await asyncio.sleep(1.5)
self.assertFalse(test_view.has_connection_with_name(test_name, collection="bookmarks"))
# Confirm that updating bookmarks manually, the view updates appropriately
bookmarks = {"b0azwuYvz": "omniverse://ov-b0azwuYvz/bookmarked_dir"}
under_test._update_bookmarks(bookmarks)
under_test._update_nucleus_servers(bookmarks)
await asyncio.sleep(1.5)
self.assertTrue(test_view.has_connection_with_name(test_name, collection="bookmarks"))
| 10,523 | Python | 52.693877 | 122 | 0.666445 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/tests/test_asset_types.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import omni.kit.test
import omni.client
from omni.kit.helper.file_utils import asset_types
from omni.kit.widget.filebrowser import FileBrowserItem, FileBrowserItemFactory
from ..model import FilePickerModel
class TestAssetTypes(omni.kit.test.AsyncTestCase):
"""Testing FilePickerModel.*asset_type"""
async def setUp(self):
self.test_filenames = [
("test.settings.usd", asset_types.ASSET_TYPE_USD_SETTINGS),
("test.settings.usda", asset_types.ASSET_TYPE_USD_SETTINGS),
("test.settings.usdc", asset_types.ASSET_TYPE_USD_SETTINGS),
("test.settings.usdz", asset_types.ASSET_TYPE_USD_SETTINGS),
("test.fbx", asset_types.ASSET_TYPE_FBX),
("test.obj", asset_types.ASSET_TYPE_OBJ),
("test.mdl", asset_types.ASSET_TYPE_MATERIAL),
("test.mtlx", asset_types.ASSET_TYPE_MATERIAL),
("test.bmp", asset_types.ASSET_TYPE_IMAGE),
("test.gif", asset_types.ASSET_TYPE_IMAGE),
("test.jpg", asset_types.ASSET_TYPE_IMAGE),
("test.jpeg", asset_types.ASSET_TYPE_IMAGE),
("test.png", asset_types.ASSET_TYPE_IMAGE),
("test.tga", asset_types.ASSET_TYPE_IMAGE),
("test.tif", asset_types.ASSET_TYPE_IMAGE),
("test.tiff", asset_types.ASSET_TYPE_IMAGE),
("test.hdr", asset_types.ASSET_TYPE_IMAGE),
("test.dds", asset_types.ASSET_TYPE_IMAGE),
("test.exr", asset_types.ASSET_TYPE_IMAGE),
("test.psd", asset_types.ASSET_TYPE_IMAGE),
("test.ies", asset_types.ASSET_TYPE_IMAGE),
("test.wav", asset_types.ASSET_TYPE_SOUND),
("test.wav", asset_types.ASSET_TYPE_SOUND),
("test.wave", asset_types.ASSET_TYPE_SOUND),
("test.ogg", asset_types.ASSET_TYPE_SOUND),
("test.oga", asset_types.ASSET_TYPE_SOUND),
("test.flac", asset_types.ASSET_TYPE_SOUND),
("test.fla", asset_types.ASSET_TYPE_SOUND),
("test.mp3", asset_types.ASSET_TYPE_SOUND),
("test.m4a", asset_types.ASSET_TYPE_SOUND),
("test.spx", asset_types.ASSET_TYPE_SOUND),
("test.opus", asset_types.ASSET_TYPE_SOUND),
("test.adpcm", asset_types.ASSET_TYPE_SOUND),
("test.py", asset_types.ASSET_TYPE_SCRIPT),
("test.nvdb", asset_types.ASSET_TYPE_VOLUME),
("test.vdb", asset_types.ASSET_TYPE_VOLUME),
("test.svg", asset_types.ASSET_TYPE_ICON),
(".thumbs", asset_types.ASSET_TYPE_HIDDEN),
]
try:
# test USD only when available
import omni.usd
except ImportError:
pass
else:
self.test_filenames.extend([
("test.usd", asset_types.ASSET_TYPE_USD),
("test.usda", asset_types.ASSET_TYPE_USD),
("test.usdc", asset_types.ASSET_TYPE_USD),
("test.usdz", asset_types.ASSET_TYPE_USD),
])
async def tearDown(self):
pass
def _create_folder_item(self, path: str) -> FileBrowserItem:
item = FileBrowserItemFactory.create_group_item(path, path)
return item
def _create_file_item(self, path: str) -> FileBrowserItem:
item = FileBrowserItemFactory.create_group_item(path, path)
item._is_folder = False
return item
async def test_get_icon(self):
"""Testing FilePickerModel.get_icon returns expected icon for asset type"""
under_test = FilePickerModel()
for test_filename in self.test_filenames:
filename, asset_type = test_filename
if asset_type not in [asset_types.ASSET_TYPE_ICON, asset_types.ASSET_TYPE_HIDDEN]:
expected = asset_types._known_asset_types[asset_type].glyph
result = under_test.get_icon(self._create_file_item(filename), False)
self.assertEqual(result, expected,
"Expected icon of {filename} to be {expected} - got {result}")
# Test folder type
self.assertEqual(under_test.get_icon(self._create_folder_item("folder"), False), None)
# Test unknown file type
self.assertEqual(under_test.get_icon(self._create_file_item("test.unknown"), False), None)
async def test_get_thumbnail(self):
"""Testing FilePickerModel.get_thumbnail returns correct thumbnail for asset type"""
under_test = FilePickerModel()
for test_filename in self.test_filenames:
filename, asset_type = test_filename
if asset_type not in [asset_types.ASSET_TYPE_ICON, asset_types.ASSET_TYPE_HIDDEN]:
expected = asset_types._known_asset_types[asset_type].thumbnail
result = under_test.get_thumbnail(self._create_file_item(filename))
self.assertEqual(result, expected,
"Expected thumbnail of {filename} to be {expected} - got {result}")
# Test folder type
result = under_test.get_thumbnail(self._create_folder_item("folder"))
self.assertEqual(os.path.basename(result), "folder_256.png")
# Test unknown file type
result = under_test.get_thumbnail(self._create_file_item("test.unknown"))
self.assertEqual(os.path.basename(result), "unknown_file_256.png")
| 5,791 | Python | 46.867768 | 98 | 0.619755 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/tests/test_navigate.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import platform
import omni.kit.test
import asyncio
import omni.kit.app
import omni.client
from typing import Callable
from unittest.mock import Mock, patch, ANY, call
from ..api import FilePickerAPI
from ..model import FilePickerModel
from ..view import FilePickerView
from omni.kit.widget.filebrowser import FileBrowserModel, FileBrowserItem, FileBrowserItemFactory
from omni.kit.widget.nucleus_connector import NucleusConnectorExtension
class TestSanitizePath(omni.kit.test.AsyncTestCase):
"""Testing FilePickerModel.sanitize_path"""
async def setUp(self):
self.previous_retry_values = omni.client.set_retries(0, 0, 0)
self.test_paths = [
("my-computer://C:\\temp\\test\\file.mdl", "my-computer://c:/temp/test/file.mdl"),
(" /home/user/ ", "/home/user/"),
(
"http://content.ov.nvidia.com/omniverse://ov-content/Users/[email protected]/Bugs/OM21975/OM21975.usd",
"omniverse://ov-content/Users/[email protected]/Bugs/OM21975/OM21975.usd",
),
(
"omniverse://content.ov.nvidia.com/Users/[email protected]/assets/FREE_%C5%BBuk_3D_model.usdz",
"omniverse://content.ov.nvidia.com/Users/[email protected]/assets/FREE_Żuk_3D_model.usdz",
)
]
async def tearDown(self):
omni.client.set_retries(*self.previous_retry_values)
async def test_sanitize_path(self):
"""Testing FilePickerModel.sanitize_path returns expected path after normalization"""
under_test = FilePickerModel()
for test_path in self.test_paths:
input, expected = test_path
self.assertEqual(under_test.sanitize_path(input), expected)
class TestFindItemInSubTree(omni.kit.test.AsyncTestCase):
"""Testing FilePickerModel.find_item_in_subtree_async"""
async def setUp(self):
self.previous_retry_values = omni.client.set_retries(0, 0, 0)
self.test_listings = {
"omniverse://": ["omniverse://ov-sandbox", "omniverse://ov-test"],
"omniverse://ov-test": ["Lib", "NVIDIA", "Projects", "Users"],
"omniverse://ov-test/NVIDIA": ["Assets", "Materials", "Samples"],
"omniverse://ov-test/NVIDIA/Samples": ["Astronaut", "Flight", "Marbles", "Attic"],
"omniverse://ov-test/NVIDIA/Samples/Astronaut": ["Astronaut.usd", "Materials", "Props"],
"my-computer://": ["/", "Desktop", "Documents", "Downloads"],
"/": ["bin", "etc", "home", "lib", "tmp"],
"/home": ["jack", "jill"],
"/home/jack": ["Desktop", "Documents", "Downloads"],
"/home/jack/Documents": ["test.usd"],
}
async def tearDown(self):
omni.client.set_retries(*self.previous_retry_values)
async def _mock_populate_async_impl(self, item: FileBrowserItem, callback_async: Callable):
if not item.populated:
if item.path in self.test_listings:
subdirs = self.test_listings[item.path]
else:
subdirs = []
for subdir in subdirs:
if item.path.endswith("://"):
path = subdir
elif item.path == "/":
path = f"/{subdir}"
else:
path = f"{item.path}/{subdir}"
item.add_child(FileBrowserItemFactory.create_group_item(subdir, path))
item.populated = True
return None
async def _mock_populate_async_timeout(self, item: FileBrowserItem, callback_async: Callable):
return asyncio.TimeoutError(1.0)
async def test_find_nucleus_path_succeeds(self):
"""Testing FilePickerModel.find_item_in_subtree_async with Nucleus path should succeed"""
with patch.object(FileBrowserItem, "populate_async", autospec=True) as mock_populate_async:
mock_populate_async.side_effect = self._mock_populate_async_impl
root_name = "ov-test"
model = FileBrowserModel(root_name, f"omniverse://{root_name}")
collection = FileBrowserItemFactory.create_group_item("Omniverse", "omniverse://")
collection.add_child(model.root)
test_path = f"{root_name}/NVIDIA/Samples/Astronaut/Astronaut.usd"
under_test = FilePickerModel()
item = await under_test.find_item_in_subtree_async(collection, test_path)
assert item != None
self.assertEqual(item.path, f"omniverse://{test_path}")
async def test_find_linux_path_succeeds(self):
"""Testing FilePickerModel.find_item_in_subtree_async with Linux path should succeed"""
with patch.object(FileBrowserItem, "populate_async", autospec=True) as mock_populate_async:
mock_populate_async.side_effect = self._mock_populate_async_impl
root_name = "/"
model = FileBrowserModel(root_name, root_name)
collection = FileBrowserItemFactory.create_group_item("My Computer", "my-computer://")
collection.add_child(model.root)
test_path = "/home/jack/Documents/test.usd"
under_test = FilePickerModel()
item = await under_test.find_item_in_subtree_async(collection, test_path)
assert item != None
self.assertEqual(item.path, test_path)
async def test_find_invalid_path_fails(self):
"""Testing FilePickerModel.find_item_in_subtree_async from aliased Nucleus path should succeed"""
with patch.object(FileBrowserItem, "populate_async", autospec=True) as mock_populate_async:
mock_populate_async.side_effect = self._mock_populate_async_impl
root_name = "ov-test"
model = FileBrowserModel(root_name, f"omniverse://{root_name}")
collection = FileBrowserItemFactory.create_group_item("Omniverse", "omniverse://")
collection.add_child(model.root)
# Expect exception.
with self.assertRaises(RuntimeWarning) as e:
test_path = f"{root_name}/invalid/path"
under_test = FilePickerModel()
await under_test.find_item_in_subtree_async(collection, test_path)
assert str(e.exception).startswith("Path not found")
async def test_populate_async_times_out(self):
"""Testing FileBrowserItem.populate_async times out"""
with patch.object(FileBrowserItem, "populate_async", autospec=True) as mock_populate_async:
mock_populate_async.side_effect = self._mock_populate_async_timeout
root_name = "ov-test"
model = FileBrowserModel(root_name, f"omniverse://{root_name}")
collection = FileBrowserItemFactory.create_group_item("Omniverse", "omniverse://")
collection.add_child(model.root)
# Expect timeout exception.
with self.assertRaises(asyncio.TimeoutError) as e:
test_path = f"{root_name}/NVIDIA/Samples/Astronaut/Astronaut.usd"
under_test = FilePickerModel()
await under_test.find_item_in_subtree_async(collection, test_path)
class TestFindItem(omni.kit.test.AsyncTestCase):
"""Testing FilePickerModel.find_item_async"""
async def setUp(self):
self.previous_retry_values = omni.client.set_retries(0, 0, 0)
self.collections = {
"omniverse": FileBrowserItemFactory.create_group_item("Omniverse", "omniverse"),
"my-computer": FileBrowserItemFactory.create_group_item("My Computer", "my-computer"),
"bookmarks": FileBrowserItemFactory.create_group_item("Bookmarks", "bookmarks"),
}
self.test_listings = {
self.collections["omniverse"]: [
"omniverse://ov-test/NVIDIA/Samples/Astronaut/Astronaut.usd",
],
self.collections["my-computer"]: [
"/home/jack/Documents/foo.usd",
"/Downloads/bar.usd",
],
self.collections["bookmarks"]: [
"omniverse://ov-test/NVIDIA/Samples/Astronaut/Astronaut.usd",
]
}
async def tearDown(self):
omni.client.set_retries(*self.previous_retry_values)
async def _mock_find_item_in_subtree_async_impl(self, root: FileBrowserItem, path: str):
if root in self.test_listings:
for fullpath in self.test_listings[root]:
if fullpath.endswith(path):
return FileBrowserItemFactory.create_group_item(os.path.basename(path), fullpath)
raise RuntimeWarning(f"Path not found: '{path}'")
async def test_parse_collection_succeeds(self):
"""Testing FilePickerModel.find_item_async should search the appropriate collection"""
with patch.object(FilePickerModel, "find_item_in_subtree_async") as mock_find_item_in_subtree:
test_path = "path/to/my/file.usd"
under_test = FilePickerModel()
under_test.collections = self.collections
# Path with explicit 'omniverse://' prefix should search the omniverse collection
mock_find_item_in_subtree.reset_mock()
await under_test.find_item_async(f"omniverse://{test_path}", None)
mock_find_item_in_subtree.assert_called_once_with(self.collections.get("omniverse"), test_path)
# Path with no 'omniverse://' prefix should search the local collection
mock_find_item_in_subtree.reset_mock()
await under_test.find_item_async(test_path, None)
mock_find_item_in_subtree.assert_called_once_with(self.collections.get("my-computer"), test_path)
async def test_omniverse_url_found(self):
"""Testing FilePickerModel.find_item_async execs callback when omniverse path is found"""
with patch.object(FilePickerModel, "find_item_in_subtree_async") as mock_find_item_in_subtree:
mock_find_item_in_subtree.side_effect = self._mock_find_item_in_subtree_async_impl
mock_callback = Mock()
test_path = "omniverse://ov-test/NVIDIA/Samples/Astronaut/Astronaut.usd"
under_test = FilePickerModel()
under_test.collections = self.collections
found = await under_test.find_item_async(test_path, mock_callback)
self.assertEqual(found.path, test_path)
async def test_filesystem_url_found(self):
"""Testing FilePickerModel.find_item_async execs callback when local path is found"""
with patch.object(FilePickerModel, "find_item_in_subtree_async") as mock_find_item_in_subtree:
mock_find_item_in_subtree.side_effect = self._mock_find_item_in_subtree_async_impl
mock_callback = Mock()
test_path = "/home/jack/Documents/foo.usd"
under_test = FilePickerModel()
under_test.collections = self.collections
found = await under_test.find_item_async(test_path, mock_callback)
self.assertEqual(found.path, test_path)
async def test_path_not_found(self):
"""Testing FilePickerModel.find_item_async execs callback when path not found"""
with patch.object(FilePickerModel, "find_item_in_subtree_async") as mock_find_item_in_subtree:
mock_find_item_in_subtree.side_effect = self._mock_find_item_in_subtree_async_impl
mock_callback = Mock()
test_path = "invalid/path"
under_test = FilePickerModel()
under_test.collections = self.collections
found = await under_test.find_item_async(test_path, mock_callback)
# After searching all collections and not finding the path, exec callback with input set to None
self.assertEqual(found, None)
mock_callback.assert_called_once_with(None)
async def test_aliased_omniverse_url_searched(self):
"""Testing FilePickerModel.find_item_async searches both the aliased and real server paths"""
# Create a server connection with an aliased name
root = self.collections["omniverse"]
serv = FileBrowserItemFactory.create_group_item("ov-alias", "omniverse://ov-test")
root.add_child(serv)
with patch.object(FilePickerModel, "find_item_in_subtree_async") as mock_find_item_in_subtree:
mock_find_item_in_subtree.side_effect = self._mock_find_item_in_subtree_async_impl
test_path = "omniverse://ov-test/file/not/found.usd"
under_test = FilePickerModel()
under_test.collections = self.collections
found = await under_test.find_item_async(test_path)
# Even though Url is not found, confirm that it was searched for under both the aliased and real server names.
self.assertEqual(found, None)
self.assertEqual(mock_find_item_in_subtree.call_count, 2)
expected_path = test_path.replace("omniverse://", "")
# First, search all servers under root, but expect not find item in the server named "ov-alias"
self.assertEqual(mock_find_item_in_subtree.call_args_list[0], call(root, expected_path))
# Even though the server is named "ov-alias", it's real path is "ov-test". Expect to search this specific server.
self.assertEqual(mock_find_item_in_subtree.call_args_list[1], call(serv, expected_path.replace("ov-test/", "")))
class TestApiNavigate(omni.kit.test.AsyncTestCase):
"""Testing FilePickerAPI.navigate_to"""
async def setUp(self):
self.previous_retry_values = omni.client.set_retries(0, 0, 0)
self.test_listings = [
"omniverse://ov-test/NVIDIA/Samples/Astronaut/Astronaut.usd",
]
async def tearDown(self):
omni.client.set_retries(*self.previous_retry_values)
async def _mock_find_item_async_impl(self, url: str, callback: Callable = None):
item = None
if url in self.test_listings:
item = FileBrowserItemFactory.create_group_item(os.path.basename(url), url)
return item
async def _mock_find_item_async_hangs(self, url: str, callback: Callable = None):
while True:
await asyncio.sleep(.1)
def _mock_connect_server_impl(self, name: str, server_url: str, on_success_fn: Callable = None, on_failed_fn: Callable = None):
if on_success_fn:
on_success_fn(name, server_url)
async def _mock_stat_async_succeeds(self, url: str):
return omni.client.Result.OK, None
async def _mock_stat_async_fails(self, url: str):
return omni.client.Result.ERROR, None
async def test_local_path(self):
"""Testing FilePickerModel.is_local_path returns expected answer"""
under_test = FilePickerModel()
self.assertTrue(under_test.is_local_path("file:/home/usr/data/foo.usd"))
self.assertTrue(under_test.is_local_path("/home/user/data/foo.usd"))
self.assertTrue(under_test.is_local_path("C:/temp/foo.usd"))
self.assertTrue(under_test.is_local_path("z:/temp/foo.usd"))
self.assertFalse(under_test.is_local_path("omniverse://ov-test/foo.usd"))
self.assertFalse(under_test.is_local_path("ov-test/foo.usd"))
async def test_path_found(self):
"""Testing FilePickerAPI.navigate_to execs callback when Omniverse path found"""
with patch.object(FilePickerModel, "find_item_async", side_effect=self._mock_find_item_async_impl),\
patch.object(FilePickerView, "has_connection_with_name", return_value=True),\
patch.object(FilePickerView, "select_and_center") as mock_select_and_center,\
patch("omni.client.stat_async", side_effect=self._mock_stat_async_succeeds):
mock_callback = Mock()
test_path = "omniverse://ov-test/NVIDIA/Samples/Astronaut/Astronaut.usd"
under_test = FilePickerAPI(FilePickerModel(), FilePickerView("test-view"))
await under_test.navigate_to_async(test_path, mock_callback)
await omni.kit.app.get_app().next_update_async()
# Confirm callback exec'd, and view centered on found item
mock_callback.assert_called_once()
self.assertEqual(mock_callback.call_args[0][0].path, test_path)
mock_select_and_center.assert_called_once()
self.assertEqual(mock_select_and_center.call_args[0][0].path, test_path)
async def test_path_with_spaces_found(self):
"""Testing that any spaces around url are stripped and navigating to it still succeeds"""
with patch.object(FilePickerModel, "find_item_async", side_effect=self._mock_find_item_async_impl),\
patch.object(FilePickerView, "has_connection_with_name", return_value=True),\
patch.object(FilePickerView, "select_and_center") as mock_select_and_center,\
patch("omni.client.stat_async", side_effect=self._mock_stat_async_succeeds):
mock_callback = Mock()
test_path = " omniverse://ov-test/NVIDIA/Samples/Astronaut/Astronaut.usd "
under_test = FilePickerAPI(FilePickerModel(), FilePickerView("test-view"))
await under_test.navigate_to_async(test_path, mock_callback)
await omni.kit.app.get_app().next_update_async()
# Confirm callback exec'd, and view centered on found item
mock_callback.assert_called_once()
self.assertEqual(mock_callback.call_args[0][0].path, test_path.strip())
mock_select_and_center.assert_called_once()
self.assertEqual(mock_select_and_center.call_args[0][0].path, test_path.strip())
async def test_server_not_connected(self):
"""Testing FilePickerAPI.navigate_to connects server if not already connected"""
with patch.object(FilePickerModel, "find_item_async", side_effect=self._mock_find_item_async_impl),\
patch.object(FilePickerView, "has_connection_with_name", return_value=False),\
patch.object(FilePickerView, "select_and_center") as mock_select_and_center,\
patch.object(NucleusConnectorExtension, "connect", side_effect=self._mock_connect_server_impl) as mock_connect_server,\
patch("omni.client.stat_async", side_effect=self._mock_stat_async_succeeds):
mock_callback = Mock()
test_path = "omniverse://ov-test/NVIDIA/Samples/Astronaut/Astronaut.usd"
under_test = FilePickerAPI(FilePickerModel(), FilePickerView("test-view"))
await under_test.navigate_to_async(test_path, mock_callback)
await omni.kit.app.get_app().next_update_async()
# Confirm attempt to connect server
broken_url = omni.client.break_url(test_path)
mock_connect_server.assert_called_once_with(broken_url.host, f'{broken_url.scheme}://{broken_url.host}', on_success_fn=ANY)
# Confirm callback exec'd, and view centered on found item
mock_callback.assert_called_once()
self.assertEqual(mock_callback.call_args[0][0].path, test_path)
mock_select_and_center.assert_called_once()
self.assertEqual(mock_select_and_center.call_args[0][0].path, test_path)
async def test_local_path_not_found(self):
"""Testing FilePickerAPI.navigate_to does not try to connect to local path"""
with patch.object(FilePickerModel, "find_item_async", side_effect=self._mock_find_item_async_impl),\
patch.object(NucleusConnectorExtension, "connect") as mock_connect_server,\
patch("omni.client.stat_async", side_effect=self._mock_stat_async_fails):
test_path = "C:/test/not_found.usd"
under_test = FilePickerAPI(FilePickerModel(), FilePickerView("test-view"))
await under_test.navigate_to_async(test_path, callback=None)
await omni.kit.app.get_app().next_update_async()
# Confirm did not attempt to connect the server
mock_connect_server.assert_not_called()
async def test_navigate_cancelled(self):
"""Testing FilePickerAPI.navigate_to gets cancelled when hung"""
with patch.object(FilePickerModel, "find_item_async", side_effect=self._mock_find_item_async_hangs),\
patch.object(FilePickerView, "has_connection_with_name", return_value=True),\
patch("omni.client.stat_async", side_effect=self._mock_stat_async_succeeds):
mock_callback = Mock()
test_path = "omniverse://ov-test/slow/network/Astronaut/Astronaut.usd"
under_test = FilePickerAPI(FilePickerModel(), FilePickerView("test-view"))
# Cancel the task 2 seconds later
# need to wrap the cancel call in a func because at init the loading pane would be None
def delay_cancel():
under_test._loading_pane.cancel_task()
loop = asyncio.get_event_loop()
loop.call_later(2, delay_cancel, *[])
await under_test.navigate_to_async(test_path, mock_callback)
# Confirm callback exec'd, and view centered on found item
mock_callback.assert_not_called()
class TestApiFindSubdirs(omni.kit.test.AsyncTestCase):
"""Testing FilePickerAPI.find_subdirs_async"""
async def setUp(self):
self.previous_retry_values = omni.client.set_retries(0, 0, 0)
self.test_listings = {
"omniverse://ov-test/NVIDIA": ["Assets", "Materials", "Samples"],
}
async def tearDown(self):
omni.client.set_retries(*self.previous_retry_values)
async def _mock_find_item_async_impl(self, path: str):
item = None
if path in self.test_listings:
item = FileBrowserItemFactory.create_group_item(os.path.basename(path), path)
return item
async def _mock_populate_async_impl(self, item: FileBrowserItem, callback: Callable):
if not item.populated:
if item.path in self.test_listings:
subdirs = self.test_listings[item.path]
else:
subdirs = []
for subdir in subdirs:
item.add_child(FileBrowserItemFactory.create_group_item(subdir, f"{item.path}/{subdir}"))
item.populated = True
return item.children
async def test_path_found(self):
"""Testing FilePickerAPI.find_subdirs_async execs callback when subdirs found"""
with patch.object(FilePickerModel, "find_item_async", side_effect=self._mock_find_item_async_impl),\
patch.object(FileBrowserItem, "populate_async", side_effect=self._mock_populate_async_impl, autospec=True):
mock_callback = Mock()
test_path = "omniverse://ov-test/NVIDIA"
under_test = FilePickerAPI(FilePickerModel(), FilePickerView("test-view"))
await under_test.find_subdirs_async(test_path, mock_callback)
# Confirm callback exec'd with list of subdirs
mock_callback.assert_called_once_with(self.test_listings[test_path])
async def test_path_not_found(self):
"""Testing FilePickerAPI.find_subdirs_async execs callback with empty list when path not found"""
with patch.object(FilePickerModel, "find_item_async", side_effect=self._mock_find_item_async_impl),\
patch.object(FileBrowserItem, "populate_async", side_effect=self._mock_populate_async_impl, autospec=True):
mock_callback = Mock()
test_path = "omniverse://unknown-path"
under_test = FilePickerAPI(FilePickerModel(), FilePickerView("test-view"))
await under_test.find_subdirs_async(test_path, mock_callback)
# Confirm callback exec'd with list of subdirs
mock_callback.assert_called_once_with([])
async def test_empty_path(self):
"""Testing FilePickerAPI.find_subdirs_async execs callback with all connections when path is empty"""
mock_callback = Mock()
# Initialize view and ensure it has at least one connection.
view = FilePickerView("test-view")
view.add_server("ov-test", "omniverse://ov-test")
under_test = FilePickerAPI(FilePickerModel(), view)
await under_test.find_subdirs_async("", mock_callback)
# Confirm callback exec'd with list of all connections
expected = []
for collection in ['omniverse', 'my-computer']:
expected.extend([i.path for i in under_test.view.all_collection_items(collection)])
mock_callback.assert_called_once_with(expected)
async def test_local_path_windows_slashes(self):
"""Testing FilePickerDialog apply path doesn't contain any windows slashes"""
from omni.kit.window.filepicker import FilePickerDialog
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
filepicker_path = f"{extension_path}/icons/NvidiaDark/"
filepicker_filename = "omniverse_logo_64.png"
if platform.system().lower() == "windows":
filepicker_path = filepicker_path.replace("/", "\\")
mock_apply_fn = Mock()
dialog = FilePickerDialog("Testing", click_apply_handler=mock_apply_fn)
await omni.kit.app.get_app().next_update_async()
dialog.set_current_directory(filepicker_path)
dialog.set_filename(filepicker_filename)
await omni.kit.app.get_app().next_update_async()
dialog._click_apply_handler(dialog.get_filename(), dialog.get_current_directory())
mock_apply_fn.assert_called_once_with(filepicker_filename, filepicker_path.replace("\\", "/"))
| 25,980 | Python | 50.34585 | 135 | 0.647229 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/tests/test_datetime.py | import omni.kit.test
import omni.kit.ui_test as ui_test
import omni.ui as ui
import omni.kit.app
from ..datetime.date_widget import DateWidget
from ..datetime.time_widget import TimeWidget
from ..datetime.timezone_widget import TimezoneWidget
from ..datetime.models import ZoneModel
import datetime
import random
import pytz
class TestDatetimeWidget(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._window = ui.Window("test_datetime_widget", width=400, height=400)
await ui_test.human_delay(10)
async def tearDown(self):
self._window.destroy()
async def test_date(self):
with self._window.frame:
with ui.VStack():
date_widget = DateWidget()
await ui_test.human_delay(10)
field = ui_test.WidgetRef(date_widget._date_field, "", self._window)
await field.click()
for _ in range(10):
if date_widget._calendar is not None:
break
await omni.kit.app.get_app().next_update_async()
calendar = date_widget._calendar
# pick a random date and set on the UI
min_date = datetime.date(calendar._year_min, 1, 1)
max_date = datetime.date(calendar._year_max, 12, 31)
date = min_date + datetime.timedelta(days=random.randint(0, (max_date - min_date).days))
calendar._year_combo.model.get_item_value_model(None, 0).set_value(date.year - calendar._year_min)
self.assertEqual(date_widget.model.year, date.year)
calendar._month_combo.model.get_item_value_model(None, 0).set_value(date.month - 1)
self.assertEqual(date_widget.model.month, date.month)
# wait for week days rebuild
await ui_test.human_delay(10)
day_button = ui_test.WidgetRef(calendar._day_buttons[date.day], "")
await ui_test.emulate_mouse_move_and_click(day_button.center)
self.assertEqual(date_widget.model.day, date.day)
date = min_date + datetime.timedelta(days=random.randint(0, (max_date - min_date).days))
date_widget.model.set_value(f"{date.year}/{date.month}/{date.day}")
self.assertEqual(date_widget.model._datetime.date(), date)
async def test_time(self):
with self._window.frame:
with ui.HStack():
time_widget = TimeWidget()
await ui_test.human_delay(10)
field = ui_test.WidgetRef(time_widget._time_field, "", self._window)
await field.click()
for _ in range(10):
if time_widget._clock is not None:
break
await omni.kit.app.get_app().next_update_async()
clock = time_widget._clock
hour = random.randint(0, 23)
minute = random.randint(0, 59)
old_hour = time_widget.model.hour
old_minute = time_widget.model.minute
if (old_hour < 12) != (hour < 12):
day_widget = ui_test.WidgetRef(clock._day_down, "", self._window)
await ui_test.emulate_mouse_move_and_click(day_widget.center)
hour_sub_noon = hour - 12 if hour >= 12 else hour
old_hour_sub_noon = old_hour - 12 if old_hour >= 12 else old_hour
if hour_sub_noon >= old_hour_sub_noon:
hour_widget = ui_test.WidgetRef(clock._hour_up, "", self._window)
hour_diff = hour_sub_noon - old_hour_sub_noon
else:
hour_widget = ui_test.WidgetRef(clock._hour_down, "", self._window)
hour_diff = old_hour_sub_noon - hour_sub_noon
for _ in range(hour_diff):
await ui_test.emulate_mouse_move_and_click(hour_widget.center)
self.assertEqual(clock._half_day.text, "AM" if hour < 12 else "PM")
self.assertEqual(clock._hour_0.text, str(hour // 10))
self.assertEqual(clock._hour_1.text, str(hour % 10))
if minute >= old_minute:
minute_widget = ui_test.WidgetRef(clock._minute_up, "", self._window)
minute_diff = minute - old_minute
else:
minute_widget = ui_test.WidgetRef(clock._minute_down, "", self._window)
minute_diff = old_minute - minute
for _ in range(minute_diff):
await ui_test.emulate_mouse_move_and_click(minute_widget.center)
self.assertEqual(clock._minute_0.text, str(minute // 10))
self.assertEqual(clock._minute_1.text, str(minute % 10))
async def test_zone(self):
dt = datetime.datetime.now(tz=datetime.timezone.utc)
zone_model = ZoneModel(dt)
with self._window.frame:
with ui.HStack():
timezone_widget = TimezoneWidget(zone_model)
await ui_test.human_delay(10)
tz_idx = random.randint(0, len(timezone_widget._timezones) - 1)
timezone_widget._timezone_combo.model.get_item_value_model(None, 0).set_value(tz_idx)
self.assertEqual(
zone_model.timezone,
dt.astimezone(pytz.timezone(timezone_widget._timezones[tz_idx])).tzinfo
) | 4,957 | Python | 40.316666 | 106 | 0.620738 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/tests/test_test_helper.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
from pathlib import Path
from tempfile import TemporaryDirectory, NamedTemporaryFile
import omni.kit.test
from omni.kit import ui_test
from omni.kit.widget.filebrowser import TREEVIEW_PANE, LISTVIEW_PANE
from ..dialog import FilePickerDialog
from ..test_helper import FilePickerTestHelper
import omni.client
class TestTestHelper(omni.kit.test.AsyncTestCase):
"""Testing the test helper functions"""
async def setUp(self):
self.previous_retry_values = omni.client.set_retries(0, 0, 0)
async def tearDown(self):
omni.client.set_retries(*self.previous_retry_values)
async def test_get_item_from_tree_view(self):
"""Testing getting item from the tree view"""
dialog = FilePickerDialog("test_get_item_from_treeview", treeview_identifier="FilePicker")
await ui_test.human_delay(10)
dialog.add_connections({"ov-test": "omniverse://ov-test"})
await ui_test.human_delay(10)
async with FilePickerTestHelper(dialog._widget) as filepicker_helper:
item = await filepicker_helper.get_item_async("FilePicker", "ov-test", pane=TREEVIEW_PANE)
self.assertTrue(bool(item))
async def test_get_item_from_table_view(self):
"""Testing getting item from the list view table"""
dialog = FilePickerDialog("test_get_item_from_table_view", treeview_identifier="FilePicker")
await ui_test.human_delay(10)
dialog.add_connections({"ov-test": "omniverse://ov-test"})
await ui_test.human_delay(10)
async with FilePickerTestHelper(dialog._widget) as filepicker_helper:
await filepicker_helper.toggle_grid_view_async(False)
item = await filepicker_helper.get_item_async("FilePicker", "Omniverse", pane=TREEVIEW_PANE)
await item.click()
await ui_test.human_delay(10)
item = await filepicker_helper.get_item_async("FilePicker", "ov-test", pane=LISTVIEW_PANE)
self.assertTrue(bool(item))
async def test_get_item_from_grid_view(self):
"""Testing getting item from the list view grid"""
dialog = FilePickerDialog("test_get_item_from_grid_view", treeview_identifier="FilePicker")
await ui_test.human_delay(10)
dialog.add_connections({"ov-test": "omniverse://ov-test"})
await ui_test.human_delay(10)
async with FilePickerTestHelper(dialog._widget) as filepicker_helper:
await filepicker_helper.toggle_grid_view_async(True)
item = await filepicker_helper.get_item_async("FilePicker", "Omniverse", pane=TREEVIEW_PANE)
await item.click()
await ui_test.human_delay(10)
item = await filepicker_helper.get_item_async("FilePicker", "ov-test", pane=LISTVIEW_PANE)
self.assertTrue(bool(item))
async def test_select_single_item(self):
dialog = FilePickerDialog("test_select_single_item", treeview_identifier="FilePicker")
with TemporaryDirectory() as tmpdir_fd:
tmpdir = Path(tmpdir_fd).resolve()
temp_fd = NamedTemporaryFile(dir=tmpdir, suffix=".mdl", delete=False)
temp_fd.close()
_, filename = os.path.split(temp_fd.name)
async with FilePickerTestHelper(dialog._widget) as filepicker_helper:
await filepicker_helper.toggle_grid_view_async(True)
selections = await filepicker_helper.select_items_async(str(tmpdir), [filename])
await ui_test.human_delay()
self.assertEqual(1, len(selections))
self.assertEqual(selections[0].name, filename)
async def test_select_multiple_items(self):
dialog = FilePickerDialog("test_select_multiple_items", treeview_identifier="FilePicker")
with TemporaryDirectory() as tmpdir_fd:
tmpdir = Path(tmpdir_fd).resolve()
temp_files = []
temp_file_path_names = []
for _ in range(2):
temp_fd = NamedTemporaryFile(dir=tmpdir, suffix=".mdl", delete=False)
temp_fd.close()
temp_file_path_names.append(temp_fd.name.replace('\\', '/'))
_, filename = os.path.split(temp_fd.name)
temp_files.append(filename)
async with FilePickerTestHelper(dialog._widget) as filepicker_helper:
await filepicker_helper.toggle_grid_view_async(True)
selections = await filepicker_helper.select_items_async(str(tmpdir), temp_files)
await ui_test.human_delay()
self.assertEqual(len(selections), len(temp_files))
self.assertEqual(set([sel.name for sel in selections]), set(temp_files))
self.assertEqual(set(dialog.get_current_selections()), set(temp_file_path_names)) | 5,231 | Python | 47 | 104 | 0.665647 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/tests/test_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.
##
import omni.kit.test
import omni.kit.app
import omni.client
from datetime import datetime
from unittest.mock import patch
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit.test_suite.helpers import get_test_data_path
from ..dialog import FilePickerDialog
class MockServer:
def __init__(self, cache_enabled=False, checkpoints_enabled=False, omniojects_enabled=False, username="", version=""):
self.cache_enabled = cache_enabled
self.checkpoints_enabled = checkpoints_enabled
self.omniojects_enabled = omniojects_enabled
self.username = username
self.version = version
class MockFileEntry:
def __init__(self, relative_path="", access="", flags="", size=0, modified_time="", created_time="", modified_by="", created_by="", version=""):
self.relative_path = relative_path
self.access = access
self.flags = flags
self.size = size
self.modified_time = modified_time
self.created_time = created_time
self.modified_by = modified_by
self.created_by = created_by
self.version = version
self.comment = "<Test Node>"
class TestTimestamp(AsyncTestCase):
# Before running each test
async def setUp(self):
self._mock_server = MockServer(
cache_enabled=False,
checkpoints_enabled=True,
omniojects_enabled=True,
username="[email protected]",
version="TestServer"
)
self._mock_file_entry_0 = MockFileEntry(
access=1,
created_by="[email protected]",
created_time=datetime.now(),
flags=513,
modified_by="[email protected]",
modified_time=datetime.now(),
relative_path="&FakeCheckpoint",
size=16070,
version=12023408
)
self._mock_file_entry_1 = MockFileEntry(
access=2,
created_by="[email protected]",
created_time=datetime(2020,1,1,12,30,30),
flags=513,
modified_by="[email protected]",
modified_time=datetime(2020,1,1,12,30,30),
relative_path="&FakeCheckpoint",
size=5070,
version=12023409
)
# After running each test
async def tearDown(self):
pass
async def _mock_get_server_info_async(self, url: str):
return omni.client.Result.OK, self._mock_server
async def _mock_list_checkpoints_async(self, query: str):
return omni.client.Result.OK, [self._mock_file_entry_1, self._mock_file_entry_0]
async def test_resolve_timestamp(self):
with patch("omni.client.get_server_info_async", side_effect=self._mock_get_server_info_async),\
patch("omni.client.list_checkpoints_async", side_effect=self._mock_list_checkpoints_async):
test_path = get_test_data_path(__name__, "../icon.png")
under_test = FilePickerDialog(
"test_resolve_timestamp",
current_directory=test_path,
enable_checkpoints=True,
enable_timestamp=True,
show_grid_view=True,
)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
# enable the timestamp resolve
ts_widget = under_test._widget._timestamp_widget
ts_widget.check = True
full_path = ts_widget.get_timestamp_url(None)
self.assertTrue(full_path.find('timestamp'))
| 3,991 | Python | 36.308411 | 148 | 0.62666 |
omniverse-code/kit/exts/omni.kit.window.filepicker/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [2.7.15] - 2023-02-21
### Fixed
- Fix issue with unexpectedly filtered items.
## [2.7.14] - 2023-02-01
### Fixed
- OM-79367: Fix rename nucleus connection does not work issue.
## [2.7.13] - 2023-01-31
### Fixed
- OM-79359: Pre-fill name in field when rename nucleus connection.
## [2.7.12] - 2023-01-18
### Updated
- `navigate_to` enables `show_udim_sequence` if URL is UDIM
## [2.7.11] - 2022-12-19
### Updated
- Update toolbar widget spacer
## [2.7.10] - 2023-01-11
### Updated
- Added UDIM support
## [2.7.9] - 2022-12-20
### Updated
- Change the ComboBoxMenu's window to scrollable.
## [2.7.8] - 2022-12-12
### Updated
- Do not skip the default item filters when a custom filter is specified
## [2.7.7] - 2022-12-12
### Updated
- Fixes detail view regression
## [2.7.6] - 2022-12-08
### Updated
- Replaces omni.client.stat with async call to fix hanging app
- Refreshes the server item after a successful connection
## [2.7.4] - 2022-11-22
### Updated
- Refresh server after successfully making a connection
## [2.7.3] - 2022-11-21
### Updated
- Improve FilePickerView initialization performance on Windows
## [2.7.2] - 2022-11-08
### Updated
- Added move functionality to FilePickerModel
- Update context menu rename handling for file/folder
## [2.7.1] - 2022-11-09
### Updated
- Updated the tooltip for connection errors
## [2.6.14] - 2022-11-07
### Updated
- Add option for copy_items_with_callback to specify a destination relative path, instead of always using
the source relative path.
## [2.6.11] - 2022-11-02
### Updated
- Don't destroy search delegate.
## [2.6.9] - 2022-11-01
### Updated
- Checks for existence before connecting server
## [2.6.8] - 2022-11-01
### Updated
- Workaround for random self.view == None exception during shutdown when running tests
## [2.6.7] - 2022-10-05
### Updated
- Don't allow dialog window to be docked
## [2.6.6] - 2022-10-05
### Updated
- Fix typo
## [2.6.5] - 2022-10-03
### Updated
- Fix typo in add_bookmark menu
- Don't copy bookmark settings from carb.settings, don't destroy setings for earlier Create versions.
## [2.6.4] - 2022-09-27
### Updated
- Bookmarks stored in omni.client
## [2.6.3] - 2022-09-23
### Updated
- Don't set the warning badge for the placeholder item.
## [2.6.2] - 2022-09-20
### Updated
- Clean and reload driver when refresh ui, ensure show OV driver correctly.
## [2.6.1] - 2022-09-01
### Updated
- Reverts removal of localhost from servers list.
- Fixes flaky unittests that utilize the test helper.
## [2.6.0] - 2022-08-30
### Updated
- Refactored thumbnails provider.
## [2.5.0] - 2022-08-22
### Updated
- Moves server connection handling into separate 'nucleus_connector' extension.
## [2.4.33] - 2022-07-19
### Added
- Fixes latency in navigation.
## [2.4.32] - 2022-07-13
### Added
- Minor fixes.
## [2.4.31] - 2022-07-07
### Added
- Adds UI ready event
- Catches exceptions from delayed function calls; often raised by unit tests where the dialog is rapidly being created and destroyed.
## [2.4.30] - 2022-05-27
### Added
- Updated unit of file size to Mebibyte (instead of Megabyte)
## [2.4.29] - 2022-05-12
### Added
- Ensures add server popup is displayed within window
## [2.4.27] - 2022-04-19
### Added
- Fixes navigating to url that contains Url-encoded characters.
- Adds async versions to navigate_to and find_item functions.
- Adds select_items function to facilitate unittests.
## [2.4.26] - 2022-04-18
### Added
- Limits extent that splitter can be dragged, to prevent breaking.
## [2.4.25] - 2022-04-12
### Added
- Adds splitter to adjust width of detail pane.
## [2.4.24] - 2022-04-06
### Added
- Disable unittests from loading at startup.
## [2.4.23] - 2022-04-04
### Updated
- Fixes fullpath of filename when file selected from treeview.
## [2.4.22] - 2022-03-31
### Updated
- Removed toml setting for enabling checkpoint, passed in a kwarg instead.
- Fixed destructor for DetailDelegate.
## [2.4.21] - 2022-03-18
### Updated
- Updates search results when directory changed.
## [2.4.20] - 2022-03-14
### Updated
- Adds extended file info into detail view.
- Refactored handling of asset type.
## [2.4.18] - 2022-03-07
### Updated
- Adds custom search delegate.
## [2.4.17] - 2022-03-07
### Updated
- Added postfix name thumbnails and icons.
## [2.4.16] - 2022-02-07
### Updated
- Fixes options_pane_build_fn regression due to detail view refactoring.
## [2.4.15] - 2021-11-30
### Updated
- Introduced DetailFrameController to simplify API for adding detail frame.
## [2.4.14] - 2021-11-24
### Updated
- Added `show_grid_view` to get grid or table view.
## [2.4.13] - 2021-11-03
### Updated
- Added search box, which combines the best features from Asset Browser and Content Browser.
## [2.4.12] - 2021-11-01
### Updated
Cleaned up message dialogs in FilePickerView, fixed unittest errors.
## [2.4.11] - 2021-10-27
### Updated
- Added notification on connection error.
## [2.4.10] - 2021-10-20
### Updated
- Don't return paths with windows slash
## [2.4.9] - 2021-09-17
### Updated
- Added widget identifers
## [2.4.8] - 2021-09-17
### Updated
- Updated "Add Connection" interaction to be more intuitive.
## [2.4.7] - 2021-09-16
### Updated
- Add API to configure name label for file bar.
## [2.4.6] - 2021-08-20
### Updated
- Added UI stress test for auto-refreshing current directory when adding and deleting many files in quick succession.
## [2.4.5] - 2021-08-04
### Updated
- Fixed get_filename API.
## [2.4.4] - 2021-07-20
### Updated
- Fixes checkpoint selection
## [2.4.3] - 2021-07-13
### Updated
- Added "enable_checkpoints" setting to toml file to enable checkpoints everywhere
## [2.4.2] - 2021-07-13
### Updated
- Fixed destructor bug causing calls to init_view with invalid object instances
## [2.4.1] - 2021-07-12
### Updated
- Added detail view and corresponding menu item in combox box to active/deactivate it
- Added API methods for adding custom frames to detail view
- Moved checkpoint panel to detail view
- Updated look of file bar
## [2.3.11] - 2021-06-23
### Updated
- Pass `open_file` function to omni.kit.widget.versioning
## [2.3.10] - 2021-06-21
### Updated
- Always show "Create Checkpoint" context menu option when server supported
## [2.3.9] - 2021-06-18
### Updated
- Persist the width of the versioning panel
## [2.3.8] - 2021-06-09
### Updated
- When local windows path not found, doesn't try to connect to it.
## [2.3.7] - 2021-06-16
### Updated
- More graceful cancellation of navigation futures.
## [2.3.6] - 2021-06-09
### Updated
- Added stronger checkpoint overwrite messages
## [2.3.5] - 2021-06-10
- Always show versioning pane when enabled
## [2.3.4] - 2021-06-08
- Fixes window resize messes up versioning splitter bar.
- Relocates zoom bar out of versioning panel.
## [2.3.3] - 2021-06-07
### Updated
- Added splitter bar for resizing checkpoints panel.
- Refactored checkpoints panel and zoom bar into FilePickerView widget.
- More thorough destruction of class instances upon shutdown.
## [2.3.2] - 2021-06-04
### Updated
- Added optional message parameter to `ConfirmItemDeletionDialog` so it can be used for overrite too
## [2.3.1] - 2021-06-01
### Updated
- Eliminates manually initiated refresh of the UI when creating new folder and deleting items; these conflict with the new auto refresh.
## [2.3.0] - 2021-05-11
### Added
- Added support for `ENTER` and `ESC` keys.
- Added support for creating new empty USD files through the "New USD File" contextual menu.
- Added support for opening the browser location using the operating system's file explorer through the "Open in File Browser" contextual menu.
- Added ability to select checkpoints from the contextual menu.
## [2.2.1] - 2021-04-09
### Changed
- Show <head> entry in versioning pane.
## [2.2.0] - 2021-03-23
### Added
- Added optional versioning pane on supported server (only when omni.kit.widget.versioning is enabled) and `enable_versioning_pane` constructor parameter to enable/disable it.
- Added `Options` pane to the right of file picker. Can be enabled by passing `options_pane_build_fn` and provide custom UI build function.
## [2.1.3] - 2021-02-16
### Updated
- Fixes thumbnails for search model.
## [2.1.2] - 2021-02-10
### Changes
- Updated StyleUI handling
## [2.1.1] - 2021-02-09
### Updated
- Fixed navigation slowness caused by processing of thumbnails.
- Uses auto thumbnails generated by deeptag if manual thumbnails not available.
## [2.1.0] - 2021-02-04
### Added
- Extracted ZoomBar into its own widget.
## [2.0.1] - 2021-02-03
### Updated
- Refactored code for getting auto-generated thumbnails. The simplification allowed for easier testing.
- Fixed bug that was causing artifacts and mismatched thumbnails in grid view
### Added
- Unittests for navigating directories
- Unittests for persistent settings
- Unittests for asset types
## [2.0.0] - 2021-01-03
### Updated
- Refactored for async directory listing to improve overall stability in case of network delays.
## [1.3.10] - 2020-12-10
### Updated
- Detects bad server connections before opening files
- Removes callback from 'navigate_to' API
## [1.3.9] - 2020-12-05
### Updated
- Adds 'reconnect server' action to context menu
## [1.3.8] - 2020-12-03
### Updated
- Adds ability to rename connections and bookmarks
## [1.3.7] - 2020-12-01
### Updated
- Correctly resolves connections whose label names differ their path names
## [1.3.6] - 2020-11-26
### Updated
- Defaults browser bar to display real path
## [1.3.5] - 2020-11-25
### Updated
- Code refactor: Consolidates ListViewMenu into ContextMenu and eliminates PopupMenu base class.
## [1.3.4] - 2020-11-23
### Updated
- Double clicking on item immediately executes apply callback.
## [1.3.3] - 2020-11-20
### Updated
- Allows multi-selection deletion.
## [1.3.2] - 2020-11-19
### Updated
- Context menu responds to multi-selection actions.
## [1.3.1] - 2020-11-13
### Added
- Fixes multi-selection and added option to turn off file bar.
- Keeps connections and bookmarks between content browser and filepicker in sync.
- Scrolls to a given path upon showing dialog.
## [1.3.0] - 2020-10-31
### Added
- Now able to resolve URL paths pasted into the browser bar
## [1.2.0] - 2020-10-29
### Added
- User folders in "my-computer" collection
## [1.1.0] - 2020-10-27
### Added
- Ported context menu from omni.kit.window.content_browser.
- Consolidated API methods into api module.
- Correctly process persistent settings for connections and bookmarks.
- Display svg files as their own thumbnails.
## [0.1.5] - 2020-09-16
### Added
- Initial commit to master.
| 10,697 | Markdown | 25.678304 | 175 | 0.701412 |
omniverse-code/kit/exts/omni.kit.window.filepicker/docs/README.md | # Kit FilePicker Window [omni.kit.window.filepicker]
This Kit extension provides both a popup dialog as well as an embeddable widget that
you can add to your code for browsing the filesystem.
| 194 | Markdown | 37.999992 | 85 | 0.798969 |
omniverse-code/kit/exts/omni.kit.window.filepicker/docs/index.rst | omni.kit.window.filepicker
###########################
Kit Filepicker Dialog and embeddable Widget.
.. toctree::
:maxdepth: 1
CHANGELOG
.. automodule:: omni.kit.window.filepicker
:platform: Windows-x86_64, Linux-x86_64
:members:
:show-inheritance:
:undoc-members:
.. autoclass:: FilePickerDialog
:members:
.. autoclass:: FilePickerWidget
:members:
.. autoclass:: FilePickerView
:members:
.. autoclass:: FilePickerModel
:members:
.. autoclass:: FilePickerAPI
:members:
.. autoclass:: ContextMenu
:members:
.. autoclass:: ToolBar
:members:
.. autoclass:: DetailView
:members:
.. autoclass:: DetailFrameController
:members:
| 765 | reStructuredText | 16.409091 | 44 | 0.588235 |
omniverse-code/kit/exts/omni.kit.collaboration.viewport.camera/config/extension.toml | [package]
title = "Viewport Widget: Camera Name"
description = "The viewport widget that displays camera name of users joined the same stage."
version = "2.0.2"
changelog = "docs/CHANGELOG.md"
readme = "docs/README.md"
category = "Collaboration"
feature = true
# URL of the extension source repository.
repository = ""
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
[dependencies]
"omni.usd" = {}
"omni.ui" = {}
"omni.ui.scene" = {}
"omni.kit.usd.layers" = {}
"omni.kit.collaboration.channel_manager" = {}
"omni.kit.notification_manager" = {}
"omni.kit.viewport.utility" = {}
[[python.module]]
name = "omni.kit.collaboration.viewport.camera"
[settings]
# 0 to turn this experimental off. 3 is a resonable number for rtx
exts."omni.kit.collaboration.viewport.camera".visual.delayFrame = 3
[[test]]
waiver = "Tested skipped for now as it involves with multiple Kit instances with Nucleus."
| 1,322 | TOML | 29.767441 | 118 | 0.734493 |
omniverse-code/kit/exts/omni.kit.collaboration.viewport.camera/omni/kit/collaboration/viewport/camera/peer_user_shared_data.py | import asyncio
import carb
import omni.usd
import omni.kit.app
import omni.kit.usd.layers as layers
import omni.kit.notification_manager as nm
import omni.kit.collaboration.presence_layer as pl
from pxr import Sdf, Usd, Tf, UsdGeom
from .manipulator import PeerUserCamera
from .local_user_shared_data import LocalUserSharedData
from omni.kit.viewport.utility import get_active_viewport_window
class PeerUserSharedData:
"""
It works to manage peer user's live camera inside users.live and camera label widget.
"""
def __init__(
self, usd_context: omni.usd.UsdContext,
user_info: layers.LiveSessionUser,
local_user_shared_data: LocalUserSharedData
):
self.user_info = user_info
self.usd_context = usd_context
self.presence_layer = pl.get_presence_layer_interface(self.usd_context)
# It's used to control the status of followed user.
self.__local_user_shared_data = local_user_shared_data
self.__camera_viewport_widget: PeerUserCamera = None
self.__current_bound_camera_path = Sdf.Path.emptyPath
self.__task_or_future = None
self.__followed = False
@property
def user_id(self):
return self.user_info.user_id
@property
def user_name(self):
return self.user_info.user_name
def destroy(self):
self.followed = False
self.usd_context = None
self.destroy_camera_widget()
self.__local_user_shared_data = None
if self.__task_or_future:
self.__task_or_future.cancel()
self.__task_or_future = None
def check_and_switch_widget_mode(self, viewport_camera_position=None):
"""Update widget to check if it's out of viewport and show offscreen pointers instead."""
if self.__camera_viewport_widget:
self.__camera_viewport_widget.on_view_translation_changed(viewport_camera_position)
@property
def widget_position(self):
if self.__camera_viewport_widget:
return self.__camera_viewport_widget.position
return None
@property
def is_bound_to_builtin_camera(self):
"""If this user is bound to builtin camera, or prim in the local stage."""
return self.presence_layer.is_bound_to_builtin_camera(self.user_id)
@property
def bound_camera_prim(self) -> Usd.Prim:
"""
It will return the prim path in the local stage if property `is_bound_to_builtin_camera` is False.
Or the replicated camera path in the session layer of local stage if it's bound to builtin camera.
"""
return self.presence_layer.get_bound_camera_prim(self.user_id)
def destroy_camera_widget(self):
if self.__camera_viewport_widget:
self.__camera_viewport_widget.destroy()
self.__camera_viewport_widget = None
def update_camera_widget_label(self, position=None):
if self.__camera_viewport_widget:
self.__camera_viewport_widget.on_world_translation_changed(position)
def refresh_camera_widget(self, update_widget_label=True):
if self.presence_layer.is_in_following_mode(self.user_id):
self.destroy_camera_widget()
return
is_bound_to_builtin_camera = self.is_bound_to_builtin_camera
bound_camera_prim = self.bound_camera_prim
if not bound_camera_prim:
bound_camera_path = Sdf.Path.emptyPath
else:
bound_camera_path = bound_camera_prim.GetPath()
bound_camera_changed = self.__current_bound_camera_path != bound_camera_path
if bound_camera_changed:
# Unhide old tracked camera
if self.__followed:
self.__set_display_name_and_lock(self.__current_bound_camera_path, True)
self.__current_bound_camera_path = bound_camera_path
if not is_bound_to_builtin_camera and bound_camera_prim and self.__followed:
self.__set_display_name_and_lock(bound_camera_path, False)
if not bound_camera_prim:
self.followed = False
elif self.__followed:
self.__switch_viewport_bound_camera(bound_camera_path, True)
if not bound_camera_prim:
self.destroy_camera_widget()
return
# Don't show label widget for followed user
if not self.__followed:
if not self.__camera_viewport_widget:
self.__camera_viewport_widget = PeerUserCamera(self.user_info, bound_camera_path, self.usd_context)
elif bound_camera_changed:
self.__camera_viewport_widget.set_tracked_camera(bound_camera_path)
elif update_widget_label:
self.__camera_viewport_widget.on_world_translation_changed()
@property
def following_user_id(self):
return self.presence_layer.get_following_user_id(self.user_id)
@property
def followed(self):
return self.__followed
@followed.setter
def followed(self, value):
if value == self.__followed:
return
bound_camera_prim = self.bound_camera_prim
if value and not bound_camera_prim:
return
elif bound_camera_prim:
camera_prim_path = bound_camera_prim.GetPath()
else:
camera_prim_path = Sdf.Path.emptyPath
if value and self.following_user_id:
carb.log_warn(f"Cannot follow user {self.user_name} as the user is following other user already.")
return
if not self.is_bound_to_builtin_camera and camera_prim_path:
self.__set_display_name_and_lock(camera_prim_path, not value)
self.__switch_viewport_bound_camera(camera_prim_path, value)
def __switch_viewport_bound_camera(self, camera_path, followed):
viewport_window = get_active_viewport_window()
viewport_api = viewport_window.viewport_api
if followed:
if self.presence_layer.enter_follow_mode(self.user_id):
self.destroy_camera_widget()
self.__followed = True
self.__local_user_shared_data.following_user_id = self.user_id
viewport_api.camera_path = str(camera_path)
self.__local_user_shared_data.update_viewport_bound_camera(False)
else:
self.__local_user_shared_data.following_user_id = None
self.__followed = False
self.presence_layer.quit_follow_mode()
# Changes it to perspective camera if user is unfollowed.
viewport_api.camera_path = "/OmniverseKit_Persp"
self.__local_user_shared_data.update_viewport_bound_camera(True)
self.refresh_camera_widget(False)
def __set_display_name_and_lock(self, camera_path, clear):
if not camera_path:
return
stage = self.usd_context.get_stage()
prim = stage.GetPrimAtPath(camera_path)
if not prim:
return
with Sdf.ChangeBlock():
with Usd.EditContext(stage, stage.GetSessionLayer()):
if clear:
omni.usd.editor.set_display_name(prim, None)
prim.RemoveProperty("omni:kit:cameraLock")
else:
omni.usd.editor.set_display_name(prim, self.user_name)
prim.CreateAttribute("omni:kit:cameraLock", Sdf.ValueTypeNames.Bool).Set(True)
| 7,557 | Python | 37.561224 | 115 | 0.620087 |
omniverse-code/kit/exts/omni.kit.collaboration.viewport.camera/omni/kit/collaboration/viewport/camera/utils.py | import carb
import omni.kit.commands
import omni.kit.undo
from pxr import Sdf, Usd, UsdGeom
from omni.kit.viewport.utility import get_active_viewport_window, get_active_viewport_camera_path
class CarbProfilerScope: # pragma: no cover
def __init__(self, id, name):
self._id = id
self._name = name
def __enter__(self):
carb.profiler.begin(self._id, self._name)
def __exit__(self, type, value, trace):
carb.profiler.end(self._id)
def get_viewport_fps():
viewport_window = get_active_viewport_window()
if viewport_window:
viewport_api = viewport_window.viewport_api
return viewport_api.frame_info.get("fps")
return 0
def get_viewport_bound_camera_position(stage: Usd.Stage):
active_camera_path = get_active_viewport_camera_path()
camera = stage.GetPrimAtPath(active_camera_path)
if not camera:
return None
xformable = UsdGeom.Xformable(camera)
transform = xformable.ComputeLocalToWorldTransform(Usd.TimeCode.Default())
return transform.ExtractTranslation()
def switch_viewport_bound_camera_to_persp():
viewport_window = get_active_viewport_window()
if viewport_window:
viewport_api = viewport_window.viewport_api
else:
viewport_api = None
if not viewport_api:
return
with omni.kit.undo.disabled():
omni.kit.commands.execute("SetViewportCameraCommand", camera_path="/OmniverseKit_Persp", viewport_api=viewport_api)
| 1,483 | Python | 26.481481 | 123 | 0.689818 |
omniverse-code/kit/exts/omni.kit.collaboration.viewport.camera/omni/kit/collaboration/viewport/camera/stage_listener.py | import asyncio
import carb
import time
import omni.client
import omni.usd
import omni.kit.app as app
import omni.kit.usd.layers as layers
import omni.kit.viewport.menubar.camera as viewport_camera_menu
import omni.ui as ui
import omni.kit.notification_manager as nm
import omni.kit.collaboration.presence_layer as pl
from omni.kit.viewport.menubar.core import ViewportMenuDelegate
from pxr import Sdf, Usd, UsdGeom, Tf, Trace
from typing import Dict
from functools import partial
from .utils import get_viewport_fps, get_viewport_bound_camera_position, switch_viewport_bound_camera_to_persp
from .local_user_shared_data import LocalUserSharedData
from .peer_user_shared_data import PeerUserSharedData
from .peer_user_menu_item import PeerUserMenuItem, NoPeerUserMenuItem
from .menubar_camera_widget_delegate import (
MenuBarLiveSessionCameraFollowerButtonDelegate,
MenuBarLiveSessionCameraFollowerMenuItemDelegate
)
UPDATE_DELAY_FRAME_SETTING = "/exts/omni.kit.collaboration.viewport.camera/visual/delayFrame"
class StageListener:
def __init__(self, usd_context_name=""):
self.__usd_context = omni.usd.get_context(usd_context_name)
self.__live_syncing = layers.get_live_syncing(self.__usd_context)
self.__layers = layers.get_layers(self.__usd_context)
self.__app = app.get_app()
self.__settings = carb.settings.get_settings()
self.__update_subscription = None
self.__layers_event_subscriptions = []
self.__local_stage_objects_changed = None
self.__peer_users: Dict[str, PeerUserSharedData] = {}
self.__my_shared_data: LocalUserSharedData = None
self.__pending_local_bound_camera_changes = False
self.__pending_changed_user_ids = set()
self.__delay_dirty_tasks_or_futures = {}
self.__last_viewport_camera_position = None
# Key is the id of the viewport
self.__follow_user_menu_collections = {}
self.__last_time_in_seconds_to_broadcast_builtin_camera = 0
self.__menubar_camera_button_delegate = MenuBarLiveSessionCameraFollowerButtonDelegate()
self.__menubar_camera_menu_item_delegate = MenuBarLiveSessionCameraFollowerMenuItemDelegate()
self.__entering_or_quitting_follow_mode = False
self.__follow_user_menu_registered = False
def start(self):
for event in [
layers.LayerEventType.LIVE_SESSION_STATE_CHANGED,
layers.LayerEventType.LIVE_SESSION_USER_JOINED,
layers.LayerEventType.LIVE_SESSION_USER_LEFT,
pl.PresenceLayerEventType.BOUND_CAMERA_CHANGED,
pl.PresenceLayerEventType.BOUND_CAMERA_PROPERTIES_CHANGED,
pl.PresenceLayerEventType.BOUND_CAMERA_RESYNCED,
pl.PresenceLayerEventType.LOCAL_FOLLOW_MODE_CHANGED
]:
layers_event_sub = self.__layers.get_event_stream().create_subscription_to_pop_by_type(
event, self.__on_layers_event, name=f"omni.kit.collaboration.viewport.camera {str(event)}"
)
self.__layers_event_subscriptions.append(layers_event_sub)
stage_url = self.__usd_context.get_stage_url()
if not stage_url.startswith("omniverse:"):
return
self.__on_session_state_changed()
def __start_subscription(self):
current_session = self.__live_syncing.get_current_live_session()
if not current_session:
return
if not current_session.logged_user_name or not current_session.logged_user_id:
carb.log_error(f"Failed to track users camera as no logged username/id is detected.")
return
self.__local_stage_objects_changed = Tf.Notice.Register(
Usd.Notice.ObjectsChanged, self.__on_local_usd_changed, self.__usd_context.get_stage()
)
# OMFP-1986: All users will join session with persp camera.
switch_viewport_bound_camera_to_persp()
self.__last_viewport_camera_position = get_viewport_bound_camera_position(self.__usd_context.get_stage())
self.__my_shared_data = LocalUserSharedData(
self.__usd_context,
current_session.logged_user_name,
current_session.logged_user_id
)
self.__my_shared_data.broadcast_local_changes()
for peer_user in current_session.peer_users:
self.__track_new_user(peer_user.user_id)
self.__update_subscription = self.__app.get_update_event_stream().create_subscription_to_pop(
self.__on_update, name="omni.kit.collaboration.viewport.camera update"
)
self.__stage_subscription = self.__usd_context.get_stage_event_stream().create_subscription_to_pop(
self.__on_stage_event, name="omni.kit.collaboration.viewport.camera stage event"
)
def __on_stage_event(self, event):
if event.type == int(omni.usd.StageEventType.CLOSING):
self.__stop_subscription()
def __stop_subscription(self):
if self.__peer_users:
for _, camera_info in self.__peer_users.items():
camera_info.destroy()
self.__peer_users.clear()
self.__pending_local_bound_camera_changes = False
self.__pending_changed_user_ids.clear()
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_subscription = None
self.__stage_subscription = None
if self.__my_shared_data:
self.__my_shared_data.destroy()
self.__my_shared_data = None
if self.__local_stage_objects_changed:
self.__local_stage_objects_changed.Revoke()
self.__local_stage_objects_changed = None
self.__deregister_follow_user_menu()
self.__last_time_in_seconds_to_broadcast_builtin_camera = 0
def stop(self):
self.__stop_subscription()
self.__layers_event_subscriptions = []
if self.__menubar_camera_button_delegate:
self.__menubar_camera_button_delegate.destroy()
self.__menubar_camera_button_delegate = None
if self.__menubar_camera_menu_item_delegate:
self.__menubar_camera_menu_item_delegate.destroy()
self.__menubar_camera_menu_item_delegate = None
# 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.
@Trace.TraceFunction
@carb.profiler.profile
async def __delay_dirty(self, changed_user_ids, update_id, camera_positions_before_delay):
fps = get_viewport_fps()
delay_frames = self.__settings.get(UPDATE_DELAY_FRAME_SETTING)
if fps:
render_frame_time = 1.0 / fps * delay_frames
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 < update_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)
for user_id in changed_user_ids:
peer_user = self.__peer_users.get(user_id, None)
if peer_user:
position = camera_positions_before_delay.get(user_id, None)
peer_user.update_camera_widget_label(position)
self.__delay_dirty_tasks_or_futures.pop(update_id)
def __is_path_properties_affected(self, notice, path):
changed_info_only_paths = notice.GetChangedInfoOnlyPaths()
slice_object = Sdf.Path.FindPrefixedRange(changed_info_only_paths, path)
if not slice_object:
return False
paths = changed_info_only_paths[slice_object]
return True if paths else False
@Trace.TraceFunction
@carb.profiler.profile
def __on_local_usd_changed(self, notice, sender):
stage = self.__usd_context.get_stage()
if not sender or sender != stage or not self.__my_shared_data:
return
local_bound_camera_path = self.__my_shared_data.bound_camera_path
if not local_bound_camera_path:
return
bound_camera = stage.GetPrimAtPath(local_bound_camera_path)
if not bound_camera:
return
if self.__pending_local_bound_camera_changes:
return
if notice.ResyncedObject(bound_camera) or self.__is_path_properties_affected(notice, local_bound_camera_path):
self.__pending_local_bound_camera_changes = True
else:
# If peer users are bound to non-builtin cameras, and they are changed locally.
# The camera label needs to be updated, too.
for user_id, peer_user in self.__peer_users.items():
if peer_user.is_bound_to_builtin_camera:
continue
camera_prim = peer_user.bound_camera_prim
if not camera_prim:
peer_user.destroy_camera_widget()
continue
# Adds it into resynced last although it only updates camera label since it's bound
# to non-builtin camera.
camera_path = camera_prim.GetPath()
if notice.ResyncedObject(camera_prim) or self.__is_path_properties_affected(notice, camera_path):
self.__pending_changed_user_ids.add(user_id)
def __on_session_state_changed(self):
if not self.__live_syncing.is_in_live_session():
self.__stop_subscription()
else:
self.__register_follow_user_menu()
self.__start_subscription()
def __track_new_user(self, user_id):
if user_id in self.__peer_users:
return
current_session = self.__live_syncing.get_current_live_session()
if not current_session:
return
user_info = current_session.get_peer_user_info(user_id)
if not user_info:
return
peer_user = PeerUserSharedData(
self.__usd_context,
user_info,
self.__my_shared_data
)
self.__peer_users[user_id] = peer_user
peer_user.refresh_camera_widget()
# Uses cached viewport camera position to avoid gettting viewport camera pos for each camera,
# which is very slow.
peer_user.check_and_switch_widget_mode(self.__last_viewport_camera_position)
def __untrack_user(self, user_id):
peer_user = self.__peer_users.pop(user_id, None)
if peer_user:
peer_user.followed = False
peer_user.destroy()
def __on_layers_event(self, event):
payload = layers.get_layer_event_payload(event)
if not payload:
return
if payload.event_type == layers.LayerEventType.LIVE_SESSION_STATE_CHANGED:
if not payload.is_layer_influenced(self.__usd_context.get_stage_url()):
return
self.__on_session_state_changed()
elif payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_JOINED:
if not payload.is_layer_influenced(self.__usd_context.get_stage_url()):
return
self.__track_new_user(payload.user_id)
elif payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_LEFT:
if not payload.is_layer_influenced(self.__usd_context.get_stage_url()):
return
self.__untrack_user(payload.user_id)
else:
payload = pl.get_presence_layer_event_payload(event)
if not payload.event_type:
return
if (
payload.event_type == pl.PresenceLayerEventType.BOUND_CAMERA_CHANGED or
payload.event_type == pl.PresenceLayerEventType.BOUND_CAMERA_PROPERTIES_CHANGED or
payload.event_type == pl.PresenceLayerEventType.BOUND_CAMERA_RESYNCED
):
self.__pending_changed_user_ids.update(payload.changed_user_ids)
elif payload.event_type == pl.PresenceLayerEventType.LOCAL_FOLLOW_MODE_CHANGED:
if self.__entering_or_quitting_follow_mode:
return
self.__entering_or_quitting_follow_mode = True
try:
following_user_id = self.__my_shared_data.presence_layer.get_following_user_id()
if following_user_id and following_user_id == self.__my_shared_data.following_user_id:
return
# Unfollow previous user
current_followed_user = self.__peer_users.get(self.__my_shared_data.following_user_id, None)
if current_followed_user:
current_followed_user.followed = False
self.__pending_changed_user_ids.add(self.__my_shared_data.following_user_id)
if following_user_id:
self.__follow_user(following_user_id)
finally:
self.__entering_or_quitting_follow_mode = False
@Trace.TraceFunction
@carb.profiler.profile
def __on_update(self, dt):
if not self.__live_syncing.is_in_live_session():
return
current_time = time.monotonic()
duration = current_time - self.__last_time_in_seconds_to_broadcast_builtin_camera
# Update camera pos in 30fps for now
if duration < 0.03:
return
self.__last_time_in_seconds_to_broadcast_builtin_camera = current_time
# FIXME: Delay one frame to try to keep pace ui.scene and geometry rendering,
# although it's not ideal for only 1 frame.
all_changed_user_ids = set()
if self.__pending_changed_user_ids:
all_changed_user_ids.update(self.__pending_changed_user_ids)
delay_frame = self.__settings.get(UPDATE_DELAY_FRAME_SETTING) != 0
camera_positions_before_delay = {}
for user_id in self.__pending_changed_user_ids:
peer_user = self.__peer_users.get(user_id, None)
if not peer_user:
continue
# It will not update camera label when it's to delay frames.
peer_user.refresh_camera_widget(not delay_frame)
if delay_frame:
camera_positions_before_delay[user_id] = peer_user.widget_position
self.__pending_changed_user_ids.clear()
if delay_frame:
update_id = self.__app.get_update_number()
try:
# run_coroutine only works for Kit 105 or above.
from omni.kit.async_engine import run_coroutine
task_or_future = run_coroutine(
self.__delay_dirty(all_changed_user_ids, update_id, camera_positions_before_delay)
)
except ImportError:
# Fallback to asyncio if run_coroutine cannot be imported.
task_or_future = asyncio.ensure_future(
self.__delay_dirty(all_changed_user_ids, update_id, camera_positions_before_delay)
)
self.__delay_dirty_tasks_or_futures[update_id] = task_or_future
if self.__my_shared_data and self.__my_shared_data.update_viewport_bound_camera():
user_id = self.__my_shared_data.following_user_id
if user_id:
followed_user = self.__peer_users.get(user_id, None)
if followed_user:
followed_user.followed = False
self.__pending_local_bound_camera_changes = True
elif self.__my_shared_data.update_viewport_size():
self.__pending_local_bound_camera_changes = True
if self.__pending_local_bound_camera_changes:
self.__last_viewport_camera_position = get_viewport_bound_camera_position(self.__usd_context.get_stage())
local_bound_camera_path = self.__my_shared_data.bound_camera_path
if not local_bound_camera_path:
return
for user_id, peer_user in self.__peer_users.items():
if user_id in all_changed_user_ids:
continue
peer_user.check_and_switch_widget_mode(self.__last_viewport_camera_position)
try:
self.__my_shared_data.broadcast_local_changes()
finally:
self.__pending_local_bound_camera_changes = False
def __build_cameras(self, viewport_api, ui_shown: bool):
"""Build the menu with the list of the users"""
current_session = self.__live_syncing.get_current_live_session()
if not current_session:
return
follow_user_menu_collection = self.__follow_user_menu_collections.get(viewport_api.id, None)
if not follow_user_menu_collection:
return
follow_user_menu_collection.clear()
if ui_shown:
with follow_user_menu_collection:
if current_session.peer_users:
for peer_user in current_session.peer_users:
item = PeerUserMenuItem(
peer_user,
lambda user: self.__follow_user(user.user_id)
)
followed = peer_user.user_id == self.__my_shared_data.following_user_id
item.set_checked(followed)
else:
NoPeerUserMenuItem()
def __follow_user(self, user_id):
peer_user = self.__peer_users.get(user_id, None)
if not peer_user:
return
following_user_id = peer_user.following_user_id
following_user = self.__peer_users.get(following_user_id, None)
if following_user:
if following_user_id == self.__my_shared_data.user_id:
user_name = "me"
else:
user_name = following_user.user_name
nm.post_notification(
f"Cannot follow user {peer_user.user_name} as the user is following {user_name}.",
status=nm.NotificationStatus.WARNING
)
return
if not peer_user.bound_camera_prim:
nm.post_notification(
f"Cannot follow user {peer_user.user_info.user_name} as the user has invalid bound camera.",
status=nm.NotificationStatus.WARNING
)
return
# Unfollow previous user
current_followed_user = self.__peer_users.get(self.__my_shared_data.following_user_id, None)
if current_followed_user:
current_followed_user.followed = False
self.__pending_changed_user_ids.add(self.__my_shared_data.following_user_id)
if peer_user != current_followed_user:
peer_user.followed = True
def __build_follow_user_menu(self, viewport_context, root: ui.Menu):
viewport_api = viewport_context.get("viewport_api")
follow_user_menu_collection = ui.MenuItemCollection(
"Follow User",
checkable=True,
delegate=ViewportMenuDelegate(),
shown_changed_fn=partial(self.__build_cameras, viewport_api),
hide_on_click=False
)
self.__follow_user_menu_collections[viewport_api.id] = follow_user_menu_collection
def __register_follow_user_menu(self):
def is_follow_enabled():
settings = carb.settings.get_settings()
enabled = settings.get(f"/app/liveSession/enableMenuFollowUser")
if enabled == True or enabled == False:
return enabled
return True
if not is_follow_enabled() or self.__follow_user_menu_registered:
return
self.__follow_user_menu_registered = True
instance = viewport_camera_menu.get_instance()
instance.register_menu_item(self.__build_follow_user_menu, order=-2)
def __deregister_follow_user_menu(self):
if not self.__follow_user_menu_registered:
return
self.__follow_user_menu_registered = False
instance = viewport_camera_menu.get_instance()
instance.deregister_menu_item(self.__build_follow_user_menu)
self.__follow_user_menu_collections.clear()
| 20,858 | Python | 40.142012 | 118 | 0.60653 |
omniverse-code/kit/exts/omni.kit.collaboration.viewport.camera/omni/kit/collaboration/viewport/camera/local_user_shared_data.py | import carb
import omni.usd
import omni.kit.usd.layers as layers
import omni.kit.collaboration.presence_layer as pl
from pxr import Usd, Sdf
from omni.kit.viewport.utility import get_active_viewport_camera_path, get_active_viewport_window
class LocalUserSharedData:
def __init__(self, usd_context: omni.usd.UsdContext, user_name: str, user_id: str):
self.usd_context = usd_context
self.presence_layer = pl.get_presence_layer_interface(self.usd_context)
self.user_name = user_name
self.user_id = user_id
self.__current_bound_camera_path = None
self.__last_viewport_width = 0
self.__last_viewport_height = 0
self.__following_user_id = None
self.update_viewport_bound_camera()
def destroy(self):
self.presence_layer = None
self.usd_context = None
self.__following_user_id = None
@property
def following_user_id(self):
return self.__following_user_id
@following_user_id.setter
def following_user_id(self, value):
self.__following_user_id = value
@property
def bound_camera_path(self) -> Sdf.Path:
return self.__current_bound_camera_path
def update_viewport_bound_camera(self, broadcast=True) -> bool:
active_camera_path = get_active_viewport_camera_path()
if active_camera_path and self.__current_bound_camera_path != active_camera_path:
self.__set_bound_camera_path(active_camera_path, broadcast)
return True
return False
def update_viewport_size(self) -> bool:
viewport_window = get_active_viewport_window()
if viewport_window:
frame = viewport_window.frame
if (
self.__last_viewport_width != frame.computed_width
or self.__last_viewport_height != frame.computed_height
):
self.__last_viewport_width = frame.computed_width
self.__last_viewport_height = frame.computed_height
return True
return False
def broadcast_local_changes(self):
if not self.__current_bound_camera_path or self.__following_user_id:
return
self.presence_layer.broadcast_local_bound_camera(self.__current_bound_camera_path)
def __set_bound_camera_path(self, bound_camera_path, broadcast=True):
self.__current_bound_camera_path = bound_camera_path
# Clear bound camera as user it not bound to any cameras but following other users.
if self.__following_user_id:
camera_path = ""
else:
camera_path = bound_camera_path
if broadcast:
self.presence_layer.broadcast_local_bound_camera(camera_path)
| 2,739 | Python | 32.414634 | 97 | 0.637824 |
omniverse-code/kit/exts/omni.kit.collaboration.viewport.camera/omni/kit/collaboration/viewport/camera/menubar_camera_widget_delegate.py | __all__ = ["MenuBarLiveSessionCameraFollowerButtonDelegate", "MenuBarLiveSessionCameraFollowerMenuItemDelegate"]
import omni.ui as ui
from omni.kit.viewport.menubar.camera import AbstractCameraButtonDelegate, AbstractCameraMenuItemDelegate
from omni.kit.widget.live_session_management import LiveSessionCameraFollowerList
from pxr import Sdf
from typing import Optional
class MenuBarLiveSessionCameraFollowerBaseDelegate:
def __init__(self):
super().__init__()
self.__all_follower_widgets = {}
def build_widget_with_option(
self, parent_id, viewport_api, camera_path, camera_button_or_menu_item
) -> Optional[ui.Widget]:
widget = ui.VStack(width=0)
with widget:
ui.Spacer()
follower_widget = LiveSessionCameraFollowerList(
viewport_api.usd_context, camera_path,
show_my_following_users=camera_button_or_menu_item
)
ui.Spacer()
old_widget = self.__all_follower_widgets.pop(parent_id, None)
if old_widget:
old_widget.destroy()
self.__all_follower_widgets[parent_id] = follower_widget
return widget
def on_camera_path_changed(self, parent_id, new_camera_path: Sdf.Path):
follower_widget = self.__all_follower_widgets.get(parent_id, None)
if follower_widget:
follower_widget.track_camera(new_camera_path)
def on_parent_destroyed(self, parent_id):
follower_widget = self.__all_follower_widgets.get(parent_id, None)
if follower_widget:
follower_widget.on_parent_destroyed()
def destroy(self):
for follower_widget in self.__all_follower_widgets.values():
follower_widget.destroy()
self.__all_follower_widgets.clear()
class MenuBarLiveSessionCameraFollowerButtonDelegate(
MenuBarLiveSessionCameraFollowerBaseDelegate, AbstractCameraButtonDelegate
):
def __init__(self):
super().__init__()
def build_widget(self, parent_id, viewport_api, camera_path) -> Optional[ui.Widget]:
return super().build_widget_with_option(parent_id, viewport_api, camera_path, True)
def on_camera_path_changed(self, parent_id, new_camera_path: Sdf.Path):
super().on_camera_path_changed(parent_id, new_camera_path)
def on_parent_destroyed(self, parent_id):
super().on_parent_destroyed(parent_id)
def destroy(self):
super().destroy()
class MenuBarLiveSessionCameraFollowerMenuItemDelegate(
MenuBarLiveSessionCameraFollowerBaseDelegate, AbstractCameraMenuItemDelegate
):
def __init__(self):
super().__init__()
def build_widget(self, parent_id, viewport_api, camera_path) -> Optional[ui.Widget]:
return super().build_widget_with_option(parent_id, viewport_api, camera_path, False)
def on_camera_path_changed(self, parent_id, new_camera_path: Sdf.Path):
super().on_camera_path_changed(parent_id, new_camera_path)
def on_parent_destroyed(self, parent_id):
super().on_parent_destroyed(parent_id)
def destroy(self):
super().destroy()
| 3,215 | Python | 34.340659 | 112 | 0.658787 |
omniverse-code/kit/exts/omni.kit.collaboration.viewport.camera/omni/kit/collaboration/viewport/camera/peer_user_menu_item.py | import omni.ui as ui
import omni.kit.usd.layers as layers
import omni.kit.widget.live_session_management as lsm
from typing import Callable
from omni.kit.viewport.menubar.core import ViewportMenuDelegate, LabelMenuDelegate
class PeerUserMenuItem(ui.MenuItem):
"""
A single menu item represent a Live Sesson User
"""
def __init__(self, live_user: layers.LiveSessionUser, triggered_fn: Callable):
self.__live_user = live_user
super().__init__(
live_user.user_name,
checkable=True,
hide_on_click=False,
triggered_fn=lambda: triggered_fn(live_user),
delegate=ViewportMenuDelegate(
force_checked=False,
build_custom_widgets=lambda _1, _2: self.__build_menuitem_widgets()
)
)
def destroy(self):
super().destroy()
def __build_menuitem_widgets(self):
ui.Spacer(width=10)
lsm.build_live_session_user_layout(self.__live_user)
def set_checked(self, checked: bool) -> None:
self.checked = checked
self.delegate.checked = checked
class NoPeerUserMenuItem(ui.MenuItem):
def __init__(self):
super().__init__(
"No Users",
hide_on_click=False,
delegate=LabelMenuDelegate(enabled=False, width=120, alignment=ui.Alignment.CENTER)
)
| 1,374 | Python | 28.891304 | 95 | 0.621543 |
omniverse-code/kit/exts/omni.kit.collaboration.viewport.camera/omni/kit/collaboration/viewport/camera/manipulator/peer_user_camera_manipulator_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__ = ["PeerUserCameraManipulatorModel"]
import carb
import omni.usd
from omni.ui import scene as sc
from pxr import Gf, UsdGeom, Usd, Sdf
class PeerUserCameraManipulatorModel(sc.AbstractManipulatorModel):
"""The model tracks the position of peer user's camera in a live session."""
class PositionItem(sc.AbstractManipulatorItem):
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
class NdcPositionItem(sc.AbstractManipulatorItem):
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
class ViewportCameraPositionItem(sc.AbstractManipulatorItem):
def __init__(self):
super().__init__()
self.value = [0, 0, 0]
def __init__(self, scene_view, camera_path, usd_context):
super().__init__()
# Cached position. It's updated only when on_transform_changed is explicitly requested.
self.position = PeerUserCameraManipulatorModel.PositionItem()
self.ndc_position = PeerUserCameraManipulatorModel.NdcPositionItem()
self.viewport_camera_position = PeerUserCameraManipulatorModel.ViewportCameraPositionItem()
self.__scene_view = scene_view
self.__camera_path = Sdf.Path(camera_path)
self.__usd_context = usd_context
self.__update_position = True
self.__update_ndc_position = True
def destroy(self):
self.position = None
self.ndc_position = None
self.viewport_camera_position = None
self.__usd_context = None
self.__scene_view = None
def set_tracked_camera(self, camera_path):
camera_path = Sdf.Path(camera_path)
if camera_path != self.__camera_path:
self.__camera_path = camera_path
self.on_world_translation_changed()
def get_item(self, identifier):
if identifier == "position":
return self.position
elif identifier == "ndc_position":
return self.ndc_position
elif identifier == "viewport_camera_position":
return self.viewport_camera_position
return None
def get_as_floats(self, item):
if item == self.position:
if self.__update_position:
self.position.value = self.get_camera_position()
self.__update_position = False
return self.position.value
elif item == self.ndc_position:
if self.__update_ndc_position:
self.ndc_position.value = self._get_ndc_position()
self.__update_ndc_position = False
return self.ndc_position.value
elif item == self.viewport_camera_position:
return self.viewport_camera_position.value
return [0.0, 0.0, 0.0]
def set_floats(self, item, value):
if item != self.position:
return
if value and len(value) > 3:
value = [value[0], value[1], value[2]]
self.__update_position = False
self.__update_ndc_position = False
if value and item.value != value:
# Set directly to the item
item.value = value
self.ndc_position.value = self._get_ndc_position()
# This makes the manipulator updated
self._item_changed(item)
def on_view_translation_changed(self, viewport_camera_position=None):
if viewport_camera_position and len(viewport_camera_position) > 3:
viewport_camera_position = [
viewport_camera_position[0], viewport_camera_position[1], viewport_camera_position[2]
]
self.__update_ndc_position = True
if viewport_camera_position:
self.viewport_camera_position.value = viewport_camera_position
self._item_changed(self.ndc_position)
def on_world_translation_changed(self, position=None):
"""When position is provided, it will not re-calculate position but use provided value instead."""
# Position is changed
if position:
self.set_floats(self.position, position)
else:
self.__update_position = True
self.__update_ndc_position = True
self._item_changed(self.position)
def _get_ndc_position(self):
if self.__update_position:
self.position.value = self.get_camera_position()
self.__update_position = False
ndc_pos = self.__scene_view.scene.transform_space(sc.Space.WORLD, sc.Space.NDC, [*self.position.value, 1.0])
return ndc_pos
def get_camera_position(self):
"""Returns realtime position of currently selected object"""
stage = self.__usd_context.get_stage()
prim = stage.GetPrimAtPath(self.__camera_path)
if not prim:
return [0.0, 0.0, 0.0]
# May be empty (UsdGeom.Xform for example), so build a scene-scaled constant box
world_units = UsdGeom.GetStageMetersPerUnit(stage)
if Gf.IsClose(world_units, 0.0, 1e-6):
world_units = 0.01
world_matrix = omni.usd.get_world_transform_matrix(prim)
ref_position = world_matrix.ExtractTranslation()
extent = Gf.Vec3d(0.1 / world_units) # 10cm by default
bboxMin = ref_position - extent
bboxMax = ref_position + extent
position = [(bboxMin[0] + bboxMax[0]) * 0.5, bboxMax[1], (bboxMin[2] + bboxMax[2]) * 0.5]
return position
| 5,944 | Python | 35.030303 | 116 | 0.616252 |
omniverse-code/kit/exts/omni.kit.collaboration.viewport.camera/omni/kit/collaboration/viewport/camera/manipulator/__init__.py | from .peer_user_camera import PeerUserCamera
| 45 | Python | 21.999989 | 44 | 0.844444 |
omniverse-code/kit/exts/omni.kit.collaboration.viewport.camera/omni/kit/collaboration/viewport/camera/manipulator/peer_user_camera.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__ = ["PeerUserCamera"]
import omni.kit.usd.layers as layers
from pxr import Sdf
from omni.ui import scene as sc
from omni.kit.viewport.utility import get_active_viewport_window
from .peer_user_camera_manipulator_model import PeerUserCameraManipulatorModel
from .peer_user_camera_manipulator import PeerUserCameraManipulator
class PeerUserCamera:
def __init__(self, user_info: layers.LiveSessionUser, camera_path, usd_context):
self.__camera_path = Sdf.Path(camera_path)
self.__user_info = user_info
self.__usd_context = usd_context
self.__manipulator = None
self.__manipulator_model = None
self.__scene_view = None
self.__build_window()
def destroy(self):
if self.__manipulator:
self.__manipulator.destroy()
self.__manipulator = None
if self.__manipulator_model:
self.__manipulator_model.destroy()
self.__manipulator_model = None
if self.__viewport_window:
vp_api = self.__viewport_window.viewport_api
if self.__scene_view:
vp_api.remove_scene_view(self.__scene_view)
self.__scene_view.scene.clear()
self.__scene_view.destroy()
self.__scene_view = None
self.__viewport_window = None
def set_tracked_camera(self, camera_path):
camera_path = Sdf.Path(camera_path)
if self.__camera_path != camera_path:
self.__camera_path = camera_path
if self.__manipulator_model:
self.__manipulator_model.set_tracked_camera(self.__camera_path)
@property
def position(self):
"""Realtime position of the camera prim."""
if self.__manipulator_model:
return self.__manipulator_model.get_camera_position()
return None
def on_view_translation_changed(self, viewport_camera_position=None):
"""When the view pos from the current viewport camera is changed."""
if self.__manipulator_model:
self.__manipulator_model.on_view_translation_changed(viewport_camera_position)
def on_world_translation_changed(self, position=None):
if self.__manipulator_model:
self.__manipulator_model.on_world_translation_changed(position)
def on_viewport_camera_changed(self, position):
if self.__manipulator:
self.__manipulator.on_viewport_camera_changed(position)
def __build_window(self):
"""Called to build the widgets of the window"""
self.__viewport_window = get_active_viewport_window()
frame = self.__viewport_window.get_frame("omni.kit.collaboration.viewport.camera." + self.__user_info.user_id)
with frame:
self.__scene_view = sc.SceneView()
with self.__scene_view.scene:
self.__manipulator_model = PeerUserCameraManipulatorModel(
self.__scene_view, self.__camera_path, self.__usd_context
)
self.__manipulator = PeerUserCameraManipulator(
user_info=self.__user_info,
model=self.__manipulator_model,
usd_context=self.__usd_context
)
vp_api = self.__viewport_window.viewport_api
vp_api.add_scene_view(self.__scene_view)
| 3,825 | Python | 36.509804 | 118 | 0.628235 |
omniverse-code/kit/exts/omni.kit.collaboration.viewport.camera/omni/kit/collaboration/viewport/camera/manipulator/peer_user_camera_manipulator.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.
##
__all__ = ["PeerUserCameraManipulator"]
import math
import omni.ui as ui
import omni.kit.usd.layers as layers
from omni.ui import scene as sc
from omni.ui import color as cl
from omni.kit.viewport.utility import get_active_viewport_window
class PeerUserCameraManipulator(sc.Manipulator):
def __init__(self, **kwargs):
super().__init__(**kwargs)
# Must
self.__usd_context = kwargs.get("usd_context")
self.__user_info = kwargs.get("user_info")
self.__label_position_transform = None
self.__offscreen_position_transform = None
self.__pointer_position_transform = None
self.__pointer_arrow_rotation_transform = None
self.__offscreen_pointer = None
self.__offscreen_pointer_size = 64
self.__arrow_x_translation = 46
def destroy(self):
self.__clear()
def __clear(self):
if self.__label_position_transform:
self.__label_position_transform.clear()
self.__label_position_transform = None
if self.__offscreen_position_transform:
self.__offscreen_position_transform.clear()
self.__offscreen_position_transform = None
if self.__pointer_arrow_rotation_transform:
self.__pointer_arrow_rotation_transform.clear()
self.__pointer_arrow_rotation_transform = None
if self.__pointer_position_transform:
self.__pointer_position_transform.clear()
self.__pointer_position_transform = None
def __is_out_of_viewport(self, ndc_pos):
# Make sure its not clipped
if (ndc_pos[2] > 1.0) or (ndc_pos[0] < -1) or (ndc_pos[0] > 1) or (ndc_pos[1] < -1) or (ndc_pos[1] > 1):
return True
return False
def __get_pointer_screen_pos_and_angle(self, viewport_window, ndc_pos):
# When it's in the back of camera view,
# Draw the widget at the bottom of viewport.
if ndc_pos[2] > 1.0:
ndc_pos[1] = -1.0
ndc_pos[0] = -ndc_pos[0]
ndc_pos[0] = min(max(ndc_pos[0], -1.0), 1.0)
ndc_pos[1] = min(max(ndc_pos[1], -1.0), 1.0)
radians = math.atan2(ndc_pos[1], ndc_pos[0])
pointer_angles = radians
frame = viewport_window.frame
offset_x = ndc_pos[0] * frame.computed_width
offset_y = ndc_pos[1] * frame.computed_height
if ndc_pos[0] == -1.0:
offset_x += self.__offscreen_pointer_size
elif ndc_pos[0] == 1.0:
offset_x -= self.__offscreen_pointer_size
if ndc_pos[1] == -1.0:
offset_y += self.__offscreen_pointer_size
elif ndc_pos[1] == 1.0:
offset_y -= self.__offscreen_pointer_size
return (offset_x, offset_y, 0.0), pointer_angles
def on_viewport_camera_changed(self, position):
if position:
self.__viewport_camera_position = position
def on_build(self):
"""Called when the model is changed and rebuilds the whole slider"""
if not self.model:
return
user_info = self.__user_info
color = ui.color(*user_info.user_color)
# Initialization
if self.__offscreen_pointer is None:
ndc_position = self.model.get_as_floats(self.model.get_item("ndc_position"))
self.__offscreen_pointer = self.__is_out_of_viewport(ndc_position)
ndc_position = self.model.get_as_floats(self.model.get_item("ndc_position"))
if not ndc_position:
return
viewport_window = get_active_viewport_window()
if not viewport_window:
return
bound_camera_world_translation = self.model.get_as_floats(self.model.get_item("viewport_camera_position"))
if bound_camera_world_translation is None:
return
screen_position, pointer_angle = self.__get_pointer_screen_pos_and_angle(viewport_window, ndc_position)
self.__offscreen_position_transform = sc.Transform(
transform=sc.Matrix44.get_translation_matrix(*bound_camera_world_translation)
)
with self.__offscreen_position_transform:
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
# Make sure it's in front of camera.
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 0, -10000.0)):
with sc.Transform(scale_to=sc.Space.SCREEN):
self.__pointer_position_transform = sc.Transform(
transform=sc.Matrix44.get_translation_matrix(*screen_position)
)
with self.__pointer_position_transform:
sc.Arc(radius=28, color=color)
sc.Label(
layers.get_short_user_name(user_info.user_name), color=cl.white,
alignment=ui.Alignment.CENTER, size=16
)
arrow_transform = sc.Matrix44.get_rotation_matrix(0, 0, pointer_angle)
arrow_transform *= sc.Matrix44.get_translation_matrix(*[self.__arrow_x_translation, 0, 0])
self.__pointer_arrow_rotation_transform = sc.Transform(transform=arrow_transform)
with self.__pointer_arrow_rotation_transform:
sc.PolygonMesh(
positions=[
[14, 0, 0],
[-14, 14, 0],
[-14, -14, 0]
],
colors=[color] * 3,
vertex_counts=[3],
vertex_indices=[0, 1, 2]
)
position = self.model.get_as_floats(self.model.get_item("position"))
name_size = len(self.__user_info.user_name) * 16
self.__label_position_transform = sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position))
with self.__label_position_transform:
with sc.Transform(look_at=sc.Transform.LookAt.CAMERA):
with sc.Transform(scale_to=sc.Space.SCREEN):
with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, 50, 0)):
sc.Rectangle(color=color, width=name_size, height=40)
sc.Label(user_info.user_name, color=cl.white, alignment=ui.Alignment.CENTER, size=16)
if self.__offscreen_pointer:
self.__offscreen_position_transform.visible = True
self.__label_position_transform.visible = False
else:
self.__label_position_transform.visible = True
self.__offscreen_position_transform.visible = False
def __invalidate(self):
# Regenerate the manipulator
self.__clear()
self.invalidate()
def on_model_updated(self, item):
if not self.__offscreen_position_transform or not item:
self.__invalidate()
return
viewport_window = get_active_viewport_window()
if not viewport_window:
self.__invalidate()
return
position_item = self.model.get_item("position")
ndc_position_item = self.model.get_item("ndc_position")
if item != position_item and item != ndc_position_item:
return
ndc_pos = self.model.get_as_floats(ndc_position_item)
out_of_viewport = self.__is_out_of_viewport(ndc_pos)
mode_changed = False
if out_of_viewport != self.__offscreen_pointer:
mode_changed = True
self.__offscreen_pointer = out_of_viewport
if out_of_viewport:
self.__offscreen_position_transform.visible = True
self.__label_position_transform.visible = False
else:
self.__offscreen_position_transform.visible = False
self.__label_position_transform.visible = True
if out_of_viewport:
bound_camera_world_translation = self.model.get_as_floats(self.model.get_item("viewport_camera_position"))
if bound_camera_world_translation is None:
self.__invalidate()
return
position = bound_camera_world_translation
screen_position, pointer_angle = self.__get_pointer_screen_pos_and_angle(viewport_window, ndc_pos)
pointer_transform = sc.Matrix44.get_translation_matrix(*screen_position)
self.__pointer_position_transform.transform = pointer_transform
arrow_transform = sc.Matrix44.get_rotation_matrix(0, 0, pointer_angle)
arrow_transform *= sc.Matrix44.get_translation_matrix(*[self.__arrow_x_translation, 0, 0])
self.__pointer_arrow_rotation_transform.transform = arrow_transform
# FIXME: Don't use sc.Matrix44.get_translation_matrix(*position), as it has
# weird perf issue, which I think it's because of data type conversion.
self.__offscreen_position_transform.transform = sc.Matrix44.get_translation_matrix(
*[position[0], position[1], position[2]]
)
elif mode_changed or item == position_item:
position = self.model.get_as_floats(position_item)
self.__label_position_transform.transform = sc.Matrix44.get_translation_matrix(
*[position[0], position[1], position[2]]
)
| 10,004 | Python | 40.861925 | 118 | 0.581068 |
omniverse-code/kit/exts/omni.kit.collaboration.viewport.camera/omni/kit/collaboration/viewport/camera/tests/__init__.py | from .test_widgets import TestCollaborationViewportCamera | 57 | Python | 56.999943 | 57 | 0.912281 |
omniverse-code/kit/exts/omni.kit.collaboration.viewport.camera/omni/kit/collaboration/viewport/camera/tests/test_widgets.py | import carb
import omni.kit.test
import omni.kit.ui_test as ui_test
import omni.usd
import omni.ui as ui
import omni.client
import unittest
import omni.kit.app
import omni.kit.usd.layers as layers
import omni.kit.clipboard
import omni.kit.collaboration.presence_layer as pl
import omni.kit.collaboration.presence_layer.utils as pl_utils
import omni.kit.collaboration.presence_layer.extension as pl_extension
from omni.kit.viewport.utility import get_active_viewport_window
from omni.kit.collaboration.viewport.camera.manipulator.peer_user_camera import PeerUserCamera
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
from pxr import Usd, Sdf, UsdGeom
from omni.kit.ui_test import Vec2
from omni.kit.usd.layers.tests.mock_utils import MockLiveSyncingApi, join_new_simulated_user, quit_simulated_user
CURRENT_PATH = Path(__file__).parent.joinpath("../../../../../../data")
class ToggleExpansionState():
def __init__(self):
self.__settings = carb.settings.get_settings()
self.__key = "/persistent/exts/omni.kit.viewport.menubar.camera/expand"
self.__restore_value = self.__settings.get(self.__key)
def set(self, value: bool):
self.__settings.set(self.__key, value)
def __del__(self):
self.__settings.set(self.__key, self.__restore_value)
class TestCollaborationViewportCamera(OmniUiTest):
# Before running each test
async def setUp(self):
self.app = omni.kit.app.get_app()
self.usd_context = omni.usd.get_context()
await omni.usd.get_context().new_stage_async()
self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests")
self.layers = layers.get_layers(self.usd_context)
self.live_syncing = layers.get_live_syncing()
self.local_builtin_cameras = [
"/OmniverseKit_Persp", "/OmniverseKit_Front", "/OmniverseKit_Top", "/OmniverseKit_Right"
]
self.test_session_name = "test"
self.simulated_user_names = []
self.simulated_user_ids = []
self.stage_url = "omniverse://__fake_omniverse_server__/test/camera.usd"
async def tearDown(self):
pass
async def wait(self, frames=10):
for i in range(frames):
await self.app.next_update_async()
async def __create_simulated_users(self, count=2):
for i in range(count):
user_name = f"test{i}"
user_id = user_name
self.simulated_user_names.append(user_name)
self.simulated_user_ids.append(user_id)
join_new_simulated_user(user_name, user_id)
await self.wait(2)
async def __create_fake_stage_and_join_session(self, bound_non_default_camera=False):
format = Sdf.FileFormat.FindByExtension(".usd")
# Sdf.Layer.New will not save layer so it won't fail.
# This can be used to test layer identifier with omniverse sheme without
# touching real server.
layer = Sdf.Layer.New(format, self.stage_url)
stage = Usd.Stage.Open(layer.identifier)
camera = stage.DefinePrim("/Camera", "Camera")
session = self.live_syncing.create_live_session(self.test_session_name, layer_identifier=layer.identifier)
self.assertTrue(session)
await self.usd_context.attach_stage_async(stage)
if bound_non_default_camera:
viewport_window = get_active_viewport_window()
viewport_api = viewport_window.viewport_api
viewport_api.camera_path = str(camera.GetPath())
await self.wait()
self.assertEqual(viewport_api.camera_path, str(camera.GetPath()))
self.live_syncing.join_live_session(session)
self.assertTrue(self.live_syncing.get_current_live_session())
await self.wait()
return stage, layer
async def __bound_camera(self, shared_stage: Usd.Stage, user_id: str, camera_path: Sdf.Path):
if not camera_path:
camera_path = Sdf.Path.emptyPath
camera_path = Sdf.Path(camera_path)
bound_camera_property_path = pl_utils.get_bound_camera_property_path(user_id)
property_spec = pl_utils.get_or_create_property_spec(
shared_stage.GetRootLayer(), bound_camera_property_path,
Sdf.ValueTypeNames.String
)
builtin_camera_name = pl_utils.is_local_builtin_camera(camera_path)
if not builtin_camera_name:
property_spec.default = str(camera_path)
else:
property_spec.default = builtin_camera_name
if builtin_camera_name:
persp_camera = pl_utils.get_user_shared_root_path(user_id).AppendChild(builtin_camera_name)
shared_stage.DefinePrim(persp_camera, "Camera")
await self.wait()
@MockLiveSyncingApi("test", "test")
async def test_camera_switch(self):
await self.wait()
await self.__create_fake_stage_and_join_session(True)
await self.wait()
viewport_window = get_active_viewport_window()
viewport_api = viewport_window.viewport_api
self.assertEqual(viewport_api.camera_path, self.local_builtin_cameras[0])
@MockLiveSyncingApi("test", "test")
async def test_follow_user_menu(self):
expand_state = ToggleExpansionState()
expand_state.set(False)
await self.wait()
await self.__create_fake_stage_and_join_session()
await self.wait()
await self.__create_simulated_users()
await self.wait()
presence_layer = pl.get_presence_layer_interface(self.usd_context)
shared_stage = presence_layer.get_shared_data_stage()
self.assertTrue(shared_stage)
# make "Cameras" menu and "Follow User" menu show by simulating mouse moving and clicking
await ui_test.emulate_mouse_move(Vec2(40, 40))
await ui_test.emulate_mouse_click()
await self.wait()
await ui_test.emulate_mouse_move(Vec2(40, 240))
await ui_test.emulate_mouse_click()
await self.wait()
await self.__bound_camera(shared_stage, self.simulated_user_ids[1], Sdf.Path(self.local_builtin_cameras[0]))
await self.wait()
presence_layer.enter_follow_mode(self.simulated_user_ids[1])
await self.wait()
await self.finalize_test(golden_img_dir=self._golden_img_dir)
camera_menu = ui_test.find("Viewport//Frame/**/Menu[*].text=='Perspective'")
self.assertTrue(camera_menu)
menu_items = camera_menu.find_all("**/")
menu_item_lables = []
for widget in menu_items:
if isinstance(widget.widget, (ui.Menu, ui.MenuItem)):
menu_item_lables.append(widget.widget.text)
#make sure there are two menu items under follow user menu item
follow_users = menu_item_lables[-2:]
self.assertEqual(set(follow_users), set(self.simulated_user_names))
# Log off one user from the live session
quit_simulated_user(self.simulated_user_ids[1])
await self.wait()
# make "Cameras" menu and "Follow User" menu show by simulating mouse moving and clicking
await ui_test.emulate_mouse_move(Vec2(0, 0))
await ui_test.emulate_mouse_click()
await ui_test.emulate_mouse_move(Vec2(40, 40))
await ui_test.emulate_mouse_click()
await self.wait()
await ui_test.emulate_mouse_move(Vec2(40, 240))
await ui_test.emulate_mouse_click()
await self.wait()
menu_items = camera_menu.find_all("**/")
menu_item_lables = []
for widget in menu_items:
if isinstance(widget.widget, ui.Menu) or isinstance(widget.widget, ui.MenuItem):
menu_item_lables.append(widget.widget.text)
#make sure there are only one menu item under follow user menu item
follow_users = menu_item_lables[-1:]
self.assertEqual(follow_users, [self.simulated_user_ids[0]])
self.live_syncing.stop_all_live_sessions()
await self.wait()
async def test_camera_manipulator(self):
expand_state = ToggleExpansionState()
expand_state.set(False)
stage = self.usd_context.get_stage()
prim = stage.DefinePrim("/root", "Xform")
user = layers.LiveSessionUser("test", "test", "Kit")
camera_widget = PeerUserCamera(user, prim.GetPath(), self.usd_context)
try:
await self.wait()
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="camera_label.png")
# Moves the prim out of the viewport frame.
UsdGeom.XformCommonAPI(prim).SetTranslate((-10000, 0, 10000))
camera_widget.on_world_translation_changed()
await self.wait()
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="offscreen_pointer.png")
UsdGeom.XformCommonAPI(prim).SetTranslate((10000, 0, 10000))
camera_widget.on_world_translation_changed()
await self.wait()
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="offscreen_pointer_2.png")
finally:
camera_widget.destroy()
camera_widget = None
await self.wait()
| 9,241 | Python | 38.665236 | 116 | 0.64809 |
omniverse-code/kit/exts/omni.kit.collaboration.viewport.camera/docs/CHANGELOG.md | # Changelog
## [2.0.2] - 2023-02-02
### Changed
- Fix Sdf logging spew.
- Cherry-pick perf improvements to speed up camera label construction.
- Clear shared data only when root layer is merged.
## [2.0.1] - 2022-11-16
### Changed
- Fix lag issue of camera label.
## [2.0.0] - 2022-11-02
### Changed
- Supports camera label for new live session.
## [1.0.5] - 2022-06-15
### Changed
- Use new omni.kit.viewport.utility functions for active camera
- Update tests to pass on both Viewports
- Make tests run with Storm to avoid RTX shader-cache timeout
## [1.0.4] - 2022-04-21
### Changed
- Add unittests.
## [1.0.3] - 2022-02-24
### Changed
- Inspect new and old Viewports for active camera.
## [1.0.2] - 2022-02-21
### Changed
- Move extension to kit-tools repo.
## [1.0.1] - 2021-03-15
### Changed
- Separate viewport widgets management to single extension.
## [1.0.0] - 2021-03-09
### Changed
- Initial extension.
| 933 | Markdown | 21.238095 | 70 | 0.66881 |
omniverse-code/kit/exts/omni.kit.collaboration.viewport.camera/docs/README.md | # Viewport Widget: Camera Name [omni.kit.collaboration.viewport.camera]
This extension utilizes omni.kit.collaboration.channel_manager to exchange camera information between users in the same stage, and display a widget under camera to visualize current focused camera of users.
| 280 | Markdown | 69.249983 | 206 | 0.828571 |
omniverse-code/kit/exts/omni.kit.collaboration.viewport.camera/docs/index.rst | omni.kit.collaboration.viewport.camera
######################################
Viewport Widget: Camera Name
Introduction
============
This extension is part of the Live Session applications, which utitlizes omni.kit.collaboration.presence_layer to share
camera location in realtime, and provides widgets for Viewport to show user icon and mesh. | 345 | reStructuredText | 37.44444 | 119 | 0.710145 |
omniverse-code/kit/exts/omni.kit.widget.opengl/config/extension.toml | [package]
# Semantic Versionning is used: https://semver.org/
version = "1.0.0"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarly for displaying extension info in UI
title = "OmniUI OpenGL Widget"
description="A simple widget for drawing in omni.ui with OpenGL"
# URL of the extension source repository.
repository = ""
# Keywords for the extension
keywords = ["kit", "ui", "widget", "opengl"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
category = "Rendering"
[[native.library]]
path = "bin/${lib_prefix}omni.kit.widget.opengl${lib_ext}"
[dependencies]
"omni.ui" = {}
"omni.gpu_foundation" = {}
"omni.kit.pip_archive" = {}
# Main python module this extension provides, it will be publicly available as "import omni.kit.widget.opengl".
[[python.module]]
name = "omni.kit.widget.opengl"
# [python.pipapi]
# requirements = ["PyOpenGL"]
# use_online_index = true
[settings]
# exts."omni.kit.widget.opengl".xxx = ""
[[test]]
args = [
"--/app/docks/disabled=true",
"--/app/window/width=512",
"--/app/window/height=512",
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window",
]
dependencies = [
"omni.kit.renderer.capture",
"omni.kit.widget.opengl",
]
cppTests.libraries = [
"bin/${lib_prefix}omni.kit.widget.opengl.tests${lib_ext}"
]
| 1,774 | TOML | 26.307692 | 111 | 0.698985 |
omniverse-code/kit/exts/omni.kit.widget.opengl/omni/kit/widget/opengl/__init__.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
"""
omni.kit.widget.opengl
----------------------
omni.kit.widget.opengl module provides a way to draw with OpenGL in an omni.ui.Widget
"""
__all__ = ["OpenGLWidget", "OpenGLImageProvider", "OpenGLScene"]
from ._opengl_widget import *
class OpenGLScene:
"Simple class for an OpenGLScene object for subclassing that sets up callbacks into the omni.ui object"
def __init__(self, widget_or_provider):
widget_or_provider.set_initialize_gl_fn(self.initialize_gl)
widget_or_provider.set_draw_gl_fn(self.draw_gl)
def initialize_gl(self, viewport_width: int, viewport_height: int, first_init: bool):
pass
def draw_gl(self, viewport_width: int, viewport_height: int):
pass
| 1,162 | Python | 33.205881 | 107 | 0.717728 |
omniverse-code/kit/exts/omni.kit.widget.opengl/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``omni.kit.widget.opengl`` extension.
This project adheres to `Semantic Versioning <https://semver.org/>`_.
## [1.0.0] - 2022-06-27
### Added
- Initial version.
| 220 | Markdown | 23.555553 | 82 | 0.713636 |
omniverse-code/kit/exts/omni.kit.widget.opengl/docs/README.md | # OpenGL Widget Extension [omni.kit.widget.opengl]
Simple extension for rendering OpenGL content into an omni.ui object.
| 121 | Markdown | 39.666653 | 69 | 0.809917 |
omniverse-code/kit/exts/omni.kit.hydra_texture/config/extension.toml | [package]
version = "1.0.11"
title = "Omniverse Kit RTX Hydra Texture"
[dependencies]
"omni.kit.renderer.core" = {}
"omni.usd" = {}
"omni.hydra.rtx" = { optional=true }
"omni.hydra.iray" = { optional=true }
"omni.hydra.pxr" = { optional=true }
[[python.module]]
name = "omni.kit.hydra_texture"
[[native.plugin]]
path = "bin/${platform}/${config}/*.plugin"
[[test]]
args = [
"--/renderer/enabled=pxr",
"--/renderer/active=pxr",
"--/renderer/multiGpu/enabled=false",
"--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611
"--/renderer/multiGpu/maxGpuCount=1",
"--/app/asyncRendering=false",
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.hydra.pxr",
"omni.ui"
]
stdoutFailPatterns.exclude = [
# Engine ownership on default UsdContext is still undefined due to Viewport-1
# and GPUFoundation prevents the test from spinning up too many custom UsdContexts
"*UsdManager::destroyContext invoked on context with active hydra engines*",
# Can drop a frame or two rendering with OpenGL interop
"*HydraRenderer failed to render this frame*",
]
# RTX regression OM-51983
timeout = 600
| 1,248 | TOML | 26.755555 | 94 | 0.678686 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.