file_path
stringlengths
22
162
content
stringlengths
19
501k
size
int64
19
501k
lang
stringclasses
1 value
avg_line_length
float64
6.33
100
max_line_length
int64
18
935
alphanum_fraction
float64
0.34
0.93
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/__init__.py
from .file_window import *
27
Python
12.999994
26
0.740741
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/file_actions.py
import omni.kit.actions.core from .app_ui import AppUI, DialogOptions def register_actions(extension_id): import omni.kit.window.file action_registry = omni.kit.actions.core.get_action_registry() actions_tag = "File Actions" action_registry.register_action( extension_id, "new", omni.kit.window.file.new, display_name="File->New", description="Create a new USD stage.", tag=actions_tag, ) action_registry.register_action( extension_id, "open", omni.kit.window.file.open, display_name="File->Open", description="Open an existing USD stage.", tag=actions_tag, ) action_registry.register_action( extension_id, "open_stage", omni.kit.window.file.open_stage, display_name="File->Open Stage", description="Open an named USD stage.", tag=actions_tag, ) action_registry.register_action( extension_id, "reopen", omni.kit.window.file.reopen, display_name="File->Reopen", description="Reopen the currently opened USD stage.", tag=actions_tag, ) action_registry.register_action( extension_id, "open_with_new_edit_layer", omni.kit.window.file.open_with_new_edit_layer, display_name="File->Open With New Edit Layer", description="Open an existing USD stage with a new edit layer.", tag=actions_tag, ) action_registry.register_action( extension_id, "share", omni.kit.window.file.share, display_name="File->Share", description="Share the currently open USD stage.", tag=actions_tag, ) action_registry.register_action( extension_id, "save", lambda: omni.kit.window.file.save(dialog_options=DialogOptions.HIDE), display_name="File->Save", description="Save the currently opened USD stage to file.", tag=actions_tag, ) action_registry.register_action( extension_id, "save_with_options", lambda: omni.kit.window.file.save(dialog_options=DialogOptions.NONE), display_name="File->Save With Options", description="Save the currently opened USD stage to file.", tag=actions_tag, ) action_registry.register_action( extension_id, "save_as", lambda: omni.kit.window.file.save_as(False), display_name="File->Save As", description="Save the currently opened USD stage to a new file.", tag=actions_tag, ) action_registry.register_action( extension_id, "save_as_flattened", lambda: omni.kit.window.file.save_as(True), display_name="File->Save As Flattened", description="Save the currently opened USD stage to a new flattened file.", tag=actions_tag, ) action_registry.register_action( extension_id, "add_reference", lambda: omni.kit.window.file.add_reference(is_payload=False), display_name="File->Add Reference", description="Add a reference to a file.", tag=actions_tag, ) action_registry.register_action( extension_id, "add_payload", lambda: omni.kit.window.file.add_reference(is_payload=True), display_name="File->Add Payload", description="Add a payload to a file.", tag=actions_tag, ) def deregister_actions(extension_id): action_registry = omni.kit.actions.core.get_action_registry() action_registry.deregister_all_actions_for_extension(extension_id)
3,626
Python
31.383928
83
0.621897
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/file_window.py
"""USD File interaction for Omniverse Kit. :mod:`omni.kit.window.file` provides util functions to new/open/save/close USD files. It handles file picking dialog and prompt for unsaved stage. """ import os import time import traceback import asyncio from typing import Awaitable, Callable, List import carb import omni.ext import omni.usd import omni.kit.app import omni.kit.helper.file_utils as file_utils from pathlib import Path from functools import partial from omni.kit.helper.file_utils import asset_types import omni.kit.usd.layers as layers from omni.kit.window.file_importer import get_file_importer from omni.kit.window.file_exporter import get_file_exporter from omni.kit.widget.nucleus_connector import get_nucleus_connector from .prompt_ui import Prompt from .read_only_options_window import ReadOnlyOptionsWindow from .share_window import ShareWindow from .app_ui import AppUI, DialogOptions, SaveOptionsDelegate, OpenOptionsDelegate from .file_actions import register_actions, deregister_actions from pxr import Tf, Sdf, Usd, UsdGeom, UsdUtils _extension_instance = None TEST_DATA_PATH = "" IGNORE_UNSAVED_ON_EXIT_PATH = "/app/file/ignoreUnsavedOnExit" IGNORE_UNSAVED_STAGE = "/app/file/ignoreUnsavedStage" LAST_OPENED_DIRECTORY = "/persistent/app/omniverse/lastOpenDirectory" SHOW_UNSAVED_LAYERS_DIALOG = "/persistent/app/file/save/showUnsavedLayersDialog" class _CheckpointCommentContext: def __init__(self, comment: str): self._comment = comment def __enter__(self): try: import omni.usd_resolver omni.usd_resolver.set_checkpoint_message(self._comment) except Exception as e: carb.log_error(f"Failed to import omni.usd_resolver: {str(e)}.") return self def __exit__(self, type, value, trace): try: import omni.usd_resolver omni.usd_resolver.set_checkpoint_message("") except Exception: pass class _CallbackRegistrySubscription: """ Simple subscription. _Event has callback while this object exists. """ def __init__(self, callback_list: List, callback: Callable): """ Save the callback in the given list. """ self.__callback_list: List = callback_list self.__callback = callback callback_list.append(callback) def __del__(self): """Called by GC.""" self.__callback_list.remove(self.__callback) class FileWindowExtension(omni.ext.IExt): def on_startup(self, ext_id): global _extension_instance _extension_instance = self self._open_stage_callbacks: List = [] self._open_stage_complete_callbacks: List = [] self.ui_handler = None self._task = None self._unsaved_stage_prompt = None self._file_existed_prompt = None self._open_readonly_usd_prompt = None self._app = omni.kit.app.get_app() self._settings = carb.settings.get_settings() self._settings.set_default_bool(IGNORE_UNSAVED_ON_EXIT_PATH, False) self.ui_handler = AppUI() self._save_options = None self._open_options = None self._share_window = None 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_event(e: carb.events.IEvent): if e.type == omni.kit.app.POST_QUIT_EVENT_TYPE: ignore_unsaved_file_on_exit = self._settings.get(IGNORE_UNSAVED_ON_EXIT_PATH) usd_context = omni.usd.get_context() if not ignore_unsaved_file_on_exit and usd_context.can_close_stage() and usd_context.has_pending_edit(): self._app.try_cancel_shutdown("Interrupting shutdown - closing stage first") # OM-52366: fast shutdown will not close stage but post quit directly. fast_shutdown = carb.settings.get_settings().get("/app/fastShutdown") self.close(lambda *args: omni.kit.app.get_app().post_quit(), fast_shutdown=fast_shutdown) self._shutdown_subs = self._app.get_shutdown_event_stream().create_subscription_to_pop( on_event, name="window.file shutdown hook", order=0 ) self._ext_name = omni.ext.get_extension_name(ext_id) register_actions(self._ext_name) def on_shutdown(self): deregister_actions(self._ext_name) self._shutdown_subs = None self._save_options = None self._open_options = None if self._task: self._task.cancel() self._task = None if self._unsaved_stage_prompt: self._unsaved_stage_prompt.destroy() self._unsaved_stage_prompt = None if self._file_existed_prompt: self._file_existed_prompt.destroy() self._file_existed_prompt = None if self._open_readonly_usd_prompt: self._open_readonly_usd_prompt.destroy() self._open_readonly_usd_prompt = None global _extension_instance _extension_instance = None if self.ui_handler: self.ui_handler.destroy() self.ui_handler = None def stop_timeline(self): try: import omni.timeline timeline = omni.timeline.get_timeline_interface() if timeline: timeline.stop() else: carb.log_warn(f"Failed to stop timeline, get_timeline_interface() return None") except ModuleNotFoundError: carb.log_warn(f"Failed to stop timeline, omni.timeline not loaded") def new(self, template=None): """Create a new USD stage. If currently opened stage is dirty, a prompt will show to let you save it.""" self.stop_timeline() async def new_stage_job(): # FIXME: Delay two frames to center prompt. await self._app.next_update_async() await self._app.next_update_async() with Prompt("Please Wait", "Creating new stage...", [], [], True): await self._app.next_update_async() # Making sure prompt shows await omni.kit.stage_templates.new_stage_async(template=template) await self._app.next_update_async() # Wait anther frame for StageEvent.OPENED to be handled self.prompt_if_unsaved_stage(lambda *_: self._exclusive_task_wrapper(new_stage_job)) def open(self, open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL): """Bring up a file picker to choose a USD file to open. If currently opened stage is dirty, a prompt will show to let you save it.""" self.stop_timeline() def open_handler(loadset: int, filename: str, dirname: str, selections: List[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\...' path = filename else: path = f"{dirname or ''}/{filename}" if not omni.usd.is_usd_readable_filetype(path): FileWindowExtension.post_notification(f"Cannot open {path}. No valid stage") return result, entry = omni.client.stat(path) if result != omni.client.Result.OK: carb.log_warn(f"Failed to stat '{path}', attempting to open in read-only mode.") read_only = True else: # https://nvidia-omniverse.atlassian.net/browse/OM-45124 read_only = entry.access & omni.client.AccessFlags.WRITE == 0 if read_only: def _open_with_edit_layer(): self.open_with_new_edit_layer(path, open_loadset) def _open_original_stage(): self.open_stage(path, open_loadset, open_options=self._open_options) self._show_readonly_usd_prompt(_open_with_edit_layer, _open_original_stage) else: self.open_stage(path, open_loadset=loadset, open_options=self._open_options) file_importer = get_file_importer() if file_importer: file_importer.show_window( title="Open File", import_button_label="Open File", import_handler=partial(open_handler, open_loadset), ) if self._open_options is None: self._open_options = OpenOptionsDelegate() file_importer.add_import_options_frame("Options", self._open_options) def open_stage(self, path, open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL, open_options: OpenOptionsDelegate=None, callback: callable=None): """open stage. If the current stage is dirty, a prompt will show to let you save it.""" if not omni.usd.is_usd_readable_filetype(path): FileWindowExtension.post_notification(f"Cannot open {path}. No valid stage") if callback: callback(False) return self.stop_timeline() ui_handler = self.ui_handler self._settings.set(LAST_OPENED_DIRECTORY, os.path.dirname(path)) checkbox = None if open_options: checkbox = open_options.should_load_payload() if not checkbox: # open with payloads disabled open_loadset = omni.usd.UsdContextInitialLoadSet.LOAD_NONE async def open_stage_job(): # FIXME: Delay two frames to center prompt. await self._app.next_update_async() await self._app.next_update_async() prompt = Prompt("Please Wait", f"Opening {path}...", [], [], True, self._open_stage_callbacks, self._open_stage_complete_callbacks) prompt._window.width = 415 with prompt: context = omni.usd.get_context() start_time = time.time() result, err = await context.open_stage_async(path, open_loadset) success = True if not result or context.get_stage_state() != omni.usd.StageState.OPENED: success = False carb.log_error(f"Failed to open stage {path}: {err}") ui_handler.show_open_stage_failed_prompt(path) else: stage = context.get_stage() identifier = stage.GetRootLayer().identifier if not stage.GetRootLayer().anonymous: message_bus = omni.kit.app.get_app().get_message_bus_event_stream() message_bus.push(file_utils.FILE_OPENED_EVENT, payload=file_utils.FileEventModel(url=identifier).dict()) open_duration = time.time() - start_time omni.kit.app.send_telemetry_event("omni.kit.window.file@open_stage", duration=open_duration, data1=path, value1=float(success)) if callback: callback(False) async def open_stage_async(): result, _ = await omni.client.stat_async(path) if result == omni.client.Result.OK: FileWindowExtension._exclusive_task_wrapper(open_stage_job) return # Attempt to connect to nucleus server broken_url = omni.client.break_url(path) if broken_url.scheme == 'omniverse': server_url = omni.client.make_url(scheme='omniverse', host=broken_url.host) nucleus_connector = get_nucleus_connector() if nucleus_connector: nucleus_connector.connect(broken_url.host, server_url, on_success_fn=lambda *_: FileWindowExtension._exclusive_task_wrapper(open_stage_job), on_failed_fn=lambda *_: carb.log_error(f"Invalid stage URL: {path}") ) else: carb.log_error(f"Invalid stage URL: {path}") self.prompt_if_unsaved_stage(lambda *_: asyncio.ensure_future(open_stage_async())) def _show_readonly_usd_prompt(self, ok_fn, middle_fn): if self._open_readonly_usd_prompt: self._open_readonly_usd_prompt.destroy() self._open_readonly_usd_prompt = ReadOnlyOptionsWindow(ok_fn, middle_fn) self._open_readonly_usd_prompt.show() def _show_file_existed_prompt(self, path, on_confirm_fn, on_cancel_fn=None): file_name = os.path.basename(path) if self._file_existed_prompt: self._file_existed_prompt.destroy() self._file_existed_prompt = Prompt( f'{omni.kit.ui.get_custom_glyph_code("${glyphs}/exclamation.svg")} Overwrite', f"File {file_name} already exists, do you want to overwrite it?", ["OK", "Cancel"], [on_confirm_fn, None], False, ) self._file_existed_prompt.show() def open_with_new_edit_layer(self, path: str, open_loadset: int = omni.usd.UsdContextInitialLoadSet.LOAD_ALL, callback: Callable = None): if not omni.usd.is_usd_readable_filetype(path): FileWindowExtension.post_notification(f"Cannot open {path}. No valid stage") return self.stop_timeline() def create_handler(stage_path: str, callback: Callable, filename: str, dirname: str, extension: str = None, selections: List[str] = []): # Allow incoming directory as /path/to/dir or /path/to/dir/ dirname = dirname.rstrip('/') edit_layer_path = f"{dirname}/{filename}{extension}" self.create_stage(edit_layer_path, stage_path, callback=callback) def create_edit_layer(stage_path: str, callback: Callable): file_exporter = get_file_exporter() if file_exporter: dirname = os.path.dirname(stage_path) if Sdf.Layer.IsAnonymousLayerIdentifier(stage_path): basename = Sdf.Layer.GetDisplayNameFromIdentifier(stage_path) else: basename = os.path.basename(stage_path) edit_layer_path = f"{dirname}/{os.path.splitext(basename)[0]}_edit" file_exporter.show_window( title="Create Edit Layer", export_button_label="Save", export_handler=partial(create_handler, stage_path, callback), filename_url=edit_layer_path, ) self.prompt_if_unsaved_stage(lambda: create_edit_layer(path, callback)) def create_stage(self, edit_layer_path: str, file_path: str, callback: Callable = None): self.stop_timeline() async def create_stage_async(edit_layer_path: str, stage_path: str, callback: Callable): edit_layer = Sdf.Layer.FindOrOpen(edit_layer_path) if edit_layer: edit_layer.Clear() else: edit_layer = Sdf.Layer.CreateNew(edit_layer_path) if not edit_layer: carb.log_error(f"open_with_new_edit_layer: failed to create edit layer {edit_layer_path}") return # FIXME: Delay two frames to center prompt. await self._app.next_update_async() await self._app.next_update_async() with Prompt("Please Wait", "Creating new stage...", [], [], True): await self._app.next_update_async() # Making sure prompt shows root_layer = Sdf.Layer.CreateAnonymous() root_layer.subLayerPaths.insert(0, file_path) root_layer.subLayerPaths.insert(0, edit_layer_path) # Copy all meta base_layer = Sdf.Layer.FindOrOpen(file_path) UsdUtils.CopyLayerMetadata(base_layer, root_layer, True) omni.usd.resolve_paths(base_layer.identifier, root_layer.identifier, False, True) # Set edit target stage = Usd.Stage.Open(root_layer) edit_target = Usd.EditTarget(edit_layer) stage.SetEditTarget(edit_target) await omni.usd.get_context().attach_stage_async(stage) await self._app.next_update_async() # Wait anther frame for StageEvent.OPENED to be handled if callback: callback() async def create_stage_prompt_if_exists(edit_layer_path: str, file_path: str, callback: Callable): result, _ = await omni.client.stat_async(edit_layer_path) # File is existed already. if result == omni.client.Result.OK: self._show_file_existed_prompt( edit_layer_path, lambda: FileWindowExtension._exclusive_task_wrapper( create_stage_async, edit_layer_path, file_path, callback ) ) else: await create_stage_async(edit_layer_path, file_path, callback) asyncio.ensure_future(create_stage_prompt_if_exists(edit_layer_path, file_path, callback)) def reopen(self): """Reopen currently opened stage. If the stage is dirty, a prompt will show to let you save it.""" self.stop_timeline() async def reopen_stage_job(): context = omni.usd.get_context() path = context.get_stage_url() # FIXME: Delay two frames to center prompt. await self._app.next_update_async() await self._app.next_update_async() with Prompt("Please Wait", f"Reopening {path}...", [], [], True): await self._app.next_update_async() # Making sure prompt shows result, err = await context.reopen_stage_async() await self._app.next_update_async() # Wait anther frame for StageEvent.OPENED to be handled if not result or context.get_stage_state() != omni.usd.StageState.OPENED: carb.log_error(f"Failed to reopen stage {path}: {err}") self.ui_handler.show_open_stage_failed_prompt(path) if not (omni.usd.get_context().get_stage_state() == omni.usd.StageState.OPENED and not omni.usd.get_context().is_new_stage()): FileWindowExtension.post_notification("Cannot Reopen. No valid stage") return self.prompt_if_unsaved_stage(lambda *_: FileWindowExtension._exclusive_task_wrapper(reopen_stage_job)) def share(self): context = omni.usd.get_context() if context.get_stage_url().startswith("omniverse://"): layers_interface = layers.get_layers(context) live_syncing = layers_interface.get_live_syncing() current_session = live_syncing.get_current_live_session() if not current_session: url = context.get_stage_url() else: url = current_session.shared_link self._share_window = ShareWindow(url=url) def save(self, callback: Callable, allow_skip_sublayers: bool = False): """Save currently opened stage to file. Will call Save As for a newly created stage""" # Syncs render settings to stage before save so stage could # get the correct edit state if render settings are changed. if omni.usd.get_context().get_stage_state() != omni.usd.StageState.OPENED: FileWindowExtension.post_notification("Cannot Save. No valid stage") return self.stop_timeline() async def save_async(callback: Callable, allow_skip_sublayers: bool): is_new_stage = omni.usd.get_context().is_new_stage() or \ omni.usd.get_context().get_stage_state() != omni.usd.StageState.OPENED is_writeable = False try: filename_url = omni.usd.get_context().get_stage().GetRootLayer().identifier result, stat = await omni.client.stat_async(filename_url) except Exception: pass else: if result == omni.client.Result.OK: is_writeable = stat.flags & omni.client.ItemFlags.WRITEABLE_FILE # OM-47514 When saving a checkpoint or read-only file, use save_as instead if is_new_stage or not is_writeable: self.save_as(False, callback, allow_skip_sublayers=allow_skip_sublayers) else: stage = omni.usd.get_context().get_stage() dirty_layer_identifiers = omni.usd.get_dirty_layers(stage, True) self.ui_handler.save_root_and_sublayers("", dirty_layer_identifiers, on_save_done=callback, allow_skip_sublayers=allow_skip_sublayers) asyncio.ensure_future(save_async(callback, allow_skip_sublayers)) def save_as(self, flatten: bool, callback: Callable, allow_skip_sublayers: bool = False): """Bring up a file picker to choose a file to save current stage to.""" self.stop_timeline() def save_handler(callback: Callable, flatten: bool, filename: str, dirname: str, extension: str = '', selections: List[str] = []): path = f"{dirname}/{filename}{extension}" self.save_stage(path, callback=callback, flatten=flatten, save_options=self._save_options, allow_skip_sublayers=allow_skip_sublayers) if omni.usd.get_context().get_stage_state() != omni.usd.StageState.OPENED: FileWindowExtension.post_notification("Cannot Save As. No valid stage") return file_exporter = get_file_exporter() if file_exporter: # OM-48033: Save as should open to latest opened stage path. Solution also covers ... # OM-58150: Save as should pass in the current file name as default value. filename_url = file_utils.get_last_url_visited(asset_type=asset_types.ASSET_TYPE_USD) if filename_url: # OM-91056: File Save As should not prefill the file name filename_url = os.path.dirname(filename_url) + "/" file_exporter.show_window( title="Save File As...", export_button_label="Save", export_handler=partial(save_handler, callback, flatten), filename_url=filename_url, # OM-64312: Set save-as dialog to validate file names in file exporter should_validate=True, ) if self._save_options is None: self._save_options = SaveOptionsDelegate() file_exporter.add_export_options_frame("Save Options", self._save_options) # OM-55838: Don't show "include sesson layer" for non-flatten save-as. self._save_options.show_include_session_layer_option = flatten def save_stage(self, path: str, callback: Callable = None, flatten: bool=False, save_options: SaveOptionsDelegate=None, allow_skip_sublayers: bool=False): self.stop_timeline() stage = omni.usd.get_context().get_stage() save_comment = "" if save_options: save_comment = save_options.get_comment() include_session_layer = False if save_options and flatten: include_session_layer = save_options.include_session_layer() if flatten: path = path or stage.GetRootLayer().identifier # TODO: Currently, it's implemented differently for export w/o session layer as # flatten is a simple operation and we don't want to break the ABI of omni.usd. if include_session_layer: omni.usd.get_context().export_as_stage_with_callback(path, callback) else: async def flatten_stage_without_session_layer(path, callback): await self._app.next_update_async() await self._app.next_update_async() with Prompt("Please Wait", "Exporting flattened stage...", [], [], True): await self._app.next_update_async() usd_context = omni.usd.get_context() if usd_context.can_save_stage(): stage = usd_context.get_stage() # Creates empty anon layer. anon_layer = Sdf.Layer.CreateAnonymous() temp_stage = Usd.Stage.Open(stage.GetRootLayer(), anon_layer) success = temp_stage.Export(path) if callback: if success: callback(True, "") else: callback(False, f"Error exporting flattened stage to path: {path}.") else: error = "Stage busy or another saving task is in progress!!" CARB_LOG_ERROR(error) if callback: callback(False, error) asyncio.ensure_future(flatten_stage_without_session_layer(path, callback)) else: async def save_stage_async(path: str, callback: Callable): if path == stage.GetRootLayer().identifier: dirty_layer_identifiers = omni.usd.get_dirty_layers(stage, True) self.ui_handler.save_root_and_sublayers( "", dirty_layer_identifiers, on_save_done=callback, save_comment=save_comment, allow_skip_sublayers=allow_skip_sublayers) else: path = path or stage.GetRootLayer().identifier dirty_layer_identifiers = omni.usd.get_dirty_layers(stage, False) save_fn = lambda: self.ui_handler.save_root_and_sublayers( path, dirty_layer_identifiers, on_save_done=callback, save_comment=save_comment, allow_skip_sublayers=allow_skip_sublayers) cancel_fn = lambda: self.ui_handler.save_root_and_sublayers( "", dirty_layer_identifiers, on_save_done=callback, save_comment=save_comment, allow_skip_sublayers=allow_skip_sublayers) result, _ = await omni.client.stat_async(path) if result == omni.client.Result.OK: # Path already exists, prompt to overwrite self._show_file_existed_prompt(path, save_fn, on_cancel_fn=cancel_fn) else: save_fn() asyncio.ensure_future(save_stage_async(path, callback)) def close(self, on_closed, fast_shutdown=False): """Check if current stage is dirty. If it's dirty, it will ask if to save the file, then close stage.""" self.stop_timeline() async def close_stage_job(): if not fast_shutdown: # FIXME: Delay two frames to center prompt. await self._app.next_update_async() await self._app.next_update_async() with Prompt("Please Wait", "Closing stage...", [], [], True): await self._app.next_update_async() # Making sure prompt shows await omni.usd.get_context().close_stage_async() await self._app.next_update_async() # Wait anther frame for StageEvent.CLOSED to be handled else: # Clear dirty state to allow quit fastly. omni.usd.get_context().set_pending_edit(False) if on_closed: on_closed() self.prompt_if_unsaved_stage(lambda *_: self._exclusive_task_wrapper(close_stage_job)) def save_layers(self, new_root_path, dirty_layers, on_save_done, create_checkpoint=True, checkpoint_comment=""): """Save current layers""" # Skips if it has no real layers to be saved. self.stop_timeline() # It's possible that all layers are not dirty but it has pending edits to be saved, # like render settings, which needs to be saved into root layer during save. usd_context = omni.usd.get_context() has_pending_edit = usd_context.has_pending_edit() if not new_root_path and not dirty_layers and not has_pending_edit: if on_save_done: on_save_done(True, "") return try: async def save_layers_job(*_): # FIXME: Delay two frames to center prompt. await self._app.next_update_async() await self._app.next_update_async() with Prompt("Please Wait", "Saving layers...", [], [], True): await self._app.next_update_async() # Making sure prompt shows await self._app.next_update_async() # Need 2 frames since save happens on mainthread with _CheckpointCommentContext(checkpoint_comment): result, err, saved_layers = await usd_context.save_layers_async(new_root_path, dirty_layers) await self._app.next_update_async() # Wait anther frame for StageEvent.SAVED to be handled # Clear unique task since it's possible that # post-call to on_save_done needs to create unique # instance also. if _extension_instance and _extension_instance._task: _extension_instance._task = None if on_save_done: on_save_done(result, err) if result: message_bus = omni.kit.app.get_app().get_message_bus_event_stream() message_bus.push(file_utils.FILE_SAVED_EVENT, payload=file_utils.FileEventModel(url=new_root_path).dict()) else: self.ui_handler.show_save_layers_failed_prompt() FileWindowExtension._exclusive_task_wrapper(save_layers_job) except Exception as exc: carb.log_error(f"save error {exc}") traceback.print_exc() def prompt_if_unsaved_stage(self, callback: Callable): """Check if current stage is dirty. If it's dirty, ask to save the file, then execute callback. Otherwise runs callback directly.""" def should_show_stage_save_dialog(): # Use settings to control if it needs to show stage save dialog for layers save. # For application that uses kit and does not want this, it can disable this. settings = carb.settings.get_settings() settings.set_default_bool(SHOW_UNSAVED_LAYERS_DIALOG, True) show_stage_save_dialog = settings.get(SHOW_UNSAVED_LAYERS_DIALOG) return show_stage_save_dialog ignore_unsaved = self._settings.get(IGNORE_UNSAVED_STAGE) if omni.usd.get_context().has_pending_edit() and not ignore_unsaved: if omni.usd.get_context().is_new_stage() or should_show_stage_save_dialog(): if self._unsaved_stage_prompt: self._unsaved_stage_prompt.destroy() self._unsaved_stage_prompt = Prompt( f'{omni.kit.ui.get_custom_glyph_code("${glyphs}/exclamation.svg")}', "Would you like to save this stage?", ["Save", "Don't Save", "Cancel"], [lambda *_: self.save(callback, allow_skip_sublayers=True), lambda *_: callback() if callback else None, None], modal=True) self._unsaved_stage_prompt.show() else: self.save(callback, allow_skip_sublayers=True) else: if callback: callback() def add_reference(self, is_payload=False): self.stop_timeline() def on_file_picked(is_payload: bool, filename: str, dirname: str, selections: List[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\...' reference_path = filename else: reference_path = f"{dirname or ''}/{filename}" name = os.path.splitext(os.path.basename(reference_path))[0] stage = omni.usd.get_context().get_stage() if stage.HasDefaultPrim(): prim_path = omni.usd.get_stage_next_free_path( stage, stage.GetDefaultPrim().GetPath().pathString + "/" + Tf.MakeValidIdentifier(name), False ) else: prim_path = omni.usd.get_stage_next_free_path(stage, "/" + Tf.MakeValidIdentifier(name), False) if is_payload: omni.kit.commands.execute( "CreatePayload", usd_context=omni.usd.get_context(), path_to=prim_path, asset_path=reference_path, instanceable=False ) else: omni.kit.commands.execute( "CreateReference", usd_context=omni.usd.get_context(), path_to=prim_path, asset_path=reference_path, instanceable=False ) file_importer = get_file_importer() if file_importer: file_importer.show_window( title="Select File", import_button_label="Add Reference" if not is_payload else "Add Payload", import_handler=partial(on_file_picked, is_payload)) def register_open_stage_addon(self, callback): return _CallbackRegistrySubscription(self._open_stage_callbacks, callback) def register_open_stage_complete(self, callback): return _CallbackRegistrySubscription(self._open_stage_complete_callbacks, callback) @staticmethod def _exclusive_task_wrapper(job: Awaitable, *args): # Only allow one task to be run if _extension_instance._task: carb.log_info("_exclusive_task_wrapper already running. Cancelling") _extension_instance._task.cancel() _extension_instance._task = None async def exclusive_task(): await job(*args) _extension_instance._task = None _extension_instance._task = asyncio.ensure_future(exclusive_task()) 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_instance(): return _extension_instance def new(template=None): file_window = get_instance() if file_window: file_window.new(template) def open(open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL): file_window = get_instance() if file_window: file_window.open(open_loadset) def open_stage(path, open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL, callback: callable=None): file_window = get_instance() if file_window: file_window.open_stage(path, open_loadset=open_loadset, callback=callback) def open_with_new_edit_layer(path, open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL, callback=None): file_window = get_instance() if file_window: file_window.open_with_new_edit_layer(path, open_loadset, callback) def reopen(): file_window = get_instance() if file_window: file_window.reopen() def share(): file_window = get_instance() if file_window: file_window.share() def save(on_save_done=None, exit=False, dialog_options=DialogOptions.NONE): file_window = get_instance() if file_window: file_window.save(on_save_done) def save_as(flatten, on_save_done=None): file_window = get_instance() if file_window: file_window.save_as(flatten, on_save_done) def close(on_closed=None): file_window = get_instance() if file_window: file_window.close(on_closed) def save_layers(new_root_path, dirty_layers, on_save_done, create_checkpoint=True, checkpoint_comment=""): file_window = get_instance() if file_window: file_window.save_layers(new_root_path, dirty_layers, on_save_done, create_checkpoint, checkpoint_comment) def prompt_if_unsaved_stage(job): file_window = get_instance() if file_window: file_window.prompt_if_unsaved_stage(job) def add_reference(is_payload=False): file_window = get_instance() if file_window: file_window.add_reference(is_payload=is_payload) def register_open_stage_addon(callback): file_window = get_instance() if file_window: return file_window.register_open_stage_addon(callback) def register_open_stage_complete(callback): file_window = get_instance() if file_window: return file_window.register_open_stage_complete(callback)
37,160
Python
45.048327
158
0.598681
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/app_ui.py
"""USD File interaction for Omniverse Kit. :mod:`omni.kit.window.file` provides util functions to new/open/save/close USD files. It handles file picking dialog and prompt for unsaved stage. """ import os import carb.settings import omni.ui as ui import omni.kit.ui from enum import Enum from typing import List, Callable from omni.kit.window.file_exporter import get_file_exporter, ExportOptionsDelegate from omni.kit.window.file_importer import ImportOptionsDelegate from omni.kit.widget.versioning import CheckpointHelper from .prompt_ui import Prompt from .save_stage_ui import StageSaveDialog from .style import get_style class DialogOptions(Enum): NONE = 0, 'Show dialog using is-required logic' FORCE = 1, 'Force dialog to show and ignore is-required logic' HIDE = 2, 'Never show dialog' class SaveOptionsDelegate(ExportOptionsDelegate): def __init__(self): super().__init__( build_fn=self._build_ui_impl, selection_changed_fn=lambda *_: self._build_ui_impl(), filename_changed_fn=lambda *_: self._build_ui_impl(), destroy_fn=self._destroy_impl ) self._widget = None self._comment_model = ui.SimpleStringModel() self._include_session_layer_checkbox = None self._hint_container = None self._sub_begin_edit = None self._sub_end_edit = None self._show_include_session_layer_option = False self._other_options_widget = None settings = carb.settings.get_settings() self._versioning_enabled = settings.get_as_bool("exts/omni.kit.window.file/enable_versioning") or False def get_comment(self): if self._comment_model: return self._comment_model.get_value_as_string() return "" def include_session_layer(self): """ When doing save-as or save-flattened-as, this option can tell if it needs to keep session layers's change or flatten session layer's change also. """ if self._include_session_layer_checkbox: return self._include_session_layer_checkbox.model.get_value_as_bool() return True @property def show_include_session_layer_option(self): return self._show_include_session_layer_option @show_include_session_layer_option.setter def show_include_session_layer_option(self, value): self._show_include_session_layer_option = value if self._other_options_widget: self._other_options_widget.visible = value def _build_ui_impl(self): if not self._versioning_enabled: return folder_url = "" file_exporter = get_file_exporter() if file_exporter and file_exporter._dialog: folder_url = file_exporter._dialog.get_current_directory() self._widget = ui.Frame() CheckpointHelper.is_checkpoint_enabled_with_callback(folder_url, self._build_options_box) def _build_option_checkbox(self, text, default_value, tooltip, identifier): with ui.VStack(): ui.Spacer() with ui.HStack(height=0): checkbox = ui.CheckBox(width=14, height=14, style={"font_size": 16}, identifier=identifier) checkbox.model.set_value(default_value) ui.Spacer(width=4) label = ui.Label(text, alignment=ui.Alignment.LEFT) label.set_tooltip(tooltip) ui.Spacer() return checkbox def _build_options_box(self, server_url: str, checkpoint_enabled: bool): with self._widget: with ui.VStack(height=0, style=get_style()): if checkpoint_enabled: ui.Label("Checkpoint comments:", height=20, alignment=ui.Alignment.LEFT_CENTER) ui.Separator(height=5) ui.Spacer(height=2) with ui.ZStack(): with ui.HStack(): ui.StringField(self._comment_model, multiline=True, height=64, style_type_name_override="Field") self._hint_container = ui.VStack() with self._hint_container: with ui.HStack(): ui.Label("Add checkpoint comments here.", height=20, style_type_name_override="Field.Hint") ui.Spacer() self._hint_container.visible = False self._sub_begin_edit = self._comment_model.subscribe_begin_edit_fn(self._on_begin_edit) self._sub_end_edit = self._comment_model.subscribe_end_edit_fn(self._on_end_edit) else: ui.Label("This server does not support checkpoints.", height=20, alignment=ui.Alignment.CENTER, word_wrap=True) # OM-55838: Add option to support excluding session layer from flattening. self._other_options_widget = ui.VStack(height=0) with self._other_options_widget: ui.Spacer(height=5) ui.Separator(height=5) ui.Label("Other Options:", height=20, alignment=ui.Alignment.LEFT_CENTER) ui.Spacer(height=5) self._include_session_layer_checkbox = self._build_option_checkbox( "Include Session Layer", False, "When this option is checked, it means it will include content\n" "of session layer into the flattened stage.", "include_session_layer" ) self._other_options_widget.visible = self.show_include_session_layer_option def _on_begin_edit(self, model): self._hint_container.visible = False def _on_end_edit(self, model: ui.AbstractValueModel): if self.get_comment(): self._hint_container.visible = False else: self._hint_container.visible = True def _destroy_impl(self, _): self._comment_model = None self._hint_container = None self._widget = None self._sub_begin_edit = None self._sub_end_edit = None self._include_session_layer_checkbox = None class OpenOptionsDelegate(ImportOptionsDelegate): def __init__(self): super().__init__( build_fn=self._build_ui_impl, destroy_fn=self._destroy_impl ) self._widget = None self._load_payload_checkbox = None def should_load_payload(self): if self._load_payload_checkbox: return self._load_payload_checkbox.model.get_value_as_bool() def _build_ui_impl(self): self._widget = ui.Frame() with self._widget: with ui.VStack(height=0, style=get_style()): ui.Separator(height=5) ui.Spacer(height=2) with ui.HStack(): ui.Spacer(width=2) self._load_payload_checkbox = ui.CheckBox(width=20, style_type_name_override="CheckBox") self._load_payload_checkbox.model.set_value(True) ui.Spacer(width=4) ui.Label("Open Payloads", width=0, height=20, style_type_name_override="Label") ui.Spacer() def _destroy_impl(self, _): self._load_payload_checkbox = None self._widget = None class AppUI: def __init__(self): self._open_stage_failed_prompt = None self._save_layers_failed_prompt = None self._save_stage_prompt = None def destroy(self): if self._open_stage_failed_prompt: self._open_stage_failed_prompt.destroy() self._open_stage_failed_prompt = None if self._save_layers_failed_prompt: self._save_layers_failed_prompt.destroy() self._save_layers_failed_prompt = None if self._save_stage_prompt: self._save_stage_prompt.destroy() self._save_stage_prompt = None def save_root_and_sublayers( self, new_root_path: str, dirty_sublayers: List[str], on_save_done: Callable = None, dialog_options: int = DialogOptions.NONE, save_comment: str = "", allow_skip_sublayers: bool = False): stage = omni.usd.get_context().get_stage() if not stage: return if dialog_options == DialogOptions.HIDE: self._save_layers(new_root_path, dirty_sublayers, on_save_done=on_save_done) return if len(dirty_sublayers) > 0 or dialog_options == DialogOptions.FORCE: if self._save_stage_prompt: self._save_stage_prompt.destroy() self._save_stage_prompt = StageSaveDialog( enable_dont_save=allow_skip_sublayers, on_save_fn=lambda layers, comment: self._save_layers( new_root_path, layers, on_save_done=on_save_done, checkpoint_comment=comment), on_dont_save_fn=lambda comment: self._dont_save_layers( new_root_path, on_save_done=on_save_done, checkpoint_comment=comment), on_cancel_fn=lambda comment: self._cancel_save(new_root_path, checkpoint_comment=comment), ) self._save_stage_prompt.show(dirty_sublayers) else: self._save_layers(new_root_path, [], on_save_done=on_save_done, checkpoint_comment=save_comment) def _save_layers( self, new_root_path, dirty_layers, on_save_done=None, create_checkpoint=True, checkpoint_comment="" ): settings = carb.settings.get_settings() versioning_enabled = settings.get_as_bool("exts/omni.kit.window.file/enable_versioning") or False if versioning_enabled and create_checkpoint: omni.client.create_checkpoint(new_root_path, checkpoint_comment) def save_done_fn(result, err): if result: if versioning_enabled and create_checkpoint: omni.client.create_checkpoint(new_root_path, checkpoint_comment) if on_save_done: on_save_done(result, err) omni.kit.window.file.save_layers( new_root_path, dirty_layers, save_done_fn, create_checkpoint, checkpoint_comment ) def _dont_save_layers(self, new_root_path, on_save_done=None, checkpoint_comment=""): if new_root_path: self._save_layers(new_root_path, [], on_save_done=on_save_done, checkpoint_comment=checkpoint_comment) elif on_save_done: on_save_done(True, "") def _cancel_save(self, new_root_path, checkpoint_comment=""): if new_root_path: self._save_layers(new_root_path, [], None, checkpoint_comment=checkpoint_comment) def show_open_stage_failed_prompt(self, path): if not self._open_stage_failed_prompt: self._open_stage_failed_prompt = Prompt( f'{omni.kit.ui.get_custom_glyph_code("${glyphs}/exclamation.svg")} Open Stage Failed', "", ["OK"], [None], ) self._open_stage_failed_prompt.set_text( f"Failed to open stage {os.path.basename(path)}. Please check console for error." ) self._open_stage_failed_prompt.show() return self._open_stage_failed_prompt def show_save_layers_failed_prompt(self): if not self._save_layers_failed_prompt: self._save_layers_failed_prompt = Prompt( f'{omni.kit.ui.get_custom_glyph_code("${glyphs}/exclamation.svg")} Save Layer(s) Failed', "Failed to save layers. Please check console for error.", ["OK"], [None], ) self._save_layers_failed_prompt.show() return self._save_layers_failed_prompt
11,906
Python
40.34375
131
0.592474
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/read_only_options_window.py
import carb import omni.usd import omni.ui as ui from pathlib import Path CURRENT_PATH = Path(__file__).parent.absolute() ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("icons") class ReadOnlyOptionsWindow: def __init__(self, open_with_new_edit_fn, open_original_fn, modal=False): self._title = "Opening a Read Only File" self._modal = modal self._buttons = [] self._content_buttons = [ ("Open With New Edit Layer", "open_edit_layer.svg", open_with_new_edit_fn), ("Open Original File", "pencil.svg", open_original_fn), ] self._build_ui() def destroy(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): 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 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) 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,269
Python
34.543478
91
0.492199
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_stop_animation.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 platform import unittest import os import pathlib import asyncio import shutil import tempfile import omni.kit.app import omni.usd import omni.timeline 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, select_prims, wait_stage_loading, arrange_windows from omni.kit.window.file_exporter.test_helper import FileExporterTestHelper class FileWindowStopAnimation(AsyncTestCase): # Before running each test async def setUp(self): 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() # load stage await open_stage(get_test_data_path(__name__, "physics_animation.usda")) # setup events self._future_test = None self._required_stage_event = -1 self._stage_event_sub = omni.usd.get_context().get_stage_event_stream().create_subscription_to_pop(self._on_stage_event, name="omni.usd.window.file") # After running each test async def tearDown(self): # free events self._future_test = None self._required_stage_event = -1 self._stage_event_sub = None await wait_stage_loading() await omni.usd.get_context().new_stage_async() def _on_stage_event(self, event): if self._future_test and int(self._required_stage_event) == int(event.type) and not self._future_test.done(): self._future_test.set_result(event.type) async def reset_stage_event(self, stage_event): self._required_stage_event = stage_event self._future_test = asyncio.Future() async def wait_for_stage_event(self): async def wait_for_event(): await self._future_test try: await asyncio.wait_for(wait_for_event(), timeout=30.0) except asyncio.TimeoutError: carb.log_error(f"wait_for_stage_event timeout waiting for {self._required_stage_event}") self._future_test = None self._required_stage_event = -1 async def test_l1_stop_animation_save(self): def get_box_pos(): stage = omni.usd.get_context().get_stage() prim = stage.GetPrimAtPath("/World/boxActor") attr = prim.GetAttribute("xformOp:translate") return attr.Get() def play_anim(): timeline = omni.timeline.get_timeline_interface() if timeline: timeline.play() # setup orig_pos = get_box_pos() tmpdir = tempfile.mkdtemp() orig_file = get_test_data_path(__name__, "physics_animation.usda").replace("\\", "/") new_file = f"{tmpdir}/physics_animation.usd".replace("\\", "/") # play anim play_anim() await ui_test.human_delay(100) # save as await self.reset_stage_event(omni.usd.StageEventType.SAVED) omni.kit.actions.core.get_action_registry().get_action("omni.kit.window.file", "save_as").execute() await ui_test.human_delay(10) async with FileExporterTestHelper() as file_export_helper: await file_export_helper.click_apply_async(filename_url=new_file) await self.wait_for_stage_event() # play anim play_anim() await ui_test.human_delay(100) # save await self.reset_stage_event(omni.usd.StageEventType.SAVED) omni.kit.actions.core.get_action_registry().get_action("omni.kit.window.file", "save").execute() await ui_test.human_delay(10) # check _check_and_select_all and _on_select_all_fn for StageSaveDialog check_box = ui_test.find("Select Files to Save##file.py//Frame/VStack[0]/ScrollingFrame[0]/VStack[0]/HStack[0]/CheckBox[0]") await check_box.click(human_delay_speed=10) await check_box.click(human_delay_speed=10) await ui_test.human_delay() await ui_test.find("Select Files to Save##file.py//Frame/**/Button[*].text=='Save Selected'").click() await ui_test.human_delay() await self.wait_for_stage_event() # load saved file await open_stage(new_file) # verify boxActor is in same place new_pos = get_box_pos() self.assertAlmostEqual(orig_pos[0], new_pos[0], places=5) self.assertAlmostEqual(orig_pos[1], new_pos[1], places=5) self.assertAlmostEqual(orig_pos[2], new_pos[2], places=5)
5,013
Python
37.56923
157
0.655496
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_file_save.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 carb import os import tempfile import shutil import omni.kit.app import omni.kit.commands import omni.kit.test from pathlib import Path from unittest.mock import Mock, patch from omni.kit.window.file_exporter.test_helper import FileExporterTestHelper from .. import FileWindowExtension, get_instance as get_window_file from .test_base import TestFileBase from pxr import Usd import unittest class TestFileSave(TestFileBase): async def setUp(self): await super().setUp() async def tearDown(self): await super().tearDown() async def test_file_save(self): """Testing that save should write to stage url""" omni.usd.get_context().new_stage() omni.usd.get_context().set_pending_edit(False) test_file = "test_file.usda" temp_path = os.path.join(tempfile.gettempdir(), test_file) shutil.copyfile(os.path.join(self._usd_path, test_file), temp_path) omni.kit.window.file.open_stage(temp_path) await self.wait_for_update() mock_callback = Mock() omni.kit.window.file.save(mock_callback) await self.wait_for_update() self.assertEqual(omni.usd.get_context().get_stage_url(), temp_path.replace("\\", "/")) self.assertTrue(os.path.isfile(temp_path)) mock_callback.assert_called_once() self.remove_file(temp_path) async def test_file_save_with_render_setting_changes_only(self): usd_context = omni.usd.get_context() await usd_context.new_stage_async() self.assertFalse(usd_context.has_pending_edit()) with tempfile.TemporaryDirectory() as tmp_dir_name: await omni.kit.app.get_app().next_update_async() # save tmp_file_path = Path(tmp_dir_name) / "tmp.usda" result = usd_context.save_as_stage(str(tmp_file_path)) self.assertTrue(result) self.assertFalse(usd_context.has_pending_edit()) # save the file with customized key value settings = carb.settings.get_settings() setting_key_ao = "/rtx/post/aa/op" settings.set_int(setting_key_ao, 3) await omni.kit.app.get_app().next_update_async() # After changing render settings, it will be dirty. self.assertTrue(usd_context.has_pending_edit()) # Saves stage, although no layers are dirty except render settings. omni.kit.window.file.save(None) # Waiting for save to be done as it's asynchronous. for _ in range(10): await omni.kit.app.get_app().next_update_async() # Making sure that render settings are saved into root layer. self.assertFalse(usd_context.has_pending_edit()) # Reloading stage will reload the settings also. await usd_context.reopen_stage_async() await omni.kit.app.get_app().next_update_async() self.assertFalse(usd_context.has_pending_edit()) setting_value_ao = settings.get(setting_key_ao) self.assertEqual(setting_value_ao, 3) # New stage to release temp file. await usd_context.new_stage_async() async def test_file_save_read_only_file(self): """Test saving read-only file calls save_as instead""" omni.usd.get_context().new_stage() omni.usd.get_context().set_pending_edit(False) test_file = "test_file.usda" temp_path = os.path.join(tempfile.gettempdir(), test_file) shutil.copyfile(os.path.join(self._usd_path, test_file), temp_path) omni.kit.window.file.open_stage(temp_path) await self.wait_for_update() class ListEntry: def __init__(self) -> None: self.flags = 0 mock_callback = Mock() with patch.object(omni.usd.UsdContext, 'is_new_stage', return_value=False),\ patch.object(omni.client, "stat_async", return_value=(omni.client.Result.OK, ListEntry())),\ patch.object(FileWindowExtension, "save_as") as mock_save_as: omni.kit.window.file.save(mock_callback) await self.wait_for_update() mock_save_as.assert_called_once_with(False, mock_callback, allow_skip_sublayers=False) self.remove_file(temp_path) async def test_file_saveas(self): """Testing save as""" omni.usd.get_context().new_stage() omni.usd.get_context().set_pending_edit(False) temp_path = self._temp_path.replace('.usda', '.usd') mock_callback = Mock() async with FileExporterTestHelper() as file_export_helper: with patch.object(omni.usd.UsdContext, 'is_new_stage', return_value=False): omni.kit.window.file.save_as(False, mock_callback) await self.wait_for_update() await file_export_helper.click_apply_async(filename_url=temp_path) await self.wait_for_update() mock_callback.assert_called_once() self.assertTrue(os.path.isfile(temp_path)) self.remove_file(temp_path) async def _test_file_saveas_with_empty_filename(self): # pragma: no cover """Testing save as with an empty filename, should not allow saving.""" omni.usd.get_context().new_stage() omni.usd.get_context().set_pending_edit(False) temp_path = self._temp_path.replace('.usda', '.usd') mock_callback = Mock() async with FileExporterTestHelper() as file_export_helper: with patch.object(omni.usd.UsdContext, 'is_new_stage', return_value=False): omni.kit.window.file.save_as(False, mock_callback) await self.wait_for_update() await file_export_helper.click_apply_async() await self.wait_for_update() mock_callback.assert_not_called() self.assertFalse(os.path.isfile(temp_path)) async def _test_file_saveas_flattened_internal(self, include_session_layer): """Testing save as flatten""" omni.usd.get_context().new_stage() omni.usd.get_context().set_pending_edit(False) mock_callback = Mock() base, ext = os.path.splitext(self._temp_path) temp_path = base + str(include_session_layer) + ext temp_path = self._temp_path.replace('.usda', '.usd') async with FileExporterTestHelper() as file_export_helper: with patch.object(omni.usd.UsdContext, 'is_new_stage', return_value=False): omni.kit.window.file.save_as(True, mock_callback) await self.wait_for_update() import omni.kit.ui_test as ui_test file_picker = ui_test.find("Save File As...") self.assertTrue(file_picker) await file_picker.focus() include_session_layer_checkbox = file_picker.find( "**/CheckBox[*].identifier=='include_session_layer'" ) self.assertTrue(include_session_layer_checkbox) include_session_layer_checkbox.model.set_value(include_session_layer) await file_export_helper.click_apply_async(filename_url=temp_path) await self.wait_for_update() stage = Usd.Stage.Open(temp_path) prim = stage.GetPrimAtPath("/OmniverseKit_Persp") if include_session_layer: self.assertTrue(prim) else: self.assertFalse(prim) stage = None mock_callback.assert_called_once() self.assertTrue(os.path.isfile(temp_path)) self.remove_file(temp_path) @unittest.skip("A.B. temp disable, omni.physx.bundle extension causes issues") async def test_file_saveas_flattened_with_session_layer(self): await self._test_file_saveas_flattened_internal(True) async def test_file_saveas_flattened_without_session_layer(self): await self._test_file_saveas_flattened_internal(False) async def test_show_save_layers_failed_prompt(self): omni.usd.get_context().new_stage() prompt = get_window_file().ui_handler.show_save_layers_failed_prompt() await self.wait_for_update() prompt.hide() async def test_file_saveas_existed_filename(self): """Testing save as with a filename which is already existed, should not allow saving.""" # create an empty stage await omni.usd.get_context().new_stage_async() omni.usd.get_context().set_pending_edit(False) file_name = f"4Lights.usda" temp_path = os.path.join(tempfile.gettempdir(), file_name) shutil.copyfile(os.path.join(self._usd_path, file_name), temp_path) # save the current stage to the temp path where the file name already exists async with FileExporterTestHelper() as file_export_helper: with patch.object(omni.usd.UsdContext, 'is_new_stage', return_value=False): omni.kit.window.file.save_as(False, Mock()) await self.wait_for_update() await file_export_helper.click_apply_async(filename_url=temp_path) await self.wait_for_update() # check 4Lights.usda is not empty, which means saveas didn't happen stage = Usd.Stage.Open(str(temp_path)) await self.wait_for_update() prim = stage.GetPrimAtPath("/Stage/SphereLight_01") self.assertTrue(prim) self.remove_file(temp_path) async def test_invalid_save(self): """Test no valid stage save""" if omni.usd.get_context().get_stage(): await omni.usd.get_context().close_stage_async() mock_callback = Mock() omni.kit.window.file.save(mock_callback) mock_callback.assert_not_called()
10,185
Python
39.420635
104
0.633873
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_file_window.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.window.file from .test_base import TestFileBase from unittest.mock import Mock from omni.kit import ui_test from omni.kit.window.file import ReadOnlyOptionsWindow from omni.kit.window.file import register_open_stage_addon, register_open_stage_complete from omni.kit.window.file_importer import get_file_importer class TestFileWindow(TestFileBase): async def setUp(self): await super().setUp() # After running each test async def tearDown(self): await super().tearDown() async def test_read_only_options_window(self): """Testing read only options window""" self._readonly_window = ReadOnlyOptionsWindow(None, None, True) self._readonly_window.show() self.assertTrue(self._readonly_window.is_visible) self._readonly_window.destroy() async def test_stage_register(self): """Testing register_open_stage_addon and register_open_stage_complete subscription""" mock_callback1 = Mock() mock_callback2 = Mock() self._addon_subscription = register_open_stage_addon(mock_callback1) self._complete_subscription = register_open_stage_complete(mock_callback2) omni.kit.window.file.open_stage(f"{self._usd_path}/test_file.usda") await self.wait_for_update() mock_callback1.assert_called_once() mock_callback2.assert_called_once() async def test_add_reference(self): omni.kit.window.file.add_reference(is_payload=False) await ui_test.human_delay() file_importer = get_file_importer() self.assertTrue(file_importer.is_window_visible) file_importer.click_cancel()
2,103
Python
35.91228
93
0.717071
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/__init__.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 .test_file_new import * from .test_file_open import * from .test_file_save import * from .test_prompt_unsaved import * from .test_stop_animation import * from .test_file_window import * from .test_loadstage import *
657
Python
40.124997
77
0.7793
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_file_new.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 omni.usd import omni.kit.window from unittest.mock import patch from .test_base import TestFileBase class TestFileNew(TestFileBase): async def setUp(self): await super().setUp() # After running each test async def tearDown(self): await super().tearDown() async def test_file_new(self): """Testing file new""" omni.kit.window.file.new() await self.wait_for_update() # verify new layer has non-Null identifier self.assertTrue(bool(omni.usd.get_context().get_stage().GetRootLayer().identifier))
1,033
Python
32.354838
91
0.724105
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_loadstage.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 asyncio import omni.ui as ui import omni.kit.app import omni.kit.test import omni.kit.ui_test as ui_test from omni.ui.tests.test_base import OmniUiTest from omni.kit.test_suite.helpers import get_test_data_path, wait_stage_loading from omni.kit import ui_test class TestOpenStage(OmniUiTest): """Testing omni.usd.core""" async def setUp(self): await super().setUp() await wait_stage_loading() self._future_test = None self._required_stage_event = -1 self._stage_event_sub = omni.usd.get_context().get_stage_event_stream().create_subscription_to_pop(self._on_stage_event, name="omni.usd.menu.file") # After running each test async def tearDown(self): await super().tearDown() def _on_stage_event(self, event): if self._future_test and int(self._required_stage_event) == int(event.type) and not self._future_test.done(): self._future_test.set_result(event.type) async def reset_stage_event(self, stage_event): self._required_stage_event = stage_event self._future_test = asyncio.Future() async def wait_for_stage_event(self): async def wait_for_event(): await self._future_test try: await asyncio.wait_for(wait_for_event(), timeout=30.0) except asyncio.TimeoutError: carb.log_error(f"wait_for_stage_event timeout waiting for {self._required_stage_event}") self._future_test = None self._required_stage_event = -1 async def test_open_stage(self): def on_load_complete(success): if not success: if self._future_test: self._future_test.set_result(False) usd_context = omni.usd.get_context() # test file not found stage = omni.usd.get_context().get_stage() await self.reset_stage_event(omni.usd.StageEventType.OPENED) omni.kit.window.file.open_stage("missing file", callback=on_load_complete) await self.wait_for_stage_event() stage = omni.usd.get_context().get_stage() self.assertEqual(stage, omni.usd.get_context().get_stage()) await ui_test.human_delay(50) # load valid stage stage = omni.usd.get_context().get_stage() await self.reset_stage_event(omni.usd.StageEventType.OPENED) omni.kit.window.file.open_stage(get_test_data_path(__name__, "4Lights.usda"), callback=on_load_complete) await self.wait_for_stage_event() self.assertNotEqual(stage, omni.usd.get_context().get_stage()) await ui_test.human_delay(50) # create new stage await usd_context.new_stage_async() await ui_test.human_delay(50) # load a material as usd file stage = omni.usd.get_context().get_stage() await self.reset_stage_event(omni.usd.StageEventType.OPENED) success = omni.kit.window.file.open_stage(get_test_data_path(__name__, "anno_material.mdl"), callback=on_load_complete) await self.wait_for_stage_event() self.assertEqual(stage, omni.usd.get_context().get_stage()) await ui_test.human_delay(50)
3,594
Python
38.076087
155
0.663884
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_prompt_unsaved.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 omni.usd import omni.kit.window from unittest.mock import Mock, patch from omni.usd import UsdContext from carb.settings import ISettings from .test_base import TestFileBase from .. import FileWindowExtension # run tests last as it doesn't cleanup modela dialogs class zzTestPromptIfUnsavedStage(TestFileBase): async def setUp(self): await super().setUp() self._show_unsaved_layers_dialog = False self._ignore_unsaved_stage = False # After running each test async def tearDown(self): await super().tearDown() def _mock_get_carb_setting(self, setting: str): from ..scripts.file_window import SHOW_UNSAVED_LAYERS_DIALOG, IGNORE_UNSAVED_STAGE if setting == SHOW_UNSAVED_LAYERS_DIALOG: return self._show_unsaved_layers_dialog elif setting == IGNORE_UNSAVED_STAGE: return self._ignore_unsaved_stage return False async def test_save_unsaved_stage(self): """Testing click save when prompted to save unsaved stage""" self._ignore_unsaved_stage = False self._show_unsaved_layers_dialog = True mock_callback = Mock() with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting),\ patch.object(UsdContext, "has_pending_edit", return_value=True),\ patch.object(UsdContext, "is_new_stage", return_value=True),\ patch.object(FileWindowExtension, "save") as mock_file_save: # Show prompt and click Save omni.kit.window.file.prompt_if_unsaved_stage(mock_callback) await self.click_unsaved_stage_prompt(button=0) mock_file_save.assert_called_once_with(mock_callback, allow_skip_sublayers=True) async def test_dont_save_unsaved_stage(self): """Testing click don't save when prompted to save unsaved stage""" self._ignore_unsaved_stage = False self._show_unsaved_layers_dialog = True mock_callback = Mock() with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting),\ patch.object(UsdContext, "has_pending_edit", return_value=True),\ patch.object(UsdContext, "is_new_stage", return_value=True),\ patch.object(FileWindowExtension, "save") as mock_file_save: # Show prompt and click Don't Save omni.kit.window.file.prompt_if_unsaved_stage(mock_callback) await self.click_unsaved_stage_prompt(button=1) mock_file_save.assert_not_called() mock_callback.assert_called_once() async def test_cancel_unsaved_stage(self): """Testing click cancel when prompted to save unsaved stage""" self._ignore_unsaved_stage = False self._show_unsaved_layers_dialog = True mock_callback = Mock() with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting),\ patch.object(UsdContext, "has_pending_edit", return_value=True),\ patch.object(UsdContext, "is_new_stage", return_value=True),\ patch.object(FileWindowExtension, "save") as mock_file_save: # Show prompt and click Don't Save omni.kit.window.file.prompt_if_unsaved_stage(mock_callback) await self.click_unsaved_stage_prompt(button=2) mock_file_save.assert_not_called() mock_callback.assert_not_called() async def test_no_prompt(self): """Testing unsaved stage prompt not shown""" self._ignore_unsaved_stage = False self._show_unsaved_layers_dialog = False mock_callback = Mock() with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting),\ patch.object(UsdContext, "has_pending_edit", return_value=True),\ patch.object(UsdContext, "is_new_stage", return_value=False),\ patch.object(FileWindowExtension, "save") as mock_file_save: omni.kit.window.file.prompt_if_unsaved_stage(mock_callback) mock_file_save.assert_called_once_with(mock_callback, allow_skip_sublayers=True) async def test_ignore_unsaved(self): """Testing ignore unsaved setting set to True""" self._ignore_unsaved_stage = True mock_callback = Mock() with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting),\ patch.object(UsdContext, "has_pending_edit", return_value=True),\ patch.object(FileWindowExtension, "save") as mock_file_save: omni.kit.window.file.prompt_if_unsaved_stage(mock_callback) mock_file_save.assert_not_called() mock_callback.assert_called_once() async def test_no_pending_edit(self): """Testing stage with no pending edit""" self._ignore_unsaved_stage = False mock_callback = Mock() with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting),\ patch.object(UsdContext, "has_pending_edit", return_value=False),\ patch.object(FileWindowExtension, "save") as mock_file_save: omni.kit.window.file.prompt_if_unsaved_stage(mock_callback) mock_file_save.assert_not_called() mock_callback.assert_called_once()
5,662
Python
43.590551
90
0.668492
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_base.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 os import random import string import carb import omni.kit.app import omni.usd import asyncio import omni.kit.ui_test as ui_test from omni.ui.tests.test_base import OmniUiTest from .. import get_instance as get_window_file class TestFileBase(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() from omni.kit.window.file.scripts.file_window import TEST_DATA_PATH self._usd_path = TEST_DATA_PATH.absolute() token = carb.tokens.get_tokens_interface() temp_dir = token.resolve("${temp}") def get_random_string(): return "".join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)) self._temp_path = os.path.join(temp_dir, get_random_string(), "test.usda").replace("\\", "/") self._temp_edit_path = os.path.join(temp_dir, get_random_string(), "test_edit.usda").replace("\\", "/") self._dirname = os.path.dirname(self._temp_path).replace("\\", "/") self._filename = os.path.basename(self._temp_path) # After running each test async def tearDown(self): await super().tearDown() async def wait_for_update(self, usd_context=omni.usd.get_context(), wait_frames=20): 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 def remove_file(self, full_path: str): import stat try: os.chmod(full_path, stat.S_IRWXU| stat.S_IRWXG| stat.S_IRWXO) # 0777 os.remove(full_path) except Exception: # Don't know what's causing these errors: "PermissionError: [WinError 5] Access is denied", but don't want # to fail tests for this reason. pass async def click_file_existed_prompt(self, accept: bool = True): dialog = get_window_file()._file_existed_prompt button = 0 if accept else 1 if dialog and dialog._button_list[button][1]: # If file exists, click accept at the prompt to continue dialog._button_list[button][1]() await self.wait_for_update() async def click_save_stage_prompt(self, button: int = 0): dialog = get_window_file().ui_handler._save_stage_prompt if button == 0: dialog._on_save_fn() elif button == 1: dialog._on_dont_save_fn() elif button == 2: dialog._on_cacnel_fn() async def click_unsaved_stage_prompt(self, button: int = 0): dialog = get_window_file()._unsaved_stage_prompt _, click_fn = dialog._button_list[button] if click_fn: click_fn() await self.wait_for_update()
3,325
Python
37.229885
118
0.633383
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_file_open.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 os import tempfile import shutil import omni.kit.app import omni.kit.commands import omni.kit.test import unittest from unittest.mock import Mock, patch from carb.settings import ISettings from omni.kit.window.file_exporter.test_helper import FileExporterTestHelper from omni.kit.window.file_importer.test_helper import FileImporterTestHelper from pxr import Sdf from omni.kit.widget.nucleus_connector import NucleusConnectorExtension from .. import get_instance as get_window_file from .test_base import TestFileBase class TestFileOpen(TestFileBase): async def setUp(self): await super().setUp() # After running each test async def tearDown(self): await super().tearDown() def _mock_get_carb_setting(self, setting: str): from ..scripts.file_window import SHOW_UNSAVED_LAYERS_DIALOG, IGNORE_UNSAVED_STAGE if setting == SHOW_UNSAVED_LAYERS_DIALOG: return True elif setting == IGNORE_UNSAVED_STAGE: return True return False async def test_file_open(self): """Testing file open""" omni.usd.get_context().new_stage() omni.usd.get_context().set_pending_edit(False) omni.kit.window.file.open_stage(f"{self._usd_path}/test_file.usda") await self.wait_for_update() # check file is loaded stage = omni.usd.get_context().get_stage() prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)] self.assertEquals(prim_list, ['/World', '/World/defaultLight']) async def test_open(self): """Test omni.kit.window.file.open""" async with FileImporterTestHelper() as file_importer_helper: omni.kit.window.file.open() from omni.kit.window.file_importer import get_file_importer file_importer = get_file_importer() self.assertTrue(file_importer.is_window_visible) async def test_file_open_with_new_edit_layer(self): """Testing that open with new edit layer executes the callback upon success""" omni.usd.get_context().new_stage() omni.usd.get_context().set_pending_edit(False) layer = Sdf.Layer.CreateNew(self._temp_path) self.assertTrue(layer, f"Failed to create temp layer {self._temp_path}.") layer.Save() layer = None mock_callback = Mock() async with FileExporterTestHelper() as file_export_helper: omni.kit.window.file.open_with_new_edit_layer(self._temp_path, callback=mock_callback) await self.wait_for_update() await file_export_helper.click_apply_async() await self.wait_for_update() mock_callback.assert_called_once() @unittest.skip("Crashes when run in random order") # OM-77535 async def test_file_open_with_new_edit_layer_overwrites_existing_file(self): """Testing that open with new edit layer overwrites existing file""" layer = Sdf.Layer.CreateNew(self._temp_path) self.assertTrue(layer, f"Failed to create temp layer {self._temp_path}.") layer.Save() layer = None layer = Sdf.Layer.CreateNew(self._temp_edit_path) self.assertTrue(layer, f"Failed to create temp layer {self._temp_edit_path}.") layer.Save() layer = None async def open_with_new_edit_layer(path): async with FileExporterTestHelper() as file_export_helper: omni.kit.window.file.open_with_new_edit_layer(path) await self.wait_for_update() await file_export_helper.click_apply_async() await self.wait_for_update() await self.click_file_existed_prompt(accept=True) current_stage = omni.usd.get_context().get_stage() self.assertTrue(current_stage) name, _ = os.path.splitext(path) expected_layer_name = f"{name}_edit" self.assertTrue(current_stage.GetRootLayer().anonymous) self.assertEqual(len(current_stage.GetRootLayer().subLayerPaths), 2) sublayer0 = current_stage.GetRootLayer().subLayerPaths[0] sublayer1 = current_stage.GetRootLayer().subLayerPaths[1] file_name, _ = os.path.splitext(sublayer0) self.assertEqual(file_name, expected_layer_name) self.assertEqual(os.path.normpath(sublayer1), os.path.normpath(path)) # First time, creates new edit layer await open_with_new_edit_layer(self._temp_path) # Second time, creates the same name to make sure it correctly overwrites. await omni.usd.get_context().close_stage_async() await open_with_new_edit_layer(self._temp_path) async def test_file_reopen(self): """Testing file reopen""" await omni.usd.get_context().new_stage_async() omni.usd.get_context().set_pending_edit(False) omni.kit.window.file.open_stage(f"{self._usd_path}/4Lights.usda") await self.wait_for_update() # verify its a unmodified stage self.assertFalse(omni.kit.undo.can_undo()) ## create prim omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") # verify its a modified stage self.assertTrue(omni.kit.undo.can_undo()) # Skip unsaved stage prompt with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting): omni.kit.window.file.reopen() await self.wait_for_update() # verify its a unmodified stage self.assertFalse(omni.kit.undo.can_undo()) async def test_file_reopen_with_new_edit_layer(self): temp_dir = tempfile.mkdtemp() omni.usd.get_context().new_stage() omni.usd.get_context().set_pending_edit(False) omni.kit.window.file.open_stage(f"{self._usd_path}/4Lights.usda") await self.wait_for_update() async with FileExporterTestHelper() as file_export_helper: stage = omni.usd.get_context().get_stage() stage_url = stage.GetRootLayer().identifier # Re-open with edit layer omni.kit.window.file.open_with_new_edit_layer(stage_url) await self.wait_for_update() # Save edit layer to temp dir temp_url = f"{temp_dir}/4Lights_layer.usd".replace("\\", "/") await file_export_helper.click_apply_async(filename_url=temp_url) await self.wait_for_update() layer = omni.usd.get_context().get_stage().GetRootLayer() expected = [temp_url, stage_url.replace("\\", "/")] self.assertTrue(layer.anonymous) self.assertTrue(len(layer.subLayerPaths) == 2) self.assertEqual(layer.subLayerPaths[0], expected[0]) self.assertEqual(layer.subLayerPaths[1], expected[1]) # cleanup shutil.rmtree(temp_dir, ignore_errors=True) async def test_show_open_stage_failed_prompt(self): """Testing show_open_stage_failed_prompt""" omni.usd.get_context().new_stage() prompt = get_window_file().ui_handler.show_open_stage_failed_prompt("Test Window File Show Open Stage Failed Prompt") await self.wait_for_update() prompt.hide() async def test_connect_nucleus_when_opening_unreachable_file(self): """Testing that when opening an unreachable file, will try to auto-connect to Nucleus server""" omni.usd.get_context().new_stage() omni.usd.get_context().set_pending_edit(False) test_host = "ov-unconnected" test_url = f"omniverse://{test_host}/test_file.usda" async def mock_stat_async(url: str): return (omni.client.Result.ERROR_CONNECTION, None) with patch("omni.client.stat_async", side_effect=mock_stat_async),\ patch.object(NucleusConnectorExtension, "connect") as mock_nucleus_connect: omni.kit.window.file.open_stage(test_url) await self.wait_for_update() # Confirm attempt to connect to Nucleus server self.assertEqual(mock_nucleus_connect.call_args[0], (test_host, f"omniverse://{test_host}")) async def test_file_close(self): """Testing try to close a file which has been modified""" await omni.usd.get_context().new_stage_async() omni.usd.get_context().set_pending_edit(False) omni.kit.window.file.open_stage(f"{self._usd_path}/4Lights.usda") await self.wait_for_update() # modify the stage omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") # try to close a modified stage mock_callback = Mock() with patch.object(ISettings, "get", side_effect=self._mock_get_carb_setting): omni.kit.window.file.close(mock_callback) await self.wait_for_update() mock_callback.assert_called_once()
9,309
Python
40.377778
125
0.653883
omniverse-code/kit/exts/omni.hydra.engine.stats/omni/hydra/engine/stats/__init__.py
from ._stats import *
22
Python
10.499995
21
0.681818
omniverse-code/kit/exts/omni.hydra.engine.stats/omni/hydra/engine/stats/tests/test_bindings.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__ = ['TestStatsBindings'] import omni.kit.test from omni.kit.test import AsyncTestCase import omni.hydra.engine.stats as engine_stats class TestStatsBindings(AsyncTestCase): '''Simple test against the interfaces of the bindings to fail if they change''' def setUp(self): super().setUp() # After running each test def tearDown(self): super().tearDown() def assertItemIsIndexable(self, item): self.assertTrue(hasattr(item, '__getitem__')) async def test_mem_stats(self): mem_stats = engine_stats.get_mem_stats() # Item should be indexable self.assertItemIsIndexable(mem_stats) # Items should have a caetgory field self.assertIsNotNone(mem_stats[0].get('category')) async def test_mem_stats_detailed(self): mem_stats_detailed = engine_stats.get_mem_stats(detailed=True) # Item should be indexable self.assertItemIsIndexable(mem_stats_detailed) # Items should have a caetgory field self.assertIsNotNone(mem_stats_detailed[0].get('category')) async def test_device_info(self): all_devices = engine_stats.get_device_info() # Item should be indexable self.assertItemIsIndexable(all_devices) # Test getting info on individual devices for i in range(len(all_devices)): cur_device = engine_stats.get_device_info(i) self.assertEqual(cur_device['description'], all_devices[i]['description']) self.assertTrue(cur_device, all_devices[i]) async def test_active_engine_stats(self): hd_stats = engine_stats.HydraEngineStats() a = hd_stats.get_nested_gpu_profiler_result() self.assertItemIsIndexable(a) b = hd_stats.get_gpu_profiler_result() self.assertItemIsIndexable(b) c = hd_stats.reset_gpu_profiler_containers() self.assertTrue(c) self.assertIsNotNone(hd_stats.save_gpu_profiler_result_to_json) async def test_specific_engine_stats(self): hd_stats = engine_stats.HydraEngineStats(usd_context_name='', hydra_engine_name='') a = hd_stats.get_nested_gpu_profiler_result() self.assertItemIsIndexable(a) b = hd_stats.get_gpu_profiler_result() self.assertItemIsIndexable(b) c = hd_stats.reset_gpu_profiler_containers() self.assertTrue(c) self.assertIsNotNone(hd_stats.save_gpu_profiler_result_to_json)
2,895
Python
33.891566
91
0.683247
omniverse-code/kit/exts/omni.hydra.engine.stats/omni/hydra/engine/stats/tests/__init__.py
from .test_bindings import *
29
Python
13.999993
28
0.758621
omniverse-code/kit/exts/omni.kit.debug.vscode/omni/kit/debug/vscode_debugger.py
import omni.ext import omni.kit.commands import omni.kit.ui import omni.kit.debug.python EXTENSION_NAME = "VS Code Link" class DebugBreak(omni.kit.commands.Command): def do(self): omni.kit.debug.python.breakpoint() def toColor01(color): return tuple(c / 255.0 for c in color) + (1,) class Extension(omni.ext.IExt): """ Extension to enable connection of VS Code python debugger. It enables it using python ptvsd module and shows status. """ def on_startup(self): self._window = omni.kit.ui.Window(EXTENSION_NAME, 300, 150) layout = self._window.layout row_layout = layout.add_child(omni.kit.ui.RowLayout()) # Status label row_layout.add_child(omni.kit.ui.Label("Status:")) self._status_label = row_layout.add_child(omni.kit.ui.Label()) wait_info = omni.kit.debug.python.get_listen_address() info_label = layout.add_child(omni.kit.ui.Label()) info_label.text = f"Address: {wait_info}" if wait_info else "Error" # Break button self._break_button = layout.add_child(omni.kit.ui.Button("Break")) def on_click(*x): omni.kit.commands.execute("DebugBreak") self._break_button.set_clicked_fn(on_click) # Monitor for attachment self._attached = None self._set_attached(False) def on_update(dt): self._set_attached(omni.kit.debug.python.is_attached()) self._window.set_update_fn(on_update) def _set_attached(self, attached): if self._attached != attached: ATTACH_DISPLAY = { True: ("VS Code Debugger Attached", (0, 255, 255)), False: ("VS Code Debugger Unattached", (255, 0, 0)), } self._attached = attached self._break_button.enabled = attached self._status_label.text = ATTACH_DISPLAY[self._attached][0] self._status_label.set_text_color(toColor01(ATTACH_DISPLAY[self._attached][1]))
2,011
Python
29.484848
120
0.6181
omniverse-code/kit/exts/omni.kit.property.tagging/omni/kit/property/tagging/scripts/tagging_attributes_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. # from omni.kit.window.property.templates import SimplePropertyWidget, LABEL_WIDTH, LABEL_HEIGHT from omni.kit.tagging import OmniKitTaggingDelegate, get_tagging_instance from pxr import UsdShade, UsdUI import os.path import carb import carb.settings import omni.ui as ui import omni.kit.app import omni.kit.commands import omni.client EXCLUDED_NAMESPACE = "excluded" GENERATED_NAMESPACE = "generated" DOT_EXCLUDED_NAMESPACE = ".excluded" DOT_GENERATED_NAMESPACE = ".generated" EMPTY_NAMESPACE_DISPLAY_VALUE = "<empty namespace>" SPACING = 5 class TaggingAttributesWidget(SimplePropertyWidget, OmniKitTaggingDelegate): def __init__(self, style): super().__init__(title="Tagging", collapsed=False) self._style = style self._tagging = get_tagging_instance() self._tagging.set_delegate(self) self._advanced_view = False self._refresh_tags = True self._selected_asset = None self._path_names = [] self._current_tags = {} self._configured_namespaces = ["appearance"] self._init_settings() self._read_settings() def on_new_payload(self, payload): self._selected_asset = None self._refresh_tags = True # redraw if rebuild flag is true, or we have a new payload if not super().on_new_payload(payload): return False # exclude material/shaders for prim_path in self._payload: prim = self._get_prim(prim_path) if prim and (prim.IsA(UsdShade.Material) or prim.IsA(UsdShade.Shader) or prim.IsA(UsdShade.NodeGraph) or prim.IsA(UsdUI.Backdrop)): return False return payload is not None and len(payload) > 0 def clean(self): """Inherited function from subclass """ self._tag_event_sub = None self._selected_asset = None self._sub_show_advanced_view = None self._sub_hidden_tags = None self._sub_mod_hidden_tags = None self._stage_event = None self._tagging.set_delegate(None) self._tagging = None def _get_prim(self, prim_path): if prim_path: stage = self._payload.get_stage() if stage: return stage.GetPrimAtPath(prim_path) return None def _init_settings(self): settings = carb.settings.get_settings() self._sub_show_advanced_view = omni.kit.app.SettingChangeSubscription( "/persistent/exts/omni.kit.property.tagging/showAdvancedTagView", lambda *_: self._on_settings_change() ) self._sub_hidden_tags = omni.kit.app.SettingChangeSubscription( "/persistent/exts/omni.kit.property.tagging/showHiddenTags", lambda *_: self._on_settings_change() ) self._sub_mod_hidden_tags = omni.kit.app.SettingChangeSubscription( "/persistent/exts/omni.kit.property.tagging/modifyHiddenTags", lambda *_: self._on_settings_change() ) def _read_settings(self): settings = carb.settings.get_settings() self._allow_advanced_view = settings.get("/persistent/exts/omni.kit.property.tagging/showAdvancedTagView") self._show_hidden_tags = settings.get("/persistent/exts/omni.kit.property.tagging/showHiddenTags") self._modify_hidden_tags = settings.get("/persistent/exts/omni.kit.property.tagging/modifyHiddenTags") self._show_and_modify_hidden_tags = self._show_hidden_tags and self._modify_hidden_tags def _on_settings_change(self): self._read_settings() self.request_rebuild() def _get_tags_callback(self): self.request_rebuild() def updated_tags_for_url(self, url): if url in self._path_names: self._refresh_tags = True self.request_rebuild() def _get_prim_paths(self, payload): """Get the absolute paths of the full prim stack of the payload. """ stage = payload.get_stage() if stage is None: return [], [] prims = [] path_names = [] for path in payload: prim = stage.GetPrimAtPath(path) if prim: for prim_spec in prim.GetPrimStack(): identifier = prim_spec.layer.identifier broken_url = omni.client.break_url(identifier) if broken_url.scheme == "omniverse" and identifier not in path_names: path_names.append(identifier) prims.append(prim) return prims, path_names def _prim_selection_view(self): """Build the combo box that can select the absolute path of the asset whose tags we will display """ with ui.HStack(): ui.Label("Reference(s):", name="label", word_wrap=True, width=LABEL_WIDTH, height=LABEL_HEIGHT) with ui.VStack(spacing=SPACING): def current_index_changed(model, _index): index = model.get_item_value_model().get_value_as_int() self._selected_asset = self._path_names[index] self._refresh_tags = True self.request_rebuild() if self._selected_asset is None and len(self._path_names) > 0: # default - choose last asset path self._selected_asset = self._path_names[-1] index = self._path_names.index(self._selected_asset) # parse identifiers and create short readable names shorter_path_names = [] for path in self._path_names: broken_url = omni.client.break_url(path) if broken_url.path not in shorter_path_names: shorter_path_names.append(os.path.basename(broken_url.path)) if len(shorter_path_names) < len(self._path_names): shorter_path_names = self._path_names model = ui.ComboBox(index, *shorter_path_names).model model.add_item_changed_fn(lambda m, i: current_index_changed(m, i)) return shorter_path_names[index], index def _advanced_view_toggle(self): if self._allow_advanced_view: def toggle_advanced_view(model): val = model.get_value_as_bool() model.set_value(val) self._advanced_view = val self.request_rebuild() with ui.HStack(width=0, spacing=SPACING): ui.Label("Advanced view", name="label", word_wrap=True, width=LABEL_WIDTH, height=LABEL_HEIGHT) with ui.VStack(width=10): ui.Spacer() bool_check = ui.CheckBox(width=10, height=0, name="greenCheck") bool_check.model.set_value(self._advanced_view) bool_check.model.add_value_changed_fn(toggle_advanced_view) ui.Spacer() else: self._advanced_view = False def build_items(self): """Main function that builds the tagging ui """ self._sub_to_prim = None if len(self._payload) == 0: return with ui.VStack(spacing=SPACING, height=0): prims, path_names = self._get_prim_paths(self._payload) self._path_names = path_names if len(prims) == 0 or not prims[0].GetPath(): ui.Label("Nothing taggable selected") return if len(self._path_names) == 0: ui.Label("No asset paths found.", name="label", alignment=ui.Alignment.LEFT_TOP) return if len(self._path_names) == 0: with ui.VStack(height=0, spacing=SPACING): ui.Label( "No tagging service found", name="label", word_wrap=True, width=LABEL_WIDTH, height=LABEL_HEIGHT ) return if self._refresh_tags: # send a tag query to the tagging service asyncronously self._tagging.get_tags(self._path_names, self._get_tags_callback) self._refresh_tags = False path_tags = {} for path in self._path_names: # get the tags already cached from the tagging service results = self._tagging.tags_for_url(path) if results is None: results = [] path_tags[path] = self._tagging.unpack_raw_tags(results) # prim selection combo box selected_name, selected_index = self._prim_selection_view() # checkbox that enables advanced view (if enabled in preferences) self._advanced_view_toggle() if self._selected_asset is None or self._selected_asset not in path_tags: return self._current_tags = path_tags[self._selected_asset] if not self._current_tags: self._current_tags = {} for namespace in self._configured_namespaces: if namespace not in self._current_tags: self._current_tags[namespace] = {} # sort by namespace sorted_tags = [t for t in self._current_tags] sorted_tags = sorted(sorted_tags) if "" in sorted_tags: sorted_tags = sorted_tags[1:] + [""] with ui.CollapsableFrame(title=f"Tags for {selected_name}", name="groupFrame"): with ui.VStack(spacing=SPACING, height=0): for namespace in sorted_tags: if self._advanced_view: self._create_advanced_view(namespace) else: self._create_default_view(namespace) def _advanced_tag_row(self, namespace, hidden_label, key, value, editable): """Show one tag in advanced view along with buttons. A user tag will be an editable text field. A generated tag will be either hidden, non-editable, or editable, depending on preferences. """ full_tag = self._tagging.pack_tag(namespace, hidden_label, key=key, value=value) if not editable: with ui.HStack(spacing=SPACING, width=ui.Percent(100)): ui.Label(full_tag, name="hidden", style=self._style) return # remove a tag or revert (after an update) a change. def revert_tag(field, remove_btn): field.model.set_value(remove_btn.name) remove_btn.set_tooltip("Remove") # toggle revert and update buttons def on_tag_changed(field, update_btn, remove_btn, value): old_value = remove_btn.name valid = self._tagging.validate_tag(value, self._show_and_modify_hidden_tags) changed = value != old_value and valid if not valid: remove_btn.set_clicked_fn(lambda f=field, rb=remove_btn: revert_tag(f, rb)) remove_btn.set_tooltip("Revert") remove_btn.enabled = True update_btn.visible = False elif changed: remove_btn.set_clicked_fn(lambda f=field, rb=remove_btn: revert_tag(f, rb)) remove_btn.set_tooltip("Revert") remove_btn.enabled = True update_btn.visible = True elif not changed: remove_btn.set_tooltip("Remove") remove_btn.set_clicked_fn(lambda f=field, rb=remove_btn: remove_tag(f, rb)) remove_btn.enabled = True update_btn.visible = False # update a tag via changing text field and clicking "update" button. def update_value(field, update_button, remove_button): full_tag = field.model.get_value_as_string() if self._tagging.validate_tag(full_tag, self._show_and_modify_hidden_tags): old_value = remove_button.name omni.kit.commands.execute( "UpdateTag", asset_path=self._selected_asset, old_tag=old_value, new_tag=full_tag ) update_button.visible = False # update names so we know when the value changes remove_button.name = full_tag # remove a tag or revert (after an update) a change. def remove_tag(field, remove_btn): full_tag = remove_btn.name if self._tagging.validate_tag(full_tag, self._show_and_modify_hidden_tags): omni.kit.commands.execute("RemoveTag", asset_path=self._selected_asset, tag=full_tag) field.visible = False remove_btn.visible = False with ui.HStack(spacing=SPACING, width=ui.Percent(100)): field = ui.StringField() update_button = ui.Button( tooltip="Update", style=self._style["check"], image_height=self._style["check"]["height"], image_width=self._style["check"]["width"], width=1, ) remove_button = ui.Button( tooltip="Remove", style=self._style["remove"], image_height=self._style["remove"]["height"], image_width=self._style["remove"]["width"], width=1, name=full_tag, ) ui.Spacer(width=2) remove_button.set_clicked_fn(lambda f=field, rb=remove_button: remove_tag(f, rb)) update_button.set_clicked_fn(lambda f=field, ub=update_button, rb=remove_button: update_value(f, ub, rb)) update_button.visible = False field.model.set_value(full_tag) field.model.add_value_changed_fn( lambda m, f=field, ub=update_button, rb=remove_button: on_tag_changed( f, ub, rb, m.get_value_as_string() ) ) def _advanced_new_tag_row(self, namespace): """This allows adding a new tag, but the text box must include the namespace (unlike in default view). For example: appearance.user.car """ # add a new tag (must be valid) def add_tag(model): full_tag = model.get_value_as_string() if self._tagging.validate_tag(full_tag, self._show_and_modify_hidden_tags): omni.kit.commands.execute("AddTag", asset_path=self._selected_asset, tag=full_tag) model.set_value("") # toggle add button enabled def on_new_tag_changed(btn, value): valid = self._tagging.validate_tag(value, self._show_and_modify_hidden_tags) if valid: btn.enabled = True else: btn.enabled = False with ui.HStack(spacing=SPACING, width=ui.Percent(100)): model = ui.StringField(name="new_tag:" + namespace).model b = ui.Button( "Add", tooltip="Add new tag", style=self._style["plus"], image_height=self._style["plus"]["height"], image_width=self._style["plus"]["height"], width=60, clicked_fn=lambda m=model: add_tag(m), ) b.enabled = False model.add_value_changed_fn(lambda m, btn=b: on_new_tag_changed(btn, m.get_value_as_string())) def _create_advanced_view(self, namespace): """Create the full advanced view for each namespace. """ namespace_name = namespace or EMPTY_NAMESPACE_DISPLAY_VALUE with ui.CollapsableFrame(title=f"Advanced tag view: {namespace_name}", name="subFrame"): with ui.VStack(spacing=SPACING, height=0): # show non-hidden tags first for key in self._current_tags[namespace]: if not key[0] == ".": value = self._current_tags[namespace][key] self._advanced_tag_row(namespace, None, key, value, True) # show hidden tags if self._show_hidden_tags: for hidden_label in self._current_tags[namespace]: if hidden_label[0] == ".": for key, value in self._current_tags[namespace][hidden_label].items(): self._advanced_tag_row( namespace, hidden_label[1:], key, value, self._modify_hidden_tags ) self._advanced_new_tag_row(namespace) def _default_user_tag_row(self, namespace, key, generated_tags): """Show a user created tag and the button to remove it. """ with ui.HStack(spacing=SPACING): ui.Label(key, name="label") ui.Spacer() if namespace == "": full_tag = key else: full_tag = ".".join([namespace, key]) with ui.HStack(width=60): ui.Spacer(width=2) if key in generated_tags: if namespace == "": excluded_tag = "." + ".".join([EXCLUDED_NAMESPACE, key]) else: excluded_tag = "." + ".".join([namespace, EXCLUDED_NAMESPACE, key]) b = ui.Button( style=self._style["remove"], width=1, image_height=self._style["remove"]["height"], image_width=self._style["remove"]["width"], tooltip="Reject", clicked_fn=lambda t=full_tag, ap=self._selected_asset: omni.kit.commands.execute( "AddTag", asset_path=ap, tag=excluded_tag, excluded=t ), ) else: b = ui.Button( style=self._style["remove"], width=1, image_height=self._style["remove"]["height"], image_width=self._style["remove"]["width"], tooltip="Remove", clicked_fn=lambda t=full_tag, ap=self._selected_asset: omni.kit.commands.execute( "RemoveTag", asset_path=ap, tag=t ), ) ui.Spacer(width=2) def _default_generated_tag_row(self, namespace, key): """Show a generated created tag and the buttons to confirm it or reject it. """ with ui.HStack(spacing=SPACING): ui.Label(key, name="generated", style=self._style) ui.Spacer() if namespace == "": user_tag = key exclude_tag = "." + ".".join([EXCLUDED_NAMESPACE, key]) else: user_tag = ".".join([namespace, key]) exclude_tag = "." + ".".join([namespace, EXCLUDED_NAMESPACE, key]) with ui.HStack(width=60): ui.Spacer(width=2) a = ui.Button( width=1, style=self._style["check"], tooltip="Confirm", image_height=self._style["check"]["height"], image_width=self._style["check"]["width"], clicked_fn=lambda t=user_tag, ap=self._selected_asset: omni.kit.commands.execute( "AddTag", asset_path=ap, tag=t ), ) ui.Spacer(width=15) b = ui.Button( width=1, style=self._style["remove"], tooltip="Reject", image_height=self._style["remove"]["height"], image_width=self._style["remove"]["width"], clicked_fn=lambda t=exclude_tag, ap=self._selected_asset: omni.kit.commands.execute( "AddTag", asset_path=ap, tag=t ), ) ui.Spacer(width=2) def _default_new_tag_row(self, namespace): """Show a text box and button to create a new user tag in the given namespace. """ def add_tag(namespace, model): value = model.get_value_as_string() if namespace == "": full_tag = value else: full_tag = ".".join([namespace, value]) # if the tag we are adding is excluded, we want to remove the exclusion (this is undoable) excluded = "" if ( namespace in self._current_tags and DOT_EXCLUDED_NAMESPACE in self._current_tags[namespace] and value in self._current_tags[namespace][DOT_EXCLUDED_NAMESPACE] ): if namespace == "": excluded = "." + ".".join([EXCLUDED_NAMESPACE, value]) else: excluded = "." + ".".join([namespace, EXCLUDED_NAMESPACE, value]) if self._tagging.validate_tag(full_tag, self._show_and_modify_hidden_tags): omni.kit.commands.execute( "AddTag", asset_path=self._selected_asset, tag=full_tag, excluded=excluded ) model.set_value("") def on_new_tag_changed(btn, value): if not namespace == "": value = ".".join([namespace, value]) valid = self._tagging.validate_tag(value, self._show_and_modify_hidden_tags) if valid: btn.enabled = True else: btn.enabled = False with ui.HStack(spacing=SPACING, width=ui.Percent(100)): field = ui.StringField(name="new_tag:" + namespace) model = field.model with ui.HStack(spacing=SPACING, width=60): b = ui.Button( "Add", style=self._style["plus"], image_height=self._style["plus"]["height"], image_width=self._style["plus"]["height"], tooltip="Add new tag", width=60, clicked_fn=lambda m=model, n=namespace: add_tag(n, m), ) b.enabled = False model.add_value_changed_fn(lambda m, btn=b: on_new_tag_changed(btn, m.get_value_as_string())) def _create_default_view(self, namespace): """ This is the default tag view, which shows tags both added by the user and generated hidden tags. When generated tags are "removed" we actually do not delete them, but add another tag with the namespace ".excluded" instead of ".generated" """ def safe_int(value): try: return int(value) except ValueError: return 0 # populate special namespaces user_tags = {} excluded_tags = [] generated_tags = {} if namespace in self._current_tags: user_tags = {n: self._current_tags[namespace][n] for n in self._current_tags[namespace] if n[0] != "."} if DOT_EXCLUDED_NAMESPACE in self._current_tags[namespace]: excluded_tags = self._current_tags[namespace][DOT_EXCLUDED_NAMESPACE] if DOT_GENERATED_NAMESPACE in self._current_tags[namespace]: generated_tags = { key: safe_int(value) for key, value in self._current_tags[namespace][DOT_GENERATED_NAMESPACE].items() if key not in excluded_tags } sorted_by_confidence = [key for key in generated_tags] sorted_by_confidence.sort(key=lambda x: -generated_tags[x]) # skip empty blocks unless they are "appearance" if len(user_tags) == 0 and len(sorted_by_confidence) == 0 and namespace not in self._configured_namespaces: return namespace_name = namespace or EMPTY_NAMESPACE_DISPLAY_VALUE with ui.CollapsableFrame(title=f"Tags for {namespace_name}", name="subFrame"): with ui.VStack(spacing=SPACING): # first list user added tags (non-hidden tags) for key, _ in user_tags.items(): self._default_user_tag_row(namespace, key, generated_tags) # generated tags if sorted_by_confidence and len(sorted_by_confidence) > 0: for key in sorted_by_confidence: if key in user_tags or key in excluded_tags: continue self._default_generated_tag_row(namespace, key) self._default_new_tag_row(namespace)
25,219
Python
41.673435
120
0.543558
omniverse-code/kit/exts/omni.kit.property.tagging/omni/kit/property/tagging/scripts/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 UI_STYLES = {} UI_STYLES["NvidiaLight"] = { "Label::generated": {"color": 0xFF777777, "font_size": 14}, "Label::hidden": {"color": 0xFF777777, "font_size": 14}, "check": { "width": 15, "height": 15, "Button.Image": {"color": 0xFF75A270}, "Button": {"background_color": 0xFFD6D6D6}, }, "remove": { "width": 15, "height": 15, "Button.Image": {"color": 0xFF3333AA}, "Button": {"background_color": 0xFFD6D6D6}, }, "plus": { "Button.Label": {"color": 0xFF333333}, "Button.Label:disabled": {"color": 0xFF666666}, "width": 15, "height": 15, "Button.Image": {"color": 0xFF75A270}, "Button.Image:disabled": {"color": 0xFF666666}, "stack_direction": ui.Direction.LEFT_TO_RIGHT, }, } UI_STYLES["NvidiaDark"] = { "Label::generated": {"color": 0xFF777777, "font_size": 14}, "Label::hidden": {"color": 0xFF777777, "font_size": 14}, "check": {"width": 15, "height": 15, "Button.Image": {"color": 0xFF75A270}, "Button": {"background_color": 0x0}}, "remove": {"width": 15, "height": 15, "Button.Image": {"color": 0xFF3333AA}, "Button": {"background_color": 0x0}}, "plus": { "Button.Label": {"color": 0xFFCCCCCC}, "Button.Label:disabled": {"color": 0xFF666666}, "width": 15, "height": 15, "Button.Image": {"color": 0xFF75A270}, "Button.Image:disabled": {"color": 0xFF666666}, "stack_direction": ui.Direction.LEFT_TO_RIGHT, }, }
2,024
Python
35.818181
118
0.606719
omniverse-code/kit/exts/omni.kit.property.tagging/omni/kit/property/tagging/scripts/tagging_commands.py
import omni.kit.commands import omni.kit.tagging import omni.client class AddTagCommand(omni.kit.commands.Command): """ Add a tag to an asset **Command**. Fails if we are not connected to the tagging server. Args: asset_path (str): Path to the asset. Should start with omniverse: or it will just return tag (str): packed string tag, such as appearance.Car, or .appearance.generated.Truck=99 excluded (str): excluded version of the tag (or empty string) to remove if present """ def __init__(self, asset_path: str, tag: str, excluded: str = ""): self._asset_path = asset_path self._tag = tag self._excluded = excluded def do(self): broken_url = omni.client.break_url(self._asset_path) if broken_url.scheme != "omniverse": return tagging = omni.kit.tagging.get_tagging_instance() tagging.tags_action(self._asset_path, self._tag, action="add") if self._excluded: tagging.tags_action(self._asset_path, self._excluded, action="remove") def undo(self): broken_url = omni.client.break_url(self._asset_path) if broken_url.scheme != "omniverse": return tagging = omni.kit.tagging.get_tagging_instance() tagging.tags_action(self._asset_path, self._tag, action="remove") if self._excluded: tagging.tags_action(self._asset_path, self._excluded, action="add") class RemoveTagCommand(omni.kit.commands.Command): """ Remove a tag to an asset **Command**. Fails if we are not connected to the tagging server. Args: asset_path (str): Path to the asset. Should start with omniverse: or it will just return tag (str): packed string tag, such as appearance.Car, or .appearance.generated.Truck=99 """ def __init__(self, asset_path: str, tag: str): self._asset_path = asset_path self._tag = tag def do(self): broken_url = omni.client.break_url(self._asset_path) if broken_url.scheme != "omniverse": return tagging = omni.kit.tagging.get_tagging_instance() tagging.tags_action(self._asset_path, self._tag, action="remove") def undo(self): broken_url = omni.client.break_url(self._asset_path) if broken_url.scheme != "omniverse": return tagging = omni.kit.tagging.get_tagging_instance() tagging.tags_action(self._asset_path, self._tag, action="add") class UpdateTagCommand(omni.kit.commands.Command): """ Remove a tag to an asset **Command**. Fails if we are not connected to the tagging server. Args: asset_path (str): Path to the asset. Should start with omniverse: or it will just return old_tag (str): packed string tag, such as appearance.Car, or .appearance.generated.Truck=99 new_tag (str): packed string tag, such as appearance.Car, or .appearance.generated.Truck=99 """ def __init__(self, asset_path: str, old_tag: str, new_tag): self._asset_path = asset_path self._old_tag = old_tag self._new_tag = new_tag def do(self): broken_url = omni.client.break_url(self._asset_path) if broken_url.scheme != "omniverse": return tagging = omni.kit.tagging.get_tagging_instance() tagging.tags_action(self._asset_path, old_tag=self._old_tag, action="update", new_tag=self._new_tag) def undo(self): broken_url = omni.client.break_url(self._asset_path) if broken_url.scheme != "omniverse": return tagging = omni.kit.tagging.get_tagging_instance() tagging.tags_action(self._asset_path, old_tag=self._new_tag, action="update", new_tag=self._old_tag) omni.kit.commands.register_all_commands_in_module(__name__)
3,827
Python
36.529411
108
0.634962
omniverse-code/kit/exts/omni.kit.property.tagging/omni/kit/property/tagging/scripts/__init__.py
from .tagging_properties import * from .tagging_commands import *
66
Python
21.333326
33
0.787879
omniverse-code/kit/exts/omni.kit.property.tagging/omni/kit/property/tagging/scripts/tagging_properties.py
import os import carb import omni.ext from pxr import Sdf, UsdShade from pathlib import Path from .style import UI_STYLES class TaggingPropertyExtension(omni.ext.IExt): def __init__(self): self._registered = False self._icon_path = "" super().__init__() def on_startup(self, ext_id): manager = omni.kit.app.get_app().get_extension_manager() extension_path = manager.get_extension_path(ext_id) self._icon_path = Path(extension_path).joinpath("data").joinpath("icons") self._hooks = manager.subscribe_to_extension_enable( on_enable_fn=lambda _: self._register_widget(), on_disable_fn=lambda _: self._unregister_widget(), ext_name="omni.kit.window.property", hook_name="omni.kit.window.property listener", ) def destroy(self): if self._registered: self._unregister_widget() def on_shutdown(self): self._hooks = None if self._registered: self._unregister_widget() def _register_widget(self): theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" style = UI_STYLES[theme] # update icon paths style["check"]["image_url"] = str(self._icon_path.joinpath("check.svg")) style["remove"]["image_url"] = str(self._icon_path.joinpath("remove.svg")) style["plus"]["image_url"] = str(self._icon_path.joinpath("plus.svg")) try: import omni.kit.window.property as p from .tagging_attributes_widget import TaggingAttributesWidget w = p.get_window() if w: w.register_widget("prim", "tagging", TaggingAttributesWidget(style)) self._registered = True except Exception as exc: carb.log_error(f"Error registering tagging widget {exc}") def _unregister_widget(self): try: import omni.kit.window.property as p w = p.get_window() if w: w.unregister_widget("prim", "tagging") self._registered = False except Exception as e: carb.log_warn(f"Unable to unregister 'tagging:/attributes': {e}")
2,256
Python
33.723076
108
0.595301
omniverse-code/kit/exts/omni.kit.property.tagging/omni/kit/property/tagging/tests/test_tagging.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 pathlib import omni.kit.app import omni.kit.commands import omni.kit.test import omni.ui as ui from omni.kit import ui_test from omni.ui.tests.test_base import OmniUiTest from pxr import Kind, Sdf, Gf class TestTaggingWidget(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() ext_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) self._golden_img_dir = pathlib.Path(ext_path).joinpath("data/tests/golden_img") from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget import omni.kit.window.property as p self._w = p.get_window() # After running each test async def tearDown(self): await super().tearDown() # Test(s) async def test_tagging_ui(self): usd_context = omni.usd.get_context() await self.docked_test_window( window=self._w._window, width=450, height=250, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) # new stage await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() ## create prim omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") # verify one prim prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll() if prim.GetPath().pathString not in ['/Render', '/Render/Vars']] self.assertTrue(prim_list == ['/Sphere']) # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/Sphere"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) # verify image await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_tagging_ui.png")
2,414
Python
35.590909
143
0.676056
omniverse-code/kit/exts/omni.kit.property.tagging/omni/kit/property/tagging/tests/__init__.py
from .test_tagging import *
28
Python
13.499993
27
0.75
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/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. # """The documentation of the omni.ui aka UI Framework""" from .scripts.ui_doc import UIDoc from functools import partial import asyncio import carb import carb.settings import omni.ext import omni.kit.app import omni.ui as ui EXTENSION_NAME = "Omni.UI Documentation" class ExampleExtension(omni.ext.IExt): """The Demo extension""" WINDOW_NAME = "Omni::UI Doc" _ui_doc = None def __init__(self): super().__init__() @staticmethod def ui_doc(): return ExampleExtension._ui_doc def get_name(self): """Return the name of the extension""" return EXTENSION_NAME def on_startup(self, ext_id): """Caled to load the extension""" extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id) ExampleExtension._ui_doc = UIDoc(extension_path) ui.Workspace.set_show_window_fn( ExampleExtension.WINDOW_NAME, lambda show: show and ExampleExtension._ui_doc.build_window(ExampleExtension.WINDOW_NAME), ) ui.Workspace.show_window(ExampleExtension.WINDOW_NAME) # Dock this extension into mainwindow if running as standalone settings = carb.settings.get_settings() standalone_mode = settings.get_as_bool("app/settings/standalone_mode") if standalone_mode: asyncio.ensure_future(self._dock_window(ExampleExtension.WINDOW_NAME, omni.ui.DockPosition.SAME)) def on_shutdown(self): """Called when the extesion us unloaded""" ExampleExtension._ui_doc.shutdown() ExampleExtension._ui_doc = None ui.Workspace.set_show_window_fn(ExampleExtension.WINDOW_NAME, None) 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("DockSpace") if window and dockspace: window.dock_in(dockspace, position, ratio=ratio) window.dock_tab_bar_visible = False
2,717
Python
33.405063
109
0.676849
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/__init__.py
# NOTE: all imported classes must have different class names from .extension import *
86
Python
27.999991
60
0.790698
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/ui_doc.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. # """The documentation of the omni.ui aka UI Framework""" from .abstract_model_doc import AbstractModelDoc from .attribute_editor_demo import AttributeEditorWindow from .canvas_frame_doc import CanvasFrameDoc from .checkbox_doc import CheckBoxDoc from .colorwidget_doc import ColorWidgetDoc from .combobox_doc import ComboBoxDoc from .custom_window_example import BrickSunStudyWindow from .dnd_doc import DNDDoc from .doc_page import DocPage from .field_doc import FieldDoc from .image_doc import ImageDoc from .layout_doc import LayoutDoc from .length_doc import LengthDoc from .md_doc import MdDoc from .menu_bar_doc import MenuBarDoc from .menu_doc import MenuDoc from .multifield_doc import MultiFieldDoc from .plot_doc import PlotDoc from .progressbar_doc import ProgressBarDoc from .scrolling_frame_doc import ScrollingFrameDoc from .shape_doc import ShapeDoc from .slider_doc import SliderDoc from .styling_doc import StylingDoc from .treeview_doc import TreeViewDoc from .widget_doc import WidgetDoc from .window_doc import WindowDoc from .workspace_doc import WorkspaceDoc from omni.kit.documentation.builder import DocumentationBuilderWindow from omni.kit.documentation.builder import DocumentationBuilderMd from omni.ui import color as cl from omni.ui import constant as fl from pathlib import Path import omni.kit.app as app import omni.ui as ui EXTENSION_NAME = "OMNI.UI Demo" SPACING = 5 CURRENT_PATH = Path(__file__).parent DOCS_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("docs") MVD_PAGES = ["overview.md", "model.md", "delegate.md"] class UIDoc(DocPage): """UI Doc Class""" def __init__(self, extension_path): super().__init__(extension_path) self.omniverse_version, _, _ = app.get_app_interface().get_build_version().partition("-") self.vertical_scrollbar_on = True self._extension_path = extension_path self._style_system = { "Button": { "background_color": 0xFFE1E1E1, "border_color": 0xFFADADAD, "border_width": 0.5, "border_radius": 0.0, "margin": 5.0, "padding": 5.0, }, "Button.Label": {"color": 0xFF000000}, "Button:hovered": {"background_color": 0xFFFBF1E5, "border_color": 0xFFD77800}, "Button:pressed": {"background_color": 0xFFF7E4CC, "border_color": 0xFF995400, "border_width": 1.0}, } self._example_windows = {} self._window_list = [["Attribute Editor", AttributeEditorWindow()], ["Custom Window", BrickSunStudyWindow()]] self._mvd_pages = [DocumentationBuilderMd(DOCS_PATH.joinpath(filename)) for filename in MVD_PAGES] self.index_list = [ ["LAYOUT"], [ "Arrangement of elements", LayoutDoc(extension_path), [ "HStack", "VStack", "ZStack", "Spacing", "Frame", "VGrid", "HGrid", "CollapsableFrame", "Placer", "Visibility", "Direction", ], ], ["Lengths", LengthDoc(extension_path), ["Pixel", "Percent", "Fraction"]], ["WIDGETS"], ["Styling", StylingDoc(extension_path), ["The Style Sheet Syntax", "Shades", "URL Shades", "Font Size"]], [ "Base Widgets", WidgetDoc(extension_path), ["Button", "RadioButton", "Label", "Tooltip", "Debug Color", "Font"], ], ["Menu", MenuDoc(extension_path), []], ["ScrollingFrame", ScrollingFrameDoc(extension_path), []], ["CanvasFrame", CanvasFrameDoc(extension_path), []], ["Image", ImageDoc(extension_path), []], ["CheckBox", CheckBoxDoc(extension_path), []], ["AbstractValueModel", AbstractModelDoc(extension_path), []], ["ComboBox", ComboBoxDoc(extension_path), []], ["ColorWidget", ColorWidgetDoc(extension_path), []], ["MultiField", MultiFieldDoc(extension_path), []], ["TreeView", TreeViewDoc(extension_path), []], [ "Shapes", ShapeDoc(extension_path), ["Rectangle", "Circle", "Triangle", "Line", "FreeRectangle", "FreeBezierCurve"], ], ["Fields", FieldDoc(extension_path), ["StringField"]], ["Sliders", SliderDoc(extension_path), ["FloatSlider", "IntSlider", "FloatDrag", "IntDrag"]], ["ProgressBar", ProgressBarDoc(extension_path), []], ["Plot", PlotDoc(extension_path), []], ["Drag and Drop", DNDDoc(extension_path), ["Minimal Example", "Styling and Tooltips"]], ] # Add .md files here self.index_list.append(["MODEL-DELEGATE-VIEW"]) for page in self._mvd_pages: catalog = page.catalog topic = catalog[0]["name"] sub_topics = [c["name"] for c in catalog[0]["children"]] self.index_list.append([topic, MdDoc(extension_path, page), sub_topics]) self.index_list += [ ["WINDOWING SYSTEM"], [ "Windows", WindowDoc(extension_path), ["Window", "ToolBar", "Multiple Modal Windows", "Overlay Other Windows", "Workspace", "Popup"], ], ["MenuBar", MenuBarDoc(extension_path), ["MenuBar"]], ["Workspace", WorkspaceDoc(extension_path), ["Controlling Windows", "Capture Layout"]], ] try: # TODO(vyudin): can we remove? import omni.kit.widget.webview webview_enabled = True except: webview_enabled = False if webview_enabled: from .web_doc import WebViewWidgetDoc web_view_widget_doc = WebViewWidgetDoc() self.index_list += [ ["WEB WIDGETS"], ["WebViewWidget", web_view_widget_doc, web_view_widget_doc.get_sections()], ] def get_style(self): cl.ui_docs_nvidia = cl("#76b900") # Content cl.ui_docs_bg = cl.white cl.ui_docs_text = cl("#1a1a1a") cl.ui_docs_h1_bg = cl.black cl.ui_docs_code_bg = cl("#eeeeee") cl.ui_docs_code_line = cl("#bbbbbb") fl.ui_docs_code_radius = 2 fl.ui_docs_text_size = 18 # Catalog cl.ui_docs_catalog_bg = cl.black cl.ui_docs_catalog_hovered = cl("#1b1f20") style = DocumentationBuilderWindow.get_style() style.update({ "Button::placed:hovered": {"background_color": 0xFF1111FF, "border_color": 0xFFFF0000, "border_width": 2}, "CanvasFrame": {"background_color": 0xFFDDDDDD}, "Circle::blue": {"background_color": 0xFFFF1111, "border_color": 0xFF0000CC, "border_width": 2}, "Circle::default": {"background_color": 0xFF000000, "border_color": 0xFFFFFFFF, "border_width": 1}, "Circle::placed:pressed": {"background_color": 0xFF1111FF, "border_color": 0xFFFF0000, "border_width": 2}, "Circle::red": {"background_color": 0xFF1111FF, "border_color": 0xFFFF0000, "border_width": 2}, "Image::index_h2": {"color": 0xFF484849, "image_url": f"{self._extension_path}/icons/plus.svg"}, "Image::index_h2:selected": {"color": 0xFF5D5D5D, "image_url": f"{self._extension_path}/icons/minus.svg"}, "Image::omniverse_image": {"image_url": "resources/icons/ov_logo_square.png", "margin": 5}, "Label::caption": {"color": 0xFFFFFFFF, "font_size": 22.0, "margin_width": 10, "margin_height": 4}, "Label::code": {"color": cl.ui_docs_text}, "Label::index_h1": { "color": cl.ui_docs_nvidia, "font_size": 16.0, "margin_height": 5, "margin_width": 20, }, "Label::index_h2": {"color": 0xFFD9D9D9, "font_size": 16.0, "margin_height": 5, "margin_width": 5}, "Label::index_h2:selected": {"color": 0xFF404040}, "Label::index_h3": {"color": 0xFF404040, "font_size": 16.0, "margin_height": 5, "margin_width": 30}, "Label::omniverse_version": {"font_size": 16.0, "color": 0xFF4D4D4D, "margin": 10}, "Label::section": { "color": cl.ui_docs_nvidia, "font_size": 22.0, "margin_width": 10, "margin_height": 4, }, "Label::text": {"color": cl.ui_docs_text, "font_size": fl.ui_docs_text_size}, "Line::default": {"color": 0xFF000000, "border_width": 1}, "Line::demo": {"color": 0xFF555500, "border_width": 3}, "Line::separator": {"color": 0xFF111111, "border_width": 2}, "Line::underline": {"color": 0xFF444444, "border_width": 2}, "Rectangle::caption": {"background_color": cl.ui_docs_nvidia}, "Rectangle::code": { "background_color": cl.ui_docs_code_bg, "border_color": cl.ui_docs_code_line, "border_width": 1.0, "border_radius": fl.ui_docs_code_radius, }, "Rectangle::placed:hovered": { "background_color": 0xFFFF6E00, "border_color": 0xFF111111, "border_width": 2, }, "Rectangle::section": {"background_color": cl.ui_docs_h1_bg}, "Rectangle::selection_h2": {"background_color": cl.ui_docs_catalog_bg}, "Rectangle::selection_h2:hovered": {"background_color": 0xFF4A4A4E}, "Rectangle::selection_h2:pressed": {"background_color": 0xFFB98029}, "Rectangle::selection_h2:selected": {"background_color": 0xFFFCFCFC}, "Rectangle::selection_h3": {"background_color": 0xFFE3E3E3}, "Rectangle::selection_h3:hovered": {"background_color": 0xFFD6D6D6}, "Rectangle::table": {"background_color": 0x0, "border_color": 0xFFCCCCCC, "border_width": 0.25}, "ScrollingFrame::canvas": {"background_color": cl.ui_docs_bg}, "Triangle::default": {"background_color": 0xFF00FF00, "border_color": 0xFFFFFFFF, "border_width": 1}, "Triangle::orientation": {"background_color": 0xFF444444, "border_color": 0xFFFFFFFF, "border_width": 3}, "VStack::layout": {"margin": 50}, "VStack::layout_md": {"margin": 1}, }) return style def build_window(self, title): """Caled to load the extension""" self._window = ui.Window(title, width=1000, height=600, dockPreference=ui.DockPreference.LEFT_BOTTOM) # Populate UI once the window is visible self._window.frame.set_build_fn(self.build_window_content) # Dock it to the same space where Layers is docked if ui.Workspace.get_window("Content"): self._window.deferred_dock_in("Content") def rebuild(self): """Rebuild all the content""" self._window.frame.rebuild() def build_window_content(self): global_style = self.get_style() with ui.HStack(): # Side panel with the table of contents with ui.ScrollingFrame( width=250, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, ): with ui.ZStack(height=0): ui.Rectangle(style={"background_color": 0xFF313134}) with ui.VStack(style=global_style, height=0): # Omniverse logo and version with ui.ZStack(): ui.Rectangle(style={"background_color": 0xFF000000}) with ui.VStack(style=global_style, height=0): ui.Image(height=250, alignment=ui.Alignment.CENTER, name="omniverse_image") # Cut the end of the version. It's enough to print: # "Omniverse Version: 103.0+master..." text = f"Omniverse Version: {self.omniverse_version}" if len(text) > 32: text = text[:32] + "..." ui.Label( text, alignment=ui.Alignment.CENTER, name="omniverse_version", tooltip=self.omniverse_version, # elided_text=True, content_clipping=True, ) # The table of contents with ui.VStack(): for entry in self.index_list: if len(entry) == 1: # If entry has nothing, it's a h1 title ui.Label(entry[0], name="index_h1") else: # Otherwise it's h2 title and it has h3 subtitles title = entry[0] sub_titles = entry[2] if len(entry) < 4: entry.append(None) entry.append(None) # Draw h2 title stack = ui.ZStack() entry[3] = stack with stack: ui.Rectangle( name="selection_h2", mouse_pressed_fn=lambda x, y, b, a, e=entry: self.show_a_doc(e), ) with ui.HStack(): ui.Spacer(width=10) with ui.VStack(width=0): ui.Spacer() ui.Image(name="index_h2", width=10, height=10) ui.Spacer() ui.Label(title, name="index_h2") # Draw h3 titles, they appear only if h2 is selected stack = ui.VStack(visible=False) entry[4] = stack with stack: for sub in sub_titles: with ui.ZStack(): ui.Rectangle( name="selection_h3", mouse_pressed_fn=lambda x, y, b, a, e=entry, n=sub: self.show_a_doc( e, n ), ) ui.Label(sub, name="index_h3") ui.Label("WINDOW EXAMPLES", name="index_h1") with ui.VStack(): for entry in self._window_list: with ui.ZStack(): ui.Rectangle( name="selection_h2", mouse_pressed_fn=lambda x, y, b, a, n=entry[0], w=entry[1]: self._show_a_window( n, w ), ) with ui.HStack(): ui.Spacer(width=20) ui.Label(entry[0], name="index_h2") ui.Spacer(height=10) # The document if self.vertical_scrollbar_on: vertical_scrollbar_policy = ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON else: vertical_scrollbar_policy = ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF self._doc_scrolling_frame = ui.ScrollingFrame( style=global_style, name="canvas", horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=vertical_scrollbar_policy, ) self._add_all_docs() def clean_entries(self): """Should be called when the extesion is reloaded to destroy the items, that can't be auto destroyed.""" for entry in self.index_list: if len(entry) > 1 and entry[1]: entry[1].clean() def shutdown(self): """Should be called when the extesion us unloaded""" # Unfortunatley, the member variables are not destroyed when the extension is unloaded. We need to do it # automatically. Usually, it's OK because the Python garbage collector will eventually destroy everythigng. But # we need the images to be destroyed right now because Kit know nothing about Python garbage collector and it # will fire warning that texture is not destroyed. for page in self._mvd_pages: page.destroy() self._mvd_pages = [] self.clean_entries() self._window = None def show_a_doc(self, entry, navigate_to=None): """ show a single doc """ # Unselect/uncheck everything on the side panel for index_entry in self.index_list: if len(index_entry) == 5: _, _, _, item, sub_items = index_entry item.selected = False sub_items.visible = False self.clean_entries() # Select and show the given title _, doc, _, item, sub_items = entry item.selected = True sub_items.visible = True if isinstance(doc, MdDoc): style = "layout_md" else: style = "layout" with self._doc_scrolling_frame: # The page itself with ui.VStack(height=0, spacing=20, name=style): doc.create_doc(navigate_to) if not navigate_to: # Scroll up if there is nothing to jump to because scrolling frame remembers the scrolling position of # the previous page self._doc_scrolling_frame.scroll_y = 0 def _show_a_window(self, name, window_class): """ window an example window """ if name not in self._example_windows: self._example_windows[name] = window_class.build_window() self._example_windows[name].visible = True def _add_all_docs(self): """The body of the document""" self.clean_entries() with self._doc_scrolling_frame: # The page itself with ui.VStack(height=0, spacing=20, name="layout"): self._section_title("What is Omni::UI?") self._text( "Omni::UI is Omniverse's UI toolkit for creating beautiful and flexible graphical user interfaces " "in the Kit extensions. Omni::UI provides the basic types necessary to create rich extensions with " "a fluid and dynamic user interface in Omniverse Kit. It gives a layout system and includes " "widgets for creating visual components, receiving user input, and creating data models. It allows " "user interface components to be built around their behavior and enables a declarative flavor of " "describing the layout of the application. Omni::UI gives a very flexible styling system that " "allows for deep customizing of the final look of the application." ) for entry in self.index_list: if len(entry) > 1 and entry[1] is not None: entry[1].create_doc()
20,840
Python
46.151584
120
0.518042
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/workspace_doc.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. # """The documentation for Workspaces""" from omni import ui from .doc_page import DocPage import json SPACING = 5 class WorkspaceDoc(DocPage): """document Workspace class""" def _undock(self, selection): if not selection: return for item in selection: item.window.undock() def _dock(self, left, right, position): if not left or not right: return target = right[0].window for item in left: item.window.dock_in(target, position) def _left(self, selection): if not selection: return for item in selection: item.window.position_x -= 100 def _right(self, selection): if not selection: return for item in selection: item.window.position_x += 100 def _set_visibility(self, selection, visible): if not selection: return for item in selection: if visible is not None: item.window.visible = visible else: item.window.visible = not item.window.visible def _dock_reorder(self, selection): if not selection: return docking_groups = [ui.Workspace.get_docked_neighbours(item.window) for item in selection] for group in docking_groups: # Reverse order for i, window in enumerate(reversed(group)): window.dock_order = i def _tabs(self, selection, visible): if not selection: return for item in selection: item.window.dock_tab_bar_visible = visible def _focus(self, selection): if not selection: return for item in selection: item.window.focus() break def create_doc(self, navigate_to=None): self._section_title("Workspace") self._caption("Controlling Windows", navigate_to) class WindowItem(ui.AbstractItem): def __init__(self, window): super().__init__() # Don't keep the window because it prevents the window from closing. self._window_title = window.title self.title_model = ui.SimpleStringModel(self._window_title) self.type_model = ui.SimpleStringModel(type(window).__name__) @property def window(self): return ui.Workspace.get_window(self._window_title) class WindowModel(ui.AbstractItemModel): def __init__(self): super().__init__() self._root = ui.SimpleStringModel("Windows") self.update() def update(self): self._children = [WindowItem(i) for i in ui.Workspace.get_windows()] self._item_changed(None) def get_item_children(self, item): if item is not None: return [] return self._children def get_item_value_model_count(self, item): return 2 def get_item_value_model(self, item, column_id): if item is None: return self._root if column_id == 0: return item.title_model if column_id == 1: return item.type_model self._window_model = WindowModel() self._tree_left = None self._tree_right = None with ui.VStack(style=self._style_system): ui.Button("Refresh", clicked_fn=lambda: self._window_model.update()) with ui.HStack(): ui.Button("Clear", clicked_fn=ui.Workspace.clear) ui.Button("Focus", clicked_fn=lambda: self._focus(self._tree_left.selection)) with ui.HStack(): ui.Button("Visibile", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, True)) ui.Button("Invisibile", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, False)) ui.Button("Toggle Visibility", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, None)) with ui.HStack(): ui.Button( "Dock Right", clicked_fn=lambda: self._dock( self._tree_left.selection, self._tree_right.selection, ui.DockPosition.RIGHT ), ) ui.Button( "Dock Left", clicked_fn=lambda: self._dock( self._tree_left.selection, self._tree_right.selection, ui.DockPosition.LEFT ), ) ui.Button( "Dock Top", clicked_fn=lambda: self._dock( self._tree_left.selection, self._tree_right.selection, ui.DockPosition.TOP ), ) ui.Button( "Dock Bottom", clicked_fn=lambda: self._dock( self._tree_left.selection, self._tree_right.selection, ui.DockPosition.BOTTOM ), ) ui.Button( "Dock Same", clicked_fn=lambda: self._dock( self._tree_left.selection, self._tree_right.selection, ui.DockPosition.SAME ), ) ui.Button("Undock", clicked_fn=lambda: self._undock(self._tree_left.selection)) with ui.HStack(): ui.Button("Move Left", clicked_fn=lambda: self._left(self._tree_left.selection)) ui.Button("MoveRight", clicked_fn=lambda: self._right(self._tree_left.selection)) with ui.HStack(): ui.Button( "Reverse Docking Tabs of Neighbours", clicked_fn=lambda: self._dock_reorder(self._tree_left.selection), ) ui.Button("Hide Tabs", clicked_fn=lambda: self._tabs(self._tree_left.selection, False)) ui.Button("Show Tabs", clicked_fn=lambda: self._tabs(self._tree_left.selection, True)) with ui.HStack(height=400): with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", ): self._tree_left = ui.TreeView(self._window_model, column_widths=[ui.Fraction(1), 80]) with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", ): self._tree_right = ui.TreeView(self._window_model, column_widths=[ui.Fraction(1), 80]) self._caption("Capture Layout", navigate_to) def generate(label): dump = ui.Workspace.dump_workspace() label.text = json.dumps(dump, sort_keys=True, indent=4) def restore(label): dump = label.text ui.Workspace.restore_workspace(json.loads(dump)) with ui.HStack(style=self._style_system): ui.Button("Generate", clicked_fn=lambda: generate(self._label)) ui.Button("Restore", clicked_fn=lambda: restore(self._label)) self._label = self._code("Press Generate to dump layout") # some padding at the bottom ui.Spacer(height=100)
8,098
Python
35.813636
120
0.551988
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/menu_bar_doc.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. # """The documentation for the MenuBar""" from omni import ui from .doc_page import DocPage SPACING = 5 class MenuBarDoc(DocPage): """ document MenuBar classes""" def __init__(self, extension_path): super().__init__(extension_path) self._window_menu_example = None def create_and_show_window_with_menu(self): if not self._window_menu_example: self._window_menu_example = ui.Window( "Window Menu Example", width=300, height=300, flags=ui.WINDOW_FLAGS_MENU_BAR | ui.WINDOW_FLAGS_NO_BACKGROUND, ) menu_bar = self._window_menu_example.menu_bar with menu_bar: with ui.Menu("File"): ui.MenuItem("Load") ui.MenuItem("Save") ui.MenuItem("Export") with ui.Menu("Window"): ui.MenuItem("Hide") with self._window_menu_example.frame: with ui.VStack(): ui.Button("This Window has a Menu") def show_hide_menu(menubar): menubar.visible = not menubar.visible ui.Button("Click here to show/hide Menu", clicked_fn=lambda m=menu_bar: show_hide_menu(m)) def add_menu(menubar): with menubar: with ui.Menu("New Menu"): ui.MenuItem("I don't do anything") ui.Button("Add New Menu", clicked_fn=lambda m=menu_bar: add_menu(m)) self._window_menu_example.visible = True def create_doc(self, navigate_to=None): self._section_title("MenuBar") self._text( "All the Windows in Omni.UI can have a MenuBar. To add a MenuBar to your window add this flag to your " "constructor - omni.ui.Window(flags=ui.WINDOW_FLAGS_MENU_BAR). The MenuBar object can then be accessed " "through the menu_bar read-only property on your window\n" "A MenuBar is a container so it is built like a Frame or Stack but only takes Menu objects as children. " "You can leverage the 'priority' property on the Menu to order them. They will automatically be sorted " "when they are added, but if you change the priority of an item then you need to explicitly call sort()." ) self._caption("MenuBar", navigate_to) self._text("This class is used to construct a MenuBar for the Window") with ui.HStack(width=0): ui.Button("window with MenuBar Example", width=180, clicked_fn=self.create_and_show_window_with_menu) ui.Label("this populates the menuBar", name="text", width=180, style={"margin_width": 10})
3,237
Python
41.051948
117
0.599629
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/checkbox_doc.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. # """The documentation for CheckBox""" from omni import ui from .doc_page import DocPage SPACING = 5 class CheckBoxDoc(DocPage): """ document for CheckBox""" def create_doc(self, navigate_to=None): self._section_title("CheckBox") self._text( "A CheckBox is an option button that can be switched on (checked) or off (unchecked). Checkboxes are " "typically used to represent features in an application that can be enabled or disabled without affecting " "others." ) self._text( "The checkbox is implemented using the model-delegate-view pattern. The model is the central component of this " "system. It is the application's dynamic data structure independent of the widget. It directly manages the " "data, logic, and rules of the checkbox. If the model is not specified, the simple one is created " "automatically when the object is constructed." ) self._text( "In the following example, the models of two checkboxes are connected, and if one checkbox is changed, it " "makes another checkbox be changed as well." ) with ui.HStack(width=0, spacing=SPACING): # Create two checkboxes first = ui.CheckBox() second = ui.CheckBox() # Connect one to another first.model.add_value_changed_fn(lambda a, b=second: b.model.set_value(not a.get_value_as_bool())) second.model.add_value_changed_fn(lambda a, b=first: b.model.set_value(not a.get_value_as_bool())) # Set the first one to True first.model.set_value(True) self._text("One of two") self._code( """ # Create two checkboxes first = ui.CheckBox() second = ui.CheckBox() # Connect one to another first.model.add_value_changed_fn( lambda a, b=second: b.model.set_value(not a.get_value_as_bool())) second.model.add_value_changed_fn( lambda a, b=first: b.model.set_value(not a.get_value_as_bool())) """ ) self._text("In the following example, that is a bit more complicated, only one checkbox can be enabled.") with ui.HStack(width=0, spacing=SPACING): # Create two checkboxes first = ui.CheckBox() second = ui.CheckBox() third = ui.CheckBox() def like_radio(model, first, second): """Turn on the model and turn off two checkboxes""" if model.get_value_as_bool(): model.set_value(True) first.model.set_value(False) second.model.set_value(False) # Connect one to another first.model.add_value_changed_fn(lambda a, b=second, c=third: like_radio(a, b, c)) second.model.add_value_changed_fn(lambda a, b=first, c=third: like_radio(a, b, c)) third.model.add_value_changed_fn(lambda a, b=first, c=second: like_radio(a, b, c)) # Set the first one to True first.model.set_value(True) self._text("Almost like radio box") self._code( """ # Create two checkboxes first = ui.CheckBox() second = ui.CheckBox() third = ui.CheckBox() def like_radio(model, first, second): '''Turn on the model and turn off two checkboxes''' if model.get_value_as_bool(): model.set_value(True) first.model.set_value(False) second.model.set_value(False) # Connect one to another first.model.add_value_changed_fn( lambda a, b=second, c=third: like_radio(a, b, c)) second.model.add_value_changed_fn( lambda a, b=first, c=third: like_radio(a, b, c)) third.model.add_value_changed_fn( lambda a, b=first, c=second: like_radio(a, b, c)) """ ) with ui.HStack(width=0, spacing=SPACING): ui.CheckBox(enabled=False).model.set_value(True) ui.CheckBox(enabled=False) self._text("Disabled") self._code( """ ui.CheckBox(enabled=False).model.set_value(True) ui.CheckBox(enabled=False) """ ) ui.Spacer(height=10)
4,949
Python
36.786259
124
0.578299
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/combobox_doc.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. # """The documentation for ComboBox""" from omni import ui from .doc_page import DocPage class ComboBoxDoc(DocPage): """ document for ComboBox""" def create_doc(self, navigate_to=None): self._section_title("ComboBox") self._text("The ComboBox widget is a combined button and a drop-down list.") self._text( "A combo box is a selection widget that displays the current item and can pop up a list of selectable " "items." ) self._exec_code( """ ui.ComboBox(1, "Option 1", "Option 2", "Option 3") """ ) self._text("The following example demonstrates how to add items to the combo box.") self._exec_code( """ editable_combo = ui.ComboBox() ui.Button( "Add item to combo", clicked_fn=lambda m=editable_combo.model: m.append_child_item( None, ui.SimpleStringModel("Hello World")), ) """ ) self._text("The minimal model implementation. It requires to hold the value models and reimplement two methods.") self._exec_code( """ class MinimalItem(ui.AbstractItem): def __init__(self, text): super().__init__() self.model = ui.SimpleStringModel(text) class MinimalModel(ui.AbstractItemModel): def __init__(self): super().__init__() self._current_index = ui.SimpleIntModel() self._current_index.add_value_changed_fn( lambda a: self._item_changed(None)) self._items = [ MinimalItem(text) for text in ["Option 1", "Option 2"] ] def get_item_children(self, item): return self._items def get_item_value_model(self, item, column_id): if item is None: return self._current_index return item.model self._minimal_model = MinimalModel() ui.ComboBox(self._minimal_model, style={"font_size": 22}) """ ) self._text( "The example of communication between widgets. Type anything in the field and it will appear in the combo " "box." ) self._exec_code( """ editable_combo = None class StringModel(ui.SimpleStringModel): ''' String Model activated when editing is finished. Adds item to combo box. ''' def __init__(self): super().__init__("") def end_edit(self): combo_model = editable_combo.model # Get all the options ad list of strings all_options = [ combo_model.get_item_value_model(child).as_string for child in combo_model.get_item_children() ] # Get the current string of this model fieldString = self.as_string if fieldString: if fieldString in all_options: index = all_options.index(fieldString) else: # It's a new string in the combo box combo_model.append_child_item( None, ui.SimpleStringModel(fieldString) ) index = len(all_options) combo_model.get_item_value_model().set_value(index) self._field_model = StringModel() def combo_changed(combo_model, item): all_options = [ combo_model.get_item_value_model(child).as_string for child in combo_model.get_item_children() ] current_index = combo_model.get_item_value_model().as_int self._field_model.as_string = all_options[current_index] with ui.HStack(): ui.StringField(self._field_model) editable_combo = ui.ComboBox(width=0, arrow_only=True) editable_combo.model.add_item_changed_fn(combo_changed) """ ) ui.Spacer(height=10) # TODO omni.ui: restore functionality for Kit Next if True: return self._text("The USD example. It tracks the stage cameras and can assign the current camera.") self._exec_code( """ class CamerasItem(ui.AbstractItem): def __init__(self, model): super().__init__() self.model = model class CamerasModel(ui.AbstractItemModel): def __init__(self): super().__init__() # Omniverse interfaces self._viewport = omni.kit.viewport.utility.get_active_viewport() self._stage_update = \\ omni.stageupdate.get_stage_update_interface() self._usd_context = omni.usd.get_context() self._stage_subscription = \\ self._stage_update.create_stage_update_node( "CamerasModel", None, None, None, self._on_prim_created, None, self._on_prim_removed ) # The list of the cameras is here self._cameras = [] # The current index of the editable_combo box self._current_index = ui.SimpleIntModel() self._current_index.add_value_changed_fn( self._current_index_changed) # Iterate the stage and get all the cameras stage = self._usd_context.get_stage() for prim in Usd.PrimRange(stage.GetPseudoRoot()): if prim.IsA(UsdGeom.Camera): self._cameras.append( CamerasItem( ui.SimpleStringModel( prim.GetPath().pathString))) def get_item_children(self, item): return self._cameras def get_item_value_model(self, item, column_id): if item is None: return self._current_index return item.model def _on_prim_created(self, path): self._cameras.append( CamerasItem(ui.SimpleStringModel(path))) self._item_changed(None) def _on_prim_removed(self, path): cameras = [cam.model.as_string for cam in self._cameras] if path in cameras: index = cameras.index(path) del self._cameras[index] self._current_index.as_int = 0 self._item_changed(None) def _current_index_changed(self, model): index = model.as_int self.self._viewport.camera_path = self._cameras[index].model.as_string self._item_changed(None) self._combo_model = CamerasModel() ui.ComboBox(self._combo_model) """ )
7,786
Python
34.076576
121
0.509504
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/slider_doc.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. # """The documentation for Sliders""" from omni import ui from omni.ui import color as cl from .doc_page import DocPage import re SPACING = 5 class SliderDoc(DocPage): """ document for Slider""" def create_doc(self, navigate_to=None): self._section_title("Drag & Slider") self._text( "There are 2 main kind of Sliders, <Type>Slider and <Type>Drag. The Sliders are more like traditionalal " "slider that can be drag and snap where you click, the value can be shown on the slider or not but can not " "be edited directly by double clicking" ) self._text( "The Drags are more like Field in the way that they behave like a Field, you can double clic to edit the " "value but they also have a mean to be 'Dragged' to increase / decrease the value" ) self._text( "They currently support minimal styling, simple background color (background_color) and text color (color)." ) self._caption("FloatSlider", navigate_to) def build_slider_table(label, slider_command): def mystrip(line: str, number: int) -> str: """Remove `number` spaces from the begin of the line""" n = 0 l = len(line) while n < number and n < l and line[n] == " ": n += 1 return line[n:] # Remove whitespaces from the command but keep the newline symbols code = "\n".join(mystrip(line, 16) for line in slider_command.split("\n") if line) with ui.HStack(): with ui.ZStack(width=130): ui.Rectangle(name="table") ui.Label(label, name="text", alignment=ui.Alignment.RIGHT, style={"margin": SPACING}) with ui.ZStack(): ui.Rectangle(name="table") with ui.HStack(name="margin", style={"HStack::margin": {"margin": SPACING / 2}}, spacing=SPACING): exec(code) with ui.ZStack(width=ui.Fraction(2)): ui.Rectangle(name="table") with ui.ZStack(name="margin", style={"ZStack::margin": {"margin": SPACING / 2}}): ui.Rectangle(name="code") ui.Label(code, name="code") with ui.VStack(): build_slider_table( "Default", """ ui.FloatSlider() """, ) build_slider_table( "Min/Max", """ ui.FloatSlider(min=0, max=10) """, ) build_slider_table( "Hard Min/Max", """ model = ui.SimpleFloatModel(1.0, min=0, max=100) ui.FloatSlider(model, min=0, max=10) """, ) build_slider_table( "With Style", """ ui.FloatSlider( min=-180, max=180, style={ "draw_mode": ui.SliderDrawMode.HANDLE, "background_color": cl("#BBBBBB"), "color": cl.black } ) """, ) build_slider_table( "Transparent bg", """ ui.FloatSlider( min=-180, max=180, style={ "draw_mode": ui.SliderDrawMode.HANDLE, "background_color": cl.transparent, "color": cl.black, "font_size":20.0 } ) """, ) build_slider_table( "different slider color", """ ui.FloatSlider( min=0, max=1, style={ "draw_mode": ui.SliderDrawMode.HANDLE, "background_color": cl.transparent, "color": cl.black, "font_size":20.0, "secondary_color": cl.red, "secondary_selected_color": cl("#FF00FF") } ) """, ) build_slider_table( "Field & Slider", """ field = ui.FloatField(height=15, width=50) ui.FloatSlider( min=0, max=20, step=.1, model=field.model, style={"color":cl.transparent} ) # default value field.model.set_value(12.0) """, ) build_slider_table( "Filled Mode Slider", """ ui.FloatSlider( height=20, style={"background_color": cl("#DDDDDD"), "secondary_color": cl("#AAAAAA"), "color": cl("#111111")} ).model.set_value(0.5) """, ) build_slider_table( "Rounded Slider", """ ui.FloatSlider( height=20, style={"border_radius": 20, "background_color": cl.black, "secondary_color": cl("#DDDDDD"), "color": cl("#AAAAAA")} ).model.set_value(0.5) """, ) build_slider_table( "Slider Step", """ slider = ui.FloatSlider( step=0.25, height=0, style={"border_radius": 20, "background_color": cl.black, "secondary_color": cl("#DDDDDD"), "color": cl("#AAAAAA")}) slider.model.set_value(0.5) """, ) build_slider_table( "Handle Step", """ slider = ui.FloatSlider( step=0.2, height=0, style={"draw_mode": ui.SliderDrawMode.HANDLE}) slider.model.set_value(0.4) """, ) self._caption("IntSlider", navigate_to) with ui.VStack(): build_slider_table( "Default", """ ui.IntSlider() """, ) build_slider_table( "Min/Max", """ ui.IntSlider(min=0, max=20) """, ) build_slider_table( "With Style", """ ui.IntSlider( min=0, max=20, style={ "draw_mode": ui.SliderDrawMode.HANDLE, "background_color": cl("#BBFFBB"), "color": cl("#FF00FF"), "font_size": 14.0 } ) """, ) self._caption("FloatDrag", navigate_to) with ui.VStack(): build_slider_table("Default", "ui.FloatDrag()") build_slider_table("Min/Max", "ui.FloatDrag(min=-10, max=10, step=0.01)") self._caption("IntDrag", navigate_to) with ui.VStack(): build_slider_table("Default", "ui.IntDrag()") build_slider_table("Min/Max", "ui.IntDrag(min=0, max=50)") ui.Spacer(height=10)
8,360
Python
33.407407
120
0.417105
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/length_doc.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. # """The documentation for Length""" from omni import ui from .doc_page import DocPage SPACING = 5 class LengthDoc(DocPage): """ document for Length classes""" def create_doc(self, navigate_to=None): self._section_title("Lengths") self._text( "The Framework UI offers several different units for expressing length: Pixel, Percent and Fraction." ) self._text("There is no restriction on which units can be used where.") self._caption("Pixel", navigate_to) self._text("Pixel is the size in pixels and scaled with the HiDPI scale factor.") with ui.HStack(): ui.Button("40px", width=ui.Pixel(40)) ui.Button("60px", width=ui.Pixel(60)) ui.Button("100px", width=100) ui.Button("120px", width=120) ui.Button("150px", width=150) self._code( """ with ui.HStack(): ui.Button("40px", width=ui.Pixel(40)) ui.Button("60px", width=ui.Pixel(60)) ui.Button("100px", width=100) ui.Button("120px", width=120) ui.Button("150px", width=150) """ ) self._caption("Percent", navigate_to) self._text("Percent and Fraction units make it possible to specify sizes relative to the parent size.") self._text("Percent is 1/100th of the parent size.") with ui.HStack(): ui.Button("5%", width=ui.Percent(5)) ui.Button("10%", width=ui.Percent(10)) ui.Button("15%", width=ui.Percent(15)) ui.Button("20%", width=ui.Percent(20)) ui.Button("25%", width=ui.Percent(25)) self._code( """ with ui.HStack(): ui.Button("5%", width=ui.Percent(5)) ui.Button("10%", width=ui.Percent(10)) ui.Button("15%", width=ui.Percent(15)) ui.Button("20%", width=ui.Percent(20)) ui.Button("25%", width=ui.Percent(25)) """ ) self._caption("Fraction", navigate_to) self._text( "Fraction length is made to take the available space of the parent widget and then divide it among all the " "child widgets with Fraction length in proportion to their Fraction factor." ) with ui.HStack(): ui.Button("One", width=ui.Fraction(1)) ui.Button("Two", width=ui.Fraction(2)) ui.Button("Three", width=ui.Fraction(3)) ui.Button("Four", width=ui.Fraction(4)) ui.Button("Five", width=ui.Fraction(5)) self._code( """ with ui.HStack(): ui.Button("One", width=ui.Fraction(1)) ui.Button("Two", width=ui.Fraction(2)) ui.Button("Three", width=ui.Fraction(3)) ui.Button("Four", width=ui.Fraction(4)) ui.Button("Five", width=ui.Fraction(5)) """ ) ui.Spacer(height=10)
3,405
Python
34.479166
120
0.576799
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/shape_doc.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. # """The documentation for Shapes""" from omni import ui from omni.ui import color as cl from .doc_page import DocPage import inspect SPACING = 5 def editable_curve(): with ui.ZStack(height=400): # The Bezier tangents tangents = [(50, 50), (-50, -50)] # Four draggable rectangles that represent the control points placer1 = ui.Placer(draggable=True, offset_x=0, offset_y=0) with placer1: rect1 = ui.Rectangle(width=20, height=20) placer2 = ui.Placer(draggable=True, offset_x=50, offset_y=50) with placer2: rect2 = ui.Rectangle(width=20, height=20) placer3 = ui.Placer(draggable=True, offset_x=100, offset_y=100) with placer3: rect3 = ui.Rectangle(width=20, height=20) placer4 = ui.Placer(draggable=True, offset_x=150, offset_y=150) with placer4: rect4 = ui.Rectangle(width=20, height=20) # The bezier curve curve = ui.FreeBezierCurve(rect1, rect4) curve.start_tangent_width = ui.Pixel(tangents[0][0]) curve.start_tangent_height = ui.Pixel(tangents[0][1]) curve.end_tangent_width = ui.Pixel(tangents[1][0]) curve.end_tangent_height = ui.Pixel(tangents[1][1]) # The logic of moving the control points def left_moved(_): x = placer1.offset_x y = placer1.offset_y tangent = tangents[0] placer2.offset_x = x + tangent[0] placer2.offset_y = y + tangent[1] def right_moved(_): x = placer4.offset_x y = placer4.offset_y tangent = tangents[1] placer3.offset_x = x + tangent[0] placer3.offset_y = y + tangent[1] def left_tangent_moved(_): x1 = placer1.offset_x y1 = placer1.offset_y x2 = placer2.offset_x y2 = placer2.offset_y tangent = (x2 - x1, y2 - y1) tangents[0] = tangent curve.start_tangent_width = ui.Pixel(tangent[0]) curve.start_tangent_height = ui.Pixel(tangent[1]) def right_tangent_moved(_): x1 = placer4.offset_x y1 = placer4.offset_y x2 = placer3.offset_x y2 = placer3.offset_y tangent = (x2 - x1, y2 - y1) tangents[1] = tangent curve.end_tangent_width = ui.Pixel(tangent[0]) curve.end_tangent_height = ui.Pixel(tangent[1]) # Callback for moving the control points placer1.set_offset_x_changed_fn(left_moved) placer1.set_offset_y_changed_fn(left_moved) placer2.set_offset_x_changed_fn(left_tangent_moved) placer2.set_offset_y_changed_fn(left_tangent_moved) placer3.set_offset_x_changed_fn(right_tangent_moved) placer3.set_offset_y_changed_fn(right_tangent_moved) placer4.set_offset_x_changed_fn(right_moved) placer4.set_offset_y_changed_fn(right_moved) def editable_rect(): with ui.ZStack(height=200): # Four draggable rectangles that represent the control points with ui.Placer(draggable=True, offset_x=0, offset_y=0): control1 = ui.Circle(width=10, height=10, name="default") with ui.Placer(draggable=True, offset_x=150, offset_y=150): control2 = ui.Circle(width=10, height=10, name="default") # The rectangle that fits to the control points ui.FreeRectangle(control1, control2) class ShapeDoc(DocPage): """ document for Shapes""" def create_doc(self, navigate_to=None): """ descriptions for the shapes widgets""" self._section_title("Shape") self._text("Shape enable you to build custom widget with specific look") self._text("There are many shape you can use, Rectangle, Circle, Triangle, Line, etc") self._text( "In most case those Shape will fit into the Widget size and scale accoringly to the layout they are in " "For some of them you can fix the size to enable to have more precise control over they size" ) self._caption("Rectangle", navigate_to) self._text( "You can use Rectable to draw rectangle shape, you can have backgroundColor, borderColor, " "borderWidth, border_radius. mixed it with other controls using ZStack to create advance look" ) with ui.VStack(): self._shape_table(f"""ui.Rectangle(name="default")""", "(Default) The rectangle is scaled to fit") self._shape_table( """ui.Rectangle( style={"background_color": cl("#888888"), "border_color": cl("#222222"), "border_width": 2.0, "border_radius": 5.0} )""", "this rectangle use its own style to control colors and shape", ) self._shape_table( """ui.Rectangle( width=20, height=20, style={"background_color": cl("#888888"), "border_color": cl("#222222")} )""", "using fixed width and height", ) self._shape_table( """with ui.ZStack(height=20): ui.Rectangle(height=20, style={"background_color": cl("#888888"), "border_color": cl("#111111"), "border_width": .5, "border_radius": 8.0} ) with ui.HStack(): ui.Spacer(width=10) ui.Image( "resources/icons/Cloud.png", width=20, height=20 ) ui.Label( "Search Field", style={"color": cl("#DDDDDD")} )""", "Compose with ZStack for advanced control", ) self._text("Support for specific Rounded Corner") corner_flags = { "NONE": ui.CornerFlag.NONE, "TOP_LEFT": ui.CornerFlag.TOP_LEFT, "TOP_RIGHT": ui.CornerFlag.TOP_RIGHT, "BOTTOM_LEFT": ui.CornerFlag.BOTTOM_LEFT, "BOTTOM_RIGHT": ui.CornerFlag.BOTTOM_RIGHT, "TOP": ui.CornerFlag.TOP, "BOTTOM": ui.CornerFlag.BOTTOM, "LEFT": ui.CornerFlag.LEFT, "RIGHT": ui.CornerFlag.RIGHT, "ALL": ui.CornerFlag.ALL, } with ui.ScrollingFrame( height=100, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style={"ScrollingFrame": {"background_color": cl.transparent}}, ): with ui.HStack(): for key, value in corner_flags.items(): with ui.ZStack(): ui.Rectangle(name="table") with ui.VStack(style={"VStack": {"margin": SPACING * 2}}): ui.Rectangle( style={"background_color": cl("#AA4444"), "border_radius": 20.0, "corner_flag": value} ) ui.Spacer(height=10) ui.Label(key, style={"color": cl.black, "font_size": 8}, alignment=ui.Alignment.CENTER) self._caption("Circle", navigate_to) self._text("You can use Circle to draw circular shape, you can have backgroundColor, borderColor, borderWidth") with ui.VStack(): self._shape_table( f"""ui.Circle(name="default")""", "(Default) The circle is scaled to fit, the alignment is centered" ) self._shape_table( f"""ui.Circle(name="default")""", "This circle, is scaled to Fit too with the Row 100 height", 100 ) self._shape_table( f"""ui.Circle( name="blue", radius=20, size_policy=ui.CircleSizePolicy.FIXED, alignment=ui.Alignment.LEFT_CENTER)""", "This circle has a fixed radius of 20, the alignment is LEFT_CENTER", ) self._shape_table( f"""ui.Circle( name="red", radius=10, size_policy=ui.CircleSizePolicy.FIXED, alignment=ui.Alignment.RIGHT_CENTER)""", "This circle has a fixed radius of 10, the alignment is RIGHT_CENTER", ) self._shape_table( """ui.Circle( style={"background_color": cl("#00FFFF"),}, size_policy=ui.CircleSizePolicy.STRETCH, alignment=ui.Alignment.CENTER_TOP)""", "This circle has a radius to fill the bound, with an alignment is CENTER_TOP", ) self._shape_table( """ui.Circle( style={"background_color": cl.green, "border_color": cl.blue, "border_width": 5}, radius=10, size_policy=ui.CircleSizePolicy.FIXED, alignment=ui.Alignment.CENTER_BOTTOM)""", "This circle has a fixed radius of 5, the alignment is CENTER_BOTTOM, and a custom style ", ) self._text("Supported Alignment value for the Circle") alignments = { "CENTER": ui.Alignment.CENTER, "LEFT_TOP": ui.Alignment.LEFT_TOP, "LEFT_CENTER": ui.Alignment.LEFT_CENTER, "LEFT_BOTTOM": ui.Alignment.LEFT_BOTTOM, "CENTER_TOP": ui.Alignment.CENTER_TOP, "CENTER_BOTTOM": ui.Alignment.CENTER_BOTTOM, "RIGHT_TOP": ui.Alignment.RIGHT_TOP, "RIGHT_CENTER": ui.Alignment.RIGHT_CENTER, "RIGHT_BOTTOM": ui.Alignment.RIGHT_BOTTOM, } with ui.ScrollingFrame( height=150, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style={"ScrollingFrame": {"background_color": cl.transparent}}, ): with ui.HStack(): for key, value in alignments.items(): with ui.ZStack(): ui.Rectangle(name="table") with ui.VStack(style={"VStack": {"margin": SPACING * 2}}, spacing=SPACING * 2): with ui.ZStack(): ui.Rectangle(name="table") ui.Circle( radius=10, size_policy=ui.CircleSizePolicy.FIXED, name="orientation", alignment=value, style={"background_color": cl("#AA4444")}, ) ui.Label(key, style={"color": cl.black, "font_size": 8}, alignment=ui.Alignment.CENTER) self._caption("Triangle", navigate_to) self._text( "You can use Triangle to draw Triangle shape, you can have backgroundColor, borderColor, borderWidth" ) with ui.VStack(): self._shape_table( f"""ui.Triangle(name="default")""", "(Default) The triange is scaled to fit, base on the left and tip on the center right", 100, ) self._shape_table( """ui.Triangle( style={"border_color": cl.black, "border_width": 2}, alignment=ui.Alignment.CENTER_TOP)""", "Default triange with custom color and border", 100, ) self._text("the Alignment define where is the Tip of the Triangle, base will be at the oposite side") alignments = { "LEFT_TOP": ui.Alignment.LEFT_TOP, "LEFT_CENTER": ui.Alignment.LEFT_CENTER, "LEFT_BOTTOM": ui.Alignment.LEFT_BOTTOM, "CENTER_TOP": ui.Alignment.CENTER_TOP, "CENTER_BOTTOM": ui.Alignment.CENTER_BOTTOM, "RIGHT_TOP": ui.Alignment.RIGHT_TOP, "RIGHT_CENTER": ui.Alignment.RIGHT_CENTER, "RIGHT_BOTTOM": ui.Alignment.RIGHT_BOTTOM, } colors = [cl.red, cl("#FFFF00"), cl("#FF00FF"), cl("#FF0FF0"), cl.green, cl("#F00FFF"), cl("#FFF000"), cl("#AA3333")] index = 0 with ui.ScrollingFrame( height=100, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style={"ScrollingFrame": {"background_color": cl.transparent}}, ): with ui.HStack(): for key, value in alignments.items(): with ui.ZStack(): ui.Rectangle(name="table") with ui.VStack(style={"VStack": {"margin": SPACING * 2}}, spacing=SPACING * 2): color = colors[index] index = index + 1 ui.Triangle(name="orientation", alignment=value, style={"background_color": color}) ui.Label(key, style={"color": cl.black, "font_size": 8}, alignment=ui.Alignment.CENTER) self._caption("Line", navigate_to) self._text("You can use Line to draw Line shape, you can use color, border_width") with ui.VStack(): self._shape_table( f"""ui.Line(name="default")""", "(Default) The Line is scaled to fit, base on the left and tip on the center right", 100, ) self._shape_table( """ui.Line(name="default", alignment=ui.Alignment.H_CENTER, style={"border_width":1, "color": cl.blue})""", "The Line is scaled to fit, centered top to bottom, color red and line width 1", 100, ) self._shape_table( """ui.Line(name="default", alignment=ui.Alignment.LEFT, style={"border_width":5, "color": cl("#880088")})""", "The Line is scaled to fit, Aligned Left , color purple and line width 5", 100, ) self._text("the Alignment define where is the line is in the Widget, always fit") alignments = { "LEFT": ui.Alignment.LEFT, "RIGHT": ui.Alignment.RIGHT, "H_CENTER": ui.Alignment.H_CENTER, "TOP": ui.Alignment.TOP, "BOTTOM": ui.Alignment.BOTTOM, "V_CENTER": ui.Alignment.V_CENTER, } with ui.ScrollingFrame( height=100, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style={"ScrollingFrame": {"background_color": cl.transparent}}, ): with ui.HStack(height=100): for key, value in alignments.items(): with ui.ZStack(): ui.Rectangle(name="table") with ui.VStack(style={"VStack": {"margin": SPACING * 2}}, spacing=SPACING * 2): ui.Line(name="demo", alignment=value) ui.Label(key, style={"color": cl.black, "font_size": 8}, alignment=ui.Alignment.CENTER) self._caption("FreeRectangle", navigate_to) self._text( "The free widget is the widget that is independent of the layout. It means it can be stuck to other " "widgets." ) editable_rect() self._code(inspect.getsource(editable_rect).split("\n", 1)[-1]) self._caption("FreeBezierCurve", navigate_to) self._text("Bezier curves are used to model smooth curves that can be scaled infinitely.") self._text( "FreeBezierCurve is using two widgets to get the position of the curve ends. It means it's possible to " "stick the curve to the layout's widgets, and the curve will follow the changes of the layout " "automatically." ) editable_curve() self._code(inspect.getsource(editable_curve).split("\n", 1)[-1]) ui.Spacer(height=10)
16,893
Python
41.661616
125
0.524063
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/scrolling_frame_doc.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. # """The documentation for Scrolling Frame""" from omni import ui from .doc_page import DocPage SPACING = 5 class ScrollingFrameDoc(DocPage): """ document for Menu""" def create_doc(self, navigate_to=None): self._section_title("ScrollingFrame") self._text( "The ScrollingFrame class provides the ability to scroll onto another widget. ScrollingFrame is used to " "display the contents of a child widget within a frame. If the widget exceeds the size of the frame, the " "frame can provide scroll bars so that the entire area of the child widget can be viewed." ) with ui.HStack(style=self._style_system): left_frame = ui.ScrollingFrame( height=250, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) with left_frame: with ui.VStack(height=0): for i in range(20): ui.Button(f"Button Left {i}") right_frame = ui.ScrollingFrame( height=250, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) with right_frame: with ui.VStack(height=0): for i in range(20): ui.Button(f"Button Right {i}") # Synchronize the scroll position of two frames def set_scroll_y(frame, y): frame.scroll_y = y left_frame.set_scroll_y_changed_fn(lambda y, frame=right_frame: set_scroll_y(frame, y)) right_frame.set_scroll_y_changed_fn(lambda y, frame=left_frame: set_scroll_y(frame, y)) self._code( """ with ui.HStack(style=style_system): left_frame = ui.ScrollingFrame( height=250, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) with left_frame: with ui.VStack(height=0): for i in range(20): ui.Button(f"Button Left {i}") right_frame = ui.ScrollingFrame( height=250, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) with right_frame: with ui.VStack(height=0): for i in range(20): ui.Button(f"Button Right {i}") # Synchronize the scroll position of two frames def set_scroll_y(frame, y): frame.scroll_y = y left_frame.set_scroll_y_changed_fn( lambda y, frame=right_frame: set_scroll_y(frame, y)) right_frame.set_scroll_y_changed_fn( lambda y, frame=left_frame: set_scroll_y(frame, y) """ ) ui.Spacer(height=10)
3,595
Python
38.086956
118
0.596106
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/treeview_doc.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. # """The documentation for Widget""" from .doc_page import DocPage from pathlib import Path import asyncio import omni.ui as ui import time class TreeViewDoc(DocPage): """Document for TreeView""" def __init__(self, extension_path): super().__init__(extension_path) self._selection = None self._model = None def clean(self): """Should be called when the extesion us unloaded or reloaded""" # Unfortunatley, the member variables are not destroyed when the extension is unloaded. We need to do it # automatically. Usually, it's OK because the Python garbage collector will eventually destroy everythigng. But # we need the images to be destroyed right now because Kit know nothing about Python garbage collector and it # will fire warning that texture is not destroyed. if self._selection: self._selection._stage_event_sub = None self._selection._tree_view = None self._selection = None if self._model: self._model.stage_subscription = None self._model = None self._command_model = None self._list_model = None self._name_value_model = None self._name_value_delegate = None def create_doc(self, navigate_to=None): self._section_title("TreeView") self._text( "TreeView is a widget that presents a hierarchical view of information. Each item can have a number of " "subitems. An indentation often visualizes this in a list. An item can be expanded to reveal subitems, if " "any exist, and collapsed to hide subitems." ) self._text( "TreeView can be used in file manager applications, where it allows the user to navigate the file system " "directories. They are also used to present hierarchical data, such as the scene object hierarchy." ) self._text( "TreeView uses a model-delegate-view pattern to manage the relationship between data and the way it is presented. " "The separation of functionality gives developers greater flexibility to customize the presentation of " "items and provides a standard interface to allow a wide range of data sources to be used with other " "widgets." ) self._text("The following example demonstrates how to make a single level tree appear like a simple list.") class CommandItem(ui.AbstractItem): """Single item of the model""" def __init__(self, text): super().__init__() self.name_model = ui.SimpleStringModel(text) class CommandModel(ui.AbstractItemModel): """ Represents the list of commands registered in Kit. It is used to make a single level tree appear like a simple list. """ def __init__(self): super().__init__() self._commands = [] try: import omni.kit.commands except ModuleNotFoundError: return omni.kit.commands.subscribe_on_change(self._commands_changed) self._commands_changed() def _commands_changed(self): """Called by subscribe_on_change""" self._commands = [] import omni.kit.commands for cmd_list in omni.kit.commands.get_commands().values(): for k in cmd_list.values(): self._commands.append(CommandItem(k.__name__)) self._item_changed(None) def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is not None: # Since we are doing a flat list, we return the children of root only. # If it's not root we return. return [] return self._commands def get_item_value_model_count(self, item): """The number of columns""" return 1 def get_item_value_model(self, item, column_id): """ Return value model. It's the object that tracks the specific value. In our case we use ui.SimpleStringModel. """ if item and isinstance(item, CommandItem): return item.name_model with ui.ScrollingFrame( height=400, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", ): self._command_model = CommandModel() tree_view = ui.TreeView( self._command_model, root_visible=False, header_visible=False, style={"TreeView.Item": {"margin": 4}} ) self._text("The following example demonstrates reordering with drag and drop.") class ListItem(ui.AbstractItem): """Single item of the model""" def __init__(self, text): super().__init__() self.name_model = ui.SimpleStringModel(text) def __repr__(self): return f'"{self.name_model.as_string}"' class ListModel(ui.AbstractItemModel): """ Represents the model for lists. It's very easy to initialize it with any string list: string_list = ["Hello", "World"] model = ListModel(*string_list) ui.TreeView(model) """ def __init__(self, *args): super().__init__() self._children = [ListItem(t) for t in args] def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is not None: # Since we are doing a flat list, we return the children of root only. # If it's not root we return. return [] return self._children def get_item_value_model_count(self, item): """The number of columns""" return 1 def get_item_value_model(self, item, column_id): """ Return value model. It's the object that tracks the specific value. In our case we use ui.SimpleStringModel. """ return item.name_model class ListModelWithReordering(ListModel): """ Represents the model for the list with the ability to reorder the list with drag and drop. """ def __init__(self, *args): super().__init__(*args) def get_drag_mime_data(self, item): """Returns Multipurpose Internet Mail Extensions (MIME) data for be able to drop this item somewhere""" # As we don't do Drag and Drop to the operating system, we return the string. return item.name_model.as_string def drop_accepted(self, target_item, source, drop_location=-1): """Reimplemented from AbstractItemModel. Called to highlight target when drag and drop.""" # If target_item is None, it's the drop to root. Since it's # list model, we support reorganizetion of root only and we # don't want to create tree. return not target_item and drop_location >= 0 def drop(self, target_item, source, drop_location=-1): """Reimplemented from AbstractItemModel. Called when dropping something to the item.""" try: source_id = self._children.index(source) except ValueError: # Not in the list. This is the source from another model. return if source_id == drop_location: # Nothing to do return self._children.remove(source) if drop_location > len(self._children): # Drop it to the end self._children.append(source) else: if source_id < drop_location: # Becase when we removed source, the array became shorter drop_location = drop_location - 1 self._children.insert(drop_location, source) self._item_changed(None) with ui.ScrollingFrame( height=400, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", ): self._list_model = ListModelWithReordering("Simplest", "List", "Model", "With", "Reordering") tree_view = ui.TreeView( self._list_model, root_visible=False, header_visible=False, style={"TreeView.Item": {"margin": 4}}, drop_between_items=True, ) self._text("The following example demonstrates the ability to edit TreeView items.") class FloatModel(ui.AbstractValueModel): """An example of custom float model that can be used for formatted string output""" def __init__(self, value: float): super().__init__() self._value = value def get_value_as_float(self): """Reimplemented get float""" return self._value or 0.0 def get_value_as_string(self): """Reimplemented get string""" # This string gors to the field. if self._value is None: return "" # General format. This prints the number as a fixed-point # number, unless the number is too large, in which case it # switches to 'e' exponent notation. return "{0:g}".format(self._value) def set_value(self, value): """Reimplemented set""" try: value = float(value) except ValueError: value = None if value != self._value: # Tell the widget that the model is changed self._value = value self._value_changed() class NameValueItem(ui.AbstractItem): """Single item of the model""" def __init__(self, text, value): super().__init__() self.name_model = ui.SimpleStringModel(text) self.value_model = FloatModel(value) def __repr__(self): return f'"{self.name_model.as_string} {self.value_model.as_string}"' class NameValueModel(ui.AbstractItemModel): """ Represents the model for name-value table. It's very easy to initialize it with any string-float list: my_list = ["Hello", 1.0, "World", 2.0] model = NameValueModel(*my_list) ui.TreeView(model) """ def __init__(self, *args): super().__init__() # ["Hello", 1.0, "World", 2.0"] -> [("Hello", 1.0), ("World", 2.0)] regrouped = zip(*(iter(args),) * 2) self._children = [NameValueItem(*t) for t in regrouped] def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is not None: # Since we are doing a flat list, we return the children of root only. # If it's not root we return. return [] return self._children def get_item_value_model_count(self, item): """The number of columns""" return 2 def get_item_value_model(self, item, column_id): """ Return value model. It's the object that tracks the specific value. In our case we use ui.SimpleStringModel for the first column and SimpleFloatModel for the second column. """ return item.value_model if column_id == 1 else item.name_model class EditableDelegate(ui.AbstractItemDelegate): """ Delegate is the representation layer. TreeView calls the methods of the delegate to create custom widgets for each item. """ def __init__(self): super().__init__() self.subscription = None def build_branch(self, model, item, column_id, level, expanded): """Create a branch widget that opens or closes subtree""" pass def build_widget(self, model, item, column_id, level, expanded): """Create a widget per column per item""" stack = ui.ZStack(height=20) with stack: value_model = model.get_item_value_model(item, column_id) label = ui.Label(value_model.as_string) if column_id == 1: field = ui.FloatField(value_model, visible=False) else: field = ui.StringField(value_model, visible=False) # Start editing when double clicked stack.set_mouse_double_clicked_fn(lambda x, y, b, m, f=field, l=label: self.on_double_click(b, f, l)) def on_double_click(self, button, field, label): """Called when the user double-clicked the item in TreeView""" if button != 0: return # Make Field visible when double clicked field.visible = True field.focus_keyboard() # When editing is finished (enter pressed of mouse clicked outside of the viewport) self.subscription = field.model.subscribe_end_edit_fn( lambda m, f=field, l=label: self.on_end_edit(m, f, l) ) def on_end_edit(self, model, field, label): """Called when the user is editing the item and pressed Enter or clicked outside of the item""" field.visible = False label.text = model.as_string self.subscription = None with ui.ScrollingFrame( height=400, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", style={"Field": {"background_color": 0xFF000000}}, ): self._name_value_model = NameValueModel("First", 0.2, "Second", 0.3, "Last", 0.4) self._name_value_delegate = EditableDelegate() tree_view = ui.TreeView( self._name_value_model, delegate=self._name_value_delegate, root_visible=False, header_visible=False, style={"TreeView.Item": {"margin": 4}}, ) class AsyncQueryModel(ListModel): """ This is an example of async filling the TreeView model. It's collecting only as many as it's possible of USD prims for 0.016s and waits for the next frame, so the UI is not locked even if the USD Stage is extremely big. """ def __init__(self): super().__init__() self._stop_event = None def destroy(self): self.stop() def stop(self): """Stop traversing the stage""" if self._stop_event: self._stop_event.set() def reset(self): """Traverse the stage and keep materials""" self.stop() self._stop_event = asyncio.Event() self._children.clear() self._item_changed(None) asyncio.ensure_future(self.__get_all(self._stop_event)) def __push_collected(self, collected): """Add given array to the model""" for c in collected: self._children.append(c) self._item_changed(None) async def __get_all(self, stop_event): """Traverse the stage portion at time, so it doesn't freeze""" stop_event.clear() start_time = time.time() # The widget will be updated not faster than 60 times a second update_every = 1.0 / 60.0 import omni.usd from pxr import Usd from pxr import UsdShade context = omni.usd.get_context() stage = context.get_stage() if not stage: return # Buffer to keep the portion of the items before sending to the # widget collected = [] for p in stage.Traverse( Usd.TraverseInstanceProxies(Usd.PrimIsActive and Usd.PrimIsDefined and Usd.PrimIsLoaded) ): if stop_event.is_set(): break if p.IsA(UsdShade.Material): # Collect materials only collected.append(ListItem(str(p.GetPath()))) elapsed_time = time.time() # Loop some amount of time so fps will be about 60FPS if elapsed_time - start_time > update_every: start_time = elapsed_time # Append the portion and update the widget if collected: self.__push_collected(collected) collected = [] # Wait one frame to let other tasks go await omni.kit.app.get_app().next_update_async() self.__push_collected(collected) try: import omni.usd from pxr import Usd usd_available = True except ModuleNotFoundError: usd_available = False if usd_available: self._text( "This is an example of async filling the TreeView model. It's collecting only as many as it's possible " "of USD prims for 0.016s and waits for the next frame, so the UI is not locked even if the USD Stage " "is extremely big." ) with ui.ScrollingFrame( height=400, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", style={"Field": {"background_color": 0xFF000000}}, ): self._async_query_model = AsyncQueryModel() ui.TreeView( self._async_query_model, root_visible=False, header_visible=False, style={"TreeView.Item": {"margin": 4}}, ) self._loaded_label = ui.Label("Press Button to Load Materials", name="text") with ui.HStack(): ui.Button("Traverse All", clicked_fn=self._async_query_model.reset) ui.Button("Stop Traversing", clicked_fn=self._async_query_model.stop) def _item_changed(model, item): if item is None: count = len(model._children) self._loaded_label.text = f"{count} Materials Traversed" self._async_query_sub = self._async_query_model.subscribe_item_changed_fn(_item_changed) self._text("For the example code please see the following file:") current_file_name = Path(__file__).resolve() self._code(f"{current_file_name}", elided_text=True) ui.Spacer(height=10)
20,987
Python
39.130019
127
0.532377
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/dnd_doc.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. # """The documentation of the omni.ui aka UI Framework""" from omni import ui from omni.ui import color as cl from .doc_page import DocPage import inspect def simple_dnd(): def drag(url): """Called for the drag operation. Returns drag data.""" return url def drop_accept(url): """Called to check the drag data is acceptable.""" return True def drop(widget, event): """Called when dropping the data.""" widget.source_url = event.mime_data def drag_area(url): """Create a draggable image.""" image = ui.Image(url, width=64, height=64) image.set_drag_fn(lambda: drag(url)) def drop_area(): """A drop area that shows image when drop.""" with ui.ZStack(width=64, height=64): ui.Rectangle() image = ui.Image() image.set_accept_drop_fn(drop_accept) image.set_drop_fn(lambda a, w=image: drop(w, a)) with ui.HStack(): drag_area("resources/icons/Nav_Flymode.png") drag_area("resources/icons/Move_64.png") ui.Spacer(width=64) drop_area() def complex_dnd(): def drag(url): # Draw the image and the image name in the drag tooltip with ui.VStack(): ui.Image(url, width=32, height=32) ui.Label(url) return url def drop_accept(url, ext): # Accept drops of specific extension only return url.endswith(ext) def drop(widget, event): widget.source_url = event.mime_data def drag_area(url): image = ui.Image(url, width=64, height=64) image.set_drag_fn(lambda: drag(url)) def drop_area(ext): # If drop is acceptable, the rectangle is blue style = {} style["Rectangle"] = {"background_color": cl("#999999")} style["Rectangle:drop"] = {"background_color": cl("#004499")} stack = ui.ZStack(width=64, height=64) with stack: ui.Rectangle(style=style) ui.Label(f"Accepts {ext}") image = ui.Image(style={"margin": 2}) stack.set_accept_drop_fn(lambda d, e=ext: drop_accept(d, e)) stack.set_drop_fn(lambda a, w=image: drop(w, a)) with ui.HStack(): drag_area("resources/icons/sound.png") drag_area("resources/icons/stage.png") drag_area("resources/glyphs/menu_audio.svg") drag_area("resources/glyphs/menu_camera.svg") ui.Spacer(width=64) drop_area(".png") ui.Spacer(width=64) drop_area(".svg") class DNDDoc(DocPage): """The document for Drag and Drop""" def create_doc(self, navigate_to=None): self._section_title("Drag and Drop") self._caption("Minimal Example", navigate_to) self._text( "Omni::UI includes methods to perform Drag and Drop operations quickly. Drag and Drop with Omni::UI is " "straightforward." ) self._text( "A drag and drop operation consists of three parts: the drag, accept the drop, and the drop. For drag, " "Widget has a single callback drag_fn. By adding this function to a widget, you set the callback attached " "to the drag operation. The function should return the string data to drag." ) self._text( "To accept the drop Widget has a callback accept_drop_fn. It's called when the mouse enters the widget " "area. It takes the drag string data and should return either the widget can accept this data for the " "drop." ) self._text( "For the drop part, Widget has a callback drop_fn. With this method, we specify if Widget accepts drops. " "And it's called when the user drops the string data to the widget." ) simple_dnd() self._code(inspect.getsource(simple_dnd).split("\n", 1)[-1]) self._caption("Styling and Tooltips", navigate_to) self._text("It's possible to customize the drag tooltip with creating widgets in drag_fn.") self._text( "To show the drop widget accepts drops visually, there is a style 'drop', and it's propagated to the " "children widgets." ) complex_dnd() self._code(inspect.getsource(complex_dnd).split("\n", 1)[-1]) ui.Spacer(height=10)
4,786
Python
32.711267
119
0.616172
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/web_doc.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. # """The documentation for Web features such as WebViewWidget implementations""" from .doc_page import DocPage from typing import List import json import omni.kit.widget.webview as webview import omni.ui as ui _BASE_STYLE = { "WebViewWidget": {"border_width": 0.5, "margin": 5.0, "padding": 5.0, "border_color": 0xFFFD761D}, "Label": {"color": 0xFF000000, "margin": 5.0}, "CheckBox": {"margin": 5.0}, } class WebViewWidgetDoc(DocPage): """ Document for WebViewWidget""" def __init__(self): self._sections = [ ("Displaying an url", self.create_displaying_an_url), ("Styling", self.create_styling), ("Content loading", self.create_content_loading), ("Non-opaque contents", self.create_non_opaque_contents), ("Communication", self.create_js_host_communication), ("Web page debugging", self.create_web_page_debugging), ] def get_sections(self) -> List[str]: return [t for (t, _) in self._sections] def create_doc(self, navigate_to=None): self._section_title("WebViewWidget") for (title, create_func) in self._sections: self._caption(title, navigate_to) create_func() def create_displaying_an_url(self): self._text( """The WebViewWidget type displays web pages. The url can be loaded with 'load_url()'. The load progress can be observed with 'loading_changed_fn' and 'progress_changed_fn' as well as the WebViewWidget properties 'loading' and 'progress'. """ ) with ui.VStack(style=_BASE_STYLE): loading_label = ui.Label("Load label") def update_progress(progress: float): loading_label.text = f"Loading {(progress * 100.0):.0f}% ..." def update_loading(loading: bool): if not loading: loading_label.text = "Loading done." web_view = webview.WebViewWidget( width=ui.Percent(100), height=ui.Pixel(500), loading_changed_fn=update_loading, progress_changed_fn=update_progress, ) urls = ["https://www.nvidia.com", "https://news.ycombinator.com", "http://google.com"] web_view.load_url(urls[0]) def change_url(model, _item): url = urls[model.get_item_value_model().as_int] web_view.load_url(url) url_selector = ui.ComboBox(0, *urls) url_selector.model.add_item_changed_fn(change_url) def create_styling(self): self._text( """The WebViewWidget can be styled normally. Here we create a web view with rounded corners and wider borders. In this example, we also use 'url' constructor property to start the load.""" ) style = { "WebViewWidget": { "border_width": 3, "border_radius": 7, "margin": 5.0, "padding": 5.0, "border_color": 0xFFFD761D, } } with ui.VStack(style=_BASE_STYLE): webview.WebViewWidget(width=ui.Percent(100), height=ui.Pixel(500), url="https://www.google.com") def create_content_loading(self): self._text( """The WebViewWidget can be populated with static html with the 'html' constructor property. In this case, the 'url' property describes the base url of the document.""" ) style = {"WebViewWidget": {"border_width": 0.5, "margin": 5.0, "padding": 5.0, "border_color": 0xFFFD761D}} with ui.VStack(style=style): webview.WebViewWidget( width=ui.Percent(100), height=ui.Pixel(500), html='<body><h1>Hello from web page</h1><p>This is web content. Here\'s a link <a href="http://wwf.org">into the wild.</a></p></body>', url="http://example.com/content_loading", ) def create_non_opaque_contents(self): self._text( """The WebViewWidget can be marked non-opaque so transparent or translucent contents work. The magenta circles are omni.ui widgets and can be seen beneath and on top of the WebViewWidget. The web page is marked as transparent with 'contents_is_opaque=False' and then with HTML body css property 'background: transparent'. """ ) html = """<body style="background: transparent"> <h3 style="background: rgba(255, 0, 0, 0.4)">Web page input</h3> <input type="text" value="..text 1.." /> <br/> <input type="text" value="..text 2.." style="background: rgba(255,255,255,0.5)"/> <br/> <input type="text" value="..text 3.." /> <br/> <input type="text" value="..text 4.." style="background: rgba(255,255,255,0.5)"/> <br/> <input type="text" value="..text last.." /> <br/> </body> """ with ui.VStack(style=_BASE_STYLE): ui.Circle( radius=100, size_policy=ui.CircleSizePolicy.FIXED, alignment=ui.Alignment.LEFT_BOTTOM, style={"background_color": 0xDDFF00AA}, ) webview.WebViewWidget( width=ui.Percent(100), height=ui.Pixel(200), contents_is_opaque=False, html=html, url="http://example.com/non_opaque_contents", style={"background_color": 0}, ) ui.Circle( radius=100, size_policy=ui.CircleSizePolicy.FIXED, alignment=ui.Alignment.LEFT_TOP, style={"background_color": 0xDDFFAAAA}, ) def create_js_host_communication(self): self._text( """The WebViewWidget can control the JavaScript application by using WebViewWidget.evaluate_javascript. The JavaScript application can send data to the host application by using window.nvwebview.messageHandlers.<name>.postMessage("msg"). """ ) html = """<body> <script> function sendToHost() { var v = document.getElementById("toHost"); window.nvwebview.messageHandlers.hostApp.postMessage(v.value); } function receiveFromHost(data) { document.getElementById('fromHost').value = data; } </script> <h3>From JS application to host application</h3> Text to send: <input id="toHost" type="text" value="Hello from &quot;JS&quot; application" size="75" /> <br/> <input type="button" value="Send message to host application" onclick="javascript: sendToHost();" /> <br/> <h3>From host application to JS application</h3> <input id="fromHost" type="text" value="Message from host application comes here" readonly size="75"/> <br/> </body> """ message_to_send = 'Hello from "host" application \U0001f600.' webview_widget = None message_from_js_label = None send_to_js_button = None with ui.VStack(style=_BASE_STYLE): send_to_js_button = ui.Button("Send hello to JS application", width=0) message_from_js_label = ui.Label("Message from JS application comes here") webview_widget = webview.WebViewWidget(width=ui.Percent(100), height=ui.Pixel(300)) def send_to_js(): webview_widget.evaluate_javascript(f"receiveFromHost({json.dumps(message_to_send)})") send_to_js_button.set_clicked_fn(send_to_js) def update_message_from_js_label(msg: str): message_from_js_label.text = msg webview_widget.set_user_script_message_handler_fn("hostApp", update_message_from_js_label) webview_widget.load_html_from_url(html, "https://example.com/js_host_communication") def create_web_page_debugging(self): self._text( """The WebViewWidget.set_remote_web_page_debugging_enabled(true) can be used to enable Chrome Web Inspector debugging for all the WebViewWidget instances. Enable the web page debugging below. Using the desktop Chrome browser, navigate to chrome://inspect to see list of WebViewWidget instances in the process. """ ) webview.WebViewWidget.set_remote_web_page_debugging_enabled(False) checkbox = None def update_remote_debugging(value_model): webview.WebViewWidget.set_remote_web_page_debugging_enabled(value_model.get_value_as_bool()) with ui.HStack(style=_BASE_STYLE): ui.Label("Remote web page debugging enabled", width=0, style={"color": 0xFF000000}) checkbox = ui.CheckBox() checkbox.model.add_value_changed_fn(update_remote_debugging) with ui.VStack(): ui.Spacer() ui.Spacer()
9,073
Python
39.150442
166
0.616665
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/attribute_editor_demo.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. # """an example of creating a custom attribute Editor window""" from omni import ui from pathlib import Path ICON_PATH = Path(__file__).parent.parent.joinpath("icons") LIGHT_WINDOW_STYLE = { # main frame style "ScrollingFrame::canvas": {"background_color": 0xFFCACACA}, "Frame::main_frame": {"background_color": 0xFFCACACA}, # title bar style "Label::title": {"color": 0xFF777777, "font_size": 16.0}, "Rectangle::titleBar": {"background_color": 0xFFCACACA}, "Rectangle::timeSelection": {"background_color": 0xFF888888, "border_radius": 5.0}, "Triangle::timeArrows": {"background_color": 0xFFCACACA}, "Label::timeLabel": {"color": 0xFFDDDDDD, "font_size": 16.0}, # custom widget slider "Rectangle::sunStudySliderBackground": { "background_color": 0xFFBBBBBB, "border_color": 0xFF888888, "border_width": 1.0, "border_radius": 10.0, }, "Rectangle::sunStudySliderForground": {"background_color": 0xFF888888}, "Circle::slider": {"background_color": 0xFFBBBBBB}, "Circle::slider:hovered": {"background_color": 0xFFCCCCCC}, "Circle::slider:pressed": {"background_color": 0xFFAAAAAA}, "Triangle::selector": {"background_color": 0xFF888888}, "Triangle::selector:hovered": {"background_color": 0xFF999999}, "Triangle::selector:pressed": {"background_color": 0xFF777777}, # toolbar "Triangle::play_button": {"background_color": 0xFF6E6E6E}, } KIT_GREEN = 0xFF8A8777 LABEL_PADDING = 120 DARK_WINDOW_STYLE = { "Window": {"background_color": 0xFF444444}, "Button": {"background_color": 0xFF292929, "margin": 3, "padding": 3, "border_radius": 2}, "Button.Label": {"color": 0xFFCCCCCC}, "Button:hovered": {"background_color": 0xFF9E9E9E}, "Button:pressed": {"background_color": 0xC22A8778}, "VStack::main_v_stack": {"secondary_color": 0x0, "margin_width": 10, "margin_height": 0}, "VStack::frame_v_stack": {"margin_width": 15}, "Rectangle::frame_background": {"background_color": 0xFF343432, "border_radius": 5}, "Field::models": {"background_color": 0xFF23211F, "font_size": 14, "color": 0xFFAAAAAA, "border_radius": 4.0}, "Frame": {"background_color": 0xFFAAAAAA}, "Label::transform": {"font_size": 12, "color": 0xFF8A8777}, "Circle::transform": {"background_color": 0x558A8777}, "Field::transform": { "background_color": 0xFF23211F, "border_radius": 3, "corner_flag": ui.CornerFlag.RIGHT, "font_size": 12, }, "Slider::transform": { "background_color": 0xFF23211F, "border_radius": 3, "draw_mode": ui.SliderDrawMode.DRAG, "corner_flag": ui.CornerFlag.RIGHT, "font_size": 14, }, "Label::transform_label": {"font_size": 12, "color": 0xFFDDDDDD}, "Label": {"font_size": 12, "color": 0xFF8A8777}, "Label::label": {"font_size": 14, "color": 0xFF8A8777}, "Label::title": {"font_size": 14, "color": 0xFFAAAAAA}, "Triangle::title": {"background_color": 0xFFAAAAAA}, "ComboBox::path": {"font_size": 12, "secondary_color": 0xFF23211F, "color": 0xFFAAAAAA}, "ComboBox::choices": { "font_size": 12, "color": 0xFFAAAAAA, "background_color": 0xFF23211F, "secondary_color": 0xFF23211F, }, "ComboBox:hovered:choices": {"background_color": 0xFF33312F, "secondary_color": 0xFF33312F}, "Slider::value_less": { "font_size": 12, "color": 0x0, "border_radius": 5, "background_color": 0xFF23211F, "secondary_color": KIT_GREEN, "border_color": 0xFFAAFFFF, "border_width": 0, }, "Slider::value": { "font_size": 14, "color": 0xFFAAAAAA, "border_radius": 5, "background_color": 0xFF23211F, "secondary_color": KIT_GREEN, }, "Rectangle::add": {"background_color": 0xFF23211F}, "Rectangle:hovered:add": {"background_color": 0xFF73414F}, "CheckBox::greenCheck": {"font_size": 10, "background_color": KIT_GREEN, "color": 0xFF23211F}, "CheckBox::whiteCheck": {"font_size": 10, "background_color": 0xFFDDDDDD, "color": 0xFF23211F}, "Slider::colorField": {"background_color": 0xFF23211F, "font_size": 14, "color": 0xFF8A8777}, # Frame "CollapsableFrame::standard_collapsable": { "background_color": 0xFF343432, "secondary_color": 0xFF343432, "font_size": 16, "border_radius": 2.0, "border_color": 0x0, "border_width": 0, }, "CollapsableFrame:hovered:standard_collapsable": {"secondary_color": 0xFFFBF1E5}, "CollapsableFrame:pressed:standard_collapsable": {"secondary_color": 0xFFF7E4CC}, } CollapsableFrame_style = { "CollapsableFrame": { "background_color": 0xFF343432, "secondary_color": 0xFF343432, "color": 0xFFAAAAAA, "border_radius": 4.0, "border_color": 0x0, "border_width": 0, "font_size": 14, "padding": 0, }, "HStack::header": {"margin": 5}, "CollapsableFrame:hovered": {"secondary_color": 0xFF3A3A3A}, "CollapsableFrame:pressed": {"secondary_color": 0xFF343432}, } class AttributeEditorWindow: """ example of an Attribute Editor Window using Omni::UI """ def __init__(self): self._editor_window = None self._window_Frame = None def set_style_light(self, button): """ """ self._window_Frame.set_style(LIGHT_WINDOW_STYLE) def set_style_dark(self, button): """ """ self._window_Frame.set_style(DARK_WINDOW_STYLE) def shutdown(self): """Should be called when the extesion us unloaded""" # Unfortunatley, the member variables are not destroyed when the extension is unloaded. We need to do it # automatically. Usually, it's OK because the Python garbage collector will eventually destroy everythigng. But # we need the images to be destroyed right now because Kit know nothing about Python garbage collector and it # will fire warning that texture is not destroyed. self._editor_window = None def _create_object_selection_frame(self): with ui.Frame(): with ui.ZStack(): ui.Rectangle(name="frame_background") with ui.VStack(spacing=5, name="this", style={"VStack::this": {"margin": 5, "margin_width": 15}}): with ui.HStack(height=0): ui.StringField(name="models").model.set_value("(9 models selected)") with ui.VStack(width=0, height=0): ui.Spacer(width=0, height=3) ui.Image( "resources/glyphs/lock_open.svg", width=25, height=12, style={"color": KIT_GREEN, "marging_width": 5}, ) ui.Spacer(width=0) with ui.VStack(width=0, height=0): ui.Spacer(width=0, height=3) ui.Image("resources/glyphs/settings.svg", width=25, height=12, style={"color": KIT_GREEN}) ui.Spacer(width=0) with ui.HStack(height=0): with ui.ZStack(width=60): ui.Image(f"{ICON_PATH}/Add.svg", width=60, height=30) with ui.HStack(name="this", style={"HStack::this": {"margin_height": 0}}): ui.Spacer(width=15) ui.Label("Add", style={"font_size": 16, "color": 0xFFAAAAAA, "margin_width": 10}) ui.Spacer(width=50) with ui.ZStack(): ui.Rectangle(style={"background_color": 0xFF23211F, "border_radius": 4.0}) with ui.HStack(): with ui.VStack(width=0): ui.Spacer(width=0) ui.Image("resources/glyphs/sync.svg", width=25, height=12) ui.Spacer(width=0) ui.StringField(name="models").model.set_value("Search") def _create_control_state(self, state=0): control_type = [ f"{ICON_PATH}/Expression.svg", f"{ICON_PATH}/Mute Channel.svg", f"{ICON_PATH}/mixed properties.svg", f"{ICON_PATH}/Default value.svg", f"{ICON_PATH}/Changed value.svg", f"{ICON_PATH}/Animation Curve.svg", f"{ICON_PATH}/Animation Key.svg", ] if state == 0: ui.Circle(name="transform", width=20, radius=3.5, size_policy=ui.CircleSizePolicy.FIXED) else: with ui.VStack(width=0): ui.Spacer() ui.Image(control_type[state - 1], width=20, height=12) ui.Spacer() def _create_checkbox_control(self, name, value, label_width=100, line_width=ui.Fraction(1)): with ui.HStack(): ui.Label(name, name="label", width=0) ui.Spacer(width=10) ui.Line(style={"color": 0x338A8777}, width=line_width) ui.Spacer(width=5) with ui.VStack(width=10): ui.Spacer() ui.CheckBox(width=10, height=0, name="greenCheck").model.set_value(value) ui.Spacer() self._create_control_state(0) def _create_path_combo(self, name, paths): with ui.HStack(): ui.Label(name, name="label", width=LABEL_PADDING) with ui.ZStack(): ui.StringField(name="models").model.set_value(paths) with ui.HStack(): ui.Spacer() ui.Circle(width=10, height=20, style={"background_color": 0xFF555555}) ui.ComboBox(0, paths, paths, name="path", width=0, height=0, arrow_only=True) ui.Spacer(width=5) ui.Image("resources/icons/folder.png", width=15) ui.Spacer(width=5) ui.Image("resources/icons/find.png", width=15) self._create_control_state(2) def _build_transform_frame(self): # Transform Frame with ui.CollapsableFrame(title="Transform", style=CollapsableFrame_style): with ui.VStack(spacing=8, name="frame_v_stack"): ui.Spacer(height=0) components = ["Position", "Rotation", "Scale"] for component in components: with ui.HStack(): with ui.HStack(width=LABEL_PADDING): ui.Label(component, name="transform", width=50) self._create_control_state() ui.Spacer() # Field (X) all_axis = ["X", "Y", "Z"] colors = {"X": 0xFF5555AA, "Y": 0xFF76A371, "Z": 0xFFA07D4F} for axis in all_axis: with ui.HStack(): with ui.ZStack(width=15): ui.Rectangle( width=15, height=20, style={ "background_color": colors[axis], "border_radius": 3, "corner_flag": ui.CornerFlag.LEFT, }, ) ui.Label(axis, name="transform_label", alignment=ui.Alignment.CENTER) ui.FloatDrag(name="transform", min=-1000000, max=1000000, step=0.01) self._create_control_state(0) ui.Spacer(height=0) def _build_checked_header(self, collapsed, title): triangle_alignment = ui.Alignment.RIGHT_CENTER if not collapsed: triangle_alignment = ui.Alignment.CENTER_BOTTOM with ui.HStack(style={"HStack": {"margin_width": 15, "margin_height": 5}}): with ui.VStack(width=20): ui.Spacer() ui.Triangle( alignment=triangle_alignment, name="title", width=8, height=8, style={"background_color": 0xFFCCCCCC}, ) ui.Spacer() ui.Label(title, name="title", width=0) ui.Spacer() ui.CheckBox(width=10, name="whiteCheck").model.set_value(True) self._create_control_state() def _build_custom_callapsable_frame(self): with ui.CollapsableFrame( title="Light Property", style=CollapsableFrame_style, build_header_fn=self._build_checked_header ): with ui.VStack(spacing=12, name="frame_v_stack"): ui.Spacer(height=5) with ui.HStack(): ui.Label("Slider", name="label", width=LABEL_PADDING) ui.IntSlider(name="value_less", min=0, max=100, usingGauge=True).model.set_value(30) self._create_control_state() self._create_checkbox_control("Great UI", True) self._create_checkbox_control("Hard To Build", False) self._create_checkbox_control("Support very very very long checkbox label", True) ui.Spacer(height=0) def _build_dropdown_frame(self): with ui.Frame(): with ui.ZStack(): ui.Rectangle(name="frame_background") with ui.VStack(height=0, spacing=10, name="frame_v_stack"): ui.Spacer(height=5) for index in range(3): with ui.HStack(): ui.Label("Drop Down", name="label", width=LABEL_PADDING) ui.ComboBox(0, "Choice 1", "Choice 2", "Choice 3", height=10, name="choices") self._create_control_state() self._create_checkbox_control("Check Box", False) ui.Spacer(height=0) def _build_scale_and_bias_frame(self): with ui.CollapsableFrame(title="Scale And Bias Output", collapsed=False, style=CollapsableFrame_style): with ui.VStack(name="frame_v_stack"): with ui.HStack(): ui.Spacer(width=100) ui.Label("Scale", name="label", alignment=ui.Alignment.CENTER) ui.Spacer(width=10) ui.Label("Bias", name="label", alignment=ui.Alignment.CENTER) with ui.VStack(spacing=8): colors = ["Red", "Green", "Blue", "Alpha"] for color in colors: with ui.HStack(): ui.Label(color, name="label", width=LABEL_PADDING) ui.FloatSlider(name="value", min=0, max=2).model.set_value(1.0) self._create_control_state(6) ui.Spacer(width=20) ui.FloatSlider(name="value", min=-1.0, max=1.0).model.set_value(0.0) state = None if color == "Red": state = 2 elif color == "Blue": state = 5 else: state = 3 self._create_control_state(state) ui.Spacer(height=0) ui.Spacer(height=5) with ui.VStack(spacing=14): self._create_checkbox_control("Warp to Output Range", True) ui.Line(style={"color": KIT_GREEN}) self._create_checkbox_control("Border Color", True) self._create_checkbox_control("Zero Alpha Border", False) with ui.HStack(): self._create_checkbox_control("Cutout Alpha", False, label_width=20, line_width=20) self._create_checkbox_control("Scale Alpha For Mi Pmap Coverage", True) self._create_checkbox_control("Border Color", True) ui.Spacer(height=0) def _build_color_picker_frame(self): def color_drag(args): with ui.HStack(spacing=2): color_model = ui.MultiFloatDragField( args[0], args[1], args[2], width=200, h_spacing=5, name="colorField" ).model ui.ColorWidget(color_model, width=10, height=10) def color4_drag(args): with ui.HStack(spacing=2): color_model = ui.MultiFloatDragField( args[0], args[1], args[2], args[3], width=200, h_spacing=5, style={"color": 0xFFAAAAAA, "background_color": 0xFF000000, "draw_mode": ui.SliderDrawMode.HANDLE}, ).model ui.ColorWidget(color_model, width=10, height=10) with ui.CollapsableFrame(title="Color Controls", collapsed=False, style=CollapsableFrame_style): with ui.VStack(name="frame_v_stack"): with ui.VStack(spacing=8): colors = [("Red", [1.0, 0.0, 0.0]), ("Green", [0.0, 1.0, 0.0]), ("Blue", [0.0, 0.0, 1.0])] for color in colors: with ui.HStack(): ui.Label(color[0], name="label", width=LABEL_PADDING) if len(color[1]) == 4: color4_drag(color[1]) else: color_drag(color[1]) self._create_control_state(0) ui.Line(style={"color": 0x338A8777}) color = ("RGBA", [1.0, 0.0, 1.0, 0.5]) with ui.HStack(): ui.Label(color[0], name="label", width=LABEL_PADDING) color4_drag(color[1]) self._create_control_state(0) ui.Spacer(height=0) def _build_frame_with_radio_button(self): with ui.CollapsableFrame(title="Compression Quality", collapsed=False, style=CollapsableFrame_style): with ui.VStack(spacing=8, name="frame_v_stack"): ui.Spacer(height=5) with ui.HStack(): with ui.VStack(width=LABEL_PADDING): ui.Label(" Select One...", name="label", width=100, height=0) ui.Spacer(width=100) with ui.VStack(spacing=10): values = ["Faster", "Normal", "Production", "Highest"] for value in values: with ui.HStack(): with ui.ZStack(width=20): outer_style = { "border_width": 1, "border_color": KIT_GREEN, "background_color": 0x0, "border_radius": 2, } ui.Rectangle(width=12, height=12, style=outer_style) if value == "Faster": outer_style = {"background_color": KIT_GREEN, "border_radius": 2} with ui.Placer(offset_x=3, offset_y=3): ui.Rectangle(width=10, height=10, style=outer_style) ui.Label(value, name="label", aligment=ui.Alignment.LEFT) ui.Spacer(height=0) def build_window(self): """ build the window for the Class""" self._editor_window = ui.Window("Attribute Editor", width=450, height=800) self._editor_window.deferred_dock_in("Layers") self._editor_window.setPosition(0, 0) self._editor_window.frame.set_style(DARK_WINDOW_STYLE) with self._editor_window.frame: with ui.VStack(): with ui.HStack(height=20): ui.Label("Styling : ", alignment=ui.Alignment.RIGHT_CENTER) ui.Button("Light Mode", clicked_fn=lambda b=None: self.set_style_light(b)) ui.Button("Dark Mode", clicked_fn=lambda b=None: self.set_style_dark(b)) ui.Spacer() ui.Spacer(height=10) self._window_Frame = ui.ScrollingFrame( name="canvas", horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, ) with self._window_Frame: with ui.VStack(height=0, name="main_v_stack", spacing=6): # create object selection Frame self._create_object_selection_frame() # create build transform Frame self._build_transform_frame() # DropDown Frame self._build_dropdown_frame() # Custom Collapsable Frame self._build_custom_callapsable_frame() # Custom Collapsable Frame with ui.CollapsableFrame(title="Files", style=CollapsableFrame_style): with ui.VStack(spacing=10, name="frame_v_stack"): ui.Spacer(height=0) self._create_path_combo("UI Path", "omni:/Project/Cool_ui.usd") self._create_path_combo("Texture Path", "omni:/Project/cool_texture.png") ui.Spacer(height=0) # Custom Collapsable Frame with ui.CollapsableFrame(title="Images Options", collapsed=True, style=CollapsableFrame_style): with ui.VStack(spacing=10, name="frame_v_stack"): self._create_path_combo("Images Path", "omni:/Library/Images/") ui.Spacer(height=0) # Custom Collapsable Frame self._build_frame_with_radio_button() # Scale And Bias self._build_scale_and_bias_frame() # Color Pickrs self._build_color_picker_frame() return self._editor_window
23,430
Python
45.582505
119
0.509902
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/progressbar_doc.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. # """The documentation for ProgressBar""" from omni import ui from omni.ui import color as cl from .doc_page import DocPage SPACING = 5 class CustomProgressValueModel(ui.AbstractValueModel): """An example of custom float model that can be used for progress bar""" def __init__(self, value: float): super().__init__() self._value = value def set_value(self, value): """Reimplemented set""" try: value = float(value) except ValueError: value = None if value != self._value: # Tell the widget that the model is changed self._value = value self._value_changed() def get_value_as_float(self): return self._value def get_value_as_string(self): return "Custom Overlay" class ProgressBarDoc(DocPage): """ document for ProgressBar""" def create_doc(self, navigate_to=None): self._section_title("ProgressBar") self._text("A progressbar is widget that indicates the progress of an operation.") self._text("In the following example, it shows how to use progress bar and override the overlay text.") with ui.VStack(spacing=SPACING): # Create progressbars first = ui.ProgressBar() # Range is [0.0, 1.0] first.model.set_value(0.5) second = ui.ProgressBar() second.model.set_value(1.0) # Overrides the overlay of progressbar model = CustomProgressValueModel(0.8) third = ui.ProgressBar(model) third.model.set_value(0.1) # Styling its color fourth = ui.ProgressBar(style={"color": cl("#0000DD")}) fourth.model.set_value(0.3) # Styling its border width ui.ProgressBar(style={"border_width": 2, "color": cl("#0000DD")}).model.set_value(0.7) # Styling its border radius ui.ProgressBar(style={"border_radius": 100, "color": cl("#0000DD")}).model.set_value(0.6) # Styling its background color ui.ProgressBar(style={"border_radius": 100, "background_color": cl("#0000DD")}).model.set_value(0.6) # Styling the text color ui.ProgressBar(style={"border_radius": 100, "secondary_color": cl("#00DDDD")}).model.set_value(0.6) # Two progress bars in a row with padding with ui.HStack(): ui.ProgressBar(style={"color": cl("#0000DD"), "padding": 100}).model.set_value(1.0) ui.ProgressBar().model.set_value(0.0) self._code( """ # Create progressbars first = ui.ProgressBar() # Range is [0.0, 1.0] first.model.set_value(0.5) second = ui.ProgressBar() second.model.set_value(1.0) # Overrides the overlay of progressbar model = CustomProgressValueModel(0.8) third = ui.ProgressBar(model) third.model.set_value(0.1) # Styling its color fourth = ui.ProgressBar(style={"color": cl("#0000DD")}) fourth.model.set_value(0.3) # Styling its border width ui.ProgressBar(style={"border_width": 2, "color": cl("#0000DD")}).model.set_value(0.7) # Styling its border radius ui.ProgressBar(style={"border_radius": 100, "color": cl("#0000DD")}).model.set_value(0.6) # Styling its background color ui.ProgressBar(style={"border_radius": 100, "background_color": cl("#0000DD")}).model.set_value(0.6) # Styling the text color ui.ProgressBar(style={"border_radius": 100, "secondary_color": cl("#00DDDD")}).model.set_value(0.6) # Two progress bars in a row with padding with ui.HStack(): ui.ProgressBar(style={"color": cl("#0000DD"), "padding": 100}).model.set_value(1.0) ui.ProgressBar().model.set_value(0.0) """ ) ui.Spacer(height=10)
4,492
Python
34.377952
112
0.592164
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/menu_doc.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. # """The documentation for Menu""" from omni import ui from .doc_page import DocPage class MenuDoc(DocPage): """ document for Menu""" def __init__(self, extension_path): super().__init__(extension_path) self._context_menu = ui.Menu( "Context menu", name="this", style={ "Menu": {"background_color": 0xFFAA0000, "color": 0xFFFFFFFF, "background_selected_color": 0xFF00AA00}, "MenuItem": {"color": 0xFFFFFFFF, "background_selected_color": 0xFF00AA00}, "Separator": {"color": 0xFFFFFFFF}, }, ) self._pushed_menu = ui.Menu( "Pushed menu", style={ "Menu": {"background_color": 0xFF000000, "color": 0xFFFFFFFF, "background_selected_color": 0xFFAAAAAA}, "MenuItem": {"color": 0xFFFFFFFF, "background_selected_color": 0xFFAAAAAA}, }, ) def _show_context_menu(self, x, y, button, modifier): """The context menu example""" # Display context menu only if the right button is pressed if button != 1: return # Reset the previous context popup self._context_menu.clear() with self._context_menu: ui.MenuItem("Delete Shot") ui.Separator() ui.MenuItem("Attach Selected Camera") with ui.Menu("Sub-menu"): ui.MenuItem("One") ui.MenuItem("Two") ui.MenuItem("Three") ui.Separator() ui.MenuItem("Four") with ui.Menu("Five"): ui.MenuItem("Six") ui.MenuItem("Seven") # Show it self._context_menu.show() def _show_pushed_menu(self, x, y, button, modifier, widget): """The Pushed menu example""" # Display context menu only if the left mouse button is pressed if button != 0: return # Reset the previous context popup self._pushed_menu.clear() with self._pushed_menu: ui.MenuItem("Camera 1") ui.MenuItem("Camera 2") ui.MenuItem("Camera 3") ui.Separator() with ui.Menu("More Cameras"): ui.MenuItem("This Menu is Pushed") ui.MenuItem("and Aligned with a widget") # Show it self._pushed_menu.show_at( (int)(widget.screen_position_x), (int)(widget.screen_position_y + widget.computed_content_height) ) def create_doc(self, navigate_to=None): self._section_title("Menu") self._text( "The Menu class provides a menu widget for use in menu bars, context menus, and other popup menus. It can " "be either a pull-down menu in a menu bar or a standalone context menu. Pull-down menus are shown by the " "menu bar when the user clicks on the respective item. Context menus are usually invoked by some special " "keyboard key or by right-clicking." ) with ui.HStack(style=self._style_system): ui.Button("Right click to context menu", width=0, mouse_pressed_fn=self._show_context_menu) self._code( """ def _on_startup(self): .... with ui.HStack(style=style_system): ui.Button( "Right click to context menu", width=0, mouse_pressed_fn=self._show_context_menu ) .... def _show_context_menu(self, x, y, button, modifier): # Display context menu only if the right button is pressed if button != 1: return # Reset the previous context popup self._context_menu.clear() with self._context_menu: with ui.Menu("Sub-menu"): ui.MenuItem("One") ui.MenuItem("Two") ui.MenuItem("Three") ui.MenuItem("Four") with ui.Menu("Five"): ui.MenuItem("Six") ui.MenuItem("Seven") ui.MenuItem("Delete Shot") ui.MenuItem("Attach Selected Camera") """ ) with ui.HStack(style=self._style_system): bt = ui.Button("Pushed Button Menu", width=0, style={"background_color": 0xFF000000, "color": 0xFFFFFFFF}) bt.set_mouse_pressed_fn(lambda x, y, b, m, widget=bt: self._show_pushed_menu(x, y, b, m, widget)) ui.Spacer(height=100)
5,068
Python
36
119
0.547948
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/md_doc.py
# Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .doc_page import DocPage from omni.kit.documentation.builder import DocumentationBuilderMd from omni.kit.documentation.builder import DocumentationBuilderPage class MdDoc(DocPage): def __init__(self, extension_path, md: DocumentationBuilderMd): super().__init__(extension_path) self.__md = md self.__page = None def clean(self): """Should be called when the extesion us unloaded or reloaded""" if self.__page: self.__page.destroy() self.__page = None def create_doc(self, navigate_to=None): """Issue the UI""" self.__page = DocumentationBuilderPage(self.__md, navigate_to)
1,108
Python
35.966665
76
0.710289
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/abstract_model_doc.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. # """The documentation for Abstract Model """ from omni import ui from pxr import UsdGeom import omni.kit.commands import omni.usd from .doc_page import DocPage SPACING = 5 class VisibilityWatchModel(ui.AbstractValueModel): """The value model that is reimplemented in Python to watch the visibility of the selection""" def __init__(self): super(VisibilityWatchModel, self).__init__() self._usd_context = omni.usd.get_context() self._selection = None self._events = None self._stage_event_sub = None if self._usd_context is not None: self._selection = self._usd_context.get_selection() self._events = self._usd_context.get_stage_event_stream() self._stage_event_sub = self._events.create_subscription_to_pop( self._on_stage_event, name="omni.example.ui abstract model stage update" ) self.prim = None def clean(self): """Should be called when the extesion us unloaded or reloaded""" self._usd_context = None self._selection = None self._events = None self._stage_event_sub = None self.prim = None def _on_stage_event(self, event): if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): self._on_selection_changed() def _on_selection_changed(self): selection = self._selection.get_selected_prim_paths() stage = self._usd_context.get_stage() # When TC runs tests, it's possible that stage is None if selection and stage: self.prim = stage.GetPrimAtPath(selection[0]) # Say to the widgets that the model value is changed self._value_changed() def get_value_as_bool(self): """Reimplemented get bool""" if self.prim: if self.prim.HasAttribute(UsdGeom.Tokens.visibility): attribute = self.prim.GetAttribute(UsdGeom.Tokens.visibility) if attribute: return attribute.Get() == UsdGeom.Tokens.inherited def set_value(self, value): """Reimplemented set bool""" if self.prim: omni.kit.commands.execute("ToggleVisibilitySelectedPrims", selected_paths=[self.prim.GetPath()]) # Say to the widgets that the model value is changed self._value_changed() class AbstractModelDoc(DocPage): """ document for CheckBox""" def __init__(self, extension_path): super().__init__(extension_path) self._visibility_model = VisibilityWatchModel() def clean(self): """Should be called when the extesion us unloaded or reloaded""" # Unfortunatley, the member variables are not destroyed when the extension is unloaded. We need to do it # automatically. Usually, it's OK because the Python garbage collector will eventually destroy everythigng. But # we need the images to be destroyed right now because Kit know nothing about Python garbage collector and it # will fire warning that texture is not destroyed. if self._visibility_model: self._visibility_model.clean() self._visibility_model = None def create_doc(self, navigate_to=None): self._section_title("AbstractValueModel") self._text( "The AbstractValueModel class provides an abstract interface for the model that holds a single value. It's " "a central component of the model-delegate-view pattern used in many widgets like CheckBox, StringField(TODO), " "Slider(TODO), RadioBox(TODO). It's a dynamic data structure independent of the widget implementation. And " "it holds the data, logic, and rules of the widgets and defines the standard interface that widgets must " "use to be able to interoperate with the data model. It is not supposed to be instantiated directly. " "Instead, the user should subclass it to create new models." ) self._text( "In the next example, AbstractValueModel class is reimplemented to provide control over the visibility of " "the selected object." ) with ui.HStack(width=0, spacing=SPACING): ui.CheckBox(self._visibility_model) self._text("Visibility of Selected Prim") self._code( """ class VisibilityWatchModel(ui.AbstractValueModel): ''' The value model that is reimplemented in Python to watch the visibility of the selection. ''' def __init__(self): super(VisibilityWatchModel, self).__init__() self._usd_context = omni.usd.get_context() self._selection = self._usd_context.get_selection() self._events = self._usd_context.get_stage_event_stream() self._stage_event_sub = \\ self._events.create_subscription_to_pop( self._on_stage_event, name="omni.example.ui visibilitywatch stage update") self.prim = None def _on_stage_event(self, event): if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): self._on_selection_changed() def _on_selection_changed(self): selection = self._selection.get_selected_prim_paths() stage = self._usd_context.get_stage() if selection and stage: self.prim = stage.GetPrimAtPath(selection[0]) # Say to the widgets that the model value is changed self._value_changed() def get_value_as_bool(self): '''Reimplemented get bool''' if self.prim: attribute = \\ UsdGeom.Imageable(self.prim).GetVisibilityAttr() inherited = \\ attribute.Get() == UsdGeom.Tokens.inherited return inherited if attribute else False def set_value(self, value): '''Reimplemented set bool''' if self.prim: omni.kit.commands.execute( "ToggleVisibilitySelectedPrims", selected_paths=[self.prim.GetPath()]) # Say to the widgets that the model value is changed self._value_changed() """ ) ui.Spacer(height=10)
6,940
Python
41.32317
124
0.610375
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/field_doc.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. # """The documentation for Field """ from .doc_page import DocPage from omni import ui import inspect SPACING = 5 def field_callbacks(): def on_value(label): label.text = "Value is changed" def on_begin(label): label.text = "Editing is started" def on_end(label): label.text = "Editing is finished" label = ui.Label("Nothing happened", name="text") model = ui.StringField().model model.add_value_changed_fn(lambda m, l=label: on_value(l)) model.add_begin_edit_fn(lambda m, l=label: on_begin(l)) model.add_end_edit_fn(lambda m, l=label: on_end(l)) def multiline_field(): initial_text = inspect.getsource(field_callbacks) model = ui.SimpleStringModel(initial_text) field = ui.StringField(model, multiline=True) class FieldDoc(DocPage): """ document for Field""" def create_doc(self, navigate_to=None): self._section_title("Field") self._caption("StringField", navigate_to) self._text( "The StringField widget is a one-line text editor. A field allows the user to enter and edit a single line " "of plain text. It's implemented using the model-delegate-view pattern and uses AbstractValueModel as the central " "component of the system." ) self._text("The following example demonstrates the way how to connect a StringField and a Label.") field_style = { "Field": { "background_color": 0xFFFFFFFF, "background_selected_color": 0xFFD77800, "border_color": 0xFF444444, "border_radius": 1, "border_width": 0.5, "color": 0xFF444444, "font_size": 16.0, }, "Field:hovered": {"border_color": 0xFF000000}, "Field:pressed": {"background_color": 0xFFFFFFFF, "border_color": 0xFF995400, "border_width": 0.75}, } def setText(label, text): """Sets text on the label""" # This function exists because lambda cannot contain assignment label.text = f"You wrote '{text}'" with ui.HStack(): field = ui.StringField(style=field_style) ui.Spacer(width=SPACING) label = ui.Label("", name="text") field.model.add_value_changed_fn(lambda m, label=label: setText(label, m.get_value_as_string())) self._code( """ def setText(label, text): '''Sets text on the label''' # This function exists because lambda cannot contain assignment label.text = f"You wrote '{text}'" with ui.HStack(): field = ui.StringField(style=field_style) label = ui.Label("") field.model.add_value_changed_fn( lambda m, label=label: setText(label, m.get_value_as_string())) """ ) self._text( "The following example demonstrates that the model decides the content of the field. The field can have " "only one of two options, either 'True' or 'False' because the model supports only those two possibilities." ) with ui.HStack(): checkbox = ui.CheckBox(width=0) field = ui.StringField() field.model = checkbox.model self._code( """ with ui.HStack(): checkbox = ui.CheckBox(width=0) field = ui.StringField() field.model = checkbox.model """ ) self._text( "In this example, the field can have anything because the model accepts any string, but the model returns " "bool for checkbox, and the checkbox is off when the string is empty or 'False'." ) with ui.HStack(): checkbox = ui.CheckBox(width=0) field = ui.StringField() checkbox.model = field.model self._code( """ with ui.HStack(): checkbox = ui.CheckBox(width=0) field = ui.StringField() checkbox.model = field.model """ ) self._caption("FloatField and IntField", navigate_to) self._text( "There are fields for string, float and int models. The following example shows how they interact with " "each other:" ) self._text("All three fields share the same SimpleFloatModel:") with ui.HStack(): self._text("FloatField") self._text("IntField") self._text("StringField") with ui.HStack(): left = ui.FloatField() center = ui.IntField() right = ui.StringField() center.model = left.model right.model = left.model self._text("All three fields share the same SimpleIntModel:") with ui.HStack(): self._text("FloatField") self._text("IntField") self._text("StringField") with ui.HStack(): left = ui.FloatField() center = ui.IntField() right = ui.StringField() left.model = center.model right.model = center.model self._text("All three fields share the same SimpleStringModel:") with ui.HStack(): self._text("FloatField") self._text("IntField") self._text("StringField") with ui.HStack(): left = ui.FloatField() center = ui.IntField() right = ui.StringField() left.model = right.model center.model = right.model self._text( "The widget doesn't keep the data due to the model-delegate-view pattern. However, there are two ways to track the " "state of the widget. It's possible to reimplement AbstractValueModel, for details see the chapter " "`AbstractValueModel`. The second way is using the callbacks of the model. This is a minimal example " "of callbacks." ) field_callbacks() self._code(inspect.getsource(field_callbacks).split("\n", 1)[-1]) self._caption("Multiline StringField", navigate_to) self._text( "Property `multiline` of `StringField` allows to press enter and create a new line. It's possible to " "finish editing with Ctrl-Enter." ) with ui.Frame(style=field_style, height=300): multiline_field() self._code(inspect.getsource(multiline_field).split("\n", 1)[-1]) ui.Spacer(height=10)
7,030
Python
34.155
128
0.582077
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/multifield_doc.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. # """The documentation for Shapes""" from omni import ui from .doc_page import DocPage import inspect import omni.usd from .colorwidget_doc import USDColorModel SPACING = 5 def simplest_field(): ui.MultiIntField(0, 0, 0, 0) def simplest_drag(): ui.MultiFloatDragField(0.0, 0.0, 0.0, 0.0) def matrix_field(): args = [1.0 if i % 5 == 0 else 0.0 for i in range(16)] ui.MultiFloatField(*args, width=ui.Percent(50), h_spacing=5, v_spacing=2) def usd_field(): with ui.HStack(spacing=SPACING): model = USDColorModel() ui.ColorWidget(model, width=0) ui.MultiFloatField(model) def usd_drag(): with ui.HStack(spacing=SPACING): model = USDColorModel() ui.ColorWidget(model, width=0) ui.MultiFloatDragField(model, min=0.0, max=2.0) class MultiFieldDoc(DocPage): """Document for MultiField""" def create_doc(self, navigate_to=None): """Descriptions for MultiField""" self._section_title("MultiField") self._text( "MultiField widget groups are the widgets that have multiple similar widgets to represent each item in the " "model. It's handy to use them for arrays and multi-component data like float3, matrix, and color." ) simplest_field() self._code(inspect.getsource(simplest_field).split("\n", 1)[-1]) simplest_drag() self._code(inspect.getsource(simplest_drag).split("\n", 1)[-1]) matrix_field() self._code(inspect.getsource(matrix_field).split("\n", 1)[-1]) # TODO omni.ui: restore functionality for Kit Next if False: usd_field() self._code(inspect.getsource(usd_field).split("\n", 1)[-1]) usd_drag() self._code(inspect.getsource(usd_drag).split("\n", 1)[-1])
2,255
Python
28.68421
120
0.659867
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/colorwidget_doc.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. # """The documentation for ColorWidget""" from .doc_page import DocPage from omni import ui from pxr import Gf from pxr import UsdGeom from typing import Any import inspect import omni.kit.commands import omni.usd import weakref SPACING = 5 class SetDisplayColorCommand(omni.kit.commands.Command): """ Change prim display color undoable **Command**. Unlike ChangePropertyCommand, it can undo property creation. Args: gprim (Gprim): Prim to change display color on. value: Value to change to. value: Value to undo to. """ def __init__(self, gprim: UsdGeom.Gprim, color: Any, prev: Any): self._gprim = gprim self._color = color self._prev = prev def do(self): color_attr = self._gprim.CreateDisplayColorAttr() color_attr.Set([self._color]) def undo(self): color_attr = self._gprim.GetDisplayColorAttr() if self._prev is None: color_attr.Clear() else: color_attr.Set([self._prev]) class FloatModel(ui.SimpleFloatModel): def __init__(self, parent): super().__init__() self._parent = weakref.ref(parent) def begin_edit(self): parent = self._parent() parent.begin_edit(None) def end_edit(self): parent = self._parent() parent.end_edit(None) class USDColorItem(ui.AbstractItem): def __init__(self, model): super().__init__() self.model = model class USDColorModel(ui.AbstractItemModel): def __init__(self): super().__init__() # Create root model self._root_model = ui.SimpleIntModel() self._root_model.add_value_changed_fn(lambda a: self._item_changed(None)) # Create three models per component self._items = [USDColorItem(FloatModel(self)) for i in range(3)] for item in self._items: item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item)) # Omniverse contexts self._usd_context = omni.usd.get_context() self._selection = self._usd_context.get_selection() self._events = self._usd_context.get_stage_event_stream() self._stage_event_sub = self._events.create_subscription_to_pop( self._on_stage_event, name="omni.example.ui colorwidget stage update" ) # Privates self._subscription = None self._gprim = None self._prev_color = None self._edit_mode_counter = 0 def _on_stage_event(self, event): """Called with subscription to pop""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): self._on_selection_changed() def _on_selection_changed(self): """Called when the user changes the selection""" selection = self._selection.get_selected_prim_paths() stage = self._usd_context.get_stage() self._subscription = None self._gprim = None # When TC runs tests, it's possible that stage is None if selection and stage: self._gprim = UsdGeom.Gprim.Get(stage, selection[0]) if self._gprim: color_attr = self._gprim.GetDisplayColorAttr() usd_watcher = omni.usd.get_watcher() self._subscription = usd_watcher.subscribe_to_change_info_path( color_attr.GetPath(), self._on_usd_changed ) # Change the widget color self._on_usd_changed() def _on_value_changed(self, item): """Called when the submodel is chaged""" if not self._gprim: return if self._edit_mode_counter > 0: # Change USD only if we are in the edit mode. color_attr = self._gprim.CreateDisplayColorAttr() color = Gf.Vec3f( self._items[0].model.get_value_as_float(), self._items[1].model.get_value_as_float(), self._items[2].model.get_value_as_float(), ) color_attr.Set([color]) self._item_changed(item) def _on_usd_changed(self, path=None): """Called with UsdWatcher when something in USD is changed""" color = self._get_current_color() or Gf.Vec3f(0.0) for i in range(len(self._items)): self._items[i].model.set_value(color[i]) def _get_current_color(self): """Returns color of the current object""" if self._gprim: color_attr = self._gprim.GetDisplayColorAttr() if color_attr: color_array = color_attr.Get() if color_array: return color_array[0] def get_item_children(self, item): """Reimplemented from the base class""" return self._items def get_item_value_model(self, item, column_id): """Reimplemented from the base class""" if item is None: return self._root_model return item.model def begin_edit(self, item): """ Reimplemented from the base class. Called when the user starts editing. """ if self._edit_mode_counter == 0: self._prev_color = self._get_current_color() self._edit_mode_counter += 1 def end_edit(self, item): """ Reimplemented from the base class. Called when the user finishes editing. """ self._edit_mode_counter -= 1 if not self._gprim or self._edit_mode_counter > 0: return color = Gf.Vec3f( self._items[0].model.get_value_as_float(), self._items[1].model.get_value_as_float(), self._items[2].model.get_value_as_float(), ) omni.kit.commands.execute("SetDisplayColor", gprim=self._gprim, color=color, prev=self._prev_color) def color_field(): with ui.HStack(spacing=SPACING): color_model = ui.ColorWidget(width=0, height=0).model for item in color_model.get_item_children(): component = color_model.get_item_value_model(item) ui.FloatField(component) def color_drag(): with ui.HStack(spacing=SPACING): color_model = ui.ColorWidget(0.125, 0.25, 0.5, width=0, height=0).model for item in color_model.get_item_children(): component = color_model.get_item_value_model(item) ui.FloatDrag(component) def color_combo(): with ui.HStack(spacing=SPACING): color_model = ui.ColorWidget(width=0, height=0).model ui.ComboBox(color_model) def two_usd_color_boxes(): with ui.HStack(spacing=SPACING): ui.ColorWidget(USDColorModel(), width=0) ui.Label("First ColorWidget", name="text") with ui.HStack(spacing=SPACING): ui.ColorWidget(USDColorModel(), width=0) ui.Label("Second ColorWidget has independed model", name="text") class ColorWidgetDoc(DocPage): """Document for ColorWidget""" def create_doc(self, navigate_to=None): self._section_title("ColorWidget") self._text( "The ColorWidget widget is a button that displays the color from the item model and can open a picker " "window. The color dialog's function is to allow users to choose colors." ) self._text("Fields connected to the color model") color_field() self._code(inspect.getsource(color_field).split("\n", 1)[-1]) self._text("Drags connected to the color model") color_drag() self._code(inspect.getsource(color_drag).split("\n", 1)[-1]) self._text("ComboBox connected to the color model.") color_combo() self._code(inspect.getsource(color_combo).split("\n", 1)[-1]) # TODO omni.ui: restore functionality for Kit Next if False: self._text("Two different models that watch USD Stage. Undo/Redo example.") two_usd_color_boxes() with ui.ScrollingFrame(height=250, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON): self._code( inspect.getsource(FloatModel) + "\n" + inspect.getsource(USDColorItem) + "\n" + inspect.getsource(USDColorModel) + "\n" + inspect.getsource(two_usd_color_boxes) ) ui.Spacer(height=20)
8,824
Python
31.806691
115
0.600748
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/widget_doc.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. # """The documentation for Widget""" from .doc_page import DocPage from omni import ui from omni.ui import color as cl from pathlib import Path import inspect import random SPACING = 5 def tooltip_fixed_position(): ui.Button("Fixed-position Tooltip", width=200, tooltip="Hello World", tooltip_offset_y=22) def tooltip_random_position(): button = ui.Button("Random-position Tooltip", width=200, tooltip_offset_y=22) def create_tooltip(button=button): button.tooltip_offset_x = random.randint(0, 200) ui.Label("Hello World") button.set_tooltip_fn(create_tooltip) def image_button(): style = { "Button": {"stack_direction": ui.Direction.TOP_TO_BOTTOM}, "Button.Image": { "color": cl("#99CCFF"), "image_url": "resources/icons/Learn_128.png", "alignment": ui.Alignment.CENTER, }, "Button.Label": {"alignment": ui.Alignment.CENTER}, } def direction(model, button, style=style): value = model.get_item_value_model().get_value_as_int() direction = ( ui.Direction.TOP_TO_BOTTOM, ui.Direction.BOTTOM_TO_TOP, ui.Direction.LEFT_TO_RIGHT, ui.Direction.RIGHT_TO_LEFT, ui.Direction.BACK_TO_FRONT, ui.Direction.FRONT_TO_BACK, )[value] style["Button"]["stack_direction"] = direction button.set_style(style) def align(model, button, image, style=style): value = model.get_item_value_model().get_value_as_int() alignment = ( ui.Alignment.LEFT_TOP, ui.Alignment.LEFT_CENTER, ui.Alignment.LEFT_BOTTOM, ui.Alignment.CENTER_TOP, ui.Alignment.CENTER, ui.Alignment.CENTER_BOTTOM, ui.Alignment.RIGHT_TOP, ui.Alignment.RIGHT_CENTER, ui.Alignment.RIGHT_BOTTOM, )[value] if image: style["Button.Image"]["alignment"] = alignment else: style["Button.Label"]["alignment"] = alignment button.set_style(style) def layout(model, button, padding, style=style): padding = "padding" if padding else "margin" style["Button"][padding] = model.get_value_as_float() button.set_style(style) def spacing(model, button): button.spacing = model.get_value_as_float() button = ui.Button("Label", style=style, width=64, height=64) with ui.HStack(width=ui.Percent(50)): ui.Label('"Button": {"stack_direction"}', name="text") options = ( 0, "TOP_TO_BOTTOM", "BOTTOM_TO_TOP", "LEFT_TO_RIGHT", "RIGHT_TO_LEFT", "BACK_TO_FRONT", "FRONT_TO_BACK", ) model = ui.ComboBox(*options).model model.add_item_changed_fn(lambda m, i, b=button: direction(m, b)) alignment = ( 4, "LEFT_TOP", "LEFT_CENTER", "LEFT_BOTTOM", "CENTER_TOP", "CENTER", "CENTER_BOTTOM", "RIGHT_TOP", "RIGHT_CENTER", "RIGHT_BOTTOM", ) with ui.HStack(width=ui.Percent(50)): ui.Label('"Button.Image": {"alignment"}', name="text") model = ui.ComboBox(*alignment).model model.add_item_changed_fn(lambda m, i, b=button: align(m, b, 1)) with ui.HStack(width=ui.Percent(50)): ui.Label('"Button.Label": {"alignment"}', name="text") model = ui.ComboBox(*alignment).model model.add_item_changed_fn(lambda m, i, b=button: align(m, b, 0)) with ui.HStack(width=ui.Percent(50)): ui.Label("padding", name="text") model = ui.FloatSlider(min=0, max=500).model model.add_value_changed_fn(lambda m, b=button: layout(m, b, 1)) with ui.HStack(width=ui.Percent(50)): ui.Label("margin", name="text") model = ui.FloatSlider(min=0, max=500).model model.add_value_changed_fn(lambda m, b=button: layout(m, b, 0)) with ui.HStack(width=ui.Percent(50)): ui.Label("Button.spacing", name="text") model = ui.FloatSlider(min=0, max=50).model model.add_value_changed_fn(lambda m, b=button: spacing(m, b)) class WidgetDoc(DocPage): """ document for Widget""" def radio_button(self): style = { "": {"background_color": cl.transparent, "image_url": f"{self._extension_path}/icons/radio_off.svg"}, ":checked": {"image_url": f"{self._extension_path}/icons/radio_on.svg"}, } collection = ui.RadioCollection() for i in range(5): with ui.HStack(style=style): ui.RadioButton(radio_collection=collection, width=30, height=30) ui.Label(f"Option {i}", name="text") ui.IntSlider(collection.model, min=0, max=4) def create_doc(self, navigate_to=None): self._section_title("Widgets") self._text( "The widget provides all the base functionality for most ui elements" "There is a lot of default feature " ) self._caption("Button", navigate_to) self._text( "The Button widget provides a command button. The command button, is perhaps the most commonly used widget " "in any graphical user interface. Click a button to execute a command. It is rectangular and typically " "displays a text label describing its action." ) def make_longer_text(button): """Set the text of the button longer""" button.text = "Longer " + button.text def make_shorter_text(button): """Set the text of the button shorter""" splitted = button.text.split(" ", 1) button.text = splitted[1] if len(splitted) > 1 else splitted[0] with ui.HStack(style=self._style_system): btn_with_text = ui.Button("Text", width=0) ui.Button("Press me", width=0, clicked_fn=lambda b=btn_with_text: make_longer_text(b)) btn_with_text.set_clicked_fn(lambda b=btn_with_text: make_shorter_text(b)) self._code( """ def make_longer_text(button): '''Set the text of the button longer''' button.text = "Longer " + button.text def make_shorter_text(button): '''Set the text of the button shorter''' splitted = button.text.split(" ", 1) button.text = \\ splitted[1] if len(splitted) > 1 else splitted[0] with ui.HStack(style=style_system): btn_with_text = ui.Button("Text", width=0) ui.Button( "Press me", width=0, clicked_fn=lambda b=btn_with_text: make_longer_text(b) ) btn_with_text.set_clicked_fn( lambda b=btn_with_text: make_shorter_text(b)) """ ) image_button() self._code(inspect.getsource(image_button).split("\n", 1)[-1]) self._caption("RadioButton", navigate_to) self._text( "RadioButton is the widget that allows the user to choose only one of a predefined set of mutually " "exclusive options." ) self._text( "RadioButtons are arranged in collections of two or more with the class RadioGroup, which is the central " "component of the system and controls the behavior of all the RadioButtons in the collection." ) self.radio_button() self._code(inspect.getsource(self.radio_button).split("\n", 1)[-1]) self._caption("Label", navigate_to) self._text( "Labels are used everywhere in omni.ui. They are text-only objects, and don't have a background color" "But you can control the color, font_size and alignment in the styling." ) self._exec_code( """ ui.Label("this is a simple label", style={"color": cl.black}) """ ) self._exec_code( """ ui.Label("label with aligment", style={"color": cl.black}, alignment=ui.Alignment.CENTER) """ ) self._exec_code( """ label_style = {"Label": {"font_size": 16, "color": cl.blue, "alignment":ui.Alignment.RIGHT }} ui.Label("Label with style", style=label_style) """ ) self._exec_code( """ ui.Label( "Label can be elided: Lorem ipsum dolor " "sit amet, consectetur adipiscing elit, sed do " "eiusmod tempor incididunt ut labore et dolore " "magna aliqua. Ut enim ad minim veniam, quis " "nostrud exercitation ullamco laboris nisi ut " "aliquip ex ea commodo consequat. Duis aute irure " "dolor in reprehenderit in voluptate velit esse " "cillum dolore eu fugiat nulla pariatur. Excepteur " "sint occaecat cupidatat non proident, sunt in " "culpa qui officia deserunt mollit anim id est " "laborum.", style={"color":cl.black}, elided_text=True, ) """ ) self._caption("Tooltip", navigate_to) self._text( "All Widget can be augmented with a tooltip, it can take 2 forms, either a simple ui.Label or a callback" "when using the callback, tooltip_fn= or widget.set_tooltip_fn() you can create virtually any widget for " "the tooltip" ) self._exec_code( """ tooltip_style = { "Tooltip": {"background_color": cl("#DDDD00"), "color": cl("#333333"), "margin_width": 3 , "margin_height": 2 , "border_width":3, "border_color": cl.red }} ui.Button("Simple Label Tooltip", name="tooltip", width=200, tooltip=" I am a text ToolTip ", style=tooltip_style) """ ) self._exec_code( """ def create_tooltip(): with ui.VStack(width=200, style=tooltip_style): with ui.HStack(): ui.Label("Fancy tooltip", width=150) ui.IntField().model.set_value(12) ui.Line(height=2, style={"color": cl.white}) with ui.HStack(): ui.Label("Anything is possible", width=150) ui.StringField().model.set_value("you bet") image_source = "resources/desktop-icons/omniverse_512.png" ui.Image( image_source, width=200, height=200, alignment=ui.Alignment.CENTER, style={"margin": 0}, ) tooltip_style = { "Tooltip": {"background_color": cl("#444444"), "border_width":2, "border_radius":5}, } ui.Button("Callback function Tooltip", width=200, style=tooltip_style, tooltip_fn=create_tooltip) """ ) tooltip_fixed_position() self._code(inspect.getsource(tooltip_fixed_position).split("\n", 1)[-1]) tooltip_random_position() self._code(inspect.getsource(tooltip_random_position).split("\n", 1)[-1]) ui.Spacer(height=50) self._caption("Debug Color", navigate_to) self._text("All Widget can be styled to use a debug color that enable you to visualize their frame") self._exec_code( """ style = {"background_color": cl("#DDDD00"), "color": cl("#333333"), "debug_color": cl("#FF000022") } ui.Label("Label with Debug", width=200, style=style) """ ) self._exec_code( """ style = {":hovered": {"debug_color": cl("#00FFFF22") }, "Label": {"padding": 3, "background_color": cl("#DDDD00"), "color": cl("#333333"), "debug_color": cl("#0000FF22") }} with ui.HStack(width=500, style=style): ui.Label("Label 1", width=50) ui.Label("Label 2") ui.Label("Label 3", width=100, alignment=ui.Alignment.CENTER) ui.Spacer() ui.Label("Label 3", width=50) """ ) self._caption("Font", navigate_to) self._text( "It's possible to set the font of the label using styles. The style key 'font' should point to the font " "file, which allows packaging of the font to the extension. We support both TTF and OTF formats. " "All text-based widgets support custom fonts." ) self._exec_code( """ ui.Label( "The quick brown fox jumps over the lazy dog", style={ "font_size": 55, "font": "${fonts}/OpenSans-SemiBold.ttf", "alignment": ui.Alignment.CENTER }, word_wrap=True, ) """ ) ui.Spacer(height=10)
13,547
Python
34.465968
120
0.552668
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/plot_doc.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. # """The documentation for Menu""" from omni import ui from omni.ui import color as cl from .doc_page import DocPage import math class PlotDoc(DocPage): """ document for Plot""" def __init__(self, extension_path): super().__init__(extension_path) self._data = [] for i in range(360): self._data.append(math.cos(math.radians(i))) def create_doc(self, navigate_to=None): self._section_title("Plot") self._text("The Plot class displayes a line or histogram image.") self._text("The data of image is specified as a data array or a provider function.") ui.Plot(ui.Type.LINE, -1.0, 1.0, *self._data, width=360, height=100, style={"color": cl.red}) self._code( """ self._data = [] for i in range(360): self._data.append(math.cos(math.radians(i))) ui.Plot(ui.Type.LINE, -1.0, 1.0, *self._data, width=360, height=100, style={"color": cl.red}) """ ) plot = ui.Plot( ui.Type.HISTOGRAM, -1.0, 1.0, self._on_data_provider, 360, width=360, height=100, style={"color": cl.blue}, ) plot.value_stride = 6 self._code( """ def _on_data_provider(self, index): return math.sin(math.radians(index)) plot = ui.Plot(ui.Type.HISTOGRAM, -1.0, 1.0, self._on_data_provider, 360, width=360, height=100, style={"color": cl.blue}) plot.value_stride = 6 """ ) ui.Spacer(height=100) def _on_data_provider(self, index): return math.sin(math.radians(index))
2,140
Python
29.585714
130
0.590187
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/styling_doc.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. # """The documentation for Styling""" from .doc_page import DocPage from functools import partial from omni import ui from omni.ui import color as cl from omni.ui import constant as fl from omni.ui import url import inspect SPACING = 5 def named_shades(): def set_color(color): cl.example_color = color def set_width(value): fl.example_width = value cl.example_color = cl.green fl.example_width = 1.0 with ui.HStack(height=100, spacing=5): with ui.ZStack(): ui.Rectangle( style={ "background_color": cl.shade( "aqua", orange=cl.orange, another=cl.example_color, transparent=cl.transparent, black=cl.black, ), "border_width": fl.shade(1, orange=4, another=8), "border_radius": fl.one, "border_color": cl.black, }, ) ui.Label( "ui.Rectangle(\n" "\tstyle={\n" '\t\t"background_color":\n' "\t\t\tcl.shade(\n" '\t\t\t\t"aqua",\n' "\t\t\t\torange=cl(1, 0.5, 0),\n" "\t\t\t\tanother=cl.example_color),\n" '\t\t"border_width":\n' "\t\t\tfl.shade(1, orange=4, another=8)})", alignment=ui.Alignment.CENTER, word_wrap=True, style={"color": cl.black, "margin": 15}, ) with ui.ZStack(): ui.Rectangle( style={ "background_color": cl.example_color, "border_width": fl.example_width, "border_radius": fl.one, "border_color": cl.black, } ) ui.Label( "ui.Rectangle(\n" "\tstyle={\n" '\t\t"background_color": cl.example_color,\n' '\t\t"border_width": fl.example_width)})', alignment=ui.Alignment.CENTER, word_wrap=True, style={"color": cl.black, "margin": 15}, ) with ui.HStack(): ui.Button("ui.set_shade()", clicked_fn=partial(ui.set_shade, "")) ui.Button('ui.set_shade("orange")', clicked_fn=partial(ui.set_shade, "orange")) ui.Button('ui.set_shade("another")', clicked_fn=partial(ui.set_shade, "another")) with ui.HStack(): ui.Button("fl.example_width = 1", clicked_fn=partial(set_width, 1)) ui.Button("fl.example_width = 4", clicked_fn=partial(set_width, 4)) with ui.HStack(): ui.Button('cl.example_color = "green"', clicked_fn=partial(set_color, "green")) ui.Button("cl.example_color = cl(0.8)", clicked_fn=partial(set_color, cl(0.8))) def url_shades(): def set_url(url_path: str): url.example_url = url_path walk = "resources/icons/Nav_Walkmode.png" fly = "resources/icons/Nav_Flymode.png" url.example_url = walk with ui.HStack(height=100, spacing=5): with ui.ZStack(): ui.Image(style={"image_url": url.example_url}) ui.Label( 'ui.Image(\n\tstyle={"image_url": cl.example_url})\n', alignment=ui.Alignment.CENTER, word_wrap=True, style={"color": cl.black, "margin": 15}, ) with ui.ZStack(): ui.ImageWithProvider( style={ "image_url": url.shade( "resources/icons/Move_local_64.png", another="resources/icons/Move_64.png", orange="resources/icons/Rotate_local_64.png", ) } ) ui.Label( "ui.ImageWithProvider(\n" "\tstyle={\n" '\t\t"image_url":\n' "\t\t\tst.shade(\n" '\t\t\t\t"Move_local_64.png",\n' '\t\t\t\tanother="Move_64.png")})\n', alignment=ui.Alignment.CENTER, word_wrap=True, style={"color": cl.black, "margin": 15}, ) with ui.HStack(): ui.Button("ui.set_shade()", clicked_fn=partial(ui.set_shade, "")) ui.Button('ui.set_shade("another")', clicked_fn=partial(ui.set_shade, "another")) with ui.HStack(): ui.Button("url.example_url = Nav_Walkmode.png", clicked_fn=partial(set_url, walk)) ui.Button("url.example_url = Nav_Flymode.png", clicked_fn=partial(set_url, fly)) def font_size(): def value_changed(label, value): label.style = {"color": ui.color(0), "font_size": value.as_float} slider = ui.FloatSlider(min=1.0, max=150.0) slider.model.as_float = 10.0 label = ui.Label("Omniverse", style={"color": ui.color(0), "font_size": 7.0}) slider.model.add_value_changed_fn(partial(value_changed, label)) class StylingDoc(DocPage): """ document for Styling workflow""" def create_doc(self, navigate_to=None): self._section_title("Styling") self._caption("The Style Sheet Syntax", navigate_to) self._text( "OMNI.UI Style Sheet rules are almost identical to those of HTML CSS. Style sheets consist of a sequence " "of style rules. A style rule is made up of a selector and a declaration. The selector specifies which " "widgets are affected by the rule; the declaration specifies which properties should be set on the widget. " "For example:" ) with ui.VStack(width=0, style={"Button": {"background_color": cl("#097EFF")}}): ui.Button("Style Example") self._code( """ with ui.VStack(width=0, style={"Button": {"background_color": cl("#097EFF")}}): ui.Button("Style Example") """ ) self._text( 'In the above style rule, Button is the selector, and { "background_color": cl("#097EFF") } is the ' "declaration. The rule specifies that Button should use blue as its background color." ) with ui.VStack(): self._table("Selector", "Example", "Explanation", cl.black) self._table("Type Selector", "Button", "Matches instances of Button.") self._table( "Name Selector", "Button::okButton", "Matches all Button instances whose object name is okButton." ) self._table( "State Selector", "Button:hovered", "Matches all Button instances whose state is hovered. It means the mouse should be in the widget area. " "Pseudo-states appear at the end of the selector, with a colon (:) in between. The supported states are " "hovered and pressed.", ) self._text("It's possible to omit the selector and override the property in all the widget types:") with ui.VStack(width=0, style={"background_color": cl("#097EFF")}): ui.Button("Style Example") self._code( """ with ui.VStack(width=0, style={"background_color": cl("#097EFF")}): ui.Button("Style Example") """ ) self._text( "The difference with the previous button is that all the colors, including pressed color and hovered " "color, are overridden." ) style1 = { "Button": {"border_width": 0.5, "border_radius": 0.0, "margin": 5.0, "padding": 5.0}, "Button::one": { "background_color": cl("#097EFF"), "background_gradient_color": cl("#6DB2FA"), "border_color": cl("#1D76FD"), }, "Button.Label::one": {"color": cl.white}, "Button::one:hovered": {"background_color": cl("#006EFF"), "background_gradient_color": cl("#5AAEFF")}, "Button::one:pressed": {"background_color": cl("#6DB2FA"), "background_gradient_color": cl("#097EFF")}, "Button::two": {"background_color": cl.white, "border_color": cl("#B1B1B1")}, "Button.Label::two": {"color": cl("#272727")}, "Button::three:hovered": { "background_color": cl("#006EFF"), "background_gradient_color": cl("#5AAEFF"), "border_color": cl("#1D76FD"), }, "Button::four:pressed": { "background_color": cl("#6DB2FA"), "background_gradient_color": cl("#097EFF"), "border_color": cl("#1D76FD"), }, } with ui.HStack(style=style1): ui.Button("One", name="one") ui.Button("Two", name="two") ui.Button("Three", name="three") ui.Button("Four", name="four") ui.Button("Five", name="five") self._code( """ style1 = { "Button": { "border_width": 0.5, "border_radius": 0.0, "margin": 5.0, "padding": 5.0 }, "Button::one": { "background_color": cl("#097EFF"), "background_gradient_color": cl("#6DB2FA"), "border_color": cl("#1D76FD"), }, "Button.Label::one": { "color": cl.white, }, "Button::one:hovered": { "background_color": cl("#006EFF"), "background_gradient_color": cl("#5AAEFF") }, "Button::one:pressed": { "background_color": cl("#6DB2FA"), "background_gradient_color": cl("#097EFF") }, "Button::two": { "background_color": cl.white, "border_color": cl("#B1B1B1") }, "Button.Label::two": { "color": cl("#272727") }, "Button::three:hovered": { "background_color": cl("#006EFF"), "background_gradient_color": cl("#5AAEFF"), "border_color": cl("#1D76FD"), }, "Button::four:pressed": { "background_color": cl("#6DB2FA"), "background_gradient_color": cl("#097EFF"), "border_color": cl("#1D76FD"), }, } with ui.HStack(style=style1): ui.Button("One", name="one") ui.Button("Two", name="two") ui.Button("Three", name="three") ui.Button("Four", name="four") ui.Button("Five", name="five") """ ) self._text( "It's possible to assign any style override to any level of the widget. It can be assigned to both parents " "and children at the same time." ) with ui.HStack(style=self._style_system): ui.Button("One") ui.Button("Two", style={"color": cl("#AAAAAA")}) ui.Button("Three", style={"background_color": cl("#097EFF"), "background_gradient_color": cl("#6DB2FA")}) ui.Button( "Four", style={":hovered": {"background_color": cl("#006EFF"), "background_gradient_color": cl("#5AAEFF")}} ) ui.Button( "Five", style={"Button:pressed": {"background_color": cl("#6DB2FA"), "background_gradient_color": cl("#097EFF")}}, ) self._code( """ style_system = { "Button": { "background_color": cl("#E1E1E1"), "border_color": cl("#ADADAD"), "border_width": 0.5, "border_radius": 0.0, "margin": 5.0, "padding": 5.0, }, "Button.Label": { "color": cl.black, }, "Button:hovered": { "background_color": cl("#E5F1FB"), "border_color": cl("#0078D7") }, "Button:pressed": { "background_color": cl("#CCE4F7"), "border_color": cl("#005499"), "border_width": 1.0 }, } with ui.HStack(style=style_system): ui.Button("One") ui.Button("Two", style={"color": cl("#AAAAAA")}) ui.Button("Three", style={ "background_color": cl("#097EFF"), "background_gradient_color": cl("#6DB2FA")} ) ui.Button( "Four", style={ ":hovered": { "background_color": cl("#006EFF"), "background_gradient_color": cl("#5AAEFF") } } ) ui.Button( "Five", style={ "Button:pressed": { "background_color": cl("#6DB2FA"), "background_gradient_color": cl("#097EFF") } }, ) """ ) self._caption("Color Syntax", navigate_to) self._text( "There are many ways that colors can be described with omni.ui.color. If alpha is not specified, it is assumed to be 255 or 1.0." ) self._code( """ from omni.ui import color as cl cl("#CCCCCC") # RGB cl("#CCCCCCFF") # RGBA cl(128, 128, 128) # RGB cl(0.5, 0.5, 0.5) # RGB cl(128, 128, 128, 255) # RGBA cl(0.5, 0.5, 0.5, 1.0) # RGBA cl(128) # RGB all the same cl(0.5) # RGB all the same cl.blue """ ) self._text( "Note: You may see something like this syntax in older code, but that syntax is not suggested anymore:" ) self._code('"background_color": 0xFF886644 # Same as cl("#446688FF")') self._text( "Because of the way bytes are packed with little-endian format in that syntax, the color components appear to be backwards (ABGR). " "Going forward only omni.ui.color syntax should be used." ) self._caption("Shades", navigate_to) self._text( "Shades are used to have multiple named color palettes with the ability to runtime switch. The shade can " "be defined with the following code:" ) self._code('cl.shade(cl("#0066FF"), red=cl.red, green=cl("#00FF66"))') self._text( "It can be assigned to the color style. It's possible to switch the color with the following command " "globally:" ) self._code('cl.set_shade("red")') named_shades() self._code(inspect.getsource(named_shades).split("\n", 1)[-1]) self._caption("URL Shades", navigate_to) self._text("It's also possible to use shades for specifying shortcuts to the images and style-based paths.") url_shades() self._code(inspect.getsource(url_shades).split("\n", 1)[-1]) self._caption("Font Size", navigate_to) self._text("It's possible to set the font size with the style:") font_size() self._code(inspect.getsource(font_size).split("\n", 1)[-1]) ui.Spacer(height=10)
15,870
Python
35.823666
144
0.497669
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/custom_window_example.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. # """an example of creating a custom with shapes and drags window""" # TODO : This need clean up for full documentation from omni import ui EXTENSION_NAME = "Brick Demo Window" LIGHT_WINDOW_STYLE = { # main frame style "ScrollingFrame::canvas": {"background_color": 0xFFCACACA}, "Frame::main_frame": {"background_color": 0xFFCACACA}, # title bar style "Label::title": {"color": 0xFF777777, "font_size": 16.0}, "Rectangle::titleBar": {"background_color": 0xFFCACACA}, "Rectangle::timeSelection": {"background_color": 0xFF888888, "border_radius": 5.0}, "Triangle::timeArrows": {"background_color": 0xFFCACACA}, "Label::timeLabel": {"color": 0xFFDDDDDD, "font_size": 16.0}, # custom widget slider "Rectangle::sunStudySliderBackground": { "background_color": 0xFFBBBBBB, "border_color": 0xFF888888, "border_width": 1.0, "border_radius": 10.0, }, "Rectangle::sunStudySliderForground": {"background_color": 0xFF888888}, "Circle::slider": {"background_color": 0xFFBBBBBB}, "Circle::slider:hovered": {"background_color": 0xFFCCCCCC}, "Circle::slider:pressed": {"background_color": 0xFFAAAAAA}, "Triangle::selector": {"background_color": 0xFF888888}, "Triangle::selector:hovered": {"background_color": 0xFF999999}, "Triangle::selector:pressed": {"background_color": 0xFF777777}, # toolbar "Triangle::play_button": {"background_color": 0xFF6E6E6E}, } DARK_WINDOW_STYLE = { # main frame style "ScrollingFrame::canvas": {"background_color": 0xFF454545}, "Frame::main_frame": {"background_color": 0xFF454545}, # title bar style "Label::title": {"color": 0xFF777777, "font_size": 16.0}, "Rectangle::titleBar": {"background_color": 0xFF454545}, "Rectangle::timeSelection": {"background_color": 0xFF888888, "border_radius": 5.0}, "Triangle::timeArrows": {"background_color": 0xFF454545}, "Label::timeLabel": {"color": 0xFF454545, "font_size": 16.0}, # custom widget slider "Rectangle::sunStudySliderBackground": { "background_color": 0xFF666666, "border_color": 0xFF333333, "border_width": 1.0, "border_radius": 10.0, }, "Rectangle::sunStudySliderForground": {"background_color": 0xFF333333}, "Circle::slider": {"background_color": 0xFF888888}, "Triangle::selector": {"background_color": 0xFF888888}, # toolbar "Triangle::play_button": {"background_color": 0xFF6E6E6E}, } class BrickSunStudyWindow: """ example of sun study window using Omni::UI """ def __init__(self): self._is_playing = False self._window_Frame = None self._time_selector_left_spacer = None self._slider_spacer = None self._slider_spacer_width = [200] self._start_time_offset = [200] self._start_time_label = None self._start_time = "8:00 AM" self._end_time_offset = [600] self._end_time_label = None self._end_time = "6:00 PM" self._time_of_day_offset = [200] self._mouse_press_position = [0, 0] def _play_pause_fn(self, x, y): """ """ self._is_playing = not self._is_playing self._play_button.visible = not self._is_playing self._pause_button.visible = self._is_playing def _on_object_mouse_pressed(self, position, x, y): position[0] = x position[1] = y def on_placer_mouse_moved_both(self, placer, offset, position, x, y): # TODO: DPI is the problem we need to solve offset[0] += x - position[0] offset[1] += y - position[1] placer.offset_x = max(offset[0], 0) placer.offset_y = offset[1] self._on_object_mouse_pressed(position, x, y) def on_time_placer_mouse_moved_X(self, placer, offset, position, x, y): # TODO: DPI is the problem we need to solve offset[0] += x - position[0] offset[0] = max(offset[0], 0) placer.offset_x = offset[0] # this is not very correct but serve ok for this demo hours = int(offset[0] / 800 * 24) time = "AM" if hours > 12: hours = hours - 12 time = "PM" self._current_time_label.text = f"{hours}:00 {time}" self._on_object_mouse_pressed(position, x, 0) def on_start_placer_mouse_moved_X(self, placer, offset, position, x, y): # TODO: DPI is the problem we need to solve offset[0] += x - position[0] offset[0] = max(offset[0], 0) placer.offset_x = offset[0] self._time_range_placer.offset_x = offset[0] + 50 self._time_range_rectangle.width = ui.Pixel(self._end_time_offset[0] - self._start_time_offset[0] + 3) # this is not very correct but serve ok for this demo hours = int(offset[0] / 800 * 24) time = "AM" if hours > 12: hours = hours - 12 time = "PM" self._start_time_label.text = f"{hours}:00 {time}" self._on_object_mouse_pressed(position, x, 0) def on_end_placer_mouse_moved_X(self, placer, offset, position, x, y): # TODO: DPI is the problem we need to solve offset[0] += x - position[0] offset[0] = max(offset[0], 0) placer.offset_x = offset[0] self._time_range_rectangle.width = ui.Pixel(self._end_time_offset[0] - self._start_time_offset[0] + 3) # this is not very correct but serve ok for this demo hours = int(offset[0] / 800 * 24) time = "AM" if hours > 12: hours = hours - 12 time = "PM" self._end_time_label.text = f"{hours}:00 {time}" self._on_object_mouse_pressed(position, x, 0) def set_style_light(self, button): """ """ self._window_Frame.set_style(LIGHT_WINDOW_STYLE) def set_style_dark(self, button): """ """ self._window_Frame.set_style(DARK_WINDOW_STYLE) def _build_title_bar(self): """ return the title bar stack""" with ui.VStack(): with ui.ZStack(height=30): ui.Rectangle(name="titleBar") # Title Bar with ui.HStack(): ui.Spacer(width=10, height=0) with ui.VStack(width=0): ui.Spacer(width=0, height=8) ui.Label("Sun Study", name="title", width=0, alignment=ui.Alignment.LEFT) ui.Spacer(width=0, height=ui.Fraction(1)) ui.Spacer(width=ui.Fraction(1)) with ui.VStack(width=0): ui.Spacer(height=5) with ui.HStack(): ui.Spacer(width=10, height=0) ui.Image("resources/icons/[email protected]", width=20, height=20) ui.Spacer(width=10) ui.Image("resources/icons/[email protected]", width=20, height=20) ui.Spacer(width=5) ui.Spacer(height=5) # Shadow ui.Image("resources/icons/TitleBarShadow_wAlpha_v2.png", fill_policy=ui.FillPolicy.STRETCH, height=20) def _build_time_arrow(self, arrowAlignment): with ui.VStack(width=0): # remove spacer with Fraction Padding ui.Spacer() ui.Triangle(name="timeArrows", width=12, height=12, alignment=arrowAlignment) ui.Spacer() def _build_start_time_selector(self): """ """ selector_placer = ui.Placer(offset_x=self._start_time_offset[0]) with selector_placer: with ui.VStack( width=80, mouse_pressed_fn=lambda x, y, b, a, c=self._mouse_press_position: self._on_object_mouse_pressed( c, x, y ), mouse_moved_fn=lambda x, y, b, a: self.on_start_placer_mouse_moved_X( selector_placer, self._start_time_offset, self._mouse_press_position, x, y ), opaque_for_mouse_events=True, ): # SELECTOR START self._start_time_selector_stack = ui.ZStack() with self._start_time_selector_stack: ui.Rectangle(height=25, name="timeSelection") with ui.HStack(height=25): # remove spacer with Padding ui.Spacer(width=5) self._build_time_arrow(ui.Alignment.LEFT_CENTER) ui.Spacer(width=5) self._start_time_label = ui.Label( self._start_time, name="timeLabel", alignment=ui.Alignment.RIGHT_CENTER ) ui.Spacer(width=5) with ui.HStack(height=20): # Selector tip, Spacer will be removed wiht Padding ui.Spacer() def show_hide_start_time_selector(): self._start_time_selector_stack.visible = not self._start_time_selector_stack.visible ui.Triangle( width=10, height=17, name="selector", alignment=ui.Alignment.CENTER_BOTTOM, mouse_pressed_fn=lambda x, y, b, a: show_hide_start_time_selector(), ) ui.Spacer() def _build_end_time_selector(self): self._end_time_placer = ui.Placer(offset_x=self._end_time_offset[0]) with self._end_time_placer: with ui.VStack( width=80, mouse_pressed_fn=lambda x, y, b, a: self._on_object_mouse_pressed( self._mouse_press_position, x, y ), mouse_moved_fn=lambda x, y, b, a: self.on_end_placer_mouse_moved_X( self._end_time_placer, self._end_time_offset, self._mouse_press_position, x, y ), opaque_for_mouse_events=True, ): # SELECTOR END self._end_time_selector_stack = ui.ZStack() with self._end_time_selector_stack: ui.Rectangle(height=25, name="timeSelection") with ui.HStack(height=25): ui.Spacer(width=5) self._end_time_label = ui.Label( self._end_time, name="timeLabel", widthalignment=ui.Alignment.RIGHT_CENTER ) ui.Spacer(width=5) self._build_time_arrow(ui.Alignment.RIGHT_CENTER) ui.Spacer(width=5) def show_hide_end_time_selector(): self._end_time_selector_stack.visible = not self._end_time_selector_stack.visible with ui.HStack(height=20): ui.Spacer() ui.Triangle( width=10, height=17, name="selector", alignment=ui.Alignment.CENTER_BOTTOM, mouse_pressed_fn=lambda x, y, b, a: show_hide_end_time_selector(), ) ui.Spacer() def _build_central_slider(self): """ """ # custom slider Widget with ui.VStack(height=70): ui.Spacer(height=40) with ui.HStack(): with ui.ZStack(height=20): ui.Rectangle(name="sunStudySliderBackground") self._time_range_placer = ui.Placer(offset_x=self._start_time_offset[0]) with self._time_range_placer: self._time_range_rectangle = ui.Rectangle(name="sunStudySliderForground", width=500, height=30) circle_placer = ui.Placer(offset_x=self._time_of_day_offset[0]) with circle_placer: ui.Circle( name="slider", width=30, height=30, radius=10, mouse_pressed_fn=lambda x, y, b, a: self._on_object_mouse_pressed( self._mouse_press_position, x, y ), mouse_moved_fn=lambda x, y, b, a: self.on_time_placer_mouse_moved_X( circle_placer, self._time_of_day_offset, self._mouse_press_position, x, y ), opaque_for_mouse_events=True, ) def _build_custom_slider(self): """ return the slider stack""" side_padding = 50 with ui.HStack(height=70): ui.Spacer(width=side_padding) # from Padding (will be removed by Padding on the HStack) with ui.ZStack(): self._build_central_slider() # Selectors with ui.ZStack(height=40): # Selector Height self._build_start_time_selector() self._build_end_time_selector() ui.Spacer(width=side_padding) def _build_control_bar(self): """ """ with ui.HStack(height=40): ui.Spacer(width=50) ui.Image("resources/icons/[email protected]", width=25) ui.Spacer(width=10) ui.Image("resources/icons/[email protected]", width=20) ui.Spacer(width=10) ui.Image("resources/icons/[email protected]", width=20) ui.Spacer(width=ui.Fraction(2)) # with ui.ZStack(): self._play_button = ui.Image( "resources/icons/[email protected]", height=30, width=30, mouse_pressed_fn=lambda x, y, button, modifier: self._play_pause_fn(x, y), ) self._pause_button = ui.Image( "resources/icons/[email protected]", height=30, width=30, mouse_pressed_fn=lambda x, y, button, modifier: self._play_pause_fn(x, y), ) self._pause_button.visible = False ui.Spacer(width=ui.Fraction(1)) with ui.HStack(width=120): self._current_time_label = ui.Label("9:30 AM", name="title") ui.Label(" October 21, 2019", name="title") ui.Spacer(width=30) def build_window(self): """ build the window for the Class""" self._window = ui.Window("Brick Sun Study", width=800, height=250, flags=ui.WINDOW_FLAGS_NO_TITLE_BAR) with self._window.frame: with ui.VStack(): with ui.HStack(height=20): ui.Label("Styling : ", alignment=ui.Alignment.RIGHT_CENTER) ui.Button("Light Mode", clicked_fn=lambda b=None: self.set_style_light(b)) ui.Button("Dark Mode", clicked_fn=lambda b=None: self.set_style_dark(b)) ui.Spacer() ui.Spacer(height=10) self._window_Frame = ui.ScrollingFrame( style=LIGHT_WINDOW_STYLE, name="canvas", height=200, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, ) with self._window_Frame: with ui.VStack(height=0): # Build the toolbar for the window self._build_title_bar() ui.Spacer(height=10) # build the custom slider self._build_custom_slider() ui.Spacer(height=10) self._build_control_bar() # botton Padding ui.Spacer(height=10) return self._window
16,391
Python
40.498734
119
0.532426
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/window_doc.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. # """The documentation for Windows""" from .doc_page import DocPage from omni import ui from omni.ui import color as cl import inspect import json import carb.settings SPACING = 5 def popup_example(self): class StrModel(ui.AbstractValueModel): def __init__(self, **kwargs): super().__init__() self.__str = "" self.__parent = None self.__window = None self.__frame = None self.__tooltips = ["Hello", "World", "Hello World"] self.__kwargs = kwargs def set_parent(self, parent): self.__parent = parent def set_value(self, value): self.__str = str(value) self._value_changed() self._set_tips() def get_value_as_string(self): return self.__str def begin_edit(self): if self.__window and self.__window.visible: return # Create and show the window with field and list of tips self.__window = ui.Window("0", **self.__kwargs) with self.__window.frame: with ui.VStack(width=0, height=0): width = self.__parent.computed_content_width # Field with the same model field = ui.StringField(self, width=width) field.focus_keyboard() self.__frame = ui.Frame() self.__window.position_x = self.__parent.screen_position_x self.__window.position_y = self.__parent.screen_position_y self._set_tips() def _set_tips(self): """Generates list of tips""" if not self.__frame: return found = False with self.__frame: with ui.VStack(): for t in self.__tooltips: if self.__str and self.__str in t: ui.Button(t) found = True if not found: for t in self.__tooltips: ui.Button(t) def destroy(self): self.__parent = None self.__frame = None self.__window = None window_args = { "flags": ui.WINDOW_FLAGS_POPUP | ui.WINDOW_FLAGS_NO_TITLE_BAR, "auto_resize": True, "padding_x": 0, "padding_y": 0, } self._model = StrModel(**window_args) self._field = ui.StringField(self._model) self._model.set_parent(self._field) class WindowDoc(DocPage): """ document Windows classes""" def __init__(self, extension_path): super().__init__(extension_path) self._window_example = None self._modal_window_example = None self._no_close_window_example = None self._style_window_example = None self._simple_toolbar = None self._rotating_toolbar = None self._toolbar_rotation = ui.DockPosition.BOTTOM self._modal_test = [] self._model = None def clean(self): self._model = None def build_toolbar(self): """Caled to load the extension""" def top_toolbar_changeAxis(frame, axis): with frame: stack = None if axis == ui.ToolBarAxis.X: stack = ui.HStack(spacing=15, height=24) else: stack = ui.VStack(spacing=15, height=24) with stack: ui.Spacer() ui.Image("resources/icons/Select_model_64.png", width=24, height=24) ui.Image("resources/icons/Move_64.png", width=24, height=24) ui.Image("resources/icons/Rotate_global.png", width=24, height=24) ui.Image("resources/icons/Scale_64.png", width=24, height=24) ui.Image("resources/icons/Snap_64.png", width=24, height=24) ui.Spacer() self._top_toolbar = ui.ToolBar("UI ToolBar", noTabBar=False, padding_x=0, padding_y=0) self._top_toolbar.set_axis_changed_fn( lambda axis, frame=self._top_toolbar.frame: top_toolbar_changeAxis(frame, axis) ) top_toolbar_changeAxis(self._top_toolbar.frame, ui.ToolBarAxis.X) self._right_toolbar = ui.ToolBar("Right Size ToolBar", noTabBar=True, padding_x=5, padding_y=0) with self._right_toolbar.frame: with ui.VStack(spacing=15, width=25): ui.Spacer(height=1) ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20) ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20) ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20) ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20) ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20) ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20) ui.Image("resources/icons/SunStudy_64.png", width=20, height=20) ui.Spacer() self._left_toolbar = ui.ToolBar("Left Size ToolBar", noTabBar=True, padding_x=5, padding_y=0) with self._left_toolbar.frame: with ui.VStack(spacing=0): ui.Spacer(height=10) ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20) ui.Spacer() self._bottom_toolbar = ui.ToolBar("Bottom ToolBar", noTabBar=True, padding_x=0, padding_y=0) with self._bottom_toolbar.frame: with ui.HStack(height=18): ui.Spacer() with ui.ZStack(width=200, height=15): ui.Rectangle( width=120, style={"background_color": cl("#809EAB"), "corner_flag": ui.CornerFlag.LEFT, "border_radius": 2}, ) ui.Rectangle( width=200, style={ "background_color": cl.transparent, "border_color": cl("#222222"), "border_width": 1.0, "border_radius": 2, }, ) ui.Label("FPS 30", style={"color": cl.white, "margin_width": 10, "font_size": 8}) ui.Spacer() self._bottom_toolbar.dock_in_window("Viewport", ui.DockPosition.BOTTOM) self._top_toolbar.dock_in_window("Viewport", ui.DockPosition.TOP) self._left_toolbar.dock_in_window("Viewport", ui.DockPosition.LEFT) self._right_toolbar.dock_in_window("Viewport", ui.DockPosition.RIGHT) # TODO omni.ui: restore functionality for Kit Next self._settings = carb.settings.get_settings() self._settings.set("/app/docks/autoHideTabBar", True) self._settings.set("/app/docks/noWindowMenuButton", False) self._settings.set("app/window/showStatusBar", False) self._settings.set("app/window/showStatusBar", False) self._settings.set("/app/viewport/showSettingsMenu", True) self._settings.set("/app/viewport/showCameraMenu", False) self._settings.set("/app/viewport/showRendererMenu", True) self._settings.set("/app/viewport/showHideMenu", True) self._settings.set("/app/viewport/showLayerMenu", False) def create_and_show_window(self): if not self._window_example: self._window_example = ui.Window("Example Window", width=300, height=300) button_size = None button_dock = None with self._window_example.frame: with ui.VStack(): ui.Button("click me") button_size = ui.Button("") def move_me(window): window.setPosition(200, 200) def size_me(window): window.width = 300 window.height = 300 ui.Button("move to 200,200", clicked_fn=lambda w=self._window_example: move_me(w)) ui.Button("set size 300,300", clicked_fn=lambda w=self._window_example: size_me(w)) button_dock = ui.Button("Undocked") def update_button(window, button): computed_width = (int)(button.computed_width) computed_height = (int)(button.computed_height) button.text = ( "Window size is {:.1f} x {:.1f}\n".format(window.width, window.height) + "Window position is {:.1f} x {:.1f}\n".format(window.position_x, window.position_y) + "Button size is {:.1f} x {:.1f}".format(computed_width, computed_height) ) def update_docking(docked, button): button.text = "Docked" if docked else "Undocked" for fn in [ self._window_example.set_width_changed_fn, self._window_example.set_height_changed_fn, self._window_example.set_position_x_changed_fn, self._window_example.set_position_y_changed_fn, ]: fn(lambda value, b=button_size, w=self._window_example: update_button(w, b)) self._window_example.set_docked_changed_fn(lambda value, b=button_dock: update_docking(value, b)) self._window_example.visible = True def close_modal_window_me(self): if self._modal_window_example: self._modal_window_example.visible = False def create_and_show_modal_window(self): if not self._modal_window_example: window_flags = ui.WINDOW_FLAGS_NO_RESIZE window_flags |= ui.WINDOW_FLAGS_NO_SCROLLBAR window_flags |= ui.WINDOW_FLAGS_MODAL self._modal_window_example = ui.Window("Example Modal Window", width=200, height=200, flags=window_flags) with self._modal_window_example.frame: with ui.VStack(): ui.Button("I am Modal") ui.Button("You Can't Click outsite ") ui.Button("click here to close me", height=100, clicked_fn=self.close_modal_window_me) self._modal_window_example.visible = True def create_and_show_window_no_close(self): if not self._no_close_window_example: window_flags = ui.WINDOW_FLAGS_NO_CLOSE self._no_close_window_example = ui.Window( "Example Modal Window", width=400, height=200, flags=window_flags, visibility_changed_fn=self._update_window_visible, ) with self._no_close_window_example.frame: with ui.VStack(): ui.Button("I dont have Close button") ui.Button("my Size is 400x200 ") def close_me(window): if window: window.visible = False ui.Button( "click here to close me", height=100, clicked_fn=lambda w=self._no_close_window_example: close_me(w), ) self._no_close_window_example.visible = True def create_styled_window(self): if not self._style_window_example: self._style_window_example = ui.Window("Styled Window Example", width=300, height=300) self._style_window_example.frame.set_style( { "Window": { "background_color": cl.blue, "border_radius": 10, "border_width": 5, "border_color": cl.red, } } ) with self._style_window_example.frame: with ui.VStack(): ui.Button("I am a Styled Window") ui.Spacer(height=10) ui.Button( """Style is attached to 'Window' {"Window": {"background_color": cl.blue, "border_radius": 10, "border_width": 5, "border_color": cl.red}""", height=200, ) self._style_window_example.visible = True def _update_window_visible(self, value): self._window_checkbox.model.set_value(value) def create_simple_toolbar(self): if self._simple_toolbar: self._simple_toolbar.visible = not self._simple_toolbar.visible else: self._simple_toolbar = ui.ToolBar("simple toolbar", noTabBar=True) with self._simple_toolbar.frame: with ui.HStack(spacing=15, height=28): ui.Spacer() ui.Image("resources/icons/Select_model_64.png", width=24, height=24) ui.Image("resources/icons/Move_64.png", width=24, height=24) ui.Image("resources/icons/Rotate_global.png", width=24, height=24) ui.Image("resources/icons/Scale_64.png", width=24, height=24) ui.Image("resources/icons/Snap_64.png", width=24, height=24) ui.Spacer() self._simple_toolbar.dock_in_window("Viewport", ui.DockPosition.TOP) self._simple_toolbar.frame.set_style({"Window": {"background_color": cl("#DDDDDD")}}) def create_rotating_toolbar(self): if not self._rotating_toolbar: def toolbar_changeAxis(frame, axis): with frame: stack = None if axis == ui.ToolBarAxis.X: stack = ui.HStack(spacing=15, height=30) else: stack = ui.VStack(spacing=15, width=30) with stack: ui.Spacer() ui.Image("resources/icons/Select_model_64.png", width=24, height=24) ui.Image("resources/icons/Move_64.png", width=24, height=24) ui.Image("resources/icons/Rotate_global.png", width=24, height=24) ui.Image("resources/icons/Scale_64.png", width=24, height=24) ui.Image("resources/icons/Snap_64.png", width=24, height=24) ui.Spacer() self._rotating_toolbar = ui.ToolBar("Rotating ToolBar", noTabBar=False, padding_x=5, padding_y=5, margin=5) self._rotating_toolbar.set_axis_changed_fn( lambda axis, frame=self._rotating_toolbar.frame: toolbar_changeAxis(frame, axis) ) toolbar_changeAxis(self._rotating_toolbar.frame, ui.ToolBarAxis.X) if self._toolbar_rotation == ui.DockPosition.RIGHT: self._toolbar_rotation = ui.DockPosition.BOTTOM else: self._toolbar_rotation = ui.DockPosition.RIGHT self._rotating_toolbar.dock_in_window("Viewport", self._toolbar_rotation) def create_doc(self, navigate_to=None): self._section_title("Windows") self._text( "With omni ui you can create a varierty of Window type and style" " the main Window type are floating window that can optionally be docked into the Main Window.\n" "There are also other type of window like ToolBar, DialogBox, Etc that you can use" ) self._caption("Window", navigate_to) self._text("This class is used to construct a regular Window") with ui.ScrollingFrame(height=350, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF): with ui.VStack(height=0): with ui.HStack(width=0): ui.Button("click for window Example", width=180, clicked_fn=self.create_and_show_window) ui.Label("this create a regular Window", name="text", width=180, style={"margin_width": 10}) ui.Label( """ ui.Window("Example Window", position_x=100, position_y=100)""", name="text", ) with ui.HStack(width=0): ui.Button("Window without close", width=180, clicked_fn=self.create_and_show_window_no_close) self._window_checkbox = ui.CheckBox(style={"margin": 5}) # this Tie the window visibility with the checkox def update_check_box(value, self): self._no_close_window_example.visible = value self._window_checkbox.model.add_value_changed_fn( lambda a, this=self: update_check_box(a.get_value_as_bool(), self) ) ui.Label("this create a regular Window", name="text", width=150, style={"margin_width": 10}) ui.Label('ui.Window("Example Window", )', name="text") # Modal example is off because there are few issue but this MR need to go in with ui.HStack(width=0): ui.Button("click for Custom Window", width=180, clicked_fn=self.create_and_show_modal_window) ui.Label("this create a custom Window", name="text", width=180, style={"margin_width": 10}) ui.Label( "window_flags = ui.WINDOW_FLAGS_NO_COLLAPSE\n" "window_flags |= ui.WINDOW_FLAGS_NO_RESIZE\n" "window_flags |= ui.WINDOW_FLAGS_NO_CLOSE\n" "window_flags |= ui.WINDOW_FLAGS_NO_SCROLLBAR\n" "window_flags |= ui.WINDOW_FLAGS_NO_TITLE_BAR\n\n" "ui.Window('Example Window', flags=window_flags", name="text", ) with ui.HStack(width=0): ui.Button("click for Styled Window", width=180, clicked_fn=self.create_styled_window) ui.Spacer(width=20) ui.Label( """ self._style_window_example = ui.Window("Styled Window Example", width=300, height=300) self._style_window_example.frame.set_style({"Window": {"background_color": cl.blue, "border_radius": 10, "border_width": 5, "border_color": cl.red}) with self._style_window_example.frame: with ui.VStack(): ui.Button("I am a Styled Window") ui.Button("Style is attached to 'Window'", height=200)""", name="text", ) self._text("All the Window Flags") self._text( """ WINDOW_FLAGS_NONE WINDOW_FLAGS_NO_TITLE_BAR WINDOW_FLAGS_NO_RESIZE WINDOW_FLAGS_NO_MOVE WINDOW_FLAGS_NO_SCROLLBAR WINDOW_FLAGS_NO_COLLAPSE WINDOW_FLAGS_NO_SAVED_SETTINGS WINDOW_FLAGS_SHOW_HORIZONTAL_SCROLLBAR WINDOW_FLAGS_FORCE_VERTICAL_SCROLLBAR WINDOW_FLAGS_FORCE_HORIZONTAL_SCROLLBAR WINDOW_FLAGS_NO_FOCUS_ON_APPEARING WINDOW_FLAGS_NO_CLOSE """ ) self._text("Available Window Properties, call can be used in the constructor") self._text( """ title : set the title for the window visible: set the window to be visible or not frame: read only property to get the frame of the window padding_x: padding on the window around the Frame padding_y: padding on the window around the Frame flags: the window flags, not that you can pass then on the constructor but also change them after ! """ ) self._caption("ToolBar", navigate_to) with ui.ScrollingFrame(height=60, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF): with ui.VStack(height=0): with ui.HStack(width=0): ui.Button("ToolBar Example", width=180, clicked_fn=self.create_simple_toolbar) ui.Label("this create a ToolBar Docked at the top", name="text", width=280) ui.Label("""ui.ToolBar("Awesome ToolBar", noTabBar=True)""", name="text") with ui.HStack(width=0): ui.Button("Axis changing ToolBar Example", width=180, clicked_fn=self.create_rotating_toolbar) ui.Label("see how the orientation of the toolbar can change", name="text", width=280) ui.Label("""ui.ToolBar("Awesome ToolBar")""", name="text") self._text( "This file contain a very complete example of many type of toolbar\n" "location is " + __file__ + "\n" ) self._caption("Multiple Modal Windows", navigate_to) self._text( "Omni::UI supports the conception of multiple modal windows. When the new modal window is created, it " "makes other modal windows inactive. And when it's destroyed, the previous modal window becomes active, " "blocking all other windows." ) ui.Button("Multiple Modal Windows", clicked_fn=self._on_modal_in_modal_clicked) self._caption("Overlay Other Windows", navigate_to) self._text( "When creating two windows with the same title, only one window will be displayed, and it will contain " "the widgets from both windows. This ability allows for overlaying omni.ui Widgets to any ImGui window. " "For example, it's possible to add a button to the viewport with creating a new window with the title " '"Viewport".' ) def overlay_viewport(self): self._overlay_window = None def create_overlay_window(self): if self._overlay_window: self._overlay_window = None else: self._overlay_window = ui.Window("Viewport") with self._overlay_window.frame: with ui.HStack(): ui.Spacer() ui.Label("Hello World", width=0) ui.Spacer() self._overaly_button = ui.Button( "Create or Remove Viewport Label", style=self._style_system, clicked_fn=lambda: create_overlay_window(self), ) overlay_viewport(self) self._code(inspect.getsource(overlay_viewport).split("\n", 1)[-1]) self._caption("Workspace", navigate_to) class WindowItem(ui.AbstractItem): def __init__(self, window): super().__init__() # Don't keep the window because it prevents the window from closing. self._window_title = window.title self.title_model = ui.SimpleStringModel(self._window_title) self.type_model = ui.SimpleStringModel(type(window).__name__) @property def window(self): return ui.Workspace.get_window(self._window_title) class WindowModel(ui.AbstractItemModel): def __init__(self): super().__init__() self._root = ui.SimpleStringModel("Windows") self.update() def update(self): self._children = [WindowItem(i) for i in ui.Workspace.get_windows()] self._item_changed(None) def get_item_children(self, item): if item is not None: return [] return self._children def get_item_value_model_count(self, item): return 2 def get_item_value_model(self, item, column_id): if item is None: return self._root if column_id == 0: return item.title_model if column_id == 1: return item.type_model self._window_model = WindowModel() self._tree_left = None self._tree_right = None with ui.VStack(style=self._style_system): ui.Button("Refresh", clicked_fn=lambda: self._window_model.update()) with ui.HStack(): ui.Button("Clear", clicked_fn=ui.Workspace.clear) ui.Button("Focus", clicked_fn=lambda: self._focus(self._tree_left.selection)) with ui.HStack(): ui.Button("Visibile", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, True)) ui.Button("Invisibile", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, False)) ui.Button("Toggle Visibility", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, None)) with ui.HStack(): ui.Button( "Dock Right", clicked_fn=lambda: self._dock( self._tree_left.selection, self._tree_right.selection, ui.DockPosition.RIGHT ), ) ui.Button( "Dock Left", clicked_fn=lambda: self._dock( self._tree_left.selection, self._tree_right.selection, ui.DockPosition.LEFT ), ) ui.Button( "Dock Top", clicked_fn=lambda: self._dock( self._tree_left.selection, self._tree_right.selection, ui.DockPosition.TOP ), ) ui.Button( "Dock Bottom", clicked_fn=lambda: self._dock( self._tree_left.selection, self._tree_right.selection, ui.DockPosition.BOTTOM ), ) ui.Button( "Dock Same", clicked_fn=lambda: self._dock( self._tree_left.selection, self._tree_right.selection, ui.DockPosition.SAME ), ) ui.Button("Undock", clicked_fn=lambda: self._undock(self._tree_left.selection)) with ui.HStack(): ui.Button("Move Left", clicked_fn=lambda: self._left(self._tree_left.selection)) ui.Button("MoveRight", clicked_fn=lambda: self._right(self._tree_left.selection)) with ui.HStack(): ui.Button( "Reverse Docking Tabs of Neighbours", clicked_fn=lambda: self._dock_reorder(self._tree_left.selection), ) ui.Button("Hide Tabs", clicked_fn=lambda: self._tabs(self._tree_left.selection, False)) ui.Button("Show Tabs", clicked_fn=lambda: self._tabs(self._tree_left.selection, True)) with ui.HStack(height=400): with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", ): self._tree_left = ui.TreeView(self._window_model, column_widths=[ui.Fraction(1), 80]) with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", ): self._tree_right = ui.TreeView(self._window_model, column_widths=[ui.Fraction(1), 80]) self._caption("Popup", navigate_to) self._text( "The Popup window is a window that disappears when the user clicks outside of the window. To create a popup " "window, it's necessary to use the flag ui.WINDOW_FLAGS_POPUP. It's very useful for creating a menu with " "custom widgets inside." ) self._text("Start typing for popup") popup_example(self) self._code(inspect.getsource(popup_example).split("\n", 1)[-1]) # some padding at the bottom ui.Spacer(height=100) def _undock(self, selection): if not selection: return for item in selection: item.window.undock() def _dock(self, left, right, position): if not left or not right: return target = right[0].window for item in left: item.window.dock_in(target, position) def _left(self, selection): if not selection: return for item in selection: item.window.position_x -= 100 def _right(self, selection): if not selection: return for item in selection: item.window.position_x += 100 def _set_visibility(self, selection, visible): if not selection: return for item in selection: if visible is not None: item.window.visible = visible else: item.window.visible = not item.window.visible def _dock_reorder(self, selection): if not selection: return docking_groups = [ui.Workspace.get_docked_neighbours(item.window) for item in selection] for group in docking_groups: # Reverse order for i, window in enumerate(reversed(group)): window.dock_order = i def _on_modal_in_modal_clicked(self): def close_me(id): self._modal_test[id].visible = False def put_on_front(id): if not self._modal_test[id]: return self._modal_test[id].set_top_modal() def toggle(id): if not self._modal_test[id]: return self._modal_test[id].visible = not self._modal_test[id].visible window_id = len(self._modal_test) prev_id = max(0, window_id - 1) window_flags = ui.WINDOW_FLAGS_NO_RESIZE window_flags |= ui.WINDOW_FLAGS_NO_SCROLLBAR window_flags |= ui.WINDOW_FLAGS_MODAL modal_window = ui.Window(f"Modal Window #{window_id}", width=200, height=200, flags=window_flags) self._modal_test.append(modal_window) with modal_window.frame: with ui.VStack(height=0): ui.Label(f"This is the window #{window_id}") ui.Button("One Modal More", clicked_fn=self._on_modal_in_modal_clicked) ui.Button(f"Bring #{prev_id} To Top", clicked_fn=lambda id=prev_id: put_on_front(id)) ui.Button(f"Toggle visibility of #{prev_id}", clicked_fn=lambda id=prev_id: toggle(id)) ui.Button("Close", clicked_fn=lambda id=window_id: close_me(id))
31,379
Python
40.618037
121
0.541445
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/image_doc.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. # """The documentation for Images""" from omni import ui from .doc_page import DocPage import inspect SPACING = 5 def image_hot_switch(): styles = [ { "": {"image_url": "resources/icons/Nav_Walkmode.png"}, ":hovered": {"image_url": "resources/icons/Nav_Flymode.png"}, }, { "": {"image_url": "resources/icons/Move_local_64.png"}, ":hovered": {"image_url": "resources/icons/Move_64.png"}, }, { "": {"image_url": "resources/icons/Rotate_local_64.png"}, ":hovered": {"image_url": "resources/icons/Rotate_global.png"}, }, ] def set_image(model, image): value = model.get_item_value_model().get_value_as_int() image.set_style(styles[value]) image = ui.Image(width=64, height=64, style=styles[0]) with ui.HStack(width=ui.Percent(50)): ui.Label("Select a texture to display", name="text") model = ui.ComboBox(0, "Navigation", "Move", "Rotate").model model.add_item_changed_fn(lambda m, i, im=image: set_image(m, im)) class ImageDoc(DocPage): """ document for Image""" def create_doc(self, navigate_to=None): self._section_title("Image") self._text("The Image type displays an image.") self._text("The source of the image is specified as a URL using the source property.") self._text( "By default, specifying the width and height of the item causes the image to be scaled to that size. This " "behavior can be changed by setting the fill_mode property, allowing the image to be stretched or scaled " "instead. The property alignment controls where to align the scaled image." ) code_width = 320 image_source = "resources/desktop-icons/omniverse_512.png" with ui.VStack(): self._image_table( f"""ui.Image( '{image_source}', fill_policy=ui.FillPolicy.STRETCH)""", "(Default) The image is scaled to fit, the alignment is ignored", code_width=code_width, ) self._image_table( f"""ui.Image( '{image_source}', fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, alignment=ui.Alignment.LEFT_CENTER)""", "The image is scaled uniformly to fit without cropping and aligned to the left", code_width=code_width, ) self._image_table( f"""ui.Image( '{image_source}', fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, alignment=ui.Alignment.CENTER)""", "The image is scaled uniformly to fit without cropping and aligned to the center", code_width=code_width, ) self._image_table( f"""ui.Image( '{image_source}', fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, alignment=ui.Alignment.RIGHT_CENTER)""", "The image is scaled uniformly to fit without croppingt and aligned to right", code_width=code_width, ) self._image_table( f"""ui.Image( '{image_source}', fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, alignment=ui.Alignment.CENTER_TOP)""", "The image is scaled uniformly to fill, cropping if necessary and aligned to the top", code_width=code_width, ) self._image_table( f"""ui.Image( '{image_source}', fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, alignment=ui.Alignment.CENTER)""", "The image is scaled uniformly to fill, cropping if necessary and centered", code_width=code_width, ) self._image_table( f"""ui.Image( '{image_source}', fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, alignment=ui.Alignment.CENTER_BOTTOM)""", "The image is scaled uniformly to fill, cropping if necessary and aligned to the bottom", code_width=code_width, ) self._image_table( f"""ui.Image( '{image_source}', fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, alignment=ui.Alignment.CENTER, style={{'border_radius': 10}})""", "The image has rounded corners", code_width=code_width, ) ui.Spacer(height=20) ui.Line() ui.Spacer(height=10) self._text("The Image can use style image_url") ui.Spacer(height=10) ui.Line() ui.Spacer(height=20) code_width = 470 self._image_table( f"""ui.Image(style={{'image_url': 'resources/desktop-icons/omniverse_128.png'}})""", "The image has a styled URL", code_width=code_width, ) self._image_table( f"""with ui.HStack(spacing =5, style={{"Image":{{'image_url': 'resources/desktop-icons/omniverse_128.png'}}}}): ui.Image() ui.Image() ui.Image() """, "The image has a styled URL", code_width=code_width, ) self._image_table( f"""ui.Image(style={{ 'image_url': 'resources/desktop-icons/omniverse_128.png', 'alignment': ui.Alignment.RIGHT_CENTER}})""", "The image has styled Alignment", code_width=code_width, ) self._image_table( f"""ui.Image(style={{ 'image_url': 'resources/desktop-icons/omniverse_256.png', 'fill_policy': ui.FillPolicy.PRESERVE_ASPECT_CROP, 'alignment': ui.Alignment.RIGHT_CENTER}})""", "The image has styled fill_policy", code_width=code_width, ) self._text( "It's possible to set a different image per style state. And switch them depending on the mouse hovering, " "selection state, etc." ) image_hot_switch() self._code(inspect.getsource(image_hot_switch).split("\n", 1)[-1]) ui.Spacer(height=10)
7,160
Python
39.005586
119
0.525978
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/layout_doc.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. # """The documentation for Layouts""" from omni import ui from omni.ui import color as cl from .doc_page import DocPage import inspect import asyncio import omni.kit.app SPACING = 5 def collapsable_simple(): with ui.CollapsableFrame("Header"): with ui.VStack(height=0): ui.Button("Hello World") ui.Button("Hello World") def collapsable_custom(style_system): def custom_header(collapsed, title): with ui.HStack(style=style_system): with ui.ZStack(width=30): ui.Circle(name="title") with ui.HStack(): ui.Spacer() align = ui.Alignment.V_CENTER ui.Line(name="title", width=6, alignment=align) ui.Spacer() if collapsed: with ui.VStack(): ui.Spacer() align = ui.Alignment.H_CENTER ui.Line(name="title", height=6, alignment=align) ui.Spacer() ui.Label(title, name="title") style = { "CollapsableFrame": { "background_color": cl.transparent, "secondary_color": cl.transparent, "border_radius": 0, "border_color": cl("#B2B2B2"), "border_width": 0.5, }, "CollapsableFrame:hovered": {"secondary_color": cl("#E5F1FB")}, "CollapsableFrame:pressed": {"secondary_color": cl("#CCE4F7")}, "Label::title": {"color": cl.black}, "Circle::title": { "color": cl.black, "background_color": cl.transparent, "border_color": cl("#B2B2B2"), "border_width": 0.75, }, "Line::title": {"color": cl("#666666"), "border_width": 1}, } style.update(style_system) with ui.CollapsableFrame("Header", build_header_fn=custom_header, style=style): with ui.VStack(height=0): ui.Button("Hello World") ui.Button("Hello World") def collapsable_layout(style_system): style = { "CollapsableFrame": { "border_color": cl("#005B96"), "border_radius": 4, "border_width": 2, "padding": 0, "margin": 0, } } frame = ui.CollapsableFrame("Header", style=style) with frame: with ui.VStack(height=0): ui.Button("Hello World") ui.Button("Hello World") def set_style(field, model, style=style, frame=frame): frame_style = style["CollapsableFrame"] frame_style[field] = model.get_value_as_float() frame.set_style(style) with ui.HStack(): ui.Label("Padding:", width=ui.Percent(10), name="text") model = ui.FloatSlider(min=0, max=50).model model.add_value_changed_fn(lambda m: set_style("padding", m)) with ui.HStack(): ui.Label("Margin:", width=ui.Percent(10), name="text") model = ui.FloatSlider(min=0, max=50).model model.add_value_changed_fn(lambda m: set_style("margin", m)) def direction(): def rotate(dirs, stack, label): dirs[0] = (dirs[0] + 1) % len(dirs[1]) stack.direction = dirs[1][dirs[0]] label.text = str(stack.direction) dirs = [ 0, [ ui.Direction.LEFT_TO_RIGHT, ui.Direction.RIGHT_TO_LEFT, ui.Direction.TOP_TO_BOTTOM, ui.Direction.BOTTOM_TO_TOP, ], ] stack = ui.Stack(ui.Direction.LEFT_TO_RIGHT, width=0, height=0) with stack: for name in ["One", "Two", "Three", "Four"]: ui.Button(name) with ui.HStack(): with ui.HStack(): ui.Label("Current direcion is ", name="text", width=0) label = ui.Label("", name="text") button = ui.Button("Change") button.set_clicked_fn(lambda d=dirs, s=stack, l=label: rotate(d, s, l)) rotate(dirs, stack, label) def recreate(self): self._recreate_ui = ui.Frame(height=40) def changed(model, recreate_ui=self._recreate_ui): with recreate_ui: with ui.HStack(): for i in range(model.get_value_as_int()): ui.Button(f"Button #{i}") model = ui.IntDrag(min=0, max=10).model self._sub_recreate = model.subscribe_value_changed_fn(changed) def clipping(self): self._clipping_frame = ui.Frame() with self._clipping_frame: ui.Button("Hello World") def set_width(model): self._clipping_frame.width = ui.Pixel(model.as_float) def set_height(model): self._clipping_frame.height = ui.Pixel(model.as_float) def set_hclipping(model): self._clipping_frame.horizontal_clipping = model.as_bool def set_vclipping(model): self._clipping_frame.horizontal_clipping = model.as_bool width = ui.FloatDrag(min=50, max=1000).model height = ui.FloatDrag(min=50, max=1000).model hclipping = ui.ToolButton(text="HClipping").model vclipping = ui.ToolButton(text="VClipping").model self._width = width.subscribe_value_changed_fn(set_width) self._height = height.subscribe_value_changed_fn(set_height) self._hclipping = hclipping.subscribe_value_changed_fn(set_hclipping) self._vclipping = vclipping.subscribe_value_changed_fn(set_vclipping) width.set_value(100) height.set_value(100) def visibility(): def invisible(button): button.visible = False def visible(buttons): for button in buttons: button.visible = True buttons = [] with ui.HStack(): for n in ["One", "Two", "Three", "Four", "Five"]: button = ui.Button(n, width=0) button.set_clicked_fn(lambda b=button: invisible(b)) buttons.append(button) ui.Spacer() button = ui.Button("Visible all", width=0) button.set_clicked_fn(lambda b=buttons: visible(b)) def vgrid(): with ui.ScrollingFrame( height=425, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ): with ui.VGrid(column_width=100, row_height=100): for i in range(100): with ui.ZStack(): ui.Rectangle( style={ "border_color": cl.black, "background_color": cl.white, "border_width": 1, "margin": 0, } ) ui.Label(f"{i}", style={"margin": 5}) def hgrid(): with ui.ScrollingFrame( height=425, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, ): with ui.HGrid(column_width=100, row_height=100): for i in range(100): with ui.ZStack(): ui.Rectangle( style={ "border_color": cl.black, "background_color": cl.white, "border_width": 1, "margin": 0, } ) ui.Label(f"{i}", style={"margin": 5}) def placer_track(self, id): # Initial size BEGIN = 50 + 100 * id END = 120 + 100 * id HANDLE_WIDTH = 10 class EditScope: """The class to avoid circular event calling""" def __init__(self): self.active = False def __enter__(self): self.active = True def __exit__(self, type, value, traceback): self.active = False def __bool__(self): return not self.active class DoLater: """A helper to collect data and process it one frame later""" def __init__(self): self.__task = None self.__data = [] def do(self, data): # Collect data self.__data.append(data) # Update in the next frame. We need it because we want to accumulate the affected prims if self.__task is None or self.__task.done(): self.__task = asyncio.ensure_future(self.__delayed_do()) async def __delayed_do(self): # Wait one frame await omni.kit.app.get_app().next_update_async() print(f"In the previous frame the user clicked the rectangles: {self.__data}") self.__data.clear() self.edit = EditScope() self.dolater = DoLater() def start_moved(start, body, end): if not self.edit: # Something already edits it return with self.edit: body.offset_x = start.offset_x rect.width = ui.Pixel(end.offset_x - start.offset_x + HANDLE_WIDTH) def body_moved(start, body, end, rect): if not self.edit: # Something already edits it return with self.edit: start.offset_x = body.offset_x end.offset_x = body.offset_x + rect.width.value - HANDLE_WIDTH def end_moved(start, body, end, rect): if not self.edit: # Something already edits it return with self.edit: body.offset_x = start.offset_x rect.width = ui.Pixel(end.offset_x - start.offset_x + HANDLE_WIDTH) with ui.ZStack(height=30): # Body body = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=BEGIN) with body: rect = ui.Rectangle(width=END - BEGIN + HANDLE_WIDTH) rect.set_mouse_pressed_fn(lambda x, y, b, m, id=id: self.dolater.do(id)) # Left handle start = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=BEGIN) with start: ui.Rectangle(width=HANDLE_WIDTH, style={"background_color": cl("#FF660099")}) # Right handle end = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=END) with end: ui.Rectangle(width=HANDLE_WIDTH, style={"background_color": cl("#FF660099")}) # Connect them together start.set_offset_x_changed_fn(lambda _, s=start, b=body, e=end: start_moved(s, b, e)) body.set_offset_x_changed_fn(lambda _, s=start, b=body, e=end, r=rect: body_moved(s, b, e, r)) end.set_offset_x_changed_fn(lambda _, s=start, b=body, e=end, r=rect: end_moved(s, b, e, r)) def placer_percents(self): # The size of the rectangle SIZE = 20.0 with ui.ZStack(height=300): # Background ui.Rectangle(style={"background_color": cl("#999999")}) # Small rectangle p = ui.Percent(50) placer = ui.Placer(draggable=True, offset_x=p, offset_y=p) with placer: ui.Rectangle(width=SIZE, height=SIZE) def clamp_x(offset): if offset.value < 0: placer.offset_x = ui.Percent(0) max_per = 100.0 - SIZE / placer.computed_width * 100.0 if offset.value > max_per: placer.offset_x = ui.Percent(max_per) def clamp_y(offset): if offset.value < 0: placer.offset_y = ui.Percent(0) max_per = 100.0 - SIZE / placer.computed_height * 100.0 if offset.value > max_per: placer.offset_y = ui.Percent(max_per) # Calbacks placer.set_offset_x_changed_fn(clamp_x) placer.set_offset_y_changed_fn(clamp_y) class LayoutDoc(DocPage): """ document Layout classes""" def create_doc(self, navigate_to=None): self._section_title("Layout") self._text("We have three main components: VStack, HStack, and ZStack.") self._caption("HStack", navigate_to) self._text("This class is used to construct horizontal layout objects.") with ui.HStack(): ui.Button("One") ui.Button("Two") ui.Button("Three") ui.Button("Four") ui.Button("Five") self._text("The simplest use of the class is like this:") self._code( """ with ui.HStack(): ui.Button("One") ui.Button("Two") ui.Button("Three") ui.Button("Four") ui.Button("Five") """ ) self._caption("VStack", navigate_to) self._text("The VStack class lines up widgets vertically.") with ui.VStack(width=100.0): with ui.VStack(): ui.Button("One") ui.Button("Two") ui.Button("Three") ui.Button("Four") ui.Button("Five") self._text("The simplest use of the class is like this:") self._code( """ with ui.VStack(): ui.Button("One") ui.Button("Two") ui.Button("Three") ui.Button("Four") ui.Button("Five") """ ) self._caption("ZStack", navigate_to) self._text("A view that overlays its children, aligning them on top of each other.") with ui.VStack(width=100.0): with ui.ZStack(): ui.Button("Very Long Text to See How Big it Can Be", height=0) ui.Button("Another\nMultiline\nButton", width=0) self._code( """ with ui.ZStack(): ui.Button("Very Long Text to See How Big it Can Be", height=0) ui.Button("Another\\nMultiline\\nButton", width=0) """ ) self._caption("Spacing", navigate_to) self._text("Spacing is a non-stretchable space in pixels between child items of the layout.") def set_spacing(stack, spacing): stack.spacing = spacing spacing_stack = ui.HStack(style={"margin": 0}) with spacing_stack: for name in ["One", "Two", "Three", "Four"]: ui.Button(name) with ui.HStack(spacing=SPACING): with ui.HStack(width=100): ui.Spacer() ui.Label("spacing", width=0, name="text") with ui.HStack(width=ui.Percent(20)): field = ui.FloatField(width=50) slider = ui.FloatSlider(min=0, max=50, style={"color": cl.transparent}) # Link them together slider.model = field.model slider.model.add_value_changed_fn(lambda m, s=spacing_stack: set_spacing(s, m.get_value_as_float())) self._code( """ def set_spacing(stack, spacing): stack.spacing = spacing ui.Spacer(height=SPACING) spacing_stack = ui.HStack(style={"margin": 0}) with spacing_stack: for name in ["One", "Two", "Three", "Four"]: ui.Button(name) ui.Spacer(height=SPACING) with ui.HStack(spacing=SPACING): with ui.HStack(width=100): ui.Spacer() ui.Label("spacing", width=0, name="text") with ui.HStack(width=ui.Percent(20)): field = ui.FloatField(width=50) slider = ui.FloatSlider(min=0, max=50, style={"color": cl.transparent}) # Link them together slider.model = field.model slider.model.add_value_changed_fn( lambda m, s=spacing_stack: set_spacing(s, m.get_value_as_float())) """ ) self._caption("VGrid", navigate_to) self._text( "Grid is a container that arranges its child views in a grid. The grid vertical/horizontal direction is " "the direction the grid size growing with creating more children." ) self._text("It has two modes for cell width.") self._text(" - If the user set column_count, the column width is computed from the grid width.") self._text(" - If the user sets column_width, the column count is computed.") self._text("It also has two modes for height.") self._text( " - If the user sets row_height, VGrid uses it to set the height for all the cells. It's the fast mode " "because it's considered that the cell height never changes. VGrid easily predict which cells are visible." ) self._text( " - If the user sets nothing, VGrid computes the size of the children. This mode is slower than the " "previous one, but the advantage is that all the rows can be different custom sizes. VGrid still draws " "only visible items, but to predict it, it uses cache, which can be big if VGrid has hundreds of " "thousands of items." ) vgrid() self._code(inspect.getsource(vgrid).split("\n", 1)[-1]) self._caption("HGrid", navigate_to) self._text("HGrid works exactly like VGrid, but with swapped width and height..") hgrid() self._code(inspect.getsource(hgrid).split("\n", 1)[-1]) self._caption("Frame", navigate_to) self._text( "Frame is a container that can keep only one child. Each child added to Frame overrides the previous one. " "This feature is used for creating dynamic layouts. The whole layout can be easily recreated with a " "simple callback. In the following example, the buttons are recreated each time the slider changes." ) recreate(self) self._code(inspect.getsource(recreate).split("\n", 1)[-1]) self._text( "Another feature of Frame is the ability to clip its child. When the content of Frame is bigger than " "Frame itself, the exceeding part is not drawn if the clipping is on." ) clipping(self) self._code(inspect.getsource(clipping).split("\n", 1)[-1]) self._caption("CollapsableFrame", navigate_to) self._text( "CollapsableFrame is a frame widget that can hide or show its content. It has two states expanded and " "collapsed. When it's collapsed, it looks like a button. If it's expanded, it looks like a button and a " "frame with the content. It's handy to group properties, and temporarily hide them to get more space for " "something else." ) collapsable_simple() self._code(inspect.getsource(collapsable_simple).split("\n", 1)[-1]) self._text("It's possible to use a custom header.") collapsable_custom(self._style_system) self._code(inspect.getsource(collapsable_custom).split("\n", 1)[-1]) self._text("The next example demonstrates how padding and margin work in the collapsable frame.") collapsable_layout(self._style_system) self._code(inspect.getsource(collapsable_layout).split("\n", 1)[-1]) self._caption("Examples", navigate_to) with ui.VStack(style=self._style_system): for i in range(2): with ui.HStack(): ui.Spacer(width=50) with ui.VStack(height=0): ui.Button("Left {}".format(i), height=0) ui.Button("Vertical {}".format(i), height=50) with ui.HStack(width=ui.Fraction(2)): ui.Button("Right {}".format(i)) ui.Button("Horizontal {}".format(i), width=ui.Fraction(2)) ui.Spacer(width=50) self._code( """ with ui.VStack(): for i in range(2): with ui.HStack(): ui.Spacer() with ui.VStack(height=0): ui.Button("Left {}".format(i), height=0) ui.Button("Vertical {}".format(i), height=50) with ui.HStack(width=ui.Fraction(2)): ui.Button("Right {}".format(i)) ui.Button("Horizontal {}".format(i), width=ui.Fraction(2)) ui.Spacer() """ ) self._caption("Placer", navigate_to) self._text( "Enable you to place a widget presisely with offset. Placer's property `draggable` allows changing " "the position of the child widget with dragging it with the mouse." ) with ui.ScrollingFrame( height=170, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, ): with ui.ZStack(): with ui.HStack(): for index in range(60): ui.Line(width=10, style={"color": cl.black, "border_width": 0.5}, alignment=ui.Alignment.LEFT) with ui.VStack(): ui.Line( height=10, width=600, style={"color": cl.black, "border_width": 0.5}, alignment=ui.Alignment.TOP, ) for index in range(15): ui.Line( height=10, width=600, style={"color": cl.black, "border_width": 0.5}, alignment=ui.Alignment.TOP, ) ui.Line( height=10, width=600, style={"color": cl.black, "border_width": 0.5}, alignment=ui.Alignment.TOP, ) with ui.Placer(offset_x=100, offset_y=10): ui.Button("moved 100px in X, and 10px in Y", width=0, height=20, name="placed") with ui.Placer(offset_x=200, offset_y=50): ui.Button("moved 200px X , and 50 Y", width=0, height=0) def set_text(widget, text): widget.text = text with ui.Placer(draggable=True, offset_x=300, offset_y=100): ui.Circle(radius=50, width=50, height=50, size_policy=ui.CircleSizePolicy.STRETCH, name="placed") placer = ui.Placer(draggable=True, drag_axis=ui.Axis.Y, offset_x=400, offset_y=120) with placer: with ui.ZStack(width=150, height=40): ui.Rectangle(name="placed") with ui.HStack(spacing=5): ui.Circle( radius=3, width=15, size_policy=ui.CircleSizePolicy.FIXED, style={"background_color": cl.white}, ) ui.Label("UP / Down", style={"color": cl.white, "font_size": 16.0}) offset_label = ui.Label("120", style={"color": cl.white}) placer.set_offset_y_changed_fn(lambda o: set_text(offset_label, str(o))) self._code( """ with ui.Placer( draggable=True, offset_x=300, offset_y=100): ui.Circle( radius=50, width=50, height=50, size_policy=ui.CircleSizePolicy.STRETCH, name="placed" ) placer = ui.Placer( draggable=True, drag_axis=ui.Axis.Y, offset_x=400, offset_y=120) with placer: with ui.ZStack( width=150, height=40, ): ui.Rectangle(name="placed") with ui.HStack(spacing=5): ui.Circle( radius=3, width=15, size_policy=ui.CircleSizePolicy.FIXED, style={"background_color": cl.white}, ) ui.Label( "UP / Down", style={ "color": cl.white, "font_size": 16.0 } ) offset_label = ui.Label( "120", style={"color": cl.white}) placer.set_offset_y_changed_fn( lambda o: set_text(offset_label, str(o))) """ ) self._text( "The following example shows the way to interact between three Placers to create a resizable rectangle. " "The rectangle can be moved on X-axis and can be resized with small side handles." ) self._text( "When multiple widgets fire the callbacks simultaneously, it's possible to collect the event data and " "process them one frame later using asyncio." ) with ui.ZStack(): placer_track(self, 0) placer_track(self, 1) self._code(inspect.getsource(placer_track).split("\n", 1)[-1]) self._text( "It's possible to set `offset_x` and `offset_y` in percents. It allows stacking the children to the " "proportions of the parent widget. If the parent size is changed, then the offset is updated accordingly." ) placer_percents(self) self._code(inspect.getsource(placer_percents).split("\n", 1)[-1]) self._caption("Visibility", navigate_to) self._text( "This property holds whether the widget is visible. Invisible widget is not rendered, and it doesn't take " "part in the layout. The layout skips it." ) self._text("In the following example click the button to hide it.") visibility() self._code(inspect.getsource(visibility).split("\n", 1)[-1]) self._caption("Direction", navigate_to) self._text( "It's possible to determine the direction of a stack with the property direction. The stack is able to " "change its direction dynamically." ) direction() self._code(inspect.getsource(direction).split("\n", 1)[-1]) ui.Spacer(height=50)
26,307
Python
34.647696
119
0.541415
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/canvas_frame_doc.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. # """The documentation for Scrolling Frame""" from omni import ui from .doc_page import DocPage import inspect SPACING = 5 TEXT = ( "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut " "labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco " "laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in " "voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat " "non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." ) def simple_canvasframe(): IMAGE = "resources/icons/ov_logo_square.png" with ui.CanvasFrame(height=256): with ui.VStack(height=0, spacing=10): ui.Label(TEXT, name="text", word_wrap=True) ui.Button("Button") ui.Image(IMAGE, width=128, height=128) class CanvasFrameDoc(DocPage): """ document for Menu""" def create_doc(self, navigate_to=None): self._section_title("CanvasFrame") self._text( "CanvasFrame is the widget that allows the user to pan and zoom its children with a mouse. It has the layout " "that can be infinitely moved in any direction." ) with ui.Frame(style=self._style_system): simple_canvasframe() self._code(inspect.getsource(simple_canvasframe).split("\n", 1)[-1]) ui.Spacer(height=10)
1,903
Python
35.615384
122
0.705202
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/doc_page.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. # """The documentation of the omni.ui aka UI Framework""" # Add imports here that are needed in the _exec_code calls. from omni import ui from omni.ui import color as cl import omni.usd from pxr import Usd from pxr import UsdGeom import subprocess import sys SPACING = 5 class DocPage: """The Demo extension""" def __init__(self, extension_path): self._extension_path = extension_path self._style_system = { "Button": { "background_color": 0xFFE1E1E1, "border_color": 0xFFADADAD, "border_width": 0.5, "border_radius": 0.0, "margin": 5.0, "padding": 5.0, }, "Button.Label": {"color": 0xFF000000}, "Button:hovered": {"background_color": 0xFFFBF1E5, "border_color": 0xFFD77800}, "Button:pressed": {"background_color": 0xFFF7E4CC, "border_color": 0xFF995400, "border_width": 1.0}, } self._copy_context_menu = ui.Menu("Copy Context menu", name="this") def clean(self): """Should be called when the extesion us unloaded or reloaded""" pass def _show_copy_menu(self, x, y, button, modifier, text): """The context menu to copy the text""" # Display context menu only if the right button is pressed if button != 1: return def copy_text(text_value): # we need to find a cross plartform way currently Window Only subprocess.run(["clip.exe"], input=text_value.strip().encode("utf-8"), check=True) # Reset the previous context popup self._copy_context_menu.clear() with self._copy_context_menu: ui.MenuItem("Copy Code", triggered_fn=lambda t=text: copy_text(t)) # Show it self._copy_context_menu.show() def create_doc(self, navigate_to=None): """ Class should overide this methods. Args: navigate_to: The chapter it's necessary to navigate the scrollbar. """ pass def _text(self, text): """Create a formated paragraph of the text""" ui.Label(text, name="text", word_wrap=True, skip_draw_when_clipped=True) def _section_title(self, text): """Create a title separator""" with ui.ZStack(): ui.Rectangle(name="section") ui.Label(text, name="section", alignment=ui.Alignment.CENTER) def _caption(self, text, navigate_to=None): """Create a formated heading""" with ui.ZStack(): background = ui.Rectangle(name="caption") if navigate_to == text: background.scroll_here_y(0.0) ui.Label(text, name="caption", alignment=ui.Alignment.LEFT_CENTER) def _code(self, text, elided_text=False): """Create a code snippet""" stack = ui.ZStack() with stack: ui.Rectangle(name="code") label = ui.Label(text, name="code", skip_draw_when_clipped=True, elided_text=elided_text) if not sys.platform == "linux": stack.set_mouse_pressed_fn(lambda x, y, b, m, text=text: self._show_copy_menu(x, y, b, m, text)) return label def _exec_code(self, code): """Execute the code and create a snippet""" # Python magic to capture output of exec locals_from_execution = {} exec(f"class Execution():\n def __init__(self):\n{code}", None, locals_from_execution) self._first = locals_from_execution["Execution"]() self._code(code) def _image_table(self, code, description, description_width=ui.Fraction(1), code_width=ui.Fraction(1)): """Create a row of the table that demostrates images""" # TODO: We need to use style padding instead of thousands of spacers with ui.HStack(): with ui.ZStack(width=140): ui.Rectangle(name="table") with ui.HStack(): ui.Spacer(width=SPACING / 2) with ui.VStack(): ui.Spacer(height=SPACING / 2) # Execute the provided code exec(code) ui.Spacer(height=SPACING / 2) ui.Spacer(width=SPACING / 2) with ui.ZStack(width=description_width): ui.Rectangle(name="table") with ui.HStack(): ui.Spacer(width=SPACING / 2) ui.Label(description, style={"margin": 5}, name="text", word_wrap=True) ui.Spacer(width=SPACING / 2) with ui.ZStack(width=code_width): ui.Rectangle(name="table") with ui.HStack(): ui.Spacer(width=SPACING / 2) with ui.VStack(): ui.Spacer(height=SPACING / 2) with ui.ZStack(): ui.Rectangle(name="code") ui.Label(f"\n\t{code}\n\n", name="code") ui.Spacer(height=SPACING / 2) ui.Spacer(width=SPACING / 2) def _shape_table(self, code, description, row_height=0): """Create a row of the table that demostrates images""" # TODO: We need to use style padding instead of thousands of spacers with ui.HStack(height=row_height): with ui.ZStack(): ui.Rectangle(name="table") # Execute the provided code with ui.ZStack(name="margin", style={"ZStack::margin": {"margin": SPACING * 2}}): ui.Rectangle(name="code") exec(code) with ui.ZStack(width=ui.Fraction(2)): ui.Rectangle(name="table") ui.Label(description, name="text", style={"margin": SPACING}, word_wrap=True) with ui.ZStack(width=300): ui.Rectangle(name="table") with ui.ZStack(name="margin", style={"ZStack::margin": {"margin": SPACING / 2}}): ui.Rectangle(name="code") ui.Label(f"\n\t{code}\n\n", name="code") def _table(self, selector, example, explanatoin, color=None): """Create a one row of a table""" localStyle = {} if color is not None: localStyle = {"color": color} # TODO: We need to use style padding instead of thousands of spacers with ui.HStack(height=0, style=localStyle): with ui.ZStack(width=100): ui.Rectangle(name="table") with ui.HStack(height=0): ui.Spacer(width=SPACING) ui.Label(selector, name="text") ui.Spacer(width=SPACING) with ui.ZStack(width=120): ui.Rectangle(name="table") with ui.HStack(height=0): ui.Spacer(width=SPACING) ui.Label(example, name="text") ui.Spacer(width=SPACING) with ui.ZStack(): ui.Rectangle(name="table") with ui.HStack(height=0): ui.Spacer(width=SPACING) ui.Label(explanatoin, name="text", word_wrap=True) ui.Spacer(width=SPACING)
7,721
Python
39.857143
112
0.553685
omniverse-code/kit/exts/omni.kit.window.commands/omni/kit/window/commands/main.py
from collections import defaultdict from inspect import isclass from functools import partial import omni.kit.commands import omni.kit.undo from omni import ui from .history import HistoryModel, HistoryDelegate, MainItem from .search import SearchModel, SearchDelegate, CommandItem, Columns class Window: def __init__(self, title, menu_path): self._menu_path = menu_path self._win_history = ui.Window(title, width=700, height=500) self._win_history.set_visibility_changed_fn(self._on_visibility_changed) self._win_search = None self._search_frame = None self._doc_frame = None self._history_delegate = HistoryDelegate() self._search_delegate = SearchDelegate() self._build_ui() omni.kit.commands.subscribe_on_change(self._update_ui) self._update_ui() def on_shutdown(self): self._win_history = None self._win_search = None self._search_frame = None self._doc_frame = None self._history_delegate = None self._search_delegate = None omni.kit.commands.unsubscribe_on_change(self._update_ui) def show(self): self._win_history.visible = True self._win_history.focus() def hide(self): self._win_history.visible = False if self._win_search is not None: self._win_search.visible = False def _on_visibility_changed(self, visible): if not visible: omni.kit.ui.get_editor_menu().set_value(self._menu_path, False) if self._win_search is not None: self._win_search.visible = False def _build_ui(self): with self._win_history.frame: with ui.VStack(): with ui.HStack(height=20): ui.Button("Clear history", width=60, clicked_fn=self._clear_history) ui.Button("Search commands", width=60, clicked_fn=self._show_registered) with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, style_type_name_override="TreeView", ): self._history_model = HistoryModel() self._history_tree_view = ui.TreeView( self._history_model, delegate=self._history_delegate, root_visible=False, style={"TreeView.Item::error": {"color": 0xFF0000BB}}, column_widths=[ui.Fraction(1)], ) self._history_tree_view.set_mouse_double_clicked_fn(self._on_double_click) with ui.HStack(height=20): ui.Label("Generate script to clipboard from:", width=0) ui.Button("Top-level commands", width=60, clicked_fn=partial(self._copy_to_clipboard, False)) ui.Button("Selected commands", width=60, clicked_fn=partial(self._copy_to_clipboard, True)) def _on_double_click(self, x, y, b, m): if len(self._history_tree_view.selection) <= 0: return item = self._history_tree_view.selection[0] if isinstance(item, MainItem): self._history_tree_view.set_expanded(item, not self._history_tree_view.is_expanded(item), False) def _copy_to_clipboard(self, only_selected): omni.kit.clipboard.copy(self._generate_command_script(only_selected)) def _clear_history(self): omni.kit.undo.clear_history() self._history_model._commands_changed() def _show_registered(self): if self._win_search is None: self._win_search = ui.Window( "Search Commands", width=700, height=500, dockPreference=ui.DockPreference.MAIN ) with self._win_search.frame: with ui.VStack(): with ui.HStack(height=20): ui.Label("Find: ", width=0) self._search_field = ui.StringField() self._search_field.model.add_value_changed_fn(lambda _: self._refresh_list()) with ui.HStack(height=300): self._search_frame = ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, style_type_name_override="TreeView", ) with self._search_frame: self._search_tree_model = SearchModel() self._search_tree_view = ui.TreeView( self._search_tree_model, delegate=self._search_delegate, selection_changed_fn=self._on_selection_changed, root_visible=False, header_visible=True, columns_resizable=True, column_widths=[x.width for x in Columns.ORDER], ) self._doc_frame = ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, ) self._refresh_list() self._win_search.visible = True self._win_search.focus() def _on_selection_changed(self, selected_items): with self._doc_frame: with ui.VStack(height=40): for item in selected_items: if isinstance(item, CommandItem): ui.Label(f"{item.command_model.as_string}{item.class_sig}", height=30) ui.Label(f"Documentation:", height=30) if item.doc is None or item.doc == omni.kit.commands.Command.__doc__: ui.Label("\n\t<None>") else: ui.Label(item.doc.strip()) def _update_ui(self): self._history_model._commands_changed() self._refresh_list() # TODO: check if this is called too much def _refresh_list(self): if self._search_frame is None: return search_str = self._search_field.model.get_value_as_string().lower().strip() self._search_tree_model._clear_commands() commands = omni.kit.commands.get_commands() for cmd_list in commands.values(): for command in cmd_list.values(): if search_str == "" or command.__name__.lower().find(search_str) != -1: if self._search_tree_model: class_sig = omni.kit.commands.get_command_class_signature(command.__name__) self._search_tree_model._add_command(CommandItem(command, class_sig)) self._search_tree_view.clear_selection() self._search_tree_model._commands_changed() def _generate_command_script(self, only_selected): history = omni.kit.undo.get_history().values() imports = "import omni.kit.commands\n" code_str = "" arg_imports = defaultdict(set) def parse_module_name(name): if name == "builtins": return nonlocal imports lst = name.split(".") if len(lst) == 1: imports += "import " + name + "\n" else: arg_imports[lst[0]].add(".".join(lst[1:])) def arg_import(val): if isclass(val): parse_module_name(val.__module__) else: parse_module_name(val.__class__.__module__) return val def gen_cmd_str(cmd): if len(cmd.kwargs.items()) > 0: args = ",\n\t".join(["{}={!r}".format(k, arg_import(v)) for k, v in cmd.kwargs.items()]) return f"\nomni.kit.commands.execute('{cmd.name}',\n\t{args})\n" else: return f"\nomni.kit.commands.execute('{cmd.name}')\n" # generate a script executing top-level commands or all selected commands if only_selected: for item in self._history_tree_view.selection: if isinstance(item, MainItem): code_str += gen_cmd_str(item._data) else: for cmd in history: if cmd.level == 0: code_str += gen_cmd_str(cmd) for k, v in arg_imports.items(): imports += f"from {k} import " + ", ".join(v) + "\n" return imports + code_str
8,837
Python
41.085714
113
0.539097
omniverse-code/kit/exts/omni.kit.window.commands/omni/kit/window/commands/search.py
import inspect from pathlib import Path import carb.settings import omni.ext import omni.kit.app from omni import ui class SearchModel(ui.AbstractItemModel): """ Represents the list of commands registered in Kit. It is used to make a single level tree appear like a simple list. """ def __init__(self): super().__init__() self._commands = [] def _clear_commands(self): self._commands = [] def _commands_changed(self): self._item_changed(None) def _add_command(self, item): if item and isinstance(item, CommandItem): self._commands.append(item) def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is None: return self._commands return item.children def get_item_value_model_count(self, item): """The number of columns""" return Columns.get_count() def get_item_value_model(self, item, column_id): """Return value model.""" if item and isinstance(item, CommandItem): return Columns.get_model(item, column_id) class SearchDelegate(ui.AbstractItemDelegate): def __init__(self): super().__init__() self._icon_path = Path(__file__).parent.parent.parent.parent.parent.joinpath("icons") self._style = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" # Read all the svg files in the directory self._icons = {icon.stem: icon for icon in self._icon_path.joinpath(self._style).glob("*.svg")} def build_widget(self, model, item, column_id, level, expanded): value_model = model.get_item_value_model(item, column_id) text = value_model.as_string ui.Label(text, style_type_name_override="TreeView.Item") def build_branch(self, model, item, column_id, level, expanded): """Create a branch widget that opens or closes subtree""" if column_id == 0: with ui.HStack(width=16 * (level + 2), height=0): ui.Spacer() if model.can_item_have_children(item): # Draw the +/- icon image_name = "Minus" if expanded else "Plus" ui.Image( str(self._icons.get(image_name)), width=10, height=10, style_type_name_override="TreeView.Item" ) ui.Spacer(width=4) def build_header(self, column_id): label = Columns.get_label(column_id) ui.Label(label, height=30, width=20) class CommandItem(ui.AbstractItem): """Single item of the model""" def __init__(self, command, class_sig): super().__init__() self.command_model = ui.SimpleStringModel(command.__name__) manager = omni.kit.app.get_app().get_extension_manager() ext_id = manager.get_extension_id_by_module(command.__module__) ext_name = omni.ext.get_extension_name(ext_id) if ext_id else "Unknown" self.extension_model = ui.SimpleStringModel(ext_name) self.undo_model = ui.SimpleBoolModel(hasattr(command, "undo") and inspect.isfunction(command.undo)) self.doc = command.__doc__ or (command.__init__ is not None and command.__init__.__doc__) self.class_sig = class_sig self.children = [] # uncomment these lines if child items are needed later on # if doc is not None: # self.children.append(CommandChildItem(doc)) class CommandChildItem(CommandItem): def __init__(self, arg): super().__init__(str(arg)) self.children = [] class Columns: """ Store UI info about the columns in one place so it's easier to keep in """ class ColumnData: def __init__(self, label, column, width, attrib_name): self.label = label self.column = column self.width = width self.attrib_name = attrib_name Command = ColumnData("Command", 0, ui.Fraction(1), "command_model") Extension = ColumnData("Extension", 1, ui.Pixel(200), "extension_model") CanUndo = ColumnData("Can Undo", 2, ui.Pixel(80), "undo_model") ORDER = [Command, Extension, CanUndo] @classmethod def get_count(cls): return len(cls.ORDER) @classmethod def get_label(cls, index): return cls.ORDER[index].label @classmethod def get_model(cls, entry: CommandItem, index): return getattr(entry, cls.ORDER[index].attrib_name)
4,521
Python
33.519084
119
0.610263
omniverse-code/kit/exts/omni.kit.window.commands/omni/kit/window/commands/extension.py
import carb.settings import omni.ext import omni.kit.ui from .main import Window EXTENSION_NAME = "Commands" class Extension(omni.ext.IExt): def on_startup(self): self._menu_path = f"Window/{EXTENSION_NAME}" self._window = None open_by_default = carb.settings.get_settings().get("exts/omni.kit.window.commands/windowOpenByDefault") self._menu = omni.kit.ui.get_editor_menu().add_item( self._menu_path, self._on_menu_click, True, value=open_by_default ) if open_by_default: self._on_menu_click(None, True) def on_shutdown(self): if self._window is not None: self._window.on_shutdown() self._menu = None self._window = None def _on_menu_click(self, menu, toggled): if toggled: if self._window is None: self._window = Window(EXTENSION_NAME, self._menu_path) else: self._window.show() else: if self._window is not None: self._window.hide()
1,062
Python
28.527777
111
0.582863
omniverse-code/kit/exts/omni.kit.window.commands/omni/kit/window/commands/history.py
from pathlib import Path import carb.settings from omni import ui import omni.kit.undo class HistoryData: def __init__(self): self._data = omni.kit.undo.get_history() if len(self._data): self._curr = next(iter(self._data)) self._last = next(reversed(self._data)) else: self._curr = 0 self._last = -1 def is_not_empty(self): return self._curr <= self._last def get_next(self): self._curr += 1 return self._data[self._curr - 1] def is_next_lower(self, level): return self._data[self._curr].level > level class HistoryModel(ui.AbstractItemModel): def __init__(self): super().__init__() self._root = MainItem(None, HistoryData()) def _commands_changed(self): self._root = MainItem(None, HistoryData()) self._item_changed(None) def get_item_children(self, item): if item is None: return self._root.children return item.children def get_item_value_model_count(self, item): return 1 def get_item_value_model(self, item, column_id): if column_id == 0: return item.name_model class HistoryDelegate(ui.AbstractItemDelegate): def __init__(self): super().__init__() self._icon_path = Path(__file__).parent.parent.parent.parent.parent.joinpath("icons") self._style = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" # Read all the svg files in the directory self._icons = {icon.stem: icon for icon in self._icon_path.joinpath(self._style).glob("*.svg")} def build_widget(self, model, item, column_id, level, expanded): """Create a widget per column per item""" value_model = model.get_item_value_model(item, column_id) # call out commands that had errors text = value_model.as_string name = "" if hasattr(item, "_data") and hasattr(item._data, "error") and item._data.error: text = "[ERROR] " + text name = "error" ui.Label(text, name=name, style_type_name_override="TreeView.Item") def build_branch(self, model, item, column_id, level, expanded): """Create a branch widget that opens or closes subtree""" if column_id == 0: with ui.HStack(width=16 * (level + 2), height=0): ui.Spacer() if model.can_item_have_children(item): # Draw the +/- icon image_name = "Minus" if expanded else "Plus" ui.Image( str(self._icons.get(image_name)), width=10, height=10, style_type_name_override="TreeView.Item" ) ui.Spacer(width=4) def build_header(self, column_id): pass class MainItem(ui.AbstractItem): def __init__(self, command_data, history): super().__init__() self._data = command_data if command_data is None: self._create_root(history) else: self._create_node(history) def _create_root(self, history): self.children = [] while history.is_not_empty(): self.children.append(MainItem(history.get_next(), history)) def _create_node(self, history): self.name_model = ui.SimpleStringModel(self._data.name) self.children = [ParamItem(arg, val) for arg, val in self._data.kwargs.items()] while history.is_not_empty() and history.is_next_lower(self._data.level): next_command = history.get_next() self.children.append(MainItem(next_command, history)) class ParamItem(ui.AbstractItem): def __init__(self, arg, val): super().__init__() self.name_model = ui.SimpleStringModel(str(arg) + "=" + str(val)) self.children = []
3,889
Python
32.534482
119
0.580869
omniverse-code/kit/exts/omni.kit.window.commands/omni/kit/window/commands/tests/test_extension.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 re from pathlib import Path import omni.kit.app import omni.kit.commands import omni.kit.undo from omni.kit.window.commands import Window from omni.ui.tests.test_base import OmniUiTest _result = [] class TestAppendCommand(omni.kit.commands.Command): def __init__(self, x, y): self._x = x self._y = y def do(self): global _result _result.append(self._x) _result.append(self._y) def undo(self): global _result del _result[-1] del _result[-1] class TestCommandsWindow(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) self._golden_img_dir = Path(extension_path).joinpath("data").joinpath("tests").absolute() # make sure we are starting from a clean state omni.kit.undo.clear_stack() # Register all commands omni.kit.commands.register(TestAppendCommand) # After running each test async def tearDown(self): # Unregister all commands omni.kit.commands.unregister(TestAppendCommand) await super().tearDown() async def test_simple_command(self): window = await self.create_test_window(1000, 600) with window.frame: win = Window("Commands", "Commands") win.show() global _result # Execute and undo _result = [] omni.kit.commands.execute("TestAppend", x=1, y=2) self.assertListEqual(_result, [1, 2]) omni.kit.undo.undo() self.assertListEqual(_result, []) script = """import omni.kit.commands omni.kit.commands.execute('TestAppend', x=1, y=2) omni.kit.commands.execute('Undo')""" result = win._generate_command_script(False) # strip all whitespaces to ease our comparison s = re.sub("[\s+]", "", script) r = re.sub("[\s+]", "", result) # test script self.assertEqual(s, r) for i in range(50): await omni.kit.app.get_app().next_update_async() # test image await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="test_simple_command.png", use_log=False )
2,862
Python
28.822916
110
0.620196
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/renderer_capture/__init__.py
from omni.kit.renderer_capture import *
40
Python
19.49999
39
0.8
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer/capture/scripts/extension.py
import carb.settings import omni.ext import omni.kit.renderer_capture class Extension(omni.ext.IExt): def __init__(self): omni.ext.IExt.__init__(self) pass def on_startup(self): self._settings = carb.settings.get_settings() self._settings.set_default_bool("/exts/omni.kit.renderer.capture/autostartCapture", True) self._autostart = self._settings.get("/exts/omni.kit.renderer.capture/autostartCapture") if self._autostart: self._renderer_capture = omni.kit.renderer_capture.acquire_renderer_capture_interface() self._renderer_capture.startup() def on_shutdown(self): if self._autostart: self._renderer_capture.shutdown() self._renderer_capture = None
772
Python
31.208332
99
0.65544
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer/capture/tests/__init__.py
from .test_renderer_capture import *
37
Python
17.999991
36
0.783784
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer/capture/tests/test_renderer_capture.py
import os import sys import inspect import pathlib import importlib import carb import carb.dictionary import carb.settings import carb.tokens import omni.appwindow import omni.kit.app import omni.kit.test import omni.kit.renderer.bind import omni.kit.renderer_capture import omni.kit.renderer_capture_test OUTPUTS_DIR = omni.kit.test.get_test_output_path() USE_TUPLES = True # Ancient hack coming from dark times SET_ALPHA_TO_1_SETTING_PATH = "/app/captureFrame/setAlphaTo1" class RendererCaptureTest(omni.kit.test.AsyncTestCase): async def setUp(self): self._settings = carb.settings.get_settings() self._dict = carb.dictionary.acquire_dictionary_interface() self._app_window_factory = omni.appwindow.acquire_app_window_factory_interface() self._renderer = omni.kit.renderer.bind.acquire_renderer_interface() self._renderer_capture = omni.kit.renderer_capture.acquire_renderer_capture_interface() self._renderer_capture_test = omni.kit.renderer_capture_test.acquire_renderer_capture_test_interface() self._renderer.startup() self._renderer_capture.startup() self._renderer_capture_test.startup() def __test_name(self) -> str: return f"{self.__class__.__name__}.{inspect.stack()[1][3]}" async def tearDown(self): self._renderer_capture_test.shutdown() self._renderer_capture.shutdown() self._renderer.shutdown() self._renderer_capture_test = None self._renderer_capture = None self._renderer = None self._app_window_factory = None self._settings = None def _create_and_attach_window(self, w, h, window_type): app_window = self._app_window_factory.create_window_by_type(window_type) app_window.startup_with_desc( title="Renderer capture test OS window", width=w, height=h, x=omni.appwindow.POSITION_CENTERED, y=omni.appwindow.POSITION_CENTERED, decorations=True, resize=True, always_on_top=False, scale_to_monitor=False, dpi_scale_override=1.0 ) self._app_window_factory.set_default_window(app_window) self._renderer.attach_app_window(app_window) return app_window def _detach_and_destroy_window(self, app_window): self._app_window_factory.set_default_window(None) self._renderer.detach_app_window(app_window) app_window.shutdown() def _capture_callback(self, buf, buf_size, w, h, fmt): if USE_TUPLES: self._captured_buffer = omni.kit.renderer_capture.convert_raw_bytes_to_rgba_tuples(buf, buf_size, w, h, fmt) else: self._captured_buffer = omni.kit.renderer_capture.convert_raw_bytes_to_list(buf, buf_size, w, h, fmt) self._captured_buffer_w = w self._captured_buffer_h = h self._captured_buffer_fmt = fmt def _get_pil_image_from_captured_data(self): from PIL import Image image = Image.new('RGBA', [self._captured_buffer_w, self._captured_buffer_h]) if USE_TUPLES: image.putdata(self._captured_buffer) else: buf_channel_it = iter(self._captured_buffer) captured_buffer_tuples = list(zip(buf_channel_it, buf_channel_it, buf_channel_it, buf_channel_it)) image.putdata(captured_buffer_tuples) return image def _get_pil_image_size_data(self, path): from PIL import Image image = Image.open(path) image_data = list(image.getdata()) image_w, image_h = image.size image.close() return image_w, image_h, image_data def _disable_alpha_to_1(self): self._settings.set_default(SET_ALPHA_TO_1_SETTING_PATH, False) self._setAlphaTo1 = self._settings.get(SET_ALPHA_TO_1_SETTING_PATH) self._settings.set(SET_ALPHA_TO_1_SETTING_PATH, False) def _restore_alpha_to_1(self): self._settings.set(SET_ALPHA_TO_1_SETTING_PATH, self._setAlphaTo1) async def test_0001_capture_swapchain_to_file(self): test_name = self.__test_name() TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png") TEST_IMG_W = 8 TEST_IMG_H = 8 TEST_COLOR = (255, 0, 0, 255) app_window = self._create_and_attach_window(TEST_IMG_W, TEST_IMG_H, omni.appwindow.WindowType.VIRTUAL) test_color_unit = tuple(c / 255.0 for c in TEST_COLOR) self._renderer.set_clear_color(app_window, test_color_unit) self._renderer_capture.capture_next_frame_swapchain(TEST_IMG_PATH, app_window) await omni.kit.app.get_app().next_update_async() self._renderer_capture.wait_async_capture(app_window) image_size_data = self._get_pil_image_size_data(TEST_IMG_PATH) self.assertEqual(len(image_size_data), 3) self.assertEqual(image_size_data[0], TEST_IMG_W) self.assertEqual(image_size_data[1], TEST_IMG_H) self.assertEqual(image_size_data[2][0], TEST_COLOR) self._detach_and_destroy_window(app_window) app_window = None async def test_0002_capture_swapchain_callback(self): test_name = self.__test_name() TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png") TEST_IMG_W = 16 TEST_IMG_H = 16 TEST_COLOR = (0, 255, 255, 255) app_window = self._create_and_attach_window(TEST_IMG_W, TEST_IMG_H, omni.appwindow.WindowType.VIRTUAL) test_color_unit = tuple(c / 255.0 for c in TEST_COLOR) self._renderer.set_clear_color(app_window, test_color_unit) self._renderer_capture.capture_next_frame_swapchain_callback(self._capture_callback, app_window) await omni.kit.app.get_app().next_update_async() self._renderer_capture.wait_async_capture(app_window) image = self._get_pil_image_from_captured_data() image.save(TEST_IMG_PATH) self.assertEqual(self._captured_buffer_w, TEST_IMG_W) self.assertEqual(self._captured_buffer_h, TEST_IMG_H) if USE_TUPLES: self.assertEqual(self._captured_buffer[0], TEST_COLOR) else: self.assertEqual(self._captured_buffer[0], TEST_COLOR[0]) self.assertEqual(self._captured_buffer[1], TEST_COLOR[1]) self.assertEqual(self._captured_buffer[2], TEST_COLOR[2]) self.assertEqual(self._captured_buffer[3], TEST_COLOR[3]) self._detach_and_destroy_window(app_window) app_window = None async def test_0003_capture_texture_to_file(self): test_name = self.__test_name() TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png") TEST_IMG_W = 4 TEST_IMG_H = 4 TEST_COLOR = (255, 255, 0, 255) app_window = self._create_and_attach_window(12, 12, omni.appwindow.WindowType.VIRTUAL) test_color_unit = tuple(c / 255.0 for c in TEST_COLOR) texture = self._renderer_capture_test.create_solid_color_texture(test_color_unit, TEST_IMG_W, TEST_IMG_H) self._renderer_capture.capture_next_frame_texture(TEST_IMG_PATH, texture) await omni.kit.app.get_app().next_update_async() self._renderer_capture.wait_async_capture(app_window) image_size_data = self._get_pil_image_size_data(TEST_IMG_PATH) self.assertEqual(len(image_size_data), 3) self.assertEqual(image_size_data[0], TEST_IMG_W) self.assertEqual(image_size_data[1], TEST_IMG_H) self.assertEqual(image_size_data[2][0], TEST_COLOR) self._renderer_capture_test.cleanup_gpu_resources() self._detach_and_destroy_window(app_window) app_window = None async def test_0004_capture_texture_callback(self): test_name = self.__test_name() TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png") TEST_IMG_W = 6 TEST_IMG_H = 6 TEST_COLOR = (255, 0, 255, 255) app_window = self._create_and_attach_window(12, 12, omni.appwindow.WindowType.VIRTUAL) test_color_unit = tuple(c / 255.0 for c in TEST_COLOR) texture = self._renderer_capture_test.create_solid_color_texture(test_color_unit, TEST_IMG_W, TEST_IMG_H) self._renderer_capture.capture_next_frame_texture_callback(self._capture_callback, texture) await omni.kit.app.get_app().next_update_async() self._renderer_capture.wait_async_capture(app_window) image = self._get_pil_image_from_captured_data() image.save(TEST_IMG_PATH) self.assertEqual(self._captured_buffer_w, TEST_IMG_W) self.assertEqual(self._captured_buffer_h, TEST_IMG_H) if USE_TUPLES: self.assertEqual(self._captured_buffer[0], TEST_COLOR) else: self.assertEqual(self._captured_buffer[0], TEST_COLOR[0]) self.assertEqual(self._captured_buffer[1], TEST_COLOR[1]) self.assertEqual(self._captured_buffer[2], TEST_COLOR[2]) self.assertEqual(self._captured_buffer[3], TEST_COLOR[3]) self._renderer_capture_test.cleanup_gpu_resources() self._detach_and_destroy_window(app_window) app_window = None async def test_0005_capture_rp_resource_to_file(self): test_name = self.__test_name() TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png") TEST_IMG_W = 5 TEST_IMG_H = 5 TEST_COLOR = (0, 255, 0, 255) app_window = self._create_and_attach_window(12, 12, omni.appwindow.WindowType.VIRTUAL) test_color_unit = tuple(c / 255.0 for c in TEST_COLOR) rp_resource = self._renderer_capture_test.create_solid_color_rp_resource(test_color_unit, TEST_IMG_W, TEST_IMG_H) self._renderer_capture.capture_next_frame_rp_resource(TEST_IMG_PATH, rp_resource) await omni.kit.app.get_app().next_update_async() self._renderer_capture.wait_async_capture(app_window) image_size_data = self._get_pil_image_size_data(TEST_IMG_PATH) self.assertEqual(len(image_size_data), 3) self.assertEqual(image_size_data[0], TEST_IMG_W) self.assertEqual(image_size_data[1], TEST_IMG_H) self.assertEqual(image_size_data[2][0], TEST_COLOR) self._renderer_capture_test.cleanup_gpu_resources() self._detach_and_destroy_window(app_window) app_window = None async def test_0006_capture_rp_resource_callback(self): test_name = self.__test_name() TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png") TEST_IMG_W = 6 TEST_IMG_H = 6 TEST_COLOR = (0, 0, 255, 255) app_window = self._create_and_attach_window(12, 12, omni.appwindow.WindowType.VIRTUAL) test_color_unit = tuple(c / 255.0 for c in TEST_COLOR) rp_resource = self._renderer_capture_test.create_solid_color_rp_resource(test_color_unit, TEST_IMG_W, TEST_IMG_H) self._renderer_capture.capture_next_frame_rp_resource_callback(self._capture_callback, rp_resource) await omni.kit.app.get_app().next_update_async() self._renderer_capture.wait_async_capture(app_window) image = self._get_pil_image_from_captured_data() image.save(TEST_IMG_PATH) self.assertEqual(self._captured_buffer_w, TEST_IMG_W) self.assertEqual(self._captured_buffer_h, TEST_IMG_H) if USE_TUPLES: self.assertEqual(self._captured_buffer[0], TEST_COLOR) else: self.assertEqual(self._captured_buffer[0], TEST_COLOR[0]) self.assertEqual(self._captured_buffer[1], TEST_COLOR[1]) self.assertEqual(self._captured_buffer[2], TEST_COLOR[2]) self.assertEqual(self._captured_buffer[3], TEST_COLOR[3]) self._renderer_capture_test.cleanup_gpu_resources() self._detach_and_destroy_window(app_window) app_window = None async def test_0007_capture_os_swapchain_to_file(self): test_name = self.__test_name() TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png") TEST_IMG_W = 256 TEST_IMG_H = 32 TEST_COLOR = (255, 128, 0, 255) app_window = self._create_and_attach_window(TEST_IMG_W, TEST_IMG_H, omni.appwindow.WindowType.OS) test_color_unit = tuple(c / 255.0 for c in TEST_COLOR) self._renderer.set_clear_color(app_window, test_color_unit) self._renderer_capture.capture_next_frame_swapchain(TEST_IMG_PATH, app_window) await omni.kit.app.get_app().next_update_async() self._renderer_capture.wait_async_capture(app_window) image_size_data = self._get_pil_image_size_data(TEST_IMG_PATH) self.assertEqual(len(image_size_data), 3) self.assertEqual(image_size_data[0], TEST_IMG_W) self.assertEqual(image_size_data[1], TEST_IMG_H) self.assertEqual(image_size_data[2][0], TEST_COLOR) self._detach_and_destroy_window(app_window) app_window = None async def test_0008_capture_transparent_swapchain_to_file(self): self._disable_alpha_to_1() test_name = self.__test_name() TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png") TEST_IMG_W = 8 TEST_IMG_H = 8 TEST_COLOR = (255, 0, 0, 0) app_window = self._create_and_attach_window(TEST_IMG_W, TEST_IMG_H, omni.appwindow.WindowType.VIRTUAL) test_color_unit = tuple(c / 255.0 for c in TEST_COLOR) self._renderer.set_clear_color(app_window, test_color_unit) self._renderer_capture.capture_next_frame_swapchain(TEST_IMG_PATH, app_window) await omni.kit.app.get_app().next_update_async() self._renderer_capture.wait_async_capture(app_window) image_size_data = self._get_pil_image_size_data(TEST_IMG_PATH) self.assertEqual(len(image_size_data), 3) self.assertEqual(image_size_data[0], TEST_IMG_W) self.assertEqual(image_size_data[1], TEST_IMG_H) self.assertEqual(image_size_data[2][0], TEST_COLOR) self._detach_and_destroy_window(app_window) app_window = None self._restore_alpha_to_1() async def test_0009_capture_transparent_swapchain_callback(self): self._disable_alpha_to_1() test_name = self.__test_name() TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png") TEST_IMG_W = 16 TEST_IMG_H = 16 TEST_COLOR = (0, 255, 255, 0) app_window = self._create_and_attach_window(TEST_IMG_W, TEST_IMG_H, omni.appwindow.WindowType.VIRTUAL) test_color_unit = tuple(c / 255.0 for c in TEST_COLOR) self._renderer.set_clear_color(app_window, test_color_unit) self._renderer_capture.capture_next_frame_swapchain_callback(self._capture_callback, app_window) await omni.kit.app.get_app().next_update_async() self._renderer_capture.wait_async_capture(app_window) image = self._get_pil_image_from_captured_data() image.save(TEST_IMG_PATH) self.assertEqual(self._captured_buffer_w, TEST_IMG_W) self.assertEqual(self._captured_buffer_h, TEST_IMG_H) if USE_TUPLES: self.assertEqual(self._captured_buffer[0], TEST_COLOR) else: self.assertEqual(self._captured_buffer[0], TEST_COLOR[0]) self.assertEqual(self._captured_buffer[1], TEST_COLOR[1]) self.assertEqual(self._captured_buffer[2], TEST_COLOR[2]) self.assertEqual(self._captured_buffer[3], TEST_COLOR[3]) self._detach_and_destroy_window(app_window) app_window = None self._restore_alpha_to_1() async def __test_capture_rp_resource_with_format(self, format_desc_item): test_name = self.__test_name() TEST_IMG_PATH_NOEXT = os.path.join(OUTPUTS_DIR, test_name) TEST_IMG_W = 15 TEST_IMG_H = 15 TEST_COLOR = (12.34, 34.56, 67.89, 128.0) app_window = self._create_and_attach_window(12, 12, omni.appwindow.WindowType.VIRTUAL) files = {} format_desc_item["format"] = "exr" rp_resource = self._renderer_capture_test.create_solid_color_rp_resource_hdr(TEST_COLOR, TEST_IMG_W, TEST_IMG_H) async def capture(): filename = TEST_IMG_PATH_NOEXT + "_" + format_desc_item["compression"] + ".exr" files[format_desc_item["compression"]] = filename self._renderer_capture.capture_next_frame_rp_resource_to_file(filename, rp_resource, None, format_desc_item) await omni.kit.app.get_app().next_update_async() self._renderer_capture.wait_async_capture(app_window) format_desc_item["compression"] = "none" await capture() format_desc_item["compression"] = "rle" await capture() format_desc_item["compression"] = "b44" await capture() file_sizes = {} for file_key, file_path in files.items(): file_sizes[file_key] = os.path.getsize(file_path) self.assertNotEqual(file_sizes["none"], file_sizes["rle"]) self.assertNotEqual(file_sizes["none"], file_sizes["b44"]) self.assertNotEqual(file_sizes["rle"], file_sizes["b44"]) self._renderer_capture_test.cleanup_gpu_resources() self._detach_and_destroy_window(app_window) app_window = None async def test_0010_capture_rp_resource_hdr_to_file_carb_dict(self): format_desc_item = self._dict.create_item(None, "", carb.dictionary.ItemType.DICTIONARY) await self.__test_capture_rp_resource_with_format(format_desc_item) async def test_0010_capture_rp_resource_hdr_to_file_py_dict(self): format_desc_item = {} await self.__test_capture_rp_resource_with_format(format_desc_item)
17,721
Python
39.277273
121
0.639806
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer_capture_test/__init__.py
import functools from ._renderer_capture_test import * # Cached interface instance pointer @functools.lru_cache() def get_renderer_capture_test_interface() -> IRendererCaptureTest: if not hasattr(get_renderer_capture_test_interface, "renderer_capture_test"): get_renderer_capture_test_interface.renderer_capture_test = acquire_renderer_capture_test_interface() return get_renderer_capture_test_interface.renderer_capture_test
444
Python
39.454542
109
0.783784
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer_capture/__init__.py
from ._renderer_capture import *
33
Python
15.999992
32
0.757576
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/ogn/OgnSdTestStageSynchronizationDatabase.py
"""Support for simplified access to data on nodes of type omni.syntheticdata.SdTestStageSynchronization Synthetic Data node to test the pipeline stage synchronization """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnSdTestStageSynchronizationDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.syntheticdata.SdTestStageSynchronization Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.exec inputs.gpu inputs.randomMaxProcessingTimeUs inputs.randomSeed inputs.renderResults inputs.rp inputs.swhFrameNumber inputs.tag inputs.traceError Outputs: outputs.exec outputs.fabricSWHFrameNumber outputs.swhFrameNumber """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:exec', 'execution', 0, None, 'OnDemand connection : trigger', {}, True, None, False, ''), ('inputs:gpu', 'uint64', 0, 'gpuFoundations', 'PostRender connection : pointer to shared context containing gpu foundations', {}, True, 0, False, ''), ('inputs:randomMaxProcessingTimeUs', 'uint', 0, None, 'Maximum number of micro-seconds to randomly (uniformely) wait for in order to simulate varying workload', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''), ('inputs:randomSeed', 'uint', 0, None, 'Random seed for the randomization', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''), ('inputs:renderResults', 'uint64', 0, None, 'OnDemand connection : pointer to render product results', {}, True, 0, False, ''), ('inputs:rp', 'uint64', 0, 'renderProduct', 'PostRender connection : pointer to render product for this view', {}, True, 0, False, ''), ('inputs:swhFrameNumber', 'uint64', 0, None, 'Fabric frame number', {}, True, 0, False, ''), ('inputs:tag', 'token', 0, None, 'A tag to identify the node', {}, True, "", False, ''), ('inputs:traceError', 'bool', 0, None, 'If true print an error message when the frame numbers are out-of-sync', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('outputs:exec', 'execution', 0, None, 'OnDemand connection : trigger', {}, True, None, False, ''), ('outputs:fabricSWHFrameNumber', 'uint64', 0, None, 'Fabric frame number from the fabric', {}, True, None, False, ''), ('outputs:swhFrameNumber', 'uint64', 0, None, 'Fabric frame number', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.exec = og.AttributeRole.EXECUTION role_data.outputs.exec = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def exec(self): data_view = og.AttributeValueHelper(self._attributes.exec) return data_view.get() @exec.setter def exec(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.exec) data_view = og.AttributeValueHelper(self._attributes.exec) data_view.set(value) @property def gpu(self): data_view = og.AttributeValueHelper(self._attributes.gpu) return data_view.get() @gpu.setter def gpu(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.gpu) data_view = og.AttributeValueHelper(self._attributes.gpu) data_view.set(value) @property def randomMaxProcessingTimeUs(self): data_view = og.AttributeValueHelper(self._attributes.randomMaxProcessingTimeUs) return data_view.get() @randomMaxProcessingTimeUs.setter def randomMaxProcessingTimeUs(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.randomMaxProcessingTimeUs) data_view = og.AttributeValueHelper(self._attributes.randomMaxProcessingTimeUs) data_view.set(value) @property def randomSeed(self): data_view = og.AttributeValueHelper(self._attributes.randomSeed) return data_view.get() @randomSeed.setter def randomSeed(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.randomSeed) data_view = og.AttributeValueHelper(self._attributes.randomSeed) data_view.set(value) @property def renderResults(self): data_view = og.AttributeValueHelper(self._attributes.renderResults) return data_view.get() @renderResults.setter def renderResults(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.renderResults) data_view = og.AttributeValueHelper(self._attributes.renderResults) data_view.set(value) @property def rp(self): data_view = og.AttributeValueHelper(self._attributes.rp) return data_view.get() @rp.setter def rp(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.rp) data_view = og.AttributeValueHelper(self._attributes.rp) data_view.set(value) @property def swhFrameNumber(self): data_view = og.AttributeValueHelper(self._attributes.swhFrameNumber) return data_view.get() @swhFrameNumber.setter def swhFrameNumber(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.swhFrameNumber) data_view = og.AttributeValueHelper(self._attributes.swhFrameNumber) data_view.set(value) @property def tag(self): data_view = og.AttributeValueHelper(self._attributes.tag) return data_view.get() @tag.setter def tag(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.tag) data_view = og.AttributeValueHelper(self._attributes.tag) data_view.set(value) @property def traceError(self): data_view = og.AttributeValueHelper(self._attributes.traceError) return data_view.get() @traceError.setter def traceError(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.traceError) data_view = og.AttributeValueHelper(self._attributes.traceError) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def exec(self): data_view = og.AttributeValueHelper(self._attributes.exec) return data_view.get() @exec.setter def exec(self, value): data_view = og.AttributeValueHelper(self._attributes.exec) data_view.set(value) @property def fabricSWHFrameNumber(self): data_view = og.AttributeValueHelper(self._attributes.fabricSWHFrameNumber) return data_view.get() @fabricSWHFrameNumber.setter def fabricSWHFrameNumber(self, value): data_view = og.AttributeValueHelper(self._attributes.fabricSWHFrameNumber) data_view.set(value) @property def swhFrameNumber(self): data_view = og.AttributeValueHelper(self._attributes.swhFrameNumber) return data_view.get() @swhFrameNumber.setter def swhFrameNumber(self, value): data_view = og.AttributeValueHelper(self._attributes.swhFrameNumber) data_view.set(value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnSdTestStageSynchronizationDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSdTestStageSynchronizationDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSdTestStageSynchronizationDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
11,401
Python
44.067194
222
0.643277
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/ogn/OgnSdFabricTimeRangeExecutionDatabase.py
"""Support for simplified access to data on nodes of type omni.syntheticdata.SdFabricTimeRangeExecution Read a rational time range from Fabric or RenderVars and signal its execution if the current time fall within this range. The range is [begin,end[, that is the end time does not belong to the range. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnSdFabricTimeRangeExecutionDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.syntheticdata.SdFabricTimeRangeExecution Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.exec inputs.gpu inputs.renderResults inputs.timeRangeBeginDenominatorToken inputs.timeRangeBeginNumeratorToken inputs.timeRangeEndDenominatorToken inputs.timeRangeEndNumeratorToken inputs.timeRangeName Outputs: outputs.exec outputs.timeRangeBeginDenominator outputs.timeRangeBeginNumerator outputs.timeRangeEndDenominator outputs.timeRangeEndNumerator """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''), ('inputs:gpu', 'uint64', 0, None, 'Pointer to shared context containing gpu foundations.', {}, True, 0, False, ''), ('inputs:renderResults', 'uint64', 0, None, 'Render results', {}, True, 0, False, ''), ('inputs:timeRangeBeginDenominatorToken', 'token', 0, None, 'Attribute name of the range begin time denominator', {ogn.MetadataKeys.DEFAULT: '"timeRangeStartDenominator"'}, True, "timeRangeStartDenominator", False, ''), ('inputs:timeRangeBeginNumeratorToken', 'token', 0, None, 'Attribute name of the range begin time numerator', {ogn.MetadataKeys.DEFAULT: '"timeRangeStartNumerator"'}, True, "timeRangeStartNumerator", False, ''), ('inputs:timeRangeEndDenominatorToken', 'token', 0, None, 'Attribute name of the range end time denominator', {ogn.MetadataKeys.DEFAULT: '"timeRangeEndDenominator"'}, True, "timeRangeEndDenominator", False, ''), ('inputs:timeRangeEndNumeratorToken', 'token', 0, None, 'Attribute name of the range end time numerator', {ogn.MetadataKeys.DEFAULT: '"timeRangeEndNumerator"'}, True, "timeRangeEndNumerator", False, ''), ('inputs:timeRangeName', 'token', 0, None, 'Time range name used to read from the Fabric or RenderVars.', {}, True, "", False, ''), ('outputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''), ('outputs:timeRangeBeginDenominator', 'uint64', 0, None, 'Time denominator of the last time range change (begin)', {}, True, None, False, ''), ('outputs:timeRangeBeginNumerator', 'int64', 0, None, 'Time numerator of the last time range change (begin)', {}, True, None, False, ''), ('outputs:timeRangeEndDenominator', 'uint64', 0, None, 'Time denominator of the last time range change (end)', {}, True, None, False, ''), ('outputs:timeRangeEndNumerator', 'int64', 0, None, 'Time numerator of the last time range change (end)', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.exec = og.AttributeRole.EXECUTION role_data.outputs.exec = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def exec(self): data_view = og.AttributeValueHelper(self._attributes.exec) return data_view.get() @exec.setter def exec(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.exec) data_view = og.AttributeValueHelper(self._attributes.exec) data_view.set(value) @property def gpu(self): data_view = og.AttributeValueHelper(self._attributes.gpu) return data_view.get() @gpu.setter def gpu(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.gpu) data_view = og.AttributeValueHelper(self._attributes.gpu) data_view.set(value) @property def renderResults(self): data_view = og.AttributeValueHelper(self._attributes.renderResults) return data_view.get() @renderResults.setter def renderResults(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.renderResults) data_view = og.AttributeValueHelper(self._attributes.renderResults) data_view.set(value) @property def timeRangeBeginDenominatorToken(self): data_view = og.AttributeValueHelper(self._attributes.timeRangeBeginDenominatorToken) return data_view.get() @timeRangeBeginDenominatorToken.setter def timeRangeBeginDenominatorToken(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.timeRangeBeginDenominatorToken) data_view = og.AttributeValueHelper(self._attributes.timeRangeBeginDenominatorToken) data_view.set(value) @property def timeRangeBeginNumeratorToken(self): data_view = og.AttributeValueHelper(self._attributes.timeRangeBeginNumeratorToken) return data_view.get() @timeRangeBeginNumeratorToken.setter def timeRangeBeginNumeratorToken(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.timeRangeBeginNumeratorToken) data_view = og.AttributeValueHelper(self._attributes.timeRangeBeginNumeratorToken) data_view.set(value) @property def timeRangeEndDenominatorToken(self): data_view = og.AttributeValueHelper(self._attributes.timeRangeEndDenominatorToken) return data_view.get() @timeRangeEndDenominatorToken.setter def timeRangeEndDenominatorToken(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.timeRangeEndDenominatorToken) data_view = og.AttributeValueHelper(self._attributes.timeRangeEndDenominatorToken) data_view.set(value) @property def timeRangeEndNumeratorToken(self): data_view = og.AttributeValueHelper(self._attributes.timeRangeEndNumeratorToken) return data_view.get() @timeRangeEndNumeratorToken.setter def timeRangeEndNumeratorToken(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.timeRangeEndNumeratorToken) data_view = og.AttributeValueHelper(self._attributes.timeRangeEndNumeratorToken) data_view.set(value) @property def timeRangeName(self): data_view = og.AttributeValueHelper(self._attributes.timeRangeName) return data_view.get() @timeRangeName.setter def timeRangeName(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.timeRangeName) data_view = og.AttributeValueHelper(self._attributes.timeRangeName) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def exec(self): data_view = og.AttributeValueHelper(self._attributes.exec) return data_view.get() @exec.setter def exec(self, value): data_view = og.AttributeValueHelper(self._attributes.exec) data_view.set(value) @property def timeRangeBeginDenominator(self): data_view = og.AttributeValueHelper(self._attributes.timeRangeBeginDenominator) return data_view.get() @timeRangeBeginDenominator.setter def timeRangeBeginDenominator(self, value): data_view = og.AttributeValueHelper(self._attributes.timeRangeBeginDenominator) data_view.set(value) @property def timeRangeBeginNumerator(self): data_view = og.AttributeValueHelper(self._attributes.timeRangeBeginNumerator) return data_view.get() @timeRangeBeginNumerator.setter def timeRangeBeginNumerator(self, value): data_view = og.AttributeValueHelper(self._attributes.timeRangeBeginNumerator) data_view.set(value) @property def timeRangeEndDenominator(self): data_view = og.AttributeValueHelper(self._attributes.timeRangeEndDenominator) return data_view.get() @timeRangeEndDenominator.setter def timeRangeEndDenominator(self, value): data_view = og.AttributeValueHelper(self._attributes.timeRangeEndDenominator) data_view.set(value) @property def timeRangeEndNumerator(self): data_view = og.AttributeValueHelper(self._attributes.timeRangeEndNumerator) return data_view.get() @timeRangeEndNumerator.setter def timeRangeEndNumerator(self, value): data_view = og.AttributeValueHelper(self._attributes.timeRangeEndNumerator) data_view.set(value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnSdFabricTimeRangeExecutionDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSdFabricTimeRangeExecutionDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSdFabricTimeRangeExecutionDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
12,894
Python
47.844697
227
0.669148
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/ogn/OgnSdRenderVarDisplayTextureDatabase.py
"""Support for simplified access to data on nodes of type omni.syntheticdata.SdRenderVarDisplayTexture Synthetic Data node to expose texture resource of a visualization render variable """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnSdRenderVarDisplayTextureDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.syntheticdata.SdRenderVarDisplayTexture Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.exec inputs.renderResults inputs.renderVarDisplay Outputs: outputs.cudaPtr outputs.exec outputs.format outputs.height outputs.referenceTimeDenominator outputs.referenceTimeNumerator outputs.rpResourcePtr outputs.width """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''), ('inputs:renderResults', 'uint64', 0, None, 'Render results pointer', {}, True, 0, False, ''), ('inputs:renderVarDisplay', 'token', 0, None, 'Name of the renderVar', {}, True, "", False, ''), ('outputs:cudaPtr', 'uint64', 0, None, 'Display texture CUDA pointer', {}, True, None, False, ''), ('outputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''), ('outputs:format', 'uint64', 0, None, 'Display texture format', {}, True, None, False, ''), ('outputs:height', 'uint', 0, None, 'Display texture height', {}, True, None, False, ''), ('outputs:referenceTimeDenominator', 'uint64', 0, None, 'Reference time represented as a rational number : denominator', {}, True, None, False, ''), ('outputs:referenceTimeNumerator', 'int64', 0, None, 'Reference time represented as a rational number : numerator', {}, True, None, False, ''), ('outputs:rpResourcePtr', 'uint64', 0, None, 'Display texture RpResource pointer', {}, True, None, False, ''), ('outputs:width', 'uint', 0, None, 'Display texture width', {}, True, None, False, ''), ]) @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.exec = og.AttributeRole.EXECUTION role_data.outputs.exec = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def exec(self): data_view = og.AttributeValueHelper(self._attributes.exec) return data_view.get() @exec.setter def exec(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.exec) data_view = og.AttributeValueHelper(self._attributes.exec) data_view.set(value) @property def renderResults(self): data_view = og.AttributeValueHelper(self._attributes.renderResults) return data_view.get() @renderResults.setter def renderResults(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.renderResults) data_view = og.AttributeValueHelper(self._attributes.renderResults) data_view.set(value) @property def renderVarDisplay(self): data_view = og.AttributeValueHelper(self._attributes.renderVarDisplay) return data_view.get() @renderVarDisplay.setter def renderVarDisplay(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.renderVarDisplay) data_view = og.AttributeValueHelper(self._attributes.renderVarDisplay) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def cudaPtr(self): data_view = og.AttributeValueHelper(self._attributes.cudaPtr) return data_view.get() @cudaPtr.setter def cudaPtr(self, value): data_view = og.AttributeValueHelper(self._attributes.cudaPtr) data_view.set(value) @property def exec(self): data_view = og.AttributeValueHelper(self._attributes.exec) return data_view.get() @exec.setter def exec(self, value): data_view = og.AttributeValueHelper(self._attributes.exec) data_view.set(value) @property def format(self): data_view = og.AttributeValueHelper(self._attributes.format) return data_view.get() @format.setter def format(self, value): data_view = og.AttributeValueHelper(self._attributes.format) data_view.set(value) @property def height(self): data_view = og.AttributeValueHelper(self._attributes.height) return data_view.get() @height.setter def height(self, value): data_view = og.AttributeValueHelper(self._attributes.height) data_view.set(value) @property def referenceTimeDenominator(self): data_view = og.AttributeValueHelper(self._attributes.referenceTimeDenominator) return data_view.get() @referenceTimeDenominator.setter def referenceTimeDenominator(self, value): data_view = og.AttributeValueHelper(self._attributes.referenceTimeDenominator) data_view.set(value) @property def referenceTimeNumerator(self): data_view = og.AttributeValueHelper(self._attributes.referenceTimeNumerator) return data_view.get() @referenceTimeNumerator.setter def referenceTimeNumerator(self, value): data_view = og.AttributeValueHelper(self._attributes.referenceTimeNumerator) data_view.set(value) @property def rpResourcePtr(self): data_view = og.AttributeValueHelper(self._attributes.rpResourcePtr) return data_view.get() @rpResourcePtr.setter def rpResourcePtr(self, value): data_view = og.AttributeValueHelper(self._attributes.rpResourcePtr) data_view.set(value) @property def width(self): data_view = og.AttributeValueHelper(self._attributes.width) return data_view.get() @width.setter def width(self, value): data_view = og.AttributeValueHelper(self._attributes.width) data_view.set(value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnSdRenderVarDisplayTextureDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSdRenderVarDisplayTextureDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSdRenderVarDisplayTextureDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
10,061
Python
42.938864
156
0.646158
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/ogn/OgnSdPostCompRenderVarTexturesDatabase.py
"""Support for simplified access to data on nodes of type omni.syntheticdata.SdPostCompRenderVarTextures Synthetic Data node to compose a front renderVar texture into a back renderVar texture """ import numpy import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnSdPostCompRenderVarTexturesDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.syntheticdata.SdPostCompRenderVarTextures Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.cudaPtr inputs.format inputs.gpu inputs.height inputs.mode inputs.parameters inputs.renderVar inputs.rp inputs.width Predefined Tokens: tokens.line tokens.grid """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:cudaPtr', 'uint64', 0, None, 'Front texture CUDA pointer', {}, True, 0, False, ''), ('inputs:format', 'uint64', 0, None, 'Front texture format', {}, True, 0, False, ''), ('inputs:gpu', 'uint64', 0, 'gpuFoundations', 'Pointer to shared context containing gpu foundations', {}, True, 0, False, ''), ('inputs:height', 'uint', 0, None, 'Front texture height', {}, True, 0, False, ''), ('inputs:mode', 'token', 0, None, 'Mode : grid, line', {ogn.MetadataKeys.DEFAULT: '"line"'}, True, "line", False, ''), ('inputs:parameters', 'float3', 0, None, 'Parameters', {ogn.MetadataKeys.DEFAULT: '[0, 0, 0]'}, True, [0, 0, 0], False, ''), ('inputs:renderVar', 'token', 0, None, 'Name of the back RenderVar', {ogn.MetadataKeys.DEFAULT: '"LdrColor"'}, True, "LdrColor", False, ''), ('inputs:rp', 'uint64', 0, 'renderProduct', 'Pointer to render product for this view', {}, True, 0, False, ''), ('inputs:width', 'uint', 0, None, 'Front texture width', {}, True, 0, False, ''), ]) class tokens: line = "line" grid = "grid" class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def cudaPtr(self): data_view = og.AttributeValueHelper(self._attributes.cudaPtr) return data_view.get() @cudaPtr.setter def cudaPtr(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.cudaPtr) data_view = og.AttributeValueHelper(self._attributes.cudaPtr) data_view.set(value) @property def format(self): data_view = og.AttributeValueHelper(self._attributes.format) return data_view.get() @format.setter def format(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.format) data_view = og.AttributeValueHelper(self._attributes.format) data_view.set(value) @property def gpu(self): data_view = og.AttributeValueHelper(self._attributes.gpu) return data_view.get() @gpu.setter def gpu(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.gpu) data_view = og.AttributeValueHelper(self._attributes.gpu) data_view.set(value) @property def height(self): data_view = og.AttributeValueHelper(self._attributes.height) return data_view.get() @height.setter def height(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.height) data_view = og.AttributeValueHelper(self._attributes.height) data_view.set(value) @property def mode(self): data_view = og.AttributeValueHelper(self._attributes.mode) return data_view.get() @mode.setter def mode(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.mode) data_view = og.AttributeValueHelper(self._attributes.mode) data_view.set(value) @property def parameters(self): data_view = og.AttributeValueHelper(self._attributes.parameters) return data_view.get() @parameters.setter def parameters(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.parameters) data_view = og.AttributeValueHelper(self._attributes.parameters) data_view.set(value) @property def renderVar(self): data_view = og.AttributeValueHelper(self._attributes.renderVar) return data_view.get() @renderVar.setter def renderVar(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.renderVar) data_view = og.AttributeValueHelper(self._attributes.renderVar) data_view.set(value) @property def rp(self): data_view = og.AttributeValueHelper(self._attributes.rp) return data_view.get() @rp.setter def rp(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.rp) data_view = og.AttributeValueHelper(self._attributes.rp) data_view.set(value) @property def width(self): data_view = og.AttributeValueHelper(self._attributes.width) return data_view.get() @width.setter def width(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.width) data_view = og.AttributeValueHelper(self._attributes.width) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnSdPostCompRenderVarTexturesDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSdPostCompRenderVarTexturesDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSdPostCompRenderVarTexturesDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
9,264
Python
41.695852
148
0.630937
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/ogn/OgnSdTextureToLinearArrayDatabase.py
"""Support for simplified access to data on nodes of type omni.syntheticdata.SdTextureToLinearArray SyntheticData node to copy the input texture into a linear array buffer """ import numpy import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnSdTextureToLinearArrayDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.syntheticdata.SdTextureToLinearArray Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.cudaMipmappedArray inputs.format inputs.height inputs.hydraTime inputs.mipCount inputs.outputHeight inputs.outputWidth inputs.simTime inputs.stream inputs.width Outputs: outputs.data outputs.height outputs.hydraTime outputs.simTime outputs.stream outputs.width """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:cudaMipmappedArray', 'uint64', 0, None, 'Pointer to the CUDA Mipmapped Array', {}, True, 0, False, ''), ('inputs:format', 'uint64', 0, None, 'Format', {}, True, 0, False, ''), ('inputs:height', 'uint', 0, None, 'Height', {}, True, 0, False, ''), ('inputs:hydraTime', 'double', 0, None, 'Hydra time in stage', {}, True, 0.0, False, ''), ('inputs:mipCount', 'uint', 0, None, 'Mip Count', {}, True, 0, False, ''), ('inputs:outputHeight', 'uint', 0, None, 'Requested output height', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''), ('inputs:outputWidth', 'uint', 0, None, 'Requested output width', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''), ('inputs:simTime', 'double', 0, None, 'Simulation time', {}, True, 0.0, False, ''), ('inputs:stream', 'uint64', 0, None, 'Pointer to the CUDA Stream', {}, True, 0, False, ''), ('inputs:width', 'uint', 0, None, 'Width', {}, True, 0, False, ''), ('outputs:data', 'float4[]', 0, None, 'Buffer array data', {ogn.MetadataKeys.MEMORY_TYPE: 'cuda', ogn.MetadataKeys.DEFAULT: '[]'}, True, [], False, ''), ('outputs:height', 'uint', 0, None, 'Buffer array height', {}, True, None, False, ''), ('outputs:hydraTime', 'double', 0, None, 'Hydra time in stage', {}, True, None, False, ''), ('outputs:simTime', 'double', 0, None, 'Simulation time', {}, True, None, False, ''), ('outputs:stream', 'uint64', 0, None, 'Pointer to the CUDA Stream', {}, True, None, False, ''), ('outputs:width', 'uint', 0, None, 'Buffer array width', {}, True, None, False, ''), ]) class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def cudaMipmappedArray(self): data_view = og.AttributeValueHelper(self._attributes.cudaMipmappedArray) return data_view.get() @cudaMipmappedArray.setter def cudaMipmappedArray(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.cudaMipmappedArray) data_view = og.AttributeValueHelper(self._attributes.cudaMipmappedArray) data_view.set(value) @property def format(self): data_view = og.AttributeValueHelper(self._attributes.format) return data_view.get() @format.setter def format(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.format) data_view = og.AttributeValueHelper(self._attributes.format) data_view.set(value) @property def height(self): data_view = og.AttributeValueHelper(self._attributes.height) return data_view.get() @height.setter def height(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.height) data_view = og.AttributeValueHelper(self._attributes.height) data_view.set(value) @property def hydraTime(self): data_view = og.AttributeValueHelper(self._attributes.hydraTime) return data_view.get() @hydraTime.setter def hydraTime(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.hydraTime) data_view = og.AttributeValueHelper(self._attributes.hydraTime) data_view.set(value) @property def mipCount(self): data_view = og.AttributeValueHelper(self._attributes.mipCount) return data_view.get() @mipCount.setter def mipCount(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.mipCount) data_view = og.AttributeValueHelper(self._attributes.mipCount) data_view.set(value) @property def outputHeight(self): data_view = og.AttributeValueHelper(self._attributes.outputHeight) return data_view.get() @outputHeight.setter def outputHeight(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.outputHeight) data_view = og.AttributeValueHelper(self._attributes.outputHeight) data_view.set(value) @property def outputWidth(self): data_view = og.AttributeValueHelper(self._attributes.outputWidth) return data_view.get() @outputWidth.setter def outputWidth(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.outputWidth) data_view = og.AttributeValueHelper(self._attributes.outputWidth) data_view.set(value) @property def simTime(self): data_view = og.AttributeValueHelper(self._attributes.simTime) return data_view.get() @simTime.setter def simTime(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.simTime) data_view = og.AttributeValueHelper(self._attributes.simTime) data_view.set(value) @property def stream(self): data_view = og.AttributeValueHelper(self._attributes.stream) return data_view.get() @stream.setter def stream(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.stream) data_view = og.AttributeValueHelper(self._attributes.stream) data_view.set(value) @property def width(self): data_view = og.AttributeValueHelper(self._attributes.width) return data_view.get() @width.setter def width(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.width) data_view = og.AttributeValueHelper(self._attributes.width) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self.data_size = 0 self._batchedWriteValues = { } @property def data(self): data_view = og.AttributeValueHelper(self._attributes.data) return data_view.get(reserved_element_count=self.data_size, on_gpu=True) @data.setter def data(self, value): data_view = og.AttributeValueHelper(self._attributes.data) data_view.set(value, on_gpu=True) self.data_size = data_view.get_array_size() @property def height(self): data_view = og.AttributeValueHelper(self._attributes.height) return data_view.get() @height.setter def height(self, value): data_view = og.AttributeValueHelper(self._attributes.height) data_view.set(value) @property def hydraTime(self): data_view = og.AttributeValueHelper(self._attributes.hydraTime) return data_view.get() @hydraTime.setter def hydraTime(self, value): data_view = og.AttributeValueHelper(self._attributes.hydraTime) data_view.set(value) @property def simTime(self): data_view = og.AttributeValueHelper(self._attributes.simTime) return data_view.get() @simTime.setter def simTime(self, value): data_view = og.AttributeValueHelper(self._attributes.simTime) data_view.set(value) @property def stream(self): data_view = og.AttributeValueHelper(self._attributes.stream) return data_view.get() @stream.setter def stream(self, value): data_view = og.AttributeValueHelper(self._attributes.stream) data_view.set(value) @property def width(self): data_view = og.AttributeValueHelper(self._attributes.width) return data_view.get() @width.setter def width(self, value): data_view = og.AttributeValueHelper(self._attributes.width) data_view.set(value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnSdTextureToLinearArrayDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSdTextureToLinearArrayDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSdTextureToLinearArrayDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
12,568
Python
41.177852
160
0.620942
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/ogn/OgnSdTestInstanceMappingDatabase.py
"""Support for simplified access to data on nodes of type omni.syntheticdata.SdTestInstanceMapping Synthetic Data node to test the instance mapping pipeline """ import numpy import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnSdTestInstanceMappingDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.syntheticdata.SdTestInstanceMapping Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.exec inputs.instanceMapPtr inputs.instancePrimPathPtr inputs.minInstanceIndex inputs.minSemanticIndex inputs.numInstances inputs.numSemantics inputs.semanticLabelTokenPtrs inputs.semanticLocalTransformPtr inputs.semanticMapPtr inputs.semanticPrimPathPtr inputs.semanticWorldTransformPtr inputs.stage inputs.swhFrameNumber inputs.testCaseIndex Outputs: outputs.exec outputs.semanticFilterPredicate outputs.success Predefined Tokens: tokens.simulation tokens.postRender tokens.onDemand """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''), ('inputs:instanceMapPtr', 'uint64', 0, None, 'Array pointer of numInstances uint16_t containing the semantic index of the instance prim first semantic prim parent', {}, True, 0, False, ''), ('inputs:instancePrimPathPtr', 'uint64', 0, None, 'Array pointer of numInstances uint64_t containing the prim path tokens for every instance prims', {}, True, 0, False, ''), ('inputs:minInstanceIndex', 'uint', 0, None, 'Instance index of the first instance prim in the instance arrays', {}, True, 0, False, ''), ('inputs:minSemanticIndex', 'uint', 0, None, 'Semantic index of the first semantic prim in the semantic arrays', {}, True, 0, False, ''), ('inputs:numInstances', 'uint', 0, None, 'Number of instances prim in the instance arrays', {}, True, 0, False, ''), ('inputs:numSemantics', 'uint', 0, None, 'Number of semantic prim in the semantic arrays', {}, True, 0, False, ''), ('inputs:semanticLabelTokenPtrs', 'uint64[]', 0, None, 'Array containing for every input semantic filters the corresponding array pointer of numSemantics uint64_t representing the semantic label of the semantic prim', {}, True, [], False, ''), ('inputs:semanticLocalTransformPtr', 'uint64', 0, None, 'Array pointer of numSemantics 4x4 float matrices containing the transform from world to object space for every semantic prims', {}, True, 0, False, ''), ('inputs:semanticMapPtr', 'uint64', 0, None, 'Array pointer of numSemantics uint16_t containing the semantic index of the semantic prim first semantic prim parent', {}, True, 0, False, ''), ('inputs:semanticPrimPathPtr', 'uint64', 0, None, 'Array pointer of numSemantics uint32_t containing the prim part of the prim path tokens for every semantic prims', {}, True, 0, False, ''), ('inputs:semanticWorldTransformPtr', 'uint64', 0, None, 'Array pointer of numSemantics 4x4 float matrices containing the transform from local to world space for every semantic entity', {}, True, 0, False, ''), ('inputs:stage', 'token', 0, None, 'Stage in {simulation, postrender, ondemand}', {}, True, "", False, ''), ('inputs:swhFrameNumber', 'uint64', 0, None, 'Fabric frame number', {}, True, 0, False, ''), ('inputs:testCaseIndex', 'int', 0, None, 'Test case index', {ogn.MetadataKeys.DEFAULT: '-1'}, True, -1, False, ''), ('outputs:exec', 'execution', 0, 'Received', 'Executes when the event is received', {}, True, None, False, ''), ('outputs:semanticFilterPredicate', 'token', 0, None, 'The semantic filter predicate : a disjunctive normal form of semantic type and label', {}, True, None, False, ''), ('outputs:success', 'bool', 0, None, 'Test value : false if failed', {}, True, None, False, ''), ]) class tokens: simulation = "simulation" postRender = "postRender" onDemand = "onDemand" @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.exec = og.AttributeRole.EXECUTION role_data.outputs.exec = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def exec(self): data_view = og.AttributeValueHelper(self._attributes.exec) return data_view.get() @exec.setter def exec(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.exec) data_view = og.AttributeValueHelper(self._attributes.exec) data_view.set(value) @property def instanceMapPtr(self): data_view = og.AttributeValueHelper(self._attributes.instanceMapPtr) return data_view.get() @instanceMapPtr.setter def instanceMapPtr(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.instanceMapPtr) data_view = og.AttributeValueHelper(self._attributes.instanceMapPtr) data_view.set(value) @property def instancePrimPathPtr(self): data_view = og.AttributeValueHelper(self._attributes.instancePrimPathPtr) return data_view.get() @instancePrimPathPtr.setter def instancePrimPathPtr(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.instancePrimPathPtr) data_view = og.AttributeValueHelper(self._attributes.instancePrimPathPtr) data_view.set(value) @property def minInstanceIndex(self): data_view = og.AttributeValueHelper(self._attributes.minInstanceIndex) return data_view.get() @minInstanceIndex.setter def minInstanceIndex(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.minInstanceIndex) data_view = og.AttributeValueHelper(self._attributes.minInstanceIndex) data_view.set(value) @property def minSemanticIndex(self): data_view = og.AttributeValueHelper(self._attributes.minSemanticIndex) return data_view.get() @minSemanticIndex.setter def minSemanticIndex(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.minSemanticIndex) data_view = og.AttributeValueHelper(self._attributes.minSemanticIndex) data_view.set(value) @property def numInstances(self): data_view = og.AttributeValueHelper(self._attributes.numInstances) return data_view.get() @numInstances.setter def numInstances(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.numInstances) data_view = og.AttributeValueHelper(self._attributes.numInstances) data_view.set(value) @property def numSemantics(self): data_view = og.AttributeValueHelper(self._attributes.numSemantics) return data_view.get() @numSemantics.setter def numSemantics(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.numSemantics) data_view = og.AttributeValueHelper(self._attributes.numSemantics) data_view.set(value) @property def semanticLabelTokenPtrs(self): data_view = og.AttributeValueHelper(self._attributes.semanticLabelTokenPtrs) return data_view.get() @semanticLabelTokenPtrs.setter def semanticLabelTokenPtrs(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.semanticLabelTokenPtrs) data_view = og.AttributeValueHelper(self._attributes.semanticLabelTokenPtrs) data_view.set(value) self.semanticLabelTokenPtrs_size = data_view.get_array_size() @property def semanticLocalTransformPtr(self): data_view = og.AttributeValueHelper(self._attributes.semanticLocalTransformPtr) return data_view.get() @semanticLocalTransformPtr.setter def semanticLocalTransformPtr(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.semanticLocalTransformPtr) data_view = og.AttributeValueHelper(self._attributes.semanticLocalTransformPtr) data_view.set(value) @property def semanticMapPtr(self): data_view = og.AttributeValueHelper(self._attributes.semanticMapPtr) return data_view.get() @semanticMapPtr.setter def semanticMapPtr(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.semanticMapPtr) data_view = og.AttributeValueHelper(self._attributes.semanticMapPtr) data_view.set(value) @property def semanticPrimPathPtr(self): data_view = og.AttributeValueHelper(self._attributes.semanticPrimPathPtr) return data_view.get() @semanticPrimPathPtr.setter def semanticPrimPathPtr(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.semanticPrimPathPtr) data_view = og.AttributeValueHelper(self._attributes.semanticPrimPathPtr) data_view.set(value) @property def semanticWorldTransformPtr(self): data_view = og.AttributeValueHelper(self._attributes.semanticWorldTransformPtr) return data_view.get() @semanticWorldTransformPtr.setter def semanticWorldTransformPtr(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.semanticWorldTransformPtr) data_view = og.AttributeValueHelper(self._attributes.semanticWorldTransformPtr) data_view.set(value) @property def stage(self): data_view = og.AttributeValueHelper(self._attributes.stage) return data_view.get() @stage.setter def stage(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.stage) data_view = og.AttributeValueHelper(self._attributes.stage) data_view.set(value) @property def swhFrameNumber(self): data_view = og.AttributeValueHelper(self._attributes.swhFrameNumber) return data_view.get() @swhFrameNumber.setter def swhFrameNumber(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.swhFrameNumber) data_view = og.AttributeValueHelper(self._attributes.swhFrameNumber) data_view.set(value) @property def testCaseIndex(self): data_view = og.AttributeValueHelper(self._attributes.testCaseIndex) return data_view.get() @testCaseIndex.setter def testCaseIndex(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.testCaseIndex) data_view = og.AttributeValueHelper(self._attributes.testCaseIndex) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def exec(self): data_view = og.AttributeValueHelper(self._attributes.exec) return data_view.get() @exec.setter def exec(self, value): data_view = og.AttributeValueHelper(self._attributes.exec) data_view.set(value) @property def semanticFilterPredicate(self): data_view = og.AttributeValueHelper(self._attributes.semanticFilterPredicate) return data_view.get() @semanticFilterPredicate.setter def semanticFilterPredicate(self, value): data_view = og.AttributeValueHelper(self._attributes.semanticFilterPredicate) data_view.set(value) @property def success(self): data_view = og.AttributeValueHelper(self._attributes.success) return data_view.get() @success.setter def success(self, value): data_view = og.AttributeValueHelper(self._attributes.success) data_view.set(value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnSdTestInstanceMappingDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSdTestInstanceMappingDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSdTestInstanceMappingDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
16,282
Python
45.65616
251
0.6525
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/ogn/OgnSdFrameIdentifierDatabase.py
"""Support for simplified access to data on nodes of type omni.syntheticdata.SdFrameIdentifier Synthetic Data node to expose pipeline frame identifier. """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnSdFrameIdentifierDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.syntheticdata.SdFrameIdentifier Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.exec inputs.renderResults Outputs: outputs.durationDenominator outputs.durationNumerator outputs.exec outputs.externalTimeOfSimNs outputs.frameNumber outputs.rationalTimeOfSimDenominator outputs.rationalTimeOfSimNumerator outputs.sampleTimeOffsetInSimFrames outputs.type Predefined Tokens: tokens.NoFrameNumber tokens.FrameNumber tokens.ConstantFramerateFrameNumber """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''), ('inputs:renderResults', 'uint64', 0, None, 'Render results', {}, True, 0, False, ''), ('outputs:durationDenominator', 'uint64', 0, None, 'Duration denominator.\nOnly valid if eConstantFramerateFrameNumber', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''), ('outputs:durationNumerator', 'int64', 0, None, 'Duration numerator.\nOnly valid if eConstantFramerateFrameNumber.', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''), ('outputs:exec', 'execution', 0, 'Received', 'Executes for each newFrame event received', {}, True, None, False, ''), ('outputs:externalTimeOfSimNs', 'int64', 0, None, 'External time in Ns.\nOnly valid if eConstantFramerateFrameNumber.', {ogn.MetadataKeys.DEFAULT: '-1'}, True, -1, False, ''), ('outputs:frameNumber', 'int64', 0, None, 'Frame number.\nValid if eFrameNumber or eConstantFramerateFrameNumber.', {ogn.MetadataKeys.DEFAULT: '-1'}, True, -1, False, ''), ('outputs:rationalTimeOfSimDenominator', 'uint64', 0, None, 'rational time of simulation denominator.', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''), ('outputs:rationalTimeOfSimNumerator', 'int64', 0, None, 'rational time of simulation numerator.', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''), ('outputs:sampleTimeOffsetInSimFrames', 'uint64', 0, None, 'Sample time offset.\nOnly valid if eConstantFramerateFrameNumber.', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''), ('outputs:type', 'token', 0, None, 'Type of the frame identifier.', {ogn.MetadataKeys.ALLOWED_TOKENS: 'NoFrameNumber,FrameNumber,ConstantFramerateFrameNumber', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '["NoFrameNumber", "FrameNumber", "ConstantFramerateFrameNumber"]', ogn.MetadataKeys.DEFAULT: '"NoFrameNumber"'}, True, "NoFrameNumber", False, ''), ]) class tokens: NoFrameNumber = "NoFrameNumber" FrameNumber = "FrameNumber" ConstantFramerateFrameNumber = "ConstantFramerateFrameNumber" @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.exec = og.AttributeRole.EXECUTION role_data.outputs.exec = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def exec(self): data_view = og.AttributeValueHelper(self._attributes.exec) return data_view.get() @exec.setter def exec(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.exec) data_view = og.AttributeValueHelper(self._attributes.exec) data_view.set(value) @property def renderResults(self): data_view = og.AttributeValueHelper(self._attributes.renderResults) return data_view.get() @renderResults.setter def renderResults(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.renderResults) data_view = og.AttributeValueHelper(self._attributes.renderResults) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def durationDenominator(self): data_view = og.AttributeValueHelper(self._attributes.durationDenominator) return data_view.get() @durationDenominator.setter def durationDenominator(self, value): data_view = og.AttributeValueHelper(self._attributes.durationDenominator) data_view.set(value) @property def durationNumerator(self): data_view = og.AttributeValueHelper(self._attributes.durationNumerator) return data_view.get() @durationNumerator.setter def durationNumerator(self, value): data_view = og.AttributeValueHelper(self._attributes.durationNumerator) data_view.set(value) @property def exec(self): data_view = og.AttributeValueHelper(self._attributes.exec) return data_view.get() @exec.setter def exec(self, value): data_view = og.AttributeValueHelper(self._attributes.exec) data_view.set(value) @property def externalTimeOfSimNs(self): data_view = og.AttributeValueHelper(self._attributes.externalTimeOfSimNs) return data_view.get() @externalTimeOfSimNs.setter def externalTimeOfSimNs(self, value): data_view = og.AttributeValueHelper(self._attributes.externalTimeOfSimNs) data_view.set(value) @property def frameNumber(self): data_view = og.AttributeValueHelper(self._attributes.frameNumber) return data_view.get() @frameNumber.setter def frameNumber(self, value): data_view = og.AttributeValueHelper(self._attributes.frameNumber) data_view.set(value) @property def rationalTimeOfSimDenominator(self): data_view = og.AttributeValueHelper(self._attributes.rationalTimeOfSimDenominator) return data_view.get() @rationalTimeOfSimDenominator.setter def rationalTimeOfSimDenominator(self, value): data_view = og.AttributeValueHelper(self._attributes.rationalTimeOfSimDenominator) data_view.set(value) @property def rationalTimeOfSimNumerator(self): data_view = og.AttributeValueHelper(self._attributes.rationalTimeOfSimNumerator) return data_view.get() @rationalTimeOfSimNumerator.setter def rationalTimeOfSimNumerator(self, value): data_view = og.AttributeValueHelper(self._attributes.rationalTimeOfSimNumerator) data_view.set(value) @property def sampleTimeOffsetInSimFrames(self): data_view = og.AttributeValueHelper(self._attributes.sampleTimeOffsetInSimFrames) return data_view.get() @sampleTimeOffsetInSimFrames.setter def sampleTimeOffsetInSimFrames(self, value): data_view = og.AttributeValueHelper(self._attributes.sampleTimeOffsetInSimFrames) data_view.set(value) @property def type(self): data_view = og.AttributeValueHelper(self._attributes.type) return data_view.get() @type.setter def type(self, value): data_view = og.AttributeValueHelper(self._attributes.type) data_view.set(value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnSdFrameIdentifierDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSdFrameIdentifierDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSdFrameIdentifierDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
11,174
Python
46.151899
353
0.667442
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/ogn/OgnSdPostInstanceMappingDatabase.py
"""Support for simplified access to data on nodes of type omni.syntheticdata.SdPostInstanceMapping Synthetic Data node to compute and store scene instances semantic hierarchy information """ import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnSdPostInstanceMappingDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.syntheticdata.SdPostInstanceMapping Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.exec inputs.gpu inputs.rp inputs.semanticFilterName Outputs: outputs.exec outputs.instanceMapSDCudaPtr outputs.instanceMappingInfoSDPtr outputs.instancePrimTokenSDCudaPtr outputs.lastUpdateTimeDenominator outputs.lastUpdateTimeNumerator outputs.semanticLabelTokenSDCudaPtr outputs.semanticLocalTransformSDCudaPtr outputs.semanticMapSDCudaPtr outputs.semanticPrimTokenSDCudaPtr outputs.semanticWorldTransformSDCudaPtr Predefined Tokens: tokens.InstanceMappingInfoSDhost tokens.SemanticMapSD tokens.SemanticMapSDhost tokens.SemanticPrimTokenSD tokens.SemanticPrimTokenSDhost tokens.InstanceMapSD tokens.InstanceMapSDhost tokens.InstancePrimTokenSD tokens.InstancePrimTokenSDhost tokens.SemanticLabelTokenSD tokens.SemanticLabelTokenSDhost tokens.SemanticLocalTransformSD tokens.SemanticLocalTransformSDhost tokens.SemanticWorldTransformSD tokens.SemanticWorldTransformSDhost """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''), ('inputs:gpu', 'uint64', 0, 'gpuFoundations', 'Pointer to shared context containing gpu foundations', {}, True, 0, False, ''), ('inputs:rp', 'uint64', 0, 'renderProduct', 'Pointer to render product for this view', {}, True, 0, False, ''), ('inputs:semanticFilterName', 'token', 0, None, 'Name of the semantic filter to apply to the semanticLabelToken', {ogn.MetadataKeys.DEFAULT: '"default"'}, True, "default", False, ''), ('outputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''), ('outputs:instanceMapSDCudaPtr', 'uint64', 0, None, 'cuda uint16_t buffer pointer of size numInstances containing the instance parent semantic index', {}, True, None, False, ''), ('outputs:instanceMappingInfoSDPtr', 'uint64', 0, None, 'uint buffer pointer containing the following information :\n[ numInstances, minInstanceId, numSemantics, minSemanticId, numProtoSemantic,\n lastUpdateTimeNumeratorHigh, lastUpdateTimeNumeratorLow, , lastUpdateTimeDenominatorHigh, lastUpdateTimeDenominatorLow ]', {}, True, None, False, ''), ('outputs:instancePrimTokenSDCudaPtr', 'uint64', 0, None, 'cuda uint64_t buffer pointer of size numInstances containing the instance path token', {}, True, None, False, ''), ('outputs:lastUpdateTimeDenominator', 'uint64', 0, None, 'Time denominator of the last time the data has changed', {}, True, None, False, ''), ('outputs:lastUpdateTimeNumerator', 'int64', 0, None, 'Time numerator of the last time the data has changed', {}, True, None, False, ''), ('outputs:semanticLabelTokenSDCudaPtr', 'uint64', 0, None, 'cuda uint64_t buffer pointer of size numSemantics containing the semantic label token', {}, True, None, False, ''), ('outputs:semanticLocalTransformSDCudaPtr', 'uint64', 0, None, 'cuda float44 buffer pointer of size numSemantics containing the local semantic transform', {}, True, None, False, ''), ('outputs:semanticMapSDCudaPtr', 'uint64', 0, None, 'cuda uint16_t buffer pointer of size numSemantics containing the semantic parent semantic index', {}, True, None, False, ''), ('outputs:semanticPrimTokenSDCudaPtr', 'uint64', 0, None, 'cuda uint32_t buffer pointer of size numSemantics containing the prim part of the semantic path token', {}, True, None, False, ''), ('outputs:semanticWorldTransformSDCudaPtr', 'uint64', 0, None, 'cuda float44 buffer pointer of size numSemantics containing the world semantic transform', {}, True, None, False, ''), ]) class tokens: InstanceMappingInfoSDhost = "InstanceMappingInfoSDhost" SemanticMapSD = "SemanticMapSD" SemanticMapSDhost = "SemanticMapSDhost" SemanticPrimTokenSD = "SemanticPrimTokenSD" SemanticPrimTokenSDhost = "SemanticPrimTokenSDhost" InstanceMapSD = "InstanceMapSD" InstanceMapSDhost = "InstanceMapSDhost" InstancePrimTokenSD = "InstancePrimTokenSD" InstancePrimTokenSDhost = "InstancePrimTokenSDhost" SemanticLabelTokenSD = "SemanticLabelTokenSD" SemanticLabelTokenSDhost = "SemanticLabelTokenSDhost" SemanticLocalTransformSD = "SemanticLocalTransformSD" SemanticLocalTransformSDhost = "SemanticLocalTransformSDhost" SemanticWorldTransformSD = "SemanticWorldTransformSD" SemanticWorldTransformSDhost = "SemanticWorldTransformSDhost" @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.exec = og.AttributeRole.EXECUTION role_data.outputs.exec = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def exec(self): data_view = og.AttributeValueHelper(self._attributes.exec) return data_view.get() @exec.setter def exec(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.exec) data_view = og.AttributeValueHelper(self._attributes.exec) data_view.set(value) @property def gpu(self): data_view = og.AttributeValueHelper(self._attributes.gpu) return data_view.get() @gpu.setter def gpu(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.gpu) data_view = og.AttributeValueHelper(self._attributes.gpu) data_view.set(value) @property def rp(self): data_view = og.AttributeValueHelper(self._attributes.rp) return data_view.get() @rp.setter def rp(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.rp) data_view = og.AttributeValueHelper(self._attributes.rp) data_view.set(value) @property def semanticFilterName(self): data_view = og.AttributeValueHelper(self._attributes.semanticFilterName) return data_view.get() @semanticFilterName.setter def semanticFilterName(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.semanticFilterName) data_view = og.AttributeValueHelper(self._attributes.semanticFilterName) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def exec(self): data_view = og.AttributeValueHelper(self._attributes.exec) return data_view.get() @exec.setter def exec(self, value): data_view = og.AttributeValueHelper(self._attributes.exec) data_view.set(value) @property def instanceMapSDCudaPtr(self): data_view = og.AttributeValueHelper(self._attributes.instanceMapSDCudaPtr) return data_view.get() @instanceMapSDCudaPtr.setter def instanceMapSDCudaPtr(self, value): data_view = og.AttributeValueHelper(self._attributes.instanceMapSDCudaPtr) data_view.set(value) @property def instanceMappingInfoSDPtr(self): data_view = og.AttributeValueHelper(self._attributes.instanceMappingInfoSDPtr) return data_view.get() @instanceMappingInfoSDPtr.setter def instanceMappingInfoSDPtr(self, value): data_view = og.AttributeValueHelper(self._attributes.instanceMappingInfoSDPtr) data_view.set(value) @property def instancePrimTokenSDCudaPtr(self): data_view = og.AttributeValueHelper(self._attributes.instancePrimTokenSDCudaPtr) return data_view.get() @instancePrimTokenSDCudaPtr.setter def instancePrimTokenSDCudaPtr(self, value): data_view = og.AttributeValueHelper(self._attributes.instancePrimTokenSDCudaPtr) data_view.set(value) @property def lastUpdateTimeDenominator(self): data_view = og.AttributeValueHelper(self._attributes.lastUpdateTimeDenominator) return data_view.get() @lastUpdateTimeDenominator.setter def lastUpdateTimeDenominator(self, value): data_view = og.AttributeValueHelper(self._attributes.lastUpdateTimeDenominator) data_view.set(value) @property def lastUpdateTimeNumerator(self): data_view = og.AttributeValueHelper(self._attributes.lastUpdateTimeNumerator) return data_view.get() @lastUpdateTimeNumerator.setter def lastUpdateTimeNumerator(self, value): data_view = og.AttributeValueHelper(self._attributes.lastUpdateTimeNumerator) data_view.set(value) @property def semanticLabelTokenSDCudaPtr(self): data_view = og.AttributeValueHelper(self._attributes.semanticLabelTokenSDCudaPtr) return data_view.get() @semanticLabelTokenSDCudaPtr.setter def semanticLabelTokenSDCudaPtr(self, value): data_view = og.AttributeValueHelper(self._attributes.semanticLabelTokenSDCudaPtr) data_view.set(value) @property def semanticLocalTransformSDCudaPtr(self): data_view = og.AttributeValueHelper(self._attributes.semanticLocalTransformSDCudaPtr) return data_view.get() @semanticLocalTransformSDCudaPtr.setter def semanticLocalTransformSDCudaPtr(self, value): data_view = og.AttributeValueHelper(self._attributes.semanticLocalTransformSDCudaPtr) data_view.set(value) @property def semanticMapSDCudaPtr(self): data_view = og.AttributeValueHelper(self._attributes.semanticMapSDCudaPtr) return data_view.get() @semanticMapSDCudaPtr.setter def semanticMapSDCudaPtr(self, value): data_view = og.AttributeValueHelper(self._attributes.semanticMapSDCudaPtr) data_view.set(value) @property def semanticPrimTokenSDCudaPtr(self): data_view = og.AttributeValueHelper(self._attributes.semanticPrimTokenSDCudaPtr) return data_view.get() @semanticPrimTokenSDCudaPtr.setter def semanticPrimTokenSDCudaPtr(self, value): data_view = og.AttributeValueHelper(self._attributes.semanticPrimTokenSDCudaPtr) data_view.set(value) @property def semanticWorldTransformSDCudaPtr(self): data_view = og.AttributeValueHelper(self._attributes.semanticWorldTransformSDCudaPtr) return data_view.get() @semanticWorldTransformSDCudaPtr.setter def semanticWorldTransformSDCudaPtr(self, value): data_view = og.AttributeValueHelper(self._attributes.semanticWorldTransformSDCudaPtr) data_view.set(value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnSdPostInstanceMappingDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSdPostInstanceMappingDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSdPostInstanceMappingDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
15,172
Python
47.476038
356
0.679475
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/scripts/menu.py
# Copyright (c) 2021-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__ = ["SynthDataMenuContainer"] from omni.kit.viewport.menubar.core import ( ComboBoxModel, ComboBoxItem, ComboBoxMenuDelegate, CheckboxMenuDelegate, IconMenuDelegate, SliderMenuDelegate, ViewportMenuContainer, ViewportMenuItem, ViewportMenuSeparator ) from .SyntheticData import SyntheticData from .visualizer_window import VisualizerWindow import carb import omni.ui as ui from pathlib import Path import weakref ICON_PATH = Path(carb.tokens.get_tokens_interface().resolve("${omni.syntheticdata}")).joinpath("data") UI_STYLE = {"Menu.Item.Icon::SyntheticData": {"image_url": str(ICON_PATH.joinpath("sensor_icon.svg"))}} class SensorAngleModel(ui.AbstractValueModel): def __init__(self, getter, setter, *args, **kwargs): super().__init__(*args, **kwargs) self.__getter = getter self.__setter = setter def destroy(self): self.__getter = None self.__setter = None def get_value_as_float(self) -> float: return self.__getter() def get_value_as_int(self) -> int: return int(self.get_value_as_float()) def set_value(self, value): value = float(value) if self.get_value_as_float() != value: self.__setter(value) self._value_changed() class SensorVisualizationModel(ui.AbstractValueModel): def __init__(self, sensor: str, visualizer_window, *args, **kwargs): super().__init__(*args, **kwargs) self.__sensor = sensor self.__visualizer_window = visualizer_window def get_value_as_bool(self) -> bool: try: return bool(self.__sensor in self.__visualizer_window.visualization_activation) except: return False def get_value_as_int(self) -> int: return 1 if self.get_value_as_bool() else 0 def set_value(self, enabled): enabled = bool(enabled) if self.get_value_as_bool() != enabled: self.__visualizer_window.on_sensor_item_clicked(enabled, self.__sensor) self._value_changed() def sensor(self): return self.__sensor class MenuContext: def __init__(self, viewport_api): self.__visualizer_window = VisualizerWindow(f"{viewport_api.id}", viewport_api) self.__hide_on_click = False self.__sensor_models = set() def destroy(self): self.__sensor_models = set() self.__visualizer_window.close() @property def hide_on_click(self) -> bool: return self.__hide_on_click def add_render_settings_items(self): render_product_combo_model = self.__visualizer_window.render_product_combo_model if render_product_combo_model: ViewportMenuItem( "RenderProduct", delegate=ComboBoxMenuDelegate(model=render_product_combo_model), hide_on_click=self.__hide_on_click, ) render_var_combo_model = self.__visualizer_window.render_var_combo_model if render_var_combo_model: ViewportMenuItem( "RenderVar", delegate=ComboBoxMenuDelegate(model=render_var_combo_model), hide_on_click=self.__hide_on_click, ) def add_angles_items(self): render_var_combo_model = self.__visualizer_window.render_var_combo_model if render_var_combo_model: ViewportMenuItem( name="Angle", hide_on_click=self.__hide_on_click, delegate=SliderMenuDelegate( model=SensorAngleModel(render_var_combo_model.get_combine_angle, render_var_combo_model.set_combine_angle), min=-100.0, max=100.0, tooltip="Set Combine Angle", ), ) ViewportMenuItem( name="X", hide_on_click=self.__hide_on_click, delegate=SliderMenuDelegate( model=SensorAngleModel(render_var_combo_model.get_combine_divide_x, render_var_combo_model.set_combine_divide_x), min=-100.0, max=100.0, tooltip="Set Combine Divide X", ), ) ViewportMenuItem( name="Y", hide_on_click=self.__hide_on_click, delegate=SliderMenuDelegate( model=SensorAngleModel(render_var_combo_model.get_combine_divide_y, render_var_combo_model.set_combine_divide_y), min=-100.0, max=100.0, tooltip="Set Combine Divide Y", ), ) def add_sensor_selection(self): for sensor_label, sensor in SyntheticData.get_registered_visualization_template_names_for_display(): model = SensorVisualizationModel(sensor, self.__visualizer_window) self.__sensor_models.add(model) ViewportMenuItem( name=sensor_label, hide_on_click=self.__hide_on_click, delegate=CheckboxMenuDelegate(model=model, tooltip=f'Enable "{sensor}" visualization') ) if SyntheticData.get_visualization_template_name_default_activation(sensor): model.set_value(True) def clear_all(self, *args, **kwargs): for smodel in self.__sensor_models: smodel.set_value(False) def set_as_default(self, *args, **kwargs): for smodel in self.__sensor_models: SyntheticData.set_visualization_template_name_default_activation(smodel.sensor(), smodel.get_value_as_bool()) def reset_to_default(self, *args, **kwargs): default_sensors = [] for _, sensor in SyntheticData.get_registered_visualization_template_names_for_display(): if SyntheticData.get_visualization_template_name_default_activation(sensor): default_sensors.append(sensor) for smodel in self.__sensor_models: smodel.set_value(smodel.sensor() in default_sensors) def show_window(self, *args, **kwargs): self.__visualizer_window.toggle_enable_visualization() class SynthDataMenuContainer(ViewportMenuContainer): def __init__(self): super().__init__(name="SyntheticData", visible_setting_path="/exts/omni.syntheticdata/menubar/visible", order_setting_path="/exts/omni.syntheticdata/menubar/order", delegate=IconMenuDelegate("SyntheticData"), # tooltip="Synthetic Data Sensors"), style=UI_STYLE) self.__menu_context: Dict[str, MenuContext] = {} def __del__(self): self.destroy() def destroy(self): for menu_ctx in self.__menu_context.values(): menu_ctx.destroy() self.__menu_context = {} super().destroy() def build_fn(self, desc: dict): viewport_api = desc.get("viewport_api") if not viewport_api: return viewport_api_id = viewport_api.id menu_ctx = self.__menu_context.get(viewport_api_id) if menu_ctx: menu_ctx.destroy() menu_ctx = MenuContext(viewport_api) self.__menu_context[viewport_api_id] = menu_ctx with self: menu_ctx.add_render_settings_items() ViewportMenuSeparator() menu_ctx.add_angles_items() ViewportMenuSeparator() menu_ctx.add_sensor_selection() if carb.settings.get_settings().get_as_bool("/exts/omni.syntheticdata/menubar/showSensorDefaultButton"): ViewportMenuSeparator() ViewportMenuItem(name="Set as default", hide_on_click=menu_ctx.hide_on_click, onclick_fn=menu_ctx.set_as_default) ViewportMenuItem(name="Reset to default", hide_on_click=menu_ctx.hide_on_click, onclick_fn=menu_ctx.reset_to_default) ViewportMenuSeparator() ViewportMenuItem(name="Clear All", hide_on_click=menu_ctx.hide_on_click, onclick_fn=menu_ctx.clear_all) ViewportMenuItem(name="Show Window", hide_on_click=menu_ctx.hide_on_click, onclick_fn=menu_ctx.show_window) super().build_fn(desc) def clear_all(self): for menu_ctx in self.__menu_context.values(): menu_ctx.clear_all()
8,981
Python
36.739496
133
0.595813
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/tests/pipeline/test_instance_mapping_update.py
import carb import os.path from pxr import Gf, UsdGeom, UsdLux, Sdf import omni.hydratexture import omni.kit.test from omni.syntheticdata import SyntheticData, SyntheticDataStage from ..utils import add_semantics # Test the instance mapping update Fabric flag class TestInstanceMappingUpdate(omni.kit.test.AsyncTestCase): def __init__(self, methodName: str) -> None: super().__init__(methodName=methodName) # Dictionnary containing the pair (file_path , reference_data). If the reference data is None only the existence of the file is validated. self._golden_references = {} def _texture_render_product_path(self, hydra_texture) -> str: '''Return a string to the UsdRender.Product used by the texture''' render_product = hydra_texture.get_render_product_path() if render_product and (not render_product.startswith('/')): render_product = '/Render/RenderProduct_' + render_product return render_product def _assert_count_equal(self, counter_template_name, count): count_output = SyntheticData.Get().get_node_attributes( counter_template_name, ["outputs:count"], self._render_product_path ) assert "outputs:count" in count_output assert count_output["outputs:count"] == count def _activate_fabric_time_range(self) -> None: sdg_iface = SyntheticData.Get() if not sdg_iface.is_node_template_registered("TestSimFabricTimeRange"): sdg_iface.register_node_template( SyntheticData.NodeTemplate( SyntheticDataStage.ON_DEMAND, "omni.syntheticdata.SdTestSimFabricTimeRange" ), template_name="TestSimFabricTimeRange" ) sdg_iface.activate_node_template( "TestSimFabricTimeRange", attributes={"inputs:timeRangeName":"testFabricTimeRangeTrigger"} ) if not sdg_iface.is_node_template_registered("TestPostRenderFabricTimeRange"): sdg_iface.register_node_template( SyntheticData.NodeTemplate( SyntheticDataStage.POST_RENDER, "omni.syntheticdata.SdFabricTimeRangeExecution", [ SyntheticData.NodeConnectionTemplate( SyntheticData.renderer_template_name(), attributes_mapping= { "outputs:rp": "inputs:renderResults", "outputs:gpu": "inputs:gpu" } ) ] ), template_name="TestPostRenderFabricTimeRange" ) sdg_iface.activate_node_template( "TestPostRenderFabricTimeRange", 0, [self._render_product_path], attributes={"inputs:timeRangeName":"testFabricTimeRangeTrigger"} ) if not sdg_iface.is_node_template_registered("TestPostProcessFabricTimeRange"): sdg_iface.register_node_template( SyntheticData.NodeTemplate( SyntheticDataStage.ON_DEMAND, "omni.syntheticdata.SdFabricTimeRangeExecution", [ SyntheticData.NodeConnectionTemplate("PostProcessDispatch"), SyntheticData.NodeConnectionTemplate("TestPostRenderFabricTimeRange") ] ), template_name="TestPostProcessFabricTimeRange" ) sdg_iface.activate_node_template( "TestPostProcessFabricTimeRange", 0, [self._render_product_path], attributes={"inputs:timeRangeName":"testFabricTimeRangeTrigger"} ) if not sdg_iface.is_node_template_registered("TestPostProcessFabricTimeRangeCounter"): sdg_iface.register_node_template( SyntheticData.NodeTemplate( SyntheticDataStage.ON_DEMAND, "omni.graph.action.Counter", [ SyntheticData.NodeConnectionTemplate( "TestPostProcessFabricTimeRange", attributes_mapping={"outputs:exec": "inputs:execIn"} ) ] ), template_name="TestPostProcessFabricTimeRangeCounter" ) sdg_iface.activate_node_template( "TestPostProcessFabricTimeRangeCounter", 0, [self._render_product_path] ) def _activate_instance_mapping_update(self) -> None: sdg_iface = SyntheticData.Get() if not sdg_iface.is_node_template_registered("TestPostProcessInstanceMappingUpdate"): sdg_iface.register_node_template( SyntheticData.NodeTemplate( SyntheticDataStage.ON_DEMAND, "omni.syntheticdata.SdTimeChangeExecution", [ SyntheticData.NodeConnectionTemplate("InstanceMappingPtr"), SyntheticData.NodeConnectionTemplate("PostProcessDispatch") ] ), template_name="TestPostProcessInstanceMappingUpdate" ) if not sdg_iface.is_node_template_registered("TestPostProcessInstanceMappingUpdateCounter"): sdg_iface.register_node_template( SyntheticData.NodeTemplate( SyntheticDataStage.ON_DEMAND, "omni.graph.action.Counter", [ SyntheticData.NodeConnectionTemplate( "TestPostProcessInstanceMappingUpdate", attributes_mapping={"outputs:exec": "inputs:execIn"} ) ] ), template_name="TestPostProcessInstanceMappingUpdateCounter" ) sdg_iface.activate_node_template( "TestPostProcessInstanceMappingUpdateCounter", 0, [self._render_product_path] ) async def _request_fabric_time_range_trigger(self, number_of_frames=1): sdg_iface = SyntheticData.Get() sdg_iface.set_node_attributes("TestSimFabricTimeRange",{"inputs:numberOfFrames":number_of_frames}) sdg_iface.request_node_execution("TestSimFabricTimeRange") await omni.kit.app.get_app().next_update_async() async def setUp(self): """Called at the begining of every tests""" self._settings = carb.settings.acquire_settings_interface() self._hydra_texture_factory = omni.hydratexture.acquire_hydra_texture_factory_interface() self._usd_context_name = '' self._usd_context = omni.usd.get_context(self._usd_context_name) await self._usd_context.new_stage_async() # renderer renderer = "rtx" if renderer not in self._usd_context.get_attached_hydra_engine_names(): omni.usd.add_hydra_engine(renderer, self._usd_context) # create the hydra textures self._hydra_texture_0 = self._hydra_texture_factory.create_hydra_texture( "TEX0", 1920, 1080, self._usd_context_name, hydra_engine_name=renderer, is_async=self._settings.get("/app/asyncRendering") ) self._hydra_texture_rendered_counter = 0 def on_hydra_texture_0(event: carb.events.IEvent): self._hydra_texture_rendered_counter += 1 self._hydra_texture_rendered_counter_sub = self._hydra_texture_0.get_event_stream().create_subscription_to_push_by_type( omni.hydratexture.EVENT_TYPE_DRAWABLE_CHANGED, on_hydra_texture_0, name='async rendering test drawable update', ) stage = omni.usd.get_context().get_stage() world_prim = UsdGeom.Xform.Define(stage,"/World") UsdGeom.Xformable(world_prim).AddTranslateOp().Set((0, 0, 0)) UsdGeom.Xformable(world_prim).AddRotateXYZOp().Set((0, 0, 0)) self._render_product_path = self._texture_render_product_path(self._hydra_texture_0) await omni.syntheticdata.sensors.next_render_simulation_async(self._render_product_path) await omni.syntheticdata.sensors.next_render_simulation_async(self._render_product_path) async def tearDown(self): """Called at the end of every tests""" self._hydra_texture_rendered_counter_sub = None self._hydra_texture_0 = None self._usd_context.close_stage() omni.usd.release_all_hydra_engines(self._usd_context) self._hydra_texture_factory = None self._settings = None wait_iterations = 6 for _ in range(wait_iterations): await omni.kit.app.get_app().next_update_async() async def test_case_0(self): """Test case 0 : no time range""" self._activate_fabric_time_range() await omni.syntheticdata.sensors.next_render_simulation_async(self._render_product_path, 11) self._assert_count_equal("TestPostProcessFabricTimeRangeCounter", 0) async def test_case_1(self): """Test case 1 : setup a time range of 5 frames""" self._activate_fabric_time_range() await omni.syntheticdata.sensors.next_render_simulation_async(self._render_product_path) await self._request_fabric_time_range_trigger(5) await omni.syntheticdata.sensors.next_render_simulation_async(self._render_product_path, 11) self._assert_count_equal("TestPostProcessFabricTimeRangeCounter", 5) async def test_case_2(self): """Test case 2 : initial instance mapping setup""" self._activate_instance_mapping_update() await omni.syntheticdata.sensors.next_render_simulation_async(self._render_product_path, 11) self._assert_count_equal("TestPostProcessInstanceMappingUpdateCounter", 1) async def test_case_3(self): """Test case 3 : setup an instance mapping with 1, 2, 3, 4 changes""" stage = omni.usd.get_context().get_stage() self._activate_instance_mapping_update() await omni.syntheticdata.sensors.next_render_simulation_async(self._render_product_path, 1) self._assert_count_equal("TestPostProcessInstanceMappingUpdateCounter", 1) sphere_prim = stage.DefinePrim("/World/Sphere", "Sphere") add_semantics(sphere_prim, "sphere") await omni.syntheticdata.sensors.next_render_simulation_async(self._render_product_path, 3) self._assert_count_equal("TestPostProcessInstanceMappingUpdateCounter", 2) sub_sphere_prim = stage.DefinePrim("/World/Sphere/Sphere", "Sphere") await omni.syntheticdata.sensors.next_render_simulation_async(self._render_product_path, 5) self._assert_count_equal("TestPostProcessInstanceMappingUpdateCounter", 3) add_semantics(sub_sphere_prim, "sphere") await omni.syntheticdata.sensors.next_render_simulation_async(self._render_product_path, 1) self._assert_count_equal("TestPostProcessInstanceMappingUpdateCounter", 4)
11,297
Python
45.303279
146
0.610605
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/tests/sensors/test_display_rendervar.py
# NOTE: # omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests # For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html import os import unittest import omni.kit.test from omni.kit.viewport.utility import get_active_viewport from omni.syntheticdata import SyntheticData # Test the semantic filter class TestDisplayRenderVar(omni.kit.test.AsyncTestCase): def __init__(self, methodName: str) -> None: super().__init__(methodName=methodName) async def setUp(self): await omni.usd.get_context().new_stage_async() self.render_product_path = get_active_viewport().render_product_path await omni.kit.app.get_app().next_update_async() async def wait_for_frames(self): wait_iterations = 6 for _ in range(wait_iterations): await omni.kit.app.get_app().next_update_async() async def test_valid_ldrcolor_texture(self): SyntheticData.Get().activate_node_template("LdrColorDisplay", 0, [self.render_product_path]) await self.wait_for_frames() display_output_names = ["outputs:rpResourcePtr", "outputs:width", "outputs:height", "outputs:format"] display_outputs = SyntheticData.Get().get_node_attributes("LdrColorDisplay", display_output_names, self.render_product_path) assert(display_outputs and all(o in display_outputs for o in display_output_names) and display_outputs["outputs:rpResourcePtr"] != 0 and display_outputs["outputs:format"] == 11) SyntheticData.Get().deactivate_node_template("LdrColorDisplay", 0, [self.render_product_path]) async def test_valid_bbox3d_texture(self): SyntheticData.Get().activate_node_template("BoundingBox3DDisplay", 0, [self.render_product_path]) await self.wait_for_frames() display_output_names = ["outputs:rpResourcePtr", "outputs:width", "outputs:height", "outputs:format"] display_outputs = SyntheticData.Get().get_node_attributes("BoundingBox3DDisplay", display_output_names, self.render_product_path) assert(display_outputs and all(o in display_outputs for o in display_output_names) and display_outputs["outputs:rpResourcePtr"] != 0 and display_outputs["outputs:format"] == 11) SyntheticData.Get().deactivate_node_template("BoundingBox3DDisplay", 0, [self.render_product_path]) async def test_valid_cam3dpos_texture(self): SyntheticData.Get().activate_node_template("Camera3dPositionDisplay", 0, [self.render_product_path]) await self.wait_for_frames() display_output_names = ["outputs:rpResourcePtr", "outputs:width", "outputs:height", "outputs:format"] display_outputs = SyntheticData.Get().get_node_attributes("Camera3dPositionDisplay", display_output_names, self.render_product_path) assert(display_outputs and all(o in display_outputs for o in display_output_names) and display_outputs["outputs:rpResourcePtr"] != 0 and display_outputs["outputs:format"] == 11) SyntheticData.Get().deactivate_node_template("Camera3dPositionDisplay", 0, [self.render_product_path])
3,130
Python
61.619999
185
0.720447
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/tests/sensors/test_cross_correspondence.py
# NOTE: # omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests # For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html import os import math import asyncio from PIL import Image from time import time from pathlib import Path import carb import numpy as np from numpy.lib.arraysetops import unique import omni.kit.test from pxr import Gf, UsdGeom from omni.kit.viewport.utility import get_active_viewport, next_viewport_frame_async, create_viewport_window # Import extension python module we are testing with absolute import path, as if we are external user (other extension) import omni.syntheticdata as syn from ..utils import add_semantics FILE_DIR = os.path.dirname(os.path.realpath(__file__)) TIMEOUT = 200 cameras = ["/World/Cameras/CameraFisheyeLeft", "/World/Cameras/CameraPinhole", "/World/Cameras/CameraFisheyeRight"] # Having a test class derived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test # This test has to run last and thus it's prefixed as such to force that: # - This is because it has to create additional viewports which makes the test # get stuck if it's not the last one in the OV process session class ZZHasToRunLast_TestCrossCorrespondence(omni.kit.test.AsyncTestCase): def __init__(self, methodName: str) -> None: super().__init__(methodName=methodName) self.golden_image_path = Path(os.path.dirname(os.path.abspath(__file__))) / ".." / "data" / "golden" self.output_image_path = Path(os.path.dirname(os.path.abspath(__file__))) / ".." / "data" / "output" self.StdDevTolerance = 0.1 self.sensorViewport = None # Before running each test async def setUp(self): global cameras np.random.seed(1234) # Load the scene scenePath = os.path.join(FILE_DIR, "../data/scenes/cross_correspondence.usda") await omni.usd.get_context().open_stage_async(scenePath) await omni.kit.app.get_app().next_update_async() # Get the main-viewport as the sensor-viewport self.sensorViewport = get_active_viewport() await next_viewport_frame_async(self.sensorViewport) # Setup viewports resolution = self.sensorViewport.resolution viewport_windows = [None] * 2 x_pos, y_pos = 12, 75 for i in range(len(viewport_windows)): viewport_windows[i] = create_viewport_window(width=resolution[0], height=resolution[1], position_x=x_pos, position_y=y_pos) viewport_windows[i].width = 500 viewport_windows[i].height = 500 x_pos += 500 # Setup cameras self.sensorViewport.camera_path = cameras[0] for i in range(len(viewport_windows)): viewport_windows[i].viewport_api.camera_path = cameras[i + 1] async def test_golden_image_rt_cubemap(self): settings = carb.settings.get_settings() settings.set_string("/rtx/rendermode", "RaytracedLighting") settings.set_bool("/rtx/fishEye/useCubemap", True) await omni.kit.app.get_app().next_update_async() # Use default viewport for sensor target as otherwise sensor enablement doesn't work # also the test will get stuck # Initialize Sensor await syn.sensors.create_or_retrieve_sensor_async( self.sensorViewport, syn._syntheticdata.SensorType.CrossCorrespondence ) # Render one frame await syn.sensors.next_sensor_data_async(self.sensorViewport,True) data = syn.sensors.get_cross_correspondence(self.sensorViewport) golden_image = np.load(self.golden_image_path / "cross_correspondence.npz")["array"] # normalize xy (uv offset) to zw channels' value range # x100 seems like a good number to bring uv offset to ~1 data[:, [0, 1]] *= 100 golden_image[:, [0, 1]] *= 100 std_dev = np.sqrt(np.square(data - golden_image).astype(float).mean()) if std_dev >= self.StdDevTolerance: if not os.path.isdir(self.output_image_path): os.mkdir(self.output_image_path) np.savez_compressed(self.output_image_path / "cross_correspondence.npz", array=data) golden_image = ((golden_image + 1.0) / 2) * 255 data = ((data + 1.0) / 2) * 255 Image.fromarray(golden_image.astype(np.uint8), "RGBA").save( self.output_image_path / "cross_correspondence_golden.png" ) Image.fromarray(data.astype(np.uint8), "RGBA").save(self.output_image_path / "cross_correspondence.png") self.assertTrue(std_dev < self.StdDevTolerance) async def test_golden_image_rt_non_cubemap(self): settings = carb.settings.get_settings() settings.set_string("/rtx/rendermode", "RaytracedLighting") settings.set_bool("/rtx/fishEye/useCubemap", False) await omni.kit.app.get_app().next_update_async() # Use default viewport for sensor target as otherwise sensor enablement doesn't work # also the test will get stuck # Initialize Sensor await syn.sensors.create_or_retrieve_sensor_async( self.sensorViewport, syn._syntheticdata.SensorType.CrossCorrespondence ) # Render one frame await syn.sensors.next_sensor_data_async(self.sensorViewport,True) data = syn.sensors.get_cross_correspondence(self.sensorViewport) golden_image = np.load(self.golden_image_path / "cross_correspondence.npz")["array"] # normalize xy (uv offset) to zw channels' value range # x100 seems like a good number to bring uv offset to ~1 data[:, [0, 1]] *= 100 golden_image[:, [0, 1]] *= 100 std_dev = np.sqrt(np.square(data - golden_image).astype(float).mean()) if std_dev >= self.StdDevTolerance: if not os.path.isdir(self.output_image_path): os.mkdir(self.output_image_path) np.savez_compressed(self.output_image_path / "cross_correspondence.npz", array=data) golden_image = ((golden_image + 1.0) / 2) * 255 data = ((data + 1.0) / 2) * 255 Image.fromarray(golden_image.astype(np.uint8), "RGBA").save( self.output_image_path / "cross_correspondence_golden.png" ) Image.fromarray(data.astype(np.uint8), "RGBA").save(self.output_image_path / "cross_correspondence.png") self.assertTrue(std_dev < self.StdDevTolerance) async def test_golden_image_pt(self): settings = carb.settings.get_settings() settings.set_string("/rtx/rendermode", "PathTracing") settings.set_int("/rtx/pathtracing/spp", 32) settings.set_bool("/rtx/fishEye/useCubemap", False) await omni.kit.app.get_app().next_update_async() # Use default viewport for sensor target as otherwise sensor enablement doesn't work # also the test will get stuck # Initialize Sensor await syn.sensors.create_or_retrieve_sensor_async( self.sensorViewport, syn._syntheticdata.SensorType.CrossCorrespondence ) # Render one frame await syn.sensors.next_sensor_data_async(self.sensorViewport,True) data = syn.sensors.get_cross_correspondence(self.sensorViewport) golden_image = np.load(self.golden_image_path / "cross_correspondence.npz")["array"] # normalize xy (uv offset) to zw channels' value range # x100 seems like a good number to bring uv offset to ~1 data[:, [0, 1]] *= 100 golden_image[:, [0, 1]] *= 100 std_dev = np.sqrt(np.square(data - golden_image).astype(float).mean()) if std_dev >= self.StdDevTolerance: if not os.path.isdir(self.output_image_path): os.mkdir(self.output_image_path) np.savez_compressed(self.output_image_path / "cross_correspondence.npz", array=data) golden_image = ((golden_image + 1.0) / 2) * 255 data = ((data + 1.0) / 2) * 255 Image.fromarray(golden_image.astype(np.uint8), "RGBA").save( self.output_image_path / "cross_correspondence_golden.png" ) Image.fromarray(data.astype(np.uint8), "RGBA").save(self.output_image_path / "cross_correspondence.png") self.assertTrue(std_dev < self.StdDevTolerance) async def test_same_position(self): global cameras # Make sure our cross correspondence values converage around 0 when the target and reference cameras are # in the same position settings = carb.settings.get_settings() settings.set_string("/rtx/rendermode", "PathTracing") settings.set_int("/rtx/pathtracing/spp", 32) settings.set_bool("/rtx/fishEye/useCubemap", False) # Use default viewport for sensor target as otherwise sensor enablement doesn't work # also the test will get stuck # Move both cameras to the same position camera_left = omni.usd.get_context().get_stage().GetPrimAtPath(cameras[0]) camera_right = omni.usd.get_context().get_stage().GetPrimAtPath(cameras[2]) UsdGeom.XformCommonAPI(camera_left).SetTranslate(Gf.Vec3d(-10, 4, 0)) UsdGeom.XformCommonAPI(camera_right).SetTranslate(Gf.Vec3d(-10, 4, 0)) await omni.kit.app.get_app().next_update_async() # Initialize Sensor await syn.sensors.create_or_retrieve_sensor_async( self.sensorViewport, syn._syntheticdata.SensorType.CrossCorrespondence ) # Render one frame await syn.sensors.next_sensor_data_async(self.sensorViewport,True) raw_data = syn.sensors.get_cross_correspondence(self.sensorViewport) # Get histogram parameters du_scale = float(raw_data.shape[1] - 1) dv_scale = float(raw_data.shape[0] - 1) du_img = raw_data[:, :, 0] * du_scale dv_img = raw_data[:, :, 1] * dv_scale # Clear all invalid pixels by setting them to 10000.0 invalid_mask = (raw_data[:, :, 2] == -1) du_img[invalid_mask] = 10000.0 dv_img[invalid_mask] = 10000.0 # Selection mask du_selected = (du_img >= -1.0) & (du_img < 1.0) dv_selected = (dv_img >= -1.0) & (dv_img < 1.0) # Calculate bins bins = np.arange(-1.0, 1.0 + 0.1, 0.1) # calculate histograms for cross correspondence values along eacheach axis hist_du, edges_du = np.histogram(du_img[du_selected], bins=bins) hist_dv, edges_dv = np.histogram(dv_img[dv_selected], bins=bins) # ensure the (0.0, 0.0) bins contain the most values self.assertTrue(np.argmax(hist_du) == 10) self.assertTrue(np.argmax(hist_dv) == 10) # After running each test async def tearDown(self): pass
10,904
Python
42.795181
141
0.646735
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/tests/sensors/test_rendervar_buff_host_ptr.py
# NOTE: # omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests # For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html import unittest import numpy as np import ctypes import omni.kit.test from omni.gpu_foundation_factory import TextureFormat from omni.kit.viewport.utility import get_active_viewport from pxr import UsdGeom, UsdLux # Import extension python module we are testing with absolute import path, as if we are external user (other extension) import omni.syntheticdata as syn from ..utils import add_semantics # Test the SyntheticData following nodes : # - SdPostRenderVarTextureToBuffer : node to convert a texture device rendervar into a buffer device rendervar # - SdPostRenderVarToHost : node to readback a device rendervar into a host rendervar # - SdRenderVarPtr : node to expose in the action graph, raw device / host pointers on the renderVars # # the tests consists in pulling the ptr data and comparing it with the data ouputed by : # - SdRenderVarToRawArray # class TestRenderVarBuffHostPtr(omni.kit.test.AsyncTestCase): _tolerance = 1.1 _outputs_ptr = ["outputs:dataPtr","outputs:width","outputs:height","outputs:bufferSize","outputs:format", "outputs:strides"] _outputs_arr = ["outputs:data","outputs:width","outputs:height","outputs:bufferSize","outputs:format"] @staticmethod def _texture_element_size(texture_format): if texture_format == int(TextureFormat.RGBA16_SFLOAT): return 8 elif texture_format == int(TextureFormat.RGBA32_SFLOAT): return 16 elif texture_format == int(TextureFormat.R32_SFLOAT): return 4 elif texture_format == int(TextureFormat.RGBA8_UNORM): return 4 elif texture_format == int(TextureFormat.R32_UINT): return 4 else: return 0 @staticmethod def _assert_equal_tex_infos(out_a, out_b): assert((out_a["outputs:width"] == out_b["outputs:width"]) and (out_a["outputs:height"] == out_b["outputs:height"]) and (out_a["outputs:format"] == out_b["outputs:format"])) @staticmethod def _assert_equal_buff_infos(out_a, out_b): assert((out_a["outputs:bufferSize"] == out_b["outputs:bufferSize"])) @staticmethod def _assert_equal_data(data_a, data_b): assert(np.amax(np.square(data_a - data_b)) < TestRenderVarBuffHostPtr._tolerance) def _get_raw_array(self, render_var): ptr_outputs = syn.SyntheticData.Get().get_node_attributes(render_var + "ExportRawArray", TestRenderVarBuffHostPtr._outputs_arr, self.render_product) is_texture = ptr_outputs["outputs:width"] > 0 if is_texture: elem_size = TestRenderVarBuffHostPtr._texture_element_size(ptr_outputs["outputs:format"]) arr_shape = (ptr_outputs["outputs:height"], ptr_outputs["outputs:width"], elem_size) ptr_outputs["outputs:data"] = ptr_outputs["outputs:data"].reshape(arr_shape) return ptr_outputs def _get_ptr_array(self, render_var, ptr_suffix): ptr_outputs = syn.SyntheticData.Get().get_node_attributes(render_var + ptr_suffix, TestRenderVarBuffHostPtr._outputs_ptr, self.render_product) c_ptr = ctypes.cast(ptr_outputs["outputs:dataPtr"],ctypes.POINTER(ctypes.c_ubyte)) is_texture = ptr_outputs["outputs:width"] > 0 if is_texture: elem_size = TestRenderVarBuffHostPtr._texture_element_size(ptr_outputs["outputs:format"]) arr_shape = (ptr_outputs["outputs:height"], ptr_outputs["outputs:width"], elem_size) arr_strides = ptr_outputs["outputs:strides"] buffer_size = arr_strides[1] * arr_shape[1] arr_strides = (arr_strides[1], arr_strides[0], 1) data_ptr = np.ctypeslib.as_array(c_ptr,shape=(buffer_size,)) data_ptr = np.lib.stride_tricks.as_strided(data_ptr, shape=arr_shape, strides=arr_strides) else: data_ptr = np.ctypeslib.as_array(c_ptr,shape=(ptr_outputs["outputs:bufferSize"],)) ptr_outputs["outputs:dataPtr"] = data_ptr return ptr_outputs def _assert_equal_rv_ptr(self, render_var:str, ptr_suffix:str, texture=None): arr_out = self._get_raw_array(render_var) ptr_out = self._get_ptr_array(render_var,ptr_suffix) if not texture is None: if texture: TestRenderVarBuffHostPtr._assert_equal_tex_infos(arr_out,ptr_out) else: TestRenderVarBuffHostPtr._assert_equal_buff_infos(arr_out,ptr_out) TestRenderVarBuffHostPtr._assert_equal_data(arr_out["outputs:data"],ptr_out["outputs:dataPtr"]) def _assert_equal_rv_ptr_size(self, render_var:str, ptr_suffix:str, arr_size:int): ptr_out = self._get_ptr_array(render_var,ptr_suffix) data_ptr = ptr_out["outputs:dataPtr"] # helper for setting the value : print the size if None if arr_size is None: print(f"EqualRVPtrSize : {render_var} = {data_ptr.size}") else: assert(data_ptr.size==arr_size) def _assert_equal_rv_arr(self, render_var:str, ptr_suffix:str, texture=None): arr_out_a = self._get_raw_array(render_var) arr_out_b = self._get_raw_array(render_var+ptr_suffix) if not texture is None: if texture: TestRenderVarBuffHostPtr._assert_equal_tex_infos(arr_out_a,arr_out_b) else: TestRenderVarBuffHostPtr._assert_equal_buff_infos(arr_out_a,arr_out_b) TestRenderVarBuffHostPtr._assert_equal_data( arr_out_a["outputs:data"].flatten(),arr_out_b["outputs:data"].flatten()) def _assert_executed_rv_ptr(self, render_var:str, ptr_suffix:str): ptr_outputs = syn.SyntheticData.Get().get_node_attributes(render_var + ptr_suffix, ["outputs:exec"], self.render_product) assert(ptr_outputs["outputs:exec"]>0) def __init__(self, methodName: str) -> None: super().__init__(methodName=methodName) async def setUp(self): await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() world_prim = UsdGeom.Xform.Define(stage,"/World") UsdGeom.Xformable(world_prim).AddTranslateOp().Set((0, 0, 0)) UsdGeom.Xformable(world_prim).AddRotateXYZOp().Set((0, 0, 0)) sphere_prim = stage.DefinePrim("/World/Sphere", "Sphere") add_semantics(sphere_prim, "sphere") UsdGeom.Xformable(sphere_prim).AddTranslateOp().Set((0, 0, 0)) UsdGeom.Xformable(sphere_prim).AddScaleOp().Set((77, 77, 77)) UsdGeom.Xformable(sphere_prim).AddRotateXYZOp().Set((-90, 0, 0)) sphere_prim.GetAttribute("primvars:displayColor").Set([(1, 0.3, 1)]) capsule0_prim = stage.DefinePrim("/World/Sphere/Capsule0", "Capsule") add_semantics(capsule0_prim, "capsule0") UsdGeom.Xformable(capsule0_prim).AddTranslateOp().Set((3, 0, 0)) UsdGeom.Xformable(capsule0_prim).AddRotateXYZOp().Set((0, 0, 0)) capsule0_prim.GetAttribute("primvars:displayColor").Set([(0.3, 1, 0)]) capsule1_prim = stage.DefinePrim("/World/Sphere/Capsule1", "Capsule") add_semantics(capsule1_prim, "capsule1") UsdGeom.Xformable(capsule1_prim).AddTranslateOp().Set((-3, 0, 0)) UsdGeom.Xformable(capsule1_prim).AddRotateXYZOp().Set((0, 0, 0)) capsule1_prim.GetAttribute("primvars:displayColor").Set([(0, 1, 0.3)]) capsule2_prim = stage.DefinePrim("/World/Sphere/Capsule2", "Capsule") add_semantics(capsule2_prim, "capsule2") UsdGeom.Xformable(capsule2_prim).AddTranslateOp().Set((0, 3, 0)) UsdGeom.Xformable(capsule2_prim).AddRotateXYZOp().Set((0, 0, 0)) capsule2_prim.GetAttribute("primvars:displayColor").Set([(0.7, 0.1, 0.4)]) capsule3_prim = stage.DefinePrim("/World/Sphere/Capsule3", "Capsule") add_semantics(capsule3_prim, "capsule3") UsdGeom.Xformable(capsule3_prim).AddTranslateOp().Set((0, -3, 0)) UsdGeom.Xformable(capsule3_prim).AddRotateXYZOp().Set((0, 0, 0)) capsule3_prim.GetAttribute("primvars:displayColor").Set([(0.1, 0.7, 0.4)]) spherelight = UsdLux.SphereLight.Define(stage, "/SphereLight") spherelight.GetIntensityAttr().Set(30000) spherelight.GetRadiusAttr().Set(30) self.viewport = get_active_viewport() self.render_product = self.viewport.render_product_path await omni.kit.app.get_app().next_update_async() async def test_host_arr(self): render_vars = [ "BoundingBox2DLooseSD", "SemanticLocalTransformSD" ] for render_var in render_vars: syn.SyntheticData.Get().activate_node_template(render_var + "ExportRawArray", 0, [self.render_product]) syn.SyntheticData.Get().activate_node_template(render_var + "hostExportRawArray", 0, [self.render_product]) await syn.sensors.next_render_simulation_async(self.render_product, 1) for render_var in render_vars: self._assert_equal_rv_arr(render_var,"host", False) async def test_host_ptr_size(self): render_vars = { "BoundingBox3DSD" : 576, "BoundingBox2DLooseSD" : 144, "SemanticLocalTransformSD" : 320, "Camera3dPositionSD" : 14745600, "SemanticMapSD" : 10, "InstanceSegmentationSD" : 3686400, "SemanticBoundingBox3DCamExtentSD" : 120, "SemanticBoundingBox3DFilterInfosSD" : 24 } for render_var in render_vars: syn.SyntheticData.Get().activate_node_template(render_var + "hostPtr", 0, [self.render_product]) await syn.sensors.next_render_simulation_async(self.render_product, 1) for render_var, arr_size in render_vars.items(): self._assert_equal_rv_ptr_size(render_var,"hostPtr", arr_size) async def test_buff_arr(self): render_vars = [ "Camera3dPositionSD", "DistanceToImagePlaneSD", ] for render_var in render_vars: syn.SyntheticData.Get().activate_node_template(render_var + "ExportRawArray", 0, [self.render_product]) syn.SyntheticData.Get().activate_node_template(render_var + "buffExportRawArray", 0, [self.render_product]) await syn.sensors.next_render_simulation_async(self.render_product, 1) for render_var in render_vars: self._assert_equal_rv_arr(render_var, "buff") async def test_host_ptr(self): render_vars = [ "BoundingBox2DTightSD", "BoundingBox3DSD", "InstanceMapSD" ] for render_var in render_vars: syn.SyntheticData.Get().activate_node_template(render_var + "ExportRawArray", 0, [self.render_product]) syn.SyntheticData.Get().activate_node_template(render_var + "hostPtr", 0, [self.render_product]) await syn.sensors.next_render_simulation_async(self.render_product, 1) for render_var in render_vars: self._assert_equal_rv_ptr(render_var,"hostPtr",False) self._assert_executed_rv_ptr(render_var,"hostPtr") async def test_host_ptr_tex(self): render_vars = [ "NormalSD", "DistanceToCameraSD" ] for render_var in render_vars: syn.SyntheticData.Get().activate_node_template(render_var + "ExportRawArray", 0, [self.render_product]) syn.SyntheticData.Get().activate_node_template(render_var + "hostPtr", 0, [self.render_product]) await syn.sensors.next_render_simulation_async(self.render_product, 1) for render_var in render_vars: self._assert_equal_rv_ptr(render_var,"hostPtr",True) async def test_buff_host_ptr(self): render_vars = [ "LdrColorSD", "InstanceSegmentationSD", ] for render_var in render_vars: syn.SyntheticData.Get().activate_node_template(render_var + "ExportRawArray", 0, [self.render_product]) syn.SyntheticData.Get().activate_node_template(render_var + "buffhostPtr", 0, [self.render_product]) await syn.sensors.next_render_simulation_async(self.render_product, 1) for render_var in render_vars: self._assert_equal_rv_ptr(render_var, "buffhostPtr",True) async def test_empty_semantic_host_ptr(self): await omni.usd.get_context().new_stage_async() self.viewport = get_active_viewport() self.render_product = self.viewport.render_product_path await omni.kit.app.get_app().next_update_async() render_vars = [ "BoundingBox2DTightSD", "BoundingBox3DSD", "InstanceMapSD" ] for render_var in render_vars: syn.SyntheticData.Get().activate_node_template(render_var + "hostPtr", 0, [self.render_product]) await syn.sensors.next_render_simulation_async(self.render_product, 1) for render_var in render_vars: self._assert_executed_rv_ptr(render_var,"hostPtr") # After running each test async def tearDown(self): pass
13,257
Python
48.103704
156
0.646225
omniverse-code/kit/exts/omni.usd.schema.audio/pxr/AudioSchema/__init__.py
#!/usr/bin/env python3 # # Copyright (c) 2020-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.log omni.log.warn("pxr.AudioSchema is deprecated - please use pxr.OmniAudioSchema instead") from pxr.OmniAudioSchema import *
597
Python
34.176469
87
0.80067
omniverse-code/kit/exts/omni.rtx.ujitsoprocessors/omni/rtx/ujitsoprocessors/__init__.py
from ._ujitsoprocessors import *
33
Python
15.999992
32
0.787879
omniverse-code/kit/exts/omni.rtx.ujitsoprocessors/omni/rtx/ujitsoprocessors/tests/__init__.py
from .test_ujitsoprocessors import *
37
Python
17.999991
36
0.810811
omniverse-code/kit/exts/omni.rtx.ujitsoprocessors/omni/rtx/ujitsoprocessors/tests/test_ujitsoprocessors.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.app from omni.kit.test import AsyncTestCase import pathlib import omni.rtx.ujitsoprocessors try: import omni.kit.test TestClass = omni.kit.test.AsyncTestCase TEST_DIR = str(pathlib.Path(__file__).parent.parent.parent.parent.parent.parent.parent) except ImportError: from . import TestRtScenegraph TestClass = TestRtScenegraph TEST_DIR = "." class TestConverter(AsyncTestCase): async def setUp(self): self._iface = omni.rtx.ujitsoprocessors.acquire_ujitsoprocessors_interface() async def tearDown(self): pass async def test_001_startstop(self): print(self._iface.runHTTPJobs("", ""));
1,104
Python
29.694444
91
0.744565
omniverse-code/kit/exts/omni.kit.window.privacy/omni/kit/window/privacy/__init__.py
from .privacy_window import *
30
Python
14.499993
29
0.766667
omniverse-code/kit/exts/omni.kit.window.privacy/omni/kit/window/privacy/privacy_window.py
import toml import os import asyncio import weakref import carb import carb.settings import carb.tokens import omni.client import omni.kit.app import omni.kit.ui import omni.ext from omni import ui WINDOW_NAME = "About" class PrivacyWindow: def __init__(self, privacy_file=None): if not privacy_file: privacy_file = carb.tokens.get_tokens_interface().resolve("${omni_config}/privacy.toml") privacy_data = toml.load(privacy_file) if os.path.exists(privacy_file) else {} # NVIDIA Employee? privacy_dict = privacy_data.get("privacy", {}) userId = privacy_dict.get("userId", None) if not userId or not userId.endswith("@nvidia.com"): return # Already set? extraDiagnosticDataOptIn = privacy_dict.get("extraDiagnosticDataOptIn", None) if extraDiagnosticDataOptIn: return self._window = ui.Window( "Privacy", flags=ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE, auto_resize=True, ) def on_ok_clicked(): allow_for_public_build = self._cb.model.as_bool carb.log_info(f"writing privacy file: '{privacy_file}'. allow_for_public_build: {allow_for_public_build}") privacy_data.setdefault("privacy", {})["extraDiagnosticDataOptIn"] = ( "externalBuilds" if allow_for_public_build else "internalBuilds" ) with open(privacy_file, "w") as f: toml.dump(privacy_data, f) self._window.visible = False text = """ By accessing or using Omniverse Beta, you agree to share usage and performance data as well as diagnostic data, including crash data. This will help us to optimize our features, prioritize development, and make positive changes for future development. As an NVIDIA employee, your email address will be associated with any collected diagnostic data from internal builds to help us improve Omniverse. Below, you can optionally choose to associate your email address with any collected diagnostic data from publicly available builds. Please contact us at [email protected] for any questions. """ with self._window.frame: with ui.ZStack(width=0, height=0): with ui.VStack(style={"margin": 5}, height=0): ui.Label(text, width=600, style={"font_size": 18}, word_wrap=True) ui.Separator() with ui.HStack(height=0): self._cb = ui.CheckBox(width=0, height=0) self._cb.model.set_value(True) ui.Label( "Associate my @nvidia.com email address with diagnostic data from publicly available builds.'", value=True, style={"font_size": 16}, ) with ui.HStack(height=0): ui.Spacer() ui.Button("OK", width=100, clicked_fn=lambda: on_ok_clicked()) ui.Spacer() self._window.visible = True self.on_ok_clicked = on_ok_clicked async def _create_window(ext_weak): # Wait for few frames to get everything in working state first for _ in range(5): await omni.kit.app.get_app().next_update_async() if ext_weak(): ext_weak()._window = PrivacyWindow() class Extension(omni.ext.IExt): def on_startup(self, ext_id): asyncio.ensure_future(_create_window(weakref.ref(self))) def on_shutdown(self): self._window = None
3,676
Python
37.302083
359
0.606094
omniverse-code/kit/exts/omni.kit.window.privacy/omni/kit/window/privacy/tests/__init__.py
from .test_window_privacy import *
35
Python
16.999992
34
0.771429
omniverse-code/kit/exts/omni.kit.window.privacy/omni/kit/window/privacy/tests/test_window_privacy.py
import tempfile import toml import omni.kit.test import omni.kit.window.privacy class TestPrivacyWindow(omni.kit.test.AsyncTestCase): async def test_privacy(self): with tempfile.TemporaryDirectory() as tmp_dir: privacy_file = f"{tmp_dir}/privacy.toml" def write_data(data): with open(privacy_file, "w") as f: toml.dump(data, f) # NVIDIA User, first time write_data({"privacy": {"userId": "[email protected]"}}) w = omni.kit.window.privacy.PrivacyWindow(privacy_file) self.assertIsNotNone(w._window) w.on_ok_clicked() data = toml.load(privacy_file) self.assertEqual(data["privacy"]["extraDiagnosticDataOptIn"], "externalBuilds") # NVIDIA User, second time w = omni.kit.window.privacy.PrivacyWindow(privacy_file) self.assertFalse(hasattr(w, "_window")) # NVIDIA User, first time, checkbox off write_data({"privacy": {"userId": "[email protected]"}}) w = omni.kit.window.privacy.PrivacyWindow(privacy_file) self.assertIsNotNone(w._window) w._cb.model.set_value(False) w.on_ok_clicked() data = toml.load(privacy_file) self.assertEqual(data["privacy"]["extraDiagnosticDataOptIn"], "internalBuilds") # Non NVIDIA User write_data({"privacy": {"userId": "[email protected]"}}) w = omni.kit.window.privacy.PrivacyWindow(privacy_file) self.assertFalse(hasattr(w, "_window"))
1,602
Python
34.622221
91
0.591136
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/ext_utils.py
from __future__ import annotations from collections import defaultdict from contextlib import suppress from types import ModuleType from typing import Dict, Tuple import fnmatch import sys import unittest import carb import omni.kit.app from .unittests import get_tests_to_remove_from_modules # Type for collecting module information corresponding to extensions ModuleMap_t = Dict[str, Tuple[str, bool]] # ============================================================================================================== def get_module_to_extension_map() -> ModuleMap_t: """Returns a dictionary mapping the names of Python modules in an extension to (OwningExtension, EnabledState) e.g. for this extension it would contain {"omni.kit.test": (["omni.kit.test", True])} It will be expanded to include the implicit test modules added by the test management. """ module_map = {} manager = omni.kit.app.get_app().get_extension_manager() for extension in manager.fetch_extension_summaries(): ext_id = None enabled = False with suppress(KeyError): if extension["enabled_version"]["enabled"]: ext_id = extension["enabled_version"]["id"] enabled = True if ext_id is None: try: ext_id = extension["latest_version"]["id"] except KeyError: # Silently skip any extensions that do not have enough information to identify them continue ext_dict = manager.get_extension_dict(ext_id) # Look for the defined Python modules, skipping processing of any extensions that have no Python modules try: module_list = ext_dict["python"]["module"] except (KeyError, TypeError): continue # Walk through the list of all modules independently as there is no guarantee they are related. for module in module_list: # Some modules do not have names, only paths - just ignore them with suppress(KeyError): module_map[module["name"]] = (ext_id, enabled) # Add the two test modules that are explicitly added by the testing system if not module["name"].endswith(".tests"): module_map[module["name"] + ".tests"] = (ext_id, enabled) module_map[module["name"] + ".ogn.tests"] = (ext_id, enabled) return module_map # ============================================================================================================== def extension_from_test_name(test_name: str, module_map: ModuleMap_t) -> tuple[str, bool, str, bool] | None: """Given a test name, return None if the extension couldn't be inferred from the name, otherwise a tuple containing the name of the owning extension, a boolean indicating if it is currently enabled, a string indicating in which Python module the test was found, and a boolean indicating if that module is currently imported, or None if it was not. Args: test_name: Full name of the test to look up module_map: Module to extension mapping. Passed in for sharing as it's expensive to compute. The algorithm walks backwards from the full name to find the maximum-length Python import module known to be part of an extension that is part of the test name. It does this because the exact import paths can be nested or not nested. e.g. omni.kit.window.tests is not part of omni.kit.window Extracting the extension from the test name is a little tricky but all of the information is available. Here is how it attempts to decompose a sample test name .. code-block:: text omni.graph.nodes.tests.tests_for_samples.TestsForSamples.test_for_sample +--------------+ +---+ +---------------+ +-------------+ +-------------+ Import path | | | | Testing subdirectory | | | | | Test File Test Class Test Name Each extension has a list of import paths of Python modules it explicitly defines, and in addition it will add implicit imports for .tests and .ogn.tests submodules that are not explicitly listed in the extension dictionary. With this structure the user could have done any of these imports: .. code-block:: python import omni.graph.nodes import omni.graph.nodes.tests import omni.graph.nodes.test_for_samples Each nested one may or may not have been exposed by the parent so it is important to do a greedy match. This is how the process of decoding works for this test: .. code-block:: text Split the test name on "." ["omni", "graph", "nodes", "tests", "tests_for_samples", "TestsForSamples", "test_for_sample"] Starting at the entire list, recursively remove one element until a match in the module dictionary is found Fail: "omni.graph.nodes.tests.tests_for_samples.TestsForSamples.test_for_sample" Fail: "omni.graph.nodes.tests.tests_for_samples.TestsForSamples" Fail: "omni.graph.nodes.tests.tests_for_samples" Succeed: "omni.graph.nodes.tests" If no success, of if sys.modules does not contain the found module: Return the extension id, enabled state, and None for the module Else: Check the module recursively for exposed attributes with the rest of the names. In this example: file_object = getattr(module, "tests_for_samples") class_object = getattr(file_object, "TestsForSamples") test_object = getattr(class_object, "test_for_sample") If test_object is valid: Return the extension id, enabled state, and the found module Else: Return the extension id, enabled state, and None for the module """ class_elements = test_name.split(".") for el in range(len(class_elements), 0, -1): check_module = ".".join(class_elements[:el]) # If the extension owned the module then process it, otherwise continue up to the parent element try: (ext_id, is_enabled) = module_map[check_module] except KeyError: continue # The module was found in an extension definition but not imported into the Python namespace yet try: module = sys.modules[check_module] except KeyError: return (ext_id, is_enabled, check_module, False) # This checks to make sure that the actual test is registered in the module that was found. # e.g. if the full name is omni.graph.nodes.tests.TestStuff.test_stuff then we would expect to find # a module named "omni.graph.nodes.tests" that contains "TestStuff", and the object "TestStuff" will # in turn contain "test_stuff". sub_module = module for elem in class_elements[el:]: sub_module = getattr(sub_module, elem, None) if sub_module is None: break return (ext_id, is_enabled, module, sub_module is not None) return None # ============================================================================================================== def test_only_extension_dependencies(ext_id: str) -> set[str]: """Returns a set of extensions with test-only dependencies on the given one. Not currently used as dynamically enabling random extensions is not stable enough to use here yet. """ test_only_extensions = set() # Set of extensions that are enabled only in testing mode manager = omni.kit.app.get_app().get_extension_manager() ext_dict = manager.get_extension_dict(ext_id) # Find the test-only dependencies that may also not be enabled yet if ext_dict and "test" in ext_dict: for test_info in ext_dict["test"]: try: new_extensions = test_info["dependencies"] except (KeyError, TypeError): new_extensions = [] for new_extension in new_extensions: with suppress(KeyError): test_only_extensions.add(new_extension) return test_only_extensions # ============================================================================================================== def decompose_test_list( test_list: list[str] ) -> tuple[list[unittest.TestCase], set[str], set[str], defaultdict[str, set[str]]]: """Read in the given log file and return the list of tests that were run, in the order in which they were run. TODO: Move this outside the core omni.kit.test area as it requires external knowledge If any modules containing the tests in the log are not currently available then they are reported for the user to intervene and most likely enable the owning extensions. Args: test_list: List of tests to decompose and find modules and extensions for Returns: Tuple of (tests, not_found, extensions, modules) gleaned from the log file tests: List of unittest.TestCase for all tests named in the log file, in the order they appeared not_found: Name of tests whose location could not be determined, or that did not exist extensions: Name of extensions containing modules that look like they contain tests from "not_found" modules: Map of extension to list of modules where the extension is enabled but the module potentially containing the tests from "not_found" has not been imported. """ module_map = get_module_to_extension_map() not_found = set() # The set of full names of tests whose module was not found # Map of enabled extensions to modules in them that contain tests in the log but which are not imported modules_not_imported = defaultdict(set) test_names = [] modules_found = set() # Modules matching the tests extensions_to_enable = set() # Walk the test list and parse out all of the test run information for test_name in test_list: test_info = extension_from_test_name(test_name, module_map) if test_info is None: not_found.add(test_name) else: (ext_id, ext_enabled, module, module_imported) = test_info if ext_enabled: if module is None: not_found.add(test_name) elif not module_imported: modules_not_imported[ext_id].add(module) else: test_names.append(test_name) modules_found.add(module) else: extensions_to_enable.add(ext_id) # Carefully find all of the desired test cases, preserving the order in which they were encountered since that is # a key feature of reading tests from a log test_mapping: dict[str, unittest.TestCase] = {} # Mapping of test name onto discovered test case for running for module in modules_found: # Find all of the individual tests in the TestCase classes and add those that match any of the disabled patterns # Uses get_tests_to_remove_from_modules because it considers possible tests and ogn.tests submodules test_cases = get_tests_to_remove_from_modules([module]) for test_case in test_cases: if test_case.id() in test_names: test_mapping[test_case.id()] = test_case tests: list[unittest.TestCase] = [] for test_name in test_names: if test_name in test_mapping: tests.append(test_mapping[test_name]) return (tests, not_found, extensions_to_enable, modules_not_imported) # ============================================================================================================== def find_disabled_tests() -> list[unittest.TestCase]: """Scan the existing tests and the extension.toml to find all tests that are currently disabled""" manager = omni.kit.app.get_app().get_extension_manager() # Find the per-extension list of (python_modules, disabled_patterns). def __get_disabled_patterns() -> list[tuple[list[ModuleType], list[str]]]: disabled_patterns = [] summaries = manager.fetch_extension_summaries() for extension in summaries: try: if not extension["enabled_version"]["enabled"]: continue except KeyError: carb.log_info(f"Could not find enabled state of extension {extension}") continue ext_id = extension["enabled_version"]["id"] ext_dict = manager.get_extension_dict(ext_id) # Look for the defined Python modules modules = [] with suppress(KeyError, TypeError): modules += [sys.modules[module_info["name"]] for module_info in ext_dict["python"]["module"]] # Look for unreliable tests regex_list = [] with suppress(KeyError, TypeError): test_info = ext_dict["test"] for test_details in test_info or []: with suppress(KeyError): regex_list += test_details["pythonTests"]["unreliable"] if regex_list: disabled_patterns.append((modules, regex_list)) return disabled_patterns # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - def _match(to_match: str, pattern: str) -> bool: """Match that supports wildcards and '!' to invert it""" should_match = True if pattern.startswith("!"): pattern = pattern[1:] should_match = False return should_match == fnmatch.fnmatch(to_match, pattern) tests = [] for modules, regex_list in __get_disabled_patterns(): # Find all of the individual tests in the TestCase classes and add those that match any of the disabled patterns # Uses get_tests_to_remove_from_modules because it considers possible tests and ogn.tests submodules test_cases = get_tests_to_remove_from_modules(modules) for test_case in test_cases: for regex in regex_list: if _match(test_case.id(), regex): tests.append(test_case) break return tests
14,477
Python
46.782178
120
0.60344
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/ext_test_generator.py
# WARNING: This file/interface is likely to be removed after transition from Legacy Viewport is complete. # Seee merge_requests/17255 __all__ = ["get_tests_to_run"] # Rewrite a Legacy Viewport test to launch with Viewport backend only def _get_viewport_next_test_config(test): # Check for flag to run test only on legacy Viewport if test.config.get("viewport_legacy_only", False): return None # Get the test dependencies test_dependencies = test.config.get("dependencies", tuple()) # Check if legacy Viewport is in the test dependency list if "omni.kit.window.viewport" not in test_dependencies: return None # Deep copy the config dependencies test_dependencies = list(test_dependencies) # Re-write any 'omni.kit.window.viewport' dependency as 'omni.kit.viewport.window' for i in range(len(test_dependencies)): cur_dep = test_dependencies[i] if cur_dep == "omni.kit.window.viewport": test_dependencies[i] = "omni.kit.viewport.window" # Shallow copy of the config test_config = test.config.copy() # set the config name test_config["name"] = "viewport_next" # Replace the dependencies test_config["dependencies"] = test_dependencies # Add any additional args by deep copying the arg list test_args = list(test.config.get("args", tuple())) test_args.append("--/exts/omni.kit.viewport.window/startup/windowName=Viewport") # Replace the args test_config["args"] = test_args # TODO: Error if legacy Viewport somehow still inserting itself into the test run # Return the new config return test_config def get_tests_to_run(test, ExtTest, run_context, is_parallel_run: bool, valid: bool): """For a test gather all unique test-runs that should be invoked""" # First run the additional tests, followed by the original / base-case # No need to run additional tests of the original is not valid if valid: # Currently the only usage of this method is to have legacy Viewport test run against new Viewport additional_tests = { 'viewport_next': _get_viewport_next_test_config } for test_name, get_config in additional_tests.items(): new_config = get_config(test) if new_config: yield ExtTest( ext_id=test.ext_id, ext_info=test.ext_info, test_config=new_config, test_id=f"{test.test_id}-{test_name}", is_parallel_run=is_parallel_run, run_context=run_context, test_app=test.test_app, valid=valid ) # Run the original / base-case yield test
2,762
Python
35.84
106
0.640116
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/teamcity.py
import os import sys import time import pathlib from functools import lru_cache _quote = {"'": "|'", "|": "||", "\n": "|n", "\r": "|r", "[": "|[", "]": "|]"} def escape_value(value): return "".join(_quote.get(x, x) for x in value) @lru_cache() def is_running_in_teamcity(): return bool(os.getenv("TEAMCITY_VERSION")) @lru_cache() def get_teamcity_build_url() -> str: teamcity_url = os.getenv("TEAMCITY_BUILD_URL") if teamcity_url and not teamcity_url.startswith("http"): teamcity_url = "https://" + teamcity_url return teamcity_url or "" # TeamCity Service messages documentation # https://www.jetbrains.com/help/teamcity/service-messages.html def teamcity_publish_artifact(artifact_path: str, stream=sys.stdout): if not is_running_in_teamcity(): return tc_message = f"##teamcity[publishArtifacts '{escape_value(artifact_path)}']\n" stream.write(tc_message) stream.flush() def teamcity_log_fail(teamCityName, msg, stream=sys.stdout): if not is_running_in_teamcity(): return tc_message = f"##teamcity[testFailed name='{teamCityName}' message='{teamCityName} failed. Reason {msg}. Check artifacts for logs']\n" stream.write(tc_message) stream.flush() def teamcity_test_retry_support(enabled: bool, stream=sys.stdout): """ With this option enabled, the successful run of a test will mute its previous failure, which means that TeamCity will mute a test if it fails and then succeeds within the same build. Such tests will not affect the build status. """ if not is_running_in_teamcity(): return retry_support = str(bool(enabled)).lower() tc_message = f"##teamcity[testRetrySupport enabled='{retry_support}']\n" stream.write(tc_message) stream.flush() def teamcity_show_image(label: str, image_path: str, stream=sys.stdout): if not is_running_in_teamcity(): return tc_message = f"##teamcity[testMetadata type='image' name='{label}' value='{image_path}']\n" stream.write(tc_message) stream.flush() def teamcity_publish_image_artifact(src_path: str, dest_path: str, inline_image_label: str = None, stream=sys.stdout): if not is_running_in_teamcity(): return tc_message = f"##teamcity[publishArtifacts '{src_path} => {dest_path}']\n" stream.write(tc_message) if inline_image_label: result_path = str(pathlib.PurePath(dest_path).joinpath(os.path.basename(src_path)).as_posix()) teamcity_show_image(inline_image_label, result_path) stream.flush() def teamcity_message(message_name, stream=sys.stdout, **properties): if not is_running_in_teamcity(): return current_time = time.time() (current_time_int, current_time_fraction) = divmod(current_time, 1) current_time_struct = time.localtime(current_time_int) timestamp = time.strftime("%Y-%m-%dT%H:%M:%S.", current_time_struct) + "%03d" % (int(current_time_fraction * 1000)) message = "##teamcity[%s timestamp='%s'" % (message_name, timestamp) for k in sorted(properties.keys()): value = properties[k] if value is None: continue message += f" {k}='{escape_value(str(value))}'" message += "]\n" # Python may buffer it for a long time, flushing helps to see real-time result stream.write(message) stream.flush() # Based on metadata message for TC: # https://www.jetbrains.com/help/teamcity/reporting-test-metadata.html#Reporting+Additional+Test+Data def teamcity_metadata_message(metadata_value, stream=sys.stdout, metadata_name="", metadata_testname=""): teamcity_message( "testMetadata", stream=stream, testName=metadata_testname, name=metadata_name, value=metadata_value, ) def teamcity_status(text, status: str = "success", stream=sys.stdout): teamcity_message("buildStatus", stream=stream, text=text, status=status)
3,924
Python
30.910569
138
0.667686
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/repo_test_context.py
import json import logging import os logger = logging.getLogger(__name__) class RepoTestContext: # pragma: no cover def __init__(self): self.context = None repo_test_context_file = os.environ.get("REPO_TEST_CONTEXT", None) if repo_test_context_file and os.path.exists(repo_test_context_file): print("Found repo test context file:", repo_test_context_file) with open(repo_test_context_file) as f: self.context = json.load(f) logger.info("repo test context:", self.context) def get(self): return self.context
609
Python
28.047618
77
0.627258
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/nvdf.py
import itertools import json import logging import os import re import sys import time import urllib.error import urllib.request from collections import defaultdict from functools import lru_cache from pathlib import Path from typing import Dict, List, Tuple import carb.settings import omni.kit.app from .gitlab import get_gitlab_build_url, is_running_in_gitlab from .teamcity import get_teamcity_build_url, is_running_in_teamcity from .utils import call_git, get_global_test_output_path, is_running_on_ci logger = logging.getLogger(__name__) @lru_cache() def get_nvdf_report_filepath() -> str: return os.path.join(get_global_test_output_path(), "nvdf_data.json") def _partition(pred, iterable): """Use a predicate to partition entries into false entries and true entries""" t1, t2 = itertools.tee(iterable) return itertools.filterfalse(pred, t1), filter(pred, t2) def _get_json_data(report_data: List[Dict[str, str]], app_info: dict, ci_info: dict) -> Dict: """Transform report_data into json data Input: {"event": "start", "test_id": "omni.kit.viewport", "ext_name": "omni.kit.viewport", "start_time": 1664831914.002093} {"event": "stop", "test_id": "omni.kit.viewport", "ext_name": "omni.kit.viewport", "success": true, "skipped": false, "stop_time": 1664831927.1145973, "duration": 13.113} ... Output: { "omni.kit.viewport+omni.kit.viewport": { "app": { ... }, "teamcity": { ... }, "test": { "b_success": false, "d_duration": 1.185, "s_ext_name": "omni.kit.viewport", "s_name": "omni.kit.viewport", "s_type": "exttest", "ts_start_time": 1664893802530, "ts_stop_time": 1664893803715 "result": { ... }, }, }, } """ def _aggregate_json_data(data: dict, config=""): test_id = data["test_id"] + config # increment retries count - that info is not available in the report_data, start count at 0 (-1 + 1 = 0) # by keeping all passed results we can know if all retries failed and set consecutive_failure to true if data["event"] == "start": retries = test_retries.get(test_id, -1) + 1 test_retries[test_id] = retries data["retries"] = retries else: retries = test_retries.get(test_id, 0) if data["event"] == "stop": test_results[test_id].append(data.get("passed", False)) test_id += f"{CONCAT_CHAR}{retries}" test_data = json_data.get(test_id, {}).get("test", {}) test_data.update(data) # special case for time, convert it to nvdf ts_ format right away if "start_time" in test_data: test_data["ts_start_time"] = int(test_data.pop("start_time") * 1000) if "stop_time" in test_data: test_data["ts_stop_time"] = int(test_data.pop("stop_time") * 1000) # event is discarded if "event" in test_data: test_data.pop("event") # init passed to false if needed, it can be missing if a test crashes (no stop event) if "passed" not in test_data: test_data["passed"] = False json_data.update({test_id: {"app": app_info, "ci": ci_info, "test": test_data}}) CONCAT_CHAR = "|" MIN_CONSECUTIVE_FAILURES = 3 # this value is in sync with repo.toml testExtMaxTestRunCount=3 test_retries: Dict[str, int] = {} test_results = defaultdict(list) exttest, unittest = _partition(lambda data: data["test_type"] == "unittest", report_data) # add exttests - group by name + retry count json_data: Dict[str, str] = {} for data in exttest: _aggregate_json_data(data) # second loop to only keep exttest with results for key, data in list(json_data.items()): if not data.get("test", {}).get("result"): del json_data[key] # add all unittests - group by name + config + retry count for data in unittest: config = data["ext_test_id"].rsplit(CONCAT_CHAR, maxsplit=1) config = f"{CONCAT_CHAR}{config[1]}" if len(config) > 1 else "" _aggregate_json_data(data, config) # second loop to tag all consecutive failures (when all results are false and equal or above the retry count) for key, data in json_data.items(): results = test_results.get(key.rsplit(CONCAT_CHAR, maxsplit=1)[0]) all_failures = results and not any(results) and len(results) >= MIN_CONSECUTIVE_FAILURES - 1 if all_failures: data["test"]["consecutive_failure"] = all_failures return json_data def _can_post_to_nvdf() -> bool: if omni.kit.app.get_app().is_app_external(): logger.info("nvdf is disabled for external build") return False if not is_running_on_ci(): logger.info("nvdf posting only enabled on CI") return False return True def post_to_nvdf(report_data: List[Dict[str, str]]): if not report_data or not _can_post_to_nvdf(): return try: app_info = get_app_info() ci_info = _get_ci_info() json_data = _get_json_data(report_data, app_info, ci_info) with open(get_nvdf_report_filepath(), "w") as f: json.dump(json_data, f, skipkeys=True, sort_keys=True, indent=4) # convert json_data to nvdf form and add to list json_array = [] for data in json_data.values(): data["ts_created"] = int(time.time() * 1000) json_array.append(to_nvdf_form(data)) # post all results in one request project = "omniverse-kit-tests-results-v2" json_str = json.dumps(json_array, skipkeys=True) _post_json(project, json_str) # print(json_str) # uncomment to debug except Exception as e: logger.warning(f"Exception occurred: {e}") def post_coverage_to_nvdf(coverage_data: Dict[str, Dict]): if not coverage_data or not _can_post_to_nvdf(): return try: app_info = get_app_info() ci_info = _get_ci_info() # convert json_data to nvdf form and add to list json_array = [] for data in coverage_data.values(): data["ts_created"] = int(time.time() * 1000) data["app"] = app_info data["ci"] = ci_info json_array.append(to_nvdf_form(data)) # post all results in one request project = "omniverse-kit-tests-coverage-v2" json_str = json.dumps(json_array, skipkeys=True) _post_json(project, json_str) # print(json_str) # uncomment to debug except Exception as e: logger.warning(f"Exception occurred: {e}") def _post_json(project: str, json_str: str): url = f"https://gpuwa.nvidia.com/dataflow/{project}/posting" try: resp = None req = urllib.request.Request(url) req.add_header("Content-Type", "application/json; charset=utf-8") json_data_bytes = json_str.encode("utf-8") # needs to be bytes # use a short 10 seconds timeout to avoid taking too much time in case of problems resp = urllib.request.urlopen(req, json_data_bytes, timeout=10) except (urllib.error.URLError, json.JSONDecodeError) as e: logger.warning(f"Error sending request to nvdf, response: {resp}, exception: {e}") def query_nvdf(query: str) -> dict: project = "df-omniverse-kit-tests-results-v2*" url = f"https://gpuwa.nvidia.com:443/elasticsearch/{project}/_search" try: resp = None req = urllib.request.Request(url) req.add_header("Content-Type", "application/json; charset=utf-8") json_data = json.dumps(query).encode("utf-8") # use a short 10 seconds timeout to avoid taking too much time in case of problems with urllib.request.urlopen(req, data=json_data, timeout=10) as resp: return json.loads(resp.read()) except (urllib.error.URLError, json.JSONDecodeError) as e: logger.warning(f"Request error to nvdf, response: {resp}, exception: {e}") return {} @lru_cache() def _detect_kit_branch_and_mr(full_kit_version: str) -> Tuple[str, int]: match = re.search(r"^([^\+]+)\+([^\.]+)", full_kit_version) if match is None: logger.warning(f"Cannot detect kit SDK branch from: {full_kit_version}") branch = "Unknown" else: if match[2] == "release": branch = f"release/{match[1]}" else: branch = match[2] # merge requests will be named mr1234 with 1234 being the merge request number if branch.startswith("mr") and branch[2:].isdigit(): mr = int(branch[2:]) branch = "" # if we have an mr we don't have the branch name else: mr = 0 return branch, mr @lru_cache() def _find_repository_info() -> str: """Get repo remote origin url, fallback on yaml if not found""" res = call_git(["config", "--get", "remote.origin.url"]) remote_url = res.stdout.strip("\n") if res and res.returncode == 0 else "" if remote_url: return remote_url # Attempt to find the repository from yaml file kit_root = Path(sys.argv[0]).parent if kit_root.stem.lower() != "kit": info_yaml = kit_root.joinpath("INFO.yaml") if not info_yaml.exists(): info_yaml = kit_root.joinpath("PACKAGE-INFO.yaml") if info_yaml.exists(): repo_re = re.compile(r"^Repository\s*:\s*(.+)$", re.MULTILINE) content = info_yaml.read_text() matches = repo_re.findall(content) if len(matches) == 1: return matches[0].strip() return "" @lru_cache() def get_app_info() -> Dict: """This should be part of omni.kit.app. Example response: { "app_name": "omni.app.full.kit", "app_version": "1.0.1", "kit_version_full": "103.1+release.10030.f5f9dcab.tc", "kit_version": "103.1", "kit_build_number": 10030, "branch": "master" "config": "release", "platform": "windows-x86_64", "python_version": "cp37" } """ app = omni.kit.app.get_app() ver = app.get_build_version() # eg 103.1+release.10030.f5f9dcab.tc branch, mr = _detect_kit_branch_and_mr(ver) settings = carb.settings.get_settings() info = { "app_name": settings.get("/app/name"), "app_name_full": settings.get("/app/window/title") or settings.get("/app/name"), "app_version": settings.get("/app/version"), "branch": branch, "merge_request": mr, "git_hash": ver.rsplit(".", 2)[1], "git_remote_url": _find_repository_info(), "kit_version_full": ver, "kit_version": ver.split("+", 1)[0], "kit_build_number": int(ver.rsplit(".", 3)[1]), } info.update(app.get_platform_info()) return info @lru_cache() def _get_ci_info() -> Dict: info = { "ci_name": "local", } if is_running_in_teamcity(): info.update( { "ci_name": "teamcity", "build_id": os.getenv("TEAMCITY_BUILD_ID") or "", "build_config_name": os.getenv("TEAMCITY_BUILDCONF_NAME") or "", "build_url": get_teamcity_build_url(), "project_name": os.getenv("TEAMCITY_PROJECT_NAME") or "", } ) elif is_running_in_gitlab(): info.update( { "ci_name": "gitlab", "build_id": os.getenv("CI_PIPELINE_ID") or "", "build_config_name": os.getenv("CI_JOB_NAME") or "", "build_url": get_gitlab_build_url(), "project_name": os.getenv("CI_PROJECT_NAME") or "", } ) # todo : support github return info def to_nvdf_form(data: dict) -> Dict: """Convert dict to NVDF-compliant form. https://confluence.nvidia.com/display/nvdataflow/NVDataFlow#NVDataFlow-PostingPayload """ reserved = {"ts_created", "_id"} prefixes = {str: "s_", float: "d_", int: "l_", bool: "b_", list: "obj_", tuple: "obj_"} key_illegal_pattern = "[!@#$%^&*.]+" def _convert(d): result = {} try: for key, value in d.items(): key = re.sub(key_illegal_pattern, "_", key) if key in reserved: result[key] = value elif key.startswith("ts_"): result[key] = value elif isinstance(value, dict): # note that nvdf docs state this should prefix with 'obj_', but without works also. # We choose not to as it matches up with existing fields from kit benchmarking result[key] = _convert(value) elif hasattr(value, "__dict__"): # support for Classes result[key] = _convert(value.__dict__) elif isinstance(value, (list, tuple)): _type = type(value[0]) if value else str result[prefixes[_type] + key] = value elif isinstance(value, (str, float, int, bool)): result[prefixes[type(value)] + key] = value else: raise ValueError(f"Type {type(value)} not supported in nvdf (data: {data})") return result except Exception as e: raise Exception(f"Exception for {key} {value} -> {e}") return _convert(data) def remove_nvdf_form(data: dict): prefixes = ["s_", "d_", "l_", "b_"] def _convert(d): result = {} try: for key, value in d.items(): if isinstance(value, dict): # note that nvdf docs state this should prefix with 'obj_', but without works also. # We choose not to as it matches up with existing fields from kit benchmarking result[key] = _convert(value) elif hasattr(value, "__dict__"): # support for Classes result[key] = _convert(value.__dict__) elif isinstance(value, (list, tuple, str, float, int, bool)): if key[:2] in prefixes: key = key[2:] result[key] = value else: raise ValueError(f"Type {type(value)} not supported in nvdf (data: {data})") return result except Exception as e: raise Exception(f"Exception for {key} {value} -> {e}") return _convert(data)
14,649
Python
35.901763
174
0.569117
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/__init__.py
import asyncio import omni.kit.app import omni.ext from .async_unittest import AsyncTestCase from .async_unittest import AsyncTestCaseFailOnLogError from .async_unittest import AsyncTestSuite from .utils import get_setting, get_global_test_output_path, get_test_output_path from .ext_utils import decompose_test_list from .ext_utils import extension_from_test_name from .ext_utils import find_disabled_tests from .ext_utils import get_module_to_extension_map from .ext_utils import test_only_extension_dependencies from . import unittests from .unittests import get_tests_from_modules from .unittests import get_tests_to_remove_from_modules from .unittests import run_tests from .unittests import get_tests from .unittests import remove_from_dynamic_test_cache from .exttests import run_ext_tests, shutdown_ext_tests from .exttests import ExtTest, ExtTestResult from .test_reporters import TestRunStatus from .test_reporters import add_test_status_report_cb from .test_reporters import remove_test_status_report_cb from .test_coverage import PyCoverageCollector from .test_populators import DEFAULT_POPULATOR_NAME, TestPopulator, TestPopulateAll, TestPopulateDisabled from .reporter import generate_report try: from omni.kit.omni_test_registry import omni_test_registry except ImportError: # omni_test_registry is copied at build time into the omni.kit.test extension directory in _build pass async def _auto_run_tests(run_tests_and_exit: bool): # Skip 2 updates to make sure all extensions loaded and initialized await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() # Run Extension tests? # This part runs on the parent Kit Process that triggers all extension tests test_exts = list(get_setting("/exts/omni.kit.test/testExts", default=[])) if len(test_exts) > 0: # Quit on finish: def on_finish(result: bool): # generate coverage report at the end? if get_setting("/exts/omni.kit.test/testExtGenerateCoverageReport", default=False): generate_report() returncode = 0 if result else 21 omni.kit.app.get_app().post_quit(returncode) exclude_exts = list(get_setting("/exts/omni.kit.test/excludeExts", default=[])) run_ext_tests(test_exts, on_finish_fn=on_finish, exclude_exts=exclude_exts) return # Print tests? # This part runs on the child Kit Process to print the number of extension tests if len(test_exts) == 0 and get_setting("/exts/omni.kit.test/printTestsAndQuit", default=False): unittests.print_tests() omni.kit.app.get_app().post_quit(0) return # Run python tests? # This part runs on the child Kit Process that performs the extension tests if run_tests_and_exit: tests_filter = get_setting("/exts/omni.kit.test/runTestsFilter", default="") from unittest.result import TestResult # Quit on finish: def on_finish(result: TestResult): returncode = 0 if result.wasSuccessful() else 13 cpp_test_res = get_setting("/exts/omni.kit.test/~cppTestResult", default=None) if cpp_test_res is not None: returncode += cpp_test_res if not get_setting("/exts/omni.kit.test/doNotQuit", default=False): omni.kit.app.get_app().post_quit(returncode) unittests.run_tests(unittests.get_tests(tests_filter), on_finish) class _TestAutoRunner(omni.ext.IExt): """Automatically run tests based on setting""" def __init__(self): super().__init__() self._py_coverage = PyCoverageCollector() def on_startup(self): # Report generate mode? if get_setting("/exts/omni.kit.test/testExtGenerateReport", default=False): generate_report() omni.kit.app.get_app().post_quit(0) return # Otherwise: regular test run run_tests_and_exit = get_setting("/exts/omni.kit.test/runTestsAndQuit", default=False) ui_mode = get_setting("/exts/omni.kit.test/testExtUIMode", default=False) # If launching a Python test then start test coverage subsystem (might do nothing depending on the settings) if run_tests_and_exit or ui_mode: self._py_coverage.startup() def on_app_ready(e): asyncio.ensure_future(_auto_run_tests(run_tests_and_exit)) self._app_ready_sub = ( omni.kit.app.get_app() .get_startup_event_stream() .create_subscription_to_pop_by_type( omni.kit.app.EVENT_APP_READY, on_app_ready, name="omni.kit.test start tests" ) ) def on_shutdown(self): # Stop coverage and generate report if it's started. self._py_coverage.shutdown() shutdown_ext_tests()
4,851
Python
39.099173
116
0.683983
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/sampling.py
import datetime import logging import random from statistics import mean from .nvdf import get_app_info, query_nvdf from .utils import clamp, get_setting, is_running_on_ci logger = logging.getLogger(__name__) class SamplingFactor: LOWER_BOUND = 0.0 UPPER_BOUND = 1.0 MID_POINT = 0.5 class Sampling: """Basic Tests Sampling support""" AGG_TEST_IDS = "test_ids" AGG_LAST_PASSED = "last_passed" LAST_PASSED_COUNT = 3 TEST_IDS_COUNT = 1000 DAYS = 4 def __init__(self, app_info: dict): self.tests_sample = [] self.tests_run_count = [] self.query_result = False self.app_info = app_info def run_query(self, extension_name: str, unittests: list, running_on_ci: bool): # when running locally skip the nvdf query if running_on_ci: try: self.query_result = self._query_nvdf(extension_name, unittests) except Exception as e: logger.warning(f"Exception while doing nvdf query: {e}") else: self.query_result = True # populate test list if empty, can happen both locally and on CI if self.query_result and not self.tests_sample: self.tests_sample = unittests self.tests_run_count = [SamplingFactor.MID_POINT] * len(self.tests_sample) def get_tests_to_skip(self, sampling_factor: float) -> list: if not self.query_result: return [] weights = self._calculate_weights() samples_count = len(self.tests_sample) # Grab (1.0 - sampling factor) to get the list of tests to skip sampling_factor = SamplingFactor.UPPER_BOUND - sampling_factor sampling_count = clamp(int(sampling_factor * float(samples_count)), 0, samples_count) # use sampling seed if available seed = int(get_setting("/exts/omni.kit.test/testExtSamplingSeed", default=-1)) if seed >= 0: random.seed(seed) sampled_tests = self._random_choices_no_replace( population=self.tests_sample, weights=weights, k=sampling_count, ) return sampled_tests def _query_nvdf(self, extension_name: str, unittests: list) -> bool: # pragma: no cover query = self._es_query(extension_name, days=self.DAYS, hours=0) r = query_nvdf(query) for aggs in r.get("aggregations", {}).get(self.AGG_TEST_IDS, {}).get("buckets", {}): key = aggs.get("key") if key not in unittests: continue hits = aggs.get(self.AGG_LAST_PASSED, {}).get("hits", {}).get("hits", []) if not hits: continue all_failed = False for hit in hits: passed = hit["_source"]["test"]["b_passed"] all_failed = all_failed or not passed # consecutive failed tests cannot be skipped if all_failed: continue self.tests_sample.append(key) self.tests_run_count.append(aggs.get("doc_count", 0)) return True def _random_choices_no_replace(self, population, weights, k) -> list: """Similar to numpy.random.Generator.choice() with replace=False""" weights = list(weights) positions = range(len(population)) indices = [] while True: needed = k - len(indices) if not needed: break for i in random.choices(positions, weights, k=needed): if weights[i]: weights[i] = SamplingFactor.LOWER_BOUND indices.append(i) return [population[i] for i in indices] def _calculate_weights(self) -> list: """Simple weight adjusting to make sure all tests run an equal amount of times""" samples_min = min(self.tests_run_count) samples_max = max(self.tests_run_count) samples_width = samples_max - samples_min samples_mean = mean(self.tests_run_count) def _calculate_weight(test_count: int): if samples_width == 0: return SamplingFactor.MID_POINT weight = SamplingFactor.MID_POINT + (samples_mean - float(test_count)) / float(samples_width) # clamp is not set to [0.0, 1.0] to have better random distribution return clamp( weight, SamplingFactor.LOWER_BOUND + 0.05, SamplingFactor.UPPER_BOUND - 0.05, ) return [_calculate_weight(c) for c in self.tests_run_count] def _es_query(self, extension_name: str, days: int, hours: int) -> dict: target_date = datetime.datetime.utcnow() - datetime.timedelta(days=days, hours=hours) kit_version = self.app_info["kit_version"] platform = self.app_info["platform"] branch = self.app_info["branch"] merge_request = self.app_info["merge_request"] query = { "aggs": { self.AGG_TEST_IDS: { "terms": {"field": "test.s_test_id", "order": {"_count": "desc"}, "size": self.TEST_IDS_COUNT}, "aggs": { self.AGG_LAST_PASSED: { "top_hits": { "_source": "test.b_passed", "size": self.LAST_PASSED_COUNT, "sort": [{"ts_created": {"order": "desc"}}], } } }, } }, "size": 0, "query": { "bool": { "filter": [ {"match_all": {}}, {"term": {"test.s_ext_test_id": extension_name}}, {"term": {"app.s_kit_version": kit_version}}, {"term": {"app.s_platform": platform}}, {"term": {"app.s_branch": branch}}, {"term": {"app.l_merge_request": merge_request}}, { "range": { "ts_created": { "gte": target_date.isoformat() + "Z", "format": "strict_date_optional_time", } } }, ], } }, } return query def get_tests_sampling_to_skip(extension_name: str, sampling_factor: float, unittests: list) -> list: # pragma: no cover """Return a list of tests that can be skipped for a given extension based on a sampling factor When using tests sampling we have to run: 1) all new tests (not found on nvdf) 2) all failed tests (ie: only consecutive failures, flaky tests are not considered) 3) sampling tests (sampling factor * number of tests) By applying (1 - sampling factor) we get a list of tests to skip, which are garanteed not to contain any test from point 1 or 2. """ ts = Sampling(get_app_info()) ts.run_query(extension_name, unittests, is_running_on_ci()) return ts.get_tests_to_skip(sampling_factor)
7,260
Python
37.015707
121
0.52865
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/test_populators.py
"""Support for the population of a test list from various configurable sources""" from __future__ import annotations import abc import unittest from .ext_utils import find_disabled_tests from .unittests import get_tests __all__ = [ "DEFAULT_POPULATOR_NAME", "TestPopulator", "TestPopulateAll", "TestPopulateDisabled", ] # The name of the default populator, implemented with TestPopulateAll DEFAULT_POPULATOR_NAME = "All Tests" # ============================================================================================================== class TestPopulator(abc.ABC): """Base class for the objects used to populate the initial list of tests, before filtering.""" def __init__(self, name: str, description: str): """Set up the populator with the important information it needs for getting tests from some location Args: name: Name of the populator, which can be used for a menu description: Verbose description of the populator, which can be used for the tooltip of the menu item """ self.name: str = name self.description: str = description self.tests: list[unittest.TestCase] = [] # Remembers the tests it retrieves for later use # -------------------------------------------------------------------------------------------------------------- def destroy(self): """Opportunity to clean up any allocated resources""" pass # -------------------------------------------------------------------------------------------------------------- @abc.abstractmethod def get_tests(self, call_when_done: callable): """Populate the internal list of raw tests and then call the provided function when it has been done. The callable takes one optional boolean 'canceled' that is only True if the test retrieval was not done. """ # ============================================================================================================== class TestPopulateAll(TestPopulator): """Implementation of the TestPopulator that returns a list of all tests known to Kit""" def __init__(self): super().__init__( DEFAULT_POPULATOR_NAME, "Use all of the tests in currently enabled extensions that pass the filters", ) def get_tests(self, call_when_done: callable): self.tests = get_tests() call_when_done() # ============================================================================================================== class TestPopulateDisabled(TestPopulator): """Implementation of the TestPopulator that returns a list of all tests disabled by their extension.toml file""" def __init__(self): super().__init__( "Disabled Tests", "Use all tests from enabled extensions whose extension.toml flags them as disabled", ) def get_tests(self, call_when_done: callable): self.tests = find_disabled_tests() call_when_done()
3,004
Python
39.608108
116
0.542943
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/crash_process.py
def _error(stream, msg): stream.write(f"[error] [{__file__}] {msg}\n") def _crash_process_win(pid): # fmt: off import ctypes POINTER = ctypes.POINTER LPVOID = ctypes.c_void_p PVOID = LPVOID HANDLE = LPVOID PHANDLE = POINTER(HANDLE) ULONG = ctypes.c_ulong SIZE_T = ctypes.c_size_t LONG = ctypes.c_long NTSTATUS = LONG DWORD = ctypes.c_uint32 ACCESS_MASK = DWORD INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value BOOL = ctypes.c_int byref = ctypes.byref long = int WAIT_TIMEOUT = 0x102 WAIT_FAILED = 0xFFFFFFFF WAIT_OBJECT_0 = 0 STANDARD_RIGHTS_ALL = long(0x001F0000) SPECIFIC_RIGHTS_ALL = long(0x0000FFFF) SYNCHRONIZE = long(0x00100000) STANDARD_RIGHTS_REQUIRED = long(0x000F0000) PROCESS_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFFF) THREAD_CREATE_FLAGS_SKIP_THREAD_ATTACH = long(0x00000002) def NT_SUCCESS(x): return x >= 0 windll = ctypes.windll # HANDLE WINAPI OpenProcess( # IN DWORD dwDesiredAccess, # IN BOOL bInheritHandle, # IN DWORD dwProcessId # ); _OpenProcess = windll.kernel32.OpenProcess _OpenProcess.argtypes = [DWORD, BOOL, DWORD] _OpenProcess.restype = HANDLE # NTSTATUS NtCreateThreadEx( # OUT PHANDLE hThread, # IN ACCESS_MASK DesiredAccess, # IN PVOID ObjectAttributes, # IN HANDLE ProcessHandle, # IN PVOID lpStartAddress, # IN PVOID lpParameter, # IN ULONG Flags, # IN SIZE_T StackZeroBits, # IN SIZE_T SizeOfStackCommit, # IN SIZE_T SizeOfStackReserve, # OUT PVOID lpBytesBuffer # ); _NtCreateThreadEx = windll.ntdll.NtCreateThreadEx _NtCreateThreadEx.argtypes = [PHANDLE, ACCESS_MASK, PVOID, HANDLE, PVOID, PVOID, ULONG, SIZE_T, SIZE_T, SIZE_T, PVOID] _NtCreateThreadEx.restype = NTSTATUS # DWORD WINAPI WaitForSingleObject( # HANDLE hHandle, # DWORD dwMilliseconds # ); _WaitForSingleObject = windll.kernel32.WaitForSingleObject _WaitForSingleObject.argtypes = [HANDLE, DWORD] _WaitForSingleObject.restype = DWORD hProcess = _OpenProcess( PROCESS_ALL_ACCESS, 0, # bInheritHandle pid ) if not hProcess: raise ctypes.WinError() # this injects a new thread into the process running the test code. this thread starts executing at address 0, # causing a crash. # # alternatives considered: # # DebugBreakProcess(): in order for DebugBreakProcess() to send the breakpoint, a debugger must be attached. this # can be accomplished with DebugActiveProcess()/WaitForDebugEvent()/ContinueDebugEvent(). unfortunately, when a # debugger is attached, UnhandledExceptionFilter() is ignored. UnhandledExceptionFilter() is where the test process # runs the crash dump code. # # CreateRemoteThread(): this approach does not work if the target process is stuck waiting for the loader lock. # # the solution below uses NtCreateThreadEx to create the faulting thread in the test process. unlike # CreateRemoteThread(), NtCreateThreadEx accepts the THREAD_CREATE_FLAGS_SKIP_THREAD_ATTACH flag which skips # THREAD_ATTACH in DllMain thereby avoiding the loader lock. hThread = HANDLE(INVALID_HANDLE_VALUE) status = _NtCreateThreadEx( byref(hThread), (STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL), 0, # ObjectAttributes hProcess, 0, # lpStartAddress (calls into null causing a crash) 0, # lpParameter THREAD_CREATE_FLAGS_SKIP_THREAD_ATTACH, 0, # StackZeroBits 0, # StackZeroBits (must be 0 to crash) 0, # SizeOfStackReserve 0, # lpBytesBuffer ) if not NT_SUCCESS(status): raise OSError(None, "NtCreateThreadEx failed", None, status) waitTimeMs = 30 * 1000 status = _WaitForSingleObject(hProcess, waitTimeMs) if status == WAIT_TIMEOUT: raise TimeoutError("timed out while waiting for target process to exit") elif status == WAIT_FAILED: raise ctypes.WinError() elif status != WAIT_OBJECT_0: raise OSError(None, "failed to wait for target process to exit", None, status) # fmt: on def crash_process(process, stream): """ Triggers a crash dump in the test process, terminating the process. Returns True if the test process was terminated, False if the process is still running. """ import os assert process pid = process.pid if os.name == "nt": try: _crash_process_win(pid) except Exception as e: _error(stream, f"Failed crashing timed out process: {pid}. Error: {e}") else: import signal try: process.send_signal(signal.SIGABRT) process.wait(timeout=30) # seconds except Exception as e: _error(stream, f"Failed crashing timed out process: {pid}. Error: {e}") return not process.is_running()
5,281
Python
34.449664
122
0.625071
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/utils.py
import glob import hashlib import os import shutil import sys from datetime import datetime from functools import lru_cache from pathlib import Path from typing import List, Tuple import carb import carb.settings import carb.tokens import omni.ext from .gitlab import is_running_in_gitlab from .teamcity import is_running_in_teamcity _settings_iface = None def get_setting(path, default=None): global _settings_iface if not _settings_iface: _settings_iface = carb.settings.get_settings() setting = _settings_iface.get(path) return setting if setting is not None else default def get_local_timestamp(): return ( # ':' is not path-friendly on windows datetime.now() .isoformat(timespec="seconds") .replace(":", "-") ) @lru_cache() def _split_argv() -> Tuple[List[str], List[str]]: """Return list of argv before `--` and after (processed and unprocessed)""" try: index = sys.argv.index("--") return list(sys.argv[:index]), list(sys.argv[index + 1 :]) except ValueError: return list(sys.argv), [] def get_argv() -> List[str]: return _split_argv()[0] def get_unprocessed_argv() -> List[str]: return _split_argv()[1] def resolve_path(path, root) -> str: path = carb.tokens.get_tokens_interface().resolve(path) if not os.path.isabs(path): path = os.path.join(root, path) return os.path.normpath(path) @lru_cache() def _get_passed_test_output_path(): return get_setting("/exts/omni.kit.test/testOutputPath", default=None) @lru_cache() def get_global_test_output_path(): """Get global extension test output path. It is shared for all extensions.""" # If inside test process, we have testoutput for actual extension, just go on folder up: output_path = _get_passed_test_output_path() if output_path: return os.path.abspath(os.path.join(output_path, "..")) # If inside ext test runner process, use setting: output_path = carb.tokens.get_tokens_interface().resolve( get_setting("/exts/omni.kit.test/testExtOutputPath", default="") ) output_path = os.path.abspath(output_path) return output_path @lru_cache() def get_test_output_path(): """Get local extension test output path. It is unique for each extension test process.""" output_path = _get_passed_test_output_path() # If not passed we probably not inside test process, default to global if not output_path: return get_global_test_output_path() output_path = os.path.abspath(carb.tokens.get_tokens_interface().resolve(output_path)) return output_path @lru_cache() def get_ext_test_id() -> str: return str(get_setting("/exts/omni.kit.test/extTestId", default="")) def cleanup_folder(path): try: for p in glob.glob(f"{path}/*"): if os.path.isdir(p): if omni.ext.is_link(p): omni.ext.destroy_link(p) else: shutil.rmtree(p) else: os.remove(p) except Exception as exc: # pylint: disable=broad-except carb.log_warn(f"Unable to clean up files: {path}: {exc}") def ext_id_to_fullname(ext_id: str) -> str: return omni.ext.get_extension_name(ext_id) def clamp(value, min_value, max_value): return max(min(value, max_value), min_value) @lru_cache() def is_running_on_ci(): return is_running_in_teamcity() or is_running_in_gitlab() def call_git(args, cwd=None): import subprocess cmd = ["git"] + args carb.log_verbose("run process: {}".format(cmd)) try: res = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True) if res.returncode != 0: carb.log_warn(f"Error running process: {cmd}. Result: {res}. Stderr: {res.stderr}") return res except FileNotFoundError: carb.log_warn("Failed calling git") except PermissionError: carb.log_warn("No permission to execute git") def _hash_file_impl(path, hash, as_text): mode = "r" if as_text else "rb" encoding = "utf-8" if as_text else None with open(path, mode, encoding=encoding) as f: while True: data = f.readline().encode("utf-8") if as_text else f.read(65536) if not data: break hash.update(data) def hash_file(path, hash): # Try as text first, to avoid CRLF/LF mismatch on both platforms try: return _hash_file_impl(path, hash, as_text=True) except UnicodeDecodeError: return _hash_file_impl(path, hash, as_text=False) def sha1_path(path, hash_length=16) -> str: exclude_files = ["extension.gen.toml"] hash = hashlib.sha1() if os.path.isfile(path): hash_file(path, hash) else: for p in glob.glob(f"{path}/**", recursive=True): if not os.path.isfile(p) or os.path.basename(p) in exclude_files: continue hash_file(p, hash) return hash.hexdigest()[:hash_length] def sha1_list(strings: List[str], hash_length=16) -> str: hash = hashlib.sha1() for s in strings: hash.update(s.encode("utf-8")) return hash.hexdigest()[:hash_length]
5,195
Python
27.23913
95
0.635226
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/test_reporters.py
from enum import Enum from typing import Callable, Any class TestRunStatus(Enum): UNKNOWN = 0 RUNNING = 1 PASSED = 2 FAILED = 3 _callbacks = [] def add_test_status_report_cb(callback: Callable[[str, TestRunStatus, Any], None]): """Add callback to be called when tests start, fail, pass.""" global _callbacks _callbacks.append(callback) def remove_test_status_report_cb(callback: Callable[[str, TestRunStatus, Any], None]): """Remove callback to be called when tests start, fail, pass.""" global _callbacks _callbacks.remove(callback) def _test_status_report(test_id: str, status: TestRunStatus, **kwargs): for cb in _callbacks: cb(test_id, status, **kwargs)
720
Python
23.033333
86
0.679167
omniverse-code/kit/exts/omni.kit.test/omni/kit/test/async_unittest.py
"""Async version of python unittest module. AsyncTestCase, AsyncTestSuite and AsyncTextTestRunner classes were copied from python unittest source and async/await keywords were added. There are two ways of registering tests, which must all be in the 'tests' submodule of your python module. 1. 'from X import *" from every file containing tests 2. Add the line 'scan_for_test_modules = True' in your __init__.py file to pick up tests in every file starting with 'test_' """ import asyncio import time import unittest import warnings from unittest.case import _Outcome import carb import omni.kit.app from .reporter import TestReporter from .test_reporters import TestRunStatus from .utils import get_ext_test_id, is_running_on_ci KEY_FAILING_TESTS = "Failing tests" STARTED_UNITTEST = "started " async def await_or_call(func): """ Awaits on function if it is a coroutine, calls it otherwise. """ if asyncio.iscoroutinefunction(func): await func() else: func() class LogErrorChecker: """Automatically subscribes to logging events and monitors if error were produced during the test.""" def __init__(self): # Setup this test case to fail if any error is produced self._error_count = 0 def on_log_event(e): if e.payload["level"] >= carb.logging.LEVEL_ERROR: self._error_count = self._error_count + 1 self._log_stream = omni.kit.app.get_app().get_log_event_stream() self._log_sub = self._log_stream.create_subscription_to_pop(on_log_event, name="test log event") def shutdown(self): self._log_stream = None self._log_sub = None def get_error_count(self): self._log_stream.pump() return self._error_count class AsyncTestCase(unittest.TestCase): """Base class for all async test cases. Derive from it to make your tests auto discoverable. Test methods must start with `test_` prefix. Test cases allow for generation and/or adaptation of tests at runtime. See testing_exts_python.md for more details. """ # If true test will check for Carbonite logging messages and fail if any error level or higher was produced during the test. fail_on_log_error = False async def run(self, result=None): # Log error checker self._log_error_checker = None if self.fail_on_log_error: carb.log_warn( "[DEPRECATION WARNING] `AsyncTestCaseFailOnLogError` is deprecated. Replace with `AsyncTestCase`. Errors are captured from stdout by an external test runner process now." ) # Make sure log buffer pumped: await omni.kit.app.get_app().next_update_async() self._log_error_checker = LogErrorChecker() orig_result = result if result is None: result = self.defaultTestResult() startTestRun = getattr(result, "startTestRun", None) if startTestRun is not None: startTestRun() result.startTest(self) testMethod = getattr(self, self._testMethodName) if getattr(self.__class__, "__unittest_skip__", False) or getattr(testMethod, "__unittest_skip__", False): # If the class or method was skipped. try: skip_why = getattr(self.__class__, "__unittest_skip_why__", "") or getattr( testMethod, "__unittest_skip_why__", "" ) self._addSkip(result, self, skip_why) finally: result.stopTest(self) return expecting_failure_method = getattr(testMethod, "__unittest_expecting_failure__", False) expecting_failure_class = getattr(self, "__unittest_expecting_failure__", False) expecting_failure = expecting_failure_class or expecting_failure_method outcome = _Outcome(result) try: self._outcome = outcome with outcome.testPartExecutor(self): await await_or_call(self.setUp) if outcome.success: outcome.expecting_failure = expecting_failure with outcome.testPartExecutor(self, isTest=True): await await_or_call(testMethod) outcome.expecting_failure = False with outcome.testPartExecutor(self): await await_or_call(self.tearDown) # Log error checks if self._log_error_checker: await omni.kit.app.get_app().next_update_async() error_count = self._log_error_checker.get_error_count() if error_count > 0: self.fail(f"Test failure because of {error_count} error message(s) logged during it.") self.doCleanups() for test, reason in outcome.skipped: self._addSkip(result, test, reason) self._feedErrorsToResult(result, outcome.errors) if outcome.success: if expecting_failure: if outcome.expectedFailure: self._addExpectedFailure(result, outcome.expectedFailure) else: self._addUnexpectedSuccess(result) else: result.addSuccess(self) return result finally: if self._log_error_checker: self._log_error_checker.shutdown() result.stopTest(self) if orig_result is None: stopTestRun = getattr(result, "stopTestRun", None) if stopTestRun is not None: stopTestRun() # explicitly break reference cycles: # outcome.errors -> frame -> outcome -> outcome.errors # outcome.expectedFailure -> frame -> outcome -> outcome.expectedFailure outcome.errors.clear() outcome.expectedFailure = None # clear the outcome, no more needed self._outcome = None class AsyncTestCaseFailOnLogError(AsyncTestCase): """Test Case which automatically subscribes to logging events and fails if any error were produced during the test. This class is for backward compatibility, you can also just change value of `fail_on_log_error`. """ # Enable failure on error fail_on_log_error = True class OmniTestResult(unittest.TextTestResult): def __init__(self, stream, descriptions, verbosity): # If we are running under CI we will use default unittest reporter with higher verbosity. if not is_running_on_ci(): verbosity = 2 super(OmniTestResult, self).__init__(stream, descriptions, verbosity) self.reporter = TestReporter(stream) self.on_status_report_fn = None def _report_status(self, *args, **kwargs): if self.on_status_report_fn: self.on_status_report_fn(*args, **kwargs) @staticmethod def get_tc_test_id(test): if isinstance(test, str): return test # Use dash as a clear visual separator of 3 parts: test_id = "%s - %s - %s" % (test.__class__.__module__, test.__class__.__qualname__, test._testMethodName) # Dots have special meaning in TC, replace with / test_id = test_id.replace(".", "/") ext_test_id = get_ext_test_id() if ext_test_id: # In the context of extension test it has own test id. Convert to TC form by getting rid of dots. ext_test_id = ext_test_id.replace(".", "+") test_id = f"{ext_test_id}.{test_id}" return test_id def addSuccess(self, test): super(OmniTestResult, self).addSuccess(test) def addError(self, test, err, *k): super(OmniTestResult, self).addError(test, err) fail_message = self._get_error_message(test, "Error", self.errors) self.report_fail(test, "Error", err, fail_message) def addFailure(self, test, err, *k): super(OmniTestResult, self).addFailure(test, err) fail_message = self._get_error_message(test, "Fail", self.failures) self.report_fail(test, "Failure", err, fail_message) def report_fail(self, test, fail_type: str, err, fail_message: str): tc_test_id = self.get_tc_test_id(test) test_id = test.id() # pass the failing test info back to the ext testing framework in parent proc self.stream.write(f"##omni.kit.test[append, {KEY_FAILING_TESTS}, {test_id}]\n") self.reporter.unittest_fail(test_id, tc_test_id, fail_type, fail_message) self._report_status(test_id, TestRunStatus.FAILED, fail_message=fail_message) def _get_error_message(self, test, fail_type: str, errors: list) -> str: # In python/Lib/unittest/result.py the failures are reported with _exc_info_to_string() that is private. # To get the same result we grab the latest errors/failures from `self.errors[-1]` or `self.failures[-1]` # In python/Lib/unittest/runner.py from the `printErrorList` function we also copied the logic here. exc_info = errors[-1][1] if errors[-1] else "" error_msg = [] error_msg.append(self.separator1) error_msg.append(f"{fail_type.upper()}: {self.getDescription(test)}") error_msg.append(self.separator2) error_msg.append(exc_info) return "\n".join(error_msg) def startTest(self, test): super(OmniTestResult, self).startTest(test) tc_test_id = self.get_tc_test_id(test) test_id = test.id() self.stream.write("\n") # python tests can start but never finish (crash, time out, etc) # track it from the parent proc with a pragma message (see _extract_metadata_pragma in exttests.py) self.stream.write(f"##omni.kit.test[set, {test_id}, {STARTED_UNITTEST}{tc_test_id}]\n") self.reporter.unittest_start(test_id, tc_test_id, captureStandardOutput="true") self._report_status(test_id, TestRunStatus.RUNNING) def stopTest(self, test): super(OmniTestResult, self).stopTest(test) tc_test_id = self.get_tc_test_id(test) test_id = test.id() # test finished, delete it from the metadata self.stream.write(f"##omni.kit.test[del, {test_id}]\n") # test._outcome is None when test is skipped using decorator. # When skipped using self.skipTest() it contains list of skipped test cases skipped = test._outcome is None or bool(test._outcome.skipped) # self.skipped last index contains the current skipped test, name is at index 0, reason at index 1 skip_reason = self.skipped[-1][1] if skipped and self.skipped else "" # skipped tests are marked as "passed" not to confuse reporting down the line passed = test._outcome.success if test._outcome and not skipped else True self.reporter.unittest_stop(test_id, tc_test_id, passed=passed, skipped=skipped, skip_reason=skip_reason) if passed: self._report_status(test_id, TestRunStatus.PASSED) class TeamcityTestResult(OmniTestResult): def __init__(self, stream, descriptions, verbosity): carb.log_warn("[DEPRECATION WARNING] `TeamcityTestResult` is deprecated. Replace with `OmniTestResult`.") super(TeamcityTestResult, self).__init__(stream, descriptions, verbosity) class AsyncTextTestRunner(unittest.TextTestRunner): """A test runner class that displays results in textual form. It prints out the names of tests as they are run, errors as they occur, and a summary of the results at the end of the test run. """ async def run(self, test, on_status_report_fn=None): "Run the given test case or test suite." result = self._makeResult() unittest.signals.registerResult(result) result.failfast = self.failfast result.buffer = self.buffer result.tb_locals = self.tb_locals result.on_status_report_fn = on_status_report_fn with warnings.catch_warnings(): if self.warnings: # if self.warnings is set, use it to filter all the warnings warnings.simplefilter(self.warnings) # if the filter is 'default' or 'always', special-case the # warnings from the deprecated unittest methods to show them # no more than once per module, because they can be fairly # noisy. The -Wd and -Wa flags can be used to bypass this # only when self.warnings is None. if self.warnings in ["default", "always"]: warnings.filterwarnings( "module", category=DeprecationWarning, message=r"Please use assert\w+ instead." ) startTime = time.time() startTestRun = getattr(result, "startTestRun", None) if startTestRun is not None: startTestRun() try: await test(result) finally: stopTestRun = getattr(result, "stopTestRun", None) if stopTestRun is not None: stopTestRun() stopTime = time.time() timeTaken = stopTime - startTime result.printErrors() if hasattr(result, "separator2"): self.stream.writeln(result.separator2) run = result.testsRun self.stream.writeln("Ran %d test%s in %.3fs" % (run, run != 1 and "s" or "", timeTaken)) self.stream.writeln() expectedFails = unexpectedSuccesses = skipped = 0 try: results = map(len, (result.expectedFailures, result.unexpectedSuccesses, result.skipped)) except AttributeError: pass else: expectedFails, unexpectedSuccesses, skipped = results infos = [] if not result.wasSuccessful(): self.stream.write("FAILED") failed, errored = len(result.failures), len(result.errors) if failed: infos.append("failures=%d" % failed) if errored: infos.append("errors=%d" % errored) else: self.stream.write("OK") if skipped: infos.append("skipped=%d" % skipped) if expectedFails: infos.append("expected failures=%d" % expectedFails) if unexpectedSuccesses: infos.append("unexpected successes=%d" % unexpectedSuccesses) if infos: self.stream.writeln(" (%s)" % (", ".join(infos),)) else: self.stream.write("\n") return result def _isnotsuite(test): "A crude way to tell apart testcases and suites with duck-typing" try: iter(test) except TypeError: return True return False class AsyncTestSuite(unittest.TestSuite): """A test suite is a composite test consisting of a number of TestCases. For use, create an instance of TestSuite, then add test case instances. When all tests have been added, the suite can be passed to a test runner, such as TextTestRunner. It will run the individual test cases in the order in which they were added, aggregating the results. When subclassing, do not forget to call the base class constructor. """ async def run(self, result, debug=False): topLevel = False if getattr(result, "_testRunEntered", False) is False: result._testRunEntered = topLevel = True for index, test in enumerate(self): if result.shouldStop: break if _isnotsuite(test): self._tearDownPreviousClass(test, result) self._handleModuleFixture(test, result) self._handleClassSetUp(test, result) result._previousTestClass = test.__class__ if getattr(test.__class__, "_classSetupFailed", False) or getattr(result, "_moduleSetUpFailed", False): continue if not debug: await test(result) else: await test.debug() if self._cleanup: self._removeTestAtIndex(index) if topLevel: self._tearDownPreviousClass(None, result) self._handleModuleTearDown(result) result._testRunEntered = False return result
16,411
Python
39.927681
186
0.613796