file_path
stringlengths
32
153
content
stringlengths
0
3.14M
omniverse-code/kit/include/omni/inspect/IInspectJsonSerializer.h
// 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. // #pragma once #include <omni/core/Omni.h> #include "IInspector.h" namespace omni { using namespace omni::core; } namespace omni { namespace inspect { OMNI_DECLARE_INTERFACE(IInspectJsonSerializer); //! Base class for object inspection requests. class IInspectJsonSerializer_abi : public omni::Inherits<omni::inspect::IInspector, OMNI_TYPE_ID("omni.inspect.IInspectJsonSerializer")> { protected: /** Set the output location of the serializer data to be a specified file path. * Doesn't actually do anything with it until data is being written though. * * @param[in] filePath Absolute location of the file to be written. */ virtual void setOutputToFilePath_abi(OMNI_ATTR("c_str, not_null") const char* filePath) noexcept = 0; /** Set the output location of the serializer data to be a local string. * No check is made to ensure that the string size doesn't get too large so when in doubt use a file path. */ virtual void setOutputToString_abi() noexcept = 0; /** Get the current location of the output data. * * @returns Path to the output file, or nullptr if output is going to a string */ virtual const char* getOutputLocation_abi() noexcept = 0; /** Get the current output as a string. If the output is being sent to a file path then read the file at that path * and return the contents of the file (with the usual caveats about file size). * * @returns String representation of the output so far */ virtual const char* asString_abi() noexcept = 0; /** Clear the contents of the serializer output, either emptying the file or clearing the string, depending on * where the current output is directed. */ virtual void clear_abi() noexcept = 0; /** Write out a JSON key for an object property. * * @param[in] key The string value for the key. This can be nullptr. * @param[in] keyLen The length of @ref key, excluding the null terminator. * @returns whether or not validation succeeded. */ virtual bool writeKeyWithLength_abi(OMNI_ATTR("c_str")const char* key, size_t keyLen) noexcept = 0; /** Write out a JSON key for an object property. * * @param[in] key The key name for this property. This may be nullptr. * @returns whether or not validation succeeded. */ virtual bool writeKey_abi(OMNI_ATTR("c_str")const char* key) noexcept = 0; /** Write out a JSON null value. * * @returns whether or not validation succeeded. */ virtual bool writeNull_abi() noexcept = 0; /** Write out a JSON boolean value. * * @param[in] value The boolean value. * @returns whether or not validation succeeded. */ virtual bool writeBool_abi(bool value) noexcept = 0; /** Write out a JSON integer value. * * @param[in] value The integer value. * @returns whether or not validation succeeded. */ virtual bool writeInt_abi(int32_t value) noexcept = 0; /** Write out a JSON unsigned integer value. * * @param[in] value The unsigned integer value. * @returns whether or not validation succeeded. */ virtual bool writeUInt_abi(uint32_t value) noexcept = 0; /** Write out a JSON 64-bit integer value. * * @param[in] value The 64-bit integer value. * @returns whether or not validation succeeded. * @note 64 bit integers will be written as a string of they are too long * to be stored as a number that's interoperable with javascript's * double precision floating point format. */ virtual bool writeInt64_abi(int64_t value) noexcept = 0; /** Write out a JSON 64-bit unsigned integer value. * * @param[in] value The 64-bit unsigned integer value. * @returns whether or not validation succeeded. * @note 64 bit integers will be written as a string of they are too long * to be stored as a number that's interoperable with javascript's * double precision floating point format. */ virtual bool writeUInt64_abi(uint64_t value) noexcept = 0; /** Write out a JSON pointer value as an unsigned int 64. * Not available through the Python bindings as Python has no concept of pointers. Use either writeUInt64() * or writeBase64Encoded() to write out binary data. * * @param[in] value The pointer value. * @returns whether or not validation succeeded. * @note Pointers will be written as a string of they are too long * to be stored as a number that's interoperable with javascript's * double precision floating point format. */ virtual OMNI_ATTR("no_py") bool writePointer_abi(OMNI_ATTR("in")const void* value) noexcept = 0; /** Write out a JSON double (aka number) value. * * @param[in] value The double value. * @returns whether or not validation succeeded. */ virtual bool writeDouble_abi(double value) noexcept = 0; /** Write out a JSON float (aka number) value. * * @param[in] value The double value. * @returns whether or not validation succeeded. */ virtual bool writeFloat_abi(float value) noexcept = 0; /** Write out a JSON string value. * * @param[in] value The string value. This can be nullptr if @p len is 0. * @param[in] len The length of @p value, excluding the null terminator. * @returns whether or not validation succeeded. */ virtual bool writeStringWithLength_abi(OMNI_ATTR("c_str")const char* value, size_t len) noexcept = 0; /** Write out a JSON string value. * * @param[in] value The string value. This can be nullptr. * @returns whether or not validation succeeded. */ virtual bool writeString_abi(OMNI_ATTR("c_str")const char* value) noexcept = 0; /** Write a binary blob into the output JSON as a base64 encoded string. * * @param[in] value The binary blob to write in. * @param[in] size The number of bytes of data in @p value. * @returns whether or not validation succeeded. * @remarks This will take the input bytes and encode it in base64, then store that as base64 data in a string. */ virtual OMNI_ATTR("no_py") bool writeBase64Encoded_abi(OMNI_ATTR("in")const void* value, size_t size) noexcept = 0; /** Begin a JSON array. * * @returns whether or not validation succeeded. * @note This may throw a std::bad_alloc or a std::length_error if the stack of scopes gets too large */ virtual bool openArray_abi() noexcept = 0; /** Finish writing a JSON array. * * @returns whether or not validation succeeded. */ virtual bool closeArray_abi() noexcept = 0; /** Begin a JSON object. * * @returns whether or not validation succeeded. */ virtual bool openObject_abi() noexcept = 0; /** Finish writing a JSON object. * * @returns whether or not validation succeeded. */ virtual bool closeObject_abi() noexcept = 0; /** Finishes writing the entire JSON dictionary. * * @returns whether or not validation succeeded. */ virtual bool finish_abi() noexcept = 0; }; } // namespace inspect } // namespace omni #include "IInspectJsonSerializer.gen.h"
omniverse-code/kit/include/omni/inspect/IInspectJsonSerializer.gen.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/Interface.h> #include <omni/core/OmniAttr.h> #include <omni/core/ResultError.h> #include <functional> #include <type_traits> #include <utility> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL //! Base class for object inspection requests. template <> class omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi> : public omni::inspect::IInspectJsonSerializer_abi { public: OMNI_PLUGIN_INTERFACE("omni::inspect::IInspectJsonSerializer") /** Set the output location of the serializer data to be a specified file path. * Doesn't actually do anything with it until data is being written though. * * @param[in] filePath Absolute location of the file to be written. */ void setOutputToFilePath(const char* filePath) noexcept; /** Set the output location of the serializer data to be a local string. * No check is made to ensure that the string size doesn't get too large so when in doubt use a file path. */ void setOutputToString() noexcept; /** Get the current location of the output data. * * @returns Path to the output file, or nullptr if output is going to a string */ const char* getOutputLocation() noexcept; /** Get the current output as a string. If the output is being sent to a file path then read the file at that path * and return the contents of the file (with the usual caveats about file size). * * @returns String representation of the output so far */ const char* asString() noexcept; /** Clear the contents of the serializer output, either emptying the file or clearing the string, depending on * where the current output is directed. */ void clear() noexcept; /** Write out a JSON key for an object property. * * @param[in] key The string value for the key. This can be nullptr. * @param[in] keyLen The length of @ref key, excluding the null terminator. * @returns whether or not validation succeeded. */ bool writeKeyWithLength(const char* key, size_t keyLen) noexcept; /** Write out a JSON key for an object property. * * @param[in] key The key name for this property. This may be nullptr. * @returns whether or not validation succeeded. */ bool writeKey(const char* key) noexcept; /** Write out a JSON null value. * * @returns whether or not validation succeeded. */ bool writeNull() noexcept; /** Write out a JSON boolean value. * * @param[in] value The boolean value. * @returns whether or not validation succeeded. */ bool writeBool(bool value) noexcept; /** Write out a JSON integer value. * * @param[in] value The integer value. * @returns whether or not validation succeeded. */ bool writeInt(int32_t value) noexcept; /** Write out a JSON unsigned integer value. * * @param[in] value The unsigned integer value. * @returns whether or not validation succeeded. */ bool writeUInt(uint32_t value) noexcept; /** Write out a JSON 64-bit integer value. * * @param[in] value The 64-bit integer value. * @returns whether or not validation succeeded. * @note 64 bit integers will be written as a string of they are too long * to be stored as a number that's interoperable with javascript's * double precision floating point format. */ bool writeInt64(int64_t value) noexcept; /** Write out a JSON 64-bit unsigned integer value. * * @param[in] value The 64-bit unsigned integer value. * @returns whether or not validation succeeded. * @note 64 bit integers will be written as a string of they are too long * to be stored as a number that's interoperable with javascript's * double precision floating point format. */ bool writeUInt64(uint64_t value) noexcept; /** Write out a JSON pointer value as an unsigned int 64. * Not available through the Python bindings as Python has no concept of pointers. Use either writeUInt64() * or writeBase64Encoded() to write out binary data. * * @param[in] value The pointer value. * @returns whether or not validation succeeded. * @note Pointers will be written as a string of they are too long * to be stored as a number that's interoperable with javascript's * double precision floating point format. */ bool writePointer(const void* value) noexcept; /** Write out a JSON double (aka number) value. * * @param[in] value The double value. * @returns whether or not validation succeeded. */ bool writeDouble(double value) noexcept; /** Write out a JSON float (aka number) value. * * @param[in] value The double value. * @returns whether or not validation succeeded. */ bool writeFloat(float value) noexcept; /** Write out a JSON string value. * * @param[in] value The string value. This can be nullptr if @p len is 0. * @param[in] len The length of @p value, excluding the null terminator. * @returns whether or not validation succeeded. */ bool writeStringWithLength(const char* value, size_t len) noexcept; /** Write out a JSON string value. * * @param[in] value The string value. This can be nullptr. * @returns whether or not validation succeeded. */ bool writeString(const char* value) noexcept; /** Write a binary blob into the output JSON as a base64 encoded string. * * @param[in] value The binary blob to write in. * @param[in] size The number of bytes of data in @p value. * @returns whether or not validation succeeded. * @remarks This will take the input bytes and encode it in base64, then store that as base64 data in a string. */ bool writeBase64Encoded(const void* value, size_t size) noexcept; /** Begin a JSON array. * * @returns whether or not validation succeeded. * @note This may throw a std::bad_alloc or a std::length_error if the stack of scopes gets too large */ bool openArray() noexcept; /** Finish writing a JSON array. * * @returns whether or not validation succeeded. */ bool closeArray() noexcept; /** Begin a JSON object. * * @returns whether or not validation succeeded. */ bool openObject() noexcept; /** Finish writing a JSON object. * * @returns whether or not validation succeeded. */ bool closeObject() noexcept; /** Finishes writing the entire JSON dictionary. * * @returns whether or not validation succeeded. */ bool finish() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline void omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::setOutputToFilePath(const char* filePath) noexcept { setOutputToFilePath_abi(filePath); } inline void omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::setOutputToString() noexcept { setOutputToString_abi(); } inline const char* omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::getOutputLocation() noexcept { return getOutputLocation_abi(); } inline const char* omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::asString() noexcept { return asString_abi(); } inline void omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::clear() noexcept { clear_abi(); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeKeyWithLength(const char* key, size_t keyLen) noexcept { return writeKeyWithLength_abi(key, keyLen); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeKey(const char* key) noexcept { return writeKey_abi(key); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeNull() noexcept { return writeNull_abi(); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeBool(bool value) noexcept { return writeBool_abi(value); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeInt(int32_t value) noexcept { return writeInt_abi(value); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeUInt(uint32_t value) noexcept { return writeUInt_abi(value); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeInt64(int64_t value) noexcept { return writeInt64_abi(value); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeUInt64(uint64_t value) noexcept { return writeUInt64_abi(value); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writePointer(const void* value) noexcept { return writePointer_abi(value); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeDouble(double value) noexcept { return writeDouble_abi(value); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeFloat(float value) noexcept { return writeFloat_abi(value); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeStringWithLength(const char* value, size_t len) noexcept { return writeStringWithLength_abi(value, len); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeString(const char* value) noexcept { return writeString_abi(value); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::writeBase64Encoded(const void* value, size_t size) noexcept { return writeBase64Encoded_abi(value, size); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::openArray() noexcept { return openArray_abi(); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::closeArray() noexcept { return closeArray_abi(); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::openObject() noexcept { return openObject_abi(); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::closeObject() noexcept { return closeObject_abi(); } inline bool omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>::finish() noexcept { return finish_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
omniverse-code/kit/include/omni/inspect/MemorySizes.h
// 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. // #pragma once // Collection of helpers to get memory size information #include <array> #include <iostream> #include <map> #include <set> #include <string> #include <unordered_map> #include <unordered_set> #include <type_traits> namespace omni { namespace inspect { // Uncomment this to enable debug output in this file // #define MEMORY_DEBUG constexpr bool memoryDebug{ #ifdef MEMORY_DEBUG true #else false #endif }; template <typename> struct sfinae_true : std::true_type {}; template <typename> struct sfinae_false : std::false_type {}; using SizeFunction = std::add_pointer<size_t()>::type; // // This detail implementation will allow switching on map types so that their size can be recursively calculated // namespace detail { // Until C++17... template <typename... Ts> using void_t = void; // Check for map-like objects template<typename Object, typename U = void> struct isMappishImpl : std::false_type {}; template<typename Object> struct isMappishImpl<Object, void_t<typename Object::key_type, typename Object::mapped_type, decltype(std::declval<Object&>()[std::declval<const typename Object::key_type&>()])>> : std::true_type {}; // Check for array types, whose size is entirely described by the object size template<typename Contained> struct isArrayImpl : std::false_type {}; template<typename Contained, size_t Size> struct isArrayImpl<std::array<Contained, Size>> : std::true_type {}; // Check for other iterable types template<typename Contained> struct isIterableImpl : std::false_type {}; template<typename Contained, typename Allocator> struct isIterableImpl<std::vector<Contained, Allocator>> : std::true_type {}; template<typename Contained, typename Allocator> struct isIterableImpl<std::set<Contained, Allocator>> : std::true_type {}; template<typename Contained, typename Allocator> struct isIterableImpl<std::unordered_set<Contained, Allocator>> : std::true_type {}; template <typename Object, typename Enable = void> struct hasCalculateMemorySizeFunctionImpl : std::false_type {}; template <typename Object> struct hasCalculateMemorySizeFunctionImpl<Object, void_t<decltype(std::declval<const Object&>().calculateMemorySize())>> : std::true_type {}; } template <typename Object> struct isMappish : detail::isMappishImpl<Object>::type {}; template <typename Object> struct isArray : detail::isArrayImpl<Object>::type {}; template <typename Object> struct isIterable : detail::isIterableImpl<Object>::type {}; template <typename Object> struct hasCalculateMemorySizeFunction : detail::hasCalculateMemorySizeFunctionImpl<Object>::type {}; // // Fallback to sizeof() template <typename Object, std::enable_if_t<! hasCalculateMemorySizeFunction<Object>{} && ! isMappish<Object>{} && ! isIterable<Object>{} && ! isArray<Object>{}, bool> = 0> size_t calculateMemorySize(const Object& object) { memoryDebug && (std::cout << "POD " << typeid(object).name() << " = " << sizeof(Object) << std::endl); return sizeof(Object); } // If the object has a calculateMemorySize() function use it // template <typename Object, typename std::enable_if_t<hasCalculateMemorySizeFunction<Object>{}, bool> = 0> size_t calculateMemorySize(const Object& object) { memoryDebug && (std::cout << "Has Method " << typeid(object).name() << " = " << object.calculateMemorySize() << std::endl); return object.calculateMemorySize(); } // // Third check, has to be at the end so that recursive calls work, handle map-like objects (map, unordered_map) template <typename Object, std::enable_if_t<isMappish<Object>{}, bool> = 0> size_t calculateMemorySize(const Object& object) { size_t size = sizeof(Object); for(auto it = object.begin(); it != object.end(); ++it) { size += calculateMemorySize(it->first); size += calculateMemorySize(it->second); } memoryDebug && (std::cout << "Mappish " << typeid(object).name() << " = " << size << std::endl); return size; } // // Fourth check, handle the array type, which doesn't have a separately allocated set of members template <typename Object, std::enable_if_t<isArray<Object>{}, bool> = 0> size_t calculateMemorySize(const Object& object) { memoryDebug && (std::cout << "Array " << typeid(object).name() << " = " << sizeof(Object) << std::endl); return sizeof(Object); } // // Fifth check, has to be at the end so that recursive calls work, handle the rest of the single object container-like objects // (set, unordered_set, vector) template <typename Object, std::enable_if_t<isIterable<Object>{} && ! isArray<Object>{}, bool> = 0> size_t calculateMemorySize(const Object& object) { size_t size = sizeof(Object); for(const auto& member : object) { size += calculateMemorySize(member); } memoryDebug && (std::cout << "Iterable " << typeid(object).name() << " = " << size << std::endl); return size; } // Helper macro to make it easy to add the memory used by class members to the IInspector #define INSPECT_MEMORY_CLASS_MEMBER(INSPECTOR, OBJECT, MEMBER_NAME) \ INSPECTOR.useMemory(&(OBJECT.MEMBER_NAME), omni::inspect::calculateMemorySize(OBJECT.MEMBER_NAME)); } // namespace inspect } // namespace omni
omniverse-code/kit/include/omni/inspect/PyIInspectMemoryUse.gen.h
// Copyright (c) 2021-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. // // --------- Warning: This is a build system generated file. ---------- // #pragma once #include <omni/core/ITypeFactory.h> #include <omni/python/PyBind.h> #include <omni/python/PyString.h> #include <omni/python/PyVec.h> #include <sstream> auto bindIInspectMemoryUse(py::module& m) { // hack around pybind11 issues with C++17 // - https://github.com/pybind/pybind11/issues/2234 // - https://github.com/pybind/pybind11/issues/2666 // - https://github.com/pybind/pybind11/issues/2856 py::class_<omni::core::Generated<omni::inspect::IInspectMemoryUse_abi>, omni::python::detail::PyObjectPtr<omni::core::Generated<omni::inspect::IInspectMemoryUse_abi>>, omni::core::Api<omni::inspect::IInspector_abi>> clsParent(m, "_IInspectMemoryUse"); py::class_<omni::inspect::IInspectMemoryUse, omni::core::Generated<omni::inspect::IInspectMemoryUse_abi>, omni::python::detail::PyObjectPtr<omni::inspect::IInspectMemoryUse>, omni::core::Api<omni::inspect::IInspector_abi>> cls(m, "IInspectMemoryUse", R"OMNI_BIND_RAW_(Base class for object inspection requests.)OMNI_BIND_RAW_"); cls.def(py::init( [](const omni::core::ObjectPtr<omni::core::IObject>& obj) { auto tmp = omni::core::cast<omni::inspect::IInspectMemoryUse>(obj.get()); if (!tmp) { throw std::runtime_error("invalid type conversion"); } return tmp; })); cls.def(py::init( []() { auto tmp = omni::core::createType<omni::inspect::IInspectMemoryUse>(); if (!tmp) { throw std::runtime_error("unable to create omni::inspect::IInspectMemoryUse instantiation"); } return tmp; })); cls.def("use_memory", [](omni::inspect::IInspectMemoryUse* self, const void* ptr, size_t bytesUsed) { auto return_value = self->useMemory(ptr, bytesUsed); return return_value; }, R"OMNI_BIND_RAW_(Add a block of used memory Returns false if the memory was not recorded (e.g. because it was already recorded) @param[in] ptr Pointer to the memory location being logged as in-use @param[in] bytesUsed Number of bytes in use at that location)OMNI_BIND_RAW_", py::arg("ptr"), py::arg("bytes_used")); cls.def("reset", &omni::inspect::IInspectMemoryUse::reset, R"OMNI_BIND_RAW_(Reset the memory usage data to a zero state)OMNI_BIND_RAW_"); cls.def( "total_used", &omni::inspect::IInspectMemoryUse::totalUsed, R"OMNI_BIND_RAW_(@returns the total number of bytes of memory used since creation or the last call to reset().)OMNI_BIND_RAW_"); return omni::python::PyBind<omni::inspect::IInspectMemoryUse>::bind(cls); }
omniverse-code/kit/include/omni/inspect/IInspectMemoryUse.gen.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/Interface.h> #include <omni/core/OmniAttr.h> #include <omni/core/ResultError.h> #include <functional> #include <type_traits> #include <utility> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL //! Base class for object inspection requests. template <> class omni::core::Generated<omni::inspect::IInspectMemoryUse_abi> : public omni::inspect::IInspectMemoryUse_abi { public: OMNI_PLUGIN_INTERFACE("omni::inspect::IInspectMemoryUse") /** Add a block of used memory * Returns false if the memory was not recorded (e.g. because it was already recorded) * * @param[in] ptr Pointer to the memory location being logged as in-use * @param[in] bytesUsed Number of bytes in use at that location */ bool useMemory(const void* ptr, size_t bytesUsed) noexcept; /** Reset the memory usage data to a zero state */ void reset() noexcept; /** @returns the total number of bytes of memory used since creation or the last call to reset(). */ size_t totalUsed() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline bool omni::core::Generated<omni::inspect::IInspectMemoryUse_abi>::useMemory(const void* ptr, size_t bytesUsed) noexcept { return useMemory_abi(ptr, bytesUsed); } inline void omni::core::Generated<omni::inspect::IInspectMemoryUse_abi>::reset() noexcept { reset_abi(); } inline size_t omni::core::Generated<omni::inspect::IInspectMemoryUse_abi>::totalUsed() noexcept { return totalUsed_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
omniverse-code/kit/include/omni/inspect/PyIInspectJsonSerializer.gen.h
// Copyright (c) 2021-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. // // --------- Warning: This is a build system generated file. ---------- // #pragma once #include <omni/core/ITypeFactory.h> #include <omni/python/PyBind.h> #include <omni/python/PyString.h> #include <omni/python/PyVec.h> #include <sstream> auto bindIInspectJsonSerializer(py::module& m) { // hack around pybind11 issues with C++17 // - https://github.com/pybind/pybind11/issues/2234 // - https://github.com/pybind/pybind11/issues/2666 // - https://github.com/pybind/pybind11/issues/2856 py::class_<omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>, omni::python::detail::PyObjectPtr<omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>>, omni::core::Api<omni::inspect::IInspector_abi>> clsParent(m, "_IInspectJsonSerializer"); py::class_<omni::inspect::IInspectJsonSerializer, omni::core::Generated<omni::inspect::IInspectJsonSerializer_abi>, omni::python::detail::PyObjectPtr<omni::inspect::IInspectJsonSerializer>, omni::core::Api<omni::inspect::IInspector_abi>> cls(m, "IInspectJsonSerializer", R"OMNI_BIND_RAW_(Base class for object inspection requests.)OMNI_BIND_RAW_"); cls.def(py::init( [](const omni::core::ObjectPtr<omni::core::IObject>& obj) { auto tmp = omni::core::cast<omni::inspect::IInspectJsonSerializer>(obj.get()); if (!tmp) { throw std::runtime_error("invalid type conversion"); } return tmp; })); cls.def(py::init( []() { auto tmp = omni::core::createType<omni::inspect::IInspectJsonSerializer>(); if (!tmp) { throw std::runtime_error("unable to create omni::inspect::IInspectJsonSerializer instantiation"); } return tmp; })); cls.def_property("output_to_file_path", nullptr, [](omni::inspect::IInspectJsonSerializer* self, const char* filePath) { self->setOutputToFilePath(filePath); }); cls.def_property_readonly("output_location", &omni::inspect::IInspectJsonSerializer::getOutputLocation); cls.def("set_output_to_string", &omni::inspect::IInspectJsonSerializer::setOutputToString, R"OMNI_BIND_RAW_(Set the output location of the serializer data to be a local string. No check is made to ensure that the string size doesn't get too large so when in doubt use a file path.)OMNI_BIND_RAW_"); cls.def("as_string", &omni::inspect::IInspectJsonSerializer::asString, R"OMNI_BIND_RAW_(Get the current output as a string. If the output is being sent to a file path then read the file at that path and return the contents of the file (with the usual caveats about file size). @returns String representation of the output so far)OMNI_BIND_RAW_"); cls.def("clear", &omni::inspect::IInspectJsonSerializer::clear, R"OMNI_BIND_RAW_(Clear the contents of the serializer output, either emptying the file or clearing the string, depending on where the current output is directed.)OMNI_BIND_RAW_"); cls.def("write_key_with_length", [](omni::inspect::IInspectJsonSerializer* self, const char* key, size_t keyLen) { auto return_value = self->writeKeyWithLength(key, keyLen); return return_value; }, R"OMNI_BIND_RAW_(Write out a JSON key for an object property. @param[in] key The string value for the key. This can be nullptr. @param[in] keyLen The length of @ref key, excluding the null terminator. @returns whether or not validation succeeded.)OMNI_BIND_RAW_", py::arg("key"), py::arg("key_len")); cls.def("write_key", [](omni::inspect::IInspectJsonSerializer* self, const char* key) { auto return_value = self->writeKey(key); return return_value; }, R"OMNI_BIND_RAW_(Write out a JSON key for an object property. @param[in] key The key name for this property. This may be nullptr. @returns whether or not validation succeeded.)OMNI_BIND_RAW_", py::arg("key")); cls.def("write_null", &omni::inspect::IInspectJsonSerializer::writeNull, R"OMNI_BIND_RAW_(Write out a JSON null value. @returns whether or not validation succeeded.)OMNI_BIND_RAW_"); cls.def("write_bool", &omni::inspect::IInspectJsonSerializer::writeBool, R"OMNI_BIND_RAW_(Write out a JSON boolean value. @param[in] value The boolean value. @returns whether or not validation succeeded.)OMNI_BIND_RAW_", py::arg("value")); cls.def("write_int", &omni::inspect::IInspectJsonSerializer::writeInt, R"OMNI_BIND_RAW_(Write out a JSON integer value. @param[in] value The integer value. @returns whether or not validation succeeded.)OMNI_BIND_RAW_", py::arg("value")); cls.def("write_u_int", &omni::inspect::IInspectJsonSerializer::writeUInt, R"OMNI_BIND_RAW_(Write out a JSON unsigned integer value. @param[in] value The unsigned integer value. @returns whether or not validation succeeded.)OMNI_BIND_RAW_", py::arg("value")); cls.def("write_int64", &omni::inspect::IInspectJsonSerializer::writeInt64, R"OMNI_BIND_RAW_(Write out a JSON 64-bit integer value. @param[in] value The 64-bit integer value. @returns whether or not validation succeeded. @note 64 bit integers will be written as a string of they are too long to be stored as a number that's interoperable with javascript's double precision floating point format.)OMNI_BIND_RAW_", py::arg("value")); cls.def("write_u_int64", &omni::inspect::IInspectJsonSerializer::writeUInt64, R"OMNI_BIND_RAW_(Write out a JSON 64-bit unsigned integer value. @param[in] value The 64-bit unsigned integer value. @returns whether or not validation succeeded. @note 64 bit integers will be written as a string of they are too long to be stored as a number that's interoperable with javascript's double precision floating point format.)OMNI_BIND_RAW_", py::arg("value")); cls.def("write_double", &omni::inspect::IInspectJsonSerializer::writeDouble, R"OMNI_BIND_RAW_(Write out a JSON double (aka number) value. @param[in] value The double value. @returns whether or not validation succeeded.)OMNI_BIND_RAW_", py::arg("value")); cls.def("write_float", &omni::inspect::IInspectJsonSerializer::writeFloat, R"OMNI_BIND_RAW_(Write out a JSON float (aka number) value. @param[in] value The double value. @returns whether or not validation succeeded.)OMNI_BIND_RAW_", py::arg("value")); cls.def("write_string_with_length", [](omni::inspect::IInspectJsonSerializer* self, const char* value, size_t len) { auto return_value = self->writeStringWithLength(value, len); return return_value; }, R"OMNI_BIND_RAW_(Write out a JSON string value. @param[in] value The string value. This can be nullptr if @p len is 0. @param[in] len The length of @p value, excluding the null terminator. @returns whether or not validation succeeded.)OMNI_BIND_RAW_", py::arg("value"), py::arg("len")); cls.def("write_string", [](omni::inspect::IInspectJsonSerializer* self, const char* value) { auto return_value = self->writeString(value); return return_value; }, R"OMNI_BIND_RAW_(Write out a JSON string value. @param[in] value The string value. This can be nullptr. @returns whether or not validation succeeded.)OMNI_BIND_RAW_", py::arg("value")); cls.def("open_array", &omni::inspect::IInspectJsonSerializer::openArray, R"OMNI_BIND_RAW_(Begin a JSON array. @returns whether or not validation succeeded. @note This may throw a std::bad_alloc or a std::length_error if the stack of scopes gets too large)OMNI_BIND_RAW_"); cls.def("close_array", &omni::inspect::IInspectJsonSerializer::closeArray, R"OMNI_BIND_RAW_(Finish writing a JSON array. @returns whether or not validation succeeded.)OMNI_BIND_RAW_"); cls.def("open_object", &omni::inspect::IInspectJsonSerializer::openObject, R"OMNI_BIND_RAW_(Begin a JSON object. @returns whether or not validation succeeded.)OMNI_BIND_RAW_"); cls.def("close_object", &omni::inspect::IInspectJsonSerializer::closeObject, R"OMNI_BIND_RAW_(Finish writing a JSON object. @returns whether or not validation succeeded.)OMNI_BIND_RAW_"); cls.def("finish", &omni::inspect::IInspectJsonSerializer::finish, R"OMNI_BIND_RAW_(Finishes writing the entire JSON dictionary. @returns whether or not validation succeeded.)OMNI_BIND_RAW_"); return omni::python::PyBind<omni::inspect::IInspectJsonSerializer>::bind(cls); }
omniverse-code/kit/include/omni/inspect/IInspectSerializer.gen.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/Interface.h> #include <omni/core/OmniAttr.h> #include <omni/core/ResultError.h> #include <functional> #include <type_traits> #include <utility> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL //! Base class for object serialization requests. template <> class omni::core::Generated<omni::inspect::IInspectSerializer_abi> : public omni::inspect::IInspectSerializer_abi { public: OMNI_PLUGIN_INTERFACE("omni::inspect::IInspectSerializer") /** Write a fixed string to the serializer output location * * @param[in] toWrite String to be written to the serializer */ void writeString(const char* toWrite) noexcept; /** Write a printf-style formatted string to the serializer output location * * @param[in] fmt Formatting string in the printf() style * @param[in] args Variable list of arguments to the formatting string */ void write(const char* fmt, ...) noexcept; /** Set the output location of the serializer data to be a specified file path. * Doesn't actually do anything with it until data is being written though. * Recognizes the special file paths "cout", "stdout", "cerr", and "stderr" as the standard output streams. * * @param[in] filePath New location of the output file */ void setOutputToFilePath(const char* filePath) noexcept; /** Set the output location of the serializer data to be a local string. * No check is made to ensure that the string size doesn't get too large so when in doubt use a file path. */ void setOutputToString() noexcept; /** Get the current location of the output data. * * @returns Current file path where the output is going. nullptr means the output is going to a string. */ const char* getOutputLocation() noexcept; /** Get the current output as a string. * * @returns The output that has been sent to the serializer. If the output is being sent to a file path then read * the file at that path and return the contents of the file. If the output is being sent to stdout or stderr * then nothing is returned as that output is unavailable after flushing. */ const char* asString() noexcept; /** Clear the contents of the serializer output, either emptying the file or clearing the string, depending on * where the current output is directed. */ void clear() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline void omni::core::Generated<omni::inspect::IInspectSerializer_abi>::writeString(const char* toWrite) noexcept { writeString_abi(toWrite); } inline void omni::core::Generated<omni::inspect::IInspectSerializer_abi>::write(const char* fmt, ...) noexcept { va_list arg_list_; va_start(arg_list_, fmt); write_abi(fmt, arg_list_); va_end(arg_list_); } inline void omni::core::Generated<omni::inspect::IInspectSerializer_abi>::setOutputToFilePath(const char* filePath) noexcept { setOutputToFilePath_abi(filePath); } inline void omni::core::Generated<omni::inspect::IInspectSerializer_abi>::setOutputToString() noexcept { setOutputToString_abi(); } inline const char* omni::core::Generated<omni::inspect::IInspectSerializer_abi>::getOutputLocation() noexcept { return getOutputLocation_abi(); } inline const char* omni::core::Generated<omni::inspect::IInspectSerializer_abi>::asString() noexcept { return asString_abi(); } inline void omni::core::Generated<omni::inspect::IInspectSerializer_abi>::clear() noexcept { clear_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
omniverse-code/kit/include/omni/inspect/PyIInspectSerializer.gen.h
// Copyright (c) 2021-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. // // --------- Warning: This is a build system generated file. ---------- // #pragma once #include <omni/core/ITypeFactory.h> #include <omni/python/PyBind.h> #include <omni/python/PyString.h> #include <omni/python/PyVec.h> #include <sstream> auto bindIInspectSerializer(py::module& m) { // hack around pybind11 issues with C++17 // - https://github.com/pybind/pybind11/issues/2234 // - https://github.com/pybind/pybind11/issues/2666 // - https://github.com/pybind/pybind11/issues/2856 py::class_<omni::core::Generated<omni::inspect::IInspectSerializer_abi>, omni::python::detail::PyObjectPtr<omni::core::Generated<omni::inspect::IInspectSerializer_abi>>, omni::core::Api<omni::inspect::IInspector_abi>> clsParent(m, "_IInspectSerializer"); py::class_<omni::inspect::IInspectSerializer, omni::core::Generated<omni::inspect::IInspectSerializer_abi>, omni::python::detail::PyObjectPtr<omni::inspect::IInspectSerializer>, omni::core::Api<omni::inspect::IInspector_abi>> cls(m, "IInspectSerializer", R"OMNI_BIND_RAW_(Base class for object serialization requests.)OMNI_BIND_RAW_"); cls.def(py::init( [](const omni::core::ObjectPtr<omni::core::IObject>& obj) { auto tmp = omni::core::cast<omni::inspect::IInspectSerializer>(obj.get()); if (!tmp) { throw std::runtime_error("invalid type conversion"); } return tmp; })); cls.def(py::init( []() { auto tmp = omni::core::createType<omni::inspect::IInspectSerializer>(); if (!tmp) { throw std::runtime_error("unable to create omni::inspect::IInspectSerializer instantiation"); } return tmp; })); cls.def_property("output_to_file_path", nullptr, [](omni::inspect::IInspectSerializer* self, const char* filePath) { self->setOutputToFilePath(filePath); }); cls.def_property_readonly("output_location", &omni::inspect::IInspectSerializer::getOutputLocation); cls.def("write_string", [](omni::inspect::IInspectSerializer* self, const char* toWrite) { self->writeString(toWrite); }, R"OMNI_BIND_RAW_(Write a fixed string to the serializer output location @param[in] toWrite String to be written to the serializer)OMNI_BIND_RAW_", py::arg("to_write")); cls.def("set_output_to_string", &omni::inspect::IInspectSerializer::setOutputToString, R"OMNI_BIND_RAW_(Set the output location of the serializer data to be a local string. No check is made to ensure that the string size doesn't get too large so when in doubt use a file path.)OMNI_BIND_RAW_"); cls.def("as_string", &omni::inspect::IInspectSerializer::asString, R"OMNI_BIND_RAW_(Get the current output as a string. @returns The output that has been sent to the serializer. If the output is being sent to a file path then read the file at that path and return the contents of the file. If the output is being sent to stdout or stderr then nothing is returned as that output is unavailable after flushing.)OMNI_BIND_RAW_"); cls.def("clear", &omni::inspect::IInspectSerializer::clear, R"OMNI_BIND_RAW_(Clear the contents of the serializer output, either emptying the file or clearing the string, depending on where the current output is directed.)OMNI_BIND_RAW_"); return omni::python::PyBind<omni::inspect::IInspectSerializer>::bind(cls); }
omniverse-code/kit/include/omni/ext/IExt.h
// Copyright (c) 2019-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. // //! @file //! @brief omni.ext interface definition file #pragma once #include "../../carb/Interface.h" namespace omni { //! Namespace for Omniverse Extension system namespace ext { /** * Extension plugin interface. * * Interface for writing simple C++ plugins used by extension system. * When extension loads a plugin with this interface it gets automatically acquired and \ref IExt::onStartup() is * called. \ref IExt::onShutdown() is called when extension gets shutdown. * * @see ExtensionManager */ class IExt { public: CARB_PLUGIN_INTERFACE("omni::ext::IExt", 0, 1); /** * Called by the Extension Manager when the extension is being started. * * @param extId Unique extension id is passed in. It can be used to query more extension info from extension * manager. */ virtual void onStartup(const char* extId) = 0; /** * Called by the Extension Manager when the extension is shutdown. */ virtual void onShutdown() = 0; }; } // namespace ext } // namespace omni
omniverse-code/kit/include/omni/ext/IExtensionHooks.h
// Copyright (c) 2020-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. // #pragma once #include <omni/core/IObject.h> #include <omni/ext/IExtensionData.h> namespace omni { namespace ext { //! Declaration of IExtensionHooks OMNI_DECLARE_INTERFACE(IExtensionHooks); //! Hooks that can be defined by plugins to better understand how the plugin is being used by the extension system. class IExtensionHooks_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.ext.IExtensionHooks")> { protected: //! Called when an extension loads the plugin. //! //! If multiple extensions load the plugin, this method will be called multiple times. //! @param ext The \ref IExtensionData_abi of the starting extension virtual void onStartup_abi(OMNI_ATTR("not_null") IExtensionData* ext) noexcept = 0; //! Called when an extension that uses this plugin is unloaded. //! //! If multiple extension load the plugin, this method will be called multiple times. //! @param ext The \ref IExtensionData_abi of the extension that is shutting down virtual void onShutdown_abi(IExtensionData* ext) noexcept = 0; }; } // namespace ext } // namespace omni #include "IExtensionHooks.gen.h"
omniverse-code/kit/include/omni/ext/ExtensionsUtils.h
// Copyright (c) 2019-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. // //! @file //! @brief Utilities for omni.ext #pragma once #include "IExtensions.h" #include "../../carb/ObjectUtils.h" #include "../../carb/dictionary/DictionaryUtils.h" #include "../../carb/settings/ISettings.h" #include "../../carb/settings/SettingsUtils.h" #include <functional> #include <string> #include <utility> #include <vector> namespace omni { namespace ext { /** * Helper function to look up the path from an extension dictionary. * @warning Undefined behavior results if `extId` is not a valid Extension ID. Check for the existence of the extension * before calling this function. * @param manager A pointer to the \ref ExtensionManager * @param extId The Extension ID as required by \ref ExtensionManager::getExtensionDict() * @returns a `std::string` representing the `path` member of the extension info dictionary * @see ExtensionManager, ExtensionManager::getExtensionDict() */ inline std::string getExtensionPath(ExtensionManager* manager, const char* extId) { auto dict = carb::dictionary::getCachedDictionaryInterface(); carb::dictionary::Item* infoDict = manager->getExtensionDict(extId); return infoDict ? dict->get<const char*>(infoDict, "path") : ""; } /** * Helper function to find the Extension ID of a given Extension. * @param manager A pointer to the \ref ExtensionManager * @param extFullName The full extension name as required by \ref ExtensionManager::fetchExtensionVersions() * @returns The Extension ID of the enabled extension, or "" if the extension was not found or not enabled */ inline const char* getEnabledExtensionId(ExtensionManager* manager, const char* extFullName) { size_t count; ExtensionInfo* extensions; manager->fetchExtensionVersions(extFullName, &extensions, &count); for (size_t i = 0; i < count; i++) { if (extensions[i].enabled) return extensions[i].id; } return nullptr; } /** * Helper function to check if an extension is enabled by name. * @param manager A pointer to the \ref ExtensionManager * @param extFullName The full extension name as required by \ref ExtensionManager::fetchExtensionVersions() * @returns `true` if the extension is enabled (that is if \ref getEnabledExtensionId() would return a non-`nullptr` * value); `false` if the extension is not found or not enabled */ inline bool isExtensionEnabled(ExtensionManager* manager, const char* extFullName) { return getEnabledExtensionId(manager, extFullName) != nullptr; } /** * Helper function to fetch all extension packages and load them into the memory. * * @warning This function is extemely slow, can take seconds, depending on the size of registry. * * After calling this function extension manager will have all registry extensions loaded into memory. Functions like * \ref ExtensionManager::getRegistryExtensions() will be returning a full list of all extensions after. * * @param manager A pointer to the \ref ExtensionManager * @returns A vector of of \ref ExtensionInfo objects */ inline std::vector<ExtensionInfo> fetchAllExtensionPackages(ExtensionManager* manager) { std::vector<ExtensionInfo> packages; ExtensionSummary* summaries; size_t summaryCount; manager->fetchExtensionSummaries(&summaries, &summaryCount); for (size_t i = 0; i < summaryCount; i++) { const ExtensionSummary& summary = summaries[i]; ExtensionInfo* extensions; size_t extensionCount; manager->fetchExtensionPackages(summary.fullname, &extensions, &extensionCount); packages.insert(packages.end(), extensions, extensions + extensionCount); } return packages; } /** * A wrapper object to allow passing an invocable type (i.e. lambda) as an extension hook. */ class ExtensionStateChangeHookLambda : public IExtensionStateChangeHook { public: /** * Constructor. * @note Typically this is not constructed directly. Instead use \ref createExtensionStateChangeHook(). * @param fn a `std::function` that will be called on extension state change. May be empty. */ ExtensionStateChangeHookLambda(const std::function<void(const char*, ExtensionStateChangeType)>& fn) : m_fn(fn) { } /** * State change handler function. * @note Typically this is not called directly; it is called by \ref ExtensionManager. * @param extId The Extension ID that is changing * @param type The \ref ExtensionStateChangeType describing the state change */ void onStateChange(const char* extId, ExtensionStateChangeType type) override { if (m_fn) m_fn(extId, type); } private: std::function<void(const char*, ExtensionStateChangeType)> m_fn; CARB_IOBJECT_IMPL }; /** * Wrapper to pass an invocable object to Extension Manager Hooks. * @param hooks The \ref IExtensionManagerHooks instance * @param onStateChange The `std::function` that captures the invocable type (may be empty) * @param type The type to monitor for (see \ref IExtensionManagerHooks::createExtensionStateChangeHook()) * @param extFullName See \ref IExtensionManagerHooks::createExtensionStateChangeHook() * @param extDictPath See \ref IExtensionManagerHooks::createExtensionStateChangeHook() * @param order See \ref IExtensionManagerHooks::createExtensionStateChangeHook() * @param hookName See \ref IExtensionManagerHooks::createExtensionStateChangeHook() * @returns see \ref IExtensionManagerHooks::createExtensionStateChangeHook() */ inline IHookHolderPtr createExtensionStateChangeHook( IExtensionManagerHooks* hooks, const std::function<void(const char* extId, ExtensionStateChangeType type)>& onStateChange, ExtensionStateChangeType type, const char* extFullName = "", const char* extDictPath = "", Order order = kDefaultOrder, const char* hookName = nullptr) { return hooks->createExtensionStateChangeHook( carb::stealObject(new ExtensionStateChangeHookLambda(onStateChange)).get(), type, extFullName, extDictPath, order, hookName); } /** * A wrapper function to subscribe to extension enable (and optionally disable) events. * @param manager The \ref ExtensionManager instance * @param onEnable The `std::function` that captures the invocable to call on enable (may be empty). If the extension is * already enabled, this is invoked immediately * @param onDisable The `std::function` that captures the invocable to call on disable (may be empty) * @param extFullName See \ref IExtensionManagerHooks::createExtensionStateChangeHook() * @param hookName See \ref IExtensionManagerHooks::createExtensionStateChangeHook() * @returns a `std::pair` of \ref IHookHolderPtr objects (`first` represents the enable holder and `second` represents * the disable holder) */ inline std::pair<IHookHolderPtr, IHookHolderPtr> subscribeToExtensionEnable( ExtensionManager* manager, const std::function<void(const char* extId)>& onEnable, const std::function<void(const char* extId)>& onDisable = nullptr, const char* extFullName = "", const char* hookName = nullptr) { // Already enabled? if (extFullName && extFullName[0] != '\0') { const char* enabledExtId = getEnabledExtensionId(manager, extFullName); if (enabledExtId) onEnable(enabledExtId); } // Subscribe for enabling: IHookHolderPtr holder0 = createExtensionStateChangeHook( manager->getHooks(), [onEnable = onEnable](const char* extId, ExtensionStateChangeType) { onEnable(extId); }, ExtensionStateChangeType::eAfterExtensionEnable, extFullName, "", kDefaultOrder, hookName); // Optionally subscribe for disabling IHookHolderPtr holder1; if (onDisable) holder1 = createExtensionStateChangeHook( manager->getHooks(), [onDisable = onDisable](const char* extId, ExtensionStateChangeType) { onDisable(extId); }, ExtensionStateChangeType::eBeforeExtensionShutdown, extFullName, "", kDefaultOrder, hookName); return std::make_pair(holder0, holder1); } //! The result of parsing an extension URL. //! //! Given "omniverse://path/to/object", `scheme` would contain "omniverse" and `path` would contain "path/to/object" struct ExtPathUrl { std::string scheme; //!< The extension URL scheme std::string path; //!< The extension URL path }; /** * Simple helper function to parse a given URL into a scheme and a path. * @note If a path is given such as "f:/path/to/ext", this will return as \ref ExtPathUrl::scheme empty and everything * in \ref ExtPathUrl::path. * @param url The extension URL to parse * @returns a \ref ExtPathUrl containing the separate parts */ inline ExtPathUrl parseExtUrl(const std::string& url) { const std::string kSchemeDelimiter = ":"; auto pos = url.find(kSchemeDelimiter); if (pos == std::string::npos || pos == 1) return { "", url }; ExtPathUrl res = {}; res.scheme = url.substr(0, pos); res.path = url.substr(pos + kSchemeDelimiter.size() + 1); res.path = res.path.erase(0, res.path.find_first_not_of("/")); return res; } } // namespace ext } // namespace omni
omniverse-code/kit/include/omni/ext/IExtensions.h
// Copyright (c) 2020-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. // //! @file //! @brief omni.ext Extension System interfaces #pragma once #include "../../carb/Framework.h" #include "../../carb/IObject.h" #include "../../carb/Interface.h" #include "../../carb/events/IEvents.h" namespace omni { namespace ext { /** * Extension version struct * * Follows Semantic Versioning 2.0. https://semver.org/ */ struct Version { int32_t major; //!< The major version (i.e. the 'x' in x.y.z), incremented for incompatible changes int32_t minor; //!< The minor version (i.e. the 'y' in x.y.z), for backwards compatible functionality int32_t patch; //!< The patch version (i.e. the 'z' in x.y.z), for backwards compatible bug fixes const char* prerelease; //!< The pre-release string const char* build; //!< The build string }; //! A struct describing Extension information struct ExtensionInfo { const char* id; //!< Unique Identifier used for python module name const char* name; //!< Extension name const char* packageId; //!< A package identifier Version version; //!< The version descriptor bool enabled; //!< Indicates whether this extension is enabled const char* title; //!< An optional descriptive title const char* path; //!< Extension path }; //! An enum describing Extensions Path type enum class ExtensionPathType { eCollection, //!< Folder with extensions eDirectPath, //!< Direct path to extension (as single file or a folder) eExt1Folder, //!< Deprecated Ext 1.0 Folder eCollectionUser, //!< Folder with extensions, read and stored in persistent settings eCollectionCache, //!< Folder with extensions, used for caching extensions downloaded from the registry eCount //!< Count of items in this enumeration }; //! A struct for describing Extension Folder information struct ExtensionFolderInfo { const char* path; //!< Extension path ExtensionPathType type; //!< Type of information in `path` member. }; //! A struct for describing Registry Provider information struct RegistryProviderInfo { const char* name; //!< The name of the Registry Provider }; //! A bit type for Extension Summary //! @see ExtensionSummary using ExtensionSummaryFlag = uint32_t; //! Empty flag constexpr ExtensionSummaryFlag kExtensionSummaryFlagNone = 0; //! Extension Summary flag meaning that extensions are enabled constexpr ExtensionSummaryFlag kExtensionSummaryFlagAnyEnabled = (1 << 1); //! Extension Summary flag meaning that an extension is built-in constexpr ExtensionSummaryFlag kExtensionSummaryFlagBuiltin = (1 << 2); //! Extension Summary flag meaning that an extension is installed constexpr ExtensionSummaryFlag kExtensionSummaryFlagInstalled = (1 << 3); //! A struct describing an Extension Summary //! @see ExtensionManager::fetchExtensionSummaries() struct ExtensionSummary { const char* fullname; //!< The full extension name, typically "ext_name-ext_tag" ExtensionSummaryFlag flags; //!< Summary flags about this extension //! Information about the enabled version, if any. If not present, \ref ExtensionInfo::id will be an empty string. ExtensionInfo enabledVersion; //! Information about the latest version. ExtensionInfo latestVersion; }; /** * Extension manager change event stream events */ //! An event type denoting a changed script. //! @see carb::events::IEvents const carb::events::EventType kEventScriptChanged = CARB_EVENTS_TYPE_FROM_STR("SCRIPT_CHANGED"); //! An event type denoting a changed folder. //! @see carb::events::IEvents const carb::events::EventType kEventFolderChanged = CARB_EVENTS_TYPE_FROM_STR("FOLDER_CHANGED"); /** * Extra events sent to IApp::getMessageBusEventStream() by extension manager */ //! An event type denoting the beginning of registry refresh. //! @see carb::events::IEvents const carb::events::EventType kEventRegistryRefreshBegin = CARB_EVENTS_TYPE_FROM_STR("omni.ext.REGISTRY_REFRESH_BEGIN"); //! An event type denoting the successful end of registry refresh. //! @see carb::events::IEvents const carb::events::EventType kEventRegistryRefreshEndSuccess = CARB_EVENTS_TYPE_FROM_STR("omni.ext.REGISTRY_REFRESH_END_SUCCESS"); //! An event type denoting end of registry refresh with failure. //! @see carb::events::IEvents const carb::events::EventType kEventRegistryRefreshEndFailure = CARB_EVENTS_TYPE_FROM_STR("omni.ext.REGISTRY_REFRESH_END_FAILURE"); //! An event type denoting the beginning of pulling an extension. //! @see carb::events::IEvents const carb::events::EventType kEventExtensionPullBegin = CARB_EVENTS_TYPE_FROM_STR("omni.ext.EXTENSION_PULL_BEGIN"); //! An event type denoting the successful end of pulling an extension. //! @see carb::events::IEvents const carb::events::EventType kEventExtensionPullEndSuccess = CARB_EVENTS_TYPE_FROM_STR("omni.ext.EXTENSION_PULL_END_SUCCESS"); //! An event type denoting the end of pulling an extension with failure. //! @see carb::events::IEvents const carb::events::EventType kEventExtensionPullEndFailure = CARB_EVENTS_TYPE_FROM_STR("omni.ext.EXTENSION_PULL_END_FAILURE"); /** * Version lock generation parameters * @see ExtensionManager::generateVersionLock() */ struct VersionLockDesc { bool separateFile; //!< Separate file bool skipCoreExts; //!< Skip core extensions bool overwrite; //!< Overwrite }; /** * The download state communicated by registry provider to extension manager * * Generally for index refresh or extension pull operations */ enum class DownloadState { eDownloading, //!< Currently downloading eDownloadSuccess, //!< Downloading finished successfully eDownloadFailure //!< Download failed }; /** * Input to running custom extension solver. * @see ExtensionManager::solveExtensions() */ struct SolverInput { //! List of extension names to enable (and therefore solve) //! //! Names may include full or partial versions, such as "omni.foo-1.2.3", or "omni.foo-1" //! The count of names is specified in `extensionNameCount`. const char** extensionNames; //! The number of names provided in the `extensionNames` array size_t extensionNameCount; //! Automatically add already enabled extension to the input (to take into account) bool addEnabled; //! If `true`, exclude extensions that are currently already enabled from the result. bool returnOnlyDisabled; }; /** * Interface to be implemented by registry providers. * * Extension manager will use it to pull (when resolving dependencies) and publish extensions. * * This is a sub-interface, with version controlled by \ref IExtensions. * * @see ExtensionManager, ExtensionManager::addRegistryProvider(), IExtensions */ class IRegistryProvider : public carb::IObject { public: /** * Called by ExtensionManager to begin an asynchronous index refresh or check status on an asynchronous refresh * * This function will be called many times and should return immediately. The returned state should be one of * \ref DownloadState. The first call to this function should begin a background index refresh and return * \ref DownloadState::eDownloading. Further calls to this function may return the same result while the refresh is * in process. When the refresh is finished, the next call should return \ref DownloadState::eDownloadSuccess, at * which point the \ref ExtensionManager will call \ref syncIndex(). * * @see ExtensionManager * @returns the \ref DownloadState */ virtual DownloadState refreshIndex() = 0; /** * Called by ExtensionManager to get the index * * Extension manager will call that function from time to time to get remote index. The structure of this dictionary * is a map from extension ids to extension configuration (mostly extension.toml files). * * @see ExtensionManager, carb::dictionary::IDictionary * @returns A \ref carb::dictionary::Item tree representing the remote index. */ virtual carb::dictionary::Item* syncIndex() = 0; /** * Called by ExtensionManager to trigger extension publishing * * @see ExtensionManager, unpublishExtension(), carb::dictionary::IDictionary * @param extPath The path to the extension to publish * @param extDict A \ref carb::dictionary::Item containing data about this extension * @returns `true` if publishing was successful; `false` if an error occurs */ virtual bool publishExtension(const char* extPath, carb::dictionary::Item* extDict) = 0; /** * Called by ExtensionManager to remove an extension * * @see ExtensionManager, publishExtension() * @param extId the extension ID of the extension to remove * @returns `true` if removal was successful; `false` if an error occurs */ virtual bool unpublishExtension(const char* extId) = 0; /** * Called by ExtensionManager to pull an extension, from a remote location to local cache * * @see ExtensionManager * @param extId The extension ID of the extension to pull * @param extFolder The folder to store the extension files in * @returns `true` if pulling was successful; `false` if an error occurs */ virtual bool pullExtension(const char* extId, const char* extFolder) = 0; /** * Called by ExtensionManager to asynchronously pull an extension, from a remote location to local cache * * This function will be called several times. The first time it is called for a given @p extId and @p extFolder, it * should start a background download process and return \ref DownloadState::eDownloading. It will be called * periodically to check the download state. Once the extension has been downloaded, this function should return * @ref DownloadState::eDownloadSuccess, or @ref DownloadState::eDownloadFailure if an error occurs. * @see ExtensionManager, DownloadState * @param extId The extension ID of the extension to pull * @param extFolder The folder to store the extension files in * @returns the current \ref DownloadState of the given \p extId */ virtual DownloadState pullExtensionAsync(const char* extId, const char* extFolder) = 0; /** * Called by ExtensionManager to set the maximum level of index stripping * * @rst .. deprecated:: This method is deprecated and no longer called. @endrst */ CARB_DEPRECATED("Not called. Index stripping was deprecated.") virtual bool setMaxStrippingLevel(int32_t level) = 0; }; //! Pointer type using IRegistryProviderPtr = carb::ObjectPtr<IRegistryProvider>; /** * Interface to be implemented to add new extension path protocols. */ class IPathProtocolProvider : public carb::IObject { public: /** * Called by ExtensionManager to register a protocol * * It must return local file system path for the provided url to be registered instead of url. It is a job of * protocol provider to update and maintain that local path. Extension manager will treat that path the same as * regular local extension search paths. * @param url The protocol to register * @returns A local filesystem path */ virtual const char* addPath(const char* url) = 0; /** * Called by ExtensionManager to unregister a protocol * @param url The protocol previously passed to \ref addPath(). */ virtual void removePath(const char* url) = 0; }; //! Pointer type using IPathProtocolProviderPtr = carb::ObjectPtr<IPathProtocolProvider>; class IExtensionManagerHooks; /** * The manager class that is responsible for all Extensions. * @see IExtensions::createExtensionManager */ class ExtensionManager : public carb::IObject { public: /** * Process all outstanding extension changes since the previous call to this function. * * If an extension was changed it will be reloaded. If it was added or removed (including adding new folders) * changes will also be applied. Events (@ref kEventScriptChanged, @ref kEventFolderChanged) are also dispatched. */ virtual void processAndApplyAllChanges() = 0; /** * Returns the number of registered local extensions. * @returns the number of registered local extensions */ virtual size_t getExtensionCount() const = 0; /** * Fills an array with information about registered local extensions. * * @param extensions The array of \ref ExtensionInfo structs to be filled. It must be large enough to hold * @ref getExtensionCount() entries. */ virtual void getExtensions(ExtensionInfo* extensions) const = 0; /** * Get an extension info dictionary for a single extension. * @see carb::dictionary::IDictionary * @param extId The extension ID to retrieve info for * @returns A \ref carb::dictionary::Item pointer containing the information; `nullptr` if the extension was not * found. */ virtual carb::dictionary::Item* getExtensionDict(const char* extId) const = 0; /** * Helper function to enable or disable a single extension. * @note The operation is deferred until \ref processAndApplyAllChanges() is called. Use * \ref setExtensionEnabledImmediate() to perform the action immediately. * @see setExtensionEnabledBatch * @param extensionId The extension ID to enable or disable * @param enabled `true` to enable the extension; `false` to disable the extension */ void setExtensionEnabled(const char* extensionId, bool enabled) { setExtensionEnabledBatch(&extensionId, 1, enabled); } /** * Enables or disables several extensions. * @note The operation is deferred until \ref processAndApplyAllChanges() is called. Use * \ref setExtensionEnabledBatchImmediate() to perform the action immediately. * @param extensionIds An array of extension IDs that should be enabled or disabled * @param extensionIdCount The number of items in \p extensionIds * @param enabled `true` to enable the extensions; `false` to disable the extensions */ virtual void setExtensionEnabledBatch(const char** extensionIds, size_t extensionIdCount, bool enabled) = 0; /** * Helper function to enable or disable a single extension, immediately. * @see setExtensionEnabledBatchImmediate * @param extensionId The extension ID to enable or disable * @param enabled `true` to enable the extension; `false` to disable the extension * @returns `true` if the operation could be completed; `false` otherwise */ bool setExtensionEnabledImmediate(const char* extensionId, bool enabled) { return setExtensionEnabledBatchImmediate(&extensionId, 1, enabled); } /** * Enables or disables several extensions immediately. * @param extensionIds An array of extension IDs that should be enabled or disabled * @param extensionIdCount The number of items in \p extensionIds * @param enabled `true` to enable the extensions; `false` to disable the extensions * @returns `true` if the operation could be completed; `false` otherwise */ virtual bool setExtensionEnabledBatchImmediate(const char** extensionIds, size_t extensionIdCount, bool enabled) = 0; /** * Set extensions to exclude on following solver/startup routines. * * @note The extensions set persist until next call to this function. * @param extensionIds An array of extension IDs that should be excluded * @param extensionIdCount The number of items in \p extensionIds */ virtual void setExtensionsExcluded(const char** extensionIds, size_t extensionIdCount) = 0; /** * Gets number of monitored extension folders. * * @return Extension folder count. */ virtual size_t getFolderCount() const = 0; /** * Gets monitored extension folders. * @param extensionFolderInfos The extension folder info array to be filled. It must be large enough to hold * @ref getFolderCount() entries. */ virtual void getFolders(ExtensionFolderInfo* extensionFolderInfos) const = 0; /** * Add extension path. * @see removePath() * @param path The path to add (folder or direct path) * @param type An \ref ExtensionPathType describing how \p path should be treated */ virtual void addPath(const char* path, ExtensionPathType type = ExtensionPathType::eCollection) = 0; /** * Remove extension path. * @see addPath() * @param path The path previously given to \ref addPath() */ virtual void removePath(const char* path) = 0; /** * Accesses the IEventStream that is used for change events. * * @see carb::events::IEventStream * @returns The \ref carb::events::IEventStream used for change events */ virtual carb::events::IEventStream* getChangeEventStream() const = 0; /** * Interface to install hooks to "extend" extension manager. * @returns an \ref IExtensionManagerHooks instance to allow hooking the Extension Manager */ virtual IExtensionManagerHooks* getHooks() const = 0; /** * Adds a new registry provider. * @see IRegistryProvider, removeRegistryProvider() * @param providerName unique name for the registry provider * @param provider a \ref IRegistryProvider instance that will be retained by `*this` * @returns `true` if registration was successful; `false` otherwise (i.e. the provided name was not unique) */ virtual bool addRegistryProvider(const char* providerName, IRegistryProvider* provider) = 0; /** * Removes a registry provider. * @see IRegistryProvider, addRegistryProvider() * @param providerName the unique name previously passed to \ref addRegistryProvider() */ virtual void removeRegistryProvider(const char* providerName) = 0; /** * Gets the number of current registry providers. * @returns the number of registry providers */ virtual size_t getRegistryProviderCount() const = 0; /** * Fills an array with info about current registry providers. * @param infos an array of \ref RegistryProviderInfo objects to be filled. It must be large enough to hold * @ref getRegistryProviderCount() entries. */ virtual void getRegistryProviders(RegistryProviderInfo* infos) = 0; /** * Non blocking call to initiate registry refresh. */ virtual void refreshRegistry() = 0; /** * Blocking call to synchronize with remote registry. * @returns `true` if the synchronization was successful; `false` if an error occurred. */ virtual bool syncRegistry() = 0; /** * Gets the number of extensions in the registry. */ virtual size_t getRegistryExtensionCount() const = 0; /** * Fills an array with compatible extensions in the registry. * * @param extensions an array of \ref ExtensionInfo objects to be filled. It must be large enough to hold * @ref getRegistryExtensionCount() entries. */ virtual void getRegistryExtensions(ExtensionInfo* extensions) const = 0; /** * Gets the number of extension packages in the registry. */ virtual size_t getRegistryExtensionPackageCount() const = 0; /** * Fills the array with all extension packages in the registry. * * @note this function will return all extensions in the registry, including packages for other platforms, * incompatible with current runtime. * * @param extensions an array of \ref ExtensionInfo objects to be filled. It must be large enough to hold * @ref getRegistryExtensionPackageCount() entries. */ virtual void getRegistryExtensionPackages(ExtensionInfo* extensions) const = 0; /** * Get an extension info dictionary for a single extension from the registry. * @see carb::dictionary::IDictionary * @param extId The extension ID to retrieve information for * @returns A \ref carb::dictionary::Item containing information about the given extension; `nullptr` if the * extension ID was not found. */ virtual carb::dictionary::Item* getRegistryExtensionDict(const char* extId) = 0; /** * Package and upload extension to the registry. * * @note If \p providerName is empty and there are multiple providers, the provider specified in the setting key * `/app/extensions/registryPublishDefault` is used. * @see unpublishExtension() * @param extId The extension ID to publish * @param providerName The provider name to use for publish. If an empty string is provided and multiple providers * are registered, the provider specified in the setting key `/app/extensions/registryPublishDefault` is used. * @param allowOverwrite If `true`, the extension already specified in the registry maybe overwritten */ virtual bool publishExtension(const char* extId, const char* providerName = "", bool allowOverwrite = false) = 0; /** * Removes an extension from the registry. * * @note If \p providerName is empty and there are multiple providers, the provider specified in the setting key * `/app/extensions/registryPublishDefault` is used. * @see publishExtension() * @param extId The extension ID to unpublish * @param providerName The provider name to use. If an empty string is provided and multiple providers * are registered, the provider specified in the setting key `/app/extensions/registryPublishDefault` is used. */ virtual bool unpublishExtension(const char* extId, const char* providerName = "") = 0; /** * Downloads the specified extension from the registry. * @note This is a blocking call. Use @ref pullExtensionAsync() if asynchronous behavior is desired. * @see pullExtensionAsync() * @param extId The extension ID to download * @returns `true` if the extension was downloaded successfully; `false` otherwise. */ virtual bool pullExtension(const char* extId) = 0; /** * Starts an asynchronous extension download from the registry. * @note this function returns immediately * @see pullExtension() * @param extId The extension ID to download */ virtual void pullExtensionAsync(const char* extId) = 0; /** * Fetches extension summaries for all extensions. * * Summary are extensions grouped by version. One summary per fullname(name+tag). * @note The array that is received is valid until the next call to this function. * @param[out] summaries Receives an array of \ref ExtensionSummary instances * @param[out] summaryCount Receives the size of the array passed to \p summaries. */ virtual void fetchExtensionSummaries(ExtensionSummary** summaries, size_t* summaryCount) = 0; /** * Fetch all matching compatible extensions. * * A partial version can also be passed. So `omni.foo`, `omni.foo-2`, `omni.foo-1.2.3` all valid values for * @p nameAndVersion. * * @note The returned array is valid until next call of this function. * @param nameAndVersion The name (and optional partial or full version) to search * @param[out] extensions Receives an array of \ref ExtensionInfo instances * @param[out] extensionCount Receives the size of the array passed to \p extensions */ virtual void fetchExtensionVersions(const char* nameAndVersion, ExtensionInfo** extensions, size_t* extensionCount) = 0; /** * Fetch all matching extension packages. * * A partial version can also be passed. So `omni.foo`, `omni.foo-2`, `omni.foo-1.2.3` all valid values for * @p nameAndVersion. * * This function will return all extensions in the registry, including packages for other platforms, incompatible * with current runtime. * * @note The returned array is valid until next call of this function. * @param nameAndVersion The name (and optional partial or full version) to search * @param[out] extensions Receives an array of \ref ExtensionInfo instances * @param[out] extensionCount Receives the size of the array passed to \p extensions */ virtual void fetchExtensionPackages(const char* nameAndVersion, ExtensionInfo** extensions, size_t* extensionCount) = 0; /** * Disables all enabled extensions. * * @note this is called automatically upon destruction. */ virtual void disableAllExtensions() = 0; /** * Adds user paths from persistent settings. * * All of the extension search path from persistent settings are added as \ref ExtensionPathType::eCollectionUser. */ virtual void addUserPaths() = 0; /** * Add cache paths from settings. * * All of the cache paths from settings are added as \ref ExtensionPathType::eCollectionCache. * This is necessary for registry usage. */ virtual void addCachePath() = 0; /** * Generate settings that contains versions of started dependencies to lock them (experimental). * @param extId The extension ID * @param desc A \ref VersionLockDesc descriptor * @returns `true` if generation succeeded; `false` otherwise */ virtual bool generateVersionLock(const char* extId, const VersionLockDesc& desc) = 0; /** * Adds a new path protocol provider. * @see removePathProtocolProvider() * @param scheme A unique name for this provider * @param provider A \ref IPathProtocolProvider instance that will be retained by the Extension Manager * @returns `true` if the provider was registered; `false` otherwise (i.e. if \p scheme is not unique) */ virtual bool addPathProtocolProvider(const char* scheme, IPathProtocolProvider* provider) = 0; /** * Removes a path protocol provider. * @see addPathProtocolProvider() * @param scheme The unique name previously passed to \ref addPathProtocolProvider() */ virtual void removePathProtocolProvider(const char* scheme) = 0; /** * Runs the extension dependencies solver on the input. * * Input is a list of extension, they can be names, full id, partial versions like `ommi.foo-2`. * * If solver succeeds it returns a list of extensions that satisfy the input and `true`, otherwise `errorMessage` * contains explanation of what failed. * * @note The returned array and error message is valid until next call of this function. * @param input The \ref SolverInput containing a list of extensions * @param[out] extensions If `true` returned, receives an array of \ref ExtensionInfo instances that satisfy * \p input, otherwise undefined * @param[out] extensionCount If `true` returned, receives the count of items passed to \p extensions, otherwise * undefined * @param[out] errorMessage If `false` returned, receives an error message, otherwise undefined * @returns `true` if the solver succeeds and \p extensions and \p extensionCount contain the array of extensions * that satisfy \p input; `false` otherwise, \p errorMessage contains a description of the error, but * \p extensions and \p extensionCount are undefined and should not be accessed. */ virtual bool solveExtensions(const SolverInput& input, ExtensionInfo** extensions, size_t* extensionCount, const char** errorMessage) = 0; /** * Gets number of local extension packages. * @returns the number of local extension packages */ virtual size_t getExtensionPackageCount() const = 0; /** * Fills an array with local extension packages. * * @note This function will return all local extensions, including packages for other platforms, incompatible * with current targets. * @param extensions An array of \ref ExtensionInfo instances to be filled. It must be large enough to hold * @ref getExtensionPackageCount() entries. */ virtual void getExtensionPackages(ExtensionInfo* extensions) const = 0; /** * Removes a downloaded extension. * @param extId The extension ID to remove * @returns `true` if the extension was removed; `false` otherwise */ virtual bool uninstallExtension(const char* extId) = 0; }; /** * omni.ext plugin interface * * This interface is used to access the \ref ExtensionManager */ struct IExtensions { CARB_PLUGIN_INTERFACE("omni::ext::IExtensions", 1, 1) /** * Creates a new extension manager. * @warning This function should not be used; instead call \ref createExtensionManager() to return a RAII pointer. * @param changeEventStream The \ref carb::events::IEventStream to push change events. The stream will not be * pumped by the manager. Optional (may be `nullptr`) * @returns A pointer to an \ref ExtensionManager */ ExtensionManager*(CARB_ABI* createExtensionManagerPtr)(carb::events::IEventStream* changeEventStream); /** * Creates a new extension manager. * @param changeEventStream The \ref carb::events::IEventStream to push change events. The stream will not be * pumped by the manager. Optional (may be `nullptr`) * @returns An RAII pointer to an \ref ExtensionManager */ carb::ObjectPtr<ExtensionManager> createExtensionManager(carb::events::IEventStream* changeEventStream = nullptr); }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Extension Manager Hooks // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Different moments in extension state lifetime. * * Used with \ref IExtensionStateChangeHook::onStateChange() to receive notifications at different points of an * extension state change. */ enum class ExtensionStateChangeType { eBeforeExtensionEnable, //!< Sent right before extension is enabled. eAfterExtensionEnable, //!< Sent right after extension is enabled. eBeforeExtensionShutdown, //!< Sent right before extension is disabled. eAfterExtensionShutdown, //!< Sent right after extension is disabled. eCount, //!< Count of extension state change entries. }; /** * An interface that can be implemented to receive extension state changes. */ class IExtensionStateChangeHook : public carb::IObject { public: /** * Called by the ExtensionManager upon extension state changes. * @see ExtensionManager * @param extId The extension ID that is experiencing a state change * @param type The \ref ExtensionStateChangeType that describes the type of state change */ virtual void onStateChange(const char* extId, ExtensionStateChangeType type) = 0; }; //! RAII pointer type using IExtensionStateChangeHookPtr = carb::ObjectPtr<IExtensionStateChangeHook>; /** * Hook call order. * * Lower hook values are called first. Negative values are acceptable. * @see kDefaultOrder */ using Order = int32_t; /** * Default order. */ static constexpr Order kDefaultOrder = 0; /** * Hook holder. Hook is valid while the holder is alive. */ class IHookHolder : public carb::IObject { }; //! RAII pointer type for \ref IHookHolder. using IHookHolderPtr = carb::ObjectPtr<IHookHolder>; /** * Extension manager subclass with all the hooks that can be installed into it. * @see ExtensionManager::getHooks() */ class IExtensionManagerHooks { public: /** * Installs a hook for extension state change. * * The hook will be called for the states specified by \ref ExtensionStateChangeType. * * You can filter for extensions with specific config/dict to only be called for those. That allows to implement * new configuration parameters handled by your hook. * * @param hook The instance that will be called. The \ref ExtensionManager will retain this object until the * returned \ref IHookHolderPtr expires * @param type Extension state change moment to hook into (see \ref ExtensionStateChangeType) * @param extFullName Extension name to look for. Hook is only called for extensions with matching name. Can be * empty. * @param extDictPath Extension dictionary path to look for. Hook is only called if it is present. * @param order Hook call order (if there are multiple). * @param hookName Hook name for debugging and logging. Optional (may be `nullptr`) * @returns a \ref IHookHolder object. When it expires \p hook will be released and no longer active. */ IHookHolderPtr createExtensionStateChangeHook(IExtensionStateChangeHook* hook, ExtensionStateChangeType type, const char* extFullName = "", const char* extDictPath = "", Order order = kDefaultOrder, const char* hookName = nullptr); //! @copydoc createExtensionStateChangeHook() virtual IHookHolder* createExtensionStateChangeHookPtr(IExtensionStateChangeHook* hook, ExtensionStateChangeType type, const char* extFullName = "", const char* extDictPath = "", Order order = kDefaultOrder, const char* hookName = nullptr) = 0; }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Inline Functions // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////// ExtensionManagerHooks ////////////// inline IHookHolderPtr IExtensionManagerHooks::createExtensionStateChangeHook(IExtensionStateChangeHook* hook, ExtensionStateChangeType type, const char* extFullName, const char* extDictPath, Order order, const char* hookName) { return carb::stealObject( this->createExtensionStateChangeHookPtr(hook, type, extFullName, extDictPath, order, hookName)); } ////////////// IExtensions ////////////// inline carb::ObjectPtr<ExtensionManager> IExtensions::createExtensionManager(carb::events::IEventStream* changeEventStream) { return carb::stealObject(this->createExtensionManagerPtr(changeEventStream)); } } // namespace ext } // namespace omni
omniverse-code/kit/include/omni/ext/IExtensionHooks.gen.h
// Copyright (c) 2020-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. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/Interface.h> #include <omni/core/OmniAttr.h> #include <omni/core/ResultError.h> #include <functional> #include <type_traits> #include <utility> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL //! Hooks that can be defined by plugins to better understand how the plugin is being used by the extension system. template <> class omni::core::Generated<omni::ext::IExtensionHooks_abi> : public omni::ext::IExtensionHooks_abi { public: OMNI_PLUGIN_INTERFACE("omni::ext::IExtensionHooks") //! Called when an extension loads the plugin. //! //! If multiple extensions load the plugin, this method will be called multiple times. void onStartup(omni::core::ObjectParam<omni::ext::IExtensionData> ext) noexcept; //! Called when an extension that uses this plugin is unloaded. //! //! If multiple extension load the plugin, this method will be called multiple times. void onShutdown(omni::core::ObjectParam<omni::ext::IExtensionData> ext) noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline void omni::core::Generated<omni::ext::IExtensionHooks_abi>::onStartup( omni::core::ObjectParam<omni::ext::IExtensionData> ext) noexcept { onStartup_abi(ext.get()); } inline void omni::core::Generated<omni::ext::IExtensionHooks_abi>::onShutdown( omni::core::ObjectParam<omni::ext::IExtensionData> ext) noexcept { onShutdown_abi(ext.get()); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
omniverse-code/kit/include/omni/ext/IExtensionData.h
// Copyright (c) 2020-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. // #pragma once #include <omni/core/IObject.h> namespace omni { namespace ext { //! Declaration of IExtensionData. OMNI_DECLARE_INTERFACE(IExtensionData); //! Information about an extension. class IExtensionData_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.ext.IExtensionData")> { protected: //! Access the extension id. For example: "omni.example.greet". //! //! @returns The Extension ID. The memory returned is valid for the lifetime of `*this`. virtual OMNI_ATTR("c_str, not_null") const char* getId_abi() noexcept = 0; //! Access the directory which contains the extension. For example: //! c:/users/ncournia/dev/kit/kit/_build/windows-x86_64/debug/exts/omni.example.greet. //! //! @returns The Extension Directory. The memory returned is valid for the lifetime of `*this`. virtual OMNI_ATTR("c_str, not_null") const char* getDirectory_abi() noexcept = 0; }; } // namespace ext } // namespace omni #include "IExtensionData.gen.h"
omniverse-code/kit/include/omni/ext/IExtensionData.gen.h
// Copyright (c) 2020-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. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/Interface.h> #include <omni/core/OmniAttr.h> #include <omni/core/ResultError.h> #include <functional> #include <type_traits> #include <utility> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL //! Information about an extension. template <> class omni::core::Generated<omni::ext::IExtensionData_abi> : public omni::ext::IExtensionData_abi { public: OMNI_PLUGIN_INTERFACE("omni::ext::IExtensionData") //! The extension id. For example: omni.example.greet. //! //! The memory returned is valid for the lifetime of this object. const char* getId() noexcept; //! The directory which contains the extension. For example: //! c:/users/ncournia/dev/kit/kit/_build/windows-x86_64/debug/exts/omni.example.greet. //! //! The memory returned is valid for the lifetime of this object. const char* getDirectory() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline const char* omni::core::Generated<omni::ext::IExtensionData_abi>::getId() noexcept { return getId_abi(); } inline const char* omni::core::Generated<omni::ext::IExtensionData_abi>::getDirectory() noexcept { return getDirectory_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
omniverse-code/kit/include/omni/python/PyString.h
// Copyright (c) 2022-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. // #pragma once #include "PyBind.h" #include "../String.h" namespace pybind11 { namespace detail { //! This converts between @c omni::string and native Python @c str types. template <> struct type_caster<omni::string> { // NOTE: The _ is needed to convert the character literal into a `pybind::descr` or functions using this type will // fail to initialize inside of `def`. PYBIND11_TYPE_CASTER(omni::string, _("omni::string")); //! Convert @a src Python string into @c omni::string instance. bool load(handle src, bool) { PyObject* source = src.ptr(); if (PyObject* source_bytes_raw = PyUnicode_AsEncodedString(source, "UTF-8", "strict")) { auto source_bytes = reinterpret_steal<bytes>(handle{ source_bytes_raw }); char* str; Py_ssize_t str_len; int rc = PyBytes_AsStringAndSize(source_bytes.ptr(), &str, &str_len); // Getting the string should always work here -- we've already ensured it encoded to UTF-8 bytes if (rc == -1) { return false; } this->value.assign(str, omni::string::size_type(str_len)); return true; } else { return false; } } //! Convert @a src string into a Python Unicode string. //! //! @note //! The return value policy and parent object arguments are ignored. The return policy is irrelevant, as the source //! string is always copied into the native form. The parent object is not supported by the Python string type. static handle cast(const omni::string& src, return_value_policy, handle) noexcept { PyObject* native = PyUnicode_FromStringAndSize(src.data(), Py_ssize_t(src.size())); return handle{ native }; } }; } // namespace detail } // namespace pybind11
omniverse-code/kit/include/omni/python/PyVec.h
// Copyright (c) 2020-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. // #pragma once #include "PyBind.h" #include <cstring> namespace omni { namespace python { namespace detail { template <typename VT, typename T, size_t S> T getVectorValue(const VT& vector, size_t i) { if (i >= S) { throw py::index_error(); } const T* components = reinterpret_cast<const T*>(&vector); return components[i]; } template <typename VT, typename T, size_t S> void setVectorValue(VT& vector, size_t i, T value) { if (i >= S) { throw py::index_error(); } T* components = reinterpret_cast<T*>(&vector); components[i] = value; } template <typename VT, typename T, size_t S> py::list getVectorSlice(const VT& s, const py::slice& slice) { size_t start, stop, step, slicelength; if (!slice.compute(S, &start, &stop, &step, &slicelength)) throw py::error_already_set(); py::list returnList; for (size_t i = 0; i < slicelength; ++i) { returnList.append(getVectorValue<VT, T, S>(s, start)); start += step; } return returnList; } template <typename VT, typename T, size_t S> void setVectorSlice(VT& s, const py::slice& slice, const py::sequence& value) { size_t start, stop, step, slicelength; if (!slice.compute(S, &start, &stop, &step, &slicelength)) throw py::error_already_set(); if (slicelength != value.size()) throw std::runtime_error("Left and right hand size of slice assignment have different sizes!"); for (size_t i = 0; i < slicelength; ++i) { setVectorValue<VT, T, S>(s, start, value[i].cast<T>()); start += step; } } template <typename TupleT, class T, size_t S> py::class_<TupleT> bindVec(py::module& m, const char* name, const char* docstring = nullptr) { py::class_<TupleT> c(m, name, docstring); c.def(py::init<>()); // Python special methods for iterators, [], len(): c.def("__len__", [](const TupleT&) { return S; }); c.def("__getitem__", [](const TupleT& t, size_t i) { return getVectorValue<TupleT, T, S>(t, i); }); c.def("__setitem__", [](TupleT& t, size_t i, T v) { setVectorValue<TupleT, T, S>(t, i, v); }); c.def("__getitem__", [](const TupleT& t, py::slice slice) -> py::list { return getVectorSlice<TupleT, T, S>(t, slice); }); c.def("__setitem__", [](TupleT& t, py::slice slice, const py::sequence& value) { setVectorSlice<TupleT, T, S>(t, slice, value); }); c.def("__eq__", [](TupleT& self, TupleT& other) { return 0 == std::memcmp(&self, &other, sizeof(TupleT)); }); // That allows passing python sequence into C++ function which accepts concrete TupleT: py::implicitly_convertible<py::sequence, TupleT>(); return c; } } // namespace detail } // namespace python } // namespace omni
omniverse-code/kit/include/omni/python/PyBind.h
// Copyright (c) 2020-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. // //! @file //! //! @brief Python binding helpers. #pragma once #include "../core/IObject.h" #include "../log/ILog.h" #include "../../carb/IObject.h" #include "../../carb/BindingsPythonUtils.h" #include <pybind11/pybind11.h> #include <pybind11/functional.h> #include <sstream> #include <vector> namespace py = pybind11; namespace omni { //! Python related functionality. namespace python { //! Private implementation details for Python. namespace detail { //! pybind11 "holder" for objects inherited from @ref omni::core::ObjectPtr. //! //! By default, @ref omni::core::ObjectPtr does not have a constructor that //! accepts a lone pointer. This is because it is ambiguous if @c //! addReference() should be called on the pointer. Unfortunately, pybind11 //! expects such a constructor to exists. The purpose of this class is provide //! the constructor pybind11 expects. //! //! Note that we're careful to never generate bindings that call the ambiguous //! constructor. To protect against future breakage, @ref OMNI_FATAL_UNLESS is //! used to flag bad code is being generated. Unfortunately, this check must be //! performed at runtime. //! //! An future alternative to this approach is to patch pybind11 //! //! OM-18948: Update PyBind to not require a raw pointer to "holder" //! constructor. template <typename T> class PyObjectPtr : public core::ObjectPtr<T> { public: //! Allow implicit conversion from `nullptr` to an @ref omni::core::ObjectPtr. constexpr PyObjectPtr(std::nullptr_t = nullptr) noexcept { } //! Never call this method as it will terminate the application. See class //! description for rationale. explicit PyObjectPtr(T*) { // if this assertion hits, something is amiss in our bindings (or PyBind was updated) OMNI_FATAL_UNLESS(false, "pybind11 created an ambiguous omni::core::ObjectPtr"); } //! Copy constructor. PyObjectPtr(const core::ObjectPtr<T>& other) noexcept : core::ObjectPtr<T>(other) { } //! Copy constructor. template <typename U> PyObjectPtr(const core::ObjectPtr<U>& other) noexcept : core::ObjectPtr<T>(other) { } //! Move constructor. template <typename U> PyObjectPtr(core::ObjectPtr<U>&& other) noexcept : core::ObjectPtr<T>(std::move(other)) { } }; } // namespace detail } // namespace python } // namespace omni #ifndef DOXYGEN_BUILD // tell pybind the smart pointer it should use to manage or interfaces PYBIND11_DECLARE_HOLDER_TYPE(T, omni::python::detail::PyObjectPtr<T>, true); PYBIND11_DECLARE_HOLDER_TYPE(T, omni::core::ObjectPtr<T>, true); // See comment block for DISABLE_PYBIND11_DYNAMIC_CAST for an explanation. namespace pybind11 { template <typename itype> struct polymorphic_type_hook<itype, detail::enable_if_t<std::is_base_of<omni::core::IObject, itype>::value>> { static const void* get(const itype* src, const std::type_info*&) { return src; } }; } // namespace pybind11 namespace omni { namespace python { //! Specialize this class to define hand-written bindings for T. template <typename T> struct PyBind { template <typename S> static S& bind(S& s) { return s; } }; //! Given a pointer, pokes around in pybind's internals to see if there's already a PyObject managing the pointer. This //! can be used to avoid data copies. inline bool hasPyObject(const void* p) { auto& instances = py::detail::get_internals().registered_instances; return (instances.end() != instances.find(p)); } //! Converts a C value to Python. Makes a copy if needed. //! //! The default template (this template) handles: //! - pointer to primitive type (int, float, etc.) //! - pointer to interface //! - primitive value (int, float, etc.) template <typename T, bool isInterface = std::is_base_of<omni::core::IObject, typename std::remove_pointer<T>::type>::value, bool isStruct = std::is_class<typename std::remove_pointer<T>::type>::value> class ValueToPython { public: explicit ValueToPython(T orig) : m_orig{ orig } { } T get() { return m_orig; } private: T m_orig; }; //! Specialization of ValueToPython //! //! This specialization handles: //! //! - pointer to struct template <typename T> class ValueToPython<T, /*interface*/ false, /*struct*/ true> { public: using Type = typename std::remove_pointer<T>::type; explicit ValueToPython(Type* orig) { m_orig = orig; if (!hasPyObject(orig)) { m_copy.reset(new Type{ *orig }); } } Type* getData() { if (m_copy) { return m_copy.get(); } else { return m_orig; } } private: Type* m_orig; std::unique_ptr<Type> m_copy; }; template <typename T, bool isPointer = std::is_pointer<T>::value, bool isInterface = std::is_base_of<omni::core::IObject, typename std::remove_pointer<T>::type>::value, bool isStruct = std::is_class<typename std::remove_pointer<T>::type>::value> struct PyCopy { // code generator shouldn't get here }; // primitive value template <typename T> struct PyCopy<T, false, false, false> { static py::object toPython(T cObj) { return py::cast(cObj); } static T fromPython(py::object pyObj) { return pyObj.cast<T>(); } }; // pointer to struct or primitive template <typename T, bool isStruct> struct PyCopy<T, /*isPointer=*/true, false, isStruct> { /* static py::object toPython(T cObj) { return py::cast(cObj); } */ static void fromPython(T out, py::object pyObj) { *out = *(pyObj.cast<T>()); } }; // struct template <typename T> struct PyCopy<T, false, false, true> { static py::object toPython(const T& cObj) { return py::cast(cObj); } static const T& fromPython(py::object pyObj) { return *pyObj.cast<T*>(); } }; template <typename T, bool elementIsPointer = std::is_pointer<typename std::remove_pointer<T>::type>::value, bool elementIsInterfacePointer = std::is_base_of<omni::core::IObject, typename std::remove_pointer<typename std::remove_pointer<T>::type>::type>::value, bool elementIsStruct = std::is_class<typename std::remove_pointer<T>::type>::value> struct PyArrayCopy { using ItemType = typename std::remove_const<typename std::remove_pointer<T>::type>::type; static py::object toPython(T in, uint32_t count) { py::tuple out(count); for (uint32_t i = 0; i < count; ++i) { out[i] = PyCopy<ItemType>::toPython(in[i]); } return out; } static void fromPython(T out, uint32_t count, py::sequence in) { if (count != uint32_t(in.size())) { std::ostringstream msg; msg << "expected " << count << " elements in the sequence, python returned " << int32_t(in.size()); throw std::runtime_error(msg.str()); } T dst = out; for (const auto& elem : in) { PyCopy<T>::fromPython(dst, elem); ++dst; } } }; template <typename T, bool elementIsInterfacePointer, bool elementIsStruct> struct PyArrayCopy<T, /*elementIsPointer=*/true, elementIsInterfacePointer, elementIsStruct> { // TODO: handle array of pointers }; template <> struct PyArrayCopy<const char* const*, /*elementIsPointer=*/true, /*elementIsInterfacePointer=*/false, /*elementIsStruct=*/false> { static py::object toPython(const char* const* in, uint32_t count) { py::tuple out(count); for (uint32_t i = 0; i < count; ++i) { out[i] = py::str(in[i]); } return out; } }; template <typename T> class ArrayToPython { public: using ItemType = typename std::remove_const<typename std::remove_pointer<T>::type>::type; ArrayToPython(T src, uint32_t sz) : m_tuple{ PyArrayCopy<T>::toPython(src, sz) } { } py::tuple& getPyObject() { return m_tuple; } private: py::tuple m_tuple; }; template <typename T> class ArrayFromPython { public: using ItemType = typename std::remove_const<typename std::remove_pointer<T>::type>::type; ArrayFromPython(py::sequence seq) { m_data.reserve(seq.size()); for (auto pyObj : seq) { m_data.emplace_back(PyCopy<ItemType>::fromPython(pyObj)); } } T getData() { return m_data.data(); } uint32_t getCount() const { return uint32_t(m_data.size()); } py::tuple createPyObject() { py::tuple out{ m_data.size() }; for (size_t i = 0; i < m_data.size(); ++i) { out[i] = PyCopy<ItemType>::toPython(m_data[i]); } return out; } private: std::vector<ItemType> m_data; }; template <typename T, bool isInterface = std::is_base_of<omni::core::IObject, typename std::remove_pointer<T>::type>::value, bool isStruct = std::is_class<typename std::remove_pointer<T>::type>::value> class PointerFromPython { // code generator should never instantiate this version }; // inout pointer to struct template <typename T> class PointerFromPython<T, /*interface=*/false, /*struct=*/true> { public: using Type = typename std::remove_const<typename std::remove_pointer<T>::type>::type; PointerFromPython() : m_copy{ new Type } { } explicit PointerFromPython(T orig) : m_copy{ new Type{ *orig } } { } T getData() { return m_copy.get(); } py::object createPyObject() { return py::cast(std::move(m_copy.release()), py::return_value_policy::take_ownership); } private: std::unique_ptr<Type> m_copy; }; // inout pointer to primitive type template <typename T> class PointerFromPython<T, /*interface=*/false, /*struct=*/false> { public: using Type = typename std::remove_const<typename std::remove_pointer<T>::type>::type; PointerFromPython() = default; explicit PointerFromPython(T orig) : m_copy{ *orig } { } T getData() { return &m_copy; } py::object createPyObject() { return py::cast(m_copy); } private: Type m_copy; }; inline void throwIfNone(const py::object& pyObj) { if (pyObj.is_none()) { throw std::runtime_error("python object must not be None"); } } } // namespace python } // namespace omni #endif // DOXYGEN_BUILD //! Declare a compilation unit as script language bindings. //! //! This macro should be called from each Python module to correctly initialize //! bindings. //! //! @param name_ The name of the module (e.g. "omni.core-pyd"). This is passed //! to @ref CARB_GLOBALS_EX which will be used as `g_carbClientName` for the //! module. This will also be the name of the module's default logging channel. //! //! @param desc_ The description passed to @ref OMNI_GLOBALS_ADD_DEFAULT_CHANNEL //! to describe the Python module's default logging channel. #define OMNI_PYTHON_GLOBALS(name_, desc_) CARB_BINDINGS_EX(name_, desc_)
omniverse-code/kit/include/omni/platforminfo/IOsInfo.h
// Copyright (c) 2021-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. // /** @file * @brief Helper interface to retrieve operating system info. */ #pragma once #include "../core/IObject.h" namespace omni { /** Platform and operating system info namespace. */ namespace platforminfo { /** Forward declaration of the IOSInfo API object. */ class IOsInfo; /** Names for the supported operating systems. */ enum class OMNI_ATTR("prefix=e") Os { eUnknown, ///< The OS is unknown or could not be determined. eWindows, ///< Microsoft Windows. eLinux, ///< Any flavor of Linux. eMacOs, ///< Mac OS. }; /** Names for the processor architecture for the system. */ enum class OMNI_ATTR("prefix=e") Architecture { eUnknown, ///< The architecture is unknown or could not be determined. eX86_64, ///< Intel X86 64 bit. eAarch64, ///< ARM 64-bit. }; /** A three-part operating system version number. This includes the major, minor, and * build number. This is often expressed as "<major>.<minor>.<buildNumber>" when printed. */ struct OsVersion { uint32_t major; ///< Major version. uint32_t minor; ///< Minor version. uint32_t buildNumber; ///< OS specific build number. }; /** Information about the active compositor on the system. */ struct CompositorInfo { const char* name; ///< The name of the active compositor. This must not be modified. const char* vendor; ///< The vendor of the active compositor. This must not be modified. int32_t releaseVersion; ///< The release version number of the active compositor. }; /** Interface to collect and retrieve information about the operating system. */ class IOsInfo_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.platforminfo.IOsInfo")> { protected: /** Retrieves the processor architecture for this platform. * * @returns An architecture name. This will never be * @ref omni::platforminfo::Architecture::eUnknown. * * @thread_safety This call is thread safe. */ virtual Architecture getArchitecture_abi() noexcept = 0; /** Retrieves an identifier for the current platform. * * @returns An operating system name. This will never be * @ref omni::platforminfo::Os::eUnknown. * * @thread_safety This call is thread safe. */ virtual Os getOs_abi() noexcept = 0; /** Retrieves the OS version information. * * @returns The operating system version numbers. These will be retrieved from the system * as directly as possible. If possible, these will not be parsed from a string * version of the operating system's name. * * @thread_safety This call is thread safe. */ virtual OsVersion getOsVersion_abi() noexcept = 0; /** Retrieves the name and version information for the system compositor. * * @returns An object describing the active compositor. * * @thread_safety This call is thread safe. */ virtual CompositorInfo getCompositorInfo_abi() noexcept = 0; /** Retrieves the friendly printable name of the operating system. * * @returns A string describing the operating system. This is retrieved from the system and * does not necessarily follow any specific formatting. This may or may not contain * specific version information. This string is intended for display to users. * * @thread_safety This call is thread safe. */ virtual const char* getPrettyName_abi() noexcept = 0; /** Retrieves the name of the operating system. * * @returns A string describing the operating system. This is retrieved from the system if * possible and does not necessarily follow any specific formatting. This may * include different information than the 'pretty' name (though still identifying * the same operating system version). This string is more intended for logging * or parsing purposes than display to the user. * * @thread_safety This call is thread safe. */ virtual const char* getName_abi() noexcept = 0; /** Retrieves the operating system distribution name. * * @returns The operating system distribution name. For Windows 10 and up, this often * contains the build's version name (ie: v1909). For Linux, this contains the * distro name (ie: "Ubuntu", "Gentoo", etc). * * @thread_safety This call is thread safe. */ virtual const char* getDistroName_abi() noexcept = 0; /** Retrieves the operating system's build code name. * * @returns The code name of the operating system's current version. For Windows 10 and up, * this is the Microsoft internal code name for each release (ie: "RedStone 5", * "21H2", etc). If possible it will be retrieved from the system. If not * available, a best guess will be made based on the build version number. For * Linux, this will be the build name of the current installed version (ie: * "Bionic", "Xenial", etc). * * @thread_safety This call is thread safe. */ virtual const char* getCodeName_abi() noexcept = 0; /** Retrieves the operating system's kernel version as a string. * * @returns A string containing the OS's kernel version information. There is no standard * layout for a kernel version across platforms so this isn't split up into a * struct of numeric values. For example, Linux kernel versions often contain * major-minor-hotfix-build_number-string components whereas Mac OS is typically * just major-minor-hotfix. Windows kernel versions are also often four values. * This is strictly for informational purposes. Splitting this up into numerical * components is left as an exercise for the caller if needed. */ virtual const char* getKernelVersion_abi() noexcept = 0; }; } // namespace platforminfo } // namespace omni #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "IOsInfo.gen.h" /** @copydoc omni::platforminfo::IOsInfo_abi */ class omni::platforminfo::IOsInfo : public omni::core::Generated<omni::platforminfo::IOsInfo_abi> { }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "IOsInfo.gen.h"
omniverse-code/kit/include/omni/platforminfo/IDisplayInfo.gen.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/OmniAttr.h> #include <omni/core/Interface.h> #include <omni/core/ResultError.h> #include <functional> #include <utility> #include <type_traits> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL /** Interface to collect and retrieve information about displays attached to the system. Each * display is a viewport onto the desktop's virtual screen space and has an origin and size. * Most displays are capable of switching between several modes. A mode is a combination of * a viewport resolution (width, height, and color depth), and refresh rate. Display info * may be collected using this interface, but it does not handle making changes to the current * mode for any given display. */ template <> class omni::core::Generated<omni::platforminfo::IDisplayInfo_abi> : public omni::platforminfo::IDisplayInfo_abi { public: OMNI_PLUGIN_INTERFACE("omni::platforminfo::IDisplayInfo") /** Retrieves the total number of displays connected to the system. * * @returns The total number of displays connected to the system. This typically includes * displays that are currently turned off. Note that the return value here is * volatile and may change at any point due to user action (either in the OS or * by unplugging or connecting a display). This value should not be cached for * extended periods of time. * * @thread_safety This call is thread safe. */ size_t getDisplayCount() noexcept; /** Retrieves information about a single connected display. * * @param[in] displayIndex The zero based index of the display to retrieve the information * for. This call will fail if the index is out of the range of * the number of connected displays, thus it is not necessary to * IDisplayInfo::getDisplayCount() to enumerate display information * in a counted loop. * @param[out] infoOut Receives the information for the requested display. This may * not be `nullptr`. This returned information may change at any * time due to user action and should therefore not be cached. * @returns `true` if the information for the requested display is successfully retrieved. * Returns `false` if the @p displayIndex index was out of the range of connected * display devices or the information could not be retrieved for any reason. * * @thread_safety This call is thread safe. */ bool getDisplayInfo(size_t displayIndex, omni::platforminfo::DisplayInfo* infoOut) noexcept; /** Retrieves the total number of display modes for a given display. * * @param[in] display The display to retrieve the mode count for. This may not be * `nullptr`. This must have been retrieved from a recent call to * IDisplayInfo::getDisplayInfo(). * @returns The total number of display modes supported by the requested display. Returns * 0 if the mode count information could not be retrieved. A connected valid * display will always support at least one mode. * * @thread_safety This call is thread safe. */ size_t getModeCount(const omni::platforminfo::DisplayInfo* display) noexcept; /** Retrieves the information for a single display mode for a given display. * * @param[in] display The display to retrieve the mode count for. This may not be * `nullptr`. This must have been retrieved from a recent call to * IDisplayInfo::getDisplayInfo(). * @param[in] modeIndex The zero based index of the mode to retrieve for the given * display. This make also be @ref kModeIndexCurrent to retrieve the * information for the given display's current mode. This call will * simply fail if this index is out of range of the number of modes * supported by the given display, thus it is not necessary to call * IDisplayInfo::getModeCount() to use in a counted loop. * @param[out] infoOut Receives the information for the requested mode of the given * display. This may not be `nullptr`. * @returns `true` if the information for the requested mode is successfully retrieved. * Returns `false` if the given index was out of range of the number of modes * supported by the given display or the mode's information could not be retrieved * for any reason. * * @thread_safety This call is thread safe. */ bool getModeInfo(const omni::platforminfo::DisplayInfo* display, omni::platforminfo::ModeIndex modeIndex, omni::platforminfo::ModeInfo* infoOut) noexcept; /** Retrieves the total virtual screen size that all connected displays cover. * * @param[out] origin Receives the coordinates of the origin of the rectangle that the * virtual screen covers. This may be `nullptr` if the origin point * is not needed. * @param[out] size Receives the width and height of the rectangle that the virtual * screen covers. This may be `nullptr` if the size is not needed. * @returns `true` if either the origin, size, or both origin and size of the virtual * screen are retrieved successfully. Returns `false` if the size of the virtual * screen could not be retrieved or both @p origin and @p size are `nullptr`. * * @remarks This retrieves the total virtual screen size for the system. This is the * union of the rectangles that all connected displays cover. Note that this * will also include any empty space between or around displays that is not * covered by another display. * * @thread_safety This call is thread safe. */ bool getTotalDisplaySize(carb::Int2* origin, carb::Int2* size) noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline size_t omni::core::Generated<omni::platforminfo::IDisplayInfo_abi>::getDisplayCount() noexcept { return getDisplayCount_abi(); } inline bool omni::core::Generated<omni::platforminfo::IDisplayInfo_abi>::getDisplayInfo( size_t displayIndex, omni::platforminfo::DisplayInfo* infoOut) noexcept { return getDisplayInfo_abi(displayIndex, infoOut); } inline size_t omni::core::Generated<omni::platforminfo::IDisplayInfo_abi>::getModeCount( const omni::platforminfo::DisplayInfo* display) noexcept { return getModeCount_abi(display); } inline bool omni::core::Generated<omni::platforminfo::IDisplayInfo_abi>::getModeInfo( const omni::platforminfo::DisplayInfo* display, omni::platforminfo::ModeIndex modeIndex, omni::platforminfo::ModeInfo* infoOut) noexcept { return getModeInfo_abi(display, modeIndex, infoOut); } inline bool omni::core::Generated<omni::platforminfo::IDisplayInfo_abi>::getTotalDisplaySize(carb::Int2* origin, carb::Int2* size) noexcept { return getTotalDisplaySize_abi(origin, size); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL static_assert(std::is_standard_layout<omni::platforminfo::ModeInfo>::value, "omni::platforminfo::ModeInfo must be standard layout to be used in ONI ABI"); static_assert(std::is_standard_layout<omni::platforminfo::DisplayInfo>::value, "omni::platforminfo::DisplayInfo must be standard layout to be used in ONI ABI");
omniverse-code/kit/include/omni/platforminfo/IOsInfo2.h
// 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. // /** @file * @brief Helper interface to retrieve operating system info. */ #pragma once #include "IOsInfo.h" namespace omni { /** Platform and operating system info namespace. */ namespace platforminfo { /** Forward declaration of the IOSInfo2 API object. */ class IOsInfo2; /** Extended interface to collect and retrieve more information about the operating system. * This inherits from omni::platforminfo::IOsInfo and also provides all of its functionality. */ class IOsInfo2_abi : public omni::core::Inherits<omni::platforminfo::IOsInfo, OMNI_TYPE_ID("omni.platforminfo.IOsInfo2")> { protected: /** [Windows] Tests whether this process is running under compatibility mode. * * @returns `true` if this process is running in compatibility mode for an older version * of Windows. Returns `false` otherwise. Returns `false` on all non-Windows * platforms. * * @remarks Windows 10 and up allow a way for apps to run in 'compatibility mode'. This * causes many of the OS version functions to return values that represent an * older version of windows (ie: Win8.1 and earlier) instead of the actual version * information. This can allow some apps that don't fully support Win10 and up to * start properly. */ virtual bool isCompatibilityModeEnabled_abi() noexcept = 0; }; } // namespace platforminfo } // namespace omni #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "IOsInfo2.gen.h" /** @copydoc omni::platforminfo::IOsInfo2_abi */ class omni::platforminfo::IOsInfo2 : public omni::core::Generated<omni::platforminfo::IOsInfo2_abi> { }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "IOsInfo2.gen.h"
omniverse-code/kit/include/omni/platforminfo/IOsInfo.gen.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/OmniAttr.h> #include <omni/core/Interface.h> #include <omni/core/ResultError.h> #include <functional> #include <utility> #include <type_traits> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL /** Interface to collect and retrieve information about the operating system. */ template <> class omni::core::Generated<omni::platforminfo::IOsInfo_abi> : public omni::platforminfo::IOsInfo_abi { public: OMNI_PLUGIN_INTERFACE("omni::platforminfo::IOsInfo") /** Retrieves the processor architecture for this platform. * * @returns An architecture name. This will never be * @ref omni::platforminfo::Architecture::eUnknown. * * @thread_safety This call is thread safe. */ omni::platforminfo::Architecture getArchitecture() noexcept; /** Retrieves an identifier for the current platform. * * @returns An operating system name. This will never be * @ref omni::platforminfo::Os::eUnknown. * * @thread_safety This call is thread safe. */ omni::platforminfo::Os getOs() noexcept; /** Retrieves the OS version information. * * @returns The operating system version numbers. These will be retrieved from the system * as directly as possible. If possible, these will not be parsed from a string * version of the operating system's name. * * @thread_safety This call is thread safe. */ omni::platforminfo::OsVersion getOsVersion() noexcept; /** Retrieves the name and version information for the system compositor. * * @returns An object describing the active compositor. * * @thread_safety This call is thread safe. */ omni::platforminfo::CompositorInfo getCompositorInfo() noexcept; /** Retrieves the friendly printable name of the operating system. * * @returns A string describing the operating system. This is retrieved from the system and * does not necessarily follow any specific formatting. This may or may not contain * specific version information. This string is intended for display to users. * * @thread_safety This call is thread safe. */ const char* getPrettyName() noexcept; /** Retrieves the name of the operating system. * * @returns A string describing the operating system. This is retrieved from the system if * possible and does not necessarily follow any specific formatting. This may * include different information than the 'pretty' name (though still identifying * the same operating system version). This string is more intended for logging * or parsing purposes than display to the user. * * @thread_safety This call is thread safe. */ const char* getName() noexcept; /** Retrieves the operating system distribution name. * * @returns The operating system distribution name. For Windows 10 and up, this often * contains the build's version name (ie: v1909). For Linux, this contains the * distro name (ie: "Ubuntu", "Gentoo", etc). * * @thread_safety This call is thread safe. */ const char* getDistroName() noexcept; /** Retrieves the operating system's build code name. * * @returns The code name of the operating system's current version. For Windows 10 and up, * this is the Microsoft internal code name for each release (ie: "RedStone 5", * "21H2", etc). If possible it will be retrieved from the system. If not * available, a best guess will be made based on the build version number. For * Linux, this will be the build name of the current installed version (ie: * "Bionic", "Xenial", etc). * * @thread_safety This call is thread safe. */ const char* getCodeName() noexcept; /** Retrieves the operating system's kernel version as a string. * * @returns A string containing the OS's kernel version information. There is no standard * layout for a kernel version across platforms so this isn't split up into a * struct of numeric values. For example, Linux kernel versions often contain * major-minor-hotfix-build_number-string components whereas Mac OS is typically * just major-minor-hotfix. Windows kernel versions are also often four values. * This is strictly for informational purposes. Splitting this up into numerical * components is left as an exercise for the caller if needed. */ const char* getKernelVersion() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline omni::platforminfo::Architecture omni::core::Generated<omni::platforminfo::IOsInfo_abi>::getArchitecture() noexcept { return getArchitecture_abi(); } inline omni::platforminfo::Os omni::core::Generated<omni::platforminfo::IOsInfo_abi>::getOs() noexcept { return getOs_abi(); } inline omni::platforminfo::OsVersion omni::core::Generated<omni::platforminfo::IOsInfo_abi>::getOsVersion() noexcept { return getOsVersion_abi(); } inline omni::platforminfo::CompositorInfo omni::core::Generated<omni::platforminfo::IOsInfo_abi>::getCompositorInfo() noexcept { return getCompositorInfo_abi(); } inline const char* omni::core::Generated<omni::platforminfo::IOsInfo_abi>::getPrettyName() noexcept { return getPrettyName_abi(); } inline const char* omni::core::Generated<omni::platforminfo::IOsInfo_abi>::getName() noexcept { return getName_abi(); } inline const char* omni::core::Generated<omni::platforminfo::IOsInfo_abi>::getDistroName() noexcept { return getDistroName_abi(); } inline const char* omni::core::Generated<omni::platforminfo::IOsInfo_abi>::getCodeName() noexcept { return getCodeName_abi(); } inline const char* omni::core::Generated<omni::platforminfo::IOsInfo_abi>::getKernelVersion() noexcept { return getKernelVersion_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL static_assert(std::is_standard_layout<omni::platforminfo::OsVersion>::value, "omni::platforminfo::OsVersion must be standard layout to be used in ONI ABI"); static_assert(std::is_standard_layout<omni::platforminfo::CompositorInfo>::value, "omni::platforminfo::CompositorInfo must be standard layout to be used in ONI ABI");
omniverse-code/kit/include/omni/platforminfo/IMemoryInfo.gen.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/OmniAttr.h> #include <omni/core/Interface.h> #include <omni/core/ResultError.h> #include <functional> #include <utility> #include <type_traits> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL /** Interface to collect and retrieve information about memory installed in the system. */ template <> class omni::core::Generated<omni::platforminfo::IMemoryInfo_abi> : public omni::platforminfo::IMemoryInfo_abi { public: OMNI_PLUGIN_INTERFACE("omni::platforminfo::IMemoryInfo") /** Retrieves the total installed physical RAM in the system. * * @returns The number of bytes of physical RAM installed in the system. This value will * not change during the lifetime of the calling process. * * @thread_safety This call is thread safe. */ size_t getTotalPhysicalMemory() noexcept; /** Retrieves the available physical memory in the system. * * @returns The number of bytes of physical RAM that is currently available for use by the * operating system. Note that this is not a measure of how much memory is * available to the calling process, but rather for the entire system. * * @thread_safety This call is thread safe. However, two consecutive or concurrent calls * are unlikely to return the same value. */ size_t getAvailablePhysicalMemory() noexcept; /** Retrieves the total page file space in the system. * * @returns The number of bytes of page file space in the system. The value will not * change during the lifetime of the calling process. * * @thread_safety This call is thread safe. */ size_t getTotalPageFileMemory() noexcept; /** Retrieves the available page file space in the system. * * @returns The number of bytes of page file space that is currently available for use * by the operating system. * * @thread_safety This call is thread safe. However, two consecutive or concurrent calls * are unlikely to return the same value. */ size_t getAvailablePageFileMemory() noexcept; /** Retrieves the total memory usage for the calling process. * * @returns The number of bytes of memory used by the calling process. This will not * necessarily be the amount of the process's virtual memory space that is * currently in use, but rather the amount of memory that the OS currently * has wired for this process (ie: the process's working set memory). It is * possible that the process could have a lot more memory allocated, just * inactive as far as the OS is concerned. * * @thread_safety This call is thread safe. However, two consecutive calls are unlikely * to return the same value. */ size_t getProcessMemoryUsage() noexcept; /** Retrieves the peak memory usage of the calling process. * * @returns The maximum number of bytes of memory used by the calling process. This will * not necessarily be the maximum amount of the process's virtual memory space that * was ever allocated, but rather the maximum amount of memory that the OS ever had * wired for the process (ie: the process's working set memory). It is possible * that the process could have had a lot more memory allocated, just inactive as * far as the OS is concerned. */ size_t getProcessPeakMemoryUsage() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline size_t omni::core::Generated<omni::platforminfo::IMemoryInfo_abi>::getTotalPhysicalMemory() noexcept { return getTotalPhysicalMemory_abi(); } inline size_t omni::core::Generated<omni::platforminfo::IMemoryInfo_abi>::getAvailablePhysicalMemory() noexcept { return getAvailablePhysicalMemory_abi(); } inline size_t omni::core::Generated<omni::platforminfo::IMemoryInfo_abi>::getTotalPageFileMemory() noexcept { return getTotalPageFileMemory_abi(); } inline size_t omni::core::Generated<omni::platforminfo::IMemoryInfo_abi>::getAvailablePageFileMemory() noexcept { return getAvailablePageFileMemory_abi(); } inline size_t omni::core::Generated<omni::platforminfo::IMemoryInfo_abi>::getProcessMemoryUsage() noexcept { return getProcessMemoryUsage_abi(); } inline size_t omni::core::Generated<omni::platforminfo::IMemoryInfo_abi>::getProcessPeakMemoryUsage() noexcept { return getProcessPeakMemoryUsage_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
omniverse-code/kit/include/omni/platforminfo/ICpuInfo.gen.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/OmniAttr.h> #include <omni/core/Interface.h> #include <omni/core/ResultError.h> #include <functional> #include <utility> #include <type_traits> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL /** Interface to collect information about the CPUs installed in the calling system. This * can provide some basic information about the CPU(s) and get access to features that are * supported by them. */ template <> class omni::core::Generated<omni::platforminfo::ICpuInfo_abi> : public omni::platforminfo::ICpuInfo_abi { public: OMNI_PLUGIN_INTERFACE("omni::platforminfo::ICpuInfo") /** Retrieves the total number of CPU packages installed on the system. * * @returns The total number of CPU packages installed in the system. A CPU package * is a single physical CPU chip that is connected to a physical socket on * the motherboard. * * @remarks A system may have multiple CPUs installed if the motherboard supports it. * At least in the Intel (and compatible) case, there are some restrictions * to doing this - all CPUs must be in the same family, share the same core * count, feature set, and bus speed. Outside of that, the CPUs do not need * to be identical. * * @thread_safety This call is thread safe. */ size_t getCpuPackageCount() noexcept; /** Retrieves the total number of physical cores across all CPUs in the system. * * @returns The total number of physical cores across all CPUs in the system. This includes * the sum of all physical cores on all CPU packages. This will not be zero. * * @thread_safety This call is thread safe. */ size_t getTotalPhysicalCoreCount() noexcept; /** Retrieves the total number of logical cores across all CPUs in the system. * * @returns The total number of logical cores across all CPUs in the system. This includes * the sum of all logical cores on all CPU packages. * * @thread_safety This call is thread safe. */ size_t getTotalLogicalCoreCount() noexcept; /** Retrieves the number of physical cores per CPU package in the system. * * @returns The total number of physical cores per CPU package. Since all CPU packages * must have the same core counts, this is a common value to all packages. * * @thread_safety This call is thread safe. */ size_t getPhysicalCoresPerPackage() noexcept; /** Retrieves the number of logical cores per CPU package in the system. * * @returns The total number of logical cores per CPU package. Since all CPU packages * must have the same core counts, this is a common value to all packages. * * @thread_safety This call is thread safe. */ size_t getLogicalCoresPerPackage() noexcept; /** Checks if a requested feature is supported by the CPU(s) in the system. * * @returns `true` if the requested feature is supported. Returns `false` otherwise. * * @remarks See @ref omni::platforminfo::CpuFeature for more information on the features * that can be queried. * * @thread_safety This call is thread safe. */ bool isFeatureSupported(omni::platforminfo::CpuFeature feature) noexcept; /** Retrieves the friendly name of a CPU in the system. * * @param[in] cpuIndex The zero based index of the CPU package to retrieve the name * for. This should be less than the return value of * ICpuInfo::getCpuPackageCount(). * @returns The friendly name of the requested CPU package. This string should be suitable * for display to the user. This will contain a rough outline of the processor * model and architecture. It may or may not contain the clock speed. * * @thread_safety This call is thread safe. */ const char* getPrettyName(size_t cpuIndex) noexcept; /** Retrieves the identifier of a CPU in the system. * * @param[in] cpuIndex The zero based index of the CPU package to retrieve the identifier * for. This should be less than the return value of * ICpuInfo::getCpuPackageCount(). * @returns The identifier string of the requested CPU package. This string should be * suitable for display to the user. This will contain information about the * processor family, vendor, and architecture. * * @thread_safety This call is thread safe. */ const char* getIdentifier(size_t cpuIndex) noexcept; /** Retrieves the vendor string for a CPU package in the system. * * @param[in] cpuIndex The zero based index of the CPU package to retrieve the vendor * for. This should be less than the return value of * ICpuInfo::getCpuPackageCount(). * @returns The name of the vendor as reported by the CPU itself. This may be something * along the lines of "GenuineIntel" or "AuthenticAMD" for x86_64 architectures, * or the name of the CPU implementer for ARM architectures. * * @thread_safety This call is thread safe. */ const char* getVendor(size_t cpuIndex) noexcept; /** Note: the mask may be 0 if out of range of 64 bits. */ /** Retrieves a bit mask for the processor cores in a CPU package in the system. * * @param[in] cpuIndex The zero based index of the CPU package to retrieve the identifier * for. This should be less than the return value of * ICpuInfo::getCpuPackageCount(). * @returns A mask identifying which CPU cores the given CPU covers. A set bit indicates * a core that belongs to the given CPU. A 0 bit indicates either a core from * another package or a non-existent core. This may also be 0 if more than 64 * cores are present in the system or they are out of range of a single 64-bit * value. * * @thread_safety This call is thread safe. */ uint64_t getProcessorMask(size_t cpuIndex) noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline size_t omni::core::Generated<omni::platforminfo::ICpuInfo_abi>::getCpuPackageCount() noexcept { return getCpuPackageCount_abi(); } inline size_t omni::core::Generated<omni::platforminfo::ICpuInfo_abi>::getTotalPhysicalCoreCount() noexcept { return getTotalPhysicalCoreCount_abi(); } inline size_t omni::core::Generated<omni::platforminfo::ICpuInfo_abi>::getTotalLogicalCoreCount() noexcept { return getTotalLogicalCoreCount_abi(); } inline size_t omni::core::Generated<omni::platforminfo::ICpuInfo_abi>::getPhysicalCoresPerPackage() noexcept { return getPhysicalCoresPerPackage_abi(); } inline size_t omni::core::Generated<omni::platforminfo::ICpuInfo_abi>::getLogicalCoresPerPackage() noexcept { return getLogicalCoresPerPackage_abi(); } inline bool omni::core::Generated<omni::platforminfo::ICpuInfo_abi>::isFeatureSupported( omni::platforminfo::CpuFeature feature) noexcept { return isFeatureSupported_abi(feature); } inline const char* omni::core::Generated<omni::platforminfo::ICpuInfo_abi>::getPrettyName(size_t cpuIndex) noexcept { return getPrettyName_abi(cpuIndex); } inline const char* omni::core::Generated<omni::platforminfo::ICpuInfo_abi>::getIdentifier(size_t cpuIndex) noexcept { return getIdentifier_abi(cpuIndex); } inline const char* omni::core::Generated<omni::platforminfo::ICpuInfo_abi>::getVendor(size_t cpuIndex) noexcept { return getVendor_abi(cpuIndex); } inline uint64_t omni::core::Generated<omni::platforminfo::ICpuInfo_abi>::getProcessorMask(size_t cpuIndex) noexcept { return getProcessorMask_abi(cpuIndex); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
omniverse-code/kit/include/omni/platforminfo/ICpuInfo.h
// Copyright (c) 2021-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. // /** @file * @brief Helper interface to retrieve CPU info. */ #pragma once #include "../core/IObject.h" namespace omni { /** Platform and operating system info namespace. */ namespace platforminfo { /** Forward declaration of the API layer. */ class ICpuInfo; /** CPU feature names. Each feature name is used with ICpuInfo::isFeatureSupported() to * determine if the requested CPU running on the calling system supports the feature. * These feature flags mostly focus on the availability of specific instructions sets * on the host CPU. */ enum class OMNI_ATTR("prefix=e") CpuFeature { /** Intel specific features. These names are largely labeled to match the mnemonics * used in the Intel Instruction Set Programming Reference document from Intel. For * the most part, only the casing differs and '-' has been converted to an underscore. * * @note Many of these features originated with Intel hardware and therefore have * 'X86' in their name. However, many of these features are or can also be * supported on AMD CPUs. If an AMD CPU is detected, these feature names could * still be valid and the related instructions usable. * * @{ */ eX86Sse, ///< Intel SSE instructions are supported. eX86Sse2, ///< Intel SSE2 instructions are supported. eX86Sse3, ///< Intel SSE3 instructions are supported. eX86Ssse3, ///< Intel supplementary SSE3 instructions are supported. eX86Fma, ///< Fused multiply-add SIMD operations are supported. eX86Sse41, ///< Intel SSE4.1 instructions are supported. eX86Sse42, ///< Intel SSE4.2 instructions are supported. eX86Avx, ///< Intel AVX instructions are supported. eX86F16c, ///< 16-bit floating point conversion instructions are supported. eX86Popcnt, ///< Instruction for counting set bits are supported. eX86Tsc, ///< The `RDTSC` instruction is supported. eX86Mmx, ///< Intel MMX instructions are supported. eX86Avx2, ///< Intel AVX2 instructions are supported. eX86Avx512F, ///< The AVX-512 foundation instructions are supported. eX86Avx512Dq, ///< The AVX-512 double and quad word instructions are supported. eX86Avx512Ifma, ///< The AVX-512 integer fused multiply-add instructions are supported. eX86Avx512Pf, ///< The AVX-512 prefetch instructions are supported. eX86Avx512Er, ///< The AVX-512 exponential and reciprocal instructions are supported. eX86Avx512Cd, ///< The AVX-512 conflict detection instructions are supported. eX86Avx512Bw, ///< The AVX-512 byte and word instructions are supported. eX86Avx512Vl, ///< The AVX-512 vector length extensions instructions are supported. eX86Avx512_Vbmi, ///< The AVX-512 vector byte manipulation instructions are supported. eX86Avx512_Vbmi2, ///< The AVX-512 vector byte manipulation 2 instructions are supported. eX86Avx512_Vnni, ///< The AVX-512 vector neural network instructions are supported. eX86Avx512_Bitalg, ///< The AVX-512 bit algorithms instructions are supported. eX86Avx512_Vpopcntdq, ///< The AVX-512 vector population count instructions are supported. eX86Avx512_4Vnniw, ///< The AVX-512 word vector neural network instructions are supported. eX86Avx512_4fmaps, ///< The AVX-512 packed single fused multiply-add instructions are supported. eX86Avx512_Vp2intersect, ///< The AVX-512 vector pair intersection instructions are supported. eX86AvxVnni, ///< The AVX VEX-encoded versions of the neural network instructions are supported. eX86Avx512_Bf16, ///< The AVX-512 16-bit floating point vector NN instructions are supported. /** @} */ /** AMD specific features. * @{ */ eAmd3DNow, ///< The AMD 3DNow! instruction set is supported. eAmd3DNowExt, ///< The AMD 3DNow! extensions instruction set is supported. eAmdMmxExt, ///< The AMD MMX extensions instruction set is supported. /** @} */ /** ARM specific features: * @{ */ eArmAsimd, ///< The advanced SIMD instructions are supported. eArmNeon, ///< The ARM Neon instruction set is supported. eArmAtomics, ///< The ARMv8 atomic instructions are supported. eArmSha, ///< The SHA1 and SHA2 instruction sets are supported. eArmCrypto, ///< The ARM AES instructions are supported. eArmCrc32, ///< The ARM CRC32 instructions are supported. /** @} */ eFeatureCount, /// Total number of features. Not a valid feature name. }; /** Interface to collect information about the CPUs installed in the calling system. This * can provide some basic information about the CPU(s) and get access to features that are * supported by them. */ class ICpuInfo_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.platforminfo.ICpuInfo")> { protected: /** Retrieves the total number of CPU packages installed on the system. * * @returns The total number of CPU packages installed in the system. A CPU package * is a single physical CPU chip that is connected to a physical socket on * the motherboard. * * @remarks A system may have multiple CPUs installed if the motherboard supports it. * At least in the Intel (and compatible) case, there are some restrictions * to doing this - all CPUs must be in the same family, share the same core * count, feature set, and bus speed. Outside of that, the CPUs do not need * to be identical. * * @thread_safety This call is thread safe. */ virtual size_t getCpuPackageCount_abi() noexcept = 0; /** Retrieves the total number of physical cores across all CPUs in the system. * * @returns The total number of physical cores across all CPUs in the system. This includes * the sum of all physical cores on all CPU packages. This will not be zero. * * @thread_safety This call is thread safe. */ virtual size_t getTotalPhysicalCoreCount_abi() noexcept = 0; /** Retrieves the total number of logical cores across all CPUs in the system. * * @returns The total number of logical cores across all CPUs in the system. This includes * the sum of all logical cores on all CPU packages. * * @thread_safety This call is thread safe. */ virtual size_t getTotalLogicalCoreCount_abi() noexcept = 0; /** Retrieves the number of physical cores per CPU package in the system. * * @returns The total number of physical cores per CPU package. Since all CPU packages * must have the same core counts, this is a common value to all packages. * * @thread_safety This call is thread safe. */ virtual size_t getPhysicalCoresPerPackage_abi() noexcept = 0; /** Retrieves the number of logical cores per CPU package in the system. * * @returns The total number of logical cores per CPU package. Since all CPU packages * must have the same core counts, this is a common value to all packages. * * @thread_safety This call is thread safe. */ virtual size_t getLogicalCoresPerPackage_abi() noexcept = 0; /** Checks if a requested feature is supported by the CPU(s) in the system. * * @returns `true` if the requested feature is supported. Returns `false` otherwise. * * @remarks See @ref omni::platforminfo::CpuFeature for more information on the features * that can be queried. * * @thread_safety This call is thread safe. */ virtual bool isFeatureSupported_abi(CpuFeature feature) noexcept = 0; /** Retrieves the friendly name of a CPU in the system. * * @param[in] cpuIndex The zero based index of the CPU package to retrieve the name * for. This should be less than the return value of * ICpuInfo::getCpuPackageCount(). * @returns The friendly name of the requested CPU package. This string should be suitable * for display to the user. This will contain a rough outline of the processor * model and architecture. It may or may not contain the clock speed. * * @thread_safety This call is thread safe. */ virtual const char* getPrettyName_abi(size_t cpuIndex) noexcept = 0; /** Retrieves the identifier of a CPU in the system. * * @param[in] cpuIndex The zero based index of the CPU package to retrieve the identifier * for. This should be less than the return value of * ICpuInfo::getCpuPackageCount(). * @returns The identifier string of the requested CPU package. This string should be * suitable for display to the user. This will contain information about the * processor family, vendor, and architecture. * * @thread_safety This call is thread safe. */ virtual const char* getIdentifier_abi(size_t cpuIndex) noexcept = 0; /** Retrieves the vendor string for a CPU package in the system. * * @param[in] cpuIndex The zero based index of the CPU package to retrieve the vendor * for. This should be less than the return value of * ICpuInfo::getCpuPackageCount(). * @returns The name of the vendor as reported by the CPU itself. This may be something * along the lines of "GenuineIntel" or "AuthenticAMD" for x86_64 architectures, * or the name of the CPU implementer for ARM architectures. * * @thread_safety This call is thread safe. */ virtual const char* getVendor_abi(size_t cpuIndex) noexcept = 0; /** Note: the mask may be 0 if out of range of 64 bits. */ /** Retrieves a bit mask for the processor cores in a CPU package in the system. * * @param[in] cpuIndex The zero based index of the CPU package to retrieve the identifier * for. This should be less than the return value of * ICpuInfo::getCpuPackageCount(). * @returns A mask identifying which CPU cores the given CPU covers. A set bit indicates * a core that belongs to the given CPU. A 0 bit indicates either a core from * another package or a non-existent core. This may also be 0 if more than 64 * cores are present in the system or they are out of range of a single 64-bit * value. * * @thread_safety This call is thread safe. */ virtual uint64_t getProcessorMask_abi(size_t cpuIndex) noexcept = 0; }; } // namespace platforminfo } // namespace omni #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "ICpuInfo.gen.h" /** @copydoc omni::platforminfo::ICpuInfo_abi */ class omni::platforminfo::ICpuInfo : public omni::core::Generated<omni::platforminfo::ICpuInfo_abi> { }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "ICpuInfo.gen.h"
omniverse-code/kit/include/omni/platforminfo/IMemoryInfo.h
// Copyright (c) 2021-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. // /** @file * @brief Helper interface to retrieve memory info. */ #pragma once #include "../core/IObject.h" namespace omni { /** Platform and operating system info namespace. */ namespace platforminfo { /** Forward declaration of the IMemoryInfo API object. */ class IMemoryInfo; /** Interface to collect and retrieve information about memory installed in the system. */ class IMemoryInfo_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.platforminfo.IMemoryInfo")> { protected: /** Retrieves the total installed physical RAM in the system. * * @returns The number of bytes of physical RAM installed in the system. This value will * not change during the lifetime of the calling process. * * @thread_safety This call is thread safe. */ virtual size_t getTotalPhysicalMemory_abi() noexcept = 0; /** Retrieves the available physical memory in the system. * * @returns The number of bytes of physical RAM that is currently available for use by the * operating system. Note that this is not a measure of how much memory is * available to the calling process, but rather for the entire system. * * @thread_safety This call is thread safe. However, two consecutive or concurrent calls * are unlikely to return the same value. */ virtual size_t getAvailablePhysicalMemory_abi() noexcept = 0; /** Retrieves the total page file space in the system. * * @returns The number of bytes of page file space in the system. The value will not * change during the lifetime of the calling process. * * @thread_safety This call is thread safe. */ virtual size_t getTotalPageFileMemory_abi() noexcept = 0; /** Retrieves the available page file space in the system. * * @returns The number of bytes of page file space that is currently available for use * by the operating system. * * @thread_safety This call is thread safe. However, two consecutive or concurrent calls * are unlikely to return the same value. */ virtual size_t getAvailablePageFileMemory_abi() noexcept = 0; /** Retrieves the total memory usage for the calling process. * * @returns The number of bytes of memory used by the calling process. This will not * necessarily be the amount of the process's virtual memory space that is * currently in use, but rather the amount of memory that the OS currently * has wired for this process (ie: the process's working set memory). It is * possible that the process could have a lot more memory allocated, just * inactive as far as the OS is concerned. * * @thread_safety This call is thread safe. However, two consecutive calls are unlikely * to return the same value. */ virtual size_t getProcessMemoryUsage_abi() noexcept = 0; /** Retrieves the peak memory usage of the calling process. * * @returns The maximum number of bytes of memory used by the calling process. This will * not necessarily be the maximum amount of the process's virtual memory space that * was ever allocated, but rather the maximum amount of memory that the OS ever had * wired for the process (ie: the process's working set memory). It is possible * that the process could have had a lot more memory allocated, just inactive as * far as the OS is concerned. */ virtual size_t getProcessPeakMemoryUsage_abi() noexcept = 0; }; } // namespace platforminfo } // namespace omni #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "IMemoryInfo.gen.h" /** @copydoc omni::platforminfo::IMemoryInfo_abi */ class omni::platforminfo::IMemoryInfo : public omni::core::Generated<omni::platforminfo::IMemoryInfo_abi> { }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "IMemoryInfo.gen.h"
omniverse-code/kit/include/omni/platforminfo/IOsInfo2.gen.h
// 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. // // --------- Warning: This is a build system generated file. ---------- // //! @file //! //! @brief This file was generated by <i>omni.bind</i>. #include <omni/core/OmniAttr.h> #include <omni/core/Interface.h> #include <omni/core/ResultError.h> #include <functional> #include <utility> #include <type_traits> #ifndef OMNI_BIND_INCLUDE_INTERFACE_IMPL /** Extended interface to collect and retrieve more information about the operating system. * This inherits from omni::platforminfo::IOsInfo and also provides all of its functionality. */ template <> class omni::core::Generated<omni::platforminfo::IOsInfo2_abi> : public omni::platforminfo::IOsInfo2_abi { public: OMNI_PLUGIN_INTERFACE("omni::platforminfo::IOsInfo2") /** [Windows] Tests whether this process is running under compatibility mode. * * @returns `true` if this process is running in compatibility mode for an older version * of Windows. Returns `false` otherwise. Returns `false` on all non-Windows * platforms. * * @remarks Windows 10 and up allow a way for apps to run in 'compatibility mode'. This * causes many of the OS version functions to return values that represent an * older version of windows (ie: Win8.1 and earlier) instead of the actual version * information. This can allow some apps that don't fully support Win10 and up to * start properly. */ bool isCompatibilityModeEnabled() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline bool omni::core::Generated<omni::platforminfo::IOsInfo2_abi>::isCompatibilityModeEnabled() noexcept { return isCompatibilityModeEnabled_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
omniverse-code/kit/include/omni/platforminfo/IDisplayInfo.h
// Copyright (c) 2021-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. // /** @file * @brief Helper interface to retrieve display info. */ #pragma once #include "../../carb/Types.h" #include "../core/IObject.h" namespace omni { /** Platform and operating system info namespace. */ namespace platforminfo { /** Forward declaration of the IDisplayInfo API object. */ class IDisplayInfo; /** Base type for the display information flags. These flags all start with @a fDisplayFlag*. */ using DisplayFlags OMNI_ATTR("flag, prefix=fDisplayFlag") = uint32_t; /** Flag that indicates that the display is the primary one in the system. * * This often means that new windows will open on this display by default or that the main * system menu (ie: Windows' task bar, Linux's or Mac OS's menu bar, etc) will appear on. */ constexpr DisplayFlags fDisplayFlagPrimary = 0x01; /** Base type for the display mode information flags. These flags all start with @a fModeFlag*. */ using ModeFlags OMNI_ATTR("flag, prefix=fModeFlag") = uint32_t; /** Flag to indicate that the screen mode is interlaced. * * An interlaced display will render every other line of the image alternating between even * and odd scanlines each frame. This can result in less flicker at the same refresh rate * as a non-interlaced display, or less data transmission required per frame at a lower * refresh rate. */ constexpr ModeFlags fModeFlagInterlaced = 0x01; /** Flag to indicate that this mode will be stretched. * * When this flag is present, it indicates that the given display mode will be stretched to * to fill the display if it is not natively supported by the hardware. This may result in * scaling artifacts depending on the amount of stretching that is done. */ constexpr ModeFlags fModeFlagStretched = 0x02; /** Flag to indicate that this mode will be centered on the display. * * When this flag is present, it indicates that the given display mode will be centered * on the display if it is not natively supported by the hardware. This will result in * blank bars being used around the edges of the display to fill in unused space. */ constexpr ModeFlags fModeFlagCentered = 0x04; /** Base type for a display mode index. */ using ModeIndex OMNI_ATTR("constant, prefix=kModeIndex") = size_t; /** Special mode index value to get the information for a display's current mode. * * This is accepted by IDisplayInfo::getModeInfo() in the @a modeIndex parameter. */ constexpr ModeIndex kModeIndexCurrent = (ModeIndex)~0ull; /** Possible display orientation names. * * These indicate how the screen is rotated from its native default orientation. The rotation * angle is considered in a clockwise direction. */ enum class OMNI_ATTR("prefix=e") Orientation { eDefault, ///< The natural display orientation for the display. e90, ///< The image is rotated 90 degrees clockwise. e180, ///< The image is rotated 180 degrees clockwise. e270, ///< The image is rotated 270 degrees clockwise. }; /** Contains information about a single display mode. This includes the mode's size in pixels, * bit depth, refresh rate, and orientation. */ struct ModeInfo { carb::Int2 size = {}; ///< Horizontal (x) and vertical (y) size of the screen in pixels. uint32_t bitsPerPixel = 0; ///< Pixel bit depth. Many modern systems will only report 32 bits. uint32_t refreshRate = 0; ///< The refresh rate of the display in Hertz or zero if not applicable. ModeFlags flags = 0; ///< Flags describing the state of the mode. Orientation orientation = Orientation::eDefault; ///< The orientation of the mode. }; /** Contains information about a single display device. This includes the name of the display, * the adapter it is connected to, the virtual coordinates on the desktop where the display's * image maps to, and the current display mode information. */ struct DisplayInfo { /** The name of the display device. This typically maps to a monitor, laptop screen, or other * pixel display device. This name should be suitable for display to a user. */ char OMNI_ATTR("c_str") displayName[128] = {}; /** The system specific identifier of the display device. This is suitable for using with * other platform specific APIs that accept a display device name. */ char OMNI_ATTR("c_str") displayId[128] = {}; /** The name of the graphics adapter the display is connected to. Typically this is the * name of the GPU or other graphics device that the display is connected to. This name * should be suitable for display to a user. */ char OMNI_ATTR("c_str") adapterName[128] = {}; /** The system specific identifier of the graphics adapter device. This is suitable for using * with other platform specific APIs that accept a graphics adapter name. */ char OMNI_ATTR("c_str") adapterId[128] = {}; /** The coordinates of the origin of this display device on the desktop's virtual screen. * In situations where there is only a single display, this will always be (0, 0). It will * be in non-mirrored multi-display setups that this can be used to determine how each * display's viewport is positioned relative to each other. */ carb::Int2 origin = {}; /** The current display mode in use on the display. */ ModeInfo current = {}; /** Flags to indicate additional information about this display. */ DisplayFlags flags = 0; }; /** Interface to collect and retrieve information about displays attached to the system. Each * display is a viewport onto the desktop's virtual screen space and has an origin and size. * Most displays are capable of switching between several modes. A mode is a combination of * a viewport resolution (width, height, and color depth), and refresh rate. Display info * may be collected using this interface, but it does not handle making changes to the current * mode for any given display. */ class IDisplayInfo_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.platforminfo.IDisplayInfo")> { protected: /** Retrieves the total number of displays connected to the system. * * @returns The total number of displays connected to the system. This typically includes * displays that are currently turned off. Note that the return value here is * volatile and may change at any point due to user action (either in the OS or * by unplugging or connecting a display). This value should not be cached for * extended periods of time. * * @thread_safety This call is thread safe. */ virtual size_t getDisplayCount_abi() noexcept = 0; /** Retrieves information about a single connected display. * * @param[in] displayIndex The zero based index of the display to retrieve the information * for. This call will fail if the index is out of the range of * the number of connected displays, thus it is not necessary to * IDisplayInfo::getDisplayCount() to enumerate display information * in a counted loop. * @param[out] infoOut Receives the information for the requested display. This may * not be `nullptr`. This returned information may change at any * time due to user action and should therefore not be cached. * @returns `true` if the information for the requested display is successfully retrieved. * Returns `false` if the @p displayIndex index was out of the range of connected * display devices or the information could not be retrieved for any reason. * * @thread_safety This call is thread safe. */ virtual bool getDisplayInfo_abi(size_t displayIndex, OMNI_ATTR("out, not_null") DisplayInfo* infoOut) noexcept = 0; /** Retrieves the total number of display modes for a given display. * * @param[in] display The display to retrieve the mode count for. This may not be * `nullptr`. This must have been retrieved from a recent call to * IDisplayInfo::getDisplayInfo(). * @returns The total number of display modes supported by the requested display. Returns * 0 if the mode count information could not be retrieved. A connected valid * display will always support at least one mode. * * @thread_safety This call is thread safe. */ virtual size_t getModeCount_abi(OMNI_ATTR("in, not_null") const DisplayInfo* display) noexcept = 0; /** Retrieves the information for a single display mode for a given display. * * @param[in] display The display to retrieve the mode count for. This may not be * `nullptr`. This must have been retrieved from a recent call to * IDisplayInfo::getDisplayInfo(). * @param[in] modeIndex The zero based index of the mode to retrieve for the given * display. This make also be @ref kModeIndexCurrent to retrieve the * information for the given display's current mode. This call will * simply fail if this index is out of range of the number of modes * supported by the given display, thus it is not necessary to call * IDisplayInfo::getModeCount() to use in a counted loop. * @param[out] infoOut Receives the information for the requested mode of the given * display. This may not be `nullptr`. * @returns `true` if the information for the requested mode is successfully retrieved. * Returns `false` if the given index was out of range of the number of modes * supported by the given display or the mode's information could not be retrieved * for any reason. * * @thread_safety This call is thread safe. */ virtual bool getModeInfo_abi(OMNI_ATTR("in, not_null") const DisplayInfo* display, ModeIndex modeIndex, OMNI_ATTR("out, not_null") ModeInfo* infoOut) noexcept = 0; /** Retrieves the total virtual screen size that all connected displays cover. * * @param[out] origin Receives the coordinates of the origin of the rectangle that the * virtual screen covers. This may be `nullptr` if the origin point * is not needed. * @param[out] size Receives the width and height of the rectangle that the virtual * screen covers. This may be `nullptr` if the size is not needed. * @returns `true` if either the origin, size, or both origin and size of the virtual * screen are retrieved successfully. Returns `false` if the size of the virtual * screen could not be retrieved or both @p origin and @p size are `nullptr`. * * @remarks This retrieves the total virtual screen size for the system. This is the * union of the rectangles that all connected displays cover. Note that this * will also include any empty space between or around displays that is not * covered by another display. * * @thread_safety This call is thread safe. */ virtual bool getTotalDisplaySize_abi(OMNI_ATTR("out") carb::Int2* origin, OMNI_ATTR("out") carb::Int2* size) noexcept = 0; }; } // namespace platforminfo } // namespace omni #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "IDisplayInfo.gen.h" /** @copydoc omni::platforminfo::IDisplayInfo_abi */ class omni::platforminfo::IDisplayInfo : public omni::core::Generated<omni::platforminfo::IDisplayInfo_abi> { }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "IDisplayInfo.gen.h"
omniverse-code/kit/include/omni/resourcemonitor/ResourceMonitorSettings.h
// 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. // #pragma once #include <omni/kit/SettingsUtils.h> #define RESOURCE_MONITOR_SETTING_GROUP_CONTEXT "resourcemonitor" #define RESOURCE_MONITOR_SETTING_TIME_BETWEEN_QUERIES "timeBetweenQueries" #define RESOURCE_MONITOR_SETTING_SEND_DEVICE_MEMORY_WARNING "sendDeviceMemoryWarning" #define RESOURCE_MONITOR_SETTING_DEVICE_MEMORY_WARN_MB "deviceMemoryWarnMB" #define RESOURCE_MONITOR_SETTING_DEVICE_MEMORY_WARN_FRACTION "deviceMemoryWarnFraction" #define RESOURCE_MONITOR_SETTING_SEND_HOST_MEMORY_WARNING "sendHostMemoryWarning" #define RESOURCE_MONITOR_SETTING_HOST_MEMORY_WARN_MB "hostMemoryWarnMB" #define RESOURCE_MONITOR_SETTING_HOST_MEMORY_WARN_FRACTION "hostMemoryWarnFraction" namespace omni { namespace resourcemonitor { constexpr const char* const kSettingTimeBetweenQueries = PERSISTENT_SETTINGS_PREFIX SETTING_SEP RESOURCE_MONITOR_SETTING_GROUP_CONTEXT SETTING_SEP \ RESOURCE_MONITOR_SETTING_TIME_BETWEEN_QUERIES; constexpr const char* const kSettingSendDeviceMemoryWarning = PERSISTENT_SETTINGS_PREFIX SETTING_SEP RESOURCE_MONITOR_SETTING_GROUP_CONTEXT SETTING_SEP \ RESOURCE_MONITOR_SETTING_SEND_DEVICE_MEMORY_WARNING; constexpr const char* const kSettingDeviceMemoryWarnMB = PERSISTENT_SETTINGS_PREFIX SETTING_SEP RESOURCE_MONITOR_SETTING_GROUP_CONTEXT SETTING_SEP \ RESOURCE_MONITOR_SETTING_DEVICE_MEMORY_WARN_MB; constexpr const char* const kSettingDeviceMemoryWarnFraction = PERSISTENT_SETTINGS_PREFIX SETTING_SEP RESOURCE_MONITOR_SETTING_GROUP_CONTEXT SETTING_SEP \ RESOURCE_MONITOR_SETTING_DEVICE_MEMORY_WARN_FRACTION; constexpr const char* const kSettingSendHostMemoryWarning = PERSISTENT_SETTINGS_PREFIX SETTING_SEP RESOURCE_MONITOR_SETTING_GROUP_CONTEXT SETTING_SEP \ RESOURCE_MONITOR_SETTING_SEND_HOST_MEMORY_WARNING; constexpr const char* const kSettingHostMemoryWarnMB = PERSISTENT_SETTINGS_PREFIX SETTING_SEP RESOURCE_MONITOR_SETTING_GROUP_CONTEXT SETTING_SEP \ RESOURCE_MONITOR_SETTING_HOST_MEMORY_WARN_MB; constexpr const char* const kSettingHostMemoryWarnFraction = PERSISTENT_SETTINGS_PREFIX SETTING_SEP RESOURCE_MONITOR_SETTING_GROUP_CONTEXT SETTING_SEP \ RESOURCE_MONITOR_SETTING_HOST_MEMORY_WARN_FRACTION; } }
omniverse-code/kit/include/omni/resourcemonitor/ResourceMonitorTypes.h
// 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. // #pragma once namespace omni { namespace resourcemonitor { enum class ResourceMonitorEventType { eUpdateDeviceMemory, ///! ResourceMonitor has updated information about device memory eUpdateHostMemory, ///! ResourceMonitor has updated information about host memory eLowDeviceMemory, ///! A device's memory has fallen below a specified threshold eLowHostMemory, ///! Host's memory has fallen below a specified threshold }; } }
omniverse-code/kit/include/omni/resourcemonitor/IResourceMonitor.h
// 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. // #pragma once #include <carb/Defines.h> #include <carb/events/IEvents.h> #include <carb/Types.h> namespace omni { namespace resourcemonitor { /** * This interface wraps the wraps the memory queries of the graphics and * GpuFoundation APIs. Clients can subscribe to the resource monitor's * event stream to be notified when memory resources fall below user-specified * thresholds. */ struct IResourceMonitor { CARB_PLUGIN_INTERFACE("omni::resourcemonitor::IResourceMonitor", 1, 0) /** * Call into GpuFoundation's SystemInfo interface and returns available main memory * * @return available main memory (in bytes) */ uint64_t(CARB_ABI* getAvailableHostMemory)(); /** * Call into GpuFoundation's SystemInfo interface and returns total main memory * * @return total main memory (in bytes) */ uint64_t(CARB_ABI* getTotalHostMemory)(); /** * Call into the Graphics API and returns available GPU memory for the * specified device. * * @param deviceIndex Index of the device to query. * * @return available GPU memory for the specified device (in bytes) */ uint64_t(CARB_ABI* getAvailableDeviceMemory)(uint32_t deviceIndex); /** * Call into the Graphics API and returns total GPU memory for the * specified device. * * @param deviceIndex Index of the device to query. * * @return total GPU memory for the specified device (in bytes) */ uint64_t(CARB_ABI* getTotalDeviceMemory)(uint32_t deviceIndex); /** * Get the resource monitor's event stream in order to subscribe to * updates and warnings. * * @return Pointer to resource monitor's event stream */ carb::events::IEventStream*(CARB_ABI* getEventStream)(); }; } // namespace resourcemonitor } // namespace omni
omniverse-code/kit/include/omni/ui/IntField.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "AbstractField.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The IntField widget is a one-line text editor with a string model. */ class OMNIUI_CLASS_API IntField : public AbstractField { OMNIUI_OBJECT(IntField) protected: /** * @brief Construct IntField */ OMNIUI_API IntField(const std::shared_ptr<AbstractValueModel>& model = {}); private: /** * @brief It's necessary to implement it to convert model to string buffer that is displayed by the field. It's * possible to use it for setting the string format. */ std::string _generateTextForField() override; /** * @brief Set/get the field data and the state on a very low level of the underlying system. */ void _updateSystemText(void*) override; /** * @brief Determines the flags that are used in the underlying system widget. */ int32_t _getSystemFlags() const override; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/TreeView.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "ItemModelHelper.h" #include <memory> OMNIUI_NAMESPACE_OPEN_SCOPE class AbstractItemModel; class AbstractItemDelegate; /** * @brief TreeView is a widget that presents a hierarchical view of information. Each item can have a number of subitems. * An indentation often visualizes this in a list. An item can be expanded to reveal subitems, if any exist, and * collapsed to hide subitems. * * TreeView can be used in file manager applications, where it allows the user to navigate the file system directories. * They are also used to present hierarchical data, such as the scene object hierarchy. * * TreeView uses a model/view pattern to manage the relationship between data and the way it is presented. The * separation of functionality gives developers greater flexibility to customize the presentation of items and provides * a standard interface to allow a wide range of data sources to be used with other widgets. * * TreeView is responsible for the presentation of model data to the user and processing user input. To allow some * flexibility in the way the data is presented, the creation of the sub-widgets is performed by the delegate. It * provides the ability to customize any sub-item of TreeView. */ class OMNIUI_CLASS_API TreeView : public Widget, public ItemModelHelper { OMNIUI_OBJECT(TreeView) public: OMNIUI_API ~TreeView() override; /** * @brief Reimplemented the method to indicate the width hint that represents the preferred size of the widget. * * @see Widget::setComputedContentWidth */ OMNIUI_API void setComputedContentWidth(float width) override; /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentHeight(float height) override; /** * @brief Reimplemented the method from ItemModelHelper that is called when the model is changed. * * @param item The item in the model that is changed. If it's NULL, the root is chaged. */ OMNIUI_API void onModelUpdated(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item) override; /** * @brief Deselects all selected items. */ OMNIUI_API void clearSelection(); /** * @brief Set current selection. */ OMNIUI_API void setSelection(std::vector<std::shared_ptr<const AbstractItemModel::AbstractItem>> items); /** * @brief Switches the selection state of the given item. */ OMNIUI_API void toggleSelection(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item); /** * @brief Extends the current selection selecting all the items between currently selected nodes and the given item. * It's when user does shift+click. */ OMNIUI_API void extendSelection(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item); /** * @brief Return the list of selected items. */ OMNIUI_API const std::vector<std::shared_ptr<const AbstractItemModel::AbstractItem>>& getSelection(); /** * @brief Set the callback that is called when the selection is changed. */ OMNIUI_CALLBACK(SelectionChanged, void, std::vector<std::shared_ptr<const AbstractItemModel::AbstractItem>>); /** * @brief Sets the function that will be called when the user use mouse enter/leave on the item. * function specification is the same as in setItemHovedFn. * void onItemHovered(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item, bool hovered) */ OMNIUI_CALLBACK(HoverChanged, void, std::shared_ptr<const AbstractItemModel::AbstractItem>, bool); /** * @brief Returns true if the given item is expanded. */ OMNIUI_API bool isExpanded(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item); /** * @brief Sets the given item expanded or collapsed. * * @param item The item to expand or collapse. * @param expanded True if it's necessary to expand, false to collapse. * @param recursive True if it's necessary to expand children. */ OMNIUI_API void setExpanded(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item, bool expanded, bool recursive); /** * @brief When called, it will make the delegate to regenerate all visible widgets the next frame. */ OMNIUI_API void dirtyWidgets(); /** * @brief The Item delegate that generates a widget per item. */ OMNIUI_PROPERTY(std::shared_ptr<AbstractItemDelegate>, delegate, WRITE, setDelegate, PROTECTED, READ, getDelegate, NOTIFY, setDelegateChangedFn); /** * @brief Widths of the columns. If not set, the width is Fraction(1). */ OMNIUI_PROPERTY(std::vector<Length>, columnWidths, READ, getColumnWidths, WRITE, setColumnWidths); /** * @brief When true, the columns can be resized with the mouse. */ OMNIUI_PROPERTY(bool, columnsResizable, DEFAULT, false, READ, isColumnsResizable, WRITE, setColumnsResizable); /** * @brief This property holds if the header is shown or not. */ OMNIUI_PROPERTY(bool, headerVisible, DEFAULT, false, READ, isHeaderVisible, WRITE, setHeaderVisible); /** * @brief This property holds if the root is shown. It can be used to make a single level tree appear like a simple * list. */ OMNIUI_PROPERTY( bool, rootVisible, DEFAULT, true, READ, isRootVisible, WRITE, setRootVisible, NOTIFY, setRootVisibleChangedFn); /** * @brief This flag allows to prevent expanding when the user clicks the plus icon. It's used in the case the user * wants to control how the items expanded or collapsed. */ OMNIUI_PROPERTY(bool, expandOnBranchClick, DEFAULT, true, READ, isExpandOnBranchClick, WRITE, setExpandOnBranchClick); /** * @brief When true, the tree nodes are never destroyed even if they are disappeared from the model. It's useul for * the temporary filtering if it's necessary to display thousands of nodes. */ OMNIUI_PROPERTY(bool, keepAlive, DEFAULT, false, READ, isKeepAlive, WRITE, setKeepAlive); /** * @brief Expand all the nodes and keep them expanded regardless their state. */ OMNIUI_PROPERTY( bool, keepExpanded, DEFAULT, false, READ, isKeepExpanded, WRITE, setKeepExpanded, NOTIFY, setKeepExpandedChangedFn); /** * @brief When true, the tree nodes can be dropped between items. */ OMNIUI_PROPERTY(bool, dropBetweenItems, DEFAULT, false, READ, isDropBetweenItems, WRITE, setDropBetweenItems); /** * @brief The expanded state of the root item. Changing this flag doesn't make the children repopulated. */ OMNIUI_PROPERTY(bool, rootExpanded, DEFAULT, true, READ, isRootExpanded, WRITE, setRootExpanded, PROTECTED, NOTIFY, _setRootExpandedChangedFn); /** * @brief Minimum widths of the columns. If not set, the minimum width is Pixel(0). */ OMNIUI_PROPERTY(std::vector<Length>, minColumnWidths, READ, getMinColumnWidths, WRITE, setMinColumnWidths); protected: /** * @brief Create TreeView with the given model. * * @param model The given model. */ OMNIUI_API TreeView(const std::shared_ptr<AbstractItemModel>& model = {}); /** * @brief Reimplemented the rendering code of the widget. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; private: friend class Inspector; /** * @brief The location of Drag and Drop. * * Specifies where exactly the user droped the item. */ enum class DropLocation : uint8_t { eOver = 0, eAbove, eBelow, eUndefined, }; struct Node { // Child nodes std::vector<std::unique_ptr<Node>> children; // Root level widget per column std::vector<std::shared_ptr<Widget>> widgets; // Branch + widget the user created in the delegate for the inspector std::vector<std::pair<std::shared_ptr<Widget>, std::shared_ptr<Widget>>> widgetsForInspector; // The state of the node. If it's false, then it's necessary to skip all the children. bool expanded = false; // True if it already has correct children. bool childrenPopulated = false; // True if it already has correct widgets. Not populated means it will be reconstructed the next frame. bool widgetsPopulated = false; // Dirty means it it will be reconstructed only if it's visible. bool widgetsDirty = false; // The corresponding item in the model. std::shared_ptr<const AbstractItemModel::AbstractItem> item = nullptr; // The indentation level uint32_t level = 0; // Selection state bool selected = false; // Flag if the widget size was already comuted and it doesn't require to be computed more. We need it to be able // to compute the size only of visible widgets. // This is the flag for _setNodeComputedWidth/_setNodeComputedHeight bool widthComputed = false; bool heightComputed = false; // Cached size of widgets float nodeHeight = 0.0f; // Cached position of widgets float positionOffset = 0.0f; // Indicates that the user drags this node bool dragInProgress = false; // True when the mouse already entered the drag and drop zone of this node and dropAccepted has the valid value. DropLocation dragEntered = DropLocation::eUndefined; // True if the current drag and drop can be accepted by the current model. bool dropAccepted = false; // When keepAlive is true, the nodes are never removed. Instead or removing, TreeView makes active = false and // such nodes are not drawing. bool active = true; // True if mouse hover on this node bool hovered = false; }; /** * @brief Populate the children of the given node. Usually, it's called when the user presses the expand button the * first time. */ void _populateNodeChildren(TreeView::Node* node); /** * @brief Calls _populateNodeChildren in every expanded node. Usually, _populateNodeChildren is called in a draw * cycle. But sometimes it's necessary to call it immediately for example when the model is changed and draw cycle * didn't happen yet. */ void _populateNodeChildrenRecursive(TreeView::Node* node); /** * @brief Populate the widgets of the given node. It's called when the user presses the expand button the first time * and when the node is expanded or collapsed. */ void _populateNodeWidget(TreeView::Node* node); /** * @brief It's only used in Inspector to make sure all the widgets prepopulated */ void _populateNodeWidgetsRecursive(TreeView::Node* node); /** * @brief Populate the widgets of the header. */ void _populateHeader(); /** * @brief Compute width of the header widgets. */ void _setHeaderComputedWidth(); /** * @brief Compute height of the header widgets. */ void _setHeaderComputedHeight(); /** * @brief Recursively draw the widgets of the given node. */ float _drawNodeInTable(const std::unique_ptr<Node>& node, const std::unique_ptr<Node>& parent, uint32_t hoveringColor, uint32_t hoveringBorderColor, uint32_t backgroundColor, uint32_t dropIndicatorColor, uint32_t dropIndicatorBorderColor, float dropIndicatorThickness, float cursorAtBeginTableX, float cursorAtBeginTableY, float currentOffset, bool blockMouse, float elapsedTime); /** * @brief Set computed width of the node and its children. */ void _setNodeComputedWidth(const std::unique_ptr<Node>& node); /** * @brief Set computed height of the node and its children. */ bool _setNodeComputedHeight(const std::unique_ptr<Node>& node, float& offset); /** * @brief Fills m_columnComputedSizes with absolute widths using property columnWidths. */ float _computeColumnWidths(float width); /** * @brief Return the node that corresponds to the given model item. * * This is the internal function that shouldn't be called from outside because it's not guaranteed that the returned * object is valid for the next draw call. */ Node* _getNode(const std::unique_ptr<TreeView::Node>& node, const std::shared_ptr<const AbstractItemModel::AbstractItem>& item) const; /** * @brief Return the node that corresponds to the given model item. * * This is the internal function that shouldn't be called from outside because it's not guaranteed that the returned * object is valid for the next draw call. */ Node* _getNode(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item) const; /** * @brief Fills gived list with the flat list of the nodes. Only expanded nodes are considered. * * @param root The node to start the flat list from. * @param list The list where the noreds are written. */ void _createFlatNodeList(std::unique_ptr<TreeView::Node>& root, std::vector<std::unique_ptr<Node>*>& list) const; /** * @brief Deselects the given node and the children. */ static void _clearNodeSelection(std::unique_ptr<TreeView::Node>& node); /** * @brief Called by TreeView when the selection is changed. It calls callbacks if they exist. */ void _onSelectionChanged(); /** * @brief It is called every frame to check if it's necessary to draw Drag And Drop highlight. Returns true if the * node needs highlight. */ bool _hasAcceptedDrop(const std::unique_ptr<TreeView::Node>& node, const std::unique_ptr<TreeView::Node>& parent, DropLocation dropLocation) const; /** * @brief This function converts the flat drop location (above-below-over) on the table to the tree's location. * * When the user drops an item, he drops it between rows. And we need to know the child index that corresponds to * the parent into which the new rows are inserted. * * @param node The node the user droped something. * @param parent The parent of the node the user droped it. * @param dropLocation Above-below-over position in the table. * @param dropNode Output. The parent node into which the new item should be inserted. * @param dropId Output. The index of child the new item should be inserted. If -1, the new item should be inseted * to the end. */ static void _getDropNode(const TreeView::Node* node, const TreeView::Node* parent, DropLocation dropLocation, TreeView::Node const** dropNode, int32_t& dropId); /** * @brief Sets the given node expanded or collapsed. It immidiatley populates children which is very useful when * doing search in the tree. * * @see TreeView::setExpanded */ void _setExpanded(TreeView::Node* node, bool expanded, bool recursive, bool pouplateChildren = true); /** * @brief Checks both the state of the node and the `keepExpanded` property. */ bool _isExpanded(TreeView::Node* node) const; /** * @brief Makes the widget and his children dirty. Dirty means that whe widget will be regenerated only if the node * is visible. */ void _setWidgetsDirty(TreeView::Node* node, bool dirty, bool recursive) const; /** * @brief Called when the user started dragging the node. It generates drag and drop buffers. */ void _beginDrag(TreeView::Node* node); /** * @brief Called when the user is dragging the node. It draws the widgets the user drags. */ void _drawDrag(float elapsedTime, uint32_t backgroundColor) const; /** * @brief Called when the user droped the node. It cleans up the drag and drop caches. It doesn't send anything to * the model because it's closing _beginDrag. And it will be called even if the user drops it somwhere else. The * code that sends the drop notification is in TreeView::_drawNodeInTable because it should accept drag and drop * from other widgets. */ void _endDrag() const; /** * @brief Calls drop with the model on the given node. * * @param node The node that accepted drop. */ void _dragDropTarget(TreeView::Node* node, TreeView::Node* parent) const; /** * @brief Called by Inspector to inspect all the children. */ std::vector<std::shared_ptr<Widget>> _getChildren(); std::vector<std::shared_ptr<const AbstractItemModel::AbstractItem>> _payloadToItems(const void* payload) const; // The main cache of this widget. It has everything that this widget draws including the hirarchy of the nodes and // the widgets they have. std::unique_ptr<Node> m_root; // Cache to quick query item node. std::unordered_map<const AbstractItemModel::AbstractItem*, Node*> m_itemNodeCache; // The cached number of columns. size_t m_columnsCount = 0; // Absolute widths of each column. std::vector<float> m_columnComputedSizes; // Absolute minimum widths of each column. std::vector<float> m_minColumnComputedSizes; // The list of the selected items. Vector because the selection order is important. std::vector<std::shared_ptr<const AbstractItemModel::AbstractItem>> m_selection; // Callback when the selection is changed std::function<void(std::vector<std::shared_ptr<const AbstractItemModel::AbstractItem>>)> m_selectionChangedFn; // Callback when item hover status is changed std::function<void(std::shared_ptr<const AbstractItemModel::AbstractItem>, bool)> m_hoverChangedFn; // Header widgets std::vector<std::shared_ptr<Frame>> m_headerWidgets; bool m_headerPopulated = false; // When the node is just selected, it used to scroll the tree view to the node. Node* m_scrollHere = nullptr; // Drag and drop caches. mutable std::unique_ptr<char[]> m_dragAndDropPayloadBuffer; mutable size_t m_dragAndDropPayloadBufferSize; mutable std::vector<const Node*> m_dragAndDropNodes; // False when internal Node structures are not synchronized with the model. Nodes are synchronized during the draw // loop. bool m_modelSynchronized = false; // Indicates that at least one node has heightComputed false bool m_contentHeightDirty = true; // Sum of all columns float m_contentWidth = 0.0f; // Height of internal content float m_contentHeight = 0.f; // Relative Y position of visible area float m_relativeRectMin = 0.f; float m_relativeRectMax = 0.f; // The variables to find the average of all the widgets created. We need it to assume the total length of the // TreeView without creating the widgets. float m_sumHeights = 0.f; uint64_t m_numHeights = 0; // If the column is resizing at this moment, it is the id of the right column. When 0, no resize happens. uint32_t m_resizeColumn = 0; // We need it for autoscrolling when drag and drop. Since ImGui rounds pixel, we can only scroll with int values, // and when FPS is very high, it doesn't scroll at all. We accumulate the small scrolling to this variable. float m_accumulatedAutoScroll = 0.0f; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/IntSlider.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "AbstractSlider.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The slider is the classic widget for controlling a bounded value. It lets the user move a slider handle along * a horizontal groove and translates the handle's position into an integer value within the legal range. */ template <typename T> class OMNIUI_CLASS_API CommonIntSlider : public AbstractSlider { public: /** * @brief Reimplemented the method from ValueModelHelper that is called when the model is changed. */ OMNIUI_API void onModelUpdated() override; /** * @brief This property holds the slider's minimum value. */ OMNIUI_PROPERTY(T, min, DEFAULT, 0, READ, getMin, WRITE, setMin); /** * @brief This property holds the slider's maximum value. */ OMNIUI_PROPERTY(T, max, DEFAULT, 100, READ, getMax, WRITE, setMax); protected: OMNIUI_API CommonIntSlider(const std::shared_ptr<AbstractValueModel>& model = {}); /** * @brief the ration calculation is requiere to draw the Widget as Gauge, it is calculated with Min/Max & Value */ virtual float _getValueRatio() override; private: /** * @brief Reimplemented. _drawContent sets everything up including styles and fonts and calls this method. */ void _drawUnderlyingItem() override; /** * @brief It has to run a very low level function to call the widget. */ virtual bool _drawUnderlyingItem(T* value, T min, T max) = 0; // The cached state of the slider. T m_valueCache; }; /** * @brief The slider is the classic widget for controlling a bounded value. It lets the user move a slider handle along * a horizontal groove and translates the handle's position into an integer value within the legal range. */ class OMNIUI_CLASS_API IntSlider : public CommonIntSlider<int64_t> { OMNIUI_OBJECT(IntSlider) protected: /** * @brief Constructs IntSlider * * @param model The widget's model. If the model is not assigned, the default model is created. */ OMNIUI_API IntSlider(const std::shared_ptr<AbstractValueModel>& model = {}) : CommonIntSlider<int64_t>{ model } { } private: /** * @brief Runs a very low level function to call the widget. */ OMNIUI_API virtual bool _drawUnderlyingItem(int64_t* value, int64_t min, int64_t max) override; }; /** * @brief The slider is the classic widget for controlling a bounded value. It lets the user move a slider handle along * a horizontal groove and translates the handle's position into an integer value within the legal range. * * The difference with IntSlider is that UIntSlider has unsigned min/max. */ class OMNIUI_CLASS_API UIntSlider : public CommonIntSlider<uint64_t> { OMNIUI_OBJECT(UIntSlider) protected: /** * @brief Constructs UIntSlider * * @param model The widget's model. If the model is not assigned, the default model is created. */ OMNIUI_API UIntSlider(const std::shared_ptr<AbstractValueModel>& model = {}) : CommonIntSlider<uint64_t>{ model } { } private: /** * @brief Runs a very low level function to call the widget. */ OMNIUI_API virtual bool _drawUnderlyingItem(uint64_t* value, uint64_t min, uint64_t max) override; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/Workspace.h
// Copyright (c) 2020-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. // //! @file //! //! @brief omni::ui Workspace #pragma once #include "Api.h" #include "WindowHandle.h" #include <functional> #include <memory> #include <stack> #include <vector> namespace omni { namespace kit { class IAppWindow; } } OMNIUI_NAMESPACE_OPEN_SCOPE namespace windowmanager { class IWindowCallback; } class WindowHandle; class Window; class ToolBar; /** * @brief Workspace object provides access to the windows in Kit. * * TODO: It's more like a namespace because all the methods are static. But the idea is to have it as a singleton, and * it will allow using it as the abstract factory for many systems (Kit full and Kit mini for example). */ class Workspace { public: class AppWindowGuard; /** * @brief Singleton that tracks the current application window. */ class AppWindow { public: OMNIUI_API static AppWindow& instance(); omni::kit::IAppWindow* getCurrent(); private: friend class AppWindowGuard; AppWindow() = default; ~AppWindow() = default; AppWindow(const AppWindow&) = delete; AppWindow& operator=(const AppWindow&) = delete; void push(omni::kit::IAppWindow* window); void pop(); std::stack<omni::kit::IAppWindow*> m_stack; }; /** * @brief Guard that pushes the current application window to class AppWindow when created and pops when destroyed. */ class AppWindowGuard { public: AppWindowGuard(omni::kit::IAppWindow* window); ~AppWindowGuard(); }; Workspace() = delete; /** * @brief Returns current DPI Scale. */ OMNIUI_API static float getDpiScale(); /** * @brief Returns the list of windows ordered from back to front. * * If the window is a Omni::UI window, it can be upcasted. */ OMNIUI_API static std::vector<std::shared_ptr<WindowHandle>> getWindows(); /** * @brief Find Window by name. */ OMNIUI_API static std::shared_ptr<WindowHandle> getWindow(const std::string& title); /** * @brief Find Window by window callback. */ OMNIUI_API static std::shared_ptr<WindowHandle> getWindowFromCallback(const windowmanager::IWindowCallback* callback); /** * @brief Get all the windows that docked with the given widow. */ OMNIUI_API static std::vector<std::shared_ptr<WindowHandle>> getDockedNeighbours(const std::shared_ptr<WindowHandle>& member); /** * @brief Get currently selected window inedx from the given dock id. */ OMNIUI_API static uint32_t getSelectedWindowIndex(uint32_t dockId); /** * @brief Undock all. */ OMNIUI_API static void clear(); /** * @brief Get the width in points of the current main window. */ OMNIUI_API static float getMainWindowWidth(); /** * @brief Get the height in points of the current main window. */ OMNIUI_API static float getMainWindowHeight(); /** * @brief Get all the windows of the given dock ID */ OMNIUI_API static std::vector<std::shared_ptr<WindowHandle>> getDockedWindows(uint32_t dockId); /** * @brief Return the parent Dock Node ID * * @param dockId the child Dock Node ID to get parent */ OMNIUI_API static uint32_t getParentDockId(uint32_t dockId); /** * @brief Get two dock children of the given dock ID. * * @return true if the given dock ID has children * @param dockId the given dock ID * @param first output. the first child dock ID * @param second output. the second child dock ID */ OMNIUI_API static bool getDockNodeChildrenId(uint32_t dockId, uint32_t& first, uint32_t& second); /** * @brief Returns the position of the given dock ID. Left/Right/Top/Bottom */ OMNIUI_API static WindowHandle::DockPosition getDockPosition(uint32_t dockId); /** * @brief Returns the width of the docking node. * * @param dockId the given dock ID */ OMNIUI_API static float getDockIdWidth(uint32_t dockId); /** * @brief Returns the height of the docking node. * * It's different from the window height because it considers dock tab bar. * * @param dockId the given dock ID */ OMNIUI_API static float getDockIdHeight(uint32_t dockId); /** * @brief Set the width of the dock node. * * It also sets the width of parent nodes if necessary and modifies the * width of siblings. * * @param dockId the given dock ID * @param width the given width */ OMNIUI_API static void setDockIdWidth(uint32_t dockId, float width); /** * @brief Set the height of the dock node. * * It also sets the height of parent nodes if necessary and modifies the * height of siblings. * * @param dockId the given dock ID * @param height the given height */ OMNIUI_API static void setDockIdHeight(uint32_t dockId, float height); /** * @brief Makes the window visible or create the window with the callback provided with set_show_window_fn. * * @return true if the window is already created, otherwise it's necessary to wait one frame * @param title the given window title * @param show true to show, false to hide */ OMNIUI_API static bool showWindow(const std::string& title, bool show = true); /** * @brief Addd the callback that is triggered when a new window is created */ OMNIUI_API static void setWindowCreatedCallback( std::function<void(const std::shared_ptr<WindowHandle>& window)> windowCreatedCallbackFn); /** * @brief Add the callback to create a window with the given title. When the callback's argument is true, it's * necessary to create the window. Otherwise remove. */ OMNIUI_API static void setShowWindowFn(const std::string& title, std::function<void(bool)> showWindowFn); /** * @brief Add the callback that is triggered when a window's visibility changed */ OMNIUI_API static uint32_t setWindowVisibilityChangedCallback(std::function<void(const std::string& title, bool visible)> windowVisibilityChangedCallbackFn); /** * @brief Remove the callback that is triggered when a window's visibility changed */ OMNIUI_API static void removeWindowVisibilityChangedCallback(uint32_t id); /** * @brief Call it from inside each windows' setVisibilityChangedFn to triggered VisibilityChangedCallback. */ OMNIUI_API static void onWindowVisibilityChanged(const std::string& title, bool visible); private: friend class Window; friend class ToolBar; /** * @brief Register Window, so it's possible to return it in getWindows. It's called by Window creator. */ OMNIUI_API static void RegisterWindow(const std::shared_ptr<Window>& window); /** * @brief Deregister window. It's called by Window destructor. */ OMNIUI_API static void OmitWindow(const Window* window); /** * @brief * */ static std::vector<std::shared_ptr<WindowHandle>> _getWindows(const void* windowsStorage, bool considerRegistered = false); }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/FloatDrag.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "FloatSlider.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The drag widget that looks like a field but it's possible to change the value with dragging. */ class OMNIUI_CLASS_API FloatDrag : public FloatSlider { OMNIUI_OBJECT(FloatDrag) protected: /** * @brief Construct FloatDrag */ OMNIUI_API FloatDrag(const std::shared_ptr<AbstractValueModel>& model = {}); private: /** * @brief Reimplemented. It has to run a very low level function to call the widget. */ virtual bool _drawUnderlyingItem(double* value, double min, double max) override; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/Label.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Alignment.h" #include "FontHelper.h" #include "Widget.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The Label widget provides a text to display. * * Label is used for displaying text. No additional to Widget user interaction functionality is provided. */ class OMNIUI_CLASS_API Label : public Widget, public FontHelper { OMNIUI_OBJECT(Label) public: OMNIUI_API ~Label() override; /** * @brief Reimplemented the method to indicate the width hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the size of the text. * * @see Widget::setComputedContentWidth */ OMNIUI_API void setComputedContentWidth(float width) override; /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the size of the text. * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentHeight(float height) override; /** * @brief Reimplemented. Something happened with the style or with the parent style. We need to update the saved * font. */ OMNIUI_API void onStyleUpdated() override; /** * @brief Return the exact width of the content of this label. Computed content width is a size hint and may be * bigger than the text in the label */ OMNIUI_API float exactContentWidth(); /** * @brief Return the exact height of the content of this label. Computed content height is a size hint and may be * bigger than the text in the label */ OMNIUI_API float exactContentHeight(); /** * @brief This property holds the label's text. */ OMNIUI_PROPERTY(std::string, text, READ, getText, WRITE, setText, NOTIFY, setTextChangedFn); /** * @brief This property holds the label's word-wrapping policy * If this property is true then label text is wrapped where necessary at word-breaks; otherwise it is not wrapped * at all. * By default, word wrap is disabled. */ OMNIUI_PROPERTY(bool, wordWrap, DEFAULT, false, READ, isWordWrap, WRITE, setWordWrap); /** * @brief When the text of a big length has to be displayed in a small area, it can be useful to give the user a * visual hint that not all text is visible. Label can elide text that doesn't fit in the area. When this property * is true, Label elides the middle of the last visible line and replaces it with "...". */ OMNIUI_PROPERTY(bool, elidedText, DEFAULT, false, READ, isElidedText, WRITE, setElidedText); /** * @brief Customized elidedText string when elidedText is True, default is "...". */ OMNIUI_PROPERTY(std::string, elidedTextStr, DEFAULT, "...", READ, getElidedTextStr, WRITE, setElidedTextStr); /** * @brief This property holds the alignment of the label's contents * By default, the contents of the label are left-aligned and vertically-centered. */ OMNIUI_PROPERTY(Alignment, alignment, DEFAULT, Alignment::eLeftCenter, READ, getAlignment, WRITE, setAlignment); /** * @brief Hide anything after a '##' string or not */ OMNIUI_PROPERTY(bool, hideTextAfterHash, DEFAULT, true, READ, isHideTextAfterHash, WRITE, setHideTextAfterHash); protected: /** * @brief Create a label with the given text. * * @param text The text for the label. */ OMNIUI_API Label(const std::string& text); /** * @brief Reimplemented the rendering code of the widget. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; private: /** * @brief Compute the size of the text and save result to the private members. * * @param width Is used for wrapping. If wrapping enabled, it has the maximum allowed text width. If there is no * wrapping, it's ignored. */ void _computeTextSize(float width); // Flag that the text size is computed. We need it because we don't want to compute the size each call of draw(). bool m_textMinimalSizeComputed = false; float m_textMinimalWidth; float m_textMinimalHeight; // We need it for multiline eliding. float m_lastAvailableHeight = 0.0f; // The pointer to the font that is used by this label. void* m_font = nullptr; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/Rectangle.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Shape.h" OMNIUI_NAMESPACE_OPEN_SCOPE struct RectangleStyleSnapshot; /** * @brief The Rectangle widget provides a colored rectangle to display. */ class OMNIUI_CLASS_API Rectangle : public Shape { OMNIUI_OBJECT(Rectangle) public: OMNIUI_API ~Rectangle() override; protected: /** * @brief Constructs Rectangle */ OMNIUI_API Rectangle(); /** * @brief Reimplemented the rendering code of the widget. */ OMNIUI_API void _drawShape(float elapsedTime, float x, float y, float width, float height) override; /** * @brief Reimplemented the draw shadow of the shape. */ OMNIUI_API void _drawShadow( float elapsedTime, float x, float y, float width, float height, uint32_t shadowColor, float dpiScale, ImVec2 shadowOffset, float shadowThickness, uint32_t shadowFlag) override; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/RadioButton.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Button.h" #include <functional> OMNIUI_NAMESPACE_OPEN_SCOPE class RadioCollection; /** * @brief RadioButton is the widget that allows the user to choose only one of a predefined set of mutually exclusive * options. * * RadioButtons are arranged in collections of two or more with the class RadioCollection, which is the central * component of the system and controls the behavior of all the RadioButtons in the collection. * * @see RadioCollection */ class OMNIUI_CLASS_API RadioButton : public Button { OMNIUI_OBJECT(RadioButton) public: OMNIUI_API ~RadioButton() override; /** * @brief This property holds the button's text. */ OMNIUI_PROPERTY(std::shared_ptr<RadioCollection>, radioCollection, READ, getRadioCollection, WRITE, setRadioCollection, NOTIFY, onRadioCollectionChangedFn); protected: /** * @brief Constructs RadioButton */ OMNIUI_API RadioButton(); private: /** * @brief Reimplemented from InvisibleButton. Called then the user clicks this button. We don't use `m_clickedFn` * because the user can set it. If we are using it in our internal code and the user overrides it, the behavior of * the button will be changed. */ OMNIUI_API void _clicked() override; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/AbstractItemModel.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Api.h" #include <functional> #include <memory> #include <string> #include <unordered_set> #include <vector> OMNIUI_NAMESPACE_OPEN_SCOPE class AbstractValueModel; class ItemModelHelper; /** * @brief The central component of the item widget. It is the application's dynamic data structure, independent of the * user interface, and it directly manages the nested data. It follows closely model-view pattern. It's abstract, and it * defines the standard interface to be able to interoperate with the components of the model-view architecture. It is * not supposed to be instantiated directly. Instead, the user should subclass it to create a new model. * * The overall architecture is described in the following drawing: * * \internal * * # Data is inside the model (cache) * # Data is outside the model (mirror) * |----------------------------| * |-------------------| * | AbstractItemModel | * | AbstractItemModel | * | |------- Data -------|| * | | |----- Data -----| * | | |- Item1 || <-- AbstractItem * | | -- AbstractItem -->| |- Item1 | * | | | |- SubItem1 || <-- AbstractItem * | | -- AbstractItem -->| | |- Sub1 | * | | | | |- SubSubItem1|| <-- AbstractItem * | | -- AbstractItem -->| | | |- SubSub1| * | | | | |- SubSubItem2|| <-- AbstractItem * | | -- AbstractItem -->| | | |- SubSub2| * | | | |- SubItem2 || <-- AbstractItem * | | -- AbstractItem -->| | |- Sub2 | * | | |- Item2 || <-- AbstractItem * | | -- AbstractItem -->| |- Item2 | * | | |- SubItem3 || <-- AbstractItem * | | -- AbstractItem -->| |- Sub3 | * | | |- SubItem4 || <-- AbstractItem * | | -- AbstractItem -->| |- Sub4 | * | |--------------------|| * | | |----------------| * |----------------------------| * |-------------------| * | * | * | * | * |----------------------------| * |----------------------------| * | ItemModelHelper | * | ItemModelHelper | * ||--------------------------|| * ||--------------------------|| * || Root || * || Root || * || |- World || * || |- World || * || | |- Charater || * || | |- Charater || * || | | |- Head || * || | | |- Head || * || | | |- Body || * || | | |- Body || * || | |- Sphere || * || | |- Sphere || * || |- Materials || * || |- Materials || * || |- GGX || * || |- GGX || * || |- GTR || * || |- GTR || * ||--------------------------|| * ||--------------------------|| * |----------------------------| * |----------------------------| * * \endinternal * * The item model doesn't return the data itself. Instead, it returns the value model that can contain any data type and * supports callbacks. Thus the client of the model can track the changes in both the item model and any value it holds. * * From any item, the item model can get both the value model and the nested items. Therefore, the model is flexible to * represent anything from color to complicated tree-table construction. * * TODO: We can see there is a lot of methods that are similar to the AbstractValueModel. We need to template them. */ class OMNIUI_CLASS_API AbstractItemModel { public: /** * @brief The object that is associated with the data entity of the AbstractItemModel. * * The item should be created and stored by the model implementation. And can contain any data in it. Another option * would be to use it as a raw pointer to the data. In any case it's the choice of the model how to manage this * class. */ class AbstractItem { public: virtual ~AbstractItem() = default; }; OMNIUI_API virtual ~AbstractItemModel(); // We assume that all the operations with the model should be performed with smart pointers because it will register // subscription. If the object is copied or moved, it will break the subscription. // No copy AbstractItemModel(const AbstractItemModel&) = delete; // No copy-assignment AbstractItemModel& operator=(const AbstractItemModel&) = delete; // No move constructor and no move-assignments are allowed because of 12.8 [class.copy]/9 and 12.8 [class.copy]/20 // of the C++ standard /** * @brief Returns the vector of items that are nested to the given parent item. * * @param id The item to request children from. If it's null, the children of root will be returned. */ OMNIUI_API virtual std::vector<std::shared_ptr<const AbstractItem>> getItemChildren( const std::shared_ptr<const AbstractItem>& parentItem = nullptr) = 0; /** * @brief Returns true if the item can have children. In this way the delegate usually draws +/- icon. * * @param id The item to request children from. If it's null, the children of root will be returned. */ OMNIUI_API virtual bool canItemHaveChildren(const std::shared_ptr<const AbstractItem>& parentItem = nullptr); /** * @brief Creates a new item from the value model and appends it to the list of the children of the given item. */ OMNIUI_API virtual std::shared_ptr<const AbstractItem> appendChildItem(const std::shared_ptr<const AbstractItem>& parentItem, std::shared_ptr<AbstractValueModel> model); /** * @brief Removes the item from the model. * * There is no parent here because we assume that the reimplemented model deals with its data and can figure out how * to remove this item. */ OMNIUI_API virtual void removeItem(const std::shared_ptr<const AbstractItem>& item); /** * @brief Returns the number of columns this model item contains. */ OMNIUI_API virtual size_t getItemValueModelCount(const std::shared_ptr<const AbstractItem>& item = nullptr) = 0; /** * @brief Get the value model associated with this item. * * @param item The item to request the value model from. If it's null, the root value model will be returned. * @param index The column number to get the value model. */ OMNIUI_API virtual std::shared_ptr<AbstractValueModel> getItemValueModel(const std::shared_ptr<const AbstractItem>& item = nullptr, size_t index = 0) = 0; /** * @brief Called when the user starts the editing. If it's a field, this method is called when the user activates * the field and places the cursor inside. */ OMNIUI_API virtual void beginEdit(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item); /** * @brief Called when the user finishes the editing. If it's a field, this method is called when the user presses * Enter or selects another field for editing. It's useful for undo/redo. */ OMNIUI_API virtual void endEdit(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item); /** * @brief Called to determine if the model can perform drag and drop to the given item. If this method returns * false, the widget shouldn't highlight the visual element that represents this item. */ OMNIUI_API virtual bool dropAccepted(const std::shared_ptr<const AbstractItem>& itemTarget, const std::shared_ptr<const AbstractItem>& itemSource, int32_t dropLocation = -1); /** * @brief Called to determine if the model can perform drag and drop of the given string to the given item. If this * method returns false, the widget shouldn't highlight the visual element that represents this item. */ OMNIUI_API virtual bool dropAccepted(const std::shared_ptr<const AbstractItem>& itemTarget, const char* source, int32_t dropLocation = -1); /** * @brief Called when the user droped one item to another. * * @note Small explanation why the same default value is declared in multiple places. We use the default value to be * compatible with the previous API and especially with Stage 2.0. Thr signature in the old Python API is: `def * drop(self, target_item, source)`. So when the user drops something over the item, we call 2-args `drop(self, * target_item, source)`, see `PyAbstractItemModel::drop`, and to call 2-args drop PyBind11 needs default value in * both here and Python implementation of `AbstractItemModel.drop`. W also set the default value in * `pybind11::class_<AbstractItemModel>.def("drop")` and PyBind11 uses it when the user calls the C++ binding of * AbstractItemModel from the python code. * * @see PyAbstractItemModel::drop */ OMNIUI_API virtual void drop(const std::shared_ptr<const AbstractItem>& itemTarget, const std::shared_ptr<const AbstractItem>& itemSource, int32_t dropLocation = -1); /** * @brief Called when the user droped a string to the item. */ OMNIUI_API virtual void drop(const std::shared_ptr<const AbstractItem>& itemTarget, const char* source, int32_t dropLocation = -1); /** * @brief Returns Multipurpose Internet Mail Extensions (MIME) for drag and drop. */ OMNIUI_API virtual std::string getDragMimeData(const std::shared_ptr<const AbstractItem>& item); /** * @brief Subscribe the ItemModelHelper widget to the changes of the model. * * We need to use regular pointers because we subscribe in the constructor of the widget and unsubscribe in the * destructor. In constructor smart pointers are not available. We also don't allow copy and move of the widget. * * TODO: It's similar to AbstractValueModel::subscribe, we can template it. */ OMNIUI_API void subscribe(ItemModelHelper* widget); /** * @brief Unsubscribe the ItemModelHelper widget from the changes of the model. * * TODO: It's similar to AbstractValueModel::unsubscribe, we can template it. */ OMNIUI_API void unsubscribe(ItemModelHelper* widget); /** * @brief Adds the function that will be called every time the value changes. * * @return The id of the callback that is used to remove the callback. * * TODO: It's similar to AbstractValueModel::addItemChangedFn, we can template it. */ OMNIUI_API uint32_t addItemChangedFn(std::function<void(const AbstractItemModel*, const AbstractItemModel::AbstractItem*)> fn); /** * @brief Remove the callback by its id. * * @param id The id that addValueChangedFn returns. * * TODO: It's similar to AbstractValueModel::removeItemChangedFn, we can template it. */ OMNIUI_API void removeItemChangedFn(uint32_t id); /** * @brief Adds the function that will be called every time the user starts the editing. * * @return The id of the callback that is used to remove the callback. */ OMNIUI_API uint32_t addBeginEditFn(std::function<void(const AbstractItemModel*, const AbstractItemModel::AbstractItem*)> fn); /** * @brief Remove the callback by its id. * * @param id The id that addBeginEditFn returns. */ OMNIUI_API void removeBeginEditFn(uint32_t id); /** * @brief Adds the function that will be called every time the user finishes the editing. * * @return The id of the callback that is used to remove the callback. */ OMNIUI_API uint32_t addEndEditFn(std::function<void(const AbstractItemModel*, const AbstractItemModel::AbstractItem*)> fn); /** * @brief Remove the callback by its id. * * @param id The id that addEndEditFn returns. */ OMNIUI_API void removeEndEditFn(uint32_t id); /** * @brief Called by the widget when the user starts editing. It calls beginEdit and the callbacks. */ OMNIUI_API void processBeginEditCallbacks(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item); /** * @brief Called by the widget when the user finishes editing. It calls endEdit and the callbacks. */ OMNIUI_API void processEndEditCallbacks(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item); protected: /** * @brief Constructs AbstractItemModel */ OMNIUI_API AbstractItemModel(); /** * @brief Called when any data of the model is changed. It will notify the subscribed widgets. * * @param item The item in the model that is changed. If it's NULL, the root is chaged. */ OMNIUI_API void _itemChanged(const std::shared_ptr<const AbstractItem>& item); // All the widgets who use this model. See description of subscribe for the information why it's regular pointers. // TODO: we can use m_callbacks for subscribe-unsubscribe. But in this way it's nesessary to keep widget-id map. // When the _valueChanged code will be more complicated, we need to do it. Now it's simple enought and m_widgets // stays here. std::unordered_set<ItemModelHelper*> m_widgets; // All the callbacks. std::vector<std::function<void(const AbstractItemModel*, const AbstractItemModel::AbstractItem*)>> m_itemChangedCallbacks; // Callbacks that called when the user starts the editing. std::vector<std::function<void(const AbstractItemModel*, const AbstractItemModel::AbstractItem*)>> m_beginEditCallbacks; // Callbacks that called when the user finishes the editing. std::vector<std::function<void(const AbstractItemModel*, const AbstractItemModel::AbstractItem*)>> m_endEditCallbacks; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/RasterHelper.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Api.h" #include "Callback.h" #include "Property.h" #include "RasterPolicy.h" OMNIUI_NAMESPACE_OPEN_SCOPE class Widget; struct RasterHelperPrivate; /** * @brief The "RasterHelper" class is used to manage the draw lists or raster * images. This class is responsible for rasterizing (or baking) the UI, which * involves adding information about widgets to the cache. Once the UI has been * baked, the draw list cache can be used to quickly re-render the UI without * having to iterate over the widgets again. This is useful because it allows * the UI to be rendered more efficiently, especially in cases where the widgets * have not changed since the last time the UI was rendered. The "RasterHelper" * class provides methods for modifying the cache and rendering the UI from the * cached information. */ class OMNIUI_CLASS_API RasterHelper : private CallbackHelper<RasterHelper> { public: OMNIUI_API virtual ~RasterHelper(); /** * @brief Determine how the content of the frame should be rasterized. */ OMNIUI_PROPERTY(RasterPolicy, rasterPolicy, DEFAULT, RasterPolicy::eNever, READ, getRasterPolicy, WRITE, setRasterPolicy, PROTECTED, NOTIFY, _setRasterPolicyChangedFn); /** * @brief This method regenerates the raster image of the widget, even if * the widget's content has not changed. This can be used with both the * eOnDemand and eAuto raster policies, and is used to update the content * displayed in the widget. Note that this operation may be * resource-intensive, and should be used sparingly. */ OMNIUI_API void invalidateRaster(); protected: friend class MenuDelegate; /** * @brief Constructor */ OMNIUI_API RasterHelper(); /** * @brief Should be called by the widget in init time. */ void _rasterHelperInit(Widget& widget); /** * @brief Should be called by the widget in destroy time. */ void _rasterHelperDestroy(); OMNIUI_API bool _rasterHelperBegin(float posX, float posY, float width, float height); OMNIUI_API void _rasterHelperEnd(); OMNIUI_API void _rasterHelperSetDirtyDrawList(); OMNIUI_API void _rasterHelperSetDirtyLod(); OMNIUI_API void _rasterHelperSuspendRasterization(bool stopRasterization); OMNIUI_API bool _isInRasterWindow() const; private: void _captureRaster(float originX, float originY); void _drawRaster(float originX, float originY) const; bool _isDirtyDrawList() const; std::unique_ptr<RasterHelperPrivate> m_prv; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/Api.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #ifdef _WIN32 # define OMNIUI_EXPORT __declspec(dllexport) # define OMNIUI_IMPORT __declspec(dllimport) # define OMNIUI_CLASS_EXPORT #else # define OMNIUI_EXPORT __attribute__((visibility("default"))) # define OMNIUI_IMPORT # define OMNIUI_CLASS_EXPORT __attribute__((visibility("default"))) #endif #if defined(OMNIUI_STATIC) # define OMNIUI_API # define OMNIUI_CLASS_API #else # if defined(OMNIUI_EXPORTS) # define OMNIUI_API OMNIUI_EXPORT # define OMNIUI_CLASS_API OMNIUI_CLASS_EXPORT # else # define OMNIUI_API OMNIUI_IMPORT # define OMNIUI_CLASS_API # endif #endif #define OMNIUI_NS omni::ui #define OMNIUI_NAMESPACE_USING_DIRECTIVE using namespace OMNIUI_NS; #define OMNIUI_NAMESPACE_OPEN_SCOPE \ namespace omni \ { \ namespace ui \ { #define OMNIUI_NAMESPACE_CLOSE_SCOPE \ } \ }
omniverse-code/kit/include/omni/ui/Font.h
// Copyright (c) 2019-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. // #pragma once #include "Api.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief List of all font sizes */ enum class FontStyle { eNone, /** * @brief 14 */ eNormal, /** * @brief 16 */ eLarge, /** * @brief 12 */ eSmall, /** * @brief 18 */ eExtraLarge, /** * @brief 20 */ eXXL, /** * @brief 22 */ eXXXL, /** * @brief 10 */ eExtraSmall, /** * @brief 8 */ eXXS, /** * @brief 6 */ eXXXS, /** * @brief 66 */ eUltra, eCount }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/Frame.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Container.h" #include "RasterHelper.h" OMNIUI_NAMESPACE_OPEN_SCOPE struct FramePrivate; /** * @brief The Frame is a widget that can hold one child widget. * * Frame is used to crop the contents of a child widget or to draw small widget in a big view. The child widget must be * specified with addChild(). */ class OMNIUI_CLASS_API Frame : public Container, public RasterHelper { OMNIUI_OBJECT(Frame) public: using CallbackHelperBase = Widget; OMNIUI_API ~Frame() override; OMNIUI_API void destroy() override; /** * @brief Reimplemented adding a widget to this Frame. The Frame class can not contain multiple widgets. The widget * overrides * * @see Container::addChild */ OMNIUI_API void addChild(std::shared_ptr<Widget> widget) override; /** * @brief Reimplemented removing all the child widgets from this Stack. * * @see Container::clear */ OMNIUI_API void clear() override; /** * @brief Reimplemented the method to indicate the width hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the minimal size of the child widgets. * * @see Widget::setComputedContentWidth */ OMNIUI_API void setComputedContentWidth(float width) override; /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the minimal size of the child widgets. * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentHeight(float height) override; /** * @brief It's called when the style is changed. It should be propagated to children to make the style cached and * available to children. */ OMNIUI_API void cascadeStyle() override; /** * @brief Next frame the content will be forced to re-bake. */ OMNIUI_API void forceRasterDirty(BakeDirtyReason reason) override; /** * @brief Set the callback that will be called once the frame is visible and the content of the callback will * override the frame child. It's useful for lazy load. */ OMNIUI_CALLBACK(Build, void); /** * @brief After this method is called, the next drawing cycle build_fn will be called again to rebuild everything. */ OMNIUI_API virtual void rebuild(); /** * @brief Change dirty bits when the visibility is changed. */ OMNIUI_API void setVisiblePreviousFrame(bool wasVisible, bool dirtySize = true) override; /** * @brief When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is * on. It only works for horizontal direction. */ OMNIUI_PROPERTY(bool, horizontalClipping, DEFAULT, false, READ, isHorizontalClipping, WRITE, setHorizontalClipping); /** * @brief When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is * on. It only works for vertial direction. */ OMNIUI_PROPERTY(bool, verticalClipping, DEFAULT, false, READ, isVerticalClipping, WRITE, setVerticalClipping); /** * @brief A special mode where the child is placed to the transparent borderless window. We need it to be able to * place the UI to the exact stacking order between other windows. */ OMNIUI_PROPERTY(bool, separateWindow, DEFAULT, false, READ, isSeparateWindow, WRITE, setSeparateWindow); OMNIUI_PROPERTY(bool, frozen, DEFAULT, false, READ, isFrozen, WRITE, setFrozen, PROTECTED, NOTIFY, _setFrozenChangedFn); protected: /** * @brief Constructs Frame */ OMNIUI_API Frame(); /** * @brief Reimplemented the rendering code of the widget. * * Draw the content. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; /** * @brief Return the list of children for the Container. */ OMNIUI_API const std::vector<std::shared_ptr<Widget>> _getChildren() const override; /** * @brief This method fills an unordered set with the visible minimum and * maximum values of the Widget and children. */ OMNIUI_API void _fillVisibleThreshold(void* thresholds) const override; // Disables padding. We need it mostly for CollapsableFrame because it creates multiple nested frames and we need to // have only one padding applied. bool m_needPadding = true; private: friend class Placer; friend class Inspector; static float _evaluateLayout(const Length& canvasLength, float availableLength, float dpiScale); /** * @brief Replaces m_canvas with m_canvasPending is possible. */ void _processPendingWidget(); /** * @brief Used in Inspector. Calls build_fn if necessary. */ void _populate(); // The only child of this frame std::shared_ptr<Widget> m_canvas; // The widget that will be the current at the next draw std::shared_ptr<Widget> m_canvasPending; // Lazy load callback. It's destroyed right after it's called. std::function<void()> m_buildFn; // Flag to rebuild the children with m_buildFn. bool m_needRebuildWithCallback = false; std::unique_ptr<FramePrivate> m_prv; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/AbstractSlider.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "FontHelper.h" #include "ValueModelHelper.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The abstract widget that is base for drags and sliders. */ class OMNIUI_CLASS_API AbstractSlider : public Widget, public ValueModelHelper, public FontHelper { public: // TODO: this need to be moved to be a Header like Alignment enum class DrawMode : uint8_t { // filled mode will render the left portion of the slider with filled solid color from styling eFilled = 0, // handle mode draw a knobs at the slider position eHandle, // The Slider doesn't display either Handle or Filled Rect eDrag }; OMNIUI_API ~AbstractSlider() override; /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentHeight(float height) override; /** * @brief Reimplemented. Something happened with the style or with the parent style. We need to gerenerate the * cache. */ OMNIUI_API void onStyleUpdated() override; protected: OMNIUI_API AbstractSlider(const std::shared_ptr<AbstractValueModel>& model); /** * @brief Reimplemented the rendering code of the widget. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; /** * @brief Should be called before editing the model to make sure model::beginEdit called properly. */ OMNIUI_API virtual void _beginModelChange(); /** * @brief Should be called after editing the model to make sure model::endEdit called properly. */ OMNIUI_API virtual void _endModelChange(); /** * @brief the ration calculation is requiere to draw the Widget as Gauge, it is calculated with Min/Max & Value */ virtual float _getValueRatio() = 0; // True if the mouse is down bool m_editActive = false; private: /** * @brief _drawContent sets everything up including styles and fonts and calls this method. */ virtual void _drawUnderlyingItem() = 0; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/VGrid.h
// Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Api.h" #include "Grid.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief Shortcut for Grid{eTopToBottom}. The grid grows from top to bottom with the widgets placed. * * @see Grid */ class OMNIUI_CLASS_API VGrid : public Grid { OMNIUI_OBJECT(VGrid) public: OMNIUI_API ~VGrid() override; protected: /** * @brief Construct a grid that grows from top to bottom with the widgets placed. */ OMNIUI_API VGrid(); }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/RasterPolicy.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Api.h" #include <cstdint> OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief Used to set the rasterization behaviour. */ enum class RasterPolicy : uint8_t { // Do not rasterize the widget at any time. eNever = 0, // Rasterize the widget as soon as possible and always use the // rasterized version. This means that the widget will only be updated // when the user called invalidateRaster. eOnDemand, // Automatically determine whether to rasterize the widget based on // performance considerations. If necessary, the widget will be // rasterized and updated when its content changes. eAuto }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/IntDrag.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "IntSlider.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The drag widget that looks like a field but it's possible to change the value with dragging. */ class OMNIUI_CLASS_API IntDrag : public IntSlider { OMNIUI_OBJECT(IntDrag) public: /** * @brief This property controls the steping speed on the drag, its float to enable slower speed, * but of course the value on the Control are still integer */ OMNIUI_PROPERTY(float, step, DEFAULT, 0.1f, READ, getStep, WRITE, setStep); protected: /** * @brief Constructs IntDrag * * @param model The widget's model. If the model is not assigned, the default model is created. */ OMNIUI_API IntDrag(const std::shared_ptr<AbstractValueModel>& model = {}); private: /** * @brief Reimplemented. It has to run a very low level function to call the widget. */ virtual bool _drawUnderlyingItem(int64_t* value, int64_t min, int64_t max) override; }; class OMNIUI_CLASS_API UIntDrag : public UIntSlider { OMNIUI_OBJECT(UIntDrag) public: /** * @brief This property controls the steping speed on the drag, its float to enable slower speed, * but of course the value on the Control are still integer */ OMNIUI_PROPERTY(float, step, DEFAULT, 0.1f, READ, getStep, WRITE, setStep); protected: /** * @brief Constructs UIntDrag * * @param model The widget's model. If the model is not assigned, the default model is created. */ OMNIUI_API UIntDrag(const std::shared_ptr<AbstractValueModel>& model = {}); private: /** * @brief Reimplemented. It has to run a very low level function to call the widget. */ virtual bool _drawUnderlyingItem(uint64_t* value, uint64_t min, uint64_t max) override; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/Placer.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Axis.h" #include "Container.h" #include "RasterHelper.h" #include <vector> OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The Placer class place a single widget to a particular position based on the offet */ class OMNIUI_CLASS_API Placer : public Container, public RasterHelper { OMNIUI_OBJECT(Placer) public: using CallbackHelperBase = Widget; OMNIUI_API ~Placer() override; OMNIUI_API void destroy() override; /** * @brief Reimplemented adding a widget to this Placer. The Placer class can not contain multiple widgets. * * @see Container::addChild */ OMNIUI_API void addChild(std::shared_ptr<Widget> widget) override; /** * @brief Reimplemented to simply set the single child to null * * @see Container::clear */ OMNIUI_API void clear() override; /** * @brief Reimplemented the method to indicate the width hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the minimal size of the child widget. * * @see Widget::setComputedContentWidth */ OMNIUI_API void setComputedContentWidth(float width) override; /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the minimal size of the child widget. * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentHeight(float height) override; /** * @brief It's called when the style is changed. It should be propagated to children to make the style cached and * available to children. */ OMNIUI_API void cascadeStyle() override; /** * @brief Next frame the content will be forced to re-bake. */ OMNIUI_API void forceRasterDirty(BakeDirtyReason reason) override; /** * @brief offsetX defines the offset placement for the child widget relative to the Placer * * TODO: We will need percents to be able to keep the relative position when scaling. * Example: In Blender sequencer when resizing the window the relative position of tracks is not changing. */ OMNIUI_PROPERTY(Length, offsetX, DEFAULT, Pixel(0.0f), READ, getOffsetX, WRITE, setOffsetX, NOTIFY, setOffsetXChangedFn); /** * @brief offsetY defines the offset placement for the child widget relative to the Placer * */ OMNIUI_PROPERTY(Length, offsetY, DEFAULT, Pixel(0.0f), READ, getOffsetY, WRITE, setOffsetY, NOTIFY, setOffsetYChangedFn); /** * @brief Provides a convenient way to make an item draggable. * * TODO: * dragMaximumX * dragMaximumY * dragMinimumX * dragMinimumY * dragThreshold */ OMNIUI_PROPERTY(bool, draggable, DEFAULT, false, READ, isDraggable, WRITE, setDraggable); /** * @brief Sets if dragging can be horizontally or vertically. */ OMNIUI_PROPERTY(Axis, dragAxis, DEFAULT, Axis::eXY, READ, getDragAxis, WRITE, setDragAxis); /** * @brief The placer size depends on the position of the child when false. */ OMNIUI_PROPERTY(bool, stableSize, DEFAULT, false, READ, isStableSize, WRITE, setStableSize); /** * @brief Set number of frames to start dragging if drag is not detected the first frame. */ OMNIUI_PROPERTY(uint32_t, framesToStartDrag, DEFAULT, 0, READ, getFramesToStartDrag, WRITE, setFramesToStartDrag); protected: /** * @brief Construct Placer */ OMNIUI_API Placer(); /** * @brief Reimplemented the rendering code of the widget. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; /** * @brief Return the list of children for the Container. */ OMNIUI_API const std::vector<std::shared_ptr<Widget>> _getChildren() const override; /** * @brief This method fills an unordered set with the visible minimum and * maximum values of the Widget and children. */ OMNIUI_API void _fillVisibleThreshold(void* thresholds) const override; private: std::shared_ptr<Widget> m_childWidget; // True when the user drags the child. We need it to know if the user was dragging the child on the previous frame. bool m_dragActive = false; // Count duration when the mouse button is pressed. We need it to detect the second frame from mouse click. uint32_t m_pressedFrames = 0; float m_offsetXCached; float m_offsetYCached; float m_widthCached; float m_heightCached; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/Inspector.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Widget.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief Inspector is the helper to check the internal state of the widget. * It's not recommended to use it for the routine UI. */ class OMNIUI_CLASS_API Inspector { public: /** * @brief Get the children of the given Widget. */ OMNIUI_API static std::vector<std::shared_ptr<Widget>> getChildren(const std::shared_ptr<Widget>& widget); /** * @brief Get the resolved style of the given Widget. */ OMNIUI_API static const std::shared_ptr<StyleContainer>& getResolvedStyle(const std::shared_ptr<Widget>& widget); /** * @brief Start counting how many times Widget::setComputedWidth is called */ OMNIUI_API static void beginComputedWidthMetric(); /** * @brief Increases the number Widget::setComputedWidth is called */ OMNIUI_API static void bumpComputedWidthMetric(); /** * @brief Start counting how many times Widget::setComputedWidth is called * and return the number */ OMNIUI_API static size_t endComputedWidthMetric(); /** * @brief Start counting how many times Widget::setComputedHeight is called */ OMNIUI_API static void beginComputedHeightMetric(); /** * @brief Increases the number Widget::setComputedHeight is called */ OMNIUI_API static void bumpComputedHeightMetric(); /** * @brief Start counting how many times Widget::setComputedHeight is called * and return the number */ OMNIUI_API static size_t endComputedHeightMetric(); /** * @brief Provides the information about font atlases */ OMNIUI_API static std::vector<std::pair<std::string, uint32_t>> getStoredFontAtlases(); }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/Window.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Api.h" #include "Callback.h" #include "Property.h" #include "RasterPolicy.h" #include "WindowHandle.h" #include "Workspace.h" #include "windowmanager/WindowManagerUtils.h" #include <carb/IObject.h> #include <carb/input/InputTypes.h> // KeyPressed #include <float.h> #include <memory> #include <string> namespace omni { namespace ui { namespace windowmanager { class IWindowCallback; } } } OMNIUI_NAMESPACE_OPEN_SCOPE class Frame; class MenuBar; /** * @brief The Window class represents a window in the underlying windowing system. * * This window is a child window of main Kit window. And it can be docked. * * Rasterization * * omni.ui generates vertices every frame to render UI elements. One of the * features of the framework is the ability to bake a DrawList per window and * reuse it if the content has not changed, which can significantly improve * performance. However, in some cases, such as the Viewport window and Console * window, it may not be possible to detect whether the window content has * changed, leading to a frozen window. To address this problem, you can control * the rasterization behavior by adjusting RasterPolicy. The RasterPolicy is an * enumeration class that defines the rasterization behavior of a window. It has * three possible values: * * NEVER: Do not rasterize the widget at any time. * ON_DEMAND: Rasterize the widget as soon as possible and always use the * rasterized version. The widget will only be updated when the user calls * invalidateRaster. * AUTO: Automatically determine whether to rasterize the widget based on * performance considerations. If necessary, the widget will be rasterized and * updated when its content changes. * * To resolve the frozen window issue, you can manually set the RasterPolicy of * the problematic window to Never. This will force the window to rasterize its * content and use the rasterized version until the user explicitly calls * invalidateRaster to request an update. * * window = ui.Window("Test window", raster_policy=ui.RasterPolicy.NEVER) */ class OMNIUI_CLASS_API Window : public std::enable_shared_from_this<Window>, public WindowHandle, protected CallbackHelper<Window> { public: typedef uint32_t Flags; static constexpr Flags kWindowFlagNone = 0; static constexpr Flags kWindowFlagNoTitleBar = (1 << 0); static constexpr Flags kWindowFlagNoResize = (1 << 1); static constexpr Flags kWindowFlagNoMove = (1 << 2); static constexpr Flags kWindowFlagNoScrollbar = (1 << 3); static constexpr Flags kWindowFlagNoScrollWithMouse = (1 << 4); static constexpr Flags kWindowFlagNoCollapse = (1 << 5); static constexpr Flags kWindowFlagNoBackground = 1 << 7; static constexpr Flags kWindowFlagNoSavedSettings = (1 << 8); static constexpr Flags kWindowFlagNoMouseInputs = 1 << 9; static constexpr Flags kWindowFlagMenuBar = 1 << 10; static constexpr Flags kWindowFlagShowHorizontalScrollbar = (1 << 11); static constexpr Flags kWindowFlagNoFocusOnAppearing = (1 << 12); static constexpr Flags kWindowFlagForceVerticalScrollbar = (1 << 14); static constexpr Flags kWindowFlagForceHorizontalScrollbar = (1 << 15); static constexpr Flags kWindowFlagNoDocking = (1 << 21); static constexpr Flags kWindowFlagPopup = (1 << 26); static constexpr Flags kWindowFlagModal = (1 << 27); static constexpr Flags kWindowFlagNoClose = (1 << 31); static constexpr float kWindowFloatInvalid = FLT_MAX; // this will need to be reviewed, it is not clear in the future we can really have known position for docking enum class DockPreference : uint8_t { eDisabled, eMain, eRight, eLeft, eRightTop, eRightBottom, eLeftBottom }; enum class DockPolicy : uint8_t { eDoNothing, eCurrentWindowIsActive, eTargetWindowIsActive }; enum class FocusPolicy : uint8_t { eFocusOnLeftMouseDown, // Focus Window on left mouse down and right-click-up. eFocusOnAnyMouseDown, // Focus Window on any mouse down. eFocusOnHover, // Focus Window when mouse hovered over it. // Default to existing behavior: eFocusOnLeftMouseDown eDefault = eFocusOnLeftMouseDown, }; virtual ~Window(); /** * @brief Removes all the callbacks and circular references. */ OMNIUI_API virtual void destroy(); // We need it to make sure it's created as a shared pointer. template <typename... Args> static std::shared_ptr<Window> create(Args&&... args) { /* make_shared doesn't work because the constructor is protected: */ /* auto ptr = std::make_shared<This>(std::forward<Args>(args)...); */ /* TODO: Find the way to use make_shared */ auto window = std::shared_ptr<Window>{ new Window{ std::forward<Args>(args)... } }; Workspace::RegisterWindow(window); return window; } /** * @brief Notifies the window that window set has changed. * * \internal * TODO: We probably don't need it. * \endinternal */ OMNIUI_API void notifyAppWindowChange(omni::kit::IAppWindow* newAppWindow) override; /** * @brief Returns window set draw callback pointer for the given UI window. * * \internal * TODO: We probably don't need it. * \endinternal */ OMNIUI_API windowmanager::IWindowCallback* getWindowCallback() const; /** * @brief Moves the window to the specific OS window. */ OMNIUI_API void moveToAppWindow(omni::kit::IAppWindow* newAppWindow); /** * @brief Current IAppWindow */ OMNIUI_API omni::kit::IAppWindow * getAppWindow() const; /** * @brief Brings this window to the top level of modal windows. */ OMNIUI_API void setTopModal() const; /** * @brief Get DPI scale currently associated to the current window's viewport. It's static since currently we can * only have one window. * * \internal * TODO: class MainWindow * \endinternal */ OMNIUI_API static float getDpiScale(); /** * @brief Get the width in points of the current main window. * * \internal * TODO: class MainWindow * \endinternal */ OMNIUI_API static float getMainWindowWidth(); /** * @brief Get the height in points of the current main window. * * \internal * TODO: class MainWindow * \endinternal */ OMNIUI_API static float getMainWindowHeight(); /** * @brief Deferred docking. We need it when we want to dock windows before they were actually created. It's helpful * when extension initialization, before any window is created. * * @param[in] targetWindowTitle Dock to window with this title when it appears. * @param[in] activeWindow Make target or this window active when docked. */ OMNIUI_API virtual void deferredDockIn(const std::string& targetWindowTitle, DockPolicy activeWindow = DockPolicy::eDoNothing); /** * @brief Indicates if the window was already destroyed. */ OMNIUI_API bool isValid() const; /** * @brief Determine how the content of the window should be rastered. */ OMNIUI_API RasterPolicy getRasterPolicy() const; /** * @brief Determine how the content of the window should be rastered. */ OMNIUI_API void setRasterPolicy(RasterPolicy policy); /** * @brief Sets the function that will be called when the user presses the keyboard key on the focused window. */ OMNIUI_CALLBACK(KeyPressed, void, int32_t, carb::input::KeyboardModifierFlags, bool); /** * @brief This property holds the window's title. */ OMNIUI_PROPERTY(std::string, title, READ_VALUE, getTitle, WRITE, setTitle); /** * @brief This property holds whether the window is visible. */ OMNIUI_PROPERTY(bool, visible, DEFAULT, true, READ_VALUE, isVisible, WRITE, setVisible, NOTIFY, setVisibilityChangedFn); /** * @brief The main layout of this window. */ OMNIUI_PROPERTY(std::shared_ptr<Frame>, frame, READ, getFrame, PROTECTED, WRITE, setFrame); /** * @brief The MenuBar for this Window, it is always present but hidden when the MENUBAR Flag is missing * you need to use kWindowFlagMenuBar to show it */ OMNIUI_PROPERTY(std::shared_ptr<MenuBar>, menuBar, READ, getMenuBar, PROTECTED, WRITE, setMenuBar); /** * @brief This property holds the window Width */ OMNIUI_PROPERTY(float, width, DEFAULT, 400, READ_VALUE, getWidth, WRITE, setWidth, NOTIFY, setWidthChangedFn); /** * @brief This property holds the window Height */ OMNIUI_PROPERTY(float, heigh, DEFAULT, 600, READ_VALUE, getHeight, WRITE, setHeight, NOTIFY, setHeightChangedFn); /** * @brief This property set the padding to the frame on the X axis */ OMNIUI_PROPERTY(float, paddingX, DEFAULT, 4.f, READ, getPaddingX, WRITE, setPaddingX); /** * @brief This property set the padding to the frame on the Y axis */ OMNIUI_PROPERTY(float, paddingY, DEFAULT, 4.f, READ, getPaddingY, WRITE, setPaddingY); /** * @brief Read only property that is true when the window is focused. */ OMNIUI_PROPERTY( bool, focused, DEFAULT, false, READ, getFocused, NOTIFY, setFocusedChangedFn, PROTECTED, WRITE, _setFocused); /** * @brief This property set/get the position of the window in the X Axis. * The default is kWindowFloatInvalid because we send the window position to the underlying system only if the * position is explicitly set by the user. Otherwise the underlying system decides the position. */ OMNIUI_PROPERTY(float, positionX, DEFAULT, kWindowFloatInvalid, READ_VALUE, getPositionX, WRITE, setPositionX, NOTIFY, setPositionXChangedFn); /** * @brief This property set/get the position of the window in the Y Axis. * The default is kWindowFloatInvalid because we send the window position to the underlying system only if the * position is explicitly set by the user. Otherwise the underlying system decides the position. */ OMNIUI_PROPERTY(float, positionY, DEFAULT, kWindowFloatInvalid, READ_VALUE, getPositionY, WRITE, setPositionY, NOTIFY, setPositionYChangedFn); /** * @brief This property set/get the position of the window in both axis calling the property */ OMNIUI_API void setPosition(float x, float y); /** * @brief This property set the Flags for the Window */ OMNIUI_PROPERTY(Flags, flags, DEFAULT, kWindowFlagNone, READ, getFlags, WRITE, setFlags, NOTIFY, setFlagsChangedFn); /** * @brief setup the visibility of the TabBar Handle, this is the small triangle at the corner of the view * If it is not shown then it is not possible to undock that window and it need to be closed/moved programatically * */ OMNIUI_PROPERTY(bool, noTabBar, DEFAULT, false, READ, getNoTabBar, WRITE, setNoTabBar); /** * @brief setup the window to resize automatically based on its content * */ OMNIUI_PROPERTY(bool, autoResize, DEFAULT, false, READ, getAutoResize, WRITE, setAutoResize); /** * @brief Has true if this window is docked. False otherwise. It's a read-only property. */ OMNIUI_PROPERTY( bool, docked, DEFAULT, false, READ_VALUE, isDocked, NOTIFY, setDockedChangedFn, PROTECTED, WRITE, setDocked); /** * @brief Has true if this window is currently selected in the dock. False otherwise. It's a read-only property. */ OMNIUI_PROPERTY(bool, selectedInDock, DEFAULT, false, READ_VALUE, isSelectedInDock, NOTIFY, setSelectedInDockChangedFn, PROTECTED, WRITE, setSelectedInDock); /** * @brief place the window in a specific docking position based on a target window name. * We will find the target window dock node and insert this window in it, either by spliting on ratio or on top * if the window is not found false is return, otherwise true * */ OMNIUI_API bool dockInWindow(const std::string& windowName, const Window::DockPosition& dockPosition, const float& ratio = 0.5); /** * @brief place a named window in a specific docking position based on a target window name. * We will find the target window dock node and insert this named window in it, either by spliting on ratio or on * top if the windows is not found false is return, otherwise true * */ OMNIUI_API static bool dockWindowInWindow(const std::string& windowName, const std::string& targetWindowName, const Window::DockPosition& dockPosition, const float& ratio = 0.5); /** * @brief Move the Window Callback to a new OS Window */ OMNIUI_API void moveToNewOSWindow(); /** * @brief Bring back the Window callback to the Main Window and destroy the Current OS Window */ OMNIUI_API void moveToMainOSWindow(); /** * @brief When true, only the current window will receive keyboard events when it's focused. It's useful to override * the global key bindings. */ OMNIUI_PROPERTY(bool, exclusiveKeyboard, DEFAULT, false, READ_VALUE, isExclusiveKeyboard, WRITE, setExclusiveKeyboard); /** * @brief If the window is able to be separated from the main application window. */ OMNIUI_PROPERTY(bool, detachable, DEFAULT, true, READ_VALUE, isDetachable, WRITE, setDetachable); /** * @brief Vitrual window is the window that is rendered to internal buffer. */ OMNIUI_PROPERTY(bool, virtual, DEFAULT, false, READ_VALUE, isVirtual, PROTECTED, WRITE, _setVirtual); /** * @brief How the Window gains focus. */ OMNIUI_PROPERTY(FocusPolicy, focusPolicy, DEFAULT, FocusPolicy::eDefault, READ_VALUE, getFocusPolicy, WRITE, setFocusPolicy); protected: /** * @brief Construct the window, add it to the underlying windowing system, and makes it appear. * * TODO: By default, the window should not be visible, and the user must call setVisible(true), or show() or similar * to make it visible because right now it's impossible to create invisible window. * * @param title The window title. It's also used as an internal window ID. * @param dockPrefence In the old Kit determines where the window should be docked. In Kit Next it's unused. */ OMNIUI_API Window(const std::string& title, Window::DockPreference dockPrefence = DockPreference::eDisabled); /** * @brief Execute the rendering code of the widget. * * It's in protected section because it can be executed only by this object itself. */ virtual void _draw(const char* windowName, float elapsedTime); /** * @brief Execute the update code for the window, this is to be called inside some ImGui::Begin* code * it is used by modal popup and the main begin window code * * It's in protected section so object overiding behavior can re-use this logic */ void _updateWindow(const char* windowName, float elapsedTime, bool cachePosition); /** * @brief this will push the window style, this need to be called within the _draw function to enable styling */ void _pushWindowStyle(); /** * @brief if you have pushed Window StyleContainer you need to pop it before the end of the _draw method */ void _popWindowStyle(); private: /** * @brief Used as a callback of the underlying windowing system. Calls draw(). */ static void _drawWindow(const char* windowName, float elapsedTime, void* window); /** * @brief Used as a callback when the user call setPosition(X!Y) */ void _positionExplicitlyChanged(); /** * @brief Used as a callback when the user call setPosition(X!Y) */ void _sizeExplicitlyChanged(); /** * @brief Internal function that adds the window to the top level of the stack of modal windows. */ void _addToModalStack() const; /** * @brief Internal function that removes the window from the stack of modal windows. */ void _removeFromModalStack() const; /** * @brief Internal function that returns true if it's on the top of the stack of modal windows. */ bool _isTopModal() const; /** * @brief Force propagate the window state to the backend. */ void _forceWindowState(); /** * @brief Update the Window's focused state, retuns whether it has changed. */ bool _updateFocusState(); // we only support this when in the new kit stack, we might also want to make it a setting bool m_multiOSWindowSupport = false; bool m_enableWindowDetach = false; // we have some marker to tack os window move and timing bool m_osWindowMoving = false; bool m_mouseWasDragging = false; carb::Float2 m_mouseDragPoint = {}; carb::Float2 m_mouseDeltaOffset = {}; Window::DockPreference m_dockingPreference; bool m_positionExplicitlyChanged = false; bool m_sizeExplicitlyChanged = false; float m_prevContentRegionWidth = 0.0f; float m_prevContentRegionHeight = 0.0f; omni::kit::IAppWindow* m_appWindow = nullptr; omni::ui::windowmanager::IWindowCallbackPtr m_uiWindow; uint32_t m_pushedColorCount = { 0 }; uint32_t m_pushedFloatCount = { 0 }; // We need it for multi-modal windows because when the modal window is just created, ImGui puts it to (60, 60) and // the second frame the position is correct. We need to know when it's the first frame of the modal window. bool m_wasModalPreviousFrame = false; bool m_wasVisiblePreviousFrame = false; bool m_firstAppearance = true; // The name of the window we need to dock when it will appear. std::string m_deferredDocking; DockPolicy m_deferredDockingMakeTargetActive = DockPolicy::eDoNothing; class DeferredWindowRelease; std::unique_ptr<DeferredWindowRelease> m_deferedWindowRelease; std::function<void(int32_t, carb::input::KeyboardModifierFlags, bool)> m_keyPressedFn; // True if the title bar context menu is open. bool m_titleMenuOpened = false; bool m_destroyed = false; // True if the previous frame is visible bool m_wasPreviousShowItems = false; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/Ellipse.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Alignment.h" #include "Shape.h" OMNIUI_NAMESPACE_OPEN_SCOPE struct EllipseStyleSnapshot; /** * @brief The Ellipse widget provides a colored ellipse to display. */ class OMNIUI_CLASS_API Ellipse : public Shape { OMNIUI_OBJECT(Ellipse) public: OMNIUI_API ~Ellipse() override; protected: /** * @brief Constructs Ellipse */ OMNIUI_API Ellipse(); /** * @brief Reimplemented the rendering code of the shape. * * @see Widget::_drawContent */ OMNIUI_API void _drawShape(float elapsedTime, float x, float y, float width, float height) override; /** * @brief Reimplemented the draw shadow of the shape. */ OMNIUI_API void _drawShadow( float elapsedTime, float x, float y, float width, float height, uint32_t shadowColor, float dpiScale, ImVec2 shadowOffset, float shadowThickness, uint32_t shadowFlag) override; private: // this need to become a property, stylable ? int32_t m_numSegments = 40; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/StringField.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "AbstractField.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The StringField widget is a one-line text editor with a string model. */ class OMNIUI_CLASS_API StringField : public AbstractField { OMNIUI_OBJECT(StringField) public: /** * @brief This property holds the password mode. If the field is in the password mode when the entered text is obscured. */ OMNIUI_PROPERTY(bool, passwordMode, DEFAULT, false, READ, isPasswordMode, WRITE, setPasswordMode); /** * @brief This property holds if the field is read-only. */ OMNIUI_PROPERTY(bool, readOnly, DEFAULT, false, READ, isReadOnly, WRITE, setReadOnly); /** * @brief Multiline allows to press enter and create a new line. */ OMNIUI_PROPERTY(bool, multiline, DEFAULT, false, READ, isMultiline, WRITE, setMultiline); /** * @brief This property holds if the field allows Tab input. */ OMNIUI_PROPERTY(bool, allowTabInput, DEFAULT, false, READ, isTabInputAllowed, WRITE, setTabInputAllowed); protected: /** * @brief Constructs StringField * * @param model The widget's model. If the model is not assigned, the default model is created. */ OMNIUI_API StringField(const std::shared_ptr<AbstractValueModel>& model = {}); private: /** * @brief It's necessary to implement it to convert model to string buffer that is displayed by the field. It's * possible to use it for setting the string format. */ std::string _generateTextForField() override; /** * @brief Set/get the field data and the state on a very low level of the underlying system. */ void _updateSystemText(void*) override; /** * @brief Determines the flags that are used in the underlying system widget. */ int32_t _getSystemFlags() const override; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/CanvasFrame.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include <imgui/imgui.h> #include "Frame.h" #include "ScrollBarPolicy.h" OMNIUI_NAMESPACE_OPEN_SCOPE struct CanvasFramePrivate; /** * @brief CanvasFrame is a widget that allows the user to pan and zoom its children with a mouse. It has a layout * that can be infinitely moved in any direction. */ class OMNIUI_CLASS_API CanvasFrame : public Frame { OMNIUI_OBJECT(CanvasFrame) public: OMNIUI_API ~CanvasFrame() override; /** * @brief Reimplemented the method to indicate the width hint that represents the preferred size of the widget. * * @see Widget::setComputedContentWidth */ OMNIUI_API void setComputedContentWidth(float width) override; /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentHeight(float height) override; /** * @brief Transforms screen-space X to canvas-space X */ OMNIUI_API float screenToCanvasX(float x) const; /** * @brief Transforms screen-space Y to canvas-space Y */ OMNIUI_API float screenToCanvasY(float y) const; /** * @brief Specify the mouse button and key to pan the canvas. */ OMNIUI_API void setPanKeyShortcut(uint32_t mouseButton, carb::input::KeyboardModifierFlags keyFlag); /** * @brief Specify the mouse button and key to zoom the canvas. */ OMNIUI_API void setZoomKeyShortcut(uint32_t mouseButton, carb::input::KeyboardModifierFlags keyFlag); /** * @brief The horizontal offset of the child item. */ OMNIUI_PROPERTY(float, panX, DEFAULT, 0.0f, READ, getPanX, WRITE, setPanX, NOTIFY, setPanXChangedFn); /** * @brief The vertical offset of the child item. */ OMNIUI_PROPERTY(float, panY, DEFAULT, 0.0f, READ, getPanY, WRITE, setPanY, NOTIFY, setPanYChangedFn); /** * @brief The zoom level of the child item. */ OMNIUI_PROPERTY(float, zoom, DEFAULT, 1.0f, READ, getZoom, WRITE, setZoom, NOTIFY, setZoomChangedFn); /** * @brief The zoom minimum of the child item. */ OMNIUI_PROPERTY(float, zoomMin, DEFAULT, 0.0f, READ, getZoomMin, WRITE, setZoomMin, NOTIFY, setZoomMinChangedFn); /** * @brief The zoom maximum of the child item. */ OMNIUI_PROPERTY(float, zoomMax, DEFAULT, std::numeric_limits<float>::max(), READ, getZoomMax, WRITE, setZoomMax, NOTIFY, setZoomMaxChangedFn); /** * @brief When true, zoom is smooth like in Bifrost even if the user is using mouse wheel that doesn't provide * smooth scrolling. */ OMNIUI_PROPERTY(bool, smoothZoom, DEFAULT, false, READ, isSmoothZoom, WRITE, setSmoothZoom); /** * @brief Provides a convenient way to make the content draggable and zoomable. */ OMNIUI_PROPERTY(bool, draggable, DEFAULT, true, READ, isDraggable, WRITE, setDraggable); /** * @brief This boolean property controls the behavior of CanvasFrame. When * set to true, the widget will function in the old way. When set to false, * the widget will use a newer and faster implementation. This variable is * included as a transition period to ensure that the update does not break * any existing functionality. Please be aware that the old behavior may be * deprecated in the future, so it is recommended to set this variable to * false once you have thoroughly tested the new implementation. */ OMNIUI_PROPERTY(bool, compatibility, DEFAULT, true, READ, isCompatibility, WRITE, setCompatibility, PROTECTED, NOTIFY, _setCompatibilityChangedFn); protected: /** * @brief Constructs CanvasFrame */ OMNIUI_API CanvasFrame(); /** * @brief Reimplemented the rendering code of the widget. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; /** * @brief Returns true to let the children widgets know they are in scalable * environment. * * @return bool - true */ OMNIUI_API bool _isParentCanvasFrame() const override; private: /** * @brief This function contains the drawing code for the old behavior of * the widget. It's only called when the 'compatibility' variable is set to * true. This function is included as a transition period to ensure that the * update does not break any existing functionality. Please be aware that * the old behavior may be deprecated in the future. */ void _drawContentCompatibility(float elapsedTime); // True when the user pans the child. We need it to know if the user did it on the previous frame to be able to // continue panning outside of the widget. bool m_panActive = false; // That's how the pan is initiated uint32_t m_panMouseButton; carb::input::KeyboardModifierFlags m_panKeyFlag; // That's how the zoom is initiated uint32_t m_zoomMouseButton; carb::input::KeyboardModifierFlags m_zoomKeyFlag; // focus position for mouse move scrolling zoom ImVec2 m_focusPosition; // flag to show whether the mouse moving zoom is active bool m_zoomMoveActive = false; // The real zoom, we need it to make the zoom smooth when scrolling with mouse. float m_zoomSmooth; // Return the zoom with limits cap float _getZoom(float zoom); std::unique_ptr<CanvasFramePrivate> m_prv; // only mouse click inside the CanvasFrame considers the signal of checking the pan and zoom bool m_panStarted = false; bool m_zoomStarted = false; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/MenuBar.h
// Copyright (c) 2020-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. // #pragma once #include "Menu.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The MenuBar class provides a MenuBar at the top of the Window, could also be the MainMenuBar of the MainWindow * * it can only contain Menu, at the moment there is no way to remove item appart from clearing it all together */ class OMNIUI_CLASS_API MenuBar : public Menu { OMNIUI_OBJECT(MenuBar) public: OMNIUI_API ~MenuBar() override; protected: /** * @brief Construct MenuBar */ OMNIUI_API MenuBar(bool mainMenuBar = false); /** * @brief Reimplemented the rendering code of the widget. * * Draw the content. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; private: void _drawContentCompatibility(float elapsedTime); bool m_mainMenuBar = { false }; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/FloatField.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "AbstractField.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The FloatField widget is a one-line text editor with a string model. */ class OMNIUI_CLASS_API FloatField : public AbstractField { OMNIUI_OBJECT(FloatField) public: /** * @brief This property holds the field value's precision */ OMNIUI_PROPERTY(uint32_t, precision, DEFAULT, 5, READ, getPrecision, WRITE, setPrecision); protected: /** * @brief Construct FloatField */ OMNIUI_API FloatField(const std::shared_ptr<AbstractValueModel>& model = {}); private: /** * @brief It's necessary to implement it to convert model to string buffer that is displayed by the field. It's * possible to use it for setting the string format. */ std::string _generateTextForField() override; /** * @brief Set/get the field data and the state on a very low level of the underlying system. */ void _updateSystemText(void*) override; /** * @brief Determines the flags that are used in the underlying system widget. */ int32_t _getSystemFlags() const override; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/ContainerScope.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Api.h" #include <memory> #include <stack> // Creates the scope with the given stack widget. So all the items in the scope will be automatically placed to the // given stack. // TODO: Probably it's not the best name. #define OMNIKIT_WITH_CONTAINER(A) \ for (omni::ui::ContainerScope<> __parent{ A }; __parent.isValid(); __parent.invalidate()) OMNIUI_NAMESPACE_OPEN_SCOPE class Container; class Widget; /** * @brief Singleton object that holds the stack of containers. We use it to automatically add widgets to the top * container when the widgets are created. */ class OMNIUI_CLASS_API ContainerStack { public: // Singleton pattern. ContainerStack(const ContainerStack&) = delete; ContainerStack& operator=(const ContainerStack&) = delete; // No move constructor and no move-assignments are allowed because of 12.8 [class.copy]/9 and 12.8 [class.copy]/20 // of the C++ standard /** * @brief The only instance of the singleton. */ OMNIUI_API static ContainerStack& instance(); /** * @brief Push the container to the top of the stack. All the newly created widgets will be added to this container. */ OMNIUI_API void push(std::shared_ptr<Container> current); /** * @brief Removes the container from the stack. The previous one will be active. */ OMNIUI_API void pop(); /** * @brief Add the given widget to the top container. */ OMNIUI_API bool addChildToTop(std::shared_ptr<Widget> child); private: // Disallow instantiation outside of the class. ContainerStack() = default; std::stack<std::shared_ptr<Container>> m_stack; }; /** * @brief Puts the given container to the top of the stack when this object is constructed. And removes this container * when it's destructed. */ class OMNIUI_CLASS_API ContainerScopeBase { public: OMNIUI_API ContainerScopeBase(const std::shared_ptr<Container> current); OMNIUI_API virtual ~ContainerScopeBase(); /** * @brief Returns the container it was created with. */ const std::shared_ptr<Container>& get() const { return m_current; } /** * @brief Checks if this object is valid. It's always valid untill it's invalidated. Once it's invalidated, there is * no way to make it valid again. */ bool isValid() const { return m_isValid; } /** * @brief Makes this object invalid. */ void invalidate() { m_isValid = false; } private: std::shared_ptr<Container> m_current; bool m_isValid; }; /** * @brief The templated class ContainerScope creates a new container and puts it to the top of the stack. */ template <class T = void> class ContainerScope : public ContainerScopeBase { public: template <typename... Args> ContainerScope(Args&&... args) : ContainerScopeBase{ T::create(std::forward<Args>(args)...) } { } }; /** * @brief Specialization. It takes existing container and puts it to the top of the stack. */ template <> class ContainerScope<void> : public ContainerScopeBase { public: template <typename... Args> ContainerScope(const std::shared_ptr<Container> current) : ContainerScopeBase{ std::move(current) } { } }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/Button.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Alignment.h" #include "InvisibleButton.h" #include "Stack.h" OMNIUI_NAMESPACE_OPEN_SCOPE class Label; class Rectangle; class Image; /** * @brief The Button widget provides a command button. * * The command button, is perhaps the most commonly used widget in any graphical user interface. Click a button to * execute a command. It is rectangular and typically displays a text label describing its action. */ class OMNIUI_CLASS_API Button : public InvisibleButton { OMNIUI_OBJECT(Button) public: OMNIUI_API ~Button() override; OMNIUI_API void destroy() override; /** * @brief Reimplemented the method to indicate the width hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the size of the text. * * @see Widget::setComputedContentWidth */ OMNIUI_API void setComputedContentWidth(float width) override; /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the size of the text. * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentHeight(float height) override; /** * @brief Reimplemented. Something happened with the style or with the parent style. We need to gerenerate the * cache. */ OMNIUI_API void onStyleUpdated() override; /** * @brief Reimplemented. It's called when the style is changed. It should be propagated to children to make the * style cached and available to children. */ OMNIUI_API void cascadeStyle() override; /** * @brief This property holds the button's text. */ OMNIUI_PROPERTY(std::string, text, READ, getText, WRITE, setText, NOTIFY, setTextChangedFn); /** * @brief This property holds the button's optional image URL. */ OMNIUI_PROPERTY(std::string, imageUrl, READ, getImageUrl, WRITE, setImageUrl, NOTIFY, setImageUrlChangedFn); /** * @brief This property holds the width of the image widget. Do not use this function to find the width of the * image. */ OMNIUI_PROPERTY(Length, imageWidth, DEFAULT, Fraction{ 1.0f }, READ, getImageWidth, WRITE, setImageWidth, NOTIFY, setImageWidthChangedFn); /** * @brief This property holds the height of the image widget. Do not use this function to find the height of the * image. */ OMNIUI_PROPERTY(Length, imageHeight, DEFAULT, Fraction{ 1.0f }, READ, getImageHeight, WRITE, setImageHeight, NOTIFY, setImageHeightChangedFn); /** * @brief Sets a non-stretchable space in points between image and text. */ OMNIUI_PROPERTY(float, spacing, DEFAULT, 0.0f, READ, getSpacing, WRITE, setSpacing, NOTIFY, setSpacingChangedFn); protected: /** * @brief Construct a button with a text on it. * * @param text The text for the button to use. */ OMNIUI_API Button(const std::string& text = {}); /** * @brief Reimplemented the rendering code of the widget. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; private: /** * @brief Compute the size of the button and save result to the private members. */ void _computeButtonSize(); /** * @brief Return the name of the child widget. Basically it creates a string like this: "Button.{childType}". */ std::string _childTypeName(const std::string& childType) const; // Flag that the content size is computed. We need it because we don't want to recompute the size each call of // draw(). bool m_minimalContentSizeComputed = false; float m_minimalContentWidth; float m_minimalContentHeight; // Flag when the image visibility can potentially be changed bool m_imageVisibilityUpdated = false; // The background rectangle of the button for fast access. std::shared_ptr<Rectangle> m_rectangleWidget; // The main layout. All the sub-widgets (Label and Rectangle) are children of the main layout. std::shared_ptr<Stack> m_labelImageLayout; // The text of the button for fast access. std::shared_ptr<Label> m_labelWidget; std::shared_ptr<Image> m_imageWidget; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/SimpleStringModel.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "AbstractValueModel.h" #include <memory> OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief A very simple value model that holds a single string. */ class OMNIUI_CLASS_API SimpleStringModel : public AbstractValueModel { public: using Base = SimpleStringModel; using CarriedType = std::string; template <typename... Args> static std::shared_ptr<SimpleStringModel> create(Args&&... args) { /* make_shared doesn't work because the constructor is protected: */ /* auto ptr = std::make_shared<This>(std::forward<Args>(args)...); */ /* TODO: Find the way to use make_shared */ return std::shared_ptr<SimpleStringModel>{ new SimpleStringModel{ std::forward<Args>(args)... } }; } /** * @brief Get the value. */ OMNIUI_API bool getValueAsBool() const override; OMNIUI_API double getValueAsFloat() const override; OMNIUI_API int64_t getValueAsInt() const override; OMNIUI_API std::string getValueAsString() const override; /** * @brief Set the value. */ OMNIUI_API void setValue(bool value) override; OMNIUI_API void setValue(double value) override; OMNIUI_API void setValue(int64_t value) override; OMNIUI_API void setValue(std::string value) override; protected: OMNIUI_API SimpleStringModel(const std::string& defaultValue = {}); private: std::string m_value; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/ScrollBarPolicy.h
// Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Api.h" #include <cstdint> OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief Describes when the scroll bar should appear. */ enum class ScrollBarPolicy : uint8_t { /** * @brief Show a scroll bar when the content is too big to fit to the provided area. */ eScrollBarAsNeeded = 0, /** * @brief Never show a scroll bar. */ eScrollBarAlwaysOff, /** * @brief Always show a scroll bar. */ eScrollBarAlwaysOn }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/Spacer.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Widget.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The Spacer class provides blank space. * * Normally, it's used to place other widgets correctly in a layout. * * TODO: Do we need to handle mouse events in this class? */ class OMNIUI_CLASS_API Spacer : public Widget { OMNIUI_OBJECT(Spacer) public: OMNIUI_API ~Spacer() override; protected: /** * @brief Construct Spacer */ OMNIUI_API Spacer(); /** * @brief Reimplemented the rendering code of the widget. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/MenuItemCollection.h
// Copyright (c) 2020-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. // #pragma once #include "Menu.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The MenuItemCollection is the menu that unchecks children when one of * them is checked */ class OMNIUI_CLASS_API MenuItemCollection : public Menu { OMNIUI_OBJECT(MenuItemCollection) public: OMNIUI_API ~MenuItemCollection() override; /** * @brief Adds the menu. We subscribe to the `checked` changes and uncheck * others. */ void addChild(std::shared_ptr<Widget> widget) override; protected: /** * @brief Construct MenuItemCollection */ OMNIUI_API MenuItemCollection(const std::string& text = ""); }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/StyleStore.h
// 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. // #pragma once #include "Api.h" #include <algorithm> #include <cctype> #include <string> #include <vector> OMNIUI_NAMESPACE_OPEN_SCOPE inline std::string __toLower(std::string name) { std::transform(name.begin(), name.end(), name.begin(), [](unsigned char c) { return std::tolower(c); }); return name; } /** * @brief A common template for indexing the style properties of the specific * types. */ template <typename T> class StyleStore { public: OMNIUI_API virtual ~StyleStore() = default; /** * @brief Save the color by name */ OMNIUI_API virtual void store(const std::string& name, T color, bool readOnly = false) { size_t found = this->find(name); if (found == SIZE_MAX) { m_store.emplace_back(__toLower(name), color, readOnly); } else if (!m_store[found].readOnly) { m_store[found].value = color; m_store[found].readOnly = readOnly; } } /** * @brief Return the color by index. */ OMNIUI_API T get(size_t id) const { if (id == SIZE_MAX) { return static_cast<T>(NULL); } return m_store[id].value; } /** * @brief Return the index of the color with specific name. */ OMNIUI_API size_t find(const std::string& name) const { std::string lowerName = __toLower(name); auto found = std::find_if(m_store.begin(), m_store.end(), [&lowerName](const auto& it) { return it.name == lowerName; }); if (found != m_store.end()) { return std::distance(m_store.begin(), found); } return SIZE_MAX; } protected: StyleStore() { } struct Entry { Entry(std::string entryName, T entryValue, bool entryReadOnly = false) : name{ std::move(entryName) }, value{ entryValue }, readOnly{ entryReadOnly } { } std::string name; T value; bool readOnly; }; std::vector<Entry> m_store; }; /** * @brief A singleton that stores all the UI Style color properties of omni.ui. */ class OMNIUI_CLASS_API ColorStore : public StyleStore<uint32_t> { public: /** * @brief Get the instance of this singleton object. */ OMNIUI_API static ColorStore& getInstance(); // A singleton pattern ColorStore(ColorStore const&) = delete; void operator=(ColorStore const&) = delete; private: ColorStore(); }; /** * @brief A singleton that stores all the UI Style float properties of omni.ui. */ class OMNIUI_CLASS_API FloatStore : public StyleStore<float> { public: /** * @brief Get the instance of this singleton object. */ OMNIUI_API static FloatStore& getInstance(); // A singleton pattern FloatStore(FloatStore const&) = delete; void operator=(FloatStore const&) = delete; private: FloatStore(); }; /** * @brief A singleton that stores all the UI Style string properties of omni.ui. */ class OMNIUI_CLASS_API StringStore : public StyleStore<const char*> { public: OMNIUI_API ~StringStore() override; /** * @brief Get the instance of this singleton object. */ OMNIUI_API static StringStore& getInstance(); // A singleton pattern StringStore(StringStore const&) = delete; void operator=(StringStore const&) = delete; OMNIUI_API void store(const std::string& name, const char* string_value, bool readOnly = false) override; private: StringStore(); }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/Alignment.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // //! @file //! //! @brief omni::ui Alignment types. #pragma once #include "Api.h" #include <cstdint> OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief Used when it's necessary to align the content to the wigget. */ enum Alignment : uint8_t { eUndefined = 0, eLeft = 1 << 1, eRight = 1 << 2, eHCenter = 1 << 3, eTop = 1 << 4, eBottom = 1 << 5, eVCenter = 1 << 6, eLeftTop = eLeft | eTop, eLeftCenter = eLeft | eVCenter, eLeftBottom = eLeft | eBottom, eCenterTop = eHCenter | eTop, eCenter = eHCenter | eVCenter, eCenterBottom = eHCenter | eBottom, eRightTop = eRight | eTop, eRightCenter = eRight | eVCenter, eRightBottom = eRight | eBottom, }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/Axis.h
// Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Api.h" #include <stdint.h> OMNIUI_NAMESPACE_OPEN_SCOPE enum class Axis : uint8_t { eNone = 0, eX = 1, eY = 2, eXY = 3, }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/StyleContainer.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Api.h" #include "Property.h" #include "StyleProperties.h" #include <array> #include <string> #include <unordered_map> #include <vector> OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The StyleContainer class encapsulates the look and feel of a GUI. * * It's a place holder for the future work to support CSS style description. StyleContainer supports various properties, * pseudo-states, and subcontrols that make it possible to customize the look of widgets. It can only be edited by * merging with another style. */ class OMNIUI_CLASS_API StyleContainer { public: enum class State { eNormal = 0, eHovered, ePressed, eDisabled, eSelected, eChecked, eDrop, eCount }; StyleContainer() = default; template <typename... Args> StyleContainer(Args... args) { _initializeBlock(args...); } /** * @brief Preset with a default style. */ OMNIUI_API static const StyleContainer& defaultStyle(); /** * @brief Check if the style contains anything. */ OMNIUI_API bool valid() const; /** * @brief Merges another style to this style. The given style is strongest. */ OMNIUI_API void merge(const StyleContainer& style); /** * @brief Find the style state group by type and name. It's pretty slow, so it shouldn't be used in the draw cycle. */ OMNIUI_API size_t getStyleStateGroupIndex(const std::string& type, const std::string& name) const; /** * @brief Get all the types in this StyleContainer. */ OMNIUI_API std::vector<std::string> getCachedTypes() const; /** * @brief Get all the names related to the type in this StyleContainer. */ OMNIUI_API std::vector<std::string> getCachedNames(const std::string& type) const; /** * @brief Get all the available states in the given index in this StyleContainer. */ OMNIUI_API std::vector<State> getCachedStates(size_t styleStateGroupIndex) const; /** * @brief Find the given property in the data structure using the style state group index. If the property is not * found, it continues finding in cascading and parent blocks. The style state group index can be obtained with * getStyleStateGroupIndex. * * @tparam T StyleFloatProperty or StyleColorProperty * @tparam U float or uint32_t */ template <typename T, typename U> bool resolveStyleProperty( size_t styleStateGroupIndex, State state, T property, U* result, bool checkParentGroup = true) const; /** * @brief Get the the mapping between property and its string * * @tparam T StyleFloatProperty, StyleEnumProperty, StyleColorProperty, StyleStringProperty or State */ template <typename T> static const std::unordered_map<std::string, T>& getNameToPropertyMapping(); /** * @brief Get the Property from the string * * @tparam T StyleFloatProperty, StyleEnumProperty, StyleColorProperty or StyleStringProperty */ template <typename T> static T getPropertyEnumeration(const std::string& property); private: /** * @brief StyleContainer block represents one single block of properties. * * It keeps the indices of all possible properties, the values are in the vectors, and the index represents the * position of the value in the vector. Thus, since we always know if the property exists and its location, it's * possible to access the value very fast. Variadic arguments of the constructor allow creating styles with any * number of properties. The initialization usually looks like this: * * StyleBlock{ StyleColorProperty::eBackgroundColor, 0xff292929, StyleFloatProperty::eMargin, 3.0f } * */ class OMNIUI_CLASS_API StyleBlock { public: /** * @brief Construct a new StyleContainer Block object. It's usually looks like this: * * StyleBlock{ StyleColorProperty::eBackgroundColor, 0xff292929, StyleFloatProperty::eMargin, 3.0f } * */ template <typename... Args> StyleBlock(Args... args) { // TODO: with reserve it will be faster. m_floatIndices.fill(SIZE_MAX); m_enumIndices.fill(SIZE_MAX); m_colorIndices.fill(SIZE_MAX); m_stringIndices.fill(SIZE_MAX); _initialize(args...); } /** * @brief Query the properties in the block. * * @tparam T StyleFloatProperty or StyleColorProperty * @tparam U float or uint32_t * @param property For example StyleFloatProperty::ePadding * @param result the pointer to the result where the resolved property will be written * @return true when the block contains given property * @return false when the block doesn't have the given property */ template <typename T, typename U> bool get(T property, U* result) const; /** * @brief Merge another property into this one. * * @param styleBlock The given property. It's stronger than the current one. */ void merge(const StyleBlock& styleBlock); /** * @brief Introducing a new conception of cascading and parenting * * This relationship can be described in the following diagram. We keep the indices of other nodes when they are * available. And it allows fast iterating cascade styles when resolving the properties. * * Button <-------cascade--+ Button:hovered * ^ ^ * | | * parent parent * | | * + + * Button::name <--cascade--+ Button::name::hovered * */ OMNIUI_PROPERTY(size_t, parentIndex, DEFAULT, SIZE_MAX, READ, getParentIndex, WRITE, setParentIndex); OMNIUI_PROPERTY(size_t, cascadeIndex, DEFAULT, SIZE_MAX, READ, getCascadeIndex, WRITE, setCascadeIndex); private: /** * @brief A helper for variadic construction. */ OMNIUI_API void _initialize(StyleFloatProperty property, const char* value); /** * @brief A helper for variadic construction. */ OMNIUI_API void _initialize(StyleFloatProperty property, float value); /** * @brief A helper for variadic construction. */ OMNIUI_API void _initialize(StyleColorProperty property, const char* value); /** * @brief A helper for variadic construction. */ OMNIUI_API void _initialize(StyleColorProperty property, uint32_t value); /** * @brief A helper for variadic construction. */ OMNIUI_API void _initialize(StyleEnumProperty property, uint32_t value); /** * @brief A helper for variadic construction. */ OMNIUI_API void _initialize(StyleStringProperty property, const char* value); /** * @brief A helper for variadic construction. */ template <typename T, typename U, typename... Args> void _initialize(T property, U value, Args... args) { _initialize(property, value); _initialize(args...); } // The data model of the style block is simple. We keep all the values in the vector and all the indices in the // array. It allows us to track which properties are in this block with excellent performance. If the property // is not here, its index is SIZE_MAX. // // +------------------+ +----------+ // | m_floatIndices | | m_floats | // |------------------| |----------| // | padding +------------> 0.0 | // | margin +------> 1.0 | // | radius | | | | // | thickness +---+ | | | // +------------------+ +----------+ // std::array<size_t, static_cast<size_t>(StyleFloatProperty::eCount)> m_floatIndices = {}; std::array<size_t, static_cast<size_t>(StyleColorProperty::eCount)> m_colorIndices = {}; std::array<size_t, static_cast<size_t>(StyleStringProperty::eCount)> m_stringIndices = {}; std::vector<uint32_t> m_enums = {}; std::array<size_t, static_cast<size_t>(StyleEnumProperty::eCount)> m_enumIndices = {}; }; /** * @brief Find the given property in the given block index. If the property is not found, it continues finding in * cascading and parent blocks. * * @tparam T StyleFloatProperty or StyleColorProperty * @tparam U float or uint32_t */ template <typename T, typename U> bool _resolveStyleProperty(size_t blockIndex, T property, U* result, bool checkParentGroup) const; /** * @brief A helper for variadic construction. */ template <typename... Args> void _initializeBlock(StyleFloatProperty prop, Args... args) { static const std::string empty{}; _initializeBlock(empty, prop, args...); } /** * @brief A helper for variadic construction. */ template <typename... Args> void _initializeBlock(StyleEnumProperty prop, Args... args) { static const std::string empty{}; _initializeBlock(empty, prop, args...); } /** * @brief A helper for variadic construction. */ template <typename... Args> void _initializeBlock(StyleColorProperty prop, Args... args) { static const std::string empty{}; _initializeBlock(empty, prop, args...); } /** * @brief A helper for variadic construction. */ template <typename... Args> void _initializeBlock(StyleStringProperty prop, Args... args) { static const std::string empty{}; _initializeBlock(empty, prop, args...); } /** * @brief A helper for variadic construction. */ template <typename... Args> void _initializeBlock(const std::string& scope, Args... args) { // Can't move it to cpp because of the variadic template std::string type; std::string name; State state; StyleContainer::_parseScopeString(scope, type, name, state); if (state == State::eCount) { // TODO: Warning message. BTW, what do we need to use for warnings? return; } auto index = _createStyleStateGroup(type, name); m_styleStateGroups[index][static_cast<int32_t>(state)] = m_styleBlocks.size(); m_styleBlocks.emplace_back(args...); } /** * @brief Create a StyleContainer State Group object and puts it to the internal data structure. * * @return the index of created or existed StyleContainer State Group object in the data structure. */ OMNIUI_API size_t _createStyleStateGroup(const std::string& type, const std::string& name); /** * @brief Perses a string that looks like "Widget::name:state", split it to the parts and return the parts. */ OMNIUI_API static void _parseScopeString(const std::string& input, std::string& type, std::string& name, State& state); /** * @brief This is the group that contains indices to blocks. The index per state. Also, it has an index of the group * that is the parent of this group. * * It's different from the block. The block has a list of properties. The group has the indices to the block. */ struct StyleStateIndices { public: StyleStateIndices() : m_parent{ SIZE_MAX } { // By default everything is invalid. m_indices.fill(SIZE_MAX); } size_t& operator[](size_t i) { // Fast access the indices return m_indices[i]; } const size_t& operator[](size_t i) const { // Fast access the indices return m_indices[i]; } size_t getParentIndex() const { return m_parent; } void setParentIndex(size_t i) { m_parent = i; } private: std::array<size_t, static_cast<size_t>(State::eCount)> m_indices; size_t m_parent; }; using StyleBlocks = std::unordered_map<std::string, std::unordered_map<std::string, size_t>>; // The data structure is pretty simple. We keep all the style blocks in the vector. We have an array with all the // possible states (StyleContainer State Group) of the block. The states are hovered, pressed, etc. The // StyleContainer State Group has the indices of the style blocks in the data structure. The StyleContainer State // Groups are also placed to the vector, and it allows us to keep the index of the StyleContainer State Group in // each widget. Also, we have a dictionary that maps the string names to the indices of StyleContainer State Group. // See the following diagram for details. // // The workflow is simple. Once the style is changed, the widget should ask the index of StyleContainer State Group // with the method `getStyleStateGroupIndex`, and use this index in the draw cycle to query style properties with // the method // `_resolveStyleProperty`. // // +-----------------------------+ +---------------------+ +----------------+ // | m_styleStateGroupIndicesMap | | m_styleStateGroups | | m_styleBlocks | // |-----------------------------| |---------------------| |----------------| // | 'Widget' | | +---------> +-StyleBlock-+ | // | '' +-------------------------> +------------|----+ | | | padding | | // | 'name' | | | normal | | | | | margin | | // | 'Button' | | | hovered +--+ | | | | color | | // | '' | | +-----------------+ | | | background | | // | 'cancel' +-------------------> +-----------------+ | | +------------+ | // | | | | normal +-------------> +-StyleBlock-+ | // | | | | hovered | | | | padding | | // | | | +-----------------+ | | | margin | | // | | | | | | color | | // | | | | | | background | | // | | | | | +------------+ | // +-----------------------------+ +---------------------+ +----------------+ std::vector<StyleBlock> m_styleBlocks = {}; std::vector<StyleStateIndices> m_styleStateGroups = {}; StyleBlocks m_styleStateGroupIndicesMap; // The index of the block that is the global override. It's the block with no name and no type. size_t m_globalOverrideIndex = SIZE_MAX; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/Shape.h
// Copyright (c) 2019-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. // #pragma once #include <imgui/imgui.h> #include "StyleProperties.h" #include "Widget.h" OMNIUI_NAMESPACE_OPEN_SCOPE struct ShapeStyleSnapshot; /** * @brief The Shape widget provides a base class for all the Shape Widget * currently implemented are Rectangle, Circle, Tiangle, Line * TODO: those need to have a special draw overide to deal with intersection better */ class OMNIUI_CLASS_API Shape : public Widget { OMNIUI_OBJECT(Shape) public: OMNIUI_API ~Shape() override; /** * @brief Determines which style entry the shape should use for the background. It's very useful when we need to use * a custom color. For example, when we draw the triangle for a collapsable frame, we use "color" instead of * "background_color". */ OMNIUI_PROPERTY(StyleColorProperty, backgroundColorProperty, DEFAULT, StyleColorProperty::eBackgroundColor, READ, getBackgroundColorProperty, WRITE, setBackgroundColorProperty); /** * @brief Determines which style entry the shape should use for the border color. */ OMNIUI_PROPERTY(StyleColorProperty, borderColorProperty, DEFAULT, StyleColorProperty::eBorderColor, READ, getBorderColorProperty, WRITE, setBorderColorProperty); /** * @brief Determines which style entry the shape should use for the shadow color. */ OMNIUI_PROPERTY(StyleColorProperty, shadowColorProperty, DEFAULT, StyleColorProperty::eShadowColor, READ, getShadowColorProperty, WRITE, setShadowColorProperty); protected: OMNIUI_API Shape(); OMNIUI_API void _drawContent(float elapsedTime) override; OMNIUI_API void _drawShapeShadow(float elapsedTime, float x, float y, float width, float height); virtual void _drawShape(float elapsedTime, float x, float y, float width, float height){} virtual void _drawShadow( float elapsedTime, float x, float y, float width, float height, uint32_t shadowColor, float dpiScale, ImVec2 shadowOffset, float shadowThickness, uint32_t shadowFlag){} /** * @brief Segment-circle intersection. * Follows closely https://stackoverflow.com/questions/1073336/circle-line-segment-collision-detection-algorithm * * @param p1 start of line * @param p2 end of line * @param center center of circle * @param r radius * @return true intercects * @return false doesn't intersect */ static bool _intersects(float p1X, float p1Y, float p2X, float p2Y, float centerX, float centerY, float r); }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/ShadowFlag.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Api.h" #include <cstdint> OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief Used to specify how shadow is rendered */ enum ShadowFlag : uint8_t { eNone = 0, eCutOutShapeBackground = 1 << 0 // Do not render the shadow shape under the objects to be shadowed to save on // fill-rate or facilitate blending. Slower on CPU. }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/CornerFlag.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Api.h" #include <cstdint> OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief Used to specify one or many corners of a rectangle. */ enum CornerFlag : uint32_t { eNone = 0, eTopLeft = 1 << 0, // 0x1 eTopRight = 1 << 1, // 0x2 eBottomLeft = 1 << 2, // 0x4 eBottomRight = 1 << 3, // 0x8 eTop = eTopLeft | eTopRight, // 0x3 eBottom = eBottomLeft | eBottomRight, // 0xC eLeft = eTopLeft | eBottomLeft, // 0x5 eRight = eTopRight | eBottomRight, // 0xA eAll = 0xF // In your function calls you may use ~0 (= all bits sets) instead of ImDrawCornerFlags_All, as a // convenience }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/Property.h
// Copyright (c) 2020-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. // #pragma once #include "Api.h" #include "Profile.h" #include <boost/preprocessor.hpp> #include <functional> #include <memory> #include <vector> /** * @brief Defines and declares a property in the class. * * Example: * OMNIUI_PROPERTY(float, height, * [PROTECTED], * [READ, getHeight], * [READ_VALUE, getHeightByValue], * [WRITE, setHeight], * [DEFAULT, 0.0f], * [NOTIFY, onHeightChanged]) * * Usage: * OMNIUI_PROPERTY( * Length, height, * DEFAULT, Fraction{ 1.0f }, * READ, getHeight, * WRITE, setHeight, * PROTECTED, * NOTIFY, _setHeightChangedFn); * * Expands to: * private: * Length m_height = Fraction{ 1.0f }; * PropertyCallback<Length const&> m__setHeightChangedFnCallbacks{ this }; * public: * virtual Length const& getHeight() const * { * return m_height; * } * public: * virtual void setHeight(Length const& v) * { * if (!checkIfEqual(m_height, v)) * { * m_height = v; * m__setHeightChangedFnCallbacks(v); * } * } * protected: * virtual void _setHeightChangedFn(std::function<void(Length const&)> f) * { * m__setHeightChangedFnCallbacks.add(std::move(f)); * } * public: * * Everything on the right side of PROTECTED keyword will go to the protected section. * * The difference between READ and READ_VALUE is that READ returns const reference, READ_VALUE returns value. * * TODO: Callbacks are executed right on the time the value is changed. It would be better to accumulate them and * execute once altogether. The question: at which point we need to execute them? */ #define OMNIUI_PROPERTY(type, name, ...) OMNIUI_PROPERTY_DEFINE(type, name, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)(END)) // Defines a private member variable and public members #define OMNIUI_PROPERTY_DEFINE(type, name, arguments) \ OMNIUI_PROPERTY_DEFINE_VAR( \ type, name, OMNIUI_PROPERTY_FIND_DEFAULT(arguments), OMNIUI_PROPERTY_FIND_NOTIFY(arguments), arguments) \ BOOST_PP_CAT(OMNIUI_PROPERTY_PUBLIC_, BOOST_PP_SEQ_ELEM(0, arguments)) \ (type, name, OMNIUI_PROPERTY_FIND_NOTIFY(arguments), arguments) public: // Expands to // private: // type m_name [= default]; #define OMNIUI_PROPERTY_DEFINE_VAR(type, name, default, notify, arguments) \ private: \ type OMNI_PROPERTY_NAME(name) OMNIUI_PROPERTY_DEFAULT(default); \ OMNIUI_PROPERTY_DEFINE_CALLBACKS(type, notify) // Expands to `m_name` #define OMNI_PROPERTY_NAME(name) BOOST_PP_CAT(m_, name) #define OMNI_PROPERTY_CALLBACK_NAME(...) BOOST_PP_CAT(BOOST_PP_CAT(m_, __VA_ARGS__), Callbacks) // If something is passed, expands to `= args`, otherwise expands to empty #define OMNIUI_PROPERTY_DEFAULT(...) BOOST_PP_IF(BOOST_PP_IS_EMPTY(__VA_ARGS__), BOOST_PP_EMPTY(), = __VA_ARGS__) #define OMNIUI_PROPERTY_DEFINE_CALLBACK_EMPTY(type, ...) BOOST_PP_EMPTY() #define OMNIUI_PROPERTY_DEFINE_CALLBACK_VAR(type, ...) \ PropertyCallback<CallbackHelperBase, type const&> OMNI_PROPERTY_CALLBACK_NAME(__VA_ARGS__){ this }; #define OMNIUI_PROPERTY_DEFINE_CALLBACKS(type, ...) \ BOOST_PP_IF( \ BOOST_PP_IS_EMPTY(__VA_ARGS__), OMNIUI_PROPERTY_DEFINE_CALLBACK_EMPTY, OMNIUI_PROPERTY_DEFINE_CALLBACK_VAR) \ (type, __VA_ARGS__) #define OMNIUI_PROPERTY_CALLBACK_CODE(type, name, ...) \ BOOST_PP_IF(BOOST_PP_IS_EMPTY(__VA_ARGS__), BOOST_PP_EMPTY(), OMNI_PROPERTY_CALLBACK_NAME(__VA_ARGS__)(v);) // It works like a chain. For example we have arguments like this: (READ)(getHeight)(WRITE)(setHeight)(PROTECTED). // It works with getHeight and calls OMNIUI_PROPERTY_PUBLIC_*WRITE* with arguments (WRITE)(setHeight)(PROTECTED). // The called macro is doing the same. /* Common macro to expand all other property-get macros */ #define OMNIUI_PROPERTY_DECLARE_GETTER(scope, getDeclaration, qual_type, type, name, notify, arguments) \ scope: \ virtual qual_type BOOST_PP_SEQ_ELEM(1, arguments)() const \ getDeclaration \ /* Call the proper macro for the next argument */ \ BOOST_PP_CAT(OMNIUI_PROPERTY_PUBLIC_, BOOST_PP_SEQ_ELEM(2, arguments)) \ (type, name, notify, BOOST_PP_SEQ_REST_N(2, arguments)) /* READ key, declare the virtual function to return by const reference */ #define OMNIUI_PROPERTY_PUBLIC_READ(type, name, notify, arguments) \ OMNIUI_PROPERTY_DECLARE_GETTER(public, \ {return OMNI_PROPERTY_NAME(name);}, \ type const&, \ type, name, notify, arguments) #define OMNIUI_PROPERTY_PROTECTED_READ(type, name, notify, arguments) \ OMNIUI_PROPERTY_DECLARE_GETTER(protected, \ {return OMNI_PROPERTY_NAME(name);}, \ type const&, \ type, name, notify, arguments) /* READ_VALUE key, declare the virtual function to return by value (copy) */ #define OMNIUI_PROPERTY_PUBLIC_READ_VALUE(type, name, notify, arguments) \ OMNIUI_PROPERTY_DECLARE_GETTER(public, \ {return OMNI_PROPERTY_NAME(name);}, \ type, \ type, name, notify, arguments) #define OMNIUI_PROPERTY_PROTECTED_READ_VALUE(type, name, notify, arguments) \ OMNIUI_PROPERTY_DECLARE_GETTER(protected, \ {return OMNI_PROPERTY_NAME(name);}, \ type, \ type, name, notify, arguments) /* GET_VALUE key, declare the virtual function, but use must implement it */ #define OMNIUI_PROPERTY_PUBLIC_GET_VALUE(type, name, notify, arguments) \ OMNIUI_PROPERTY_DECLARE_GETTER(public, \ ;, \ type, \ type, name, notify, arguments) #define OMNIUI_PROPERTY_PROTECTED_GET_VALUE(type, name, notify, arguments) \ OMNIUI_PROPERTY_DECLARE_GETTER(protected, \ ;, \ type, \ type, name, notify, arguments) /* Common macro for scoped write implementation */ #define OMNIUI_PROPERTY_SCOPED_WRITE(scope, type, name, notify, arguments) \ scope: \ virtual void BOOST_PP_SEQ_ELEM(1, arguments)(type const& v) \ { \ if (!checkIfEqual(OMNI_PROPERTY_NAME(name), v)) \ { \ OMNI_PROPERTY_NAME(name) = v; \ OMNIUI_PROFILE_VERBOSE_FUNCTION; \ OMNIUI_PROPERTY_CALLBACK_CODE(type, name, notify) \ } \ } \ /* Call the proper macro for the next argument */ \ BOOST_PP_CAT(OMNIUI_PROPERTY_PUBLIC_, BOOST_PP_SEQ_ELEM(2, arguments)) \ (type, name, notify, BOOST_PP_SEQ_REST_N(2, arguments)) /* WRITE key for public access */ #define OMNIUI_PROPERTY_PUBLIC_WRITE(type, name, notify, arguments) \ OMNIUI_PROPERTY_SCOPED_WRITE(public, type, name, notify, arguments) /* WRITE key for protected access */ #define OMNIUI_PROPERTY_PROTECTED_WRITE(type, name, notify, arguments) \ OMNIUI_PROPERTY_SCOPED_WRITE(protected, type, name, notify, arguments) #define OMNIUI_PROPERTY_PUBLIC_NOTIFY(type, name, notify, arguments) \ public: \ virtual void notify(std::function<void(type const&)> f) \ { \ OMNI_PROPERTY_CALLBACK_NAME(notify).add(std::move(f)); \ } \ /* Call the proper macro for the next argument */ \ BOOST_PP_CAT(OMNIUI_PROPERTY_PUBLIC_, BOOST_PP_SEQ_ELEM(2, arguments)) \ (type, name, notify, BOOST_PP_SEQ_REST_N(2, arguments)) #define OMNIUI_PROPERTY_PROTECTED_NOTIFY(type, name, notify, arguments) \ protected: \ virtual void notify(std::function<void(type const&)> f) \ { \ OMNI_PROPERTY_CALLBACK_NAME(notify).add(std::move(f)); \ } \ /* Call the proper macro for the next argument */ \ BOOST_PP_CAT(OMNIUI_PROPERTY_PROTECTED_, BOOST_PP_SEQ_ELEM(2, arguments)) \ (type, name, notify, BOOST_PP_SEQ_REST_N(2, arguments)) #define OMNIUI_PROPERTY_PUBLIC_PROTECTED(type, name, notify, arguments) \ /* Change the next keyword to PROTECTED */ \ BOOST_PP_CAT(OMNIUI_PROPERTY_PROTECTED_, BOOST_PP_SEQ_ELEM(1, arguments)) \ (type, name, notify, BOOST_PP_SEQ_REST_N(1, arguments)) #define OMNIUI_PROPERTY_PROTECTED_PROTECTED(type, name, notify, arguments) /* Should never happen */ \ BOOST_PP_ERROR(0x0001) #define OMNIUI_PROPERTY_PUBLIC_DEFAULT(type, name, notify, arguments) \ /* Skip and continue working with the next keyword */ \ BOOST_PP_CAT(OMNIUI_PROPERTY_PUBLIC_, BOOST_PP_SEQ_ELEM(2, arguments)) \ (type, name, notify, BOOST_PP_SEQ_REST_N(2, arguments)) #define OMNIUI_PROPERTY_PROTECTED_DEFAULT(type, name, notify, arguments) \ /* Skip and continue working with the next keyword */ \ BOOST_PP_CAT(OMNIUI_PROPERTY_PROTECTED_, BOOST_PP_SEQ_ELEM(2, arguments)) \ (type, name, notify, BOOST_PP_SEQ_REST_N(2, arguments)) #define OMNIUI_PROPERTY_PUBLIC_END(type, name, notify, arguments) #define OMNIUI_PROPERTY_PROTECTED_END(type, name, notify, arguments) // Looking for DEFAULT in the sequece #define OMNIUI_PROPERTY_FIND_DEFAULT(arguments) \ BOOST_PP_CAT(OMNIUI_PROPERTY_FIND_DEFAULT_, BOOST_PP_SEQ_ELEM(0, arguments))(arguments) #define OMNIUI_PROPERTY_FIND_DEFAULT_READ(arguments) \ BOOST_PP_CAT(OMNIUI_PROPERTY_FIND_DEFAULT_, BOOST_PP_SEQ_ELEM(2, arguments)) \ (BOOST_PP_SEQ_REST_N(2, arguments)) #define OMNIUI_PROPERTY_FIND_DEFAULT_READ_VALUE(arguments) \ BOOST_PP_CAT(OMNIUI_PROPERTY_FIND_DEFAULT_, BOOST_PP_SEQ_ELEM(2, arguments)) \ (BOOST_PP_SEQ_REST_N(2, arguments)) #define OMNIUI_PROPERTY_FIND_DEFAULT_GET_VALUE(arguments) \ BOOST_PP_CAT(OMNIUI_PROPERTY_FIND_DEFAULT_, BOOST_PP_SEQ_ELEM(2, arguments)) \ (BOOST_PP_SEQ_REST_N(2, arguments)) #define OMNIUI_PROPERTY_FIND_DEFAULT_WRITE(arguments) \ BOOST_PP_CAT(OMNIUI_PROPERTY_FIND_DEFAULT_, BOOST_PP_SEQ_ELEM(2, arguments)) \ (BOOST_PP_SEQ_REST_N(2, arguments)) #define OMNIUI_PROPERTY_FIND_DEFAULT_NOTIFY(arguments) \ BOOST_PP_CAT(OMNIUI_PROPERTY_FIND_DEFAULT_, BOOST_PP_SEQ_ELEM(2, arguments)) \ (BOOST_PP_SEQ_REST_N(2, arguments)) #define OMNIUI_PROPERTY_FIND_DEFAULT_PROTECTED(arguments) \ BOOST_PP_CAT(OMNIUI_PROPERTY_FIND_DEFAULT_, BOOST_PP_SEQ_ELEM(1, arguments)) \ (BOOST_PP_SEQ_REST_N(1, arguments)) #define OMNIUI_PROPERTY_FIND_DEFAULT_DEFAULT(arguments) BOOST_PP_SEQ_ELEM(1, arguments) #define OMNIUI_PROPERTY_FIND_DEFAULT_END(arguments) BOOST_PP_EMPTY() // Looking for NOTIFY in the sequece #define OMNIUI_PROPERTY_FIND_NOTIFY(arguments) \ BOOST_PP_CAT(OMNIUI_PROPERTY_FIND_NOTIFY_, BOOST_PP_SEQ_ELEM(0, arguments))(arguments) #define OMNIUI_PROPERTY_FIND_NOTIFY_READ(arguments) \ BOOST_PP_CAT(OMNIUI_PROPERTY_FIND_NOTIFY_, BOOST_PP_SEQ_ELEM(2, arguments)) \ (BOOST_PP_SEQ_REST_N(2, arguments)) #define OMNIUI_PROPERTY_FIND_NOTIFY_READ_VALUE(arguments) \ BOOST_PP_CAT(OMNIUI_PROPERTY_FIND_NOTIFY_, BOOST_PP_SEQ_ELEM(2, arguments)) \ (BOOST_PP_SEQ_REST_N(2, arguments)) #define OMNIUI_PROPERTY_FIND_NOTIFY_GET_VALUE(arguments) \ BOOST_PP_CAT(OMNIUI_PROPERTY_FIND_NOTIFY_, BOOST_PP_SEQ_ELEM(2, arguments)) \ (BOOST_PP_SEQ_REST_N(2, arguments)) #define OMNIUI_PROPERTY_FIND_NOTIFY_WRITE(arguments) \ BOOST_PP_CAT(OMNIUI_PROPERTY_FIND_NOTIFY_, BOOST_PP_SEQ_ELEM(2, arguments)) \ (BOOST_PP_SEQ_REST_N(2, arguments)) #define OMNIUI_PROPERTY_FIND_NOTIFY_DEFAULT(arguments) \ BOOST_PP_CAT(OMNIUI_PROPERTY_FIND_NOTIFY_, BOOST_PP_SEQ_ELEM(2, arguments)) \ (BOOST_PP_SEQ_REST_N(2, arguments)) #define OMNIUI_PROPERTY_FIND_NOTIFY_PROTECTED(arguments) \ BOOST_PP_CAT(OMNIUI_PROPERTY_FIND_NOTIFY_, BOOST_PP_SEQ_ELEM(1, arguments)) \ (BOOST_PP_SEQ_REST_N(1, arguments)) #define OMNIUI_PROPERTY_FIND_NOTIFY_NOTIFY(arguments) BOOST_PP_SEQ_ELEM(1, arguments) #define OMNIUI_PROPERTY_FIND_NOTIFY_END(arguments) BOOST_PP_EMPTY() OMNIUI_NAMESPACE_OPEN_SCOPE class Widget; // We need a custom fuction to test if the objects are equal because some objects don't provide equal operator. template <typename T> inline bool checkIfEqual(T const& t, T const& u) { return t == u; } OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/SimpleListModel.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "AbstractItemModel.h" #include <memory> OMNIUI_NAMESPACE_OPEN_SCOPE class SimpleStringModel; /** * @brief A very simple model that holds the the root model and the flat list of models. */ class OMNIUI_CLASS_API SimpleListModel : public AbstractItemModel { public: static std::shared_ptr<SimpleListModel> create(); template <typename T> static std::shared_ptr<SimpleListModel> create(const std::vector<T>& valueList, int32_t rootValue = 0); /** * @brief Reimplemented. Returns the vector of items that are nested to the given parent item. */ OMNIUI_API std::vector<std::shared_ptr<const AbstractItem>> getItemChildren( const std::shared_ptr<const AbstractItem>& parentItem = nullptr) override; /** * @brief Reimplemented. Creates a new item from the value model and appends it to the list of the children of the * given item. */ OMNIUI_API std::shared_ptr<const AbstractItem> appendChildItem(const std::shared_ptr<const AbstractItem>& parentItem, std::shared_ptr<AbstractValueModel> model) override; /** * @brief Reimplemented. Removes the item from the model. */ OMNIUI_API void removeItem(const std::shared_ptr<const AbstractItem>& item) override; OMNIUI_API size_t getItemValueModelCount(const std::shared_ptr<const AbstractItem>& item = nullptr) override; /** * @brief Reimplemented. Get the value model associated with this item. */ OMNIUI_API std::shared_ptr<AbstractValueModel> getItemValueModel(const std::shared_ptr<const AbstractItem>& item = nullptr, size_t index = 0) override; protected: /** * @param rootModel The model that will be returned when querying the root item. * @param models The list of all the value submodels of this model. */ OMNIUI_API SimpleListModel(std::shared_ptr<AbstractValueModel> rootModel, const std::vector<std::shared_ptr<AbstractValueModel>>& models); private: /** * @brief Storrage for the items. */ class ListItem : public AbstractItemModel::AbstractItem { public: ListItem(const std::shared_ptr<AbstractValueModel>& model) : m_model{ model }, m_callbackId{ -1 } { } ~ListItem() override; // No copy ListItem(const ListItem&) = delete; // No copy-assignment ListItem& operator=(const ListItem&) = delete; // No move constructor and no move-assignments are allowed because of 12.8 [class.copy]/9 and 12.8 // [class.copy]/20 of the C++ standard /** * @brief Keep callbackId from the model. When this object is destroyed, it removes this callback. * */ void setCallbackId(int32_t callbackId); private: friend class SimpleListModel; std::shared_ptr<AbstractValueModel> m_model; int32_t m_callbackId; }; std::shared_ptr<AbstractValueModel> m_rootModel; std::vector<std::shared_ptr<ListItem>> m_items; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/CollapsableFrame.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Alignment.h" #include "Frame.h" OMNIUI_NAMESPACE_OPEN_SCOPE class Rectangle; /** * @brief CollapsableFrame is a frame widget that can hide or show its content. It has two states expanded and * collapsed. When it's collapsed, it looks like a button. If it's expanded, it looks like a button and a frame with the * content. It's handy to group properties, and temporarily hide them to get more space for something else. */ class OMNIUI_CLASS_API CollapsableFrame : public Frame { OMNIUI_OBJECT(CollapsableFrame) public: /** * @brief Reimplemented. It adds a widget to m_body. * * @see Container::addChild */ OMNIUI_API void addChild(std::shared_ptr<Widget> widget) override; /** * @brief Reimplemented the method to indicate the width hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the minimal size of the child widgets. * * @see Widget::setComputedContentWidth */ OMNIUI_API void setComputedContentWidth(float width) override; /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the minimal size of the child widgets. * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentHeight(float height) override; /** * @brief Set flags to rebuild the body and header of this frame on the next drawing cycle */ OMNIUI_API void rebuild() override; /** * @brief Set dynamic header that will be created dynamiclly when it is needed. The function is called inside a * ui.Frame scope that the widget will be parented correctly. */ OMNIUI_CALLBACK(BuildHeader, void, bool, std::string); /** * @brief The state of the CollapsableFrame. */ OMNIUI_PROPERTY(bool, collapsed, DEFAULT, false, READ, isCollapsed, WRITE, setCollapsed, NOTIFY, setCollapsedChangedFn); /** * @brief The header text */ OMNIUI_PROPERTY(std::string, title, READ, getTitle, WRITE, setTitle, NOTIFY, setTitleChangedFn); /** * @brief This property holds the alignment of the label in the default header. * By default, the contents of the label are left-aligned and vertically-centered. */ OMNIUI_PROPERTY(Alignment, alignment, DEFAULT, Alignment::eLeftCenter, READ, getAlignment, WRITE, setAlignment, NOTIFY, setAlignmentChangedFn); protected: /** * @brief Constructs CollapsableFrame * * @param text The text for the caption of the frame. */ OMNIUI_API CollapsableFrame(const std::string& text = {}); /** * @brief Creates widgets that represent the header. Basically, it creates a triangle and a label. This function is * called every time the frame collapses/expands, so if Python user wants to reimplement it, he doesn't care about * keeping widgets and tracking the state of the frame. */ virtual void _buildHeader(); private: /** * @brief Checks if it's necessary to recreate the header and call _buildHeader. */ void _updateHeader(); /** * @brief Sets a flag that it's necessary to recreate the header. */ void _invalidateState(); // The important widgets we need to access. // Two rectangles to fill the background. std::shared_ptr<Rectangle> m_backgroundHeader; std::shared_ptr<Rectangle> m_backgroundBody; // The frame for the title std::shared_ptr<Frame> m_header; // The frame for the body std::shared_ptr<Frame> m_body; // If true, the header will be recreated. bool m_headerNeedsToBeUpdated = true; std::function<void(bool, std::string)> m_buildHeaderFn; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/Line.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Alignment.h" #include "ArrowHelper.h" #include "Shape.h" OMNIUI_NAMESPACE_OPEN_SCOPE struct LineStyleSnapshot; /** * @brief The Line widget provides a colored line to display. */ class OMNIUI_CLASS_API Line : public Shape, public ArrowHelper { OMNIUI_OBJECT(Line) public: OMNIUI_API ~Line() override; /** * @brief Sets the function that will be called when the user use mouse enter/leave on the line. It's the override * to prevent Widget from the bounding box logic. * The function specification is: * void onMouseHovered(bool hovered) */ OMNIUI_API void setMouseHoveredFn(std::function<void(bool)> fn) override; /** * @brief Sets the function that will be called when the user presses the mouse button inside the widget. The * function should be like this: * void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) * * It's the override to prevent the bounding box logic. */ OMNIUI_API void setMousePressedFn(std::function<void(float, float, int32_t, carb::input::KeyboardModifierFlags)> fn) override; /** * @brief Sets the function that will be called when the user releases the mouse button if this button was pressed * inside the widget. * void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) */ OMNIUI_API void setMouseReleasedFn(std::function<void(float, float, int32_t, carb::input::KeyboardModifierFlags)> fn) override; /** * @brief Sets the function that will be called when the user presses the mouse button twice inside the widget. The * function specification is the same as in setMousePressedFn. * void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) */ OMNIUI_API void setMouseDoubleClickedFn(std::function<void(float, float, int32_t, carb::input::KeyboardModifierFlags)> fn) override; /** * @brief Reimplemented the method to indicate the width hint that represents the preferred size of the widget. * Currently this widget can't be smaller than 1 pixel * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentWidth(float width) override; /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * Currently this widget can't be smaller than 1 pixel * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentHeight(float height) override; /** * @brief This property holds the alignment of the Line can only LEFT, RIGHT, VCENTER, HCENTER , BOTTOM, TOP. * By default, the Line is HCenter. */ OMNIUI_PROPERTY(Alignment, alignment, DEFAULT, Alignment::eVCenter, READ, getAlignment, WRITE, setAlignment); protected: /** * @brief Constructs Line */ OMNIUI_API Line(); /** * @brief Reimplemented the rendering code of the shape. * * @see Widget::_drawContent */ OMNIUI_API void _drawShape(float elapsedTime, float x, float y, float width, float height) override; /** * @brief Reimplemented the draw shadow of the shape. */ OMNIUI_API void _drawShadow( float elapsedTime, float x, float y, float width, float height, uint32_t shadowColor, float dpiScale, ImVec2 shadowOffset, float shadowThickness, uint32_t shadowFlag) override; private: // Don't use m_mouseHoveredFn and m_isHovered to prevent the bbox logic of Widget. std::function<void(bool)> m_mouseHoveredLineFn; std::function<void(float, float, int32_t, carb::input::KeyboardModifierFlags)> m_mousePressedLineFn; std::function<void(float, float, int32_t, carb::input::KeyboardModifierFlags)> m_mouseReleasedLineFn; std::function<void(float, float, int32_t, carb::input::KeyboardModifierFlags)> m_mouseDoubleClickedLineFn; bool m_isHoveredLine = false; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/MultiField.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "AbstractMultiField.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief MultiFloatField is the widget that has a sub widget (FloatField) per model item. * * It's handy to use it for multi-component data, like for example, float3 or color. */ class OMNIUI_CLASS_API MultiFloatField : public AbstractMultiField { OMNIUI_OBJECT(MultiFloatField) protected: /** * Constructor. */ OMNIUI_API MultiFloatField(const std::shared_ptr<AbstractItemModel>& model = {}); /** * @brief Create the widget with the model provided. */ OMNIUI_API std::shared_ptr<Widget> _createField(const std::shared_ptr<AbstractValueModel>& model) override; /** * @brief Called to assign the new model to the widget created with `_createField` */ OMNIUI_API void _setFieldModel(std::shared_ptr<Widget>& widget, const std::shared_ptr<AbstractValueModel>& model) override; }; /** * @brief MultiIntField is the widget that has a sub widget (IntField) per model item. * * It's handy to use it for multi-component data, like for example, int3. */ class OMNIUI_CLASS_API MultiIntField : public AbstractMultiField { OMNIUI_OBJECT(MultiIntField) protected: /** * Constructor. */ OMNIUI_API MultiIntField(const std::shared_ptr<AbstractItemModel>& model = {}); /** * @brief Create the widget with the model provided. */ OMNIUI_API std::shared_ptr<Widget> _createField(const std::shared_ptr<AbstractValueModel>& model) override; /** * @brief Called to assign the new model to the widget created with `_createField` */ OMNIUI_API void _setFieldModel(std::shared_ptr<Widget>& widget, const std::shared_ptr<AbstractValueModel>& model) override; }; /** * @brief MultiStringField is the widget that has a sub widget (StringField) per model item. * * It's handy to use it for string arrays. */ class OMNIUI_CLASS_API MultiStringField : public AbstractMultiField { OMNIUI_OBJECT(MultiStringField) protected: /** * Constructor. */ OMNIUI_API MultiStringField(const std::shared_ptr<AbstractItemModel>& model = {}); /** * @brief Create the widget with the model provided. */ OMNIUI_API std::shared_ptr<Widget> _createField(const std::shared_ptr<AbstractValueModel>& model) override; /** * @brief Called to assign the new model to the widget created with `_createField` */ OMNIUI_API void _setFieldModel(std::shared_ptr<Widget>& widget, const std::shared_ptr<AbstractValueModel>& model) override; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/CheckBox.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "FontHelper.h" #include "ValueModelHelper.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief A CheckBox is an option button that can be switched on (checked) or off (unchecked). Checkboxes are typically * used to represent features in an application that can be enabled or disabled without affecting others. * * The checkbox is implemented using the model-view pattern. The model is the central component of this system. It is * the application's dynamic data structure independent of the widget. It directly manages the data, logic, and rules of * the checkbox. If the model is not specified, the simple one is created automatically when the object is constructed. */ class OMNIUI_CLASS_API CheckBox : public Widget, public ValueModelHelper, public FontHelper { OMNIUI_OBJECT(CheckBox) public: OMNIUI_API ~CheckBox() override; /** * @brief Reimplemented the method to indicate the width hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the size of the checkbox square. * * @see Widget::setComputedContentWidth */ OMNIUI_API void setComputedContentWidth(float width) override; /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the size of the checkbox square. * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentHeight(float height) override; /** * @brief Reimplemented the method from ValueModelHelper that is called when the model is changed. * * TODO: We can avoid it if we create templated ValueModelHelper that manages data. */ OMNIUI_API void onModelUpdated() override; /** * @brief Reimplemented. Something happened with the style or with the parent style. We need to gerenerate the * cache. */ OMNIUI_API void onStyleUpdated() override; protected: /** * @brief CheckBox with specified model. If model is not specified, it's using the default one. */ OMNIUI_API CheckBox(const std::shared_ptr<AbstractValueModel>& model = {}); /** * @brief Reimplemented the rendering code of the widget. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; private: // The state of the checkbox. We need to cache it anyway. Because we can't query the model every frame because the // model can be written in python and query filesystem or USD. Of course, it can be cached on the Model level, but // it means we ask the user to cache it, which is not preferable. Right now, we allow the model to do very expensive // operations. bool m_value = false; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/ToolBar.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Api.h" #include "Property.h" #include "Window.h" #include <memory> #include <string> namespace omni { namespace kit { struct Window; } } OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The ToolBar class represents a window in the underlying windowing system that as some fixed size property * */ class OMNIUI_CLASS_API ToolBar : public Window { public: enum class Axis : uint8_t { eX = 0, eY = 1, eNone = 2, }; virtual ~ToolBar(){}; // We need it to make sure it's created as a shared pointer. template <typename... Args> static std::shared_ptr<ToolBar> create(Args&&... args) { /* make_shared doesn't work because the constructor is protected: */ /* auto ptr = std::make_shared<This>(std::forward<Args>(args)...); */ /* TODO: Find the way to use make_shared */ auto window = std::shared_ptr<ToolBar>{ new ToolBar{ std::forward<Args>(args)... } }; Workspace::RegisterWindow(window); return window; } /** * @breif axis for the toolbar */ OMNIUI_PROPERTY(ToolBar::Axis, axis, DEFAULT, Axis::eX, READ, getAxis, WRITE, setAxis, NOTIFY, setAxisChangedFn); protected: /** * @brief Construct ToolBar */ OMNIUI_API ToolBar(const std::string& title); /** * @brief Execute the rendering code of the widget. * * It's in protected section because it can be executed only by this object itself. */ virtual void _draw(const char* windowName, float elapsedTime) override; private: float m_prevContentRegionWidth = 0.0f; float m_prevContentRegionHeight = 0.0f; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/IGlyphManager.h
// Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include <omni/kit/KitTypes.h> #include <omni/ui/Font.h> namespace carb { namespace imgui { struct Font; } } namespace omni { namespace ui { struct GlyphInfo { const char* code; float scale; }; constexpr char kFontFileSettingsPath[] = "/app/font/file"; constexpr char kFontSizeSettingsPath[] = "/app/font/size"; constexpr char kFontScaleSettingsPath[] = "/app/font/scale"; constexpr char kResourceConfigFileSettingsPath[] = "/app/resourceConfig"; constexpr char kFontSaveAtlasSettingsPath[] = "/app/font/saveAtlas"; constexpr char kFontCustomRegionFilesSettingsPath[] = "/app/font/customRegionFiles"; constexpr char kFontCustomFontPathSettingsPath[] = "/app/font/customFontPath"; struct FontAtlas; /** * Defines a interface managing custom glyphs for the UI system. */ class IGlyphManager { public: CARB_PLUGIN_INTERFACE("omni::ui::IGlyphManager", 1, 0); virtual ~IGlyphManager(){}; virtual void setFontPath(const char* fontPath) = 0; virtual void setFontSize(float fontSize) = 0; virtual void setFontScale(float fontScale) = 0; virtual void setResourcesConfigPath(const char* resourcesConfigPath) = 0; virtual FontAtlas* createFontAtlas() = 0; virtual void destroyFontAtlas(FontAtlas* fontAtlas) = 0; virtual void* getContextFontAtlas(FontAtlas* fontAtlas) = 0; /** * Rebuilds fonts. If fontAtlas is nullptr, will create internal font atlas - deprecated approach. */ virtual void rebuildFonts(FontAtlas* fontAtlas) = 0; /** * Associates a registered glyph such as a SVG or PNG * * @param glyphPath The glyph resource path. Ex ${glyphs}/folder-solid.svg */ virtual bool registerGlyph(const char* glyphPath, FontStyle style) = 0; /** * Retrieves glyph Unicode character code for a registered glyph resource. * * @param glyphPath The glyph resource path. Ex ${glyphs}/folder-solid.svg * @return The glyph information */ virtual GlyphInfo getGlyphInfo(const char* glyphPath, FontStyle style = FontStyle::eNormal) const = 0; virtual void* getFont(FontStyle style) = 0; }; } }
omniverse-code/kit/include/omni/ui/ColorWidget.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "ItemModelHelper.h" OMNIUI_NAMESPACE_OPEN_SCOPE class AbstractItemModel; /** * @brief The ColorWidget widget is a button that displays the color from the item model and can open a picker window to * change the color. */ class OMNIUI_CLASS_API ColorWidget : public Widget, public ItemModelHelper { OMNIUI_OBJECT(ColorWidget) public: OMNIUI_API ~ColorWidget() override; /** * @brief Reimplemented the method to indicate the width hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the size of the ColorWidget square. * * @see Widget::setComputedContentWidth */ OMNIUI_API void setComputedContentWidth(float width) override; /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the size of the ColorWidget square. * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentHeight(float height) override; /** * @brief Reimplemented the method from ItemModelHelper that is called when the model is changed. * * @param item The item in the model that is changed. If it's NULL, the root is chaged. */ OMNIUI_API void onModelUpdated(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item) override; // TODO: Color space // TODO: Property for float/int // TODO: Property for disabling color picker // TODO: Property for disabling popup // TODO: Property for disabling alpha protected: /** * @brief Construct ColorWidget */ OMNIUI_API ColorWidget(const std::shared_ptr<AbstractItemModel>& model = {}); /** * @brief Reimplemented the rendering code of the widget. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; private: // The cached state of the ColorWidget allows to query the model only if it's changed. static constexpr size_t kRgbaComponentsNumber = 4; size_t m_componentsNumber = 0; float m_colorBuffer[kRgbaComponentsNumber] = { 0.0f }; bool m_popupOpen = false; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/WindowHandle.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // //! @file //! //! @brief omni::ui WindowHandle #pragma once #include "Api.h" #include <memory> #include <string> namespace omni { namespace kit { class IAppWindow; } } OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief WindowHandle is a handle object to control any of the windows in Kit. It can be created any time, and if it's * destroyed, the source window doesn't disappear. */ class OMNIUI_CLASS_API WindowHandle { public: // This is the DockPosition relative to a Split in a DockNode, Same reflect that the position is not Splitted but // over the other window in the same dockNode enum class DockPosition : uint8_t { eLeft = 0, eRight = 1, eTop = 2, eBottom = 3, eSame = 4 }; virtual ~WindowHandle(); /** * @brief The title of the window. */ OMNIUI_API virtual std::string getTitle() const; /** * @brief The position of the window in points. */ OMNIUI_API virtual float getPositionX() const; /** * @brief Set the position of the window in points. */ OMNIUI_API virtual void setPositionX(const float& positionX); /** * @brief The position of the window in points. */ OMNIUI_API virtual float getPositionY() const; /** * @brief Set the position of the window in points. */ OMNIUI_API virtual void setPositionY(const float& positionY); /** * @brief The width of the window in points. */ OMNIUI_API virtual float getWidth() const; /** * @brief Set the width of the window in points. */ OMNIUI_API virtual void setWidth(const float& width); /** * @brief The height of the window in points. */ OMNIUI_API virtual float getHeight() const; /** * @brief Set the height of the window in points. */ OMNIUI_API virtual void setHeight(const float& height); /** * @brief Returns whether the window is visible. */ OMNIUI_API virtual bool isVisible() const; /** * @brief Set the visibility of the windows. It's the way to hide the window. */ OMNIUI_API virtual void setVisible(const bool& visible); /** * @brief Checks if the current docking space has the tab bar. */ OMNIUI_API virtual bool isDockTabBarVisible() const; /** * @brief Sets the visibility of the current docking space tab bar. Unlike * disabled, invisible tab bar can be shown with a little triangle in top * left corner of the window. */ OMNIUI_API virtual void setDockTabBarVisible(const bool& visible); /** * @brief Checks if the current docking space is disabled. The disabled * docking tab bar can't be shown by the user. */ OMNIUI_API virtual bool isDockTabBarEnabled() const; /** * @brief Sets the visibility of the current docking space tab bar. The disabled * docking tab bar can't be shown by the user. */ OMNIUI_API virtual void setDockTabBarEnabled(const bool& disabled); /** * @brief Undock the window and make it floating. */ OMNIUI_API virtual void undock(); /** * @brief Dock the window to the existing window. It can split the window to two parts or it can convert the window * to a docking tab. */ OMNIUI_API virtual void dockIn(const std::shared_ptr<WindowHandle>& window, const DockPosition& dockPosition, float ratio = 0.5); /** * @brief The position of the window in the dock. */ OMNIUI_API virtual int32_t getDockOrder() const; /** * @brief Set the position of the window in the dock. */ OMNIUI_API virtual void setDockOrder(const int32_t& dockOrder); /** * @brief True if this window is docked. False otherwise. */ OMNIUI_API virtual bool isDocked() const; /** * @brief Returns ID of the dock node this window is docked to. */ OMNIUI_API virtual uint32_t getDockId() const; /** * @brief Brings the window to the top. If it's a docked window, it makes the window currently visible in the dock. */ OMNIUI_API virtual void focus(); /** * @brief Return true is the window is the current window in the docking area. */ OMNIUI_API virtual bool isSelectedInDock(); /** * @brief Notifies the UI window that the AppWindow it attached to has changed. */ OMNIUI_API virtual void notifyAppWindowChange(omni::kit::IAppWindow* newAppWindow); protected: friend class Workspace; /** * @brief Create a handle with the given ID. * * Only Workspace can create this object. */ OMNIUI_API WindowHandle(uint32_t windowId); /** * @brief Given an input window, check if it is the current window in the docking area. * @details This is to give the API to check if the current window is selected when we * already have the window, saving us running the slow `_GET_WINDOW`. */ OMNIUI_API bool _isWindowSelectedInDock(void *window); // Underlying ID of the window. uint32_t m_windowId = 0; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/MainWindow.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Api.h" #include "Property.h" #include <carb/IObject.h> #include <memory> #include <string> OMNIUI_NAMESPACE_OPEN_SCOPE namespace windowmanager { class IWindowCallback; } class MenuBar; struct MainWindowPrivate; /** * @brief The MainWindow class represents Main Window for the Application, draw optional MainMenuBar and StatusBar * */ class OMNIUI_CLASS_API MainWindow : public std::enable_shared_from_this<MainWindow>, protected CallbackHelper<MainWindow> { public: virtual ~MainWindow(); /** * @brief Removes all the callbacks and circular references. */ OMNIUI_API virtual void destroy(); // We need it to make sure it's created as a shared pointer. template <typename... Args> static std::shared_ptr<MainWindow> create(Args&&... args) { /* make_shared doesn't work because the constructor is protected: */ /* auto ptr = std::make_shared<This>(std::forward<Args>(args)...); */ /* TODO: Find the way to use make_shared */ auto window = std::shared_ptr<MainWindow>{ new MainWindow{ std::forward<Args>(args)... } }; return window; } /** * @brief The main MenuBar for the application */ OMNIUI_PROPERTY(std::shared_ptr<MenuBar>, mainMenuBar, READ, getMainMenuBar, PROTECTED, WRITE, setMainMenuBar); /** * @brief This represents Styling opportunity for the Window background */ OMNIUI_PROPERTY(std::shared_ptr<Frame>, mainFrame, READ, getMainFrame, PROTECTED, WRITE, setMainFrame); /** * @brief The StatusBar Frame is empty by default and is meant to be filled by other part of the system */ OMNIUI_PROPERTY(std::shared_ptr<Frame>, statusBarFrame, READ, getStatusBarFrame, PROTECTED, WRITE, setStatusBarFrame); /** * @brief Workaround to reserve space for C++ status bar */ OMNIUI_PROPERTY(bool, cppStatusBarEnabled, DEFAULT, false, READ, getCppStatusBarEnabled, WRITE, setCppStatusBarEnabled); /** * @brief When show_foreground is True, MainWindow prevents other windows from showing. */ OMNIUI_PROPERTY(bool, showForeground, DEFAULT, false, READ, isShowForeground, WRITE, setShowForeground, PROTECTED, NOTIFY, _setShowForegroundChangedFn); protected: /** * @brief Construct the main window, add it to the underlying windowing system, and makes it appear. */ OMNIUI_API MainWindow(bool showForeground = false); /** * @brief Execute the rendering code of the widget. * * It's in protected section because it can be executed only by this object itself. */ virtual void _draw(float elapsedTime); /** * @brief Execute the rendering code that prevents other windows from showing. */ virtual void _drawForeground(float elapsedTime); private: // We need it to keep carb::settings::ThreadSafeLocalCache<bool> and avoid // including carb stuff here. std::unique_ptr<MainWindowPrivate> m_prv; float m_viewportSizeX = 0.0f; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/Plot.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "StyleProperties.h" #include "Widget.h" #include <float.h> OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The Plot widget provides a line/histogram to display. */ class OMNIUI_CLASS_API Plot : public Widget { OMNIUI_OBJECT(Plot) public: OMNIUI_API ~Plot() override; /** * @brief This type is used to determine the type of the image. */ enum class Type { eLine, eHistogram, eLine2D, }; /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * Currently this widget can't be smaller than 1 pixel * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentHeight(float height) override; /** * @brief Sets the function that will be called when when data required. */ OMNIUI_API virtual void setDataProviderFn(std::function<float(int)> fn, int valuesCount); /** * @brief Sets the image data value. */ OMNIUI_API virtual void setData(const std::vector<float>& valueList); /** * @brief Sets the 2d data. X coordinate helps to put the point at the exact * position. Useful when the points are at different distance. */ OMNIUI_API virtual void setXYData(const std::vector<std::pair<float, float>>& valueList); /** * @brief This property holds the type of the image, can only be line or histogram. * By default, the type is line. */ OMNIUI_PROPERTY(Type, type, DEFAULT, Type::eLine, READ, getType, WRITE, setType); /** * @brief This property holds the min scale values. * By default, the value is FLT_MAX. */ OMNIUI_PROPERTY(float, scaleMin, DEFAULT, FLT_MAX, READ, getScaleMin, WRITE, setScaleMin); /** * @brief This property holds the max scale values. * By default, the value is FLT_MAX. */ OMNIUI_PROPERTY(float, scaleMax, DEFAULT, FLT_MAX, READ, getScaleMax, WRITE, setScaleMax); /** * @brief This property holds the value offset. * By default, the value is 0. */ OMNIUI_PROPERTY(int, valueOffset, DEFAULT, 0, READ, getValueOffset, WRITE, setValueOffset); /** * @brief This property holds the stride to get value list. * By default, the value is 1. */ OMNIUI_PROPERTY(int, valueStride, DEFAULT, 1, READ, getValueStride, WRITE, setValueStride); /** * @brief This property holds the title of the image. */ OMNIUI_PROPERTY(std::string, title, DEFAULT, "", READ, getTitle, WRITE, setTitle); protected: /** * @brief Construct Plot * * @param type The type of the image, can be line or histogram. * @param scaleMin The minimal scale value. * @param scaleMax The maximum scale value. * @param valueList The list of values to draw the image. */ OMNIUI_API Plot(Type type, float scaleMin, float scaleMax, const std::vector<float>& valueList); /** * @brief Reimplemented the rendering code of the widget. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; private: std::vector<float> m_plotData; std::vector<std::pair<float, float>> m_plotXYData; float m_prevWidth = 0; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/MultiDragField.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "MultiField.h" #include <limits> OMNIUI_NAMESPACE_OPEN_SCOPE class FloatDrag; class IntDrag; /** * @brief The base class for MultiFloatDragField and MultiIntDragField. We need it because there classes are very * similar, so we can template them. * * @tparam T FloatDrag or IntDrag * @tparam U float or Int */ template <typename T, typename U> class OMNIUI_CLASS_API MultiDragField : public AbstractMultiField { public: /** * @brief Reimplemented. Called by the model when the model value is changed. */ OMNIUI_API void onModelUpdated(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item) override; // TODO: We are going to get min/max from the model. /** * @brief This property holds the drag's minimum value. */ OMNIUI_PROPERTY(U, min, DEFAULT, std::numeric_limits<U>::lowest(), READ, getMin, WRITE, setMin, NOTIFY, setMinChangedFn); /** * @brief This property holds the drag's maximum value. */ OMNIUI_PROPERTY(U, max, DEFAULT, std::numeric_limits<U>::max(), READ, getMax, WRITE, setMax, NOTIFY, setMaxChangedFn); /** * @brief This property controls the steping speed on the drag */ OMNIUI_PROPERTY(float, step, DEFAULT, 0.001f, READ, getStep, WRITE, setStep, NOTIFY, setStepChangedFn); protected: /** * @brief Constructs MultiDragField * * @param model The widget's model. If the model is not assigned, the default model is created. */ OMNIUI_API MultiDragField(const std::shared_ptr<AbstractItemModel>& model = {}); /** * @brief Create the widget with the model provided. */ OMNIUI_API std::shared_ptr<Widget> _createField(const std::shared_ptr<AbstractValueModel>& model) override; /** * @brief Called to assign the new model to the widget created with `_createField` */ OMNIUI_API void _setFieldModel(std::shared_ptr<Widget>& widget, const std::shared_ptr<AbstractValueModel>& model) override; private: /** * @brief Called when the min/max property is changed. It propagates min/max to children. */ void _onMinMaxChanged(); /** * @brief Called when the user changes step */ void _onStepChanged(float step); std::vector<std::weak_ptr<T>> m_drags; }; /** * @brief MultiFloatDragField is the widget that has a sub widget (FloatDrag) per model item. * * It's handy to use it for multi-component data, like for example, float3 or color. */ class OMNIUI_CLASS_API MultiFloatDragField : public MultiDragField<FloatDrag, double> { OMNIUI_OBJECT(MultiFloatDragField) protected: /** * @brief Constructs MultiFloatDragField * * @param model The widget's model. If the model is not assigned, the default model is created. */ OMNIUI_API MultiFloatDragField(const std::shared_ptr<AbstractItemModel>& model = {}) : MultiDragField<FloatDrag, double>{ model } { } }; /** * @brief MultiIntDragField is the widget that has a sub widget (IntDrag) per model item. * * It's handy to use it for multi-component data, like for example, int3. */ class OMNIUI_CLASS_API MultiIntDragField : public MultiDragField<IntDrag, int32_t> { OMNIUI_OBJECT(MultiIntDragField) protected: /** * @brief Constructs MultiIntDragField * * @param model The widget's model. If the model is not assigned, the default model is created. */ OMNIUI_API MultiIntDragField(const std::shared_ptr<AbstractItemModel>& model = {}) : MultiDragField<IntDrag, int32_t>{ model } { } }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/Callback.h
// Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Api.h" #include "Profile.h" #include <omni/kit/IApp.h> #include <boost/preprocessor.hpp> #include <algorithm> #include <functional> #include <vector> // Receives: 3, 1, (int, char, float) // Generates: char arg1 #define OMNIUI_ARGUMENT_NAME(z, n, seq) BOOST_PP_TUPLE_ELEM(n, seq) arg##n // Receives: int, char, float // Generates: (int arg0, char arg1, float arg2) #define OMNIUI_FUNCTION_ARGS(...) \ BOOST_PP_IF( \ BOOST_PP_IS_EMPTY(__VA_ARGS__), (), \ (BOOST_PP_ENUM(BOOST_PP_TUPLE_SIZE(BOOST_PP_VARIADIC_TO_TUPLE(__VA_ARGS__)), OMNIUI_ARGUMENT_NAME, \ BOOST_PP_IF(BOOST_PP_IS_EMPTY(__VA_ARGS__), (error), BOOST_PP_VARIADIC_TO_TUPLE(__VA_ARGS__))))) // Receives: int, char, float // Generates: (arg0, arg1, arg2) #define OMNIUI_CALL_ARGS(...) \ BOOST_PP_IF(BOOST_PP_IS_EMPTY(__VA_ARGS__), (), (BOOST_PP_ENUM_PARAMS(BOOST_PP_VARIADIC_SIZE(__VA_ARGS__), arg))) #define OMNIUI_VA_TEMPLATE(type, ...) type BOOST_PP_COMMA_IF(BOOST_PP_NOT(BOOST_PP_IS_EMPTY(__VA_ARGS__))) __VA_ARGS__ template <typename T> inline T __return_type_init() { return static_cast<T>(NULL); } template <> inline std::string __return_type_init<std::string>() { return std::string(""); } /** * @brief This is the macro to define a widget callback. It creates the callback holder and four methods: set, on * changed, has and call. * * Using: OMNIUI_CALLBACK(MouseReleased, void, float, float, int32_t, carb::input::KeyboardModifierFlags); * * Expands to: * private: * Callback<void, float, float, int32_t, carb::input::KeyboardModifierFlags> m_MouseReleasedCallback{ this }; * public: * virtual void setMouseReleasedFn( * std::function<void(float, float, int32_t, carb::input::KeyboardModifierFlags)> fn) * { * m_MouseReleasedCallback.set(std::move(fn)); * } * virtual void setMouseReleasedChangedFn(std::function<void()> fn) * { * m_MouseReleasedCallback.setOnChanged(std::move(fn)); * } * void callMouseReleasedFn(float arg0, float arg1, int32_t arg2, carb::input::KeyboardModifierFlags arg3) * { * if (this->hasMouseReleasedFn()) * { * m_MouseReleasedCallback(arg0, arg1, arg2, arg3); * } * return static_cast<void>(0); * } * bool hasMouseReleasedFn() const * { * return m_MouseReleasedCallback; * } */ #define OMNIUI_CALLBACK(name, type, ...) \ private: \ Callback<CallbackHelperBase, OMNIUI_VA_TEMPLATE(type, __VA_ARGS__)> m_##name##Callback{ this }; \ \ public: \ virtual void set##name##Fn(std::function<type(__VA_ARGS__)> fn) \ { \ m_##name##Callback.set(std::move(fn)); \ } \ \ virtual void set##name##ChangedFn(std::function<void()> fn) \ { \ m_##name##Callback.setOnChanged(std::move(fn)); \ } \ type call##name##Fn OMNIUI_FUNCTION_ARGS(__VA_ARGS__) \ { \ if (this->has##name##Fn()) \ { \ OMNIUI_PROFILE_VERBOSE_FUNCTION; \ return m_##name##Callback OMNIUI_CALL_ARGS(__VA_ARGS__); \ } \ \ return __return_type_init<type>(); \ } \ \ bool has##name##Fn() const \ { \ return m_##name##Callback; \ } OMNIUI_NAMESPACE_OPEN_SCOPE template <typename W> class CallbackBase; /** * @brief Base class for the objects that should automatically clean up the callbacks. It collects all the callbacks * created with OMNIUI_CALLBACK and is able to clean all of them. We use it to destroy the callbacks if the parent * object is destroyed, and it helps to break circular references created by pybind11 because pybind11 can't use weak * pointers. */ template <typename W> class OMNIUI_CLASS_API CallbackHelper { public: using CallbackHelperBase = W; void initializeCallback(CallbackBase<W>* callback) { if (callback) { m_callbacks.push_back(callback); } } void disposeCallback(CallbackBase<W>* callback) { auto found = std::find(m_callbacks.begin(), m_callbacks.end(), callback); if (found != m_callbacks.end()) { m_callbacks.erase(found); } } void destroyCallbacks() { if (!m_callbacksValid) { return; } m_callbacksValid = false; for (auto& callback : m_callbacks) { callback->destroy(); } } private: std::vector<CallbackBase<W>*> m_callbacks; bool m_callbacksValid = true; }; /** * @brief Base object for callback containers. */ template <typename W> class OMNIUI_CLASS_API CallbackBase { public: CallbackBase(CallbackHelper<W>* widget) : m_parent{ widget } { if (m_parent) { m_parent->initializeCallback(this); } } virtual ~CallbackBase() { if (m_parent) { m_parent->disposeCallback(this); } } virtual operator bool() const = 0; virtual void destroy() = 0; private: CallbackHelper<W>* m_parent; }; /** * @brief Callback containers that is used with OMNIUI_CALLBACK macro. It keeps only one function, but it's possible to * set up another function called when the main one is replaced. */ template <typename W, typename T, typename... Args> class Callback : public CallbackBase<W> { public: using CallbackType = std::function<T(Args...)>; Callback(CallbackHelper<W>* widget) : CallbackBase<W>{ widget } { } void set(std::function<T(Args...)> fn) { m_callback = std::move(fn); if (m_onChanged) { m_onChanged(); } } void setOnChanged(std::function<void()> fn) { m_onChanged = std::move(fn); } T operator()(Args... args) { if (m_callback) { return m_callback(args...); } // TODO: Error on empty m_callback? return noCallbackValue(static_cast<const T*>(nullptr)); } operator bool() const override { return static_cast<bool>(m_callback); } void destroy() override { m_callback = {}; m_onChanged = {}; } private: static void noCallbackValue(const void*) { return; } template <typename R> static R noCallbackValue(const R*) { return R{}; } CallbackType m_callback; std::function<void()> m_onChanged; }; /** * @brief Callback containers that is used with OMNIUI_PROPERTY macro. */ template <typename W, typename... Args> class PropertyCallback : public CallbackBase<W> { public: PropertyCallback(CallbackHelper<W>* widget) : CallbackBase<W>{ widget } { } void add(std::function<void(Args...)> fn) { // TODO: There exists code that does ui_obj.set_xxx_changed_fn(None) which assumes // the callback is removed, not added to a list if (fn) { m_callbacks.emplace_back(std::move(fn)); } } void operator()(Args... args) { // TODO: Handle mutation during iteration better const size_t n = m_callbacks.size(); for (size_t i = 0; i < n; ++i) { if (i < m_callbacks.size()) { m_callbacks[i](args...); } else { break; } } } operator bool() const override { return !m_callbacks.empty(); } void destroy() override { m_callbacks.clear(); } private: std::vector<std::function<void(Args...)>> m_callbacks; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/Container.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Widget.h" #include <memory> OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The container is an abstract widget that can hold one or several child widgets. * * The user is allowed to add or replace child widgets. If the widget has multiple children internally (like Button) and * the user doesn't have access to them, it's not necessary to use this class. */ class OMNIUI_CLASS_API Container : public Widget { public: OMNIUI_API ~Container() override; /** * @brief Adds widget to this container in a manner specific to the container. If it's allowed to have one * sub-widget only, it will be overwriten. */ virtual void addChild(std::shared_ptr<Widget> widget){} /** * @brief Removes the container items from the container. */ virtual void clear(){} protected: friend class Inspector; OMNIUI_API Container(); /** * @brief Return the list of children for the Container, only used by Inspector and for debug/inspection * perspective. */ OMNIUI_API virtual const std::vector<std::shared_ptr<Widget>> _getChildren() const { return {}; } }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/FreeShape.h
// Copyright (c) 2020-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. // #pragma once #include "BezierCurve.h" #include "Circle.h" #include "Ellipse.h" #include "Line.h" #include "Rectangle.h" #include "Triangle.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The free widget is the widget that is independent of the layout. It means it is stuck to other widgets. * When initializing, it's necessary to provide two widgets, and the shape is drawn from one widget position to * the another. */ template <typename T> class OMNIUI_CLASS_API FreeShape : public T { /** * @brief Reimplemented the method to indicate the width hint that represents the preferred size of the widget. * It always returns 0 because FreeShape is layout-free. */ OMNIUI_API void setComputedContentWidth(float height) override { // This Widget doesn't modify the layout as it's a free-floating shape. Widget::setComputedContentWidth(0.0f); } /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * It always returns 0 because FreeShape is layout-free. */ OMNIUI_API void setComputedContentHeight(float height) override { // This Widget doesn't modify the layout as it's a free-floating shape. Widget::setComputedContentHeight(0.0f); } protected: /** * @brief Initialize the the shape with bounds limited to the positions of the given widgets. * * @param start The bound corder is in the center of this given widget. * @param end The bound corder is in the center of this given widget. */ OMNIUI_API FreeShape(std::shared_ptr<Widget> start, std::shared_ptr<Widget> end) : m_startPointWidget{ start }, m_endPointWidget{ end } { m_bbox.width = 0.0f; m_bbox.height = 0.0f; } /** * @brief Reimplemented the rendering code of the shape. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override { auto startPointWidget = m_startPointWidget.lock(); auto endPointWidget = m_endPointWidget.lock(); if (!startPointWidget || !endPointWidget) { return; } // Shape bound corners. 0.5 to have the point in the middle of the widget. float startX = startPointWidget->getScreenPositionX() + startPointWidget->getComputedWidth() * 0.5f; float startY = startPointWidget->getScreenPositionY() + startPointWidget->getComputedHeight() * 0.5f; float endX = endPointWidget->getScreenPositionX() + endPointWidget->getComputedWidth() * 0.5f; float endY = endPointWidget->getScreenPositionY() + endPointWidget->getComputedHeight() * 0.5f; m_bbox.width = fabsf(endX - startX); m_bbox.height = fabsf(endY - startY); this->_drawShapeShadow(elapsedTime, startX, startY, endX - startX, endY - startY); this->_drawShape(elapsedTime, startX, startY, endX - startX, endY - startY); } OMNIUI_API Widget::BoundingBox _getInteractionBBox() const override { return m_bbox; } // Weak pointers to the widgets the shape should stick to. std::weak_ptr<Widget> m_startPointWidget; std::weak_ptr<Widget> m_endPointWidget; // Track our bounding box for mouse events, because we set computed width/height to zero. Widget::BoundingBox m_bbox; }; #define _OMNIUI_DEFINE_FREE_SHAPE(name, parent) \ class name : public FreeShape<parent> \ { \ OMNIUI_OBJECT(name) \ \ protected: \ OMNIUI_API \ name(std::shared_ptr<Widget> start, std::shared_ptr<Widget> end) \ : FreeShape<parent>{ std::move(start), std::move(end) } \ { \ } \ } _OMNIUI_DEFINE_FREE_SHAPE(FreeBezierCurve, BezierCurve); _OMNIUI_DEFINE_FREE_SHAPE(FreeCircle, Circle); _OMNIUI_DEFINE_FREE_SHAPE(FreeEllipse, Ellipse); _OMNIUI_DEFINE_FREE_SHAPE(FreeLine, Line); _OMNIUI_DEFINE_FREE_SHAPE(FreeRectangle, Rectangle); _OMNIUI_DEFINE_FREE_SHAPE(FreeTriangle, Triangle); #undef _OMNIUI_DEFINE_FREE_SHAPE OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/AbstractMultiField.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "ItemModelHelper.h" OMNIUI_NAMESPACE_OPEN_SCOPE class AbstractItemModel; class AbstractValueModel; class ValueModelHelper; class Stack; /** * @brief AbstractMultiField is the abstract class that has everything to create a custom widget per model item. * * The class that wants to create multiple widgets per item needs to reimplement the method _createField. */ class OMNIUI_CLASS_API AbstractMultiField : public Widget, public ItemModelHelper { OMNIUI_OBJECT(AbstractMultiField) public: OMNIUI_API ~AbstractMultiField() override; /** * @brief Reimplemented the method to indicate the width hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the size of the text. * * @see Widget::setComputedContentWidth */ OMNIUI_API void setComputedContentWidth(float width) override; /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the size of the text. * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentHeight(float height) override; /** * @brief Reimplemented. Something happened with the style or with the parent style. We need to gerenerate the * cache. */ OMNIUI_API void onStyleUpdated() override; /** * @brief Reimplemented. Called by the model when the model value is changed. * * @param item The item in the model that is changed. If it's NULL, the root is chaged. */ OMNIUI_API void onModelUpdated(const std::shared_ptr<const AbstractItemModel::AbstractItem>& item) override; /** * @brief The max number of fields in a line. */ OMNIUI_PROPERTY( uint8_t, columnCount, DEFAULT, 4, READ, getColumnCount, WRITE, setColumnCount, NOTIFY, setColumnCountChangedFn); /** * @brief Sets a non-stretchable horizontal space in pixels between child fields. */ OMNIUI_PROPERTY(float, hSpacing, DEFAULT, 0.0f, READ, getHSpacing, WRITE, setHSpacing, NOTIFY, setHSpacingChangedFn); /** * @brief Sets a non-stretchable vertical space in pixels between child fields. */ OMNIUI_PROPERTY(float, vSpacing, DEFAULT, 0.0f, READ, getVSpacing, WRITE, setVSpacing, NOTIFY, setVSpacingChangedFn); protected: /** * Constructor. */ OMNIUI_API AbstractMultiField(const std::shared_ptr<AbstractItemModel>& model = {}); /** * @brief Reimplemented the rendering code of the widget. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; /** * @brief It's necessary to implement this method to create a custom widget per model item. It creates the widget * with the model provided and returns it. */ OMNIUI_API virtual std::shared_ptr<Widget> _createField(const std::shared_ptr<AbstractValueModel>& model){ return {}; } /** * @brief Called to assign the new model to the widget created with `_createField` */ OMNIUI_API virtual void _setFieldModel(std::shared_ptr<Widget>& widget, const std::shared_ptr<AbstractValueModel>& model){} protected: // All the widgets to change the name std::vector<std::shared_ptr<Widget>> m_children; private: /** * @brief Called when the spacing property is changed. It propagates spacing to children. */ void _onSpacingChanged(); // The main layout. All the sub-widgets are children of the main layout. std::shared_ptr<Stack> m_mainLayout; // All the stacks. We need them to change spacing. std::vector<std::shared_ptr<Stack>> m_stacks; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/MenuHelper.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Api.h" #include "Callback.h" #include "Property.h" OMNIUI_NAMESPACE_OPEN_SCOPE class Widget; class Frame; class MenuDelegate; /** * @brief The helper class for the menu that draws the menu line. */ class OMNIUI_CLASS_API MenuHelper : private CallbackHelper<MenuHelper> { public: OMNIUI_API virtual ~MenuHelper(); /** * @brief Returns true if the item is in horizontal layout. */ bool isInHorizontalLayout() const; /** * @brief Sets the function that is called when an action is activated by the user; for example, when the user * clicks a menu option, or presses an action's shortcut key combination. */ OMNIUI_CALLBACK(Triggered, void); /** * @brief This property holds the menu's text. */ OMNIUI_PROPERTY(std::string, text, READ, getText, WRITE, setText, PROTECTED, NOTIFY, _setTextChangedFn); /** * @brief This property holds the menu's hotkey text. */ OMNIUI_PROPERTY( std::string, hotkeyText, READ, getHotkeyText, WRITE, setHotkeyText, PROTECTED, NOTIFY, _setHotkeyTextChangedFn); /** * @brief This property holds whether this menu item is checkable. A checkable item is one which has an on/off * state. */ OMNIUI_PROPERTY( bool, checkable, DEFAULT, false, READ, isCheckable, WRITE, setCheckable, PROTECTED, NOTIFY, _setCheckableChangedFn); /** * @brief The delegate that generates a widget per menu item. */ OMNIUI_PROPERTY(std::shared_ptr<MenuDelegate>, delegate, READ, getDelegate, WRITE, setDelegate, PROTECTED, NOTIFY, _setDelegateChangedFn); /** * @brief Hide or keep the window when the user clicked this item. */ OMNIUI_PROPERTY(bool, hideOnClick, DEFAULT, true, READ, isHideOnClick, WRITE, setHideOnClick); OMNIUI_PROPERTY(bool, compatibility, DEFAULT, true, READ, isMenuCompatibility, WRITE, setMenuCompatibility, PROTECTED, NOTIFY, _setMenuCompatibilityChangedFn); protected: friend class MenuDelegate; /** * @brief Constructor */ OMNIUI_API MenuHelper(); /** * @brief Should be called by the widget in init time. */ void _menuHelperInit(Widget& widget); /** * @brief Should be called by the widget in destroy time. */ void _menuHelperDestroy(); /** * @brief Eval and return width of the item. */ float _menuHelperEvalWidth(Widget& widget, float proposed); /** * @brief Eval and return height of the item. */ float _menuHelperEvalHeight(Widget& widget, float proposed); /** * @brief Should be called by the widget during draw. */ void _menuHelperDraw(Widget& widget, float elapsedTime); /** * @brief Should be called by the widget during change of the style. */ void _menuHelperCascadeStyle(); /** * @brief Should be called to make the item dirty. */ void _menuHelperInvalidate(); /** * @brief Iterate the parents and find the delegate. */ const std::shared_ptr<MenuDelegate>& _obtainDelegate(Widget& widget); /** * @brief Convert Widget to MenuHelper if possible. */ static MenuHelper* _getMenuHelper(Widget& widget); private: /** * @brief Check if the item is dirty and call the delegate. */ void _verifyFrame(Widget& widget); /** * @brief Convert MenuHelper to Widget if possible. */ const Widget* _getWidget() const; /** * @brief List of siblings. */ std::vector<std::shared_ptr<Widget>> _getSiblings() const; /** * @brief Iterate the parents and find the delegate. */ const std::shared_ptr<MenuDelegate>& _obtainDelegateRecursive(Widget& widget, uint16_t depth = 0); // All the widgets of the item std::shared_ptr<Frame> m_frame; // Dirty flag bool m_dirty = true; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/Image.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Alignment.h" #include "Widget.h" #include <mutex> OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The Image widget displays an image. * * The source of the image is specified as a URL using the source property. By default, specifying the width and height * of the item causes the image to be scaled to that size. This behavior can be changed by setting the fill_mode * property, allowing the image to be stretched or scaled instead. The property alignment controls where to align the * scaled image. */ class OMNIUI_CLASS_API Image : public Widget { OMNIUI_OBJECT(Image) public: enum class FillPolicy : uint8_t { eStretch = 0, ePreserveAspectFit, ePreserveAspectCrop }; OMNIUI_API ~Image() override; OMNIUI_API void destroy() override; /** * @brief Reimplemented. Called when the style or the parent style is changed. */ OMNIUI_API void onStyleUpdated() override; /** * @brief Returns true if the image has non empty sourceUrl obtained through the property or the style. */ OMNIUI_API bool hasSourceUrl() const; /** * @brief This property holds the image URL. It can be an `omni:` path, a `file:` path, a direct path or the path * relative to the application root directory. */ OMNIUI_PROPERTY(std::string, sourceUrl, READ, getSourceUrl, WRITE, setSourceUrl, NOTIFY, setSourceUrlChangedFn); /** * @brief This property holds the alignment of the image when the fill policy is ePreserveAspectFit or * ePreserveAspectCrop. * By default, the image is centered. */ OMNIUI_PROPERTY(Alignment, alignment, DEFAULT, Alignment::eCenter, READ, getAlignment, WRITE, setAlignment); /** * @brief Define what happens when the source image has a different size than the item. */ OMNIUI_PROPERTY(FillPolicy, fillPolicy, DEFAULT, FillPolicy::ePreserveAspectFit, READ, getFillPolicy, WRITE, setFillPolicy, NOTIFY, setFillPolicyChangedFn); /** * @brief Prevents image blurring when it's placed to fractional position (like x=0.5, y=0.5) */ OMNIUI_PROPERTY(bool, pixelAligned, DEFAULT, false, READ, getPixelAligned, WRITE, setPixelAligned); // TODO: Image rotation // TODO: Right now, it's useless because we load the image in the background, and when the object is created, the // texture is not loaded. There is no way to wait for the texture. We need to add a method to force load. And we // will be able to use texture dimensions as a read-only property. It will help us to achieve /** * @brief The progress of the image loading. * * TODO: For now we only have two states, 0.0 and 1.0 */ OMNIUI_PROPERTY( float, progress, DEFAULT, 0.0f, READ, getProgress, NOTIFY, setProgressChangedFn, PROTECTED, WRITE, _setProgress); protected: /** * @brief Construct image with given url. If the url is empty, it gets the image URL from styling. */ OMNIUI_API Image(const std::string& sourceUrl = {}); /** * @brief the default constructor will need to get the image URL from styling */ // OMNIUI_API // Image(); /** * @brief Reimplemented the rendering code of the widget. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; private: /** * @brief Check if it's necessary to load new textures and load them for all the style states. */ void _loadSourceUrl(); /** * @brief Load the given texture for the given style state. If the texture was loaded before, it just modifies the * indexes without reloading. */ void _loadSourceUrl(const std::string sourceUrl, StyleContainer::State state); // Returns true if the url from the style is changed since the image is loaded. bool _hasStyleUrlChanged() const; // This function triggers the progress of the image loading in the main thread in next frame. void _deferredTriggerProgressDone(); // The mutex for the texture operations, because we load the texture in the background. std::mutex m_textureMutex; // Flag to check all the textures if it's necessary to reload them. bool m_texturesLoaded = false; struct TextureData; // It is the cache of preloaded textures. We need it because we can switch the texture depending on the widget style // state. It can be a separate texture for hovered, disabled, selected, etc. widget. To switch the texture fast, we // preload them for all the states. To be sure that the same texture is not loaded twice, we keep them in a separate // vector, and we keep the index of the texture per style state. To know which texture is already loaded, we keep // the map name to the texture index. // Index of the texture per style state std::array<size_t, static_cast<size_t>(StyleContainer::State::eCount)> m_styleStateToTextureDataIndex; // Resolved style. We need it to know if style shade is changed. It's void* // to indicate that it can't be used as a string andit can only be used to // check if the style became dirty. std::array<const void*, static_cast<size_t>(StyleContainer::State::eCount)> m_styleStateToResolvedStyle; // Index of the texture per filename std::unordered_map<std::string, size_t> m_imageUrlToTextureDataIndex; // Texture data for all the loaded textures std::vector<std::unique_ptr<TextureData>> m_textureData; class DeferredTriggerProgressDone; std::unique_ptr<DeferredTriggerProgressDone> m_deferredTriggerProgressDone; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/ProgressBar.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "FontHelper.h" #include "ValueModelHelper.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief A progressbar is a classic widget for showing the progress of an operation. */ class OMNIUI_CLASS_API ProgressBar : public Widget, public ValueModelHelper, public FontHelper { OMNIUI_OBJECT(ProgressBar) public: OMNIUI_API ~ProgressBar() override; /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentHeight(float height) override; /** * @brief Reimplemented. Something happened with the style or with the parent style. We need to gerenerate the * cache. */ OMNIUI_API void onStyleUpdated() override; /** * @brief Reimplemented the method from ValueModelHelper that is called when the model is changed. */ OMNIUI_API void onModelUpdated() override; protected: /** * @brief Construct ProgressBar * * @param model The model that determines if the button is checked. */ OMNIUI_API ProgressBar(const std::shared_ptr<AbstractValueModel>& model = {}); /** * @brief Reimplemented the rendering code of the widget. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; private: void _drawUnderlyingItem(); // The cached state. double m_valueCache = 0; std::string m_overlayCache; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/DockSpace.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Api.h" #include "Property.h" #include <carb/IObject.h> #include <omni/ui/Frame.h> #include <memory> #include <string> OMNIUI_NAMESPACE_OPEN_SCOPE namespace windowmanager { struct WindowSet; class IWindowCallback; } class MenuBar; /** * @brief The DockSpace class represents Dock Space for the OS Window * */ class OMNIUI_CLASS_API DockSpace { public: virtual ~DockSpace(); // We need it to make sure it's created as a shared pointer. template <typename... Args> static std::shared_ptr<DockSpace> create(Args&&... args) { /* make_shared doesn't work because the constructor is protected: */ /* auto ptr = std::make_shared<This>(std::forward<Args>(args)...); */ /* TODO: Find the way to use make_shared */ auto dockSpace = std::shared_ptr<DockSpace>{ new DockSpace{ std::forward<Args>(args)... } }; return dockSpace; } /** * @brief This represents Styling opportunity for the Window background */ OMNIUI_PROPERTY(std::shared_ptr<Frame>, dockFrame, READ, getDockFrame, PROTECTED, WRITE, setDockFrame); protected: /** * @brief Construct the main window, add it to the underlying windowing system, and makes it appear. */ OMNIUI_API DockSpace(windowmanager::WindowSet* windowSet = nullptr); /** * @brief Execute the rendering code of the widget. * * It's in protected section because it can be executed only by this object itself. */ virtual void _draw(float elapsedTime); private: // the windowCallback carb::ObjectPtr<windowmanager::IWindowCallback> m_windowCallback; windowmanager::WindowSet* m_windowSet = nullptr; std::string m_name; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/Grid.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Stack.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief Grid is a container that arranges its child views in a grid. The grid vertical/horizontal direction is the * direction the grid size growing with creating more children. */ class OMNIUI_CLASS_API Grid : public Stack { OMNIUI_OBJECT(Grid) public: OMNIUI_API ~Grid() override; /** * @brief Reimplemented the method to indicate the width hint that represents the preferred size of the widget. * * @see Widget::setComputedContentWidth */ OMNIUI_API void setComputedContentWidth(float width) override; /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentHeight(float height) override; /** * @brief The width of the column. It's only possible to set it if the grid is vertical. Once it's set, the column * count depends on the size of the widget. */ OMNIUI_PROPERTY(float, columnWidth, DEFAULT, 0.0f, READ, getColumnWidth, WRITE, setColumnWidth, PROTECTED, NOTIFY, _setColumnWidthChangedFn); /** * @brief The height of the row. It's only possible to set it if the grid is horizontal. Once it's set, the row * count depends on the size of the widget. */ OMNIUI_PROPERTY( float, rowHeight, DEFAULT, 0.0f, READ, getRowHeight, WRITE, setRowHeight, PROTECTED, NOTIFY, _setRowHeightChangedFn); /** * @brief The number of columns. It's only possible to set it if the grid is vertical. Once it's set, the column * width depends on the widget size. */ OMNIUI_PROPERTY(uint32_t, columnCount, DEFAULT, 1, READ, getColumnCount, WRITE, setColumnCount, PROTECTED, NOTIFY, _setColumnCountChangedFn); /** * @brief The number of rows. It's only possible to set it if the grid is horizontal. Once it's set, the row height * depends on the widget size. */ OMNIUI_PROPERTY( uint32_t, rowCount, DEFAULT, 1, READ, getRowCount, WRITE, setRowCount, PROTECTED, NOTIFY, _setRowCountChangedFn); protected: /** * @brief Constructor. * * @param direction Determines the direction the widget grows when adding more children. * * @see Stack::Direction */ OMNIUI_API Grid(Direction direction); /** * @brief Reimplemented the rendering code of the widget. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; private: /** * @brief The grid has two modes of working. When the current mode is eSizeFromCount, the grid computes the size of * the cell using the number of columns/rows. When eCountFromSize, the size of the cells is always the same, but the * number of columns varies depending on the grid's full size. */ enum class CellSizeMode : uint8_t { eSizeFromCount, eCountFromSize }; CellSizeMode m_cellSizeMode = CellSizeMode::eSizeFromCount; // Flag to determine if the property set by user or by this class. bool m_internalPropertyChange = false; // True to determine that height (for V) or width (for H) was set explicitly. bool m_isLineSizeSet = false; // List of line offsets. It's empty if height (for V) or width (for H) was set explicitly. std::vector<float> m_lineOffset; // Currently visible lines. size_t m_lineLower = 0; // Max for the first frame and then it will be corrected. size_t m_lineUpper = SIZE_MAX; size_t m_prevColumnCount = 0; size_t m_prevRowCount = 0; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/VStack.h
// Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Api.h" #include "Stack.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief Shortcut for Stack{eTopToBottom}. The widgets are placed in a column, with suitable sizes. * * @see Stack */ class OMNIUI_CLASS_API VStack : public Stack { OMNIUI_OBJECT(VStack) public: OMNIUI_API ~VStack() override; protected: /** * @brief Construct a stack with the widgets placed in a column from top to bottom. */ OMNIUI_API VStack(); }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/ScrollingFrame.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Frame.h" #include "ScrollBarPolicy.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The ScrollingFrame class provides the ability to scroll onto another widget. * * ScrollingFrame is used to display the contents of a child widget within a frame. If the widget exceeds the size of * the frame, the frame can provide scroll bars so that the entire area of the child widget can be viewed. The child * widget must be specified with addChild(). */ class OMNIUI_CLASS_API ScrollingFrame : public Frame { OMNIUI_OBJECT(ScrollingFrame) public: OMNIUI_API ~ScrollingFrame() override; /** * @brief Reimplemented the method to indicate the width hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the minimal size of the child widgets. * * @see Widget::setComputedContentWidth */ OMNIUI_API void setComputedContentWidth(float width) override; /** * @brief Reimplemented the method to indicate the height hint that represents the preferred size of the widget. * Currently this widget can't be smaller than the minimal size of the child widgets. * * @see Widget::setComputedContentHeight */ OMNIUI_API void setComputedContentHeight(float height) override; /** * @brief The horizontal position of the scroll bar. When it's changed, the contents will be scrolled accordingly. */ OMNIUI_PROPERTY(float, scrollX, DEFAULT, 0.0f, READ, getScrollX, WRITE, setScrollX, NOTIFY, setScrollXChangedFn); /** * @brief The vertical position of the scroll bar. When it's changed, the contents will be scrolled accordingly. */ OMNIUI_PROPERTY(float, scrollY, DEFAULT, 0.0f, READ, getScrollY, WRITE, setScrollY, NOTIFY, setScrollYChangedFn); /** * @brief The max position of the horizontal scroll bar. */ OMNIUI_PROPERTY(float, scrollXMax, DEFAULT, 0.0f, READ, getScrollXMax, PROTECTED, WRITE, setScrollXMax); /** * @brief The max position of the vertical scroll bar. */ OMNIUI_PROPERTY(float, scrollYMax, DEFAULT, 0.0f, READ, getScrollYMax, PROTECTED, WRITE, setScrollYMax); /** * @brief This property holds the policy for the horizontal scroll bar. */ OMNIUI_PROPERTY(ScrollBarPolicy, horizontalScrollBarPolicy, DEFAULT, ScrollBarPolicy::eScrollBarAsNeeded, READ, getHorizontalScrollBarPolicy, WRITE, setHorizontalScrollBarPolicy); /** * @brief This property holds the policy for the vertical scroll bar. */ OMNIUI_PROPERTY(ScrollBarPolicy, verticalScrollBarPolicy, DEFAULT, ScrollBarPolicy::eScrollBarAsNeeded, READ, getVerticalScrollBarPolicy, WRITE, setVerticalScrollBarPolicy); protected: /** * @brief Construct ScrollingFrame */ OMNIUI_API ScrollingFrame(); /** * @brief Reimplemented the rendering code of the widget. * * Draw the content in the scrolling frame. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; private: void _scrollXExplicitlyChanged(); void _scrollYExplicitlyChanged(); // Flags for synchronization of the scrollX and scrollY properties and the underlying windowing system. bool m_scrollXExplicitlyChanged = false; bool m_scrollYExplicitlyChanged = false; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/SimpleNumericModel.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "AbstractValueModel.h" #include "Property.h" #include <memory> OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief A very simple value model that holds a single number. It's still an abstract class. It's necessary to * reimplement `setValue(std::string value)` because each numeric type can be represented with different string. */ template <typename T> class OMNIUI_CLASS_API SimpleNumericModel : public AbstractValueModel { public: using Base = SimpleNumericModel<T>; using CarriedType = T; /** * @brief This property holds the model's minimum value. */ OMNIUI_PROPERTY(T, min, DEFAULT, T(1), READ_VALUE, getMin, WRITE, setMin); /** * @brief This property holds the model's maximum value. */ OMNIUI_PROPERTY(T, max, DEFAULT, T(0), READ_VALUE, getMax, WRITE, setMax); /** * @brief Get the value as bool. */ bool getValueAsBool() const override { return m_value != static_cast<T>(0); } /** * @brief Get the value as double. */ double getValueAsFloat() const override { return static_cast<double>(m_value); } /** * @brief Get the value as int64_t. */ int64_t getValueAsInt() const override { return static_cast<int64_t>(m_value); } /** * @brief Get the value as string. */ std::string getValueAsString() const override { return std::to_string(m_value); } /** * @brief Set the bool value. It will convert bool to the model's typle. */ void setValue(bool value) override { this->_setNumericValue(static_cast<T>(value)); } /** * @brief Set the double value. It will convert double to the model's typle. */ void setValue(double value) override { this->_setNumericValue(static_cast<T>(value)); } /** * @brief Set the int64_t value. It will convert int64_t to the model's typle. */ void setValue(int64_t value) override { this->_setNumericValue(static_cast<T>(value)); } protected: SimpleNumericModel(T defaultValue = static_cast<T>(0)) : m_value{ defaultValue } { } /** * @brief Template to set the value of native type. */ void _setNumericValue(T value) { // Clamp if (this->getMin() <= this->getMax()) { value = std::min(this->getMax(), std::max(this->getMin(), value)); } if (m_value != value) { m_value = value; this->_valueChanged(); } } private: T m_value; }; #define SIMPLENUMERICMODEL_CREATOR(THIS) \ public: \ using This = THIS; \ template <typename... Args> \ static std::shared_ptr<This> create(Args&&... args) \ { \ return std::shared_ptr<This>{ new This{ std::forward<Args>(args)... } }; \ } \ \ protected: \ THIS(CarriedType devaultValue = {}) : SimpleNumericModel<CarriedType>{ devaultValue } \ { \ } /** * @brief A very simple bool model. */ class OMNIUI_CLASS_API SimpleBoolModel : public SimpleNumericModel<bool> { SIMPLENUMERICMODEL_CREATOR(SimpleBoolModel) public: OMNIUI_API std::string getValueAsString() const override; // Reimplemented because it's a special case for string. OMNIUI_API void setValue(std::string value) override; }; /** * @brief A very simple double model. */ class OMNIUI_CLASS_API SimpleFloatModel : public SimpleNumericModel<double> { SIMPLENUMERICMODEL_CREATOR(SimpleFloatModel) public: // Reimplemented because it's a special case for string. OMNIUI_API void setValue(std::string value) override; }; /** * @brief A very simple Int model. */ class OMNIUI_CLASS_API SimpleIntModel : public SimpleNumericModel<int64_t> { SIMPLENUMERICMODEL_CREATOR(SimpleIntModel) public: // Reimplemented because it's a special case for string. OMNIUI_API void setValue(std::string value) override; }; #undef SIMPLENUMERICMODEL_CREATOR OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/AbstractItemDelegate.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "AbstractItemModel.h" OMNIUI_NAMESPACE_OPEN_SCOPE class AbstractItemModel; /** * @brief AbstractItemDelegate is used to generate widgets that display and edit data items from a model. */ class OMNIUI_CLASS_API AbstractItemDelegate { public: OMNIUI_API virtual ~AbstractItemDelegate(); /** * @brief This pure abstract method must be reimplemented to generate custom collapse/expand button. */ OMNIUI_API virtual void buildBranch(const std::shared_ptr<AbstractItemModel>& model, const std::shared_ptr<const AbstractItemModel::AbstractItem>& item = nullptr, size_t index = 0, uint32_t level = 0, bool expanded = false); /** * @brief This pure abstract method must be reimplemented to generate custom widgets for specific item in the model. */ virtual void buildWidget(const std::shared_ptr<AbstractItemModel>& model, const std::shared_ptr<const AbstractItemModel::AbstractItem>& item = nullptr, size_t index = 0, uint32_t level = 0, bool expanded = false) = 0; /** * @brief This pure abstract method must be reimplemented to generate custom widgets for the header table. */ OMNIUI_API virtual void buildHeader(size_t index = 0); protected: /** * @brief Constructs AbstractItemDelegate */ OMNIUI_API AbstractItemDelegate(); }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/AbstractValueModel.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Api.h" #include <functional> #include <string> #include <unordered_set> #include <vector> OMNIUI_NAMESPACE_OPEN_SCOPE class ValueModelHelper; class OMNIUI_CLASS_API AbstractValueModel { public: OMNIUI_API virtual ~AbstractValueModel(); // We assume that all the operations with the model should be performed with smart pointers because it will register // subscription. If the object is copied or moved, it will break the subscription. // No copy AbstractValueModel(const AbstractValueModel&) = delete; // No copy-assignment AbstractValueModel& operator=(const AbstractValueModel&) = delete; // No move constructor and no move-assignments are allowed because of 12.8 [class.copy]/9 and 12.8 [class.copy]/20 // of the C++ standard /** * @brief Return the bool representation of the value. */ virtual bool getValueAsBool() const = 0; /** * @brief Return the float representation of the value. */ virtual double getValueAsFloat() const = 0; /** * @brief Return the int representation of the value. */ virtual int64_t getValueAsInt() const = 0; /** * @brief Return the string representation of the value. */ virtual std::string getValueAsString() const = 0; /** * @brief A helper that calls the correct getValueXXX method. */ template <class T> OMNIUI_API T getValue() const; /** * @brief Called when the user starts the editing. If it's a field, this method is called when the user activates * the field and places the cursor inside. This method should be reimplemented. */ OMNIUI_API virtual void beginEdit(); /** * @brief Called when the user finishes the editing. If it's a field, this method is called when the user presses * Enter or selects another field for editing. It's useful for undo/redo. This method should be reimplemented. */ OMNIUI_API virtual void endEdit(); /** * @brief Set the value. */ virtual void setValue(bool value) = 0; virtual void setValue(double value) = 0; virtual void setValue(int64_t value) = 0; virtual void setValue(std::string value) = 0; /** * @brief Subscribe the ValueModelHelper widget to the changes of the model. * * We need to use regular pointers because we subscribe in the constructor of the widget and unsubscribe in the * destructor. In constructor smart pointers are not available. We also don't allow copy and move of the widget. */ OMNIUI_API void subscribe(ValueModelHelper* widget); /** * @brief Unsubscribe the ValueModelHelper widget from the changes of the model. */ OMNIUI_API void unsubscribe(ValueModelHelper* widget); /** * @brief Adds the function that will be called every time the value changes. * * @return The id of the callback that is used to remove the callback. */ OMNIUI_API uint32_t addValueChangedFn(std::function<void(const AbstractValueModel*)> fn); /** * @brief Remove the callback by its id. * * @param id The id that addValueChangedFn returns. */ OMNIUI_API void removeValueChangedFn(uint32_t id); /** * @brief Adds the function that will be called every time the user starts the editing. * * @return The id of the callback that is used to remove the callback. */ OMNIUI_API uint32_t addBeginEditFn(std::function<void(const AbstractValueModel*)> fn); /** * @brief Remove the callback by its id. * * @param id The id that addBeginEditFn returns. */ OMNIUI_API void removeBeginEditFn(uint32_t id); /** * @brief Adds the function that will be called every time the user finishes the editing. * * @return The id of the callback that is used to remove the callback. */ OMNIUI_API uint32_t addEndEditFn(std::function<void(const AbstractValueModel*)> fn); /** * @brief Remove the callback by its id. * * @param id The id that addEndEditFn returns. */ OMNIUI_API void removeEndEditFn(uint32_t id); /** * @brief Called by the widget when the user starts editing. It calls beginEdit and the callbacks. */ OMNIUI_API void processBeginEditCallbacks(); /** * @brief Called by the widget when the user finishes editing. It calls endEdit and the callbacks. */ OMNIUI_API void processEndEditCallbacks(); protected: friend class AbstractMultiField; /** * @brief Constructs AbstractValueModel */ OMNIUI_API AbstractValueModel(); /** * @brief Called when any data of the model is changed. It will notify the subscribed widgets. */ OMNIUI_API void _valueChanged(); // All the widgets who use this model. See description of subscribe for the information why it's regular pointers. // TODO: we can use m_callbacks for subscribe-unsubscribe. But in this way it's nesessary to keep widget-id map. // When the _valueChanged code will be more complicated, we need to do it. Now it's simple enought and m_widgets // stays here. std::unordered_set<ValueModelHelper*> m_widgets; // Callbacks that called when the value is changed. std::vector<std::function<void(const AbstractValueModel*)>> m_valueChangedCallbacks; // Callbacks that called when the user starts the editing. std::vector<std::function<void(const AbstractValueModel*)>> m_beginEditCallbacks; // Callbacks that called when the user finishes the editing. std::vector<std::function<void(const AbstractValueModel*)>> m_endEditCallbacks; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/InvisibleButton.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Widget.h" #include <functional> OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief The InvisibleButton widget provides a transparent command button. */ class OMNIUI_CLASS_API InvisibleButton : public Widget { OMNIUI_OBJECT(InvisibleButton) public: OMNIUI_API ~InvisibleButton() override; /** * @brief Sets the function that will be called when when the button is activated (i.e., pressed down then released * while the mouse cursor is inside the button). */ OMNIUI_CALLBACK(Clicked, void); protected: /** * Constructor. */ OMNIUI_API InvisibleButton(); /** * @brief Reimplemented the rendering code of the widget. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; private: /** * @brief Called then the user clicks this button. */ OMNIUI_API virtual void _clicked(); std::function<void()> m_clickedFn; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/MenuDelegate.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Api.h" #include "Callback.h" #include "Property.h" #include <memory> #include <functional> OMNIUI_NAMESPACE_OPEN_SCOPE class MenuHelper; /** * @brief MenuDelegate is used to generate widgets that represent the menu item. */ class OMNIUI_CLASS_API MenuDelegate : CallbackHelper<MenuDelegate> { public: /** * @brief Constructor */ OMNIUI_API MenuDelegate(); OMNIUI_API virtual ~MenuDelegate(); /** * @brief This method must be reimplemented to generate custom item. */ OMNIUI_API virtual void buildItem(const MenuHelper* item); /** * @brief This method must be reimplemented to generate custom title. */ OMNIUI_API virtual void buildTitle(const MenuHelper* item); /** * @brief This method must be reimplemented to generate custom widgets on * the bottom of the window. */ OMNIUI_API virtual void buildStatus(const MenuHelper* item); /** * @brief Get the default delegate that is used when the menu doesn't have * anything. */ OMNIUI_API static const std::shared_ptr<MenuDelegate>& getDefaultDelegate(); /** * @brief Set the default delegate to use it when the item doesn't have a * delegate. */ OMNIUI_API static void setDefaultDelegate(std::shared_ptr<MenuDelegate> delegate); /** * @brief Called to create a new item */ OMNIUI_CALLBACK(OnBuildItem, void, MenuHelper const*); /** * @brief Called to create a new title */ OMNIUI_CALLBACK(OnBuildTitle, void, MenuHelper const*); /** * @brief Called to create a new widget on the bottom of the window */ OMNIUI_CALLBACK(OnBuildStatus, void, MenuHelper const*); /** * @brief Determine if Menu children should use this delegate when they * don't have the own one. */ OMNIUI_PROPERTY(bool, propagate, DEFAULT, true, READ_VALUE, isPropagate, WRITE, setPropagate); private: /** * @brief Return true if at least one of the siblings have the hotkey text. */ static bool _siblingsHaveHotkeyText(const MenuHelper* item); /** * @brief Return true if at least one of the siblings is checkable. */ static bool _siblingsHaveCheckable(const MenuHelper* item); }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/BezierCurve.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "ArrowHelper.h" #include "Shape.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief Smooth curve that can be scaled infinitely. */ class OMNIUI_CLASS_API BezierCurve : public Shape, public ArrowHelper { OMNIUI_OBJECT(BezierCurve) public: OMNIUI_API ~BezierCurve() override; /** * @brief Sets the function that will be called when the user use mouse enter/leave on the line. It's the override * to prevent Widget from the bounding box logic. * The function specification is: * void onMouseHovered(bool hovered) */ OMNIUI_API void setMouseHoveredFn(std::function<void(bool)> fn) override; /** * @brief Sets the function that will be called when the user presses the mouse button inside the widget. The * function should be like this: * void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) * * It's the override to prevent the bounding box logic. * * Where: * button is the number of the mouse button pressed * modifier is the flag for the keyboard modifier key */ OMNIUI_API void setMousePressedFn(std::function<void(float, float, int32_t, carb::input::KeyboardModifierFlags)> fn) override; /** * @brief Sets the function that will be called when the user releases the mouse button if this button was pressed * inside the widget. * void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) */ OMNIUI_API void setMouseReleasedFn(std::function<void(float, float, int32_t, carb::input::KeyboardModifierFlags)> fn) override; /** * @brief Sets the function that will be called when the user presses the mouse button twice inside the widget. The * function specification is the same as in setMousePressedFn. * void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) */ OMNIUI_API void setMouseDoubleClickedFn(std::function<void(float, float, int32_t, carb::input::KeyboardModifierFlags)> fn) override; /** * @brief This property holds the X coordinate of the start of the curve relative to the width bound of the curve. */ OMNIUI_PROPERTY( Length, startTangentWidth, DEFAULT, Fraction{ 1.0f }, READ, getStartTangentWidth, WRITE, setStartTangentWidth); /** * @brief This property holds the Y coordinate of the start of the curve relative to the width bound of the curve. */ OMNIUI_PROPERTY( Length, startTangentHeight, DEFAULT, Pixel{ 0.0f }, READ, getStartTangentHeight, WRITE, setStartTangentHeight); /** * @brief This property holds the X coordinate of the end of the curve relative to the width bound of the curve. */ OMNIUI_PROPERTY(Length, endTangentWidth, DEFAULT, Fraction{ -1.0f }, READ, getEndTangentWidth, WRITE, setEndTangentWidth); /** * @brief This property holds the Y coordinate of the end of the curve relative to the width bound of the curve. */ OMNIUI_PROPERTY(Length, endTangentHeight, DEFAULT, Pixel{ 0.0f }, READ, getEndTangentHeight, WRITE, setEndTangentHeight); protected: /** * @brief Initialize the the curve. */ OMNIUI_API BezierCurve(); /** * @brief Reimplemented the rendering code of the shape. * * @see Widget::_drawContent */ OMNIUI_API void _drawShape(float elapsedTime, float x, float y, float width, float height) override; /** * @brief Reimplemented the draw shadow of the shape. */ OMNIUI_API void _drawShadow( float elapsedTime, float x, float y, float width, float height, uint32_t shadowColor, float dpiScale, ImVec2 shadowOffset, float shadowThickness, uint32_t shadowFlag) override; private: /** * @brief Return width/height of two tangents. */ void _evaluateTangents( float width, float height, float& startWidth, float& startHeight, float& endWidth, float& endHeight) const; // void _calculteNormalPoints( // const ImVec2& p1, const ImVec2& p2, float dist, int id, int size, std::vector<ImVec2>& points); // Don't use m_mouseHoveredFn and m_isHovered to prevent the bbox logic of Widget. std::function<void(bool)> m_mouseHoveredLineFn; bool m_isHoveredLine = false; // Don't use m_mousePressedFn to prevent the bbox logic of Widget. std::function<void(float, float, int32_t, carb::input::KeyboardModifierFlags)> m_mousePressedLineFn; std::function<void(float, float, int32_t, carb::input::KeyboardModifierFlags)> m_mouseReleasedLineFn; std::function<void(float, float, int32_t, carb::input::KeyboardModifierFlags)> m_mouseDoubleClickedLineFn; }; OMNIUI_NAMESPACE_CLOSE_SCOPE
omniverse-code/kit/include/omni/ui/ToolButton.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include "Button.h" #include "ValueModelHelper.h" OMNIUI_NAMESPACE_OPEN_SCOPE /** * @brief ToolButton is functionally similar to Button, but provides a model that determines if the button is checked. * This button toggles between checked (on) and unchecked (off) when the user clicks it. */ class OMNIUI_CLASS_API ToolButton : public Button, public ValueModelHelper { OMNIUI_OBJECT(ToolButton) public: OMNIUI_API ~ToolButton() override; /** * @brief Reimplemented from ValueModelHelper. It's called when the model is changed. */ OMNIUI_API void onModelUpdated() override; protected: /** * @brief Construct a checkable button with the model. If the bodel is not provided, then the default model is * created. * * @param model The model that determines if the button is checked. */ OMNIUI_API ToolButton(const std::shared_ptr<AbstractValueModel>& model = {}); /** * @brief Reimplemented the rendering code of the widget. * * @see Widget::_drawContent */ OMNIUI_API void _drawContent(float elapsedTime) override; private: /** * @brief Reimplemented from InvisibleButton. Called then the user clicks this button. We don't use `m_clickedFn` * because the user can set it. If we are using it in our internal code and the user overrides it, the behavior of * the button will be changed. */ OMNIUI_API void _clicked() override; // Flag to call onModelUpdated bool m_modelUpdated = false; }; OMNIUI_NAMESPACE_CLOSE_SCOPE