file_path
stringlengths
21
202
content
stringlengths
19
1.02M
size
int64
19
1.02M
lang
stringclasses
8 values
avg_line_length
float64
5.88
100
max_line_length
int64
12
993
alphanum_fraction
float64
0.27
0.93
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/scripts/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. # from functools import lru_cache from omni.ui import color as cl from omni.ui import constant as fl # If declared as global instead of a function, build doc for omni.kit.window.property will fail, what?? @lru_cache() def get_radio_mark_url() -> str: import omni.kit.app return f"{omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)}/data/icons/radiomark.svg" MENU_TITLE = cl.shade(cl("#25282A")) MENU_BACKGROUND = cl.shade(cl("#25282ACC")) MENU_MEDIUM = cl.shade(cl("#6E6E6E")) MENU_LIGHT = cl.shade(cl("#D6D6D6")) MENU_SELECTION = cl.shade(cl("#34C7FF3B")) MENU_SELECTION_BORDER = cl.shade(cl("#34C7FF")) MENU_ITEM_CHECKMARK_COLOR = cl.shade(cl("#34C7FF")) MENU_ITEM_MARGIN = fl.shade(5) MENU_ITEM_MARGIN_HEIGHT = fl.shade(3) MENU_STYLE = { "Menu.Title": {"color": MENU_TITLE, "background_color": 0x0}, "Menu.Title:hovered": { "background_color": MENU_SELECTION, "border_width": 1, "border_color": MENU_SELECTION_BORDER, }, "Menu.Title:pressed": {"background_color": MENU_SELECTION}, "Menu.Item": { "color": MENU_LIGHT, "margin_width": MENU_ITEM_MARGIN, "margin_HEIGHT": MENU_ITEM_MARGIN_HEIGHT, }, "Menu.Item.CheckMark": {"color": MENU_ITEM_CHECKMARK_COLOR}, "Menu.Separator": { "color": MENU_MEDIUM, "margin_HEIGHT": MENU_ITEM_MARGIN_HEIGHT, "border_width": 1.5, }, "Menu.Window": { "background_color": MENU_BACKGROUND, "border_width": 0, "border_radius": 0, "background_selected_color": MENU_SELECTION, "secondary_padding": 1, "secondary_selected_color": MENU_SELECTION_BORDER, "margin": 2, }, "MenuItem": { "background_selected_color": MENU_SELECTION, "secondary_padding": 1, "secondary_selected_color": MENU_SELECTION_BORDER, }, }
2,318
Python
33.102941
126
0.664366
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/scripts/__init__.py
from .context_menu import * from .viewport_menu import *
57
Python
18.333327
28
0.754386
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/scripts/context_menu.py
# Copyright (c) 2020-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. # """The context menus""" import os, sys import weakref import copy import asyncio import carb import carb.events import omni.kit.ui import omni.kit.usd.layers as layers from omni import ui from functools import partial from typing import Callable, List, Union, Tuple from pathlib import Path from pxr import Usd, Sdf, Gf, Tf, UsdShade, UsdGeom, Trace, UsdUtils, Kind from .singleton import Singleton _extension_instance = None TEST_DATA_PATH = "" SETTING_HIDE_CREATE_MENU = "/exts/omni.kit.context_menu/hideCreateMenu" class ContextMenuEventType: ADDED = 0 # New menu entry is added REMOVED = 0 # Menu entry is removed @Singleton class _CustomMenuDict: """ The singleton object that holds custom context menu which is private """ def __init__(self) -> None: self.__custom_menu_dict = {} self.__counter = 0 self.__event_stream = carb.events.get_events_interface().create_event_stream() def add_menu(self, menu: Union[str, list], index: str, extension_id: str) -> int: menu_id = self.__counter if not index in self.__custom_menu_dict: self.__custom_menu_dict[index] = {} if not extension_id in self.__custom_menu_dict[index]: self.__custom_menu_dict[index][extension_id] = {} self.__custom_menu_dict[index][extension_id][menu_id] = menu self.__counter += 1 self.__event_stream.dispatch(ContextMenuEventType.ADDED, payload={"index": index, "extension_id": extension_id}) return menu_id def remove_menu(self, menu_id: int, index: str, extension_id: str) -> None: # NOTE: removing a menu dictionary that does not exist is not valid if ( index in self.__custom_menu_dict and extension_id in self.__custom_menu_dict[index] and menu_id in self.__custom_menu_dict[index][extension_id] ): del self.__custom_menu_dict[index][extension_id][menu_id] self.__event_stream.dispatch(ContextMenuEventType.REMOVED, payload={"index": index, "extension_id": extension_id}) return carb.log_error(f"remove_menu index:{index} extension_id:{extension_id} doesn't exist.") def get_menu_dict(self, index: str, extension_id: str) -> List[dict]: # NOTE: getting a menu dictionary that does not exist is valid and will return empty list if index in self.__custom_menu_dict and extension_id in self.__custom_menu_dict[index]: return self._merge_submenus(list(self.__custom_menu_dict[index][extension_id].values())) return [] ## merge submenus ## def _get_duplicate_item(self, compare_item: dict, item_list: list) -> bool: for item in item_list: if isinstance(compare_item["name"], str) and isinstance(item["name"], str): if item["name"] != "" and compare_item["name"] == item["name"]: return item elif isinstance(compare_item["name"], dict) and isinstance(item["name"], dict): if compare_item["name"].keys() == item["name"].keys(): return item return None def __merge_submenu(self, keys: list, main_item: dict, merge_item: dict) -> dict: for key in keys: if isinstance(main_item[key], str) and isinstance(merge_item[key], str): main_item[key] = copy.copy(main_item[key]) + merge_item[key] elif isinstance(main_item[key], list) and isinstance(merge_item[key], list): main_item[key] = main_item[key].copy() for item in merge_item[key]: duplicate_item = self._get_duplicate_item(item, main_item[key]) if duplicate_item: dup_item_name = duplicate_item["name"] if (not dup_item_name) or not (hasattr(dup_item_name, "keys")): if dup_item_name != "": carb.log_warn(f"_merge_submenu: failed to merge duplicate item {dup_item_name}") else: duplicate_item["name"] = self.__merge_submenu( dup_item_name.keys(), copy.copy(dup_item_name), item["name"] ) else: main_item[key].append(item) return main_item def _merge_submenus(self, main_list: list) -> list: """ merge submenus into new dict without changing the original """ new_list = [] for item in main_list: duplicate_item = self._get_duplicate_item(item, new_list) if duplicate_item: dup_item_name = duplicate_item["name"] if (not dup_item_name) or not (hasattr(dup_item_name, "keys")): if dup_item_name != "": carb.log_warn(f"_merge_submenus: failed to merge duplicate item {dup_item_name}") else: duplicate_item["name"] = self.__merge_submenu( dup_item_name.keys(), copy.copy(dup_item_name), item["name"] ) else: new_list.append(copy.copy(item)) return new_list def get_event_stream(self): return self.__event_stream class ContextMenuExtension(omni.ext.IExt): """Context menu core functionality. See omni.kit.viewport_legacy.context_menu for datailed usage. Example using viewport mouse event to trigger: .. code-block:: python class ContextMenu: def on_startup(self): # get window event stream import omni.kit.viewport_legacy viewport_win = get_viewport_interface().get_viewport_window() # on_mouse_event called when event dispatched self._stage_event_sub = viewport_win.get_mouse_event_stream().create_subscription_to_pop(self.on_mouse_event) def on_shutdown(self): # remove event self._stage_event_sub = None def on_mouse_event(self, event): # check its expected event if event.type != int(omni.kit.ui.MenuEventType.ACTIVATE): return # get context menu core functionality & check its enabled context_menu = omni.kit.context_menu.get_instance() if context_menu is None: carb.log_error("context_menu is disabled!") return # get parameters passed by event objects = {} objects["test_path"] = event.payload["test_path"] # setup objects, this is passed to all functions objects["test"] = "this is a test" # setup menu menu_list = [ # name is name shown on menu. (if name is "" then a menu spacer is added. Can be combined with show_fn) # glyph is icon shown on menu # name_fn funcion to get menu item name # show_fn funcion or list of functions used to decide if menu item is shown. All functions must return True to show # enabled_fn funcion or list of functions used to decide if menu item is enabled. All functions must return True to be enabled # onclick_fn function called when user clicks menu item # onclick_action action called when user clicks menu item # populate_fn a fucntion to be called to populate the menu. Can be combined with show_fn # appear_after a identifier of menu name. Used by custom menus and will allow cusom menu to change order {"name": "Test Menu", "glyph": "question.svg", "show_fn": [ContextMenu.has_reason_to_show, ContextMenu.has_another_reason_to_show], "onclick_fn": ContextMenu.clear_default_prim }, {"name": "", "show_fn": ContextMenu.has_another_reason_to_show}, {"populate_fn": context_menu.show_create_menu}, {"name": ""}, {"name": "Copy URL Link", "glyph": "menu_link.svg", "onclick_fn": ContextMenu.copy_prim_url}, ] # add custom menus menu_list += omni.kit.context_menu.get_menu_dict("MENU", "") menu_list += omni.kit.context_menu.get_menu_dict("MENU", "stagewindow") omni.kit.context_menu.reorder_menu_dict(menu_dict) # show menu context_menu.show_context_menu("stagewindow", objects, menu_list) # show_fn functions def has_reason_to_show(objects: dict): if not "test_path" in objects: return False return True def has_another_reason_to_show(objects: dict): if not "test_path" in objects: return False return True def copy_prim_url(objects: dict): try: import omni.kit.clipboard omni.kit.clipboard.copy("My hovercraft is full of eels") except ImportError: carb.log_warn("Could not import omni.kit.clipboard.") """ # ---------------------------------------------- menu global populate functions ---------------------------------------------- class uiMenu(ui.Menu): def __init__(self, *args, **kwargs): self.glyph = None self.submenu = False if "glyph" in kwargs: self.glyph = kwargs["glyph"] del kwargs["glyph"] if "submenu" in kwargs: self.submenu = kwargs["submenu"] del kwargs["submenu"] tearable = False if "tearable" in kwargs: tearable = kwargs["tearable"] del kwargs["tearable"] super().__init__(*args, **kwargs, menu_compatibility=False, tearable=tearable) class uiMenuItem(ui.MenuItem): def __init__(self, *args, **kwargs): self.glyph = None self.submenu = False if "glyph" in kwargs: self.glyph = kwargs["glyph"] del kwargs["glyph"] super().__init__(*args, **kwargs, menu_compatibility=False) class DefaultMenuDelegate(ui.MenuDelegate): EXTENSION_FOLDER_PATH = Path() ICON_PATH = EXTENSION_FOLDER_PATH.joinpath("data/icons") ICON_SIZE = 14 TEXT_SIZE = 18 ICON_SPACING = [7, 7] MARGIN_SIZE = [4, 4] SUBMENU_SPACING = 4 SUBMENU_ICON_SIZE = 11.7 COLOR_LABEL_ENABLED = 0xFFCCCCCC COLOR_LABEL_DISABLED = 0xFF6F6F6F COLOR_TICK_ENABLED = 0xFFCCCCCC COLOR_TICK_DISABLED = 0xFF4F4F4F COLOR_SEPARATOR = 0xFF6F6F6F # doc compiler breaks if `omni.kit.app.get_app()` or `carb.settings.get_settings()` is called try: EXTENSION_FOLDER_PATH = Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) ICON_PATH = EXTENSION_FOLDER_PATH.joinpath("data/icons") ICON_SIZE = carb.settings.get_settings().get("exts/omni.kit.context_menu/icon_size") ICON_SPACING = carb.settings.get_settings().get("exts/omni.kit.context_menu/icon_spacing") TEXT_SIZE = carb.settings.get_settings().get("exts/omni.kit.context_menu/text_size") MARGIN_SIZE = carb.settings.get_settings().get("exts/omni.kit.context_menu/margin_size") SUBMENU_SPACING = carb.settings.get_settings().get("exts/omni.kit.context_menu/submenu_spacing") SUBMENU_ICON_SIZE = carb.settings.get_settings().get("exts/omni.kit.context_menu/submenu_icon_size") COLOR_LABEL_ENABLED = carb.settings.get_settings().get("exts/omni.kit.context_menu/color_label_enabled") COLOR_LABEL_DISABLED = carb.settings.get_settings().get("exts/omni.kit.context_menu/color_label_disabled") COLOR_TICK_ENABLED = carb.settings.get_settings().get("exts/omni.kit.context_menu/color_tick_enabled") COLOR_TICK_DISABLED = carb.settings.get_settings().get("exts/omni.kit.context_menu/color_tick_disabled") COLOR_SEPARATOR = carb.settings.get_settings().get("exts/omni.kit.context_menu/color_separator") except Exception as exc: carb.log_warn(f"DefaultMenuDelegate: failed to get EXTENSION_FOLDER_PATH and deafults {exc}") def get_style(self): return {"Label::Enabled": {"margin_width": self.MARGIN_SIZE[0], "margin_height": self.MARGIN_SIZE[1], "color": self.COLOR_LABEL_ENABLED}, "Label::Disabled": {"margin_width": self.MARGIN_SIZE[0], "margin_height": self.MARGIN_SIZE[1], "color": self.COLOR_LABEL_DISABLED}, "Image::Icon": {"margin_width": 0, "margin_height": 0, "color": self.COLOR_LABEL_ENABLED}, "Image::SubMenu": {"image_url": f"{self.ICON_PATH}/subdir.svg", "margin_width": 0, "margin_height": 0, "color": self.COLOR_LABEL_ENABLED}, "Image::TickEnabled": {"image_url": f"{self.ICON_PATH}/checked.svg", "margin_width": 0, "margin_height": 0, "color": self.COLOR_TICK_ENABLED}, "Image::TickDisabled": {"image_url": f"{self.ICON_PATH}/checked.svg", "margin_width": 0, "margin_height": 0, "color": self.COLOR_TICK_DISABLED}, "Menu.Separator": {"color": self.COLOR_SEPARATOR} } def build_item(self, item: ui.Menu): if isinstance(item, ui.Separator): return super().build_item(item) elif not isinstance(item, ContextMenuExtension.uiMenu) and not isinstance(item, ContextMenuExtension.uiMenuItem): carb.log_warn(f"build_item: bad context menu item {item.text} - Should be uiMenu/uiMenuItem") return super().build_item(item) style = ContextMenuExtension.default_delegate.get_style() if item.delegate and hasattr(item.delegate, "get_style"): style |= item.delegate.get_style() with ui.HStack(height=0, style=style): ui.Spacer(width=4) # build tick if item.checkable: ui.Image("", width=self.ICON_SIZE, name="TickEnabled" if item.checked else "TickDisabled") # build glyph if item.glyph: glyph_path = item.glyph if "/" in item.glyph.replace("\\", "/") else carb.tokens.get_tokens_interface().resolve("${glyphs}/"+ item.glyph) ui.Spacer(width=self.ICON_SPACING[0]) ui.Image(glyph_path, width=self.ICON_SIZE, name="Icon") ui.Spacer(width=self.ICON_SPACING[1]) # build label ui.Label(f"{item.text} ", height=self.TEXT_SIZE, name="Enabled" if item.enabled else "Disabled") # build subdir marker if item.submenu: ui.Image("", width=self.SUBMENU_ICON_SIZE, name="SubMenu") ui.Spacer(width=self.SUBMENU_SPACING) default_delegate = DefaultMenuDelegate() def _set_prim_translation(stage, prim_path: Sdf.Path, translate: Gf.Vec3d): prim = stage.GetPrimAtPath(prim_path) if not prim or not prim.IsA(UsdGeom.Xformable): return xformable = UsdGeom.Xformable(prim) for op in xformable.GetOrderedXformOps(): if op.GetOpType() == UsdGeom.XformOp.TypeTranslate and "pivot" not in op.SplitName(): precision = op.GetPrecision() desired_translate = ( translate if precision == UsdGeom.XformOp.Precision else Gf.Vec3f(translate[0], translate[1], translate[2]) ) omni.kit.commands.execute("ChangeProperty", prop_path=op.GetAttr().GetPath().pathString, value=desired_translate, prev=None) break elif op.GetOpType() == UsdGeom.XformOp.TypeTransform: matrix = op.Get() matrix.SetTranslate(translate) omni.kit.commands.execute("ChangeProperty", prop_path=op.GetAttr().GetPath().pathString, value=matrix, prev=None) break def create_prim(objects: dict, prim_type: str, attributes: dict, create_group_xform: bool = False) -> None: """ create prims Args: objects: context_menu data prim_type: created prim's type attributes: created prim's cutsom attributes create_group_xform: passed to CreatePrimWithDefaultXformCommand Returns: None """ usd_context = omni.usd.get_context() stage = usd_context.get_stage() with omni.kit.undo.group(): with layers.active_authoring_layer_context(usd_context): if "mouse_pos" in objects and not create_group_xform: mouse_pos = objects["mouse_pos"] omni.kit.commands.execute( "CreatePrimWithDefaultXform", prim_type=prim_type, attributes=attributes, select_new_prim=True ) paths = usd_context.get_selection().get_selected_prim_paths() if stage: for path in paths: ContextMenuExtension._set_prim_translation( stage, path, Gf.Vec3d(mouse_pos[0], mouse_pos[1], mouse_pos[2]) ) elif create_group_xform: paths = usd_context.get_selection().get_selected_prim_paths() if stage.HasDefaultPrim() and stage.GetDefaultPrim().GetPath().pathString in paths: post_notification("Cannot Group default prim") return omni.kit.commands.execute("GroupPrims", prim_paths=paths) else: prim_path = None if "use_hovered" in objects and objects["use_hovered"]: prim = get_hovered_prim(objects) if prim: new_path = omni.usd.get_stage_next_free_path(stage, prim.GetPrimPath().pathString + "/" + prim_type, False) future_prim = Usd.SchemaRegistry.GetTypeFromName(prim_type) if omni.usd.can_prim_have_children(stage, Sdf.Path(new_path), future_prim): prim_path = new_path else: post_notification(f"Cannot create prim below {prim.GetPrimPath().pathString} as nested prims are not supported for this type.") omni.kit.commands.execute( "CreatePrimWithDefaultXform", prim_type=prim_type, prim_path=prim_path, attributes=attributes, select_new_prim=True ) def create_mesh_prim(objects: dict, prim_type: str) -> None: """ create mesh prims Args: objects: context_menu data prim_type: created prim's type Returns: None """ usd_context = omni.usd.get_context() stage = usd_context.get_stage() prim_path = None if "use_hovered" in objects and objects["use_hovered"]: prim = get_hovered_prim(objects) if prim: # mesh prims are always UsdGeom.Gprim so just check for ancestor prim_type new_path = omni.usd.get_stage_next_free_path(stage, prim.GetPrimPath().pathString + "/" + prim_type, False) if omni.usd.is_ancestor_prim_type(stage, Sdf.Path(new_path), UsdGeom.Gprim): post_notification(f"Cannot create prim below {prim.GetPrimPath().pathString} as nested prims are not supported for this type.") else: prim_path = new_path with omni.kit.undo.group(): with layers.active_authoring_layer_context(usd_context): omni.kit.commands.execute( "CreateMeshPrimWithDefaultXform", prim_type=prim_type, prim_path=prim_path, select_new_prim=True, prepend_default_prim=False if prim_path else True ) if "mouse_pos" in objects: mouse_pos = objects["mouse_pos"] paths = usd_context.get_selection().get_selected_prim_paths() if stage: for path in paths: ContextMenuExtension._set_prim_translation( stage, path, Gf.Vec3d(mouse_pos[0], mouse_pos[1], mouse_pos[2]) ) def show_selected_prims_names(self, objects: dict, delegate=None) -> None: """ populate function that builds menu items with selected prim info Args: objects: context_menu data Returns: None """ context_menu = omni.kit.context_menu.get_instance() if context_menu is None: carb.log_error("context_menu is disabled!") return paths = omni.usd.get_context().get_selection().get_selected_prim_paths() hovered = None if "use_hovered" in objects and objects["use_hovered"]: hovered = omni.kit.context_menu.get_hovered_prim(objects) if not "prim_list" in objects and len(paths) == 0: menu_name = f"(nothing selected)" else: if "prim_list" in objects: paths = objects["prim_list"] if len(paths) > 1: menu_name = f"({len(paths)} models selected)" elif "prim_list" in objects: if paths[0].GetPath() == hovered.GetPrimPath() if hovered else None: menu_name = f"({paths[0].GetPath().name} selected & hovered)" hovered = None else: menu_name = f"({paths[0].GetPath().name} selected)" else: menu_name = f"({os.path.basename(paths[0])} selected)" if hovered: menu_name += f"\n({hovered.GetPath().name} hovered)" context_menu._menu_title = ContextMenuExtension.uiMenuItem( f'{menu_name}', triggered_fn=None, enabled=False if delegate else True, delegate=delegate if delegate else ContextMenuExtension.default_delegate, tearable=True if delegate else False, glyph="menu_prim.svg" ) if not carb.settings.get_settings().get(SETTING_HIDE_CREATE_MENU): ui.Separator() def show_create_menu(self, objects: dict): """ populate function that builds create menu Args: objects: context_menu data Returns: None """ prim = None prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] self.build_create_menu(objects, prim_list) def build_create_menu(self, objects: dict, prim_list: list, custom_menu: dict = [], delegate=None): def is_create_type_enabled(type: str): settings = carb.settings.get_settings() if type == "Shape": if settings.get("/app/primCreation/hideShapes") == True or \ settings.get("/app/primCreation/enableMenuShape") == False: return False return True enabled = settings.get(f"/app/primCreation/enableMenu{type}") if enabled == True or enabled == False: return enabled return True if carb.settings.get_settings().get(SETTING_HIDE_CREATE_MENU): return custom_menu += omni.kit.context_menu.get_menu_dict("CREATE", "") usd_context = omni.usd.get_context() paths = usd_context.get_selection().get_selected_prim_paths() item_delegate = delegate if delegate else ContextMenuExtension.default_delegate style = delegate.get_style() if delegate and hasattr(delegate, "get_style") else ContextMenuExtension.default_delegate.get_style() item = ContextMenuExtension.uiMenu( f'Create', style=style, delegate=item_delegate, glyph="menu_create.svg", submenu=True ) self._context_menu_items.append(item) with item: try: geometry_mesh_prim_list = omni.kit.primitive.mesh.get_geometry_mesh_prim_list() item = ContextMenuExtension.uiMenu(f'Mesh', delegate=item_delegate, glyph="menu_prim.svg", submenu=True) self._context_menu_items.append(item) with item: for mesh in geometry_mesh_prim_list: self.menu_item(mesh, triggered_fn=partial(ContextMenuExtension.create_mesh_prim, objects, mesh), delegate=item_delegate) except Exception: pass if is_create_type_enabled("Shape"): def on_create_shape(objects, prim_type): shapes = omni.kit.menu.create.get_geometry_standard_prim_list() shape_attrs = shapes.get(prim_type, {}) ContextMenuExtension.create_prim(objects, prim_type, shape_attrs) item = ContextMenuExtension.uiMenu(f'Shape', delegate=item_delegate, glyph="menu_prim.svg", submenu=True) self._context_menu_items.append(item) with item: for geom in omni.kit.menu.create.get_geometry_standard_prim_list().keys(): self.menu_item( geom, triggered_fn=partial(on_create_shape, objects, geom), delegate=item_delegate ) if is_create_type_enabled("Light"): item = ContextMenuExtension.uiMenu(f'Light', delegate=item_delegate, glyph="menu_light.svg", submenu=True) self._context_menu_items.append(item) with item: for light in omni.kit.menu.create.get_light_prim_list(): self.menu_item( light[0], triggered_fn=partial(ContextMenuExtension.create_prim, objects, light[1], light[2]), delegate=item_delegate ) if is_create_type_enabled("Audio"): item = ContextMenuExtension.uiMenu(f'Audio', delegate=item_delegate, glyph="menu_audio.svg", submenu=True) self._context_menu_items.append(item) with item: for sound in omni.kit.menu.create.get_audio_prim_list(): self.menu_item( sound[0], triggered_fn=partial(ContextMenuExtension.create_prim, objects, sound[1], sound[2]), delegate=item_delegate ) if is_create_type_enabled("Camera"): self.menu_item( f'Camera', triggered_fn=partial(ContextMenuExtension.create_prim, objects, "Camera", {}), glyph="menu_camera.svg", delegate=item_delegate ), if is_create_type_enabled("Scope"): self.menu_item( f'Scope', triggered_fn=partial(ContextMenuExtension.create_prim, objects, "Scope", {}), glyph="menu_scope.svg", delegate=item_delegate ), if is_create_type_enabled("Xform"): self.menu_item( f'Xform', triggered_fn=partial(ContextMenuExtension.create_prim, objects, "Xform", {}), glyph="menu_xform.svg", delegate=item_delegate ), if custom_menu: for menu_entry in custom_menu: if isinstance(menu_entry, list): for item in menu_entry: if self._build_menu(item, objects, delegate=item_delegate): self.menu_item_count += 1 elif self._build_menu(menu_entry, objects, delegate=item_delegate): self.menu_item_count += 1 def build_add_menu(self, objects: dict, prim_list: list, custom_menu: list = None, delegate = None): if carb.settings.get_settings().get(SETTING_HIDE_CREATE_MENU): return menu = omni.kit.context_menu.get_menu_dict("ADD", "") menu = menu + custom_menu if menu: root_menu = ContextMenuExtension.uiMenu( f'Add', delegate=delegate if delegate else ContextMenuExtension.default_delegate, glyph="menu_add.svg", submenu=True) self._context_menu_items.append(root_menu) with root_menu: menu_item_count = self.menu_item_count for menu_entry in menu: if isinstance(menu_entry, list): for item in menu_entry: if self._build_menu(item, objects, None): self.menu_item_count += 1 elif self._build_menu(menu_entry, objects, None): self.menu_item_count += 1 if self.menu_item_count == menu_item_count: root_menu.visible = False def select_prims_using_material(self, objects: dict): """ select stage prims using material Args: objects: context_menu data Returns: None """ if not any(item in objects for item in ["prim", "prim_list"]): return prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] omni.usd.get_context().get_selection().clear_selected_prim_paths() paths = [] for mat_prim in prim_list: for prim in objects["stage"].Traverse(): if omni.usd.is_prim_material_supported(prim): mat, rel = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() if mat and mat.GetPrim().GetPath() == mat_prim.GetPath(): paths.append(prim.GetPath().pathString) omni.usd.get_context().get_selection().set_selected_prim_paths(paths, True) def find_in_browser(self, objects: dict) -> None: """ select prim in content_browser Args: objects: context_menu data Returns: None """ prim = objects["prim_list"][0] url_path = omni.usd.get_url_from_prim(prim) try: from omni.kit.window.content_browser import get_content_window content_browser = get_content_window() if content_browser: content_browser.navigate_to(url_path) except Exception as exc: carb.log_warn(f"find_in_browser error {exc}") def duplicate_prim(self, objects: dict): """ duplicate prims Args: objects: context_menu data Returns: None """ paths = [] usd_context = omni.usd.get_context() usd_context.get_selection().clear_selected_prim_paths() edit_mode = layers.get_layers(usd_context).get_edit_mode() is_auto_authoring = edit_mode == layers.LayerEditMode.AUTO_AUTHORING omni.kit.undo.begin_group() for prim in objects["prim_list"]: old_prim_path = prim.GetPath().pathString new_prim_path = omni.usd.get_stage_next_free_path(objects["stage"], old_prim_path, False) omni.kit.commands.execute( "CopyPrim", path_from=old_prim_path, path_to=new_prim_path, exclusive_select=False, copy_to_introducing_layer=is_auto_authoring ) paths.append(new_prim_path) omni.kit.undo.end_group() omni.usd.get_context().get_selection().set_selected_prim_paths(paths, True) def delete_prim(self, objects: dict, destructive=False): """ delete prims Args: objects: context_menu data destructive: If it's true, it will remove all corresponding prims in all layers. Otherwise, it will deactivate the prim in current edit target if its def is not in the current edit target. By default, it will be non-destructive. Returns: None """ prims = objects.get("prim_list", []) if prims: prim_paths = [prim.GetPath() for prim in prims] omni.kit.commands.execute("DeletePrims", paths=prim_paths, destructive=destructive) def copy_prim_url(self, objects: dict): """ Copies url of Prim in USDA references format. @planet.usda@</Planet> """ paths = "" for prim in objects["prim_list"]: if paths: paths += " " paths += omni.usd.get_url_from_prim(prim) omni.kit.clipboard.copy(paths) def copy_prim_path(self, objects: dict) -> None: """ copy prims path to clipboard Args: objects: context_menu data Returns: None """ paths = "" for prim in objects["prim_list"]: if paths: paths += " " paths += f"{prim.GetPath()}" omni.kit.clipboard.copy(paths) def group_selected_prims(self, objects: dict): """ group prims Args: prims: list of prims Returns: None """ # because widget.layer and widget.stage can get confused if prims are just renamed. clear selection and wait a frame, then do the rename to allow for this omni.usd.get_context().get_selection().clear_selected_prim_paths() asyncio.ensure_future(self._group_list(objects)) def ungroup_selected_prims(self, objects: dict): """ ungroup prims Args: prims: list of prims Returns: None """ # because widget.layer and widget.stage can get confused if prims are just renamed. clear selection and wait a frame, then do the rename to allow for this omni.usd.get_context().get_selection().clear_selected_prim_paths() asyncio.ensure_future(self._ungroup_list(objects)) async def _group_list(self, objects: dict): await omni.kit.app.get_app().next_update_async() prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] paths = [] for prim in prim_list: paths.append(prim.GetPath().pathString) omni.usd.get_context().get_selection().set_selected_prim_paths(paths, True) omni.usd.get_context().get_selection().set_selected_prim_paths(paths, True) ContextMenuExtension.create_prim(objects, prim_type="Xform", attributes={}, create_group_xform=True) async def _ungroup_list(self, objects: dict): await omni.kit.app.get_app().next_update_async() prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] paths = [] for prim in prim_list: paths.append(prim.GetPath().pathString) omni.usd.get_context().get_selection().set_selected_prim_paths(paths, True) omni.usd.get_context().get_selection().set_selected_prim_paths(paths, True) usd_context = omni.usd.get_context() stage = usd_context.get_stage() with omni.kit.undo.group(): with layers.active_authoring_layer_context(usd_context): omni.kit.commands.execute("UngroupPrims", prim_paths=paths) def refresh_payload_or_reference(self, objects: dict): async def reload(layer_handles): context = omni.usd.get_context() for layer in layer_handles: (all_layers, _, _) = UsdUtils.ComputeAllDependencies(layer.identifier) if all_layers: layers_state = layers.get_layers_state(context) all_dirty_layers = [] for dep_layer in all_layers: if layers_state.is_layer_outdated(dep_layer.identifier): all_dirty_layers.append(dep_layer) if all_dirty_layers: Sdf.Layer.ReloadLayers(all_dirty_layers) prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] layer_handles = set() for prim in prim_list: for (ref, intro_layer) in omni.usd.get_composed_references_from_prim(prim): layer = Sdf.Find(intro_layer.ComputeAbsolutePath(ref.assetPath)) if ref.assetPath else None if layer: layer_handles.add(layer) for (ref, intro_layer) in omni.usd.get_composed_payloads_from_prim(prim): layer = Sdf.Find(intro_layer.ComputeAbsolutePath(ref.assetPath)) if ref.assetPath else None if layer: layer_handles.add(layer) asyncio.ensure_future(reload(layer_handles)) def convert_payload_to_reference(self, objects: dict): prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] async def convert(prim_list): await omni.kit.app.get_app().next_update_async() with omni.kit.undo.group(): with Sdf.ChangeBlock(): for prim in prim_list: stage = prim.GetStage() ref_and_layers = omni.usd.get_composed_payloads_from_prim(prim) for payload, _ in ref_and_layers: reference = Sdf.Reference(assetPath=payload.assetPath.replace("\\", "/"), primPath=payload.primPath, layerOffset=payload.layerOffset) omni.kit.commands.execute("RemovePayload", stage=stage, prim_path=prim.GetPath(), payload=payload) omni.kit.commands.execute("AddReference", stage=stage, prim_path=prim.GetPath(), reference=reference) try: property_window = omni.kit.window.property.get_window() if property_window: property_window._window.frame.rebuild() except Exception: pass asyncio.ensure_future(convert(prim_list)) def convert_reference_to_payload(self, objects: dict): prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] async def convert(prim_list): await omni.kit.app.get_app().next_update_async() with omni.kit.undo.group(): with Sdf.ChangeBlock(): for prim in prim_list: stage = prim.GetStage() ref_and_layers = omni.usd.get_composed_references_from_prim(prim) for reference, _ in ref_and_layers: payload = Sdf.Payload(assetPath=reference.assetPath.replace("\\", "/"), primPath=reference.primPath, layerOffset=reference.layerOffset) omni.kit.commands.execute("RemoveReference", stage=stage, prim_path=prim.GetPath(), reference=reference) omni.kit.commands.execute("AddPayload", stage=stage, prim_path=prim.GetPath(), payload=payload) try: property_window = omni.kit.window.property.get_window() if property_window: property_window._window.frame.rebuild() except Exception: pass asyncio.ensure_future(convert(prim_list)) def refresh_reference_payload_name(self, objects: dict): """ checks if prims have references/payload and returns name """ if not any(item in objects for item in ["prim", "prim_list"]): return None prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] if not prim_list: return None has_payload = self._prims_have_payloads(prim_list) has_reference = self._prims_have_references(prim_list) if has_payload and has_reference: return "Refresh Payload & Reference" elif has_payload: return "Refresh Payload" return "Refresh Reference" def get_prim_group(self, prim): """ if the prim is or has a parent prim that is a group Kind, returns that prim otherwise None """ model_api = Usd.ModelAPI(prim) if model_api and Kind.Registry.IsA(model_api.GetKind(), "group"): return prim else: if prim.GetParent().IsValid(): return self.get_prim_group(prim.GetParent()) else: return None # ---------------------------------------------- menu show test functions ---------------------------------------------- def is_one_prim_selected(self, objects: dict): """ checks if one prim is selected """ if not "prim_list" in objects: return False return len(objects["prim_list"]) == 1 def is_material(self, objects: dict): """ checks if prims are UsdShade.Material """ if not any(item in objects for item in ["prim", "prim_list"]): return prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] for prim in prim_list: if not prim.IsA(UsdShade.Material): return False return True def has_payload_or_reference(self, objects: dict): """ checks if prims have payloads or references """ if not any(item in objects for item in ["prim", "prim_list"]): return False prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] if not prim_list: return False return self._prims_have_references(prim_list) or self._prims_have_payloads(prim_list) def can_convert_references_or_payloads(self, objects): """ Checkes if references can be converted into payloads or vice versa. """ if not any(item in objects for item in ["prim", "prim_list"]): return False prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] if not prim_list: return False for prim in prim_list: ref_and_layers = omni.usd.get_composed_references_from_prim(prim) if ref_and_layers: return True payload_and_layers = omni.usd.get_composed_payloads_from_prim(prim) if payload_and_layers: return True return False def _prims_have_payloads(self, prim_list): for prim in prim_list: for prim_spec in prim.GetPrimStack(): if prim_spec.HasInfo(Sdf.PrimSpec.PayloadKey) and prim_spec.GetInfo(Sdf.PrimSpec.PayloadKey).ApplyOperations([]): return True return False def _prims_have_references(self, prim_list): for prim in prim_list: for prim_spec in prim.GetPrimStack(): if prim_spec.HasInfo(Sdf.PrimSpec.ReferencesKey) and prim_spec.GetInfo(Sdf.PrimSpec.ReferencesKey).ApplyOperations([]): return True return False def has_payload(self, objects: dict): """ checks if prims have payloads """ if not any(item in objects for item in ["prim", "prim_list"]): return False prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] if not prim_list: return False return self._prims_have_payloads(prim_list) def has_reference(self, objects: dict): """ checks if prims have references """ if not any(item in objects for item in ["prim", "prim_list"]): return False prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] if not prim_list: return False return self._prims_have_references(prim_list) def can_be_copied(self, objects: dict): """ checks if prims can be copied """ if not "prim_list" in objects: return False for prim in objects["prim_list"]: if not omni.usd.can_be_copied(prim): return False return True def can_use_find_in_browser(self, objects: dict): """ checks if prims are authored """ prim = objects["prim_list"][0] layer = omni.usd.get_sdf_layer(prim) authored_prim = omni.usd.get_authored_prim(prim) return authored_prim and authored_prim != prim def can_show_find_in_browser(self, objects: dict): """ checks if one prim is selected and have URL (authored) """ if not any(item in objects for item in ["prim", "prim_list"]): return False prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] if len(prim_list) != 1: return False prim = prim_list[0] url_path = omni.usd.get_url_from_prim(prim) if url_path is not None and url_path[0:5] == "anon:": url_path = None return url_path != None def can_delete(self, objects: dict): """ checks if prims can be deleted """ if not any(item in objects for item in ["prim", "prim_list"]): return False prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] for prim in prim_list: if not prim.IsValid(): return False no_delete = prim.GetMetadata("no_delete") if no_delete is not None and no_delete is True: return False return True async def can_assign_material_async(self, objects: dict, menu_item: ui.Widget): """ async show function. The `menu_item` is created but not visible, if this item is shown then `menu_item.visible = True` This scans all the prims in the stage looknig for a material, if one is found then it can "assign material" and `menu_item.visible = True` """ if carb.settings.get_settings().get_as_bool("/exts/omni.kit.context_menu/show_assign_material") == False: return if not self.is_prim_selected(objects) or not self.is_material_bindable(objects): return menu_item.visible = True return def is_prim_selected(self, objects: dict): """ checks if any prims are selected """ if not any(item in objects for item in ["prim", "prim_list"]): return False return True def is_prim_in_group(self, objects: dict): """ checks if any prims are in group(s) """ if not "stage" in objects or not "prim_list" in objects or not objects["stage"]: return False stage = objects["stage"] if not stage: return False prim_list = objects["prim_list"] for path in prim_list: if isinstance(path, Usd.Prim): prim = path else: prim = stage.GetPrimAtPath(path) if prim: if not self.get_prim_group(prim): return False return True def is_material_bindable(self, objects: dict): """ checks if prims support matrial binding """ if not any(item in objects for item in ["prim", "prim_list"]): return False prim_list = [objects["prim"]] if "prim" in objects else objects["prim_list"] for prim in prim_list: if not omni.usd.is_prim_material_supported(prim): return False return True def prim_is_type(self, objects: dict, type: Tf.Type) -> bool: """ checks if prims are given class/schema """ if not "stage" in objects or not "prim_list" in objects or not objects["stage"]: return False stage = objects["stage"] if not stage: return False prim_list = objects["prim_list"] for path in prim_list: if isinstance(path, Usd.Prim): prim = path else: prim = stage.GetPrimAtPath(path) if prim: if not prim.IsA(type): return False return len(prim_list) > 0 # ---------------------------------------------- core functions ---------------------------------------------- def __init__(self): super().__init__() self._clipboard = {} def on_startup(self, ext_id): global _extension_instance _extension_instance = self self._context_menu = None self._context_menu_items = [] self._content_window = None self._listeners = [] manager = omni.kit.app.get_app().get_extension_manager() extension_path = manager.get_extension_path(ext_id) global TEST_DATA_PATH TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests") def on_shutdown(self): global _extension_instance _extension_instance = None self._listeners = None if self._context_menu: self._context_menu.destroy() self._context_menu = None self._context_menu_items = [] @property def name(self) -> str: if self._context_menu: return self._context_menu.text return None def close_menu(self): if self._context_menu: self._context_menu.destroy() self._context_menu = None self._context_menu_items = [] self._content_window = None self._menu_title = None self._clipboard = [] def separator(self, name: str="") -> bool: if self.menu_item_count > 1: if isinstance(self.menu_item_prev, ui.Separator) and self.menu_item_prev.text == name: return False self.menu_item_prev = ui.Separator(name) return True return False def menu_item(self, name: str, triggered_fn: Callable = None, enabled: bool = True, checkable: bool = False, checked: bool = False, is_async_func=False, delegate=None, additional_kwargs=None, glyph=""): menuitem_kwargs = {"triggered_fn": triggered_fn, "enabled": enabled, "checkable": checkable, "checked": checked} if additional_kwargs: menuitem_kwargs.update(additional_kwargs) if delegate and hasattr(delegate, "get_parameters"): delegate.get_parameters(name, menuitem_kwargs) # async functions are created but are not visible, so exclude from prev logic if is_async_func: item = ContextMenuExtension.uiMenuItem(name, **menuitem_kwargs, delegate=delegate if delegate else ContextMenuExtension.default_delegate, glyph=glyph) self._context_menu_items.append(item) return item item = ContextMenuExtension.uiMenuItem(name, **menuitem_kwargs, delegate=delegate if delegate else ContextMenuExtension.default_delegate, glyph=glyph) self._context_menu_items.append(item) self.menu_item_prev = item self.menu_item_count += 1 return self.menu_item_prev def _get_fn_result(self, menu_entry: dict, name: str, objects: list): try: 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(objects): return False else: if not menu_entry[name](objects): return False return True except Exception as exc: carb.log_warn(f"_get_fn_result error for {name}: {exc}") return False def _has_click_fn(self, menu_entry): if "onclick_fn" in menu_entry and menu_entry["onclick_fn"] is not None: return True if "onclick_action" in menu_entry and menu_entry["onclick_action"] is not None: return True return False def _execute_action(self, action: Tuple, objects): if not action: return try: import omni.kit.actions.core import omni.kit.app async def execute_action(action): await omni.kit.app.get_app().next_update_async() # only forward the accepted parameters for this action action_obj = omni.kit.actions.core.acquire_action_registry().get_action(action[0], action[1]) params = {key: objects[key] for key in action_obj.parameters if key in objects} omni.kit.actions.core.execute_action(*action, **params) # omni.ui can sometimes crash is menu callback does ui calls. # To avoid this, use async function with frame delay asyncio.ensure_future(execute_action(action)) except ModuleNotFoundError: carb.log_warn(f"execute_action: error omni.kit.actions.core not loaded") except Exception as exc: carb.log_warn(f"execute_action: error {exc}") def _set_hotkey_for_action(self, menu_entry: dict, menu_item: ui.MenuItem): try: from omni.kit.hotkeys.core import get_hotkey_registry onclick_action = menu_entry["onclick_action"] hotkey_registry = get_hotkey_registry() if not hotkey_registry: raise ImportError for hk in hotkey_registry.get_all_hotkeys_for_extension(onclick_action[0]): menu_item.hotkey_text = hk.key_text if hk.action_id == onclick_action[1] else None except ImportError: pass def _build_menu(self, menu_entry: dict, objects: dict, delegate) -> bool: if "name" in menu_entry and isinstance(menu_entry["name"], dict): menu_entry_name = menu_entry["name"] if "name_fn" in menu_entry: menu_entry_name = menu_entry["name_fn"](objects) for item in menu_entry_name: menu_item_count = self.menu_item_count glyph = None if "glyph" in menu_entry and menu_entry["glyph"]: glyph = menu_entry["glyph"] menu = ContextMenuExtension.uiMenu(f"{item}", tearable=menu_entry.get("tearable", True if delegate else False), delegate=delegate if delegate else ContextMenuExtension.default_delegate, glyph=glyph, submenu=True) self._context_menu_items.append(menu) with menu: for menu_entry in menu_entry_name[item]: if isinstance(menu_entry, list): for item in menu_entry: self._build_menu(item, objects, delegate) else: self._build_menu(menu_entry, objects, delegate) # no submenu items created, remove if menu_item_count == self.menu_item_count: menu.visible = False return False return True if not self._get_fn_result(menu_entry, "show_fn", objects): return False if "populate_fn" in menu_entry: self.menu_item_prev = None menu_entry["populate_fn"](objects) return True menu_entry_name = menu_entry["name"] if "name" in menu_entry else "" if "name_fn" in menu_entry and menu_entry["name_fn"] is not None: menu_entry_name = menu_entry["name_fn"](objects) if menu_entry_name == "" or menu_entry_name.endswith("/"): header = menu_entry["header"] if "header" in menu_entry else "" if "show_fn_async" in menu_entry: menu_item = ui.Separator(header, visible=False) asyncio.ensure_future(menu_entry["show_fn_async"](objects, menu_item)) return self.separator(header) checked = False checkable = False if "checked_fn" in menu_entry and self._has_click_fn(menu_entry): checkable = True checked = self._get_fn_result(menu_entry, "checked_fn", objects) menu_item = None is_async_func = bool("show_fn_async" in menu_entry) additional_kwargs = menu_entry.get("additional_kwargs", None) glyph = None if "glyph" in menu_entry and menu_entry["glyph"]: glyph = menu_entry["glyph"] if self._has_click_fn(menu_entry): enabled = self._get_fn_result(menu_entry, "enabled_fn", objects) if "onclick_action" in menu_entry and menu_entry["onclick_action"]: triggered_fn=partial(self._execute_action, menu_entry["onclick_action"], objects) else: triggered_fn=partial(menu_entry["onclick_fn"], objects) menu_item = self.menu_item( menu_entry_name, triggered_fn=triggered_fn, enabled=enabled, checkable=checkable, checked=checked, is_async_func=is_async_func, delegate=delegate, glyph=glyph, additional_kwargs=additional_kwargs, ) else: menu_item = self.menu_item(menu_entry_name, enabled=False, checkable=checkable, checked=checked, is_async_func=is_async_func, delegate=delegate, glyph=glyph, additional_kwargs=additional_kwargs) if "onclick_action" in menu_entry: self._set_hotkey_for_action(menu_entry, menu_item) if menu_item and is_async_func: menu_item.visible = False asyncio.ensure_future(menu_entry["show_fn_async"](objects, menu_item)) return True def _is_menu_visible(self, menu_entry: dict, objects: dict): if not self._get_fn_result(menu_entry, "show_fn", objects): return False if "populate_fn" in menu_entry: return True return True def show_context_menu(self, menu_name: str, objects: dict, menu_list: List[dict], min_menu_entries: int = 1, delegate = None) -> None: """ build context menu from menu_list Args: menu_name: menu name objects: context_menu data menu_list: list of dictonaries containing context menu values min_menu_entries: minimal number of menu needed for menu to be visible Returns: None """ try: if self._context_menu: self._context_menu.destroy() self._context_menu_items = [] style = delegate.get_style() if delegate and hasattr(delegate, "get_style") else ContextMenuExtension.default_delegate.get_style() menuitem_kwargs = { "tearable": True if delegate else False } if delegate and hasattr(delegate, "get_parameters"): delegate.get_parameters("tearable", menuitem_kwargs) self._context_menu = ContextMenuExtension.uiMenu(f"Context menu {menu_name}", delegate=delegate if delegate else ContextMenuExtension.default_delegate, style=style, **menuitem_kwargs) # setup globals objects["clipboard"] = self._clipboard if "stage" not in objects: # TODO: We can't use `context.get_stage()` because this context # menu can be called for Stage Viewer and it has own stage. objects["stage"] = omni.usd.get_context().get_stage() self.menu_item_count = 0 top_level_menu_count = 0 self.menu_item_prev = None with self._context_menu: for menu_entry in menu_list: if isinstance(menu_entry, list): for item in menu_entry: if self._build_menu(item, objects, delegate): self.menu_item_count += 1 top_level_menu_count += 1 elif self._build_menu(menu_entry, objects, delegate): self.menu_item_count += 1 top_level_menu_count += 1 # Show it if top_level_menu_count >= min_menu_entries: # if the last menu item was a Separator, hide it if isinstance(self.menu_item_prev, ui.Separator): self.menu_item_prev.visible = False if all(k in objects for k in ("menu_xpos", "menu_ypos")): self._context_menu.show_at(objects["menu_xpos"], objects["menu_ypos"]) else: self._context_menu.show() except Exception as exc: import traceback carb.log_error(f"show_context_menu: error {traceback.format_exc()}") def bind_material_to_prims_dialog(self, stage: Usd.Stage, prims: list): carb.log_warn("omni.kit.context_menu.get_instance().bind_material_to_prims_dialog() is deprecated. Use omni.kit.material.library.bind_material_to_prims_dialog() instead") import omni.kit.material.library omni.kit.material.library.bind_material_to_prims_dialog(stage, prims) ################## public static functions ################## def get_instance(): """ get instance of context menu class """ return _extension_instance def close_menu(): if _extension_instance: _extension_instance.close_menu() def add_menu(menu_dict, index: str = "MENU", extension_id: str = ""): """add custom menu to any context_menu Examples menu = {"name": "Open in Material Editor", "onclick_fn": open_material} # add to all context menus self._my_custom_menu = omni.kit.context_menu.add_menu(menu, "MENU", "") # add to omni.kit.widget.stage context menu self._my_custom_menu = omni.kit.context_menu.add_menu(menu, "MENU", "omni.kit.widget.stage") Args: menu_dict: a dictonary containing menu settings. See ContextMenuExtension docs for infomation on values index: name of the menu EG. "MENU" extension_id: name of the target EG. "" or "omni.kit.widget.stage" NOTE: index and extension_id are extension arbitary values. add_menu(menu, "MENU", "omni.kit.widget.stage") works as omni.kit.widget.stage retreives custom context_menus with get_menu_dict("MENU", "omni.kit.widget.stage") Adding a menu to an extension that doesn't support context_menus would have no effect. Returns: MenuSubscription. Keep a copy of this as the custom menu will be removed when `release()` is explictly called or this is garbage collected """ class MenuSubscription: def __init__(self, menu_id): self.__id = menu_id def release(self): if self.__id is not None: _CustomMenuDict().remove_menu(self.__id, index, extension_id) self.__id = None def __del__(self): self.release() menu_id = _CustomMenuDict().add_menu(menu_dict, index, extension_id) return MenuSubscription(menu_id) def get_menu_dict(index: str = "MENU", extension_id: str = "") -> List[dict]: """get custom menus see add_menu for dictonary info Args: index: name of the menu extension_id: name of the target Returns: a list of dictonaries containing custom menu settings. See ContextMenuExtension docs for infomation on values """ return _CustomMenuDict().get_menu_dict(index, extension_id) def reorder_menu_dict(menu_dict: List[dict]): """reorder menus using "appear_after" value in menu Args: menu_dict: list of dictonaries Returns: None """ def find_entry(menu_dict, name): for index, menu_entry in enumerate(menu_dict): if "name" in menu_entry: if menu_entry["name"] == name: return index return -1 for index, menu_entry in enumerate(menu_dict.copy()): if "appear_after" in menu_entry: new_index = find_entry(menu_dict, menu_entry["appear_after"]) if new_index != -1: menu_dict.remove(menu_entry) menu_dict.insert(new_index + 1, menu_entry) def get_menu_event_stream(): """ Gets menu event stream """ return _CustomMenuDict().get_event_stream() def post_notification(message: str, info: bool = False, duration: int = 3): try: import omni.kit.notification_manager as nm if info: type = nm.NotificationStatus.INFO else: type = nm.NotificationStatus.WARNING nm.post_notification(message, status=type, duration=duration) except ModuleNotFoundError: carb.log_warn(message) def get_hovered_prim(objects): if "hovered_prim" in objects: return objects["hovered_prim"] if "prim_list" in objects and len(objects['prim_list'])==1: return objects['prim_list'][0] return None
67,155
Python
41.051346
228
0.558707
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/scripts/viewport_menu.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__ = ['ViewportMenu'] import omni.kit import omni.usd import carb import omni.kit.usd.layers as layers from .context_menu import get_instance from .style import MENU_STYLE from .context_menu import ContextMenuExtension from pxr import Usd, UsdShade, Sdf, Gf from typing import Sequence from omni import ui class ViewportMenu: class MenuDelegate(ContextMenuExtension.DefaultMenuDelegate): TEXT_SIZE = 14 ICON_SIZE = 14 MARGIN_SIZE = [3, 3] def get_style(self): vp_style = MENU_STYLE.copy() vp_style["Label::Enabled"] = {"margin_width": self.MARGIN_SIZE[0],"margin_height": self.MARGIN_SIZE[1],"color": self.COLOR_LABEL_ENABLED} vp_style["Label::Disabled"] = {"margin_width": self.MARGIN_SIZE[0], "margin_height": self.MARGIN_SIZE[1], "color": self.COLOR_LABEL_DISABLED} return vp_style menu_delegate = MenuDelegate() @staticmethod def is_on_clipboard(objects, name): clipboard = objects["clipboard"] if not name in clipboard: return False return clipboard[name] != None @staticmethod def is_prim_on_clipboard(objects): return ViewportMenu.is_on_clipboard(objects, "prim_paths") @staticmethod async def can_show_clear_clipboard(objects, menu_item): return False @staticmethod def is_material_bindable(objects): # pragma: no cover if not "prim_list" in objects: return False for prim in objects["prim_list"]: if not omni.usd.is_prim_material_supported(prim): return False return True # ---------------------------------------------- menu onClick functions ---------------------------------------------- @staticmethod def bind_material_to_prim_dialog(objects): import omni.kit.material.library if not "prim_list" in objects: return omni.kit.material.library.bind_material_to_prims_dialog(objects["stage"], objects["prim_list"]) @staticmethod def set_prim_to_pos(path, new_pos): usd_context = omni.usd.get_context() stage = usd_context.get_stage() if stage: prim = stage.GetPrimAtPath(path) attr_position, attr_rotation, attr_scale, attr_order = omni.usd.TransformHelper().get_transform_attr( prim.GetAttributes() ) if attr_position: if attr_position.GetName() == "xformOp:translate": attr_position.Set(Gf.Vec3d(new_pos[0], new_pos[1], new_pos[2])) elif attr_position.GetName() == "xformOp:transform": value = attr_position.Get() if isinstance(value, Gf.Matrix4d): matrix = value else: matrix = Gf.Matrix4d(*value) eps_unused, scale_orient_mat_unused, abs_scale, rot_mat, abs_position, persp_mat_unused = ( matrix.Factor() ) rot_mat.Orthonormalize(False) abs_rotation = Gf.Rotation.DecomposeRotation3( rot_mat, Gf.Vec3d.XAxis(), Gf.Vec3d.YAxis(), Gf.Vec3d.ZAxis(), 1.0 ) abs_rotation = [ Gf.RadiansToDegrees(abs_rotation[0]), Gf.RadiansToDegrees(abs_rotation[1]), Gf.RadiansToDegrees(abs_rotation[2]), ] # split matrix into rotation and translation/scale matrix_pos = Gf.Matrix4d().SetIdentity() matrix_rot = Gf.Matrix4d().SetIdentity() matrix_pos.SetScale(abs_scale) matrix_pos.SetTranslateOnly(Gf.Vec3d(new_pos[0], new_pos[1], new_pos[2])) matrix_rot.SetRotate( Gf.Rotation(Gf.Vec3d.XAxis(), abs_rotation[0]) * Gf.Rotation(Gf.Vec3d.YAxis(), abs_rotation[1]) * Gf.Rotation(Gf.Vec3d.ZAxis(), abs_rotation[2]) ) # build final matrix attr_position.Set(matrix_rot * matrix_pos) else: carb.log_error(f"unknown existing position type. {attr_position}") else: attr_position = prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Float3, False) attr_position.Set(Gf.Vec3d(new_pos[0], new_pos[1], new_pos[2])) if attr_order: attr_order = omni.usd.TransformHelper().add_to_attr_order(attr_order, attr_position.GetName()) else: attr_order = prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False) attr_order.Set(["xformOp:translate"]) @staticmethod def copy_prim_to_clipboard(objects): objects["clipboard"]["prim_paths"] = [] for prim in objects["prim_list"]: objects["clipboard"]["prim_paths"].append(prim.GetPath().pathString) def clear_clipboard(objects): if "clipboard" in objects: del objects["clipboard"] @staticmethod def paste_prim_from_clipboard(objects): clipboard = objects["clipboard"] set_pos = "mouse_pos" in objects and len(objects["clipboard"]["prim_paths"]) == 1 usd_context = omni.usd.get_context() edit_mode = layers.get_layers(usd_context).get_edit_mode() is_auto_authoring = edit_mode == layers.LayerEditMode.AUTO_AUTHORING omni.kit.undo.begin_group() for prim_path in objects["clipboard"]["prim_paths"]: new_prim_path = omni.usd.get_stage_next_free_path(objects["stage"], prim_path, False) omni.kit.commands.execute( "CopyPrim", path_from=prim_path, path_to=new_prim_path, exclusive_select=True, copy_to_introducing_layer=is_auto_authoring ) if set_pos: ViewportMenu.set_prim_to_pos(new_prim_path, objects["mouse_pos"]) omni.kit.undo.end_group() @staticmethod def show_create_menu(objects): prim_list = None if "prim_list" in objects: prim_list = objects["prim_list"] get_instance().build_create_menu( objects, prim_list, omni.kit.context_menu.get_menu_dict("CREATE", "omni.kit.window.viewport"), delegate=ViewportMenu.menu_delegate ) get_instance().build_add_menu( objects, prim_list, omni.kit.context_menu.get_menu_dict("ADD", "omni.kit.window.viewport") ) @staticmethod def show_menu(usd_context_name: str, prim_path: str = None, world_pos: Sequence[float] = None, stage=None): # get context menu core functionality & check its enabled if hasattr(omni.kit, "context_menu"): context_menu = get_instance() else: context_menu = None if context_menu is None: carb.log_info("context_menu is disabled!") return usd_context = omni.usd.get_context(usd_context_name) # get stage if stage is None: stage = usd_context.get_stage() if stage is None: carb.log_error("stage not avaliable") return None # setup objects, this is passed to all functions objects = {} objects["stage"] = stage objects["usd_context_name"] = usd_context_name prim_list = [] paths = usd_context.get_selection().get_selected_prim_paths() if len(paths) > 0: for path in paths: prim = stage.GetPrimAtPath(path) if prim: prim_list.append(prim) elif prim_path: prim = stage.GetPrimAtPath(prim_path) if prim: prim_list.append(prim) if prim_list: objects["prim_list"] = prim_list if world_pos is not None: # Legacy name 'mouse_pos' objects["mouse_pos"] = world_pos # But it's actually the world-space position objects["world_position"] = world_pos # setup menu menu_dict = [ {"populate_fn": lambda o, d=ViewportMenu.menu_delegate: context_menu.show_selected_prims_names(o, d)}, {"populate_fn": ViewportMenu.show_create_menu}, { "name": "Find in Content Browser", "glyph": "menu_search.svg", "show_fn": [ context_menu.is_one_prim_selected, context_menu.can_show_find_in_browser, ], "onclick_fn": context_menu.find_in_browser, }, {"name": ""}, { "name": "Group Selected", "glyph": "group_selected.svg", "show_fn": context_menu.is_prim_selected, "onclick_fn": context_menu.group_selected_prims, }, { "name": "Ungroup Selected", "glyph": "group_selected.svg", "show_fn": [ context_menu.is_prim_selected, context_menu.is_prim_in_group, ], "onclick_fn": context_menu.ungroup_selected_prims, }, { "name": "Duplicate", "glyph": "menu_duplicate.svg", "show_fn": context_menu.can_be_copied, "onclick_fn": context_menu.duplicate_prim, }, { "name": "Delete", "glyph": "menu_delete.svg", "show_fn": context_menu.can_delete, "onclick_fn": context_menu.delete_prim, }, {"name": ""}, { "name": "Copy", "glyph": "menu_duplicate.svg", "show_fn": context_menu.can_be_copied, "onclick_fn": ViewportMenu.copy_prim_to_clipboard, }, { "name": "Paste Here", "glyph": "menu_paste.svg", "show_fn": ViewportMenu.is_prim_on_clipboard, "onclick_fn": ViewportMenu.paste_prim_from_clipboard, }, # this will not be shown, used by tests to cleanup clipboard { "name": "Clear Clipboard", "glyph": "menu_duplicate.svg", "show_fn_async": ViewportMenu.can_show_clear_clipboard, "onclick_fn": ViewportMenu.clear_clipboard, }, {"name": ""}, { "name": "Refresh Reference", "glyph": "sync.svg", "name_fn": context_menu.refresh_reference_payload_name, "show_fn": [context_menu.is_prim_selected, context_menu.has_payload_or_reference], "onclick_fn": context_menu.refresh_payload_or_reference, }, {"name": ""}, { "name": "Select Bound Objects", "glyph": "menu_search.svg", "show_fn": context_menu.is_material, "onclick_fn": context_menu.select_prims_using_material, }, { "name": "Assign Material", "glyph": "menu_material.svg", "show_fn_async": context_menu.can_assign_material_async, "onclick_fn": ViewportMenu.bind_material_to_prim_dialog, }, {"name": "", "show_fn_async": context_menu.can_assign_material_async}, { "name": "Copy URL Link", "glyph": "menu_link.svg", "show_fn": [ context_menu.is_prim_selected, context_menu.is_one_prim_selected, context_menu.can_show_find_in_browser, ], "onclick_fn": context_menu.copy_prim_url, }, { "name": "Copy Prim Path", "glyph": "menu_link.svg", "show_fn": [ context_menu.is_prim_selected, context_menu.is_one_prim_selected, context_menu.can_show_find_in_browser, ], "onclick_fn": context_menu.copy_prim_path, }, ] menu_dict += omni.kit.context_menu.get_menu_dict("MENU", "") menu_dict += omni.kit.context_menu.get_menu_dict("MENU", "omni.kit.window.viewport") omni.kit.context_menu.reorder_menu_dict(menu_dict) # show menu context_menu.show_context_menu("viewport", objects, menu_dict, delegate=ViewportMenu.menu_delegate)
13,265
Python
38.718563
153
0.5317
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_assign_material.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import os import carb import omni.kit.app import omni.usd from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from pxr import Tf, UsdShade from omni.kit.test_suite.helpers import get_test_data_path, select_prims, wait_stage_loading, arrange_windows from omni.kit.material.library.test_helper import MaterialLibraryTestHelper class TestContextMenuAssignMaterial(AsyncTestCase): # Before running each test async def setUp(self): import omni.kit.material.library await arrange_windows() # wait for material to be preloaded so create menu is complete & menus don't rebuild during tests await omni.kit.material.library.get_mdl_list_async() await ui_test.human_delay(50) # After running each test async def tearDown(self): await wait_stage_loading() async def test_assign_material(self): # new stage usd_context = omni.usd.get_context() await usd_context.new_stage_async() stage = usd_context.get_stage() # setup await ui_test.find("Stage").focus() # create root prim rootname = "/World" stage.SetDefaultPrim(stage.DefinePrim(rootname)) # create Looks folder omni.kit.commands.execute("CreatePrim", prim_path="{}/Looks".format(rootname), prim_type="Scope", select_new_prim=True) # create material kit_folder = carb.tokens.get_tokens_interface().resolve("${kit}") omni_pbr_mtl = os.path.normpath(kit_folder + "/mdl/core/Base/OmniPBR.mdl") mtl_path = omni.usd.get_stage_next_free_path(stage, "{}/Looks/{}".format(rootname, Tf.MakeValidIdentifier("OmniPBR")), False) omni.kit.commands.execute("CreateMdlMaterialPrim", mtl_url=omni_pbr_mtl, mtl_name="OmniPBR", mtl_path=mtl_path) # create sphere omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere", select_new_prim=True) # select prim await select_prims(["/World/Sphere"]) # expand stage window... stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True").widget.set_expanded(None, True, True) # get prim prim = stage.GetPrimAtPath("/World/Sphere") # click on context menu item & assign ma viewport = ui_test.find("Viewport") await viewport.focus() await viewport.right_click() await ui_test.human_delay(10) await ui_test.select_context_menu("Assign Material") # assign material await ui_test.human_delay() async with MaterialLibraryTestHelper() as material_test_helper: await material_test_helper.handle_assign_material_dialog(1, 0) bound_material, relationship = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() strength = UsdShade.MaterialBindingAPI.GetMaterialBindingStrength(relationship) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, mtl_path) self.assertEqual(strength, UsdShade.Tokens.weakerThanDescendants) # click on context menu item viewport = ui_test.find("Viewport") await viewport.focus() await viewport.right_click() await ui_test.human_delay(10) await ui_test.select_context_menu("Assign Material") # assign material with different strength await ui_test.human_delay() async with MaterialLibraryTestHelper() as material_test_helper: await material_test_helper.handle_assign_material_dialog(1, 1) bound_material, relationship = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() strength = UsdShade.MaterialBindingAPI.GetMaterialBindingStrength(relationship) self.assertEqual(bound_material.GetPrim().GetPrimPath().pathString, mtl_path) self.assertEqual(strength, UsdShade.Tokens.strongerThanDescendants)
4,351
Python
41.252427
133
0.69892
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_populate_fn.py
## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.commands import omni.kit.test import pathlib import omni.ui as ui from omni.ui.tests.test_base import OmniUiTest from omni.kit import ui_test from pxr import Kind, Sdf, Gf from omni.kit.test_suite.helpers import get_test_data_path, select_prims, get_prims, wait_stage_loading, arrange_windows from omni.kit.context_menu import ContextMenuExtension class TestContextMenuPopulateFn(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() await arrange_windows() # After running each test async def tearDown(self): await super().tearDown() # Test(s) async def test_populate_context_menu(self): menu = {"name": "Entry 0"} entry0 = omni.kit.context_menu.add_menu(menu, "TEST", "NO_SEP_TEST") # add separator menu = {"name": ""} sep = omni.kit.context_menu.add_menu(menu, "TEST", "NO_SEP_TEST") menu = { "name": "Entry 1", "populate_fn": lambda *_: ContextMenuExtension.uiMenuItem("Entry 1") } entry1 = omni.kit.context_menu.add_menu(menu, "TEST", "NO_SEP_TEST") menu_list = omni.kit.context_menu.get_menu_dict("TEST", "NO_SEP_TEST") omni.kit.context_menu.get_instance().show_context_menu("TEST", {}, menu_list) await ui_test.human_delay() menu_dict = await ui_test.get_context_menu(get_all=True) self.assertEqual(menu_dict["_"], ['Entry 0', '', 'Entry 1'])
1,933
Python
36.192307
121
0.679772
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_prim_copy_paste.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import os import omni.kit.app import omni.usd from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from pxr import Sdf, UsdShade from omni.kit.viewport.utility import get_ui_position_for_prim from omni.kit.test_suite.helpers import ( open_stage, get_test_data_path, select_prims, get_prims, wait_stage_loading, arrange_windows ) class PrimMeshCopyPatse(AsyncTestCase): # Before running each test async def setUp(self): self._viewport_window = await arrange_windows("Stage", 768) await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() stage.SetDefaultPrim(stage.DefinePrim("/World")) await wait_stage_loading() # expand treeview stage_window = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") stage_window.widget.set_expanded(None, True, True) await ui_test.human_delay(50) # After running each test async def tearDown(self): await wait_stage_loading() await omni.usd.get_context().new_stage_async() async def test_prim_copy_paste(self): def find_menu_item(menu_path: str): from omni import ui from omni.kit.ui_test.menu import _find_menu_item, _find_context_menu_item return _find_context_menu_item(menu_path, ui.Menu.get_current(), _find_menu_item) await wait_stage_loading() # setup stage = omni.usd.get_context().get_stage() stage_window = ui_test.find("Stage") safe_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32) tree_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") await stage_window.focus() # get context menu & create scope await stage_window.right_click(pos=safe_target) menu_dict = await ui_test.get_context_menu() await ui_test.human_delay() await ui_test.select_context_menu("Create/Scope", offset=ui_test.Vec2(10, 10)) base_prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] # create mesh, no children await select_prims([]) await stage_window.right_click(pos=safe_target) await ui_test.human_delay() await ui_test.select_context_menu("Create/Mesh/Sphere", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay(10) # wait for VP to be ready await wait_stage_loading() await ui_test.human_delay(100) prim_pos, valid = get_ui_position_for_prim(self._viewport_window, "/World/Sphere") self.assertTrue(valid) viewport = ui_test.find("Viewport") await viewport.focus() # open VP context menu & copy prim await viewport.right_click(pos=ui_test.Vec2(prim_pos[0], prim_pos[1] + 30)) await ui_test.human_delay(50) await ui_test.select_context_menu("Copy", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay(50) # copy VP context menu & paste here await viewport.right_click(pos=ui_test.Vec2(prim_pos[0] + 50, prim_pos[1] + 50)) await ui_test.human_delay(50) await ui_test.select_context_menu("Paste Here", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay(50) # verify await ui_test.human_delay(50) stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath("/World/Sphere_01") self.assertTrue(prim.IsValid()) # clear VP context menu clipboard await viewport.right_click(pos=ui_test.Vec2(prim_pos[0] + 50, prim_pos[1] + 50)) await ui_test.human_delay(50) find_menu_item("Clear Clipboard").call_triggered_fn() await ui_test.human_delay(10) omni.kit.context_menu.close_menu()
4,358
Python
37.919643
117
0.658559
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_prim_shape_children.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import os import omni.kit.app import omni.usd from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from pxr import Sdf, UsdShade from omni.kit.test_suite.helpers import ( open_stage, get_test_data_path, select_prims, get_prims, wait_stage_loading, arrange_windows ) class CreatePrimShapeChildren(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows("Stage", 768) await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() stage.SetDefaultPrim(stage.DefinePrim("/World")) stage.DefinePrim("/World/Red_Herring", "Scope") await wait_stage_loading() # expand treeview stage_window = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") stage_window.widget.set_expanded(None, True, True) await ui_test.human_delay(50) # After running each test async def tearDown(self): await wait_stage_loading() async def test_create_prim_children_shape(self): await wait_stage_loading() # setup stage = omni.usd.get_context().get_stage() stage_window = ui_test.find("Stage") safe_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32) tree_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") await stage_window.focus() # get context menu & create scope await stage_window.right_click(pos=safe_target) menu_dict = await ui_test.get_context_menu() await ui_test.human_delay() await ui_test.select_context_menu(f"Create/Scope", offset=ui_test.Vec2(10, 10)) base_prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] # create shape, no children await select_prims([]) for shape in menu_dict['Create']['Shape']['_']: await stage_window.right_click(pos=safe_target) await ui_test.human_delay() await ui_test.select_context_menu(f"Create/Shape/{shape}", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay(10) prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] created_prims = [x for x in prims if x not in base_prims] # create shape with as child (should fail) await tree_widget.find(f"**/StringField[*].model.path=='/World/Red_Herring'").click() for prim_path in created_prims: widget = tree_widget.find(f"**/StringField[*].model.path=='{prim_path}'") widget.widget.scroll_here_y(0.5) await ui_test.human_delay(10) widget = tree_widget.find(f"**/StringField[*].model.path=='{prim_path}'") menu_pos = widget.position + ui_test.Vec2(10, 10) for shape in menu_dict['Create']['Shape']['_']: await stage_window.right_click(menu_pos) await ui_test.select_context_menu(f"Create/Shape/{shape}", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay(10) # verify prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] final_prims = [x for x in prims if x not in base_prims] self.assertEqual(final_prims, ['/World/Capsule', '/World/Cone', '/World/Cube', '/World/Cylinder', '/World/Sphere', '/World/Capsule_01', '/World/Cone_01', '/World/Cube_01', '/World/Cylinder_01', '/World/Sphere_01', '/World/Capsule_02', '/World/Cone_02', '/World/Cube_02', '/World/Cylinder_02', '/World/Sphere_02', '/World/Capsule_03', '/World/Cone_03', '/World/Cube_03', '/World/Cylinder_03', '/World/Sphere_03', '/World/Capsule_04', '/World/Cone_04', '/World/Cube_04', '/World/Cylinder_04', '/World/Sphere_04', '/World/Capsule_05', '/World/Cone_05', '/World/Cube_05', '/World/Cylinder_05', '/World/Sphere_05']) async def test_create_prim_children_shape_scope_empty(self): await wait_stage_loading() # setup stage = omni.usd.get_context().get_stage() stage_window = ui_test.find("Stage") safe_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32) tree_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") await stage_window.focus() # get context menu & create scope await stage_window.right_click(pos=safe_target) menu_dict = await ui_test.get_context_menu() await ui_test.human_delay() await ui_test.select_context_menu(f"Create/Scope", offset=ui_test.Vec2(10, 10)) base_prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] # create shape, no children for shape in menu_dict['Create']['Shape']['_']: await select_prims(["/World/Scope"]) await stage_window.right_click(pos=safe_target) await ui_test.human_delay() await ui_test.select_context_menu(f"Create/Shape/{shape}", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay(10) prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] created_prims = [x for x in prims if x not in base_prims] # verify prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] self.assertEqual(prims, ['/World', '/World/Red_Herring', '/World/Scope', '/World/Capsule', '/World/Cone', '/World/Cube', '/World/Cylinder', '/World/Sphere']) async def test_create_prim_children_shape_xform_empty(self): await wait_stage_loading() # setup stage = omni.usd.get_context().get_stage() stage_window = ui_test.find("Stage") safe_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32) tree_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") await stage_window.focus() # get context menu & create scope await stage_window.right_click(pos=safe_target) menu_dict = await ui_test.get_context_menu() await ui_test.human_delay() await ui_test.select_context_menu(f"Create/Xform", offset=ui_test.Vec2(10, 10)) base_prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] # create shape, no children for shape in menu_dict['Create']['Shape']['_']: await select_prims(["/World/Xform"]) await stage_window.right_click(pos=safe_target) await ui_test.human_delay() await ui_test.select_context_menu(f"Create/Shape/{shape}", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay(10) prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] created_prims = [x for x in prims if x not in base_prims] # verify prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] self.assertEqual(prims, ['/World', '/World/Red_Herring', '/World/Xform', '/World/Capsule', '/World/Cone', '/World/Cube', '/World/Cylinder', '/World/Sphere']) async def test_create_prim_children_shape_scope_hover(self): await wait_stage_loading() # setup stage = omni.usd.get_context().get_stage() stage_window = ui_test.find("Stage") safe_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32) tree_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") await stage_window.focus() # get context menu & create scope await stage_window.right_click(pos=safe_target) menu_dict = await ui_test.get_context_menu() await ui_test.human_delay() await ui_test.select_context_menu(f"Create/Scope", offset=ui_test.Vec2(10, 10)) base_prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] # create shape, no children for shape in menu_dict['Create']['Shape']['_']: await select_prims(["/World/Scope"]) #await stage_window.right_click(pos=safe_target) stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") await stage_widget.find(f"**/StringField[*].model.path=='/World/Scope'").right_click() await ui_test.human_delay() await ui_test.select_context_menu(f"Create/Shape/{shape}", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay(10) prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] created_prims = [x for x in prims if x not in base_prims] # verify prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] self.assertEqual(prims, ['/World', '/World/Red_Herring', '/World/Scope', '/World/Scope/Capsule', '/World/Scope/Cone', '/World/Scope/Cube', '/World/Scope/Cylinder', '/World/Scope/Sphere']) async def test_create_prim_children_shape_xform_hover(self): await wait_stage_loading() # setup stage = omni.usd.get_context().get_stage() stage_window = ui_test.find("Stage") safe_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32) tree_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") await stage_window.focus() # get context menu & create scope await stage_window.right_click(pos=safe_target) menu_dict = await ui_test.get_context_menu() await ui_test.human_delay() await ui_test.select_context_menu(f"Create/Xform", offset=ui_test.Vec2(10, 10)) base_prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] # create shape, no children for shape in menu_dict['Create']['Shape']['_']: await select_prims(["/World/Xform"]) #await stage_window.right_click(pos=safe_target) stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") await stage_widget.find(f"**/StringField[*].model.path=='/World/Xform'").right_click() await ui_test.human_delay() await ui_test.select_context_menu(f"Create/Shape/{shape}", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay(10) prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] created_prims = [x for x in prims if x not in base_prims] # verify prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] self.assertEqual(prims, ['/World', '/World/Red_Herring', '/World/Xform', '/World/Xform/Capsule', '/World/Xform/Cone', '/World/Xform/Cube', '/World/Xform/Cylinder', '/World/Xform/Sphere'])
11,776
Python
50.204348
618
0.64071
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_add_mdl_file.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import os import omni.kit.app import omni.usd from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from pxr import Sdf, UsdShade from omni.kit.test_suite.helpers import get_test_data_path, wait_stage_loading, arrange_windows from omni.kit.material.library.test_helper import MaterialLibraryTestHelper class TestCreateMenuContextMenu(AsyncTestCase): # Before running each test async def setUp(self): # manually arrange windows as linux fails to auto-arrange await arrange_windows() # After running each test async def tearDown(self): await wait_stage_loading() async def test_viewport_menu_add_mdl_file(self): # new stage usd_context = omni.usd.get_context() await usd_context.new_stage_async() stage = usd_context.get_stage() # setup await ui_test.find("Stage").focus() viewport = ui_test.find("Viewport") await viewport.focus() # click on context menu item await viewport.right_click() await ui_test.human_delay(50) await ui_test.select_context_menu("Create/Material/Add MDL File") await ui_test.human_delay() # use add material dialog async with MaterialLibraryTestHelper() as material_test_helper: await material_test_helper.handle_add_material_dialog(get_test_data_path(__name__, "TESTEXPORT.mdl")) # wait for material to load & UI to refresh await wait_stage_loading() # verify # NOTE: TESTEXPORT.mdl material is named "Material" so that is the prim created shader = UsdShade.Shader(stage.GetPrimAtPath("/Looks/Material/Shader")) identifier = shader.GetSourceAssetSubIdentifier("mdl") self.assertTrue(identifier == "Material")
2,261
Python
37.338982
113
0.704998
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/__init__.py
from .test_context_menu import * from .test_icon_menu import * from .test_add_mdl_file import * from .test_assign_material import * from .test_prim_mesh_children_stage import CreatePrimMeshChildrenStage from .test_prim_mesh_children_viewport import CreatePrimMeshChildrenViewport from .test_prim_shape_children import CreatePrimShapeChildren from .test_no_style_leaking import TestContextMenuNoStyleLeakage from .test_menu_delegate import TestContextMenuDelegate from .test_delegate_style import TestContextMenuDelegateStyle from .test_group_prims import TestContextMenuGroupPrims from .test_populate_fn import TestContextMenuPopulateFn from .test_enable_menu import TestEnableCreateMenu from .test_prim_copy_paste import PrimMeshCopyPatse
741
Python
48.466663
76
0.850202
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_group_prims.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import os import carb import omni.kit.app import omni.usd import omni.kit.undo from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from pxr import Tf, UsdShade from omni.kit.test_suite.helpers import get_test_data_path, select_prims, get_prims, wait_stage_loading, arrange_windows from omni.kit.material.library.test_helper import MaterialLibraryTestHelper class TestContextMenuGroupPrims(AsyncTestCase): # Before running each test async def setUp(self): import omni.kit.material.library await arrange_windows() # wait for material to be preloaded so create menu is complete & menus don't rebuild during tests await omni.kit.material.library.get_mdl_list_async() await ui_test.human_delay(50) # After running each test async def tearDown(self): await wait_stage_loading() async def test_group_prims(self): # new stage usd_context = omni.usd.get_context() await usd_context.new_stage_async() stage = usd_context.get_stage() # setup stage = omni.usd.get_context().get_stage() stage_window = ui_test.find("Stage") safe_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32) tree_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") await stage_window.focus() # create root prim rootname = "/World" stage.SetDefaultPrim(stage.DefinePrim(rootname)) ## create prim omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") await ui_test.human_delay() # verify prims were created prim_list = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)] self.assertTrue(prim_list == ['/World', '/World/Sphere']) # group sphere & world await select_prims(['/World', '/World/Sphere']) # get context menu & create scope await stage_window.right_click(pos=safe_target) menu_dict = await ui_test.get_context_menu() await ui_test.human_delay() await ui_test.select_context_menu(f"Group Selected", offset=ui_test.Vec2(10, 10)) # verify prims were not grouped prim_list = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)] self.assertTrue(prim_list == ['/World', '/World/Sphere']) # select sphere await select_prims(["/World/Sphere"]) # get context menu & create scope await stage_window.right_click(pos=safe_target) menu_dict = await ui_test.get_context_menu() await ui_test.human_delay() await ui_test.select_context_menu(f"Group Selected", offset=ui_test.Vec2(10, 10)) # verify prims were grouped prim_list = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)] self.assertTrue(prim_list == ['/World', '/World/Group', '/World/Group/Sphere']) # ungroup the prims await select_prims(['/World/Group']) # get context menu & create scope await stage_window.right_click(pos=safe_target) menu_dict = await ui_test.get_context_menu() await ui_test.human_delay() await ui_test.select_context_menu(f"Ungroup Selected", offset=ui_test.Vec2(10, 10)) # verify prims were ungrouped prim_list = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)] self.assertTrue(prim_list == ['/World', '/World/Sphere'])
4,094
Python
39.95
121
0.672692
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_menu_delegate.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.commands import omni.kit.test from omni.ui.tests.test_base import OmniUiTest import omni.ui as ui from omni.kit import ui_test from pxr import Kind, Sdf, Gf import pathlib class TestContextMenuDelegate(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() # After running each test async def tearDown(self): await super().tearDown() # Test(s) async def test_delegate_context_menu(self): from omni.kit.context_menu import ContextMenuExtension def stub_fn(): pass def show_stub_false(objects): return False # setup menu menu_list = [ { "name": "Set Authoring Layer", "glyph": "menu_rename.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Create Sublayer", "glyph": "menu_create_sublayer.svg", "onclick_fn": stub_fn, }, { "name": "Insert Sublayer", "glyph": "menu_insert_sublayer.svg", "onclick_fn": stub_fn, }, { "name": "Merge Down One", "glyph": "menu_merge_down.svg", "onclick_fn": stub_fn, }, { "name": "Flatten Sublayers", "glyph": "menu_flatten_layers.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Save", "glyph": "menu_save.svg", "onclick_fn": stub_fn, }, { "name": "Save As", "glyph": "menu_save_as.svg", "onclick_fn": stub_fn, }, { "name": "Save As And Replace", "glyph": "menu_save_as.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Reload Layer", "glyph": "menu_refresh.svg", "onclick_fn": stub_fn, }, { "name": "Remove Layer", "glyph": "menu_remove_layer.svg", "onclick_fn": stub_fn, }, { "name": "Delete Prim", "glyph": "menu_delete.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Select Bound Objects", "glyph": "menu_search.svg", "onclick_fn": stub_fn, }, {"name": ""}, {"glyph": "menu_link.svg", "name": { 'SubMenu': [ {'name': 'Set up axis +Y', 'onclick_fn': stub_fn}, {'name': 'Set up axis +Z', 'onclick_fn': stub_fn} ] }, }, {"glyph": "none.svg", "name": { 'SubMenu Hidden': [ {'name': 'Set up axis +Y', "show_fn": show_stub_false, 'onclick_fn': stub_fn}, {'name': 'Set up axis +Z', "show_fn": show_stub_false, 'onclick_fn': stub_fn} ] } }, ] delegate_calls = {"init": 0, "build_item": 0, "build_status": 0, "build_title": 0, "get_style": 0, "get_parameters": 0} class MenuDelegate(ContextMenuExtension.DefaultMenuDelegate): def __init__(self, **kwargs): nonlocal delegate_calls super().__init__(**kwargs) delegate_calls["init"] += 1 def build_item(self, item: ui.MenuHelper): nonlocal delegate_calls super().build_item(item) delegate_calls["build_item"] += 1 def build_status(self, item: ui.MenuHelper): nonlocal delegate_calls super().build_status(item) delegate_calls["build_status"] += 1 def build_title(self, item: ui.MenuHelper): nonlocal delegate_calls super().build_title(item) delegate_calls["build_title"] += 1 def get_style(self): nonlocal delegate_calls delegate_calls["get_style"] += 1 return {} def get_parameters(self, name, kwargs): nonlocal delegate_calls delegate_calls["get_parameters"] += 1 await ui_test.human_delay(50) menu_delegate = MenuDelegate() window = await self.create_test_window(width=200, height=330) context_menu = omni.kit.context_menu.get_instance() context_menu.show_context_menu("delegate", {"menu_xpos": 4, "menu_ypos": 4}, menu_list, delegate=menu_delegate) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await self.finalize_test_no_image() await ui_test.human_delay(50) self.assertEqual(delegate_calls, {'init': 1, 'build_item': 21, 'build_status': 2, 'build_title': 2, 'get_style': 17, 'get_parameters': 15})
5,744
Python
32.994083
147
0.475453
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_no_style_leaking.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.commands import omni.kit.test from omni.ui.tests.test_base import OmniUiTest import omni.ui as ui from omni.kit import ui_test from omni.kit.test_suite.helpers import wait_stage_loading, arrange_windows from pxr import Kind, Sdf, Gf import pathlib class TestContextMenuNoStyleLeakage(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() await arrange_windows() await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() stage.SetDefaultPrim(stage.DefinePrim("/World")) from omni.kit.context_menu.scripts.context_menu import TEST_DATA_PATH self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() self._usd_path = TEST_DATA_PATH.absolute().joinpath("usd").absolute() # After running each test async def tearDown(self): await super().tearDown() # Test(s) async def test_no_style_leaking(self): def stub_fn(): pass def show_stub_false(objects): return False # setup menu menu_list = [ { "name": "Set Authoring Layer", "glyph": "menu_rename.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Create Sublayer", "glyph": "menu_create_sublayer.svg", "onclick_fn": stub_fn, }, { "name": "Insert Sublayer", "glyph": "menu_insert_sublayer.svg", "onclick_fn": stub_fn, }, { "name": "Merge Down One", "glyph": "menu_merge_down.svg", "onclick_fn": stub_fn, }, { "name": "Flatten Sublayers", "glyph": "menu_flatten_layers.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Save", "glyph": "menu_save.svg", "onclick_fn": stub_fn, }, { "name": "Save As", "glyph": "menu_save_as.svg", "onclick_fn": stub_fn, }, { "name": "Save As And Replace", "glyph": "menu_save_as.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Reload Layer", "glyph": "menu_refresh.svg", "onclick_fn": stub_fn, }, { "name": "Remove Layer", "glyph": "menu_remove_layer.svg", "onclick_fn": stub_fn, }, { "name": "Delete Prim", "glyph": "menu_delete.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Select Bound Objects", "glyph": "menu_search.svg", "onclick_fn": stub_fn, }, {"name": ""}, {"glyph": "menu_link.svg", "name": { 'SubMenu': [ {'name': 'Set up axis +Y', 'onclick_fn': stub_fn}, {'name': 'Set up axis +Z', 'onclick_fn': stub_fn} ] }, }, {"glyph": "none.svg", "name": { 'SubMenu Hidden': [ {'name': 'Set up axis +Y', "show_fn": show_stub_false, 'onclick_fn': stub_fn}, {'name': 'Set up axis +Z', "show_fn": show_stub_false, 'onclick_fn': stub_fn} ] } }, ] await wait_stage_loading() await ui_test.find("Stage").focus() viewport = ui_test.find("Viewport") await viewport.focus() # show viewport context menu await viewport.right_click() await ui_test.human_delay(10) # without closing context menu open new one & check for style leaking window = await self.create_test_window(width=200, height=330) context_menu = omni.kit.context_menu.get_instance() context_menu.show_context_menu("toolbar", {"menu_xpos": 4, "menu_ypos": 4}, menu_list) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_context_menu_style_leak_ui.png")
5,102
Python
33.47973
124
0.489808
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_context_menu.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import pathlib import omni.kit.app import omni.kit.commands import omni.kit.test import omni.ui as ui import omni.usd from omni.ui.tests.test_base import OmniUiTest from omni.kit import ui_test from pxr import Kind, Sdf, Gf, Usd class TestContextMenu(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() from omni.kit.context_menu.scripts.context_menu import TEST_DATA_PATH self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() self._usd_path = TEST_DATA_PATH.absolute().joinpath("usd").absolute() self._usd_context = omni.usd.get_context() await self._usd_context.new_stage_async() # After running each test async def tearDown(self): await super().tearDown() # Test(s) async def test_basic_context_menu(self): def stub_fn(): pass def show_stub_false(objects): return False # setup menu menu_list = [ { "name": "Set Authoring Layer", "glyph": "menu_rename.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Create Sublayer", "glyph": "menu_create_sublayer.svg", "onclick_fn": stub_fn, }, { "name": "Insert Sublayer", "glyph": "menu_insert_sublayer.svg", "onclick_fn": stub_fn, }, { "name": "Merge Down One", "glyph": "menu_merge_down.svg", "onclick_fn": stub_fn, }, { "name": "Flatten Sublayers", "glyph": "menu_flatten_layers.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Save", "glyph": "menu_save.svg", "onclick_fn": stub_fn, }, { "name": "Save As", "glyph": "menu_save_as.svg", "onclick_fn": stub_fn, }, { "name": "Save As And Replace", "glyph": "menu_save_as.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Reload Layer", "glyph": "menu_refresh.svg", "onclick_fn": stub_fn, }, { "name": "Remove Layer", "glyph": "menu_remove_layer.svg", "onclick_fn": stub_fn, }, { "name": "Delete Prim", "glyph": "menu_delete.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Select Bound Objects", "glyph": "menu_search.svg", "onclick_fn": stub_fn, }, {"name": ""}, {"glyph": "menu_link.svg", "name": { 'SubMenu': [ {'name': 'Set up axis +Y', 'onclick_fn': stub_fn}, {'name': 'Set up axis +Z', 'onclick_fn': stub_fn} ] }, }, {"glyph": "none.svg", "name": { 'SubMenu Hidden': [ {'name': 'Set up axis +Y', "show_fn": show_stub_false, 'onclick_fn': stub_fn}, {'name': 'Set up axis +Z', "show_fn": show_stub_false, 'onclick_fn': stub_fn} ] } }, ] window = await self.create_test_window(width=200, height=330) context_menu = omni.kit.context_menu.get_instance() context_menu.show_context_menu("toolbar", {"menu_xpos": 4, "menu_ypos": 4}, menu_list) await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_context_menu_ui.png") async def test_conversion_between_payloads_and_references(self): from omni.kit import ui_test stage = self._usd_context.get_stage() prim = stage.DefinePrim("/root/prim", "Xform") reference_layer = Sdf.Layer.CreateAnonymous() reference_layer2 = Sdf.Layer.CreateAnonymous() reference_stage = Usd.Stage.Open(reference_layer) reference_prim = reference_stage.DefinePrim("/root/reference", "Xform") payload_prim = reference_stage.DefinePrim("/root/payload", "Xform") default_prim = reference_stage.GetPrimAtPath("/root") reference_stage.SetDefaultPrim(default_prim) reference_prim.GetReferences().AddReference(reference_layer2.identifier) payload_prim.GetPayloads().AddPayload(reference_layer2.identifier) prim.GetReferences().AddReference(reference_layer.identifier) await ui_test.wait_n_updates(2) self._usd_context.get_selection().set_selected_prim_paths(["/root/prim/reference"], True) await ui_test.wait_n_updates(2) self._usd_context.get_selection().set_selected_prim_paths([], True) ref_and_layers = omni.usd.get_composed_references_from_prim(prim) self.assertTrue(len(ref_and_layers) == 1) reference_prim = stage.GetPrimAtPath("/root/prim/reference") ref_and_layers = omni.usd.get_composed_references_from_prim(reference_prim) self.assertTrue(len(ref_and_layers) == 1) payload_prim = stage.GetPrimAtPath("/root/prim/payload") payload_and_layers = omni.usd.get_composed_payloads_from_prim(payload_prim) self.assertTrue(len(payload_and_layers) == 1) await ui_test.find("Stage").focus() stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True") prim_widget = stage_widget.find("**/Label[*].text=='prim'") self.assertTrue(prim_widget) await prim_widget.right_click() await ui_test.select_context_menu("Convert References to Payloads") await ui_test.wait_n_updates(5) reference_prim = stage.GetPrimAtPath("/root/prim") ref_and_layers = omni.usd.get_composed_references_from_prim(prim) self.assertTrue(len(ref_and_layers) == 0) payload_and_layers = omni.usd.get_composed_payloads_from_prim(prim) self.assertTrue(len(payload_and_layers) == 1) prim_widget = stage_widget.find("**/Label[*].text=='prim'") await prim_widget.right_click() await ui_test.select_context_menu("Convert Payloads to References") await ui_test.wait_n_updates(5) payload_and_layers = omni.usd.get_composed_payloads_from_prim(prim) self.assertTrue(len(payload_and_layers) == 0) reference_prim = stage.GetPrimAtPath("/root/prim") ref_and_layers = omni.usd.get_composed_references_from_prim(prim) self.assertTrue(len(ref_and_layers) == 1) reference_prim_widget = stage_widget.find("**/Label[*].text=='reference'") self.assertTrue(reference_prim_widget) await reference_prim_widget.right_click() with self.assertRaises(Exception): await ui_test.select_context_menu("Convert Payloads to References") await ui_test.select_context_menu("Convert References to Payloads") prim = stage.GetPrimAtPath("/root/prim/reference") ref_and_layers = omni.usd.get_composed_references_from_prim(prim) self.assertTrue(len(ref_and_layers) == 0) prim = stage.GetPrimAtPath("/root/prim/reference") payload_and_layers = omni.usd.get_composed_payloads_from_prim(prim) self.assertTrue(len(payload_and_layers) == 1) payload_prim_widget = stage_widget.find("**/Label[*].text=='payload'") self.assertTrue(payload_prim_widget) await payload_prim_widget.right_click() with self.assertRaises(Exception): await ui_test.select_context_menu("Convert References to Payloads") await ui_test.select_context_menu("Convert Payloads to References") prim = stage.GetPrimAtPath("/root/prim/payload") payload_and_layers = omni.usd.get_composed_payloads_from_prim(prim) self.assertTrue(len(payload_and_layers) == 0) reference_prim = stage.GetPrimAtPath("/root/prim/payload") ref_and_layers = omni.usd.get_composed_references_from_prim(prim) self.assertTrue(len(ref_and_layers) == 1)
8,933
Python
38.706666
113
0.567335
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_icon_menu.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.commands import omni.kit.test import omni.ui as ui import omni.usd from omni.ui.tests.test_base import OmniUiTest from omni.kit import ui_test from pxr import Kind, Sdf, Gf, Usd from pathlib import Path class TestIconMenu(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() from omni.kit.context_menu.scripts.context_menu import TEST_DATA_PATH self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() self._usd_path = TEST_DATA_PATH.absolute().joinpath("usd").absolute() self._usd_context = omni.usd.get_context() await self._usd_context.new_stage_async() # After running each test async def tearDown(self): await super().tearDown() # Test(s) async def test_icon_menu(self): def stub_fn(): pass def show_stub_false(objects): return False # setup menu icon_path = str(Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)).joinpath("data/tests/icons/button.svg")) menu_list = [ { "name": "Set Authoring Layer", "glyph": icon_path, "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Create Sublayer", "glyph": icon_path, "onclick_fn": stub_fn, }, { "name": "Insert Sublayer", "glyph": icon_path, "onclick_fn": stub_fn, }, { "name": "Merge Down One", "glyph": icon_path, "onclick_fn": stub_fn, }, { "name": "Flatten Sublayers", "glyph": icon_path, "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Save", "glyph": icon_path, "onclick_fn": stub_fn, }, { "name": "Save As", "glyph": icon_path, "onclick_fn": stub_fn, }, { "name": "Save As And Replace", "glyph": icon_path, "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Reload Layer", "glyph": icon_path, "onclick_fn": stub_fn, }, { "name": "Remove Layer", "glyph": icon_path, "onclick_fn": stub_fn, }, { "name": "Delete Prim", "glyph": icon_path, "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Select Bound Objects", "glyph": icon_path, "onclick_fn": stub_fn, }, {"name": ""}, {"glyph": "menu_link.svg", "name": { 'SubMenu': [ {'name': 'Set up axis +Y', 'onclick_fn': stub_fn}, {'name': 'Set up axis +Z', 'onclick_fn': stub_fn} ] }, }, {"glyph": "none.svg", "name": { 'SubMenu Hidden': [ {'name': 'Set up axis +Y', "show_fn": show_stub_false, 'onclick_fn': stub_fn}, {'name': 'Set up axis +Z', "show_fn": show_stub_false, 'onclick_fn': stub_fn} ] } }, ] window = await self.create_test_window(width=200, height=330) context_menu = omni.kit.context_menu.get_instance() context_menu.show_context_menu("toolbar", {"menu_xpos": 4, "menu_ypos": 4}, menu_list) await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_icon_menu_ui.png")
4,526
Python
32.533333
156
0.468626
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_enable_menu.py
## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import carb import omni.kit.app import omni.kit.test import omni.usd from omni.ui.tests.test_base import OmniUiTest from omni.kit import ui_test from omni.kit.test_suite.helpers import wait_stage_loading, arrange_windows class TestEnableCreateMenu(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() await arrange_windows() await omni.usd.get_context().new_stage_async() await wait_stage_loading() # After running each test async def tearDown(self): await super().tearDown() # Test(s) async def test_enable_create_menu(self): settings = carb.settings.get_settings() def reset_prim_creation(): settings.set("/app/primCreation/hideShapes", False) settings.set("/app/primCreation/enableMenuShape", True) settings.set("/app/primCreation/enableMenuLight", True) settings.set("/app/primCreation/enableMenuAudio", True) settings.set("/app/primCreation/enableMenuCamera", True) settings.set("/app/primCreation/enableMenuScope", True) settings.set("/app/primCreation/enableMenuXform", True) def verify_menu(menu_dict: dict, mesh:bool, shape:bool, light:bool, audio:bool, camera:bool, scope:bool, xform:bool): self.assertEqual("Mesh" in menu_dict, mesh) self.assertEqual("Shape" in menu_dict, shape) self.assertEqual("Light" in menu_dict, light) self.assertEqual("Audio" in menu_dict, audio) self.assertEqual("Camera" in menu_dict["_"], camera) self.assertEqual("Scope" in menu_dict["_"], scope) self.assertEqual("Xform" in menu_dict["_"], xform) async def test_menu(mesh:bool, shape:bool, light:bool, audio:bool, camera:bool, scope:bool, xform:bool): # right click on viewport await ui_test.find("Viewport").right_click() await ui_test.human_delay(10) #get context menu as dict menu_dict = await ui_test.get_context_menu() omni.kit.context_menu.close_menu() # verify verify_menu(menu_dict['Create'], mesh, shape, light, audio, camera, scope, xform) await ui_test.human_delay(10) try: # verify default reset_prim_creation() await test_menu(mesh=True, shape=True, light=True, audio=True, camera=True, scope=True, xform=True) # verify hide shapes reset_prim_creation() settings.set("/app/primCreation/hideShapes", True) await test_menu(mesh=True, shape=False, light=True, audio=True, camera=True, scope=True, xform=True) reset_prim_creation() settings.set("/app/primCreation/enableMenuShape", False) await test_menu(mesh=True, shape=False, light=True, audio=True, camera=True, scope=True, xform=True) # verify hide light reset_prim_creation() settings.set("/app/primCreation/enableMenuLight", False) await test_menu(mesh=True, shape=True, light=False, audio=True, camera=True, scope=True, xform=True) # verify hide audio reset_prim_creation() settings.set("/app/primCreation/enableMenuAudio", False) await test_menu(mesh=True, shape=True, light=True, audio=False, camera=True, scope=True, xform=True) # verify hide camera reset_prim_creation() settings.set("/app/primCreation/enableMenuCamera", False) await test_menu(mesh=True, shape=True, light=True, audio=True, camera=False, scope=True, xform=True) # verify hide scope reset_prim_creation() settings.set("/app/primCreation/enableMenuScope", False) await test_menu(mesh=True, shape=True, light=True, audio=True, camera=True, scope=False, xform=True) # verify hide xform reset_prim_creation() settings.set("/app/primCreation/enableMenuXform", False) await test_menu(mesh=True, shape=True, light=True, audio=True, camera=True, scope=True, xform=False) finally: reset_prim_creation()
4,667
Python
43.884615
125
0.643668
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_delegate_style.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.commands import omni.kit.test import pathlib import omni.ui as ui from omni.ui.tests.test_base import OmniUiTest from omni.kit import ui_test from omni.kit.test_suite.helpers import wait_stage_loading, arrange_windows from pxr import Kind, Sdf, Gf class TestContextMenuDelegateStyle(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() await arrange_windows() await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() stage.SetDefaultPrim(stage.DefinePrim("/World")) from omni.kit.context_menu.scripts.context_menu import TEST_DATA_PATH self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() self._usd_path = TEST_DATA_PATH.absolute().joinpath("usd").absolute() # After running each test async def tearDown(self): await super().tearDown() # Test(s) async def test_context_menu_style_leaks(self): from omni.kit.context_menu import ContextMenuExtension def stub_fn(): pass def show_stub_false(objects): return False # setup menu menu_list = [ { "name": "Set Authoring Layer", "glyph": "menu_rename.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Create Sublayer", "glyph": "menu_create_sublayer.svg", "onclick_fn": stub_fn, }, { "name": "Insert Sublayer", "glyph": "menu_insert_sublayer.svg", "onclick_fn": stub_fn, }, { "name": "Merge Down One", "glyph": "menu_merge_down.svg", "onclick_fn": stub_fn, }, { "name": "Flatten Sublayers", "glyph": "menu_flatten_layers.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Save", "glyph": "menu_save.svg", "onclick_fn": stub_fn, }, { "name": "Save As", "glyph": "menu_save_as.svg", "onclick_fn": stub_fn, }, { "name": "Save As And Replace", "glyph": "menu_save_as.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Reload Layer", "glyph": "menu_refresh.svg", "onclick_fn": stub_fn, }, { "name": "Remove Layer", "glyph": "menu_remove_layer.svg", "onclick_fn": stub_fn, }, { "name": "Delete Prim", "glyph": "menu_delete.svg", "onclick_fn": stub_fn, }, {"name": ""}, { "name": "Select Bound Objects", "glyph": "menu_search.svg", "onclick_fn": stub_fn, }, {"name": ""}, {"glyph": "menu_link.svg", "name": { 'SubMenu': [ {'name': 'Set up axis +Y', 'onclick_fn': stub_fn}, {'name': 'Set up axis +Z', 'onclick_fn': stub_fn} ] }, }, {"glyph": "none.svg", "name": { 'SubMenu Hidden': [ {'name': 'Set up axis +Y', "show_fn": show_stub_false, 'onclick_fn': stub_fn}, {'name': 'Set up axis +Z', "show_fn": show_stub_false, 'onclick_fn': stub_fn} ] } }, ] class MenuDelegate(ContextMenuExtension.DefaultMenuDelegate): TEXT_SIZE = 14 ICON_SIZE = 14 MARGIN_SIZE = [3, 3] def get_style(self): from omni.kit.context_menu import style vp_style = style.MENU_STYLE.copy() vp_style["Label::Enabled"] = {"margin_width": self.MARGIN_SIZE[0],"margin_height": self.MARGIN_SIZE[1],"color": self.COLOR_LABEL_ENABLED} vp_style["Label::Disabled"] = {"margin_width": self.MARGIN_SIZE[0], "margin_height": self.MARGIN_SIZE[1], "color": self.COLOR_LABEL_DISABLED} return vp_style def get_parameters(self, name, kwargs): kwargs["tearable"] = False window = await self.create_test_window(width=200, height=280) context_menu = omni.kit.context_menu.get_instance() context_menu.show_context_menu("viewport", {"menu_xpos": 4, "menu_ypos": 4}, menu_list, delegate=MenuDelegate()) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_context_menu_style_ui.png")
5,589
Python
34.605095
157
0.496869
omniverse-code/kit/exts/omni.kit.context_menu/omni/kit/context_menu/tests/test_prim_mesh_children_viewport.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import os import omni.kit.app import omni.usd from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from pxr import Sdf, UsdShade from omni.kit.test_suite.helpers import ( open_stage, get_test_data_path, select_prims, get_prims, wait_stage_loading, arrange_windows ) class CreatePrimMeshChildrenViewport(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows("Stage") await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() stage.SetDefaultPrim(stage.DefinePrim("/World")) await wait_stage_loading() # After running each test async def tearDown(self): await wait_stage_loading() async def test_create_prim_nochildren_mesh(self): await wait_stage_loading() # setup stage = omni.usd.get_context().get_stage() viewport_window = ui_test.find("Viewport") await viewport_window.focus() base_prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] # create light to be parent await viewport_window.right_click() menu_dict = await ui_test.get_context_menu() await ui_test.human_delay(10) await ui_test.select_context_menu("Create/Light/Distant Light", offset=ui_test.Vec2(10, 10)) # select light await ui_test.human_delay(10) await viewport_window.click() await ui_test.human_delay(10) # create meshes for mesh in menu_dict['Create']['Mesh']['_']: await viewport_window.right_click() await ui_test.human_delay() await ui_test.select_context_menu(f"Create/Mesh/{mesh}", offset=ui_test.Vec2(10, 10)) await ui_test.human_delay(10) # verify prims = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] final_prims = [x for x in prims if x not in base_prims] self.assertEqual(final_prims, ['/World/DistantLight', '/World/Cone', '/World/Cube', '/World/Cylinder', '/World/Disk', '/World/Plane', '/World/Sphere', '/World/Torus'])
2,683
Python
36.802816
175
0.671264
omniverse-code/kit/exts/omni.kit.context_menu/docs/index.rst
omni.kit.context_menu ########################### Context Menu Libraries .. toctree:: :maxdepth: 1 CHANGELOG Python API Reference ********************* .. automodule:: omni.kit.context_menu :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :imported-members: :exclude-members: partial :noindex: pathlib
357
reStructuredText
13.916666
43
0.582633
omniverse-code/kit/exts/omni.kit.window.property/config/extension.toml
[package] version = "1.8.2" category = "Internal" authors = ["NVIDIA"] title = "Property Window" description="Kit Property Window." repository = "" keywords = ["kit", "ui", "property"] changelog="docs/CHANGELOG.md" preview_image = "data/preview.png" icon = "data/icon.png" readme = "docs/README.md" [dependencies] "omni.usd" = {} "omni.ui" = {} "omni.client" = {} "omni.kit.menu.utils" = {} "omni.kit.context_menu" = {} # Main python module this extension provides, it will be publicly available as "import omni.example.hello". [[python.module]] name = "omni.kit.window.property" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.renderer.capture", "omni.kit.mainwindow", ] [settings] ext."omni.kit.window.property".labelAlignment = "left" ext."omni.kit.window.property".checkboxAlignment = "left" [documentation] pages = [ "docs/Overview.md", "docs/CHANGELOG.md", ]
989
TOML
20.521739
107
0.670374
omniverse-code/kit/exts/omni.kit.window.property/omni/kit/window/property/property_widget.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["PropertyWidget"] from abc import abstractmethod from typing import Optional import omni.ui as ui from .property_filter import PropertyFilter # Base class of a property widget class PropertyWidget: """ Base class to create a group of widgets in Property Window """ def __init__(self, title: str): self._title = title # Ensure we always have a valid filter because PropertyWidgets may be created outside PropertyWindow self._filter = PropertyFilter() @abstractmethod def clean(self): """ Clean up function to be called before destorying the object. """ pass @abstractmethod def reset(self): """ Clean up function to be called when previously built widget is no longer visible given new scheme/payload """ pass @abstractmethod def build_impl(self): """ Main function to creates the UI elements. """ pass @abstractmethod def on_new_payload(self, payload) -> bool: """ Called when a new payload is delivered. PropertyWidget can take this opportunity to update its ui models, or schedule full UI rebuild. Args: payload: The new payload to refresh UI or update model. Return: True if the UI needs to be rebuilt. build_impl will be called as a result. False if the UI does not need to be rebuilt. build_impl will not be called. """ pass def build(self, filter: Optional[PropertyFilter] = None): # TODO some other decoration/styling here if filter: self._filter = filter self.build_impl()
2,131
Python
29.89855
113
0.66213
omniverse-code/kit/exts/omni.kit.window.property/omni/kit/window/property/property_filter.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui class PropertyFilter: """User defined filters for properties. For now, just a substring filter on property names""" def __init__(self): self._name = ui.SimpleStringModel() def matches(self, name: str) -> bool: """Returns True if name matches filter, so property should be visible""" return not self.name or self.name.lower() in name.lower() @property def name_model(self): return self._name @property def name(self): return self._name.as_string @name.setter def name(self, n): self._name.as_string = n
1,043
Python
29.705881
97
0.701822
omniverse-code/kit/exts/omni.kit.window.property/omni/kit/window/property/managed_frame.py
import omni.ui as ui collapsed_settings = {} def prep(frame: ui.CollapsableFrame, type: str): global collapsed_settings index_name = f"{type}/{frame.title}" state = collapsed_settings.get(index_name, None) if not state is None: frame.collapsed = state frame.set_collapsed_changed_fn(lambda c, i=index_name: set_collapsed_state(i, c)) def set_collapsed_state(index_name: str, state: bool): global collapsed_settings if state == None: del collapsed_settings[index_name] else: collapsed_settings[index_name] = state def get_collapsed_state(index_name: str=None): global collapsed_settings if index_name: state = collapsed_settings.get(index_name, None) return state return collapsed_settings def reset_collapsed_state(): global collapsed_settings collapsed_settings = {}
874
Python
21.435897
85
0.680778
omniverse-code/kit/exts/omni.kit.window.property/omni/kit/window/property/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. # __all__ = ["get_window", "PropertyExtension"] import omni.ext import omni.kit.ui import weakref import omni.ui as ui from functools import partial from pathlib import Path from .window import PropertyWindow from .templates.header_context_menu import GroupHeaderContextMenu _property_window_instance = None TEST_DATA_PATH = "" def get_window(): return _property_window_instance if not _property_window_instance else _property_window_instance() class PropertyExtension(omni.ext.IExt): WINDOW_NAME = "Property" MENU_PATH = f"Window/{WINDOW_NAME}" def __init__(self): super().__init__() self._window = None self._header_context_menu = GroupHeaderContextMenu() def on_startup(self, ext_id): ui.Workspace.set_show_window_fn(PropertyExtension.WINDOW_NAME, partial(self.show_window, None)) editor_menu = omni.kit.ui.get_editor_menu() if editor_menu: self._menu = editor_menu.add_item(PropertyExtension.MENU_PATH, self.show_window, toggle=True, value=True) ui.Workspace.show_window(PropertyExtension.WINDOW_NAME) manager = omni.kit.app.get_app().get_extension_manager() extension_path = manager.get_extension_path(ext_id) global TEST_DATA_PATH TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests") def on_shutdown(self): self._menu = None if self._window: self._window.destroy() self._window = None if self._header_context_menu: self._header_context_menu.destroy() self._header_context_menu = None ui.Workspace.set_show_window_fn(PropertyExtension.WINDOW_NAME, None) def _visiblity_changed_fn(self, visible): omni.kit.ui.get_editor_menu().set_value(PropertyExtension.MENU_PATH, visible) def show_window(self, menu, value): global _property_window_instance if value: if self._window is None: self._window = PropertyWindow() self._window.set_visibility_changed_listener(self._visiblity_changed_fn) _property_window_instance = weakref.ref(self._window) self._window.set_visible(value) elif self._window: self._window.set_visible(value)
2,722
Python
33.910256
117
0.680382
omniverse-code/kit/exts/omni.kit.window.property/omni/kit/window/property/property_scheme_delegate.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["PropertySchemeDelegate"] from abc import abstractmethod from typing import List class PropertySchemeDelegate: """ PropertySchemeDelegate is a class to test given payload and determine what widgets to be drawn in what order. """ @abstractmethod def get_widgets(self, payload) -> List[str]: """ Tests the payload and gathers widgets in interest to be drawn in specific order. """ return [] def get_unwanted_widgets(self, payload) -> List[str]: """ Tests the payload and returns a list of widget names which this delegate does not want to include. Note that if there is another PropertySchemeDelegate returning widget in its get_widgets that conflicts with names in get_unwanted_widgets, get_widgets always wins (i.e. the Widget will be drawn). This function is optional. """ return []
1,342
Python
36.305555
117
0.71535
omniverse-code/kit/exts/omni.kit.window.property/omni/kit/window/property/window.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["PropertyWindow"] import copy from typing import Any, List, Optional import carb import carb.settings import omni.ui as ui from omni.kit.widget.searchfield import SearchField from .property_filter import PropertyFilter from .property_scheme_delegate import PropertySchemeDelegate from .property_widget import PropertyWidget from .templates.simple_property_widget import LABEL_HEIGHT # Property Window framework class PropertyWindow: def __init__(self, window_kwargs=None, properties_frame_kwargs=None): """ Create a PropertyWindow Args: window_kwargs: Additional kwargs to pass to ui.Window properties_frame_kwargs: Additional kwargs to pass to ui.ScrollingFrame """ window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR self._settings = carb.settings.get_settings() self._visibility_changed_listener = None self._window_kwargs = { "title": "Property", "width": 600, "height": 800, "flags": window_flags, "dockPreference": ui.DockPreference.RIGHT_BOTTOM, } if window_kwargs: self._window_kwargs.update(window_kwargs) self._properties_frame_kwargs = { "name": "canvas", "horizontal_scrollbar_policy": ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, "vertical_scrollbar_policy": ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, } if properties_frame_kwargs: self._properties_frame_kwargs.update(properties_frame_kwargs) self._window = ui.Window(**self._window_kwargs) self._window.set_visibility_changed_fn(self._visibility_changed_fn) self._window.frame.set_build_fn(self._rebuild_window) # Dock it to the same space where Layers is docked, make it the first tab and the active tab. self._window.deferred_dock_in("Details", ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE) self._window.dock_order = 0 self._scheme = "" self._payload = None self._scheme_delegates = {} self._scheme_delegates_layout = {} self._widgets_top = {} self._widgets_bottom = {} self._built_widgets = set() self._notification_paused = False self._notifications_while_paused = [] self._filter = PropertyFilter() self._window_frame = None # for compatiblity with clients that look for this to modify ScrollingFrame def destroy(self): self._visibility_changed_listener = None self._window = None def set_visible(self, visible: bool): if self._window: self._window.visible = visible def _on_search(self, search_words: Optional[List[str]]) -> None: self._filter.name = "" if search_words is None else " ".join(search_words) def _rebuild_window(self): # We should only rebuild the properties ScrollingFrame on payload change, but that doesn't work # reliably so as a workaround we rebuild the entire window including static searchfield. use_default_style = ( carb.settings.get_settings().get_as_string("/persistent/app/window/useDefaultStyle") or False ) if use_default_style: style = {} else: from .style import get_style style = get_style() with ui.VStack(style=style): if carb.settings.get_settings().get_as_bool("/ext/omni.kit.window.property/enableSearch"): with ui.HStack(height=0): ui.Spacer(width=8) self._searchfield = SearchField( on_search_fn=self._on_search, subscribe_edit_changed=True, show_tokens=False, height=LABEL_HEIGHT, style=style, ) # Workaround for needing to rebuild SearchField: fill with existing filter text if self._filter.name: self._searchfield._search_field.model.as_string = self._filter.name self._searchfield._set_in_searching(True) ui.Spacer(width=5 + 12) # scrollbar width is 12 ui.Spacer(height=5) self._window_frame = ui.ScrollingFrame(**self._properties_frame_kwargs) with self._window_frame: with ui.VStack(height=0, name="main_v_stack", spacing=6): if self._scheme != "": widgets_to_build = [] unwanted_widgets = [] scheme_delegates_layout = self._scheme_delegates_layout.get(self._scheme) scheme_delegates = self._scheme_delegates.setdefault(self._scheme, {}) scheme_delegates_filtered = [] if scheme_delegates_layout: for delegate_name in scheme_delegates_layout: delegate = scheme_delegates.get(delegate_name) if delegate: scheme_delegates_filtered.append(delegate) else: scheme_delegates_filtered = scheme_delegates.values() for delegate in scheme_delegates_filtered: widgets_to_build.extend(delegate.get_widgets(self._payload)) unwanted_widgets.extend(delegate.get_unwanted_widgets(self._payload)) # ordered top stack + reverse ordered bottom stack all_registered_widgets = { **self._widgets_top.setdefault(self._scheme, {}), **dict(reversed(list(self._widgets_bottom.setdefault(self._scheme, {}).items()))), } # keep order widget_name_already_built = set() built_widgets = set() for widget_name in widgets_to_build: # skip dup if widget_name in widget_name_already_built: continue widget = all_registered_widgets.get(widget_name) if widget and widget.on_new_payload(self._payload): widget.build(self._filter) built_widgets.add(widget) widget_name_already_built.add(widget_name) # Build the rest of the widgets that are not unwanted unwanted_widgets_set = set(unwanted_widgets) all_widgets = all_registered_widgets.keys() for widget_name in all_widgets: if widget_name not in widget_name_already_built and widget_name not in unwanted_widgets_set: widget = all_registered_widgets.get(widget_name) if widget and widget.on_new_payload(self._payload): widget.build(self._filter) built_widgets.add(widget) # Reset those widgets that are built before but no longer needed for widget in self._built_widgets: if widget not in built_widgets: widget.reset() self._built_widgets = built_widgets def _visibility_changed_fn(self, visible): if not visible: # When the property window is no longer visible, reset all the built widget so they don't take CPU time in background for widget in self._built_widgets: widget.reset() self._built_widgets.clear() # schedule a rebuild of window frame. _rebuild_window won't be actually called until the window is visible again. self._window.frame.rebuild() if self._visibility_changed_listener: self._visibility_changed_listener(visible) def set_visibility_changed_listener(self, listener): self._visibility_changed_listener = listener def register_widget(self, scheme: str, name: str, property_widget: PropertyWidget, top_stack: bool = True): """ Registers a PropertyWidget to PropertyWindow. Args: scheme (str): Scheme of the PropertyWidget will work with. name (str): A unique name to identify the PropertyWidget under. Widget with existing name will be overridden. property_widget (property_widget.PropertyWidget): A PropertyWidget instance to be added. top_stack (bool): Widgets are managed in double stack: True to register the widget to "Top" stack which layouts widgets from top to bottom. False to register the widget to "Button" stack which layouts widgets from bottom to top and always below the "Top" stack. """ if top_stack: self._widgets_top.setdefault(scheme, {})[name] = property_widget self._widgets_bottom.setdefault(scheme, {}).pop(name, None) else: self._widgets_bottom.setdefault(scheme, {})[name] = property_widget self._widgets_top.setdefault(scheme, {}).pop(name, None) if scheme == self._scheme: self._window.frame.rebuild() def unregister_widget(self, scheme: str, name: str, top_stack: bool = True): """ Unregister a PropertyWidget from PropertyWindow. Args: scheme (str): Scheme of the PropertyWidget to be removed from. name (str): The name to find the PropertyWidget and remove. top_stack (bool): see @register_widget """ if top_stack: widget = self._widgets_top.setdefault(scheme, {}).pop(name, None) else: widget = self._widgets_bottom.setdefault(scheme, {}).pop(name, None) if widget: widget.clean() if scheme == self._scheme: self._window.frame.rebuild() def register_scheme_delegate(self, scheme: str, name: str, delegate: PropertySchemeDelegate): """ Register a PropertySchemeDelegate for a given scheme. A PropertySchemeDelegate tests the payload and determines what widgets to be drawn in what order. A scheme can have multiple PropertySchemeDelegate and their result will be merged to display all relevant widgets. PropertySchemeDelegate does not hide widgets that are not returned from its get_widgets function. If you want to hide certain widget, return them in PropertySchemeDelegate.get_unwanted_widgets. See PropertySchemeDelegate's documentation for details. Args: scheme (str): Scheme of the PropertySchemeDelegate to be added to. name (str): A unique name to identify the PropertySchemeDelegate under. Delegate with existing name will be overridden. delegate (PropertySchemeDelegate): A PropertySchemeDelegate instance to be added. """ self._scheme_delegates.setdefault(scheme, {})[name] = delegate if scheme == self._scheme: self._window.frame.rebuild() def unregister_scheme_delegate(self, scheme: str, name: str): """ Unregister a PropertySchemeDelegate from PropertyWindow by name. Args: scheme (str): Scheme of the PropertySchemeDelegate to be removed from. name (str): The name to find the PropertySchemeDelegate and remove. """ self._scheme_delegates.setdefault(scheme, {}).pop(name, None) if scheme == self._scheme: self._window.frame.rebuild() def set_scheme_delegate_layout(self, scheme: str, layout: List[str]): """ Register a list of PropertySchemeDelegate's names to finalize the order and visibility of all registered PropertySchemeDelegate. Useful if you need a fixed layout of Property Widgets for your Kit experience. Remark: If you're a Property Widget writer, DO NOT call this function. It should only be called by Kit Experience to tune the final look and layout of the Property Window. Args: scheme (str): Scheme of the PropertySchemeDelegate order to be added to. layout (List(str)): a list of PropertySchemeDelegate's name, in the order of being processed when building UI. Scheme delegate not in this will be skipped. """ self._scheme_delegates_layout[scheme] = layout if scheme == self._scheme: self._window.frame.rebuild() def reset_scheme_delegate_layout(self, scheme: str): """ Reset the order so PropertySchemeDelegate will be processed in the order of registration when building UI. Args: scheme (str): Scheme of the PropertySchemeDelegate order to be removed from. """ self._scheme_delegates_layout.pop(scheme) if scheme == self._scheme: self._window.frame.rebuild() def notify(self, scheme: str, payload: Any): """ Notify Property Window of a scheme and/or payload change. This is the function to trigger refresh of PropertyWindow. Args: scheme (str): Scheme of this notification. payload: Payload to refresh the widgets. """ if self._notification_paused: self._notifications_while_paused.append((scheme, copy.copy(payload))) else: if self._scheme != scheme: if payload: self._scheme = scheme self._payload = payload self._window.frame.rebuild() elif self._payload != payload: self._payload = payload self._window.frame.rebuild() def get_scheme(self): """ Gets the current scheme being displayed in Property Window. """ return self._scheme def request_rebuild(self): """ Requests the entire property window to be rebuilt. """ if self._window: self._window.frame.rebuild() @property def paused(self): """ Gets if property window refresh is paused. """ return self._notification_paused @paused.setter def paused(self, to_pause: bool): """ Sets if property window refresh is paused. When property window is paused, calling `notify` will not refresh Property Window content. When property window is resumed, the window will refresh using the queued schemes and payloads `notified` to Property Window while paused. Args: to_pause: True to pause property window refresh. False to resume property window refresh. """ if to_pause: self._notification_paused = True else: if self._notification_paused: self._notification_paused = False for notification in self._notifications_while_paused: self.notify(notification[0], notification[1]) self._notifications_while_paused.clear() @property def properties_frame(self): """Gets the ui.ScrollingFrame container of PropertyWidgets""" return self._window_frame # misnamed for backwards compatibility
16,027
Python
44.276836
151
0.592937
omniverse-code/kit/exts/omni.kit.window.property/omni/kit/window/property/templates/simple_property_widget.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = [ "LABEL_WIDTH", "LABEL_WIDTH_LIGHT", "LABEL_HEIGHT", "HORIZONTAL_SPACING", "build_frame_header", "SimplePropertyWidget", "GroupHeaderContextMenu", "GroupHeaderContextMenuEvent", "PropertyWidget", # omni.kit.property.environment tries to import this from here ] import asyncio import functools import traceback import carb import omni.ui as ui import omni.kit.window.property.managed_frame import omni.kit.app from omni.kit.async_engine import run_coroutine from omni.kit.widget.highlight_label import HighlightLabel from omni.kit.window.property.property_widget import PropertyWidget from omni.kit.window.property.style import get_style from .header_context_menu import GroupHeaderContextMenu, GroupHeaderContextMenuEvent LABEL_WIDTH = 160 LABEL_WIDTH_LIGHT = 235 LABEL_HEIGHT = 18 HORIZONTAL_SPACING = 4 def handle_exception(func): """ Decorator to print exception in async functions """ @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 def build_frame_header(collapsed, text: str, id: str = None): """Custom header for CollapsibleFrame""" if id is None: id = text if collapsed: alignment = ui.Alignment.RIGHT_CENTER width = 5 height = 7 else: alignment = ui.Alignment.CENTER_BOTTOM width = 7 height = 5 header_stack = ui.HStack(spacing=8) with header_stack: with ui.VStack(width=0): ui.Spacer() ui.Triangle( style_type_name_override="CollapsableFrame.Header", width=width, height=height, alignment=alignment ) ui.Spacer() ui.Label(text, style_type_name_override="CollapsableFrame.Header") def show_attribute_context_menu(b): if b != 1: return event = GroupHeaderContextMenuEvent(group_id=id, payload=[]) GroupHeaderContextMenu.on_mouse_event(event) header_stack.set_mouse_pressed_fn(lambda x, y, b, _: show_attribute_context_menu(b)) class SimplePropertyWidget(PropertyWidget): """ SimplePropertyWidget provides a simple vertical list of "Label" -> "Value widget" pair layout. """ def __init__(self, title: str, collapsed: bool = False, collapsable: bool = True): super().__init__(title) self._collapsed_default = collapsed self._collapsed = collapsed self._collapsable = collapsable self._collapsable_frame = None self._payload = None self._pending_rebuild_task = None self._filter_changed_sub = None self.__style = get_style() def clean(self): """ See PropertyWidget.clean """ self.reset() if self._pending_rebuild_task is not None: self._pending_rebuild_task.cancel() self._pending_rebuild_task = None if self._collapsable_frame is not None: self._collapsable_frame.set_build_fn(None) if self._collapsable: self._collapsable_frame.set_collapsed_changed_fn(None) self._collapsable_frame = None def reset(self): """ See PropertyWidget.reset """ # Do not cancel rebuild task here as we are called from that task through derived build_items() pass def request_rebuild(self): """ Request the widget to rebuild. It will be rebuilt on next frame. """ if self._pending_rebuild_task: return self._pending_rebuild_task = run_coroutine(self._delayed_rebuild()) def add_label(self, label: str): """ Add a Label with a highlight text based on current filter """ filter_text = self._filter.name HighlightLabel(label, highlight=filter_text, name="label", width=LABEL_WIDTH, height=LABEL_HEIGHT, style=self.__style) def add_item(self, label: str, value): """ This function is supposed to be called inside of build_items function. Adds a "Label" -> "Value widget" pair item to the widget. "value" will be an uneditable string in a StringField. Args: label (str): The label text of the entry. value: The value to be stringified and displayed in a StringField. """ if not self._filter.matches(label): return with ui.HStack(spacing=HORIZONTAL_SPACING): self.add_label(label) ui.StringField(name="models").model.set_value(str(value)) self._any_item_visible = True def add_item_with_model(self, label: str, model, editable: bool = False, identifier: str=None): """ This function is supposed to be called inside of build_items function. Adds a "Label" -> "Value widget with model" pair item to the widget. "value" will be an editable string in a StringField backed by supplied model. Args: label (str): The label text of the entry. model: The model to be used by the string field. editable: If the StringField generated from model should be editable. Default is False. """ if not self._filter.matches(label): return with ui.HStack(spacing=HORIZONTAL_SPACING): self.add_label(label) sf = ui.StringField(name="models", model=model, enabled=editable) if identifier and sf: sf.identifier = identifier self._any_item_visible = True def on_new_payload(self, payload, ignore_large_selection=False) -> bool: """ See PropertyWidget.on_new_payload """ self._payload = payload if ( not ignore_large_selection and payload and hasattr(payload, "is_large_selection") and payload.is_large_selection() ): return False return True def build_items(self): """ When deriving from SimplePropertyWidget, override this function to build your items. """ self.add_item("Hello", "World") def build_impl(self): """ See PropertyWidget.build_impl """ if self._filter_changed_sub is None: self._filter_changed_sub = self._filter.name_model.add_value_changed_fn(self._on_filter_changed) if self._collapsable: self._collapsable_frame = ui.CollapsableFrame( self._title, build_header_fn=self._build_frame_header, collapsed=self._collapsed_default ) def on_collapsed_changed(collapsed): self._collapsed = collapsed self._collapsable_frame.set_collapsed_changed_fn(on_collapsed_changed) omni.kit.window.property.managed_frame.prep(self._collapsable_frame, type="Property") else: self._collapsable_frame = ui.Frame(height=0, style={"Frame": {"padding": 0}}) # We cannot use build_fn because rebuild() won't trigger on invisible frames and toggling visible # first causes flicker during property search. So we build explicitly here. # request_rebuild() is still deferred to support batching of changes. self.request_rebuild() def _build_frame_header(self, collapsed, text: str, id: str = None): build_frame_header(collapsed, text, id) def _build_frame(self): import time start = time.time() with ui.VStack(height=0, spacing=5, name="frame_v_stack"): # ui.Spacer(height=0) self._any_item_visible = False self.build_items() if self._filter.name: self._collapsable_frame.visible = self._any_item_visible else: # for compatibility with widgets which don't support filtering self._collapsable_frame.visible = True ui.Spacer(height=0) took = time.time() - start if took > 0.2: import carb carb.log_warn(f"{self.__class__.__name__}.build_items took {took} seconds") @handle_exception async def _delayed_rebuild(self): if self._pending_rebuild_task is not None: try: if self._collapsable_frame: with self._collapsable_frame: self._build_frame() self._collapsable_frame.rebuild() # force rebuild of frame header too finally: self._pending_rebuild_task = None def _on_filter_changed(self, m: ui.AbstractValueModel): """ Called when filter changes. Default calls request_rebuild(). Derived classes can override to optimize by selectively changing property visibility. """ self.request_rebuild()
9,549
Python
34.110294
126
0.620903
omniverse-code/kit/exts/omni.kit.window.property/omni/kit/window/property/templates/header_context_menu.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 typing import Any import omni.kit.commands import omni.kit.undo import omni.usd class GroupHeaderContextMenuEvent: def __init__(self, group_id: str, payload: Any): self.group_id = group_id self.payload = payload self.type = 0 class GroupHeaderContextMenu: _instance = None def __init__(self): GroupHeaderContextMenu._instance = self def __del__(self): self.destroy() def destroy(self): GroupHeaderContextMenu._instance = None @classmethod def on_mouse_event(cls, event: GroupHeaderContextMenuEvent): if cls._instance: cls._instance._on_mouse_event(event) def _on_mouse_event(self, event: GroupHeaderContextMenuEvent): import omni.kit.context_menu # check its expected event if event.type != int(omni.kit.ui.MenuEventType.ACTIVATE): return # setup objects, this is passed to all functions objects = { "payload": event.payload, } menu_list = omni.kit.context_menu.get_menu_dict( "group_context_menu." + event.group_id, "omni.kit.window.property" ) omni.kit.context_menu.get_instance().show_context_menu( "group_context_menu." + event.group_id, objects, menu_list )
1,737
Python
28.965517
78
0.668969
omniverse-code/kit/exts/omni.kit.window.property/omni/kit/window/property/tests/property_test.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.kit.app import omni.kit.commands import omni.kit.test import omni.ui as ui from omni.ui.tests.test_base import OmniUiTest async def wait_for_update(usd_context=omni.usd.get_context(), wait_frames=10): max_loops = 0 while max_loops < wait_frames: _, files_loaded, total_files = usd_context.get_stage_loading_status() await omni.kit.app.get_app().next_update_async() if files_loaded or total_files: continue max_loops = max_loops + 1 class TestPropertyWindow(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() from omni.kit.window.property.extension import TEST_DATA_PATH self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() self._usd_path = TEST_DATA_PATH.absolute() import omni.kit.window.property as p self._w = p.get_window() # After running each test async def tearDown(self): await super().tearDown() # test scheme async def test_property_window_scheme(self): from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate from omni.kit.window.property.templates import LABEL_HEIGHT, SimplePropertyWidget class SchemeTestWidget(SimplePropertyWidget): def __init__(self, name: str): super().__init__(title="SchemeTestWidget", collapsable=False) self._name = name nonlocal init_called init_called = True def on_new_payload(self, payload): nonlocal new_payload_called new_payload_called = True return True def build_items(self): nonlocal build_items_called build_items_called = True ui.Separator() with ui.HStack(height=0): ui.Spacer(width=8) ui.Button(self._name, width=52, height=LABEL_HEIGHT, name="add") ui.Spacer(width=88 - 52) widget = ui.StringField(name="scheme_name", height=LABEL_HEIGHT, enabled=False) widget.model.set_value(f"{self._name}-" * 100) ui.Separator() class TestPropertySchemeDelegate(PropertySchemeDelegate): def get_widgets(self, payload): widgets_to_build = [] if len(payload): # should still only appear once widgets_to_build.append("test_property_window_scheme_test") widgets_to_build.append("test_property_window_scheme_test") return widgets_to_build # enable custom widget/scheme w = self._w init_called = False w.register_widget("test_scheme_1", "test_property_window_scheme_test", SchemeTestWidget("TEST1")) self.assertTrue(init_called) init_called = False w.register_widget("test_scheme_2", "test_property_window_scheme_test", SchemeTestWidget("TEST2")) self.assertTrue(init_called) init_called = False w.register_widget("test_scheme_3", "test_property_window_scheme_test", SchemeTestWidget("TEST3")) self.assertTrue(init_called) init_called = False w.register_widget("test_scheme_4", "test_property_window_scheme_test", SchemeTestWidget("TEST4")) self.assertTrue(init_called) w.register_scheme_delegate( "test_scheme_delegate", "test_property_window_scheme_test_scheme", TestPropertySchemeDelegate() ) w.set_scheme_delegate_layout("test_scheme_delegate", ["test_property_window_scheme_test_scheme"]) self.assertEqual(w.get_scheme(), "") # draw (should draw SchemeTestWidget item "TEST1") for scheme in ["test_scheme_1", "test_scheme_2", "test_scheme_3", "test_scheme_4"]: new_payload_called = False build_items_called = False await self.docked_test_window( window=self._w._window, width=450, height=200, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) w.notify(scheme, {"payload": ["Items..."]}) await wait_for_update() self.assertTrue(w.get_scheme() == scheme) self.assertTrue(new_payload_called) self.assertTrue(build_items_called) await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name=f"property_window_{scheme}.png" ) # disable custom widget/scheme await self.docked_test_window( window=self._w._window, width=450, height=200, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) w.reset_scheme_delegate_layout("test_scheme_delegate") w.unregister_widget("test_scheme_4", "test_property_window_scheme_test") w.unregister_widget("test_scheme_3", "test_property_window_scheme_test") w.unregister_widget("test_scheme_2", "test_property_window_scheme_test") w.unregister_widget("test_scheme_1", "test_property_window_scheme_test") w.unregister_scheme_delegate("test_scheme_delegate", "test_property_window_scheme_test_scheme") # draw (should draw nothing) for scheme in ["test_scheme_1", "test_scheme_2", "test_scheme_3", "test_scheme_4"]: new_payload_called = False build_items_called = False await self.docked_test_window( window=self._w._window, width=450, height=200, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) w.notify(scheme, {"payload": ["Items..."]}) await wait_for_update() self.assertTrue(w.get_scheme() == scheme) self.assertFalse(new_payload_called) self.assertFalse(build_items_called) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=f"property_window_empty.png") await wait_for_update() async def test_pause_resume_property_window(self): from omni.kit.window.property.templates import LABEL_HEIGHT, SimplePropertyWidget class SchemeTestWidget(SimplePropertyWidget): def __init__(self, name: str): super().__init__(title="SchemeTestWidget", collapsable=False) self._name = name def on_new_payload(self, payload): if not super().on_new_payload(payload): return False return self._payload == self._name def build_items(self): ui.Separator() with ui.HStack(height=0): ui.Spacer(width=8) ui.Button(self._name, width=52, height=LABEL_HEIGHT, name="add") ui.Spacer(width=88 - 52) widget = ui.StringField(name="scheme_name", height=LABEL_HEIGHT, enabled=False) widget.model.set_value(f"{self._name}-" * 100) ui.Separator() # enable custom widget/scheme w = self._w w.register_widget("test_scheme_1", "test_property_window_scheme_test", SchemeTestWidget("TEST1")) w.register_widget("test_scheme_1", "test_property_window_scheme_test2", SchemeTestWidget("TEST2")) w.register_widget("test_scheme_2", "test_property_window_scheme_test3", SchemeTestWidget("TEST3")) # Not paused, refresh normally, show TEST1 await self.docked_test_window( window=self._w._window, width=450, height=200, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) w.notify("test_scheme_1", "TEST1") await wait_for_update() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="property_window_paused.png") # Pause property window w.paused = True # Paused, property window stops updating, show TEST1 await self.docked_test_window( window=self._w._window, width=450, height=200, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) w.notify("test_scheme_1", "TEST2") await wait_for_update() w.notify("test_scheme_2", "TEST3") await wait_for_update() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="property_window_paused.png") # Resume property window, refresh to last scheme/payload, show TEST3 w.paused = False await self.docked_test_window( window=self._w._window, width=450, height=200, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) await wait_for_update() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="property_window_resumed.png") # Not paused, refresh normally, show TEST2 await self.docked_test_window( window=self._w._window, width=450, height=200, restore_window=ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position=ui.DockPosition.BOTTOM, ) w.notify("test_scheme_1", "TEST2") await wait_for_update() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="property_window_resumed2.png") w.unregister_widget("test_scheme_2", "test_property_window_scheme_test3") w.unregister_widget("test_scheme_1", "test_property_window_scheme_test2") w.unregister_widget("test_scheme_1", "test_property_window_scheme_test") # clear the schema - notify("", "") is ignored w.notify("", "payload") await wait_for_update()
10,878
Python
40.522901
119
0.607189
omniverse-code/kit/exts/omni.kit.window.property/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.8.2] - 2022-08-08 ### Added - Added style for `Grab` color. ## [1.8.1] - 2021-04-26 ### Changed - Added `identifier` parameter to `add_item_with_model` to set StringField identifier ## [1.8.0] - 2021-03-17 ### Changed - Changed builder function to a class member to enable polymorphism ## [1.7.0] - 2022-02-14 ### Added - Added context menu for collaspeable header - Added `request_rebuild` ## [1.6.3] - 2021-06-29 ### Changed - Added Field::url style ## [1.6.2] - 2021-06-21 ### Changed - Fixed issue with layer metadata not showing sometimes ## [1.6.1] - 2021-05-18 ### Added - Updated Checkbox style ## [1.6.0] - 2021-04-28 ### Added - Added `paused` property to Property Window API to pause/resume handling `notify` function. ## [1.5.5] - 2021-04-23 ### Changed - Fixed exception when using different payload class ## [1.5.4] - 2021-04-21 ### Changed - Added warning if build_items takes too long to process ## [1.5.3] - 2021-02-02 ### Changed - Used PrimCompositionQuery to query references. - Fixed removing reference from a layer that's under different directory than introducing layer. - Fixed finding referenced assets in Content Window with relative paths. ## [1.5.2] - 2020-12-09 ### Changed - Added extension icon - Added readme - Updated preview image ## [1.5.1] - 2020-11-20 ### Changed - Prevented exception on shutdown in simple_property_widget function `_delayed_rebuild` ## [1.5.0] - 2020-11-18 ### Added - Added `top_stack` parameter to `PropertyWindow.register_widget` and `PropertyWindow.unregister_widget`. Set True to register the widget to "Top" stack which layouts widgets from top down. False to register the widget to "Button" stack which layouts widgets from bottom up and always below the "Top" stack. Default is True. Order only matters when no `PropertySchemeDelegate` applies on the widget. ## [1.4.0] - 2020-11-16 ### Added - Added `reset` function to `PropertyWidget`. It will be called when a widget is no longer applicable to build under new scheme/payload. ## [1.3.1] - 2020-10-22 ### Added - Changed style label text color ## [1.3.0] - 2020-10-19 ### Added - Added "request_rebuild" function to "SimplePropertyWidget". It collects rebuild requests and rebuild on next frame. ## [1.2.0] - 2020-10-19 ### Added - Added get_scheme to PropertyWindow class. ## [1.1.0] - 2020-10-02 ### Changed - Update to CollapsableFrame open by default setting. ## [1.0.0] - 2020-09-17 ### Added - Created.
2,547
Markdown
27.311111
399
0.702788
omniverse-code/kit/exts/omni.kit.window.property/docs/README.md
# omni.kit.window.property ## Introduction Property window extensions are for viewing and editing Usd Prim Attributes ## This extension enables all other property windows and is the controlling API
201
Markdown
24.249997
79
0.80597
omniverse-code/kit/exts/omni.kit.window.property/docs/index.rst
omni.kit.window.property: Property Window Extension #################################################### .. toctree:: :maxdepth: 1 Overview.md CHANGELOG Property Window ========================== .. automodule:: omni.kit.window.property :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :imported-members: :show-inheritance: :exclude-members: PropertyExtension, partial :noindex: omni.kit.window.property.templates Property Widget ========================== .. automodule:: omni.kit.window.property.property_widget :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :imported-members: :show-inheritance: :exclude-members: abstractmethod Property Scheme Delegate ========================== .. automodule:: omni.kit.window.property.property_scheme_delegate :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :imported-members: :show-inheritance: :exclude-members: List, abstractmethod Property Widgets Templates ========================== .. automodule:: omni.kit.window.property.templates :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :imported-members: :show-inheritance: :exclude-members: build_frame_header
1,296
reStructuredText
24.431372
65
0.619599
omniverse-code/kit/exts/omni.videoencoding/video_encoding/__init__.py
from .impl import *
20
Python
9.499995
19
0.7
omniverse-code/kit/exts/omni.videoencoding/video_encoding/_video_encoding.pyi
""" Bindings for the omni::IVideoEncoding interface. """ from __future__ import annotations import video_encoding._video_encoding import typing __all__ = [ "IVideoEncoding", "acquire_video_encoding_interface", "release_video_encoding_interface" ] class IVideoEncoding(): def encode_next_frame_from_buffer(self, buffer_rgba8: buffer, width: int = 0, height: int = 0) -> bool: """ Encode a frame and write the result to disk. Args: buffer_rgba8 raw frame image data; format: R8G8B8A8; size: width * height * 4 width frame width; can be inferred from shape of buffer_rgba8 if set appropriately height frame height; can be inferred from shape of buffer_rgba8 if set appropriately Returns: True if successful, else False. """ def encode_next_frame_from_file(self, frame_filename: str) -> None: """ Read a frame from an image file, encode, and write to disk. Warning: pixel formats other than RGBA8 will probably not work (yet). Args: frame_filename name of the file to read. Supported file formats: see carb::imaging """ def finalize_encoding(self) -> None: """ Indicate that all frames have been encoded. This will ensure that writing to the output video file is done, and close it. """ def start_encoding(self, video_filename: str, framerate: float, nframes: int, overwrite_video: bool) -> bool: """ Prepare the encoding plugin to process frames. Args: video_filename name of the MP4 file where the encoded video will be written framerate number of frames per second nframes total number of frames; if unknown, set to 0 overwrite_video if set, overwrite existing MP4 file; otherwise, refuse to do anything if the file specified in video_filename exists. Returns: True if preparation succeeded and the encoding plugin is ready; False otherwise. """ pass def acquire_video_encoding_interface(plugin_name: str = None, library_path: str = None) -> IVideoEncoding: pass def release_video_encoding_interface(arg0: IVideoEncoding) -> None: pass
2,254
unknown
39.267856
145
0.656167
omniverse-code/kit/exts/omni.videoencoding/video_encoding/tests/test_encoding.py
import omni.kit.test import carb.settings import os import tempfile import numpy as np from video_encoding import get_video_encoding_interface VIDEO_FULL_RANGE_PATH = "/exts/omni.videoencoding/vui/videoFullRangeFlag" class Test(omni.kit.test.AsyncTestCase): def get_next_frame(self, shape=(480,640,4)): values = self._rng.random(shape) result = (values * 255.).astype(np.uint8) return result async def setUp(self): print('setUp called') self._rng = np.random.default_rng(seed=1234) self._settings = carb.settings.acquire_settings_interface() self._encoding_interface = get_video_encoding_interface() async def tearDown(self): self._rng = None def _encode_test_sequence(self, n_frames=10): n_frames = 10 with tempfile.TemporaryDirectory() as tmpdirname: video_filename = os.path.join(tmpdirname,'output.mp4') self.assertTrue(self._encoding_interface.start_encoding(video_filename, 24, n_frames, True), msg="Failed to initialize encoding interface.") for i_frame in range(n_frames): frame_data = self.get_next_frame() self._encoding_interface.encode_next_frame_from_buffer(frame_data) self._encoding_interface.finalize_encoding() encoded_size = os.path.getsize(video_filename) return encoded_size async def test_encoding_interface(self): self._settings.set(VIDEO_FULL_RANGE_PATH, False) encoded_size = self._encode_test_sequence(n_frames=10) expected_encoded_size = 721879 self.assertAlmostEqual(encoded_size / expected_encoded_size, 1., places=1, msg=f"Expected encoded video size {expected_encoded_size}; got: {encoded_size}") async def test_encoding_interface_with_full_range(self): self._settings.set(VIDEO_FULL_RANGE_PATH, True) encoded_size = self._encode_test_sequence(n_frames=10) expected_encoded_size = 1081165 self.assertAlmostEqual(encoded_size / expected_encoded_size, 1., places=1, msg=f"Expected encoded video size {expected_encoded_size}; got: {encoded_size}")
2,201
Python
34.516128
104
0.663789
omniverse-code/kit/exts/omni.videoencoding/video_encoding/tests/__init__.py
from .test_encoding import *
28
Python
27.999972
28
0.785714
omniverse-code/kit/exts/omni.videoencoding/video_encoding/impl/__init__.py
from .video_encoding import *
30
Python
14.499993
29
0.766667
omniverse-code/kit/exts/omni.videoencoding/video_encoding/impl/video_encoding.py
import os import carb import omni.ext from .._video_encoding import * # Put interface object publicly to use in our API. _video_encoding_api = None def get_video_encoding_interface() -> IVideoEncoding: return _video_encoding_api def encode_image_file_sequence(filename_pattern, start_number, frame_rate, output_file, overwrite_existing) -> bool: video_encoding_api = get_video_encoding_interface() if video_encoding_api is None: carb.log_warn("Video encoding api not available; cannot encode video.") return False # acquire list of available frame image files, based on start_number and filename_pattern next_frame = start_number frame_filenames = [] while True: frame_filename = filename_pattern % (next_frame) if os.path.isfile(frame_filename) and os.access(frame_filename, os.R_OK): frame_filenames.append(frame_filename) next_frame += 1 else: break carb.log_warn(f"Found {len(frame_filenames)} frames to encode.") if len(frame_filenames) == 0: carb.log_warn(f"No frames to encode.") return False if not video_encoding_api.start_encoding(output_file, frame_rate, len(frame_filenames), overwrite_existing): return try: for frame_filename in frame_filenames: video_encoding_api.encode_next_frame_from_file(frame_filename) except: raise finally: video_encoding_api.finalize_encoding() return True # Use extension entry points to acquire and release interface. class Extension(omni.ext.IExt): def __init__(self): pass def on_startup(self, ext_id): global _video_encoding_api _video_encoding_api = acquire_video_encoding_interface() # print(f"[video encoding] _video_encoding interface: {_video_encoding_api}") def on_shutdown(self): global _video_encoding_api release_video_encoding_interface(_video_encoding_api) _video_encoding_api = None
2,016
Python
29.560606
116
0.669147
omniverse-code/kit/exts/omni.videoencoding/config/extension.toml
[package] version = "0.1.0" title = "Video Encoding Extension" category = "Internal" [dependencies] "omni.assets.plugins" = {} [[python.module]] name = "video_encoding" [[native.plugin]] path = "bin/*.plugin" recursive = false [settings] # Video encoding bitrate. exts."omni.videoencoding".bitrate = 16777216 # Video encoding framerate. Can be overridden by setting the framerate argument of start_encoding() exts."omni.videoencoding".framerate = 60.0 # I-Frame interval (every nth frame is an I-Frame) exts."omni.videoencoding".iframeinterval = 60 # Largest expected frame width exts."omni.videoencoding".maxEncodeWidth = 4096 # Largest expected frame height exts."omni.videoencoding".maxEncodeHeight = 4096 # Video encoding preset. Choices are: # "PRESET_DEFAULT" # "PRESET_HP" # "PRESET_HQ" # "PRESET_BD" # "PRESET_LOW_LATENCY_DEFAULT" # "PRESET_LOW_LATENCY_HQ" # "PRESET_LOW_LATENCY_HP" # "PRESET_LOSSLESS_DEFAULT" # "PRESET_LOSSLESS_HP" exts."omni.videoencoding".preset = "PRESET_DEFAULT" # Video encoding profile. Choices are: # "H264_PROFILE_BASELINE" # "H264_PROFILE_MAIN" # "H264_PROFILE_HIGH" # "H264_PROFILE_HIGH_444" # "H264_PROFILE_STEREO" # "H264_PROFILE_SVC_TEMPORAL_SCALABILITY" # "H264_PROFILE_PROGRESSIVE_HIGH" # "H264_PROFILE_CONSTRAINED_HIGH" # "HEVC_PROFILE_MAIN" # "HEVC_PROFILE_MAIN10" # "HEVC_PROFILE_FREXT" exts."omni.videoencoding".profile = "H264_PROFILE_HIGH" # Rate control mode. Choices are: # "RC_CONSTQP" # "RC_VBR" # "RC_CBR" # "RC_CBR_LOWDELAY_HQ" # "RC_CBR_HQ" # "RC_VBR_HQ" exts."omni.videoencoding".rcMode = "RC_VBR" # Rate control target quality. Range: 0-51, with 0-automatic exts."omni.videoencoding".rcTargetQuality = 0 [[test]] dependencies = [ ] args = [ "--no-window", ]
1,737
TOML
22.173333
99
0.717904
omniverse-code/kit/exts/omni.kit.test_suite.browser/docs/index.rst
omni.kit.test_suite.browser ################################### viewport tests .. toctree:: :maxdepth: 1 CHANGELOG
124
reStructuredText
11.499999
35
0.491935
omniverse-code/kit/exts/omni.kit.window.content_browser/scripts/demo_content_browser.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 weakref from omni.kit.window.content_browser import get_content_window from omni.kit.window.filepicker import FilePickerDialog class DemoContentBrowserClient: """ Example that demonstrates how to add custom actions to the content browser. """ def __init__(self): # Get the Content extension object. Same as: omni.kit.window.content_browser.get_extension() # Keep as weakref to guard against the extension being removed at any time. If it is removed, # then invoke appropriate handler; in this case the destroy method. self._content_browser_ref = weakref.ref(get_content_window(), lambda ref: self.destroy()) self._init_context_menu() def _init_context_menu(self): def file_extension_of(path: str, exts: [str]): _, ext = os.path.splitext(path) return ext in exts content_browser = self._content_browser_ref() if not content_browser: return # Add these items to the context menu and target to USD file types. content_browser.add_context_menu( "Collect Asset", "spinner.svg", lambda menu, path: self._collect_asset(path), lambda path: file_extension_of(path, [".usd"]), ) content_browser.add_context_menu( "Convert Asset", "menu_insert_sublayer.svg", lambda menu, path: self._convert_asset(path), lambda path: file_extension_of(path, [".usd"]), ) # Add these items to the list view menu and target to USD file types. content_browser.add_listview_menu( "Echo Selected", "spinner.svg", lambda menu, path: self._echo_selected(path), None ) # Add these items to the list view menu and target to USD file types. content_browser.add_import_menu( "My Custom Import", "spinner.svg", lambda menu, path: self._import_stuff(path), None ) def _collect_asset(self, path: str): print(f"Collecting asset {path}.") def _convert_asset(self, path: str): print(f"Converting asset {path}.") def _echo_selected(self, path: str): content_browser = self._content_browser_ref() if content_browser: print(f"Current directory is {path}.") selections = content_browser.get_current_selections(pane=1) print(f"TreeView selections = {selections}") selections = content_browser.get_current_selections(pane=2) print(f"ListView selections = {selections}") def _import_stuff(self, path: str): def on_apply(dialog: FilePickerDialog, filename: str, dirname: str): dialog.hide() print(f"Importing: {dirname}/{filename}") dialog = FilePickerDialog( "Download Files", width=800, height=400, splitter_offset=260, enable_filename_input=False, current_directory="Downloads", grid_view_scale=1, apply_button_label="Import", click_apply_handler=lambda filename, dirname: on_apply(dialog, filename, dirname), click_cancel_handler=lambda filename, dirname: dialog.hide(), ) dialog.show() def destroy(self): content_browser = self._content_browser_ref() if content_browser: content_browser.delete_context_menu("Collect Asset") content_browser.delete_context_menu("Convert Asset") content_browser.delete_listview_menu("Echo Selected") content_browser.delete_import_menu("My Custom Import") self._content_browser_ref = None if __name__ == "__main__": DemoContentBrowserClient()
4,188
Python
38.518868
101
0.63467
omniverse-code/kit/exts/omni.kit.window.content_browser/config/extension.toml
[package] title = "Content" version = "2.6.8" category = "core" feature = true description = "A window for browsing Omniverse content" 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.client" = {} "omni.kit.clipboard" = {} "omni.kit.window.filepicker" = {} "omni.kit.widget.filebrowser" = {} "omni.kit.window.popup_dialog" = {} "omni.kit.widget.versioning" = {} "omni.kit.window.file_exporter" = {} "omni.kit.window.file" = { optional=true } "omni.kit.pip_archive" = {} "omni.kit.window.drop_support" = {} "omni.usd" = {} "omni.kit.menu.utils" = {} "omni.kit.window.content_browser_registry" = {} "omni.kit.ui_test" = {} [[python.module]] name = "omni.kit.window.content_browser" [[python.scriptFolder]] path = "scripts" [python.pipapi] requirements = ["psutil"] [settings] exts."omni.kit.window.content_browser".timeout = 10.0 exts."omni.kit.window.content_browser".show_grid_view = true exts."omni.kit.window.content_browser".enable_checkpoints = true exts."omni.kit.window.content_browser".show_only_collections = ["bookmarks", "omniverse", "my-computer"] # Uncomment and modify the following setting to add default server connections # exts."omni.kit.window.content_browser".mounted_servers = {"my-server" = "omniverse://my-server", "another-server" = "omniverse://another-server"} [[test]] args = [ "--/renderer/enabled=pxr", "--/renderer/active=pxr", "--/renderer/multiGpu/enabled=false", "--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611 "--/renderer/multiGpu/maxGpuCount=1", "--/app/asyncRendering=false", "--/app/file/ignoreUnsavedOnExit=true", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/persistent/app/omniverse/filepicker/options_menu/show_details=false", "--/persistent/app/stage/dragDropImport='reference'", "--no-window", ] dependencies = [ "omni.kit.window.viewport", "omni.kit.window.stage", "omni.kit.ui_test", "omni.kit.test_suite.helpers", "omni.kit.renderer.core", ] [documentation] pages = [ "docs/Overview.md", "docs/CHANGELOG.md", ]
2,309
TOML
28.240506
147
0.680381
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/external_drag_drop_helper.py
import os import asyncio import carb import omni.client import omni.appwindow import omni.ui as ui from typing import List, Tuple from omni.kit.window.drop_support import ExternalDragDrop external_drag_drop = None def setup_external_drag_drop(window_name: str, browser_widget, window_frame: ui.Frame): global external_drag_drop destroy_external_drag_drop() external_drag_drop = ExternalDragDrop(window_name=window_name, drag_drop_fn=lambda e, p, a=browser_widget.api, f=window_frame: _on_ext_drag_drop(e, p, a, f)) def destroy_external_drag_drop(): global external_drag_drop if external_drag_drop: external_drag_drop.destroy() external_drag_drop = None def _cleanup_slashes(path: str, is_directory: bool = False) -> str: """ Makes path/slashes uniform Args: path: path is_directory is path a directory, so final slash can be added Returns: path """ path = os.path.normpath(path) path = path.replace("\\", "/") if is_directory: if path[-1] != "/": path += "/" return path def _on_ext_drag_drop(edd: ExternalDragDrop, payload: List[str], api, frame: ui.Frame): import omni.kit.notification_manager 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 search_frame = api.tool_bar._search_frame search_delegate = api.tool_bar._search_delegate if search_delegate and search_frame and search_frame.visible: pos_x, pos_y = get_current_mouse_coords() if (pos_x > search_frame.screen_position_x and pos_y > search_frame.screen_position_y and pos_x < search_frame.screen_position_x + search_frame.computed_width and pos_y < search_frame.screen_position_y + search_frame.computed_height): if hasattr(search_delegate, "handle_drag_drop"): if search_delegate.handle_drag_drop(payload): return target_dir = api.get_current_directory() if not target_dir: omni.kit.notification_manager.post_notification("No target directory", hide_after_timeout=False) return # get common source path common_path = "" if len(payload) > 1: common_path = os.path.commonpath(payload) if not common_path: common_path = os.path.dirname(payload[0]) common_path = _cleanup_slashes(common_path, True) # get payload payload = edd.expand_payload(payload) # copy files async def do_copy(): from .progress_popup import ProgressPopup from .file_ops import copy_item_async copy_cancelled = False def do_cancel_copy(): nonlocal copy_cancelled copy_cancelled = True # show progress... waiting_popup = ProgressPopup("Copying...", status_text="Copying...") waiting_popup.status_text = "Copying..." waiting_popup.progress = 0.0 waiting_popup.centre_in_window(frame) waiting_popup.set_cancel_fn(do_cancel_copy) waiting_popup.show() try: await omni.kit.app.get_app().next_update_async() current_file = 0 total_files = len(payload) for file_path in payload: if copy_cancelled: break file_path = _cleanup_slashes(file_path) target_path = target_dir.rstrip("/") + "/" + file_path.replace(common_path, "") # update progress waiting_popup.progress = float(current_file) / total_files waiting_popup.status_text = f"Copying {os.path.basename(target_path)}..." waiting_popup.centre_in_window(frame) # copy file # OM-90753: Route through same code path as normal copy item await copy_item_async(file_path, target_path) current_file += 1 except Exception as exc: carb.log_error(f"error {exc}") await omni.kit.app.get_app().next_update_async() api.refresh_current_directory() waiting_popup.hide() del waiting_popup asyncio.ensure_future(do_copy())
4,475
Python
32.654135
136
0.612291
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/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 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_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath(f"icons/{THEME}") def get_style(): if THEME == "NvidiaLight": style = { "Rectangle": {"background_color": 0xFF535354}, "Splitter": {"background_color": 0x0, "margin_width": 0}, "Splitter:hovered": {"background_color": 0xFFB0703B}, "Splitter:pressed": {"background_color": 0xFFB0703B}, "ToolBar": {"alignment": ui.Alignment.CENTER, "margin_height": 2}, "ToolBar.Button": {"background_color": 0xFF535354, "color": 0xFF9E9E9E}, "ToolBar.Button::filter": {"background_color": 0x0, "color": 0xFF9E9E9E}, "ToolBar.Button::import": { "background_color": 0xFFD6D6D6, "color": 0xFF535354, "stack_direction": ui.Direction.LEFT_TO_RIGHT, "border_radius": 3, }, "ToolBar.Button.Label": {"color": 0xFF535354, "alignment": ui.Alignment.LEFT_CENTER}, "ToolBar.Button.Image": {"background_color": 0x0, "color": 0xFFFFFFFF, "alignment": ui.Alignment.CENTER}, "ToolBar.Button:hovered": {"background_color": 0xFFB8B8B8}, "Recycle.Button.Label": {"color": 0xFF9E9E9E, "alignment": ui.Alignment.LEFT_CENTER}, "Recycle.Button.Image": {"image_url": "resources/glyphs/trash.svg", "background_color": 0x0, "color": 0xFFFFFFFF, "alignment": ui.Alignment.CENTER}, "Recycle.Button:hovered": {"background_color": 0xFF3A3A3A}, } else: style = { "Splitter": {"background_color": 0x0, "margin_width": 0}, "Splitter:hovered": {"background_color": 0xFFB0703B}, "Splitter:pressed": {"background_color": 0xFFB0703B}, "ToolBar": {"alignment": ui.Alignment.CENTER, "margin_height": 2}, "ToolBar.Button": {"background_color": 0x0, "color": 0xFF9E9E9E}, "ToolBar.Button::import": { "background_color": 0xFF23211F, "color": 0xFF9E9E9E, "stack_direction": ui.Direction.LEFT_TO_RIGHT, "border_radius": 3, }, "ToolBar.Button.Label": {"color": 0xFF9E9E9E, "alignment": ui.Alignment.LEFT_CENTER}, "ToolBar.Button.Image": {"background_color": 0x0, "color": 0xFFFFFFFF, "alignment": ui.Alignment.CENTER}, "ToolBar.Button:hovered": {"background_color": 0xFF3A3A3A}, "Recycle.Button.Label": {"color": 0xFF9E9E9E, "alignment": ui.Alignment.LEFT_CENTER}, "Recycle.Button.Image": {"image_url": "resources/glyphs/trash.svg", "background_color": 0x0, "color": 0xFFFFFFFF, "alignment": ui.Alignment.CENTER}, "Recycle.Button:hovered": {"background_color": 0xFF3A3A3A}, } return style
3,527
Python
49.399999
160
0.620357
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/extension.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os import asyncio import carb import omni.ext import omni.kit.ui import omni.ui as ui import omni.kit.window.content_browser_registry as registry from functools import partial from typing import Union, Callable, List from omni.kit.helper.file_utils import FILE_OPENED_EVENT from omni.kit.window.filepicker import SearchDelegate, UI_READY_EVENT from omni.kit.widget.filebrowser import FileBrowserModel, FileBrowserItem from omni.kit.menu.utils import MenuItemDescription from .window import ContentBrowserWindow from .api import ContentBrowserAPI 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 ContentBrowserExtension(omni.ext.IExt): """The Content Browser extension""" WINDOW_NAME = "Content" MENU_GROUP = "Window" def __init__(self): super().__init__() self._window = None def on_startup(self, ext_id): # Save away this instance as singleton for the editor window global g_singleton g_singleton = self ui.Workspace.set_show_window_fn(ContentBrowserExtension.WINDOW_NAME, partial(self.show_window, None)) self._menu = [MenuItemDescription( name=ContentBrowserExtension.WINDOW_NAME, ticked=True, # menu item is ticked ticked_fn=self._is_visible, # gets called when the menu needs to get the state of the ticked menu onclick_fn=self._toggle_window )] omni.kit.menu.utils.add_menu_items(self._menu, name=ContentBrowserExtension.MENU_GROUP) ui.Workspace.show_window(ContentBrowserExtension.WINDOW_NAME, True) # Listen for relevant event stream events event_stream = omni.kit.app.get_app().get_message_bus_event_stream() self._stage_event_subscription = event_stream.create_subscription_to_pop_by_type( FILE_OPENED_EVENT, self._on_stage_event) self._content_browser_inited_subscription = event_stream.create_subscription_to_pop_by_type( UI_READY_EVENT, self.decorate_from_registry) def _on_stage_event(self, stage_event): if not stage_event: return if "url" in stage_event.payload: stage_url = stage_event.payload["url"] default_folder = os.path.dirname(stage_url) self.navigate_to(default_folder) async def _destroy_window_async(self): # wait one frame, this is due to the one frame defer # in Window::_moveToMainOSWindow() await omni.kit.app.get_app().next_update_async() if self._window: self._window.destroy() self._window = None def _visibility_changed_fn(self, visible): if not visible: # Destroy the window, since we are creating new window # in show_window asyncio.ensure_future(self._destroy_window_async()) def show_window(self, menu, value): """Shows this window. Inputs are for backwards compatibility only and not used.""" if value: self._window = ContentBrowserWindow() self._window.set_visibility_changed_listener(self._visibility_changed_fn) elif self._window: self._window.set_visible(value) # this only tags test menu to update when menu is opening, so it # doesn't matter that is called before window has been destroyed omni.kit.menu.utils.refresh_menu_items(ContentBrowserExtension.MENU_GROUP) def _is_visible(self) -> bool: return False if self._window is None else self._window.get_visible() def _toggle_window(self): if self._is_visible(): self.show_window(None, False) else: self.show_window(None, True) def on_shutdown(self): # pragma: no cover omni.kit.menu.utils.remove_menu_items(self._menu, name=ContentBrowserExtension.MENU_GROUP) self._stage_event_subscription = None if self._window: self._window.destroy() self._window = None ui.Workspace.set_show_window_fn(ContentBrowserExtension.WINDOW_NAME, None) global g_singleton g_singleton = None @property def window(self) -> ui.Window: """ui.Window: Main dialog window for this extension.""" return self._window @property def api(self) -> ContentBrowserAPI: if self._window: return self._window.widget.api return None def add_connections(self, connections: dict): """ Adds specified server connections to the tree 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://". """ if self.api: self.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: RuntimeWarning: If path doesn't exist or is unreachable. """ if self.api: try: self.api.set_current_directory(path) except Exception: raise def get_current_directory(self) -> str: """ Returns the current directory fom the browser bar. Returns: str: The system path, which may be different from the displayed path. """ if self.api: return self.api.get_current_directory() return None 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: List[str]: List of system paths (which may be different from displayed paths, e.g. bookmarks) """ if self.api: return self.api.get_current_selections(pane) return [] def subscribe_selection_changed(self, fn: Callable): """ Subscribes to file selection changes. Args: fn (Callable): callback function when file selection changed. """ if self.api: registry.register_selection_handler(fn) self.api.subscribe_selection_changed(fn) def unsubscribe_selection_changed(self, fn: Callable): """ Unsubscribes this callback from selection changes. Args: fn (Callable): callback function when file selection changed. """ if self.api: registry.deregister_selection_handler(fn) self.api.unsubscribe_selection_changed(fn) def navigate_to(self, url: str): """ Navigates to the given url, expanding all parent directories along the path. Args: url (str): The path to navigate to. """ if self.api: self.api.navigate_to(url) async def navigate_to_async(self, url: str): """ Asynchronously navigates to the given url, expanding all parent directories along the path. Args: url (str): The url to navigate to. """ if self.api: await self.api.navigate_to_async(url) async def select_items_async(self, url: str, filenames: List[str] = []) -> List[FileBrowserItem]: """ Asynchronously selects display items by their names. Args: url (str): Url of the parent folder. filenames (str): Names of items to select. Returns: List[FileBrowserItem]: List of selected items. """ if self.api: return await self.api.select_items_async(url, filenames=filenames) return [] def add_context_menu(self, name: str, glyph: str, click_fn: Callable, show_fn: Callable, index: int = 0, separator_name="_add_on_end_separator_") -> str: """ Add menu item, with corresponding callbacks, to the context menu. Args: name (str): Name of the menu item (e.g. 'Open'), this name must be unique across the context menu. glyph (str): Associated glyph to display for this menu item. click_fn (Callable): This callback function is executed when the menu item is clicked. Function signature is void fn(name: str, path: str), where name is menu name and path is absolute path to clicked item. show_fn (Callable): Returns True to display this menu item. Function signature - bool fn(path: str). For example, test filename extension to decide whether to display a 'Play Sound' action. index (int): The 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 self.api: registry.register_context_menu(name, glyph, click_fn, show_fn, index) return self.api.add_context_menu(name, glyph, click_fn, show_fn, index, separator_name=separator_name) return None def delete_context_menu(self, name: str): """ Delete the menu item, with the given name, from the context menu. Args: name (str): Name of the menu item (e.g. 'Open'). """ try: registry.deregister_context_menu(name) self.api.delete_context_menu(name) except AttributeError: # it can happen when content_browser is unloaded early. This way we don't need to unsubscribe pass def add_listview_menu(self, name: str, glyph: str, click_fn: Callable, show_fn: Callable, index: int = -1) -> str: """ Add menu item, with corresponding callbacks, to the list view menu. Args: name (str): Name of the menu item (e.g. 'Open'), this name must be unique across the list view menu. glyph (str): Associated glyph to display for this menu item. click_fn (Callable): This callback function is executed when the menu item is clicked. Function signature: void fn(name: str, path: str), where name is menu name and path is absolute path to clicked item. show_fn (Callable): Returns True to display this menu item. Function signature: bool fn(path: str). For example, test filename extension to decide whether to display a 'Play Sound' action. index (int): The position that this menu item will be inserted to. Returns: str: Name of menu item if successful, None otherwise. """ if self.api: registry.register_listview_menu(name, glyph, click_fn, show_fn, index) return self.api.add_listview_menu(name, glyph, click_fn, show_fn, index) return None def delete_listview_menu(self, name: str): """ Delete the menu item, with the given name, from the list view menu. Args: name (str) - Name of the menu item (e.g. 'Open'). """ if self.api: registry.deregister_listview_menu(name) self.api.delete_listview_menu(name) def add_import_menu(self, name: str, glyph: str, click_fn: Callable, show_fn: Callable) -> str: """ Add menu item, with corresponding callbacks, to the Import combo box. Args: name (str): Name of the menu item, this name must be unique across the menu. glyph (str): Associated glyph to display for this menu item. click_fn (Callable): This callback function is executed when the menu item is clicked. Function signature: void fn(name: str, path: str), where name is menu name and path is absolute path to clicked item. show_fn (Callable): Returns True to display this menu item. Function signature: bool fn(path: str). For example, test filename extension to decide whether to display a 'Play Sound' action. Returns: str: Name of menu item if successful, None otherwise. """ if self.api: registry.register_import_menu(name, glyph, click_fn, show_fn) self.api.add_import_menu(name, glyph, click_fn, show_fn) def delete_import_menu(self, name: str): """ Delete the menu item, with the given name, from the Import combo box. Args: name (str): Name of the menu item. """ if self.api: registry.deregister_import_menu(name) self.api.delete_import_menu(name) def add_file_open_handler(self, name: str, open_fn: Callable, file_type: Union[int, Callable]) -> str: """ Registers callback/handler to open a file of matching type. Args: name (str): Unique name of handler. open_fn (Callable): This function is executed when a matching file is selected for open, i.e. double clicked, right mouse menu open, or path submitted to browser bar. Function signature: void open_fn(full_path: str), full_path is the file's system path. file_type (Union[int, func]): Can either be an enumerated int that is one of: [FILE_TYPE_USD, FILE_TYPE_IMAGE, FILE_TYPE_SOUND, FILE_TYPE_TEXT, FILE_TYPE_VOLUME] or a more general boolean function that returns True if this function should be activated on the given file. Function signature: bool file_type(full_path: str). Returns: str - Name if successful, None otherwise. """ if self.api: registry.register_file_open_handler(name, open_fn, file_type) return self.api.add_file_open_handler(name, open_fn, file_type) return None def delete_file_open_handler(self, name: str): """ Unregisters the named file open handler. Args: name (str): Name of the handler. """ if self._window: registry.deregister_file_open_handler(name) self.api.delete_file_open_handler(name) def get_file_open_handler(self, url: str) -> Callable: """ Returns the matching file open handler for the given file path. Args: url str: The url of the file to open. """ if self.api: return self.api.get_file_open_handler(url) def set_search_delegate(self, delegate: SearchDelegate): """ Sets a custom search delegate for the tool bar. Args: delegate (SearchDelegate): Object that creates the search widget. """ if self.api: registry.register_search_delegate(delegate) self.api.set_search_delegate(delegate) def unset_search_delegate(self, delegate: SearchDelegate): """ Clears the custom search delegate for the tool bar. Args: delegate (:obj:`SearchDelegate`): Object that creates the search widget. """ if self.api: registry.deregister_search_delegate(delegate) self.api.set_search_delegate(None) def decorate_from_registry(self, event: carb.events.IEvent): if not self.api: return try: # Ensure event is for the content window payload = event.payload.get_dict() if payload.get('title') != "Content": return except Exception as e: return # Add custom menu functions for id, args in registry.custom_menus().items(): context, name = id.split('::') if not context or not name: continue if context == "context": self.api.add_context_menu(args['name'], args['glyph'], args['click_fn'], args['show_fn'], args['index']) elif context == "listview": self.api.add_listview_menu(args['name'], args['glyph'], args['click_fn'], args['show_fn'], args['index']) elif context == "import": self.api.add_import_menu(args['name'], args['glyph'], args['click_fn'], args['show_fn']) elif context == "file_open": self.api.add_file_open_handler(args['name'], args['click_fn'], args['show_fn']) else: pass # Add custom selection handlers for handler in registry.selection_handlers(): self.api.subscribe_selection_changed(handler) # Set search delegate if any if registry.search_delegate(): self.api.set_search_delegate(registry.search_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 (FileBrowserModel): Model to display. """ if self.api: self.api.show_model(model) 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. """ if self._window: self._window.widget._view.toggle_grid_view(show_grid_view) def toggle_bookmark_from_path(self, name: str, path: str, is_bookmark: bool, is_folder: bool = True) -> bool: """ 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. Returns: bool: True if successful. """ if self.api: self.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.""" if self.api: self.api.refresh_current_directory() def get_checkpoint_widget(self) -> 'CheckpointWidget': """Returns the checkpoint widget""" if self._window: return self._window.widget._checkpoint_widget return None def get_timestamp_widget(self) -> 'TimestampWidget': """Returns the timestamp widget""" if self._window: return self._window.widget._timestamp_widget return None def get_instance(): global g_singleton return g_singleton
20,089
Python
37.413002
157
0.616258
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/__init__.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # """A window extension for browsing filesystem, including Nucleus, content""" __all__ = ['ContentBrowserExtension', 'get_content_window'] FILE_TYPE_USD = 1 FILE_TYPE_IMAGE = 2 FILE_TYPE_SOUND = 3 FILE_TYPE_TEXT = 4 FILE_TYPE_VOLUME = 5 SETTING_ROOT = "/exts/omni.kit.window.content_browser/" SETTING_PERSISTENT_ROOT = "/persistent" + SETTING_ROOT SETTING_PERSISTENT_CURRENT_DIRECTORY = SETTING_PERSISTENT_ROOT + "current_directory" from .extension import ContentBrowserExtension, get_instance from .window import ContentBrowserWindow from .widget import ContentBrowserWidget def get_content_window() -> ContentBrowserExtension: """Returns the singleton content_browser extension instance""" return get_instance()
1,158
Python
37.633332
84
0.784111
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/test_helper.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.ui_test as ui_test import omni.ui as ui import omni.kit.app from typing import List, Dict from omni.kit.widget.filebrowser import FileBrowserItem from .extension import get_instance class ContentBrowserTestHelper: """Test helper for the content browser window""" async def __aenter__(self): return self async def __aexit__(self, *args): pass async def toggle_grid_view_async(self, show_grid_view: bool): """ Toggles the list view between the grid and tree layouts. Args: show_grid_view (bool): If True, set the layout to grid, otherwise tree. """ content_browser = get_instance() if content_browser: content_browser.toggle_grid_view(show_grid_view) await ui_test.human_delay(10) async def navigate_to_async(self, url: str): """ Navigates to the given url, expanding all parent directories along the path. Args: url (str): The url to navigate to. """ content_browser = get_instance() if content_browser: await content_browser.navigate_to_async(url) async def get_item_async(self, url: str) -> FileBrowserItem: """ Retrieves an item by its url. Args: url (str): Url of the item. Returns: FileBrowserItem """ content_browser = get_instance() if content_browser: return await content_browser.api.model.find_item_async(url) return None async def select_items_async(self, dir_url: str, names: List[str]) -> List[FileBrowserItem]: """ Selects display items by their names. Args: dir_url (str): Url of the parent folder. names (List[str]): Names of items to select. Returns: List[FileBrowserItem]: List of selected items. """ content_browser = get_instance() selections = [] if content_browser: selections = await content_browser.select_items_async(dir_url, names) await ui_test.human_delay(10) return selections async def get_treeview_item_async(self, name: str) -> ui_test.query.WidgetRef: """ Retrieves the ui_test widget of the tree view item by name. Args: name (str): Label name of the widget. Returns: ui_test.query.WidgetRef """ if name: tree_view = ui_test.find("Content//Frame/**/TreeView[*].identifier=='content_browser_treeview'") widget = tree_view.find(f"**/Label[*].text=='{name}'") if widget: widget.widget.scroll_here(0.5, 0.5) await ui_test.human_delay(10) return widget return None async def get_gridview_item_async(self, name: str): # get content window widget ref in grid view if name: grid_view = ui_test.find("Content//Frame/**/VGrid[*].identifier=='content_browser_treeview_grid_view'") widget = grid_view.find(f"**/Label[*].text=='{name}'") if widget: widget.widget.scroll_here(0.5, 0.5) await ui_test.human_delay(10) return widget return None async def drag_and_drop_tree_view(self, url: str, names: List[str] = [], drag_target: ui_test.Vec2 = (0,0)): """ Drag and drop items from the tree view. Args: url (str): Url of the parent folder. names (List[str]): Names of items to drag. drag_target (ui_test.Vec2): Screen location to drop the item. """ await self.toggle_grid_view_async(False) selections = await self.select_items_async(url, names) if selections: item = selections[-1] widget = await self.get_treeview_item_async(item.name) if widget: await widget.drag_and_drop(drag_target) for i in range(10): await omni.kit.app.get_app().next_update_async() async def refresh_current_directory(self): content_browser = get_instance() if content_browser: content_browser.refresh_current_directory() async def get_config_menu_settings(self) -> Dict: """ Returns settings from the config menu as a dictionary. Returns: Dict """ content_browser = get_instance() if content_browser: widget = content_browser._window._widget config_menu = widget._tool_bar._config_menu return config_menu.get_values() return {} async def set_config_menu_settings(self, settings: Dict): """ Writes to settings of the config menu. """ content_browser = get_instance() if content_browser: widget = content_browser._window._widget config_menu = widget._tool_bar._config_menu for setting, value in settings.items(): config_menu.set_value(setting, value) # wait for window to update await ui_test.human_delay(50)
5,643
Python
31.813953
115
0.591707
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/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 carb.settings from omni.kit.window.filepicker.context_menu import UdimContextMenu, CollectionContextMenu, BookmarkContextMenu, ConnectionContextMenu from omni.kit.window.filepicker.context_menu import ContextMenu as FilePickerContextMenu from .file_ops import * from omni.kit.widget.filebrowser import save_items_to_clipboard, get_clipboard_items class ContextMenu(FilePickerContextMenu): """ 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__(**kwargs) try: import omni.usd omni_usd_supported = True except Exception: omni_usd_supported = False if omni_usd_supported: self.add_menu_item( "Open", "show.svg", lambda menu, url: open_file(url), lambda url: get_file_open_handler(url) != None, index=0, ) self.add_menu_item( "Open With Payloads Disabled", "show.svg", lambda menu, url: open_file(url, load_all=False), lambda url: get_file_open_handler(url) != None, index=1, ) self.add_menu_item( "Open With New Edit Layer", "external_link.svg", lambda menu, url: open_stage_with_new_edit_layer(url), lambda url: omni.usd.is_usd_writable_filetype(url), index=2, ) self.add_menu_item( "Copy", "copy.svg", lambda menu, _: save_items_to_clipboard(self._context["selected"]), # OM-94626: can't copy when select nothing lambda url: len(self._context["selected"]) >= 1, index=-2, ) self.add_menu_item( "Cut", "none.svg", lambda menu, _: cut_items(self._context["selected"], self._view), lambda url: self._context["item"].writeable and len(self._context["selected"]) >= 1, ) self.add_menu_item( "Paste", "copy.svg", lambda menu, url: paste_items(self._context["item"], get_clipboard_items(), view=self._view), lambda url: self._context["item"].is_folder and self._context["item"].writeable and\ len(self._context["selected"]) <= 1 and len(get_clipboard_items()) > 0, index=-2, ) self.add_menu_item( "Download", "cloud_download.svg", lambda menu, _: download_items(self._context["selected"]), # OM-94626: can't download when select nothing lambda url: len(self._context["selected"]) >= 1 and \ carb.settings.get_settings().get_as_bool("exts/omni.kit.window.content_browser/show_download_menuitem"), index=3, separator_name="_placeholder_" )
3,480
Python
39.476744
134
0.582759
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/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 omni.client import asyncio from typing import Union, Callable, List, Optional from carb import log_error, log_info from collections import OrderedDict, namedtuple from omni.kit.widget.filebrowser import FileBrowserItem from omni.kit.window.filepicker import FilePickerModel, asset_types from . import FILE_TYPE_USD, FILE_TYPE_IMAGE, FILE_TYPE_SOUND, FILE_TYPE_TEXT, FILE_TYPE_VOLUME FileOpenAction = namedtuple("FileOpenAction", "name open_fn matching_type") class ContentBrowserModel(FilePickerModel): """The model class for :obj:`ContentBrowserWidget`.""" def __init__(self, item_filter_fn=None, timeout=3.0): super().__init__(timeout=timeout) self._file_open_dict = OrderedDict() self._on_selection_changed_subs = set() self._item_filter_fn = item_filter_fn def add_file_open_handler(self, name: str, open_fn: Callable, file_type: Union[int, Callable]) -> str: """ Registers callback/handler to open a file of matching type. Args: name (str): Unique name of handler. open_fn (Callable): This function is executed when a matching file is selected for open, i.e. double clicked, right mouse menu open, or url submitted to browser bar. Function signature: void open_fn(url: str). file_type (Union[int, func]): Can either be an enumerated int that is one of: [FILE_TYPE_USD, FILE_TYPE_IMAGE, FILE_TYPE_SOUND, FILE_TYPE_TEXT, FILE_TYPE_VOLUME] or a more general boolean function that returns True if this function should be activated on the given file. Function signature: bool file_type(url: str). Returns: str: Name if successful, None otherwise. """ if name: self._file_open_dict[name] = FileOpenAction(name, open_fn, file_type) return name else: return None def delete_file_open_handler(self, name: str): """ Unregisters the named file open handler. Args: name (str): Name of the handler. """ if name and name in self._file_open_dict: self._file_open_dict.pop(name) def get_file_open_handler(self, url: str) -> Callable: """ Returns the matching file open handler for the given item. Args: url str: The url of the item to open. """ if not url: return None broken_url = omni.client.break_url(url) # Note: It's important that we use an ordered dict so that we can search by order # of insertion. for _, tup in self._file_open_dict.items(): _, open_fn, file_type = tup if isinstance(file_type, Callable): if file_type(broken_url.path): return open_fn else: asset_type = { FILE_TYPE_USD: asset_types.ASSET_TYPE_USD, FILE_TYPE_IMAGE: asset_types.ASSET_TYPE_IMAGE, FILE_TYPE_SOUND: asset_types.ASSET_TYPE_SOUND, FILE_TYPE_TEXT: asset_types.ASSET_TYPE_SCRIPT, FILE_TYPE_VOLUME: asset_types.ASSET_TYPE_VOLUME, }.get(file_type, None) if asset_type and asset_types.is_asset_type(broken_url.path, asset_type): return open_fn return None async def open_stage_async(self, url: str, open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL): """ Async function for opening a USD file. Args: url (str): Url to file. """ try: import omni.kit.window.file omni.kit.window.file.open_stage(url, open_loadset) except Exception as e: log_error(str(e)) else: log_info(f"Success! Opened '{url}'.\n") async def open_with_new_edit_layer(self, url: str, open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL): """ Async function for opening a USD file, then creating a new layer. Args: url (str): Url to file. """ try: import omni.kit.window.file omni.kit.window.file.open_with_new_edit_layer(url, open_loadset) except Exception as e: log_error(str(e)) else: log_info(f"Success! Opened '{url}' with new edit layer.\n") def download_items_with_callback(self, src_urls: List[str], dst_urls: List[str], callback: Optional[Callable] = None): """ Downloads specified items. Upon success, executes the given callback. Args: src_urls (List[str]): Paths of items to download. dst_urls (List[str]): Destination paths. callback (Callable): Callback to execute upon success. Function signature is void callback([str]). Raises: :obj:`Exception` """ try: self.copy_items_with_callback(src_urls, dst_urls, callback=callback) except Exception: raise def subscribe_selection_changed(self, fn: Callable): """ Subscribes to file selection changes. Args: fn (Callable): callback function when file selection changed. """ self._on_selection_changed_subs.add(fn) def unsubscribe_selection_changed(self, fn: Callable): """ Unsubscribes this callback from selection changes. Args: fn (Callable): callback function when file selection changed. """ if fn in self._on_selection_changed_subs: self._on_selection_changed_subs.remove(fn) def notify_selection_subs(self, pane: int, selected: [FileBrowserItem]): for fn in self._on_selection_changed_subs or []: async def async_cb(pane: int, selected: [FileBrowserItem]): # Making sure callback was not removed between async schedule/execute if fn in self._on_selection_changed_subs: fn(pane, selected) asyncio.ensure_future(async_cb(pane, selected)) def destroy(self): super().destroy() if self._file_open_dict: self._file_open_dict.clear() self._file_open_dict = None if self._on_selection_changed_subs: self._on_selection_changed_subs.clear() self._on_selection_changed_subs = None
6,889
Python
35.455026
122
0.608797
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/prompt.py
import omni import omni.ui as ui from .style import ICON_PATH class Prompt: def __init__( self, title, text, content_buttons, modal=False, ): self._title = title self._text = text self._content_buttons = content_buttons self._modal = modal self._buttons = [] self._build_ui() def __del__(self): for button in self._buttons: button.set_clicked_fn(None) self._buttons.clear() def show(self): self._window.visible = True def hide(self): self._window.visible = False def is_visible(self): return self._window.visible def _build_ui(self): import carb.settings self._window = ui.Window( self._title, visible=False, height=0, dockPreference=ui.DockPreference.DISABLED ) self._window.flags = ( ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE ) if self._modal: self._window.flags = self._window.flags | ui.WINDOW_FLAGS_MODAL theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" button_style = { "Button": {"stack_direction": ui.Direction.LEFT_TO_RIGHT}, "Button.Image": {"alignment": ui.Alignment.CENTER}, "Button.Label": {"alignment": ui.Alignment.LEFT_CENTER} } def button_cliked_fn(button_fn): if button_fn: button_fn() self.hide() with self._window.frame: with ui.VStack(height=0): ui.Spacer(width=0, height=10) if self._text: with ui.HStack(height=0): ui.Spacer() self._text_label = ui.Label(self._text, word_wrap=True, width=self._window.width - 80, height=0) ui.Spacer() ui.Spacer(width=0, height=10) with ui.VStack(height=0): ui.Spacer(height=0) for button in self._content_buttons: (button_text, button_icon, button_fn) = button with ui.HStack(): ui.Spacer(width=40) ui_button = ui.Button( " " + button_text, image_url=f"{ICON_PATH}/{button_icon}", image_width=24, height=40, clicked_fn=lambda a=button_fn: button_cliked_fn(a), style=button_style ) ui.Spacer(width=40) ui.Spacer(height=5) self._buttons.append(ui_button) ui.Spacer(height=5) with ui.HStack(): ui.Spacer() cancel_button = ui.Button("Cancel", width=80, height=0) cancel_button.set_clicked_fn(lambda: self.hide()) self._buttons.append(cancel_button) ui.Spacer(width=40) ui.Spacer(height=0) ui.Spacer(width=0, height=10)
3,461
Python
33.969697
120
0.469806
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/api.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import asyncio from typing import List, Callable, Union from omni.kit.window.filepicker import FilePickerAPI from omni.kit.widget.filebrowser import FileBrowserItem from .file_ops import add_file_open_handler, delete_file_open_handler, get_file_open_handler class ContentBrowserAPI(FilePickerAPI): """This class defines the API methods for :obj:`ContentBrowserWidget`.""" def __init__(self): super().__init__() self._on_selection_changed_subs = set() def add_import_menu(self, name: str, glyph: str, click_fn: Callable, show_fn: Callable) -> str: """ Adds menu item, with corresponding callbacks, to the Import combo box. Args: name (str): Name of the menu item, this name must be unique across the menu. glyph (str): Associated glyph to display for this menu item. click_fn (Callable): This callback function is executed when the menu item is clicked. Function signature: void fn(name: str, path: str), where name is menu name and path is absolute path to clicked item. show_fn (Callable): Returns True to display this menu item. Function signature: bool fn(path: str). For example, test filename extension to decide whether to display a 'Play Sound' action. Returns: str: Name of menu item if successful, None otherwise. """ if self.tool_bar: import_menu = self.tool_bar.import_menu if import_menu: return import_menu.add_menu_item(name, glyph, click_fn, show_fn) return None def delete_import_menu(self, name: str): """ Deletes the menu item, with the given name, from the Import combo box. Args: name (str): Name of the menu item. """ if self.tool_bar: import_menu = self.tool_bar.import_menu if import_menu: import_menu.delete_menu_item(name) def add_file_open_handler(self, name: str, open_fn: Callable, file_type: Union[int, Callable]) -> str: """ Registers callback/handler to open a file of matching type. Args: name (str): Unique name of handler. open_fn (Callable): This function is executed when a matching file is selected for open, i.e. double clicked, right mouse menu open, or path submitted to browser bar. Function signature: void open_fn(full_path: str), full_path is the file's system path. file_type (Union[int, func]): Can either be an enumerated int that is one of: [FILE_TYPE_USD, FILE_TYPE_IMAGE, FILE_TYPE_SOUND, FILE_TYPE_TEXT, FILE_TYPE_VOLUME] or a more general boolean function that returns True if this function should be activated on the given file. Function signature: bool file_type(full_path: str). Returns: str: Name if successful, None otherwise. """ return add_file_open_handler(name, open_fn, file_type) def delete_file_open_handler(self, name: str): """ Unregisters the named file open handler. Args: name (str): Name of the handler. """ delete_file_open_handler(name) def get_file_open_handler(self, url: str) -> Callable: """ Returns the matching file open handler for the given file path. Args: url str: The url of the file to open. """ return get_file_open_handler(url) def subscribe_selection_changed(self, fn: Callable): """ Subscribes to file selection changes. Args: fn (Callable): callback function when file selection changed. """ self._on_selection_changed_subs.add(fn) def unsubscribe_selection_changed(self, fn: Callable): """ Unsubscribe this callback from selection changes. Args: fn (Callable): callback function when file selection changed. """ if fn in self._on_selection_changed_subs: self._on_selection_changed_subs.remove(fn) def _notify_selection_subs(self, pane: int, selected: List[FileBrowserItem]): for fn in self._on_selection_changed_subs or []: async def async_cb(pane: int, selected: List[FileBrowserItem]): # Making sure callback was not removed between async schedule/execute if fn in self._on_selection_changed_subs: fn(pane, selected) asyncio.ensure_future(async_cb(pane, selected)) def destroy(self): super().destroy() if self._on_selection_changed_subs: self._on_selection_changed_subs.clear()
5,183
Python
37.977443
121
0.634382
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tool_bar.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from typing import Optional import omni.ui as ui from omni.kit.window.filepicker import ToolBar as FilePickerToolBar, BaseContextMenu from omni.kit.widget.filebrowser import FileBrowserItem from omni.kit.widget.options_menu import OptionsModel, OptionItem from omni.kit.widget.filter import FilterButton from .style import get_style, ICON_PATH class ImportMenu(BaseContextMenu): def __init__(self, **kwargs): super().__init__(title="Import menu", **kwargs) self._menu_dict = [] self._offset_x = kwargs.get("offset_x", -1) self._offset_y = kwargs.get("offset_y", 1) def show_relative(self, parent: ui.Widget, item: Optional[FileBrowserItem] = None): if item and len(self._menu_dict) > 0: self.show(item) if parent: self.menu.show_at( parent.screen_position_x + self._offset_x, parent.screen_position_y + parent.computed_height + self._offset_y, ) def destroy(self): super().destroy() self._menu_dict = [] class ToolBar(FilePickerToolBar): def __init__(self, **kwargs): self._import_button = None self._import_menu = None self._filter_button = None self._filter_values_changed_handler = kwargs.get("filter_values_changed_handler", None) self._import_menu = kwargs.pop("import_menu", ImportMenu()) super().__init__(**kwargs) def _build_ui(self): with ui.HStack(height=0, style=get_style(), style_type_name_override="ToolBar"): with ui.VStack(width=0): ui.Spacer() self._import_button = ui.Button( "Import ", image_url=f"{ICON_PATH}/plus.svg", image_width=12, height=24, spacing=4, style_type_name_override="ToolBar.Button", name="import", ) self._import_button.set_clicked_fn( lambda: self._import_menu and self._import_menu.show_relative(self._import_button, self._current_directory_provider()) ) ui.Spacer() super()._build_ui() def _build_widgets(self): ui.Spacer(width=2) self._build_filter_button() def _build_filter_button(self): filter_items = [ OptionItem("audio", text="Audio"), OptionItem("materials", text="Materials"), OptionItem("scripts", text="Scripts"), OptionItem("textures", text="Textures"), OptionItem("usd", text="USD"), OptionItem("volumes", text="Volumes"), ] with ui.VStack(width=0): ui.Spacer() self._filter_button = FilterButton(filter_items, menu_width=150) ui.Spacer() def on_filter_changed(model: OptionsModel, _): if self._filter_values_changed_handler: values = {} for item in self._filter_button.model.get_item_children(): values[item.name] = item.value self._filter_values_changed_handler(values) self.__sub_filter = self._filter_button.model.subscribe_item_changed_fn(on_filter_changed) @property def import_menu(self): return self._import_menu @property def filter_values(self): if self._filter_button: values = {} for item in self._filter_button.model.get_item_children(): values[item.name] = item.value return values return {} def destroy(self): super().destroy() self._import_button = None if self._filter_button: self.__sub_filter = None self._filter_button.destroy() self._filter_button = None self._filter_values_changed_handler = None
4,393
Python
35.616666
112
0.581152
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/widget.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os import omni.kit.app import carb import carb.settings import omni.client from typing import List, Dict from omni.kit.helper.file_utils import asset_types from omni.kit.window.filepicker import FilePickerWidget from omni.kit.widget.filebrowser import FileBrowserItem, LISTVIEW_PANE from omni.kit.widget.versioning import CheckpointModel, CheckpointItem from .api import ContentBrowserAPI from .context_menu import ContextMenu, UdimContextMenu, CollectionContextMenu, BookmarkContextMenu, ConnectionContextMenu from .tool_bar import ToolBar from .file_ops import get_file_open_handler, open_file, open_stage, drop_items from . import FILE_TYPE_USD, SETTING_ROOT, SETTING_PERSISTENT_CURRENT_DIRECTORY # 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 ContentBrowserWidget(FilePickerWidget): """The Content Browser widget""" def __init__(self, **kwargs): # Retrieve settings settings = carb.settings.get_settings() # OM-75244: Remember the last browsed directory upon Content Browser open kwargs["treeview_identifier"] = kwargs.get('treeview_identifier', None) kwargs["settings_root"] = SETTING_ROOT kwargs["enable_checkpoints"] = settings.get_as_bool("exts/omni.kit.window.content_browser/enable_checkpoints") kwargs["enable_timestamp"] = settings.get_as_bool("exts/omni.kit.window.content_browser/enable_timestamp") kwargs["show_only_collections"] = settings.get("exts/omni.kit.window.content_browser/show_only_collections") # Hard-coded configs kwargs["allow_multi_selection"] = True kwargs["enable_file_bar"] = False kwargs["drop_handler"] = lambda dst, src: drop_items(dst, [src]) kwargs["item_filter_fn"] = self._item_filter_fn # OM-77963: Make use of environment variable to disable check for soft-delete features in Content Browser kwargs["enable_soft_delete"] = True if os.getenv("OMNI_FEATURE_SOFT_DELETE", "0") == "1" else False # Additional fields self._visible_asset_types = [] # Inject cusdtomized API kwargs["api"] = ContentBrowserAPI() # Initialize and build the widget super().__init__("Content", **kwargs) def destroy(self): super().destroy() if self._visible_asset_types: self._visible_asset_types.clear() self._visible_asset_types = None def _build_tool_bar(self): """Overrides base builder, injects custom tool bar""" self._tool_bar = ToolBar( visited_history_size=20, current_directory_provider=lambda: self._view.get_root(LISTVIEW_PANE), branching_options_handler=self._api.find_subdirs_with_callback, apply_path_handler=self._open_and_navigate_to, toggle_bookmark_handler=self._api.toggle_bookmark_from_path, config_values_changed_handler=lambda _: self._apply_config_options(), filter_values_changed_handler=lambda _: self._apply_filter_options(), begin_edit_handler=self._on_begin_edit, prefix_separator="://", search_delegate=self._default_search_delegate, enable_soft_delete=self._enable_soft_delete, ) def _build_checkpoint_widget(self): """Overrides base builder, adds items to context menu""" super()._build_checkpoint_widget() # Add context menu to checkpoints def on_restore_checkpoint(cp: CheckpointItem, model: CheckpointModel): path = model.get_url() restore_path = path + "?" + cp.entry.relative_path model.restore_checkpoint(path, restore_path) # Create checkpoints context menu self._checkpoint_widget.add_context_menu( "Open", "show.svg", lambda menu, cp: (open_file(cp.get_full_url()) if cp else None), None, index=0, ) self._checkpoint_widget.add_context_menu( "Open With Payloads Disabled", "show.svg", lambda menu, cp: (open_file(cp.get_full_url(), load_all=False) if cp else None), None, index=1, ) self._checkpoint_widget.add_context_menu( "", "", None, None, index=98, ) self._checkpoint_widget.add_context_menu( "Restore Checkpoint", "restore.svg", lambda menu, cp: on_restore_checkpoint(cp, self._checkpoint_widget._model), lambda menu, cp: 1 if (cp and cp.get_relative_path()) else 0, index=99, ) # Open checkpoint file on double click self._checkpoint_widget.set_mouse_double_clicked_fn( lambda b, k, cp: (open_file(cp.get_full_url()) if cp else None)) def _build_context_menus(self): """Overrides base builder, injects custom context menus""" self._context_menus = dict() self._context_menus['item'] = ContextMenu(view=self._view, checkpoint=self._checkpoint_widget) self._context_menus['list_view'] = ContextMenu(view=self._view, checkpoint=self._checkpoint_widget) self._context_menus['collection'] = CollectionContextMenu(view=self._view) self._context_menus['connection'] = ConnectionContextMenu(view=self._view) self._context_menus['bookmark'] = BookmarkContextMenu(view=self._view) self._context_menus['udim'] = UdimContextMenu(view=self._view) # Register open handler for usd files if self._api: self._api.add_file_open_handler("usd", open_stage, FILE_TYPE_USD) def _get_mounted_servers(self) -> Dict: """Overrides base getter, returns mounted server dict from settings""" # OM-85963 Fixes flaky unittest: test_mount_default_servers. Purposely made this a function in order to inject test data. settings = carb.settings.get_settings() mounted_servers = {} try: mounted_servers = settings.get_settings_dictionary("exts/omni.kit.window.content_browser/mounted_servers").get_dict() except Exception: pass # OM-71835: Auto-connect server specified in the setting. We normally don't make the connection on startup # due to possible delays; however, we make this exception to facilitate the streaming workflows. return mounted_servers, True def _on_mouse_double_clicked(self, pane: int, button: int, key_mod: int, item: FileBrowserItem): if not item: return if button == 0 and not item.is_folder: if self._timestamp_widget: url = self._timestamp_widget.get_timestamp_url(item.path) else: url = item.path open_file(url) def _on_selection_changed(self, pane: int, selected: List[FileBrowserItem] = []): super()._on_selection_changed(pane, selected) if self._api: self._api._notify_selection_subs(pane, selected) # OM-75244: record the last browsed directory settings = carb.settings.get_settings() settings.set(SETTING_PERSISTENT_CURRENT_DIRECTORY, self._current_directory) def _open_and_navigate_to(self, url: str): if not url: return # Make sure url is normalized before trying to open as file. url = omni.client.normalize_url(url.strip()) if get_file_open_handler(url): # If there's a suitable file open handler then execute in a separate thread open_file(url) # Navigate to the file location self._api.navigate_to(url) def _apply_filter_options(self): map_filter_options = { "audio": asset_types.ASSET_TYPE_SOUND, "materials": asset_types.ASSET_TYPE_MATERIAL, "scripts": asset_types.ASSET_TYPE_SCRIPT, "textures": asset_types.ASSET_TYPE_IMAGE, "usd": asset_types.ASSET_TYPE_USD, "volumes": asset_types.ASSET_TYPE_VOLUME, } visible_types = [] settings = self._tool_bar.filter_values for label, visible in settings.items(): if visible: visible_types.append(map_filter_options[label]) self._visible_asset_types = visible_types self._refresh_ui() def _item_filter_fn(self, item: FileBrowserItem) -> bool: """ Default item filter callback. Returning True means the item is visible. Args: item (:obj:`FileBrowseritem`): Item in question. Returns: bool """ # Show items of unknown asset types? asset_type = asset_types.get_asset_type(item.path) if not self._visible_asset_types: # Visible asset types not specified if asset_type == asset_types.ASSET_TYPE_UNKNOWN: return self._show_unknown_asset_types else: return True return asset_type in self._visible_asset_types
9,631
Python
42.192825
130
0.643028
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/file_ops.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os import asyncio import omni.client import carb.settings import omni.kit.notification_manager import omni.kit.app from typing import Callable, List, Union from datetime import datetime from functools import lru_cache, partial from collections import OrderedDict, namedtuple from carb import log_warn, log_info from typing import Callable, List from omni.kit.helper.file_utils import asset_types from omni.kit.widget.filebrowser import FileBrowserItem, is_clipboard_cut, save_items_to_clipboard, clear_clipboard from omni.kit.widget.filebrowser.model import FileBrowserItemFields from omni.kit.window.file_exporter import get_file_exporter from omni.kit.window.filepicker.item_deletion_dialog import ConfirmItemDeletionDialog from omni.kit.window.filepicker.utils import get_user_folders_dict from omni.kit.window.filepicker.view import FilePickerView from omni.kit.window.filepicker.file_ops import * from .prompt import Prompt from . import FILE_TYPE_USD, FILE_TYPE_IMAGE, FILE_TYPE_SOUND, FILE_TYPE_TEXT, FILE_TYPE_VOLUME FileOpenAction = namedtuple("FileOpenAction", "name open_fn matching_type") _file_open_dict = OrderedDict() @lru_cache() def __get_input() -> carb.input.IInput: return carb.input.acquire_input_interface() def _is_ctrl_down() -> bool: input = __get_input() return ( input.get_keyboard_value(None, carb.input.KeyboardInput.LEFT_CONTROL) + input.get_keyboard_value(None, carb.input.KeyboardInput.RIGHT_CONTROL) > 0 ) def add_file_open_handler(name: str, open_fn: Callable, file_type: Union[int, Callable]) -> str: """ Registers callback/handler to open a file of matching type. Args: name (str): Unique name of handler. open_fn (Callable): This function is executed when a matching file is selected for open, i.e. double clicked, right mouse menu open, or url submitted to browser bar. Function signature: void open_fn(url: str). file_type (Union[int, func]): Can either be an enumerated int that is one of: [FILE_TYPE_USD, FILE_TYPE_IMAGE, FILE_TYPE_SOUND, FILE_TYPE_TEXT, FILE_TYPE_VOLUME] or a more general boolean function that returns True if this function should be activated on the given file. Function signature: bool file_type(url: str). Returns: str: Name if successful, None otherwise. """ global _file_open_dict if name: _file_open_dict[name] = FileOpenAction(name, open_fn, file_type) return name else: return None def delete_file_open_handler(name: str): """ Unregisters the named file open handler. Args: name (str): Name of the handler. """ global _file_open_dict if name and name in _file_open_dict: _file_open_dict.pop(name) def get_file_open_handler(url: str) -> Callable: """ Returns the matching file open handler for the given item. Args: url str: The url of the item to open. """ if not url: return None broken_url = omni.client.break_url(url) # Note: It's important that we use an ordered dict so that we can search by order # of insertion. global _file_open_dict for _, tup in _file_open_dict.items(): _, open_fn, file_type = tup if isinstance(file_type, Callable): if file_type(broken_url.path): return open_fn else: asset_type = { FILE_TYPE_USD: asset_types.ASSET_TYPE_USD, FILE_TYPE_IMAGE: asset_types.ASSET_TYPE_IMAGE, FILE_TYPE_SOUND: asset_types.ASSET_TYPE_SOUND, FILE_TYPE_TEXT: asset_types.ASSET_TYPE_SCRIPT, FILE_TYPE_VOLUME: asset_types.ASSET_TYPE_VOLUME, }.get(file_type, None) if asset_type and asset_types.is_asset_type(broken_url.path, asset_type): return open_fn return None def copy_items(dst_item: FileBrowserItem, src_paths: List[str]): try: from omni.kit.notification_manager import post_notification except Exception: post_notification = log_warn if dst_item and src_paths: try: def on_copied(results): for result in results: if isinstance(result, Exception): post_notification(str(result)) # prepare src_paths and dst_paths for copy items dst_paths = [] dst_root = dst_item.path for src_path in src_paths: rel_path = os.path.basename(src_path) dst_paths.append(f"{dst_root}/{rel_path}") copy_items_with_callback(src_paths, dst_paths, on_copied) except Exception as e: log_warn(f"Error encountered during copy: {str(e)}") def copy_items_with_callback(src_paths: List[str], dst_paths: List[str], callback: Callable = None, copy_callback: Callable[[str, str, omni.client.Result], None] = None): """ Copies items. Upon success, executes the given callback. Args: src_pathss ([str]): Paths of items to download. dst_paths ([str]): Destination paths. callback (func): Callback to execute upon success. Function signature is void callback(List[Union[Exception, str]). copy_callback (func): Callback per every copy. Function signature is void callback([str, str, omni.client.Result]). Raises: :obj:`Exception` """ if not (dst_paths and src_paths): return tasks = [] # should not get here, but just to be safe, if src_paths and dst_paths are not of the same length, don't copy if len(src_paths) != len(dst_paths): carb.log_warn( f"Cannot copy items from {src_paths} to {dst_paths}, source and destination paths should match in number.") return for src_path, dst_path in zip(src_paths, dst_paths): tasks.append(copy_item_async(src_path, dst_path, callback=copy_callback)) try: asyncio.ensure_future(exec_tasks_async(tasks, callback=callback)) except Exception: raise async def copy_item_async(src_path: str, dst_path: str, timeout: float = 300.0, callback: Callable[[str, str, omni.client.Result], None] = None) -> str: """ Async function. Copies item (recursively) from one path to another. Note: this function simply uses the copy function from omni.client and makes no attempt to optimize for copying from one Omniverse server to another. For that, use the Copy Service. Example usage: await copy_item_async("my_file.usd", "C:/tmp", "omniverse://ov-content/Users/me") Args: src_path (str): Source path to item being copied. dst_path (str): Destination path to copy the item. timeout (float): Number of seconds to try before erroring out. Default 10. callback (func): Callback to copy result. Returns: str: Destination path name Raises: :obj:`RuntimeWarning`: If error or timeout. """ if isinstance(timeout, (float, int)): timeout = max(300, timeout) try: # OM-67900: add source url in copied item checkpoint src_checkpoint = None result, entries = await omni.client.list_checkpoints_async(src_path) if result == omni.client.Result.OK and entries: src_checkpoint = entries[-1].relative_path checkpoint_msg = f"Copied from {src_path}" if src_checkpoint: checkpoint_msg = f"{checkpoint_msg}?{src_checkpoint}" result, _ = await omni.client.stat_async(dst_path) if result == omni.client.Result.OK: dst_name = os.path.basename(dst_path) async def on_overwrite(dialog): result = await asyncio.wait_for( omni.client.copy_async( src_path, dst_path, behavior=omni.client.CopyBehavior.OVERWRITE, message=checkpoint_msg), timeout=timeout) if callback: callback(src_path, dst_path, result) dialog.hide() def on_cancel(dialog): dialog.hide() dialog = ConfirmItemDeletionDialog( title="Confirm File Overwrite", message="You are about to overwrite", items=[FileBrowserItem(dst_path, FileBrowserItemFields(dst_name, datetime.now(), 0, 0), is_folder=False)], ok_handler=lambda dialog: asyncio.ensure_future(on_overwrite(dialog)), cancel_handler=lambda dialog: on_cancel(dialog), ) dialog.show() else: result = await asyncio.wait_for(omni.client.copy_async(src_path, dst_path, message=checkpoint_msg), timeout=timeout) if callback: callback(src_path, dst_path, result) except asyncio.TimeoutError: raise RuntimeWarning(f"Error unable to copy '{src_path}' to '{dst_path}': Timed out after {timeout} secs.") except Exception as e: raise RuntimeWarning(f"Error copying '{src_path}' to '{dst_path}': {e}") if result != omni.client.Result.OK: raise RuntimeWarning(f"Error copying '{src_path}' to '{dst_path}': {result}") return dst_path def drop_items(dst_item: FileBrowserItem, src_paths: List[str], callback: Callable = None): # src_paths is a list of str but when multiple items are selected, the str was a \n joined path string, so # we need to re-construct the src_paths paths = src_paths[0].split("\n") # remove any udim_sequence as that are not real files for path in paths.copy(): if asset_types.is_udim_sequence(path): paths.remove(path) if not paths: return # OM-52387: drag and drop is now move instead of copy; # Additionally, drag with ctrl down would be copy similar to windows file explorer if _is_ctrl_down(): copy_items(dst_item, paths) else: # warn user for move operation since it will overwrite items with the same name in the dst folder from omni.kit.window.popup_dialog import MessageDialog def on_okay(dialog: MessageDialog, dst_item: FileBrowserItem, paths: List[str], callback: Callable=None): move_items(dst_item, paths, callback=callback) dialog.hide() warning_msg = f"This will replace any file with the same name in {dst_item.path}." dialog = MessageDialog( title="MOVE", message="Do you really want to move these files?", warning_message=warning_msg, ok_handler=lambda dialog, dst_item=dst_item, paths=paths, callback=callback: on_okay( dialog, dst_item, paths, callback), ok_label="Confirm", ) dialog.show() def cut_items(src_items: List[FileBrowserItem], view: FilePickerView): if not src_items: return save_items_to_clipboard(src_items, is_cut=True) # to maintain the left treeview pane selection, only update listview for filebrowser view._filebrowser.refresh_ui(listview_only=True) def paste_items(dst_item: FileBrowserItem, src_items: List[FileBrowserItem], view: FilePickerView): src_paths = [item.path for item in src_items] # if currently the clipboard is for cut operation, then use move if is_clipboard_cut(): def _on_cut_pasted(dst_item, src_items, view): # sync up item changes for src and dst items to_update = set([dst_item]) for item in src_items: to_update.add(item.parent) for item in to_update: view._filebrowser._models.sync_up_item_changes(item) # clear clipboard and update item style clear_clipboard() view._filebrowser.refresh_ui(listview_only=True) drop_items(dst_item, ["\n".join(src_paths)], callback=lambda: _on_cut_pasted(dst_item, src_items, view)) # else use normal copy else: copy_items(dst_item, src_paths) def open_file(url: str, load_all=True): async def open_file_async(open_fn: Callable, url: str, load_all=True): result, entry = await omni.client.stat_async(url) if result == omni.client.Result.OK: # OM-57423: Make sure this is not a folder is_folder = (entry.flags & omni.client.ItemFlags.CAN_HAVE_CHILDREN) > 0 if is_folder: return if open_fn: import inspect sig = inspect.signature(open_fn) if sig and "load_all" in sig.parameters: if asyncio.iscoroutinefunction(open_fn): await open_fn(url, load_all) else: open_fn(url, load_all) return if asyncio.iscoroutinefunction(open_fn): await open_fn(url) else: open_fn(url) open_fn = get_file_open_handler(url) if open_fn: asyncio.ensure_future(open_file_async(open_fn, url, load_all)) # Register file open handler for USD's def open_stage(url, load_all=True): result, entry = omni.client.stat(url) if result == omni.client.Result.OK: read_only = entry.access & omni.client.AccessFlags.WRITE == 0 else: read_only = False if read_only: def _open_with_edit_layer(): open_stage_with_new_edit_layer(url, load_all) def _open_original_stage(): asyncio.ensure_future(open_stage_async(url, load_all)) _show_readonly_usd_prompt(_open_with_edit_layer, _open_original_stage) else: asyncio.ensure_future(open_stage_async(url, load_all)) async def open_stage_async(url: str, load_all=True): """ Async function for opening a USD file. Args: url (str): Url to file. """ try: import omni.kit.window.file if load_all: open_loadset = omni.usd.UsdContextInitialLoadSet.LOAD_ALL else: open_loadset = omni.usd.UsdContextInitialLoadSet.LOAD_NONE omni.kit.window.file.open_stage(url, open_loadset) except Exception as e: log_warn(str(e)) else: log_info(f"Success! Opened '{url}'.\n") def open_stage_with_new_edit_layer(url: str, load_all=True): """ Async function for opening a USD file, then creating a new layer. Args: url (str): Url to file. """ try: import omni.usd import omni.kit.window.file if load_all: open_loadset = omni.usd.UsdContextInitialLoadSet.LOAD_ALL else: open_loadset = omni.usd.UsdContextInitialLoadSet.LOAD_NONE omni.kit.window.file.open_with_new_edit_layer(url, open_loadset) except Exception as e: log_warn(str(e)) else: log_info(f"Success! Opened '{url}' with new edit layer.\n") def download_items(selections: List[FileBrowserItem]): if not selections: return def on_download(src_items: List[FileBrowserItem], filename: str, dirname: str): if ':/' in filename or filename.startswith('\\\\'): # Filename is a pasted fullpath. The first test finds paths that start with 'C:/' or 'omniverse://'; # the second finds MS network paths that start like '\\analogfs\VENDORS\...' dst_root = os.path.dirname(filename) else: dst_root = os.path.dirname(f"{(dirname or '').rstrip('/')}/{filename}") # OM-65721: When downloading a single item, should use the filename provided dst_name = None # for single item, rename by user input if len(src_items) == 1: dst_name = os.path.basename(filename) _, src_ext = os.path.splitext(src_items[0].path) # make sure ext is included if user didn't input it # TODO: here the assumption is that we don't want to download a file as another file format, so # appending if the filename input didn't end with the current ext if not dst_name.endswith(src_ext): dst_name = dst_name + src_ext if src_items and dst_root: # prepare src_paths and dst_paths for download items src_paths = [] dst_paths = [] for src_item in src_items: src_paths.append(src_item.path) dst_root = dst_root.rstrip("/") if dst_name: dst_path = f"{dst_root}/{dst_name}" # if not specified, or user typed in an empty name, use the source path basename instead else: dst_path = f"{dst_root}/{os.path.basename(src_item.path)}" dst_paths.append(dst_path) try: # Callback to handle exceptions def __notify(results: List[Union[Exception, str]]): for result in results: if isinstance(result, Exception): omni.kit.notification_manager.post_notification(str(result)) # Callback to handle copy result def __copy_notify(src: str, dst: str, result: omni.client.Result): if result == omni.client.Result.OK: omni.kit.notification_manager.post_notification(f"{src} downloaded") else: omni.kit.notification_manager.post_notification(f"Error copying '{src}' to '{dst}': {result}") copy_items_with_callback(src_paths, dst_paths, callback=__notify, copy_callback=__copy_notify) except Exception as e: log_warn(f"Error encountered during download: {str(e)}") file_exporter = get_file_exporter() if file_exporter: # OM-65721: Pre-populate the filename field for download; use original file/folder name for single selection # and "<multiple selected>" to indicate multiple items are selected (in this case downloaded item will use) # their source names # TODO: Is it worth creating a constant (either on this class or in this module) for this? selected_filename = "<multiple selected>" is_single_selection = len(selections) == 1 if is_single_selection: _, selected_filename = os.path.split(selections[0].path) # OM-73142: Resolve to the actual download directory download_dir = get_user_folders_dict().get("Downloads", "") file_exporter.show_window( title="Download Files", show_only_collections=["my-computer"], file_postfix_options=[None], file_extension_types=[("*", "All files")], export_button_label="Save", export_handler=lambda filename, dirname, **kwargs: on_download(selections, filename, dirname), filename_url=f"{download_dir}/{selected_filename}", enable_filename_input=is_single_selection, # OM-99158: Fix issue with apply button disabled when multiple items are selected for download show_only_folders=True, ) _open_readonly_usd_prompt = None def _show_readonly_usd_prompt(ok_fn, middle_fn): global _open_readonly_usd_prompt _open_readonly_usd_prompt = Prompt( "Opening a Read Only File", "", [ ("Open With New Edit Layer", "open_edit_layer.svg", ok_fn), ("Open Original File", "pencil.svg", middle_fn), ], modal=False ) _open_readonly_usd_prompt.show()
19,991
Python
37.819417
170
0.62148
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/window.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui import weakref from .widget import ContentBrowserWidget from .external_drag_drop_helper import setup_external_drag_drop, destroy_external_drag_drop class ContentBrowserWindow: """The Content Browser window""" def __init__(self): self._title = "Content" self._window = None self._widget = None self._visiblity_changed_listener = None self._build_ui(self._title, 1000, 600) def _build_ui(self, title, width, height): window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR self._window = ui.Window( title, width=width, height=height, flags=window_flags, dockPreference=ui.DockPreference.LEFT_BOTTOM ) self._window.set_visibility_changed_fn(self._visibility_changed_fn) # Dock it to the same space where Console is docked, make it the first tab and the active tab. self._window.deferred_dock_in("Console", ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE) self._window.dock_order = 2 with self._window.frame: # We are using `weakref.proxy` to avoid circular reference. The # circular reference is made when calling `set_width_changed_fn`. # `self._widget` is captured to the callable, and since the window # keeps the callable, it keeps self._widget. At the same time, # `self._widget` keeps the window because we pass it to the # constructor. To break circular referencing, we use # `weakref.proxy`. self._widget = ContentBrowserWidget( window=weakref.proxy(self._window), treeview_identifier="content_browser_treeview", ) self._window.set_width_changed_fn(self._widget._on_window_width_changed) # External Drag & Drop setup_external_drag_drop(title, self._widget, self._window.frame) def _visibility_changed_fn(self, visible): if self._visiblity_changed_listener: self._visiblity_changed_listener(visible) @property def widget(self) -> ContentBrowserWidget: return self._widget def set_visibility_changed_listener(self, listener): self._visiblity_changed_listener = listener def destroy(self): if self._widget: self._widget.destroy() self._widget = None if self._window: self._window.destroy() self._window = None self._visiblity_changed_listener = None destroy_external_drag_drop() def set_visible(self, value): self._window.visible = value def get_visible(self): if self._window: return self._window.visible return False
3,143
Python
37.814814
111
0.655743
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/test_drag_drop.py
import omni.kit.test import os import random import shutil import tempfile from unittest.mock import patch from pathlib import Path import omni.appwindow from omni import ui from carb.input import KeyboardInput from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from ..test_helper import ContentBrowserTestHelper from ..extension import get_instance class TestDragDrog(AsyncTestCase): """Testing ContentBrowser drag and drop behavior""" async def setUp(self): await ui_test.find("Content").focus() async def tearDown(self): pass def _prepare_test_dir(self, temp_dir): # make sure we start off clean if os.path.exists(temp_dir): os.rmdir(temp_dir) os.mkdir(temp_dir) src_paths = [] # create a file under test dir, and a folder containg a file; with open(os.path.join(temp_dir, "test.mdl"), "w") as _: pass src_paths.append("test.mdl") test_folder_path = os.path.join(temp_dir, "src_folder") os.mkdir(test_folder_path) with open(os.path.join(test_folder_path, "test_infolder.usd"), "w") as _: pass src_paths.extend(["src_folder", "src_folder/test_infolder.usd"]) # create the destination folder dst_folder_path = os.path.join(temp_dir, "dst_folder") os.mkdir(dst_folder_path) return src_paths, dst_folder_path def _get_child_paths(self, root_dir): paths = [] def _iter_listdir(root): for p in os.listdir(root): full_path = os.path.join(root, p) if os.path.isdir(full_path): yield full_path for child in _iter_listdir(full_path): yield child else: yield full_path for p in _iter_listdir(root_dir): paths.append(p.replace(root_dir, "").replace("\\", "/").lstrip("/")) return paths async def test_drop_to_move(self): """Testing drop items would move items inside the destination.""" temp_dir = os.path.join(tempfile.gettempdir(), f"tmp{random.randint(0, int('0xffff', 16))}") temp_dir = str(Path(temp_dir).resolve()) src_paths, dst_path = self._prepare_test_dir(temp_dir) async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.toggle_grid_view_async(False) await ui_test.human_delay(50) await content_browser_helper.refresh_current_directory() await ui_test.human_delay(100) await content_browser_helper.navigate_to_async(dst_path) await ui_test.human_delay(100) await content_browser_helper.navigate_to_async(temp_dir) await ui_test.human_delay(100) await content_browser_helper.refresh_current_directory() await ui_test.human_delay(100) target_item = await content_browser_helper.get_treeview_item_async("dst_folder") if not target_item: return await content_browser_helper.drag_and_drop_tree_view( temp_dir, src_paths[:-1], drag_target=target_item.position) await ui_test.human_delay(20) window = ui_test.find("MOVE") self.assertIsNotNone(window) await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) await ui_test.human_delay(20) # files should be moved inside dst folder self.assertTrue(len(os.listdir(temp_dir)) == 1) self.assertTrue(os.path.exists(dst_path)) results = self._get_child_paths(os.path.join(temp_dir, dst_path)) self.assertEqual(set(results), set(src_paths)) # Cleanup shutil.rmtree(temp_dir) async def test_drop_to_copy(self): """Testing drop with CTRL pressed copies items.""" temp_dir = os.path.join(tempfile.gettempdir(), f"tmp{random.randint(0, int('0xffff', 16))}") temp_dir = str(Path(temp_dir).resolve()) src_paths, dst_path = self._prepare_test_dir(temp_dir) async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.toggle_grid_view_async(False) await ui_test.human_delay(50) await content_browser_helper.refresh_current_directory() await ui_test.human_delay(100) await content_browser_helper.navigate_to_async(dst_path) await ui_test.human_delay(100) await content_browser_helper.navigate_to_async(temp_dir) await ui_test.human_delay(100) await content_browser_helper.refresh_current_directory() await ui_test.human_delay(100) target_item = await content_browser_helper.get_treeview_item_async("dst_folder") if not target_item: return async with ui_test.KeyDownScope(KeyboardInput.LEFT_CONTROL): await content_browser_helper.drag_and_drop_tree_view( temp_dir, src_paths[:-1], drag_target=target_item.position) await ui_test.human_delay(10) # files should be copied inside dst folder self.assertTrue(len(os.listdir(temp_dir)) == 3) # source paths should still exist for src_path in src_paths: self.assertTrue(os.path.exists(os.path.join(temp_dir, src_path))) # source paths should also be copied in dst folder self.assertTrue(os.path.exists(dst_path)) results = self._get_child_paths(os.path.join(temp_dir, dst_path)) self.assertEqual(set(results), set(src_paths)) # Cleanup shutil.rmtree(temp_dir) class TestExternalDragDrog(AsyncTestCase): """Testing ContentBrowser external drag and drop behavior""" async def setUp(self): await ui_test.find("Content").focus() # hide viewport to avoid drop fn triggered for viewport ui.Workspace.show_window("Viewport", False) window = ui_test.find("Content") await ui_test.emulate_mouse_move(window.center) content_browser = get_instance() content_browser.set_current_directory("/test/target") async def tearDown(self): pass async def test_external_drop_copy(self): """Testing external drop triggers copy.""" with patch.object(omni.client, "copy_async", return_value=omni.client.Result.OK) as mock_client_copy: # simulate drag/drop omni.appwindow.get_default_app_window().get_window_drop_event_stream().push(0, 0, {'paths': ["dummy"]}) await ui_test.human_delay(20) mock_client_copy.assert_called_once() async def test_external_drop_existing_item(self): """Testing external drop with existing item prompts user for deletion.""" with patch.object(omni.client, "stat_async", return_value=(omni.client.Result.OK, None)) as mock_client_stat: # simulate drag/drop omni.appwindow.get_default_app_window().get_window_drop_event_stream().push(0, 0, {'paths': ["dummy"]}) await ui_test.human_delay(20) mock_client_stat.assert_called_once() confirm_deletion = ui_test.find("Confirm File Overwrite") self.assertTrue(confirm_deletion.window.visible)
7,427
Python
39.590164
117
0.620035
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/test_registry.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from unittest.mock import patch, Mock from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from ..api import ContentBrowserAPI from .. import get_instance class TestRegistry(AsyncTestCase): """Testing Content Browser Registry""" async def setUp(self): pass async def tearDown(self): pass async def test_custom_menus(self): """Test persisting custom menus""" test_menus = { "context": { "name": "my context menu", "glyph": "my glyph", "click_fn": Mock(), "show_fn": Mock(), }, "listview": { "name": "my listview menu", "glyph": "my glyph", "click_fn": Mock(), "show_fn": Mock(), }, "import": { "name": "my import menu", "glyph": None, "click_fn": Mock(), "show_fn": Mock(), }, "file_open": { "context": "file_open", "name": "my file_open handler", "glyph": None, "click_fn": Mock(), "show_fn": Mock(), } } # Register menus under_test = get_instance() for context, test_menu in test_menus.items(): if context == "context": under_test.add_context_menu(test_menu["name"], test_menu["glyph"], test_menu["click_fn"], test_menu["show_fn"]) elif context == "listview": under_test.add_listview_menu(test_menu["name"], test_menu["glyph"], test_menu["click_fn"], test_menu["show_fn"]) elif context == "import": under_test.add_import_menu(test_menu["name"], test_menu["glyph"], test_menu["click_fn"], test_menu["show_fn"]) elif context == "file_open": under_test.add_file_open_handler(test_menu["name"], test_menu["click_fn"], test_menu["show_fn"]) else: pass with patch.object(ContentBrowserAPI, "add_context_menu") as mock_add_context_menu,\ patch.object(ContentBrowserAPI, "add_listview_menu") as mock_add_listview_menu,\ patch.object(ContentBrowserAPI, "add_import_menu") as mock_add_import_menu,\ patch.object(ContentBrowserAPI, "add_file_open_handler") as mock_add_file_open_handler: # Hide then show window again under_test.show_window(None, False) await ui_test.human_delay(4) under_test.show_window(None, True) await ui_test.human_delay(4) # Confirm all mocks got called with appropriate inputs for context, test_menu in test_menus.items(): if context == "context": mock_add_context_menu.assert_called_with(test_menu["name"], test_menu["glyph"], test_menu["click_fn"], test_menu["show_fn"], 0) elif context == "listview": mock_add_listview_menu.assert_called_with(test_menu["name"], test_menu["glyph"], test_menu["click_fn"], test_menu["show_fn"], -1) elif context == "import": mock_add_import_menu.assert_called_with(test_menu["name"], test_menu["glyph"], test_menu["click_fn"], test_menu["show_fn"]) elif context == "file_open": mock_add_file_open_handler.assert_called_with(test_menu["name"], test_menu["click_fn"], test_menu["show_fn"]) else: pass async def test_selection_handlers(self): """Test persisting selection handlers""" test_handler_1 = Mock() test_handler_2 = Mock() test_handlers = [test_handler_1, test_handler_2, test_handler_1] under_test = get_instance() for test_handler in test_handlers: under_test.subscribe_selection_changed(test_handler) with patch.object(ContentBrowserAPI, "subscribe_selection_changed") as mock_subscribe_selection_changed: # Hide then show window again under_test.show_window(None, False) await ui_test.human_delay(4) under_test.show_window(None, True) await ui_test.human_delay(4) self.assertEqual(mock_subscribe_selection_changed.call_count, 2) async def test_search_delegate(self): """Test persisting search delegate""" test_search_delegate = Mock() under_test = get_instance() under_test.set_search_delegate(test_search_delegate) # Confirm search delegate restored from registry with patch.object(ContentBrowserAPI, "set_search_delegate") as mock_set_search_delegate: # Hide then show window again under_test.show_window(None, False) await ui_test.human_delay(4) under_test.show_window(None, True) await ui_test.human_delay(4) mock_set_search_delegate.assert_called_with(test_search_delegate)
5,454
Python
42.29365
145
0.585075
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/test_widget.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import carb import omni.kit.test import omni.client from omni.kit import ui_test from unittest.mock import patch from ..widget import ContentBrowserWidget from ..api import ContentBrowserAPI from .. import get_content_window, SETTING_PERSISTENT_CURRENT_DIRECTORY class TestContentBrowserWidget(omni.kit.test.AsyncTestCase): async def setUp(self): await ui_test.find("Content").focus() async def tearDown(self): # Clear all bookmarks saved by omni.client, as a result of mounting test servers pass async def wait_for_update(self, wait_frames=20): for _ in range(wait_frames): await omni.kit.app.get_app().next_update_async() async def test_mount_default_servers(self): """Testing that the widget mounts the server specified from the settings""" content_browser = get_content_window() under_test = content_browser.window.widget test_servers = {"my-server": "omniverse://my-server", "her-server": "omniverse://her-server"} # Re-run init_view to confirm that the the widget adds the servers specified in # the settings. OM-85963: Mock out all the actual calls to connect the servers because # they trigger a host of other actions, incl. callbacks on bookmarks changed, that make # this test unreliable. with patch.object(ContentBrowserWidget, "_get_mounted_servers", return_value=(test_servers, True)),\ patch.object(ContentBrowserAPI, "add_connections") as mock_add_connections,\ patch.object(ContentBrowserAPI, "connect_server") as mock_connect_server,\ patch.object(ContentBrowserAPI, "subscribe_client_bookmarks_changed"): # Initialize the view and expect to mount servers under_test._init_view(None, None) # Check that widget attempted to add list of servers specified in settings mock_add_connections.assert_called_once_with(test_servers) # Check that widget attempted to connect to first server in list mock_connect_server.assert_called_once_with(test_servers['my-server'])
2,552
Python
46.277777
108
0.716301
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/__init__.py
## Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from .test_extension import * from .test_navigate import * from .test_test_helper import * from .test_registry import * from .test_widget import * from .test_download import * from .test_drag_drop import * from .test_rename import * from .test_cut_paste import * from .test_prompt import *
731
Python
37.526314
77
0.77565
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/test_prompt.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from omni.kit import ui_test from ..prompt import Prompt class TestPrompt(omni.kit.test.AsyncTestCase): async def setUp(self): pass async def tearDown(self): pass async def test_prompt(self): """Testing Prompt window""" prompt = Prompt( "TestPrompt", "TestLabel", [ ("test_button", "pencil.svg", None), ], modal=False ) prompt.hide() self.assertFalse(prompt.is_visible()) prompt.show() self.assertTrue(prompt.is_visible()) button = ui_test.find("TestPrompt//Frame/**/Button[*].text==' test_button'") await button.click() #self.assertFalse(prompt.is_visible()) del prompt
1,228
Python
32.216215
85
0.640065
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/test_extension.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import asyncio import omni.kit.app from unittest.mock import Mock, patch, ANY from .. import get_content_window from omni.kit import ui_test from omni.kit.test_suite.helpers import open_stage, get_test_data_path from omni.kit.helper.file_utils import FILE_OPENED_EVENT from omni.kit.widget.filebrowser import is_clipboard_cut, get_clipboard_items, clear_clipboard class MockItem: def __init__(self, path: str): self.name = path self.path = path self.writeable = True self.is_folder = True self.is_deleted = False class TestContentBrowser(omni.kit.test.AsyncTestCase): """ Testing omni.kit.window.content_browser extension. NOTE that since the dialog is a singleton, we use an async lock to ensure that only one test runs at a time. In practice, this is not a issue since there's only one instance in the app. """ __lock = asyncio.Lock() async def setUp(self): pass async def wait_for_update(self, wait_frames=20): for _ in range(wait_frames): await omni.kit.app.get_app().next_update_async() async def tearDown(self): pass async def test_set_search_delegate(self): """Testing that hiding the window destroys it""" mock_search_delegate = Mock() async with self.__lock: under_test = get_content_window() await self.wait_for_update() under_test.set_search_delegate(mock_search_delegate) under_test.unset_search_delegate(mock_search_delegate) mock_search_delegate.build_ui.assert_called_once() async def test_open_event(self): """Testing that on open event should auto navigate""" under_test = get_content_window() event_stream = omni.kit.app.get_app().get_message_bus_event_stream() event_stream.push(FILE_OPENED_EVENT, payload={"url": get_test_data_path(__name__, "bound_shapes.usda")}) with patch.object(under_test, "navigate_to") as mock: await ui_test.human_delay(50) mock.assert_called_once() event_stream.push(FILE_OPENED_EVENT, payload={"url": get_test_data_path(__name__, "bound_shapes.usda")}) async def test_interface(self): """Testing all simple interface""" under_test = get_content_window() under_test.set_current_directory("omniverse:/") self.assertEqual(under_test.get_current_directory(), "omniverse:/") self.assertEqual(under_test.get_current_selections(), []) under_test.show_model(None) def dummy(*args, **kwargs): pass under_test.subscribe_selection_changed(dummy) under_test.unsubscribe_selection_changed(dummy) under_test.delete_context_menu("test") under_test.toggle_bookmark_from_path("", "omniverse:/", False) #under_test.add_checkpoint_menu("test", "", None, None) #under_test.delete_checkpoint_menu("test") under_test.add_listview_menu("test", "", None, None) under_test.delete_listview_menu("test") under_test.add_import_menu("test", "", None, None) under_test.delete_import_menu("test") self.assertEqual(under_test.get_file_open_handler("test"), None) under_test.add_file_open_handler("test", dummy, None) under_test.delete_file_open_handler("test") self.assertIsNotNone(under_test.api) self.assertIsNotNone(under_test.get_checkpoint_widget()) self.assertIsNone(under_test.get_timestamp_widget()) async def test_api(self): """Testing rest api interface""" api = get_content_window().api self.assertIsNotNone(api) #api._post_warning("test") def dummy(*args, **kwargs): pass api.subscribe_selection_changed(dummy) api._notify_selection_subs(2, []) return mock_item_list = [MockItem(str(i)) for i in range(10)] with patch.object(api.view, "get_selections", return_value=mock_item_list) as mock: api.copy_selected_items() mock.assert_called_once() self.assertFalse(is_clipboard_cut()) mock.reset_mock() api.cut_selected_items() self.assertEqual(get_clipboard_items(), mock_item_list) mock.assert_called_once() with patch.object(api.view, "get_selections", return_value=mock_item_list) as mock: api.delete_selected_items() mock.assert_called_once() mock_item_list1 = [MockItem("test")] with patch("omni.kit.widget.filebrowser.get_clipboard_items", return_value=mock_item_list) as mock, \ patch.object(api.view, "get_selections", return_value=mock_item_list1) as mock2: api.paste_items() api.clear_clipboard() mock2.assert_called_once()
5,291
Python
41.677419
119
0.650539
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/test_rename.py
import omni.kit.test import os import random import shutil import tempfile from pathlib import Path from unittest.mock import patch from omni import ui from carb.input import KeyboardInput from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from ..test_helper import ContentBrowserTestHelper # FIXME: Currently force this to run before test_navigate, since it was not easy to close out the # "add neclues connection" window in test class TestFileRename(AsyncTestCase): """Testing ContentBrowserWidget drag and drop behavior""" async def setUp(self): await ui_test.find("Content").focus() async def tearDown(self): pass def _prepare_test_dir(self, temp_dir, temp_file): # make sure we start off clean if os.path.exists(temp_dir): os.rmdir(temp_dir) os.makedirs(temp_dir) with open(os.path.join(temp_dir, temp_file), "w") as _: pass async def test_rename_file(self): """Testing renaming a file.""" temp_dir = os.path.join(tempfile.gettempdir(), f"tmp{random.randint(0, int('0xffff', 16))}") temp_dir = str(Path(temp_dir).resolve()) filename = "temp.mdl" self._prepare_test_dir(temp_dir, filename) async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.navigate_to_async("omniverse:/") await ui_test.human_delay(50) await content_browser_helper.refresh_current_directory() await ui_test.human_delay(50) await content_browser_helper.navigate_to_async(temp_dir) await ui_test.human_delay(50) await content_browser_helper.toggle_grid_view_async(True) await ui_test.human_delay(50) t = await content_browser_helper.get_item_async(temp_dir + "/" + filename) await content_browser_helper.refresh_current_directory() await ui_test.human_delay(50) item = await content_browser_helper.get_gridview_item_async(filename) if item is None: return await item.right_click() await ui_test.human_delay() return await ui_test.select_context_menu("Rename") popup = ui.Workspace.get_window(f"Rename {filename}") self.assertIsNotNone(popup) self.assertTrue(popup.visible) def dummy(*args, **kwargs): return "dummy.txt" with patch( "omni.kit.window.popup_dialog.InputDialog.get_value", side_effect=dummy ): await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) await ui_test.human_delay(10) # file should have been renamed to dummy.txt now self.assertFalse(os.path.exists(os.path.join(temp_dir, filename))) self.assertTrue(os.path.exists(os.path.join(temp_dir, "dummy.txt"))) await content_browser_helper.navigate_to_async("omniverse:/") await ui_test.human_delay(50) # Cleanup shutil.rmtree(temp_dir) async def test_rename_folder(self): """Testing renaming a folder.""" temp_dir = os.path.join(tempfile.gettempdir(), f"tmp{random.randint(0, int('0xffff', 16))}") temp_dir = str(Path(temp_dir).resolve()) src_folder = os.path.join(temp_dir, "test_folder") filename = "temp.mdl" self._prepare_test_dir(src_folder, filename) async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.navigate_to_async("omniverse:/") await ui_test.human_delay(50) await content_browser_helper.refresh_current_directory() # TODO: need to refresh the browser item here, but why await content_browser_helper.navigate_to_async(src_folder) await content_browser_helper.navigate_to_async(temp_dir) t = await content_browser_helper.get_item_async(src_folder) await content_browser_helper.toggle_grid_view_async(True) await content_browser_helper.refresh_current_directory() await ui_test.human_delay(50) item = await content_browser_helper.get_gridview_item_async("test_folder") if item is None: return await item.right_click() await ui_test.human_delay() return await ui_test.select_context_menu("Rename") popup = ui.Workspace.get_window("Rename test_folder") self.assertIsNotNone(popup) self.assertTrue(popup.visible) def dummy(*args, **kwargs): return "renamed_folder" with patch( "omni.kit.window.popup_dialog.InputDialog.get_value", side_effect=dummy ): await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) await ui_test.human_delay(20) # file should have been renamed to dummy.txt now self.assertFalse(os.path.exists(src_folder)) renamed_folder = os.path.join(temp_dir, "renamed_folder") self.assertTrue(os.path.exists(renamed_folder)) self.assertTrue(os.path.exists(os.path.join(renamed_folder, filename))) await content_browser_helper.navigate_to_async("omniverse:/") await ui_test.human_delay(50) # Cleanup shutil.rmtree(temp_dir)
5,535
Python
38.827338
100
0.618428
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/test_download.py
import omni.kit.test import os from pathlib import Path from tempfile import TemporaryDirectory, NamedTemporaryFile from unittest.mock import patch, Mock import omni.ui as ui import carb.settings from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from omni.kit.window.file_exporter import get_file_exporter from ..widget import ContentBrowserWidget from ..test_helper import ContentBrowserTestHelper from ..file_ops import download_items from .. import get_content_window from ..context_menu import ContextMenu class TestDownload(AsyncTestCase): """Testing ContentBrowserWidget._download_items""" async def setUp(self): await ui_test.find("Content").focus() async def tearDown(self): # hide download window on test teardown window = ui.Workspace.get_window("Download Files") if window: window.visible = False async def test_no_selection(self): """Testing when nothing is selected, don't open up file exporter.""" # currently marking this as the first test to run since ui.Workspace.get_window result would not # be None if other tests had shown the window once download_items([]) await ui_test.human_delay() window = ui.Workspace.get_window("Download Files") try: self.assertIsNone(window) except AssertionError: # in the case where the window is created, then the window should be invisible self.assertFalse(window.visible) async def test_single_selection(self): """Testing when downloading with a single item selected.""" with TemporaryDirectory() as tmpdir_fd: # need to resolve to deal with the abbreviated user filename such as "LINE8~1" tmpdir = Path(tmpdir_fd).resolve() temp_fd = NamedTemporaryFile(dir=tmpdir, suffix=".mdl", delete=False) temp_fd.close() _, filename = os.path.split(temp_fd.name) async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.refresh_current_directory() await content_browser_helper.navigate_to_async(str(tmpdir)) items = await content_browser_helper.select_items_async(str(tmpdir), [filename]) await ui_test.human_delay() with patch("omni.kit.notification_manager.post_notification") as mock_post_notification: self.assertEqual(len(items), 1) download_items(items) await ui_test.human_delay(10) file_exporter = get_file_exporter() self.assertIsNotNone(file_exporter) # the filename for file exporter should be pre-filled (same as the source filename) self.assertEqual(file_exporter._dialog.get_filename(), filename) # the filename field should enable input self.assertTrue(file_exporter._dialog._widget._enable_filename_input) file_exporter._dialog.set_current_directory(str(tmpdir)) await ui_test.human_delay() window = ui.Workspace.get_window("Download Files") self.assertTrue(window.visible) file_exporter._dialog.set_filename("dummy") file_exporter.click_apply() await ui_test.human_delay(10) # should have created a downloaded file in the same directory, with the same extension self.assertTrue(tmpdir.joinpath("dummy.mdl").exists) mock_post_notification.assert_called_once() async def test_multi_selection(self): """Testing when downloading with multiple items selected.""" with TemporaryDirectory() as tmpdir_fd: # need to resolve to deal with the abbreviated user filename such as "LINE8~1" tmpdir = Path(tmpdir_fd).resolve() temp_files = [] for _ in range(2): temp_fd = NamedTemporaryFile(dir=tmpdir, suffix=".mdl", delete=False) temp_fd.close() _, filename = os.path.split(temp_fd.name) temp_files.append(filename) async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.refresh_current_directory() await content_browser_helper.navigate_to_async(str(tmpdir)) items = await content_browser_helper.select_items_async(str(tmpdir), temp_files) await ui_test.human_delay() with patch("omni.kit.notification_manager.post_notification") as mock_post_notification: self.assertEqual(len(items), len(temp_files)) download_items(items) await ui_test.human_delay(10) file_exporter = get_file_exporter() self.assertIsNotNone(file_exporter) window = ui.Workspace.get_window("Download Files") self.assertTrue(window.visible) # the filename field should disable input self.assertFalse(file_exporter._dialog._widget._enable_filename_input) with TemporaryDirectory() as another_tmpdir_fd: dst_tmpdir = Path(another_tmpdir_fd) file_exporter._dialog.set_current_directory(str(dst_tmpdir)) await ui_test.human_delay() # OM-99158: Check that the apply button is not disabled self.assertTrue(file_exporter._dialog._widget.file_bar._apply_button.enabled) file_exporter.click_apply() await ui_test.human_delay(10) # should have created downloaded files in the dst directory downloaded_files = [file for file in os.listdir(dst_tmpdir)] self.assertEqual(set(temp_files), set(downloaded_files)) self.assertEqual(mock_post_notification.call_count, len(items)) async def test_multi_results(self): """Testing when downloading with multiple results.""" with TemporaryDirectory() as tmpdir_fd: # need to resolve to deal with the abbreviated user filename such as "LINE8~1" tmpdir = Path(tmpdir_fd).resolve() temp_files = [] for _ in range(3): temp_fd = NamedTemporaryFile(dir=tmpdir, suffix=".mdl", delete=False) temp_fd.close() _, filename = os.path.split(temp_fd.name) temp_files.append(filename) async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.refresh_current_directory() await content_browser_helper.navigate_to_async(str(tmpdir)) items = await content_browser_helper.select_items_async(str(tmpdir), temp_files) await ui_test.human_delay() with patch.object(omni.kit.window.content_browser.file_ops, "copy_items_with_callback", side_effect=self._mock_copy_items_with_callback),\ patch("omni.kit.notification_manager.post_notification") as mock_post_notification: self.assertEqual(len(items), len(temp_files)) download_items(items) await ui_test.human_delay(10) file_exporter = get_file_exporter() self.assertIsNotNone(file_exporter) window = ui.Workspace.get_window("Download Files") self.assertTrue(window.visible) # the filename field should disable input self.assertFalse(file_exporter._dialog._widget._enable_filename_input) with TemporaryDirectory() as another_tmpdir_fd: dst_tmpdir = Path(another_tmpdir_fd) file_exporter._dialog.set_current_directory(str(dst_tmpdir)) await ui_test.human_delay() # OM-99158: Check that the apply button is not disabled self.assertTrue(file_exporter._dialog._widget.file_bar._apply_button.enabled) file_exporter.click_apply() await ui_test.human_delay(10) self.assertEqual(mock_post_notification.call_count, len(items)) def _mock_copy_items_with_callback(self, src_paths, dst_paths, callback=None, copy_callback=None): # Fist one succeeded on copy # Second one failed on copy # Thrid has exception during copy copy_callback(src_paths[0], dst_paths[0], omni.client.Result.OK) copy_callback(src_paths[1], dst_paths[1], omni.client.Result.ERROR_NOT_SUPPORTED) expected_results = [dst_paths[0],dst_paths[1], Exception("Test Exception")] callback(expected_results) async def test_show_download_menuitem_setting(self): """Testing show download menuitem setting works as expect.""" old_setting_value = carb.settings.get_settings().get("exts/omni.kit.window.content_browser/show_download_menuitem") item = Mock() item.path = "test" item.is_folder = False item.writeable = True carb.settings.get_settings().set("exts/omni.kit.window.content_browser/show_download_menuitem", True) await ui_test.human_delay(10) menu_with_download = ContextMenu() menu_with_download.show(item, [item]) await ui_test.human_delay(30) menu_dict = await ui_test.get_context_menu(menu_with_download.menu) has_download_menuitem = False for name in menu_dict["_"]: if name == "Download": has_download_menuitem = True self.assertTrue(has_download_menuitem) menu_with_download.destroy() carb.settings.get_settings().set("exts/omni.kit.window.content_browser/show_download_menuitem", False) await ui_test.human_delay(10) menu_without_download = ContextMenu() await ui_test.human_delay(10) menu_without_download.show(item, [item]) menu_dict = await ui_test.get_context_menu(menu_without_download.menu) has_download_menuitem = False for name in menu_dict["_"]: if name == "Download": has_download_menuitem = True self.assertFalse(has_download_menuitem) menu_without_download.destroy() carb.settings.get_settings().set("exts/omni.kit.window.content_browser/show_download_menuitem", old_setting_value)
10,524
Python
46.840909
150
0.624382
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/test_navigate.py
## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import omni.kit.app import omni.client from unittest.mock import patch, Mock from omni.kit import ui_test from omni.kit.test.async_unittest import AsyncTestCase from omni.kit.test_suite.helpers import get_test_data_path from .. import get_content_window class TestNavigate(AsyncTestCase): """Testing ContentBrowserWidget.open_and_navigate_to""" async def setUp(self): await ui_test.find("Content").focus() async def tearDown(self): pass async def test_file_found_and_opened(self): """Testing when navigating to USD file, opens it""" content_browser = get_content_window() under_test = content_browser.window.widget url = get_test_data_path(__name__, "4Lights.usda") mock_open_stage = Mock() with patch("omni.kit.window.content_browser.file_ops.get_file_open_handler", return_value=mock_open_stage): # patch("omni.kit.window.content_browser.widget.open_stage") as mock_open_stage: under_test._open_and_navigate_to(url) await ui_test.human_delay(4) mock_open_stage.assert_called_once_with(omni.client.normalize_url(url)) async def test_file_with_spaces_found_and_opened(self): """Testing file with surrounding spaces is correctly found""" content_browser = get_content_window() under_test = content_browser.window.widget url = " " + get_test_data_path(__name__, "4Lights.usda") + " " mock_open_stage = Mock() with patch("omni.kit.window.content_browser.file_ops.get_file_open_handler", return_value=mock_open_stage): under_test._open_and_navigate_to(url) await ui_test.human_delay(4) mock_open_stage.assert_called_once_with(omni.client.normalize_url(url.strip())) async def test_folder_found_not_opened(self): """Testing when navigating to folder with USD extension, doesn't open it""" content_browser = get_content_window() under_test = content_browser.window.widget url = get_test_data_path(__name__, "folder.usda") mock_open_stage = Mock() with patch("omni.kit.window.content_browser.file_ops.get_file_open_handler", return_value=mock_open_stage): under_test._open_and_navigate_to(url) await ui_test.human_delay(4) mock_open_stage.assert_not_called() async def test_invalid_usd_path_still_opened(self): """Testing that even if a USD path is invalid, we still try to open it""" content_browser = get_content_window() under_test = content_browser.window.widget url = get_test_data_path(__name__, "not-found.usda") mock_open_stage = Mock() with patch("omni.kit.window.content_browser.file_ops.get_file_open_handler", return_value=mock_open_stage): under_test._open_and_navigate_to(url) await ui_test.human_delay(4) mock_open_stage.assert_called_once_with(omni.client.normalize_url(url.strip()))
3,449
Python
44.394736
115
0.679327
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/test_test_helper.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import omni.kit.app import omni.usd from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from omni.kit.test_suite.helpers import open_stage, get_test_data_path, get_prims, wait_stage_loading, arrange_windows from ..test_helper import ContentBrowserTestHelper class TestDragDropTreeView(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows("Stage", 512) # After running each test async def tearDown(self): await wait_stage_loading() async def test_config_menu_setting(self): await ui_test.find("Content").focus() async with ContentBrowserTestHelper() as content_browser_helper: old_setting = await content_browser_helper.get_config_menu_settings() # TODO: Why this not works as expect? await content_browser_helper.set_config_menu_settings({"test": "test"}) test_dict = await content_browser_helper.get_config_menu_settings() standard_dict = {'hide_unknown': False, 'hide_thumbnails': True, 'show_details': True, 'show_udim_sequence': False} self.assertEqual(test_dict,standard_dict) await content_browser_helper.set_config_menu_settings(old_setting) async def test_select_single_item(self): await ui_test.find("Content").focus() # select file to show info usd_path = get_test_data_path(__name__) async with ContentBrowserTestHelper() as content_browser_helper: selections = await content_browser_helper.select_items_async(usd_path, names=["4Lights.usda"]) await ui_test.human_delay(4) # Verify selections self.assertEqual([sel.name for sel in selections], ['4Lights.usda']) async def test_select_multiple_items(self): await ui_test.find("Content").focus() # select file to show info usd_path = get_test_data_path(__name__) filenames = ["4Lights.usda", "bound_shapes.usda", "quatCube.usda"] async with ContentBrowserTestHelper() as content_browser_helper: selections = await content_browser_helper.select_items_async(usd_path, names=filenames+["nonexistent.usda"]) await ui_test.human_delay(4) # Verify selections self.assertEqual(sorted([sel.name for sel in selections]), sorted(filenames)) async def test_drag_drop_single_item(self): await open_stage(get_test_data_path(__name__, "bound_shapes.usda")) await wait_stage_loading() await ui_test.find("Content").focus() await ui_test.find("Stage").focus() # verify prims usd_context = omni.usd.get_context() stage = usd_context.get_stage() paths = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)] self.assertEqual(paths, ['/World', '/World/defaultLight', '/World/Cone', '/World/Cube', '/World/Sphere', '/World/Cylinder', '/World/Looks', '/World/Looks/OmniPBR', '/World/Looks/OmniPBR/Shader', '/World/Looks/OmniGlass', '/World/Looks/OmniGlass/Shader', '/World/Looks/OmniSurface_Plastic', '/World/Looks/OmniSurface_Plastic/Shader']) # drag/drop files to stage window stage_window = ui_test.find("Stage") drag_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 32) async with ContentBrowserTestHelper() as content_browser_helper: for file_path in ["4Lights.usda", "quatCube.usda"]: await content_browser_helper.drag_and_drop_tree_view(get_test_data_path(__name__, file_path), drag_target=drag_target) # verify prims paths = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)] self.assertEqual(paths, ['/World', '/World/defaultLight', '/World/Cone', '/World/Cube', '/World/Sphere', '/World/Cylinder', '/World/Looks', '/World/Looks/OmniPBR', '/World/Looks/OmniPBR/Shader', '/World/Looks/OmniGlass', '/World/Looks/OmniGlass/Shader', '/World/Looks/OmniSurface_Plastic', '/World/Looks/OmniSurface_Plastic/Shader', '/World/_Lights', '/World/_Lights/SphereLight_01', '/World/_Lights/SphereLight_02', '/World/_Lights/SphereLight_03', '/World/_Lights/SphereLight_00', '/World/_Lights/Cube', '/World/quatCube', '/World/quatCube/Cube']) async def test_drag_drop_multiple_items(self): await open_stage(get_test_data_path(__name__, "bound_shapes.usda")) await wait_stage_loading() await ui_test.find("Content").focus() await ui_test.find("Stage").focus() # verify prims usd_context = omni.usd.get_context() stage = usd_context.get_stage() paths = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)] self.assertEqual(paths, ['/World', '/World/defaultLight', '/World/Cone', '/World/Cube', '/World/Sphere', '/World/Cylinder', '/World/Looks', '/World/Looks/OmniPBR', '/World/Looks/OmniPBR/Shader', '/World/Looks/OmniGlass', '/World/Looks/OmniGlass/Shader', '/World/Looks/OmniSurface_Plastic', '/World/Looks/OmniSurface_Plastic/Shader']) # drag/drop files to stage window stage_window = ui_test.find("Stage") drag_target = stage_window.position + ui_test.Vec2(stage_window.size.x / 2, stage_window.size.y - 96) async with ContentBrowserTestHelper() as content_browser_helper: usd_path = get_test_data_path(__name__) await content_browser_helper.drag_and_drop_tree_view(usd_path, names=["4Lights.usda", "quatCube.usda"], drag_target=drag_target) # verify prims paths = [prim.GetPath().pathString for prim in get_prims(stage) if not omni.usd.is_hidden_type(prim)] self.assertEqual(paths, ['/World', '/World/defaultLight', '/World/Cone', '/World/Cube', '/World/Sphere', '/World/Cylinder', '/World/Looks', '/World/Looks/OmniPBR', '/World/Looks/OmniPBR/Shader', '/World/Looks/OmniGlass', '/World/Looks/OmniGlass/Shader', '/World/Looks/OmniSurface_Plastic', '/World/Looks/OmniSurface_Plastic/Shader', '/World/_Lights', '/World/_Lights/SphereLight_01', '/World/_Lights/SphereLight_02', '/World/_Lights/SphereLight_03', '/World/_Lights/SphereLight_00', '/World/_Lights/Cube', '/World/quatCube', '/World/quatCube/Cube'])
6,769
Python
58.385964
557
0.679864
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/test_cut_paste.py
import omni.kit.test from unittest.mock import patch import omni.client from omni import ui from carb.input import KeyboardInput from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from omni.kit.test_suite.helpers import get_test_data_path from omni.kit.widget.filebrowser import is_clipboard_cut, get_clipboard_items, clear_clipboard from ..test_helper import ContentBrowserTestHelper class TestCutPaste(AsyncTestCase): """Testing ContentBrowserWidget cut and paste behavior""" async def setUp(self): await ui_test.find("Content").focus() async def tearDown(self): pass async def test_paste_availability(self): """Testing paste context menu shows up correctly.""" test_dir = get_test_data_path(__name__) test_file = "4Lights.usda" test_folder = "folder.usda" async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.navigate_to_async(test_dir) await content_browser_helper.toggle_grid_view_async(True) await ui_test.human_delay(100) item = await content_browser_helper.get_gridview_item_async(test_file) folder_item = await content_browser_helper.get_gridview_item_async(test_folder) if not item: return await item.right_click() await ui_test.human_delay() context_menu = await ui_test.get_context_menu() context_options = context_menu["_"] self.assertIn("Cut", context_options) self.assertNotIn("Paste", context_options) await ui_test.select_context_menu("Cut") # now paste should be available await ui_test.human_delay() await folder_item.right_click() await ui_test.human_delay() context_menu = await ui_test.get_context_menu() context_options = context_menu["_"] self.assertIn("Paste", context_options) # paste will not be available if more than one item is selected, but Cut should await content_browser_helper.select_items_async(test_dir, [test_file, test_folder]) await item.right_click() await ui_test.human_delay() context_menu = await ui_test.get_context_menu() context_options = context_menu["_"] self.assertNotIn("Paste", context_options) self.assertIn("Cut", context_options) clear_clipboard() async def test_cut_and_paste(self): """Testing cut and paste.""" test_dir = get_test_data_path(__name__) test_file = "4Lights.usda" test_folder = "folder.usda" async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.navigate_to_async(test_dir) await content_browser_helper.toggle_grid_view_async(True) await ui_test.human_delay(100) item = await content_browser_helper.get_gridview_item_async(test_file) folder_item = await content_browser_helper.get_gridview_item_async(test_folder) if not item: return if not folder_item: return await folder_item.right_click() await ui_test.human_delay() await ui_test.select_context_menu("Cut") # cut clipboard should have one item in it self.assertTrue(is_clipboard_cut()) self.assertEqual(1, len(get_clipboard_items())) self.assertEqual(get_clipboard_items()[0].path.replace("\\", "/").lower(), f"{test_dir}/{test_folder}".replace("\\", "/").lower()) # cut clipboard should still have one item in it, but updated await item.right_click() await ui_test.human_delay() await ui_test.select_context_menu("Cut") self.assertTrue(is_clipboard_cut()) self.assertEqual(1, len(get_clipboard_items())) cut_path = get_clipboard_items()[0].path self.assertEqual(cut_path.replace("\\", "/").lower(), f"{test_dir}/{test_file}".replace("\\", "/").lower()) with patch.object(omni.client, "move_async", return_value=(omni.client.Result.OK, None)) as mock_move: await folder_item.right_click() await ui_test.human_delay() await ui_test.select_context_menu("Paste") await ui_test.human_delay(10) window = ui_test.find("MOVE") self.assertIsNotNone(window) await ui_test.emulate_keyboard_press(KeyboardInput.ENTER) await ui_test.human_delay() mock_move.assert_called_once() # clipboard should be cleared now self.assertEqual(get_clipboard_items(), []) self.assertFalse(is_clipboard_cut())
4,918
Python
40.68644
119
0.610207
omniverse-code/kit/exts/omni.kit.window.content_browser/omni/kit/window/content_browser/tests/test_external_drag_drop.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 import tempfile import omni.kit.app import omni.usd from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from omni.kit.test_suite.helpers import open_stage, get_test_data_path, get_prims, wait_stage_loading, arrange_windows from omni.kit.window.content_browser import get_content_window class TestExternalDragDrop(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows("Stage", 512) # After running each test async def tearDown(self): await wait_stage_loading() async def test_external_drag_drop(self): # position mouse await ui_test.find("Content").click() await ui_test.human_delay() with tempfile.TemporaryDirectory() as tmpdir: test_file = f"{tmpdir}/bound_shapes.usda" # browse to tempdir content_browser = get_content_window() content_browser.navigate_to(str(tmpdir)) await ui_test.human_delay(50) # if target file exists remove if os.path.exists(test_file): os.remove(test_file) # simulate drag/drop item_path = get_test_data_path(__name__, "bound_shapes.usda") omni.appwindow.get_default_app_window().get_window_drop_event_stream().push(0, 0, {'paths': [item_path]}) await ui_test.human_delay(50) # verify exists self.assertTrue(os.path.exists(test_file))
1,924
Python
36.01923
118
0.678274
omniverse-code/kit/exts/omni.kit.window.content_browser/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [2.6.8] - 2023-01-19 ### Updated - Removed restriction on moving/copying files between servers. ## [2.6.7] - 2023-01-11 ### Updated - Added UDIM support ## [2.6.6] - 2022-12-08 ### Fixed - Bring content_browser window into focus during tests, as Stage window was on top now. ## [2.6.5] - 2022-11-27 ### Updated - Switch out pyperclip with linux-friendly copy & paste ## [2.6.4] - 2022-11-08 ### Updated - Added rename/move features to content browser, UX is similar to Navigator. ## [2.6.3] - 2022-11-15 ### Updated - Updated the docs. ## [2.6.2] - 2022-11-15 ### Fixed - Fix error message when delete a file in content browser(OM-72757) ## [2.6.1] - 2022-11-09 ### Updated - Auto-connects user specified server at startup ## [2.5.9] - 2022-11-07 ### Updated - Add option to overwrite downloading a single file/folder using user input, and pre-populate filename - Downloading with multi-selection will disable filename field input - Added tests for download ## [2.5.8] - 2022-11-03 ### Updated - Persist customizations when window is closed and re-opened. ## [2.5.7] - 2022-11-03 ### Fixed - Restores 'mounted_servers' setting for specifying default server connections. ## [2.5.6] - 2022-11-01 ### Updated - When opening a stage, auto-connect to nucleus. ## [2.5.5] - 2022-10-28 ### Fixed - delete folder in Content browser auto select and center it's parent (OM-65585) ## [2.5.4] - 2022-10-14 ### Fixed - external drag/drop works again (OM-65824) ## [2.5.3] - 2022-09-30 ### Fixed - Set the menu checkbox when the window is appearing ## [2.5.2] - 2022-09-28 ### Updated - Use omni.client instead of carb.settings to store bookmarks. ## [2.5.1] - 2022-09-20 ### Updated - Change menu refresh to use interal async for not block ui. ## [2.5.0] - 2022-08-30 ### Fixed - Refactored thumbnails provider ## [2.4.33] - 2022-07-27 ### Fixed - Fixed the window when changing layout (OM-48414) ## [2.4.32] - 2022-07-26 ### Added - Don't invadvertently try to open directories as USD files during navigation - Strip spaces around Url - Adds unittests for test helper ## [2.4.31] - 2022-07-19 ### Added - Fixes placement of filter menu ## [2.4.30] - 2022-07-13 ### Added - Added test helper. ## [2.4.29] - 2022-07-08 ### Fixed - the issue of 'ContentBrowserExtension' object has no attribute '_window' while calling `shutdown_extensions` function of omni.kit.window.content_browser ## [2.4.28] - 2022-05-11 ### Added - Prevents copying files from one server to another, which currently crashes the app. ## [2.4.27] - 2022-05-03 ### Added - Adds api to retrieve the checkpoint widget. - Adds async option to navigate_to function. ## [2.4.24] - 2022-04-26 ### Added - Restores open with payloads disabled to context menus. ## [2.4.23] - 2022-04-18 ### Added - Limits extent that splitter can be dragged, to prevent breaking. ## [2.4.22] - 2022-04-12 ### Added - Adds splitter to adjust width of detail pane. ## [2.4.21] - 2022-04-11 ### Fixed - Empty window when changing layout (OM-48414) ## [2.4.20] - 2022-04-06 ### Added - Disable unittests from loading at startup. ## [2.4.19] - 2022-04-04 ### Updated - Removed "show real path" option. ## [2.4.18] - 2022-03-31 ### Updated - Removed "Open with payloads disabled" from context menu in widget. ## [2.4.17] - 2022-03-18 ### Updated - Updates search results when directory changed. ## [2.4.16] - 2022-03-18 ### Fixed - `add_import_menu` is permanent and the Import menu is not destroyed when the window is closed ## [2.4.15] - 2022-03-14 ### Updated - Refactored asset type handling ## [2.4.13] - 2022-03-08 ### Updated - Sends external drag drop to search delegate ## [2.4.12] - 2022-02-15 ### Updated - Adds custom search delegate ## [2.4.11] - 2022-01-20 ### Updated - Adds setting to customize what collections are shown ## [2.4.10] - 2021-11-22 ### Updated - Simplified code for building checkpoint widget. ## [2.4.9] - 2021-11-16 ### Updated - Ported search box to filepicker and refactored the tool bar into a shared component. ## [2.4.8] - 2021-09-17 ### Updated - Added widget identifers ## [2.4.7] - 2021-08-13 ### Updated - Added "Open With Payloads Disabled" to checkpoint menu ## [2.4.6] - 2021-08-12 ### Updated - Fixed the "copy URL/description" functions for checkpoints. ## [2.4.5] - 2021-08-09 ### Updated - Smoother update of thumbnails while populating a search filter. ## [2.4.4] - 2021-07-20 ### Updated - Disables "restore checkpoint" action menu for head version ## [2.4.3] - 2021-07-20 ### Updated - Fixes checkoint selection ## [2.4.2] - 2021-07-12 ### Updated - Starts up in tree view if "show_grid_view" setting is set to false. ## [2.4.1] - 2021-07-12 ### Updated - Moved checkpoints panel to new detail view ## [2.3.7] - 2021-06-25 ### Updated - Enabled persistent pane settings ## [2.3.6] - 2021-06-24 ### Updated - Pass open_file to `FilePickerView` - `get_file_open_handler` ignore checkpoint ## [2.3.5] - 2021-06-21 ### Updated - Update the directory path from either tree or list view. ## [2.3.4] - 2021-06-10 ### Updated - Menu options are persistent ## [2.3.3] - 2021-06-08 ### Updated - When "show checkpoints" unchecked, the panel is hidden and remains so. ## [2.3.2] - 2021-06-07 ### Updated - Added splitter bar for resizing checkpoints panel. - Refactored checkpoints panel and zoom bar into FilePickerView widget. - More thorough destruction of class instances upon shutdown. ## [2.3.1] - 2021-05-18 ### Updated - Eliminates manually initiated refresh of the UI when creating new folder, deleting items, and copying items; these conflict with auto refresh. ### [2.2.2] - 2021-04-09 ### Changes - Added drag/drop support from outside kit ## [2.2.1] - 2021-04-09 ### Changed - Show <head> entry in versioning pane. ## [2.2.0] - 2021-03-19 ### Added - Supported drag and drop from versioning pane. ## [2.1.3] - 2021-02-16 ### Updated - Fixes thumbnails for search model. ## [2.1.2] - 2021-02-10 ### Changes - Updated StyleUI handling ## [2.1.1] - 2021-02-09 ### Updated - Fixed navigation slowness caused by processing of thumbnails. - Uses auto thumbnails generated by deeptag if manual thumbnails not available. ## [2.1.0] - 2021-02-04 ### Added - Added `subscribe_selection_changed` to extension interface. - Added optional versioning pane on supported server (only when omni.kit.widget.versioning is enabled). ## [2.0.0] - 2021-01-03 ### Updated - Refactored for async directory listing to improve overall stability in case of network delays. ## [1.8.10] - 2020-12-10 ### Updated - UI speedup: Opens file concurrently with navigating to path. ## [1.8.9] - 2020-12-5 ### Updated - Adds 'reconnect server' action to context menu ## [1.8.8] - 2020-12-03 ### Updated - Adds ability to rename connections and bookmarks ## [1.8.7] - 2020-12-01 ### Updated - Renamed to just "Content". - Applies visibility filter to search results. ## [1.8.6] - 2020-11-26 ### Updated - Defaults browser bar to display real path ## [1.8.5] - 2020-11-25 ### Updated - Adds file_open set of APIs to open files with user specified apps. - Pasting a URL into browser bar opens the file. ## [1.8.4] - 2020-11-23 ### Updated - Allows multi-selection copies. ## [1.8.3] - 2020-11-20 ### Updated - Allows multi-selection deletion. - Updates and scrolls to download folder upon downloading files. ## [1.8.2] - 2020-11-19 ### Updated - Allows multi-selection downloads. ## [1.8.1] - 2020-11-06 ### Added - Keep connections and bookmarks between content browser and filepicker in sync. ## [1.8.0] - 2020-10-31 ### Added - Now able to resolve URL paths pasted into the browser bar ## [1.7.1] - 2020-10-30 ### Fixed - Fix reference leak when shutting down content browser ## [1.7.0] - 2020-10-29 ### Added - API methods to add menu items to the import button - User folders to "my-computer" collection - Refactored Options Menu into generic popup_dialog window - Fixed opening of USD files and updated to use the open_stage function from omni.kit.window.file ## [1.6.0] - 2020-10-27 ### Added - Ported context menu to omni.kit.window.filepicker. - Consolidated API methods into api module. ## [1.0.0] - 2020-10-14 ### Added - Initial commit for internal release.
8,285
Markdown
23.808383
154
0.686421
omniverse-code/kit/exts/omni.usd.schema.omniscripting/pxr/OmniScriptingSchemaTools/_omniScriptingSchemaTools.pyi
from __future__ import annotations import pxr.OmniScriptingSchemaTools._omniScriptingSchemaTools import typing __all__ = [ "applyOmniScriptingAPI", "removeOmniScriptingAPI" ] def applyOmniScriptingAPI(*args, **kwargs) -> None: pass def removeOmniScriptingAPI(*args, **kwargs) -> None: pass __MFB_FULL_PACKAGE_NAME = 'omniScriptingSchemaTools'
362
unknown
21.687499
61
0.743094
omniverse-code/kit/exts/omni.usd.schema.omniscripting/pxr/OmniScriptingSchema/_omniScriptingSchema.pyi
from __future__ import annotations import pxr.OmniScriptingSchema._omniScriptingSchema import typing import Boost.Python import pxr.Usd __all__ = [ "OmniScriptingAPI" ] class OmniScriptingAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def CreateOmniScriptingScriptsAttr(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetOmniScriptingScriptsAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class _CanApplyResult(Boost.Python.instance): @property def whyNot(self) -> None: """ :type: None """ __instance_size__ = 56 pass __MFB_FULL_PACKAGE_NAME = 'omniScriptingSchema'
1,031
unknown
26.157894
89
0.646945
omniverse-code/kit/exts/omni.kit.filebrowser_column.acl/config/extension.toml
[package] version = "1.0.0" authors = ["NVIDIA"] title = "Access Column in Content Browser" description="The column that is showing the access flags of the file." readme = "docs/README.md" repository = "" keywords = ["column", "filebrowser", "content", "tag"] changelog="docs/CHANGELOG.md" preview_image = "data/preview.png" [dependencies] "omni.client" = {} "omni.kit.widget.filebrowser" = {} [[python.module]] name = "omni.kit.filebrowser_column.acl" # Additional python module with tests, to make them discoverable by test system. [[python.module]] name = "omni.kit.filebrowser_column.acl.tests" [[test]] dependencies = [ "omni.kit.mainwindow", "omni.kit.renderer.capture", ] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", ]
787
TOML
23.624999
80
0.696315
omniverse-code/kit/exts/omni.kit.filebrowser_column.acl/omni/kit/filebrowser_column/acl/__init__.py
from .acl_extension import AclExtension
40
Python
19.49999
39
0.85
omniverse-code/kit/exts/omni.kit.filebrowser_column.acl/omni/kit/filebrowser_column/acl/acl_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. # from omni.kit.widget.filebrowser import ColumnItem from omni.kit.widget.filebrowser import AbstractColumnDelegate import asyncio import carb import functools import omni.client import omni.ui as ui import traceback def handle_exception(func): """ Decorator to print exception in async functions """ @functools.wraps(func) async def wrapper(*args, **kwargs): try: return await func(*args, **kwargs) except asyncio.CancelledError: 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 class AclDelegate(AbstractColumnDelegate): """ The object that adds the new column "Access" to fileblowser. The columns displays access flags. """ @property def initial_width(self): """The width of the column""" return ui.Pixel(40) def build_header(self): """Build the header""" ui.Label("ACL", style_type_name_override="TreeView.Header") @handle_exception async def build_widget(self, item: ColumnItem): """ Build the widget for the given item. Works inside Frame in async mode. Once the widget is created, it will replace the content of the frame. It allow to await something for a while and create the widget when the result is available. """ result, entry = await omni.client.stat_async(item.path) if result != omni.client.Result.OK: ui.Label("Error", style_type_name_override="TreeView.Item") return flags = entry.access text = "" if flags & omni.client.AccessFlags.READ: text += "R" if flags & omni.client.AccessFlags.WRITE: text += "W" if flags & omni.client.AccessFlags.ADMIN: text += "A" text = text or "none" ui.Label(text, style_type_name_override="TreeView.Item")
2,467
Python
29.85
76
0.653425
omniverse-code/kit/exts/omni.kit.filebrowser_column.acl/omni/kit/filebrowser_column/acl/tests/acl_test.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 ..acl_delegate import AclDelegate from ..acl_delegate import ColumnItem from omni.ui.tests.test_base import OmniUiTest from pathlib import Path import asyncio import omni.kit.app import omni.ui as ui import tempfile CURRENT_PATH = Path(__file__).parent.joinpath("../../../../../data") class AwaitWithFrame: """ A future-like object that runs the given future and makes sure it's always in the given frame's scope. It allows for creating widgets asynchronously. """ def __init__(self, frame: ui.Frame, future: asyncio.Future): self._frame = frame self._future = future def __await__(self): # create an iterator object from that iterable iter_obj = iter(self._future.__await__()) # infinite loop while True: try: with self._frame: yield next(iter_obj) except StopIteration: break self._frame = None self._future = None class TestAcl(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests") # After running each test async def tearDown(self): self._golden_img_dir = None await super().tearDown() async def test_general(self): temp = tempfile.NamedTemporaryFile() window = await self.create_test_window() with window.frame: frame = ui.Frame(style={"TreeView.Item": {"color": 0xFFFFFFFF}}) item = ColumnItem(temp.name) delegate = AclDelegate() await AwaitWithFrame(frame, delegate.build_widget(item)) await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir) temp.close()
2,284
Python
29.466666
82
0.652364
omniverse-code/kit/exts/omni.kit.filebrowser_column.acl/docs/CHANGELOG.md
# Changelog This document records all notable changes to `omni.kit.filebrowser_column.acl` extension. ## [1.0.0] - 2020-10-05 ### Added - Initial example implementation of extension that creates a column in Content Explorer
228
Markdown
21.899998
70
0.758772
omniverse-code/kit/exts/omni.kit.filebrowser_column.acl/docs/README.md
# omni.kit.filebrowser_column.acl ## Access column in Content Browser The example extension adds a new column to Content Browser. The extension is based on `omni.client` and is showing the access flags of the file.
217
Markdown
30.142853
76
0.78341
omniverse-code/kit/exts/omni.kit.window.splash/omni/splash/__init__.py
from ._splash import *
23
Python
10.999995
22
0.695652
omniverse-code/kit/exts/omni.kit.window.splash/omni/splash/tests/__init__.py
from .test_splash import *
27
Python
12.999994
26
0.740741
omniverse-code/kit/exts/omni.kit.window.splash/omni/splash/tests/test_splash.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import omni.kit.app from omni.kit.test import AsyncTestCase import omni.splash class TestSplash(AsyncTestCase): async def setUp(self): self._splash_iface = omni.splash.acquire_splash_screen_interface() async def tearDown(self): pass async def test_001_close_autocreated(self): # This test just closes the automatically created by the extension on startup self._splash_iface.close_all() async def test_002_create_destroy_splash(self): splash = self._splash_iface.create("${resources}/splash/splash.png", 1.0) self._splash_iface.show(splash) for _ in range(3): await omni.kit.app.get_app().next_update_async() self.assertTrue(self._splash_iface.is_valid(splash)) for _ in range(3): await omni.kit.app.get_app().next_update_async() self._splash_iface.close(splash)
1,350
Python
31.951219
85
0.704444
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/capture_progress.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 from enum import Enum, IntEnum import datetime import subprocess import carb import omni.ui as ui import omni.kit.app class CaptureStatus(IntEnum): NONE = 0 CAPTURING = 1 PAUSED = 2 FINISHING = 3 TO_START_ENCODING = 4 ENCODING = 5 CANCELLED = 6 class CaptureProgress: def __init__(self): self._init_internal() def _init_internal(self, total_frames=1): self._total_frames = total_frames # at least to capture 1 frame if self._total_frames < 1: self._total_frames = 1 self._capture_status = CaptureStatus.NONE self._elapsed_time = 0.0 self._estimated_time_remaining = 0.0 self._current_frame_time = 0.0 self._average_time_per_frame = 0.0 self._encoding_time = 0.0 self._current_frame = 0 self._first_frame_num = 0 self._got_first_frame = False self._progress = 0.0 self._current_subframe = -1 self._total_subframes = 1 self._subframe_time = 0.0 self._total_frame_time = 0.0 self._average_time_per_subframe = 0.0 self._total_preroll_frames = 0 self._prerolled_frames = 0 self._path_trace_iteration_num = 0 self._path_trace_subframe_num = 0 self._total_iterations = 0 self._average_time_per_iteration = 0.0 self._is_handling_settle_latency_frames = False self._settle_latency_frames_done = 0 self._total_settle_latency_frames = 0 @property def capture_status(self): return self._capture_status @capture_status.setter def capture_status(self, value): self._capture_status = value @property def elapsed_time(self): return self._get_time_string(self._elapsed_time) @property def estimated_time_remaining(self): return self._get_time_string(self._estimated_time_remaining) @property def current_frame_time(self): return self._get_time_string(self._current_frame_time) @property def average_frame_time(self): return self._get_time_string(self._average_time_per_frame) @property def encoding_time(self): return self._get_time_string(self._encoding_time) @property def progress(self): return self._progress @property def current_subframe(self): return self._current_subframe if self._current_subframe >= 0 else 0 @property def total_subframes(self): return self._total_subframes @property def subframe_time(self): return self._get_time_string(self._subframe_time) @property def average_time_per_subframe(self): return self._get_time_string(self._average_time_per_subframe) @property def total_preroll_frames(self): return self._total_preroll_frames @total_preroll_frames.setter def total_preroll_frames(self, value): self._total_preroll_frames = value @property def prerolled_frames(self): return self._prerolled_frames @prerolled_frames.setter def prerolled_frames(self, value): self._prerolled_frames = value @property def path_trace_iteration_num(self): return self._path_trace_iteration_num @path_trace_iteration_num.setter def path_trace_iteration_num(self, value): self._path_trace_iteration_num = value @property def path_trace_subframe_num(self): return self._path_trace_subframe_num @path_trace_subframe_num.setter def path_trace_subframe_num(self, value): self._path_trace_subframe_num = value @property def total_iterations(self): return self._total_iterations @property def average_time_per_iteration(self): return self._get_time_string(self._average_time_per_iteration) @property def current_frame_count(self): return self._current_frame - self._first_frame_num @property def total_frames(self): return self._total_frames @property def is_handling_settle_latency_frames(self): return self._is_handling_settle_latency_frames @property def settle_latency_frames_done(self): return self._settle_latency_frames_done @property def total_settle_latency_frames(self): return self._total_settle_latency_frames def start_capturing(self, total_frames, preroll_frames=0): self._init_internal(total_frames) self._total_preroll_frames = preroll_frames self._capture_status = CaptureStatus.CAPTURING def finish_capturing(self): self._init_internal() def is_prerolling(self): return ( (self._capture_status == CaptureStatus.CAPTURING or self._capture_status == CaptureStatus.PAUSED) and self._total_preroll_frames > 0 and self._total_preroll_frames > self._prerolled_frames ) def add_encoding_time(self, time): if self._estimated_time_remaining > 0.0: self._elapsed_time += self._estimated_time_remaining self._estimated_time_remaining = 0.0 self._encoding_time += time def add_frame_time(self, frame, time, pt_subframe_num=0, pt_total_subframes=0, pt_iteration_num=0, pt_iteration_per_subframe=0, \ handling_settle_latency_frames=False, settle_latency_frames_done=0, total_settle_latency_frames=0): if not self._got_first_frame: self._got_first_frame = True self._first_frame_num = frame self._current_frame = frame self._path_trace_subframe_num = pt_subframe_num self._path_trace_iteration_num = pt_iteration_num self._total_subframes = pt_total_subframes self._total_iterations = pt_iteration_per_subframe self._elapsed_time += time if self._current_frame != frame: frames_captured = self._current_frame - self._first_frame_num + 1 self._average_time_per_frame = self._elapsed_time / frames_captured self._current_frame = frame self._current_frame_time = time else: self._current_frame_time += time if frame == self._first_frame_num: self._estimated_time_remaining = 0.0 self._progress = 0.0 else: total_frame_time = self._average_time_per_frame * self._total_frames # if users pause for long times, or there are skipped frames, it's possible that elapsed time will be greater than estimated total time # if this happens, estimate it again if self._elapsed_time >= total_frame_time: if self._elapsed_time < time + self._average_time_per_frame: total_frame_time += time + self._average_time_per_frame else: total_frame_time = self._elapsed_time + self._average_time_per_frame * (self._total_frames - self._current_frame + 1) self._estimated_time_remaining = total_frame_time - self._elapsed_time self._progress = self._elapsed_time / total_frame_time self._is_handling_settle_latency_frames = handling_settle_latency_frames self._settle_latency_frames_done = settle_latency_frames_done self._total_settle_latency_frames = total_settle_latency_frames def add_single_frame_capture_time_for_pt(self, subframe, total_subframes, time): self._total_subframes = total_subframes self._elapsed_time += time if self._current_subframe != subframe: self._subframe_time = time if self._current_subframe == -1: self._average_time_per_subframe = self._elapsed_time else: self._average_time_per_subframe = self._elapsed_time / subframe self._total_frame_time = self._average_time_per_subframe * total_subframes else: self._subframe_time += time self._current_subframe = subframe if self._current_subframe == 0: self._estimated_time_remaining = 0.0 self._progress = 0.0 else: if self._elapsed_time >= self._total_frame_time: self._total_frame_time += time + self._average_time_per_subframe self._estimated_time_remaining = self._total_frame_time - self._elapsed_time self._progress = self._elapsed_time / self._total_frame_time def add_single_frame_capture_time_for_iray(self, subframe, total_subframes, iterations_done, iterations_per_subframe, time): self._total_subframes = total_subframes self._total_iterations = iterations_per_subframe self._elapsed_time += time self._path_trace_iteration_num = iterations_done if self._current_subframe != subframe: self._subframe_time = time if self._current_subframe == -1: self._average_time_per_subframe = self._elapsed_time else: self._average_time_per_subframe = self._elapsed_time / subframe self._total_frame_time = self._average_time_per_subframe * total_subframes else: self._subframe_time += time self._current_subframe = subframe if self._current_subframe == 0: self._estimated_time_remaining = 0.0 self._progress = 0.0 else: if self._elapsed_time >= self._total_frame_time: self._total_frame_time += time + self._average_time_per_subframe self._estimated_time_remaining = self._total_frame_time - self._elapsed_time self._progress = self._elapsed_time / self._total_frame_time def _get_time_string(self, time_seconds): hours = int(time_seconds / 3600) minutes = int((time_seconds - hours*3600) / 60) seconds = time_seconds - hours*3600 - minutes*60 time_string = "" if hours > 0: time_string += '{:d}h '.format(hours) if minutes > 0: time_string += '{:d}m '.format(minutes) else: if hours > 0: time_string += "0m " time_string += '{:.2f}s'.format(seconds) return time_string PROGRESS_WINDOW_WIDTH = 360 PROGRESS_WINDOW_HEIGHT = 280 PROGRESS_BAR_WIDTH = 216 PROGRESS_BAR_HEIGHT = 20 PROGRESS_BAR_HALF_HEIGHT = PROGRESS_BAR_HEIGHT / 2 TRIANGLE_WIDTH = 6 TRIANGLE_HEIGHT = 10 TRIANGLE_OFFSET_Y = 10 PROGRESS_WIN_DARK_STYLE = { "Triangle::progress_marker": {"background_color": 0xFFD1981D}, "Rectangle::progress_bar_background": { "border_width": 0.5, "border_radius": PROGRESS_BAR_HALF_HEIGHT, "background_color": 0xFF888888, }, "Rectangle::progress_bar_full": { "border_width": 0.5, "border_radius": PROGRESS_BAR_HALF_HEIGHT, "background_color": 0xFFD1981D, }, "Rectangle::progress_bar": { "background_color": 0xFFD1981D, "border_radius": PROGRESS_BAR_HALF_HEIGHT, "corner_flag": ui.CornerFlag.LEFT, "alignment": ui.Alignment.LEFT, }, } PAUSE_BUTTON_STYLE = { "NvidiaLight": { "Button.Label::pause": {"color": 0xFF333333}, "Button.Label::pause:disabled": {"color": 0xFF666666}, }, "NvidiaDark": { "Button.Label::pause": {"color": 0xFFCCCCCC}, "Button.Label::pause:disabled": {"color": 0xFF666666}, }, } class CaptureProgressWindow: def __init__(self): self._app = omni.kit.app.get_app_interface() self._update_sub = None self._window_caption = "Capture Progress" self._window = None self._progress = None self._progress_bar_len = PROGRESS_BAR_HALF_HEIGHT self._progress_step = 0.5 self._is_single_frame_mode = False self._show_pt_subframes = False self._show_pt_iterations = False self._support_pausing = True self._is_external_window = False def show( self, progress, single_frame_mode: bool = False, show_pt_subframes: bool = False, show_pt_iterations: bool = False, support_pausing: bool = True, ) -> None: self._progress = progress self._is_single_frame_mode = single_frame_mode self._show_pt_subframes = show_pt_subframes self._show_pt_iterations = show_pt_iterations self._support_pausing = support_pausing self._build_ui() self._update_sub = self._app.get_update_event_stream().create_subscription_to_pop( self._on_update, name="omni.kit.capure.viewport progress" ) def close(self): if self._is_external_window: asyncio.ensure_future(self._move_back_to_main_window()) else: self._window.destroy() self._window = None self._update_sub = None def move_to_external_window(self): self._window.move_to_new_os_window() self._is_external_window = True def move_to_main_window(self): asyncio.ensure_future(self._move_back_to_main_window()) self._is_external_window = False def is_external_window(self): return self._is_external_window async def _move_back_to_main_window(self): self._window.move_to_main_os_window() for i in range(2): await omni.kit.app.get_app().next_update_async() self._window.destroy() self._window = None self._is_external_window = False def _build_progress_bar(self): self._progress_bar_area.clear() self._progress_bar_area.set_style(PROGRESS_WIN_DARK_STYLE) with self._progress_bar_area: with ui.Placer(offset_x=self._progress_bar_len - TRIANGLE_WIDTH / 2, offset_y=TRIANGLE_OFFSET_Y): ui.Triangle( name="progress_marker", width=TRIANGLE_WIDTH, height=TRIANGLE_HEIGHT, alignment=ui.Alignment.CENTER_BOTTOM, ) with ui.ZStack(): ui.Rectangle(name="progress_bar_background", width=PROGRESS_BAR_WIDTH, height=PROGRESS_BAR_HEIGHT) ui.Rectangle(name="progress_bar", width=self._progress_bar_len, height=PROGRESS_BAR_HEIGHT) def _build_ui_timer(self, text, init_value): with ui.HStack(): with ui.HStack(width=ui.Percent(50)): ui.Spacer() ui.Label(text, width=0) with ui.HStack(width=ui.Percent(50)): ui.Spacer(width=15) timer_label = ui.Label(init_value) ui.Spacer() return timer_label def _build_multi_frames_capture_timers(self): self._ui_elapsed_time = self._build_ui_timer("Elapsed time", self._progress.elapsed_time) self._ui_remaining_time = self._build_ui_timer("Estimated time remaining", self._progress.estimated_time_remaining) frame_count_str = f"{self._progress.current_frame_count}/{self._progress.total_frames}" self._ui_frame_count = self._build_ui_timer("Current/Total frames", frame_count_str) self._ui_current_frame_time = self._build_ui_timer("Current frame time", self._progress.current_frame_time) if self._show_pt_subframes: subframes_str = f"{self._progress.path_trace_subframe_num}/{self._progress.total_subframes}" self._ui_pt_subframes = self._build_ui_timer("Subframe/Total subframes", subframes_str) if self._show_pt_iterations: subframes_str = f"{self._progress.path_trace_subframe_num}/{self._progress.total_subframes}" self._ui_pt_subframes = self._build_ui_timer("Subframe/Total subframes", subframes_str) iter_str = f"{self._progress.path_trace_iteration_num}/{self._progress.total_iterations}" self._ui_pt_iterations = self._build_ui_timer("Iterations done/Total", iter_str) self._ui_ave_frame_time = self._build_ui_timer("Average time per frame", self._progress.average_frame_time) self._ui_encoding_time = self._build_ui_timer("Encoding", self._progress.encoding_time) def _build_single_frame_capture_timers(self): self._ui_elapsed_time = self._build_ui_timer("Elapsed time", self._progress.elapsed_time) self._ui_remaining_time = self._build_ui_timer("Estimated time remaining", self._progress.estimated_time_remaining) if self._show_pt_subframes: subframe_count = f"{self._progress.current_subframe}/{self._progress.total_subframes}" self._ui_subframe_count = self._build_ui_timer("Subframe/Total subframes", subframe_count) self._ui_current_frame_time = self._build_ui_timer("Current subframe time", self._progress.subframe_time) self._ui_ave_frame_time = self._build_ui_timer("Average time per subframe", self._progress.average_time_per_subframe) if self._show_pt_iterations: subframe_count = f"{self._progress.current_subframe}/{self._progress.total_subframes}" self._ui_subframe_count = self._build_ui_timer("Subframe/Total subframes", subframe_count) iteration_count = f"{self._progress.path_trace_iteration_num}/{self._progress.total_iterations}" self._ui_iteration_count = self._build_ui_timer("Iterations done/Per subframe", iteration_count) # self._ui_ave_iteration_time = self._build_ui_timer("Average time per iteration", self._progress.average_time_per_iteration) self._ui_ave_frame_time = self._build_ui_timer("Average time per subframe", self._progress.average_time_per_subframe) def _build_notification_area(self): with ui.HStack(): ui.Spacer(width=ui.Percent(20)) self._notification = ui.Label("") ui.Spacer(width=ui.Percent(10)) def _build_ui(self): if self._window is None: style_settings = carb.settings.get_settings().get("/persistent/app/window/uiStyle") if not style_settings: style_settings = "NvidiaDark" self._window = ui.Window( self._window_caption, width=PROGRESS_WINDOW_WIDTH, height=PROGRESS_WINDOW_HEIGHT, style=PROGRESS_WIN_DARK_STYLE, ) with self._window.frame: with ui.VStack(): with ui.HStack(): ui.Spacer(width=ui.Percent(20)) self._progress_bar_area = ui.VStack() self._build_progress_bar() ui.Spacer(width=ui.Percent(20)) ui.Spacer(height=5) if self._is_single_frame_mode: self._build_single_frame_capture_timers() else: self._build_multi_frames_capture_timers() self._build_notification_area() with ui.HStack(): with ui.HStack(width=ui.Percent(50)): ui.Spacer() self._ui_pause_button = ui.Button( "Pause", height=0, clicked_fn=self._on_pause_clicked, enabled=self._support_pausing, style=PAUSE_BUTTON_STYLE[style_settings], name="pause", ) with ui.HStack(width=ui.Percent(50)): ui.Spacer(width=15) ui.Button("Cancel", height=0, clicked_fn=self._on_cancel_clicked) ui.Spacer() ui.Spacer() self._window.visible = True self._update_timers() def _on_pause_clicked(self): if self._progress.capture_status == CaptureStatus.CAPTURING and self._ui_pause_button.text == "Pause": self._progress.capture_status = CaptureStatus.PAUSED self._ui_pause_button.text = "Resume" elif self._progress.capture_status == CaptureStatus.PAUSED: self._progress.capture_status = CaptureStatus.CAPTURING self._ui_pause_button.text = "Pause" def _on_cancel_clicked(self): if ( self._progress.capture_status == CaptureStatus.CAPTURING or self._progress.capture_status == CaptureStatus.PAUSED ): self._progress.capture_status = CaptureStatus.CANCELLED def _update_timers(self): if self._is_single_frame_mode: self._ui_elapsed_time.text = self._progress.elapsed_time self._ui_remaining_time.text = self._progress.estimated_time_remaining if self._show_pt_subframes: subframe_count = f"{self._progress.current_subframe}/{self._progress.total_subframes}" self._ui_subframe_count.text = subframe_count self._ui_current_frame_time.text = self._progress.subframe_time self._ui_ave_frame_time.text = self._progress.average_time_per_subframe if self._show_pt_iterations: subframe_count = f"{self._progress.current_subframe}/{self._progress.total_subframes}" self._ui_subframe_count.text = subframe_count iteration_count = f"{self._progress.path_trace_iteration_num}/{self._progress.total_iterations}" self._ui_iteration_count.text = iteration_count self._ui_ave_frame_time.text = self._progress.average_time_per_subframe else: self._ui_elapsed_time.text = self._progress.elapsed_time self._ui_remaining_time.text = self._progress.estimated_time_remaining frame_count_str = f"{self._progress.current_frame_count}/{self._progress.total_frames}" self._ui_frame_count.text = frame_count_str self._ui_current_frame_time.text = self._progress.current_frame_time if self._show_pt_subframes: subframes_str = f"{self._progress.path_trace_subframe_num}/{self._progress.total_subframes}" self._ui_pt_subframes.text = subframes_str if self._show_pt_iterations: subframes_str = f"{self._progress.path_trace_subframe_num}/{self._progress.total_subframes}" self._ui_pt_subframes.text = subframes_str iter_str = f"{self._progress.path_trace_iteration_num}/{self._progress.total_iterations}" self._ui_pt_iterations.text = iter_str self._ui_ave_frame_time.text = self._progress.average_frame_time self._ui_encoding_time.text = self._progress.encoding_time def _update_notification(self): if self._progress.capture_status == CaptureStatus.CAPTURING: if self._progress.is_prerolling(): msg = 'Running preroll frames {}/{}, please wait...'.format( self._progress.prerolled_frames, self._progress.total_preroll_frames ) self._notification.text = msg elif not self._is_single_frame_mode: if self._progress.is_handling_settle_latency_frames: msg = 'Running settle latency frames {}/{}...'.format( self._progress.settle_latency_frames_done, self._progress.total_settle_latency_frames ) self._notification.text = msg else: self._notification.text = f"Capturing frame {self._progress.current_frame_count}..." elif self._progress.capture_status == CaptureStatus.ENCODING: self._notification.text = "Encoding..." else: self._notification.text = "" def _on_update(self, event): self._update_notification() self._update_timers() self._progress_bar_len = ( PROGRESS_BAR_WIDTH - PROGRESS_BAR_HEIGHT ) * self._progress.progress + PROGRESS_BAR_HALF_HEIGHT self._build_progress_bar()
24,530
Python
40.648557
147
0.605014
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/extension.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os import math import time import datetime import asyncio import omni.ext import carb import omni.kit.app import omni.timeline import omni.usd import omni.ui from pxr import Gf, Sdf from .capture_options import * from .capture_progress import * from .video_generation import VideoGenerationHelper from .helper import ( get_num_pattern_file_path, check_render_product_ext_availability, is_valid_render_product_prim_path, RenderProductCaptureHelper, is_kit_104_and_above, # TODO: Remove this as it is no longer used, but kept only if transitively depended on get_vp_object_visibility, set_vp_object_visibility, ) from omni.kit.viewport.utility import get_active_viewport, capture_viewport_to_file import omni.appwindow PERSISTENT_SETTINGS_PREFIX = "/persistent" FILL_VIEWPORT_SETTING = PERSISTENT_SETTINGS_PREFIX + "/app/viewport/{viewport_api_id}/fillViewport" SEQUENCE_CAPTURE_WAIT = "/app/captureSequence/waitFrames" MP4_ENCODING_BITRATE_SETTING = "/exts/omni.videoencoding/bitrate" MP4_ENCODING_IFRAME_INTERVAL_SETTING = "/exts/omni.videoencoding/iframeinterval" MP4_ENCODING_PRESET_SETTING = "/exts/omni.videoencoding/preset" MP4_ENCODING_PROFILE_SETTING = "/exts/omni.videoencoding/profile" MP4_ENCODING_RC_MODE_SETTING = "/exts/omni.videoencoding/rcMode" MP4_ENCODING_RC_TARGET_QUALITY_SETTING = "/exts/omni.videoencoding/rcTargetQuality" MP4_ENCODING_VIDEO_FULL_RANGE_SETTING = "/exts/omni.videoencoding/videoFullRangeFlag" VIDEO_FRAMES_DIR_NAME = "frames" DEFAULT_IMAGE_FRAME_TYPE_FOR_VIDEO = ".png" capture_instance = None class RenderStatus(IntEnum): # Note render status values from rtx/hydra/HydraRenderResults.h # Rendering was successful. A path tracer might not have reached a stopping criterion though. eSuccess = 0 # Rendering was successful and the renderer has reached a stopping criterion on this iteration. eStopCriterionJustReached = 1 # Rendering was successful and the renderer has reached a stopping criterion. eStopCriterionReached = 2 # Rendering failed eFailed = 3 class CaptureExtension(omni.ext.IExt): def on_startup(self): global capture_instance capture_instance = self self._options = CaptureOptions() self._progress = CaptureProgress() self._progress_window = CaptureProgressWindow() import omni.renderer_capture self._renderer = omni.renderer_capture.acquire_renderer_capture_interface() self._viewport_api = None self._app = omni.kit.app.get_app_interface() self._timeline = omni.timeline.get_timeline_interface() self._usd_context = omni.usd.get_context() self._selection = self._usd_context.get_selection() self._settings = carb.settings.get_settings() self._show_default_progress_window = True self._progress_update_fn = None self._forward_one_frame_fn = None self._capture_finished_fn = None self._to_capture_render_product = False self._render_product_path_for_capture = "" self._is_adaptivesampling_stop_criterion_reached = False class ReshadeUpdateState(): PRE_CAPTURE = 0 POST_CAPTURE = 1 POST_CAPTURE_READY = 3 def on_shutdown(self): self._progress = None self._progress_window = None global capture_instance capture_instance = None @property def options(self): return self._options @options.setter def options(self, value): self._options = value @property def progress(self): return self._progress @property def show_default_progress_window(self): return self._show_default_progress_window @show_default_progress_window.setter def show_default_progress_window(self, value): self._show_default_progress_window = value @property def progress_update_fn(self): return self._progress_update_fn @progress_update_fn.setter def progress_update_fn(self, value): self._progress_update_fn = value @property def forward_one_frame_fn(self): return self._forward_one_frame_fn @forward_one_frame_fn.setter def forward_one_frame_fn(self, value): self._forward_one_frame_fn = value @property def capture_finished_fn(self): return self._capture_finished_fn @capture_finished_fn.setter def capture_finished_fn(self, value): self._capture_finished_fn = value def start(self): self._to_capture_render_product = self._check_if_to_capture_render_product() if self._to_capture_render_product: self._render_product_path_for_capture = RenderProductCaptureHelper.prepare_render_product_for_capture( self._options.render_product, self._options.camera, Gf.Vec2i(self._options.res_width, self._options.res_height) ) if len(self._render_product_path_for_capture) == 0: carb.log_warn(f"Capture will use render product {self._options.render_product}'s original camera and resolution because it failed to make a copy of it for processing.") self._render_product_path_for_capture = self._options.render_product # use usd time code for animation play during capture, caption option's fps setting for movie encoding if CaptureOptions.INVALID_ANIMATION_FPS == self._options.animation_fps: self._capture_fps = self._timeline.get_time_codes_per_seconds() else: self._capture_fps = self._options.animation_fps if not self._prepare_folder_and_counters(): if self._render_product_path_for_capture != self._options.render_product: RenderProductCaptureHelper.remove_render_product_for_capture(self._render_product_path_for_capture) self._render_product_path_for_capture = "" return if self._prepare_viewport(): self._start_internal() def pause(self): if self._progress.capture_status == CaptureStatus.CAPTURING and self._ui_pause_button.text == "Pause": self._progress.capture_status = CaptureStatus.PAUSED def resume(self): if self._progress.capture_status == CaptureStatus.PAUSED: self._progress.capture_status = CaptureStatus.CAPTURING def cancel(self): if ( self._progress.capture_status == CaptureStatus.CAPTURING or self._progress.capture_status == CaptureStatus.PAUSED ): self._progress.capture_status = CaptureStatus.CANCELLED def _update_progress_hook(self): if self._progress_update_fn is not None: self._progress_update_fn( self._progress.capture_status, self._progress.progress, self._progress.elapsed_time, self._progress.estimated_time_remaining, self._progress.current_frame_time, self._progress.average_frame_time, self._progress.encoding_time, self._frame_counter, self._total_frame_count, ) def _get_index_for_image(self, dir, file_name, image_suffix): def is_int(string_val): try: v = int(string_val) return True except: return False images = os.listdir(dir) name_len = len(file_name) suffix_len = len(image_suffix) max_index = 0 for item in images: if item.startswith(file_name) and item.endswith(image_suffix): num_part = item[name_len : (len(item) - suffix_len)] if is_int(num_part): num = int(num_part) if max_index < num: max_index = num return max_index + 1 def _float_to_time(self, ft): hour = int(ft) ft = (ft - hour) * 60 minute = int(ft) ft = (ft - minute) * 60 second = int(ft) ft = (ft - second) * 1000000 microsecond = int(ft) return datetime.time(hour, minute, second, microsecond) def _check_if_to_capture_render_product(self): if len(self._options.render_product) == 0: return False omnigraph_exts_available = check_render_product_ext_availability() if not omnigraph_exts_available: carb.log_warn(f"Viewport Capture: unable to capture with render product {self._options.render_product} as it needs both omni.graph.nodes and omni.graph.examples.cpp enabled to work.") return False viewport_api = get_active_viewport() render_product_name = viewport_api.render_product_path if viewport_api else None if not render_product_name: carb.log_warn(f"Viewport Capture: unable to capture with render product {self._options.render_product} as Kit SDK needs updating to support viewport window render product APIs: {e}") return False if is_valid_render_product_prim_path(self._options.render_product): return True else: carb.log_warn(f"Viewport Capture: unable to capture with render product {self._options.render_product} as it's not a valid Render Product prim path") return False def _is_environment_sunstudy_player(self): if self._options.sunstudy_player is not None: return type(self._options.sunstudy_player).__module__ == "omni.kit.environment.core.sunstudy_player.player" else: carb.log_warn("Sunstudy player type check is valid only when the player is available.") return False def _update_sunstudy_player_time(self): if self._is_environment_sunstudy_player(): self._options.sunstudy_player.current_time = self._sunstudy_current_time else: self._options.sunstudy_player.update_time(self._sunstudy_current_time) def _set_sunstudy_player_time(self, current_time): if self._is_environment_sunstudy_player(): self._options.sunstudy_player.current_time = current_time else: date_time = self._options.sunstudy_player.get_date_time() time_to_set = self._float_to_time(current_time) new_date_time = datetime.datetime( date_time.year, date_time.month, date_time.day, time_to_set.hour, time_to_set.minute, time_to_set.second ) self._options.sunstudy_player.set_date_time(new_date_time) def _prepare_sunstudy_counters(self): self._total_frame_count = self._options.fps * self._options.sunstudy_movie_length_in_seconds duration = self._options.sunstudy_end_time - self._options.sunstudy_start_time self._sunstudy_iterations_per_frame = self._options.ptmb_subframes_per_frame self._sunstudy_delta_time_per_iteration = duration / float(self._total_frame_count * self._sunstudy_iterations_per_frame) self._sunstudy_current_time = self._options.sunstudy_start_time self._set_sunstudy_player_time(self._sunstudy_current_time) def _prepare_folder_and_counters(self): self._workset_dir = self._options.output_folder if not self._make_sure_directory_writeable(self._workset_dir): carb.log_warn(f"Capture failed due to unable to create folder {self._workset_dir} or this folder is not writeable.") self._finish() return False if self._options.is_capturing_nth_frames(): if self._options.capture_every_Nth_frames == 1: frames_folder = self._options.file_name + "_frames" else: frames_folder = self._options.file_name + "_" + str(self._options.capture_every_Nth_frames) + "th_frames" self._nth_frames_dir = os.path.join(self._workset_dir, frames_folder) if not self._make_sure_directory_existed(self._nth_frames_dir): carb.log_warn(f"Capture failed due to unable to create folder {self._nth_frames_dir}") self._finish() return False if self._options.is_video(): self._frames_dir = os.path.join(self._workset_dir, self._options.file_name + "_" + VIDEO_FRAMES_DIR_NAME) if not self._make_sure_directory_existed(self._frames_dir): carb.log_warn( f"Capture failed due to unable to create folder {self._workset_dir} to save frames of the video." ) self._finish() return False self._video_name = self._options.get_full_path() self._frame_pattern_prefix = os.path.join(self._frames_dir, self._options.file_name) if self._options.is_capturing_frame(): self._start_time = float(self._options.start_frame) / self._capture_fps self._end_time = float(self._options.end_frame + 1) / self._capture_fps self._time = self._start_time self._frame = self._options.start_frame self._start_number = self._frame self._total_frame_count = round((self._end_time - self._start_time) * self._capture_fps) else: self._start_time = self._options.start_time self._end_time = self._options.end_time self._time = self._options.start_time self._frame = int(self._options.start_time * self._capture_fps) self._start_number = self._frame self._total_frame_count = math.ceil((self._end_time - self._start_time) * self._capture_fps) if self._options.movie_type == CaptureMovieType.SUNSTUDY: self._prepare_sunstudy_counters() else: if self._options.is_capturing_nth_frames(): self._frame_pattern_prefix = self._nth_frames_dir if self._options.is_capturing_frame(): self._start_time = float(self._options.start_frame) / self._capture_fps self._end_time = float(self._options.end_frame + 1) / self._capture_fps self._time = self._start_time self._frame = self._options.start_frame self._start_number = self._frame self._total_frame_count = round((self._end_time - self._start_time) * self._capture_fps) else: self._start_time = self._options.start_time self._end_time = self._options.end_time self._time = self._options.start_time self._frame = int(self._options.start_time * self._capture_fps) self._start_number = self._frame self._total_frame_count = math.ceil((self._end_time - self._start_time) * self._capture_fps) if self._options.movie_type == CaptureMovieType.SUNSTUDY: self._prepare_sunstudy_counters() else: index = self._get_index_for_image(self._workset_dir, self._options.file_name, self._options.file_type) self._frame_pattern_prefix = os.path.join(self._workset_dir, self._options.file_name + str(index)) self._start_time = self._timeline.get_current_time() self._end_time = self._timeline.get_current_time() self._time = self._timeline.get_current_time() self._frame = 1 self._start_number = self._frame self._total_frame_count = 1 self._subframe = 0 self._sample_count = 0 self._frame_counter = 0 self._real_time_settle_latency_frames_done = 0 self._settle_latency_frames = self._get_settle_latency_frames() self._last_skipped_frame_path = "" self._path_trace_iterations = 0 self._time_rate = 1.0 / self._capture_fps self._time_subframe_rate = ( self._time_rate * (self._options.ptmb_fsc - self._options.ptmb_fso) / self._options.ptmb_subframes_per_frame ) return True def _prepare_viewport(self): viewport_api = get_active_viewport() if viewport_api is None: return False self._is_legacy_vp = hasattr(viewport_api, 'legacy_window') self._record_current_window_status(viewport_api) capture_camera = Sdf.Path(self._options.camera) if capture_camera != self._saved_camera: viewport_api.camera_path = capture_camera if not self._is_legacy_vp: viewport_api.updates_enabled = True if self._saved_fill_viewport_option: fv_setting_path = FILL_VIEWPORT_SETTING.format(viewport_api_id=viewport_api.id) # for application level capture, we want it to fill the viewport to make the viewport resolution the same to application window resolution # while for viewport capture, we can get images with the correct resolution so doesn't need it to fill viewport self._settings.set(fv_setting_path, self._options.app_level_capture) capture_resolution = (self._options.res_width, self._options.res_height) if capture_resolution != (self._saved_resolution_width, self._saved_resolution_height): viewport_api.resolution = capture_resolution self._settings.set_bool("/persistent/app/captureFrame/viewport", True) self._settings.set_bool("/app/captureFrame/setAlphaTo1", not self._options.save_alpha) if self._options.file_type == ".exr": self._settings.set_bool("/app/captureFrame/hdr", self._options.hdr_output) else: self._settings.set_bool("/app/captureFrame/hdr", False) if self._options.save_alpha: self._settings.set_bool("/rtx/post/backgroundZeroAlpha/enabled", True) self._settings.set_bool("/rtx/post/backgroundZeroAlpha/backgroundComposite", False) if self._options.hdr_output: self._settings.set_bool("/rtx/post/backgroundZeroAlpha/ApplyAlphaZeroPassFirst", True) if self._to_capture_render_product: viewport_api.render_product_path = self._render_product_path_for_capture # we only clear selection for non application level capture, other we will lose the ui.scene elemets during capture if not self._options.app_level_capture: self._selection.clear_selected_prim_paths() if self._options.render_preset == CaptureRenderPreset.RAY_TRACE: self._switch_renderer = self._saved_hd_engine != "rtx" or self._saved_render_mode != "RaytracedLighting" if self._switch_renderer: viewport_api.set_hd_engine("rtx", "RaytracedLighting") carb.log_info("Switching to RayTracing Mode") elif self._options.render_preset == CaptureRenderPreset.PATH_TRACE: self._switch_renderer = self._saved_hd_engine != "rtx" or self._saved_render_mode != "PathTracing" if self._switch_renderer: viewport_api.set_hd_engine("rtx", "PathTracing") carb.log_info("Switching to PathTracing Mode") elif self._options.render_preset == CaptureRenderPreset.IRAY: self._switch_renderer = self._saved_hd_engine != "iray" or self._saved_render_mode != "iray" if self._switch_renderer: viewport_api.set_hd_engine("iray", "iray") carb.log_info("Switching to IRay Mode") # now that Iray is not loaded automatically until renderer gets switched # we have to save and set the Iray settings after the renderer switch self._record_and_set_iray_settings() else: self._switch_renderer = False carb.log_info("Keeping current Render Mode") if self._options.debug_material_type == CaptureDebugMaterialType.SHADED: self._settings.set_int("/rtx/debugMaterialType", -1) elif self._options.debug_material_type == CaptureDebugMaterialType.WHITE: self._settings.set_int("/rtx/debugMaterialType", 0) else: carb.log_info("Keeping current debug mateiral type") # tell timeline window to stop force checks of end time so that it won't affect capture range self._settings.set_bool("/exts/omni.anim.window.timeline/playinRange", False) # set it to 0 to ensure we accumulate as many samples as requested even across subframes (for motion blur) # for non-motion blur path trace capture, we now rely on adaptive sampling's return status to decide if it's still # need to do more samples if self._is_capturing_pt_mb(): self._settings.set_int("/rtx/pathtracing/totalSpp", 0) # don't show light and grid during capturing self._set_vp_object_settings(viewport_api) # disable async rendering for capture, otherwise it won't capture images correctly if self._saved_async_rendering: self._settings.set_bool("/app/asyncRendering", False) if self._saved_async_renderingLatency: self._settings.set_bool("/app/asyncRenderingLowLatency", False) # Rendering to some image buffers additionally require explicitly setting `set_capture_sync(True)`, on top of # disabling the `/app/asyncRendering` setting. This can otherwise cause images to hold corrupted buffer # information by erroneously assuming a complete image buffer is available when only a first partial subframe # has been renderer (as in the case of EXR): self._renderer.set_capture_sync( self._options.file_type == ".exr" ) # frames to wait for the async settings above to be ready, they will need to be detected by viewport, and # then viewport will notify the renderer not to do async rendering self._frames_to_disable_async_rendering = 2 # Normally avoid using a high /rtx/pathtracing/spp setting since it causes GPU # timeouts for large sample counts. But a value larger than 1 can be useful in Multi-GPU setups self._settings.set_int( "/rtx/pathtracing/spp", min(self._options.spp_per_iteration, self._options.path_trace_spp) ) # Setting resetPtAccumOnlyWhenExternalFrameCounterChanges ensures we control accumulation explicitly # by simpling changing the /rtx/externalFrameCounter value self._settings.set_bool("/rtx-transient/resetPtAccumOnlyWhenExternalFrameCounterChanges", True) # Enable syncLoads in materialDB and Hydra. This is needed to make sure texture updates finish before we start the rendering self._settings.set("/rtx/materialDb/syncLoads", True) self._settings.set("/rtx/hydra/materialSyncLoads", True) self._settings.set("/rtx-transient/resourcemanager/texturestreaming/async", False) self._settings.set("/rtx-transient/resourcemanager/texturestreaming/streamingBudgetMB", 0) self._settings.set("/rtx-transient/samplerFeedbackTileSize", 1) self._settings.set("/rtx-transient/resourcemanager/texturestreaming/evictionFrameLatency", 0) #for now, reshade needs to be turned off and on again to apply settings self._settings.set_bool("/rtx/reshade/enable", False) #need to skip several updates for reshade settings to apply: self._frames_to_apply_reshade = 2 # these settings need to be True to ensure XR Output Alpha in composited image is right if not self._saved_output_alpha_in_composite: self._settings.set("/rtx/post/backgroundZeroAlpha/outputAlphaInComposite", True) # do not show the minibar of timeline window self._settings.set("/exts/omni.kit.timeline.minibar/stay_on_playing", False) # enable sequencer camera self._settings.set("/persistent/exts/omni.kit.window.sequencer/useSequencerCamera", True) # set timeline animation fps if self._capture_fps != self._saved_timeline_fps: self._timeline.set_time_codes_per_second(self._capture_fps) # return success return True def _show_progress_window(self): return ( self._options.is_video() or self._options.is_capturing_nth_frames() or (self._options.show_single_frame_progress and self._options.is_capturing_pathtracing_single_frame()) ) and self.show_default_progress_window def _start_internal(self): # if we want preroll, then set timeline's current time back with the preroll frames' time, # and rely on timeline to do the preroll using the give timecode if self._options.preroll_frames > 0: self._timeline.set_current_time(self._start_time - self._options.preroll_frames / self._capture_fps) else: self._timeline.set_current_time(self._start_time) # initialize Reshade state for update loop self._reshade_switch_state = self.ReshadeUpdateState.PRE_CAPTURE # change timeline to be in play state self._timeline.play(start_timecode=self._start_time*self._capture_fps, end_timecode=self._end_time*self._capture_fps, looping=False) # disable automatic time update in timeline so that movie capture tool can control time step self._timeline.set_auto_update(False) self._update_sub = ( omni.kit.app.get_app().get_update_event_stream().create_subscription_to_pop(self._on_update, order=1000000) ) self._is_adaptivesampling_stop_criterion_reached = False self._progress.start_capturing(self._total_frame_count, self._options.preroll_frames) # always show single frame capture progress for PT mode self._options.show_single_frame_progress = True if self._show_progress_window(): self._progress_window.show( self._progress, self._options.is_capturing_pathtracing_single_frame(), show_pt_subframes=self._options.render_preset == CaptureRenderPreset.PATH_TRACE, show_pt_iterations=self._options.render_preset == CaptureRenderPreset.IRAY ) # prepare for application level capture if self._options.app_level_capture: # move the progress window to external window, and then hide application UI if self._show_progress_window(): self._progress_window.move_to_external_window() self._settings.set("/app/window/hideUi", True) def _record_and_set_iray_settings(self): if self._options.render_preset == CaptureRenderPreset.IRAY: self._saved_iray_sample_limit = self._settings.get_as_int("/rtx/iray/progressive_rendering_max_samples") self._settings.set("/rtx/iray/progressive_rendering_max_samples", self._options.path_trace_spp) self._saved_iray_render_sync_flag = self._settings.get_as_bool("/iray/render_synchronous") if not self._saved_iray_render_sync_flag: self._settings.set_bool("/iray/render_synchronous", True) def _restore_iray_settings(self): if self._options.render_preset == CaptureRenderPreset.IRAY: self._settings.set_bool("/iray/render_synchronous", self._saved_iray_render_sync_flag) self._settings.set("/rtx/iray/progressive_rendering_max_samples", self._saved_iray_sample_limit) def __save_mp4_encoding_settings(self): self._saved_mp4_encoding_bitrate = self._settings.get_as_int(MP4_ENCODING_BITRATE_SETTING) self._saved_mp4_encoding_iframe_interval = self._settings.get_as_int(MP4_ENCODING_IFRAME_INTERVAL_SETTING) self._saved_mp4_encoding_preset = self._settings.get(MP4_ENCODING_PRESET_SETTING) self._saved_mp4_encoding_profile = self._settings.get(MP4_ENCODING_PROFILE_SETTING) self._saved_mp4_encoding_rc_mode = self._settings.get(MP4_ENCODING_RC_MODE_SETTING) self._saved_mp4_encoding_rc_target_quality = self._settings.get(MP4_ENCODING_RC_TARGET_QUALITY_SETTING) self._saved_mp4_encoding_video_full_range_flag = self._settings.get(MP4_ENCODING_VIDEO_FULL_RANGE_SETTING) def __set_mp4_encoding_settings(self): self._settings.set(MP4_ENCODING_BITRATE_SETTING, self._options.mp4_encoding_bitrate) self._settings.set(MP4_ENCODING_IFRAME_INTERVAL_SETTING, self._options.mp4_encoding_iframe_interval) self._settings.set(MP4_ENCODING_PRESET_SETTING, self._options.mp4_encoding_preset) self._settings.set(MP4_ENCODING_PROFILE_SETTING, self._options.mp4_encoding_profile) self._settings.set(MP4_ENCODING_RC_MODE_SETTING, self._options.mp4_encoding_rc_mode) self._settings.set(MP4_ENCODING_RC_TARGET_QUALITY_SETTING, self._options.mp4_encoding_rc_target_quality) self._settings.set(MP4_ENCODING_VIDEO_FULL_RANGE_SETTING, self._options.mp4_encoding_video_full_range_flag) def _save_and_set_mp4_encoding_settings(self): if self._options.is_video(): self.__save_mp4_encoding_settings() self.__set_mp4_encoding_settings() def _restore_mp4_encoding_settings(self): if self._options.is_video(): self._settings.set(MP4_ENCODING_BITRATE_SETTING, self._saved_mp4_encoding_bitrate) self._settings.set(MP4_ENCODING_IFRAME_INTERVAL_SETTING, self._saved_mp4_encoding_iframe_interval) self._settings.set(MP4_ENCODING_PRESET_SETTING, self._saved_mp4_encoding_preset) self._settings.set(MP4_ENCODING_PROFILE_SETTING, self._saved_mp4_encoding_profile) self._settings.set(MP4_ENCODING_RC_MODE_SETTING, self._saved_mp4_encoding_rc_mode) self._settings.set(MP4_ENCODING_RC_TARGET_QUALITY_SETTING, self._saved_mp4_encoding_rc_target_quality) self._settings.set(MP4_ENCODING_VIDEO_FULL_RANGE_SETTING, self._saved_mp4_encoding_video_full_range_flag) def _save_and_set_application_capture_settings(self): # as in application capture mode, we actually capture the window size instead of the renderer output, thus we do this with two steps: # 1. set it to fill the viewport, and padding to (0, -1) to make viewport's size equals to application window size # 2. resize application window to the resolution that users set in movie capture, so that we can save the images with the desired resolution # this is not ideal because when we resize the application window, the size is actaully limited by the screen resolution so it's possible that # the resulting window size could be smaller than what we want. # also, it's more intuitive that padding should be (0, 0), but it has to be (0, -1) after tests as we still have 1 pixel left at top and bottom. if self._options.app_level_capture: vp_window = omni.ui.Workspace.get_window("Viewport") self._saved_viewport_padding_x = vp_window.padding_x self._saved_viewport_padding_y = vp_window.padding_y vp_window.padding_x = 0 vp_window.padding_y = -1 app_window_factory = omni.appwindow.acquire_app_window_factory_interface() app_window = app_window_factory.get_app_window() self._saved_app_window_size = app_window.get_size() app_window.resize(self._options.res_width, self._options._res_height) def _restore_application_capture_settings(self): if self._options.app_level_capture: vp_window = omni.ui.Workspace.get_window("Viewport") vp_window.padding_x = self._saved_viewport_padding_x vp_window.padding_y = self._saved_viewport_padding_y app_window_factory = omni.appwindow.acquire_app_window_factory_interface() app_window = app_window_factory.get_app_window() app_window.resize(self._saved_app_window_size[0], self._saved_app_window_size[1]) def _record_vp_object_settings(self, viewport_api) -> None: self._saved_display_outline = get_vp_object_visibility(viewport_api, "guide/selection") self._saved_display_lights = get_vp_object_visibility(viewport_api, "scene/lights") self._saved_display_audio = get_vp_object_visibility(viewport_api, "scene/audio") self._saved_display_camera = get_vp_object_visibility(viewport_api, "scene/cameras") self._saved_display_grid = get_vp_object_visibility(viewport_api, "guide/grid") def _set_vp_object_settings(self, viewport_api) -> None: set_vp_object_visibility(viewport_api, "guide/selection", False) set_vp_object_visibility(viewport_api, "scene/lights", False) set_vp_object_visibility(viewport_api, "scene/audio", False) set_vp_object_visibility(viewport_api, "scene/cameras", False) set_vp_object_visibility(viewport_api, "guide/grid", False) def _restore_vp_object_settings(self, viewport_api): set_vp_object_visibility(viewport_api, "guide/selection", self._saved_display_outline) set_vp_object_visibility(viewport_api, "scene/lights", self._saved_display_lights) set_vp_object_visibility(viewport_api, "scene/audio", self._saved_display_audio) set_vp_object_visibility(viewport_api, "scene/cameras", self._saved_display_camera) set_vp_object_visibility(viewport_api, "guide/grid", self._saved_display_grid) def _record_current_window_status(self, viewport_api): assert viewport_api is not None, "No viewport to record to" self._viewport_api = viewport_api self._saved_camera = viewport_api.camera_path self._saved_hydra_engine = viewport_api.hydra_engine if not self._is_legacy_vp: self._saved_vp_updates_enabled = self._viewport_api.updates_enabled fv_setting_path = FILL_VIEWPORT_SETTING.format(viewport_api_id=self._viewport_api.id) self._saved_fill_viewport_option = self._settings.get_as_bool(fv_setting_path) resolution = viewport_api.resolution self._saved_resolution_width = int(resolution[0]) self._saved_resolution_height = int(resolution[1]) self._saved_hd_engine = viewport_api.hydra_engine self._saved_render_mode = viewport_api.render_mode self._saved_capture_frame_viewport = self._settings.get("/persistent/app/captureFrame/viewport") self._saved_debug_material_type = self._settings.get_as_int("/rtx/debugMaterialType") self._saved_total_spp = self._settings.get_as_int("/rtx/pathtracing/totalSpp") self._saved_spp = self._settings.get_as_int("/rtx/pathtracing/spp") self._saved_reset_pt_accum_only = self._settings.get("/rtx-transient/resetPtAccumOnlyWhenExternalFrameCounterChanges") self._record_vp_object_settings(viewport_api) self._saved_async_rendering = self._settings.get("/app/asyncRendering") self._saved_async_renderingLatency = self._settings.get("/app/asyncRenderingLowLatency") self._saved_background_zero_alpha = self._settings.get("/rtx/post/backgroundZeroAlpha/enabled") self._saved_background_zero_alpha_comp = self._settings.get("/rtx/post/backgroundZeroAlpha/backgroundComposite") self._saved_background_zero_alpha_zp_first = self._settings.get( "/rtx/post/backgroundZeroAlpha/ApplyAlphaZeroPassFirst" ) if self._options.movie_type == CaptureMovieType.SUNSTUDY: self._saved_sunstudy_current_time = self._options.sunstudy_current_time self._saved_timeline_current_time = self._timeline.get_current_time() self._saved_timeline_fps = self._timeline.get_time_codes_per_seconds() self._saved_rtx_sync_load_setting = self._settings.get("/rtx/materialDb/syncLoads") if self._to_capture_render_product: self._saved_render_product = viewport_api.render_product_path omnigraph_use_legacy_sim_setting = self._settings.get_as_bool("/persistent/omnigraph/useLegacySimulationPipeline") if omnigraph_use_legacy_sim_setting is not None and omnigraph_use_legacy_sim_setting is True: carb.log_warn("/persistent/omnigraph/useLegacySimulationPipeline setting is True, which might affect render product capture and cause the capture to have no output.") self._saved_hydra_sync_load_setting = self._settings.get("/rtx/hydra/materialSyncLoads") self._saved_async_texture_streaming = self._settings.get("/rtx-transient/resourcemanager/texturestreaming/async") self._saved_texture_streaming_budget = self._settings.get("/rtx-transient/resourcemanager/texturestreaming/streamingBudgetMB") self._saved_sampler_feedback_tile_size = self._settings.get_as_int("/rtx-transient/samplerFeedbackTileSize") self._saved_texture_streaming_eviction_frame_latency = self._settings.get_as_int("/rtx-transient/resourcemanager/texturestreaming/evictionFrameLatency") # save Reshade state in post process settings self._saved_reshade_state = bool(self._settings.get("/rtx/reshade/enable")) self._saved_output_alpha_in_composite = self._settings.get_as_bool("/rtx/post/backgroundZeroAlpha/outputAlphaInComposite") # save the visibility status of timeline window's minibar added in OM-92643 self._saved_timeline_window_mimibar_visibility = self._settings.get_as_bool("/exts/omni.kit.timeline.minibar/stay_on_playing") # save the setting for sequencer camera, we want to enable it during capture self._saved_use_sequencer_camera = self._settings.get_as_bool("/persistent/exts/omni.kit.window.sequencer/useSequencerCamera") # if to capture mp4, save encoding settings self._save_and_set_mp4_encoding_settings() # if to capture in application mode, save viewport's padding values as we will reset it to make resolution of final image match what users set as possible as we can self._save_and_set_application_capture_settings() def _restore_window_status(self): viewport_api, self._viewport_api = self._viewport_api, None assert viewport_api is not None, "No viewport to restore to" if not self._is_legacy_vp and not self._saved_vp_updates_enabled: viewport_api.updates_enabled = self._saved_vp_updates_enabled if not self._is_legacy_vp and self._saved_fill_viewport_option: fv_setting_path = FILL_VIEWPORT_SETTING.format(viewport_api_id=viewport_api.id) self._settings.set(fv_setting_path, self._saved_fill_viewport_option) viewport_api.camera_path = self._saved_camera viewport_api.resolution = (self._saved_resolution_width, self._saved_resolution_height) if self._switch_renderer: viewport_api.set_hd_engine(self._saved_hydra_engine, self._saved_render_mode) self._settings.set_bool("/persistent/app/captureFrame/viewport", self._saved_capture_frame_viewport) self._settings.set_int("/rtx/debugMaterialType", self._saved_debug_material_type) self._settings.set_int("/rtx/pathtracing/totalSpp", self._saved_total_spp) self._settings.set_int("/rtx/pathtracing/spp", self._saved_spp) self._settings.set_bool("/rtx-transient/resetPtAccumOnlyWhenExternalFrameCounterChanges", self._saved_reset_pt_accum_only) self._restore_vp_object_settings(viewport_api) self._settings.set_bool("/app/asyncRendering", self._saved_async_rendering) self._settings.set_bool("/app/asyncRenderingLowLatency", self._saved_async_renderingLatency) self._renderer.set_capture_sync(not self._saved_async_rendering) self._settings.set_bool("/rtx/post/backgroundZeroAlpha/enabled", self._saved_background_zero_alpha) self._settings.set_bool( "/rtx/post/backgroundZeroAlpha/backgroundComposite", self._saved_background_zero_alpha_comp ) self._settings.set_bool( "/rtx/post/backgroundZeroAlpha/ApplyAlphaZeroPassFirst", self._saved_background_zero_alpha_zp_first ) self._restore_iray_settings() if self._options.movie_type == CaptureMovieType.SUNSTUDY: self._set_sunstudy_player_time(self._saved_sunstudy_current_time) self._settings.set("/rtx/materialDb/syncLoads", self._saved_rtx_sync_load_setting) self._settings.set("/rtx/hydra/materialSyncLoads", self._saved_hydra_sync_load_setting) self._settings.set("/rtx-transient/resourcemanager/texturestreaming/async", self._saved_async_texture_streaming) self._settings.set("/rtx-transient/resourcemanager/texturestreaming/streamingBudgetMB", self._saved_texture_streaming_budget) self._settings.set("/rtx-transient/samplerFeedbackTileSize", self._saved_sampler_feedback_tile_size) self._settings.set("/rtx-transient/resourcemanager/texturestreaming/evictionFrameLatency", self._saved_texture_streaming_eviction_frame_latency) self._settings.set("/app/captureFrame/hdr", False) # tell timeline window it can restart force checks of end time self._settings.set_bool("/exts/omni.anim.window.timeline/playinRange", True) if self._to_capture_render_product: viewport_api.render_product_path = self._saved_render_product # set Reshade to its initial value it had before te capture: self._settings.set("/rtx/reshade/enable", self._saved_reshade_state) # set Reshade update loop state to initial value, so we're ready for the next run of the update loop: self._reshade_switch_state = self.ReshadeUpdateState.PRE_CAPTURE self._settings.set("/rtx/post/backgroundZeroAlpha/outputAlphaInComposite", self._saved_output_alpha_in_composite) if self._saved_timeline_window_mimibar_visibility: self._setting.set("/exts/omni.kit.timeline.minibar/stay_on_playing", self._saved_timeline_window_mimibar_visibility) self._settings.set("/persistent/exts/omni.kit.window.sequencer/useSequencerCamera", self._saved_use_sequencer_camera) # if to capture mp4, restore encoding settings self._restore_mp4_encoding_settings() # if to capture in application mode, restore viewport's padding values self._restore_application_capture_settings() def _clean_pngs_in_directory(self, directory): self._clean_files_in_directory(directory, ".png") def _clean_files_in_directory(self, directory, suffix): images = os.listdir(directory) for item in images: if item.endswith(suffix): os.remove(os.path.join(directory, item)) def _make_sure_directory_existed(self, directory): if not os.path.exists(directory): try: os.makedirs(directory, exist_ok=True) except OSError as error: carb.log_warn(f"Directory cannot be created: {dir}") return False return True def _make_sure_directory_writeable(self, directory): if not self._make_sure_directory_existed(directory): return False # if the directory exists, try to create a test folder and then remove it to check if it's writeable # Normally this should be done using omni.client.stat api, unfortunately it won't work well if the # give folder is a read-only one mapped by O Drive. try: test_folder_name = "(@m#C$%^)((test^file$@@).testfile" full_test_path = os.path.join(directory, test_folder_name) f = open(full_test_path, "a") f.close() os.remove(full_test_path) except OSError as error: return False return True def _finish(self): if ( self._progress.capture_status == CaptureStatus.FINISHING or self._progress.capture_status == CaptureStatus.CANCELLED ): self._update_sub = None self._restore_window_status() self._sample_count = 0 self._start_number = 0 self._frame_counter = 0 self._path_trace_iterations = 0 self._progress.capture_status = CaptureStatus.NONE # restore timeline settings # stop timeline, but re-enable auto update timeline = self._timeline timeline.set_auto_update(True) timeline.stop() self._timeline.set_current_time(self._saved_timeline_current_time) if self._capture_fps != self._saved_timeline_fps: self._timeline.set_time_codes_per_second(self._saved_timeline_fps) if self._to_capture_render_product and (self._render_product_path_for_capture != self._options.render_product): RenderProductCaptureHelper.remove_render_product_for_capture(self._render_product_path_for_capture) # restore application ui if in application level capture mode if self._options.app_level_capture: self._settings.set("/app/window/hideUi", False) if self._show_progress_window(): self._progress_window.close() if self._capture_finished_fn is not None: self._capture_finished_fn() def _wait_for_image_writing(self, seconds_to_wait: float = 5, seconds_to_sleep: float = 0.1): # wait for the last frame is written to disk # my tests of scenes of different complexity show a range of 0.2 to 1 seconds wait time # so 5 second max time should be enough and we can early quit by checking the last # frame every 0.1 seconds. seconds_tried = 0.0 carb.log_info("Waiting for frames to be ready for encoding.") while seconds_tried < seconds_to_wait: if os.path.isfile(self._frame_path) and os.access(self._frame_path, os.R_OK): break else: time.sleep(seconds_to_sleep) seconds_tried += seconds_to_sleep if seconds_tried >= seconds_to_wait: carb.log_warn(f"Wait time out. To start encoding with images already have.") def _capture_image(self, frame_path: str): if self._options.app_level_capture: self._capture_application(frame_path) else: self._capture_viewport(frame_path) def _capture_application(self, frame_path: str): async def capture_frame(capture_filename: str): try: import omni.renderer_capture renderer_capture = omni.renderer_capture.acquire_renderer_capture_interface() renderer_capture.capture_next_frame_swapchain(capture_filename) carb.log_info(f"Capturing {capture_filename} in application level.") except ImportError: carb.log_error(f"Failed to capture {capture_filename} due to unable to import omni.renderer_capture.") await omni.kit.app.get_app().next_update_async() asyncio.ensure_future(capture_frame(frame_path)) def _capture_viewport(self, frame_path: str): is_hdr = self.options._hdr_output render_product_path = self.options._render_product if self._to_capture_render_product else None format_desc = None if self._options.file_type == ".exr": format_desc = {} format_desc["format"] = "exr" format_desc["compression"] = self._options.exr_compression_method capture_viewport_to_file( self._viewport_api, file_path=frame_path, is_hdr=is_hdr, render_product_path=render_product_path, format_desc=format_desc ) carb.log_info(f"Capturing {frame_path}") def _get_current_frame_output_path(self): frame_path = "" if self._options.is_video(): frame_path = get_num_pattern_file_path( self._frames_dir, self._options.file_name, self._options.file_name_num_pattern, self._frame, DEFAULT_IMAGE_FRAME_TYPE_FOR_VIDEO, self._options.renumber_negative_frame_number_from_0, abs(self._start_number) ) else: if self._options.is_capturing_nth_frames(): if self._frame_counter % self._options.capture_every_Nth_frames == 0: frame_path = get_num_pattern_file_path( self._frame_pattern_prefix, self._options.file_name, self._options.file_name_num_pattern, self._frame, self._options.file_type, self._options.renumber_negative_frame_number_from_0, abs(self._start_number) ) else: frame_path = self._frame_pattern_prefix + self._options.file_type return frame_path def _handle_skipping_frame(self, dt): if not self._options.overwrite_existing_frames: if os.path.exists(self._frame_path): carb.log_warn(f"Frame {self._frame_path} exists, skip it...") self._settings.set_int("/rtx/pathtracing/spp", 1) self._subframe = 0 self._sample_count = 0 self._path_trace_iterations = 0 can_continue = True if self._forward_one_frame_fn is not None: can_continue = self._forward_one_frame_fn(dt) elif self._options.movie_type == CaptureMovieType.SUNSTUDY and \ (self._options.is_video() or self._options.is_capturing_nth_frames()): self._sunstudy_current_time += self._sunstudy_delta_time_per_iteration * self._sunstudy_iterations_per_frame self._update_sunstudy_player_time() else: # movie type is SEQUENCE self._time = self._start_time + (self._frame - self._start_number) * self._time_rate self._timeline.set_current_time(self._time) self._frame += 1 self._frame_counter += 1 # check if capture ends if self._forward_one_frame_fn is not None: if can_continue is False: if self._options.is_video(): self._progress.capture_status = CaptureStatus.TO_START_ENCODING elif self._options.is_capturing_nth_frames(): self._progress.capture_status = CaptureStatus.FINISHING else: if self._time >= self._end_time or self._frame_counter >= self._total_frame_count: if self._options.is_video(): self._progress.capture_status = CaptureStatus.TO_START_ENCODING elif self._options.is_capturing_nth_frames(): self._progress.capture_status = CaptureStatus.FINISHING return True else: if os.path.exists(self._frame_path) and self._last_skipped_frame_path != self._frame_path: carb.log_warn(f"Frame {self._frame_path} will be overwritten.") self._last_skipped_frame_path = self._frame_path return False def _get_default_settle_lateny_frames(self): # to workaround OM-40632, and OM-50514 FRAMES_TO_DELAY_FOR_FRAME_SKIPPING_HACK = 5 if self._options.render_preset == CaptureRenderPreset.RAY_TRACE: return FRAMES_TO_DELAY_FOR_FRAME_SKIPPING_HACK elif ( self._options.render_preset == CaptureRenderPreset.PATH_TRACE or self._options.render_preset == CaptureRenderPreset.IRAY ): pt_frames = self._options.ptmb_subframes_per_frame * self._options.path_trace_spp if pt_frames >= FRAMES_TO_DELAY_FOR_FRAME_SKIPPING_HACK: return 0 else: return FRAMES_TO_DELAY_FOR_FRAME_SKIPPING_HACK - pt_frames else: return 0 def _is_using_default_settle_latency_frames(self): return self._options.real_time_settle_latency_frames == 0 and self._settings.get(SEQUENCE_CAPTURE_WAIT) is None def _get_settle_latency_frames(self): settle_latency_frames = self._options.real_time_settle_latency_frames # Force a delay when capturing a range of frames if settle_latency_frames == 0 and (self._options.is_video() or self._options.is_capturing_nth_frames()): # Allow an explicit default to delay in SEQUENCE_CAPTURE_WAIT, when unset use logic below settle_latency_frames = self._settings.get(SEQUENCE_CAPTURE_WAIT) if settle_latency_frames is None: # Force a 4 frame delay when no sub-frames, otherwise account for sub-frames contributing to that 4 settle_latency_frames = self._get_default_settle_lateny_frames() carb.log_info(f"Forcing {settle_latency_frames} frame delay per frame for sequence capture") return settle_latency_frames def _is_handling_settle_latency_frames(self): return ((self._options.is_video() or self._options.is_capturing_nth_frames()) and self._settle_latency_frames > 0 and self._real_time_settle_latency_frames_done < self._settle_latency_frames ) def _handle_real_time_capture_settle_latency(self): # settle latency only works with sequence capture if not (self._options.is_video() or self._options.is_capturing_nth_frames()): return False if self._settle_latency_frames > 0: self._real_time_settle_latency_frames_done += 1 if self._real_time_settle_latency_frames_done > self._settle_latency_frames: self._real_time_settle_latency_frames_done = 0 return False else: self._subframe = 0 self._sample_count = 0 return True return False def _is_capturing_pt_mb(self): return CaptureRenderPreset.PATH_TRACE == self._options.render_preset and self._options.ptmb_subframes_per_frame > 1 def _is_capturing_pt_no_mb(self): return CaptureRenderPreset.PATH_TRACE == self._options.render_preset and 1 == self._options.ptmb_subframes_per_frame def _is_pt_adaptivesampling_stop_criterion_reached(self): if self._viewport_api is None: return False else: render_status = self._viewport_api.frame_info.get('status') return (render_status is not None and RenderStatus.eStopCriterionReached == render_status and self._is_capturing_pt_no_mb() ) def _on_update(self, e): dt = e.payload["dt"] if self._progress.capture_status == CaptureStatus.FINISHING: # need to turn reshade off, update, and turn on again in _restore_window_status to apply pre-capture resolution if self._reshade_switch_state == self.ReshadeUpdateState.POST_CAPTURE: self._settings.set_bool("/rtx/reshade/enable", False) self._reshade_switch_state = self.ReshadeUpdateState.POST_CAPTURE_READY return self._finish() self._update_progress_hook() elif self._progress.capture_status == CaptureStatus.CANCELLED: # need to turn reshade off, update, and turn on again in _restore_window_status to apply pre-capture resolution if self._reshade_switch_state == self.ReshadeUpdateState.POST_CAPTURE: self._settings.set_bool("/rtx/reshade/enable", False) self._reshade_switch_state = self.ReshadeUpdateState.POST_CAPTURE_READY return carb.log_warn("video recording cancelled") self._update_progress_hook() self._finish() elif self._progress.capture_status == CaptureStatus.ENCODING: if VideoGenerationHelper().encoding_done: self._progress.capture_status = CaptureStatus.FINISHING self._update_progress_hook() self._progress.add_encoding_time(dt) elif self._progress.capture_status == CaptureStatus.TO_START_ENCODING: if VideoGenerationHelper().is_encoding is False: self._wait_for_image_writing() if self._options.renumber_negative_frame_number_from_0 is True and self._start_number < 0: video_frame_start_num = 0 else: video_frame_start_num = self._start_number started = VideoGenerationHelper().generating_video( self._video_name, self._frames_dir, self._options.file_name, self._options.file_name_num_pattern, video_frame_start_num, self._total_frame_count, self._options.fps, ) if started: self._progress.capture_status = CaptureStatus.ENCODING self._update_progress_hook() self._progress.add_encoding_time(dt) else: carb.log_warn("Movie capture failed to encode the capture images.") self._progress.capture_status = CaptureStatus.FINISHING elif self._progress.capture_status == CaptureStatus.CAPTURING: if self._frames_to_disable_async_rendering >= 0: self._frames_to_disable_async_rendering -= 1 return #apply Reshade and skip frames to to pick up capturing resolution if self._reshade_switch_state == self.ReshadeUpdateState.PRE_CAPTURE: self._settings.set_bool("/rtx/reshade/enable", self._saved_reshade_state) # need to skip a couple of updates for Reshade settings to apply: if self._frames_to_apply_reshade>=0: self._frames_to_apply_reshade=self._frames_to_apply_reshade-1 return self._reshade_switch_state = self.ReshadeUpdateState.POST_CAPTURE return if self._progress.is_prerolling(): self._progress.prerolled_frames += 1 self._settings.set_int("/rtx/pathtracing/spp", 1) left_preroll_frames = self._options.preroll_frames - self._progress.prerolled_frames self._timeline.set_current_time(self._start_time - left_preroll_frames / self._capture_fps) return self._frame_path = self._get_current_frame_output_path() if self._handle_skipping_frame(dt): self._progress.add_frame_time(self._frame, dt) self._update_progress_hook() return self._settings.set_int( "/rtx/pathtracing/spp", min(self._options.spp_per_iteration, self._options.path_trace_spp) ) if self._options.render_preset == CaptureRenderPreset.IRAY: iterations_done = int(self._settings.get("/iray/progression")) self._path_trace_iterations = iterations_done self._sample_count = iterations_done else: self._sample_count += self._options.spp_per_iteration self._path_trace_iterations = self._sample_count self._timeline.set_prerolling(False) self._settings.set_int("/rtx/externalFrameCounter", self._frame) # update progress timers if self._options.is_capturing_pathtracing_single_frame(): if self._options.render_preset == CaptureRenderPreset.PATH_TRACE: self._progress.add_single_frame_capture_time_for_pt(self._subframe, self._options.ptmb_subframes_per_frame, dt) elif self._options.render_preset == CaptureRenderPreset.IRAY: self._progress.add_single_frame_capture_time_for_iray( self._subframe, self._options.ptmb_subframes_per_frame, self._path_trace_iterations, self._options.path_trace_spp, dt ) else: carb.log_warn(f"Movie capture: we don't support progress for {self._options.render_preset} in single frame capture mode.") else: self._progress.add_frame_time(self._frame, dt, self._subframe + 1, self._options.ptmb_subframes_per_frame, self._path_trace_iterations, self._options.path_trace_spp, self._is_handling_settle_latency_frames() and not self._is_using_default_settle_latency_frames(), self._real_time_settle_latency_frames_done, self._settle_latency_frames ) self._update_progress_hook() # check if path trace and meet the samples per pixels stop criterion render_status = self._viewport_api.frame_info.get('status') if RenderStatus.eStopCriterionReached == render_status and self._is_adaptivesampling_stop_criterion_reached: carb.log_info("Got continuous path tracing adaptive sampling stop criterion reached event, skip this frame for it to finish.") return self._is_adaptivesampling_stop_criterion_reached = self._is_pt_adaptivesampling_stop_criterion_reached() # capture frame when we reach the sample count for this frame and are rendering the last subframe # Note _sample_count can go over _samples_per_pixel when 'spp_per_iteration > 1' # also handle the case when we have adaptive sampling enabled and it returns stop criterion reached if (self._sample_count >= self._options.path_trace_spp) and \ (self._subframe == self._options.ptmb_subframes_per_frame - 1) or \ self._is_adaptivesampling_stop_criterion_reached: if self._handle_real_time_capture_settle_latency(): return if self._options.is_video(): self._capture_image(self._frame_path) else: if self._options.is_capturing_nth_frames(): if self._frame_counter % self._options.capture_every_Nth_frames == 0: self._capture_image(self._frame_path) else: self._progress.capture_status = CaptureStatus.FINISHING self._capture_image(self._frame_path) # reset time the *next frame* (since otherwise we capture the first sample) if self._sample_count >= self._options.path_trace_spp or self._is_adaptivesampling_stop_criterion_reached: self._sample_count = 0 self._path_trace_iterations = 0 self._subframe += 1 if self._subframe == self._options.ptmb_subframes_per_frame: self._subframe = 0 self._frame += 1 self._frame_counter += 1 self._time = self._start_time + (self._frame - self._start_number) * self._time_rate can_continue = False if self._forward_one_frame_fn is not None: can_continue = self._forward_one_frame_fn(dt) elif self._options.movie_type == CaptureMovieType.SUNSTUDY and \ (self._options.is_video() or self._options.is_capturing_nth_frames()): self._sunstudy_current_time += self._sunstudy_delta_time_per_iteration self._update_sunstudy_player_time() else: if self._options.is_video() or self._options.is_capturing_nth_frames(): cur_time = ( self._time + (self._options.ptmb_fso * self._time_rate) + self._time_subframe_rate * self._subframe ) self._timeline.set_current_time(cur_time) if self._forward_one_frame_fn is not None: if can_continue == False: if self._options.is_video(): self._progress.capture_status = CaptureStatus.TO_START_ENCODING elif self._options.is_capturing_nth_frames(): self._progress.capture_status = CaptureStatus.FINISHING else: if self._time >= self._end_time or self._frame_counter >= self._total_frame_count: if self._options.is_video(): self._progress.capture_status = CaptureStatus.TO_START_ENCODING elif self._options.is_capturing_nth_frames(): self._progress.capture_status = CaptureStatus.FINISHING @staticmethod def get_instance(): global capture_instance return capture_instance
65,590
Python
51.599038
195
0.63496
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/video_generation.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os import threading import carb try: from video_encoding import get_video_encoding_interface except ImportError: get_video_encoding_interface = lambda: None from .singleton import Singleton from .helper import get_num_pattern_file_path g_video_encoding_api = get_video_encoding_interface() @Singleton class VideoGenerationHelper: def __init__(self): self._init_internal() @property def is_encoding(self): return self._is_encoding @property def encoding_done(self): return self._is_encoding == False and self._encoding_done == True def generating_video( self, video_name, frames_dir, filename_prefix, filename_num_pattern, start_number, total_frames, frame_rate, image_type=".png" ): carb.log_warn(f"Using videoencoding plugin to encode video ({video_name})") global g_video_encoding_api self._encoding_finished = False if g_video_encoding_api is None: carb.log_warn("Video encoding api not available; cannot encode video.") return False # acquire list of available frame image files, based on start_number and filename_pattern next_frame = start_number frame_count = 0 self._frame_filenames = [] while True: frame_path = get_num_pattern_file_path( frames_dir, filename_prefix, filename_num_pattern, next_frame, image_type ) if os.path.isfile(frame_path) and os.access(frame_path, os.R_OK): self._frame_filenames.append(frame_path) next_frame += 1 frame_count += 1 if frame_count == total_frames: break else: break carb.log_warn(f"Found {len(self._frame_filenames)} frames to encode.") if len(self._frame_filenames) == 0: carb.log_warn(f"No frames to encode.") return False if not g_video_encoding_api.start_encoding(video_name, frame_rate, len(self._frame_filenames), True): carb.log_warn(f"videoencoding plug failed to start encoding.") return False if self._encoding_thread == None: self._encoding_thread = threading.Thread(target=self._encode_image_file_sequence, args=()) self._is_encoding = True self._encoding_thread.start() return True def _init_internal(self): self._video_generation_done_fn = None self._frame_filenames = [] self._encoding_thread = None self._is_encoding = False self._encoding_done = False def _encode_image_file_sequence(self): global g_video_encoding_api try: for frame_filename in self._frame_filenames: g_video_encoding_api.encode_next_frame_from_file(frame_filename) except: import traceback carb.log_warn(traceback.format_exc()) finally: g_video_encoding_api.finalize_encoding() self._init_internal() self._encoding_done = True
3,608
Python
33.701923
109
0.622228
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/capture_options.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 from enum import Enum, IntEnum import carb class CaptureMovieType(IntEnum): SEQUENCE = 0 SUNSTUDY = 1 PLAYLIST = 2 class CaptureRangeType(IntEnum): FRAMES = 0 SECONDS = 1 class CaptureRenderPreset(IntEnum): PATH_TRACE = 0 RAY_TRACE = 1 IRAY = 2 class CaptureDebugMaterialType(IntEnum): SHADED = 0 WHITE = 1 EXR_COMPRESSION_METHODS = {"zip", "zips", "dwaa", "dwab", "piz", "rle", "b44", "b44a"} MP4_ENCODING_PRESETS = { "PRESET_DEFAULT", "PRESET_HP", "PRESET_HQ", "PRESET_BD", "PRESET_LOW_LATENCY_DEFAULT", "PRESET_LOW_LATENCY_HQ", "PRESET_LOW_LATENCY_HP", "PRESET_LOSSLESS_DEFAULT", "PRESET_LOSSLESS_HP" } MP4_ENCODING_PROFILES = { "H264_PROFILE_BASELINE", "H264_PROFILE_MAIN", "H264_PROFILE_HIGH", "H264_PROFILE_HIGH_444", "H264_PROFILE_STEREO", "H264_PROFILE_SVC_TEMPORAL_SCALABILITY", "H264_PROFILE_PROGRESSIVE_HIGH", "H264_PROFILE_CONSTRAINED_HIGH", "HEVC_PROFILE_MAIN", "HEVC_PROFILE_MAIN10", "HEVC_PROFILE_FREXT" } MP4_ENCODING_RC_MODES = { "RC_CONSTQP", "RC_VBR", "RC_CBR", "RC_CBR_LOWDELAY_HQ", "RC_CBR_HQ", "RC_VBR_HQ" } class CaptureOptions: """ All Capture options that will be used when capturing. Note: When adding an attribute make sure it is exposed via the constructor. Not doing this will cause erorrs when serializing and deserializing this object. """ INVALID_ANIMATION_FPS = -1 def __init__( self, camera="camera", range_type=CaptureRangeType.FRAMES, capture_every_nth_frames=-1, fps=24, start_frame=1, end_frame=40, start_time=0, end_time=10, res_width=1920, res_height=1080, render_preset=CaptureRenderPreset.PATH_TRACE, debug_material_type=CaptureDebugMaterialType.SHADED, spp_per_iteration=1, path_trace_spp=1, ptmb_subframes_per_frame=1, ptmb_fso=0.0, ptmb_fsc=1.0, output_folder="", file_name="Capture", file_name_num_pattern=".####", file_type=".tga", save_alpha=False, hdr_output=False, show_pathtracing_single_frame_progress=False, preroll_frames=0, overwrite_existing_frames=False, movie_type=CaptureMovieType.SEQUENCE, sunstudy_start_time=0.0, sunstudy_current_time=0.0, sunstudy_end_time=0.0, sunstudy_movie_length_in_seconds=0, sunstudy_player=None, real_time_settle_latency_frames=0, renumber_negative_frame_number_from_0=False, render_product="", exr_compression_method="zips", mp4_encoding_bitrate=16777216, mp4_encoding_iframe_interval=60, mp4_encoding_preset="PRESET_DEFAULT", mp4_encoding_profile="H264_PROFILE_HIGH", mp4_encoding_rc_mode="RC_VBR", mp4_encoding_rc_target_quality=0, mp4_encoding_video_full_range_flag=False, app_level_capture=False, animation_fps=INVALID_ANIMATION_FPS ): self._camera = camera self._range_type = range_type self._capture_every_nth_frames = capture_every_nth_frames self._fps = fps self._start_frame = start_frame self._end_frame = end_frame self._start_time = start_time self._end_time = end_time self._res_width = res_width self._res_height = res_height self._render_preset = render_preset self._debug_material_type = debug_material_type self._spp_per_iteration = spp_per_iteration self._path_trace_spp = path_trace_spp self._ptmb_subframes_per_frame = ptmb_subframes_per_frame self._ptmb_fso = ptmb_fso self._ptmb_fsc = ptmb_fsc self._output_folder = output_folder self._file_name = file_name self._file_name_num_pattern = file_name_num_pattern self._file_type = file_type self._save_alpha = save_alpha self._hdr_output = hdr_output self._show_pathtracing_single_frame_progress = show_pathtracing_single_frame_progress self._preroll_frames = preroll_frames self._overwrite_existing_frames = overwrite_existing_frames self._movie_type = movie_type self._sunstudy_start_time = sunstudy_start_time self._sunstudy_current_time = sunstudy_current_time self._sunstudy_end_time = sunstudy_end_time self._sunstudy_movie_length_in_seconds = sunstudy_movie_length_in_seconds self._sunstudy_player = sunstudy_player self._real_time_settle_latency_frames = real_time_settle_latency_frames self._renumber_negative_frame_number_from_0 = renumber_negative_frame_number_from_0 self._render_product = render_product self.exr_compression_method = exr_compression_method self.mp4_encoding_bitrate = mp4_encoding_bitrate self.mp4_encoding_iframe_interval = mp4_encoding_iframe_interval self.mp4_encoding_preset = mp4_encoding_preset self.mp4_encoding_profile = mp4_encoding_profile self.mp4_encoding_rc_mode = mp4_encoding_rc_mode self.mp4_encoding_rc_target_quality = mp4_encoding_rc_target_quality self.mp4_encoding_video_full_range_flag = mp4_encoding_video_full_range_flag self._app_level_capture = app_level_capture self.animation_fps = animation_fps def to_dict(self): data = vars(self) return {key.lstrip("_"): value for key, value in data.items()} @classmethod def from_dict(cls, options): return cls(**options) @property def camera(self): return self._camera @camera.setter def camera(self, value): self._camera = value @property def range_type(self): return self._range_type @range_type.setter def range_type(self, value): self._range_type = value @property def capture_every_Nth_frames(self): return self._capture_every_nth_frames @capture_every_Nth_frames.setter def capture_every_Nth_frames(self, value): self._capture_every_nth_frames = value @property def fps(self): return self._fps @fps.setter def fps(self, value): self._fps = value @property def start_frame(self): return self._start_frame @start_frame.setter def start_frame(self, value): self._start_frame = value @property def end_frame(self): return self._end_frame @end_frame.setter def end_frame(self, value): self._end_frame = value @property def start_time(self): return self._start_time @start_time.setter def start_time(self, value): self._start_time = value @property def end_time(self): return self._end_time @end_time.setter def end_time(self, value): self._end_time = value @property def res_width(self): return self._res_width @res_width.setter def res_width(self, value): self._res_width = value @property def res_height(self): return self._res_height @res_height.setter def res_height(self, value): self._res_height = value @property def render_preset(self): return self._render_preset @render_preset.setter def render_preset(self, value): self._render_preset = value @property def debug_material_type(self): return self._debug_material_type @debug_material_type.setter def debug_material_type(self, value): self._debug_material_type = value @property def spp_per_iteration(self): return self._spp_per_iteration @spp_per_iteration.setter def spp_per_iteration(self, value): self._spp_per_iteration = value @property def path_trace_spp(self): return self._path_trace_spp @path_trace_spp.setter def path_trace_spp(self, value): self._path_trace_spp = value @property def ptmb_subframes_per_frame(self): return self._ptmb_subframes_per_frame @ptmb_subframes_per_frame.setter def ptmb_subframes_per_frame(self, value): self._ptmb_subframes_per_frame = value @property def ptmb_fso(self): return self._ptmb_fso @ptmb_fso.setter def ptmb_fso(self, value): self._ptmb_fso = value @property def ptmb_fsc(self): return self._ptmb_fsc @ptmb_fsc.setter def ptmb_fsc(self, value): self._ptmb_fsc = value @property def output_folder(self): return self._output_folder @output_folder.setter def output_folder(self, value): self._output_folder = value @property def file_name(self): return self._file_name @file_name.setter def file_name(self, value): self._file_name = value @property def file_name_num_pattern(self): return self._file_name_num_pattern @file_name_num_pattern.setter def file_name_num_pattern(self, value): self._file_name_num_pattern = value @property def file_type(self): return self._file_type @file_type.setter def file_type(self, value): self._file_type = value @property def save_alpha(self): return self._save_alpha @save_alpha.setter def save_alpha(self, value): self._save_alpha = value @property def hdr_output(self): return self._hdr_output @hdr_output.setter def hdr_output(self, value): self._hdr_output = value @property def show_pathtracing_single_frame_progress(self): return self._show_pathtracing_single_frame_progress @show_pathtracing_single_frame_progress.setter def show_pathtracing_single_frame_progress(self, value): self._show_pathtracing_single_frame_progress = value @property def preroll_frames(self): return self._preroll_frames @preroll_frames.setter def preroll_frames(self, value): self._preroll_frames = value @property def overwrite_existing_frames(self): return self._overwrite_existing_frames @overwrite_existing_frames.setter def overwrite_existing_frames(self, value): self._overwrite_existing_frames = value @property def movie_type(self): return self._movie_type @movie_type.setter def movie_type(self, value): self._movie_type = value @property def sunstudy_start_time(self): return self._sunstudy_start_time @sunstudy_start_time.setter def sunstudy_start_time(self, value): self._sunstudy_start_time = value @property def sunstudy_current_time(self): return self._sunstudy_current_time @sunstudy_current_time.setter def sunstudy_current_time(self, value): self._sunstudy_current_time = value @property def sunstudy_end_time(self): return self._sunstudy_end_time @sunstudy_end_time.setter def sunstudy_end_time(self, value): self._sunstudy_end_time = value @property def sunstudy_movie_length_in_seconds(self): return self._sunstudy_movie_length_in_seconds @sunstudy_movie_length_in_seconds.setter def sunstudy_movie_length_in_seconds(self, value): self._sunstudy_movie_length_in_seconds = value @property def sunstudy_player(self): return self._sunstudy_player @sunstudy_player.setter def sunstudy_player(self, value): self._sunstudy_player = value @property def real_time_settle_latency_frames(self): return self._real_time_settle_latency_frames @real_time_settle_latency_frames.setter def real_time_settle_latency_frames(self, value): self._real_time_settle_latency_frames = value @property def renumber_negative_frame_number_from_0(self): return self._renumber_negative_frame_number_from_0 @renumber_negative_frame_number_from_0.setter def renumber_negative_frame_number_from_0(self, value): self._renumber_negative_frame_number_from_0 = value @property def render_product(self): return self._render_product @render_product.setter def render_product(self, value): self._render_product = value @property def exr_compression_method(self): return self._exr_compression_method @exr_compression_method.setter def exr_compression_method(self, value): global EXR_COMPRESSION_METHODS if value in EXR_COMPRESSION_METHODS: self._exr_compression_method = value else: self._exr_compression_method = "zips" carb.log_warn(f"Can't set unsupported compression method {value} for exr format, set to default zip16. Supported values are: {EXR_COMPRESSION_METHODS}") @property def mp4_encoding_bitrate(self): return self._mp4_encoding_bitrate @mp4_encoding_bitrate.setter def mp4_encoding_bitrate(self, value): self._mp4_encoding_bitrate = value @property def mp4_encoding_iframe_interval(self): return self._mp4_encoding_iframe_interval @mp4_encoding_iframe_interval.setter def mp4_encoding_iframe_interval(self, value): self._mp4_encoding_iframe_interval = value @property def mp4_encoding_preset(self): return self._mp4_encoding_preset @mp4_encoding_preset.setter def mp4_encoding_preset(self, value): global MP4_ENCODING_PRESETS if value in MP4_ENCODING_PRESETS: self._mp4_encoding_preset = value else: self._mp4_encoding_preset = "PRESET_DEFAULT" carb.log_warn(f"Can't set unsupported mp4 encoding preset {value}, set to default {self._mp4_encoding_preset}. Supported values are: {MP4_ENCODING_PRESETS}") @property def mp4_encoding_profile(self): return self._mp4_encoding_profile @mp4_encoding_profile.setter def mp4_encoding_profile(self, value): global MP4_ENCODING_PROFILES if value in MP4_ENCODING_PROFILES: self._mp4_encoding_profile = value else: self._mp4_encoding_profile = "H264_PROFILE_HIGH" carb.log_warn(f"Can't set unsupported mp4 encoding profile {value}, set to default {self._mp4_encoding_profile}. Supported values are: {MP4_ENCODING_PROFILES}") @property def mp4_encoding_rc_mode(self): return self._mp4_encoding_rc_mode @mp4_encoding_rc_mode.setter def mp4_encoding_rc_mode(self, value): global MP4_ENCODING_RC_MODES if value in MP4_ENCODING_RC_MODES: self._mp4_encoding_rc_mode = value else: self._mp4_encoding_rc_mode = "RC_VBR" carb.log_warn(f"Can't set unsupported mp4 encoding rate control mode {value}, set to default {self._mp4_encoding_rc_mode}. Supported values are: {MP4_ENCODING_RC_MODES}") @property def mp4_encoding_rc_target_quality(self): return self._mp4_encoding_rc_target_quality @mp4_encoding_rc_target_quality.setter def mp4_encoding_rc_target_quality(self, value): if 0 <= value and value <= 51: self._mp4_encoding_rc_target_quality = value else: self._mp4_encoding_rc_target_quality = 0 carb.log_warn(f"Can't set unsupported mp4 encoding rate control target quality {value}, set to default {self._mp4_encoding_rc_target_quality}. Supported range is [0, 51]") @property def mp4_encoding_video_full_range_flag(self): return self._mp4_encoding_video_full_range_flag @mp4_encoding_video_full_range_flag.setter def mp4_encoding_video_full_range_flag(self, value): self._mp4_encoding_video_full_range_flag = value @property def app_level_capture(self): return self._app_level_capture @app_level_capture.setter def app_level_capture(self, value): self._app_level_capture = value @property def animation_fps(self): return self._animation_fps @animation_fps.setter def animation_fps(self, value): self._animation_fps = value def is_video(self): return self.file_type == ".mp4" def is_capturing_nth_frames(self): return self._capture_every_nth_frames > 0 def is_capturing_pathtracing_single_frame(self): return ( self.is_video() is False and self.is_capturing_nth_frames() is False and (self.render_preset == CaptureRenderPreset.PATH_TRACE or self.render_preset == CaptureRenderPreset.IRAY) ) def is_capturing_frame(self): return self._range_type == CaptureRangeType.FRAMES def get_full_path(self): return os.path.join(self._output_folder, self._file_name + self._file_type)
17,273
Python
28.629503
183
0.645632
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/helper.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 carb import omni.kit.app import omni.usd from pxr import Sdf, UsdRender, Gf, Usd ViewportObjectsSettingDict = { "guide/selection": "/app/viewport/outline/enabled", "scene/lights": "/app/viewport/show/lights", "scene/audio": "/app/viewport/show/audio", "scene/cameras": "/app/viewport/show/camera", "guide/grid": "/app/viewport/grid/enabled" } def get_num_pattern_file_path(frames_dir, file_name, num_pattern, frame_num, file_type, renumber_frames=False, renumber_offset=0): if renumber_frames: renumbered_frames = frame_num + renumber_offset else: renumbered_frames = frame_num abs_frame_num = abs(renumbered_frames) padding_length = len(num_pattern.strip(".")[len(str(abs_frame_num)) :]) if renumbered_frames >= 0: padded_string = "0" * padding_length + str(renumbered_frames) else: padded_string = "-" + "0" * padding_length + str(abs_frame_num) filename = ".".join((file_name, padded_string, file_type.strip("."))) frame_path = os.path.join(frames_dir, filename) return frame_path def is_ext_enabled(ext_name): ext_manager = omni.kit.app.get_app().get_extension_manager() return ext_manager.is_extension_enabled(ext_name) # TODO: These version checks exists only in case down-stream movie-capture has imported them # They should be removed for 105.2 and above. # def check_kit_major_version(version_num: int) -> bool: kit_version = omni.kit.app.get_app().get_build_version().split(".") try: major_ver = int(kit_version[0]) return major_ver >= version_num except Exception as e: return False def is_kit_104_and_above() -> bool: return False def is_kit_105_and_above() -> bool: return True def get_vp_object_setting_path(viewport_api, setting_key: str) -> str: usd_context_name = viewport_api.usd_context_name if setting_key.startswith("scene"): setting_path = f"/app/viewport/usdcontext-{usd_context_name}/{setting_key}/visible" else: setting_path = f"/persistent/app/viewport/{viewport_api.id}/{setting_key}/visible" return setting_path def get_vp_object_visibility(viewport_api, setting_key: str) -> bool: settings = carb.settings.get_settings() setting_path = get_vp_object_setting_path(viewport_api, setting_key) return settings.get_as_bool(setting_path) def set_vp_object_visibility(viewport_api, setting_key: str, visible: bool) -> None: if get_vp_object_visibility(viewport_api, setting_key) == visible: return settings = carb.settings.get_settings() action_key = { "guide/selection": "toggle_selection_hilight_visibility", "scene/lights": "toggle_light_visibility", "scene/audio": "toggle_audio_visibility", "scene/cameras": "toggle_camera_visibility", "guide/grid": "toggle_grid_visibility" }.get(setting_key, None) if not action_key: carb.log_error(f"No mapping between {setting_key} and omni.kit.viewport.actions") return action_registry = omni.kit.actions.core.get_action_registry() action = action_registry.get_action("omni.kit.viewport.actions", action_key) if action: action.execute(viewport_api=viewport_api, visible=visible) else: carb.log_error(f"Did not find action omni.kit.viewport.actions.{action_key}") def check_render_product_ext_availability(): return is_ext_enabled("omni.graph.nodes") and is_ext_enabled("omni.graph.examples.cpp") def is_valid_render_product_prim_path(prim_path): try: import omni.usd from pxr import UsdRender usd_context = omni.usd.get_context() stage = usd_context.get_stage() prim = stage.GetPrimAtPath(prim_path) if prim: return prim.IsA(UsdRender.Product) else: return False except Exception as e: return False class RenderProductCaptureHelper: @staticmethod def prepare_render_product_for_capture(render_product_prim_path, new_camera, new_resolution): usd_context = omni.usd.get_context() stage = usd_context.get_stage() working_layer = stage.GetSessionLayer() prim = stage.GetPrimAtPath(render_product_prim_path) path_new = omni.usd.get_stage_next_free_path(stage, render_product_prim_path, False) if prim.IsA(UsdRender.Product): with Usd.EditContext(stage, working_layer): omni.kit.commands.execute("CopyPrim", path_from=render_product_prim_path, path_to=path_new, duplicate_layers=False, combine_layers=True,exclusive_select=True) prim_new = stage.GetPrimAtPath(path_new) if prim_new.IsA(UsdRender.Product): omni.usd.editor.set_no_delete(prim_new, False) prim_new.GetAttribute("resolution").Set(new_resolution) prim_new.GetRelationship("camera").SetTargets([new_camera]) else: path_new = "" else: path_new = "" return path_new @staticmethod def remove_render_product_for_capture(render_product_prim_path): usd_context = omni.usd.get_context() stage = usd_context.get_stage() working_layer = stage.GetSessionLayer() prim = working_layer.GetPrimAtPath(render_product_prim_path) if prim: if prim.nameParent: name_parent = prim.nameParent else: name_parent = working_layer.pseudoRoot if not name_parent: return name = prim.name if name in name_parent.nameChildren: del name_parent.nameChildren[name]
6,149
Python
36.730061
174
0.660433
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/tests/__init__.py
from .test_capture_options import TestCaptureOptions from .test_capture_hdr import TestCaptureHdr from .test_capture_png import TestCapturePng from .test_capture_render_product import TestCaptureRenderProduct
208
Python
51.249987
65
0.865385
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/tests/test_helper.py
import os import os.path import asyncio import carb import omni.kit.app def clean_files_in_directory(directory, suffix): if not os.path.exists(directory): return images = os.listdir(directory) for item in images: if item.endswith(suffix): os.remove(os.path.join(directory, item)) def make_sure_directory_existed(directory): if not os.path.exists(directory): try: os.makedirs(directory, exist_ok=True) except OSError as error: carb.log_warn(f"Directory cannot be created: {dir}") return False return True # TODO: Remove this as it is no longer used, but kept only if transitively depended on # def is_kit_104_and_above(): kit_version = omni.kit.app.get_app().get_build_version().split(".") try: major_ver = int(kit_version[0]) return major_ver >= 104 except Exception as e: return False async def wait_for_image_writing(image_path, seconds_to_wait: float = 30, seconds_to_sleep: float = 0.5): seconds_tried = 0.0 carb.log_info(f"Waiting for {image_path} to be written to disk.") while seconds_tried < seconds_to_wait: if os.path.isfile(image_path) and os.access(image_path, os.R_OK): carb.log_info(f"{image_path} is written to disk in {seconds_tried}s.") break else: await asyncio.sleep(seconds_to_sleep) seconds_tried += seconds_to_sleep if seconds_tried >= seconds_to_wait: carb.log_warn(f"Waiting for {image_path} timed out..")
1,562
Python
30.259999
105
0.638924
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/tests/test_capture_hdr.py
from typing import Type import os import os.path import omni.kit.test import carb import carb.settings import carb.tokens import pathlib import gc from omni.kit.capture.viewport import CaptureOptions, CaptureExtension from omni.kit.viewport.utility import get_active_viewport, create_viewport_window, capture_viewport_to_file from .test_helper import clean_files_in_directory, make_sure_directory_existed, wait_for_image_writing KIT_ROOT = pathlib.Path(carb.tokens.acquire_tokens_interface().resolve("${kit}")).parent.parent.parent OUTPUTS_DIR = KIT_ROOT.joinpath("_testoutput/omni.kit.capture.viewport.images") class TestCaptureHdr(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): self._usd_context = '' settings = carb.settings.get_settings() self._frames_wait_for_capture_resource_ready = 6 await omni.usd.get_context(self._usd_context).new_stage_async() async def test_hdr_capture(self): viewport_api = get_active_viewport(self._usd_context) # Wait until the viewport has valid resources await viewport_api.wait_for_rendered_frames() capture_filename = "capture_hdr_test" filePath = pathlib.Path(OUTPUTS_DIR).joinpath(capture_filename) options = CaptureOptions() options.file_type = ".exr" options.output_folder = str(filePath) make_sure_directory_existed(options.output_folder) clean_files_in_directory(options.output_folder, ".exr") exr_path = os.path.join(options._output_folder, "Capture1.exr") carb.log_warn(f"Capture image path: {exr_path}") options.hdr_output = True options.camera = viewport_api.camera_path.pathString # to reduce memory consumption and save time options.res_width = 600 options.res_height = 337 capture_instance = CaptureExtension().get_instance() capture_instance.options = options capture_instance.start() await wait_for_image_writing(exr_path) options = None capture_instance = None gc.collect() assert os.path.isfile(exr_path) async def _test_exr_compression_method(self, compression_method): viewport_api = get_active_viewport(self._usd_context) # Wait until the viewport has valid resources await viewport_api.wait_for_rendered_frames() capture_filename = "capture_exr_compression_method_test_" + compression_method filePath = pathlib.Path(OUTPUTS_DIR).joinpath(capture_filename) options = CaptureOptions() options.file_type = ".exr" options.exr_compression_method = compression_method options.output_folder = str(filePath) make_sure_directory_existed(options.output_folder) clean_files_in_directory(options.output_folder, ".exr") exr_path = os.path.join(options._output_folder, "Capture1.exr") carb.log_warn(f"Capture image path: {exr_path}") options.hdr_output = True options.camera = viewport_api.camera_path.pathString # to reduce memory consumption and save time options.res_width = 600 options.res_height = 337 capture_instance = CaptureExtension().get_instance() capture_instance.options = options capture_instance.start() await wait_for_image_writing(exr_path) options = None capture_instance = None gc.collect() assert os.path.isfile(exr_path) async def test_exr_compression_method_rle(self): await self._test_exr_compression_method("rle") async def test_exr_compression_method_zip(self): await self._test_exr_compression_method("zip") async def test_exr_compression_method_dwaa(self): await self._test_exr_compression_method("dwaa") async def test_exr_compression_method_dwab(self): await self._test_exr_compression_method("dwab") async def test_exr_compression_method_piz(self): await self._test_exr_compression_method("piz") async def test_exr_compression_method_b44(self): await self._test_exr_compression_method("b44") async def test_exr_compression_method_b44a(self): await self._test_exr_compression_method("b44a") # Notes: The following multiple viewport tests will fail now and should be revisited after we confirm the # multiple viewport capture support in new SRD. # # Make sure we do not crash in the unsupported multi-view case # async def test_hdr_multiview_capture(self): # viewport_api = get_active_viewport(self._usd_context) # # Wait until the viewport has valid resources # await viewport_api.wait_for_rendered_frames() # new_viewport = create_viewport_window("Viewport 2") # capture_filename = "capture.hdr_test.multiview" # filePath = pathlib.Path(OUTPUTS_DIR).joinpath(capture_filename) # options = CaptureOptions() # options.file_type = ".exr" # options.output_folder = str(filePath) # self._make_sure_directory_existed(options.output_folder) # self._clean_files_in_directory(options.output_folder, ".exr") # exr_path = os.path.join(options._output_folder, "Capture1.exr") # carb.log_warn(f"Capture image path: {exr_path}") # options.hdr_output = True # options.camera = viewport_api.camera_path.pathString # capture_instance = CaptureExtension().get_instance() # capture_instance.options = options # capture_instance.start() # capture_viewport_to_file(new_viewport.viewport_api, file_path=exr_path) # i = self._frames_wait_for_capture_resource_ready # while i > 0: # await omni.kit.app.get_app().next_update_async() # i -= 1 # options = None # capture_instance = None # gc.collect() # assert os.path.isfile(exr_path) # if viewport_widget: # viewport_widget.destroy() # del viewport_widget # async def test_hdr_multiview_capture_legacy(self): # await self.do_test_hdr_multiview_capture(True) # async def test_hdr_multiview_capture(self): # await self.do_test_hdr_multiview_capture(False)
6,254
Python
38.588607
109
0.668372
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/tests/test_capture_options.py
from typing import Type import omni.kit.test import omni.kit.capture.viewport.capture_options as _capture_options class TestCaptureOptions(omni.kit.test.AsyncTestCase): async def test_capture_options_serialisation(self): options = _capture_options.CaptureOptions() data_dict = options.to_dict() self.assertIsInstance(data_dict, dict) async def test_capture_options_deserialisation(self): options = _capture_options.CaptureOptions() data_dict = options.to_dict() regenerated_options = _capture_options.CaptureOptions.from_dict(data_dict) self.assertIsInstance(regenerated_options, _capture_options.CaptureOptions) async def test_capture_options_values_persisted(self): options = _capture_options.CaptureOptions(camera="my_camera") data_dict = options.to_dict() regenerated_options = _capture_options.CaptureOptions.from_dict(data_dict) self.assertEqual(regenerated_options.camera, "my_camera") async def test_adding_random_attribute_fails(self): """ Test that adding new attributes without making them configurable via the __init__ will raise an exception """ options = _capture_options.CaptureOptions() options._my_new_value = "foo" data_dict = options.to_dict() with self.assertRaises(TypeError, msg="__init__() got an unexpected keyword argument 'my_new_value'"): regnerated = _capture_options.CaptureOptions.from_dict(data_dict) async def test_capture_options_unsupported_exr_compression_method(self): options = _capture_options.CaptureOptions(exr_compression_method="sth_wrong") self.assertEqual(options.exr_compression_method, "zips") async def test_capture_options_mp4_encoding_settings(self): options = _capture_options.CaptureOptions( mp4_encoding_bitrate=4194304, mp4_encoding_iframe_interval=10, mp4_encoding_preset="PRESET_LOSSLESS_HP", mp4_encoding_profile="H264_PROFILE_PROGRESSIVE_HIGH", mp4_encoding_rc_mode="RC_VBR_HQ", mp4_encoding_rc_target_quality=51, mp4_encoding_video_full_range_flag=True, ) self.assertEqual(options.mp4_encoding_bitrate, 4194304) self.assertEqual(options.mp4_encoding_iframe_interval, 10) self.assertEqual(options.mp4_encoding_preset, "PRESET_LOSSLESS_HP") self.assertEqual(options.mp4_encoding_profile, "H264_PROFILE_PROGRESSIVE_HIGH") self.assertEqual(options._mp4_encoding_rc_mode, "RC_VBR_HQ") self.assertEqual(options._mp4_encoding_rc_target_quality, 51) self.assertEqual(options.mp4_encoding_video_full_range_flag, True) async def test_capture_options_unsupported_mp4_encoding_settings(self): options = _capture_options.CaptureOptions( mp4_encoding_bitrate=4194304, mp4_encoding_iframe_interval=10, mp4_encoding_preset="PRESET_NOT_EXISTING", mp4_encoding_profile="PROFILE_NOT_EXISTING", mp4_encoding_rc_mode="RC_NOT_EXISTING", mp4_encoding_rc_target_quality=52, mp4_encoding_video_full_range_flag=True, ) self.assertEqual(options.mp4_encoding_bitrate, 4194304) self.assertEqual(options.mp4_encoding_iframe_interval, 10) self.assertEqual(options.mp4_encoding_preset, "PRESET_DEFAULT") self.assertEqual(options.mp4_encoding_profile, "H264_PROFILE_HIGH") self.assertEqual(options._mp4_encoding_rc_mode, "RC_VBR") self.assertEqual(options._mp4_encoding_rc_target_quality, 0) self.assertEqual(options.mp4_encoding_video_full_range_flag, True)
3,701
Python
47.077921
117
0.690354
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/tests/test_capture_render_product.py
import os import os.path import omni.kit.test import omni.usd import carb import carb.settings import carb.tokens import pathlib import gc import unittest from omni.kit.capture.viewport import CaptureOptions, CaptureExtension from omni.kit.viewport.utility import get_active_viewport from omni.kit.test_suite.helpers import wait_stage_loading from .test_helper import clean_files_in_directory, make_sure_directory_existed, wait_for_image_writing KIT_ROOT = pathlib.Path(carb.tokens.acquire_tokens_interface().resolve("${kit}")).parent.parent.parent OUTPUTS_DIR = KIT_ROOT.joinpath("_testoutput/omni.kit.capture.viewport.images") TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent.parent.parent) class TestCaptureRenderProduct(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): self._usd_context = '' self._frames_per_sec_to_wait_for_capture_resource_ready = 60 test_usd = TEST_DIR + "/data/tests/usd/PTAccumulateTest.usd" carb.log_warn(f"testing capture with usd {test_usd}") self._capture_folder_1spp = "rp_1spp" self._capture_folder_32spp = "rp_32spp" self._capture_folder_sequence = "rp_seq" self._context = omni.usd.get_context() self._capture_instance = CaptureExtension().get_instance() await self._context.open_stage_async(test_usd) await wait_stage_loading() for _ in range(2): await omni.kit.app.get_app().next_update_async() async def tearDown(self) -> None: self._capture_instance = None async def _test_render_product_capture(self, image_folder, render_product_name, spp, enable_hdr=True, sequence_capture=False, start_frame=0, end_frame=10): viewport_api = get_active_viewport(self._usd_context) # Wait until the viewport has valid resources await viewport_api.wait_for_rendered_frames() # wait for PT to resolve after loading, otherwise it's easy to crash i = self._frames_per_sec_to_wait_for_capture_resource_ready * 50 while i > 0: await omni.kit.app.get_app().next_update_async() i -= 1 # assert True capture_folder_name = image_folder filePath = pathlib.Path(OUTPUTS_DIR).joinpath(capture_folder_name) options = CaptureOptions() options.file_type = ".exr" options.output_folder = str(filePath) make_sure_directory_existed(options.output_folder) clean_files_in_directory(options.output_folder, ".exr") options.hdr_output = enable_hdr options.camera = viewport_api.camera_path.pathString options.render_preset = omni.kit.capture.viewport.CaptureRenderPreset.PATH_TRACE options.render_product = render_product_name options.path_trace_spp = spp # to reduce memory consumption and save time options.res_width = 600 options.res_height = 337 if sequence_capture: options.capture_every_Nth_frames = 1 options.start_frame = start_frame options.end_frame = end_frame self._capture_instance.options = options self._capture_instance.start() options = None async def _verify_file_exist(self, capture_folder_name, aov_channel): exr_path = self._get_exr_path(capture_folder_name, aov_channel) carb.log_warn(f"Verifying image: {exr_path}") await wait_for_image_writing(exr_path, 40) assert os.path.isfile(exr_path) def _get_exr_path(self, capture_folder_name, aov_channel): image_folder = pathlib.Path(OUTPUTS_DIR).joinpath(capture_folder_name) exr_path = os.path.join(str(image_folder), "Capture1_" + aov_channel + ".exr") return exr_path def _get_captured_image_size(self, capture_folder_name, aov_channel): image_folder = pathlib.Path(OUTPUTS_DIR).joinpath(capture_folder_name) exr_path = os.path.join(str(image_folder), "Capture1_" + aov_channel + ".exr") if os.path.isfile(exr_path): return os.path.getsize(exr_path) else: return 0 async def test_capture_1_default_rp(self): if True: # skip the test for vp2 due to OM-77175: we know it will fail and have a bug for it so mark it true here # and re-enable it after the bug gets fixed image_folder_name = "vp2_default_rp" default_rp_name = "/Render/RenderProduct_omni_kit_widget_viewport_ViewportTexture_0" assert True for _ in range(self._frames_per_sec_to_wait_for_capture_resource_ready * 10): await omni.kit.app.get_app().next_update_async() return await self._test_render_product_capture(image_folder_name, default_rp_name, 16, enable_hdr=False) exr_path = self._get_exr_path(image_folder_name, "LdrColor") await wait_for_image_writing(exr_path) await self._test_render_product_capture(image_folder_name, default_rp_name, 16) await self._verify_file_exist(image_folder_name, "LdrColor") for _ in range(self._frames_per_sec_to_wait_for_capture_resource_ready * 10): await omni.kit.app.get_app().next_update_async() async def test_capture_2_user_created_rp(self): await self._test_render_product_capture(self._capture_folder_1spp, "/Render/RenderView", 1) for _ in range(self._frames_per_sec_to_wait_for_capture_resource_ready * 10): await omni.kit.app.get_app().next_update_async() await self._verify_file_exist(self._capture_folder_1spp, "LdrColor") await self._verify_file_exist(self._capture_folder_1spp, "HdrColor") await self._verify_file_exist(self._capture_folder_1spp, "PtGlobalIllumination") await self._verify_file_exist(self._capture_folder_1spp, "PtReflections") await self._verify_file_exist(self._capture_folder_1spp, "PtWorldNormal") # the render product capture process will write the image file multiple times during the capture # so give it more cycles to settle down to check file size for _ in range(self._frames_per_sec_to_wait_for_capture_resource_ready * 20): await omni.kit.app.get_app().next_update_async() async def test_capture_3_rp_accumulation(self): await self._test_render_product_capture(self._capture_folder_32spp, "/Render/RenderView", 32) for _ in range(self._frames_per_sec_to_wait_for_capture_resource_ready * 10): await omni.kit.app.get_app().next_update_async() await self._verify_file_exist(self._capture_folder_32spp, "LdrColor") # the render product capture process will write the image file multiple times during the capture # so give it more cycles to settle down to check file size for _ in range(self._frames_per_sec_to_wait_for_capture_resource_ready * 20): await omni.kit.app.get_app().next_update_async() # compare result of test_capture_2_user_created_rp images to check accumulation works or not # if it works, more spp will result in smaller file size file_size_1spp = self._get_captured_image_size(self._capture_folder_1spp, "LdrColor") file_size_32spp = self._get_captured_image_size(self._capture_folder_32spp, "LdrColor") carb.log_warn(f"File size of 1spp capture is {file_size_1spp} bytes, and file size of 64spp capture is {file_size_32spp}") expected_result = file_size_32spp != file_size_1spp assert expected_result async def test_capture_4_rp_sequence(self): image_folder = pathlib.Path(OUTPUTS_DIR).joinpath(self._capture_folder_sequence, "Capture_frames") clean_files_in_directory(image_folder, ".exr") await self._test_render_product_capture(self._capture_folder_sequence, "/Render/RenderView", 1, True, True, 0, 10) start_frame_exr_path_1 = os.path.join(str(image_folder), "Capture.0000_" + "LdrColor" + ".exr") start_frame_exr_path_2 = os.path.join(str(image_folder), "Capture.0000_" + "PtGlobalIllumination" + ".exr") end_frame_exr_path_1 = os.path.join(str(image_folder), "Capture.0010_" + "LdrColor" + ".exr") end_frame_exr_path_2 = os.path.join(str(image_folder), "Capture.0010_" + "PtGlobalIllumination" + ".exr") await wait_for_image_writing(end_frame_exr_path_2, 50) assert os.path.isfile(start_frame_exr_path_1) assert os.path.isfile(start_frame_exr_path_2) assert os.path.isfile(end_frame_exr_path_1) assert os.path.isfile(end_frame_exr_path_2)
8,586
Python
49.511764
159
0.669811
omniverse-code/kit/exts/omni.kit.capture.viewport/omni/kit/capture/viewport/tests/test_capture_png.py
from typing import Type import os import os.path import omni.kit.test import carb import carb.settings import carb.tokens import pathlib import gc from omni.kit.capture.viewport import CaptureOptions, CaptureExtension from omni.kit.viewport.utility import get_active_viewport, create_viewport_window, capture_viewport_to_file from .test_helper import clean_files_in_directory, make_sure_directory_existed, wait_for_image_writing KIT_ROOT = pathlib.Path(carb.tokens.acquire_tokens_interface().resolve("${kit}")).parent.parent.parent OUTPUTS_DIR = KIT_ROOT.joinpath("_testoutput/omni.kit.capture.viewport.images") class TestCapturePng(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): self._usd_context = '' settings = carb.settings.get_settings() self._frames_wait_for_capture_resource_ready = 6 await omni.usd.get_context(self._usd_context).new_stage_async() async def test_png_capture(self): viewport_api = get_active_viewport(self._usd_context) # Wait until the viewport has valid resources await viewport_api.wait_for_rendered_frames() capture_filename = "capture_png_test" filePath = pathlib.Path(OUTPUTS_DIR).joinpath(capture_filename) options = CaptureOptions() options.file_type = ".png" options.output_folder = str(filePath) make_sure_directory_existed(options.output_folder) clean_files_in_directory(options.output_folder, ".png") exr_path = os.path.join(options._output_folder, "Capture1.png") carb.log_warn(f"Capture image path: {exr_path}") options.hdr_output = False options.camera = viewport_api.camera_path.pathString capture_instance = CaptureExtension().get_instance() capture_instance.options = options capture_instance.start() await wait_for_image_writing(exr_path) options = None capture_instance = None gc.collect() assert os.path.isfile(exr_path)
2,027
Python
37.26415
107
0.702023
omniverse-code/kit/exts/omni.kit.window.imguidebug/config/extension.toml
[package] title = "ImguiDebugWindows" description = "Extension to enable low-level debug windows" authors = ["NVIDIA"] version = "1.0.0" changelog="docs/CHANGELOG.md" readme = "docs/README.md" repository = "" [dependencies] "omni.ui" = {} [[native.plugin]] path = "bin/*.plugin" recursive = false [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/rtx-transient/debugwindows/enable=true", "--/rtx-transient/debugwindows/TestWindow=true", "--/rtx-transient/debugwindows/test=true" ] dependencies = [ "omni.kit.renderer.capture", "omni.kit.ui_test", ]
617
TOML
20.310344
59
0.685575
omniverse-code/kit/exts/omni.kit.window.imguidebug/docs/index.rst
omni.kit.debug.windows module ################################## .. toctree:: :maxdepth: 1 CHANGELOG
109
reStructuredText
12.749998
34
0.458716
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/OmniSkelSchema/_omniSkelSchema.pyi
from __future__ import annotations import pxr.OmniSkelSchema._omniSkelSchema import typing import Boost.Python import pxr.Usd import pxr.UsdGeom __all__ = [ "OmniJoint", "OmniJointBoxShapeAPI", "OmniJointCapsuleShapeAPI", "OmniJointLimitsAPI", "OmniJointShapeAPI", "OmniJointSphereShapeAPI", "OmniSkelBaseAPI", "OmniSkelBaseType", "OmniSkeletonAPI" ] class OmniJoint(pxr.UsdGeom.Xform, pxr.UsdGeom.Xformable, pxr.UsdGeom.Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def CreateBindRotationAttr(*args, **kwargs) -> None: ... @staticmethod def CreateBindScaleAttr(*args, **kwargs) -> None: ... @staticmethod def CreateBindTranslationAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRestRotationAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRestScaleAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRestTranslationAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRetargetRotationAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRetargetScaleAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRetargetTagAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRetargetTranslationAttr(*args, **kwargs) -> None: ... @staticmethod def Define(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetBindRotationAttr(*args, **kwargs) -> None: ... @staticmethod def GetBindScaleAttr(*args, **kwargs) -> None: ... @staticmethod def GetBindTranslationAttr(*args, **kwargs) -> None: ... @staticmethod def GetRestRotationAttr(*args, **kwargs) -> None: ... @staticmethod def GetRestScaleAttr(*args, **kwargs) -> None: ... @staticmethod def GetRestTranslationAttr(*args, **kwargs) -> None: ... @staticmethod def GetRetargetRotationAttr(*args, **kwargs) -> None: ... @staticmethod def GetRetargetScaleAttr(*args, **kwargs) -> None: ... @staticmethod def GetRetargetTagAttr(*args, **kwargs) -> None: ... @staticmethod def GetRetargetTranslationAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetSkeletonAndJointToken(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 40 pass class OmniJointBoxShapeAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetSize(*args, **kwargs) -> None: ... @staticmethod def SetSize(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class OmniJointCapsuleShapeAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetHeight(*args, **kwargs) -> None: ... @staticmethod def GetRadius(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def SetHeight(*args, **kwargs) -> None: ... @staticmethod def SetRadius(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class OmniJointLimitsAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def CreateEnabledAttr(*args, **kwargs) -> None: ... @staticmethod def CreateOffsetRotationAttr(*args, **kwargs) -> None: ... @staticmethod def CreateSwingHorizontalAngleAttr(*args, **kwargs) -> None: ... @staticmethod def CreateSwingVerticalAngleAttr(*args, **kwargs) -> None: ... @staticmethod def CreateTwistMaximumAngleAttr(*args, **kwargs) -> None: ... @staticmethod def CreateTwistMinimumAngleAttr(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetEnabledAttr(*args, **kwargs) -> None: ... @staticmethod def GetLocalTransform(*args, **kwargs) -> None: ... @staticmethod def GetOffsetRotationAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetSwingHorizontalAngleAttr(*args, **kwargs) -> None: ... @staticmethod def GetSwingVerticalAngleAttr(*args, **kwargs) -> None: ... @staticmethod def GetTwistMaximumAngleAttr(*args, **kwargs) -> None: ... @staticmethod def GetTwistMinimumAngleAttr(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class OmniJointShapeAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def CreateXformOpOrderAttr(*args, **kwargs) -> None: ... @staticmethod def CreateXformOpRotateXYZAttr(*args, **kwargs) -> None: ... @staticmethod def CreateXformOpScaleAttr(*args, **kwargs) -> None: ... @staticmethod def CreateXformOpTranslateAttr(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetLocalTransform(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetXformOpOrderAttr(*args, **kwargs) -> None: ... @staticmethod def GetXformOpRotateXYZAttr(*args, **kwargs) -> None: ... @staticmethod def GetXformOpScaleAttr(*args, **kwargs) -> None: ... @staticmethod def GetXformOpTranslateAttr(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class OmniJointSphereShapeAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetRadius(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def SetRadius(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class OmniSkelBaseAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class OmniSkelBaseType(pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Define(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 40 pass class OmniSkeletonAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def CreateForwardAxisAttr(*args, **kwargs) -> None: ... @staticmethod def CreateUpAxisAttr(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetForwardAxisAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetUpAxisAttr(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class _CanApplyResult(Boost.Python.instance): @property def whyNot(self) -> None: """ :type: None """ __instance_size__ = 56 pass __MFB_FULL_PACKAGE_NAME = 'omniSkelSchema'
8,960
unknown
34.418972
139
0.635826
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/AnimationSchemaTools/_animationSchemaTools.pyi
from __future__ import annotations import pxr.AnimationSchemaTools._animationSchemaTools import typing import Boost.Python __all__ = [ "AddAnimation", "AddCurve", "AddCurves", "AddKey", "AddKeys", "ComputeTangent", "CopyKey", "DeleteAnimation", "DeleteCurves", "DeleteInfinityType", "DeleteKey", "GetAllKeys", "GetCurves", "GetKey", "GetKeys", "GetTangentControlStrategy", "HasAnimation", "HasCurve", "HasInfinityType", "HasKey", "Key", "MoveKey", "RaiseTimeSamplesToEditTarget", "SetInfinityType", "SetKey", "SwitchEditTargetForSessionLayer", "TangentControlStrategy", "testSkelRoot", "verifySkelAnimation" ] class Key(Boost.Python.instance): @staticmethod def GetRelativeInTangentX(*args, **kwargs) -> None: ... @staticmethod def GetRelativeOutTangentX(*args, **kwargs) -> None: ... @property def broken(self) -> None: """ :type: None """ @property def inRawTangent(self) -> None: """ :type: None """ @property def inTangentType(self) -> None: """ :type: None """ @property def outRawTangent(self) -> None: """ :type: None """ @property def outTangentType(self) -> None: """ :type: None """ @property def time(self) -> None: """ :type: None """ @property def value(self) -> None: """ :type: None """ @property def weighted(self) -> None: """ :type: None """ __instance_size__ = 88 __safe_for_unpickling__ = True pass class TangentControlStrategy(Boost.Python.instance): @staticmethod def ValidateInControl(*args, **kwargs) -> None: ... @staticmethod def ValidateOutControl(*args, **kwargs) -> None: ... __instance_size__ = 32 pass def AddAnimation(*args, **kwargs) -> None: pass def AddCurve(*args, **kwargs) -> None: pass def AddCurves(*args, **kwargs) -> None: pass def AddKey(*args, **kwargs) -> None: pass def AddKeys(*args, **kwargs) -> None: pass def ComputeTangent(*args, **kwargs) -> None: pass def CopyKey(*args, **kwargs) -> None: pass def DeleteAnimation(*args, **kwargs) -> None: pass def DeleteCurves(*args, **kwargs) -> None: pass def DeleteInfinityType(*args, **kwargs) -> None: pass def DeleteKey(*args, **kwargs) -> None: pass def GetAllKeys(*args, **kwargs) -> None: pass def GetCurves(*args, **kwargs) -> None: pass def GetKey(*args, **kwargs) -> None: pass def GetKeys(*args, **kwargs) -> None: pass def GetTangentControlStrategy(*args, **kwargs) -> None: pass def HasAnimation(*args, **kwargs) -> None: pass def HasCurve(*args, **kwargs) -> None: pass def HasInfinityType(*args, **kwargs) -> None: pass def HasKey(*args, **kwargs) -> None: pass def MoveKey(*args, **kwargs) -> None: pass def RaiseTimeSamplesToEditTarget(*args, **kwargs) -> None: pass def SetInfinityType(*args, **kwargs) -> None: pass def SetKey(*args, **kwargs) -> None: pass def SwitchEditTargetForSessionLayer(*args, **kwargs) -> None: pass def testSkelRoot(*args, **kwargs) -> None: pass def verifySkelAnimation(*args, **kwargs) -> None: pass __MFB_FULL_PACKAGE_NAME = 'animationSchemaTools'
3,422
unknown
21.973154
61
0.590006
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/AnimationSchema/_animationSchema.pyi
from __future__ import annotations import pxr.AnimationSchema._animationSchema import typing import Boost.Python import pxr.AnimationSchema import pxr.Usd import pxr.UsdGeom __all__ = [ "AnimationCurveAPI", "AnimationData", "AnimationDataAPI", "GetTangentControlStrategy", "Infinity", "Key", "SkelAnimationAnnotation", "SkelJoint", "Tangent", "TangentControlStrategy", "Tokens" ] class AnimationCurveAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def DeleteCurve(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetCurves(*args, **kwargs) -> None: ... @staticmethod def GetDefaultTangentType(*args, **kwargs) -> None: ... @staticmethod def GetInfinityType(*args, **kwargs) -> None: ... @staticmethod def GetKeys(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetTicksPerSecond(*args, **kwargs) -> None: ... @staticmethod def SetDefaultTangentType(*args, **kwargs) -> None: ... @staticmethod def SetInfinityType(*args, **kwargs) -> None: ... @staticmethod def SetKeys(*args, **kwargs) -> None: ... @staticmethod def ValidateKeys(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class AnimationData(pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Define(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 40 pass class AnimationDataAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def CreateAnimationDataBindingRel(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetAnimationDataBindingRel(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class Infinity(Boost.Python.enum, int): Post = pxr.AnimationSchema.Infinity.Post Pre = pxr.AnimationSchema.Infinity.Pre __slots__ = () names = {'Pre': pxr.AnimationSchema.Infinity.Pre, 'Post': pxr.AnimationSchema.Infinity.Post} values = {0: pxr.AnimationSchema.Infinity.Pre, 1: pxr.AnimationSchema.Infinity.Post} pass class Key(Boost.Python.instance): @property def inTangent(self) -> None: """ :type: None """ @property def outTangent(self) -> None: """ :type: None """ @property def tangentBroken(self) -> None: """ :type: None """ @property def tangentWeighted(self) -> None: """ :type: None """ @property def time(self) -> None: """ :type: None """ @property def value(self) -> None: """ :type: None """ __instance_size__ = 88 pass class SkelAnimationAnnotation(pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def CreateEndAttr(*args, **kwargs) -> None: ... @staticmethod def CreateStartAttr(*args, **kwargs) -> None: ... @staticmethod def CreateTagAttr(*args, **kwargs) -> None: ... @staticmethod def Define(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetEndAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetStartAttr(*args, **kwargs) -> None: ... @staticmethod def GetTagAttr(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 40 pass class SkelJoint(pxr.UsdGeom.Boundable, pxr.UsdGeom.Xformable, pxr.UsdGeom.Imageable, pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def CreateHideAttr(*args, **kwargs) -> None: ... @staticmethod def Define(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetHideAttr(*args, **kwargs) -> None: ... @staticmethod def GetJoint(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 40 pass class Tangent(Boost.Python.instance): @property def time(self) -> None: """ :type: None """ @property def type(self) -> None: """ :type: None """ @property def value(self) -> None: """ :type: None """ __instance_size__ = 40 pass class TangentControlStrategy(Boost.Python.instance): @staticmethod def ValidateInControl(*args, **kwargs) -> None: ... @staticmethod def ValidateOutControl(*args, **kwargs) -> None: ... __instance_size__ = 32 pass class Tokens(Boost.Python.instance): animationDataBinding = 'animationData:binding' auto_ = 'auto' constant = 'constant' cycle = 'cycle' cycleRelative = 'cycleRelative' defaultTangentType = 'defaultTangentType' end = 'end' fixed = 'fixed' flat = 'flat' hide = 'hide' inTangentTimes = 'inTangentTimes' inTangentTypes = 'inTangentTypes' inTangentValues = 'inTangentValues' linear = 'linear' oscillate = 'oscillate' outTangentTimes = 'outTangentTimes' outTangentTypes = 'outTangentTypes' outTangentValues = 'outTangentValues' postInfinityType = 'postInfinityType' preInfinityType = 'preInfinityType' smooth = 'smooth' start = 'start' step = 'step' tag = 'tag' tangentBrokens = 'tangentBrokens' tangentWeighteds = 'tangentWeighteds' times = 'times' values = 'values' pass class _CanApplyResult(Boost.Python.instance): @property def whyNot(self) -> None: """ :type: None """ __instance_size__ = 56 pass def GetTangentControlStrategy(*args, **kwargs) -> None: pass __MFB_FULL_PACKAGE_NAME = 'animationSchema'
6,668
unknown
28.378855
143
0.612028
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/RetargetingSchema/_retargetingSchema.pyi
from __future__ import annotations import pxr.RetargetingSchema._retargetingSchema import typing import Boost.Python import pxr.Usd __all__ = [ "AnimationSkelBindingAPI", "ControlRigAPI", "JointConstraint" ] class AnimationSkelBindingAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def BakeRetargetedSkelAnimation(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def ComputeRetargetedJointLocalTransforms(*args, **kwargs) -> None: ... @staticmethod def CreateSourceSkeletonRel(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetSourceSkeleton(*args, **kwargs) -> None: ... @staticmethod def GetSourceSkeletonRel(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class ControlRigAPI(pxr.Usd.APISchemaBase, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def Apply(*args, **kwargs) -> None: ... @staticmethod def CanApply(*args, **kwargs) -> None: ... @staticmethod def CreateForwardAxisAttr(*args, **kwargs) -> None: ... @staticmethod def CreateIKTargetsAttr(*args, **kwargs) -> None: ... @staticmethod def CreateJointConstraintsRel(*args, **kwargs) -> None: ... @staticmethod def CreateJointTagsAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRetargetTagsAttr(*args, **kwargs) -> None: ... @staticmethod def CreateRetargetTransformsAttr(*args, **kwargs) -> None: ... @staticmethod def CreateTypeAttr(*args, **kwargs) -> None: ... @staticmethod def CreateUpAxisAttr(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetForwardAxisAttr(*args, **kwargs) -> None: ... @staticmethod def GetIKTargetsAttr(*args, **kwargs) -> None: ... @staticmethod def GetJointConstraintsRel(*args, **kwargs) -> None: ... @staticmethod def GetJointTagsAttr(*args, **kwargs) -> None: ... @staticmethod def GetRetargetTagsAttr(*args, **kwargs) -> None: ... @staticmethod def GetRetargetTransformsAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetTypeAttr(*args, **kwargs) -> None: ... @staticmethod def GetUpAxisAttr(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 48 pass class JointConstraint(pxr.Usd.Typed, pxr.Usd.SchemaBase, Boost.Python.instance): @staticmethod def CreateFrameAttr(*args, **kwargs) -> None: ... @staticmethod def CreateJointAttr(*args, **kwargs) -> None: ... @staticmethod def CreateSwingAttr(*args, **kwargs) -> None: ... @staticmethod def CreateTwistAttr(*args, **kwargs) -> None: ... @staticmethod def Define(*args, **kwargs) -> None: ... @staticmethod def Get(*args, **kwargs) -> None: ... @staticmethod def GetFrameAttr(*args, **kwargs) -> None: ... @staticmethod def GetJointAttr(*args, **kwargs) -> None: ... @staticmethod def GetSchemaAttributeNames(*args, **kwargs) -> None: ... @staticmethod def GetSwingAttr(*args, **kwargs) -> None: ... @staticmethod def GetTwistAttr(*args, **kwargs) -> None: ... @staticmethod def _GetStaticTfType(*args, **kwargs) -> None: ... __instance_size__ = 40 pass class _CanApplyResult(Boost.Python.instance): @property def whyNot(self) -> None: """ :type: None """ __instance_size__ = 56 pass __MFB_FULL_PACKAGE_NAME = 'retargetingSchema'
3,957
unknown
32.542373
96
0.632044
omniverse-code/kit/exts/omni.usd.schema.anim/pxr/RetargetingSchemaTools/_retargetingSchemaTools.pyi
from __future__ import annotations import pxr.RetargetingSchemaTools._retargetingSchemaTools import typing __all__ = [ "testSkelRoot", "verifySkelAnimation" ] def testSkelRoot(*args, **kwargs) -> None: pass def verifySkelAnimation(*args, **kwargs) -> None: pass __MFB_FULL_PACKAGE_NAME = 'retargetingSchemaTools'
332
unknown
19.812499
57
0.71988
omniverse-code/kit/exts/omni.hydra.ui/omni/hydra/ui/scripts/extension.py
import omni.ext from .settings import OmniHydraSettings class PublicExtension(omni.ext.IExt): def on_startup(self): self._settings = OmniHydraSettings() def on_shutdown(self): self._settings = None
225
Python
19.545453
44
0.697778
omniverse-code/kit/exts/omni.hydra.ui/omni/hydra/ui/scripts/settings.py
import asyncio import omni.ui import omni.kit.app import omni.kit.commands import carb.settings ### Copied from omni.phyx; Kit team will coalesce into omni.ui.settings module class Model(omni.ui.AbstractValueModel): def __init__(self, path): super().__init__() self._path = path val = carb.settings.get_settings().get(path) if val is None: val = 0 self._value = val def on_change(item, event_type, path=path): self._value = carb.settings.get_settings().get(path) self._value_changed() self._sub = omni.kit.app.SettingChangeSubscription(path, on_change) def get_value_as_bool(self): return self._value def get_value_as_int(self): return self._value def get_value_as_float(self): return self._value def get_value_as_string(self): return self._value def set_value(self, value): omni.kit.commands.execute("ChangeSetting", path=self._path, value=value) self._value = value self._value_changed() def create_setting_widget(setting_path, cls, **kwargs): model = Model(setting_path) widget = cls(model, **kwargs) return (model, widget) ### end omni.physx boilerplate class OmniHydraSettings(omni.ui.Window): def __init__(self): self._title = "OmniHydra Developer Settings" super().__init__(self._title, omni.ui.DockPreference.LEFT_BOTTOM, width=800, height=600) self._widgets = [] with self.frame: self._build_ui() asyncio.ensure_future(self._dock_window(self._title, omni.ui.DockPosition.SAME)) async def _dock_window(self, window_title: str, position: omni.ui.DockPosition, ratio: float = 1.0): frames = 3 while frames > 0: if omni.ui.Workspace.get_window(window_title): break frames = frames - 1 await omni.kit.app.get_app().next_update_async() window = omni.ui.Workspace.get_window(window_title) dockspace = omni.ui.Workspace.get_window("Property") if window and dockspace: window.dock_in(dockspace, position, ratio=ratio) window.dock_tab_bar_visible = False def on_shutdown(self): self._widgets = [] def _add_setting_widget(self, name, path, cls, **kwargs): with omni.ui.VStack(): omni.ui.Spacer(height=2) with omni.ui.HStack(height=20): self._widgets.append(create_setting_widget(path, cls, **kwargs)) omni.ui.Label(name) def _build_settings_ui(self): self._add_setting_widget("Use fast scene delegate", "/persistent/omnihydra/useFastSceneDelegate", omni.ui.CheckBox) self._add_setting_widget("Use scene graph instancing", "/persistent/omnihydra/useSceneGraphInstancing", omni.ui.CheckBox) self._add_setting_widget("Use skel adapter", "/persistent/omnihydra/useSkelAdapter", omni.ui.CheckBox) self._add_setting_widget("Use skel adapter blendshape", "/persistent/omnihydra/useSkelAdapterBlendShape", omni.ui.CheckBox) self._add_setting_widget("Use skel adapter deform graph", "/persistent/omnihydra/useSkelAdapterDeformGraph", omni.ui.CheckBox) self._add_setting_widget("Use cached xform time samples", "/persistent/omnihydra/useCachedXformTimeSamples", omni.ui.CheckBox) self._add_setting_widget("Use async RenderGraph in _PullFromRingBuffer", "/persistent/omnihydra/useAsyncRenderGraph", omni.ui.CheckBox) self._add_setting_widget("Use fast xform path from Fabric to renderer", "/persistent/rtx/hydra/readTransformsFromFabricInRenderDelegate", omni.ui.CheckBox) def _build_usdrt_settings_ui(self): self._add_setting_widget("Use Fabric World Bounds", "/app/omni.usd/useFabricWorldBounds", omni.ui.CheckBox) self._add_setting_widget("Use camera-based priority sorting", "/app/usdrt/scene_delegate/useWorldInterestBasedSorting", omni.ui.CheckBox) self._add_setting_widget("GPU Memory Budget %", "/app/usdrt/scene_delegate/gpuMemoryBudgetPercent", omni.ui.FloatSlider, min=0., max=100.) with omni.ui.CollapsableFrame("Geometry Streaming"): with omni.ui.VStack(): self._add_setting_widget("Enable geometry streaming", "/app/usdrt/scene_delegate/geometryStreaming/enabled", omni.ui.CheckBox) self._add_setting_widget("Enable proxy cubes for unloaded prims", "/app/usdrt/scene_delegate/enableProxyCubes", omni.ui.CheckBox) self._add_setting_widget("Solid Angle Loading To Load in first batch", "/app/usdrt/scene_delegate/geometryStreaming/solidAngleToLoadInFirstChunk", omni.ui.FloatSlider, min=0, max=1, step=0.0001) self._add_setting_widget("Solid Angle Loading Limit", "/app/usdrt/scene_delegate/geometryStreaming/solidAngleLimit", omni.ui.FloatSlider, min=0, max=1, step=0.0001) self._add_setting_widget("Solid Angle Loading Limit Divider", "/app/usdrt/scene_delegate/geometryStreaming/solidAngleLimitDivider", omni.ui.FloatSlider, min=1, max=10000, step=100) self._add_setting_widget("Number of frames between batches", "/app/usdrt/scene_delegate/numFramesBetweenLoadBatches", omni.ui.IntSlider, min=1, max=50) self._add_setting_widget("Number of vertices to load per batch", "/app/usdrt/scene_delegate/geometryStreaming/numberOfVerticesToLoadPerChunk", omni.ui.IntSlider, min=1, max=5000000) self._add_setting_widget("Number of vertices to unload per batch", "/app/usdrt/scene_delegate/geometryStreaming/numberOfVerticesToUnloadPerChunk", omni.ui.IntSlider, min=1, max=5000000) self._add_setting_widget("Number of cubes proxy instances per instancer", "/app/usdrt/scene_delegate/proxyInstanceBucketSize", omni.ui.IntSlider, min=0, max=200000) with omni.ui.CollapsableFrame("Memory Budget Experimental Stability Values"): with omni.ui.VStack(): self._add_setting_widget("Update Delay in microseconds", "/app/usdrt/scene_delegate/updateDelayInMicroSeconds", omni.ui.IntSlider, min=0, max=1000000) self._add_setting_widget("GPU Memory Deadzone %", "/app/usdrt/scene_delegate/gpuMemoryBudgetDeadZone", omni.ui.FloatSlider, min=0., max=50.) self._add_setting_widget("GPU Memory Filter Damping", "/app/usdrt/scene_delegate/gpuMemoryFilterDamping", omni.ui.FloatSlider, min=0., max=2.) with omni.ui.CollapsableFrame("Memory Limit Testing (pretend values)"): with omni.ui.VStack(): self._add_setting_widget("Enable memory testing", "/app/usdrt/scene_delegate/testing/enableMemoryTesting", omni.ui.CheckBox) self._add_setting_widget("GPU Memory Available", "/app/usdrt/scene_delegate/testing/availableDeviceMemory", omni.ui.FloatSlider, min=0., max=float(1024*1024*1024*8)) self._add_setting_widget("GPU Memory Total", "/app/usdrt/scene_delegate/testing/totalDeviceMemory", omni.ui.FloatSlider, min=0., max=float(1024*1024*1024*8)) with omni.ui.CollapsableFrame("USD Population (reload scene to see effect)"): with omni.ui.VStack(): self._add_setting_widget("Read Curves", "/app/usdrt/population/utils/readCurves", omni.ui.CheckBox) self._add_setting_widget("Read Materials", "/app/usdrt/population/utils/readMaterials", omni.ui.CheckBox) self._add_setting_widget("Read Lights", "/app/usdrt/population/utils/readLights", omni.ui.CheckBox) self._add_setting_widget("Read Primvars", "/app/usdrt/population/utils/readPrimvars", omni.ui.CheckBox) self._add_setting_widget("Enable Subcomponent merging", "/app/usdrt/population/utils/mergeSubcomponents", omni.ui.CheckBox) self._add_setting_widget("Enable Instance merging", "/app/usdrt/population/utils/mergeInstances", omni.ui.CheckBox) self._add_setting_widget("Enable Material merging", "/app/usdrt/population/utils/mergeMaterials", omni.ui.CheckBox) self._add_setting_widget("Single-threaded population", "/app/usdrt/population/utils/singleThreaded", omni.ui.CheckBox) self._add_setting_widget("Disable Light Scaling (non-RTX delegates)", "/app/usdrt/scene_delegate/disableLightScaling", omni.ui.CheckBox) self._add_setting_widget("Use Fabric Scene Graph Instancing", "/app/usdrt/population/utils/handleSceneGraphInstances", omni.ui.CheckBox) self._add_setting_widget("Use Hydra BlendShape", "/app/usdrt/scene_delegate/useHydraBlendShape", omni.ui.CheckBox) self._add_setting_widget("Number of IO threads", "/app/usdrt/population/utils/ioBoundThreadCount", omni.ui.IntSlider, min=1, max=16) def _build_section(self, name, build_func): with omni.ui.CollapsableFrame(name, height=0): with omni.ui.HStack(): omni.ui.Spacer(width=20, height=5) with omni.ui.VStack(): build_func() def _build_ui(self): with omni.ui.ScrollingFrame(horizontal_scrollbar_policy=omni.ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=omni.ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED): with omni.ui.VStack(): self._build_section("Settings (requires stage reload)", self._build_settings_ui) self._build_section("USDRT Hydra Settings", self._build_usdrt_settings_ui)
9,531
Python
63.405405
210
0.676634
omniverse-code/kit/exts/omni.kit.window.extensions/ext_template/README.md
# Extension Project Template This project was automatically generated. - `app` - It is a folder link to the location of your *Omniverse Kit* based app. - `exts` - It is a folder where you can add new extensions. It was automatically added to extension search path. (Extension Manager -> Gear Icon -> Extension Search Path). Open this folder using Visual Studio Code. It will suggest you to install few extensions that will make python experience better. Look for "${ext_id}" extension in extension manager and enable it. Try applying changes to any python files, it will hot-reload and you can observe results immediately. Alternatively, you can launch your app from console with this folder added to search path and your extension enabled, e.g.: ``` > app\omni.code.bat --ext-folder exts --enable company.hello.world ``` # App Link Setup If `app` folder link doesn't exist or broken it can be created again. For better developer experience it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. Convenience script to use is included. Run: ``` > link_app.bat ``` If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app: ``` > link_app.bat --app create ``` You can also just pass a path to create link to: ``` > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4" ``` # Sharing Your Extensions This folder is ready to be pushed to any git repository. Once pushed direct link to a git repository can be added to *Omniverse Kit* extension search paths. Link might look like this: `git://github.com/[user]/[your_repo].git?branch=main&dir=exts` Notice `exts` is repo subfolder with extensions. More information can be found in "Git URL as Extension Search Paths" section of developers manual. To add a link to your *Omniverse Kit* based app go into: Extension Manager -> Gear Icon -> Extension Search Path
2,033
Markdown
37.377358
258
0.755042