file_path
stringlengths
32
153
content
stringlengths
0
3.14M
omniverse-code/kit/gsl/README.packman.md
* Package: gsl * Version: 3.1.0.1 * From: ssh://git@gitlab-master.nvidia.com:12051/omniverse/externals/gsl.git * Branch: master * Commit: 5e0543eb9d231a0d3ccd7f5789aa51d1c896f6ae * Time: Fri Nov 06 14:03:26 2020 * Computername: KPICOTT-LT * Packman: 5.13.2
omniverse-code/kit/gsl/PACKAGE-INFO.yaml
Package : gsl
omniverse-code/kit/gsl/appveyor.yml
shallow_clone: true platform: - x86 - x64 configuration: - Debug - Release image: - Visual Studio 2017 - Visual Studio 2019 environment: NINJA_TAG: v1.8.2 NINJA_SHA512: 9B9CE248240665FCD6404B989F3B3C27ED9682838225E6DC9B67B551774F251E4FF8A207504F941E7C811E7A8BE1945E7BCB94472A335EF15E23A0200A32E6D5 NINJA_PATH: C:\Tools\ninja\ninja-%NINJA_TAG% VCVAR2017: 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvarsall.bat' VCVAR2019: 'C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat' matrix: - GSL_CXX_STANDARD: 14 USE_TOOLSET: MSVC USE_GENERATOR: MSBuild - GSL_CXX_STANDARD: 17 USE_TOOLSET: MSVC USE_GENERATOR: MSBuild - GSL_CXX_STANDARD: 14 USE_TOOLSET: LLVM USE_GENERATOR: Ninja - GSL_CXX_STANDARD: 17 USE_TOOLSET: LLVM USE_GENERATOR: Ninja cache: - C:\cmake-3.14.4-win32-x86 - C:\Tools\ninja install: - ps: | if (![IO.File]::Exists("$env:NINJA_PATH\ninja.exe")) { Start-FileDownload ` "https://github.com/ninja-build/ninja/releases/download/$env:NINJA_TAG/ninja-win.zip" $hash = (Get-FileHash ninja-win.zip -Algorithm SHA512).Hash if ($env:NINJA_SHA512 -eq $hash) { 7z e -y -bso0 ninja-win.zip -o"$env:NINJA_PATH" } else { Write-Warning "Ninja download hash changed!"; Write-Output "$hash" } } if ([IO.File]::Exists("$env:NINJA_PATH\ninja.exe")) { $env:PATH = "$env:NINJA_PATH;$env:PATH" } else { Write-Warning "Failed to find ninja.exe in expected location." } if ($env:USE_TOOLSET -ne "LLVM") { if (![IO.File]::Exists("C:\cmake-3.14.0-win32-x86\bin\cmake.exe")) { Start-FileDownload 'https://cmake.org/files/v3.14/cmake-3.14.4-win32-x86.zip' 7z x -y -bso0 cmake-3.14.4-win32-x86.zip -oC:\ } $env:PATH="C:\cmake-3.14.4-win32-x86\bin;$env:PATH" } before_build: - ps: | if ("$env:USE_GENERATOR" -eq "Ninja") { $GeneratorFlags = '-k 10' $Architecture = $env:PLATFORM if ("$env:APPVEYOR_BUILD_WORKER_IMAGE" -eq "Visual Studio 2017") { $env:VCVARSALL = "`"$env:VCVAR2017`" $Architecture" } else { $env:VCVARSALL = "`"$env:VCVAR2019`" $Architecture" } $env:CMakeGenFlags = "-G Ninja -DGSL_CXX_STANDARD=$env:GSL_CXX_STANDARD" } else { $GeneratorFlags = '/m /v:minimal' if ("$env:APPVEYOR_BUILD_WORKER_IMAGE" -eq "Visual Studio 2017") { $Generator = 'Visual Studio 15 2017' } else { $Generator = 'Visual Studio 16 2019' } if ("$env:PLATFORM" -eq "x86") { $Architecture = "Win32" } else { $Architecture = "x64" } if ("$env:USE_TOOLSET" -eq "LLVM") { $env:CMakeGenFlags = "-G `"$Generator`" -A $Architecture -T llvm -DGSL_CXX_STANDARD=$env:GSL_CXX_STANDARD" } else { $env:CMakeGenFlags = "-G `"$Generator`" -A $Architecture -DGSL_CXX_STANDARD=$env:GSL_CXX_STANDARD" } } if ("$env:USE_TOOLSET" -eq "LLVM") { $env:CC = "clang-cl" $env:CXX = "clang-cl" if ("$env:PLATFORM" -eq "x86") { $env:CFLAGS = "-m32"; $env:CXXFLAGS = "-m32"; } else { $env:CFLAGS = "-m64"; $env:CXXFLAGS = "-m64"; } } $env:CMakeBuildFlags = "--config $env:CONFIGURATION -- $GeneratorFlags" - mkdir build - cd build - if %USE_GENERATOR%==Ninja (call %VCVARSALL%) - echo %CMakeGenFlags% - cmake .. %CMakeGenFlags% build_script: - echo %CMakeBuildFlags% - cmake --build . %CMakeBuildFlags% test_script: - ctest -j2 deploy: off
omniverse-code/kit/gsl/CMakeLists.txt
cmake_minimum_required(VERSION 3.1.3...3.16) project(GSL VERSION 3.1.0 LANGUAGES CXX) include(ExternalProject) find_package(Git) # Use GNUInstallDirs to provide the right locations on all platforms include(GNUInstallDirs) # creates a library GSL which is an interface (header files only) add_library(GSL INTERFACE) # determine whether this is a standalone project or included by other projects set(GSL_STANDALONE_PROJECT OFF) if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) set(GSL_STANDALONE_PROJECT ON) endif () set(GSL_CXX_STANDARD "14" CACHE STRING "Use c++ standard") set(GSL_CXX_STD "cxx_std_${GSL_CXX_STANDARD}") if (MSVC) set(GSL_CXX_STD_OPT "-std:c++${GSL_CXX_STANDARD}") else() set(GSL_CXX_STD_OPT "-std=c++${GSL_CXX_STANDARD}") endif() # when minimum version required is 3.8.0 remove if below # both branches do exactly the same thing if (CMAKE_VERSION VERSION_LESS 3.7.9) include(CheckCXXCompilerFlag) CHECK_CXX_COMPILER_FLAG("${GSL_CXX_STD_OPT}" COMPILER_SUPPORTS_CXX_STANDARD) if(COMPILER_SUPPORTS_CXX_STANDARD) target_compile_options(GSL INTERFACE "${GSL_CXX_STD_OPT}") else() message(FATAL_ERROR "The compiler ${CMAKE_CXX_COMPILER} has no c++${GSL_CXX_STANDARD} support. Please use a different C++ compiler.") endif() else () target_compile_features(GSL INTERFACE "${GSL_CXX_STD}") # on *nix systems force the use of -std=c++XX instead of -std=gnu++XX (default) set(CMAKE_CXX_EXTENSIONS OFF) endif() # add definitions to the library and targets that consume it target_compile_definitions(GSL INTERFACE $<$<CXX_COMPILER_ID:MSVC>: # remove unnecessary warnings about unchecked iterators _SCL_SECURE_NO_WARNINGS # remove deprecation warnings about std::uncaught_exception() (from catch) _SILENCE_CXX17_UNCAUGHT_EXCEPTION_DEPRECATION_WARNING > ) # add include folders to the library and targets that consume it # the SYSTEM keyword suppresses warnings for users of the library if(GSL_STANDALONE_PROJECT) target_include_directories(GSL INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include> $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}> ) else() target_include_directories(GSL SYSTEM INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include> $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}> ) endif() if (CMAKE_VERSION VERSION_GREATER 3.7.8) if (MSVC_IDE) option(VS_ADD_NATIVE_VISUALIZERS "Configure project to use Visual Studio native visualizers" TRUE) else() set(VS_ADD_NATIVE_VISUALIZERS FALSE CACHE INTERNAL "Native visualizers are Visual Studio extension" FORCE) endif() # add natvis file to the library so it will automatically be loaded into Visual Studio if(VS_ADD_NATIVE_VISUALIZERS) target_sources(GSL INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/GSL.natvis> ) endif() endif() install(TARGETS GSL EXPORT Microsoft.GSLConfig) install( DIRECTORY include/gsl DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} ) # Make library importable by other projects install(EXPORT Microsoft.GSLConfig NAMESPACE Microsoft.GSL:: DESTINATION ${CMAKE_INSTALL_DATADIR}/cmake/Microsoft.GSL) export(TARGETS GSL NAMESPACE Microsoft.GSL:: FILE Microsoft.GSLConfig.cmake) # Add find_package() versioning support. The version for # generated Microsoft.GSLConfigVersion.cmake will be used from # last project() command. The version's compatibility is set between all # minor versions (as it was in prev. GSL releases). include(CMakePackageConfigHelpers) if(${CMAKE_VERSION} VERSION_LESS "3.14.0") write_basic_package_version_file( ${CMAKE_CURRENT_BINARY_DIR}/Microsoft.GSLConfigVersion.cmake COMPATIBILITY SameMajorVersion ) else() write_basic_package_version_file( ${CMAKE_CURRENT_BINARY_DIR}/Microsoft.GSLConfigVersion.cmake COMPATIBILITY SameMajorVersion ARCH_INDEPENDENT ) endif() install(FILES ${CMAKE_CURRENT_BINARY_DIR}/Microsoft.GSLConfigVersion.cmake DESTINATION ${CMAKE_INSTALL_DATADIR}/cmake/Microsoft.GSL) # Add Microsoft.GSL::GSL alias for GSL so that dependents can be agnostic about # whether GSL was added via `add_subdirectory` or `find_package` add_library(Microsoft.GSL::GSL ALIAS GSL) option(GSL_TEST "Generate tests." ${GSL_STANDALONE_PROJECT}) if (GSL_TEST) enable_testing() if(IOS) add_compile_definitions( GTEST_HAS_DEATH_TEST=1 ) endif() add_subdirectory(tests) endif ()
omniverse-code/kit/gsl/CMakeSettings.json
{ "configurations": [ { "name": "x64-Debug", "generator": "Ninja", "configurationType": "Debug", "inheritEnvironments": [ "msvc_x64_x64" ], "buildRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\build\\${name}", "installRoot": "${env.USERPROFILE}\\CMakeBuilds\\${workspaceHash}\\install\\${name}", "cmakeCommandArgs": "-DGSL_CXX_STANDARD=17", "buildCommandArgs": "-v", "ctestCommandArgs": "", "codeAnalysisRuleset": "CppCoreCheckRules.ruleset" } ] }
omniverse-code/kit/gsl/README.md
# GSL: Guidelines Support Library [![Build Status](https://travis-ci.org/Microsoft/GSL.svg?branch=master)](https://travis-ci.org/Microsoft/GSL) [![Build status](https://ci.appveyor.com/api/projects/status/github/Microsoft/GSL?svg=true)](https://ci.appveyor.com/project/neilmacintosh/GSL) The Guidelines Support Library (GSL) contains functions and types that are suggested for use by the [C++ Core Guidelines](https://github.com/isocpp/CppCoreGuidelines) maintained by the [Standard C++ Foundation](https://isocpp.org). This repo contains Microsoft's implementation of GSL. The library includes types like `span<T>`, `string_span`, `owner<>` and others. The entire implementation is provided inline in the headers under the [gsl](./include/gsl) directory. The implementation generally assumes a platform that implements C++14 support. While some types have been broken out into their own headers (e.g. [gsl/span](./include/gsl/span)), it is simplest to just include [gsl/gsl](./include/gsl/gsl) and gain access to the entire library. > NOTE: We encourage contributions that improve or refine any of the types in this library as well as ports to other platforms. Please see [CONTRIBUTING.md](./CONTRIBUTING.md) for more information about contributing. # Project Code of Conduct This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. # Usage of Third Party Libraries This project makes use of the [Google Test](https://github.com/google/googletest) testing library. Please see the [ThirdPartyNotices.txt](./ThirdPartyNotices.txt) file for details regarding the licensing of Google Test. # Quick Start ## Supported Compilers The GSL officially supports the current and previous major release of MSVC, GCC, Clang, and XCode's Apple-Clang. See our latest test results for the most up-to-date list of supported configurations. Compiler |Toolset Versions Currently Tested| Build Status :------- |:--|------------: XCode |11.4 & 10.3 | [![Status](https://travis-ci.org/Microsoft/GSL.svg?branch=master)](https://travis-ci.org/Microsoft/GSL) GCC |9 & 8| [![Status](https://travis-ci.org/Microsoft/GSL.svg?branch=master)](https://travis-ci.org/Microsoft/GSL) Clang |11 & 10| [![Status](https://travis-ci.org/Microsoft/GSL.svg?branch=master)](https://travis-ci.org/Microsoft/GSL) Visual Studio with MSVC | VS2017 (15.9) & VS2019 (16.4) | [![Status](https://ci.appveyor.com/api/projects/status/github/Microsoft/GSL?svg=true)](https://ci.appveyor.com/project/neilmacintosh/GSL) Visual Studio with LLVM | VS2017 (Clang 9) & VS2019 (Clang 10) | [![Status](https://ci.appveyor.com/api/projects/status/github/Microsoft/GSL?svg=true)](https://ci.appveyor.com/project/neilmacintosh/GSL) Note: For `gsl::byte` to work correctly with Clang and GCC you might have to use the ` -fno-strict-aliasing` compiler option. --- If you successfully port GSL to another platform, we would love to hear from you! - Submit an issue specifying the platform and target. - Consider contributing your changes by filing a pull request with any necessary changes. - If at all possible, add a CI/CD step and add the button to the table below! Target | CI/CD Status :------- | -----------: iOS | ![CI](https://github.com/microsoft/GSL/workflows/CI/badge.svg) Android | ![CI](https://github.com/microsoft/GSL/workflows/CI/badge.svg) Note: These CI/CD steps are run with each pull request, however failures in them are non-blocking. ## Building the tests To build the tests, you will require the following: * [CMake](http://cmake.org), version 3.1.3 (3.2.3 for AppleClang) or later to be installed and in your PATH. These steps assume the source code of this repository has been cloned into a directory named `c:\GSL`. 1. Create a directory to contain the build outputs for a particular architecture (we name it c:\GSL\build-x86 in this example). cd GSL md build-x86 cd build-x86 2. Configure CMake to use the compiler of your choice (you can see a list by running `cmake --help`). cmake -G "Visual Studio 15 2017" c:\GSL 3. Build the test suite (in this case, in the Debug configuration, Release is another good choice). cmake --build . --config Debug 4. Run the test suite. ctest -C Debug All tests should pass - indicating your platform is fully supported and you are ready to use the GSL types! ## Building GSL - Using vcpkg You can download and install GSL using the [vcpkg](https://github.com/Microsoft/vcpkg) dependency manager: git clone https://github.com/Microsoft/vcpkg.git cd vcpkg ./bootstrap-vcpkg.sh ./vcpkg integrate install vcpkg install ms-gsl The GSL port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository. ## Using the libraries As the types are entirely implemented inline in headers, there are no linking requirements. You can copy the [gsl](./include/gsl) directory into your source tree so it is available to your compiler, then include the appropriate headers in your program. Alternatively set your compiler's *include path* flag to point to the GSL development folder (`c:\GSL\include` in the example above) or installation folder (after running the install). Eg. MSVC++ /I c:\GSL\include GCC/clang -I$HOME/dev/GSL/include Include the library using: #include <gsl/gsl> ## Usage in CMake The library provides a Config file for CMake, once installed it can be found via find_package(Microsoft.GSL CONFIG) Which, when successful, will add library target called `Microsoft.GSL::GSL` which you can use via the usual `target_link_libraries` mechanism. ## Debugging visualization support For Visual Studio users, the file [GSL.natvis](./GSL.natvis) in the root directory of the repository can be added to your project if you would like more helpful visualization of GSL types in the Visual Studio debugger than would be offered by default.
omniverse-code/kit/gsl/PACKAGE-LICENSES/gsl-LICENSE.md
Copyright (c) 2015 Microsoft Corporation. All rights reserved. This code is licensed under the MIT License (MIT). Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
omniverse-code/kit/exts/omni.kit.material.library/docs/index.rst
omni.kit.material.library ########################### Material Library .. toctree:: :maxdepth: 1 CHANGELOG Python API Reference ********************* .. automodule:: omni.kit.material.library :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :imported-members: :exclude-members: chain :noindex: omni.usd._impl.utils.PrimCaching
omniverse-code/kit/exts/omni.kit.window.imageviewer/PACKAGE-LICENSES/omni.kit.window.imageviewer-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
omniverse-code/kit/exts/omni.kit.window.imageviewer/config/extension.toml
[package] version = "1.0.6" category = "Internal" feature = true title = "Image Viewer" description="Adds context menu in the Content Browser that allows to view images." authors = ["NVIDIA"] changelog = "docs/CHANGELOG.md" preview_image = "data/preview.png" icon = "data/icon.png" readme = "docs/README.md" [dependencies] "omni.ui" = {} "omni.kit.widget.imageview" = {} "omni.kit.window.content_browser" = { optional=true } "omni.kit.test" = {} "omni.usd.libs" = {} [[python.module]] name = "omni.kit.window.imageviewer" # Additional python module with tests, to make them discoverable by test system. [[python.module]] name = "omni.kit.window.imageviewer.tests" [[test]] args = ["--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false"] dependencies = [ "omni.kit.mainwindow", "omni.kit.renderer.capture", ] pythonTests.unreliable = [ "*test_general" # OM-49017 ]
omniverse-code/kit/exts/omni.kit.window.imageviewer/omni/kit/window/imageviewer/imageviewer.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.kit.widget.imageview as imageview import omni.ui as ui from .singleton import singleton @singleton class ViewerWindows: """This object keeps all the Image Viewper windows""" def __init__(self): self.__windows = {} def open_window(self, filepath: str) -> ui.Window: """Open ImageViewer window with the image file opened in it""" if filepath in self.__windows: window = self.__windows[filepath] window.visible = True else: window = ImageViewer(filepath) # When window is closed, remove it from the list window.set_visibility_changed_fn(lambda _, f=filepath: self.close(f)) self.__windows[filepath] = window return window def close(self, filepath): """Close and remove spacific window""" del self.__windows[filepath] def close_all(self): """Close and remove all windows""" self.__windows = {} class ImageViewer(ui.Window): """The window with Image Viewer""" def __init__(self, filename: str, **kwargs): if "width" not in kwargs: kwargs["width"] = 640 if "height" not in kwargs: kwargs["height"] = 480 super().__init__(filename, **kwargs) self.frame.set_style({"Window": {"background_color": 0xFF000000, "border_width": 0}}) self.frame.set_build_fn(self.__build_window) self.__filename = filename def __build_window(self): """Called to build the widgets of the window""" # For now it's only one single widget imageview.ImageView(self.__filename, smooth_zoom=True, style={"ImageView": {"background_color": 0xFF000000}}) def destroy(self): pass
omniverse-code/kit/exts/omni.kit.window.imageviewer/omni/kit/window/imageviewer/__init__.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .imageviewer import ImageViewer from .imageviewer_extension import ImageViewerExtension
omniverse-code/kit/exts/omni.kit.window.imageviewer/omni/kit/window/imageviewer/imageviewer_utils.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.kit.app def is_extension_loaded(extansion_name: str) -> bool: """ Returns True if the extension with the given name is loaded. """ def is_ext(ext_id: str, extension_name: str) -> bool: id_name = omni.ext.get_extension_name(ext_id) return id_name == extension_name app = omni.kit.app.get_app_interface() ext_manager = app.get_extension_manager() extensions = ext_manager.get_extensions() loaded = next((ext for ext in extensions if is_ext(ext["id"], extansion_name) and ext["enabled"]), None) return bool(loaded)
omniverse-code/kit/exts/omni.kit.window.imageviewer/omni/kit/window/imageviewer/content_menu.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .imageviewer import ViewerWindows from .imageviewer_utils import is_extension_loaded def content_available(): """ Returns True if the extension "omni.kit.window.content_browser" is loaded. """ return is_extension_loaded("omni.kit.window.content_browser") class ContentMenu: """ When this object is alive, Content Browser has the additional context menu with the items that allow to view image files. """ def __init__(self, version: int = 2): if version != 2: raise RuntimeError("Only version 2 is supported") content_window = self._get_content_window() if content_window: view_menu_name = "Show Image" self.__view_menu_subscription = content_window.add_file_open_handler( view_menu_name, lambda file_path: self._on_show_triggered(view_menu_name, file_path), self._is_show_visible, ) else: self.__view_menu_subscription = None def _get_content_window(self): try: import omni.kit.window.content_browser as content except ImportError: return None return content.get_content_window() def _is_show_visible(self, content_url): """True if we can show the menu item View Image""" # List of available formats: carb/source/plugins/carb.imaging/Imaging.cpp return any( content_url.endswith(f".{ext}") for ext in ["bmp", "dds", "exr", "gif", "hdr", "jpeg", "jpg", "png", "psd", "svg", "tga"] ) def _on_show_triggered(self, menu, value): """Start watching for the layer and run the editor""" ViewerWindows().open_window(value) def destroy(self): """Stop all watchers and remove the menu from the content browser""" if self.__view_menu_subscription: content_window = self._get_content_window() if content_window: content_window.delete_file_open_handler(self.__view_menu_subscription) self.__view_menu_subscription = None ViewerWindows().close_all()
omniverse-code/kit/exts/omni.kit.window.imageviewer/omni/kit/window/imageviewer/imageviewer_extension.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ext from .content_menu import content_available from .content_menu import ContentMenu class ImageViewerExtension(omni.ext.IExt): def __init__(self): super().__init__() self.__imageviewer = None self.__extensions_subscription = None # noqa: PLW0238 self.__content_menu = None def on_startup(self, ext_id): # Setup a callback when any extension is loaded/unloaded app = omni.kit.app.get_app_interface() ext_manager = app.get_extension_manager() self.__extensions_subscription = ( # noqa: PLW0238 ext_manager.get_change_event_stream().create_subscription_to_pop( self._on_event, name="omni.kit.window.imageviewer" ) ) self.__content_menu = None self._on_event(None) def _on_event(self, event): """Called when any extension is loaded/unloaded""" if self.__content_menu: if not content_available(): self.__content_menu.destroy() self.__content_menu = None else: if content_available(): self.__content_menu = ContentMenu() def on_shutdown(self): if self.__imageviewer: self.__imageviewer.destroy() self.__imageviewer = None self.__extensions_subscription = None # noqa: PLW0238 if self.__content_menu: self.__content_menu.destroy() self.__content_menu = None
omniverse-code/kit/exts/omni.kit.window.imageviewer/omni/kit/window/imageviewer/singleton.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. # def singleton(class_): """A singleton decorator""" instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance
omniverse-code/kit/exts/omni.kit.window.imageviewer/omni/kit/window/imageviewer/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 .imageviewer_test import TestImageViewer
omniverse-code/kit/exts/omni.kit.window.imageviewer/omni/kit/window/imageviewer/tests/imageviewer_test.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from pathlib import Path from omni.ui.tests.test_base import OmniUiTest import omni.kit import omni.ui as ui from ..imageviewer import ViewerWindows class TestImageViewer(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() # After running each test async def tearDown(self): self._golden_img_dir = None await super().tearDown() async def test_general(self): window = await self.create_test_window() # noqa: PLW0612, F841 await omni.kit.app.get_app().next_update_async() viewer = ViewerWindows().open_window(f"{self._golden_img_dir.joinpath('lenna.png')}") viewer.flags = ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE viewer.position_x = 0 viewer.position_y = 0 viewer.width = 256 viewer.height = 256 # One frame to show the window and another to build the frame # And a dozen frames more to let the asset load for _ in range(20): await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir)
omniverse-code/kit/exts/omni.kit.window.imageviewer/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.6] - 2022-06-17 ### Changed - Properly linted ## [1.0.5] - 2021-09-20 ### Changed - Fixed unittest path to golden image. ## [1.0.4] - 2021-08-18 ### Changed - Fixed console_browser leak ## [1.0.3] - 2020-12-08 ### Added - Description, preview image and icon ### Changed - Fixed crash on exit ## [1.0.2] - 2020-11-25 ### Changed - Pasting an image URL into the content window's browser bar or double clicking opens the file. ## [1.0.1] - 2020-11-12 ### Changed - Fixed exception in Create ## [1.0.0] - 2020-07-19 ### Added - Adds context menu in the Content Browser
omniverse-code/kit/exts/omni.kit.window.imageviewer/docs/README.md
# Image Viewer [omni.kit.window.imageviewer] It's The extension that can display stored graphical images in a new window. It can handle various graphics file formats.
omniverse-code/kit/exts/omni.kit.window.audiorecorder/PACKAGE-LICENSES/omni.kit.window.audiorecorder-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
omniverse-code/kit/exts/omni.kit.window.audiorecorder/config/extension.toml
[package] title = "Kit Audio Recorder Window" category = "Audio" version = "1.0.1" description = "A simple audio recorder window" detailedDescription = """This adds a window for recording audio to file from an audio capture device. """ preview_image = "data/preview.png" authors = ["NVIDIA"] keywords = ["audio", "capture", "recording"] [dependencies] "omni.kit.audiodeviceenum" = {} "omni.audiorecorder" = {} "omni.ui" = {} "omni.kit.window.content_browser" = { optional=true } "omni.kit.window.filepicker" = {} "omni.kit.pip_archive" = {} "omni.usd" = {} "omni.kit.menu.utils" = {} [python.pipapi] requirements = ["numpy"] [[python.module]] name = "omni.kit.window.audiorecorder" [[test]] args = [ "--/renderer/enabled=pxr", "--/renderer/active=pxr", "--/renderer/multiGpu/enabled=false", "--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611 "--/renderer/multiGpu/maxGpuCount=1", "--/app/asyncRendering=false", "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window", # Use the null device backend. # We need this to ensure the captured data is consistent. # We could use the capture test patterns mode, but there's no way to # synchronize the image capture with the audio capture right now, so we'll # have to just capture silence. "--/audio/deviceBackend=null", # needed for the UI test stuff "--/app/menu/legacy_mode=false", ] dependencies = [ "omni.hydra.pxr", "omni.kit.mainwindow", "omni.kit.ui_test", "carb.audio", ] stdoutFailPatterns.exclude = [ "*" # I don't want these but OmniUiTest forces me to use them ]
omniverse-code/kit/exts/omni.kit.window.audiorecorder/omni/kit/window/audiorecorder/__init__.py
from .audio_recorder_window import *
omniverse-code/kit/exts/omni.kit.window.audiorecorder/omni/kit/window/audiorecorder/audio_recorder_window.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb.audio import omni.audiorecorder import omni.kit.ui import omni.ui import threading import time import re import asyncio from typing import Callable from omni.kit.window.filepicker import FilePickerDialog class AudioRecorderWindowExtension(omni.ext.IExt): """Audio Recorder Window Extension""" class ComboModel(omni.ui.AbstractItemModel): class ComboItem(omni.ui.AbstractItem): def __init__(self, text): super().__init__() self.model = omni.ui.SimpleStringModel(text) def __init__(self): super().__init__() self._options = [ ["16 bit PCM", carb.audio.SampleFormat.PCM16], ["24 bit PCM", carb.audio.SampleFormat.PCM24], ["32 bit PCM", carb.audio.SampleFormat.PCM32], ["float PCM", carb.audio.SampleFormat.PCM_FLOAT], ["Vorbis", carb.audio.SampleFormat.VORBIS], ["FLAC", carb.audio.SampleFormat.FLAC], ["Opus", carb.audio.SampleFormat.OPUS], ] self._current_index = omni.ui.SimpleIntModel() self._current_index.add_value_changed_fn(lambda a: self._item_changed(None)) self._items = [AudioRecorderWindowExtension.ComboModel.ComboItem(text) for (text, value) in self._options] 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 def set_value(self, value): for i in range(0, len(self._options)): if self._options[i][1] == value: self._current_index.as_int = i break def get_value(self): return self._options[self._current_index.as_int][1] class FieldModel(omni.ui.AbstractValueModel): def __init__(self): super(AudioRecorderWindowExtension.FieldModel, self).__init__() self._value = "" def get_value_as_string(self): return self._value def begin_edit(self): pass def set_value(self, value): self._value = value self._value_changed() def end_edit(self): pass def get_value(self): return self._value def _choose_file_clicked(self): # pragma: no cover dialog = FilePickerDialog( "Select File", apply_button_label="Select", click_apply_handler=lambda filename, dirname: self._on_file_pick(dialog, filename, dirname), ) dialog.show() def _on_file_pick(self, dialog: FilePickerDialog, filename: str, dirname: str): # pragma: no cover path = "" if dirname: path = f"{dirname}/{filename}" elif filename: path = filename dialog.hide() self._file_field.model.set_value(path) def _menu_callback(self, a, b): self._window.visible = not self._window.visible def _read_callback(self, data): # pragma: no cover self._display_buffer[self._display_buffer_index] = data self._display_buffer_index = (self._display_buffer_index + 1) % self._display_len buf = [] for i in range(self._display_len): buf += self._display_buffer[(self._display_buffer_index + i) % self._display_len] width = 512 height = 128 img = omni.audiorecorder.draw_waveform_from_blob_int16( input=buf, channels=1, width=width, height=height, fg_color=[0.89, 0.54, 0.14, 1.0], bg_color=[0.0, 0.0, 0.0, 0.0], ) self._waveform_image_provider.set_bytes_data(img, [width, height]) def _close_error_window(self): self._error_window.visible = False def _record_clicked(self): if self._recording: self._record_button.set_style({"image_url": "resources/glyphs/audio_record.svg"}) self._recorder.stop_recording() self._recording = False else: result = self._recorder.begin_recording_int16( filename=self._file_field_model.get_value(), callback=self._read_callback, output_format=self._format_model.get_value(), buffer_length=200, period=25, length_type=carb.audio.UnitType.MILLISECONDS, ) if result: self._record_button.set_style({"image_url": "resources/glyphs/timeline_stop.svg"}) self._recording = True else: # pragma: no cover self._error_window = omni.ui.Window( "Audio Recorder Error", width=400, height=0, flags=omni.ui.WINDOW_FLAGS_NO_DOCKING ) with self._error_window.frame: with omni.ui.VStack(): with omni.ui.HStack(): omni.ui.Spacer() self._error_window_label = omni.ui.Label( "Failed to start recording. The file path may be incorrect or the device may be inaccessible.", word_wrap=True, width=380, alignment=omni.ui.Alignment.CENTER, ) omni.ui.Spacer() with omni.ui.HStack(): omni.ui.Spacer() self._error_window_ok_button = omni.ui.Button( width=64, height=32, clicked_fn=self._close_error_window, text="ok" ) omni.ui.Spacer() def _stop_clicked(self): pass def _create_tooltip(self, text): """Create a tooltip in a fixed style""" with omni.ui.VStack(width=400): omni.ui.Label(text, word_wrap=True) def on_startup(self): self._display_len = 8 self._display_buffer = [[0] for i in range(self._display_len)] self._display_buffer_index = 0 # self._ticker_pos = 0; self._recording = False self._recorder = omni.audiorecorder.create_audio_recorder() self._window = omni.ui.Window("Audio Recorder", width=600, height=240) with self._window.frame: with omni.ui.VStack(height=0, spacing=8): # file dialogue with omni.ui.HStack(): omni.ui.Button( width=32, height=32, clicked_fn=self._choose_file_clicked, style={"image_url": "resources/glyphs/folder.svg"}, ) self._file_field_model = AudioRecorderWindowExtension.FieldModel() self._file_field = omni.ui.StringField(self._file_field_model, height=32) # waveform with omni.ui.HStack(height=128): omni.ui.Spacer() self._waveform_image_provider = omni.ui.ByteImageProvider() self._waveform_image = omni.ui.ImageWithProvider( self._waveform_image_provider, width=omni.ui.Percent(95), height=omni.ui.Percent(100), fill_policy=omni.ui.IwpFillPolicy.IWP_STRETCH, ) omni.ui.Spacer() # buttons with omni.ui.HStack(): with omni.ui.ZStack(): omni.ui.Spacer() self._anim_label = omni.ui.Label("", alignment=omni.ui.Alignment.CENTER) with omni.ui.VStack(): omni.ui.Spacer() self._format_model = AudioRecorderWindowExtension.ComboModel() self._format = omni.ui.ComboBox( self._format_model, height=0, tooltip_fn=lambda: self._create_tooltip( "The format for the output file." + "The PCM formats will output as a WAVE file (.wav)." + "FLAC will output as a FLAC file (.flac)." + "Vorbis and Opus will output as an Ogg file (.ogg/.oga)." ), ) omni.ui.Spacer() self._record_button = omni.ui.Button( width=32, height=32, clicked_fn=self._record_clicked, style={"image_url": "resources/glyphs/audio_record.svg"}, ) omni.ui.Spacer() # add a callback to open the window self._menuEntry = omni.kit.ui.get_editor_menu().add_item("Window/Audio Recorder", self._menu_callback) self._window.visible = False def on_shutdown(self): # pragma: no cover self._recorder = None self._window = None self._menuEntry = None
omniverse-code/kit/exts/omni.kit.window.audiorecorder/omni/kit/window/audiorecorder/tests/__init__.py
from .test_audiorecorder_window import * # pragma: no cover
omniverse-code/kit/exts/omni.kit.window.audiorecorder/omni/kit/window/audiorecorder/tests/test_audiorecorder_window.py
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.app import omni.kit.test import omni.ui as ui import omni.usd import omni.timeline import carb.tokens import carb.audio from omni.ui.tests.test_base import OmniUiTest from omni.kit import ui_test #from omni.ui_query import OmniUIQuery import pathlib import asyncio import tempfile import os import platform class TestAudioRecorderWindow(OmniUiTest): # pragma: no cover async def _dock_window(self, win): await self.docked_test_window( window=win._window, width=600, height=240) #def _dump_ui_tree(self, root): # print("DUMP UI TREE START") # #windows = omni.ui.Workspace.get_windows() # #children = [windows[0].frame] # children = [root.frame] # print(str(dir(root.frame))) # def recurse(children, path=""): # for c in children: # name = path + "/" + type(c).__name__ # print(name) # if isinstance(c, omni.ui.ComboBox): # print(str(dir(c))) # recurse(omni.ui.Inspector.get_children(c), name) # recurse(children) # print("DUMP UI TREE END") # Before running each test async def setUp(self): await super().setUp() extension_path = carb.tokens.get_tokens_interface().resolve("${omni.kit.window.audiorecorder}") self._test_path = pathlib.Path(extension_path).joinpath("data").joinpath("tests").absolute() self._golden_img_dir = self._test_path.joinpath("golden") # open the dropdown window_menu = omni.kit.ui_test.get_menubar().find_menu("Window") self.assertIsNotNone(window_menu) await window_menu.click() # click the Audio Recorder entry to open it rec_menu = omni.kit.ui_test.get_menubar().find_menu("Audio Recorder") self.assertIsNotNone(rec_menu) await rec_menu.click() #self._dump_ui_tree(omni.kit.ui_test.find("Audio Recorder").window) # After running each test async def tearDown(self): await super().tearDown() self._rec = None async def _test_just_opened(self): win = omni.kit.ui_test.find("Audio Recorder") self.assertIsNotNone(win) await self._dock_window(win) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_just_opened.png") async def _test_recording(self): # wait for docking to finish. To prevent ui_test getting widgets as while window is being rebuilt await ui_test.human_delay(50) iface = carb.audio.acquire_data_interface() self.assertIsNotNone(iface) win = omni.kit.ui_test.find("Audio Recorder") self.assertIsNotNone(win) file_name_textbox = win.find("**/StringField[*]") self.assertIsNotNone(file_name_textbox) record_button = win.find("**/HStack[2]/Button[0]") self.assertIsNotNone(record_button) with tempfile.TemporaryDirectory() as temp_dir: path = os.path.join(temp_dir, "test.wav") # type our file path into the textbox await file_name_textbox.click() await file_name_textbox.input(str(path)) # the user hit the record button await record_button.click() await asyncio.sleep(1.0) # change the text in the textbox so we'll have something constant # for the image comparison await file_name_textbox.input("soundstorm_song.wav") await self._dock_window(win) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_recording.png") # wait for docking to finish. To prevent ui_test getting widgets as while window is being rebuilt await ui_test.human_delay(50) # grab these again just in case window docking broke it win = omni.kit.ui_test.find("Audio Recorder") self.assertIsNotNone(win) record_button = win.find("**/HStack[2]/Button[0]") self.assertIsNotNone(record_button) # the user hit the stop button await record_button.click() await self._dock_window(win) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_stopped.png") # wait for docking to finish. To prevent ui_test getting widgets as while window is being rebuilt await ui_test.human_delay(50) # grab these again just in case window docking broke it win = omni.kit.ui_test.find("Audio Recorder") self.assertIsNotNone(win) file_name_textbox = win.find("**/StringField[*]") self.assertIsNotNone(file_name_textbox) record_button = win.find("**/HStack[2]/Button[0]") self.assertIsNotNone(record_button) format_combobox = win.find("**/ComboBox[*]") self.assertIsNotNone(format_combobox) # analyze the data sound = iface.create_sound_from_file(path, streaming=True) self.assertIsNotNone(sound) fmt = sound.get_format() self.assertEqual(fmt.format, carb.audio.SampleFormat.PCM16) pcm = sound.get_buffer_as_int16() for i in range(len(pcm)): self.assertEqual(pcm[i], 0); sound = None # close it # try again with a different format # FIXME: We should not be manipulating the model directly, but ui_test # doesn't have a way to find any of the box item to click on, # and ComboBoxes don't respond to keyboard input either. format_combobox.model.set_value(carb.audio.SampleFormat.VORBIS) path2 = os.path.join(temp_dir, "test.oga") await file_name_textbox.input(str(path2)) # the user hit the record button await record_button.click() await asyncio.sleep(1.0) # the user hit the stop button await record_button.click() # analyze the data sound = iface.create_sound_from_file(str(path2), streaming=True) self.assertIsNotNone(sound) fmt = sound.get_format() self.assertEqual(fmt.format, carb.audio.SampleFormat.VORBIS) pcm = sound.get_buffer_as_int16() for i in range(len(pcm)): self.assertEqual(pcm[i], 0); sound = None # close it async def test_all(self): await self._test_just_opened() await self._test_recording()
omniverse-code/kit/exts/omni.command.usd/PACKAGE-LICENSES/omni.command.usd-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
omniverse-code/kit/exts/omni.command.usd/config/extension.toml
[package] title = "Command USD" description = "Usefull command for USD." category = "Internal" version = "1.0.2" readme = "docs/README.md" changelog="docs/CHANGELOG.md" preview_image = "data/preview.png" icon = "data/icon.png" [[python.module]] name = "omni.command.usd" [dependencies] "omni.kit.commands" = {} "omni.usd" = {}
omniverse-code/kit/exts/omni.command.usd/omni/command/usd/__init__.py
from .commands.usd_commands import *
omniverse-code/kit/exts/omni.command.usd/omni/command/usd/commands/__init__.py
from .usd_commands import * from .parenting_commands import *
omniverse-code/kit/exts/omni.command.usd/omni/command/usd/commands/parenting_commands.py
import omni.kit.commands import omni.usd from typing import List from pxr import Sdf class ParentPrimsCommand(omni.kit.commands.Command): def __init__( self, parent_path: str, child_paths: List[str], on_move_fn: callable = None, keep_world_transform: bool = True ): """ Move prims into children of "parent" primitives undoable **Command**. Args: parent_path: prim path to become parent of child_paths child_paths: prim paths to become children of parent_prim keep_world_transform: If it needs to keep the world transform after parenting. """ self._parent_path = parent_path self._child_paths = child_paths.copy() self._on_move_fn = on_move_fn self._keep_world_transform = keep_world_transform def do(self): with omni.kit.undo.group(): for path in self._child_paths: path_to = self._parent_path + "/" + Sdf.Path(path).name omni.kit.commands.execute( "MovePrim", path_from=path, path_to=path_to, on_move_fn=self._on_move_fn, destructive=False, keep_world_transform=self._keep_world_transform ) def undo(self): pass class UnparentPrimsCommand(omni.kit.commands.Command): def __init__( self, paths: List[str], on_move_fn: callable = None, keep_world_transform: bool = True ): """ Move prims into "/" primitives undoable **Command**. Args: paths: prim path to become parent of child_paths keep_world_transform: If it needs to keep the world transform after parenting. """ self._paths = paths.copy() self._on_move_fn = on_move_fn self._keep_world_transform = keep_world_transform def do(self): with omni.kit.undo.group(): for path in self._paths: path_to = "/" + Sdf.Path(path).name omni.kit.commands.execute( "MovePrim", path_from=path, path_to=path_to, on_move_fn=self._on_move_fn, destructive=False, keep_world_transform=self._keep_world_transform ) def undo(self): pass omni.kit.commands.register_all_commands_in_module(__name__)
omniverse-code/kit/exts/omni.command.usd/omni/command/usd/commands/usd_commands.py
import omni.kit.commands import omni.usd from typing import List from pxr import Sdf class TogglePayLoadLoadSelectedPrimsCommand(omni.kit.commands.Command): def __init__(self, selected_paths: List[str]): """ Toggles the load/unload payload of the selected primitives undoable **Command**. Args: selected_paths: Old selected prim paths. """ self._stage = omni.usd.get_context().get_stage() self._selected_paths = selected_paths.copy() def _toggle_load(self): for selected_path in self._selected_paths: selected_prim = self._stage.GetPrimAtPath(selected_path) if selected_prim.IsLoaded(): selected_prim.Unload() else: selected_prim.Load() def do(self): self._toggle_load() def undo(self): self._toggle_load() class SetPayLoadLoadSelectedPrimsCommand(omni.kit.commands.Command): def __init__(self, selected_paths: List[str], value: bool): """ Set the load/unload payload of the selected primitives undoable **Command**. Args: selected_paths: Old selected prim paths. value: True = load, False = unload """ self._stage = omni.usd.get_context().get_stage() self._selected_paths = selected_paths.copy() self._processed_path = set() self._value = value self._is_undo = False def _set_load(self): if self._is_undo: paths = self._processed_path else: paths = self._selected_paths for selected_path in paths: selected_prim = self._stage.GetPrimAtPath(selected_path) if (selected_prim.IsLoaded() and self._value) or (not selected_prim.IsLoaded() and not self._value): if selected_path in self._processed_path: self._processed_path.remove(selected_path) continue if self._value: selected_prim.Load() else: selected_prim.Unload() self._processed_path.add(selected_path) def do(self): self._set_load() def undo(self): self._is_undo = True self._value = not self._value self._set_load() self._value = not self._value self._processed_path = set() self._is_undo = False omni.kit.commands.register_all_commands_in_module(__name__)
omniverse-code/kit/exts/omni.command.usd/omni/command/usd/tests/__init__.py
from .test_command_usd import *
omniverse-code/kit/exts/omni.command.usd/omni/command/usd/tests/test_command_usd.py
import carb import omni.kit.test import omni.kit.undo import omni.kit.commands import omni.usd from pxr import Sdf, Usd def get_stage_default_prim_path(stage): if stage.HasDefaultPrim(): return stage.GetDefaultPrim().GetPath() else: return Sdf.Path.absoluteRootPath class TestCommandUsd(omni.kit.test.AsyncTestCase): async def test_toggle_payload_selected(self): carb.log_info("Test TogglePayLoadLoadSelectedPrimsCommand") await omni.usd.get_context().new_stage_async() usd_context = omni.usd.get_context() selection = usd_context.get_selection() stage = usd_context.get_stage() default_prim_path = get_stage_default_prim_path(stage) payload1 = Usd.Stage.CreateInMemory("payload1.usd") payload1.DefinePrim("/payload1/scope1", "Xform") payload1.DefinePrim("/payload1/scope1/xform", "Cube") payload2 = Usd.Stage.CreateInMemory("payload2.usd") payload2.DefinePrim("/payload2/scope2", "Xform") payload2.DefinePrim("/payload2/scope2/xform", "Cube") payload3 = Usd.Stage.CreateInMemory("payload3.usd") payload3.DefinePrim("/payload3/scope3", "Xform") payload3.DefinePrim("/payload3/scope3/xform", "Cube") payload4 = Usd.Stage.CreateInMemory("payload4.usd") payload4.DefinePrim("/payload4/scope4", "Xform") payload4.DefinePrim("/payload4/scope4/xform", "Cube") ps1 = stage.DefinePrim(default_prim_path.AppendChild("payload1"), "Xform") ps1.GetPayloads().AddPayload( Sdf.Payload(payload1.GetRootLayer().identifier, "/payload1")) ps2 = stage.DefinePrim(default_prim_path.AppendChild("payload2"), "Xform") ps2.GetPayloads().AddPayload( Sdf.Payload(payload2.GetRootLayer().identifier, "/payload2")) ps3 = stage.DefinePrim(default_prim_path.AppendChild("payload3"), "Xform") ps3.GetPayloads().AddPayload( Sdf.Payload(payload3.GetRootLayer().identifier, "/payload3")) ps4 = stage.DefinePrim(ps3.GetPath().AppendChild("payload4"), "Xform") ps4.GetPayloads().AddPayload( Sdf.Payload(payload4.GetRootLayer().identifier, "/payload4")) # unload everything stage.Unload() self.assertTrue(not ps1.IsLoaded()) self.assertTrue(not ps2.IsLoaded()) self.assertTrue(not ps3.IsLoaded()) self.assertTrue(not ps4.IsLoaded()) # if nothing selected, payload state should not change. selection.clear_selected_prim_paths() paths = selection.get_selected_prim_paths() omni.kit.commands.execute("TogglePayLoadLoadSelectedPrims", selected_paths=paths) self.assertTrue(not ps1.IsLoaded()) self.assertTrue(not ps2.IsLoaded()) self.assertTrue(not ps3.IsLoaded()) self.assertTrue(not ps4.IsLoaded()) # load payload1 selection.set_selected_prim_paths( [ ps1.GetPath().pathString ], False, ) paths = selection.get_selected_prim_paths() omni.kit.commands.execute("TogglePayLoadLoadSelectedPrims", selected_paths=paths) self.assertTrue(ps1.IsLoaded()) # unload payload1 omni.kit.commands.execute("TogglePayLoadLoadSelectedPrims", selected_paths=paths) self.assertTrue(not ps1.IsLoaded()) # load payload1, 2 and 3. 4 will load selection.set_selected_prim_paths( [ ps1.GetPath().pathString, ps2.GetPath().pathString, ps3.GetPath().pathString, ], False, ) paths = selection.get_selected_prim_paths() omni.kit.commands.execute("TogglePayLoadLoadSelectedPrims", selected_paths=paths) self.assertTrue(ps1.IsLoaded()) self.assertTrue(ps2.IsLoaded()) self.assertTrue(ps3.IsLoaded()) self.assertTrue(ps4.IsLoaded()) # unload 4 selection.set_selected_prim_paths( [ ps4.GetPath().pathString ], False, ) paths = selection.get_selected_prim_paths() omni.kit.commands.execute("TogglePayLoadLoadSelectedPrims", selected_paths=paths) self.assertTrue(not ps4.IsLoaded()) # undo omni.kit.undo.undo() self.assertTrue(ps4.IsLoaded()) # redo omni.kit.undo.redo() self.assertTrue(not ps4.IsLoaded()) async def test_set_payload_selected(self): carb.log_info("Test SetPayLoadLoadSelectedPrimsCommand") await omni.usd.get_context().new_stage_async() usd_context = omni.usd.get_context() selection = usd_context.get_selection() stage = usd_context.get_stage() default_prim_path = get_stage_default_prim_path(stage) payload1 = Usd.Stage.CreateInMemory("payload1.usd") payload1.DefinePrim("/payload1/scope1", "Xform") payload1.DefinePrim("/payload1/scope1/xform", "Cube") payload2 = Usd.Stage.CreateInMemory("payload2.usd") payload2.DefinePrim("/payload2/scope2", "Xform") payload2.DefinePrim("/payload2/scope2/xform", "Cube") payload3 = Usd.Stage.CreateInMemory("payload3.usd") payload3.DefinePrim("/payload3/scope3", "Xform") payload3.DefinePrim("/payload3/scope3/xform", "Cube") payload4 = Usd.Stage.CreateInMemory("payload4.usd") payload4.DefinePrim("/payload4/scope4", "Xform") payload4.DefinePrim("/payload4/scope4/xform", "Cube") ps1 = stage.DefinePrim(default_prim_path.AppendChild("payload1"), "Xform") ps1.GetPayloads().AddPayload( Sdf.Payload(payload1.GetRootLayer().identifier, "/payload1")) ps2 = stage.DefinePrim(default_prim_path.AppendChild("payload2"), "Xform") ps2.GetPayloads().AddPayload( Sdf.Payload(payload2.GetRootLayer().identifier, "/payload2")) ps3 = stage.DefinePrim(default_prim_path.AppendChild("payload3"), "Xform") ps3.GetPayloads().AddPayload( Sdf.Payload(payload3.GetRootLayer().identifier, "/payload3")) ps4 = stage.DefinePrim(ps3.GetPath().AppendChild("payload4"), "Xform") ps4.GetPayloads().AddPayload( Sdf.Payload(payload4.GetRootLayer().identifier, "/payload4")) # unload everything stage.Unload() self.assertTrue(not ps1.IsLoaded()) self.assertTrue(not ps2.IsLoaded()) self.assertTrue(not ps3.IsLoaded()) self.assertTrue(not ps4.IsLoaded()) # if nothing selected, payload state should not change. selection.clear_selected_prim_paths() paths = selection.get_selected_prim_paths() omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) self.assertTrue(not ps1.IsLoaded()) self.assertTrue(not ps2.IsLoaded()) self.assertTrue(not ps3.IsLoaded()) self.assertTrue(not ps4.IsLoaded()) # load payload1 selection.set_selected_prim_paths( [ ps1.GetPath().pathString ], False, ) paths = selection.get_selected_prim_paths() omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) self.assertTrue(ps1.IsLoaded()) omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) self.assertTrue(ps1.IsLoaded()) # unload payload1 omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=False) self.assertTrue(not ps1.IsLoaded()) omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=False) self.assertTrue(not ps1.IsLoaded()) # load payload1, 2 and 3. 4 will load selection.set_selected_prim_paths( [ ps1.GetPath().pathString, ps2.GetPath().pathString, ps3.GetPath().pathString, ], False, ) paths = selection.get_selected_prim_paths() omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) self.assertTrue(ps1.IsLoaded()) self.assertTrue(ps2.IsLoaded()) self.assertTrue(ps3.IsLoaded()) self.assertTrue(ps4.IsLoaded()) selection.set_selected_prim_paths( [ ps4.GetPath().pathString ], False, ) paths = selection.get_selected_prim_paths() # reload 4 omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) self.assertTrue(ps4.IsLoaded()) # unload 4 omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=False) self.assertTrue(not ps4.IsLoaded()) # undo omni.kit.undo.undo() self.assertTrue(ps4.IsLoaded()) # redo omni.kit.undo.redo() self.assertTrue(not ps4.IsLoaded()) omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=False) self.assertTrue(not ps4.IsLoaded()) omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=False) self.assertTrue(not ps4.IsLoaded()) omni.kit.undo.undo() self.assertTrue(not ps4.IsLoaded()) omni.kit.undo.redo() self.assertTrue(not ps4.IsLoaded()) omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) # -1 self.assertTrue(ps4.IsLoaded()) omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) # 0 self.assertTrue(ps4.IsLoaded()) omni.kit.undo.undo() self.assertTrue(ps4.IsLoaded()) omni.kit.undo.redo() self.assertTrue(ps4.IsLoaded()) omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=False) # 1 self.assertTrue(not ps4.IsLoaded()) # 1 omni.kit.undo.undo() self.assertTrue(ps4.IsLoaded()) # 0 omni.kit.undo.redo() self.assertTrue(not ps4.IsLoaded()) # 1 omni.kit.undo.undo() self.assertTrue(ps4.IsLoaded()) # 0 # triple undo omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) # 2 omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) # 3 omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=False) # 4 omni.kit.commands.execute("SetPayLoadLoadSelectedPrims", selected_paths=paths, value=True) # 5 self.assertTrue(ps4.IsLoaded()) # 5 omni.kit.undo.undo() self.assertTrue(not ps4.IsLoaded()) # 4 omni.kit.undo.undo() self.assertTrue(ps4.IsLoaded()) # 3 omni.kit.undo.undo() self.assertTrue(ps4.IsLoaded()) # 2 # more undo omni.kit.undo.undo() self.assertTrue(ps4.IsLoaded()) # 0 omni.kit.undo.undo() self.assertTrue(ps4.IsLoaded()) # -1
omniverse-code/kit/exts/omni.command.usd/docs/CHANGELOG.md
## [1.0.2] - 2022-11-10 ### Removed - Removed dependency on omni.kit.test ## [1.0.1] - 2021-03-15 ### Changed - Added "ParentPrimsCommand" and "UnparentPrimsCommand" ## [0.1.0] - 2021-02-17 ### Changed - Add "TogglePayLoadLoadSelectedPrimsCommand" and "SetPayLoadLoadSelectedPrimsCommand"
omniverse-code/kit/exts/omni.command.usd/docs/README.md
# Command USD [omni.command.usd] Usefull command for USD.
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/style.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["welcome_widget_style"] from omni.ui import color as cl from omni.ui import constant as fl from omni.ui import url import omni.kit.app import omni.ui as ui import pathlib EXTENSION_FOLDER_PATH = pathlib.Path( omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) ) # Pre-defined constants. It's possible to change them runtime. cl.welcome_widget_attribute_bg = cl("#1f2124") cl.welcome_widget_attribute_fg = cl("#0f1115") cl.welcome_widget_hovered = cl("#FFFFFF") cl.welcome_widget_text = cl("#CCCCCC") fl.welcome_widget_attr_hspacing = 10 fl.welcome_widget_attr_spacing = 1 fl.welcome_widget_group_spacing = 2 url.welcome_widget_icon_closed = f"{EXTENSION_FOLDER_PATH}/data/closed.svg" url.welcome_widget_icon_opened = f"{EXTENSION_FOLDER_PATH}/data/opened.svg" # The main style dict welcome_widget_style = { "Label::attribute_name": { "alignment": ui.Alignment.RIGHT_CENTER, "margin_height": fl.welcome_widget_attr_spacing, "margin_width": fl.welcome_widget_attr_hspacing, }, "Label::title": {"alignment": ui.Alignment.CENTER, "color": cl.welcome_widget_text, "font_size": 30}, "Label::attribute_name:hovered": {"color": cl.welcome_widget_hovered}, "Label::collapsable_name": {"alignment": ui.Alignment.LEFT_CENTER}, "Slider::attribute_int:hovered": {"color": cl.welcome_widget_hovered}, "Slider": { "background_color": cl.welcome_widget_attribute_bg, "draw_mode": ui.SliderDrawMode.HANDLE, }, "Slider::attribute_float": { "draw_mode": ui.SliderDrawMode.FILLED, "secondary_color": cl.welcome_widget_attribute_fg, }, "Slider::attribute_float:hovered": {"color": cl.welcome_widget_hovered}, "Slider::attribute_vector:hovered": {"color": cl.welcome_widget_hovered}, "Slider::attribute_color:hovered": {"color": cl.welcome_widget_hovered}, "CollapsableFrame::group": {"margin_height": fl.welcome_widget_group_spacing}, "Image::collapsable_opened": {"color": cl.welcome_widget_text, "image_url": url.welcome_widget_icon_opened}, "Image::collapsable_closed": {"color": cl.welcome_widget_text, "image_url": url.welcome_widget_icon_closed}, }
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/extension.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["WelcomeWindowExtension"] import asyncio import carb import omni.ext import omni.ui as ui from typing import Optional class WelcomeWindowExtension(omni.ext.IExt): """The entry point for Welcome Window""" WINDOW_NAME = "Welcome Window" # MENU_PATH = f"Window/{WINDOW_NAME}" def on_startup(self): self.__window: Optional["WelcomeWindow"] = None self.__widget: Optional["WelcomeWidget"] = None self.__render_loading: Optional["ViewportReady"] = None self.show_welcome(True) def on_shutdown(self): self._menu = None if self.__window: self.__window.destroy() self.__window = None if self.__widget: self.__widget.destroy() self.__widget = None def show_welcome(self, visible: bool): in_viewport = carb.settings.get_settings().get("/exts/omni.kit.window.welcome/embedInViewport") if in_viewport and not self.__window: self.__show_widget(visible) else: self.__show_window(visible) if not visible and self.__render_loading: self.__render_loading = None def __get_buttons(self) -> dict: return { "Create Empty Scene": self.__create_empty_scene, "Open Last Saved Scene": None, "Browse Scenes": None } def __destroy_object(self, object): # Hide it immediately object.visible = False # And destroy it in the future async def destroy_object(object): await omni.kit.app.get_app().next_update_async() object.destroy() asyncio.ensure_future(destroy_object(object)) def __show_window(self, visible: bool): if visible and self.__window is None: from .window import WelcomeWindow self.__window = WelcomeWindow(WelcomeWindowExtension.WINDOW_NAME, width=500, height=300, buttons=self.__get_buttons()) elif self.__window and not visible: self.__destroy_object(self.__window) self.__window = None elif self.__window: self.__window.visible = True def __show_widget(self, visible: bool): if visible and self.__widget is None: async def add_to_viewport(): try: from omni.kit.viewport.utility import get_active_viewport_window from .widget import WelcomeWidget viewport_window = get_active_viewport_window() with viewport_window.get_frame("omni.kit.window.welcome"): self.__widget = WelcomeWidget(self.__get_buttons(), add_background=True) except (ImportError, AttributeError): # Fallback to Welcome window self.__show_window(visible) asyncio.ensure_future(add_to_viewport()) elif self.__widget and not visible: self.__destroy_object(self.__widget) self.__widget = None elif self.__widget: self.__widget.visible = True def __button_clicked(self): self.show_welcome(False) def __create_empty_scene(self, renderer: Optional[str] = None): self.__button_clicked() settings = carb.settings.get_settings() ext_manager = omni.kit.app.get_app().get_extension_manager() if renderer is None: renderer = settings.get("/exts/omni.app.setup/backgroundRendererLoad/renderer") if not renderer: return ext_manager.set_extension_enabled_immediate("omni.kit.viewport.bundle", True) if renderer == "iray": ext_manager.set_extension_enabled_immediate(f"omni.hydra.rtx", True) ext_manager.set_extension_enabled_immediate(f"omni.hydra.{renderer}", True) else: ext_manager.set_extension_enabled_immediate(f"omni.kit.viewport.{renderer}", True) async def _new_stage_async(): if settings.get("/exts/omni.kit.window.welcome/showRenderLoading"): from .render_loading import start_render_loading_ui self.__render_loading = start_render_loading_ui(ext_manager, renderer) await omni.kit.app.get_app().next_update_async() import omni.kit.stage_templates as stage_templates stage_templates.new_stage(template=None) await omni.kit.app.get_app().next_update_async() from omni.kit.viewport.utility import get_active_viewport get_active_viewport().set_hd_engine(renderer) asyncio.ensure_future(_new_stage_async())
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["WelcomeWindowExtension"] from .extension import WelcomeWindowExtension
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/render_loading.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["start_render_loading_ui"] def start_render_loading_ui(ext_manager, renderer: str): import carb import time time_begin = time.time() carb.settings.get_settings().set("/exts/omni.kit.viewport.ready/startup/enabled", False) ext_manager.set_extension_enabled_immediate("omni.kit.viewport.ready", True) from omni.kit.viewport.ready.viewport_ready import ViewportReady, ViewportReadyDelegate class TimerDelegate(ViewportReadyDelegate): def __init__(self, time_begin): super().__init__() self.__timer_start = time.time() self.__vp_ready_cost = self.__timer_start - time_begin @property def font_size(self) -> float: return 48 @property def message(self) -> str: rtx_mode = { "RaytracedLighting": "Real-Time", "PathTracing": "Interactive (Path Tracing)", "LightspeedAperture": "Aperture (Game Path Tracer)" }.get(carb.settings.get_settings().get("/rtx/rendermode"), "Real-Time") renderer_label = { "rtx": f"RTX - {rtx_mode}", "iray": "RTX - Accurate (Iray)", "pxr": "Pixar Storm", "index": "RTX - Scientific (IndeX)" }.get(renderer, renderer) return f"Waiting for {renderer_label} to start" def on_complete(self): rtx_load_time = time.time() - self.__timer_start super().on_complete() print(f"Time until pixel: {rtx_load_time}") print(f"ViewportReady cost: {self.__vp_ready_cost}") return ViewportReady(TimerDelegate(time_begin))
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/widget.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["WelcomeWidget"] import carb import omni.kit.app import omni.ui as ui from typing import Callable, Optional class WelcomeWidget(): """The class that represents the window""" def __init__(self, buttons: dict, style: Optional[dict] = None, button_size: Optional[tuple] = None, add_background: bool = False): if style is None: from .style import welcome_widget_style style = welcome_widget_style if button_size is None: button_size = (150, 100) self.__add_background = add_background # Save the button_size for later use self.__buttons = buttons self.__button_size = button_size # Create the top-level ui.Frame self.__frame: ui.Frame = ui.Frame() # Apply the style to all the widgets of this window self.__frame.style = style # Set the function that is called to build widgets when the window is visible self.__frame.set_build_fn(self.create_ui) def destroy(self): # It will destroy all the children if self.__frame: self.__frame.destroy() self.__frame = None def create_label(self): ui.Label("Select Stage", name="title") def create_button(self, label: str, width: float, height: float, clicked_fn: Callable): ui.Button(label, width=width, height=height, clicked_fn=clicked_fn) def create_buttons(self, width: float, height: float): for label, clicked_fn in self.__buttons.items(): self.create_button(label, width=width, height=height, clicked_fn=clicked_fn) def create_background(self): bg_color = carb.settings.get_settings().get('/exts/omni.kit.viewport.ready/background_color') if bg_color: omni.ui.Rectangle(style={"background_color": bg_color}) def create_ui(self): with ui.ZStack(): if self.__add_background: self.create_background() with ui.HStack(): ui.Spacer(width=20) with ui.VStack(): ui.Spacer() self.create_label() ui.Spacer(height=20) with ui.HStack(height=100): ui.Spacer() self.create_buttons(self.__button_size[0], self.__button_size[1]) ui.Spacer() ui.Spacer() ui.Spacer(width=20) @property def visible(self): return self.__frame.visible if self.__frame else None @visible.setter def visible(self, visible: bool): if self.__frame: self.__frame.visible = visible elif visible: import carb carb.log_error("Cannot make WelcomeWidget visible after it was destroyed")
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/window.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["WelcomeWindow"] from .widget import WelcomeWidget from typing import Optional import omni.ui as ui class WelcomeWindow(ui.Window): """The class that represents the window""" def __init__(self, title: str, buttons: dict, *args, **kwargs): super().__init__(title, *args, **kwargs) self.__buttons = buttons self.__widget: Optional[WelcomeWidget] = None # Set the function that is called to build widgets when the window is visible self.frame.set_build_fn(self.__build_fn) def __destroy_widget(self): if self.__widget: self.__widget.destroy() self.__widget = None def __build_fn(self): # Destroy any existing WelcomeWidget self.__destroy_widget() # Add the Welcomwidget self.__widget = WelcomeWidget(self.__buttons) def destroy(self): # It will destroy all the children self.__destroy_widget() super().destroy() @property def wlcome_widget(self): return self.__widget
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/tests/test_widget.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["TestWidget"] from omni.kit.window.welcome.widget import WelcomeWidget import omni.kit.app import omni.kit.test import omni.ui as ui class TestWidget(omni.kit.test.AsyncTestCase): async def test_general(self): """Create a widget and make sure there are no errors""" window = ui.Window("Test") with window.frame: WelcomeWidget(buttons={}) await omni.kit.app.get_app().next_update_async()
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/tests/__init__.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .test_widget import TestWidget from .test_window import TestWindow
omniverse-code/kit/exts/omni.kit.window.welcome/omni/kit/window/welcome/tests/test_window.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["TestWindow"] from omni.kit.window.welcome.window import WelcomeWindow import omni.kit.app import omni.kit.test class TestWindow(omni.kit.test.AsyncTestCase): async def test_general(self): """Create a window and make sure there are no errors""" window = WelcomeWindow("Welcome Window Test", buttons={}) await omni.kit.app.get_app().next_update_async()
omniverse-code/kit/exts/omni.kit.widget.search_delegate/omni/kit/widget/search_delegate/delegate.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import abc class SearchDelegate: def __init__(self): self._search_dir = None @property def visible(self): return True # pragma: no cover @property def enabled(self): """Enable/disable Widget""" return True # pragma: no cover @property def search_dir(self): return self._search_dir # pragma: no cover @search_dir.setter def search_dir(self, search_dir: str): self._search_dir = search_dir # pragma: no cover @abc.abstractmethod def build_ui(self): pass # pragma: no cover @abc.abstractmethod def destroy(self): pass # pragma: no cover
omniverse-code/kit/exts/omni.kit.widget.search_delegate/omni/kit/widget/search_delegate/style.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb import omni.ui as ui from pathlib import Path try: THEME = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") except Exception: THEME = None finally: THEME = THEME or "NvidiaDark" CURRENT_PATH = Path(__file__).parent.absolute() ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath(f"icons/{THEME}") THUMBNAIL_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data").joinpath("thumbnails") def get_style(): if THEME == "NvidiaLight": BACKGROUND_COLOR = 0xFF535354 BACKGROUND_SELECTED_COLOR = 0xFF6E6E6E BACKGROUND_HOVERED_COLOR = 0xFF6E6E6E BACKGROUND_DISABLED_COLOR = 0xFF666666 TEXT_COLOR = 0xFF8D760D TEXT_HINT_COLOR = 0xFFD6D6D6 SEARCH_BORDER_COLOR = 0xFFC9974C SEARCH_HOVER_COLOR = 0xFFB8B8B8 SEARCH_CLOSE_COLOR = 0xFF858585 SEARCH_TEXT_BACKGROUND_COLOR = 0xFFD9D4BC else: BACKGROUND_COLOR = 0xFF23211F BACKGROUND_SELECTED_COLOR = 0xFF8A8777 BACKGROUND_HOVERED_COLOR = 0xFF3A3A3A BACKGROUND_DISABLED_COLOR = 0xFF666666 TEXT_COLOR = 0xFF9E9E9E TEXT_HINT_COLOR = 0xFF4A4A4A SEARCH_BORDER_COLOR = 0xFFC9974C SEARCH_HOVER_COLOR = 0xFF3A3A3A SEARCH_CLOSE_COLOR = 0xFF858585 SEARCH_TEXT_BACKGROUND_COLOR = 0xFFD9D4BC style = { "Button": { "background_color": BACKGROUND_COLOR, "selected_color": BACKGROUND_SELECTED_COLOR, "color": TEXT_COLOR, "margin": 0, "padding": 0 }, "Button:hovered": {"background_color": BACKGROUND_HOVERED_COLOR}, "Button.Label": {"color": TEXT_COLOR}, "Field": {"background_color": 0x0, "selected_color": BACKGROUND_SELECTED_COLOR, "color": TEXT_COLOR, "alignment": ui.Alignment.LEFT_CENTER}, "Label": {"background_color": 0x0, "color": TEXT_COLOR}, "Rectangle": {"background_color": 0x0}, "SearchField": { "background_color": 0, "border_radius": 0, "border_width": 0, "background_selected_color": BACKGROUND_COLOR, "margin": 0, "padding": 4, "alignment": ui.Alignment.LEFT_CENTER, }, "SearchField.Frame": { "background_color": BACKGROUND_COLOR, "border_radius": 0.0, "border_color": 0, "border_width": 2, }, "SearchField.Frame:selected": { "background_color": BACKGROUND_COLOR, "border_radius": 0, "border_color": SEARCH_BORDER_COLOR, "border_width": 2, }, "SearchField.Frame:disabled": { "background_color": BACKGROUND_DISABLED_COLOR, }, "SearchField.Hint": {"color": TEXT_HINT_COLOR}, "SearchField.Button": {"background_color": 0x0, "margin_width": 2, "padding": 4}, "SearchField.Button.Image": {"color": TEXT_HINT_COLOR}, "SearchField.Clear": {"background_color": 0x0, "padding": 4}, "SearchField.Clear:hovered": {"background_color": SEARCH_HOVER_COLOR}, "SearchField.Clear.Image": {"image_url": f"{ICON_PATH}/close.svg", "color": SEARCH_CLOSE_COLOR}, "SearchField.Word": {"background_color": SEARCH_TEXT_BACKGROUND_COLOR}, "SearchField.Word.Label": {"color": TEXT_COLOR}, "SearchField.Word.Button": {"background_color": 0, "padding": 2}, "SearchField.Word.Button.Image": {"image_url": f"{ICON_PATH}/close.svg", "color": TEXT_COLOR}, } return style
omniverse-code/kit/exts/omni.kit.widget.search_delegate/omni/kit/widget/search_delegate/__init__.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # """ A UI widget to search for files in a filesystem. """ from .widget import SearchField from .delegate import SearchDelegate from .model import SearchResultsModel, SearchResultsItem
omniverse-code/kit/exts/omni.kit.widget.search_delegate/omni/kit/widget/search_delegate/model.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import omni.ui as ui import omni.client from typing import Dict from datetime import datetime from omni.kit.widget.filebrowser import FileBrowserModel, FileBrowserItem, find_thumbnails_for_files_async from omni.kit.widget.filebrowser.model import FileBrowserItemFields from omni.kit.search_core import AbstractSearchModel, AbstractSearchItem class SearchResultsItem(FileBrowserItem): _thumbnail_dict: Dict = {} def __init__(self, path: str, fields: FileBrowserItemFields, is_folder: bool = False): super().__init__(path, fields, is_folder=is_folder) class _RedirectModel(ui.AbstractValueModel): def __init__(self, search_model, field): super().__init__() self._search_model = search_model self._field = field def get_value_as_string(self): return str(self._search_model[self._field]) def set_value(self, value): pass async def get_custom_thumbnails_for_folder_async(self) -> Dict: """ Returns the thumbnail dictionary for this (folder) item. Returns: Dict: With children url's as keys, and url's to thumbnail files as values. """ if not self.is_folder: return {} # Files in the root folder only file_urls = [] for _, item in self.children.items(): if item.is_folder or item.path in self._thumbnail_dict: # Skip if folder or thumbnail previously found pass else: file_urls.append(item.path) thumbnail_dict = await find_thumbnails_for_files_async(file_urls) for url, thumbnail_url in thumbnail_dict.items(): if url and thumbnail_url: self._thumbnail_dict[url] = thumbnail_url return self._thumbnail_dict class SearchResultsItemFactory: @staticmethod def create_item(search_item: AbstractSearchItem) -> SearchResultsItem: if not search_item: return None access = omni.client.AccessFlags.READ | omni.client.AccessFlags.WRITE fields = FileBrowserItemFields(search_item.name, search_item.date, search_item.size, access) item = SearchResultsItem(search_item.path, fields, is_folder=search_item.is_folder) item._models = ( SearchResultsItem._RedirectModel(search_item, "name"), SearchResultsItem._RedirectModel(search_item, "date"), SearchResultsItem._RedirectModel(search_item, "size"), ) return item @staticmethod def create_group_item(name: str, path: str) -> SearchResultsItem: access = omni.client.AccessFlags.READ | omni.client.AccessFlags.WRITE fields = FileBrowserItemFields(name, datetime.now(), 0, access) item = SearchResultsItem(path, fields, is_folder=True) return item class SearchResultsModel(FileBrowserModel): def __init__(self, search_model: AbstractSearchModel, **kwargs): super().__init__(**kwargs) self._root = SearchResultsItemFactory.create_group_item("Search Results", "search_results://") self._search_model = search_model # Circular dependency self._dirty_item_subscription = self._search_model.subscribe_item_changed(self.__on_item_changed) def destroy(self): # Remove circular dependency self._dirty_item_subscription = None if self._search_model: self._search_model.destroy() self._search_model = None def get_item_children(self, item: SearchResultsItem) -> [SearchResultsItem]: if self._search_model is None or item is not None: return [] # OM-92499: Skip populate for empty search model items if not self._root.populated and self._search_model.items: for search_item in self._search_model.items: self._root.add_child(SearchResultsItemFactory.create_item(search_item)) self._root.populated = True children = list(self._root.children.values()) if self._filter_fn: return list(filter(self._filter_fn, children)) else: return children def __on_item_changed(self, item): self._item_changed(item)
omniverse-code/kit/exts/omni.kit.widget.search_delegate/omni/kit/widget/search_delegate/widget.py
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni import ui from carb import log_warn from typing import Callable, List from omni.kit.search_core import SearchEngineRegistry from .delegate import SearchDelegate from .model import SearchResultsModel from .style import get_style, ICON_PATH class SearchWordButton: """ Represents a search word widget, combined with a label to show the word and a close button to remove it. Args: word (str): String of word. Keyword args: on_close_fn (callable): Function called when close button clicked. Function signure: void on_close_fn(widget: SearchWordButton) """ def __init__(self, word: str, on_close_fn: callable = None): self._container = ui.ZStack(width=0) with self._container: with ui.VStack(): ui.Spacer(height=5) ui.Rectangle(style_type_name_override="SearchField.Word") ui.Spacer(height=5) with ui.HStack(): ui.Spacer(width=3) ui.Label(word, width=0, style_type_name_override="SearchField.Word.Label") ui.Spacer(width=3) ui.Button( image_width=8, style_type_name_override="SearchField.Word.Button", clicked_fn=lambda: on_close_fn(self) if on_close_fn is not None else None, identifier="search_word_button", ) @property def visible(self) -> None: """Widget visibility""" return self._container.visible @visible.setter def visible(self, value: bool) -> None: self._container.visible = value class SearchField(SearchDelegate): """ A search field to input search words Args: callback (callable): Function called after search done. Function signature: void callback(model: SearchResultsModel) Keyword Args: width (Optional[ui.Length]): Widget widthl. Default None, means auto. height (Optional[ui.Length]): Widget height. Default ui.Pixel(26). Use None for auto. subscribe_edit_changed (bool): True to retreive on_search_fn called when input changed. Default False only retreive on_search_fn called when input ended. show_tokens (bool): Default True to show tokens if end edit. Do nothing if False. Properties: visible (bool): Widget visibility. enabled (bool): Enable/Disable widget. """ SEARCH_IMAGE_SIZE = 16 CLOSE_IMAGE_SIZE = 12 def __init__(self, callback: Callable, **kwargs): super().__init__(**kwargs) self._callback = callback self._container_args = {"style": get_style()} if kwargs.get("width") is not None: self._container_args["width"] = kwargs.get("width") self._container_args["height"] = kwargs.get("height", ui.Pixel(26)) self._subscribe_edit_changed = kwargs.get("subscribe_edit_changed", False) self._show_tokens = kwargs.get("show_tokens", True) self._search_field: ui.StringField = None self._search_engine = None self._search_engine_menu = None self._search_words: List[str] = [] self._in_searching = False self._search_label = None # OM-76011:subscribe to engine changed self.__search_engine_changed_sub = SearchEngineRegistry().subscribe_engines_changed(self._on_search_engines_changed) @property def visible(self): """ Widget visibility """ return self._container.visible @visible.setter def visible(self, value): self._container.visible = value @property def enabled(self): """ Enable/disable Widget """ return self._container.enabled @enabled.setter def enabled(self, value): self._container.enabled = value if value: self._search_label.text = "Search" else: self._search_label.text = "Search disabled. Please install a search extension." @property def search_dir(self): return self._search_dir @search_dir.setter def search_dir(self, search_dir: str): dir_changed = search_dir != self._search_dir self._search_dir = search_dir if self._in_searching and dir_changed: self.search(self._search_words) def build_ui(self): self._container = ui.ZStack(**self._container_args) with self._container: # background self._background = ui.Rectangle(style_type_name_override="SearchField.Frame") with ui.HStack(): with ui.VStack(width=0): # Search "magnifying glass" button search_button = ui.Button( image_url=f"{ICON_PATH}/search.svg", image_width=SearchField.SEARCH_IMAGE_SIZE, image_height=SearchField.SEARCH_IMAGE_SIZE, style_type_name_override="SearchField.Button", identifier="show_engine_menu", ) search_button.set_clicked_fn( lambda b=search_button: self._show_engine_menu( b.screen_position_x, b.screen_position_y + b.computed_height ) ) with ui.HStack(): with ui.ZStack(): with ui.HStack(): # Individual word widgets if self._show_tokens: self._words_container = ui.HStack() self._build_search_words() # String field to accept user input, here ui.Spacer for border of SearchField.Frame with ui.VStack(): ui.Spacer() with ui.HStack(height=0): self._search_field = ui.StringField( ui.SimpleStringModel(), mouse_double_clicked_fn=lambda x, y, btn, m: self._convert_words_to_string(), style_type_name_override="SearchField", ) ui.Spacer() self._hint_container = ui.HStack(spacing=4) with self._hint_container: # Hint label self._search_label = ui.Label("Search", width=275, style_type_name_override="SearchField.Hint") # Close icon with ui.VStack(width=20): ui.Spacer(height=2) self._clear_button = ui.Button( image_width=SearchField.CLOSE_IMAGE_SIZE, style_type_name_override="SearchField.Clear", clicked_fn=self._on_clear_clicked, ) ui.Spacer(height=2) ui.Spacer(width=2) self._clear_button.visible = False self._sub_begin_edit = self._search_field.model.subscribe_begin_edit_fn(self._on_begin_edit) self._sub_end_edit = self._search_field.model.subscribe_end_edit_fn(self._on_end_edit) if self._subscribe_edit_changed: self._sub_text_edit = self._search_field.model.subscribe_value_changed_fn(self._on_text_edit) else: self._sub_text_edit = None # check on init for if we have available search engines self._on_search_engines_changed() def destroy(self): self._callback = None self._search_field = None self._sub_begin_edit = None self._sub_end_edit = None self._sub_text_edit = None self._background = None self._hint_container = None self._clear_button = None self._search_label = None self._container = None self.__search_engine_changed_sub = None def _show_engine_menu(self, x, y): self._search_engine_menu = ui.Menu("Engines") search_names = SearchEngineRegistry().get_available_search_names(self._search_dir) if not search_names: return # TODO: We need to have predefined default search if self._search_engine is None or self._search_engine not in search_names: self._search_engine = search_names[0] def set_current_engine(engine_name): self._search_engine = engine_name with self._search_engine_menu: for name in search_names: ui.MenuItem( name, checkable=True, checked=self._search_engine == name, triggered_fn=lambda n=name: set_current_engine(n), ) self._search_engine_menu.show_at(x, y) def _get_search_words(self) -> List[str]: # Split the input string to words and filter invalid search_string = self._search_field.model.get_value_as_string() search_words = [word for word in search_string.split(" ") if word] if len(search_words) == 0: return None elif len(search_words) == 1 and search_words[0] == "": # If empty input, regard as clear return None else: return search_words def _on_begin_edit(self, model): self._set_in_searching(True) def _on_end_edit(self, model: ui.AbstractValueModel) -> None: search_words = self._get_search_words() if search_words is None: # Filter empty(hidden) word filter_words = [word for word in self._search_words if word] if len(filter_words) == 0: self._set_in_searching(False) else: if self._show_tokens: self._search_words.extend(search_words) self._build_search_words() self._search_field.model.set_value("") else: self._search_words = search_words self.search(self._search_words) def _on_text_edit(self, model: ui.AbstractValueModel) -> None: new_search_words = self._get_search_words() if new_search_words is not None: # Add current input to search words search_words = [] search_words.extend(self._search_words) search_words.extend(new_search_words) self._search_words = search_words self.search(self._search_words) def _convert_words_to_string(self) -> None: if self._show_tokens: # convert existing search words back to string filter_words = [word for word in self._search_words if word] seperator = " " self._search_words = [] self._build_search_words() original_string = seperator.join(filter_words) # Append current input input_string = self._search_field.model.get_value_as_string() if input_string: original_string = original_string + seperator + input_string self._search_field.model.set_value(original_string) def _on_clear_clicked(self) -> None: # Update UI self._set_in_searching(False) self._search_field.model.set_value("") self._search_words.clear() self._build_search_words() # Notification self.search(None) def _set_in_searching(self, in_searching: bool) -> None: self._in_searching = in_searching # Background outline self._background.selected = in_searching # Show/Hide hint frame (search icon and hint lable) self._hint_container.visible = not in_searching # Show/Hide close image self._clear_button.visible = in_searching def _build_search_words(self): if self._show_tokens: self._words_container.clear() if len(self._search_words) == 0: return with self._words_container: ui.Spacer(width=4) for index, word in enumerate(self._search_words): if word: SearchWordButton(word, on_close_fn=lambda widget, idx=index: self._hide_search_word(idx, widget)) def _hide_search_word(self, index: int, widget: SearchWordButton) -> None: # Here cannot remove the widget since this function is called by the widget # So just set invisible and change to empty word # It will be removed later if clear or edit end. widget.visible = False if index >= 0 and index < len(self._search_words): self._search_words[index] = "" self.search(self._search_words) def search(self, search_words: List[str]): """ Search using selected search engine. Args: search_words (List[str]): List of search terms. """ # TODO: We need to have predefined default search if self._search_engine is None: search_names = SearchEngineRegistry().get_search_names() self._search_engine = search_names[0] if search_names else None if self._search_engine: SearchModel = SearchEngineRegistry().get_search_model(self._search_engine) else: log_warn("No search engines registered! Please import a search extension.") return if not SearchModel: log_warn(f"Search engine '{self._search_engine}' not found.") return search_words = [word for word in search_words or [] if word] # Filter empty(hidden) word if len(search_words) > 0: search_results = SearchModel(search_text=" ".join(search_words), current_dir=self._search_dir) model = SearchResultsModel(search_results) else: model = None if self._callback: self._callback(model) def _on_search_engines_changed(self): search_names = SearchEngineRegistry().get_search_names() self.enabled = bool(search_names)
omniverse-code/kit/exts/omni.kit.widget.search_delegate/omni/kit/widget/search_delegate/tests/__init__.py
## Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## from .test_search_field import *
omniverse-code/kit/exts/omni.kit.widget.search_delegate/omni/kit/widget/search_delegate/tests/test_search_field.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. ## from unittest.mock import patch, MagicMock import omni.kit.ui_test as ui_test from omni.kit.ui_test.query import MenuRef from omni.ui.tests.test_base import OmniUiTest from omni.kit.search_core import AbstractSearchModel, AbstractSearchItem, SearchEngineRegistry from ..widget import SearchField from ..model import SearchResultsModel class MockSearchEngineRegistry(MagicMock): def get_search_names(): return "test_search" def get_search_model(_: str): return MockSearchModel class MockSearchItem(AbstractSearchItem): def __init__(self, name: str, path: str): super().__init__() self._name = name self._path = path @property def name(self): return self._name @property def path(self): return self._path class MockSearchModel(AbstractSearchModel): def __init__(self, search_text: str, current_dir: str): super().__init__() self._items = [] search_words = search_text.split(" ") # Return mock results from input search text for search_word in search_words: name = f"{search_word}.usd" self._items.append(MockSearchItem(name, f"{current_dir}/{name}")) @property def items(self): return self._items class TestSearchField(OmniUiTest): async def setUp(self): self._search_results = None async def tearDown(self): if self._search_results: self._search_results.destroy() self._search_results = None def _on_search(self, search_results: SearchResultsModel): self._search_results = search_results async def test_search_succeeds(self): """Testing search function successfully returns search results""" window = await self.create_test_window() with window.frame: under_test = SearchField(self._on_search) under_test.build_ui() search_words = ["foo", "bar"] with patch("omni.kit.widget.search_delegate.widget.SearchEngineRegistry", return_value=MockSearchEngineRegistry): under_test.search_dir = "C:/my_search_dir" under_test.search(search_words) # Assert the the search generated the expected results results = self._search_results.get_item_children(None) self.assertEqual( [f"{under_test.search_dir}/{w}.usd" for w in search_words], [result.path for result in results] ) for result in results: thumbnail = await result.get_custom_thumbnails_for_folder_async() self.assertEqual(thumbnail, {}) self.assertTrue(under_test.visible) under_test.destroy() async def test_setting_search_dir_triggers_search(self): """Testing that when done editing the search field, executes the search""" window = await self.create_test_window() mock_search = MagicMock() with window.frame: with patch.object(SearchField, "search") as mock_search: under_test = SearchField(None) under_test.build_ui() # Procedurally set search directory and search field search_words = ["foo", "bar"] under_test.search_dir = "C:/my_search_dir" under_test._on_begin_edit(None) under_test._search_field.model.set_value(" ".join(search_words)) under_test._on_end_edit(None) # Assert that the search is executed mock_search.assert_called_once_with(search_words) under_test.destroy() async def test_engine_menu(self): window = await self.create_test_window(block_devices=False) with window.frame: under_test = SearchField(None) under_test.build_ui() self._subscription = SearchEngineRegistry().register_search_model("TEST_SEARCH", MockSearchModel) window_ref = ui_test.WindowRef(window, "") button_ref = window_ref.find_all("**/Button[*].identifier=='show_engine_menu'")[0] await button_ref.click() self.assertTrue(under_test.enabled) self.assertIsNotNone(under_test._search_engine_menu) self.assertTrue(under_test._search_engine_menu.shown) menu_ref = MenuRef(under_test._search_engine_menu, "") menu_items = menu_ref.find_all("**/") self.assertEqual(len(menu_items), 1) self.assertEqual(menu_items[0].widget.text, "TEST_SEARCH") under_test.destroy() self._subscription = None async def test_edit_search(self): window = await self.create_test_window(block_devices=False) with window.frame: under_test = SearchField(self._on_search) under_test.build_ui() self._subscription = SearchEngineRegistry().register_search_model("TEST_SEARCH", MockSearchModel) search_words = ["foo", "bar"] under_test.search_dir = "C:/my_search_dir" under_test._on_begin_edit(None) under_test._search_field.model.set_value(" ".join(search_words)) under_test._on_end_edit(None) results = self._search_results.get_item_children(None) self.assertEqual(len(results), 2) # Remove first search window_ref = ui_test.WindowRef(window, "") close_ref = window_ref.find_all(f"**/Button[*].identifier=='search_word_button'")[0] await close_ref.click() results = self._search_results.get_item_children(None) self.assertEqual(len(results), 1) # Clear search await self.wait_n_updates() clear_ref = ui_test.WidgetRef(under_test._clear_button, "", window=window) await clear_ref.click() self.assertIsNone(self._search_results) self._subscription = None under_test.destroy()
omniverse-code/kit/exts/omni.kit.widget.search_delegate/docs/index.rst
omni.kit.widget.search_delegate ############################### Base module that provides a search widget for searching the file system .. toctree:: :maxdepth: 1 CHANGELOG .. automodule:: omni.kit.widget.search_delegate :platform: Windows-x86_64, Linux-x86_64 :members: :show-inheritance: :undoc-members: .. autoclass:: SearchField :members:
omniverse-code/kit/exts/omni.graph/PACKAGE-LICENSES/omni.graph-LICENSE.md
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited.
omniverse-code/kit/exts/omni.graph/config/extension.toml
[package] title = "OmniGraph Python" version = "1.50.2" category = "Graph" readme = "docs/README.md" description = "Contains the implementation of the OmniGraph core (Python Support)." preview_image = "data/preview.png" repository = "" keywords = ["kit", "omnigraph", "core"] # Main Python module, available as "import omni.graph.core" [[python.module]] name = "omni.graph.core" # Other extensions on which this one relies [dependencies] "omni.graph.core" = {} "omni.graph.tools" = {} "omni.kit.test" = {} "omni.kit.commands" = {} "omni.kit.usd_undo" = {} "omni.usd" = {} "omni.client" = {} "omni.kit.async_engine" = {} "omni.kit.stage_templates" = {} "omni.kit.pip_archive" = {} [python.pipapi] requirements = ["numpy"] # SWIPAT filed under: http://nvbugs/3193231 [[test]] stdoutFailPatterns.exclude = [ "*Ignore this error/warning*", ] pyCoverageFilter = ["omni.graph"] # Restrict coverage to omni.graph only [documentation] deps = [ ["kit-sdk", "_build/docs/kit-sdk/latest"], # WAR to include omni.graph.core refs until that workflow is moved ] pages = [ "docs/Overview.md", "docs/commands.rst", "docs/omni.graph.core.bindings.rst", "docs/autonode.rst", "docs/controller.rst", "docs/running_one_script.rst", "docs/runtimeInitialize.rst", "docs/testing.rst", "docs/CHANGELOG.md", ]
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
2
Edit dataset card