file_path
stringlengths 21
207
| content
stringlengths 5
1.02M
| size
int64 5
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/style/style_tree.py |
__all__ = ["StyleTreeView"]
from typing import Dict, cast
from ..tree.inspector_tree import ICON_PATH
import omni.ui as ui
import omni.kit.app
import carb.events
from omni.ui_query import OmniUIQuery
from .style_model import StyleModel
from .style_delegate import StyleTreeDelegate
from .resolved_style import ResolvedStyleWidget
from .style_model import StyleEnumProperty, StyleColorProperties
import json
import omni.kit.clipboard
def int32_color_to_hex(value: int) -> str:
# convert Value from int
red = value & 255
green = (value >> 8) & 255
blue = (value >> 16) & 255
alpha = (value >> 24) & 255
def hex_value_only(value: int):
hex_value = f"{value:#0{4}x}"
return hex_value[2:].upper()
hex_color = f"HEX<0x{hex_value_only(alpha)}{hex_value_only(blue)}{hex_value_only(green)}{hex_value_only(red)}>HEX"
return hex_color
def int_enum_to_constant(value: int, key: str) -> str:
result = ""
if key == "corner_flag":
enum = ui.CornerFlag(value)
result = f"UI.CONSTANT<ui.CornerFlag.{enum.name}>UI.CONSTANT"
elif key == "alignment":
enum = ui.Alignment(value)
result = f"UI.CONSTANT<ui.Alignment.{enum.name}>UI.CONSTANT"
elif key == "fill_policy":
enum = ui.FillPolicy(value)
result = f"UI.CONSTANT<ui.FillPolicy.{enum.name}>UI.CONSTANT"
elif key == "draw_mode":
enum = ui.SliderDrawMode(value)
result = f"UI.CONSTANT<ui.SliderDrawMode.{enum.name}>UI.CONSTANT"
elif key == "stack_direction":
enum = ui.Direction(value)
result = f"UI.CONSTANT<ui.Direction.{enum.name}>UI.CONSTANT"
return result
class StyleTreeView:
"""The Stage widget"""
def __init__(self, **kwargs):
self._widget = None
self._model = StyleModel(self)
self._delegate = StyleTreeDelegate(self._model)
self._main_stack = ui.VStack()
self._build_ui()
app = omni.kit.app.get_app()
self._update_sub = app.get_message_bus_event_stream().create_subscription_to_pop(
self.on_selection_changed, name="Inspector Selection Changed"
)
def on_selection_changed(self, event: carb.events.IEvent):
from ..inspector_widget import INSPECTOR_ITEM_SELECTED_ID
if event.type == INSPECTOR_ITEM_SELECTED_ID:
selection = OmniUIQuery.find_widget(event.payload["item_path"])
if selection:
self.set_widget(selection)
def toggle_visibility(self):
self._main_stack.visible = not self._main_stack.visible
def set_widget(self, widget: ui.Widget):
self._widget = widget
# self._resolved_style.set_widget(widget)
self._model.set_widget(widget)
self._tree_view.set_expanded(None, True, True)
def _build_ui(self):
with self._main_stack:
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Spacer(width=10)
ui.Button(
image_url=f"{ICON_PATH}/copy.svg",
width=20,
height=20,
style={"margin": 0},
clicked_fn=self._copy_style,
)
ui.Label("Styles", height=0, style={"font_size": 16}, alignment=ui.Alignment.CENTER)
ui.Button(
image_url=f"{ICON_PATH}/Add.svg",
style={"margin": 0},
height=20,
width=20,
clicked_fn=self._add_style,
)
ui.Spacer(width=10)
ui.Spacer(height=3)
ui.Line(height=1, style={"color": 0xFF222222, "border_width": 1})
with ui.HStack():
ui.Spacer(width=5)
with ui.VStack():
# ResolvedStyleWidget: Omni.UI API is Broken
# self._resolved_style = ResolvedStyleWidget()
# ui.Spacer(height=10)
ui.Label("Local Styles", height=0)
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style_type_name_override="TreeView.ScrollingFrame",
style={"TreeView.ScrollingFrame": {"background_color": 0xFF333333}},
):
self._tree_view = ui.TreeView(
self._model,
delegate=self._delegate,
column_widths=[ui.Fraction(1), 150],
header_visible=False,
root_visible=False,
)
self._tree_view.set_expanded(None, True, True)
ui.Spacer(width=5)
def _add_style(self):
if not self._widget:
return
style = cast(dict, self._widget.style)
if not style:
style = {}
style["color"] = 0xFF000000
self._widget.set_style(style)
self._model.update_cached_style()
def _copy_style(self):
if self._widget:
style: Dict = cast(Dict, self._widget.style)
if not style:
style = {}
has_type_names = False
# convert numbers to
for key, value in style.items():
if type(value) == dict:
has_type_names = True
for name, internal_value in value.items():
if name in StyleColorProperties:
value[name] = int32_color_to_hex(internal_value)
if name in StyleEnumProperty:
value[name] = int_enum_to_constant(internal_value, name)
else:
if key in StyleColorProperties:
style[key] = int32_color_to_hex(value)
if key in StyleEnumProperty:
style[key] = int_enum_to_constant(value, key)
if has_type_names:
style_json = json.dumps(style, indent=4)
else:
style_json = json.dumps(style)
# remove HEX Markers
style_json = style_json.replace('"HEX<', "")
style_json = style_json.replace('>HEX"', "")
# remove Constant Markers
style_json = style_json.replace('"UI.CONSTANT<', "")
style_json = style_json.replace('>UI.CONSTANT"', "")
omni.kit.clipboard.copy(style_json)
| 6,562 | Python | 34.475675 | 118 | 0.535812 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/style/widget_styles.py |
__all__ = ["ClassStyles"]
ClassStyles = {
"AbstractField": ["background_selected_color", "color", "padding"],
"AbstractSlider": [
"background_color",
"border_color",
"border_radius",
"border_width",
"color",
"draw_mode",
"padding",
"secondary_color",
"secondary_selected_color",
"font_size",
],
"Button": [
"background_color",
"border_color",
"border_radius",
"border_width",
"color",
"padding",
"font_size",
"stack_direction",
],
"CanvasFrame": ["background_color"],
"CheckBox": ["background_color", "border_radius", "font_size", "color"],
"Circle": ["background_color", "border_color", "border_width"],
"ColorWidget": ["background_color", "border_color", "border_radius", "border_width", "color"],
"ComboBox": [
"font_size",
"background_color",
"border_radius",
"color",
"padding",
"padding_height",
"padding_width",
"secondary_color",
"secondary_padding",
"secondary_selected_color",
"selected_color",
],
"DockSpace": ["background_color"],
"Frame": ["padding"],
"FreeBezierCurve": ["border_width", "color"],
"Image": [
"alignment",
"border_color",
"border_radius",
"border_width",
"color",
"corner_flag",
"fill_policy",
"image_url",
],
"ImageWithProvider": [
"alignment",
"border_color",
"border_radius",
"border_width",
"color",
"corner_flag",
"fill_policy",
"image_url",
],
"Label": ["padding", "alignment", "color", "font_size"],
"Line": ["border_width", "color"],
"MainWindow": ["background_color", "Margin_height", "margin_width"],
"Menu": [
"background_color",
"BackgroundSelected_color",
"border_color",
"border_radius",
"border_width",
"color",
"padding",
"secondary_color",
],
"MenuBar": [
"background_color",
"BackgroundSelected_color",
"border_color",
"border_radius",
"border_width",
"color",
"padding",
],
"MenuItem": ["BackgroundSelected_color", "color", "secondary_color"],
"Plot": [
"background_color",
"BackgroundSelected_color",
"border_color",
"border_radius",
"border_width",
"color",
"secondary_color",
"selected_color",
],
"ProgressBar": [
"background_color",
"border_color",
"border_radius",
"border_width",
"color",
"padding",
"secondary_color",
],
"Rectangle": [
"background_color",
"BackgroundGradient_color",
"border_color",
"border_radius",
"border_width",
"corner_flag",
],
"ScrollingFrame": ["background_color", "ScrollbarSize", "secondary_color"],
"Separator": ["color"],
"Stack": ["debug_color"],
"TreeView": ["background_color", "background_selected_color", "secondary_color", "secondary_selected_color"],
"Triangle": ["background_color", "border_color", "border_width"],
"Widget": [
"background_color",
"border_color",
"border_radius",
"border_width",
"Debug_color",
"margin",
"margin_height",
"margin_width",
],
"Window": ["background_color", "border_color", "border_radius", "border_width"],
}
| 3,607 | Python | 25.725926 | 113 | 0.512337 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/tree/inspector_tree.py |
__all__ = ["WindowItem", "WindowListModel", "InspectorTreeView"]
from typing import List, cast
import asyncio
import omni.ui as ui
import omni.kit.app
import carb
import carb.events
from .inspector_tree_model import InspectorTreeModel, WidgetItem
from .inspector_tree_delegate import InspectorTreeDelegate
from omni.ui_query import OmniUIQuery
from pathlib import Path
ICON_PATH = Path(__file__).parent.parent.parent.parent.parent.parent.joinpath("icons")
DARK_BACKGROUND = 0xFF333333
class WindowItem(ui.AbstractItem):
def __init__(self, window_name: str, display_name: str = ""):
super().__init__()
self.model = ui.SimpleStringModel(display_name if display_name else window_name)
self.window_name = window_name
class WindowListModel(ui.AbstractItemModel):
def __init__(self):
super().__init__()
self._current_index = ui.SimpleIntModel()
self._current_index.add_value_changed_fn(lambda a: self._item_changed(None))
self._items = []
self._forbidden_windows = ["Inspector"]
async def refresh_later():
await omni.kit.app.get_app().next_update_async()
self.refresh()
asyncio.ensure_future(refresh_later())
def refresh(self):
self._items = []
window_list = []
for w in ui.Workspace.get_windows():
if isinstance(w, ui.Window) and not w.title in self._forbidden_windows and w.visible:
window_list.append(w)
window_list = sorted(window_list, key=lambda a: a.title)
for index, w in enumerate(window_list):
self._items.append(WindowItem(w.title))
if w.title == "DemoWindow":
self._current_index.set_value(index)
self._item_changed(None)
def get_current_window(self) -> str:
index = self.get_item_value_model(None, 0).as_int
if not self._items:
print ("no other windows available!")
return None
item = self._items[index]
return item.window_name
def get_item_children(self, item):
return self._items
def get_item_value_model(self, item, column_id):
if item is None:
return self._current_index
return item.model
class InspectorTreeView:
def destroy(self):
self._window = None
self._frame = None
self._model = None
self._delegate.set_window(None)
def __init__(self, window: ui.Window, update_window_cb: callable, **kwargs):
self._delegate = InspectorTreeDelegate()
self._preview_window = None
self._tree_view = None
self._model = None
self._sender_id = hash("InspectorTreeView") & 0xFFFFFFFF
self._window = window
self._frame = window.frame if window else None
self._update_window_cb = update_window_cb
self._main_stack = ui.VStack()
self._update_window(window)
self._build_ui()
app = omni.kit.app.get_app()
self._update_sub_sel = app.get_message_bus_event_stream().create_subscription_to_pop(
self.on_selection_changed, name="Inspector Selection Changed"
)
self._update_sub_exp = app.get_message_bus_event_stream().create_subscription_to_pop(
self.on_expansion_changed, name="Inspector Expand"
)
def on_expansion_changed(self, event: carb.events.IEvent):
if not self._model:
# carb.log_error("NO Model setup")
return
if event.sender == self._sender_id:
# we don't respond to our own changes
return
from ..inspector_widget import INSPECTOR_ITEM_EXPANDED_ID
def set_expansion_state(item, exp_state):
for c in item.children:
c.expanded = exp_state
set_expansion_state(c, exp_state)
if event.type == INSPECTOR_ITEM_EXPANDED_ID:
expansion_path = OmniUIQuery.find_widget(event.payload["item_path"])
expansion_item = cast(ui.AbstractItem, self._model.get_item_for_widget(expansion_path))
expand = event.payload["expand"]
self.set_expanded(expansion_item, expand, True)
expansion_item.expanded = expand
set_expansion_state(expansion_item, expand)
def on_selection_changed(self, event: carb.events.IEvent):
if not self._model:
# carb.log_error("NO Model setup")
return
if event.sender == self._sender_id:
# we don't respond to our own changes
return
from ..inspector_widget import INSPECTOR_ITEM_SELECTED_ID
if event.type == INSPECTOR_ITEM_SELECTED_ID:
selection = OmniUIQuery.find_widget(event.payload["item_path"])
if selection:
selection_item, items = cast(ui.AbstractItem, self._model.get_item_with_path_for_widget(selection))
if selection_item:
if len(self._tree_view.selection) == 1 and self._tree_view.selection[0] != selection_item:
for item in reversed(items):
self._tree_view.set_expanded(item, True, False)
self._selection = [selection_item]
self._tree_view.selection = self._selection
def _update_window(self, window: ui.Window):
self._window = window
self._frame = window.frame if window else None
if self._update_window_cb:
self._update_window_cb(window)
self._model = InspectorTreeModel(window)
self._delegate.set_window(window)
self._selection: List[WidgetItem] = []
if self._tree_view:
self._tree_view.model = self._model
def toggle_visibility(self):
self._main_stack.visible = not self._main_stack.visible
def set_expanded(self, item: WidgetItem, expanded: bool, recursive: bool = False):
"""
Sets the expansion state of the given item.
Args:
item (:obj:`WidgetItem`): The item to effect.
expanded (bool): True to expand, False to collapse.
recursive (bool): Apply state recursively to descendent nodes. Default False.
"""
if self._tree_view and item:
self._tree_view.set_expanded(item, expanded, recursive)
def _build_ui(self):
with self._main_stack:
with ui.ZStack(height=0):
ui.Rectangle(style={"background_color": DARK_BACKGROUND})
with ui.VStack():
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Spacer(width=5)
ui.Label("Windows", height=20, width=0)
ui.Spacer(width=10)
def combo_changed_fn(model: WindowListModel, item: WindowItem):
window_name = model.get_current_window()
if window_name:
window: ui.Window = ui.Workspace.get_window(window_name)
if window:
self._update_window(window)
self._window_list_model = WindowListModel()
self._window_list_model.add_item_changed_fn(combo_changed_fn)
ui.ComboBox(self._window_list_model, identifier="WindowListComboBox")
ui.Spacer(width=5)
def refresh_windows():
self._window_list_model.refresh()
ui.Button(
image_url=f"{ICON_PATH}/sync.svg",
style={"margin": 0},
width=19,
height=19,
clicked_fn=refresh_windows,
)
ui.Spacer(width=5)
ui.Spacer(height=10)
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style_type_name_override="TreeView.ScrollingFrame",
style={"TreeView.ScrollingFrame": {"background_color": 0xFF23211F}},
):
with ui.VStack():
ui.Spacer(height=5)
self._tree_view = ui.TreeView(
self._model,
delegate=self._delegate,
column_widths=[ui.Fraction(1), 40],
header_visible=False,
root_visible=False,
selection_changed_fn=self._widget_selection_changed,
identifier="WidgetInspectorTree"
)
def _widget_selection_changed(self, selection: list):
if len(selection) == 0:
self._selection = selection
return
if not selection[0]:
return
if len(self._selection) > 0 and self._selection[0] == selection[0]:
return
self._selection = selection
first_widget_path = self._selection[0].path
# Send the Selection Changed Message
from ..inspector_widget import INSPECTOR_ITEM_SELECTED_ID
stream = omni.kit.app.get_app().get_message_bus_event_stream()
stream.push(INSPECTOR_ITEM_SELECTED_ID, sender=self._sender_id, payload={"item_path": first_widget_path})
return
for a_selection in self._selection:
widget: ui.Widget = a_selection.widget
print("style", widget.get_style())
print(widget.checked)
print(widget.computed_content_width)
print(widget.computed_content_height)
print(widget.computed_height)
print(widget.computed_width)
print(widget.width)
print(widget.height)
print(widget.screen_position_x)
print(widget.screen_position_y)
properties = ["font_size", "border_width", "border_color", "alignment"]
color = widget.get_resolved_style_value("color")
if color:
print("color", hex(color))
bg_color = widget.get_resolved_style_value("background_color")
if bg_color:
print("background_color", hex(bg_color))
for a_style in properties:
print(a_style, widget.get_resolved_style_value(a_style))
# widget.set_style({"debug_color": 0x1100DD00})
| 10,521 | Python | 35.282758 | 115 | 0.564015 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/tree/inspector_tree_model.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
__all__ = ["WidgetItem", "InspectorTreeModel"]
from typing import Union
import omni.ui as ui
from omni.ui_query import OmniUIQuery
class WidgetItem(ui.AbstractItem):
"""A single AbstractItemModel item that represents a single prim"""
def __init__(self, widget: ui.Widget, path: str):
super().__init__()
self.widget = widget
self.path = path
self.children = []
# True when it's necessary to repopulate its children
self.populated = False
widget_name = path.split("/")[-1]
self._widget_name = widget_name
# Get Type
self._widget_type = str(type(widget)).split(".")[-1]
self._widget_type = self._widget_type.split("'")[0]
self.type_model = ui.SimpleStringModel(self._widget_type)
self.expanded = False
def __repr__(self):
return f"<Omni::UI Widget '{str(type(self.widget))}'>"
def __str__(self):
return f"WidgetItem: {self.widget} @ {self.path}"
class InspectorTreeModel(ui.AbstractItemModel):
"""The item model that watches the stage"""
def __init__(self, window: ui.Window):
"""Flat means the root node has all the children and children of children, etc."""
super().__init__()
self._root = None
self._frame = window.frame if window else None
self._window_name = window.title if window else ""
self._window = window
self._frame_item = WidgetItem(self._frame, f"{self._window_name}//Frame")
def get_item_for_widget(self, widget: ui.Widget) -> Union[WidgetItem, None]:
def search_for_item(item: WidgetItem, widget: ui.Widget) -> Union[WidgetItem, None]:
if item.widget == widget:
return item
if isinstance(item.widget, ui.Container) or isinstance(item.widget, ui.TreeView):
for a_child_item in self.get_item_children(item):
matched_item = search_for_item(a_child_item, widget)
if matched_item:
return matched_item
return None
return search_for_item(self._frame_item, widget)
def get_item_with_path_for_widget(self, widget: ui.Widget):
parents = []
def search_for_item(item: WidgetItem, widget: ui.Widget):
if item.widget == widget:
return item
if isinstance(item.widget, ui.Container) or isinstance(item.widget, ui.TreeView):
for a_child_item in self.get_item_children(item):
matched_item = search_for_item(a_child_item, widget)
if matched_item:
parents.append(item)
return matched_item
return None
item = search_for_item(self._frame_item, widget)
return item, parents
def can_item_have_children(self, parentItem: WidgetItem) -> bool:
if not parentItem:
return True
if not parentItem.widget:
return True
if issubclass(type(parentItem.widget), ui.Container):
return True
elif issubclass(type(parentItem.widget), ui.TreeView):
return True
else:
return False
def get_item_children(self, item: WidgetItem):
"""Reimplemented from AbstractItemModel"""
if item is None:
return [self._frame_item]
if item.populated:
return item.children
widget = item.widget
# return the children of the Container
item.children = []
index = 0
for w in ui.Inspector.get_children(widget):
widget_path = OmniUIQuery.get_widget_path(self._window, w)
if widget_path:
# TODO: There are widgets that have no paths... why?
new_item = WidgetItem(w, widget_path)
item.children.append(new_item)
item.populated = True
return item.children
def get_item_value_model_count(self, item):
"""Reimplemented from AbstractItemModel"""
return 2
def get_widget_type(self, item):
return item._widget_type
def get_widget_path(self, item):
return item.path
def get_item_value_model(self, item, column_id):
"""Reimplemented from AbstractItemModel"""
if item is None:
return ui.SimpleStringModel("Window")
if column_id == 0:
return ui.SimpleStringModel(item._widget_name)
if column_id == 1:
style = item.widget.style if item and item.widget else None
return ui.SimpleBoolModel(not style == None)
if column_id == 2:
height = item.widget.computed_height
return ui.SimpleStringModel("{:10.2f}".format(height))
| 5,207 | Python | 33.039215 | 93 | 0.604955 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/tree/inspector_tree_delegate.py |
__all__ = ["InspectorTreeDelegate"]
import os.path
import omni.ui as ui
import omni.kit.app
import carb
from .inspector_tree_model import WidgetItem, InspectorTreeModel
from pathlib import Path
ICON_PATH = Path(__file__).parent.parent.parent.parent.parent.parent.joinpath("icons")
class InspectorTreeDelegate(ui.AbstractItemDelegate):
def __init__(self):
super().__init__()
self._context_menu = None
self._window_title = None
self._icon_alternatives = {
"CollapsableFrame": "Frame",
"InvisibleButton": "Button",
"ImageWithProvider": "Image",
"FloatDrag": "FloatField",
}
def set_window(self, window: ui.Window):
if window:
self._window_title = window.title
def _copy_path(self, item: WidgetItem):
try:
import omni.kit.clipboard
omni.kit.clipboard.copy(item.path)
except ImportError:
carb.log_warn("Could not import omni.kit.clipboard.")
def _expand_nodes(self, item: WidgetItem, expand=False):
from ..inspector_widget import INSPECTOR_ITEM_EXPANDED_ID
stream = omni.kit.app.get_app().get_message_bus_event_stream()
stream.push(INSPECTOR_ITEM_EXPANDED_ID, payload={"item_path": item.path, "expand": expand})
def _show_context_menu(self, button: int, item: WidgetItem):
if not self._context_menu:
self._context_menu = ui.Menu("Context")
self._context_menu.clear()
if not button == 1:
return
def send_selected_message(item: WidgetItem):
from ..inspector_widget import INSPECTOR_PREVIEW_CHANGED_ID
stream = omni.kit.app.get_app().get_message_bus_event_stream()
stream.push(
INSPECTOR_PREVIEW_CHANGED_ID, payload={"item_path": item.path, "window_name": self._window_title}
)
with self._context_menu:
ui.MenuItem("Preview", triggered_fn=lambda item=item: send_selected_message(item))
ui.MenuItem("Copy Path", triggered_fn=lambda item=item: self._copy_path(item))
if item.expanded:
ui.MenuItem(
"Collapse All", triggered_fn=lambda item=item, expand=False: self._expand_nodes(item, expand)
)
else:
ui.MenuItem("Expand All", triggered_fn=lambda item=item, expand=True: self._expand_nodes(item, expand))
self._context_menu.show()
def build_branch(self, model: InspectorTreeModel, item: WidgetItem, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
if column_id == 0:
with ui.HStack(width=25 * (level + 1), height=0, style={"Line": {"color": 0xFFAAAAAA}}):
ui.Spacer(width=25 * level + 10)
if model.can_item_have_children(item):
# ui.Spacer()
with ui.VStack():
ui.Spacer()
image_name = "Minus" if expanded else "Plus"
ui.Image(f"{ICON_PATH}/{image_name}.svg", width=10, height=10, style={"color": 0xFFCCCCCC})
ui.Spacer()
else:
ui.Spacer(width=10)
ui.Spacer()
def build_widget(self, model: InspectorTreeModel, item: WidgetItem, column_id, level, expanded):
"""Create a widget per column per item"""
value_model: ui.AbstractValueModel = model.get_item_value_model(item, column_id)
widget_type = model.get_widget_type(item)
if column_id == 0:
with ui.HStack(height=30, mouse_pressed_fn=lambda x, y, b, m, item=item: self._show_context_menu(b, item)):
with ui.VStack(width=25):
ui.Spacer()
icon = f"{widget_type}"
if not os.path.isfile(f"{ICON_PATH}/{icon}.svg"):
if icon in self._icon_alternatives:
icon = self._icon_alternatives[icon]
else:
carb.log_warn(f"{ICON_PATH}/{icon}.svg not found")
icon = "Missing"
ui.Image(f"{ICON_PATH}/{icon}.svg", width=25, height=25)
ui.Spacer()
ui.Spacer(width=10)
with ui.VStack():
ui.Spacer()
ui.Label(
value_model.as_string,
height=0,
style={"color": 0xFFEEEEEE},
tooltip=model.get_widget_path(item),
)
ui.Spacer()
elif column_id == 1:
# does it contain a Local Style
if value_model.as_bool:
with ui.HStack():
ui.Label("Style", alignment=ui.Alignment.RIGHT)
ui.Spacer(width=5)
def build_header(self, column_id):
"""Create a widget per column per item"""
label = ""
if column_id == 0:
label = "Type"
if column_id == 1:
label = "Has Style"
ui.Label(label, alignment=ui.Alignment.CENTER)
| 5,239 | Python | 37.529411 | 119 | 0.538271 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/create_widget.py |
__all__ = ["get_property_enum_class", "PropertyType", "create_property_widget"]
from typing import Tuple, Union, Callable
import omni.ui as ui
import enum
from .widget_model import WidgetModel, WidgetComboItemModel
from .widget_builder import PropertyWidgetBuilder
def get_property_enum_class(property: str) -> Callable:
if property == "direction":
return ui.Direction
elif property == "alignment":
return ui.Alignment
elif property == "fill_policy":
return ui.FillPolicy
elif property == "arc":
return ui.Alignment
elif property == "size_policy":
return ui.CircleSizePolicy
elif property == "drag_axis":
return ui.Axis
else:
return ui.Direction
class PropertyType(enum.Enum):
FLOAT = 0
INT = 1
COLOR3 = 2
BOOL = 3
STRING = 4
DOUBLE3 = 5
INT2 = 6
DOUBLE2 = 7
ENUM = 8
# TODO: Section will be moved to some location like omni.ui.settings
# #############################################################################################
def create_property_widget(
widget: ui.Widget, property: str, property_type: PropertyType, range_from=0, range_to=0, speed=1, **kwargs
) -> Tuple[Union[ui.Widget, None], Union[ui.AbstractValueModel, None]]:
"""
Create a UI widget connected with a setting.
If ``range_from`` >= ``range_to`` there is no limit. Undo/redo operations are also supported, because changing setting
goes through the :mod:`omni.kit.commands` module, using :class:`.ChangeSettingCommand`.
Args:
setting_path: Path to the setting to show and edit.
property_type: Type of the setting to expect.
range_from: Limit setting value lower bound.
range_to: Limit setting value upper bound.
Returns:
:class:`ui.Widget` connected with the setting on the path specified.
"""
property_widget: Union[ui.Widget, None] = None
model = None
# Create widget to be used for particular type
if property_type == PropertyType.INT:
model = WidgetModel(widget, property)
property_widget = PropertyWidgetBuilder.createIntWidget(model, range_from, range_to, **kwargs)
elif property_type == PropertyType.FLOAT:
model = WidgetModel(widget, property)
property_widget = PropertyWidgetBuilder.createFloatWidget(model, range_from, range_to, **kwargs)
elif property_type == PropertyType.BOOL:
model = WidgetModel(widget, property)
property_widget = PropertyWidgetBuilder.createBoolWidget(model, **kwargs)
elif property_type == PropertyType.STRING:
model = WidgetModel(widget, property)
property_widget = ui.StringField(**kwargs)
elif property_type == PropertyType.ENUM:
enum_cls = get_property_enum_class(property)
model = WidgetComboItemModel(widget, property, enum_cls)
property_widget = ui.ComboBox(model, **kwargs)
else:
print("Couldnt find widget for ", property_type, property) # Do we have any right now?
return property_widget, None
if property_widget:
try:
property_widget.model = model
except:
print(widget, "doesn't have model")
return property_widget, model
| 3,241 | Python | 34.626373 | 122 | 0.650417 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widget_builder.py |
__all__ = ["PropertyWidgetBuilder"]
import omni.ui as ui
LABEL_HEIGHT = 18
HORIZONTAL_SPACING = 4
LABEL_WIDTH = 150
class PropertyWidgetBuilder:
@classmethod
def _build_reset_button(cls, path) -> ui.Rectangle:
with ui.VStack(width=0, height=0):
ui.Spacer()
with ui.ZStack(width=15, height=15):
with ui.HStack(style={"margin_width": 0}):
ui.Spacer()
with ui.VStack(width=0):
ui.Spacer()
ui.Rectangle(width=5, height=5, name="reset_invalid")
ui.Spacer()
ui.Spacer()
btn = ui.Rectangle(width=12, height=12, name="reset", tooltip="Click to reset value")
btn.visible = False
btn.set_mouse_pressed_fn(lambda x, y, m, w, p=path, b=btn: cls._restore_defaults(path, b))
ui.Spacer()
return btn
@staticmethod
def _create_multi_float_drag_with_labels(model, labels, comp_count, **kwargs) -> None:
RECT_WIDTH = 13
SPACING = 4
with ui.ZStack():
with ui.HStack():
ui.Spacer(width=RECT_WIDTH)
widget_kwargs = {"name": "multivalue", "h_spacing": RECT_WIDTH + SPACING}
widget_kwargs.update(kwargs)
ui.MultiFloatDragField(model, **widget_kwargs)
with ui.HStack():
for i in range(comp_count):
if i != 0:
ui.Spacer(width=SPACING)
label = labels[i]
with ui.ZStack(width=RECT_WIDTH + 1):
ui.Rectangle(name="vector_label", style={"background_color": label[1]})
ui.Label(label[0], name="vector_label", alignment=ui.Alignment.CENTER)
ui.Spacer()
@classmethod
def createColorWidget(cls, model, comp_count=3, additional_widget_kwargs=None) -> ui.HStack:
with ui.HStack(spacing=HORIZONTAL_SPACING) as widget:
widget_kwargs = {"min": 0.0, "max": 1.0}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
# TODO probably need to support "A" if comp_count is 4, but how many assumptions can we make?
with ui.HStack(spacing=4):
cls._create_multi_float_drag_with_labels(
model=model,
labels=[("R", 0xFF5555AA), ("G", 0xFF76A371), ("B", 0xFFA07D4F)],
comp_count=comp_count,
**widget_kwargs,
)
widget = ui.ColorWidget(model, width=30, height=0)
# cls._create_control_state(model)
return widget
@classmethod
def createVecWidget(cls, model, range_min, range_max, comp_count=3, additional_widget_kwargs=None):
widget_kwargs = {"min": range_min, "max": range_max}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
cls._create_multi_float_drag_with_labels(
model=model,
labels=[("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F), ("W", 0xFFFFFFFF)],
comp_count=comp_count,
**widget_kwargs,
)
return model
@staticmethod
def _create_drag_or_slider(drag_widget, slider_widget, **kwargs):
if "min" in kwargs and "max" in kwargs:
range_min = kwargs["min"]
range_max = kwargs["max"]
if range_max - range_min < 100:
return slider_widget(name="value", **kwargs)
else:
if "step" not in kwargs:
kwargs["step"] = max(0.1, (range_max - range_min) / 1000.0)
else:
if "step" not in kwargs:
kwargs["step"] = 0.1
# If range is too big or no range, don't use a slider
widget = drag_widget(name="value", **kwargs)
return widget
@classmethod
def _create_label(cls, attr_name, label_width=150, additional_label_kwargs=None):
label_kwargs = {
"name": "label",
"word_wrap": True,
"width": label_width,
"height": LABEL_HEIGHT,
"alignment": ui.Alignment.LEFT,
}
if additional_label_kwargs:
label_kwargs.update(additional_label_kwargs)
ui.Label(attr_name, **label_kwargs)
ui.Spacer(width=5)
@classmethod
def createBoolWidget(cls, model, additional_widget_kwargs=None):
widget = None
with ui.HStack():
with ui.HStack(style={"margin_width": 0}, width=10):
ui.Spacer()
widget_kwargs = {"font_size": 16, "height": 16, "width": 16, "model": model}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
widget = ui.CheckBox(**widget_kwargs, style={"color": 0xFFDDDDDD, "background_color": 0xFF666666})
ui.Spacer()
return widget
@classmethod
def createFloatWidget(cls, model, range_min, range_max, additional_widget_kwargs=None):
widget_kwargs = {"model": model}
# only set range if range is valid (min < max)
if range_min < range_max:
widget_kwargs["min"] = range_min
widget_kwargs["max"] = range_max
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
widget_kwargs.update(style={"secondary_color": 0xFF444444})
return cls._create_drag_or_slider(ui.FloatDrag, ui.FloatSlider, **widget_kwargs)
@classmethod
def createIntWidget(cls, model, range_min, range_max, additional_widget_kwargs=None):
widget_kwargs = {"model": model} # This passes the model into the widget
# only set range if range is valid (min < max)
if range_min < range_max:
widget_kwargs["min"] = range_min
widget_kwargs["max"] = range_max
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
widget_kwargs.update(style={"secondary_color": 0xFF444444})
return cls._create_drag_or_slider(ui.IntDrag, ui.IntSlider, **widget_kwargs)
| 6,266 | Python | 39.694805 | 114 | 0.555538 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widget_model.py |
__all__ = ["WidgetModel", "WidgetComboValueModel", "WidgetComboNameValueItem", "WidgetComboItemModel"]
from typing import Callable
import omni.ui as ui
class WidgetModel(ui.AbstractValueModel):
"""
Model for widget Properties
"""
def __init__(self, widget: ui.Widget, property: str, dragable=True):
"""
Args:
"""
super().__init__()
self._widget = widget
self._property = property
self.initialValue = None
self._reset_button = None
self._editing = False
# def _on_change(owner, value, event_type) -> None:
# if event_type == carb.settings.ChangeEventType.CHANGED:
# owner._on_dirty()
# if owner._editing == False:
# owner._update_reset_button()
# def begin_edit(self) -> None:
# self._editing = True
# ui.AbstractValueModel.begin_edit(self)
# self.initialValue = self._settings.get(self._path)
# def end_edit(self) -> None:
# ui.AbstractValueModel.end_edit(self)
# omni.kit.commands.execute(
# "ChangeSettingCommand", path=self._path, value=self._settings.get(self._path), prev=self.initialValue
# )
# self._update_reset_button()
# self._editing = False
def get_value_as_string(self) -> str:
return str(self._widget.__getattribute__(self._property))
def get_value_as_float(self) -> float:
return self._widget.__getattribute__(self._property)
def get_value_as_bool(self) -> bool:
return self._widget.__getattribute__(self._property)
def get_value_as_int(self) -> int:
# print("here int ")
return self._widget.__getattribute__(self._property)
def set_value(self, value):
print(type(self._widget.__getattribute__(self._property)))
if type(self._widget.__getattribute__(self._property)) == ui.Length:
print("Is Length")
self._widget.__setattr__(self._property, ui.Pixel(value))
else:
self._widget.__setattr__(self._property, value)
self._value_changed()
def destroy(self):
self._widget = None
self._reset_button = None
class WidgetComboValueModel(ui.AbstractValueModel):
"""
Model to store a pair (label, value of arbitrary type) for use in a ComboBox
"""
def __init__(self, key, value):
"""
Args:
value: the instance of the Style value
"""
ui.AbstractValueModel.__init__(self)
self.key = key
self.value = value
def __repr__(self):
return f'"WidgetComboValueModel name:{self.key} value:{int(self.value)}"'
def get_value_as_string(self) -> str:
"""
this is called to get the label of the combo box item
"""
return self.key
def get_style_value(self) -> int:
"""
we call this to get the value of the combo box item
"""
return int(self.value)
class WidgetComboNameValueItem(ui.AbstractItem):
def __init__(self, key, value):
super().__init__()
self.model = WidgetComboValueModel(key, value)
def __repr__(self):
return f'"StyleComboNameValueItem {self.model}"'
class WidgetComboItemModel(ui.AbstractItemModel):
"""
Model for a combo box - for each setting we have a dictionary of key, values
"""
def __init__(self, widget: ui.Widget, property: str, class_obj: Callable):
super().__init__()
self._widget = widget
self._property = property
self._class = class_obj
self._items = []
self._default_value = self._widget.__getattribute__(property)
default_index = 0
current_index = 0
for key, value in class_obj.__members__.items():
if self._default_value == value:
default_index = current_index
self._items.append(WidgetComboNameValueItem(key, value))
current_index += 1
self._current_index = ui.SimpleIntModel(default_index)
self._current_index.add_value_changed_fn(self._current_index_changed)
def get_current_value(self):
return self._items[self._current_index.as_int].model.get_style_value()
def _current_index_changed(self, model):
self._item_changed(None)
value = self.get_current_value()
self._widget.__setattr__(self._property, self._class(value))
def get_item_children(self, item):
return self._items
def get_item_value_model(self, item, column_id: int):
if item is None:
return self._current_index
return item.model
| 4,648 | Python | 29.993333 | 115 | 0.593589 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/inspector_property_widget.py |
__all__ = ["InspectorPropertyWidget"]
import omni.ui as ui
import carb.events
import omni.kit.app
from omni.ui_query import OmniUIQuery
from .widgets.button import ButtonPropertyFrame
from .widgets.canvas_frame import CanvasPropertyFrame
from .widgets.circle import CirclePropertyFrame
from .widgets.collapsable_frame import CollapsableFramePropertyFrame
from .widgets.combox_box import ComboBoxPropertyFrame
from .widgets.frame import FramePropertyFrame
from .widgets.grid import GridPropertyFrame
from .widgets.image import ImagePropertyFrame
from .widgets.image_with_provider import ImageWithProviderPropertyFrame
from .widgets.label import LabelPropertyFrame
from .widgets.line import LinePropertyFrame
from .widgets.placer import PlacerPropertyFrame
from .widgets.scrolling_frame import ScrollingFramePropertyFrame
from .widgets.slider import SliderPropertyFrame
from .widgets.stack import StackPropertyFrame
from .widgets.string_field import StringFieldPropertyFrame
from .widgets.tree_view import TreeViewPropertyFrame
from .widgets.triangle import TrianglePropertyFrame
from .widgets.widget import WidgetPropertyFrame
class InspectorPropertyWidget:
"""The Stage widget"""
def __init__(self, **kwargs):
self._widget = None
self._main_stack = ui.VStack(
spacing=5,
width=300,
style={
"VStack": {"margin_width": 10},
"CollapsableFrame": {"background_color": 0xFF2A2A2A, "secondary_color": 0xFF2A2A2A},
},
)
self._build_ui()
app = omni.kit.app.get_app()
self._update_sub = app.get_message_bus_event_stream().create_subscription_to_pop(
self.on_selection_changed, name="Inspector Selection Changed"
)
def on_selection_changed(self, event: carb.events.IEvent):
from ..inspector_widget import INSPECTOR_ITEM_SELECTED_ID
if event.type == INSPECTOR_ITEM_SELECTED_ID:
selection = OmniUIQuery.find_widget(event.payload["item_path"])
if selection:
self.set_widget(selection)
def toggle_visibility(self):
self._main_stack.visible = not self._main_stack.visible
def set_widget(self, widget: ui.Widget):
self._widget = widget
self._build_ui()
def _build_ui(self):
self._main_stack.clear()
with self._main_stack:
ui.Spacer(height=0)
ui.Label("Properties", height=0, style={"font_size": 16}, alignment=ui.Alignment.CENTER)
ui.Spacer(height=0)
if not self._widget:
return
if isinstance(self._widget, ui.Label):
LabelPropertyFrame("Label", self._widget)
elif isinstance(self._widget, ui.Stack):
StackPropertyFrame("Stack", self._widget)
elif isinstance(self._widget, ui.Button):
ButtonPropertyFrame("Button", self._widget)
elif isinstance(self._widget, ui.Image):
ImagePropertyFrame("Image", self._widget)
elif isinstance(self._widget, ui.CanvasFrame):
CanvasPropertyFrame("CanvasFrame", self._widget)
elif isinstance(self._widget, ui.AbstractSlider):
SliderPropertyFrame("Slider", self._widget)
elif isinstance(self._widget, ui.Circle):
CirclePropertyFrame("Circle", self._widget)
elif isinstance(self._widget, ui.ComboBox):
ComboBoxPropertyFrame("ComboBox", self._widget)
elif isinstance(self._widget, ui.ScrollingFrame):
ScrollingFramePropertyFrame("ScrollingFrame", self._widget)
FramePropertyFrame("Frame", self._widget)
elif isinstance(self._widget, ui.CollapsableFrame):
CollapsableFramePropertyFrame("CollapsableFrame", self._widget)
FramePropertyFrame("Frame", self._widget)
elif isinstance(self._widget, ui.Frame):
FramePropertyFrame("Frame", self._widget)
elif isinstance(self._widget, ui.Grid):
GridPropertyFrame("Grid", self._widget)
elif isinstance(self._widget, ui.ImageWithProvider):
ImageWithProviderPropertyFrame("ImageWithProvider", self._widget)
elif isinstance(self._widget, ui.Line):
LinePropertyFrame("Line", self._widget)
elif isinstance(self._widget, ui.Placer):
PlacerPropertyFrame("Placer", self._widget)
elif isinstance(self._widget, ui.ScrollingFrame):
ScrollingFramePropertyFrame("ScrollingFrame", self._widget)
elif isinstance(self._widget, ui.StringField):
StringFieldPropertyFrame("StringField", self._widget)
elif isinstance(self._widget, ui.TreeView):
TreeViewPropertyFrame("TreeView", self._widget)
elif isinstance(self._widget, ui.Triangle):
TrianglePropertyFrame("Triangle", self._widget)
WidgetPropertyFrame("Widget", self._widget)
| 5,087 | Python | 41.049586 | 100 | 0.653823 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/base_frame.py |
__all__ = ["WidgetCollectionFrame"]
# from typing import Union, Any
from .create_widget import PropertyType
import omni.ui as ui
from .create_widget import create_property_widget
from .widget_builder import PropertyWidgetBuilder
class WidgetCollectionFrame:
parents = {} # For later deletion of parents
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
self._models = []
self._widget = widget
self._frame_widget = ui.CollapsableFrame(frame_label, height=0, build_fn=self.build_ui)
def destroy(self):
""""""
self._frame_widget.clear()
self._frame_widget = None
def build_ui(self):
with ui.VStack(height=0, spacing=5, style={"VStack": {"margin_width": 10}}):
ui.Spacer(height=5)
self._build_ui()
ui.Spacer(height=5)
def _rebuild(self):
if self._frame_widget:
self._frame_widget.rebuild()
def _add_property(
self,
widget: ui.Widget,
property: str,
property_type: PropertyType,
range_from=0,
range_to=0,
speed=1,
has_reset=True,
tooltip="",
label_width=150,
):
with ui.HStack(skip_draw_when_clipped=True):
PropertyWidgetBuilder._create_label(property, label_width=label_width)
property_widget, model = create_property_widget(
widget, property, property_type, range_from, range_to, speed
)
self._models.append(model)
# if has_reset:
# button = PropertyWidgetBuilder._build_reset_button(path)
# model.set_reset_button(button)
return property_widget, model
# def _add_setting_combo(
# self, name: str, path: str, items: Union[list, dict], callback=None, has_reset=True, tooltip=""
# ):
# with ui.HStack(skip_draw_when_clipped=True):
# PropertyWidgetBuilder._create_label(name, path, tooltip)
# property_widget, model = create_property_widget_combo(widget, items)
# #if has_reset:
# # button = PropertyWidgetBuilder._build_reset_button(path)
# # model.set_reset_button(button)
# return property_widget
def _build_ui(self):
""" virtual function that will be called in the Collapsable frame """
pass
| 2,377 | Python | 29.883116 | 105 | 0.595709 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/button.py |
__all__ = ["ButtonPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class ButtonPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "image_url", PropertyType.STRING)
self._add_property(self._widget, "text", PropertyType.STRING)
self._add_property(self._widget, "image_width", PropertyType.FLOAT)
self._add_property(self._widget, "image_height", PropertyType.FLOAT)
self._add_property(self._widget, "spacing", PropertyType.FLOAT)
| 712 | Python | 29.999999 | 76 | 0.688202 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/canvas_frame.py |
__all__ = ["CanvasPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class CanvasPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "zoom", PropertyType.FLOAT, range_from=0)
self._add_property(self._widget, "pan_x", PropertyType.FLOAT)
self._add_property(self._widget, "pan_y", PropertyType.FLOAT)
self._add_property(self._widget, "draggable", PropertyType.BOOL)
| 636 | Python | 30.849998 | 82 | 0.685535 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/tree_view.py |
__all__ = ["TreeViewPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class TreeViewPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "columns_resizable", PropertyType.BOOL)
self._add_property(self._widget, "header_visible", PropertyType.BOOL)
self._add_property(self._widget, "root_visible", PropertyType.BOOL)
self._add_property(self._widget, "expand_on_branch_click", PropertyType.BOOL)
self._add_property(self._widget, "keep_alive", PropertyType.BOOL)
self._add_property(self._widget, "keep_expanded", PropertyType.BOOL)
self._add_property(self._widget, "drop_between_items", PropertyType.BOOL)
| 897 | Python | 39.81818 | 85 | 0.696767 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/grid.py |
__all__ = ["GridPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class GridPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "columnWidth", PropertyType.FLOAT)
self._add_property(self._widget, "rowHeight", PropertyType.FLOAT)
self._add_property(self._widget, "columnCount", PropertyType.INT, range_from=0)
self._add_property(self._widget, "rowCount", PropertyType.INT, range_from=0)
| 659 | Python | 31.999998 | 87 | 0.693475 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/slider.py |
__all__ = ["SliderPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class SliderPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "min", PropertyType.INT)
self._add_property(self._widget, "max", PropertyType.INT)
| 471 | Python | 26.764704 | 68 | 0.687898 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/frame.py |
__all__ = ["FramePropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class FramePropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "horizontal_clipping", PropertyType.BOOL)
self._add_property(self._widget, "vertical_clipping", PropertyType.BOOL)
self._add_property(self._widget, "separate_window", PropertyType.BOOL)
| 580 | Python | 31.277776 | 82 | 0.701724 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/image.py |
__all__ = ["ImagePropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class ImagePropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "source_url", PropertyType.STRING, label_width=80)
self._add_property(self._widget, "alignment", PropertyType.ENUM, label_width=80)
self._add_property(self._widget, "fill_policy", PropertyType.ENUM, label_width=80)
| 609 | Python | 32.888887 | 91 | 0.697865 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/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)
| 431 | Python | 25.999998 | 75 | 0.686775 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/string_field.py |
__all__ = ["StringFieldPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class StringFieldPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "password_mode", PropertyType.BOOL)
self._add_property(self._widget, "read_only", PropertyType.BOOL)
self._add_property(self._widget, "multiline", PropertyType.BOOL)
| 572 | Python | 30.833332 | 76 | 0.699301 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/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)
| 407 | Python | 26.199998 | 72 | 0.697789 |
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)
| 562 | Python | 30.277776 | 79 | 0.69573 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/collapsable_frame.py |
__all__ = ["CollapsableFramePropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class CollapsableFramePropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "collapsed", PropertyType.BOOL)
self._add_property(self._widget, "title", PropertyType.STRING)
self._add_property(self._widget, "alignment", PropertyType.ENUM)
| 576 | Python | 31.055554 | 72 | 0.704861 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/placer.py |
__all__ = ["PlacerPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class PlacerPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "offset_x", PropertyType.FLOAT)
self._add_property(self._widget, "offset_y", PropertyType.FLOAT)
self._add_property(self._widget, "draggable", PropertyType.BOOL)
self._add_property(self._widget, "drag_axis", PropertyType.ENUM)
self._add_property(self._widget, "stable_size", PropertyType.BOOL)
| 705 | Python | 36.157893 | 74 | 0.689362 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/scrolling_frame.py |
__all__ = ["ScrollingFramePropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class ScrollingFramePropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "scroll_x", PropertyType.FLOAT)
self._add_property(self._widget, "scroll_y", PropertyType.FLOAT)
self._add_property(self._widget, "horizontal_scrollbar_policy", PropertyType.ENUM)
self._add_property(self._widget, "vertical_scrollbar_policy", PropertyType.ENUM)
| 681 | Python | 34.894735 | 90 | 0.707783 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/label.py |
__all__ = ["LabelPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class LabelPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "text", PropertyType.STRING)
self._add_property(self._widget, "alignment", PropertyType.ENUM)
self._add_property(self._widget, "word_wrap", PropertyType.BOOL)
self._add_property(self._widget, "elided_text", PropertyType.BOOL)
| 628 | Python | 32.105261 | 74 | 0.68949 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/circle.py |
__all__ = ["CirclePropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class CirclePropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "radius", PropertyType.FLOAT, range_from=0)
self._add_property(self._widget, "alignment", PropertyType.ENUM)
self._add_property(self._widget, "arc", PropertyType.ENUM)
self._add_property(self._widget, "size_policy", PropertyType.ENUM)
| 640 | Python | 31.049998 | 84 | 0.689062 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/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)
| 431 | Python | 27.799998 | 88 | 0.705336 |
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)
| 541 | Python | 30.882351 | 90 | 0.711645 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/property/widgets/widget.py |
__all__ = ["WidgetPropertyFrame"]
import omni.ui as ui
from ..base_frame import WidgetCollectionFrame
from ..create_widget import PropertyType
class WidgetPropertyFrame(WidgetCollectionFrame):
def __init__(self, frame_label: str, widget: ui.Widget) -> None:
super().__init__(frame_label, widget)
def _build_ui(self):
self._add_property(self._widget, "width", PropertyType.FLOAT, 0, 2000)
self._add_property(self._widget, "height", PropertyType.FLOAT, 0, 2000)
self._add_property(self._widget, "tooltip_offset_x", PropertyType.FLOAT, 0, 2000)
self._add_property(self._widget, "tooltip_offset_y", PropertyType.FLOAT, 0, 2000)
ui.Line(height=2, style={"color": 0xFF666666})
self._add_property(self._widget, "name", PropertyType.STRING)
ui.Line(height=2, style={"color": 0xFF666666})
self._add_property(self._widget, "checked", PropertyType.BOOL)
self._add_property(self._widget, "enabled", PropertyType.BOOL)
self._add_property(self._widget, "selected", PropertyType.BOOL)
self._add_property(self._widget, "opaque_for_mouse_events", PropertyType.BOOL)
self._add_property(self._widget, "visible", PropertyType.BOOL)
self._add_property(self._widget, "skip_draw_when_clipped", PropertyType.BOOL)
ui.Spacer(height=10)
ui.Line(height=5, style={"color": 0xFF666666, "border_width": 5})
ui.Label("Read Only", alignment=ui.Alignment.CENTER)
self._add_property(self._widget, "computed_width", PropertyType.FLOAT, 0, 2000)
self._add_property(self._widget, "computed_height", PropertyType.FLOAT, 0, 2000)
ui.Line(height=2, style={"color": 0xFF666666})
self._add_property(self._widget, "computed_content_width", PropertyType.FLOAT, 0, 2000)
self._add_property(self._widget, "computed_content_height", PropertyType.FLOAT, 0, 2000)
ui.Line(height=2, style={"color": 0xFF666666})
self._add_property(self._widget, "screen_position_x", PropertyType.FLOAT, 0, 2000)
self._add_property(self._widget, "screen_position_y", PropertyType.FLOAT, 0, 2000)
| 2,156 | Python | 39.698112 | 96 | 0.667904 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/tests/__init__.py | from .test_ui import *
| 23 | Python | 10.999995 | 22 | 0.695652 |
omniverse-code/kit/exts/omni.kit.window.inspector/omni/kit/window/inspector/tests/test_ui.py | import omni.kit.test
import omni.kit.window.inspector.inspector_window
from omni.kit import ui_test
class TestInspectorWindow(omni.kit.test.AsyncTestCase):
@classmethod
def setUpClass(cls):
cls.inspector_window = omni.kit.window.inspector.inspector_window.InspectorWindow()
async def setUp(self):
self.window_name = self.inspector_window._window.title
@classmethod
def tearDownClass(cls) -> None:
cls.inspector_window._window.destroy()
async def test_window_list(self):
'''
Check that the main combox box is doing the right thing
There's a bit of an ordering assumption going on
'''
ui_window = ui_test.find(self.window_name)
widgets = ui_window.find_all("**/WindowListComboBox")
self.assertTrue(len(widgets) == 1)
combo_box = widgets[0].widget
self.assertTrue(isinstance(combo_box, omni.ui.ComboBox))
# Make sure render settings is set
combo_box.model.get_item_value_model(None, 0).set_value(0)
window_name = combo_box.model.get_current_window()
self.assertEqual(window_name, "Render Settings")
# Set to Stage window
combo_box.model.get_item_value_model(None, 0).set_value(1)
window_name = combo_box.model.get_current_window()
self.assertEqual(window_name, "Stage")
await omni.kit.app.get_app().next_update_async()
async def test_tree_expansion(self):
# make sure render settings is the current window
ui_window = ui_test.find(self.window_name)
widgets = ui_window.find_all("**/WindowListComboBox")
combo_box = widgets[0].widget
combo_box.model.get_item_value_model(None, 0).set_value(0)
widgets = ui_window.find_all("**/WidgetInspectorTree")
self.assertTrue(len(widgets) == 1)
tree_items = widgets[0].find_all("**")
self.assertTrue(len(tree_items) == 20, f"actually was {len(tree_items)}")
# Switch to Stage Window
combo_box.model.get_item_value_model(None, 0).set_value(1)
widgets = ui_window.find_all("**/WidgetInspectorTree")
self.assertTrue(len(widgets) == 1)
tree_items = widgets[0].find_all("**")
self.assertTrue(len(tree_items) == 17, f"actually was {len(tree_items)}")
async def test_tree_basic_content(self):
# make sure render settings is the current window
ui_window = ui_test.find(self.window_name)
widgets = ui_window.find_all("**/WindowListComboBox")
combo_box = widgets[0].widget
combo_box.model.get_item_value_model(None, 0).set_value(0)
widgets = ui_window.find_all("**/WidgetInspectorTree")
self.assertTrue(len(widgets) == 1)
tree_items = widgets[0].find_all("**")
labels = [t.widget for t in tree_items if isinstance(t.widget, omni.ui.Label)]
self.assertTrue(len(labels) == 2)
self.assertTrue(labels[0].text == "Frame")
self.assertTrue(labels[1].text == "Style")
async def test_styles(self):
ui_window = ui_test.find(self.window_name)
buttons = ui_window.find_all("**/ToolButton[*]")
# enable style
for button in buttons:
if button.widget.text == "Style":
await button.click()
await ui_test.wait_n_updates(2)
trees = ui_window.find_all("**/WidgetInspectorTree")
self.assertTrue(len(trees) == 1)
tree_items = trees[0].find_all("**")
labels = [t for t in tree_items if isinstance(t.widget, omni.ui.Label)]
for label in labels:
if label.widget.text == "Frame":
await label.click()
await ui_test.wait_n_updates(2)
# check there is colorwidget widgets created
colorwidgets = ui_window.find_all("**/ColorWidget[*]")
self.assertTrue(len(colorwidgets) > 0)
| 3,881 | Python | 36.68932 | 91 | 0.627416 |
omniverse-code/kit/exts/omni.kit.window.inspector/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.6] - 2022-07-05
- add test to increase the test coverage
## [1.0.5] - 2022-05-16
- start adding tests
## [1.0.4] - 2022-01-10
- support for widgets under Treeview (i.e those created by the treeview delegate)
## [1.0.3] - 2021-11-24
### Added
- expand/collapse in tree widget
## [1.0.2] - 2021-11-24
### Changes
- Fix some bugs naming paths
- startup defaults less cluttered..
## [1.0.1] - 2021-11-24
### Changes
- Update to latest omni.ui_query
## [1.0.0] -
### TODO
- Better support for ALL <Category> >> DONE
- Better list of Property for Widget >> DONE
- Contextual Styling List
-
| 702 | Markdown | 19.085714 | 81 | 0.653846 |
omniverse-code/kit/exts/omni.kit.window.inspector/docs/overview.md | # Overview
| 12 | Markdown | 3.333332 | 10 | 0.666667 |
omniverse-code/kit/exts/omni.kit.window.inspector/docs/README.md | # UI Inspector Widget [omni.kit.window.inspector]
| 52 | Markdown | 12.249997 | 49 | 0.75 |
omniverse-code/kit/exts/omni.kit.documentation.builder/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. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.documentation.builder/scripts/generate_docs_for_sphinx.py | import argparse
import asyncio
import logging
import carb
import omni.kit.app
import omni.kit.documentation.builder
logger = logging.getLogger(__name__)
_app_ready_sub = None
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"ext_id",
help="Extension id (name-version).",
)
parser.add_argument(
"output_path",
help="Path to output generated files to.",
)
options = parser.parse_args()
async def _generate_and_exit(options):
# Skip 2 updates to make sure all extensions loaded and initialized
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
try:
result = omni.kit.documentation.builder.generate_for_sphinx(options.ext_id, options.output_path)
except Exception as e: # pylint: disable=broad-except
carb.log_error(f"Failed to generate docs for sphinx: {e}")
for _ in range(5):
await omni.kit.app.get_app().next_update_async()
returncode = 0 if result else 33
omni.kit.app.get_app().post_quit(returncode)
def on_app_ready(e):
global _app_ready_sub
_app_ready_sub = None
asyncio.ensure_future(_generate_and_exit(options))
app = omni.kit.app.get_app()
if app.is_app_ready():
on_app_ready(None)
else:
global _app_ready_sub
_app_ready_sub = app.get_startup_event_stream().create_subscription_to_pop_by_type(
omni.kit.app.EVENT_APP_READY, on_app_ready, name="omni.kit.documentation.builder generate_docs_for_sphinx"
)
if __name__ == "__main__":
main()
| 1,675 | Python | 26.475409 | 118 | 0.628657 |
omniverse-code/kit/exts/omni.kit.documentation.builder/config/extension.toml | [package]
version = "1.0.9"
authors = ["NVIDIA"]
title = "Omni.UI Documentation Builder"
description="The interactive documentation builder for omni.ui extensions"
readme = "docs/README.md"
category = "Documentation"
keywords = ["ui", "example", "docs", "documentation", "builder"]
changelog="docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
# Moved from https://gitlab-master.nvidia.com/omniverse/kit-extensions/kit-widgets
repository = ""
[dependencies]
"omni.kit.window.filepicker" = {}
[documentation]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
menu = "Help/API/omni.kit.documentation.builder"
title = "Omni UI Documentation Builder"
[[python.module]]
name = "omni.kit.documentation.builder"
[[python.scriptFolder]]
path = "scripts"
[[test]]
| 799 | TOML | 22.529411 | 82 | 0.718398 |
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_capture.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["DocumentationBuilderCapture"]
import asyncio
import omni.appwindow
import omni.kit.app
import omni.kit.imgui_renderer
import omni.kit.renderer.bind
import omni.renderer_capture
import omni.ui as ui
class DocumentationBuilderCapture:
r"""
Captures the omni.ui widgets to the image file. Works like this:
with Capture("c:\temp\1.png", 600, 600):
ui.Button("Hello World")
"""
def __init__(self, path: str, width: int, height: int, window_name: str = "Capture Window"):
self._path: str = path
self._dpi = ui.Workspace.get_dpi_scale()
self._width: int = int(width * self._dpi)
self._height: int = int(height * self._dpi)
self._window_name: str = window_name
# Interfaces
self._app_window_factory = omni.appwindow.acquire_app_window_factory_interface()
self._renderer = omni.kit.renderer.bind.acquire_renderer_interface()
self._imgui_renderer = omni.kit.imgui_renderer.acquire_imgui_renderer_interface()
self._renderer_capture = omni.renderer_capture.acquire_renderer_capture_interface()
self._virtual_app_window = None
self._window = None
def __enter__(self):
# Create virtual OS window
self._virtual_app_window = self._app_window_factory.create_window_by_type(omni.appwindow.WindowType.VIRTUAL)
self._virtual_app_window.startup_with_desc(
title=self._window_name,
width=self._width,
height=self._height,
scale_to_monitor=False,
dpi_scale_override=1.0,
)
self._imgui_renderer.attach_app_window(self._virtual_app_window)
# Create omni.ui window
self._window = ui.Window(self._window_name, flags=ui.WINDOW_FLAGS_NO_TITLE_BAR, padding_x=0, padding_y=0)
self._window.move_to_app_window(self._virtual_app_window)
self._window.width = self._width
self._window.height = self._height
# Enter the window frame
self._window.frame.__enter__()
def __exit__(self, exc_type, exc_val, exc_tb):
# Exit the window frame
self._window.frame.__exit__(exc_type, exc_val, exc_tb)
# Capture and detach at the next frame
asyncio.ensure_future(
DocumentationBuilderCapture.__capture_detach(
self._renderer_capture, self._path, self._renderer, self._virtual_app_window, self._window
)
)
@staticmethod
async def __capture_detach(renderer_capture, path, renderer, iappwindow, window):
# The next frame
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
# Capture
renderer_capture.capture_next_frame_texture(path, renderer.get_framebuffer_texture(iappwindow), iappwindow)
await omni.kit.app.get_app().next_update_async()
# Detach
renderer.detach_app_window(iappwindow)
| 3,392 | Python | 36.7 | 116 | 0.659788 |
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_window.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["DocumentationBuilderWindow"]
import weakref
import carb
import omni.ui as ui
from omni.kit.widget.filebrowser import FileBrowserItem
from omni.kit.window.filepicker import FilePickerDialog
from .documentation_capture import DocumentationBuilderCapture
from .documentation_catalog import DocumentationBuilderCatalog
from .documentation_md import DocumentationBuilderMd
from .documentation_page import DocumentationBuilderPage
from .documentation_style import get_style
class DocumentationBuilderWindow(ui.Window):
"""The window with the documentation"""
def __init__(self, title: str, **kwargs):
"""
### Arguments
`title: str`
The title of the window.
`filenames: List[str]`
The list of .md files to process.
`show_catalog: bool`
Show catalog pane (default True)
"""
self._pages = []
self._catalog = None
self.__content_frame = None
self.__content_page = None
self.__source_filenames = kwargs.pop("filenames", [])
self._show_catalog = kwargs.pop("show_catalog", True)
if "width" not in kwargs:
kwargs["width"] = 1200
if "height" not in kwargs:
kwargs["height"] = 720
if "flags" not in kwargs:
kwargs["flags"] = ui.WINDOW_FLAGS_NO_SCROLL_WITH_MOUSE | ui.WINDOW_FLAGS_NO_SCROLLBAR
super().__init__(title, **kwargs)
self._set_style()
self.frame.set_build_fn(self.__build_window)
self.__pick_folder_dialog = None
def get_page_names(self):
"""Names of all the pages to use in `set_page`"""
return [p.name for p in self._pages]
def set_page(self, name: str = None, scroll_to: str = None):
"""
Set current page
### Arguments
`name: str`
The name of the page to switch to. If None, it will set the
first page.
`scroll_to: str`
The name of the section to scroll to.
"""
if self.__content_page and self.__content_page.name == name:
self.__content_page.scroll_to(scroll_to)
return
if name is None:
page = self._pages[0]
else:
page = next((p for p in self._pages if p.name == name), None)
if page:
if self.__content_page:
self.__content_page.destroy()
with self.__content_frame:
self.__content_page = DocumentationBuilderPage(page, scroll_to)
def generate_for_sphinx(self, path: str):
"""
Produce the set of files and screenshots readable by Sphinx.
### Arguments
`path: str`
The path to produce the files.
"""
for page in self._pages:
for code_block in page.code_blocks:
image_file = f"{path}/{code_block['name']}.png"
height = int(code_block["height"] or 200)
with DocumentationBuilderCapture(image_file, 800, height):
with ui.ZStack():
# Background
ui.Rectangle(name="code_background")
# The code
with ui.VStack():
# flake8: noqa: PLW0212
self.__content_page._execute_code(code_block["code"])
carb.log_info(f"[omni.docs] Generated image: '{image_file}'")
md_file = f"{path}/{page.name}.md"
with open(md_file, "w", encoding="utf-8") as f:
f.write(page.source)
carb.log_info(f"[omni.docs] Generated md file: '{md_file}'")
def destroy(self):
if self.__pick_folder_dialog:
self.__pick_folder_dialog.destroy()
self.__pick_folder_dialog = None
if self._catalog:
self._catalog.destroy()
self._catalog = None
for page in self._pages:
page.destroy()
self._pages = []
if self.__content_page:
self.__content_page.destroy()
self.__content_page = None
self.__content_frame = None
super().destroy()
@staticmethod
def get_style():
"""
Deprecated: use omni.kit.documentation.builder.get_style()
"""
return get_style()
def _set_style(self):
self.frame.set_style(get_style())
def __build_window(self):
"""Called to build the widgets of the window"""
self.__reload_pages()
def __on_export(self):
"""Open Pick Folder dialog to add compounds"""
if self.__pick_folder_dialog:
self.__pick_folder_dialog.destroy()
self.__pick_folder_dialog = FilePickerDialog(
"Pick Output Folder",
apply_button_label="Use This Folder",
click_apply_handler=self.__on_apply_folder,
item_filter_options=["All Folders (*)"],
item_filter_fn=self.__on_filter_folder,
)
def __on_apply_folder(self, filename: str, root_path: str):
"""Called when the user press "Use This Folder" in the pick folder dialog"""
self.__pick_folder_dialog.hide()
self.generate_for_sphinx(root_path)
@staticmethod
def __on_filter_folder(item: FileBrowserItem) -> bool:
"""Used by pick folder dialog to hide all the files"""
return item.is_folder
def __reload_pages(self):
"""Called to reload all the pages"""
# Properly destroy all the past pages
for page in self._pages:
page.destroy()
self._pages = []
# Reload the pages at the drawing time
for page_source in self.__source_filenames:
if page_source.endswith(".md"):
self._pages.append(DocumentationBuilderMd(page_source))
def keep_page_name(page, catalog_data):
"""Puts the page name to the catalog data"""
for c in catalog_data:
c["page"] = page
keep_page_name(page, c["children"])
catalog_data = []
for page in self._pages:
catalog = page.catalog
keep_page_name(page.name, catalog)
catalog_data += catalog
# The layout
with ui.HStack():
if self._show_catalog:
self._catalog = DocumentationBuilderCatalog(
catalog_data,
weakref.ref(self),
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
width=300,
settings_menu=[{"name": "Export Markdown", "clicked_fn": self.__on_export}],
)
with ui.ZStack():
ui.Rectangle(name="content_background")
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
style={"ScrollingFrame": {"background_color": 0x0}},
):
self.__content_frame = ui.Frame(height=1)
self.set_page()
| 7,676 | Python | 33.12 | 97 | 0.563054 |
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/__init__.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = [
"create_docs_window",
"DocumentationBuilder",
"DocumentationBuilderCatalog",
"DocumentationBuilderMd",
"DocumentationBuilderPage",
"DocumentationBuilderWindow",
"generate_for_sphinx",
"get_style",
]
from .documentation_catalog import DocumentationBuilderCatalog
from .documentation_extension import DocumentationBuilder, create_docs_window
from .documentation_generate import generate_for_sphinx
from .documentation_md import DocumentationBuilderMd
from .documentation_page import DocumentationBuilderPage
from .documentation_style import get_style
from .documentation_window import DocumentationBuilderWindow
| 1,089 | Python | 37.92857 | 77 | 0.803489 |
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_catalog.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["DocumentationBuilderCatalog"]
import asyncio
import weakref
from typing import Any, Dict, List
import omni.kit.app
import omni.ui as ui
class _CatalogModelItem(ui.AbstractItem):
def __init__(self, catalog_data):
super().__init__()
self.__catalog_data = catalog_data
self.name_model = ui.SimpleStringModel(catalog_data["name"])
self.__children = None
self.widget = None
def destroy(self):
for c in self.__children or []:
c.destroy()
self.__children = None
self.__catalog_data = None
self.widget = None
@property
def page_name(self):
return self.__catalog_data["page"]
@property
def children(self):
if self.__children is None:
# Lazy initialization
self.__children = [_CatalogModelItem(c) for c in self.__catalog_data.get("children", [])]
return self.__children
class _CatalogModel(ui.AbstractItemModel):
def __init__(self, catalog_data):
super().__init__()
self.__root = _CatalogModelItem({"name": "Root", "children": catalog_data})
def destroy(self):
self.__root.destroy()
self.__root = None
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is None:
return self.__root.children
return item.children
def get_item_value_model_count(self, item):
"""The number of columns"""
return 1
def get_item_value_model(self, item, column_id):
"""
Return value model.
"""
return item.name_model
class _CatalogDelegate(ui.AbstractItemDelegate):
def destroy(self):
pass
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
name = f"tree{level+1}"
with ui.ZStack(width=(level + 1) * 20):
ui.Rectangle(height=28, name=name)
if level > 0:
with ui.VStack():
ui.Spacer()
with ui.HStack(height=10):
ui.Spacer()
if model.can_item_have_children(item):
image = "minus" if expanded else "plus"
ui.Image(name=image, width=10, height=10)
ui.Spacer()
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per column per item"""
name = f"tree{level}"
label = model.get_item_value_model(item, column_id).as_string
if level == 1:
label = label.upper()
with ui.ZStack():
ui.Rectangle(height=28, name=name)
with ui.VStack():
item.widget = ui.Label(label, name=name, style_type_name_override="Text")
class DocumentationBuilderCatalog:
"""The left panel"""
def __init__(self, catalog_data, parent: weakref, **kwargs):
"""
`settings_menu: List[Dict[str, Any]]`
List of items. [{"name": "Export", "clicked_fn": on_export}]
"""
width = kwargs.get("width", 200)
self.__settings_menu: List[Dict[str, Any]] = kwargs.pop("settings_menu", None)
self._model = _CatalogModel(catalog_data)
self._delegate = _CatalogDelegate()
self.__parent = parent
with ui.ScrollingFrame(**kwargs):
with ui.VStack(height=0):
with ui.ZStack():
ui.Image(height=width, name="main_logo")
if self.__settings_menu:
with ui.Frame(height=16, width=16, mouse_hovered_fn=self._on_settings_hovered):
self.__settings_image = ui.Image(
name="settings", visible=False, mouse_pressed_fn=self._on_settings
)
tree_view = ui.TreeView(
self._model,
name="catalog",
delegate=self._delegate,
root_visible=False,
header_visible=False,
selection_changed_fn=self.__selection_changed,
)
# Generate the TreeView children
ui.Inspector.get_children(tree_view)
# Expand the first level
for i in self._model.get_item_children(None):
tree_view.set_expanded(i, True, False)
self.__stop_event = asyncio.Event()
self._menu = None
def destroy(self):
self.__settings_menu = []
self.__stop_event.set()
self.__settings_image = None
self._model.destroy()
self._model = None
self._delegate.destroy()
self._delegate = None
self._menu = None
async def _show_settings(self, delay, event: asyncio.Event):
for _i in range(delay):
await omni.kit.app.get_app().next_update_async()
if event.is_set():
return
self.__settings_image.visible = True
def _on_settings_hovered(self, hovered):
self.__stop_event.set()
self.__settings_image.visible = False
if hovered:
self.__stop_event = asyncio.Event()
asyncio.ensure_future(self._show_settings(100, self.__stop_event))
def _on_settings(self, x, y, button, mod):
self._menu = ui.Menu("Scene Docs Settings")
with self._menu:
for item in self.__settings_menu:
ui.MenuItem(item["name"], triggered_fn=item["clicked_fn"])
self._menu.show()
def __selection_changed(self, selection):
if not selection:
return
self.__parent().set_page(selection[0].page_name, selection[0].name_model.as_string)
| 6,230 | Python | 32.681081 | 103 | 0.564687 |
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_md.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["DocumentationBuilderMd"]
import re
from enum import Enum, auto
from pathlib import Path
from typing import Any, Dict, List, NamedTuple, Tuple, Union
import omni.client as client
H1_CHECK = re.compile(r"# .*")
H2_CHECK = re.compile(r"## .*")
H3_CHECK = re.compile(r"### .*")
PARAGRAPH_CHECK = re.compile(r"[a-zA-Z0-9].*")
LIST_CHECK = re.compile(r"^[-+] [a-zA-Z0-9].*$")
CODE_CHECK = re.compile(r"```.*")
IMAGE_CHECK = re.compile('!\\[(?P<alt>[^\\]]*)\\]\\((?P<url>.*?)(?=\\"|\\))(?P<title>\\".*\\")?\\)')
LINK_CHECK = re.compile(r"\[(.*)\]\((.*)\)")
LINK_IN_LIST = re.compile(r"^[-+] \[(.*)\]\((.*)\)")
TABLE_CHECK = re.compile(r"^(?:\s*\|.+)+\|\s*$")
class _BlockType(Enum):
H1 = auto()
H2 = auto()
H3 = auto()
PARAGRAPH = auto()
LIST = auto()
CODE = auto()
IMAGE = auto()
LINK = auto()
TABLE = auto()
LINK_IN_LIST = auto()
class _Block(NamedTuple):
block_type: _BlockType
text: Union[str, Tuple[str]]
source: str
metadata: Dict[str, Any]
class DocumentationBuilderMd:
"""
The cache for .md file.
It contains parsed data, catalog, links, etc...
"""
def __init__(self, filename: str):
"""
### Arguments
`filename : str`
Path to .md file
"""
self.__filename = filename
self.__blocks: List[_Block] = []
result, _, content = client.read_file(f"{filename}")
if result != client.Result.OK:
content = ""
else:
content = memoryview(content).tobytes().decode("utf-8")
self._process_lines(content.splitlines())
def destroy(self):
pass
@property
def blocks(self):
return self.__blocks
@property
def catalog(self):
"""
Return the document outline in the following format:
{"name": "h1", "children": []}
"""
result = []
blocks = [b for b in self.__blocks if b.block_type in [_BlockType.H1, _BlockType.H2, _BlockType.H3]]
if blocks:
self._get_catalog_recursive(blocks, result, blocks[0].block_type.value)
return result
@property
def source(self) -> str:
content = []
code_id = 0
page_name = self.name
for block in self.__blocks:
if block.block_type == _BlockType.CODE:
content.append(self._source_code(block, page_name, code_id))
code_id += 1
else:
content.append(block.source)
return "\n\n".join(content) + "\n"
@property
def code_blocks(self) -> List[Dict[str, str]]:
page_name = self.name
blocks = [b for b in self.__blocks if b.block_type == _BlockType.CODE]
return [
{"name": f"{page_name}_{i}", "code": block.text, "height": block.metadata["height"]}
for i, block in enumerate(blocks)
if block.metadata.get("code_type", None) == "execute"
]
@property
def image_blocks(self) -> List[Dict[str, str]]:
return [
{"path": block.text, "alt": block.metadata["alt"], "title": block.metadata["title"]}
for block in self.__blocks
if block.block_type == _BlockType.IMAGE
]
@property
def name(self):
first_header = next(
(b for b in self.__blocks if b.block_type in [_BlockType.H1, _BlockType.H2, _BlockType.H3]), None
)
return first_header.text if first_header else None
def _get_catalog_recursive(self, blocks: List[_Block], children: List[Dict], level: int):
while blocks:
top = blocks[0]
top_level = top.block_type.value
if top_level == level:
children.append({"name": top.text, "children": []})
blocks.pop(0)
elif top_level > level:
self._get_catalog_recursive(blocks, children[-1]["children"], top_level)
else: # top_level < level
return
def _add_block(self, block_type, text, source, **kwargs):
self.__blocks.append(_Block(block_type, text, source, kwargs))
def _process_lines(self, content):
# Remove empty lines
while True:
while content and not content[0].strip():
content.pop(0)
if not content:
break
if H1_CHECK.match(content[0]):
self._process_h1(content)
elif H2_CHECK.match(content[0]):
self._process_h2(content)
elif H3_CHECK.match(content[0]):
self._process_h3(content)
elif CODE_CHECK.match(content[0]):
self._process_code(content)
elif IMAGE_CHECK.match(content[0]):
self._process_image(content)
elif LINK_CHECK.match(content[0]):
self._process_link(content)
elif LINK_IN_LIST.match(content[0]):
self._process_link_in_list(content)
elif LIST_CHECK.match(content[0]):
self._process_list(content)
elif TABLE_CHECK.match(content[0]):
self._process_table(content)
else:
self._process_paragraph(content)
def _process_h1(self, content):
text = content.pop(0)
self._add_block(_BlockType.H1, text[2:], text)
def _process_h2(self, content):
text = content.pop(0)
self._add_block(_BlockType.H2, text[3:], text)
def _process_h3(self, content):
text = content.pop(0)
self._add_block(_BlockType.H3, text[4:], text)
def _process_list(self, content: List[str]):
text_lines = []
while True:
current_line = content.pop(0)
text_lines.append(current_line.strip())
if not content or not LIST_CHECK.match(content[0]):
# The next line is not a paragraph.
break
self._add_block(_BlockType.LIST, tuple(text_lines), "\n".join(text_lines))
def _process_table(self, content: List[str]):
text_lines = []
while True:
current_line = content.pop(0)
text_lines.append(current_line.strip())
if not content or not TABLE_CHECK.match(content[0]):
# The next line is not a paragraph.
break
self._add_block(_BlockType.TABLE, tuple(text_lines), "\n".join(text_lines))
def _process_link(self, content):
text = content.pop(0)
self._add_block(_BlockType.LINK, text, text)
def _process_link_in_list(self, content: List[str]):
text_lines = []
while True:
current_line = content.pop(0)
text_lines.append(current_line.strip())
if not content or not LINK_CHECK.match(content[0]):
# The next line is not a link in a list.
break
self._add_block(_BlockType.LINK_IN_LIST, tuple(text_lines), "\n".join(text_lines))
def _process_paragraph(self, content: List[str]):
text_lines = []
while True:
current_line = content.pop(0)
text_lines.append(current_line.strip())
if current_line.endswith(" "):
# To create a line break, end a line with two or more spaces.
break
if not content or not PARAGRAPH_CHECK.match(content[0]):
# The next line is not a paragraph.
break
self._add_block(_BlockType.PARAGRAPH, " ".join(text_lines), "\n".join(text_lines))
def _process_code(self, content):
source = []
text = content.pop(0)
source.append(text)
code_type = text[3:].strip().split()
# Extract height
if code_type and len(code_type) > 1:
height = code_type[1]
else:
height = None
if code_type:
code_type = code_type[0]
else:
code_type = ""
code_lines = []
while content and not CODE_CHECK.match(content[0]):
text = content.pop(0)
source.append(text)
code_lines.append(text)
source.append(content.pop(0))
self._add_block(_BlockType.CODE, "\n".join(code_lines), "\n".join(source), code_type=code_type, height=height)
def _process_image(self, content: List[str]):
text = content.pop(0)
parts = IMAGE_CHECK.match(text.strip()).groupdict()
path = Path(self.__filename).parent.joinpath(parts["url"])
self._add_block(_BlockType.IMAGE, f"{path}", text, alt=parts["alt"], title=parts["title"])
@staticmethod
def get_clean_code(block):
# Remove double-comments
clean = []
skip = False
for line in block.text.splitlines():
if line.lstrip().startswith("##"):
skip = not skip
continue
if skip:
continue
if not clean and not line.strip():
continue
clean.append(line)
return "\n".join(clean)
def _source_code(self, block, page_name, code_id):
result = []
code_type = block.metadata.get("code_type", "")
if code_type == "execute":
image_name = f"{page_name}_{code_id}.png"
result.append(f"\n")
code_type = "python"
elif code_type == "execute-manual":
code_type = "python"
result.append(f"```{code_type}")
result.append(self.get_clean_code(block))
result.append("```")
return "\n".join(result)
| 10,066 | Python | 30.857595 | 118 | 0.548281 |
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_generate.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["generate_for_sphinx"]
import shutil
import traceback
from pathlib import Path
import carb
import omni.kit.app
import omni.ui as ui
from .documentation_capture import DocumentationBuilderCapture
from .documentation_md import DocumentationBuilderMd
from .documentation_style import get_style
PRINT_GENERATION_STATUS = True # Can be made into setting if needed
def _print(message):
if PRINT_GENERATION_STATUS:
print(message)
else:
carb.log_info(message)
def generate_for_sphinx(extension_id: str, path: str) -> bool:
"""
Produce the set of files and screenshots readable by Sphinx.
### Arguments
`extension_id: str`
The extension to generate documentation files
`path: str`
The path to produce the files.
### Return
`True` if generation succeded.
"""
_print(f"Generating for sphinx. Ext: {extension_id}. Path: {path}")
out_path = Path(path)
if not out_path.is_dir():
carb.log_error(f"{path} is not a directory")
return False
ext_info = omni.kit.app.get_app().get_extension_manager().get_extension_dict(extension_id)
if ext_info is None:
carb.log_error(f"Extension id {extension_id} not found")
return False
if not ext_info.get("state", {}).get("enabled", False):
carb.log_error(f"Extension id {extension_id} is not enabled")
return False
ext_path = Path(ext_info.get("path", ""))
pages = ext_info.get("documentation", {}).get("pages", [])
if len(pages) == 0:
carb.log_error(f"Extension id {extension_id} has no pages set in [documentation] section of config.")
return False
for page in pages:
_print(f"Processing page: '{page}'")
if not page.endswith(".md"):
_print(f"Not .md, skipping: '{page}'")
continue
page_path = Path(ext_path / page)
md = DocumentationBuilderMd(str(page_path))
if md.name is None:
_print(f"md is None, skipping: '{page}'")
continue
for code_block in md.code_blocks:
image_file = out_path / f"{code_block['name']}.png"
height = int(code_block["height"] or 200)
with DocumentationBuilderCapture(str(image_file), 800, height):
stack = ui.ZStack()
stack.set_style(get_style())
with stack:
# Background
ui.Rectangle(name="code_background")
# The code
with ui.VStack():
try:
_execute_code(code_block["code"])
except Exception as e:
tb = traceback.format_exception(Exception, e, e.__traceback__)
ui.Label(
"".join(tb), name="code", style_type_name_override="Text", skip_draw_when_clipped=True
)
_print(f"Generated image: '{image_file}'")
for image_block in md.image_blocks:
image_file = Path(image_block["path"])
image_out = out_path / image_file.relative_to(page_path.parent)
image_out.parent.mkdir(parents=True, exist_ok=True)
try:
shutil.copyfile(image_file, image_out)
except shutil.SameFileError:
pass
_print(f"Copied image: '{image_out}'")
md_file = out_path / f"{page_path.stem}.md"
with open(md_file, "w", encoding="utf-8") as f:
f.write(md.source)
_print(f"Generated md file: '{md_file}'")
return True
def _execute_code(code: str):
# Wrap the code in a class to provide scoping
indented = "\n".join([" " + line for line in code.splitlines()])
source = f"class Execution:\n def __init__(self):\n{indented}"
locals_from_execution = {}
# flake8: noqa: PLW0122
exec(source, None, locals_from_execution)
locals_from_execution["Execution"]()
| 4,473 | Python | 33.953125 | 118 | 0.594232 |
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_extension.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
import os.path
import typing
from functools import partial
import omni.ext
import omni.kit.app
import omni.kit.ui
from .documentation_window import DocumentationBuilderWindow
class DocumentationBuilder(omni.ext.IExt):
"""
Extension to create a documentation window for any extension which has
markdown pages defined in its extension.toml.
Such pages can have inline omni.ui code blocks which are executed.
For example,
[documentation]
pages = ["docs/Overview.md"]
menu = "Help/API/omni.kit.documentation.builder"
title = "Omni UI Documentation Builder"
"""
def __init__(self):
super().__init__()
# cache docs and window by extensions id
self._doc_info: typing.Dict[str, _DocInfo] = {}
self._editor_menu = None
self._extension_enabled_hook = None
self._extension_disabled_hook = None
def on_startup(self, ext_id: str):
self._editor_menu = omni.kit.ui.get_editor_menu()
manager = omni.kit.app.get_app().get_extension_manager()
# add menus for any extensions with docs that are already enabled
all_exts = manager.get_extensions()
for ext in all_exts:
if ext.get("enabled", False):
self._add_docs_menu(ext.get("id"))
# hook into extension enable/disable events if extension specifies "documentation" config key
hooks = manager.get_hooks()
self._extension_enabled_hook = hooks.create_extension_state_change_hook(
self.on_after_extension_enabled,
omni.ext.ExtensionStateChangeType.AFTER_EXTENSION_ENABLE,
ext_dict_path="documentation",
hook_name="omni.kit.documentation.builder",
)
self._extension_disabled_hook = hooks.create_extension_state_change_hook(
self.on_before_extension_disabled,
omni.ext.ExtensionStateChangeType.BEFORE_EXTENSION_DISABLE,
ext_dict_path="documentation",
hook_name="omni.kit.documentation.builder",
)
def on_shutdown(self):
self._extension_enabled_hook = None
self._extension_disabled_hook = None
for ext_id in list(self._doc_info.keys()):
self._destroy_docs_window(ext_id)
self._editor_menu = None
def on_after_extension_enabled(self, ext_id: str, *_):
self._add_docs_menu(ext_id)
def on_before_extension_disabled(self, ext_id: str, *_):
self._destroy_docs_window(ext_id)
def _add_docs_menu(self, ext_id: str):
doc_info = _get_doc_info(ext_id)
if doc_info and doc_info.menu_path and self._editor_menu:
doc_info.menu = self._editor_menu.add_item(doc_info.menu_path, partial(self._show_docs_window, ext_id))
self._doc_info[ext_id] = doc_info
def _show_docs_window(self, ext_id: str, *_):
window = self._doc_info[ext_id].window
if not window:
window = _create_docs_window(ext_id)
self._doc_info[ext_id].window = window
window.visible = True
def _destroy_docs_window(self, ext_id: str):
if ext_id in self._doc_info:
doc_info = self._doc_info.pop(ext_id)
if doc_info.window:
doc_info.window.destroy()
def create_docs_window(ext_name: str):
"""
Creates a DocumentationBuilderWindow for ext_name
Returns the window, or None if no such extension is enabled and has documentation
"""
# fetch by name
ext_versions = omni.kit.app.get_app().get_extension_manager().fetch_extension_versions(ext_name)
# use latest version that is enabled
for ver in ext_versions:
if ver.get("enabled", False):
return _create_docs_window(ver.get("id", ""))
return None
def _create_docs_window(ext_id: str):
"""
Creates a DocumentationBuilderWindow for ext_id
Returns the window, or None if ext_id has no documentation
"""
doc_info = _get_doc_info(ext_id)
if doc_info:
window = DocumentationBuilderWindow(doc_info.title, filenames=doc_info.pages)
return window
return None
class _DocInfo:
def __init__(self):
self.pages = []
self.menu_path = ""
self.title = ""
self.window = None
self.menu = None
def _get_doc_info(ext_id: str) -> _DocInfo:
"""
Returns extension documentation metadata if it exists.
Returns None if exension has no documentation pages.
"""
ext_info = omni.kit.app.get_app().get_extension_manager().get_extension_dict(ext_id)
if ext_info:
ext_path = ext_info.get("path", "")
doc_dict = ext_info.get("documentation", {})
doc_info = _DocInfo()
doc_info.pages = doc_dict.get("pages", [])
doc_info.menu_path = doc_dict.get("menu", "Help/API/" + ext_id)
doc_info.title = doc_dict.get("title", ext_id)
filenames = []
for page in doc_info.pages:
filenames.append(page if os.path.isabs(page) else os.path.join(ext_path, page))
if filenames:
doc_info.pages = filenames
return doc_info
return None
| 5,549 | Python | 34.806451 | 115 | 0.640115 |
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_page.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["DocumentationBuilderPage"]
import re
import subprocess
import sys
import traceback
import weakref
import webbrowser
from functools import partial
from typing import Any, Dict, List, Optional
import omni.ui as ui
from PIL import Image
from .documentation_md import LINK_CHECK, DocumentationBuilderMd, _Block, _BlockType
class DocumentationBuilderPage:
"""
Widget that draws .md page with the cache.
"""
def __init__(self, md: DocumentationBuilderMd, scroll_to: Optional[str] = None):
"""
### Arguments
`md : DocumentationBuilderMd`
MD cache object
`scroll_to : Optional[str]`
The name of the section to scroll to
"""
self.__md = md
self.__scroll_to = scroll_to
self.__images: List[ui.Image] = []
self.__code_stacks: List[ui.ZStack] = []
self.__code_locals: Dict[str, Any] = {}
self._copy_context_menu = None
self.__bookmarks: Dict[str, ui.Widget] = {}
self._dont_scale_images = False
ui.Frame(build_fn=self.__build)
def destroy(self):
self.__bookmarks: Dict[str, ui.Widget] = {}
if self._copy_context_menu:
self._copy_context_menu.destroy()
self._copy_context_menu = None
self.__code_locals = {}
for stack in self.__code_stacks:
stack.destroy()
self.__code_stacks = []
for image in self.__images:
image.destroy()
self.__images = []
@property
def name(self):
"""The name of the page"""
return self.__md.name
def scroll_to(self, where: str):
"""Scroll to the given section"""
widget = self.__bookmarks.get(where, None)
if widget:
widget.scroll_here()
def _execute_code(self, code: str):
indented = "\n".join([" " + line for line in code.splitlines()])
source = f"class Execution:\n def __init__(self):\n{indented}"
locals_from_execution = {}
# flake8: noqa: PLW0122
exec(source, None, locals_from_execution)
self.__code_locals[code] = locals_from_execution["Execution"]()
def __build(self):
self.__bookmarks: Dict[str, ui.Widget] = {}
with ui.HStack():
ui.Spacer(width=50)
with ui.VStack(height=0):
ui.Spacer(height=50)
for block in self.__md.blocks:
# Build sections one by one
# Space between sections
space = ui.Spacer(height=10)
self.__bookmarks[block.text] = space
if block.text == self.__scroll_to:
# Scroll to this section if necessary
space.scroll_here()
if block.block_type == _BlockType.H1:
self._build_h1(block)
elif block.block_type == _BlockType.H2:
self._build_h2(block)
elif block.block_type == _BlockType.H3:
self._build_h3(block)
elif block.block_type == _BlockType.PARAGRAPH:
self._build_paragraph(block)
elif block.block_type == _BlockType.LIST:
self._build_list(block)
elif block.block_type == _BlockType.TABLE:
self._build_table(block)
elif block.block_type == _BlockType.LINK:
self._build_link(block)
elif block.block_type == _BlockType.CODE:
self._build_code(block)
elif block.block_type == _BlockType.IMAGE:
self._build_image(block)
elif block.block_type == _BlockType.LINK_IN_LIST:
self._build_link_in_list(block)
ui.Spacer(height=50)
ui.Spacer(width=50)
def _build_h1(self, block: _Block):
with ui.ZStack():
ui.Rectangle(name="h1")
ui.Label(block.text, name="h1", style_type_name_override="Text")
def _build_h2(self, block: _Block):
with ui.VStack():
ui.Line(name="h2")
ui.Label(block.text, name="h2", style_type_name_override="Text")
ui.Line(name="h2")
def _build_h3(self, block: _Block):
with ui.VStack(height=0):
ui.Line(name="h3")
ui.Label(block.text, name="h3", style_type_name_override="Text")
ui.Line(name="h3")
def _build_paragraph(self, block: _Block):
ui.Label(block.text, name="paragraph", word_wrap=True, skip_draw_when_clipped=True)
def _build_list(self, block: _Block):
with ui.VStack(spacing=-5):
for list_entry in block.text:
list_entry = list_entry.lstrip("+")
list_entry = list_entry.lstrip("-")
with ui.HStack(spacing=0):
ui.Circle(
width=10, size_policy=ui.CircleSizePolicy.FIXED, alignment=ui.Alignment.LEFT_CENTER, radius=3
)
ui.Label(
list_entry,
alignment=ui.Alignment.LEFT_TOP,
name="paragraph",
word_wrap=True,
skip_draw_when_clipped=True,
)
# ui.Spacer(width=5)
def _build_link_in_list(self, block: _Block):
with ui.VStack(spacing=-5):
for list_entry in block.text:
list_entry = list_entry.lstrip("+")
list_entry = list_entry.lstrip("-")
list_entry = list_entry.lstrip()
with ui.HStack(spacing=0):
ui.Circle(
width=10, size_policy=ui.CircleSizePolicy.FIXED, alignment=ui.Alignment.LEFT_CENTER, radius=3
)
reg = re.match(LINK_CHECK, list_entry)
if reg and len(reg.groups()) == 2:
self._build_link_impl(reg.group(1), reg.group(2))
def _build_link(self, block: _Block):
text = block.text
reg = re.match(LINK_CHECK, text)
label = ""
url = ""
if reg and len(reg.groups()) == 2:
label = reg.group(1)
url = reg.group(2)
self._build_link_impl(label, url)
def _build_link_impl(self, label, url):
def _on_clicked(a, b, c, d, url):
try:
webbrowser.open(url)
except OSError:
print("Please open a browser on: " + url)
with ui.HStack():
spacer = ui.Spacer(width=5)
label = ui.Label(
label,
style_type_name_override="url_link",
name="paragraph",
word_wrap=True,
skip_draw_when_clipped=True,
tooltip=url,
)
label.set_mouse_pressed_fn(lambda a, b, c, d, u=url: _on_clicked(a, b, c, d, u))
def _build_table(self, block: _Block):
cells = []
num_columns = 0
for line in block.text:
cell_text_list = line.split("|")
cell_text_list = [c.strip() for c in cell_text_list]
cell_text_list = [c for c in cell_text_list if c]
num_columns = max(num_columns, len(cell_text_list))
cells.append(cell_text_list)
# Assume 2nd row is separators "|------|---|"
del cells[1]
frame_pixel_width = 800
grid_column_width = frame_pixel_width / num_columns
frame_pixel_height = len(cells) * 20
with ui.ScrollingFrame(
width=frame_pixel_width,
height=frame_pixel_height,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
):
with ui.VGrid(column_width=grid_column_width, row_height=20):
for i in range(len(cells)):
for j in range(num_columns):
with ui.ZStack():
bg_color = 0xFFCCCCCC if i == 0 else 0xFFFFFFF
ui.Rectangle(
style={
"border_color": 0xFF000000,
"background_color": bg_color,
"border_width": 1,
"margin": 0,
}
)
cell_val = cells[i][j]
if len(cell_val) > 66:
cell_val = cell_val[:65] + "..."
ui.Label(f"{cell_val}", style_type_name_override="table_label")
def _build_code(self, block: _Block):
def label_size_changed(label: ui.Label, short_frame: ui.Frame, overlay: ui.Frame):
max_height = ui.Pixel(200)
if label.computed_height > max_height.value:
short_frame.height = max_height
short_frame.vertical_clipping = True
with overlay:
with ui.VStack():
ui.Spacer()
with ui.ZStack():
ui.Rectangle(style_type_name_override="TextOverlay")
ui.InvisibleButton(clicked_fn=partial(remove_overlay, label, short_frame, overlay))
def remove_overlay(label: ui.Label, short_frame: ui.Frame, overlay: ui.Frame):
short_frame.height = ui.Pixel(label.computed_height)
with overlay:
ui.Spacer()
code_type = block.metadata.get("code_type", None)
is_execute_manual = code_type == "execute-manual"
is_execute = code_type == "execute"
if is_execute:
with ui.Frame(horizontal_clipping=True):
with ui.ZStack():
# Background
ui.Rectangle(name="code_background")
# The code
with ui.VStack():
try:
self._execute_code(block.text)
except Exception as e:
tb = traceback.format_exception(Exception, e, e.__traceback__)
ui.Label(
"".join(tb), name="code", style_type_name_override="Text", skip_draw_when_clipped=True
)
ui.Spacer(height=10)
# Remove double-comments
clean = DocumentationBuilderMd.get_clean_code(block)
with ui.Frame(horizontal_clipping=True):
stack = ui.ZStack(height=0)
with stack:
ui.Rectangle(name="code")
short_frame = ui.Frame()
with short_frame:
label = ui.Label(clean, name="code", style_type_name_override="Text", skip_draw_when_clipped=True)
overlay = ui.Frame()
# Enable clipping/extending the label after we know its size
label.set_computed_content_size_changed_fn(partial(label_size_changed, label, short_frame, overlay))
self.__code_stacks.append(stack)
if is_execute_manual:
ui.Spacer(height=4)
with ui.HStack():
# ui.Spacer(height=10)
def on_click(text=block.text):
try:
self._execute_code(block.text)
except Exception as e:
tb = traceback.format_exception(Exception, e, e.__traceback__)
ui.Label("".join(tb), name="code", style_type_name_override="Text", skip_draw_when_clipped=True)
button = ui.Button(
"RUN CODE", style_type_name_override="RunButton", width=50, height=20, clicked_fn=on_click
)
ui.Spacer()
if sys.platform != "linux":
stack.set_mouse_pressed_fn(lambda x, y, b, m, text=clean: b == 1 and self._show_copy_menu(x, y, b, m, text))
def _build_image(self, block: _Block):
source_url = block.text
def change_resolution_legacy(image_weak, size):
"""
Change the widget size proportionally to the image
We set a max height of 400 for anything.
"""
MAX_HEIGHT = 400
image = image_weak()
if not image:
return
width, height = size
image_height = min(image.computed_content_width * height / width, MAX_HEIGHT)
image.height = ui.Pixel(image_height)
def change_resolution(image_weak, size):
"""
This leaves the image scale untouched
"""
image = image_weak()
if not image:
return
width, height = size
image.height = ui.Pixel(height)
image.width = ui.Pixel(width)
im = Image.open(source_url)
image = ui.Image(source_url, height=200)
# Even though the legacy behaviour is probably wrong there are extensions out there with images that are
# too big, we don't want them to display differently than before
if self._dont_scale_images:
image.set_computed_content_size_changed_fn(partial(change_resolution, weakref.ref(image), im.size))
else:
image.set_computed_content_size_changed_fn(partial(change_resolution_legacy, weakref.ref(image), im.size))
self.__images.append(image)
def _show_copy_menu(self, x, y, button, modifier, text):
"""The context menu to copy the text"""
# Display context menu only if the right button is pressed
def copy_text(text_value):
# we need to find a cross plartform way currently Window Only
subprocess.run(["clip.exe"], input=text_value.strip().encode("utf-8"), check=True)
# Reset the previous context popup
self._copy_context_menu = ui.Menu("Copy Context Menu")
with self._copy_context_menu:
ui.MenuItem("Copy Code", triggered_fn=lambda t=text: copy_text(t))
# Show it
self._copy_context_menu.show()
| 14,863 | Python | 37.015345 | 120 | 0.519545 |
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/documentation_style.py | # Copyright (c) 2018-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from pathlib import Path
import omni.ui as ui
from omni.ui import color as cl
from omni.ui import constant as fl
from omni.ui import url
CURRENT_PATH = Path(__file__).parent
DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data")
FONTS_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("fonts")
def get_style():
"""
Returns the standard omni.ui style for documentation
"""
cl.documentation_nvidia = cl("#76b900")
# Content
cl.documentation_bg = cl.white
cl.documentation_text = cl("#1a1a1a")
cl.documentation_h1_bg = cl.black
cl.documentation_h1_color = cl.documentation_nvidia
cl.documentation_h2_line = cl.black
cl.documentation_h2_color = cl.documentation_nvidia
cl.documentation_exec_bg = cl("#454545")
cl.documentation_code_bg = cl("#eeeeee")
cl.documentation_code_fadeout = cl("#eeeeee01")
cl.documentation_code_fadeout_selected = cl.documentation_nvidia
cl.documentation_code_line = cl("#bbbbbb")
fl.documentation_margin = 5
fl.documentation_code_size = 16
fl.documentation_code_radius = 2
fl.documentation_text_size = 18
fl.documentation_h1_size = 36
fl.documentation_h2_size = 28
fl.documentation_h3_size = 20
fl.documentation_line_width = 0.3
cl.url_link = cl("#3333CC")
# Catalog
cl.documentation_catalog_bg = cl.black
cl.documentation_catalog_text = cl("#cccccc")
cl.documentation_catalog_h1_bg = cl("#333333")
cl.documentation_catalog_h1_color = cl.documentation_nvidia
cl.documentation_catalog_h2_bg = cl("#fcfcfc")
cl.documentation_catalog_h2_color = cl("#404040")
cl.documentation_catalog_h3_bg = cl("#e3e3e3")
cl.documentation_catalog_h3_color = cl("#404040")
cl.documentation_catalog_icon_selected = cl("#333333")
fl.documentation_catalog_tree1_size = 17
fl.documentation_catalog_tree1_margin = 5
fl.documentation_catalog_tree2_size = 19
fl.documentation_catalog_tree2_margin = 2
fl.documentation_catalog_tree3_size = 19
fl.documentation_catalog_tree3_margin = 2
url.documentation_logo = f"{DATA_PATH.joinpath('main_ov_logo_square.png')}"
url.documentation_settings = f"{DATA_PATH.joinpath('settings.svg')}"
url.documentation_plus = f"{DATA_PATH.joinpath('plus.svg')}"
url.documentation_minus = f"{DATA_PATH.joinpath('minus.svg')}"
url.documentation_font_regular = f"{FONTS_PATH}/DINPro-Regular.otf"
url.documentation_font_regular_bold = f"{FONTS_PATH}/DINPro-Bold.otf"
url.documentation_font_monospace = f"{FONTS_PATH}/DejaVuSansMono.ttf"
style = {
"Window": {"background_color": cl.documentation_catalog_bg, "border_width": 0, "padding": 0},
"Rectangle::content_background": {"background_color": cl.documentation_bg},
"Label::paragraph": {
"color": cl.documentation_text,
"font_size": fl.documentation_text_size,
"margin": fl.documentation_margin,
},
"Text::code": {
"color": cl.documentation_text,
"font": url.documentation_font_monospace,
"font_size": fl.documentation_code_size,
"margin": fl.documentation_margin,
},
"url_link": {"color": cl.url_link, "font_size": fl.documentation_text_size},
"table_label": {
"color": cl.documentation_text,
"font_size": fl.documentation_text_size,
"margin": 2,
},
"Rectangle::code": {
"background_color": cl.documentation_code_bg,
"border_color": cl.documentation_code_line,
"border_width": fl.documentation_line_width,
"border_radius": fl.documentation_code_radius,
},
"Rectangle::code_background": {"background_color": cl.documentation_exec_bg},
"Rectangle::h1": {"background_color": cl.documentation_h1_bg},
"Rectangle::tree1": {"background_color": cl.documentation_catalog_h1_bg},
"Rectangle::tree2": {"background_color": 0x0},
"Rectangle::tree2:selected": {"background_color": cl.documentation_catalog_h2_bg},
"Rectangle::tree3": {"background_color": 0x0},
"Rectangle::tree3:selected": {"background_color": cl.documentation_catalog_h3_bg},
"Text::h1": {
"color": cl.documentation_h1_color,
"font": url.documentation_font_regular,
"font_size": fl.documentation_h1_size,
"margin": fl.documentation_margin,
"alignment": ui.Alignment.CENTER,
},
"Text::h2": {
"color": cl.documentation_h2_color,
"font": url.documentation_font_regular,
"font_size": fl.documentation_h2_size,
"margin": fl.documentation_margin,
},
"Text::h3": {
"color": cl.documentation_h2_color,
"font": url.documentation_font_regular,
"font_size": fl.documentation_h3_size,
"margin": fl.documentation_margin,
},
"Text::tree1": {
"color": cl.documentation_catalog_h1_color,
"font": url.documentation_font_regular_bold,
"font_size": fl.documentation_catalog_tree1_size,
"margin": fl.documentation_catalog_tree1_margin,
},
"Text::tree2": {
"color": cl.documentation_catalog_text,
"font": url.documentation_font_regular,
"font_size": fl.documentation_catalog_tree2_size,
"margin": fl.documentation_catalog_tree2_margin,
},
"Text::tree2:selected": {"color": cl.documentation_catalog_h2_color},
"Text::tree3": {
"color": cl.documentation_catalog_text,
"font": url.documentation_font_regular,
"font_size": fl.documentation_catalog_tree3_size,
"margin": fl.documentation_catalog_tree3_margin,
},
"Text::tree3:selected": {"color": cl.documentation_catalog_h3_color},
"Image::main_logo": {"image_url": url.documentation_logo},
"Image::settings": {"image_url": url.documentation_settings},
"Image::plus": {"image_url": url.documentation_plus},
"Image::minus": {"image_url": url.documentation_minus},
"Image::plus:selected": {"color": cl.documentation_catalog_icon_selected},
"Image::minus:selected": {"color": cl.documentation_catalog_icon_selected},
"Line::h2": {"border_width": fl.documentation_line_width},
"Line::h3": {"border_width": fl.documentation_line_width},
"TextOverlay": {
"background_color": cl.documentation_bg,
"background_gradient_color": cl.documentation_code_fadeout,
},
"TextOverlay:hovered": {"background_color": cl.documentation_code_fadeout_selected},
"RunButton": {"background_color": cl("#76b900"), "border_radius": 2},
"RunButton.Label": {"color": 0xFF3E3E3E, "font_size": 14},
"RunButton:hovered": {"background_color": cl("#84d100")},
"RunButton:pressed": {"background_color": cl("#7bc200")},
}
return style
| 7,491 | Python | 42.812865 | 101 | 0.637699 |
omniverse-code/kit/exts/omni.kit.documentation.builder/omni/kit/documentation/builder/tests/test_documentation.py | # Copyright (c) 2019-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["TestDocumentation"]
import pathlib
import omni.kit.app
import omni.kit.test
from omni.ui.tests.test_base import OmniUiTest
from ..documentation_md import DocumentationBuilderMd
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
TESTS_PATH = EXTENSION_FOLDER_PATH.joinpath("data/tests")
class TestDocumentation(OmniUiTest):
async def test_builder(self):
builder = DocumentationBuilderMd(f"{TESTS_PATH}/test.md")
self.assertEqual(
builder.catalog,
[{"name": "NVIDIA", "children": [{"name": "Omiverse", "children": [{"name": "Doc", "children": []}]}]}],
)
self.assertEqual(builder.blocks[0].text, "NVIDIA")
self.assertEqual(builder.blocks[0].block_type.name, "H1")
self.assertEqual(builder.blocks[1].text, "Omiverse")
self.assertEqual(builder.blocks[1].block_type.name, "H2")
self.assertEqual(builder.blocks[2].text, "Doc")
self.assertEqual(builder.blocks[2].block_type.name, "H3")
self.assertEqual(builder.blocks[3].text, "Text")
self.assertEqual(builder.blocks[3].block_type.name, "PARAGRAPH")
clean = builder.get_clean_code(builder.blocks[4])
self.assertEqual(clean, 'ui.Label("Hello")')
self.assertEqual(builder.blocks[4].block_type.name, "CODE")
self.assertEqual(builder.blocks[5].text, ("- List1", "- List2"))
self.assertEqual(builder.blocks[5].block_type.name, "LIST")
self.assertEqual(builder.blocks[6].text, ("- [YOUTUBE](https://www.youtube.com)",))
self.assertEqual(builder.blocks[6].block_type.name, "LINK_IN_LIST")
self.assertEqual(builder.blocks[7].text, "[NVIDIA](https://www.nvidia.com)")
self.assertEqual(builder.blocks[7].block_type.name, "LINK")
self.assertEqual(
builder.blocks[8].text, ("| Noun | Adjective |", "| ---- | --------- |", "| Omniverse | Awesome |")
)
self.assertEqual(builder.blocks[8].block_type.name, "TABLE")
builder.destroy()
| 2,531 | Python | 39.838709 | 116 | 0.670881 |
omniverse-code/kit/exts/omni.kit.documentation.builder/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
| 504 | Python | 44.909087 | 76 | 0.809524 |
omniverse-code/kit/exts/omni.kit.documentation.builder/docs/CHANGELOG.md | # Changelog
The interactive documentation builder for omni.ui extensions
## [1.0.9] - 2022-11-16
### Changed
- Remove execute tag from Overview.md for publishing
## [1.0.8] - 2022-08-29
### Added
- List, link, and basic table support
- Show errors from code execute blocks
## [1.0.7] - 2022-06-27
### Added
- Create documentation menu automatically from extension.toml files
## [1.0.6] - 2022-06-22
### Fixed
- Allow md headers without initial H1 level
## [1.0.5] - 2022-06-14
### Added
- Use ui.Label for all text blocks
## [1.0.4] - 2022-05-09
### Fixed
- Missing import
## [1.0.3] - 2022-04-30
### Added
- Minimal test
## [1.0.2] - 2021-12-17
### Added
- `DocumentationBuilderWindow.get_style` to get the default style
## [1.0.1] - 2021-12-15
### Added
- A separate widget for the page `DocumentationBuilderPage`
## [1.0.0] - 2021-12-14
### Added
- The initial implementation
| 890 | Markdown | 18.8 | 67 | 0.669663 |
omniverse-code/kit/exts/omni.kit.documentation.builder/docs/README.md | # The documentation for omni.ui extensions
The interactive documentation builder for omni.ui extensions | 104 | Markdown | 33.999989 | 60 | 0.846154 |
omniverse-code/kit/exts/omni.kit.documentation.builder/docs/index.rst | omni.kit.documentation.builder
##############################
.. toctree::
:maxdepth: 1
CHANGELOG
| 108 | reStructuredText | 9.899999 | 30 | 0.481481 |
omniverse-code/kit/exts/omni.kit.documentation.builder/docs/Overview.md | # Omni.UI Documentation Builder
The Documentation Builder extension finds enabled extensions with a [documentation] section in their extension.toml
and adds a menu to show that documentation in a popup window. Extensions do not need to depend on
omni.kit.documentation.builder to enable this functionality.
For example:
```toml
[documentation]
pages = ["docs/Overview.md"]
menu = "Help/API/omni.kit.documentation.builder"
title = "Omni UI Documentation Builder"
```
Documentation pages may contain code blocks with omni.ui calls that will be executed and displayed inline, by using
the "execute" language tag after three backticks:
````{code-block} markdown
---
dedent: 4
---
```execute
import omni.ui as ui
ui.Label("Hello World!")
```
````
## generate_for_sphinx
omni.kit.documentation.builder.generate_for_sphinx can be called to generate documentation offline for sphinx web pages:
```python
import omni.kit.app
import omni.kit.documentation.builder as builder
manager = omni.kit.app.get_app().get_extension_manager()
all_exts = manager.get_extensions()
for ext in all_exts:
if ext.get("enabled", False):
builder.generate_for_sphinx(ext.get("id", ""), f"/docs/{ext.get('name')}")
```
## create_docs_window
Explicity create a documentation window with the omni.kit.documentation.builder.create_docs_window function:
```python
import omni.kit.documentation.builder as builder
builder.create_docs_window("omni.kit.documentation.builder")
```
| 1,482 | Markdown | 28.078431 | 120 | 0.749663 |
omniverse-code/kit/exts/omni.kit.documentation.builder/data/tests/test.md | # NVIDIA
## Omiverse
### Doc
Text
```execute
##
import omni.ui as ui
##
ui.Label("Hello")
```
- List1
- List2
[NVIDIA](https://www.nvidia.com)
| Noun | Adjective |
| ---- | --------- |
| Omniverse | Awesome |
| 214 | Markdown | 8.772727 | 32 | 0.551402 |
omniverse-code/kit/exts/omni.volume/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. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.volume/config/extension.toml | [package]
version = "0.1.0"
title = "Volume"
category = "Internal"
[dependencies]
"omni.usd.libs" = {}
"omni.assets.plugins" = {}
"omni.kit.pip_archive" = {}
[[python.module]]
name = "omni.volume"
# numpy is used by tests
[python.pipapi]
requirements = ["numpy"]
[[native.plugin]]
path = "bin/deps/carb.volume.plugin"
| 322 | TOML | 15.149999 | 36 | 0.661491 |
omniverse-code/kit/exts/omni.volume/omni/volume/_volume.pyi | """pybind11 carb.volume bindings"""
from __future__ import annotations
import omni.volume._volume
import typing
import numpy
_Shape = typing.Tuple[int, ...]
__all__ = [
"GridData",
"IVolume",
"acquire_volume_interface"
]
class GridData():
pass
class IVolume():
def create_from_dense(self, arg0: float, arg1: buffer, arg2: float, arg3: buffer, arg4: str) -> GridData: ...
def create_from_file(self, arg0: str) -> GridData: ...
def get_grid_class(self, arg0: GridData, arg1: int) -> int: ...
def get_grid_data(self, arg0: GridData, arg1: int) -> typing.List[int]: ...
def get_grid_type(self, arg0: GridData, arg1: int) -> int: ...
def get_index_bounding_box(self, arg0: GridData, arg1: int) -> list: ...
def get_num_grids(self, arg0: GridData) -> int: ...
def get_short_grid_name(self, arg0: GridData, arg1: int) -> str: ...
def get_world_bounding_box(self, arg0: GridData, arg1: int) -> list: ...
def mesh_to_level_set(self, arg0: numpy.ndarray[numpy.float32], arg1: numpy.ndarray[numpy.int32], arg2: numpy.ndarray[numpy.int32], arg3: float, arg4: numpy.ndarray[numpy.int32]) -> GridData: ...
def save_volume(self, arg0: GridData, arg1: str) -> bool: ...
pass
def acquire_volume_interface(plugin_name: str = None, library_path: str = None) -> IVolume:
pass
| 1,327 | unknown | 40.499999 | 199 | 0.650339 |
omniverse-code/kit/exts/omni.volume/omni/volume/__init__.py | """This module contains bindings to C++ carb::volume::IVolume interface.
All the function are in omni.volume.IVolume class, to get it use get_editor_interface method, which caches
acquire interface call:
>>> import omni.volume
>>> e = omni.volume.get_volume_interface()
>>> print(f"Is UI hidden: {e.is_ui_hidden()}")
"""
from ._volume import *
from functools import lru_cache
@lru_cache()
def get_volume_interface() -> IVolume:
"""Returns cached :class:` omni.volume.IVolume` interface"""
return acquire_volume_interface()
| 547 | Python | 29.444443 | 106 | 0.702011 |
omniverse-code/kit/exts/omni.volume/omni/volume/tests/test_volume.py | import numpy
import omni.kit.test
import omni.volume
class CreateFromDenseTest(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
pass
# After running each test
async def tearDown(self):
pass
# Actual test, notice it is "async" function, so "await" can be used if needed
async def test_create_from_dense(self):
ivolume = omni.volume.get_volume_interface()
o = numpy.array([0, 0, 0]).astype(numpy.float64)
float_x = numpy.arange(30).reshape((5, 3, 2)).astype(numpy.float32)
float_volume = ivolume.create_from_dense(0, float_x, 1, o, "floatTest")
self.assertEqual(ivolume.get_num_grids(float_volume), 1)
self.assertEqual(ivolume.get_grid_class(float_volume, 0), 0)
self.assertEqual(ivolume.get_grid_type(float_volume, 0), 1)
self.assertEqual(ivolume.get_short_grid_name(float_volume, 0), "floatTest")
float_index_bounding_box = ivolume.get_index_bounding_box(float_volume, 0)
self.assertEqual(float_index_bounding_box, [(0, 0, 0), (1, 2, 4)])
float_world_bounding_box = ivolume.get_world_bounding_box(float_volume, 0)
self.assertEqual(float_world_bounding_box, [(0, 0, 0), (2, 3, 5)])
double_x = numpy.arange(30).reshape((5, 3, 2)).astype(numpy.float64)
double_volume = ivolume.create_from_dense(0, double_x, 1, o, "doubleTest")
self.assertEqual(ivolume.get_num_grids(double_volume), 1)
self.assertEqual(ivolume.get_grid_class(double_volume, 0), 0)
self.assertEqual(ivolume.get_grid_type(double_volume, 0), 2)
self.assertEqual(ivolume.get_short_grid_name(double_volume, 0), "doubleTest")
double_index_bounding_box = ivolume.get_index_bounding_box(double_volume, 0)
self.assertEqual(double_index_bounding_box, [(0, 0, 0), (1, 2, 4)])
double_world_bounding_box = ivolume.get_world_bounding_box(double_volume, 0)
self.assertEqual(double_world_bounding_box, [(0, 0, 0), (2, 3, 5)])
| 2,028 | Python | 47.309523 | 85 | 0.661736 |
omniverse-code/kit/exts/omni.volume/omni/volume/tests/__init__.py | from .test_volume import * | 26 | Python | 25.999974 | 26 | 0.769231 |
omniverse-code/kit/exts/omni.activity.ui/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. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.activity.ui/config/extension.toml | [package]
title = "omni.ui Window Activity"
description = "The full end to end activity of the window"
feature = true
version = "1.0.20"
category = "Activity"
authors = ["NVIDIA"]
repository = ""
keywords = ["activity", "window", "ui"]
changelog = "docs/CHANGELOG.md"
icon = "data/icon.png"
preview_image = "data/preview.png"
[dependencies]
"omni.activity.core" = {}
"omni.activity.pump" = {}
"omni.activity.usd_resolver" = {}
"omni.kit.menu.utils" = {optional=true}
"omni.ui" = {}
"omni.ui.scene" = {}
"omni.kit.window.file" = {}
[[native.library]]
path = "bin/${lib_prefix}omni.activity.ui.bar${lib_ext}"
[[python.module]]
name = "omni.activity.ui"
[settings]
exts."omni.activity.ui".auto_save_location = "${cache}/activities"
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.kit.renderer.capture",
]
[documentation]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
| 986 | TOML | 20 | 66 | 0.656187 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/open_file_addon.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
import asyncio
from .activity_progress_bar import ProgressBarWidget
class OpenFileAddon:
def __init__(self):
self._stop_event = asyncio.Event()
# The progress
with ui.Frame(height=355):
self.activity_widget = ProgressBarWidget()
def new(self, model):
self.activity_widget.new(model)
def __del__(self):
self.activity_widget.destroy()
self._stop_event.set()
def mouse_pressed(self, *args):
# Bind this class to the rectangle, so when Rectangle is deleted, the
# class is deleted as well
pass
def start_timer(self):
self.activity_widget.reset_timer()
def stop_timer(self):
self.activity_widget.stop_timer()
| 1,190 | Python | 29.538461 | 77 | 0.694118 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_tree_delegate.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ActivityTreeDelegate", "ActivityProgressTreeDelegate"]
from .activity_model import SECOND_MULTIPLIER, ActivityModelItem
import omni.kit.app
import omni.ui as ui
import pathlib
from urllib.parse import unquote
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
class ActivityTreeDelegate(ui.AbstractItemDelegate):
"""
The delegate for the bottom TreeView that displays details of the activity.
"""
def __init__(self, **kwargs):
super().__init__()
self._on_expand = kwargs.pop("on_expand", None)
self._initialize_expansion = kwargs.pop("initialize_expansion", None)
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
if column_id == 0:
with ui.HStack(width=20 * (level + 1), height=0):
ui.Spacer()
if model.can_item_have_children(item):
# Draw the +/- icon
image_name = "Minus" if expanded else "Plus"
ui.ImageWithProvider(
f"{EXTENSION_FOLDER_PATH}/data/{image_name}.svg",
width=10,
height=10,
style_type_name_override="TreeView.Label",
mouse_pressed_fn=lambda x, y, b, a: self._on_expand(item)
)
ui.Spacer(width=5)
def _build_header(self, column_id, headers, headers_tooltips):
alignment = ui.Alignment.LEFT_CENTER if column_id == 0 else ui.Alignment.RIGHT_CENTER
return ui.Label(
headers[column_id], height=22, alignment=alignment, style_type_name_override="TreeView.Label", tooltip=headers_tooltips[column_id])
def build_header(self, column_id: int):
headers = [" Name", "Dur", "Start", "End", "Size "]
headers_tooltips = ["Activity Name", "Duration (second)", "Start Time (second)", "End Time (second)", "Size (MB)"]
return self._build_header(column_id, headers, headers_tooltips)
def _build_name(self, text, item, model):
tooltip = f"{text}"
short_name = unquote(text.split("/")[-1])
children_size = len(model.get_item_children(item))
label_text = short_name if children_size == 0 else short_name + " (" + str(children_size) + ")"
with ui.HStack(spacing=5):
icon_name = item.icon_name
if icon_name != "undefined":
ui.ImageWithProvider(style_type_name_override="Icon", name=icon_name, width=16)
if icon_name != "material":
ui.ImageWithProvider(style_type_name_override="Icon", name="file", width=12)
label_style_name = icon_name if item.ended else "unfinished"
ui.Label(label_text, name=label_style_name, tooltip=tooltip)
# if text == "Materials" or text == "Textures":
# self._initialize_expansion(item, True)
def _build_duration(self, item):
duration = item.total_time / SECOND_MULTIPLIER
ui.Label(f"{duration:.2f}", style_type_name_override="TreeView.Label.Right", tooltip=str(duration) + " sec")
def _build_start_and_end(self, item, model, is_start):
time_ranges = item.time_range
if len(time_ranges) == 0:
return
time_begin = model.time_begin
begin = (time_ranges[0].begin - time_begin) / SECOND_MULTIPLIER
end = (time_ranges[-1].end - time_begin) / SECOND_MULTIPLIER
if is_start:
ui.Label(f"{begin:.2f}", style_type_name_override="TreeView.Label.Right", tooltip=str(begin) + " sec")
else:
ui.Label(f"{end:.2f}", style_type_name_override="TreeView.Label.Right", tooltip=str(end) + " sec")
def _build_size(self, text, item):
if text in ["Read", "Load", "Resolve"]:
size = item.children_size
else:
size = item.size
if size != 0:
size *= 0.000001
ui.Label(f"{size:.2f}", style_type_name_override="TreeView.Label.Right", tooltip=str(size) + " MB") # from byte to MB
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per item"""
if not hasattr(model, "time_begin") or not isinstance(item, ActivityModelItem):
return
text = model.get_item_value_model(item, column_id).get_value_as_string()
with ui.VStack(height=20):
if column_id == 0:
self._build_name(text, item, model)
elif column_id == 1:
self._build_duration(item)
elif column_id == 2 or column_id == 3:
self._build_start_and_end(item, model, column_id == 2)
elif column_id == 4:
self._build_size(text, item)
class ActivityProgressTreeDelegate(ActivityTreeDelegate):
def __init__(self, **kwargs):
super().__init__()
def build_header(self, column_id: int):
headers = [" Name", "Dur", "Size "]
headers_tooltips = ["Activity Name", "Duration (second)", "Size (MB)"]
return self._build_header(column_id, headers, headers_tooltips)
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per item"""
if not hasattr(model, "time_begin") or not isinstance(item, ActivityModelItem):
return
text = model.get_item_value_model(item, column_id).get_value_as_string()
with ui.VStack(height=20):
if column_id == 0:
self._build_name(text, item, model)
elif column_id == 1:
self._build_duration(item)
elif column_id == 2:
self._build_size(text, item)
| 6,242 | Python | 42.964788 | 143 | 0.598526 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_extension.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ActivityWindowExtension", "get_instance"]
from .activity_menu import ActivityMenuOptions
from .activity_model import ActivityModelDump, ActivityModelDumpForProgress, ActivityModelStageOpen, ActivityModelStageOpenForProgress
from .activity_progress_model import ActivityProgressModel
from .activity_progress_bar import ActivityProgressBarWindow, TIMELINE_WINDOW_NAME
from .activity_window import ActivityWindow
from .open_file_addon import OpenFileAddon
from .activity_actions import register_actions, deregister_actions
import asyncio
from functools import partial
import os
from pathlib import Path
from typing import Any
from typing import Dict
from typing import Optional
import weakref
import carb.profiler
import carb.settings
import carb.tokens
import omni.activity.core
import omni.activity.profiler
import omni.ext
import omni.kit.app
import omni.kit.ui
from omni.kit.window.file import register_open_stage_addon
from omni.kit.usd.layers import get_live_syncing
import omni.ui as ui
import omni.usd_resolver
import omni.kit.commands
AUTO_SAVE_LOCATION = "/exts/omni.activity.ui/auto_save_location"
STARTUP_ACTIVITY_FILENAME = "Startup"
g_singleton = None
def get_instance():
return g_singleton
class ActivityWindowExtension(omni.ext.IExt):
"""The entry point for Activity Window"""
PROGRESS_WINDOW_NAME = "Activity Progress"
PROGRESS_MENU_PATH = f"Window/Utilities/{PROGRESS_WINDOW_NAME}"
def on_startup(self, ext_id):
import omni.kit.app
# true when we record the activity
self.__activity_started = False
self._activity_profiler = omni.activity.profiler.get_activity_profiler()
self._activity_profiler_capture_mask_uid = 0
# make sure the old activity widget is disabled before loading the new one
ext_manager = omni.kit.app.get_app_interface().get_extension_manager()
old_activity_widget = "omni.kit.activity.widget.monitor"
if ext_manager.is_extension_enabled(old_activity_widget):
ext_manager.set_extension_enabled_immediate(old_activity_widget, False)
self._timeline_window = None
self._progress_bar = None
self._addon = None
self._current_path = None
self._data = None
self.__model = None
self.__progress_model= None
self.__flatten_model = None
self._menu_entry = None
self._activity_menu_option = ActivityMenuOptions(load_data=self.load_data, get_save_data=self.get_save_data)
# The ability to show up the window if the system requires it. We use it
# in QuickLayout.
ui.Workspace.set_show_window_fn(TIMELINE_WINDOW_NAME, partial(self.show_window, None))
ui.Workspace.set_show_window_fn(
ActivityWindowExtension.PROGRESS_WINDOW_NAME, partial(self.show_progress_bar, None)
)
# add actions
self._ext_name = omni.ext.get_extension_name(ext_id)
register_actions(self._ext_name, self)
# add new menu
try:
import omni.kit.menu.utils
from omni.kit.menu.utils import MenuItemDescription
self._menu_entry = [
MenuItemDescription(name="Utilities", sub_menu=
[MenuItemDescription(
name=ActivityWindowExtension.PROGRESS_WINDOW_NAME,
ticked=True,
ticked_fn=self._is_progress_visible,
onclick_action=("omni.activity.ui", "show_activity_window"),
)]
)
]
omni.kit.menu.utils.add_menu_items(self._menu_entry, name="Window")
except (ModuleNotFoundError, AttributeError): # pragma: no cover
pass
# Listen for the app ready event
startup_event_stream = omni.kit.app.get_app().get_startup_event_stream()
self._app_ready_sub = startup_event_stream.create_subscription_to_pop_by_type(
omni.kit.app.EVENT_APP_READY, self._on_app_ready, name="Omni Activity"
)
# Listen to USD stage activity
stage_event_stream = omni.usd.get_context().get_stage_event_stream()
self._stage_event_sub = stage_event_stream.create_subscription_to_pop(
self._on_stage_event, name="Omni Activity"
)
self._activity_widget_subscription = register_open_stage_addon(self._open_file_addon)
self._activity_widget_live_subscription = get_live_syncing().register_open_stage_addon(self._open_file_addon)
# subscribe the callback to show the progress window when the prompt window disappears
# self._show_window_subscription = register_open_stage_complete(self._show_progress_window)
# message bus to update the status bar
self.__subscription = None
self.name_progress = carb.events.type_from_string("omni.kit.window.status_bar@progress")
self.name_activity = carb.events.type_from_string("omni.kit.window.status_bar@activity")
self.name_clicked = carb.events.type_from_string("omni.kit.window.status_bar@clicked")
self.message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
# subscribe the callback to show the progress window when user clicks the status bar's progress area
self.__statusbar_click_subscription = self.message_bus.create_subscription_to_pop_by_type(
self.name_clicked, lambda e: self._show_progress_window())
# watch the commands
commands = ["AddReference", "CreatePayload", "CreateSublayer", "ReplacePayload", "ReplaceReference"]
self.__command_callback_ids = [
omni.kit.commands.register_callback(
cb,
omni.kit.commands.PRE_DO_CALLBACK,
partial(ActivityWindowExtension._on_command, weakref.proxy(self), cb),
)
for cb in commands
]
# Set up singleton instance
global g_singleton
g_singleton = self
def _show_progress_window(self):
ui.Workspace.show_window(ActivityWindowExtension.PROGRESS_WINDOW_NAME)
self._progress_bar.focus()
def _on_app_ready(self, event):
if not self.__activity_started:
# Start an activity trace to measure the time between app ready and the first frame.
# This may have already happened in _on_stage_event if an empty stage was opened at startup.
self._start_activity(STARTUP_ACTIVITY_FILENAME, profiler_mask=omni.activity.profiler.CAPTURE_MASK_STARTUP)
self._app_ready_sub = None
rendering_event_stream = omni.usd.get_context().get_rendering_event_stream()
self._new_frame_sub = rendering_event_stream.create_subscription_to_push_by_type(
omni.usd.StageRenderingEventType.NEW_FRAME, self._on_new_frame, name="Omni Activity"
)
def _on_new_frame(self, event):
# Stop the activity trace measuring the time between app ready and the first frame.
self._stop_activity(completed=True, filename=STARTUP_ACTIVITY_FILENAME)
self._new_frame_sub = None
def _on_stage_event(self, event):
OPENING = int(omni.usd.StageEventType.OPENING)
OPEN_FAILED = int(omni.usd.StageEventType.OPEN_FAILED)
ASSETS_LOADED = int(omni.usd.StageEventType.ASSETS_LOADED)
if event.type is OPENING:
path = event.payload.get("val", None)
capture_mask = omni.activity.profiler.CAPTURE_MASK_SCENE_LOADING
if self._app_ready_sub != None:
capture_mask |= omni.activity.profiler.CAPTURE_MASK_STARTUP
path = STARTUP_ACTIVITY_FILENAME
self._start_activity(path, profiler_mask=capture_mask)
elif event.type is OPEN_FAILED:
self._stop_activity(completed=False)
elif event.type is ASSETS_LOADED:
self._stop_activity(completed=True)
def _model_changed(self, model, item):
self.message_bus.push(self.name_activity, payload={"text": f"{model.latest_item}"})
self.message_bus.push(self.name_progress, payload={"progress": f"{model.total_progress}"})
def on_shutdown(self):
global g_singleton
g_singleton = None
import omni.kit.commands
self._app_ready_sub = None
self._new_frame_sub = None
self._stage_event_sub = None
self._progress_menu = None
self._current_path = None
self.__model = None
self.__progress_model= None
self.__flatten_model = None
# remove actions
deregister_actions(self._ext_name)
# remove menu
try:
import omni.kit.menu.utils
omni.kit.menu.utils.remove_menu_items(self._menu_entry, name="Window")
except (ModuleNotFoundError, AttributeError): # pragma: no cover
pass
self._menu_entry = None
if self._timeline_window:
self._timeline_window.destroy()
self._timeline_window = None
if self._progress_bar:
self._progress_bar.destroy()
self._progress_bar = None
self._addon = None
if self._activity_menu_option:
self._activity_menu_option.destroy()
# Deregister the function that shows the window from omni.ui
ui.Workspace.set_show_window_fn(TIMELINE_WINDOW_NAME, None)
ui.Workspace.set_show_window_fn(ActivityWindowExtension.PROGRESS_WINDOW_NAME, None)
self._activity_widget_subscription = None
self._activity_widget_live_subscription = None
self._show_window_subscription = None
for callback_id in self.__command_callback_ids:
omni.kit.commands.unregister_callback(callback_id)
async def _destroy_window_async(self):
# wait one frame, this is due to the one frame defer
# in Window::_moveToMainOSWindow()
await omni.kit.app.get_app().next_update_async()
if hasattr(self, '_timeline_window') and self._timeline_window:
self._timeline_window.destroy()
self._timeline_window = None
async def _destroy_progress_window_async(self):
# wait one frame, this is due to the one frame defer
# in Window::_moveToMainOSWindow()
await omni.kit.app.get_app().next_update_async()
if self._progress_bar:
self._progress_bar.destroy()
self._progress_bar = None
def _visiblity_changed_fn(self, visible):
# Called when the user pressed "X"
if not visible:
# Destroy the window, since we are creating new window
# in show_window
asyncio.ensure_future(self._destroy_window_async())
def _progress_visiblity_changed_fn(self, visible):
try:
import omni.kit.menu.utils
omni.kit.menu.utils.refresh_menu_items("Window")
except (ModuleNotFoundError, AttributeError): # pragma: no cover
pass
if not visible:
# Destroy the window, since we are creating new window in show_progress_bar
asyncio.ensure_future(self._destroy_progress_window_async())
def _is_progress_visible(self) -> bool:
return False if self._progress_bar is None else self._progress_bar.visible
def show_window(self, menu, value):
if value:
self._timeline_window = ActivityWindow(
TIMELINE_WINDOW_NAME,
weakref.proxy(self.__model) if self.__model else None,
activity_menu=self._activity_menu_option,
)
self._timeline_window.set_visibility_changed_fn(self._visiblity_changed_fn)
elif self._timeline_window:
self._timeline_window.visible = False
def show_progress_bar(self, menu, value):
if value:
self._progress_bar = ActivityProgressBarWindow(
ActivityWindowExtension.PROGRESS_WINDOW_NAME,
self.__flatten_model,
activity_menu=self._activity_menu_option,
width=415,
height=355,
)
self._progress_bar.set_visibility_changed_fn(self._progress_visiblity_changed_fn)
elif self._progress_bar:
self._progress_bar.visible = False
def _open_file_addon(self):
self._addon = OpenFileAddon()
def get_save_data(self):
"""Save the current model to external file"""
if not self.__model:
return None
return self.__model.get_data()
def _save_current_activity(self, fullpath: Optional[str] = None, filename: Optional[str] = None):
"""
Saves current activity.
If the full path is not given it takes the stage name and saves it to the
auto save location from settings. It can be URL or contain tokens.
"""
if fullpath is None:
settings = carb.settings.get_settings()
auto_save_location = settings.get(AUTO_SAVE_LOCATION)
if not auto_save_location:
# No auto save location - nothing to do
return
# Resolve auto save location
token = carb.tokens.get_tokens_interface()
auto_save_location = token.resolve(auto_save_location)
def remove_files():
# only keep the latest 20 activity files, remove the old ones if necessary
file_stays = 20
sorted_files = [item for item in Path(auto_save_location).glob("*.activity")]
if len(sorted_files) < file_stays:
return
sorted_files.sort(key=lambda item: item.stat().st_mtime)
for item in sorted_files[:-file_stays]:
os.remove(item)
remove_files()
if filename is None:
# Extract filename
# Current URL
current_stage_url = omni.usd.get_context().get_stage_url()
# Using clientlib to parse it
current_stage_path = Path(omni.client.break_url(current_stage_url).path)
# Some usd layers have ":" in name
filename = current_stage_path.stem.split(":")[-1]
# Construct the full path
fullpath = omni.client.combine_urls(auto_save_location + "/", filename + ".activity")
if not fullpath:
return
self._activity_menu_option.save(fullpath)
carb.log_info(f"The activity log has been written to ${fullpath}.")
def load_data(self, data):
"""Load the model from the data"""
if self.__model:
self.__flatten_model.destroy()
self.__progress_model.destroy()
self.__model.destroy()
# Use separate models for Timeline and ProgressBar to mimic realtime model lifecycle. See _start_activity()
self.__model = ActivityModelDump(data=data)
self.__progress_model = ActivityModelDumpForProgress(data=data)
self.__flatten_model = ActivityProgressModel(weakref.proxy(self.__progress_model))
self.__flatten_model.finished_loading()
if self._timeline_window:
self._timeline_window._menu_new(weakref.proxy(self.__model))
if self._progress_bar:
self._progress_bar.new(self.__flatten_model)
def _start_activity(self, path: Optional[str] = None, profiler_mask = 0):
self.__activity_started = True
self._activity_profiler_capture_mask_uid = self._activity_profiler.enable_capture_mask(profiler_mask)
# reset all the windows
if self.__model:
self.__flatten_model.destroy()
self.__progress_model.destroy()
self.__model.destroy()
self._current_path = None
self.__model = ActivityModelStageOpen()
self.__progress_model = ActivityModelStageOpenForProgress()
self.__flatten_model = ActivityProgressModel(weakref.proxy(self.__progress_model))
self.__subscription = None
self.clear_status_bar()
if self._timeline_window:
self._timeline_window._menu_new(weakref.proxy(self.__model))
if self._progress_bar:
self._progress_bar.new(self.__flatten_model)
if self._addon:
self._addon.new(self.__flatten_model)
if path:
self.__subscription = self.__flatten_model.subscribe_item_changed_fn(self._model_changed)
# only when we have a path, we start to record the activity
self.__flatten_model.start_loading = True
if self._progress_bar:
self._progress_bar.start_timer()
if self._addon:
self._addon.start_timer()
self.__model.set_path(path)
self.__progress_model.set_path(path)
self._current_path = path
def _stop_activity(self, completed=True, filename: Optional[str] = None):
# ASSETS_LOADED could be triggered by many things e.g. selection change
# make sure we only enter this function once when the activity stops
if not self.__activity_started:
return
self.__activity_started = False
if self._activity_profiler_capture_mask_uid != 0:
self._activity_profiler.disable_capture_mask(self._activity_profiler_capture_mask_uid)
self._activity_profiler_capture_mask_uid = 0
if self.__model:
self.__model.end()
if self.__progress_model:
self.__progress_model.end()
if self._current_path:
if self._progress_bar:
self._progress_bar.stop_timer()
if self._addon:
self._addon.stop_timer()
if completed:
# make sure the progress is 1 when assets loaded
if self.__flatten_model:
self.__flatten_model.finished_loading()
self.message_bus.push(self.name_progress, payload={"progress": "1.0"})
self._save_current_activity(filename = filename)
self.clear_status_bar()
def clear_status_bar(self):
# send an empty message to status bar
self.message_bus.push(self.name_activity, payload={"text": ""})
# clear the progress bar widget
self.message_bus.push(self.name_progress, payload={"progress": "-1"})
def _on_command(self, command: str, kwargs: Dict[str, Any]):
if command == "AddReference":
path = kwargs.get("reference", None)
if path:
path = path.assetPath
self._start_activity(path)
elif command == "CreatePayload":
path = kwargs.get("asset_path", None)
self._start_activity(path)
elif command == "CreateSublayer":
path = kwargs.get("new_layer_path", None)
self._start_activity(path)
elif command == "ReplacePayload":
path = kwargs.get("new_payload", None)
if path:
path = path.assetPath
self._start_activity(path)
elif command == "ReplaceReference":
path = kwargs.get("new_reference", None)
if path:
path = path.assetPath
self._start_activity(path)
| 19,658 | Python | 39.367556 | 134 | 0.626717 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_progress_model.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ActivityProgressModel"]
import weakref
from dataclasses import dataclass
from typing import Dict, List, Set
from functools import partial
import omni.ui as ui
import omni.activity.core
import time
from urllib.parse import unquote
from .activity_model import ActivityModel, SECOND_MULTIPLIER
moving_window = 20
class ActivityProgressModel(ui.AbstractItemModel):
"""
The model that takes the source model and filters out the items that are
outside of the given time range.
"""
def __init__(self, source: ActivityModel, **kwargs):
super().__init__()
self._flattened_children = []
self._latest_item = None
self.usd_loaded_sum = 0
self.usd_sum = 0
self.usd_progress = 0
self.usd_size = 0
self.usd_speed = 0
self.texture_loaded_sum = 0
self.texture_sum = 0
self.texture_progress = 0
self.texture_size = 0
self.texture_speed = 0
self.material_loaded_sum = 0
self.material_sum = 0
self.material_progress = 0
self.total_loaded_sum = 0
self.total_sum = 0
self.total_progress = 0
self.start_loading = False
self.finish_loading = False
self.total_duration = 0
current_time = time.time()
self.prev_usd_update_time = current_time
self.prev_texture_update_time = current_time
self.texture_data = [(0, current_time)]
self.usd_data = [(0, current_time)]
self.__source: ActivityModel = source
self.__subscription = self.__source.subscribe_item_changed_fn(
partial(ActivityProgressModel._source_changed, weakref.proxy(self))
)
self.activity = omni.activity.core.get_instance()
self._load_data_from_source(self.__source)
def update_USD(self, item):
self.usd_loaded_sum = item.loaded_children_num
self.usd_sum = len(item.children)
self.usd_progress = 0 if self.usd_sum == 0 else self.usd_loaded_sum / float(self.usd_sum)
loaded_size = item.children_size * 0.000001
if loaded_size != self.usd_size:
current_time = time.time()
self.usd_data.append((loaded_size, current_time))
if len(self.usd_data) > moving_window:
self.usd_data.pop(0)
prev_size, prev_time = self.usd_data[0]
self.usd_speed = (loaded_size - prev_size) / (current_time - prev_time)
self.prev_usd_update_time = current_time
self.usd_size = loaded_size
def update_textures(self, item):
self.texture_loaded_sum = item.loaded_children_num
self.texture_sum = len(item.children)
self.texture_progress = 0 if self.texture_sum == 0 else self.texture_loaded_sum / float(self.texture_sum)
loaded_size = item.children_size * 0.000001
if loaded_size != self.texture_size:
current_time = time.time()
self.texture_data.append((loaded_size, current_time))
if len(self.texture_data) > moving_window:
self.texture_data.pop(0)
prev_size, prev_time = self.texture_data[0]
if current_time == prev_time:
return
self.texture_speed = (loaded_size - prev_size) / (current_time - prev_time)
self.prev_texture_update_time = current_time
self.texture_size = loaded_size
def update_materials(self, item):
self.material_loaded_sum = item.loaded_children_num
self.material_sum = len(item.children)
self.material_progress = 0 if self.material_sum == 0 else self.material_loaded_sum / float(self.material_sum)
def update_total(self):
self.total_sum = self.usd_sum + self.texture_sum + self.material_sum
self.total_loaded_sum = self.usd_loaded_sum + self.texture_loaded_sum + self.material_loaded_sum
self.total_progress = 0 if self.total_sum == 0 else self.total_loaded_sum / float(self.total_sum)
def _load_data_from_source(self, model):
if not model or not model.get_item_children(None):
return
for child in model.get_item_children(None):
name = child.name_model.as_string
if name == "Materials":
self.update_materials(child)
elif name in ["USD", "Textures"]:
items = model.get_item_children(child)
for item in items:
item_name = item.name_model.as_string
if item_name == "Read":
self.update_USD(item)
elif item_name == "Load":
self.update_textures(item)
self.update_total()
if model._time_begin and model._time_end:
self.total_duration = int((model._time_end - model._time_begin) / float(SECOND_MULTIPLIER))
def _source_changed(self, model, item):
name = item.name_model.as_string
if name in ["Read", "Load", "Materials"]:
if name == "Read":
self.update_USD(item)
elif name == "Load":
self.update_textures(item)
elif name == "Materials":
self.update_materials(item)
self.update_total()
# telling the tree root that the list is changing
self._item_changed(None)
def finished_loading(self):
if self.__source._time_begin and self.__source._time_end:
self.total_duration = int((self.__source._time_end - self.__source._time_begin) / float(SECOND_MULTIPLIER))
else:
self.total_duration = self.duration
self.finish_loading = True
# sometimes ASSETS_LOADED isn't called when stage is completely finished loading,
# so we force progress to be 1 when we decided that it's finished loading.
self.usd_loaded_sum = self.usd_sum
self.usd_progress = 1
self.texture_loaded_sum = self.texture_sum
self.texture_progress = 1
self.material_loaded_sum = self.material_sum
self.material_progress = 1
self.total_loaded_sum = self.total_sum
self.total_progress = 1
self._item_changed(None)
@property
def time_begin(self):
return self.__source._time_begin
@property
def duration(self):
if not self.start_loading and not self.finish_loading:
return 0
elif self.finish_loading:
return self.total_duration
elif self.start_loading and not self.finish_loading:
current_timestamp = self.activity.current_timestamp
duration = (current_timestamp - self.time_begin) / float(SECOND_MULTIPLIER)
return int(duration)
@property
def latest_item(self):
if self.finish_loading:
return None
if hasattr(self.__source, "_flattened_children") and self.__source._flattened_children:
item = self.__source._flattened_children[0]
name = item.name_model.as_string
short_name = unquote(name.split("/")[-1])
return short_name
else:
return ""
def get_data(self):
return self.__source.get_data()
def destroy(self):
self.__source = None
self.__subscription = None
self.texture_data = []
self.usd_data = []
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is None and hasattr(self.__source, "_flattened_children"):
return self.__source._flattened_children
return []
def get_item_value_model_count(self, item):
"""The number of columns"""
return self.__source.get_item_value_model_count(item)
def get_item_value_model(self, item, column_id):
"""
Return value model.
"""
return self.__source.get_item_value_model(item, column_id)
| 8,354 | Python | 36.977273 | 119 | 0.609887 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/style.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["activity_window_style"]
from omni.ui import color as cl
from omni.ui import constant as fl
from omni.ui import url
import omni.kit.app
import omni.ui as ui
import pathlib
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
# Pre-defined constants. It's possible to change them runtime.
cl.activity_window_attribute_bg = cl("#1f2124")
cl.activity_window_attribute_fg = cl("#0f1115")
cl.activity_window_hovered = cl("#FFFFFF")
cl.activity_text = cl("#9e9e9e")
cl.activity_green = cl("#4FA062")
cl.activity_usd_blue = cl("#2091D0")
cl.activity_progress_blue = cl("#4F7DA0")
cl.activity_purple = cl("#8A6592")
fl.activity_window_attr_hspacing = 10
fl.activity_window_attr_spacing = 1
fl.activity_window_group_spacing = 2
# The main style dict
activity_window_style = {
"Label::attribute_name": {
"alignment": ui.Alignment.RIGHT_CENTER,
"margin_height": fl.activity_window_attr_spacing,
"margin_width": fl.activity_window_attr_hspacing,
},
"Label::attribute_name:hovered": {"color": cl.activity_window_hovered},
"Label::collapsable_name": {"alignment": ui.Alignment.LEFT_CENTER},
"Label::time": {"font_size": 12, "color": cl.activity_text, "alignment": ui.Alignment.LEFT_CENTER},
"Label::selection_time": {"font_size": 12, "color": cl("#34C7FF")},
"Line::timeline": {"color": cl(0.22)},
"Rectangle::selected_area": {"background_color": cl(1.0, 1.0, 1.0, 0.1)},
"Slider::attribute_int:hovered": {"color": cl.activity_window_hovered},
"Slider": {
"background_color": cl.activity_window_attribute_bg,
"draw_mode": ui.SliderDrawMode.HANDLE,
},
"Slider::attribute_float": {
"draw_mode": ui.SliderDrawMode.FILLED,
"secondary_color": cl.activity_window_attribute_fg,
},
"Slider::attribute_float:hovered": {"color": cl.activity_window_hovered},
"Slider::attribute_vector:hovered": {"color": cl.activity_window_hovered},
"Slider::attribute_color:hovered": {"color": cl.activity_window_hovered},
"CollapsableFrame::group": {"margin_height": fl.activity_window_group_spacing},
"Button::options": {"background_color": 0x0, "margin": 0},
"Button.Image::options": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/options.svg", "color": cl.activity_text},
"RadioButton": {"background_color": cl.transparent},
"RadioButton.Label": {"font_size": 14, "color": cl("#A1A1A1")},
"RadioButton.Label:checked": {"font_size": 14, "color": cl("#34C7FF")},
"RadioButton:checked": {"background_color": cl.transparent},
"RadioButton:hovered": {"background_color": cl.transparent},
"RadioButton:pressed": {"background_color": cl.transparent},
"Rectangle::separator": {"background_color": cl("#707070"), "border_radius": 1.5},
"TreeView.Label": {"color": cl.activity_text},
"TreeView.Label.Right": {"color": cl.activity_text, "alignment": ui.Alignment.RIGHT_CENTER},
"Rectangle::spacer": {"background_color": cl("#1F2123")},
"ScrollingFrame": {"background_color": cl("#1F2123")},
"Label::USD": {"color": cl.activity_usd_blue},
"Label::progress": {"color": cl.activity_progress_blue},
"Label::material": {"color": cl.activity_purple},
"Label::undefined": {"color": cl.activity_text},
"Label::unfinished": {"color": cl.lightsalmon},
"Icon::USD": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/USD.svg"},
"Icon::progress": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/progress.svg", "color": cl.activity_progress_blue},
"Icon::material": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/Material.png"},
"Icon::texture": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/Texture.svg"},
"Icon::file": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/file.svg"},
}
progress_window_style = {
"RadioButton": {"background_color": cl.transparent},
"RadioButton.Label": {"font_size": 14, "color": cl("#A1A1A1")},
"RadioButton.Label:checked": {"font_size": 14, "color": cl("#34C7FF")},
"RadioButton:checked": {"background_color": cl.transparent},
"RadioButton:hovered": {"background_color": cl.transparent},
"RadioButton:pressed": {"background_color": cl.transparent},
"Rectangle::separator": {"background_color": cl("#707070"), "border_radius": 1.5},
"ProgressBar::texture": {"border_radius": 0, "color": cl.activity_green, "background_color": cl("#606060")},
"ProgressBar::USD": {"border_radius": 0, "color": cl.activity_usd_blue, "background_color": cl("#606060")},
"ProgressBar::material": {"border_radius": 0, "color": cl.activity_purple, "background_color": cl("#606060")},
"ProgressBar::progress": {"border_radius": 0, "color": cl.activity_progress_blue, "background_color": cl("#606060"), "secondary_color": cl.transparent},
"Button::options": {"background_color": 0x0, "margin": 0},
"Button.Image::options": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/options.svg", "color": cl.activity_text},
"TreeView.Label": {"color": cl.activity_text},
"TreeView.Label.Right": {"color": cl.activity_text, "alignment": ui.Alignment.RIGHT_CENTER},
"Label::USD": {"color": cl.activity_usd_blue},
"Label::progress": {"color": cl.activity_progress_blue},
"Label::material": {"color": cl.activity_purple},
"Label::undefined": {"color": cl.activity_text},
"Label::unfinished": {"color": cl.lightsalmon},
"ScrollingFrame": {"background_color": cl("#1F2123")},
"Icon::USD": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/USD.svg"},
"Icon::progress": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/progress.svg", "color": cl.activity_progress_blue},
"Icon::material": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/Material.png"},
"Icon::texture": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/Texture.svg"},
"Icon::file": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/file.svg"},
"Tree.Branch::Minus": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/Minus.svg", "color": cl("#707070")},
"Tree.Branch::Plus": {"image_url": f"{EXTENSION_FOLDER_PATH}/data/Plus.svg", "color": cl("#707070")},
}
def get_shade_from_name(name: str):
#---------------------------------------
if name == "USD":
return cl("#2091D0")
elif name == "Read":
return cl("#1A75A8")
elif name == "Resolve":
return cl("#16648F")
elif name.endswith((".usd", ".usda", ".usdc", ".usdz")):
return cl("#13567B")
#---------------------------------------
elif name == "Stage":
return cl("#d43838")
elif name.startswith("Opening"):
return cl("#A12A2A")
#---------------------------------------
elif name == "Render Thread":
return cl("#d98927")
elif name == "Execute":
return cl("#A2661E")
elif name == "Post Sync":
return cl("#626262")
#----------------------------------------
elif name == "Textures":
return cl("#4FA062")
elif name == "Load":
return cl("#3C784A")
elif name == "Queue":
return cl("#31633D")
elif name.endswith(".hdr"):
return cl("#34A24E")
elif name.endswith(".png"):
return cl("#2E9146")
elif name.endswith(".jpg") or name.endswith(".JPG"):
return cl("#2B8741")
elif name.endswith(".ovtex"):
return cl("#287F3D")
elif name.endswith(".dds"):
return cl("#257639")
elif name.endswith(".exr"):
return cl("#236E35")
elif name.endswith(".wav"):
return cl("#216631")
elif name.endswith(".tga"):
return cl("#1F5F2D")
#---------------------------------------------
elif name == "Materials":
return cl("#8A6592")
elif name.endswith(".mdl"):
return cl("#76567D")
elif "instance)" in name:
return cl("#694D6F")
elif name == "Compile":
return cl("#5D4462")
elif name == "Create Shader Variations":
return cl("#533D58")
elif name == "Load Textures":
return cl("#4A374F")
#---------------------------------------------
elif name == "Meshes":
return cl("#626262")
#---------------------------------------------
elif name == "Ray Tracing Pipeline":
return cl("#8B8000")
else:
return cl("#555555")
| 8,708 | Python | 43.661538 | 156 | 0.615641 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_filter_model.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ActivityFilterModel"]
import weakref
from dataclasses import dataclass
from typing import Dict, List, Set
from functools import partial
import omni.ui as ui
from .activity_model import ActivityModel
class ActivityFilterModel(ui.AbstractItemModel):
"""
The model that takes the source model and filters out the items that are
outside of the given time range.
"""
def __init__(self, source: ActivityModel, **kwargs):
super().__init__()
self.__source: ActivityModel = source
self.__subscription = self.__source.subscribe_item_changed_fn(
partial(ActivityFilterModel._source_changed, weakref.proxy(self))
)
self.__timerange_begin = None
self.__timerange_end = None
def _source_changed(self, model, item):
self._item_changed(item)
@property
def time_begin(self):
return self.__source._time_begin
@property
def timerange_begin(self):
return self.__timerange_begin
@timerange_begin.setter
def timerange_begin(self, value):
if self.__timerange_begin != value:
self.__timerange_begin = value
self._item_changed(None)
@property
def timerange_end(self):
return self.__timerange_end
@timerange_end.setter
def timerange_end(self, value):
if self.__timerange_end != value:
self.__timerange_end = value
self._item_changed(None)
def destroy(self):
self.__source = None
self.__subscription = None
self.__timerange_begin = None
self.__timerange_end = None
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if self.__source is None:
return []
children = self.__source.get_item_children(item)
if self.__timerange_begin is None or self.__timerange_end is None:
return children
result = []
for child in children:
for range in child.time_range:
if max(self.__timerange_begin, range.begin) <= min(self.__timerange_end, range.end):
result.append(child)
break
return result
def get_item_value_model_count(self, item):
"""The number of columns"""
return self.__source.get_item_value_model_count(item)
def get_item_value_model(self, item, column_id):
"""
Return value model.
"""
return self.__source.get_item_value_model(item, column_id)
| 2,975 | Python | 29.680412 | 100 | 0.636303 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_delegate.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ActivityDelegate"]
from ..bar._bar import AbstractActivityBarDelegate
from ..bar._bar import ActivityBar
from .activity_model import SECOND_MULTIPLIER
from .activity_pack_model import ActivityPackModelItem
from .activity_model import TimeRange
from functools import partial
from omni.ui import color as cl
from typing import List
import omni.ui as ui
import weakref
import carb
class ActivityBarDelegate(AbstractActivityBarDelegate):
def __init__(self, ranges: List[TimeRange], hide_label: bool = False):
super().__init__()
self._hide_label = hide_label
self._ranges = ranges
def get_label(self, index):
if self._hide_label:
# Can't return None because it's derived from C++
return ""
else:
# use short name
item = self._ranges[index].item
name = item.name_model.as_string
short_name = name.split("/")[-1]
# the number of children
children_num = len(item.children)
label_text = short_name if children_num == 0 else short_name + " (" + str(children_num) + ")"
return label_text
def get_tooltip_text(self, index):
time_range = self._ranges[index]
elapsed = time_range.end - time_range.begin
item = time_range.item
name = item.name_model.as_string
tooltip_name = time_range.metadata.get("name", None) or name
if name in ["Read", "Load", "Resolve"]:
# the size of children
size = item.children_size * 0.000001
else:
size = time_range.item.size * 0.000001
return f"{tooltip_name}\n{elapsed / SECOND_MULTIPLIER:.2f}s\n{size:.2f} MB"
class ActivityDelegate(ui.AbstractItemDelegate):
"""
The delegate for the TreeView for the activity chart. Instead of text, it
shows the activity on the timeline.
"""
def __init__(self, **kwargs):
super().__init__()
# Called to collapse/expand
self._on_expand = kwargs.pop("on_expand", None)
# Map between the range and range delegate
self._activity_bar_map = {}
self._activity_bar = None
def destroy(self):
self._activity_bar_map = {}
self._activity_bar = None
def build_branch(self, model, item, column_id, level, expanded): # pragma: no cover
"""Create a branch widget that opens or closes subtree"""
pass
def __on_double_clicked(self, weak_item, weak_range_item, x, y, button, modifier):
if button != 0:
return
if not self._on_expand:
return
item = weak_item()
if not item:
return
range_item = weak_range_item()
if not range_item:
return
# shift + double click will expand all
recursive = True if modifier & carb.input.KEYBOARD_MODIFIER_FLAG_SHIFT else False
self._on_expand(item, range_item, recursive)
def __on_selection(self, time_range, model, item_id):
if item_id is None:
return
item = time_range[item_id].item
if not item:
return
model.selection = item
def select_range(self, item, model):
model.selection = item
if item in self._activity_bar_map:
(_activity_bar, i) = self._activity_bar_map[item]
_activity_bar.selection = i
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per item"""
if not isinstance(item, ActivityPackModelItem):
return
if column_id != 0:
return
time_range = item.time_range
if time_range:
first_range = time_range[0]
first_item = first_range.item
with ui.VStack():
if level == 1:
ui.Spacer(height=2)
_activity_bar = ActivityBar(
time_limit=(model._time_begin, model._time_end),
time_ranges=[(t.begin, t.end) for t in time_range],
colors=[t.metadata["color"] for t in time_range],
delegate=ActivityBarDelegate(time_range),
height=25,
mouse_double_clicked_fn=partial(
ActivityDelegate.__on_double_clicked,
weakref.proxy(self),
weakref.ref(item),
weakref.ref(first_item),
),
selection_changed_fn=partial(ActivityDelegate.__on_selection, weakref.proxy(self), time_range, model),
)
for i, t in enumerate(time_range):
self._activity_bar_map[t.item] = (_activity_bar, i)
| 5,190 | Python | 33.838926 | 122 | 0.587861 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_actions.py | import omni.kit.actions.core
def register_actions(extension_id, cls):
action_registry = omni.kit.actions.core.get_action_registry()
actions_tag = "Activity Actions"
action_registry.register_action(
extension_id,
"show_activity_window",
lambda: cls.show_progress_bar(None, not cls._is_progress_visible()),
display_name="Activity show/hide window",
description="Activity show/hide window",
tag=actions_tag,
)
def deregister_actions(extension_id):
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.deregister_all_actions_for_extension(extension_id)
| 651 | Python | 30.047618 | 76 | 0.697389 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_pack_model.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ActivityPackModel"]
from time import time
from .activity_model import ActivityModel
from .activity_model import ActivityModelItem
from .activity_model import TimeRange
from collections import defaultdict
from functools import partial
from typing import List, Dict, Optional
import omni.ui as ui
import weakref
class ActivityPackModelItem(ui.AbstractItem):
def __init__(self, parent: "ActivityPackModelItem", parent_model: "ActivityPackModel", packed=True):
super().__init__()
self._is_packed = packed
self._time_ranges: List[TimeRange] = []
self._children: List[ActivityPackModelItem] = []
self._parent: ActivityPackModelItem = parent
self._parent_model: ActivityPackModel = parent_model
self._children_dirty = True
# Time range when the item is active
self._timerange_dirty = True
self.__total_time: int = 0
self.name_model = ui.SimpleStringModel("Empty")
def destroy(self):
for child in self._children:
child.destroy()
self._time_ranges = []
self._children = []
self._parent = None
self._parent_model = None
def extend_with_range(self, time_range: TimeRange):
if not self._add_range(time_range):
return False
self._children_dirty = True
return True
def dirty(self):
self._children_dirty = True
self._timerange_dirty = True
def get_children(self) -> List["ActivityPackModelItem"]:
self._update_children()
return self._children
@property
def time_range(self) -> List[TimeRange]:
self._update_timerange()
return self._time_ranges
@property
def total_time(self):
"""Return the time ranges when the item was active"""
if not self._timerange_dirty:
# Recache
_ = self.time_range
return self.__total_time
def _add_range(self, time_range: TimeRange):
"""
Try to fit the given range to the current item. Return true if it's
inserted.
"""
if not self._time_ranges:
self._time_ranges.append(time_range)
return True
# Check if it fits after the last
last = self._time_ranges[-1]
if last.end <= time_range.begin:
self._time_ranges.append(time_range)
return True
# Check if it fits before the first
first = self._time_ranges[0]
if time_range.end <= first.begin:
# prepend
self._time_ranges.insert(0, time_range)
return True
ranges_count = len(self._time_ranges)
if ranges_count <= 1:
# Checked all the combinations
return False
def _binary_search(array, time_range):
left = 0
right = len(array) - 1
while left <= right:
middle = left + (right - left) // 2
if array[middle].end < time_range.begin:
left = middle + 1
elif array[middle].end > time_range.begin:
right = middle - 1
else:
return middle
return left - 1
i = _binary_search(self._time_ranges, time_range) + 1
if i > 0 and i < ranges_count:
if time_range.end <= self._time_ranges[i].begin:
# Insert after i-1 or before i
self._time_ranges.insert(i, time_range)
return True
return False
def _create_child(self):
child = ActivityPackModelItem(weakref.proxy(self), self._parent_model)
self._children.append(child)
return child
def _pack_range(self, time_range: TimeRange):
if self._parent: # Don't pack items if it's not a leaf
for child in self._children:
if child.extend_with_range(time_range):
# Successfully packed
return child
# Can't be packed. Create a new one.
child = self._create_child()
child.extend_with_range(time_range)
return child
def _add_subchild(self, subchild: ActivityModelItem) -> Optional["ActivityPackModelItem"]:
child = None
if self._is_packed:
subchild_time_range = subchild.time_range
for time_range in subchild.time_range:
added_to_child = self._pack_range(time_range)
child = added_to_child
self._parent_model._index_subitem_timegrange_count[subchild] = len(subchild_time_range)
elif subchild not in self._parent_model._index_subitem_timegrange_count:
subchild_time_range = subchild.time_range
child = self._create_child()
for time_range in subchild_time_range:
child.extend_with_range(time_range)
self._parent_model._index_subitem_timegrange_count[subchild] = len(subchild_time_range)
return child
def _search_time_range(self, time_range, low, high):
# Classic binary search
if high >= low:
mid = (high + low) // 2
# If element is present at the middle itself
if self._time_ranges[mid].begin == time_range.begin:
return mid
# If element is smaller than mid, then it can only
# be present in left subarray
elif self._time_ranges[mid].begin > time_range.begin:
return self._search_time_range(time_range, low, mid - 1)
# Else the element can only be present in right subarray
else:
return self._search_time_range(time_range, mid + 1, high)
else:
# Element is not present in the array
return None
def _update_timerange(self):
if not self._parent_model:
return
if not self._timerange_dirty:
return
self._timerange_dirty = False
dirty_subitems = self._parent_model._index_dirty.pop(self, [])
for subitem in dirty_subitems:
time_range_count_done = self._parent_model._index_subitem_timegrange_count.get(subitem, 0)
subitem_time_range = subitem.time_range
# Check the last one. It could be changed
if time_range_count_done:
time_range = subitem_time_range[time_range_count_done - 1]
i = self._search_time_range(time_range, 0, len(self._time_ranges) - 1)
if i is not None and i < len(self._time_ranges) - 1:
if time_range.end > self._time_ranges[i + 1].begin:
# It's changed so it itersects the next range. Repack.
self._time_ranges.pop(i)
self._parent._pack_range(time_range)
for time_range in subitem_time_range[time_range_count_done:]:
self._parent._pack_range(time_range)
self._parent_model._index_subitem_timegrange_count[subitem] = len(subitem_time_range)
def _update_children(self):
if not self._children_dirty:
return
self._children_dirty = False
already_checked = set()
for range in self._time_ranges:
subitem = range.item
if subitem in already_checked:
continue
already_checked.add(subitem)
# Check child count
child_count_already_here = self._parent_model._index_child_count.get(subitem, 0)
subchildren = subitem.children
if subchildren:
# Don't touch already added
for subchild in subchildren[child_count_already_here:]:
child = self._add_subchild(subchild)
self._parent_model._index[subchild] = child
subchild._packItem = child
self._parent_model._index_child_count[subitem] = len(subchildren)
def __repr__(self):
return "<ActivityPackModelItem " + str(self._time_ranges) + ">"
class ActivityPackModel(ActivityModel):
"""Activity model that packs the given submodel"""
def __init__(self, submodel: ActivityModel, **kwargs):
self._submodel = submodel
self._destroy_submodel = kwargs.pop("destroy_submodel", None)
# Replace on_timeline_changed
self.__on_timeline_changed_sub = self._submodel.subscribe_timeline_changed(
partial(ActivityPackModel.__on_timeline_changed, weakref.proxy(self))
)
super().__init__(**kwargs)
self._time_begin = self._submodel._time_begin
self._time_end = self._submodel._time_end
# Index for fast access
self._index: Dict[ActivityModelItem, ActivityPackModelItem] = {}
self._index_child_count: Dict[ActivityModelItem, int] = {}
self._index_subitem_timegrange_count: Dict[ActivityModelItem, int] = {}
self._index_dirty: Dict[ActivityPackModelItem, List[ActivityModelItem]] = defaultdict(list)
self._root = ActivityPackModelItem(None, weakref.proxy(self), packed=False)
self.__subscription = self._submodel.subscribe_item_changed_fn(
partial(ActivityPackModel._subitem_changed, weakref.proxy(self))
)
def _subitem_changed(self, submodel, subitem):
item = self._index.get(subitem, None)
if item is None or item == self._root:
# Root
self._root.dirty()
self._item_changed(None)
elif item:
self._dirty_item(item, subitem)
self._item_changed(item)
def _dirty_item(self, item, subitem):
item.dirty()
self._index_dirty[item].append(subitem)
def destroy(self):
super().destroy()
self.__on_timeline_changed_sub = None
self.__on_model_changed_sub = None
self._index: Dict[ActivityModelItem, ActivityPackModelItem] = {}
self._index_child_count: Dict[ActivityModelItem, int] = {}
self._index_subitem_timegrange_count: Dict[ActivityModelItem, int] = {}
self._index_dirty: Dict[ActivityPackModelItem, List[ActivityModelItem]] = defaultdict(list)
self._root.destroy()
if self._destroy_submodel:
self._submodel.destroy()
self._submodel = None
self.__subscription = None
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if self._submodel is None:
return []
if item is None:
if not self._root.time_range:
# Add the initial timerange once we have it
self._submodel._root.update_flags()
root_time_range = self._submodel._root.time_range
if root_time_range:
self._root.extend_with_range(root_time_range[0])
self._root.dirty()
children = self._root.get_children()
else:
children = item.get_children()
return children
def __on_timeline_changed(self):
self._time_end = self._submodel._time_end
if self._on_timeline_changed:
self._on_timeline_changed()
| 11,645 | Python | 33.764179 | 104 | 0.589867 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/__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 *
| 705 | Python | 46.066664 | 84 | 0.812766 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_chart.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ActivityChart"]
from .activity_delegate import ActivityDelegate
from .activity_filter_model import ActivityFilterModel
from .activity_menu import ActivityMenuOptions
from .activity_model import SECOND_MULTIPLIER, TIMELINE_EXTEND_DELAY_SEC
from .activity_pack_model import ActivityPackModel
from .activity_tree_delegate import ActivityTreeDelegate
from functools import partial
from omni.ui import color as cl
from typing import Tuple
import carb.input
import math
import omni.appwindow
import omni.client
import omni.ui as ui
import weakref
DENSITY = [1, 2, 5]
def get_density(i):
# the density will be like this [1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 10000, ...]
level = math.floor(i / 3)
return (10**level) * DENSITY[i % 3]
def get_current_mouse_coords() -> Tuple[float, float]:
app_window = omni.appwindow.get_default_app_window()
input = carb.input.acquire_input_interface()
dpi_scale = ui.Workspace.get_dpi_scale()
pos_x, pos_y = input.get_mouse_coords_pixel(app_window.get_mouse())
return pos_x / dpi_scale, pos_y / dpi_scale
class ActivityChart:
"""The widget that represents the activity viewer"""
def __init__(self, model, activity_menu: ActivityMenuOptions = None, **kwargs):
self.__model = None
self.__packed_model = None
self.__filter_model = None
# Widgets
self.__timeline_frame = None
self.__selection_frame = None
self.__chart_graph = None
self.__chart_tree = None
self._activity_menu_option = activity_menu
# Timeline Zoom
self.__zoom_level = 100
self.__delegate = kwargs.pop("delegate", None) or ActivityDelegate(
on_expand=partial(ActivityChart.__on_timeline_expand, weakref.proxy(self)),
)
self.__tree_delegate = ActivityTreeDelegate(
on_expand=partial(ActivityChart.__on_treeview_expand, weakref.proxy(self)),
initialize_expansion=partial(ActivityChart.__initialize_expansion, weakref.proxy(self)),
)
self.density = 3
self.__frame = ui.Frame(
build_fn=partial(self.__build, model),
style={"ActivityBar": {"border_color": cl(0.25), "secondary_selected_color": cl.white, "border_width": 1}},
)
# Selection
self.__is_selection = False
self.__selection_from = None
self.__selection_to = None
# Pan/zoom
self.__pan_x_start = None
self.width = None
def destroy(self):
self.__model = None
if self.__packed_model:
self.__packed_model.destroy()
if self.__filter_model:
self.__filter_model.destroy()
if self.__delegate:
self.__delegate.destroy()
self.__delegate = None
self.__tree_delegate = None
def invalidate(self): # pragma: no cover
"""Rebuild all"""
# TODO: Do we need it?
self.__frame.rebuild()
def new(self, model=None):
"""Recreate the models and start recording"""
if self.__packed_model:
self.__packed_model.destroy()
if self.__filter_model:
self.__filter_model.destroy()
self.__model = model
if self.__model:
self.__packed_model = ActivityPackModel(
self.__model,
on_timeline_changed=partial(ActivityChart.__on_timeline_changed, weakref.proxy(self)),
on_selection_changed=partial(ActivityChart.__on_selection_changed, weakref.proxy(self)),
)
self.__filter_model = ActivityFilterModel(self.__model)
self.__apply_models()
self.__on_timeline_changed()
else:
if self.__chart_graph:
self.__chart_graph.dirty_widgets()
if self.__chart_tree:
self.__chart_tree.dirty_widgets()
def save_for_report(self):
return self.__model.get_report_data()
def __build(self, model):
"""Build the whole UI"""
if self._activity_menu_option:
self._options_menu = ui.Menu("Options")
with self._options_menu:
ui.MenuItem("Open...", triggered_fn=self._activity_menu_option.menu_open)
ui.MenuItem("Save...", triggered_fn=self._activity_menu_option.menu_save)
with ui.VStack():
self.__build_title()
self.__build_body()
self.__build_footer()
self.new(model)
def __build_title(self):
"""Build the top part of the widget"""
pass
def __zoom_horizontally(self, x: float, y: float, modifiers: int):
scale = 1.1**y
self.__zoom_level *= scale
self.__range_placer.width = ui.Percent(self.__zoom_level)
self.__timeline_placer.width = ui.Percent(self.__zoom_level)
# do an offset pan, so the zoom looks like happened at the mouse coordinate
origin = self.__range_frame.screen_position_x
pox_x, pos_y = get_current_mouse_coords()
offset = (pox_x - origin - self.__range_placer.offset_x) * (scale - 1)
self.__range_placer.offset_x -= offset
self.__timeline_placer.offset_x -= offset
if self.__relax_timeline():
self.__timeline_indicator.rebuild()
def __relax_timeline(self):
if self.width is None:
return
width = self.__timeline_placer.computed_width * self.width / get_density(self.density)
if width < 25 and self.density > 0:
self.density -= 1
return True
elif width > 50:
self.density += 1
return True
return False
def __selection_changed(self, selection):
"""
Called from treeview selection change, update the timeline selection
"""
if not selection:
return
# avoid selection loop
if self.__packed_model.selection and selection[0] == self.__packed_model.selection:
return
self.__delegate.select_range(selection[0], self.__packed_model)
self.selection_on_stage(selection[0])
def selection_on_stage(self, item):
if not item:
return
path = item.name_model.as_string
# skip the one which is cached locally
if path.startswith("file:"):
return
elif path.endswith("instance)"):
path = path.split(" ")[0]
usd_context = omni.usd.get_context()
usd_context.get_selection().set_selected_prim_paths([path], True)
def show_stack_from_idx(self, idx):
if idx == 0:
self._activity_stack.visible = False
self._timeline_stack.visible = True
elif idx == 1:
self._activity_stack.visible = True
self._timeline_stack.visible = False
def __build_body(self):
"""Build the middle part of the widget"""
self._collection = ui.RadioCollection()
with ui.VStack():
with ui.HStack(height=30):
ui.Spacer()
tab0 = ui.RadioButton(
text="Timeline",
width=0,
radio_collection=self._collection)
ui.Spacer(width=12)
with ui.VStack(width=3):
ui.Spacer()
ui.Rectangle(name="separator", height=16)
ui.Spacer()
ui.Spacer(width=12)
tab1 = ui.RadioButton(
text="Activities",
width=0,
radio_collection=self._collection)
ui.Spacer()
ui.Button(name="options", width=20, height=20, clicked_fn=lambda: self._options_menu.show())
with ui.ZStack():
self.__build_timeline_stack()
self.__build_activity_stack()
self._activity_stack.visible = False
tab0.set_clicked_fn(lambda: self.show_stack_from_idx(0))
tab1.set_clicked_fn(lambda: self.show_stack_from_idx(1))
def __timeline_right_pressed(self, x, y, button, modifier):
if button != 1:
return
# make to separate this from middle mouse selection
self.__is_selection = False
self.__pan_x_start = x
self.__pan_y_start = y
def __timeline_pan(self, x, y):
if self.__pan_x_start is None:
return
self.__pan_x_end = x
moved_x = self.__pan_x_end - self.__pan_x_start
self.__range_placer.offset_x += moved_x
self.__timeline_placer.offset_x += moved_x
self.__pan_x_start = x
self.__pan_y_end = y
moved_y = min(self.__pan_y_start - self.__pan_y_end, self.__range_frame.scroll_y_max)
self.__range_frame.scroll_y += moved_y
self.__pan_y_start = y
def __timeline_right_moved(self, x, y, modifier, button):
if button or self.__is_selection:
return
self.__timeline_pan(x, y)
def __timeline_right_released(self, x, y, button, modifier):
if button != 1 or self.__pan_x_start is None:
return
self.__timeline_pan(x, y)
self.__pan_x_start = None
def __build_timeline_stack(self):
self._timeline_stack = ui.VStack()
with self._timeline_stack:
with ui.ZStack():
with ui.VStack():
ui.Rectangle(height=36, name="spacer")
self.__range_frame = ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
mouse_wheel_fn=self.__zoom_horizontally)
with self.__range_frame:
self.__range_placer = ui.Placer()
with self.__range_placer:
# Chart view
self.__chart_graph = ui.TreeView(
self.__packed_model,
delegate=self.__delegate,
root_visible=False,
header_visible=True,
column_widths=[ui.Fraction(1), 0, 0, 0, 0]
)
with ui.HStack():
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
):
self.__timeline_placer = ui.Placer(
mouse_pressed_fn=self.__timeline_right_pressed,
mouse_released_fn=self.__timeline_right_released,
mouse_moved_fn=self.__timeline_right_moved,
)
with self.__timeline_placer:
# It's in placer to prevent the whole ZStack from changing size
self.__timeline_frame = ui.Frame(build_fn=self.__build_timeline)
# this is really a trick to show self.__range_frame's vertical scrollbar, and 12 is the
# kScrollBarWidth of scrollingFrame, so that we can pan vertically for the timeline
scrollbar_width = 12 * ui.Workspace.get_dpi_scale()
ui.Spacer(width=scrollbar_width)
def __build_activity_stack(self):
# TreeView with all the activities
self._activity_stack = ui.VStack()
with self._activity_stack:
with ui.ScrollingFrame():
self.__chart_tree = ui.TreeView(
self.__filter_model,
delegate=self.__tree_delegate,
root_visible=False,
header_visible=True,
column_widths=[ui.Fraction(1), 60, 60, 60, 60],
columns_resizable=True,
selection_changed_fn=self.__selection_changed,
)
def __build_footer(self):
"""Build the bottom part of the widget"""
pass
def __build_timeline(self):
"""Build the timeline on top of the chart"""
if self.__packed_model:
time_begin = self.__packed_model._time_begin
time_end = self.__packed_model._time_end
self.time_length = (time_end - time_begin) / SECOND_MULTIPLIER
else:
self.time_length = TIMELINE_EXTEND_DELAY_SEC
self.time_step = max(math.floor(self.time_length / 5.0), 1.0)
self.width = self.time_step / self.time_length
with ui.ZStack():
self.__timeline_indicator = ui.Frame(build_fn=self.__build_time_indicator)
self.__selection_frame = ui.Frame(
build_fn=self.__build_selection,
mouse_pressed_fn=self.__timeline_middle_pressed,
mouse_released_fn=self.__timeline_middle_released,
mouse_moved_fn=self.__timeline_middle_moved,
)
def __build_time_indicator(self):
density = get_density(self.density)
counts = math.floor(self.time_length / self.time_step) * density
# put a cap on the indicator numbers. Otherwise, it hits the imgui prims limits and cause crash
if counts > 10000:
carb.log_warn("Zoom level is too high to show the time indicator")
return
width = ui.Percent(self.width / density * 100)
with ui.VStack():
with ui.Placer(offset_x=-0.5 * width, height=0):
with ui.HStack():
for i in range(math.floor(counts / 5)):
ui.Label(f" {i * 5 * self.time_step / density} s", name="time", width=width * 5)
with ui.HStack():
for i in range(counts):
if i % 10 == 0:
height = 36
elif i % 5 == 0:
height = 24
else:
height = 12
ui.Line(alignment=ui.Alignment.LEFT, height=height, name="timeline", width=width)
def __build_selection(self):
"""Build the selection widgets on top of the chart"""
if self.__selection_from is None or self.__selection_to is None or self.__selection_from == self.__selection_to:
ui.Spacer()
return
if self.__packed_model is None:
return
time_begin = self.__packed_model._time_begin
time_end = self.__packed_model._time_end
selection_from = min(self.__selection_from, self.__selection_to)
selection_to = max(self.__selection_from, self.__selection_to)
with ui.HStack():
ui.Spacer(width=ui.Fraction(selection_from - time_begin))
with ui.ZStack(width=ui.Fraction(selection_to - selection_from)):
ui.Rectangle(name="selected_area")
ui.Label(
f"{(selection_from - time_begin) / SECOND_MULTIPLIER:.2f}",
height=0, elided_text=True, elided_text_str="", name="selection_time")
ui.Label(
f"< {(selection_to - selection_from) / SECOND_MULTIPLIER:.2f} s >",
height=0, elided_text=True, elided_text_str="", name="selection_time", alignment=ui.Alignment.CENTER)
ui.Label(
f"{(selection_to - time_begin) / SECOND_MULTIPLIER:.2f}",
width=ui.Fraction(time_end - selection_to), height=0,
elided_text=True, elided_text_str="", name="selection_time")
def __on_timeline_changed(self):
"""
Called to resubmit timeline because the global time range is
changed.
"""
if self.__chart_graph:
# Update visible widgets
self.__chart_graph.dirty_widgets()
if self.__timeline_frame:
self.__relax_timeline()
self.__timeline_frame.rebuild()
def __on_selection_changed(self):
"""
Called from timeline selection change, update the treeview selection
"""
selection = self.__packed_model.selection
self.__chart_tree.selection = [selection]
self.selection_on_stage(selection)
def __on_timeline_expand(self, item, range_item, recursive):
"""Called from the timeline when it wants to expand something"""
if self.__chart_graph:
expanded = not self.__chart_graph.is_expanded(item)
self.__chart_graph.set_expanded(item, expanded, recursive)
# Expand the bottom tree view as well.
if expanded != self.__chart_tree.is_expanded(range_item):
self.__chart_tree.set_expanded(range_item, expanded, recursive)
def __initialize_expansion(self, item, expanded):
# expand the treeview
if self.__chart_tree:
if expanded != self.__chart_tree.is_expanded(item):
self.__chart_tree.set_expanded(item, expanded, False)
# expand the timeline
if self.__chart_graph:
pack_item = item._packItem
if pack_item and expanded != self.__chart_graph.is_expanded(pack_item):
self.__chart_graph.set_expanded(pack_item, expanded, False)
def __on_treeview_expand(self, range_item):
"""Called from the treeview when it wants to expand something"""
# this callback is triggered when the branch is pressed, so the expand status will be opposite of the current
# expansion status
if self.__chart_tree:
expanded = not self.__chart_tree.is_expanded(range_item)
# expand the timeline as well
item = range_item._packItem
if item and expanded != self.__chart_graph.is_expanded(item):
self.__chart_graph.set_expanded(item, expanded, False)
def __timeline_middle_pressed(self, x, y, button, modifier):
if button != 2:
return
self.__is_selection = True
if self.__packed_model is None:
return
width = self.__selection_frame.computed_width
origin = self.__selection_frame.screen_position_x
time_begin = self.__packed_model._time_begin
time_end = self.__packed_model._time_end
self.__selection_from_pos_x = x
self.__selection_from = time_begin + (x - origin) / width * (time_end - time_begin)
self.__selection_from = max(self.__selection_from, time_begin)
self.__selection_from = min(self.__selection_from, time_end)
def __timeline_middle_moved(self, x, y, modifier, button):
if button or not self.__is_selection or self.__packed_model is None:
return
width = self.__selection_frame.computed_width
if width == 0:
return
origin = self.__selection_frame.screen_position_x
time_begin = self.__packed_model._time_begin
time_end = self.__packed_model._time_end
self.__selection_to = time_begin + (x - origin) / width * (time_end - time_begin)
self.__selection_to = max(self.__selection_to, time_begin)
self.__selection_to = min(self.__selection_to, time_end)
self.__selection_frame.rebuild()
def __timeline_middle_released(self, x, y, button, modifier):
if button != 2 or not self.__is_selection or self.__packed_model is None:
return
self.__selection_to_pos_x = x
width = self.__selection_frame.computed_width
origin = self.__selection_frame.screen_position_x
time_begin = self.__packed_model._time_begin
time_end = self.__packed_model._time_end
self.__selection_to = time_begin + (x - origin) / width * (time_end - time_begin)
self.__selection_to = max(self.__selection_to, time_begin)
self.__selection_to = min(self.__selection_to, time_end)
self.__selection_frame.rebuild()
self.__timeline_selected()
self.__is_selection = False
def __zoom_to_fit_selection(self):
time_begin = self.__packed_model._time_begin
time_end = self.__packed_model._time_end
selection_from = self.__filter_model.timerange_begin
selection_to = self.__filter_model.timerange_end
pre_zoom_level = self.__zoom_level
zoom_level = (time_end - time_begin) / float(selection_to - selection_from) * 100
# zoom
self.__zoom_level = zoom_level
self.__range_placer.width = ui.Percent(self.__zoom_level)
self.__timeline_placer.width = ui.Percent(self.__zoom_level)
# offset pan
origin = self.__selection_frame.screen_position_x
start = min(self.__selection_to_pos_x, self.__selection_from_pos_x)
offset = (start - origin) * zoom_level / float(pre_zoom_level) + self.__range_placer.offset_x
self.__range_placer.offset_x -= offset
self.__timeline_placer.offset_x -= offset
def __timeline_selected(self):
if self.__selection_from is None or self.__selection_to is None or self.__selection_from == self.__selection_to:
# Deselect
self.__filter_model.timerange_begin = None
self.__filter_model.timerange_end = None
return
self.__filter_model.timerange_begin = min(self.__selection_from, self.__selection_to)
self.__filter_model.timerange_end = max(self.__selection_from, self.__selection_to)
self.__zoom_to_fit_selection()
def __apply_models(self):
if self.__chart_graph:
self.__chart_graph.model = self.__packed_model
if self.__chart_tree:
self.__chart_tree.model = self.__filter_model
| 22,146 | Python | 38.689964 | 121 | 0.568771 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_model.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ActivityModel"]
from dataclasses import dataclass
from functools import lru_cache
from omni.ui import color as cl
from typing import Dict, List, Optional, Set
from .style import get_shade_from_name
import asyncio
import carb
import contextlib
import functools
import omni.activity.core
import omni.ui as ui
import traceback
import weakref
TIMELINE_EXTEND_DELAY_SEC = 5.0
SECOND_MULTIPLIER = 10000000
SMALL_ACTIVITY_THRESHOLD = 0.001
time_begin = 0
time_end = 0
@lru_cache()
def get_color_from_name(name: str):
return get_shade_from_name(name)
def get_default_metadata(name):
return {"name": name, "color": int(get_color_from_name(name))}
def handle_exception(func):
"""
Decorator to print exception in async functions
TODO: The alternative way would be better, but we want to use traceback.format_exc for better error message.
result = await asyncio.gather(*[func(*args)], return_exceptions=True)
"""
@functools.wraps(func)
async def wrapper(*args, **kwargs):
try:
return await func(*args, **kwargs)
except asyncio.CancelledError:
# We always cancel the task. It's not a problem.
pass
except Exception as e:
carb.log_error(f"Exception when async '{func}'")
carb.log_error(f"{e}")
carb.log_error(f"{traceback.format_exc()}")
return wrapper
async def event_wait(evt, timeout):
# Suppress TimeoutError because we'll return False in case of timeout
with contextlib.suppress(asyncio.TimeoutError):
await asyncio.wait_for(evt.wait(), timeout)
return evt.is_set()
@handle_exception
async def loop_forever_async(refresh_rate: float, stop_event: asyncio.Event, callback):
"""Forever loop with the ability to stop"""
while not await event_wait(stop_event, refresh_rate):
# Do something
callback()
@dataclass
class ActivityModelEvent:
"""Atomic event"""
type: omni.activity.core.EventType
time: int
payload: dict
@dataclass
class TimeRange:
"""Values or a timerange"""
item: ui.AbstractItem
begin: int
end: int
metadata: dict
class ActivityModelItem(ui.AbstractItem):
def __init__(self, name: str, parent):
super().__init__()
self.parent = parent
self.name_model = ui.SimpleStringModel(name)
self.events: List[ActivityModelEvent] = []
self.children: List[ActivityModelItem] = []
self.child_to_id: Dict[str, int] = {}
# We need it for hash
parent_path = parent.path if parent else ""
self.path = parent_path + "->" + name
if parent_path == "->Root->Textures->Load" or parent_path == "->Root->Textures->Queue":
self.icon_name = "texture"
elif parent_path == "->Root->Materials":
self.icon_name = "material"
elif parent_path == "->Root->USD->Read" or parent_path == "->Root->USD->Resolve":
self.icon_name = "USD"
else:
self.icon_name = "undefined"
self.max_time_cached = None
# True when ended
self.ended = True
# Time range when the item is active
self.__child_timerange_dirty = True
self.__dirty_event_id: Optional[int] = None
self.__timerange_cache: List[TimeRange] = []
self.__total_time: int = 0
self.__size = 0
self.__children_size = 0
self._packItem = None
def __hash__(self):
return hash(self.path)
def __eq__(self, other):
return self.path == other.path
def __repr__(self):
return "<ActivityModelItem '" + self.name_model.as_string + "'>"
@property
def loaded_children_num(self):
res = 0
for c in self.children:
if c.ended:
res += 1
return res
@property
def time_range(self) -> List[TimeRange]:
"""Return the time ranges when the item was active"""
if self.events:
# Check if it's not dirty and is not read from the json
if self.__dirty_event_id is None and self.__timerange_cache:
return self.__timerange_cache
dirty_event_id = self.__dirty_event_id
self.__dirty_event_id = None
if self.__timerange_cache:
time_range = self.__timerange_cache.pop(-1)
else:
time_range = None
# Iterate the new added events
for event in self.events[dirty_event_id:]:
if event.type == omni.activity.core.EventType.ENDED or event.type == omni.activity.core.EventType.UPDATED:
if time_range is None:
# Can't end or update if it's not started
continue
time_range.end = event.time
else:
if time_range and event.type == omni.activity.core.EventType.BEGAN and time_range.end != 0:
# The latest event is ended. We can add it to the cache.
self.__timerange_cache.append(time_range)
time_range = None
if time_range is None:
global time_begin
time_range = TimeRange(self, 0, 0, get_default_metadata(self.name_model.as_string))
time_range.begin = max(event.time, time_begin)
if "size" in event.payload:
prev_size = self.__size
self.__size = event.payload["size"]
loaded_size = self.__size - prev_size
if loaded_size > 0:
self.parent.__children_size += loaded_size
if time_range:
if time_range.end == 0:
# Range did not end, set to the end of the capture.
global time_end
time_range.end = max(time_end, time_range.begin)
if time_range.end < time_range.begin:
# Bad data, range ended before it began.
time_range.end = time_range.begin
self.__timerange_cache.append(time_range)
elif self.children:
# Check if it's not dirty
if not self.__child_timerange_dirty:
return self.__timerange_cache
self.__child_timerange_dirty = False
# Create ranges out of children
min_begin = None
max_end = None
for child in self.children:
time_range = child.time_range
if time_range:
if min_begin is None:
min_begin = time_range[0].begin
else:
min_begin = min(min_begin, time_range[0].begin)
if max_end is None:
max_end = time_range[-1].end
else:
max_end = max(max_end, time_range[-1].end)
if min_begin is not None and max_end is not None:
if self.__timerange_cache:
time_range_cache = self.__timerange_cache[0]
time_range_cache.begin = min_begin
time_range_cache.end = max_end
else:
time_range_cache = TimeRange(
self, min_begin, max_end, get_default_metadata(self.name_model.as_string)
)
if not self.__timerange_cache:
self.__timerange_cache.append(time_range_cache)
# TODO: optimize
self.__total_time = 0
for timerange in self.__timerange_cache:
self.__total_time += timerange.end - timerange.begin
return self.__timerange_cache
@property
def total_time(self):
"""Return the time ranges when the item was active"""
if self.__dirty_event_id is not None:
# Recache
_ = self.time_range
return self.__total_time
@property
def size(self):
"""Return the size of the item"""
return self.__size
@size.setter
def size(self, val):
self.__size = val
@property
def children_size(self):
return self.__children_size
@children_size.setter
def children_size(self, val):
self.__children_size = val
def find_or_create_child(self, node):
"""Return the child if it's exists, or creates one"""
name = node.name
child_id = self.child_to_id.get(name, None)
if child_id is None:
created = True
# Create a new item
child_item = ActivityModelItem(name, self)
child_id = len(self.children)
self.child_to_id[name] = child_id
self.children.append(child_item)
else:
created = False
child_item = self.children[child_id]
child_item._update_events(node)
return child_item, created
def _update_events(self, node: omni.activity.core.IEvent):
"""Returns true if the item is ended"""
if not node.event_count:
return
activity_events_count = node.event_count
if activity_events_count > 512:
# We have a problem with the following activities:
#
# IEventStream(RunLoop.update)::push() Event:0
# IEventStream(RunLoop.update)::push() Event:0
# IEventStream(RunLoop.update)::dispatch() Event:0
# IEventStream(RunLoop.update)::dispatch() Event:0
# IEventStream(RunLoop.postUpdate)::push() Event:0
# IEventStream(RunLoop.postUpdate)::push() Event:0
# IEventStream(RunLoop.postUpdate)::dispatch() Event:0
# IEventStream(RunLoop.postUpdate)::dispatch() Event:0
# IEventListener(omni.kit.renderer.plugin.dll!carb::events::LambdaEventListener::onEvent+0x0 at include\carb\events\EventsUtils.h:57)::onEvent
# IEventListener(omni.kit.renderer.plugin.dll!carb::events::LambdaEventListener::onEvent+0x0 at include\carb\events\EventsUtils.h:57)::onEvent
# IEventStream(RunLoop.preUpdate)::push() Event:0
# IEventStream(RunLoop.preUpdate)::push() Event:0
# IEventStream(RunLoop.preUpdate)::dispatch() Event:0
# IEventStream(RunLoop.preUpdate)::dispatch() Event:0
#
# Each of them has 300k events on Factory Explorer startup. (pairs
# of Begin-End with 0 duration). When trying to visualize 300k
# events at once on Python side it fails to do it in adequate time.
# Ignoring such activities saves 15s of startup time.
#
# TODO: But the best would be to not report such activities at all.
activity_events = [node.get_event(0), node.get_event(activity_events_count - 1)]
activity_events_count = 2
else:
activity_events = [node.get_event(e) for e in range(activity_events_count)]
activity_events_filtered = []
# TODO: Temporary. We need to do in in the core
# Filter out BEGAN+ENDED events with the same timestamp
i = 0
# The threshold is 1 ms
threshold = SECOND_MULTIPLIER * SMALL_ACTIVITY_THRESHOLD
while i < activity_events_count:
if (
i + 1 < activity_events_count
and activity_events[i].event_type == omni.activity.core.EventType.BEGAN
and activity_events[i + 1].event_type == omni.activity.core.EventType.ENDED
and activity_events[i + 1].event_timestamp - activity_events[i].event_timestamp < threshold
):
# Skip them
i += 2
elif (
i + 2 < activity_events_count
and activity_events[i].event_type == omni.activity.core.EventType.BEGAN
and activity_events[i + 1].event_type == omni.activity.core.EventType.UPDATED
and activity_events[i + 2].event_type == omni.activity.core.EventType.ENDED
and activity_events[i + 2].event_timestamp - activity_events[i].event_timestamp < threshold
):
# Skip them
i += 3
else:
activity_events_filtered.append(activity_events[i])
i += 1
if self.__dirty_event_id is None:
self.__dirty_event_id = len(self.events)
for activity_event in activity_events_filtered:
self.events.append(
ActivityModelEvent(activity_event.event_type, activity_event.event_timestamp, activity_event.payload)
)
def update_flags(self):
self.ended = not self.events or self.events[-1].type == omni.activity.core.EventType.ENDED
for c in self.children:
self.ended = self.ended and c.ended
if c.__child_timerange_dirty or self.__dirty_event_id is not None:
self.__child_timerange_dirty = True
def update_size(self):
if self.events:
for event in self.events:
if "size" in event.payload:
self.size = event.payload["size"]
def get_data(self):
children = []
for c in self.children:
children.append(c.get_data())
# Events
events = []
for e in self.events:
event = {"time": e.time, "type": e.type.name}
if "size" in e.payload:
event["size"] = self.size
events.append(event)
return {"name": self.name_model.as_string, "children": children, "events": events}
def get_report_data(self):
children = []
for c in self.children:
children.append(c.get_report_data())
data = {
"name": self.name_model.as_string,
"children": children,
"duration": self.total_time / SECOND_MULTIPLIER,
}
for e in self.events:
if "size" in e.payload:
data["size"] = self.size
return data
def set_data(self, data):
"""Recreate the item from the data"""
self.name_model = ui.SimpleStringModel(data["name"])
self.events: List[ActivityModelEvent] = []
for e in data["events"]:
event_type_str = e["type"]
if event_type_str == "BEGAN":
event_type = omni.activity.core.EventType.BEGAN
elif event_type_str == "ENDED":
event_type = omni.activity.core.EventType.ENDED
else: # event_type_str == "UPDATED":
event_type = omni.activity.core.EventType.UPDATED
payload = {}
if "size" in e:
self.size = e["size"]
payload["size"] = e["size"]
self.events.append(ActivityModelEvent(event_type, e["time"], payload))
self.children: List[ActivityModelItem] = []
self.child_to_id: Dict[str, int] = {}
for i, c in enumerate(data["children"]):
child = ActivityModelItem(c["name"], self)
child.set_data(c)
self.children.append(child)
self.child_to_id[c["name"]] = i
class ActivityModel(ui.AbstractItemModel):
"""Empty Activity model"""
class _Event(set):
"""
A list of callable objects. Calling an instance of this will cause a
call to each item in the list in ascending order by index.
"""
def __call__(self, *args, **kwargs):
"""Called when the instance is “called” as a function"""
# Call all the saved functions
for f in list(self):
f(*args, **kwargs)
def __repr__(self):
"""
Called by the repr() built-in function to compute the “official”
string representation of an object.
"""
return f"Event({set.__repr__(self)})"
class _EventSubscription:
"""
Event subscription.
_Event has callback while this object exists.
"""
def __init__(self, event, fn):
"""
Save the function, the event, and add the function to the event.
"""
self._fn = fn
self._event = event
event.add(self._fn)
def __del__(self):
"""Called by GC."""
self._event.remove(self._fn)
def __init__(self, **kwargs):
super().__init__()
self._stage_path = ""
self._root = ActivityModelItem("Root", None)
self.__selection = None
self._on_selection_changed = ActivityModel._Event()
self.__on_selection_changed_sub = self.subscribe_selection_changed(kwargs.pop("on_selection_changed", None))
self._on_timeline_changed = ActivityModel._Event()
self.__on_timeline_changed_sub = self.subscribe_timeline_changed(kwargs.pop("on_timeline_changed", None))
def destroy(self):
self._on_timeline_changed = None
self.__on_timeline_changed_sub = None
self.__selection = None
self._on_selection_changed = None
self.__on_selection_changed_sub = None
def subscribe_timeline_changed(self, fn):
if fn:
return ActivityModel._EventSubscription(self._on_timeline_changed, fn)
def subscribe_selection_changed(self, fn):
if fn:
return ActivityModel._EventSubscription(self._on_selection_changed, fn)
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is None:
return self._root.children
return item.children
def get_item_value_model_count(self, item):
"""The number of columns"""
return 5
def get_item_value_model(self, item, column_id):
"""
Return value model. It's the object that tracks the specific value.
"""
return item.name_model
def get_data(self):
return {"stage": self._stage_path, "root": self._root.get_data(), "begin": self._time_begin, "end": self._time_end}
def get_report_data(self):
return {"root": self._root.get_report_data()}
@property
def selection(self):
return self.__selection
@selection.setter
def selection(self, value):
if not self.__selection or self.__selection != value:
self.__selection = value
self._on_selection_changed()
class ActivityModelDump(ActivityModel):
"""Activity model with pre-defined data"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
self._data = kwargs.pop("data", [])
self._time_begin = self._data["begin"]
self._time_end = self._data["end"]
# So we can fixup time spans that started early or didn't end.
global time_begin
global time_end
time_begin = self._time_begin
time_end = self._time_end
self._root.set_data(self._data["root"])
def destroy(self):
super().destroy()
class ActivityModelDumpForProgress(ActivityModelDump):
"""Activity model for loaded data with 3 columns"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
def get_item_value_model_count(self, item):
"""The number of columns"""
return 3
class ActivityModelRealtime(ActivityModel):
"""The model that accumulates all the activities"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
activity = omni.activity.core.get_instance()
self._subscription = activity.create_callback_to_pop(self._activity)
self._timeline_stop_event = asyncio.Event()
self._timeline_extend_task = asyncio.ensure_future(
loop_forever_async(
TIMELINE_EXTEND_DELAY_SEC,
self._timeline_stop_event,
functools.partial(ActivityModelRealtime.__update_timeline, weakref.proxy(self)),
)
)
self._time_begin = activity.current_timestamp
self._time_end = self._time_begin + int(TIMELINE_EXTEND_DELAY_SEC * SECOND_MULTIPLIER)
self._activity_pump = False
# So we can fixup time spans that started early or didn't end.
global time_begin
global time_end
time_begin = self._time_begin
time_end = self._time_end
def start(self):
self._activity_pump = True
def end(self):
self._activity_pump = False
activity = omni.activity.core.get_instance()
activity.remove_callback(self._subscription)
self._timeline_stop_event.set()
if self._timeline_extend_task:
self._timeline_extend_task.cancel()
self._timeline_extend_task = None
def destroy(self):
super().destroy()
self.end()
def _activity(self, node):
"""Called when the activity happened"""
if self._activity_pump:
self._update_item(self._root, node)
def __update_timeline(self):
"""
Called once a minute to extend the timeline.
"""
activity = omni.activity.core.get_instance()
self._time_end = activity.current_timestamp + int(TIMELINE_EXTEND_DELAY_SEC * SECOND_MULTIPLIER)
# So we can fixup time spans that don't end.
global time_end
time_end = self._time_end
if self._on_timeline_changed:
self._on_timeline_changed()
def _update_item(self, parent, node, depth=0):
"""
Recursively update the item with the activity. Called when the activity
passed to the UI.
"""
item, created = parent.find_or_create_child(node)
events = node.event_count
for node_id in range(node.child_count):
child_events = self._update_item(item, node.get_child(node_id), depth + 1)
# Cascading
events += child_events
item.update_flags()
# If child is created, we need to update the parent
if created:
if parent == self._root:
self._item_changed(None)
else:
self._item_changed(parent)
# If the time/size is changed, we need to update the item
if events:
self._item_changed(item)
return events
class ActivityModelStageOpen(ActivityModelRealtime):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def set_path(self, path):
self._stage_path = path
self.start()
def destroy(self):
super().destroy()
class ActivityModelStageOpenForProgress(ActivityModelStageOpen):
def __init__(self, **kwargs):
self._flattened_children = []
super().__init__(**kwargs)
def destroy(self):
super().destroy()
self._flattened_children = []
def _update_item(self, parent, node, depth=0):
"""
Recursively update the item with the activity. Called when the activity
passed to the UI.
"""
item, created = parent.find_or_create_child(node)
for node_id in range(node.child_count):
self._update_item(item, node.get_child(node_id), depth + 1)
item.update_flags()
if parent.name_model.as_string in ["Read", "Load", "Materials"]: # Should check for "USD|Read" and "Textures|Load" if possible
if not created and item in self._flattened_children:
self._flattened_children.pop(self._flattened_children.index(item))
self._flattened_children.insert(0, item)
# make sure the list only keeps the latest items, so else insert won't be too expensive
if len(self._flattened_children) > 50:
self._flattened_children.pop()
# update the item size and parent's children_size
prev_size = item.size
item.update_size()
loaded_size = item.size - prev_size
if loaded_size > 0:
parent.children_size += loaded_size
# if there is newly created items or new updated size, we update the item
if created or loaded_size > 0:
self._item_changed(parent)
def get_item_value_model_count(self, item):
"""The number of columns"""
return 3
| 24,789 | Python | 32.912449 | 154 | 0.573601 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_menu.py | import carb.input
import omni.client
from omni.kit.widget.filebrowser import FileBrowserItem
from omni.kit.window.filepicker import FilePickerDialog
import json
import os
class ActivityMenuOptions:
def __init__(self, **kwargs):
self._pick_folder_dialog = None
self._current_filename = None
self._current_dir = None
self.load_data = kwargs.pop("load_data", None)
self.get_save_data = kwargs.pop("get_save_data", None)
def destroy(self):
if self._pick_folder_dialog:
self._pick_folder_dialog.destroy()
def __menu_save_apply_filename(self, filename: str, dir: str):
"""Called when the user presses "Save" in the pick filename dialog"""
# don't accept as long as no filename is selected
if not filename or not dir:
return
if self._pick_folder_dialog:
self._pick_folder_dialog.hide()
# add the file extension if missing
extension = filename.split(".")[-1]
filter = "json" if self._pick_folder_dialog and self._pick_folder_dialog.current_filter_option else "activity"
if extension != filter:
filename = filename + "." + filter
self._current_filename = filename
self._current_dir = dir
# add a trailing slash for the client library
if dir[-1] != os.sep:
dir = dir + os.sep
current_export_path = omni.client.combine_urls(dir, filename)
self.save(current_export_path)
def __menu_open_apply_filename(self, filename: str, dir: str):
"""Called when the user presses "Open" in the pick filename dialog"""
# don't accept as long as no filename is selected
if not filename or not dir:
return
if self._pick_folder_dialog:
self._pick_folder_dialog.hide()
# add a trailing slash for the client library
if dir[-1] != os.sep:
dir = dir + os.sep
current_path = omni.client.combine_urls(dir, filename)
if omni.client.stat(current_path)[0] != omni.client.Result.OK:
# add the file extension if missing
extension = filename.split(".")[-1]
filter = "json" if self._pick_folder_dialog and self._pick_folder_dialog.current_filter_option else "activity"
if extension != filter:
filename = filename + "." + filter
current_path = omni.client.combine_urls(dir, filename)
if omni.client.stat(current_path)[0] != omni.client.Result.OK:
# Still can't find
return
self._current_filename = filename
self._current_dir = dir
self.load(current_path)
def __menu_filter_files(self, item: FileBrowserItem) -> bool:
"""Used by pick folder dialog to hide all the files"""
if not item or item.is_folder:
return True
filter = ".json" if self._pick_folder_dialog and self._pick_folder_dialog.current_filter_option else ".activity"
if item.path.endswith(filter):
return True
else:
return False
def menu_open(self):
"""Open "Open" dialog"""
if self._pick_folder_dialog:
self._pick_folder_dialog.destroy()
self._pick_folder_dialog = FilePickerDialog(
"Open...",
allow_multi_selection=False,
apply_button_label="Open",
click_apply_handler=self.__menu_open_apply_filename,
item_filter_options=["ACTIVITY file (*.activity)", "JSON file (*.json)"],
item_filter_fn=self.__menu_filter_files,
current_filename=self._current_filename,
current_directory=self._current_dir,
)
def menu_save(self):
"""Open "Save" dialog"""
if self._pick_folder_dialog:
self._pick_folder_dialog.destroy()
self._pick_folder_dialog = FilePickerDialog(
"Save As...",
allow_multi_selection=False,
apply_button_label="Save",
click_apply_handler=self.__menu_save_apply_filename,
item_filter_options=["ACTIVITY file (*.activity)", "JSON file (*.json)"],
item_filter_fn=self.__menu_filter_files,
current_filename=self._current_filename,
current_directory=self._current_dir,
)
def save(self, filename: str):
"""Save the current model to external file"""
data = self.get_save_data()
if not data:
return
payload = bytes(json.dumps(data, sort_keys=True, indent=4).encode("utf-8"))
if not payload:
return
# Save to the file
result = omni.client.write_file(filename, payload)
if result != omni.client.Result.OK:
carb.log_error(f"[omni.activity.ui] The activity cannot be written to {filename}, error code: {result}")
return
carb.log_info(f"[omni.activity.ui] The activity saved to {filename}")
def load(self, filename: str):
"""Load the model from the file"""
result, _, content = omni.client.read_file(filename)
if result != omni.client.Result.OK:
carb.log_error(f"[omni.activity.ui] Can't read the activity file {filename}, error code: {result}")
return
data = json.loads(memoryview(content).tobytes().decode("utf-8"))
self.load_data(data)
| 5,434 | Python | 35.722973 | 122 | 0.593669 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_window.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ActivityWindow"]
from .activity_chart import ActivityChart
from .style import activity_window_style
import omni.ui as ui
LABEL_WIDTH = 120
SPACING = 4
class ActivityWindow(ui.Window):
"""The class that represents the window"""
def __init__(self, title: str, model, delegate=None, activity_menu=None, **kwargs):
super().__init__(title, raster_policy=ui.RasterPolicy.NEVER, **kwargs)
self.__chart = None
# Apply the style to all the widgets of this window
self.frame.style = activity_window_style
self.deferred_dock_in("Content", ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE)
# Set the function that is called to build widgets when the window is
# visible
self.frame.set_build_fn(lambda: self.__build(model, activity_menu))
def destroy(self):
if self.__chart:
self.__chart.destroy()
# It will destroy all the children
super().destroy()
def _menu_new(self, model=None):
if self.__chart:
self.__chart.new(model)
def get_data(self):
if self.__chart:
return self.__chart.save_for_report()
return None
def __build(self, model, activity_menu):
"""
The method that is called to build all the UI once the window is
visible.
"""
self.__chart = ActivityChart(model, activity_menu)
| 1,828 | Python | 31.087719 | 87 | 0.664114 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_progress_bar.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ActivityProgressBarWindow"]
import omni.ui as ui
from omni.ui import scene as sc
import omni.kit.app
import asyncio
from functools import partial
import math
import pathlib
import weakref
from .style import progress_window_style
from .activity_tree_delegate import ActivityProgressTreeDelegate
from .activity_menu import ActivityMenuOptions
from .activity_progress_model import ActivityProgressModel
TIMELINE_WINDOW_NAME = "Activity Timeline"
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
def convert_seconds_to_hms(sec):
result = ""
rest_sec = sec
h = math.floor(rest_sec / 3600)
if h > 0:
if h < 10:
result += "0"
result += str(h) + ":"
rest_sec -= h * 3600
else:
result += "00:"
m = math.floor(rest_sec / 60)
if m > 0:
if m < 10:
result += "0"
result += str(m) + ":"
rest_sec -= m * 60
else:
result += "00:"
if rest_sec < 10:
result += "0"
result += str(rest_sec)
return result
class Spinner(sc.Manipulator):
def __init__(self, event):
super().__init__()
self.__deg = 0
self.__spinning_event = event
def on_build(self):
self.invalidate()
if self.__spinning_event.is_set():
self.__deg = self.__deg % 360
transform = sc.Matrix44.get_rotation_matrix(0, 0, -self.__deg, True)
with sc.Transform(transform=transform):
sc.Image(f"{EXTENSION_FOLDER_PATH}/data/progress.svg", width=2, height=2)
self.__deg += 3
class ProgressBarWidget:
def __init__(self, model=None, activity_menu=None):
self.__model = None
self.__subscription = None
self._finished_ui_build = False
self.__frame = ui.Frame(build_fn=partial(self.__build, model))
self.__frame.style = progress_window_style
# for the menu
self._activity_menu_option = activity_menu
# for the timer
self._start_event = asyncio.Event()
self._stop_event = asyncio.Event()
self.spinner = None
self._progress_stack = None
def reset_timer(self):
if self._finished_ui_build:
self.total_time.text = "00:00:00"
self._start_event.set()
def stop_timer(self):
self._start_event.clear()
def new(self, model=None):
"""Recreate the models and start recording"""
self.__model = model
self.__subscription = None
self._start_event.clear()
if self.__model:
self.__subscription = self.__model.subscribe_item_changed_fn(self._model_changed)
# this is for the add on widget, no need to update the model if the ui is not ready
if self._finished_ui_build:
self.update_by_model(self.__model)
self.total_time.text = convert_seconds_to_hms(model.duration)
self.__tree.model = self.__model
def destroy(self):
self.__model = None
self.__subscription = None
self.__tree_delegate = None
self.__tree = None
self.usd_number = None
self.material_number = None
self.texture_number = None
self.total_number = None
self.usd_progress = None
self.material_progress = None
self.texture_progress = None
self.total_progress = None
self.current_event = None
self.total_progress_text = None
self._stop_event.set()
def show_stack_from_idx(self, idx):
if idx == 0:
self._activity_stack.visible = False
self._progress_stack.visible = True
elif idx == 1:
self._activity_stack.visible = True
self._progress_stack.visible = False
def update_USD(self, model):
if self._progress_stack:
self.usd_number.text = str(model.usd_loaded_sum) + "/" + str(model.usd_sum)
self.usd_progress.set_value(model.usd_progress)
self.usd_size.text = str(round(model.usd_size, 2)) + " MB"
self.usd_speed.text = str(round(model.usd_speed, 2)) + " MB/sec"
def update_textures(self, model):
if self._progress_stack:
self.texture_number.text = str(model.texture_loaded_sum) + "/" + str(model.texture_sum)
self.texture_progress.set_value(model.texture_progress)
self.texture_size.text = str(round(model.texture_size, 2)) + " MB"
self.texture_speed.text = str(round(model.texture_speed, 2)) + " MB/sec"
def update_materials(self, model):
if self._progress_stack:
self.material_number.text = str(model.material_loaded_sum) + "/" + str(model.material_sum)
self.material_progress.set_value(model.material_progress)
def update_total(self, model):
if self._progress_stack:
self.total_number.text = "Total: " + str(model.total_loaded_sum) + "/" + str(model.total_sum)
self.total_progress.set_value(model.total_progress)
self.total_progress_text.text = f"{model.total_progress * 100 :.2f}%"
if model.latest_item:
self.current_event.text = "Loading " + model.latest_item
elif model.latest_item is None:
self.current_event.text = "Done"
else:
self.current_event.text = ""
def update_by_model(self, model):
self.update_USD(model)
self.update_textures(model)
self.update_materials(model)
self.update_total(model)
if self._progress_stack:
self.total_time.text = convert_seconds_to_hms(model.duration)
def _model_changed(self, model, item):
self.update_by_model(model)
def progress_stack(self):
self._progress_stack = ui.VStack()
with self._progress_stack:
ui.Spacer(height=15)
with ui.HStack():
ui.Spacer(width=20)
with ui.VStack(spacing=4):
with ui.HStack(height=30):
ui.ImageWithProvider(style_type_name_override="Icon", name="USD", width=23)
ui.Label(" USD", width=50)
ui.Spacer()
self.usd_size = ui.Label("0 MB", alignment=ui.Alignment.RIGHT_CENTER, width=120)
ui.Spacer()
self.usd_speed = ui.Label("0 MB/sec", alignment=ui.Alignment.RIGHT_CENTER, width=140)
with ui.HStack(height=22):
self.usd_number = ui.Label("0/0", width=60, alignment=ui.Alignment.RIGHT_CENTER)
ui.Spacer(width=10)
self.usd_progress = ui.ProgressBar(name="USD").model
with ui.HStack(height=30):
ui.ImageWithProvider(style_type_name_override="Icon", name="material", width=20)
ui.Label(" Material", width=50)
ui.Spacer()
self.material_size = ui.Label("", alignment=ui.Alignment.RIGHT_CENTER, width=120)
ui.Spacer()
self.material_speed = ui.Label("", alignment=ui.Alignment.RIGHT_CENTER, width=140)
with ui.HStack(height=22):
self.material_number = ui.Label("0/0", width=60, alignment=ui.Alignment.RIGHT_CENTER)
ui.Spacer(width=10)
self.material_progress = ui.ProgressBar(height=22, name="material").model
with ui.HStack(height=30):
ui.ImageWithProvider(style_type_name_override="Icon", name="texture", width=20)
ui.Label(" Texture", width=50)
ui.Spacer()
self.texture_size = ui.Label("0 MB", alignment=ui.Alignment.RIGHT_CENTER, width=120)
ui.Spacer()
self.texture_speed = ui.Label("0 MB/sec", alignment=ui.Alignment.RIGHT_CENTER, width=140)
with ui.HStack(height=22):
self.texture_number = ui.Label("0/0", width=60, alignment=ui.Alignment.RIGHT_CENTER)
ui.Spacer(width=10)
self.texture_progress = ui.ProgressBar(height=22, name="texture").model
ui.Spacer(width=20)
def activity_stack(self):
self._activity_stack = ui.VStack()
self.__tree_delegate = ActivityProgressTreeDelegate()
with self._activity_stack:
ui.Spacer(height=10)
self.__tree = ui.TreeView(
self.__model,
delegate=self.__tree_delegate,
root_visible=False,
header_visible=True,
column_widths=[ui.Fraction(1), 50, 50],
columns_resizable=True,
)
async def infloop(self):
while not self._stop_event.is_set():
await asyncio.sleep(1)
if self._stop_event.is_set():
break
if self._start_event.is_set():
# cant use duration += 1 since when the ui is stuck, the function is not called, so we will get the
# duration wrong
if self.__model:
self.total_time.text = convert_seconds_to_hms(self.__model.duration)
def __build(self, model):
"""
The method that is called to build all the UI once the window is visible.
"""
if self._activity_menu_option:
self._options_menu = ui.Menu("Options")
with self._options_menu:
ui.MenuItem("Show Timeline", triggered_fn=lambda: ui.Workspace.show_window(TIMELINE_WINDOW_NAME))
ui.Separator()
ui.MenuItem("Open...", triggered_fn=self._activity_menu_option.menu_open)
ui.MenuItem("Save...", triggered_fn=self._activity_menu_option.menu_save)
self._collection = ui.RadioCollection()
with ui.VStack():
with ui.HStack(height=30):
ui.Spacer()
tab0 = ui.RadioButton(
text="Progress Bar",
width=0,
radio_collection=self._collection)
ui.Spacer(width=12)
with ui.VStack(width=3):
ui.Spacer()
ui.Rectangle(name="separator", height=16)
ui.Spacer()
ui.Spacer(width=12)
tab1 = ui.RadioButton(
text="Activity",
width=0,
radio_collection=self._collection)
ui.Spacer()
if self._activity_menu_option:
ui.Button(name="options", width=20, height=20, clicked_fn=lambda: self._options_menu.show())
with ui.HStack():
ui.Spacer(width=3)
with ui.ScrollingFrame():
with ui.ZStack():
self.progress_stack()
self.activity_stack()
self._activity_stack.visible = False
ui.Spacer(width=3)
tab0.set_clicked_fn(lambda: self.show_stack_from_idx(0))
tab1.set_clicked_fn(lambda: self.show_stack_from_idx(1))
with ui.HStack(height=70):
ui.Spacer(width=20)
with ui.VStack(width=20):
ui.Spacer(height=12)
with sc.SceneView().scene:
self.spinner = Spinner(self._start_event)
ui.Spacer(width=10)
with ui.VStack():
with ui.HStack(height=30):
self.total_number = ui.Label("Total: 0/0")
self.total_time = ui.Label("00:00:00", width=0, alignment=ui.Alignment.RIGHT_CENTER)
with ui.ZStack(height=22):
self.total_progress = ui.ProgressBar(name="progress").model
with ui.HStack():
ui.Spacer(width=4)
self.current_event = ui.Label("", elided_text=True)
self.total_progress_text = ui.Label("0.00%", width=0, alignment=ui.Alignment.RIGHT_CENTER)
ui.Spacer(width=4)
asyncio.ensure_future(self.infloop())
ui.Spacer(width=35)
self._finished_ui_build = True
# update ui with model, so that we keep tracking of the model even when the widget is not shown
if model:
self.new(model)
if model.start_loading and not model.finish_loading:
self._start_event.set()
class ActivityProgressBarWindow(ui.Window):
"""The class that represents the window"""
def __init__(self, title: str, model, delegate=None, activity_menu=None, **kwargs):
super().__init__(title, raster_policy=ui.RasterPolicy.NEVER, **kwargs)
self.__widget = None
self.deferred_dock_in("Property", ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE)
self.frame.set_build_fn(lambda: self.__build(model, activity_menu))
def destroy(self):
if self.__widget:
self.__widget.destroy()
# It will destroy all the children
super().destroy()
def __build(self, model, activity_menu):
self.__widget = ProgressBarWidget(model, activity_menu=activity_menu)
def new(self, model):
if self.__widget:
self.__widget.new(model)
def start_timer(self):
if self.__widget:
self.__widget.reset_timer()
def stop_timer(self):
if self.__widget:
self.__widget.stop_timer()
| 14,257 | Python | 38.826816 | 118 | 0.553553 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/activity_report.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ActivityReportWindow"]
import asyncio
import omni.kit.app
import omni.ui as ui
from omni.ui import color as cl
import math
import pathlib
from typing import Callable
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
)
def exec_after_redraw(callback: Callable, wait_frames: int = 2):
async def exec_after_redraw_async(callback: Callable, wait_frames: int):
# Wait some frames before executing
for _ in range(wait_frames):
await omni.kit.app.get_app().next_update_async()
callback()
asyncio.ensure_future(exec_after_redraw_async(callback, wait_frames))
class ReportItem(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, text, value, size, parent):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
self.value_model = ui.SimpleFloatModel(value)
self.size_model = ui.SimpleFloatModel(size)
self.parent = parent
self.children = []
self.filtered_children = []
class ReportModel(ui.AbstractItemModel):
"""
Represents the model for the report
"""
def __init__(self, data, treeview_size):
super().__init__()
self._children = []
self._parents = []
self.root = None
self.load(data)
self._sized_children = self._children[:treeview_size]
def destroy(self):
self._children = []
self._parents = []
self.root = None
self._sized_children = []
def load(self, data):
if data and "root" in data:
self.root = ReportItem("root", 0, 0, None)
self.set_data(data["root"], self.root)
# sort the data with duration
self._children.sort(key=lambda item: item.value_model.get_value_as_float(), reverse=True)
def set_data(self, data, parent):
parent_name = parent.name_model.as_string
for child in data["children"]:
size = child["size"] if "size" in child else 0
item = ReportItem(child["name"], child["duration"], size, parent)
# put the item we cares to the self._children
if parent_name in ["Resolve", "Read", "Meshes", "Textures", "Materials"]:
self._children.append(item)
parent.children.append(item)
self.set_data(child, item)
def get_item_children(self, item):
if item is not None:
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return.
return item.filtered_children
# clear previous results
for p in self._parents:
p.filtered_children = []
self._parents = []
for child in self._sized_children:
parent = child.parent
parent.filtered_children.append(child)
if parent not in self._parents:
self._parents.append(parent)
return self._parents
def get_item_value_model_count(self, item):
"""The number of columns"""
return 2
def get_item_value_model(self, item, column_id):
if column_id == 0:
return item.name_model
else:
return item.value_model
class ReportTreeDelegate(ui.AbstractItemDelegate):
def __init__(self):
super().__init__()
def build_branch(self, model, item, column_id, level, expanded=True):
"""Create a branch widget that opens or closes subtree"""
if column_id == 0:
with ui.HStack(width=20 * (level + 1), height=0):
ui.Spacer()
if model.can_item_have_children(item):
# Draw the +/- icon
image_name = "Minus" if expanded else "Plus"
ui.ImageWithProvider(
f"{EXTENSION_FOLDER_PATH}/data/{image_name}.svg",
width=10,
height=10,
)
ui.Spacer(width=5)
def build_header(self, column_id: int):
headers = ["Name", "Duration (HH:MM:SS)"]
return ui.Label(headers[column_id], height=22)
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per column per item"""
def convert_seconds_to_hms(sec):
result = ""
rest_sec = sec
h = math.floor(rest_sec / 3600)
if h > 0:
if h < 10:
result += "0"
result += str(h) + ":"
rest_sec -= h * 3600
else:
result += "00:"
m = math.floor(rest_sec / 60)
if m > 0:
if m < 10:
result += "0"
result += str(m) + ":"
rest_sec -= m * 60
else:
result += "00:"
if rest_sec < 10:
result += "0"
result += str(rest_sec)
return result
if column_id == 1 and level == 1:
return
value_model = model.get_item_value_model(item, column_id)
value = value_model.as_string
if column_id == 0 and level == 1:
value += " (" + str(len(model.get_item_children(item))) + ")"
elif column_id == 1:
value = convert_seconds_to_hms(value_model.as_int)
with ui.VStack(height=20):
ui.Label(value, elided_text=True)
class ActivityReportWindow(ui.Window):
"""The class that represents the window"""
def __init__(self, title: str, delegate=None, **kwargs):
super().__init__(title, raster_policy=ui.RasterPolicy.NEVER, **kwargs)
self.__expand_task = None
self._current_path = kwargs.pop("path", "")
self._data = kwargs.pop("data", "")
# Set the function that is called to build widgets when the window is visible
self.frame.set_build_fn(self.__build)
def destroy(self):
# It will destroy all the children
super().destroy()
if self.__expand_task is not None:
self.__expand_task.cancel()
self.__expand_task = None
if self._report_model:
self._report_model.destroy()
self._report_model = None
def __build(self):
"""
The method that is called to build all the UI once the window is
visible.
"""
treeview_size = 10
def set_treeview_size(model, size):
model._sized_children = model._children[:size]
model._item_changed(None)
with ui.VStack():
ui.Label(f"Report for opening {self._current_path}", height=70, alignment=ui.Alignment.CENTER)
self._report_model = ReportModel(self._data, treeview_size)
ui.Line(height=12, style={"color": cl.red})
root_children = []
if self._report_model.root:
root_children = self._report_model.root.children
file_children = []
# time
for child in root_children:
name = child.name_model.as_string
if name in ["USD", "Meshes", "Textures", "Materials"]:
file_children += [child]
with ui.HStack(height=0):
ui.Label(f"Total Time of {name}")
ui.Label(f" {child.value_model.as_string} ")
color = cl.red if child == root_children[-1] else cl.black
ui.Line(height=12, style={"color": color})
# number
for file in file_children:
with ui.HStack(height=0):
name = file.name_model.as_string.split(" ")[0]
ui.Label(f"Total Number of {name}")
ui.Label(f" {len(file.children)} ")
color = cl.red if file == file_children[-1] else cl.black
ui.Line(height=12, style={"color": color})
# size
for file in file_children:
size = 0
for c in file.children:
s = c.size_model.as_float
if s > 0:
size += s
with ui.HStack(height=0):
name = file.name_model.as_string.split(" ")[0]
ui.Label(f"Total Size of {name} (MB)")
ui.Label(f" {size * 0.000001} ")
color = cl.red if file == file_children[-1] else cl.black
ui.Line(height=12, style={"color": color})
ui.Spacer(height=10)
# field which can change the size of the treeview
with ui.HStack(height=0):
ui.Label("The top ", width=0)
field = ui.IntField(width=60)
field.model.set_value(treeview_size)
ui.Label(f" most time consuming task{'s' if treeview_size > 1 else ''}")
ui.Spacer(height=3)
# treeview
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
style_type_name_override="TreeView",
style={"Field": {"background_color": cl.black}},
):
self._name_value_delegate = ReportTreeDelegate()
self.treeview = ui.TreeView(
self._report_model,
delegate=self._name_value_delegate,
root_visible=False,
header_visible=True,
column_widths=[ui.Fraction(1), 130],
columns_resizable=True,
style={"TreeView.Item": {"margin": 4}},
)
field.model.add_value_changed_fn(lambda m: set_treeview_size(self._report_model, m.get_value_as_int()))
def expand_collections():
for item in self._report_model.get_item_children(None):
self.treeview.set_expanded(item, True, False)
# Finally, expand collection nodes in treeview after UI becomes ready
self.__expand_task = exec_after_redraw(expand_collections, wait_frames=2)
| 10,714 | Python | 36.465035 | 119 | 0.541628 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/tests/__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 | 463 | Python | 50.55555 | 76 | 0.812095 |
omniverse-code/kit/exts/omni.activity.ui/omni/activity/ui/tests/test_window.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["TestWindow"]
import json
import unittest
from omni.activity.ui.activity_extension import get_instance
from omni.activity.ui.activity_menu import ActivityMenuOptions
from omni.activity.ui import ActivityWindow, ActivityWindowExtension, ActivityProgressBarWindow
from omni.activity.ui.activity_model import ActivityModelRealtime, ActivityModelDumpForProgress
from omni.activity.ui.activity_progress_model import ActivityProgressModel
from omni.activity.ui.activity_report import ActivityReportWindow
from omni.ui.tests.test_base import OmniUiTest
import omni.kit.ui_test as ui_test
from omni.kit.ui_test.input import emulate_mouse, emulate_mouse_slow_move, human_delay
from omni.ui import color as cl
from ..style import get_shade_from_name
from pathlib import Path
from unittest.mock import MagicMock
import omni.client
import omni.usd
import omni.kit.app
import omni.kit.test
import math
from carb.input import KeyboardInput, MouseEventType
EXTENSION_FOLDER_PATH = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__))
TEST_DATA_PATH = EXTENSION_FOLDER_PATH.joinpath("data/tests")
TEST_FILE_NAME = "test.activity"
TEST_SMALL_FILE_NAME = "test_small.activity"
def calculate_duration(events):
duration = 0
for i in range(0, len(events), 2):
if events[i]['type'] == 'BEGAN' and events[i+1]['type'] == 'ENDED':
duration += (events[i+1]['time'] - events[i]['time']) / 10000000
return duration
def add_duration(node):
total_duration = 0
if 'children' in node:
for child in node['children']:
child_duration = add_duration(child)
total_duration += child_duration
if 'events' in child and child['events']:
event_duration = calculate_duration(child['events'])
child['duration'] = event_duration
total_duration += event_duration
node['duration'] = total_duration
return total_duration
def process_json(json_data):
add_duration(json_data['root'])
return json_data
class TestWindow(OmniUiTest):
async def load_data(self, file_name):
filename = TEST_DATA_PATH.joinpath(file_name)
result, _, content = omni.client.read_file(filename.as_posix())
self.assertEqual(result, omni.client.Result.OK)
self._data = json.loads(memoryview(content).tobytes().decode("utf-8"))
async def test_general(self):
"""Testing general look of section"""
menu = ActivityMenuOptions()
model = ActivityModelRealtime()
window = ActivityWindow("Test", model=model, activity_menu=menu)
await omni.kit.app.get_app().next_update_async()
await self.docked_test_window(
window=window,
width=300,
height=385,
)
# Wait for images
for _ in range(20):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="window.png")
self.assertIsNotNone(window.get_data())
window.destroy()
model.destroy()
menu.destroy()
async def test_activity_chart_scroll(self):
menu = ActivityMenuOptions()
model = ActivityModelRealtime()
window = ActivityWindow("Test", model=model, activity_menu=menu)
await omni.kit.app.get_app().next_update_async()
await self.docked_test_window(
window=window,
width=300,
height=385,
block_devices=False,
)
for _ in range(120):
await omni.kit.app.get_app().next_update_async()
self.assertEqual(100, math.floor(window._ActivityWindow__chart._ActivityChart__zoom_level))
await ui_test.emulate_mouse_move(ui_test.Vec2(180, 200), human_delay_speed=3)
await ui_test.emulate_mouse_scroll(ui_test.Vec2(0, 50), human_delay_speed=3)
for _ in range(20):
await omni.kit.app.get_app().next_update_async()
self.assertEqual(101, math.floor(window._ActivityWindow__chart._ActivityChart__zoom_level))
await self.finalize_test_no_image()
# Move outside the window
await ui_test.emulate_mouse_move(ui_test.Vec2(400, 400), human_delay_speed=3)
window.destroy()
model.destroy()
menu.destroy()
async def test_activity_chart_drag(self):
menu = ActivityMenuOptions()
model = ActivityModelRealtime()
window = ActivityWindow("Test", model=model, activity_menu=menu)
await omni.kit.app.get_app().next_update_async()
await self.docked_test_window(
window=window,
width=300,
height=385,
block_devices=False,
)
for _ in range(20):
await omni.kit.app.get_app().next_update_async()
start_pos = ui_test.Vec2(180, 50)
end_pos = ui_test.Vec2(230, 50)
human_delay_speed = 2
await ui_test.emulate_mouse_move(start_pos, human_delay_speed=human_delay_speed)
await emulate_mouse(MouseEventType.MIDDLE_BUTTON_DOWN)
await human_delay(human_delay_speed)
await emulate_mouse_slow_move(start_pos, end_pos, human_delay_speed=human_delay_speed)
await emulate_mouse(MouseEventType.MIDDLE_BUTTON_UP)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="test_activity_chart_drag.png")
# Move outside the window
await ui_test.emulate_mouse_move(ui_test.Vec2(400, 400), human_delay_speed=3)
window.destroy()
model.destroy()
menu.destroy()
async def test_selection(self):
menu = ActivityMenuOptions()
model = ActivityModelRealtime()
window = ActivityWindow("Test", model=model, activity_menu=menu)
await omni.kit.app.get_app().next_update_async()
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
self.assertIsNone(model.selection)
model.selection = 2
self.assertEqual(model.selection, 2)
window.destroy()
model.destroy()
menu.destroy()
async def test_activity_chart_pan(self):
menu = ActivityMenuOptions()
model = ActivityModelRealtime()
window = ActivityWindow("Test", model=model, activity_menu=menu)
await omni.kit.app.get_app().next_update_async()
await self.docked_test_window(
window=window,
width=300,
height=385,
block_devices=False,
)
for _ in range(20):
await omni.kit.app.get_app().next_update_async()
start_pos = ui_test.Vec2(180, 50)
end_pos = ui_test.Vec2(230, 50)
human_delay_speed = 2
await ui_test.emulate_mouse_move(start_pos, human_delay_speed=human_delay_speed)
await emulate_mouse(MouseEventType.RIGHT_BUTTON_DOWN)
await human_delay(human_delay_speed)
await emulate_mouse_slow_move(start_pos, end_pos, human_delay_speed=human_delay_speed)
await emulate_mouse(MouseEventType.RIGHT_BUTTON_UP)
for _ in range(20):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="test_activity_chart_pan.png")
# Move outside the window
await ui_test.emulate_mouse_move(ui_test.Vec2(400, 400), human_delay_speed=3)
window.destroy()
model.destroy()
menu.destroy()
async def test_activities_tab(self):
menu = ActivityMenuOptions()
model = ActivityModelRealtime()
window = ActivityWindow("Test", model=model, activity_menu=menu)
await omni.kit.app.get_app().next_update_async()
await self.docked_test_window(
window=window,
width=300,
height=385,
block_devices=False,
)
for _ in range(20):
await omni.kit.app.get_app().next_update_async()
human_delay_speed = 10
# Click on Activities tab
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(180, 15), human_delay_speed=2)
await human_delay(human_delay_speed)
# Click on Timeline tab
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(100, 15), human_delay_speed=2)
await human_delay(human_delay_speed)
# Click on Activities tab
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(180, 15), human_delay_speed=2)
for _ in range(20):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="test_activities_tab.png")
# Move outside the window
await ui_test.emulate_mouse_move(ui_test.Vec2(400, 400), human_delay_speed=3)
window.destroy()
model.destroy()
menu.destroy()
async def test_activity_menu_open(self):
ext = get_instance()
menu = ActivityMenuOptions(load_data=ext.load_data)
model = ActivityModelRealtime()
window = ActivityWindow("Test", model=model, activity_menu=menu)
window_width = 300
await omni.kit.app.get_app().next_update_async()
await self.docked_test_window(
window=window,
width=window_width,
height=385,
block_devices=False,
)
for _ in range(20):
await omni.kit.app.get_app().next_update_async()
human_delay_speed = 5
# Click on Activity hamburger menu
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(window_width-20, 15), human_delay_speed=2)
await human_delay(human_delay_speed)
# Click on Open menu option
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(window_width-20, 30), human_delay_speed=2)
await human_delay(human_delay_speed)
# Cancel Open dialog
await ui_test.emulate_keyboard_press(KeyboardInput.ESCAPE)
await human_delay(human_delay_speed)
# Do it all again to cover the case where it was open before, and has to be destroyed
# Click on Activity hamburger menu
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(window_width-20, 15), human_delay_speed=2)
await human_delay(human_delay_speed)
# Click on Open menu option
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(window_width-20, 30), human_delay_speed=2)
await human_delay(human_delay_speed)
# Cancel Open dialog
await ui_test.emulate_keyboard_press(KeyboardInput.ESCAPE)
await human_delay(human_delay_speed)
# simulate failure first
menu._ActivityMenuOptions__menu_open_apply_filename("broken_test", str(TEST_DATA_PATH))
await human_delay(human_delay_speed)
self.assertIsNone(menu._current_filename)
# simulate opening the file through file dialog
menu._ActivityMenuOptions__menu_open_apply_filename(TEST_SMALL_FILE_NAME, str(TEST_DATA_PATH))
await human_delay(human_delay_speed)
self.assertIsNotNone(menu._current_filename)
await self.finalize_test_no_image()
# Move outside the window
await ui_test.emulate_mouse_move(ui_test.Vec2(window_width+20, 400), human_delay_speed=3)
ext = None
window.destroy()
model.destroy()
menu.destroy()
async def test_activity_menu_save(self):
ext = get_instance()
# await self.load_data(TEST_SMALL_FILE_NAME)
menu = ActivityMenuOptions(get_save_data=ext.get_save_data)
model = ActivityModelRealtime()
window = ActivityWindow("Test", model=model, activity_menu=menu)
window_width = 300
await omni.kit.app.get_app().next_update_async()
await self.docked_test_window(
window=window,
width=window_width,
height=385,
block_devices=False,
)
for _ in range(20):
await omni.kit.app.get_app().next_update_async()
human_delay_speed = 5
# Click on Activity hamburger menu
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(window_width-20, 15), human_delay_speed=2)
await human_delay(human_delay_speed)
# Click on Save menu option
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(window_width-20, 50), human_delay_speed=2)
await human_delay(human_delay_speed)
# Cancel Open dialog
await ui_test.emulate_keyboard_press(KeyboardInput.ESCAPE)
await human_delay(human_delay_speed)
# Do it all again to cover the case where it was open before, and has to be destroyed
# Click on Activity hamburger menu
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(window_width-20, 15), human_delay_speed=2)
await human_delay(human_delay_speed)
# Click on Save menu option
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(window_width-20, 50), human_delay_speed=2)
await human_delay(human_delay_speed)
# Cancel Open dialog
await ui_test.emulate_keyboard_press(KeyboardInput.ESCAPE)
await human_delay(human_delay_speed)
# Create a mock for omni.client.write_file, so we don't have to actually write out to a file
mock_write_file = MagicMock()
# Set the return value of the mock to omni.client.Result.OK
mock_write_file.return_value = omni.client.Result.OK
# Replace the actual omni.client.write_file with the mock
omni.client.write_file = mock_write_file
# simulate opening the file through file dialog
menu._ActivityMenuOptions__menu_save_apply_filename("test", str(TEST_DATA_PATH))
await human_delay(human_delay_speed)
ext._save_current_activity()
self.assertTrue(ext._ActivityWindowExtension__model)
await self.finalize_test_no_image()
# Move outside the window
await ui_test.emulate_mouse_move(ui_test.Vec2(window_width+20, 400), human_delay_speed=3)
mock_write_file.reset_mock()
ext = None
window.destroy()
model.destroy()
menu.destroy()
async def test_activity_report(self):
"""Testing activity report window"""
await self.load_data(TEST_SMALL_FILE_NAME)
# Adding "duration" data for each child, as the test.activity files didn't already have that
self._data = process_json(self._data)
window = ActivityReportWindow("TestReport", path=TEST_SMALL_FILE_NAME, data=self._data)
await omni.kit.app.get_app().next_update_async()
await self.docked_test_window(
window=window,
width=600,
height=450,
)
# Wait for images
for _ in range(120):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="report_window.png")
window.destroy()
window = None
async def test_progress_window(self):
"""Test progress window with loaded activity"""
await self.load_data(TEST_FILE_NAME)
loaded_model = ActivityModelDumpForProgress(data=self._data)
model = ActivityProgressModel(source=loaded_model)
menu = ActivityMenuOptions()
window = ActivityProgressBarWindow(ActivityWindowExtension.PROGRESS_WINDOW_NAME, model=model, activity_menu=menu)
model.finished_loading()
await omni.kit.app.get_app().next_update_async()
await self.docked_test_window(
window=window,
width=415,
height=355,
block_devices=False,
)
# Wait for images
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
human_delay_speed = 10
window.start_timer()
await human_delay(30)
window.stop_timer()
await human_delay(5)
# Click on Activities tab
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(250, 15), human_delay_speed=2)
await human_delay(human_delay_speed)
# Click on Timeline tab
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(180, 15), human_delay_speed=2)
await human_delay(human_delay_speed)
await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="progress_window.png", threshold=.015)
self.assertIsNotNone(model.get_data())
report_data = loaded_model.get_report_data()
data = loaded_model.get_data()
self.assertIsNotNone(report_data)
self.assertGreater(len(data), len(report_data))
loaded_model.destroy()
model.destroy()
menu.destroy()
window.destroy()
async def test_chart_window_bars(self):
ext = get_instance()
ext.show_window(None, True)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
width = 415
height = 355
await self.docked_test_window(
window=ext._timeline_window,
width=width,
height=height,
block_devices=False,
)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
ext._timeline_window._ActivityWindow__chart._activity_menu_option._ActivityMenuOptions__menu_open_apply_filename(TEST_FILE_NAME, str(TEST_DATA_PATH))
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="chart_window_bars.png")
ext.show_window(None, False)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
ext = None
async def test_chart_window_activities(self):
ext = get_instance()
ext.show_window(None, True)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
width = 415
height = 355
await self.docked_test_window(
window=ext._timeline_window,
width=width,
height=height,
block_devices=False,
)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
ext._timeline_window._ActivityWindow__chart._activity_menu_option._ActivityMenuOptions__menu_open_apply_filename(TEST_FILE_NAME, str(TEST_DATA_PATH))
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
# Click on Activities tab
await ui_test.emulate_mouse_move_and_click(ui_test.Vec2(240, 15), human_delay_speed=2)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="chart_window_activities.png")
ext.show_window(None, False)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
ext = None
async def test_extension_start_stop(self):
# Disabling this part in case it is causing crashing in 105.1
# ext = get_instance()
# ext.show_window(None, True)
# for _ in range(10):
# await omni.kit.app.get_app().next_update_async()
manager = omni.kit.app.get_app().get_extension_manager()
ext_id = "omni.activity.ui"
self.assertTrue(ext_id)
self.assertTrue(manager.is_extension_enabled(ext_id))
# ext = None
manager.set_extension_enabled(ext_id, False)
for _ in range(5):
await omni.kit.app.get_app().next_update_async()
self.assertTrue(not manager.is_extension_enabled(ext_id))
manager.set_extension_enabled(ext_id, True)
for _ in range(5):
await omni.kit.app.get_app().next_update_async()
self.assertTrue(manager.is_extension_enabled(ext_id))
async def test_extension_level_progress_bar(self):
ext = get_instance()
ext._show_progress_window()
await human_delay(5)
ext.show_progress_bar(None, False)
await human_delay(5)
ext.show_progress_bar(None, True)
await human_delay(5)
self.assertTrue(ext._is_progress_visible())
ext.show_progress_bar(None, False)
ext = None
async def test_extension_level_window(self):
ext = get_instance()
await human_delay(5)
ext.show_window(None, False)
await human_delay(5)
ext.show_window(None, True)
await human_delay(5)
self.assertTrue(ext._timeline_window.visible)
ext.show_window(None, False)
ext = None
@unittest.skip("Not working in 105.1 as it tests code that is not available there.")
async def test_extension_level_commands(self):
await self.create_test_area(width=350, height=300)
ext = get_instance()
await human_delay(5)
ext._on_command("AddReference", kwargs={})
await human_delay(5)
ext._on_command("CreatePayload", kwargs={})
await human_delay(5)
ext._on_command("CreateSublayer", kwargs={})
await human_delay(5)
ext._on_command("ReplacePayload", kwargs={})
await human_delay(5)
ext._on_command("ReplaceReference", kwargs={})
await human_delay(5)
self.assertTrue(ext._ActivityWindowExtension__activity_started)
# Create a mock event object
event = MagicMock()
event.type = int(omni.usd.StageEventType.ASSETS_LOADED)
ext._on_stage_event(event)
self.assertFalse(ext._ActivityWindowExtension__activity_started)
event.type = int(omni.usd.StageEventType.OPENING)
ext._on_stage_event(event)
self.assertTrue(ext._ActivityWindowExtension__activity_started)
event.type = int(omni.usd.StageEventType.OPEN_FAILED)
ext._on_stage_event(event)
self.assertFalse(ext._ActivityWindowExtension__activity_started)
# This method doesn't exist in 105.1
ext.show_asset_load_prompt()
await human_delay(20)
self.assertTrue(ext._asset_prompt.is_visible())
ext._asset_prompt.set_text("Testing, testing")
await human_delay(20)
await self.finalize_test(golden_img_dir=TEST_DATA_PATH, golden_img_name="asset_load_prompt.png")
ext.hide_asset_load_prompt()
event.reset_mock()
ext = None
async def test_styles(self):
# full name comparisons
self.assertEqual(get_shade_from_name("USD"), cl("#2091D0"))
self.assertEqual(get_shade_from_name("Read"), cl("#1A75A8"))
self.assertEqual(get_shade_from_name("Resolve"), cl("#16648F"))
self.assertEqual(get_shade_from_name("Stage"), cl("#d43838"))
self.assertEqual(get_shade_from_name("Render Thread"), cl("#d98927"))
self.assertEqual(get_shade_from_name("Execute"), cl("#A2661E"))
self.assertEqual(get_shade_from_name("Post Sync"), cl("#626262"))
self.assertEqual(get_shade_from_name("Textures"), cl("#4FA062"))
self.assertEqual(get_shade_from_name("Load"), cl("#3C784A"))
self.assertEqual(get_shade_from_name("Queue"), cl("#31633D"))
self.assertEqual(get_shade_from_name("Materials"), cl("#8A6592"))
self.assertEqual(get_shade_from_name("Compile"), cl("#5D4462"))
self.assertEqual(get_shade_from_name("Create Shader Variations"), cl("#533D58"))
self.assertEqual(get_shade_from_name("Load Textures"), cl("#4A374F"))
self.assertEqual(get_shade_from_name("Meshes"), cl("#626262"))
self.assertEqual(get_shade_from_name("Ray Tracing Pipeline"), cl("#8B8000"))
# startswith comparisons
self.assertEqual(get_shade_from_name("Opening_test"), cl("#A12A2A"))
# endswith comparisons
self.assertEqual(get_shade_from_name("test.usda"), cl("#13567B"))
self.assertEqual(get_shade_from_name("test.hdr"), cl("#34A24E"))
self.assertEqual(get_shade_from_name("test.png"), cl("#2E9146"))
self.assertEqual(get_shade_from_name("test.jpg"), cl("#2B8741"))
self.assertEqual(get_shade_from_name("test.JPG"), cl("#2B8741"))
self.assertEqual(get_shade_from_name("test.ovtex"), cl("#287F3D"))
self.assertEqual(get_shade_from_name("test.dds"), cl("#257639"))
self.assertEqual(get_shade_from_name("test.exr"), cl("#236E35"))
self.assertEqual(get_shade_from_name("test.wav"), cl("#216631"))
self.assertEqual(get_shade_from_name("test.tga"), cl("#1F5F2D"))
self.assertEqual(get_shade_from_name("test.mdl"), cl("#76567D"))
# "in" comparisons
self.assertEqual(get_shade_from_name('(test instance) 5'), cl("#694D6F"))
# anything else
self.assertEqual(get_shade_from_name("random_test_name"), cl("#555555"))
| 25,414 | Python | 36.989537 | 157 | 0.635831 |
omniverse-code/kit/exts/omni.activity.ui/docs/CHANGELOG.md | # Changelog
## [1.0.20] - 2023-02-08
### Fixed
- total duration not correct in progress window
## [1.0.19] - 2023-01-05
### Fixed
- merge issue caused by the diff between the cherry pick MR (https://gitlab-master.nvidia.com/omniverse/kit/-/merge_requests/21206) and the original MR (https://gitlab-master.nvidia.com/omniverse/kit/-/merge_requests/21171)
## [1.0.18] - 2022-12-08
### Fixed
- try to open non-exsited URL, the spinner is always rotationg by using OPEN_FAILED event (OM-73934)
## [1.0.17] - 2022-12-05
### Changed
- Fixed pinwheel slightly offset from loading bar (OM-74619)
- Added padding on the tree view header (OM-74828)
## [1.0.16] - 2022-11-30
### Fixed
- Updated to use omni.kit.menu.utils
## [1.0.15] - 2022-11-25
### Fixed
- when new stage is created or new stage is loading, the previous stage data should be cleared
## [1.0.14] - 2022-11-23
### Fixed
- try to open non-exsited URL, the spinner is always rotationg (OM-73934)
- force loading completion in the model rather than in the widget in case widget is not available (OM-73085)
## [1.0.13] - 2022-11-22
### Changed
- Make the pinwheel invisible when it's not loading
## [1.0.12] - 2022-11-18
### Changed
- Fixed the performance issue when ASSETS_LOADED is triggered by selection change
- Changed visibility of the progress bar window, instead of poping up when the prompt window is done we show the window when user clicks the status bar's progress area
## [1.0.11] - 2022-11-21
### Changed
- fixed performance issue caused by __extend_unfinished
- create ActivityModelStageOpenForProgress model for progress bar window to solve the performance issue of progress bar
## [1.0.10] - 2022-11-16
### Added
- informative text on the total progress bar showing the activity event happening (OM-72502)
- docs for the extension (OM-52478)
## [1.0.9] - 2022-11-10
### Changed
- clear the status bar instead of sending progress as 0% when new stage is created
- also clear the status bar when the stage is loaded so it's not stuck at 100%
## [1.0.8] - 2022-11-08
### Changed
- Don't use usd_resolver python callbacks
## [1.0.7] - 2022-11-07
### Changed
- using spinner instead of the ping-pong rectangle for the floating window
## [1.0.6] - 2022-11-04
### Changed
- make sure the activity progress window is shown and on focus when open stage is triggered
## [1.0.5] - 2022-10-28
### Changed
- fix the test with a threshold
## [1.0.4] - 2022-10-26
### Changed
- Stop the timeline view when asset_loaded
- Move the Activity Window menu item under Utilities
- Disable the menu button in the floating window
- Rename windows to Activity Progress and Activity Timeline
- Removed Timeline window menu entry and only make accessible through main Activity window
- Fixed resizing issue in the Activity Progress Treeview - resizing second column resizer breaks the view
- Make the spinner active during opening stage
- Remove the material progress bar size and speed for now
- Set the Activty window invisible by default (fix OM-67358)
- Update the preview image
## [1.0.3] - 2022-10-20
### Changed
- create ActivityModelStageOpen which inherits from ActivityModelRealtime, so to move the stage_path and _flattened_children out from the ActivityModelRealtime mode
## [1.0.2] - 2022-10-18
### Changed
- Fix the auto save to be window irrelevant (when progress bar window or timeline window is closed, still working), save to "${cache}/activities", and auto delete the old files, at the moment we keep 20 of them
- Add file numbers to timeline view when necessary
- Add size to the parent time range in the tooltip of timeline view when make sense
- Force progress to 1 when assets loaded
- Fix the issue of middle and right clicked is triggered unnecessarily, e.g., mouse movement in viewport
- Add timeline view selection callback to usd stage prim selection
## [1.0.1] - 2022-10-13
### Fixed
- test failure due to self._addon is None
## [1.0.0] - 2022-06-05
### Added
- Initial window
| 3,970 | Markdown | 36.462264 | 223 | 0.734509 |
omniverse-code/kit/exts/omni.activity.ui/docs/Overview.md | # Overview
omni.activity.ui is an extension created to display progress and activities. This is the new generation of the activity monitor which replaces the old version of omni.kit.activity.widget.monitor extension since the old activity monitor has limited information on activities and doesn't always provide accurate information about the progress.
Current work of omni.activity.ui focuses on loading activities but the solution is in general and will be extended to unload and frame activities in the future.
There are currently two visual presentations for the activities. The main one is the Activity Progress window which can be manually enabled from menu: Window->Utilities->Activity Progress:

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

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

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

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

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

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

### Activities Tab
The data is presented in a regular treeview with the root item as the 6 threads. Each thread activity shows its direct subActivities. Users can also see the duration, start time, end time and size information about each activity. When users hover onto each item, it will give more detailed information.
The expansion and selection status are synced between the Timeline Tab and Activities Tab.
## Save and Load Activity Log
Both Activity Progress Window and Activity Timeline Window have a hamburger button on the top right corner where you can save or choose to open an .activity or .json log file. The saved log file has the same data from both windows and it records all the activities happening for a certain stage. When you open the same .activity file from different windows, you get a different visual representation of the data.
A typical activity entry looks like this:
```python
{
"children": [],
"events": [
{
"size": 2184029,
"time": 133129969539325474,
"type": "BEGAN"
},
{
"size": 2184029,
"time": 133129969540887869,
"type": "ENDED"
}
],
"name": "omniverse://ov-content/NVIDIA/Samples/Marbles/assets/standalone/SM_board_4/SM_board_4.usd"
},
```
This is really useful to send to people for debug purposes, e.g find the performance bottleneck of the stage loading or spot problematic texture and so on.
## Dependencies
This extension depends on two core activity extensions omni.activity.core and omni.activity.pump. omni.activity.core is the core activity progress processor which defines the activity and event structure and provides APIs to subscribe to the events dispatching on the stream. omni.activity.pump makes sure the activity and the progress gets pumped every frame. | 6,230 | Markdown | 72.305882 | 525 | 0.781059 |
omniverse-code/kit/exts/omni.kit.window.filepicker/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. | 412 | Markdown | 57.999992 | 74 | 0.839806 |
omniverse-code/kit/exts/omni.kit.window.filepicker/scripts/demo_filepicker.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
import omni.ui as ui
from omni.kit.window.filepicker import FilePickerDialog
from omni.kit.widget.filebrowser import FileBrowserItem
def options_pane_build_fn(selected_items):
with ui.CollapsableFrame("Reference Options"):
with ui.HStack(height=0, spacing=2):
ui.Label("Prim Path", width=0)
return True
def on_filter_item(dialog: FilePickerDialog, item: FileBrowserItem) -> bool:
if not item or item.is_folder:
return True
if dialog.current_filter_option == 0:
# Show only files with listed extensions
_, ext = os.path.splitext(item.path)
if ext in [".usd", ".usda", ".usdc", ".usdz"]:
return True
else:
return False
else:
# Show All Files (*)
return True
def on_click_open(dialog: FilePickerDialog, filename: str, dirname: str):
"""
The meat of the App is done in this callback when the user clicks 'Accept'. This is
a potentially costly operation so we implement it as an async operation. The inputs
are the filename and directory name. Together they form the fullpath to the selected
file.
"""
# Normally, you'd want to hide the dialog
# dialog.hide()
dirname = dirname.strip()
if dirname and not dirname.endswith("/"):
dirname += "/"
fullpath = f"{dirname}{filename}"
print(f"Opened file '{fullpath}'.")
if __name__ == "__main__":
item_filter_options = ["USD Files (*.usd, *.usda, *.usdc, *.usdz)", "All Files (*)"]
dialog = FilePickerDialog(
"Demo Filepicker",
apply_button_label="Open",
click_apply_handler=lambda filename, dirname: on_click_open(dialog, filename, dirname),
item_filter_options=item_filter_options,
item_filter_fn=lambda item: on_filter_item(dialog, item),
options_pane_build_fn=options_pane_build_fn,
)
dialog.add_connections({"ov-content": "omniverse://ov-content", "ov-rc": "omniverse://ov-rc"})
# Display dialog at pre-determined path
dialog.show(path="omniverse://ov-content/NVIDIA/Samples/Astronaut/Astronaut.usd")
| 2,545 | Python | 36.999999 | 98 | 0.677014 |
omniverse-code/kit/exts/omni.kit.window.filepicker/config/extension.toml | [package]
title = "Kit Filepicker Window"
version = "2.7.15"
category = "Internal"
description = "Filepicker popup dialog and embeddable widget"
authors = ["NVIDIA"]
slackids = ["UQY4RMR3N"]
repository = ""
keywords = ["kit", "ui"]
readme = "docs/README.md"
changelog = "docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[dependencies]
"omni.ui" = {}
"omni.usd" = {optional=true}
"omni.client" = {}
"omni.kit.notification_manager" = {}
"omni.kit.pip_archive" = {} # Pull in pip_archive to make sure psutil is found and not installed
"omni.kit.widget.filebrowser" = {}
"omni.kit.widget.browser_bar" = {}
"omni.kit.window.popup_dialog" = {}
"omni.kit.widget.versioning" = {}
"omni.kit.search_core" = {}
"omni.kit.widget.nucleus_connector" = {}
[[python.module]]
name = "omni.kit.window.filepicker"
[[python.scriptFolder]]
path = "scripts"
[python.pipapi]
requirements = ["psutil", "pyperclip"]
[settings]
exts."omni.kit.window.filepicker".timeout = 10.0
persistent.exts."omni.kit.window.filepicker".window_split = 306
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.kit.ui_test",
]
pythonTests.unreliable = [
"*test_search_returns_expected*", # OM-75424
"*test_changing_directory_while_searching*", # OM-75424
]
| 1,355 | TOML | 23.214285 | 96 | 0.681181 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/search_delegate.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import abc
import omni.ui as ui
from typing import Dict
from omni.kit.widget.filebrowser import FileBrowserModel, FileBrowserItem, find_thumbnails_for_files_async
from omni.kit.search_core import AbstractSearchModel, AbstractSearchItem
class SearchDelegate:
def __init__(self, **kwargs):
self._search_dir = None
@property
def visible(self):
return True
@property
def enabled(self):
"""Enable/disable Widget"""
return True
@property
def search_dir(self):
return self._search_dir
@search_dir.setter
def search_dir(self, search_dir: str):
self._search_dir = search_dir
@abc.abstractmethod
def build_ui(self):
pass
@abc.abstractmethod
def destroy(self):
pass
class SearchResultsItem(FileBrowserItem):
class _RedirectModel(ui.AbstractValueModel):
def __init__(self, search_model, field):
super().__init__()
self._search_model = search_model
self._field = field
def get_value_as_string(self):
return str(self._search_model[self._field])
def set_value(self, value):
pass
def __init__(self, search_item: AbstractSearchItem):
super().__init__(search_item.path, search_item)
self.search_item = search_item
self._is_folder = self.search_item.is_folder
self._models = (
self._RedirectModel(self.search_item, "name"),
self._RedirectModel(self.search_item, "date"),
self._RedirectModel(self.search_item, "size"),
)
@property
def icon(self) -> str:
"""str: Gets/sets path to icon file."""
return self.search_item.icon
@icon.setter
def icon(self, icon: str):
pass
class SearchResultsModel(FileBrowserModel):
def __init__(self, search_model: AbstractSearchModel, **kwargs):
super().__init__(**kwargs)
self._search_model = search_model
# Circular dependency
self._dirty_item_subscription = self._search_model.subscribe_item_changed(self.__on_item_changed)
self._children = []
self._thumbnail_dict: Dict = {}
def destroy(self):
# Remove circular dependency
self._dirty_item_subscription = None
if self._search_model:
self._search_model.destroy()
self._search_model = None
def get_item_children(self, item: FileBrowserItem) -> [FileBrowserItem]:
"""Converts AbstractSearchItem to FileBrowserItem"""
if self._search_model is None or item is not None:
return []
search_items = self._search_model.items or []
self._children = [SearchResultsItem(search_item) for search_item in search_items]
if self._filter_fn:
return list(filter(self._filter_fn, self._children))
else:
return self._children
def __on_item_changed(self, item):
if item is None:
self._children = []
self._item_changed(item)
async def get_custom_thumbnails_for_folder_async(self, _: SearchResultsItem) -> Dict:
"""
Returns a dictionary of thumbnails for the given search results.
Args:
item (:obj:`FileBrowseritem`): Ignored, should be set to None.
Returns:
dict: With item name as key, and fullpath to thumbnail file as value.
"""
# Files in the root folder only
file_urls = []
for item in self.get_item_children(None):
if item.is_folder or item.path in self._thumbnail_dict:
# Skip if folder or thumbnail previously found
pass
else:
file_urls.append(item.path)
thumbnail_dict = await find_thumbnails_for_files_async(file_urls)
for url, thumbnail_url in thumbnail_dict.items():
if url and thumbnail_url:
self._thumbnail_dict[url] = thumbnail_url
return self._thumbnail_dict
| 4,440 | Python | 30.496454 | 106 | 0.626126 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/item_deletion_dialog.py | # Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from typing import Callable
from typing import List
from omni.kit.widget.filebrowser import FileBrowserItem
from omni.kit.window.popup_dialog.dialog import PopupDialog
import omni.ui as ui
from .item_deletion_model import ConfirmItemDeletionListModel
from .style import get_style
class ConfirmItemDeletionDialog(PopupDialog):
"""Dialog prompting the User to confirm the deletion of the provided list of files and folders."""
def __init__(
self,
items: List[FileBrowserItem],
title: str="Confirm File Deletion",
message: str="You are about to delete",
message_fn: Callable[[None], None]=None,
parent: ui.Widget=None, # OBSOLETE
width: int=500,
ok_handler: Callable[[PopupDialog], None]=None,
cancel_handler: Callable[[PopupDialog], None]=None,
):
"""
Dialog prompting the User to confirm the deletion of the provided list of files and folders.
Args:
items ([FileBrowserItem]): List of files and folders to delete.
title (str): Title of the dialog. Default "Confirm File Deletion".
message (str): Basic message. Default "You are about to delete".
message_fn (Callable[[None], None]): Message build function.
parent (:obj:`omni.ui.Widget`): OBSOLETE. If specified, the dialog position is relative to this widget. Default `None`.
width (int): Dialog width. Default `500`.
ok_handler (Callable): Function to execute upon clicking the "Yes" button. Function signature:
void ok_handler(dialog: :obj:`PopupDialog`)
cancel_handler (Callable): Function to execute upon clicking the "No" button. Function signature:
void cancel_handler(dialog: :obj:`PopupDialog`)
"""
super().__init__(
width=width,
title=title,
ok_handler=ok_handler,
ok_label="Yes",
cancel_handler=cancel_handler,
cancel_label="No",
)
self._items = items
self._message = message
self._message_fn = message_fn
self._list_model = ConfirmItemDeletionListModel(items)
self._tree_view = None
self._build_ui()
self.hide()
def _build_ui(self) -> None:
with self._window.frame:
with ui.ZStack(style=get_style()):
ui.Rectangle(style_type_name_override="Background")
with ui.VStack(style_type_name_override="Dialog", spacing=6):
if self._message_fn:
self._message_fn()
else:
prefix_message = self._message + " this item:" if len(self._items) == 1 else f"these {len(self._items)} items:"
ui.Label(prefix_message)
scrolling_frame = ui.ScrollingFrame(
height=150,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
)
with scrolling_frame:
self._tree_view = ui.TreeView(
self._list_model,
root_visible=False,
header_visible=False,
style={"TreeView.Item": {"margin": 4}},
)
ui.Label("Are you sure you wish to proceed?")
self._build_ok_cancel_buttons()
def destroy(self) -> None:
"""Destructor."""
if self._list_model:
self._list_model = None
if self._tree_view:
self._tree_view = None
self._window = None
def rebuild_ui(self, message_fn: Callable[[None], None]) -> None:
"""
Rebuild ui widgets with new message
Args:
message_fn (Callable[[None], None]): Message build function.
"""
self._message_fn = message_fn
# Reset window or new height with new message
self._window.height = 0
self._window.frame.clear()
self._build_ui()
| 4,701 | Python | 40.610619 | 135 | 0.577962 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/view.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
import platform
import omni.kit.app
import omni.client
import carb.settings
from typing import Callable, List, Optional
from carb import events, log_warn
from omni.kit.widget.filebrowser import (
FileBrowserWidget,
FileBrowserModel,
FileBrowserItem,
FileSystemModel,
NucleusModel,
NucleusConnectionItem,
LAYOUT_DEFAULT,
TREEVIEW_PANE,
LISTVIEW_PANE,
CONNECTION_ERROR_EVENT
)
from omni.kit.widget.nucleus_connector import get_nucleus_connector, NUCLEUS_CONNECTION_SUCCEEDED_EVENT
from .model import FilePickerModel
from .bookmark_model import BookmarkItem, BookmarkModel
from .utils import exec_after_redraw, get_user_folders_dict
from .style import ICON_PATH
import carb.events
BOOKMARK_ADDED_EVENT: int = carb.events.type_from_string("omni.kit.window.filepicker.BOOKMARK_ADDED")
BOOKMARK_DELETED_EVENT: int = carb.events.type_from_string("omni.kit.window.filepicker.BOOKMARK_DELETED")
BOOKMARK_RENAMED_EVENT: int = carb.events.type_from_string("omni.kit.window.filepicker.BOOKMARK_RENAMED")
NUCLEUS_SERVER_ADDED_EVENT: int = carb.events.type_from_string("omni.kit.window.filepicker.NUCLEUS_SERVER_ADDED")
NUCLEUS_SERVER_DELETED_EVENT: int = carb.events.type_from_string("omni.kit.window.filepicker.NUCLEUS_SERVER_DELETED")
NUCLEUS_SERVER_RENAMED_EVENT: int = carb.events.type_from_string("omni.kit.window.filepicker.NUCLEUS_SERVER_RENAMED")
class FilePickerView:
"""
An embeddable UI component for browsing the filesystem. This widget is more full-functioned
than :obj:`FileBrowserWidget` but less so than :obj:`FilePickerWidget`. More specifically, this is one of
the 3 sub-components of its namesake :obj:`FilePickerWidget`. The difference is it doesn't have the Browser Bar
(at top) or the File Bar (at bottom). This gives users the flexibility to substitute in other surrounding
components instead.
Args:
title (str): Widget title. Default None.
Keyword Args:
layout (int): The overall layout of the window, one of: {LAYOUT_SPLIT_PANES, LAYOUT_SINGLE_PANE_SLIM,
LAYOUT_SINGLE_PANE_WIDE, LAYOUT_DEFAULT}. Default LAYOUT_SPLIT_PANES.
splitter_offset (int): Position of vertical splitter bar. Default 300.
show_grid_view (bool): Display grid view in the intial layout. Default True.
show_recycle_widget (bool): Display recycle widget in the intial layout. Default False.
grid_view_scale (int): Scales grid view, ranges from 0-5. Default 2.
on_toggle_grid_view_fn (Callable): Callback after toggle grid view is executed. Default None.
on_scale_grid_view_fn (Callable): Callback after scale grid view is executed. Default None.
show_only_collections (list[str]): List of collections to display, any combination of ["bookmarks",
"omniverse", "my-computer"]. If None, then all are displayed. Default None.
tooltip (bool): Display tooltips when hovering over items. Default True.
allow_multi_selection (bool): Allow multiple items to be selected at once. Default False.
mouse_pressed_fn (Callable): Function called on mouse press. Function signature:
void mouse_pressed_fn(pane: int, button: int, key_mode: int, item: :obj:`FileBrowserItem`)
mouse_double_clicked_fn (Callable): Function called on mouse double click. Function signature:
void mouse_double_clicked_fn(pane: int, button: int, key_mode: int, item: :obj:`FileBrowserItem`)
selection_changed_fn (Callable): Function called when selection changed. Function signature:
void selection_changed_fn(pane: int, selections: list[:obj:`FileBrowserItem`])
drop_handler (Callable): Function called to handle drag-n-drops.
Function signature: void drop_fn(dst_item: :obj:`FileBrowserItem`, src_paths: [str])
item_filter_fn (Callable): This handler should return True if the given tree view item is visible,
False otherwise. Function signature: bool item_filter_fn(item: :obj:`FileBrowserItem`)
thumbnail_provider (Callable): This callback returns the path to the item's thumbnail. If not specified,
then a default thumbnail is used. Signature: str thumbnail_provider(item: :obj:`FileBrowserItem`).
icon_provider (Callable): This callback provides an icon to replace the default in the tree view.
Signature str icon_provider(item: :obj:`FileBrowserItem`)
badges_provider (Callable): This callback provides the list of badges to layer atop the thumbnail
in the grid view. Callback signature: [str] badges_provider(item: :obj:`FileBrowserItem`)
treeview_identifier (str): widget identifier for treeview, only used by tests.
enable_zoombar (bool): Enables/disables zoombar. Default True.
"""
# Singleton placeholder item in the tree view
__placeholder_model = None
# use class attribute to store connected server's url
# it could shared between different file dialog (OMFP-2569)
__connected_servers = set()
def __init__(self, title: str, **kwargs):
self._title = title
self._filebrowser = None
self._layout = kwargs.get("layout", LAYOUT_DEFAULT)
self._splitter_offset = kwargs.get("splitter_offset", 300)
self._show_grid_view = kwargs.get("show_grid_view", True)
self._show_recycle_widget = kwargs.get("show_recycle_widget", False)
self._grid_view_scale = kwargs.get("grid_view_scale", 2)
# OM-66270: Add callback to record show grid view settings in between sessions
self._on_toggle_grid_view_fn = kwargs.get("on_toggle_grid_view_fn", None)
self._on_scale_grid_view_fn = kwargs.get("on_scale_grid_view_fn", None)
self._show_only_collections = kwargs.get("show_only_collections", None)
self._tooltip = kwargs.get("tooltip", True)
self._allow_multi_selection = kwargs.get("allow_multi_selection", False)
self._mouse_pressed_fn = kwargs.get("mouse_pressed_fn", None)
self._mouse_double_clicked_fn = kwargs.get("mouse_double_clicked_fn", None)
self._selection_changed_fn = kwargs.get("selection_changed_fn", None)
self._drop_handler = kwargs.get("drop_handler", None)
self._item_filter_fn = kwargs.get("item_filter_fn", None)
self._icon_provider = kwargs.get("icon_provider", None)
self._thumbnail_provider = kwargs.get("thumbnail_provider", None)
self._treeview_identifier = kwargs.get('treeview_identifier', None)
self._enable_zoombar = kwargs.get("enable_zoombar", True)
self._badges_provider = kwargs.get("badges_provider", None)
self._collections = {}
self._bookmark_model = None
self._show_add_new_connection = carb.settings.get_settings().get_as_bool("/exts/omni.kit.window.filepicker/show_add_new_connection")
if not FilePickerView.__placeholder_model:
FilePickerView.__placeholder_model = FileBrowserModel(name="Add New Connection ...")
FilePickerView.__placeholder_model.root.icon = f"{ICON_PATH}/hdd_plus.svg"
self.__expand_task = None
self._connection_failed_event_sub = None
self._connection_succeeded_event_sub = None
self._connection_status_sub = None
self._build_ui()
@property
def filebrowser(self):
return self._filebrowser
def destroy(self):
if self.__expand_task is not None:
self.__expand_task.cancel()
self.__expand_task = None
if self._filebrowser:
self._filebrowser.destroy()
self._filebrowser = None
self._mouse_pressed_fn = None
self._mouse_double_clicked_fn = None
self._selection_changed_fn = None
self._drop_handler = None
self._item_filter_fn = None
self._icon_provider = None
self._thumbnail_provider = None
self._badges_provider = None
self._collections = None
self._bookmark_model = None
self._connection_failed_event_sub = None
self._connection_succeeded_event_sub = None
self._connection_status_sub = None
@property
def show_udim_sequence(self):
return self._filebrowser.show_udim_sequence
@show_udim_sequence.setter
def show_udim_sequence(self, value: bool):
self._filebrowser.show_udim_sequence = value
@property
def notification_frame(self):
return self._filebrowser._notification_frame
def _build_ui(self):
""" """
def on_mouse_pressed(pane: int, button: int, key_mod: int, item: FileBrowserItem, x: float = 0, y: float = 0):
if button == 0 and self._is_placeholder(item):
# Left mouse button: add new connection
self.show_connect_dialog()
if self._mouse_pressed_fn and not self._is_placeholder(item):
self._mouse_pressed_fn(pane, button, key_mod, item)
def on_mouse_double_clicked(pane: int, button: int, key_mod: int, item: FileBrowserItem, x: float = 0, y: float = 0):
if self._is_placeholder(item):
return
if item and item.is_folder:
# In the special case where item errored out previously, try reconnecting the host.
broken_url = omni.client.break_url(item.path)
if broken_url.host:
def on_host_found(host: FileBrowserItem):
if host and host.alert:
self.reconnect_server(host)
try:
self._find_item_with_callback(
omni.client.make_url(scheme=broken_url.scheme, host=broken_url.host), on_host_found)
except Exception as e:
log_warn(str(e))
if self._mouse_double_clicked_fn:
self._mouse_double_clicked_fn(pane, button, key_mod, item)
def on_selection_changed(pane: int, selected: [FileBrowserItem]):
# Filter out placeholder item
selected = list(filter(lambda i: not self._is_placeholder(i), selected))
if self._selection_changed_fn:
self._selection_changed_fn(pane, selected)
self._filebrowser = FileBrowserWidget(
"All",
tree_root_visible=False,
layout=self._layout,
splitter_offset=self._splitter_offset,
show_grid_view=self._show_grid_view,
show_recycle_widget=self._show_recycle_widget,
grid_view_scale=self._grid_view_scale,
on_toggle_grid_view_fn=self._on_toggle_grid_view_fn,
on_scale_grid_view_fn=self._on_scale_grid_view_fn,
tooltip=self._tooltip,
allow_multi_selection=self._allow_multi_selection,
mouse_pressed_fn=on_mouse_pressed,
mouse_double_clicked_fn=on_mouse_double_clicked,
selection_changed_fn=on_selection_changed,
drop_fn=self._drop_handler,
filter_fn=self._item_filter_fn,
icon_provider=self._icon_provider,
thumbnail_provider=self._thumbnail_provider,
badges_provider=self._badges_provider,
treeview_identifier=self._treeview_identifier,
enable_zoombar=self._enable_zoombar
)
# Listen for connections errors that may occur during navigation
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
self._connection_failed_event_sub =\
event_stream.create_subscription_to_pop_by_type(CONNECTION_ERROR_EVENT, self._on_connection_failed)
self._connection_succeeded_event_sub = \
event_stream.create_subscription_to_pop_by_type(NUCLEUS_CONNECTION_SUCCEEDED_EVENT, self._on_connection_succeeded)
self._connection_status_sub = omni.client.register_connection_status_callback(self._server_status_changed)
self._build_bookmarks_collection()
self._build_omniverse_collection()
self._build_computer_collection()
def expand_collections():
for collection in self._collections.values():
self._filebrowser.set_expanded(collection, expanded=True, recursive=False)
# Finally, expand collection nodes in treeview after UI becomes ready
self.__expand_task = exec_after_redraw(expand_collections, wait_frames=6)
def _build_bookmarks_collection(self):
collection_id = "bookmarks"
if self._show_only_collections and collection_id not in self._show_only_collections:
return
if not self._bookmark_model:
self._bookmark_model = BookmarkModel("Bookmarks", f"{collection_id}://")
self._filebrowser.add_model_as_subtree(self._bookmark_model)
self._collections[collection_id] = self._bookmark_model.root
def _build_omniverse_collection(self):
collection_id = "omniverse"
if self._show_only_collections and collection_id not in self._show_only_collections:
return
collection = self._filebrowser.create_grouping_item("Omniverse", f"{collection_id}://", parent=None)
collection.icon = f"{ICON_PATH}/omniverse_logo_64.png"
self._collections[collection_id] = collection
# Create a placeholder item for adding new connections
if self._show_add_new_connection:
self._filebrowser.add_model_as_subtree(FilePickerView.__placeholder_model, parent=collection)
def _build_computer_collection(self):
collection_id = "my-computer"
if self._show_only_collections and collection_id not in self._show_only_collections:
return
collection = self._collections.get(collection_id, None)
if collection is None:
collection = self._filebrowser.create_grouping_item("My Computer", f"{collection_id}://", parent=None)
collection.icon = f"{ICON_PATH}/my_computer.svg"
self._collections[collection_id] = collection
try:
if platform.system().lower() == "linux":
import psutil
partitions = psutil.disk_partitions(all=True)
# OM-76424: Pre-filter some of the local directories that are of interest for users
filtered_partitions = []
for partition in partitions:
if any(x in partition.opts for x in ('nodev', 'nosuid', 'noexec')):
continue
if partition.fstype in ('tmpfs', 'proc', 'devpts', 'sysfs', 'nsfs', 'autofs', 'cgroup'):
continue
filtered_partitions.append(partition)
partitions = filtered_partitions
# OM-76424: Ensure that "/" is always there, because disk_partitions() will ignore it sometimes.
if not any(p.mountpoint == "/" for p in partitions):
from types import SimpleNamespace
e = SimpleNamespace()
e.mountpoint = "/"
e.opts = "fixed"
partitions.insert(0, e) # first entry
elif platform.system().lower() == "windows":
from ctypes import windll
# GetLocalDrives returns a bitmask with with bit i set meaning that
# the logical drive 'A' + i is available on the system.
logicalDriveBitMask = windll.kernel32.GetLogicalDrives()
from types import SimpleNamespace
partitions = list()
# iterate over all letters in the latin alphabet
for bit in range(0, (ord('Z') - ord('A') + 1)):
if logicalDriveBitMask & (1 << bit):
e = SimpleNamespace()
e.mountpoint = chr(ord('A') + bit) + ":"
e.opts = "fixed"
partitions.append(e)
else:
import psutil
partitions = psutil.disk_partitions(all=True)
except Exception:
log_warn("Warning: Could not import psutil")
return
else:
# OM-51243: Show OV Drive (O: drive) after refresh in Create
user_folders = get_user_folders_dict()
# we should remove all old Drive at first, but keep the user folder
for name in collection.children:
if name not in user_folders:
self._filebrowser.delete_child_by_name(name, collection)
# then add current Drive
for p in partitions:
if any(x in p.opts for x in ["removable", "fixed", "rw", "ro", "remote"]):
mountpoint = p.mountpoint.rstrip("\\")
item_model = FileSystemModel(mountpoint, mountpoint)
self._filebrowser.add_model_as_subtree(item_model, parent=collection)
@property
def collections(self):
"""dict: Dictionary of collections, e.g. 'bookmarks', 'omniverse', 'my-computer'."""
return self._collections
def get_root(self, pane: int = None) -> FileBrowserItem:
"""
Returns the root item of the specified pane.
Args:
pane (int): One of {TREEVIEW_PANE, LISTVIEW_PANE}.
"""
if self._filebrowser:
return self._filebrowser.get_root(pane)
return None
def all_collection_items(self, collection: str = None) -> List[FileBrowserItem]:
"""
Returns all connections as items for the specified collection. If collection is 'None', then return connections
from all collections.
Args:
collection (str): One of ['bookmarks', 'omniverse', 'my-computer']. Default None.
Returns:
List[FileBrowserItem]: All connections found.
"""
collections = [self._collections.get(collection)] if collection else self._collections.values()
connections = []
for coll in collections:
# Note: We know that collections are initally expanded so we can safely retrieve its children
# here without worrying about async delay.
if coll and coll.children:
for _, conn in coll.children.items():
if not self._is_placeholder(conn):
connections.append(conn)
return connections
def is_collection_root(self, url: str = None) -> bool:
"""
Returns True if the given url is a collection root url.
Args:
url (str): The url to query. Default None.
Returns:
bool: The result.
"""
if not url:
return False
for col in self._collections.values():
if col.path == url:
return True
# click the path field root always renturn "omniverse:///"
if url.rstrip("/") == "omniverse:":
return True
return False
def has_connection_with_name(self, name: str, collection: str = None) -> bool:
"""
Returns True if named connection exists within the collection.
Args:
name (str): name (could be aliased name) of connection
collection (str): One of {'bookmarks', 'omniverse', 'my-computer'}. Default None.
Returns:
bool
"""
connections = [i.name for i in self.all_collection_items(collection)]
return name in connections
def get_connection_with_url(self, url: str) -> Optional[NucleusConnectionItem]:
"""
Gets the connection item with the given url.
Args:
name (str): name (could be aliased name) of connection
Returns:
NucleusConnectionItem
"""
for item in self.all_collection_items(collection="omniverse"):
if item.path == url:
return item
return None
def set_item_filter_fn(self, item_filter_fn: Callable[[str], bool]):
"""
Sets the item filter function.
Args:
item_filter_fn (Callable): Signature is bool fn(item: FileBrowserItem)
"""
self._item_filter_fn = item_filter_fn
if self._filebrowser and self._filebrowser._listview_model:
self._filebrowser._listview_model.set_filter_fn(self._item_filter_fn)
def set_selections(self, selections: List[FileBrowserItem], pane: int = TREEVIEW_PANE):
"""
Selected given items in given pane.
ARGS:
selections (list[:obj:`FileBrowserItem`]): list of selections.
pane (int): One of TREEVIEW_PANE, LISTVIEW_PANE, or None for both. Default None.
"""
if self._filebrowser:
self._filebrowser.set_selections(selections, pane)
def get_selections(self, pane: int = LISTVIEW_PANE) -> List[FileBrowserItem]:
"""
Returns list of currently selected items.
Args:
pane (int): One of {TREEVIEW_PANE, LISTVIEW_PANE}.
Returns:
list[:obj:`FileBrowserItem`]
"""
if self._filebrowser:
return [sel for sel in self._filebrowser.get_selections(pane) if not self._is_placeholder(sel)]
return []
def refresh_ui(self, item: FileBrowserItem = None):
"""
Redraws the subtree rooted at the given item. If item is None, then redraws entire tree.
Args:
item (:obj:`FileBrowserItem`): Root of subtree to redraw. Default None, i.e. root.
"""
self._build_computer_collection()
if item:
item.populated = False
if self._filebrowser:
self._filebrowser.refresh_ui(item)
def is_connection_point(self, item: FileBrowserItem) -> bool:
"""
Returns true if given item is a direct child of a collection node.
Args:
item (:obj:`FileBrowserItem`): Item in question.
Returns:
bool
"""
return item in self.all_collection_items("omniverse")
def is_bookmark(self, item: FileBrowserItem, path: Optional[str] = None) -> bool:
"""
Returns true if given item is a bookmarked item, or if a given path is bookmarked.
Args:
item (:obj:`FileBrowserItem`): Item in question.
path (Optional[str]): Path in question.
Returns:
bool
"""
if path:
for item in self.all_collection_items("bookmarks"):
# compare the bookmark path with the formatted file path
if item.path == item.format_bookmark_path(path):
return True
return False
# if path is not given, check item type directly
return isinstance(item, BookmarkItem)
def is_collection_node(self, item: FileBrowserItem) -> bool:
"""
Returns true if given item is a collection node.
Args:
item (:obj:`FileBrowserItem`): Item in question.
Returns:
bool
"""
for value in self.collections.values():
if value.name == item.name:
return True
return False
def select_and_center(self, item: FileBrowserItem):
"""
Selects and centers the view on the given item, expanding the tree if needed.
Args:
item (:obj:`FileBrowserItem`): The selected item.
"""
if not self._filebrowser:
return
if (item and item.is_folder) or not item:
self._filebrowser.select_and_center(item, pane=TREEVIEW_PANE)
else:
self._filebrowser.select_and_center(item.parent, pane=TREEVIEW_PANE)
exec_after_redraw(lambda item=item: self._filebrowser.select_and_center(item, pane=LISTVIEW_PANE))
def show_model(self, model: FileBrowserModel):
"""Displays the model on the right side of the split pane"""
self._filebrowser.show_model(model)
def show_connect_dialog(self):
"""Displays the add connection dialog."""
nucleus_connector = get_nucleus_connector()
if nucleus_connector:
nucleus_connector.connect_with_dialog(on_success_fn=self.add_server)
def add_server(self, name: str, path: str, publish_event: bool = True) -> FileBrowserModel:
"""
Creates a :obj:`FileBrowserModel` rooted at the given path, and connects its subtree to the
tree view.
Args:
name (str): Name, label really, of the connection.
path (str): Fullpath of the connection, e.g. "omniverse://ov-content". Paths to
Omniverse servers should contain the prefix, "omniverse://".
publish_event (bool): If True, push a notification to the event stream.
Returns:
:obj:`FileBrowserModel`
Raises:
:obj:`RuntimeWarning`: If unable to add server.
"""
if not (name and path):
raise RuntimeWarning(f"Error adding server, invalid name: '{path}', path: '{path}'.")
collection = self._collections.get("omniverse", None)
if not collection:
return None
# First, remove the placeholder model
if self._show_add_new_connection:
self._filebrowser.delete_child(FilePickerView.__placeholder_model.root, parent=collection)
# Append the new model of desired server type
server = NucleusModel(name, path)
self._filebrowser.add_model_as_subtree(server, parent=collection)
# Finally, re-append the placeholder
if self._show_add_new_connection:
self._filebrowser.add_model_as_subtree(FilePickerView.__placeholder_model, parent=collection)
if publish_event:
# Push a notification event to the event stream
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
event_stream.push(NUCLEUS_SERVER_ADDED_EVENT, payload={"name": name, "url": path})
return server
def _on_connection_failed(self, event: events.IEvent):
if event.type == CONNECTION_ERROR_EVENT:
def set_item_warning(item: FileBrowserItem, msg: str):
if item and not self._is_placeholder(item):
self.filebrowser.set_item_warning(item, msg)
try:
broken_url = omni.client.break_url(event.payload.get('url', ""))
except Exception:
return
if broken_url.scheme == "omniverse" and broken_url.host:
url = omni.client.make_url(scheme=broken_url.scheme, host=broken_url.host)
msg = "Unable to access this server. Please double-click this item or right-click, then 'reconnect server' to refresh the connection."
self._find_item_with_callback(url, lambda item: set_item_warning(item, msg))
def _on_connection_succeeded(self, event: events.IEvent):
if event.type == NUCLEUS_CONNECTION_SUCCEEDED_EVENT:
try:
url = event.payload.get('url', "")
except Exception:
return
else:
return
def refresh_connection(item: FileBrowserItem):
if self._filebrowser:
# Clear alerts, if any
self._filebrowser.clear_item_alert(item)
self.refresh_ui(item)
self._find_item_with_callback(url, refresh_connection)
def delete_server(self, item: FileBrowserItem, publish_event: bool = True):
"""
Disconnects the subtree rooted at the given item.
Args:
item (:obj:`FileBrowserItem`): Root of subtree to disconnect.
publish_event (bool): If True, push a notification to the event stream.
"""
if not item or not self.is_connection_point(item) or self._is_placeholder(item):
return
nucleus_connector = get_nucleus_connector()
if nucleus_connector:
nucleus_connector.disconnect(item.path)
self._filebrowser.delete_child(item, parent=item.parent)
if publish_event:
# Push a notification event to the event stream
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
event_stream.push(NUCLEUS_SERVER_DELETED_EVENT, payload={"name": item.name, "url": item.path})
def rename_server(self, item: FileBrowserItem, new_name: str, publish_event: bool = True):
"""
Renames the connection item. Note: doesn't change the connection itself, only how it's labeled
in the tree view.
Args:
item (:obj:`FileBrowserItem`): Root of subtree to disconnect.
new_name (str): New name.
publish_event (bool): If True, push a notification to the event stream.
"""
if not item or not self.is_connection_point(item) or self._is_placeholder(item):
return
elif new_name == item.name:
return
old_name, server_url = item.name, item.path
self._filebrowser.delete_child(item, parent=item.parent)
self.add_server(new_name, server_url, publish_event=False)
if publish_event:
# Push a notification event to the event stream
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
event_stream.push(NUCLEUS_SERVER_RENAMED_EVENT, payload={"old_name": old_name, "new_name": new_name, "url": server_url})
def reconnect_server(self, item: FileBrowserItem):
"""
Reconnects the server at the given path. Clears out any cached authentication tokens to force the action.
Args:
item (:obj:`FileBrowserItem`): Connection item.
"""
broken_url = omni.client.break_url(item.path)
if broken_url.scheme != 'omniverse':
return
if self.is_connection_point(item):
nucleus_connector = get_nucleus_connector()
if nucleus_connector:
nucleus_connector.reconnect(item.path)
def log_out_server(self, item: NucleusConnectionItem):
"""
Log out from the server at the given path.
Args:
item (:obj:`NucleusConnectionItem`): Connection item.
"""
if not isinstance(item, NucleusConnectionItem):
return
broken_url = omni.client.break_url(item.path)
if broken_url.scheme != 'omniverse':
return
omni.client.sign_out(item.path)
def add_bookmark(self, name: str, path: str, is_folder: bool = True, publish_event: bool = True) -> BookmarkItem:
"""
Creates a :obj:`FileBrowserModel` rooted at the given path, and connects its subtree to the
tree view.
Args:
name (str): Name of the bookmark.
path (str): Fullpath of the connection, e.g. "omniverse://ov-content". Paths to
Omniverse servers should contain the prefix, "omniverse://".
is_folder (bool): If the item to be bookmarked is a folder or not. Default to True.
publish_event (bool): If True, push a notification to the event stream.
Returns:
:obj:`BookmarkItem`
"""
bookmark = None
if not (name and path):
return None
if not self._collections.get("bookmarks", None):
return None
if self._bookmark_model:
bookmark = self._bookmark_model.add_bookmark(name, path, is_folder=is_folder)
self._filebrowser.refresh_ui(self._bookmark_model.root)
if bookmark and publish_event:
# Push a notification event to the event stream
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
event_stream.push(BOOKMARK_ADDED_EVENT, payload={"name": bookmark.name, "url": bookmark.path})
return bookmark
def delete_bookmark(self, item: BookmarkItem, publish_event: bool = True):
"""
Deletes the given bookmark.
Args:
item (:obj:`FileBrowserItem`): Bookmark item.
publish_event (bool): If True, push a notification to the event stream.
"""
if not item or not self.is_bookmark(item):
return
bookmark = None
if self._bookmark_model:
bookmark = {"name": item.name, "url": item.path}
self._bookmark_model.delete_bookmark(item)
self._filebrowser.refresh_ui(self._bookmark_model.root)
if bookmark and publish_event:
# Push a notification event to the event stream
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
event_stream.push(BOOKMARK_DELETED_EVENT, payload=bookmark)
def rename_bookmark(self, item: BookmarkItem, new_name: str, new_url: str, publish_event: bool = True):
"""
Renames the bookmark item. Note: doesn't change the connection itself, only how it's labeled
in the tree view.
Args:
item (:obj:`FileBrowserItem`): Bookmark item.
new_name (str): New name.
new_url (str): New url address.
publish_event (bool): If True, push a notification to the event stream.
"""
if not item or not self.is_bookmark(item):
return
elif new_name == item.name and new_url == item.path:
return
old_name, is_folder = item.name, item.is_folder
self.delete_bookmark(item, publish_event=False)
self.add_bookmark(new_name, new_url, is_folder=is_folder, publish_event=False)
item.set_bookmark_path(new_url)
if publish_event:
# Push a notification event to the event stream
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
event_stream.push(BOOKMARK_RENAMED_EVENT, payload={"old_name": old_name, "new_name": new_name, "url": new_url})
def mount_user_folders(self, folders: dict):
"""
Mounts given set of user folders under the local collection.
Args:
folders (dict): Name, path pairs.
"""
if not folders:
return
collection = self._collections.get("my-computer", None)
if not collection:
return
for name, path in folders.items():
if os.path.exists(path):
self._filebrowser.add_model_as_subtree(FileSystemModel(name, path), parent=collection)
def _is_placeholder(self, item: FileBrowserItem) -> bool:
"""
Returns True if given item is the placeholder item.
Returns:
bool
"""
if item and self.__placeholder_model:
return item == self.__placeholder_model.root
return False
def toggle_grid_view(self, show_grid_view: bool):
"""
Toggles file picker between grid and list view.
Args:
show_grid_view (bool): True to show grid view, False to show list view.
"""
self._filebrowser.toggle_grid_view(show_grid_view)
@property
def show_grid_view(self):
"""
Gets file picker stage of grid or list view.
Returns:
bool: True if grid view shown or False if list view shown.
"""
return self._filebrowser.show_grid_view
def scale_grid_view(self, scale: float):
"""
Scale file picker's grid view icon size.
Args:
scale (float): Scale of the icon.
"""
self._filebrowser.scale_grid_view(scale)
def show_notification(self):
"""Utility to show the notification frame."""
self._filebrowser.show_notification()
def hide_notification(self):
"""Utility to hide the notification frame."""
self._filebrowser.hide_notification()
def _find_item_with_callback(self, path: str, callback: Callable):
"""
Wrapper around FilePickerModel.find_item_with_callback. This is a workaround for accessing the
model's class method, which in hindsight should've been made a utility function.
"""
model = FilePickerModel()
model.collections = self.collections
model.find_item_with_callback(path, callback)
def _server_status_changed(self, url: str, status: omni.client.ConnectionStatus) -> None:
"""Updates NucleuseConnectionItem signed in status based upon server status changed."""
item = self.get_connection_with_url(url)
if item:
if status == omni.client.ConnectionStatus.CONNECTED:
item.signed_in = True
FilePickerView.__connected_servers.add(url)
elif status == omni.client.ConnectionStatus.SIGNED_OUT:
item.signed_in = False
if url in FilePickerView.__connected_servers:
FilePickerView.__connected_servers.remove(url)
@staticmethod
def is_connected(url: str) -> bool:
return url in FilePickerView.__connected_servers
| 37,500 | Python | 40.667778 | 150 | 0.617867 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/style.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb
import omni.ui as ui
from pathlib import Path
try:
THEME = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle")
except Exception:
THEME = None
finally:
THEME = THEME or "NvidiaDark"
CURRENT_PATH = Path(__file__).parent.absolute()
ICON_ROOT = CURRENT_PATH.parent.parent.parent.parent.joinpath("icons/")
ICON_PATH = ICON_ROOT.joinpath(THEME)
THUMBNAIL_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data").joinpath("thumbnails")
def get_style():
if THEME == "NvidiaLight":
BACKGROUND_COLOR = 0xFF535354
BACKGROUND_SELECTED_COLOR = 0xFF6E6E6E
BACKGROUND_HOVERED_COLOR = 0xFF6E6E6E
SECONDARY_COLOR = 0xFFE0E0E0
BORDER_COLOR = 0xFF707070
MENU_BACKGROUND_COLOR = 0xFF343432
MENU_SEPARATOR_COLOR = 0x449E9E9E
PROGRESS_BACKGROUND = 0xFF606060
PROGRESS_BORDER = 0xFF323434
PROGRESS_BAR = 0xFFC9974C
PROGRESS_TEXT_COLOR = 0xFFD8D8D8
TITLE_COLOR = 0xFF707070
TEXT_COLOR = 0xFF8D760D
TEXT_HINT_COLOR = 0xFFD6D6D6
SPLITTER_HOVER_COLOR = 0xFFB0703B
else:
BACKGROUND_COLOR = 0xFF23211F
BACKGROUND_SELECTED_COLOR = 0xFF8A8777
BACKGROUND_HOVERED_COLOR = 0xFF3A3A3A
SECONDARY_COLOR = 0xFF9E9E9E
BORDER_COLOR = 0xFF8A8777
MENU_BACKGROUND_COLOR = 0xFF343432
MENU_SEPARATOR_COLOR = 0x449E9E9E
PROGRESS_BACKGROUND = 0xFF606060
PROGRESS_BORDER = 0xFF323434
PROGRESS_BAR = 0xFFC9974C
PROGRESS_TEXT_COLOR = 0xFFD8D8D8
TITLE_COLOR = 0xFFCECECE
TEXT_COLOR = 0xFF9E9E9E
TEXT_HINT_COLOR = 0xFF4A4A4A
SPLITTER_HOVER_COLOR = 0xFFB0703B
style = {
"Button": {
"background_color": BACKGROUND_COLOR,
"selected_color": BACKGROUND_SELECTED_COLOR,
"color": TEXT_COLOR,
"margin": 0,
"padding": 0
},
"Button:hovered": {"background_color": BACKGROUND_HOVERED_COLOR},
"Button.Label": {"color": TEXT_COLOR},
"Button.Label:disabled": {"color": BACKGROUND_HOVERED_COLOR},
"ComboBox": {
"background_color": BACKGROUND_COLOR,
"selected_color": BACKGROUND_SELECTED_COLOR,
"color": TEXT_COLOR,
},
"ComboBox:hovered": {"background_color": BACKGROUND_HOVERED_COLOR},
"ComboBox:selected": {"background_color": BACKGROUND_SELECTED_COLOR},
"ComboBox.Button": {
"background_color": BACKGROUND_COLOR,
"selected_color": BACKGROUND_SELECTED_COLOR,
"color": TEXT_COLOR,
"margin_width": 0,
"padding": 0,
},
"ComboBox.Button:hovered": {"background_color": BACKGROUND_HOVERED_COLOR},
"ComboBox.Button.Label": {"color": TEXT_COLOR, "alignment": ui.Alignment.LEFT_CENTER},
"ComboBox.Button.Glyph": {"color": 0xFFFFFFFF},
"ComboBox.Menu": {
"background_color": 0x0,
"margin": 0,
"padding": 0,
},
"ComboBox.Menu.Frame": {
"background_color": 0xFF343432,
"border_color": BORDER_COLOR,
"border_width": 0,
"border_radius": 4,
"margin": 2,
"padding": 0,
},
"ComboBox.Menu.Background": {
"background_color": 0xFF343432,
"border_color": BORDER_COLOR,
"border_width": 0,
"border_radius": 4,
"margin": 0,
"padding": 0,
},
"ComboBox.Menu.Item": {"background_color": 0x0, "color": TEXT_COLOR},
"ComboBox.Menu.Item:hovered": {"background_color": BACKGROUND_SELECTED_COLOR},
"ComboBox.Menu.Item:selected": {"background_color": BACKGROUND_SELECTED_COLOR},
"ComboBox.Menu.Item::left": {"color": TEXT_COLOR, "alignment": ui.Alignment.LEFT_CENTER},
"ComboBox.Menu.Item::right": {"color": TEXT_COLOR, "alignment": ui.Alignment.RIGHT_CENTER},
"Field": {"background_color": 0x0, "selected_color": BACKGROUND_SELECTED_COLOR, "color": TEXT_COLOR, "alignment": ui.Alignment.LEFT_CENTER},
"Label": {"background_color": 0x0, "color": TEXT_COLOR},
"Menu": {"background_color": MENU_BACKGROUND_COLOR, "color": TEXT_COLOR, "border_radius": 2},
"Menu.Item": {"background_color": 0x0, "margin": 0},
"Menu.Separator": {"background_color": 0x0, "color": MENU_SEPARATOR_COLOR},
"Rectangle": {"background_color": 0x0},
"FileBar": {"background_color": BACKGROUND_COLOR, "color": TEXT_COLOR},
"FileBar.Label": {"background_color": 0x0, "color": TEXT_COLOR, "alignment": ui.Alignment.LEFT_CENTER, "margin_width": 4, "margin_height": 0},
"FileBar.Label:disabled": {"color": TEXT_HINT_COLOR},
"DetailView": {"background_color": BACKGROUND_COLOR, "color": TEXT_COLOR, "margin": 0, "padding": 0},
"DetailView.ScrollingFrame": {"background_color": BACKGROUND_COLOR, "secondary_color": SECONDARY_COLOR},
"DetailFrame": {
"background_color": BACKGROUND_COLOR,
"secondary_color": 0xFF0000FF,
"color": TEXT_COLOR,
"border_radius": 1,
"border_color": 0xFF535354,
"margin_width": 4,
"margin_height": 1.5,
"padding": 0
},
"DetailFrame.Header.Label": {"color": TITLE_COLOR},
"DetailFrame.Header.Icon": {"color": 0xFFFFFFFF, "padding": 0, "alignment": ui.Alignment.LEFT_CENTER},
"DetailFrame.Body": {"margin_height": 2, "padding": 0},
"DetailFrame.Separator": {"background_color": TEXT_HINT_COLOR},
"DetailFrame.LineItem::left_aligned": {"alignment": ui.Alignment.LEFT_CENTER},
"DetailFrame.LineItem::right_aligned": {"alignment": ui.Alignment.RIGHT_CENTER},
"ProgressBar": {
"background_color": PROGRESS_BACKGROUND,
"border_width": 2,
"border_radius": 0,
"border_color": PROGRESS_BORDER,
"color": PROGRESS_BAR,
"secondary_color": PROGRESS_TEXT_COLOR,
"margin": 0,
"padding": 0,
"alignment": ui.Alignment.LEFT_CENTER,
},
"ProgressBar.Frame": {"background_color": BACKGROUND_COLOR, "margin": 0, "padding": 0},
"ProgressBar.Puck": {"background_color": PROGRESS_BAR, "margin": 2},
"ToolBar": {"alignment": ui.Alignment.CENTER, "margin_height": 2},
"ToolBar.Button": {"background_color": 0x0, "color": TEXT_COLOR, "margin_width": 2, "padding": 2},
"ToolBar.Button.Label": {"color": TEXT_COLOR, "alignment": ui.Alignment.LEFT_CENTER},
"ToolBar.Button.Image": {"background_color": 0x0, "color": 0xFFFFFFFF, "alignment": ui.Alignment.CENTER},
"ToolBar.Button:hovered": {"background_color": 0xFF6E6E6E},
"ToolBar.Field": {"background_color": BACKGROUND_COLOR, "color": TEXT_COLOR, "margin": 0, "padding": 0},
"Splitter": {"background_color": 0x0, "margin_width": 0},
"Splitter:hovered": {"background_color": SPLITTER_HOVER_COLOR},
"Splitter:pressed": {"background_color": SPLITTER_HOVER_COLOR},
"LoadingPane.Bg": {"background_color": BACKGROUND_COLOR},
"LoadingPane.Button": {
"background_color": BACKGROUND_HOVERED_COLOR,
"selected_color": BACKGROUND_SELECTED_COLOR,
"color": TEXT_COLOR,
},
"LoadingPane.Button:hovered": {"background_color": BACKGROUND_SELECTED_COLOR},
}
return style
| 7,983 | Python | 45.418604 | 150 | 0.613429 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/timestamp.py | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["TimestampWidget"]
import datetime
import omni.ui as ui
from .datetime import DateWidget, TimeWidget, TimezoneWidget
from typing import List
from .style import get_style
class TimestampWidget:
def __init__(self, **kwargs):
"""
Timestamp Widget.
"""
self._url = None
self._on_check_changed_fn = []
self._checkpoint_widget = None
self._frame = None
self._timestamp_checkbox = None
self._datetime_stack = None
self._desc_text = None
self._date = None
self._time = None
self._timezone = None
self._selection_changed_fn = kwargs.get("selection_changed_fn", None)
self._frame = ui.Frame(visible=True, height=100, style=get_style())
self._frame.set_build_fn(self._build_ui)
self._frame.rebuild()
def __del__(self):
self.destroy()
def destroy(self):
self._on_check_changed_fn.clear()
self._checkpoint_widget = None
self._selection_changed_fn = None
if self._timestamp_checkbox:
self._timestamp_checkbox.model.remove_value_changed_fn(self._checkbox_fn_id)
self._timestamp_checkbox = None
self._datetime_stack = None
self._frame = None
if self._date:
self._date.model.remove_value_changed_fn(self._date_fn_id)
self._date.destroy()
self._date = None
if self._time:
self._time.model.remove_value_changed_fn(self._time_fn_id)
self._time.destroy()
self._time = None
if self._timezone:
self._timezone.model.remove_value_changed_fn(self._timezone_fn_id)
self._timezone.destroy()
self._timezone = None
def rebuild(self, selected: List[str]):
self._frame.rebuild()
def _build_ui(self):
with ui.ZStack(height=32, width=0):
self._datetime_stack = ui.VStack(visible=False)
with self._datetime_stack:
with ui.HStack(height=0, spacing=6):
self._timestamp_checkbox = ui.CheckBox(width=0)
self._checkbox_fn_id = self._timestamp_checkbox.model.add_value_changed_fn(self._on_timestamp_checked)
ui.Label("Resolve with")
with ui.HStack(height=0, spacing=0):
ui.Label("Date:", width=0)
self._date = DateWidget()
self._date_fn_id = self._date.model.add_value_changed_fn(self._on_timestamp_changed)
ui.Label("Time:", width=0)
self._time = TimeWidget()
self._time_fn_id = self._time.model.add_value_changed_fn(self._on_timestamp_changed)
self._timezone = TimezoneWidget()
self._timezone_fn_id = self._timezone.model.add_value_changed_fn(self._on_timestamp_changed)
self._desc_text = ui.Label("does not support")
@staticmethod
def create_timestamp_widget() -> 'TimestampWidget':
widget = TimestampWidget()
return widget
@staticmethod
def delete_timestamp_widget(widget: 'TimestampWidget'):
if widget:
widget.destroy()
@staticmethod
def on_selection_changed(widget: 'TimestampWidget', selected: List[str]):
if not widget:
return
if selected:
widget.set_url(selected[-1] or None)
else:
widget.set_url(None)
# show timestamp status according to the checkpoint_widget status
def set_checkpoint_widget(self, widget):
self._checkpoint_widget = widget
def on_list_checkpoint(self, select):
# Fix OM-85963: It seems this called without UI (not builded or destory?) in some test
if self._datetime_stack:
has_checkpoint = self._checkpoint_widget is not None and not self._checkpoint_widget.empty()
self._datetime_stack.visible = has_checkpoint
self._desc_text.visible = not has_checkpoint
def set_url(self, url):
self._url = url
def get_timestamp_url(self, url):
if url and url != self._url:
return url
if not self._timestamp_checkbox.model.as_bool:
return self._url
dt = datetime.datetime(
self._date.model.year,
self._date.model.month,
self._date.model.day,
self._time.model.hour,
self._time.model.minute,
self._time.model.second,
tzinfo=self._timezone.model.timezone,
)
full_url = f"{self._url}?×tamp={int(dt.timestamp())}"
return full_url
def add_on_check_changed_fn(self, fn):
self._on_check_changed_fn.append(fn)
def _on_timestamp_checked(self, model):
full_url = self.get_timestamp_url(None)
for fn in self._on_check_changed_fn:
fn(full_url)
def _on_timestamp_changed(self, model):
if self._timestamp_checkbox.model.as_bool:
self._on_timestamp_checked(None)
@property
def check(self):
if self._timestamp_checkbox:
return self._timestamp_checkbox.model.as_bool
return False
@check.setter
def check(self, value: bool):
if self._timestamp_checkbox:
self._timestamp_checkbox.model.set_value(value)
| 5,838 | Python | 34.822086 | 122 | 0.595923 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/about_dialog.py | # Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from typing import Callable
from omni.kit.window.popup_dialog.dialog import PopupDialog
import omni.ui as ui
from .style import get_style, ICON_PATH
class AboutDialog(PopupDialog):
"""Dialog to show the omniverse server info."""
def __init__(
self,
server_info,
):
"""
Args:
server_info ([FileBrowserItem]): server's information.
title (str): Title of the dialog. Default "Confirm File Deletion".
width (int): Dialog width. Default `500`.
ok_handler (Callable): Function to execute upon clicking the "Yes" button. Function signature:
void ok_handler(dialog: :obj:`PopupDialog`)
"""
super().__init__(
width=400,
title="About",
ok_handler=lambda self: self.hide(),
ok_label="Close",
modal=True,
)
self._server_info = server_info
self._build_ui()
def _build_ui(self) -> None:
with self._window.frame:
with ui.ZStack(style=get_style(),spacing=6):
ui.Rectangle(style_type_name_override="Background")
with ui.VStack(style_type_name_override="Dialog", spacing=6):
ui.Spacer(height=25)
with ui.HStack(style_type_name_override="Dialog", spacing=6, height=60):
ui.Spacer(width=15)
ui.Image(
f"{ICON_PATH}/omniverse_logo_64.png",
width=50,
height=50,
alignment=ui.Alignment.CENTER
)
ui.Spacer(width=5)
with ui.VStack(style_type_name_override="Dialog"):
ui.Spacer(height=10)
ui.Label("Nucleus", style={"font_size": 20})
ui.Label(self._server_info.version)
ui.Spacer(height=5)
with ui.HStack(style_type_name_override="Dialog"):
ui.Spacer(width=15)
with ui.VStack(style_type_name_override="Dialog"):
ui.Label("Services", style={"font_size": 20})
self._build_info_item(True, "Discovery")
# OM-94622: what it this auth for? seems token is not correct
self._build_info_item(True, "Auth 1.4.5+tag-" + self._server_info.auth_token[:8])
has_tagging = False
try:
# TODO: how to check the tagging is exist? how to get it's version?
import omni.tagging_client
has_tagging = True
except ImportError:
pass
self._build_info_item(has_tagging, "Tagging")
# there always has search service in content browser
self._build_info_item(True, "NGSearch")
self._build_info_item(True, "Search")
ui.Label("Features", style={"font_size": 20})
self._build_info_item(True, "Versioning")
self._build_info_item(self._server_info.checkpoints_enabled, "Atomic checkpoints")
self._build_info_item(self._server_info.omniojects_enabled, "Omni-objects V2")
self._build_ok_cancel_buttons(disable_cancel_button=True)
def _build_info_item(self, supported: bool, info: str):
with ui.HStack(style_type_name_override="Dialog", spacing=6):
ui.Spacer(width=5)
if supported:
ui.Image(
"resources/icons/Ok_64.png",
width=20,
height=20,
alignment=ui.Alignment.CENTER
)
else:
ui.Image(
"resources/icons/Cancel_64.png",
width=20,
height=20,
alignment=ui.Alignment.CENTER
)
ui.Label(info)
ui.Spacer()
def destroy(self) -> None:
"""Destructor."""
self._window = None
| 4,829 | Python | 43.722222 | 110 | 0.502174 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/extension.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ext
import omni.kit.app
import omni.client
from carb import events, log_warn
from .utils import exec_after_redraw
from .view import (
BOOKMARK_ADDED_EVENT, BOOKMARK_DELETED_EVENT, BOOKMARK_RENAMED_EVENT,
NUCLEUS_SERVER_ADDED_EVENT, NUCLEUS_SERVER_DELETED_EVENT, NUCLEUS_SERVER_RENAMED_EVENT
)
g_singleton = None
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class FilePickerExtension(omni.ext.IExt):
"""
The filepicker extension is not necessarily integral to using the widget. However, it is useful for handling
singleton tasks for the class.
"""
def on_startup(self, ext_id):
# Save away this instance as singleton
global g_singleton
g_singleton = self
# Listen for bookmark and server connection events in order to update persistent settings
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
self._event_stream_subscriptions = [
event_stream.create_subscription_to_pop_by_type(BOOKMARK_ADDED_EVENT, self._update_persistent_bookmarks),
event_stream.create_subscription_to_pop_by_type(BOOKMARK_DELETED_EVENT, self._update_persistent_bookmarks),
event_stream.create_subscription_to_pop_by_type(BOOKMARK_RENAMED_EVENT, self._update_persistent_bookmarks),
event_stream.create_subscription_to_pop_by_type(NUCLEUS_SERVER_ADDED_EVENT, self._update_persistent_bookmarks),
event_stream.create_subscription_to_pop_by_type(NUCLEUS_SERVER_DELETED_EVENT, self._update_persistent_bookmarks),
event_stream.create_subscription_to_pop_by_type(NUCLEUS_SERVER_RENAMED_EVENT, self._update_persistent_bookmarks),
]
def _update_persistent_bookmarks(self, event: events.IEvent):
"""When a bookmark is updated or deleted, update persistent settings"""
try:
payload = event.payload.get_dict()
except Exception as e:
log_warn(f"Failed to add omni.client bookmark: {str(e)}")
return
if event.type in [BOOKMARK_ADDED_EVENT, NUCLEUS_SERVER_ADDED_EVENT]:
name = payload.get('name')
url = payload.get('url')
if name and url:
omni.client.add_bookmark(name, url)
elif event.type in [BOOKMARK_DELETED_EVENT, NUCLEUS_SERVER_DELETED_EVENT]:
name = payload.get('name')
if name:
omni.client.remove_bookmark(name)
elif event.type in [BOOKMARK_RENAMED_EVENT, NUCLEUS_SERVER_RENAMED_EVENT]:
old_name = payload.get('old_name')
new_name = payload.get('new_name')
url = payload.get('url')
if old_name and new_name and url:
omni.client.add_bookmark(new_name, url)
if old_name != new_name:
# Wait a few frames for next update to avoid race condition
exec_after_redraw(lambda: omni.client.remove_bookmark(old_name), wait_frames=6)
def on_shutdown(self):
# Clears the auth callback
self._event_stream_subscriptions.clear()
global g_singleton
g_singleton = None
def get_instance():
return g_singleton | 3,845 | Python | 44.785714 | 125 | 0.681144 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/detail_view.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
import omni.ui as ui
import asyncio
import omni.client
from omni.kit.async_engine import run_coroutine
from typing import Callable, List
from collections import namedtuple
from collections import OrderedDict
from carb import log_warn
from datetime import datetime
from omni.kit.helper.file_utils import asset_types
from omni.kit.widget.filebrowser import FileBrowserItem
from .style import get_style, ICON_PATH
class DetailFrameController:
def __init__(self,
glyph: str = None,
build_fn: Callable[[], None] = None,
selection_changed_fn: Callable[[List[str]], None] = None,
filename_changed_fn: Callable[[str], None] = None,
destroy_fn: Callable[[], None] = None,
**kwargs
):
self._frame = None
self._glyph = glyph
self._build_fn = build_fn
self._selection_changed_fn = selection_changed_fn
self._filename_changed_fn = filename_changed_fn
self._destroy_fn = destroy_fn
self._mouse_pressed_fn = kwargs.get("mouse_pressed_fn", None)
self._mouse_double_clicked_fn = kwargs.get("mouse_double_clicked_fn", None)
def build_header(self, collapsed: bool, title: str):
with ui.HStack():
if collapsed:
ui.ImageWithProvider(f"{ICON_PATH}/arrow_right.svg", width=20, height=20)
else:
ui.ImageWithProvider(f"{ICON_PATH}/arrow_down.svg", width=20, height=20)
ui.Label(title.capitalize(), style_type_name_override="DetailFrame.Header.Label")
def build_ui(self, frame: ui.Frame):
if not frame:
return
self._frame = frame
with self._frame:
try:
self._build_fn()
except Exception as e:
log_warn(f"Error detail frame build_ui: {str(e)}")
def on_selection_changed(self, selected: List[str] = []):
if self._frame and self._selection_changed_fn:
self._frame.set_build_fn(lambda: self._selection_changed_fn(selected))
self._frame.rebuild()
def on_filename_changed(self, filename: str):
if self._frame and self._filename_changed_fn:
self._frame.set_build_fn(lambda: self._filename_changed_fn(filename))
self._frame.rebuild()
def destroy(self):
try:
self._destroy_fn()
except Exception:
pass
# NOTE: DO NOT dereference callbacks so that we can rebuild this object if desired.
self._frame = None
class ExtendedFileInfo(DetailFrameController):
MockListEntry = namedtuple("MockListEntry", "relative_path modified_time created_by modified_by size")
_empty_list_entry = MockListEntry("File info", datetime.now(), "", "", 0)
def __init__(self):
super().__init__(
build_fn=self._build_ui_impl,
selection_changed_fn=self._on_selection_changed_impl,
destroy_fn=self._destroy_impl)
self._widget = None
self._current_url = ""
self._resolve_subscription = None
self._time_label = None
self._created_by_label = None
self._modified_by_label = None
self._size_label = None
def build_header(self, collapsed: bool, title: str):
with ui.HStack(style_type_name_override="DetailFrame.Header"):
if collapsed:
ui.ImageWithProvider(f"{ICON_PATH}/arrow_right.svg", width=20, height=20)
else:
ui.ImageWithProvider(f"{ICON_PATH}/arrow_down.svg", width=20, height=20)
icon = asset_types.get_icon(title)
if icon is not None:
ui.ImageWithProvider(icon, width=18, style_type_name_override="DetailFrame.Header.Icon")
ui.Spacer(width=4)
ui.Label(title, elided_text=True, tooltip=title, style_type_name_override="DetailFrame.Header.Label")
def _build_ui_impl(self, selected: List[str] = []):
self._widget = ui.Frame()
run_coroutine(self._build_ui_async(selected))
async def _build_ui_async(self, selected: List[str] = []):
entry = None
if len(selected) == 0:
self._frame.title = "No files selected"
elif len(selected) > 1:
self._frame.title = "Multiple files selected"
else:
result, entry = await omni.client.stat_async(selected[-1])
if result == omni.client.Result.OK and entry:
self._frame.title = entry.relative_path or os.path.basename(selected[-1])
if self._current_url != selected[-1]:
self._current_url = selected[-1]
self._resolve_subscription = omni.client.resolve_subscribe_with_callback(
self._current_url, [self._current_url], None,
lambda result, event, entry, url: self._on_file_change_event(result, entry))
else:
self._frame.title = os.path.basename(selected[-1])
entry = None
entry = entry or self._empty_list_entry
with self._widget:
with ui.ZStack():
ui.Rectangle()
with ui.VStack():
ui.Rectangle(height=2, style_type_name_override="DetailFrame.Separator")
with ui.VStack(style_type_name_override="DetailFrame.Body"):
with ui.HStack(style_type_name_override="DetailFrame.LineItem", spacing=3):
ui.Label("Date Modified", width=0, name="left_aligned")
self._time_label = ui.Label(
FileBrowserItem.datetime_as_string(entry.modified_time),
elided_text=True,
alignment=ui.Alignment.RIGHT_CENTER,
name="right_aligned"
)
with ui.HStack(style_type_name_override="DetailFrame.LineItem", spacing=3):
ui.Label("Created by", width=0, name="left_aligned")
self._created_by_label = ui.Label(entry.created_by,
elided_text=True,
alignment=ui.Alignment.RIGHT_CENTER,
name="right_aligned"
)
with ui.HStack(style_type_name_override="DetailFrame.LineItem", spacing=3):
ui.Label("Modified by", width=0, name="left_aligned")
self._modified_by_label = ui.Label(
entry.modified_by,
elided_text=True,
alignment=ui.Alignment.RIGHT_CENTER,
name="right_aligned"
)
with ui.HStack(style_type_name_override="DetailFrame.LineItem", spacing=3):
ui.Label("File size", width=0, name="left_aligned")
self._size_label = ui.Label(
FileBrowserItem.size_as_string(entry.size),
elided_text=True,
alignment=ui.Alignment.RIGHT_CENTER,
name="right_aligned"
)
def _on_file_change_event(self, result: omni.client.Result, entry: omni.client.ListEntry):
if result == omni.client.Result.OK and self._current_url:
self._time_label.text = FileBrowserItem.datetime_as_string(entry.modified_time)
self._created_by_label.text = entry.created_by
self._modified_by_label.text = entry.modified_by
self._size_label.text = FileBrowserItem.size_as_string(entry.size)
def _on_selection_changed_impl(self, selected: List[str] = []):
self._build_ui_impl(selected)
def _destroy_impl(self, _):
if self._widget:
self._widget.destroy()
self._widget = None
self._resolve_subscription = None
class DetailView:
def __init__(self, **kwargs):
self._widget: ui.Widget = None
self._view: ui.Widget = None
self._file_info = None
self._detail_frames: OrderedDict[str, DetailFrameController] = OrderedDict()
self._build_ui()
def _build_ui(self):
self._widget = ui.Frame()
with self._widget:
with ui.ZStack(style=get_style()):
ui.Rectangle(style_type_name_override="DetailView")
self._view = ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
style_type_name_override="DetailView.ScrollingFrame"
)
self._build_detail_frames()
def _build_detail_frames(self):
async def build_frame_async(frame: ui.Frame, detail_frame: DetailFrameController):
detail_frame.build_ui(frame)
with self._view:
with ui.VStack():
self._file_info = ExtendedFileInfo()
frame = ui.CollapsableFrame(title="File info", height=0, build_header_fn=self._file_info.build_header, style_type_name_override="DetailFrame")
run_coroutine(build_frame_async(frame, self._file_info))
for name, detail_frame in reversed(self._detail_frames.items()):
frame = ui.CollapsableFrame(title=name.capitalize(), height=0, build_header_fn=detail_frame.build_header, style_type_name_override="DetailFrame")
run_coroutine(build_frame_async(frame, detail_frame))
def get_detail_frame(self, name: str) -> DetailFrameController:
if name:
return self._detail_frames.get(name, None)
return None
def add_detail_frame(self,
name: str, glyph: str,
build_fn: Callable[[], ui.Widget],
selection_changed_fn: Callable[[List[str]], None] = None,
filename_changed_fn: Callable[[str], None] = None,
destroy_fn: Callable[[ui.Widget], None] = None):
"""
Adds sub-frame to the detail view, and populates it with a custom built widget.
Args:
name (str): Name of the widget sub-section, this name must be unique over all detail sub-sections.
glyph (str): Associated glyph to display for this subj-section
build_fn (Callable): This callback function builds the widget.
Keyword Args:
selection_changed_fn (Callable): This callback is invoked to handle selection changes.
filename_changed_fn (Callable): This callback is invoked when filename is changed.
destroy_fn (Callable): Cleanup function called when destroyed.
"""
if not name:
return
elif name in self._detail_frames.keys():
# Reject duplicates
log_warn(f"Unable to add detail widget '{name}': already exists.")
return
detail_frame = DetailFrameController(
glyph=glyph,
build_fn=build_fn,
selection_changed_fn=selection_changed_fn,
filename_changed_fn=filename_changed_fn,
destroy_fn=destroy_fn,
)
self.add_detail_frame_from_controller(name, detail_frame)
def add_detail_frame_from_controller(self, name: str, detail_frame: DetailFrameController = None):
"""
Adds sub-frame to the detail view, and populates it with a custom built widget.
Args:
name (str): Name of the widget sub-section, this name must be unique over all detail sub-sections.
controller (:obj:`DetailFrameController`): Controller object that encapsulates all aspects of creating,
updating, and deleting a detail frame widget.
"""
if not name:
return
elif name in self._detail_frames.keys():
# Reject duplicates
log_warn(f"Unable to add detail widget '{name}': already exists.")
return
if detail_frame:
self._detail_frames[name] = detail_frame
self._build_detail_frames()
def delete_detail_frame(self, name: str):
"""
Deletes the specified detail frame.
Args:
name (str): Name of the detail frame.
"""
if name in self._detail_frames.keys():
del self._detail_frames[name]
self._build_detail_frames()
def on_selection_changed(self, selected: List[FileBrowserItem] = []):
"""
When the user changes their filebrowser selection(s), invokes the callbacks for the detail frames.
Args:
selected (:obj:`FileBrowserItem`): List of new selections.
"""
selected_paths = [sel.path for sel in selected if sel]
if self._file_info:
self._file_info.on_selection_changed(selected_paths)
for _, detail_frame in self._detail_frames.items():
detail_frame.on_selection_changed(selected_paths)
def on_filename_changed(self, filename: str = ''):
"""
When the user edits the filename, invokes the callbacks for the detail frames.
Args:
filename (str): Current filename.
"""
for _, detail_frame in self._detail_frames.items():
detail_frame.on_filename_changed(filename)
def destroy(self):
for _, detail_frame in self._detail_frames.items():
detail_frame.destroy()
self._detail_frames.clear()
self._widget = None
self._view = None | 14,144 | Python | 42.523077 | 165 | 0.583498 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/__init__.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""
This Kit extension provides both a popup dialog as well as an embeddable widget that
you can add to your code for browsing the filesystem. Incorporates
:obj:`BrowserBarWidget` and :obj:`FileBrowserWidget` into a general-purpose utility.
The filesystem can either be from your local machine or the Omniverse server.
Example:
With just a few lines of code, you can create a ready-made dialog window. Then,
customize it by setting any number of attributes.
filepicker = FilePickerDialog(
"my-filepicker",
apply_button_label="Open",
click_apply_handler=on_click_open,
click_cancel_handler=on_click_cancel )
filepicker.show()
.. _Google Python Style Guide:
http://google.github.io/styleguide/pyguide.html
"""
import carb.events
UI_READY_EVENT: int = carb.events.type_from_string("omni.kit.window.filepicker.UI_READY")
SETTING_ROOT = "/exts/omni.kit.window.filepicker/"
SETTING_PERSISTENT_ROOT = "/persistent" + SETTING_ROOT
SETTING_PERSISTENT_SHOW_GRID_VIEW = SETTING_PERSISTENT_ROOT + "show_grid_view"
SETTING_PERSISTENT_GRID_VIEW_SCALE = SETTING_PERSISTENT_ROOT + "grid_view_scale"
from .extension import FilePickerExtension
from .dialog import FilePickerDialog
from .widget import FilePickerWidget
from .view import FilePickerView
from .model import FilePickerModel
from .api import FilePickerAPI
from .context_menu import (
BaseContextMenu,
ContextMenu,
CollectionContextMenu,
BookmarkContextMenu,
UdimContextMenu
)
from .detail_view import DetailView, DetailFrameController
from .tool_bar import ToolBar
from .timestamp import TimestampWidget
from omni.kit.widget.search_delegate import SearchDelegate, SearchResultsModel, SearchResultsItem
| 2,183 | Python | 37.315789 | 97 | 0.770499 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/bookmark_model.py | # Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["BookmarkItem", "BookmarkItemFactory", "BookmarkModel"]
import re
import omni.client
from typing import Dict
from datetime import datetime
from omni import ui
from omni.kit.widget.filebrowser import FileBrowserItem, FileBrowserModel, find_thumbnails_for_files_async
from omni.kit.widget.filebrowser.model import FileBrowserItemFields
from .style import ICON_PATH
class BookmarkItem(FileBrowserItem):
_thumbnail_dict: Dict = {}
def __init__(self, path: str, fields: FileBrowserItemFields, is_folder: bool = True):
super().__init__(path, fields, is_folder=is_folder)
self._path = self.format_bookmark_path(path)
self._expandable = False
def on_list_change_event(self, event: omni.client.ListEvent, entry: omni.client.ListEntry) -> bool:
"""
Handles ListEvent changes, should update this item's children list with the corresponding ListEntry.
Args:
event (:obj:`omni.client.ListEvent`): One of of {UNKNOWN, CREATED, UPDATED, DELETED, METADATA, LOCKED, UNLOCKED}.
entry (:obj:`omni.client.ListEntry`): Updated entry as defined by omni.client.
"""
# bookmark item doesn't need to populate children, so always return False indicating item is
# not changed
return False
def set_bookmark_path(self, path : str) -> None:
"""Sets the bookmark item path"""
self._path = path
@property
def readable(self) -> bool:
return (self._fields.permissions & omni.client.AccessFlags.READ) > 0
@property
def writeable(self) -> bool:
return (self._fields.permissions & omni.client.AccessFlags.WRITE) > 0
@property
def expandable(self) -> bool:
return self._expandable
@expandable.setter
def expandable(self, value: bool):
self._expandable = value
@property
def hideable(self) -> bool:
return False
def format_bookmark_path(self, path: str):
"""Helper method to generate a bookmark path from the given path."""
# OM-66726: Content Browser should edit bookmarks similar to Navigator
if self.is_local_path(path) and not path.startswith("file://"):
# Need to prefix "file://" for local path, so that local bookmark works in Navigator
path = "file://" + path
# make sure folder path ends with "/" so Navigator would recognize it as a directory
if self._is_folder:
path = path.rstrip("/") + "/"
return path
@staticmethod
def is_bookmark_folder(path: str):
"""Helper method to check if a given path is a bookmark of a folder."""
return path.endswith("/")
@staticmethod
def is_local_path(path: str) -> bool:
"""Returns True if given path is a local path"""
broken_url = omni.client.break_url(path)
if broken_url.scheme == "file":
return True
elif broken_url.scheme == "omniverse":
return False
# Return True if root directory looks like beginning of a Linux or Windows path
root_name = broken_url.path.split("/")[0]
return not root_name or re.match(r"[A-Za-z]:", root_name) is not None
async def get_custom_thumbnails_for_folder_async(self) -> Dict:
"""
Returns the thumbnail dictionary for this (folder) item.
Returns:
Dict: With children url's as keys, and url's to thumbnail files as values.
"""
if not self.is_folder:
return {}
# Files in the root folder only
file_urls = []
for _, item in self.children.items():
if item.is_folder or item.path in self._thumbnail_dict:
# Skip if folder or thumbnail previously found
pass
else:
file_urls.append(item.path)
thumbnail_dict = await find_thumbnails_for_files_async(file_urls)
for url, thumbnail_url in thumbnail_dict.items():
if url and thumbnail_url:
self._thumbnail_dict[url] = thumbnail_url
return self._thumbnail_dict
class BookmarkItemFactory:
@staticmethod
def create_bookmark_item(name: str, path: str, is_folder: bool = True) -> BookmarkItem:
if not name:
return None
access = omni.client.AccessFlags.READ | omni.client.AccessFlags.WRITE
fields = FileBrowserItemFields(name, datetime.now(), 0, access)
item = BookmarkItem(path, fields, is_folder=is_folder)
item._models = (ui.SimpleStringModel(item.name), datetime.now(), ui.SimpleStringModel(""))
return item
@staticmethod
def create_group_item(name: str, path: str) -> BookmarkItem:
item = BookmarkItemFactory.create_bookmark_item(name, path, is_folder=True)
item.icon = f"{ICON_PATH}/bookmark.svg"
item.populated = True
item.expandable = True
return item
class BookmarkModel(FileBrowserModel):
"""
A Bookmark model class for grouping bookmarks.
Args:
name (str): Name of root item.
root_path (str): Root path.
"""
def __init__(self, name: str, root_path: str, **kwargs):
super().__init__(**kwargs)
self._root = BookmarkItemFactory.create_group_item(name, root_path)
def add_bookmark(self, name: str, path: str, is_folder: bool = True) -> BookmarkItem:
if name and path:
item = BookmarkItemFactory.create_bookmark_item(name, path, is_folder=is_folder)
else:
return None
self._root.add_child(item)
self._item_changed(self._root)
return item
def delete_bookmark(self, item: BookmarkItem):
if item:
self._root.del_child(item.name)
self._item_changed(self._root)
| 6,219 | Python | 35.16279 | 125 | 0.6411 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/dialog.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb
import omni.ui as ui
from typing import List, Callable, Tuple
from omni.kit.widget.filebrowser import FileBrowserModel
from omni.kit.widget.search_delegate import SearchDelegate
from .widget import FilePickerWidget
from .detail_view import DetailFrameController
from .utils import exec_after_redraw
class FilePickerDialog:
"""
A popup window for browsing the filesystem and taking action on a selected file.
Includes a browser bar for keyboard input with auto-completion for navigation of the tree
view. For similar but different options, see also :obj:`FilePickerWidget` and :obj:`FilePickerView`.
Args:
title (str): Window title. Default None.
Keyword Args:
width (int): Window width. Default 1000.
height (int): Window height. Default 600.
click_apply_handler (Callable): Function that will be called when the user accepts
the selection. Function signature:
void apply_handler(file_name: str, dir_name: str).
click_cancel_handler (Callable): Function that will be called when the user clicks
the cancel button. Function signature:
void cancel_handler(file_name: str, dir_name: str).
other: Additional args listed for :obj:`FilePickerWidget`
"""
def __init__(self, title: str, **kwargs):
self._window = None
self._widget = None
self._width = kwargs.get("width", 1000)
self._height = kwargs.get("height", 600)
self._click_cancel_handler = kwargs.get("click_cancel_handler", None)
self._click_apply_handler = kwargs.get("click_apply_handler")
self.__show_task = None
self._key_functions = {
int(carb.input.KeyboardInput.ESCAPE): self._click_cancel_handler,
# OM-79404: Add enter key press handler
int(carb.input.KeyboardInput.ENTER): self._click_apply_handler,
}
self._build_ui(title, **kwargs)
def _build_ui(self, title: str, **kwargs):
window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_DOCKING
self._window = ui.Window(title, width=self._width, height=self._height, flags=window_flags)
self._window.set_key_pressed_fn(self._on_key_pressed)
def on_cancel(*args):
if self._click_cancel_handler:
self._click_cancel_handler(*args)
else:
self._window.visible = False
with self._window.frame:
kwargs["click_cancel_handler"] = on_cancel
self._key_functions[int(carb.input.KeyboardInput.ESCAPE)] = on_cancel
self._widget = FilePickerWidget(title, window=self._window, **kwargs)
self._window.set_width_changed_fn(self._widget._on_window_width_changed)
def _on_key_pressed(self, key, mod, pressed):
if not pressed:
return
func = self._key_functions.get(key)
if func and mod in (0, ui.Widget.FLAG_WANT_CAPTURE_KEYBOARD):
filename, dirname = self._widget.get_selected_filename_and_directory()
func(filename, dirname)
def set_visibility_changed_listener(self, listener: Callable[[bool], None]):
"""
Call the given handler when window visibility is changed.
Args:
listener (Callable): Handler with signature listener[visible: bool).
"""
if self._window:
self._window.set_visibility_changed_fn(listener)
def add_connections(self, connections: dict):
"""
Adds specified server connections to the browser.
Args:
connections (dict): A dictionary of name, path pairs. For example:
{"C:": "C:", "ov-content": "omniverse://ov-content"}. Paths to Omniverse servers
should be prefixed with "omniverse://".
"""
self._widget.api.add_connections(connections)
def set_current_directory(self, path: str):
"""
Procedurally sets the current directory path.
Args:
path (str): The full path name of the folder, e.g. "omniverse://ov-content/Users/me.
Raises:
:obj:`RuntimeWarning`: If path doesn't exist or is unreachable.
"""
self._widget.api.set_current_directory(path)
def get_current_directory(self) -> str:
"""
Returns the current directory from the browser bar.
Returns:
str: The system path, which may be different from the displayed path.
"""
return self._widget.api.get_current_directory()
def get_current_selections(self, pane: int = 2) -> List[str]:
"""
Returns current selected as list of system path names.
Args:
pane (int): Specifies pane to retrieve selections from, one of {TREEVIEW_PANE = 1, LISTVIEW_PANE = 2,
BOTH = None}. Default LISTVIEW_PANE.
Returns:
[str]: List of system paths (which may be different from displayed paths, e.g. bookmarks)
"""
return self._widget.api.get_current_selections(pane)
def set_filename(self, filename: str):
"""
Sets the filename in the file bar, at bottom of the dialog.
Args:
filename (str): The filename only (and not the fullpath), e.g. "myfile.usd".
"""
self._widget.api.set_filename(filename)
def get_filename(self) -> str:
"""
Returns:
str: Currently selected filename.
"""
return self._widget.api.get_filename()
def get_file_postfix(self) -> str:
"""
Returns:
str: Currently selected postfix.
"""
return self._widget.file_bar.selected_postfix
def set_file_postfix(self, postfix: str):
"""Sets the file postfix in the file bar."""
self._widget.file_bar.set_postfix(postfix)
def get_file_postfix_options(self) -> List[str]:
"""
Returns:
List[str]: List of all postfix strings.
"""
return self._widget.file_bar.postfix_options
def get_file_extension(self) -> str:
"""
Returns:
str: Currently selected filename extension.
"""
return self._widget.file_bar.selected_extension
def set_file_extension(self, extension: str):
"""Sets the file extension in the file bar."""
self._widget.file_bar.set_extension(extension)
def get_file_extension_options(self) -> List[Tuple[str, str]]:
"""
Returns:
List[str]: List of all extension options strings.
"""
return self._widget.file_bar.extension_options
def set_filebar_label_name(self, name: str):
"""
Sets the text of the name label for filebar, at the bottom of dialog.
Args:
name (str): By default, it's "File name" if it's not set. For some senarios that,
it only allows to choose folder, it can be configured with this API for better UX.
"""
self._widget.file_bar.label_name = name
def get_filebar_label_name(self) -> str:
"""
Returns:
str: Currently text of name label for file bar.
"""
return self._widget.file_bar.label_name
def set_item_filter_fn(self, item_filter_fn: Callable[[str], bool]):
"""
Sets the item filter function.
Args:
item_filter_fn (Callable): Signature is bool fn(item: FileBrowserItem)
"""
self._widget.set_item_filter_fn(item_filter_fn)
def set_click_apply_handler(self, click_apply_handler: Callable[[str, str], None]):
"""
Sets the function to execute upon clicking apply.
Args:
click_apply_handler (Callable): Signature is void fn(filename: str, dirname: str)
"""
self._widget.set_click_apply_handler(click_apply_handler)
# OM-79404: update key func for ENTER key when reseting click apply handler
self._key_functions[int(carb.input.KeyboardInput.ENTER)] = click_apply_handler
def navigate_to(self, path: str):
"""
Navigates to a path, i.e. the path's parent directory will be expanded and leaf selected.
Args:
path (str): The path to navigate to.
"""
self._widget.api.navigate_to(path)
def toggle_bookmark_from_path(self, name: str, path: str, is_bookmark: bool, is_folder: bool = True):
"""
Adds/deletes the given bookmark with the specified path. If deleting, then the path argument
is optional.
Args:
name (str): Name to call the bookmark or existing name if delete.
path (str): Path to the bookmark.
is_bookmark (bool): True to add, False to delete.
is_folder (bool): Whether the item to be bookmarked is a folder.
"""
self._widget.api.toggle_bookmark_from_path(name, path, is_bookmark, is_folder=is_folder)
def refresh_current_directory(self):
"""Refreshes the current directory set in the browser bar."""
self._widget.api.refresh_current_directory()
@property
def current_filter_option(self):
"""int: Index of current filter option, range 0 .. num_filter_options."""
return self._widget.current_filter_option
def add_detail_frame_from_controller(self, name: str, controller: DetailFrameController):
"""
Adds subsection to the detail view, and populate it with a custom built widget.
Args:
name (str): Name of the widget sub-section, this name must be unique over all detail sub-sections.
controller (:obj:`DetailFrameController`): Controller object that encapsulates all aspects of creating,
updating, and deleting a detail frame widget.
Returns:
ui.Widget: Handle to created widget.
"""
self._widget.api.add_detail_frame_from_controller(name, controller)
def delete_detail_frame(self, name: str):
"""
Deletes the named detail frame.
Args:
name (str): Name of the frame.
"""
self._widget.api.delete_detail_frame(name)
def set_search_delegate(self, delegate: SearchDelegate):
"""
Sets a custom search delegate for the tool bar.
Args:
delegate (:obj:`SearchDelegate`): Object that creates the search widget.
"""
self._widget.api.set_search_delegate(delegate)
def show_model(self, model: FileBrowserModel):
"""
Displays the given model in the list view, overriding the default model. For example, this model
might be the result of a search.
Args:
model (:obj:`FileBrowserModel`): Model to display.
"""
self._widget.api.show_model(model)
def show(self, path: str = None):
"""
Shows this dialog. Currently pops up atop all other windows but is not completely
modal, i.e. does not take over input focus.
Args:
path (str): If optional path is specified, then navigates to it upon startup.
"""
self._window.visible = True
if path:
if self.__show_task:
self.__show_task.cancel()
self.__show_task = exec_after_redraw(lambda path=path: self.navigate_to(path), 6)
def hide(self):
"""
Hides this dialog. Automatically called when "Cancel" buttons is clicked.
"""
self._window.visible = False
def destroy(self):
"""Destructor."""
if self.__show_task:
self.__show_task.cancel()
self.__show_task = None
if self._widget is not None:
self._widget.destroy()
self._widget = None
if self._window:
self.set_visibility_changed_listener(None)
self._window.destroy()
self._window = None
| 12,357 | Python | 34.409742 | 115 | 0.616655 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/asset_types.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb.settings
from typing import Dict
from collections import namedtuple
from .style import ICON_PATH, THUMBNAIL_PATH
AssetTypeDef = namedtuple("AssetTypeDef", "glyph thumbnail matching_exts")
# The known list of asset types, stored in this singleton variable
_known_asset_types: Dict = None
# Default Asset types
ASSET_TYPE_ANIM_USD = "anim_usd"
ASSET_TYPE_CACHE_USD = "cache_usd"
ASSET_TYPE_CURVE_ANIM_USD = "curve_anim_usd"
ASSET_TYPE_GEO_USD = "geo_usd"
ASSET_TYPE_MATERIAL_USD = "material_usd"
ASSET_TYPE_PROJECT_USD = "project_usd"
ASSET_TYPE_SEQ_USD = "seq_usd"
ASSET_TYPE_SKEL_USD = "skel_usd"
ASSET_TYPE_SKEL_ANIM_USD = "skel_anim_usd"
ASSET_TYPE_USD_SETTINGS = "settings_usd"
ASSET_TYPE_USD = "usd"
ASSET_TYPE_FBX = "fbx"
ASSET_TYPE_OBJ = "obj"
ASSET_TYPE_MATERIAL = "material"
ASSET_TYPE_IMAGE = "image"
ASSET_TYPE_SOUND = "sound"
ASSET_TYPE_SCRIPT = "script"
ASSET_TYPE_VOLUME = "volume"
ASSET_TYPE_FOLDER = "folder"
ASSET_TYPE_ICON = "icon"
ASSET_TYPE_HIDDEN = "hidden"
ASSET_TYPE_UNKNOWN = "unknown"
def _init_asset_types():
global _known_asset_types
_known_asset_types = {}
_known_asset_types[ASSET_TYPE_USD_SETTINGS] = AssetTypeDef(
f"{ICON_PATH}/settings_usd.svg",
f"{THUMBNAIL_PATH}/settings_usd_256.png",
[".settings.usd", ".settings.usda", ".settings.usdc", ".settings.usdz"],
)
_known_asset_types[ASSET_TYPE_ANIM_USD] = AssetTypeDef(
f"{ICON_PATH}/anim_usd.svg",
f"{THUMBNAIL_PATH}/anim_usd_256.png",
[".anim.usd", ".anim.usda", ".anim.usdc", ".anim.usdz"],
)
_known_asset_types[ASSET_TYPE_CACHE_USD] = AssetTypeDef(
f"{ICON_PATH}/cache_usd.svg",
f"{THUMBNAIL_PATH}/cache_usd_256.png",
[".cache.usd", ".cache.usda", ".cache.usdc", ".cache.usdz"],
)
_known_asset_types[ASSET_TYPE_CURVE_ANIM_USD] = AssetTypeDef(
f"{ICON_PATH}/anim_usd.svg",
f"{THUMBNAIL_PATH}/curve_anim_usd_256.png",
[".curveanim.usd", ".curveanim.usda", ".curveanim.usdc", ".curveanim.usdz"],
)
_known_asset_types[ASSET_TYPE_GEO_USD] = AssetTypeDef(
f"{ICON_PATH}/geo_usd.svg",
f"{THUMBNAIL_PATH}/geo_usd_256.png",
[".geo.usd", ".geo.usda", ".geo.usdc", ".geo.usdz"],
)
_known_asset_types[ASSET_TYPE_MATERIAL_USD] = AssetTypeDef(
f"{ICON_PATH}/material_usd.png",
f"{THUMBNAIL_PATH}/material_usd_256.png",
[".material.usd", ".material.usda", ".material.usdc", ".material.usdz"],
)
_known_asset_types[ASSET_TYPE_PROJECT_USD] = AssetTypeDef(
f"{ICON_PATH}/project_usd.svg",
f"{THUMBNAIL_PATH}/project_usd_256.png",
[".project.usd", ".project.usda", ".project.usdc", ".project.usdz"],
)
_known_asset_types[ASSET_TYPE_SEQ_USD] = AssetTypeDef(
f"{ICON_PATH}/sequence_usd.svg",
f"{THUMBNAIL_PATH}/sequence_usd_256.png",
[".seq.usd", ".seq.usda", ".seq.usdc", ".seq.usdz"],
)
_known_asset_types[ASSET_TYPE_SKEL_USD] = AssetTypeDef(
f"{ICON_PATH}/skel_usd.svg",
f"{THUMBNAIL_PATH}/skel_usd_256.png",
[".skel.usd", ".skel.usda", ".skel.usdc", ".skel.usdz"],
)
_known_asset_types[ASSET_TYPE_SKEL_ANIM_USD] = AssetTypeDef(
f"{ICON_PATH}/anim_usd.svg",
f"{THUMBNAIL_PATH}/skel_anim_usd_256.png",
[".skelanim.usd", ".skelanim.usda", ".skelanim.usdc", ".skelanim.usdz"],
)
_known_asset_types[ASSET_TYPE_FBX] = AssetTypeDef(
f"{ICON_PATH}/usd_stage.svg", f"{THUMBNAIL_PATH}/fbx_256.png", [".fbx"]
)
_known_asset_types[ASSET_TYPE_OBJ] = AssetTypeDef(
f"{ICON_PATH}/usd_stage.svg", f"{THUMBNAIL_PATH}/obj_256.png", [".obj"]
)
_known_asset_types[ASSET_TYPE_MATERIAL] = AssetTypeDef(
f"{ICON_PATH}/mdl.svg", f"{THUMBNAIL_PATH}/mdl_256.png", [".mdl", ".mtlx"]
)
_known_asset_types[ASSET_TYPE_IMAGE] = AssetTypeDef(
f"{ICON_PATH}/image.svg",
f"{THUMBNAIL_PATH}/image_256.png",
[".bmp", ".gif", ".jpg", ".jpeg", ".png", ".tga", ".tif", ".tiff", ".hdr", ".dds", ".exr", ".psd", ".ies", ".tx"],
)
_known_asset_types[ASSET_TYPE_SOUND] = AssetTypeDef(
f"{ICON_PATH}/sound.svg",
f"{THUMBNAIL_PATH}/sound_256.png",
[".wav", ".wave", ".ogg", ".oga", ".flac", ".fla", ".mp3", ".m4a", ".spx", ".opus", ".adpcm"],
)
_known_asset_types[ASSET_TYPE_SCRIPT] = AssetTypeDef(
f"{ICON_PATH}/script.svg", f"{THUMBNAIL_PATH}/script_256.png", [".py"]
)
_known_asset_types[ASSET_TYPE_VOLUME] = AssetTypeDef(
f"{ICON_PATH}/volume.svg",
f"{THUMBNAIL_PATH}/volume_256.png",
[".nvdb", ".vdb"],
)
_known_asset_types[ASSET_TYPE_ICON] = AssetTypeDef(None, None, [".svg"])
_known_asset_types[ASSET_TYPE_HIDDEN] = AssetTypeDef(None, None, [".thumbs"])
try:
# avoid dependency on USD in this extension and only use it when available
import omni.usd
except ImportError:
pass
else:
# readable_usd_dotted_file_exts() is auto-generated by querying USD;
# however, it includes some items that we've assigned more specific
# roles (ie, .mdl). So do this last, and subtract out any already-
# known types.
known_exts = set()
for asset_type_def in _known_asset_types.values():
known_exts.update(asset_type_def.matching_exts)
usd_exts = [
x for x in omni.usd.readable_usd_dotted_file_exts()
if x not in known_exts
]
_known_asset_types[ASSET_TYPE_USD] = AssetTypeDef(
f"{ICON_PATH}/usd_stage.svg",
f"{THUMBNAIL_PATH}/usd_stage_256.png",
usd_exts,
)
if _known_asset_types is None:
_init_asset_types()
def register_file_extensions(asset_type: str, exts: [str], replace: bool = False):
"""
Adds an asset type to the recognized list.
Args:
asset_type (str): Name of asset type.
exts ([str]): List of extensions to associate with this asset type, e.g. [".usd", ".usda"].
replace (bool): If True, replaces extensions in the existing definition. Otherwise, append
to the existing list.
"""
if not asset_type or exts == None:
return
global _known_asset_types
if asset_type in _known_asset_types:
glyph = _known_asset_types[asset_type].glyph
thumbnail = _known_asset_types[asset_type].thumbnail
if replace:
_known_asset_types[asset_type] = AssetTypeDef(glyph, thumbnail, exts)
else:
exts.extend(_known_asset_types[asset_type].matching_exts)
_known_asset_types[asset_type] = AssetTypeDef(glyph, thumbnail, exts)
else:
_known_asset_types[asset_type] = AssetTypeDef(None, None, exts)
def is_asset_type(filename: str, asset_type: str) -> bool:
"""
Returns True if given filename is of specified type.
Args:
filename (str)
asset_type (str): Tested type name.
Returns:
bool
"""
global _known_asset_types
if not (filename and asset_type):
return False
elif asset_type not in _known_asset_types:
return False
return any([filename.lower().endswith(ext.lower()) for ext in _known_asset_types[asset_type].matching_exts])
def get_asset_type(filename: str) -> str:
"""
Returns asset type, based on extension of given filename.
Args:
filename (str)
Returns:
str
"""
if not filename:
return None
global _known_asset_types
for asset_type in _known_asset_types:
if is_asset_type(filename, asset_type):
return asset_type
return ASSET_TYPE_UNKNOWN
def get_icon(filename: str) -> str:
"""
Returns icon for specified file.
Args:
filename (str)
Returns:
str: Fullpath to the icon file, None if not found.
"""
if not filename:
return None
icon = None
asset_type = get_asset_type(filename)
global _known_asset_types
if asset_type in _known_asset_types:
icon = _known_asset_types[asset_type].glyph
return icon
def get_thumbnail(filename: str) -> str:
"""
Returns thumbnail for specified file.
Args:
filename (str)
Returns:
str: Fullpath to the thumbnail file, None if not found.
"""
if not filename:
return None
thumbnail = None
asset_type = get_asset_type(filename)
global _known_asset_types
if asset_type == ASSET_TYPE_ICON:
thumbnail = filename
else:
if asset_type in _known_asset_types:
thumbnail = _known_asset_types[asset_type].thumbnail
return thumbnail or f"{THUMBNAIL_PATH}/unknown_file_256.png"
| 9,145 | Python | 33.254682 | 122 | 0.621432 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/test_helper.py | ## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from typing import List
from omni.kit import ui_test
from omni.kit.widget.filebrowser import TREEVIEW_PANE, LISTVIEW_PANE, FileBrowserItem
from .widget import FilePickerWidget
class FilePickerTestHelper:
def __init__(self, widget: FilePickerWidget):
self._widget = widget
async def __aenter__(self):
return self
async def __aexit__(self, *args):
pass
@property
def filepicker(self):
return self._widget
async def toggle_grid_view_async(self, show_grid_view: bool):
if self.filepicker and self.filepicker._view:
self.filepicker._view.toggle_grid_view(show_grid_view)
await ui_test.human_delay(10)
async def get_item_async(self, treeview_identifier: str, name: str, pane: int = LISTVIEW_PANE):
# Return item from the specified pane, handles both tree and grid views
if not self.filepicker:
return
if name:
pane_widget = None
if pane == TREEVIEW_PANE:
pane_widget = ui_test.find_all(f"{self.filepicker._title}//Frame/**/TreeView[*].identifier=='{treeview_identifier}_folder_view'")
elif self.filepicker._view.filebrowser.show_grid_view:
# LISTVIEW selected + showing grid view
pane_widget = ui_test.find_all(f"{self.filepicker._title}//Frame/**/VGrid[*].identifier=='{treeview_identifier}_grid_view'")
else:
# LISTVIEW selected + showing tree view
pane_widget = ui_test.find_all(f"{self.filepicker._title}//Frame/**/TreeView[*].identifier=='{treeview_identifier}'")
if pane_widget:
widget = pane_widget[0].find_all(f"**/Label[*].text=='{name}'")[0]
if widget:
widget.widget.scroll_here(0.5, 0.5)
await ui_test.human_delay(4)
return widget
return None
async def select_items_async(self, url: str, filenames: List[str] = []) -> List[FileBrowserItem]:
"""Helper function to programatically select multiple items in filepicker. Useful in unittests."""
if not self.filepicker:
return []
await self.filepicker.api.navigate_to_async(url)
return await self.filepicker.api.select_items_async(url, filenames=filenames)
async def get_pane_async(self, treeview_identifier: str, pane: int = LISTVIEW_PANE):
# Return the specified pane widget, handles both tree and grid views
if not self.filepicker:
return
pane_widget = None
if pane == TREEVIEW_PANE:
pane_widget = ui_test.find_all(f"{self.filepicker._title}//Frame/**/TreeView[*].identifier=='{treeview_identifier}_folder_view'")
elif self.filepicker._view.filebrowser.show_grid_view:
# LISTVIEW selected + showing grid view
pane_widget = ui_test.find_all(f"{self.filepicker._title}//Frame/**/VGrid[*].identifier=='{treeview_identifier}_grid_view'")
else:
# LISTVIEW selected + showing tree view
pane_widget = ui_test.find_all(f"{self.filepicker._title}//Frame/**/TreeView[*].identifier=='{treeview_identifier}'")
if pane_widget:
await ui_test.human_delay(4)
return pane_widget[0]
return None | 3,751 | Python | 45.320987 | 145 | 0.640896 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/context_menu.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import os
import omni.ui as ui
from functools import partial
from typing import Callable
from omni.kit.widget.filebrowser import FileBrowserItem
from omni.kit.widget.versioning import CheckpointWidget
from .view import FilePickerView
from .file_ops import *
from .style import get_style
class BaseContextMenu:
"""
Base class popup menu for the hovered FileBrowserItem. Provides API for users to add menu items.
"""
def __init__(self, title: str = None, **kwargs):
self._title: str = title
self._view: FilePickerView = kwargs.get("view", None)
self._checkpoint: CheckpointWidget = kwargs.get("checkpoint", None)
self._context_menu: ui.Menu = None
self._menu_dict: list = []
self._menu_items: list = []
self._context: dict = None
@property
def menu(self) -> ui.Menu:
""":obj:`omni.ui.Menu` The menu widget"""
return self._context_menu
@property
def context(self) -> dict:
"""dict: Provides data to the callback. Available keys are {'item', 'selected'}"""
return self._context
def show(
self,
item: FileBrowserItem,
selected: List[FileBrowserItem] = [],
):
"""
Creates the popup menu from definition for immediate display. Receives as input, information about the
item. These values are made available to the callback via the 'context' dictionary.
Args:
item (FileBrowseritem): Item for which to create menu.,
selected ([FileBrowserItem]): List of currently selected items. Default [].
"""
self._context = {}
self._context["item"] = item
self._context["selected"] = selected
self._context_menu = ui.Menu(self._title, style=get_style(), style_type_name_override="Menu")
menu_entry_built = False
with self._context_menu:
prev_entry = None
for i, menu_entry in enumerate(self._menu_dict):
if i == len(self._menu_dict) - 1 and not menu_entry.get("name"):
# Don't draw separator as last item
break
if menu_entry.get("name") or (prev_entry and prev_entry.get("name")):
# Don't draw 2 separators in a row
entry_built = self._build_menu(menu_entry, self._context)
if entry_built:
# only proceed prev_entry if the current entry is built, so that if we have menu items that
# are not built in between 2 separators, the 2nd separator will not build
prev_entry = menu_entry
menu_entry_built |= entry_built
# Show it (if there's at least one menu entry built)
if len(self._menu_dict) > 0 and menu_entry_built:
self._context_menu.show()
def hide(self):
self._context_menu.hide()
def add_menu_item(self, name: str, glyph: str, onclick_fn: Callable, show_fn: Callable, index: int = -1, separator_name: Optional[str] = None) -> str:
"""
Adds menu item, with corresponding callbacks, to this context menu.
Args:
name (str): Name of the menu item (e.g. 'Open'), this name must be unique across the context menu.
glyph (str): Associated glyph to display for this menu item.
onclick_fn (Callable): This callback function is executed when the menu item is clicked. Function signature:
void fn(context: Dict)
show_fn (Callable): Returns True to display this menu item. Function signature: bool fn(context: Dict).
For example, test filename extension to decide whether to display a 'Play Sound' action.
index (int): The position that this menu item will be inserted to.
separator_name (str): The separator name of the separator menu item. Default to '_placeholder_'. When the
index is not explicitly set, or if the index is out of range, this will be used to locate where to add
the menu item; if specified, the index passed in will be counted from the saparator with the provided
name. This is for OM-86768 as part of the effort to match Navigator and Kit UX for Filepicker/Content Browser for context menus.
Returns:
str: Name of menu item if successful, None otherwise.
"""
if not name:
return None
elif name in [item.get("name", None) for item in self._menu_dict]:
# Reject duplicates
return None
menu_item = {"name": name, "glyph": glyph or ""}
if onclick_fn:
menu_item["onclick_fn"] = lambda context, name=name: onclick_fn(name, context["item"].path)
if show_fn:
menu_item["show_fn"] = lambda context: show_fn(context["item"].path)
if index >= 0 and index <= len(self._menu_dict) and separator_name is None:
pass
else:
if separator_name is None:
separator_name = "_placeholder_"
placeholder_index = (i for i, item in enumerate(self._menu_dict) if separator_name in item)
matched = next(placeholder_index, len(self._menu_dict))
index = max(min(matched + index, len(self._menu_dict)), 0)
self._menu_dict.insert(index, menu_item)
return name
def delete_menu_item(self, name: str):
"""
Deletes the menu item, with the given name, from this context menu.
Args:
name (str): Name of the menu item (e.g. 'Open').
"""
if not name:
return
found = (i for i, item in enumerate(self._menu_dict) if name == item.get("name", None))
for j in sorted([i for i in found], reverse=True):
del self._menu_dict[j]
def _build_menu(self, menu_entry, context):
menu_entry_built = False
from omni.kit.ui import get_custom_glyph_code
if "name" in menu_entry and isinstance(menu_entry["name"], dict):
sub_menu = copy.copy(menu_entry["name"])
icon = "plus.svg"
if "glyph" in sub_menu:
icon = sub_menu["glyph"]
del sub_menu["glyph"]
gylph_char = get_custom_glyph_code("${glyphs}/" + icon)
for item in sub_menu:
menu_item = ui.Menu(f" {gylph_char} {item}")
with menu_item:
for menu_entry in sub_menu[item]:
self._build_menu(menu_entry, context)
menu_entry_built = True
self._menu_items.append(menu_item)
return menu_entry_built
if not self._get_fn_result(menu_entry, "show_fn", context):
return False
if "populate_fn" in menu_entry:
menu_item = menu_entry["populate_fn"](context)
self._menu_items.append(menu_item)
return True
if menu_entry["name"] == "":
menu_item = ui.Separator(style_type_name_override="Menu.Separator")
else:
menu_name = ""
if "glyph" in menu_entry:
menu_name = " " + get_custom_glyph_code("${glyphs}/" + menu_entry["glyph"]) + " "
if "onclick_fn" in menu_entry and menu_entry["onclick_fn"] is not None:
enabled = self._get_fn_result(menu_entry, "enabled_fn", context)
menu_item = ui.MenuItem(
menu_name + menu_entry["name"],
triggered_fn=partial(menu_entry["onclick_fn"], context),
enabled=enabled,
style_type_name_override="Menu.Item",
)
else:
menu_item = ui.MenuItem(menu_name + menu_entry["name"], enabled=False, style_type_name_override="Menu.Item")
if "show_fn_async" in menu_entry:
menu_item.visible = False
async def _delay_update_menu_item():
await menu_entry["show_fn_async"](context, menu_item)
# update menu item visiblity after the show fn result is returned
self._update_menu_item_visibility()
asyncio.ensure_future(_delay_update_menu_item())
# FIXME: in the case of when there's only one menu entry and it's show_fn_async returned false, this result will
# be wrong
self._menu_items.append(menu_item)
return True
def _get_fn_result(self, menu_entry, name, context):
if not name in menu_entry:
return True
if menu_entry[name] is None:
return True
if isinstance(menu_entry[name], list):
for show_fn in menu_entry[name]:
if not show_fn(context):
return False
else:
if not menu_entry[name](context):
return False
return True
def _update_menu_item_visibility(self):
"""
Utility to update menu item visiblity.
Mainly to eliminate the case where 2 separators are shown next to each other because of the menu items in
between them are async and made the menu items invisible.
"""
if not self._context_menu:
return
last_visible_item = None
for item in self._menu_items:
if not item.visible:
continue
# if the current item is a separator, check that the previous visible menu item is not separator to avoid
# having 2 continuous separators
if isinstance(item, ui.Separator) and last_visible_item and isinstance(last_visible_item, ui.Separator) and\
last_visible_item.visible:
item.visible = False
last_visible_item = item
self._context_menu.show()
def destroy(self):
self._context_menu = None
self._menu_dict = None
self._context = None
self._menu_items.clear()
class ContextMenu(BaseContextMenu):
"""
Creates popup menu for the hovered FileBrowserItem. In addition to the set of default actions below,
users can add more via the add_menu_item API.
"""
def __init__(self, **kwargs):
super().__init__(title="Context menu", **kwargs)
self._menu_dict = [
{
"name": "Open in File Browser",
"glyph": "folder_open.svg",
"onclick_fn": lambda context: open_in_file_browser(context["item"]),
"show_fn": [lambda context: os.path.exists(context["item"].path)],
},
{
"name": "New USD File",
"glyph": "file.svg",
"onclick_fn": lambda context: create_usd_file(context["item"]),
"show_fn": [
lambda context: context["item"].is_folder,
lambda _: is_usd_supported(),
# OM-72882: should not allow creating folder/file in read-only directory
lambda context: context["item"].writeable,
lambda context: len(context["selected"]) <= 1,
lambda context: not context["item"] in self._view.all_collection_items(collection="omniverse"),
]
},
{
"name": "Restore",
"glyph": "restore.svg",
"onclick_fn": lambda context: restore_items(context["selected"], self._view),
"show_fn": [
# OM-72882: should not allow deleting folder/file in read-only directory
lambda context: context["item"].writeable,
lambda context: context["item"].is_deleted,
],
},
{
"name": "Refresh",
"glyph": "menu_refresh.svg",
"onclick_fn": lambda context: refresh_item(context["item"], self._view),
"show_fn": [lambda context: len(context["selected"]) <= 1,]
},
{
"name": "",
"_add_on_begin_separator_": "",
},
{
"name": "",
"_add_on_end_separator_": "",
},
{
"name": "New Folder",
"glyph": "menu_plus.svg",
"onclick_fn": lambda context: create_folder(context["item"]),
"show_fn": [
lambda context: context["item"].is_folder,
# OM-72882: should not allow creating folder/file in read-only directory
lambda context: context["item"].writeable,
lambda context: len(context["selected"]) <= 1,
# TODO: Can we create any folder in the omniverer server's root folder?
#lambda context: not(context["item"].parent and \
# context["item"].parent.path == "omniverse://"),
],
},
{
"name": "",
},
{
"name": "Create Checkpoint",
"glyph": "database.svg",
"onclick_fn": lambda context: checkpoint_items(context["selected"], self._checkpoint),
"show_fn": [
lambda context: not context["item"].is_folder,
lambda context: len(context["selected"]) == 1,
],
"show_fn_async": is_item_checkpointable,
},
{
"name": "",
},
{
"name": "Rename",
"glyph": "pencil.svg",
"onclick_fn": lambda context: rename_item(context["item"], self._view),
"show_fn": [
lambda context: len(context["selected"]) == 1,
lambda context: context["item"].writeable,
]
},
{
"name": "Delete",
"glyph": "menu_delete.svg",
"onclick_fn": lambda context: delete_items(context["selected"]),
"show_fn": [
# OM-72882: should not allow deleting folder/file in read-only directory
lambda context: context["item"].writeable,
lambda context: not context["item"].is_deleted,
# OM-94626: we couldn't delete when select nothing
lambda context: len(context["selected"]) >= 1,
],
},
{
"name": "",
"_placeholder_": ""
},
{
"name": "Add Bookmark",
"glyph": "bookmark.svg",
"onclick_fn": lambda context: add_bookmark(context["item"], self._view),
"show_fn": [lambda context: len(context["selected"]) <= 1,]
},
{
"name": "Copy URL Link",
"glyph": "share.svg",
"onclick_fn": lambda context: copy_to_clipboard(context["item"]),
"show_fn": [lambda context: len(context["selected"]) <= 1,]
},
{
"name": "Obliterate",
"glyph": "menu_delete.svg",
"onclick_fn": lambda context: obliterate_items(context["selected"], self._view),
"show_fn": [
# OM-72882: should not allow deleting folder/file in read-only directory
lambda context: context["item"].writeable,
lambda context: context["item"].is_deleted,
],
},
]
class UdimContextMenu(BaseContextMenu):
"""Creates popup menu for the hovered FileBrowserItem that are Udim nodes."""
def __init__(self, **kwargs):
super().__init__(title="Udim menu", **kwargs)
self._menu_dict = [
{
"name": "Add Bookmark",
"glyph": "bookmark.svg",
"onclick_fn": lambda context: add_bookmark(context["item"], self._view),
},
]
class CollectionContextMenu(BaseContextMenu):
"""Creates popup menu for the hovered FileBrowserItem that are collection nodes."""
def __init__(self, **kwargs):
super().__init__(title="Collection menu", **kwargs)
# OM-75883: override menu dict for "Omniverse" collection node, there should be only
# one menu entry, matching Navigator UX
self._menu_dict = [
{
"name": "Add Server",
"glyph": "menu_plus.svg",
"onclick_fn": lambda context: add_connection(self._view),
"show_fn": [
lambda context: context['item'].name == "Omniverse",
lambda context: carb.settings.get_settings().get_as_bool("/exts/omni.kit.window.filepicker/show_add_new_connection"),
],
},
]
class ConnectionContextMenu(BaseContextMenu):
"""Creates popup menu for the server connection FileBrowserItem grouped under Omniverse collection node."""
def __init__(self, **kwargs):
super().__init__(title="Connection menu", **kwargs)
# OM-86768: matching context menu with Navigator UX for server connection
# TODO: Add API Tokens and Clear Cached Folders once API is exposed in omni.client
self._menu_dict = [
{
"name": "New Folder",
"glyph": "menu_plus.svg",
"onclick_fn": lambda context: create_folder(context["item"]),
"show_fn": [
# OM-72882: should not allow creating folder/file in read-only directory
lambda context: context["item"].writeable,
lambda context: len(context["selected"]) == 1,
],
},
{
"name": "Reconnect Server",
"glyph": "menu_refresh.svg",
"onclick_fn": lambda context: refresh_connection(context["item"], self._view),
},
{
"name": "",
},
{
"name": "Rename",
"glyph": "pencil.svg",
"onclick_fn": lambda context: rename_item(context["item"], self._view),
"show_fn": [
lambda context: len(context["selected"]) == 1,
]
},
{
"name": "",
},
{
"name": "Log In",
"glyph": "user.svg",
"onclick_fn": lambda context: refresh_connection(context["item"], self._view),
"show_fn": [
lambda context: not FilePickerView.is_connected(context["item"].path),
],
},
{
"name": "Log Out",
"glyph": "user.svg",
"onclick_fn": lambda context: log_out_from_connection(context["item"], self._view),
"show_fn": [
lambda context: FilePickerView.is_connected(context["item"].path),
],
},
{
"name": "",
},
{
"name": "About",
"glyph": "question.svg",
"onclick_fn": lambda context: about_connection(context["item"]),
},
{
"name": "Remove Server",
"glyph": "menu_delete.svg",
"onclick_fn": lambda context: remove_connection(context["item"], self._view),
},
]
class BookmarkContextMenu(BaseContextMenu):
"""Creates popup menu for BookmarkItems."""
def __init__(self, **kwargs):
super().__init__(title="Bookmark menu", **kwargs)
# OM-66726: Edit bookmark similar to Navigator
self._menu_dict = [
{
"name": "Edit",
"glyph": "pencil.svg",
"onclick_fn": lambda context: edit_bookmark(context['item'], self._view),
},
{
"name": "Delete",
"glyph": "menu_delete.svg",
"onclick_fn": lambda context: delete_bookmark(context['item'], self._view),
},
]
| 20,783 | Python | 40.075099 | 154 | 0.523745 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/utils.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import os
import asyncio
import omni.kit.app
import omni.ui as ui
from omni.ui import scene as sc
from typing import Callable, Coroutine, Any
from carb import log_warn, log_info
from .style import get_style, ICON_ROOT
def exec_after_redraw(callback: Callable, wait_frames: int = 2):
async def exec_after_redraw_async(callback: Callable, wait_frames: int):
try:
# Wait a few frames before executing
for _ in range(wait_frames):
await omni.kit.app.get_app().next_update_async()
callback()
except asyncio.CancelledError:
return
except Exception as e:
# Catches exceptions from this delayed function call; often raised by unit tests where the dialog is being rapidly
# created and destroyed. In this case, it's not worth the effort to relay the exception and have it caught, so better
# warn and carry on.
log_warn(f"Warning: Ignoring a minor exception: {str(e)}")
return asyncio.ensure_future(exec_after_redraw_async(callback, wait_frames))
def get_user_folders_dict() -> dict:
"""Returns dictionary of user folders as name, path pairs"""
from pathlib import Path
user_folders = {}
subfolders = ["Desktop", "Documents", "Downloads", "Pictures"]
for subfolder in subfolders:
path = os.path.join(Path.home(), subfolder)
if os.path.exists(path):
user_folders[subfolder] = path.replace("\\", "/")
return user_folders
class SingletonTask:
def __init__(self):
self._task = None
def destroy(self):
self.cancel_task()
def __del__(self):
self.destroy()
async def run_task(self, task: Coroutine) -> Any:
if self._task:
self.cancel_task()
await omni.kit.app.get_app().next_update_async()
self._task = asyncio.create_task(task)
try:
return await self._task
except asyncio.CancelledError:
log_info(f"Cancelling task ... {self._task}")
raise
except Exception as e:
raise
finally:
self._task = None
def cancel_task(self):
if self._task is not None:
self._task.cancel()
self._task = None
class Spinner(sc.Manipulator):
def __init__(self, rotation_speed: int = 2):
super().__init__()
self.__deg = 0
self.__rotation_speed = rotation_speed
def on_build(self):
self.invalidate()
self.__deg = self.__deg % 360
transform = sc.Matrix44.get_rotation_matrix(0, 0, -self.__deg, True)
with sc.Transform(transform=transform):
sc.Image(f"{ICON_ROOT}/ov_logo.png", width=1.5, height=1.5)
self.__deg += self.__rotation_speed
class AnimatedDots():
def __init__(self, period : int = 30, phase : int = 3, width : int = 10, height : int = 20):
self._period = period
self._phase = phase
self._stop_event = asyncio.Event()
self._build_ui(width=width, height=height)
def _build_ui(self, width : int = 0, height: int = 0):
self._label = ui.Label("...", width=width, height=height)
asyncio.ensure_future(self._inf_loop())
async def _inf_loop(self):
counter = 0
while not self._stop_event.is_set():
await omni.kit.app.get_app().next_update_async()
if self._stop_event.is_set():
break
# Animate text
phase = counter // self._period % self._phase + 1
self._label.text = phase * "."
counter += 1
def __del__(self):
self._stop_event.set()
class LoadingPane(SingletonTask):
def __init__(self, frame):
super().__init__()
self._frame = frame
self._scene_view = None
self._spinner = None
self._build_ui()
def _build_ui(self):
with self._frame:
with ui.ZStack(style=get_style()):
ui.Rectangle(style_type_name_override="LoadingPane.Bg")
with ui.VStack(style=get_style(), spacing=5):
ui.Spacer(height=ui.Percent(10))
with ui.HStack(height=ui.Percent(50)):
ui.Spacer()
self._scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_FIT)
with self._scene_view.scene:
self._spinner = Spinner()
ui.Spacer()
with ui.HStack(spacing=0):
ui.Spacer()
ui.Label("Changing Directory", height=20, width=0)
AnimatedDots()
ui.Spacer()
with ui.HStack(height=ui.Percent(20)):
ui.Spacer()
ui.Button(
"Cancel",
width=100, height=20,
clicked_fn=lambda: self.hide(),
style_type_name_override="LoadingPane.Button",
alignment=ui.Alignment.CENTER,
identifier="LoadingPaneCancel"
)
ui.Spacer()
ui.Spacer(height=ui.Percent(10))
def show(self):
self._frame.visible = True
def hide(self):
self.cancel_task()
self._frame.visible = False
def destroy(self):
if self._spinner:
self._spinner.invalidate()
self._spinner = None
if self._scene_view:
self._scene_view.destroy()
self._scene_view = None
if self._frame:
self._frame.visible = False
self._frame.destroy()
self._frame = None
super().destroy()
| 6,298 | Python | 33.60989 | 130 | 0.555414 |
omniverse-code/kit/exts/omni.kit.window.filepicker/omni/kit/window/filepicker/model.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import re
import urllib
import omni.client
from carb import log_warn
from typing import Callable, List, Tuple
from omni.kit.helper.file_utils import asset_types
from omni.kit.widget.filebrowser import FileBrowserItem
from .style import ICON_PATH, THUMBNAIL_PATH
class FilePickerModel:
"""The model class for :obj:`FilePickerWidget`."""
def __init__(self, **kwargs):
self._collections = {}
@property
def collections(self) -> dict:
"""[:obj:`FileBrowseItem`]: The collections loaded for this widget"""
return self._collections
@collections.setter
def collections(self, collections: dict):
self._collections = collections
def get_icon(self, item: FileBrowserItem, expanded: bool) -> str:
"""
Returns fullpath to icon for given item. Override this method to implement custom icons.
Args:
item (:obj:`FileBrowseritem`): Item in question.
expanded (bool): True if item is expanded.
Returns:
str
"""
if not item or item.is_folder:
return None
return asset_types.get_icon(item.path)
def get_thumbnail(self, item: FileBrowserItem) -> str:
"""
Returns fullpath to thumbnail for given item.
Args:
item (:obj:`FileBrowseritem`): Item in question.
Returns:
str: Fullpath to the thumbnail file, None if not found.
"""
thumbnail = None
if not item:
return None
parent = item.parent
if parent in self._collections.values() and parent.path.startswith("omniverse"):
if item.icon.endswith("hdd_plus.svg"):
# Add connection item
thumbnail = f"{THUMBNAIL_PATH}/add_mount_drive_256.png"
else:
thumbnail = f"{THUMBNAIL_PATH}/mount_drive_256.png"
elif parent in self._collections.values() and parent.path.startswith("my-computer"):
thumbnail = f"{THUMBNAIL_PATH}/local_drive_256.png"
elif item.is_folder:
thumbnail = f"{THUMBNAIL_PATH}/folder_256.png"
else:
thumbnail = asset_types.get_thumbnail(item.path)
return thumbnail or f"{THUMBNAIL_PATH}/unknown_file_256.png"
def get_badges(self, item: FileBrowserItem) -> List[Tuple[str, str]]:
"""
Returns fullpaths to badges for given item. Override this method to implement custom badges.
Args:
item (:obj:`FileBrowseritem`): Item in question.
Returns:
List[Tuple[str, str]]: Where each tuple is an (icon path, tooltip string) pair.
"""
if not item:
return None
badges = []
if not item.writeable:
badges.append((f"{ICON_PATH}/lock.svg", ""))
if item.is_deleted:
badges.append((f"{ICON_PATH}/trash_grey.svg", ""))
return badges
def find_item_with_callback(self, url: str, callback: Callable = None):
"""
Searches filebrowser model for the item with the given url. Executes callback on found item.
Args:
url (str): Url of item to search for.
callback (Callable): Invokes this callback on found item or None if not found. Function signature is
void callback(item: FileBrowserItem)
"""
asyncio.ensure_future(self.find_item_async(url, callback))
async def find_item_async(self, url: str, callback: Callable = None) -> FileBrowserItem:
"""
Searches model for the given path and executes callback on found item.
Args:
url (str): Url of item to search for.
callback (Callable): Invokes this callback on found item or None if not found. Function signature is
void callback(item: FileBrowserItem)
"""
if not url:
return None
url = omni.client.normalize_url(url)
broken_url = omni.client.break_url(url)
path, collection = None, None
if broken_url.scheme == 'omniverse':
collection = self._collections.get('omniverse')
path = self.sanitize_path(broken_url.path).strip('/')
if path:
path = f"{broken_url.host}/{path}"
else:
path = broken_url.host
elif broken_url.scheme in ['file', None]:
collection = self._collections.get('my-computer')
path = self.sanitize_path(broken_url.path).rstrip('/')
item = None
if path:
try:
item = await self.find_item_in_subtree_async(collection, path)
except asyncio.CancelledError:
raise
except Exception:
pass
if not item and broken_url.scheme == 'omniverse' and collection:
# Haven't found the item but we need to try again for connection names that are aliased; for example, a connection
# with the url "omniverse://ov-content" but renamed to "my-server".
server = None
for _, child in collection.children.items():
if ("omniverse://" + path).startswith(child.path):
server = child
break
if server:
splits = path.split("/", 1)
sub_path = splits[1] if len(splits) > 1 else ""
try:
item = await self.find_item_in_subtree_async(server, sub_path)
except asyncio.CancelledError:
raise
except Exception:
pass
else:
item = collection
if item is None:
log_warn(f"Failed to find item at '{url}'")
if callback:
callback(item)
return item
async def find_item_in_subtree_async(self, root: FileBrowserItem, path: str) -> FileBrowserItem:
if not root:
# Item not found!
raise RuntimeWarning(f"Path not found: '{path}'")
item, sub_path = root, path
while item:
if not sub_path:
# Item found
return item
# Populate current folder before searching it
try:
result = await item.populate_async(item.on_populated_async)
except asyncio.CancelledError:
raise
if isinstance(result, Exception):
raise result
elif sub_path[0] == "/":
name = "/"
sub_path = sub_path[1:]
else:
splits = sub_path.split("/", 1)
name = splits[0]
sub_path = splits[1] if len(splits) > 1 else ""
match = (child for _, child in item.children.items() if child.name == name)
try:
item = next(match)
except StopIteration:
break
# Item not found!
raise RuntimeWarning(f"Path not found: '{path}'")
@staticmethod
def is_local_path(path: str) -> bool:
"""Returns True if given path is a local path"""
broken_url = omni.client.break_url(path)
if broken_url.scheme == "file":
return True
elif broken_url.scheme == "omniverse":
return False
# Return True if root directory looks like beginning of a Linux or Windows path
root_name = broken_url.path.split("/")[0]
return not root_name or re.match(r"[A-Za-z]:", root_name) != None
def _correct_filename_case(self, file: str) -> str:
"""
Helper function to workaround problem of windows paths getting lowercased
Args:
path (str): Raw path
Returns:
str
"""
try:
import platform, glob, re
if platform.system().lower() == "windows":
# get correct case filename
ondisk = glob.glob(re.sub(r'([^:/\\])(?=[/\\]|$)|\[', r'[\g<0>]', file))[0].replace("\\", "/")
# correct drive letter case
if ondisk[0].islower() and ondisk[1] == ":":
ondisk = ondisk[0].upper() + ondisk[1:]
# has only case changed
if ondisk.lower() == file.lower():
return ondisk
except Exception as exc:
pass
return file
def sanitize_path(self, path: str) -> str:
"""
Helper function for normalizing a path that may have been copied and pasted int to browser
bar. This makes the tool more resiliant to user inputs from other apps.
Args:
path (str): Raw path
Returns:
str
"""
# Strip out surrounding white spaces
path = path.strip() if path else ""
if not path:
return path
path = omni.client.normalize_url(path)
path = urllib.parse.unquote(path).replace("\\", "/")
return self._correct_filename_case(path)
def destroy(self):
self._collections = None
| 9,600 | Python | 34.040146 | 130 | 0.561354 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.