file_path
stringlengths 32
153
| content
stringlengths 0
3.14M
|
---|---|
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/tree_view.py |
__all__ = ["TreeViewPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class TreeViewPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "columns_resizable", PropertyType.BOOL)
self._add_property(self._widget, "header_visible", PropertyType.BOOL)
self._add_property(self._widget, "root_visible", PropertyType.BOOL)
self._add_property(self._widget, "expand_on_branch_click", PropertyType.BOOL)
self._add_property(self._widget, "keep_alive", PropertyType.BOOL)
self._add_property(self._widget, "keep_expanded", PropertyType.BOOL)
self._add_property(self._widget, "drop_between_items", PropertyType.BOOL)
|
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/grid.py |
__all__ = ["GridPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class GridPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "columnWidth", PropertyType.FLOAT)
self._add_property(self._widget, "rowHeight", PropertyType.FLOAT)
self._add_property(self._widget, "columnCount", PropertyType.INT, range_from=0)
self._add_property(self._widget, "rowCount", PropertyType.INT, range_from=0)
|
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/slider.py |
__all__ = ["SliderPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class SliderPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "min", PropertyType.INT)
self._add_property(self._widget, "max", PropertyType.INT)
|
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/frame.py |
__all__ = ["FramePropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class FramePropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "horizontal_clipping", PropertyType.BOOL)
self._add_property(self._widget, "vertical_clipping", PropertyType.BOOL)
self._add_property(self._widget, "separate_window", PropertyType.BOOL)
|
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/image.py |
__all__ = ["ImagePropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class ImagePropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "source_url", PropertyType.STRING, label_width=80)
self._add_property(self._widget, "alignment", PropertyType.ENUM, label_width=80)
self._add_property(self._widget, "fill_policy", PropertyType.ENUM, label_width=80)
|
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/combox_box.py |
__all__ = ["ComboBoxPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class ComboBoxPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
pass
# self._add_property(self._widget, "arrow_only", PropertyType.BOOL)
|
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/string_field.py |
__all__ = ["StringFieldPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class StringFieldPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "password_mode", PropertyType.BOOL)
self._add_property(self._widget, "read_only", PropertyType.BOOL)
self._add_property(self._widget, "multiline", PropertyType.BOOL)
|
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/line.py |
__all__ = ["LinePropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class LinePropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "alignment", PropertyType.ENUM)
|
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/stack.py |
__all__ = ["StackPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class StackPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "spacing", PropertyType.FLOAT)
self._add_property(self._widget, "direction", PropertyType.ENUM)
self._add_property(self._widget, "content_clipping", PropertyType.BOOL)
|
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/collapsable_frame.py |
__all__ = ["CollapsableFramePropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class CollapsableFramePropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "collapsed", PropertyType.BOOL)
self._add_property(self._widget, "title", PropertyType.STRING)
self._add_property(self._widget, "alignment", PropertyType.ENUM)
|
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/placer.py |
__all__ = ["PlacerPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class PlacerPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "offset_x", PropertyType.FLOAT)
self._add_property(self._widget, "offset_y", PropertyType.FLOAT)
self._add_property(self._widget, "draggable", PropertyType.BOOL)
self._add_property(self._widget, "drag_axis", PropertyType.ENUM)
self._add_property(self._widget, "stable_size", PropertyType.BOOL)
|
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/scrolling_frame.py |
__all__ = ["ScrollingFramePropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class ScrollingFramePropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "scroll_x", PropertyType.FLOAT)
self._add_property(self._widget, "scroll_y", PropertyType.FLOAT)
self._add_property(self._widget, "horizontal_scrollbar_policy", PropertyType.ENUM)
self._add_property(self._widget, "vertical_scrollbar_policy", PropertyType.ENUM)
|
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/label.py |
__all__ = ["LabelPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class LabelPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "text", PropertyType.STRING)
self._add_property(self._widget, "alignment", PropertyType.ENUM)
self._add_property(self._widget, "word_wrap", PropertyType.BOOL)
self._add_property(self._widget, "elided_text", PropertyType.BOOL)
|
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/circle.py |
__all__ = ["CirclePropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class CirclePropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "radius", PropertyType.FLOAT, range_from=0)
self._add_property(self._widget, "alignment", PropertyType.ENUM)
self._add_property(self._widget, "arc", PropertyType.ENUM)
self._add_property(self._widget, "size_policy", PropertyType.ENUM)
|
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/triangle.py |
__all__ = ["TrianglePropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class TrianglePropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "alignment", PropertyType.ENUM, label_width=80)
|
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/image_with_provider.py |
__all__ = ["ImageWithProviderPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class ImageWithProviderPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "alignment", PropertyType.ENUM, label_width=80)
self._add_property(self._widget, "fill_policy", PropertyType.ENUM, label_width=80)
|
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/widget.py |
__all__ = ["WidgetPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class WidgetPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "width", PropertyType.FLOAT, 0, 2000)
self._add_property(self._widget, "height", PropertyType.FLOAT, 0, 2000)
self._add_property(self._widget, "tooltip_offset_x", PropertyType.FLOAT, 0, 2000)
self._add_property(self._widget, "tooltip_offset_y", PropertyType.FLOAT, 0, 2000)
ui.Line(height=2, style={"color": 0xFF666666})
self._add_property(self._widget, "name", PropertyType.STRING)
ui.Line(height=2, style={"color": 0xFF666666})
self._add_property(self._widget, "checked", PropertyType.BOOL)
self._add_property(self._widget, "enabled", PropertyType.BOOL)
self._add_property(self._widget, "selected", PropertyType.BOOL)
self._add_property(self._widget, "opaque_for_mouse_events", PropertyType.BOOL)
self._add_property(self._widget, "visible", PropertyType.BOOL)
self._add_property(self._widget, "skip_draw_when_clipped", PropertyType.BOOL)
ui.Spacer(height=10)
ui.Line(height=5, style={"color": 0xFF666666, "border_width": 5})
ui.Label("Read Only", alignment=ui.Alignment.CENTER)
self._add_property(self._widget, "computed_width", PropertyType.FLOAT, 0, 2000)
self._add_property(self._widget, "computed_height", PropertyType.FLOAT, 0, 2000)
ui.Line(height=2, style={"color": 0xFF666666})
self._add_property(self._widget, "computed_content_width", PropertyType.FLOAT, 0, 2000)
self._add_property(self._widget, "computed_content_height", PropertyType.FLOAT, 0, 2000)
ui.Line(height=2, style={"color": 0xFF666666})
self._add_property(self._widget, "screen_position_x", PropertyType.FLOAT, 0, 2000)
self._add_property(self._widget, "screen_position_y", PropertyType.FLOAT, 0, 2000)
|
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/tests/__init__.py | from .test_ui import *
|
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/tests/test_ui.py | import omni.kit.test
import omni.kit.window.inspector.inspector_window
from omni.kit import ui_test
class TestInspectorWindow(omni.kit.test.AsyncTestCase):
@classmethod
def setUpClass(cls):
cls.inspector_window = omni.kit.window.inspector.inspector_window.InspectorWindow()
async def setUp(self):
self.window_name = self.inspector_window._window.title
@classmethod
def tearDownClass(cls) -> None:
cls.inspector_window._window.destroy()
async def test_window_list(self):
'''
Check that the main combox box is doing the right thing
There's a bit of an ordering assumption going on
'''
ui_window = ui_test.find(self.window_name)
widgets = ui_window.find_all("**/WindowListComboBox")
self.assertTrue(len(widgets) == 1)
combo_box = widgets[0].widget
self.assertTrue(isinstance(combo_box, omni.ui.ComboBox))
# Make sure render settings is set
combo_box.model.get_item_value_model(None, 0).set_value(0)
window_name = combo_box.model.get_current_window()
self.assertEqual(window_name, "Render Settings")
# Set to Stage window
combo_box.model.get_item_value_model(None, 0).set_value(1)
window_name = combo_box.model.get_current_window()
self.assertEqual(window_name, "Stage")
await omni.kit.app.get_app().next_update_async()
async def test_tree_expansion(self):
# make sure render settings is the current window
ui_window = ui_test.find(self.window_name)
widgets = ui_window.find_all("**/WindowListComboBox")
combo_box = widgets[0].widget
combo_box.model.get_item_value_model(None, 0).set_value(0)
widgets = ui_window.find_all("**/WidgetInspectorTree")
self.assertTrue(len(widgets) == 1)
tree_items = widgets[0].find_all("**")
self.assertTrue(len(tree_items) == 20, f"actually was {len(tree_items)}")
# Switch to Stage Window
combo_box.model.get_item_value_model(None, 0).set_value(1)
widgets = ui_window.find_all("**/WidgetInspectorTree")
self.assertTrue(len(widgets) == 1)
tree_items = widgets[0].find_all("**")
self.assertTrue(len(tree_items) == 17, f"actually was {len(tree_items)}")
async def test_tree_basic_content(self):
# make sure render settings is the current window
ui_window = ui_test.find(self.window_name)
widgets = ui_window.find_all("**/WindowListComboBox")
combo_box = widgets[0].widget
combo_box.model.get_item_value_model(None, 0).set_value(0)
widgets = ui_window.find_all("**/WidgetInspectorTree")
self.assertTrue(len(widgets) == 1)
tree_items = widgets[0].find_all("**")
labels = [t.widget for t in tree_items if isinstance(t.widget, omni.ui.Label)]
self.assertTrue(len(labels) == 2)
self.assertTrue(labels[0].text == "Frame")
self.assertTrue(labels[1].text == "Style")
async def test_styles(self):
ui_window = ui_test.find(self.window_name)
buttons = ui_window.find_all("**/ToolButton[*]")
# enable style
for button in buttons:
if button.widget.text == "Style":
await button.click()
await ui_test.wait_n_updates(2)
trees = ui_window.find_all("**/WidgetInspectorTree")
self.assertTrue(len(trees) == 1)
tree_items = trees[0].find_all("**")
labels = [t for t in tree_items if isinstance(t.widget, omni.ui.Label)]
for label in labels:
if label.widget.text == "Frame":
await label.click()
await ui_test.wait_n_updates(2)
# check there is colorwidget widgets created
colorwidgets = ui_window.find_all("**/ColorWidget[*]")
self.assertTrue(len(colorwidgets) > 0)
|
omniverse-code/kit/exts/omni.kit.window.inspector/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.6] - 2022-07-05
- add test to increase the test coverage
## [1.0.5] - 2022-05-16
- start adding tests
## [1.0.4] - 2022-01-10
- support for widgets under Treeview (i.e those created by the treeview delegate)
## [1.0.3] - 2021-11-24
### Added
- expand/collapse in tree widget
## [1.0.2] - 2021-11-24
### Changes
- Fix some bugs naming paths
- startup defaults less cluttered..
## [1.0.1] - 2021-11-24
### Changes
- Update to latest omni.ui_query
## [1.0.0] -
### TODO
- Better support for ALL <Category> >> DONE
- Better list of Property for Widget >> DONE
- Contextual Styling List
-
|
omniverse-code/kit/exts/omni.kit.window.inspector/docs/overview.md | # Overview
|
omniverse-code/kit/exts/omni.kit.window.inspector/docs/README.md | # UI Inspector Widget [omni.kit.window.inspector]
|
omniverse-code/kit/exts/omni.kit.documentation.builder/PACKAGE-LICENSES/omni.kit.documentation.builder-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. |
omniverse-code/kit/exts/omni.kit.documentation.builder/scripts/generate_docs_for_sphinx.py | import argparse
import asyncio
import logging
import carb
import omni.kit.app
import omni.kit.documentation.builder
logger = logging.getLogger(__name__)
_app_ready_sub = None
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"ext_id",
help="Extension id (name-version).",
)
parser.add_argument(
"output_path",
help="Path to output generated files to.",
)
options = parser.parse_args()
async def _generate_and_exit(options):
# Skip 2 updates to make sure all extensions loaded and initialized
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
try:
result = omni.kit.documentation.builder.generate_for_sphinx(options.ext_id, options.output_path)
except Exception as e: # pylint: disable=broad-except
carb.log_error(f"Failed to generate docs for sphinx: {e}")
for _ in range(5):
await omni.kit.app.get_app().next_update_async()
returncode = 0 if result else 33
omni.kit.app.get_app().post_quit(returncode)
def on_app_ready(e):
global _app_ready_sub
_app_ready_sub = None
asyncio.ensure_future(_generate_and_exit(options))
app = omni.kit.app.get_app()
if app.is_app_ready():
on_app_ready(None)
else:
global _app_ready_sub
_app_ready_sub = app.get_startup_event_stream().create_subscription_to_pop_by_type(
omni.kit.app.EVENT_APP_READY, on_app_ready, name="omni.kit.documentation.builder generate_docs_for_sphinx"
)
if __name__ == "__main__":
main()
|
omniverse-code/kit/exts/omni.kit.documentation.builder/config/extension.toml | [package]
version = "1.0.9"
authors = ["NVIDIA"]
title = "Omni.UI Documentation Builder"
description="The interactive documentation builder for omni.ui extensions"
readme = "docs/README.md"
category = "Documentation"
keywords = ["ui", "example", "docs", "documentation", "builder"]
changelog="docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
# Moved from https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-widgets
repository = ""
[dependencies]
"omni.kit.window.filepicker" = {}
[documentation]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
menu = "Help/API/omni.kit.documentation.builder"
title = "Omni UI Documentation Builder"
[[python.module]]
name = "omni.kit.documentation.builder"
[[python.scriptFolder]]
path = "scripts"
[[test]]
|
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_capture.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["DocumentationBuilderCapture"]
import asyncio
import omni.appwindow
import omni.kit.app
import omni.kit.imgui_renderer
import omni.kit.renderer.bind
import omni.renderer_capture
import omni.ui as ui
class DocumentationBuilderCapture:
r"""
Captures the omni.ui widgets to the image file. Works like this:
with Capture("c:\temp\1.png", 600, 600):
ui.Button("Hello World")
"""
def __init__(self, path: str, width: int, height: int, window_name: str = "Capture Window"):
self._path: str = path
self._dpi = ui.Workspace.get_dpi_scale()
self._width: int = int(width * self._dpi)
self._height: int = int(height * self._dpi)
self._window_name: str = window_name
# Interfaces
self._app_window_factory = omni.appwindow.acquire_app_window_factory_interface()
self._renderer = omni.kit.renderer.bind.acquire_renderer_interface()
self._imgui_renderer = omni.kit.imgui_renderer.acquire_imgui_renderer_interface()
self._renderer_capture = omni.renderer_capture.acquire_renderer_capture_interface()
self._virtual_app_window = None
self._window = None
def __enter__(self):
# Create virtual OS window
self._virtual_app_window = self._app_window_factory.create_window_by_type(omni.appwindow.WindowType.VIRTUAL)
self._virtual_app_window.startup_with_desc(
title=self._window_name,
width=self._width,
height=self._height,
scale_to_monitor=False,
dpi_scale_override=1.0,
)
self._imgui_renderer.attach_app_window(self._virtual_app_window)
# Create omni.ui window
self._window = ui.Window(self._window_name, flags=ui.WINDOW_FLAGS_NO_TITLE_BAR, padding_x=0, padding_y=0)
self._window.move_to_app_window(self._virtual_app_window)
self._window.width = self._width
self._window.height = self._height
# Enter the window frame
self._window.frame.__enter__()
def __exit__(self, exc_type, exc_val, exc_tb):
# Exit the window frame
self._window.frame.__exit__(exc_type, exc_val, exc_tb)
# Capture and detach at the next frame
asyncio.ensure_future(
DocumentationBuilderCapture.__capture_detach(
self._renderer_capture, self._path, self._renderer, self._virtual_app_window, self._window
)
)
@staticmethod
async def __capture_detach(renderer_capture, path, renderer, iappwindow, window):
# The next frame
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
# Capture
renderer_capture.capture_next_frame_texture(path, renderer.get_framebuffer_texture(iappwindow), iappwindow)
await omni.kit.app.get_app().next_update_async()
# Detach
renderer.detach_app_window(iappwindow)
|
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_window.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["DocumentationBuilderWindow"]
import weakref
import carb
import omni.ui as ui
from omni.kit.widget.filebrowser import FileBrowserItem
from omni.kit.window.filepicker import FilePickerDialog
from .documentation_capture import DocumentationBuilderCapture
from .documentation_catalog import DocumentationBuilderCatalog
from .documentation_md import DocumentationBuilderMd
from .documentation_page import DocumentationBuilderPage
from .documentation_style import get_style
class DocumentationBuilderWindow(ui.Window):
"""The window with the documentation"""
def __init__(self, title: str, **kwargs):
"""
### Arguments
`title: str`
The title of the window.
`filenames: List[str]`
The list of .md files to process.
`show_catalog: bool`
Show catalog pane (default True)
"""
self._pages = []
self._catalog = None
self.__content_frame = None
self.__content_page = None
self.__source_filenames = kwargs.pop("filenames", [])
self._show_catalog = kwargs.pop("show_catalog", True)
if "width" not in kwargs:
kwargs["width"] = 1200
if "height" not in kwargs:
kwargs["height"] = 720
if "flags" not in kwargs:
kwargs["flags"] = ui.WINDOW_FLAGS_NO_SCROLL_WITH_MOUSE | ui.WINDOW_FLAGS_NO_SCROLLBAR
super().__init__(title, **kwargs)
self._set_style()
self.frame.set_build_fn(self.__build_window)
self.__pick_folder_dialog = None
def get_page_names(self):
"""Names of all the pages to use in `set_page`"""
return [p.name for p in self._pages]
def set_page(self, name: str = None, scroll_to: str = None):
"""
Set current page
### Arguments
`name: str`
The name of the page to switch to. If None, it will set the
first page.
`scroll_to: str`
The name of the section to scroll to.
"""
if self.__content_page and self.__content_page.name == name:
self.__content_page.scroll_to(scroll_to)
return
if name is None:
page = self._pages[0]
else:
page = next((p for p in self._pages if p.name == name), None)
if page:
if self.__content_page:
self.__content_page.destroy()
with self.__content_frame:
self.__content_page = DocumentationBuilderPage(page, scroll_to)
def generate_for_sphinx(self, path: str):
"""
Produce the set of files and screenshots readable by Sphinx.
### Arguments
`path: str`
The path to produce the files.
"""
for page in self._pages:
for code_block in page.code_blocks:
image_file = f"{path}/{code_block['name']}.png"
height = int(code_block["height"] or 200)
with DocumentationBuilderCapture(image_file, 800, height):
with ui.ZStack():
# Background
ui.Rectangle(name="code_background")
# The code
with ui.VStack():
# flake8: noqa: PLW0212
self.__content_page._execute_code(code_block["code"])
carb.log_info(f"[omni.docs] Generated image: '{image_file}'")
md_file = f"{path}/{page.name}.md"
with open(md_file, "w", encoding="utf-8") as f:
f.write(page.source)
carb.log_info(f"[omni.docs] Generated md file: '{md_file}'")
def destroy(self):
if self.__pick_folder_dialog:
self.__pick_folder_dialog.destroy()
self.__pick_folder_dialog = None
if self._catalog:
self._catalog.destroy()
self._catalog = None
for page in self._pages:
page.destroy()
self._pages = []
if self.__content_page:
self.__content_page.destroy()
self.__content_page = None
self.__content_frame = None
super().destroy()
@staticmethod
def get_style():
"""
Deprecated: use omni.kit.documentation.builder.get_style()
"""
return get_style()
def _set_style(self):
self.frame.set_style(get_style())
def __build_window(self):
"""Called to build the widgets of the window"""
self.__reload_pages()
def __on_export(self):
"""Open Pick Folder dialog to add compounds"""
if self.__pick_folder_dialog:
self.__pick_folder_dialog.destroy()
self.__pick_folder_dialog = FilePickerDialog(
"Pick Output Folder",
apply_button_label="Use This Folder",
click_apply_handler=self.__on_apply_folder,
item_filter_options=["All Folders (*)"],
item_filter_fn=self.__on_filter_folder,
)
def __on_apply_folder(self, filename: str, root_path: str):
"""Called when the user press "Use This Folder" in the pick folder dialog"""
self.__pick_folder_dialog.hide()
self.generate_for_sphinx(root_path)
@staticmethod
def __on_filter_folder(item: FileBrowserItem) -> bool:
"""Used by pick folder dialog to hide all the files"""
return item.is_folder
def __reload_pages(self):
"""Called to reload all the pages"""
# Properly destroy all the past pages
for page in self._pages:
page.destroy()
self._pages = []
# Reload the pages at the drawing time
for page_source in self.__source_filenames:
if page_source.endswith(".md"):
self._pages.append(DocumentationBuilderMd(page_source))
def keep_page_name(page, catalog_data):
"""Puts the page name to the catalog data"""
for c in catalog_data:
c["page"] = page
keep_page_name(page, c["children"])
catalog_data = []
for page in self._pages:
catalog = page.catalog
keep_page_name(page.name, catalog)
catalog_data += catalog
# The layout
with ui.HStack():
if self._show_catalog:
self._catalog = DocumentationBuilderCatalog(
catalog_data,
weakref.ref(self),
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
width=300,
settings_menu=[{"name": "Export Markdown", "clicked_fn": self.__on_export}],
)
with ui.ZStack():
ui.Rectangle(name="content_background")
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style={"ScrollingFrame": {"background_color": 0x0}},
):
self.__content_frame = ui.Frame(height=1)
self.set_page()
|
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/__init__.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = [
"create_docs_window",
"DocumentationBuilder",
"DocumentationBuilderCatalog",
"DocumentationBuilderMd",
"DocumentationBuilderPage",
"DocumentationBuilderWindow",
"generate_for_sphinx",
"get_style",
]
from .documentation_catalog import DocumentationBuilderCatalog
from .documentation_extension import DocumentationBuilder, create_docs_window
from .documentation_generate import generate_for_sphinx
from .documentation_md import DocumentationBuilderMd
from .documentation_page import DocumentationBuilderPage
from .documentation_style import get_style
from .documentation_window import DocumentationBuilderWindow
|
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_catalog.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["DocumentationBuilderCatalog"]
import asyncio
import weakref
from typing import Any, Dict, List
import omni.kit.app
import omni.ui as ui
class _CatalogModelItem(ui.AbstractItem):
def __init__(self, catalog_data):
super().__init__()
self.__catalog_data = catalog_data
self.name_model = ui.SimpleStringModel(catalog_data["name"])
self.__children = None
self.widget = None
def destroy(self):
for c in self.__children or []:
c.destroy()
self.__children = None
self.__catalog_data = None
self.widget = None
@property
def page_name(self):
return self.__catalog_data["page"]
@property
def children(self):
if self.__children is None:
# Lazy initialization
self.__children = [_CatalogModelItem(c) for c in self.__catalog_data.get("children", [])]
return self.__children
class _CatalogModel(ui.AbstractItemModel):
def __init__(self, catalog_data):
super().__init__()
self.__root = _CatalogModelItem({"name": "Root", "children": catalog_data})
def destroy(self):
self.__root.destroy()
self.__root = None
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is None:
return self.__root.children
return item.children
def get_item_value_model_count(self, item):
"""The number of columns"""
return 1
def get_item_value_model(self, item, column_id):
"""
Return value model.
"""
return item.name_model
class _CatalogDelegate(ui.AbstractItemDelegate):
def destroy(self):
pass
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
name = f"tree{level+1}"
with ui.ZStack(width=(level + 1) * 20):
ui.Rectangle(height=28, name=name)
if level > 0:
with ui.VStack():
ui.Spacer()
with ui.HStack(height=10):
ui.Spacer()
if model.can_item_have_children(item):
image = "minus" if expanded else "plus"
ui.Image(name=image, width=10, height=10)
ui.Spacer()
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per column per item"""
name = f"tree{level}"
label = model.get_item_value_model(item, column_id).as_string
if level == 1:
label = label.upper()
with ui.ZStack():
ui.Rectangle(height=28, name=name)
with ui.VStack():
item.widget = ui.Label(label, name=name, style_type_name_override="Text")
class DocumentationBuilderCatalog:
"""The left panel"""
def __init__(self, catalog_data, parent: weakref, **kwargs):
"""
`settings_menu: List[Dict[str, Any]]`
List of items. [{"name": "Export", "clicked_fn": on_export}]
"""
width = kwargs.get("width", 200)
self.__settings_menu: List[Dict[str, Any]] = kwargs.pop("settings_menu", None)
self._model = _CatalogModel(catalog_data)
self._delegate = _CatalogDelegate()
self.__parent = parent
with ui.ScrollingFrame(**kwargs):
with ui.VStack(height=0):
with ui.ZStack():
ui.Image(height=width, name="main_logo")
if self.__settings_menu:
with ui.Frame(height=16, width=16, mouse_hovered_fn=self._on_settings_hovered):
self.__settings_image = ui.Image(
name="settings", visible=False, mouse_pressed_fn=self._on_settings
)
tree_view = ui.TreeView(
self._model,
name="catalog",
delegate=self._delegate,
root_visible=False,
header_visible=False,
selection_changed_fn=self.__selection_changed,
)
# Generate the TreeView children
ui.Inspector.get_children(tree_view)
# Expand the first level
for i in self._model.get_item_children(None):
tree_view.set_expanded(i, True, False)
self.__stop_event = asyncio.Event()
self._menu = None
def destroy(self):
self.__settings_menu = []
self.__stop_event.set()
self.__settings_image = None
self._model.destroy()
self._model = None
self._delegate.destroy()
self._delegate = None
self._menu = None
async def _show_settings(self, delay, event: asyncio.Event):
for _i in range(delay):
await omni.kit.app.get_app().next_update_async()
if event.is_set():
return
self.__settings_image.visible = True
def _on_settings_hovered(self, hovered):
self.__stop_event.set()
self.__settings_image.visible = False
if hovered:
self.__stop_event = asyncio.Event()
asyncio.ensure_future(self._show_settings(100, self.__stop_event))
def _on_settings(self, x, y, button, mod):
self._menu = ui.Menu("Scene Docs Settings")
with self._menu:
for item in self.__settings_menu:
ui.MenuItem(item["name"], triggered_fn=item["clicked_fn"])
self._menu.show()
def __selection_changed(self, selection):
if not selection:
return
self.__parent().set_page(selection[0].page_name, selection[0].name_model.as_string)
|
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_md.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["DocumentationBuilderMd"]
import re
from enum import Enum, auto
from pathlib import Path
from typing import Any, Dict, List, NamedTuple, Tuple, Union
import omni.client as client
H1_CHECK = re.compile(r"# .*")
H2_CHECK = re.compile(r"## .*")
H3_CHECK = re.compile(r"### .*")
PARAGRAPH_CHECK = re.compile(r"[a-zA-Z0-9].*")
LIST_CHECK = re.compile(r"^[-+] [a-zA-Z0-9].*$")
CODE_CHECK = re.compile(r"```.*")
IMAGE_CHECK = re.compile('!\\[(?P<alt>[^\\]]*)\\]\\((?P<url>.*?)(?=\\"|\\))(?P<title>\\".*\\")?\\)')
LINK_CHECK = re.compile(r"\[(.*)\]\((.*)\)")
LINK_IN_LIST = re.compile(r"^[-+] \[(.*)\]\((.*)\)")
TABLE_CHECK = re.compile(r"^(?:\s*\|.+)+\|\s*$")
class _BlockType(Enum):
H1 = auto()
H2 = auto()
H3 = auto()
PARAGRAPH = auto()
LIST = auto()
CODE = auto()
IMAGE = auto()
LINK = auto()
TABLE = auto()
LINK_IN_LIST = auto()
class _Block(NamedTuple):
block_type: _BlockType
text: Union[str, Tuple[str]]
source: str
metadata: Dict[str, Any]
class DocumentationBuilderMd:
"""
The cache for .md file.
It contains parsed data, catalog, links, etc...
"""
def __init__(self, filename: str):
"""
### Arguments
`filename : str`
Path to .md file
"""
self.__filename = filename
self.__blocks: List[_Block] = []
result, _, content = client.read_file(f"{filename}")
if result != client.Result.OK:
content = ""
else:
content = memoryview(content).tobytes().decode("utf-8")
self._process_lines(content.splitlines())
def destroy(self):
pass
@property
def blocks(self):
return self.__blocks
@property
def catalog(self):
"""
Return the document outline in the following format:
{"name": "h1", "children": []}
"""
result = []
blocks = [b for b in self.__blocks if b.block_type in [_BlockType.H1, _BlockType.H2, _BlockType.H3]]
if blocks:
self._get_catalog_recursive(blocks, result, blocks[0].block_type.value)
return result
@property
def source(self) -> str:
content = []
code_id = 0
page_name = self.name
for block in self.__blocks:
if block.block_type == _BlockType.CODE:
content.append(self._source_code(block, page_name, code_id))
code_id += 1
else:
content.append(block.source)
return "\n\n".join(content) + "\n"
@property
def code_blocks(self) -> List[Dict[str, str]]:
page_name = self.name
blocks = [b for b in self.__blocks if b.block_type == _BlockType.CODE]
return [
{"name": f"{page_name}_{i}", "code": block.text, "height": block.metadata["height"]}
for i, block in enumerate(blocks)
if block.metadata.get("code_type", None) == "execute"
]
@property
def image_blocks(self) -> List[Dict[str, str]]:
return [
{"path": block.text, "alt": block.metadata["alt"], "title": block.metadata["title"]}
for block in self.__blocks
if block.block_type == _BlockType.IMAGE
]
@property
def name(self):
first_header = next(
(b for b in self.__blocks if b.block_type in [_BlockType.H1, _BlockType.H2, _BlockType.H3]), None
)
return first_header.text if first_header else None
def _get_catalog_recursive(self, blocks: List[_Block], children: List[Dict], level: int):
while blocks:
top = blocks[0]
top_level = top.block_type.value
if top_level == level:
children.append({"name": top.text, "children": []})
blocks.pop(0)
elif top_level > level:
self._get_catalog_recursive(blocks, children[-1]["children"], top_level)
else: # top_level < level
return
def _add_block(self, block_type, text, source, **kwargs):
self.__blocks.append(_Block(block_type, text, source, kwargs))
def _process_lines(self, content):
# Remove empty lines
while True:
while content and not content[0].strip():
content.pop(0)
if not content:
break
if H1_CHECK.match(content[0]):
self._process_h1(content)
elif H2_CHECK.match(content[0]):
self._process_h2(content)
elif H3_CHECK.match(content[0]):
self._process_h3(content)
elif CODE_CHECK.match(content[0]):
self._process_code(content)
elif IMAGE_CHECK.match(content[0]):
self._process_image(content)
elif LINK_CHECK.match(content[0]):
self._process_link(content)
elif LINK_IN_LIST.match(content[0]):
self._process_link_in_list(content)
elif LIST_CHECK.match(content[0]):
self._process_list(content)
elif TABLE_CHECK.match(content[0]):
self._process_table(content)
else:
self._process_paragraph(content)
def _process_h1(self, content):
text = content.pop(0)
self._add_block(_BlockType.H1, text[2:], text)
def _process_h2(self, content):
text = content.pop(0)
self._add_block(_BlockType.H2, text[3:], text)
def _process_h3(self, content):
text = content.pop(0)
self._add_block(_BlockType.H3, text[4:], text)
def _process_list(self, content: List[str]):
text_lines = []
while True:
current_line = content.pop(0)
text_lines.append(current_line.strip())
if not content or not LIST_CHECK.match(content[0]):
# The next line is not a paragraph.
break
self._add_block(_BlockType.LIST, tuple(text_lines), "\n".join(text_lines))
def _process_table(self, content: List[str]):
text_lines = []
while True:
current_line = content.pop(0)
text_lines.append(current_line.strip())
if not content or not TABLE_CHECK.match(content[0]):
# The next line is not a paragraph.
break
self._add_block(_BlockType.TABLE, tuple(text_lines), "\n".join(text_lines))
def _process_link(self, content):
text = content.pop(0)
self._add_block(_BlockType.LINK, text, text)
def _process_link_in_list(self, content: List[str]):
text_lines = []
while True:
current_line = content.pop(0)
text_lines.append(current_line.strip())
if not content or not LINK_CHECK.match(content[0]):
# The next line is not a link in a list.
break
self._add_block(_BlockType.LINK_IN_LIST, tuple(text_lines), "\n".join(text_lines))
def _process_paragraph(self, content: List[str]):
text_lines = []
while True:
current_line = content.pop(0)
text_lines.append(current_line.strip())
if current_line.endswith(" "):
# To create a line break, end a line with two or more spaces.
break
if not content or not PARAGRAPH_CHECK.match(content[0]):
# The next line is not a paragraph.
break
self._add_block(_BlockType.PARAGRAPH, " ".join(text_lines), "\n".join(text_lines))
def _process_code(self, content):
source = []
text = content.pop(0)
source.append(text)
code_type = text[3:].strip().split()
# Extract height
if code_type and len(code_type) > 1:
height = code_type[1]
else:
height = None
if code_type:
code_type = code_type[0]
else:
code_type = ""
code_lines = []
while content and not CODE_CHECK.match(content[0]):
text = content.pop(0)
source.append(text)
code_lines.append(text)
source.append(content.pop(0))
self._add_block(_BlockType.CODE, "\n".join(code_lines), "\n".join(source), code_type=code_type, height=height)
def _process_image(self, content: List[str]):
text = content.pop(0)
parts = IMAGE_CHECK.match(text.strip()).groupdict()
path = Path(self.__filename).parent.joinpath(parts["url"])
self._add_block(_BlockType.IMAGE, f"{path}", text, alt=parts["alt"], title=parts["title"])
@staticmethod
def get_clean_code(block):
# Remove double-comments
clean = []
skip = False
for line in block.text.splitlines():
if line.lstrip().startswith("##"):
skip = not skip
continue
if skip:
continue
if not clean and not line.strip():
continue
clean.append(line)
return "\n".join(clean)
def _source_code(self, block, page_name, code_id):
result = []
code_type = block.metadata.get("code_type", "")
if code_type == "execute":
image_name = f"{page_name}_{code_id}.png"
result.append(f"\n")
code_type = "python"
elif code_type == "execute-manual":
code_type = "python"
result.append(f"```{code_type}")
result.append(self.get_clean_code(block))
result.append("```")
return "\n".join(result)
|
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_generate.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["generate_for_sphinx"]
import shutil
import traceback
from pathlib import Path
import carb
import omni.kit.app
import omni.ui as ui
from .documentation_capture import DocumentationBuilderCapture
from .documentation_md import DocumentationBuilderMd
from .documentation_style import get_style
PRINT_GENERATION_STATUS = True # Can be made into setting if needed
def _print(message):
if PRINT_GENERATION_STATUS:
print(message)
else:
carb.log_info(message)
def generate_for_sphinx(extension_id: str, path: str) -> bool:
"""
Produce the set of files and screenshots readable by Sphinx.
### Arguments
`extension_id: str`
The extension to generate documentation files
`path: str`
The path to produce the files.
### Return
`True` if generation succeded.
"""
_print(f"Generating for sphinx. Ext: {extension_id}. Path: {path}")
out_path = Path(path)
if not out_path.is_dir():
carb.log_error(f"{path} is not a directory")
return False
ext_info = omni.kit.app.get_app().get_extension_manager().get_extension_dict(extension_id)
if ext_info is None:
carb.log_error(f"Extension id {extension_id} not found")
return False
if not ext_info.get("state", {}).get("enabled", False):
carb.log_error(f"Extension id {extension_id} is not enabled")
return False
ext_path = Path(ext_info.get("path", ""))
pages = ext_info.get("documentation", {}).get("pages", [])
if len(pages) == 0:
carb.log_error(f"Extension id {extension_id} has no pages set in [documentation] section of config.")
return False
for page in pages:
_print(f"Processing page: '{page}'")
if not page.endswith(".md"):
_print(f"Not .md, skipping: '{page}'")
continue
page_path = Path(ext_path / page)
md = DocumentationBuilderMd(str(page_path))
if md.name is None:
_print(f"md is None, skipping: '{page}'")
continue
for code_block in md.code_blocks:
image_file = out_path / f"{code_block['name']}.png"
height = int(code_block["height"] or 200)
with DocumentationBuilderCapture(str(image_file), 800, height):
stack = ui.ZStack()
stack.set_style(get_style())
with stack:
# Background
ui.Rectangle(name="code_background")
# The code
with ui.VStack():
try:
_execute_code(code_block["code"])
except Exception as e:
tb = traceback.format_exception(Exception, e, e.__traceback__)
ui.Label(
"".join(tb), name="code", style_type_name_override="Text", skip_draw_when_clipped=True
)
_print(f"Generated image: '{image_file}'")
for image_block in md.image_blocks:
image_file = Path(image_block["path"])
image_out = out_path / image_file.relative_to(page_path.parent)
image_out.parent.mkdir(parents=True, exist_ok=True)
try:
shutil.copyfile(image_file, image_out)
except shutil.SameFileError:
pass
_print(f"Copied image: '{image_out}'")
md_file = out_path / f"{page_path.stem}.md"
with open(md_file, "w", encoding="utf-8") as f:
f.write(md.source)
_print(f"Generated md file: '{md_file}'")
return True
def _execute_code(code: str):
# Wrap the code in a class to provide scoping
indented = "\n".join([" " + line for line in code.splitlines()])
source = f"class Execution:\n def __init__(self):\n{indented}"
locals_from_execution = {}
# flake8: noqa: PLW0122
exec(source, None, locals_from_execution)
locals_from_execution["Execution"]()
|
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_extension.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import os.path
import typing
from functools import partial
import omni.ext
import omni.kit.app
import omni.kit.ui
from .documentation_window import DocumentationBuilderWindow
class DocumentationBuilder(omni.ext.IExt):
"""
Extension to create a documentation window for any extension which has
markdown pages defined in its extension.toml.
Such pages can have inline omni.ui code blocks which are executed.
For example,
[documentation]
pages = ["docs/Overview.md"]
menu = "Help/API/omni.kit.documentation.builder"
title = "Omni UI Documentation Builder"
"""
def __init__(self):
super().__init__()
# cache docs and window by extensions id
self._doc_info: typing.Dict[str, _DocInfo] = {}
self._editor_menu = None
self._extension_enabled_hook = None
self._extension_disabled_hook = None
def on_startup(self, ext_id: str):
self._editor_menu = omni.kit.ui.get_editor_menu()
manager = omni.kit.app.get_app().get_extension_manager()
# add menus for any extensions with docs that are already enabled
all_exts = manager.get_extensions()
for ext in all_exts:
if ext.get("enabled", False):
self._add_docs_menu(ext.get("id"))
# hook into extension enable/disable events if extension specifies "documentation" config key
hooks = manager.get_hooks()
self._extension_enabled_hook = hooks.create_extension_state_change_hook(
self.on_after_extension_enabled,
omni.ext.ExtensionStateChangeType.AFTER_EXTENSION_ENABLE,
ext_dict_path="documentation",
hook_name="omni.kit.documentation.builder",
)
self._extension_disabled_hook = hooks.create_extension_state_change_hook(
self.on_before_extension_disabled,
omni.ext.ExtensionStateChangeType.BEFORE_EXTENSION_DISABLE,
ext_dict_path="documentation",
hook_name="omni.kit.documentation.builder",
)
def on_shutdown(self):
self._extension_enabled_hook = None
self._extension_disabled_hook = None
for ext_id in list(self._doc_info.keys()):
self._destroy_docs_window(ext_id)
self._editor_menu = None
def on_after_extension_enabled(self, ext_id: str, *_):
self._add_docs_menu(ext_id)
def on_before_extension_disabled(self, ext_id: str, *_):
self._destroy_docs_window(ext_id)
def _add_docs_menu(self, ext_id: str):
doc_info = _get_doc_info(ext_id)
if doc_info and doc_info.menu_path and self._editor_menu:
doc_info.menu = self._editor_menu.add_item(doc_info.menu_path, partial(self._show_docs_window, ext_id))
self._doc_info[ext_id] = doc_info
def _show_docs_window(self, ext_id: str, *_):
window = self._doc_info[ext_id].window
if not window:
window = _create_docs_window(ext_id)
self._doc_info[ext_id].window = window
window.visible = True
def _destroy_docs_window(self, ext_id: str):
if ext_id in self._doc_info:
doc_info = self._doc_info.pop(ext_id)
if doc_info.window:
doc_info.window.destroy()
def create_docs_window(ext_name: str):
"""
Creates a DocumentationBuilderWindow for ext_name
Returns the window, or None if no such extension is enabled and has documentation
"""
# fetch by name
ext_versions = omni.kit.app.get_app().get_extension_manager().fetch_extension_versions(ext_name)
# use latest version that is enabled
for ver in ext_versions:
if ver.get("enabled", False):
return _create_docs_window(ver.get("id", ""))
return None
def _create_docs_window(ext_id: str):
"""
Creates a DocumentationBuilderWindow for ext_id
Returns the window, or None if ext_id has no documentation
"""
doc_info = _get_doc_info(ext_id)
if doc_info:
window = DocumentationBuilderWindow(doc_info.title, filenames=doc_info.pages)
return window
return None
class _DocInfo:
def __init__(self):
self.pages = []
self.menu_path = ""
self.title = ""
self.window = None
self.menu = None
def _get_doc_info(ext_id: str) -> _DocInfo:
"""
Returns extension documentation metadata if it exists.
Returns None if exension has no documentation pages.
"""
ext_info = omni.kit.app.get_app().get_extension_manager().get_extension_dict(ext_id)
if ext_info:
ext_path = ext_info.get("path", "")
doc_dict = ext_info.get("documentation", {})
doc_info = _DocInfo()
doc_info.pages = doc_dict.get("pages", [])
doc_info.menu_path = doc_dict.get("menu", "Help/API/" + ext_id)
doc_info.title = doc_dict.get("title", ext_id)
filenames = []
for page in doc_info.pages:
filenames.append(page if os.path.isabs(page) else os.path.join(ext_path, page))
if filenames:
doc_info.pages = filenames
return doc_info
return None
|
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_page.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["DocumentationBuilderPage"]
import re
import subprocess
import sys
import traceback
import weakref
import webbrowser
from functools import partial
from typing import Any, Dict, List, Optional
import omni.ui as ui
from PIL import Image
from .documentation_md import LINK_CHECK, DocumentationBuilderMd, _Block, _BlockType
class DocumentationBuilderPage:
"""
Widget that draws .md page with the cache.
"""
def __init__(self, md: DocumentationBuilderMd, scroll_to: Optional[str] = None):
"""
### Arguments
`md : DocumentationBuilderMd`
MD cache object
`scroll_to : Optional[str]`
The name of the section to scroll to
"""
self.__md = md
self.__scroll_to = scroll_to
self.__images: List[ui.Image] = []
self.__code_stacks: List[ui.ZStack] = []
self.__code_locals: Dict[str, Any] = {}
self._copy_context_menu = None
self.__bookmarks: Dict[str, ui.Widget] = {}
self._dont_scale_images = False
ui.Frame(build_fn=self.__build)
def destroy(self):
self.__bookmarks: Dict[str, ui.Widget] = {}
if self._copy_context_menu:
self._copy_context_menu.destroy()
self._copy_context_menu = None
self.__code_locals = {}
for stack in self.__code_stacks:
stack.destroy()
self.__code_stacks = []
for image in self.__images:
image.destroy()
self.__images = []
@property
def name(self):
"""The name of the page"""
return self.__md.name
def scroll_to(self, where: str):
"""Scroll to the given section"""
widget = self.__bookmarks.get(where, None)
if widget:
widget.scroll_here()
def _execute_code(self, code: str):
indented = "\n".join([" " + line for line in code.splitlines()])
source = f"class Execution:\n def __init__(self):\n{indented}"
locals_from_execution = {}
# flake8: noqa: PLW0122
exec(source, None, locals_from_execution)
self.__code_locals[code] = locals_from_execution["Execution"]()
def __build(self):
self.__bookmarks: Dict[str, ui.Widget] = {}
with ui.HStack():
ui.Spacer(width=50)
with ui.VStack(height=0):
ui.Spacer(height=50)
for block in self.__md.blocks:
# Build sections one by one
# Space between sections
space = ui.Spacer(height=10)
self.__bookmarks[block.text] = space
if block.text == self.__scroll_to:
# Scroll to this section if necessary
space.scroll_here()
if block.block_type == _BlockType.H1:
self._build_h1(block)
elif block.block_type == _BlockType.H2:
self._build_h2(block)
elif block.block_type == _BlockType.H3:
self._build_h3(block)
elif block.block_type == _BlockType.PARAGRAPH:
self._build_paragraph(block)
elif block.block_type == _BlockType.LIST:
self._build_list(block)
elif block.block_type == _BlockType.TABLE:
self._build_table(block)
elif block.block_type == _BlockType.LINK:
self._build_link(block)
elif block.block_type == _BlockType.CODE:
self._build_code(block)
elif block.block_type == _BlockType.IMAGE:
self._build_image(block)
elif block.block_type == _BlockType.LINK_IN_LIST:
self._build_link_in_list(block)
ui.Spacer(height=50)
ui.Spacer(width=50)
def _build_h1(self, block: _Block):
with ui.ZStack():
ui.Rectangle(name="h1")
ui.Label(block.text, name="h1", style_type_name_override="Text")
def _build_h2(self, block: _Block):
with ui.VStack():
ui.Line(name="h2")
ui.Label(block.text, name="h2", style_type_name_override="Text")
ui.Line(name="h2")
def _build_h3(self, block: _Block):
with ui.VStack(height=0):
ui.Line(name="h3")
ui.Label(block.text, name="h3", style_type_name_override="Text")
ui.Line(name="h3")
def _build_paragraph(self, block: _Block):
ui.Label(block.text, name="paragraph", word_wrap=True, skip_draw_when_clipped=True)
def _build_list(self, block: _Block):
with ui.VStack(spacing=-5):
for list_entry in block.text:
list_entry = list_entry.lstrip("+")
list_entry = list_entry.lstrip("-")
with ui.HStack(spacing=0):
ui.Circle(
width=10, size_policy=ui.CircleSizePolicy.FIXED, alignment=ui.Alignment.LEFT_CENTER, radius=3
)
ui.Label(
list_entry,
alignment=ui.Alignment.LEFT_TOP,
name="paragraph",
word_wrap=True,
skip_draw_when_clipped=True,
)
# ui.Spacer(width=5)
def _build_link_in_list(self, block: _Block):
with ui.VStack(spacing=-5):
for list_entry in block.text:
list_entry = list_entry.lstrip("+")
list_entry = list_entry.lstrip("-")
list_entry = list_entry.lstrip()
with ui.HStack(spacing=0):
ui.Circle(
width=10, size_policy=ui.CircleSizePolicy.FIXED, alignment=ui.Alignment.LEFT_CENTER, radius=3
)
reg = re.match(LINK_CHECK, list_entry)
if reg and len(reg.groups()) == 2:
self._build_link_impl(reg.group(1), reg.group(2))
def _build_link(self, block: _Block):
text = block.text
reg = re.match(LINK_CHECK, text)
label = ""
url = ""
if reg and len(reg.groups()) == 2:
label = reg.group(1)
url = reg.group(2)
self._build_link_impl(label, url)
def _build_link_impl(self, label, url):
def _on_clicked(a, b, c, d, url):
try:
webbrowser.open(url)
except OSError:
print("Please open a browser on: " + url)
with ui.HStack():
spacer = ui.Spacer(width=5)
label = ui.Label(
label,
style_type_name_override="url_link",
name="paragraph",
word_wrap=True,
skip_draw_when_clipped=True,
tooltip=url,
)
label.set_mouse_pressed_fn(lambda a, b, c, d, u=url: _on_clicked(a, b, c, d, u))
def _build_table(self, block: _Block):
cells = []
num_columns = 0
for line in block.text:
cell_text_list = line.split("|")
cell_text_list = [c.strip() for c in cell_text_list]
cell_text_list = [c for c in cell_text_list if c]
num_columns = max(num_columns, len(cell_text_list))
cells.append(cell_text_list)
# Assume 2nd row is separators "|------|---|"
del cells[1]
frame_pixel_width = 800
grid_column_width = frame_pixel_width / num_columns
frame_pixel_height = len(cells) * 20
with ui.ScrollingFrame(
width=frame_pixel_width,
height=frame_pixel_height,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
):
with ui.VGrid(column_width=grid_column_width, row_height=20):
for i in range(len(cells)):
for j in range(num_columns):
with ui.ZStack():
bg_color = 0xFFCCCCCC if i == 0 else 0xFFFFFFF
ui.Rectangle(
style={
"border_color": 0xFF000000,
"background_color": bg_color,
"border_width": 1,
"margin": 0,
}
)
cell_val = cells[i][j]
if len(cell_val) > 66:
cell_val = cell_val[:65] + "..."
ui.Label(f"{cell_val}", style_type_name_override="table_label")
def _build_code(self, block: _Block):
def label_size_changed(label: ui.Label, short_frame: ui.Frame, overlay: ui.Frame):
max_height = ui.Pixel(200)
if label.computed_height > max_height.value:
short_frame.height = max_height
short_frame.vertical_clipping = True
with overlay:
with ui.VStack():
ui.Spacer()
with ui.ZStack():
ui.Rectangle(style_type_name_override="TextOverlay")
ui.InvisibleButton(clicked_fn=partial(remove_overlay, label, short_frame, overlay))
def remove_overlay(label: ui.Label, short_frame: ui.Frame, overlay: ui.Frame):
short_frame.height = ui.Pixel(label.computed_height)
with overlay:
ui.Spacer()
code_type = block.metadata.get("code_type", None)
is_execute_manual = code_type == "execute-manual"
is_execute = code_type == "execute"
if is_execute:
with ui.Frame(horizontal_clipping=True):
with ui.ZStack():
# Background
ui.Rectangle(name="code_background")
# The code
with ui.VStack():
try:
self._execute_code(block.text)
except Exception as e:
tb = traceback.format_exception(Exception, e, e.__traceback__)
ui.Label(
"".join(tb), name="code", style_type_name_override="Text", skip_draw_when_clipped=True
)
ui.Spacer(height=10)
# Remove double-comments
clean = DocumentationBuilderMd.get_clean_code(block)
with ui.Frame(horizontal_clipping=True):
stack = ui.ZStack(height=0)
with stack:
ui.Rectangle(name="code")
short_frame = ui.Frame()
with short_frame:
label = ui.Label(clean, name="code", style_type_name_override="Text", skip_draw_when_clipped=True)
overlay = ui.Frame()
# Enable clipping/extending the label after we know its size
label.set_computed_content_size_changed_fn(partial(label_size_changed, label, short_frame, overlay))
self.__code_stacks.append(stack)
if is_execute_manual:
ui.Spacer(height=4)
with ui.HStack():
# ui.Spacer(height=10)
def on_click(text=block.text):
try:
self._execute_code(block.text)
except Exception as e:
tb = traceback.format_exception(Exception, e, e.__traceback__)
ui.Label("".join(tb), name="code", style_type_name_override="Text", skip_draw_when_clipped=True)
button = ui.Button(
"RUN CODE", style_type_name_override="RunButton", width=50, height=20, clicked_fn=on_click
)
ui.Spacer()
if sys.platform != "linux":
stack.set_mouse_pressed_fn(lambda x, y, b, m, text=clean: b == 1 and self._show_copy_menu(x, y, b, m, text))
def _build_image(self, block: _Block):
source_url = block.text
def change_resolution_legacy(image_weak, size):
"""
Change the widget size proportionally to the image
We set a max height of 400 for anything.
"""
MAX_HEIGHT = 400
image = image_weak()
if not image:
return
width, height = size
image_height = min(image.computed_content_width * height / width, MAX_HEIGHT)
image.height = ui.Pixel(image_height)
def change_resolution(image_weak, size):
"""
This leaves the image scale untouched
"""
image = image_weak()
if not image:
return
width, height = size
image.height = ui.Pixel(height)
image.width = ui.Pixel(width)
im = Image.open(source_url)
image = ui.Image(source_url, height=200)
# Even though the legacy behaviour is probably wrong there are extensions out there with images that are
# too big, we don't want them to display differently than before
if self._dont_scale_images:
image.set_computed_content_size_changed_fn(partial(change_resolution, weakref.ref(image), im.size))
else:
image.set_computed_content_size_changed_fn(partial(change_resolution_legacy, weakref.ref(image), im.size))
self.__images.append(image)
def _show_copy_menu(self, x, y, button, modifier, text):
"""The context menu to copy the text"""
# Display context menu only if the right button is pressed
def copy_text(text_value):
# we need to find a cross plartform way currently Window Only
subprocess.run(["clip.exe"], input=text_value.strip().encode("utf-8"), check=True)
# Reset the previous context popup
self._copy_context_menu = ui.Menu("Copy Context Menu")
with self._copy_context_menu:
ui.MenuItem("Copy Code", triggered_fn=lambda t=text: copy_text(t))
# Show it
self._copy_context_menu.show()
|
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_style.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from pathlib import Path
import omni.ui as ui
from omni.ui import color as cl
from omni.ui import constant as fl
from omni.ui import url
CURRENT_PATH = Path(__file__).parent
DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data")
FONTS_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("fonts")
def get_style():
"""
Returns the standard omni.ui style for documentation
"""
cl.documentation_nvidia = cl("#76b900")
# Content
cl.documentation_bg = cl.white
cl.documentation_text = cl("#1a1a1a")
cl.documentation_h1_bg = cl.black
cl.documentation_h1_color = cl.documentation_nvidia
cl.documentation_h2_line = cl.black
cl.documentation_h2_color = cl.documentation_nvidia
cl.documentation_exec_bg = cl("#454545")
cl.documentation_code_bg = cl("#eeeeee")
cl.documentation_code_fadeout = cl("#eeeeee01")
cl.documentation_code_fadeout_selected = cl.documentation_nvidia
cl.documentation_code_line = cl("#bbbbbb")
fl.documentation_margin = 5
fl.documentation_code_size = 16
fl.documentation_code_radius = 2
fl.documentation_text_size = 18
fl.documentation_h1_size = 36
fl.documentation_h2_size = 28
fl.documentation_h3_size = 20
fl.documentation_line_width = 0.3
cl.url_link = cl("#3333CC")
# Catalog
cl.documentation_catalog_bg = cl.black
cl.documentation_catalog_text = cl("#cccccc")
cl.documentation_catalog_h1_bg = cl("#333333")
cl.documentation_catalog_h1_color = cl.documentation_nvidia
cl.documentation_catalog_h2_bg = cl("#fcfcfc")
cl.documentation_catalog_h2_color = cl("#404040")
cl.documentation_catalog_h3_bg = cl("#e3e3e3")
cl.documentation_catalog_h3_color = cl("#404040")
cl.documentation_catalog_icon_selected = cl("#333333")
fl.documentation_catalog_tree1_size = 17
fl.documentation_catalog_tree1_margin = 5
fl.documentation_catalog_tree2_size = 19
fl.documentation_catalog_tree2_margin = 2
fl.documentation_catalog_tree3_size = 19
fl.documentation_catalog_tree3_margin = 2
url.documentation_logo = f"{DATA_PATH.joinpath('main_ov_logo_square.png')}"
url.documentation_settings = f"{DATA_PATH.joinpath('settings.svg')}"
url.documentation_plus = f"{DATA_PATH.joinpath('plus.svg')}"
url.documentation_minus = f"{DATA_PATH.joinpath('minus.svg')}"
url.documentation_font_regular = f"{FONTS_PATH}/DINPro-Regular.otf"
url.documentation_font_regular_bold = f"{FONTS_PATH}/DINPro-Bold.otf"
url.documentation_font_monospace = f"{FONTS_PATH}/DejaVuSansMono.ttf"
style = {
"Window": {"background_color": cl.documentation_catalog_bg, "border_width": 0, "padding": 0},
"Rectangle::content_background": {"background_color": cl.documentation_bg},
"Label::paragraph": {
"color": cl.documentation_text,
"font_size": fl.documentation_text_size,
"margin": fl.documentation_margin,
},
"Text::code": {
"color": cl.documentation_text,
"font": url.documentation_font_monospace,
"font_size": fl.documentation_code_size,
"margin": fl.documentation_margin,
},
"url_link": {"color": cl.url_link, "font_size": fl.documentation_text_size},
"table_label": {
"color": cl.documentation_text,
"font_size": fl.documentation_text_size,
"margin": 2,
},
"Rectangle::code": {
"background_color": cl.documentation_code_bg,
"border_color": cl.documentation_code_line,
"border_width": fl.documentation_line_width,
"border_radius": fl.documentation_code_radius,
},
"Rectangle::code_background": {"background_color": cl.documentation_exec_bg},
"Rectangle::h1": {"background_color": cl.documentation_h1_bg},
"Rectangle::tree1": {"background_color": cl.documentation_catalog_h1_bg},
"Rectangle::tree2": {"background_color": 0x0},
"Rectangle::tree2:selected": {"background_color": cl.documentation_catalog_h2_bg},
"Rectangle::tree3": {"background_color": 0x0},
"Rectangle::tree3:selected": {"background_color": cl.documentation_catalog_h3_bg},
"Text::h1": {
"color": cl.documentation_h1_color,
"font": url.documentation_font_regular,
"font_size": fl.documentation_h1_size,
"margin": fl.documentation_margin,
"alignment": ui.Alignment.CENTER,
},
"Text::h2": {
"color": cl.documentation_h2_color,
"font": url.documentation_font_regular,
"font_size": fl.documentation_h2_size,
"margin": fl.documentation_margin,
},
"Text::h3": {
"color": cl.documentation_h2_color,
"font": url.documentation_font_regular,
"font_size": fl.documentation_h3_size,
"margin": fl.documentation_margin,
},
"Text::tree1": {
"color": cl.documentation_catalog_h1_color,
"font": url.documentation_font_regular_bold,
"font_size": fl.documentation_catalog_tree1_size,
"margin": fl.documentation_catalog_tree1_margin,
},
"Text::tree2": {
"color": cl.documentation_catalog_text,
"font": url.documentation_font_regular,
"font_size": fl.documentation_catalog_tree2_size,
"margin": fl.documentation_catalog_tree2_margin,
},
"Text::tree2:selected": {"color": cl.documentation_catalog_h2_color},
"Text::tree3": {
"color": cl.documentation_catalog_text,
"font": url.documentation_font_regular,
"font_size": fl.documentation_catalog_tree3_size,
"margin": fl.documentation_catalog_tree3_margin,
},
"Text::tree3:selected": {"color": cl.documentation_catalog_h3_color},
"Image::main_logo": {"image_url": url.documentation_logo},
"Image::settings": {"image_url": url.documentation_settings},
"Image::plus": {"image_url": url.documentation_plus},
"Image::minus": {"image_url": url.documentation_minus},
"Image::plus:selected": {"color": cl.documentation_catalog_icon_selected},
"Image::minus:selected": {"color": cl.documentation_catalog_icon_selected},
"Line::h2": {"border_width": fl.documentation_line_width},
"Line::h3": {"border_width": fl.documentation_line_width},
"TextOverlay": {
"background_color": cl.documentation_bg,
"background_gradient_color": cl.documentation_code_fadeout,
},
"TextOverlay:hovered": {"background_color": cl.documentation_code_fadeout_selected},
"RunButton": {"background_color": cl("#76b900"), "border_radius": 2},
"RunButton.Label": {"color": 0xFF3E3E3E, "font_size": 14},
"RunButton:hovered": {"background_color": cl("#84d100")},
"RunButton:pressed": {"background_color": cl("#7bc200")},
}
return style
|
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/tests/test_documentation.py | # Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["TestDocumentation"]
import pathlib
import omni.kit.app
import omni.kit.test
from omni.ui.tests.test_base import OmniUiTest
from ..documentation_md import DocumentationBuilderMd
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
TESTS_PATH = EXTENSION_FOLDER_PATH.joinpath("data/tests")
class TestDocumentation(OmniUiTest):
async def test_builder(self):
builder = DocumentationBuilderMd(f"{TESTS_PATH}/test.md")
self.assertEqual(
builder.catalog,
[{"name": "NVIDIA", "children": [{"name": "Omiverse", "children": [{"name": "Doc", "children": []}]}]}],
)
self.assertEqual(builder.blocks[0].text, "NVIDIA")
self.assertEqual(builder.blocks[0].block_type.name, "H1")
self.assertEqual(builder.blocks[1].text, "Omiverse")
self.assertEqual(builder.blocks[1].block_type.name, "H2")
self.assertEqual(builder.blocks[2].text, "Doc")
self.assertEqual(builder.blocks[2].block_type.name, "H3")
self.assertEqual(builder.blocks[3].text, "Text")
self.assertEqual(builder.blocks[3].block_type.name, "PARAGRAPH")
clean = builder.get_clean_code(builder.blocks[4])
self.assertEqual(clean, 'ui.Label("Hello")')
self.assertEqual(builder.blocks[4].block_type.name, "CODE")
self.assertEqual(builder.blocks[5].text, ("- List1", "- List2"))
self.assertEqual(builder.blocks[5].block_type.name, "LIST")
self.assertEqual(builder.blocks[6].text, ("- [YOUTUBE](https://www.youtube.com)",))
self.assertEqual(builder.blocks[6].block_type.name, "LINK_IN_LIST")
self.assertEqual(builder.blocks[7].text, "[NVIDIA](https://www.nvidia.com)")
self.assertEqual(builder.blocks[7].block_type.name, "LINK")
self.assertEqual(
builder.blocks[8].text, ("| Noun | Adjective |", "| ---- | --------- |", "| Omniverse | Awesome |")
)
self.assertEqual(builder.blocks[8].block_type.name, "TABLE")
builder.destroy()
|
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/tests/__init__.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
# flake8: noqa: F401
from .test_documentation import TestDocumentation
|
omniverse-code/kit/exts/omni.kit.documentation.builder/docs/CHANGELOG.md | # Changelog
The interactive documentation builder for omni.ui extensions
## [1.0.9] - 2022-11-16
### Changed
- Remove execute tag from Overview.md for publishing
## [1.0.8] - 2022-08-29
### Added
- List, link, and basic table support
- Show errors from code execute blocks
## [1.0.7] - 2022-06-27
### Added
- Create documentation menu automatically from extension.toml files
## [1.0.6] - 2022-06-22
### Fixed
- Allow md headers without initial H1 level
## [1.0.5] - 2022-06-14
### Added
- Use ui.Label for all text blocks
## [1.0.4] - 2022-05-09
### Fixed
- Missing import
## [1.0.3] - 2022-04-30
### Added
- Minimal test
## [1.0.2] - 2021-12-17
### Added
- `DocumentationBuilderWindow.get_style` to get the default style
## [1.0.1] - 2021-12-15
### Added
- A separate widget for the page `DocumentationBuilderPage`
## [1.0.0] - 2021-12-14
### Added
- The initial implementation
|
omniverse-code/kit/exts/omni.kit.documentation.builder/docs/README.md | # The documentation for omni.ui extensions
The interactive documentation builder for omni.ui extensions |
omniverse-code/kit/exts/omni.kit.documentation.builder/docs/index.rst | omni.kit.documentation.builder
##############################
.. toctree::
:maxdepth: 1
CHANGELOG
|
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")
```
|
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 |
|
omniverse-code/kit/exts/omni.volume/PACKAGE-LICENSES/omni.volume-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. |
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"
|
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
|
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()
|
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)])
|
omniverse-code/kit/exts/omni.volume/omni/volume/tests/__init__.py | from .test_volume import * |
omniverse-code/kit/exts/omni.activity.ui/PACKAGE-LICENSES/omni.activity.ui-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. |
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",
]
|
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()
|
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)
|
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)
|
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)
|
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")
|
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)
|
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)
|
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)
|
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()
|
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/__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.
#
__all__ = ["ActivityWindowExtension", "ActivityWindow", "ActivityProgressBarWindow"]
from .activity_extension import ActivityWindowExtension
from .activity_window import ActivityWindow
from .activity_progress_bar import ActivityProgressBarWindow
from ..bar._bar import *
|
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
|
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
|
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)
|
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)
|
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()
|
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)
|
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/tests/__init__.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .test_window import TestWindow |
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"))
|
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
|
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. |
omniverse-code/kit/exts/omni.kit.window.filepicker/PACKAGE-LICENSES/omni.kit.window.filepicker-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. |
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")
|
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
]
|
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
|
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()
|
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
|
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
|
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)
|
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
|
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 |
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 |
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
|
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)
|
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
|
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"
|
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 |
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),
},
]
|
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()
|
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
|
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
|
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()
|
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
|
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
|
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/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 carb
from omni import ui
from carb import log_warn
from typing import Callable, List
from omni.kit.search_core import SearchEngineRegistry
from .search_delegate import SearchDelegate, SearchResultsModel
from .style import get_style, ICON_PATH
class SearchWordButton:
"""
Represents a search word widget, combined with a label to show the word and a close button to remove it.
Args:
word (str): String of word.
Keyword args:
on_close_fn (callable): Function called when close button clicked. Function signure:
void on_close_fn(widget: SearchWordButton)
"""
def __init__(self, word: str, on_close_fn: callable = None):
self._container = ui.ZStack(width=0)
with self._container:
with ui.VStack():
ui.Spacer(height=5)
ui.Rectangle(style_type_name_override="SearchField.Word")
ui.Spacer(height=5)
with ui.HStack():
ui.Spacer(width=3)
ui.Label(word, width=0, style_type_name_override="SearchField.Word.Label")
ui.Spacer(width=3)
ui.Button(
image_width=8,
style_type_name_override="SearchField.Word.Button",
clicked_fn=lambda: on_close_fn(self) if on_close_fn is not None else None,
)
@property
def visible(self) -> None:
"""Widget visibility"""
return self._container.visible
@visible.setter
def visible(self, value: bool) -> None:
self._container.visible = value
class SearchField(SearchDelegate):
"""
A search field to input search words
Args:
callback (callable): Function called after search done. Function signature: void callback(model: SearchResultsModel)
Keyword Args:
width (Optional[ui.Length]): Widget widthl. Default None, means auto.
height (Optional[ui.Length]): Widget height. Default ui.Pixel(26). Use None for auto.
subscribe_edit_changed (bool): True to retreive on_search_fn called when input changed. Default False only retreive on_search_fn called when input ended.
show_tokens (bool): Default True to show tokens if end edit. Do nothing if False.
Properties:
visible (bool): Widget visibility.
enabled (bool): Enable/Disable widget.
"""
SEARCH_IMAGE_SIZE = 16
CLOSE_IMAGE_SIZE = 12
def __init__(self, callback: Callable, **kwargs):
super().__init__(**kwargs)
self._callback = callback
self._container_args = {"style": get_style()}
if kwargs.get("width") is not None:
self._container_args["width"] = kwargs.get("width")
self._container_args["height"] = kwargs.get("height", ui.Pixel(26))
self._subscribe_edit_changed = kwargs.get("subscribe_edit_changed", False)
self._show_tokens = kwargs.get("show_tokens", True)
self._search_field: ui.StringField = None
self._search_engine = None
self._search_engine_menu = None
self._search_words: List[str] = []
self._in_searching = False
@property
def visible(self):
"""
Widget visibility
"""
return self._container.visible
@visible.setter
def visible(self, value):
self._container.visible = value
@property
def enabled(self):
"""
Enable/disable Widget
"""
return self._container.enabled
@enabled.setter
def enabled(self, value):
self._container.enabled = value
@property
def search_dir(self):
return self._search_dir
@search_dir.setter
def search_dir(self, search_dir: str):
dir_changed = search_dir != self._search_dir
self._search_dir = search_dir
if self._in_searching and dir_changed:
self.search(self._search_words)
def build_ui(self):
self._container = ui.ZStack(**self._container_args)
with self._container:
# background
self._background = ui.Rectangle(style_type_name_override="SearchField.Frame")
with ui.HStack():
with ui.VStack(width=0):
# Search "magnifying glass" button
search_button = ui.Button(
image_url=f"{ICON_PATH}/search.svg",
image_width=SearchField.SEARCH_IMAGE_SIZE,
image_height=SearchField.SEARCH_IMAGE_SIZE,
style_type_name_override="SearchField.Button",
)
search_button.set_clicked_fn(
lambda b=search_button: self._show_engine_menu(
b.screen_position_x, b.screen_position_y + b.computed_height
)
)
with ui.HStack():
with ui.ZStack():
with ui.HStack():
# Individual word widgets
if self._show_tokens:
self._words_container = ui.HStack()
self._build_search_words()
# String field to accept user input, here ui.Spacer for border of SearchField.Frame
with ui.VStack():
ui.Spacer()
with ui.HStack(height=0):
#ui.Spacer(width=2)
self._search_field = ui.StringField(
ui.SimpleStringModel(),
mouse_double_clicked_fn=lambda x, y, btn, m: self._convert_words_to_string(),
style_type_name_override="SearchField",
)
ui.Spacer()
self._hint_container = ui.HStack(spacing=4)
with self._hint_container:
# Hint label
search_label = ui.Label("Search", style_type_name_override="SearchField.Hint")
# Close icon
with ui.VStack(width=20):
ui.Spacer(height=2)
self._clear_button = ui.Button(
image_width=SearchField.CLOSE_IMAGE_SIZE,
style_type_name_override="SearchField.Clear",
clicked_fn=self._on_clear_clicked,
)
ui.Spacer(height=2)
ui.Spacer(width=2)
self._clear_button.visible = False
self._sub_begin_edit = self._search_field.model.subscribe_begin_edit_fn(self._on_begin_edit)
self._sub_end_edit = self._search_field.model.subscribe_end_edit_fn(self._on_end_edit)
if self._subscribe_edit_changed:
self._sub_text_edit = self._search_field.model.subscribe_value_changed_fn(self._on_text_edit)
else:
self._sub_text_edit = None
def destroy(self):
self._callback = None
self._search_field = None
self._sub_begin_edit = None
self._sub_end_edit = None
self._sub_text_edit = None
self._background = None
self._hint_container = None
self._clear_button = None
self._container = None
def _show_engine_menu(self, x, y):
self._search_engine_menu = ui.Menu("Engines")
search_names = SearchEngineRegistry().get_search_names()
if not search_names:
return
# TODO: We need to have predefined default search
if self._search_engine is None:
self._search_engine = search_names[0]
def set_current_engine(engine_name):
self._search_engine = engine_name
with self._search_engine_menu:
for name in search_names:
ui.MenuItem(
name,
checkable=True,
checked=self._search_engine == name,
triggered_fn=lambda n=name: set_current_engine(n),
)
self._search_engine_menu.show_at(x, y)
def _get_search_words(self) -> List[str]:
# Split the input string to words and filter invalid
search_string = self._search_field.model.get_value_as_string()
search_words = [word for word in search_string.split(" ") if word]
if len(search_words) == 0:
return None
elif len(search_words) == 1 and search_words[0] == "":
# If empty input, regard as clear
return None
else:
return search_words
def _on_begin_edit(self, model):
self._set_in_searching(True)
def _on_end_edit(self, model: ui.AbstractValueModel) -> None:
search_words = self._get_search_words()
if search_words is None:
# Filter empty(hidden) word
filter_words = [word for word in self._search_words if word]
if len(filter_words) == 0:
self._set_in_searching(False)
else:
if self._show_tokens:
self._search_words.extend(search_words)
self._build_search_words()
self._search_field.model.set_value("")
else:
self._search_words = search_words
self.search(self._search_words)
def _on_text_edit(self, model: ui.AbstractValueModel) -> None:
new_search_words = self._get_search_words()
if new_search_words is not None:
# Add current input to search words
search_words = []
search_words.extend(self._search_words)
search_words.extend(new_search_words)
self._search_words = search_words
self.search(self._search_words)
def _convert_words_to_string(self) -> None:
if self._show_tokens:
# convert existing search words back to string
filter_words = [word for word in self._search_words if word]
seperator = " "
self._search_words = []
self._build_search_words()
original_string = seperator.join(filter_words)
# Append current input
input_string = self._search_field.model.get_value_as_string()
if input_string:
original_string = original_string + seperator + input_string
self._search_field.model.set_value(original_string)
def _on_clear_clicked(self) -> None:
# Update UI
self._set_in_searching(False)
self._search_field.model.set_value("")
self._search_words.clear()
self._build_search_words()
# Notification
self.search(None)
def _set_in_searching(self, in_searching: bool) -> None:
self._in_searching = in_searching
# Background outline
self._background.selected = in_searching
# Show/Hide hint frame (search icon and hint lable)
self._hint_container.visible = not in_searching
# Show/Hide close image
self._clear_button.visible = in_searching
def _build_search_words(self):
if self._show_tokens:
self._words_container.clear()
if len(self._search_words) == 0:
return
with self._words_container:
ui.Spacer(width=4)
for index, word in enumerate(self._search_words):
if word:
SearchWordButton(word, on_close_fn=lambda widget, idx=index: self._hide_search_word(idx, widget))
def _hide_search_word(self, index: int, widget: SearchWordButton) -> None:
# Here cannot remove the widget since this function is called by the widget
# So just set invisible and change to empty word
# It will be removed later if clear or edit end.
widget.visible = False
if index >= 0 and index < len(self._search_words):
self._search_words[index] = ""
self.search(self._search_words)
def search(self, search_words: List[str]):
"""
Search using selected search engine.
Args:
search_words (List[str]): List of search terms.
"""
# TODO: We need to have predefined default search
if self._search_engine is None:
search_names = SearchEngineRegistry().get_search_names()
self._search_engine = search_names[0] if search_names else None
if self._search_engine:
SearchModel = SearchEngineRegistry().get_search_model(self._search_engine)
else:
log_warn("No search engines registered! Please import a search extension.")
return
if not SearchModel:
log_warn(f"Search engine '{self._search_engine}' not found.")
return
search_words = [word for word in search_words or [] if word] # Filter empty(hidden) word
if len(search_words) > 0:
search_results = SearchModel(search_text=" ".join(search_words), current_dir=self._search_dir)
model = SearchResultsModel(search_results)
else:
model = None
if self._callback:
self._callback(model)
|
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)
|
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)
|
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
|
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)
|
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} |
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
|
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.