file_path
stringlengths
20
202
content
stringlengths
9
3.85M
size
int64
9
3.85M
lang
stringclasses
9 values
avg_line_length
float64
3.33
100
max_line_length
int64
8
993
alphanum_fraction
float64
0.26
0.93
omniverse-code/kit/include/omni/structuredlog/StructuredLog.Cloud.python.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. // // DO NOT MODIFY THIS FILE. This is a generated file. // This file was generated from: StructuredLog.Cloud.schema #pragma once #include <carb/BindingsPythonUtils.h> #include "StructuredLog.Cloud.gen.h" namespace omni { namespace telemetry { struct Struct_Wrap_startup_ident { /** The identifier of the cluster this pod is running on. */ std::string cluster; /** The identifier of the node this pod is running on. This will be * either a hostname or the IPv4/IPv6 address of the node. */ std::string node; }; struct Struct_Wrap_startup_application { /** The name of the app that is starting up. */ std::string name; /** The version of the app that is starting up. */ std::string version; }; struct Struct_Wrap_exit_application { /** The name of the app that is starting up. */ std::string name; /** The version of the app that is starting up. */ std::string version; }; class Wrap_omni_carb_cloud { public: Wrap_omni_carb_cloud() = default; ~Wrap_omni_carb_cloud() = default; void startup_sendEvent(std::string cloud_link_id, const Struct_Wrap_startup_ident& ident, const Struct_Wrap_startup_application& application) { Schema_omni_carb_cloud_1_0::Struct_startup_ident ident_ = {}; ident_.cluster = ident.cluster; ident_.node = ident.node; Schema_omni_carb_cloud_1_0::Struct_startup_application application_ = {}; application_.name = application.name; application_.version = application.version; OMNI_STRUCTURED_LOG(Schema_omni_carb_cloud_1_0::startup, cloud_link_id, ident_, application_); } void heartbeat_sendEvent(std::string cloud_link_id) { OMNI_STRUCTURED_LOG(Schema_omni_carb_cloud_1_0::heartbeat, cloud_link_id); } void exit_sendEvent(std::string cloud_link_id, const Struct_Wrap_exit_application& application, bool exit_abnormally) { Schema_omni_carb_cloud_1_0::Struct_exit_application application_ = {}; application_.name = application.name; application_.version = application.version; OMNI_STRUCTURED_LOG(Schema_omni_carb_cloud_1_0::exit, cloud_link_id, application_, exit_abnormally); } }; inline void definePythonModule_omni_carb_cloud(py::module& m) { using namespace omni::structuredlog; m.doc() = "bindings for structured log schema omni.carb.cloud"; { py::class_<Struct_Wrap_startup_ident> bind_ident(m, "Struct_startup_ident"); bind_ident.def(py::init<>()); bind_ident.def_readwrite("cluster", &Struct_Wrap_startup_ident::cluster); bind_ident.def_readwrite("node", &Struct_Wrap_startup_ident::node); } { py::class_<Struct_Wrap_startup_application> bind_application(m, "Struct_startup_application"); bind_application.def(py::init<>()); bind_application.def_readwrite("name", &Struct_Wrap_startup_application::name); bind_application.def_readwrite("version", &Struct_Wrap_startup_application::version); } { py::class_<Struct_Wrap_exit_application> bind_application(m, "Struct_exit_application"); bind_application.def(py::init<>()); bind_application.def_readwrite("name", &Struct_Wrap_exit_application::name); bind_application.def_readwrite("version", &Struct_Wrap_exit_application::version); } // the main structured log class py::class_<Wrap_omni_carb_cloud>(m, "Schema_omni_carb_cloud_1_0") .def(py::init<>()) .def("startup_sendEvent", &Wrap_omni_carb_cloud::startup_sendEvent, py::arg("cloud_link_id"), py::arg("ident"), py::arg("application")) .def("heartbeat_sendEvent", &Wrap_omni_carb_cloud::heartbeat_sendEvent, py::arg("cloud_link_id")) .def("exit_sendEvent", &Wrap_omni_carb_cloud::exit_sendEvent, py::arg("cloud_link_id"), py::arg("application"), py::arg("exit_abnormally")); } } // namespace telemetry } // namespace omni
4,450
C
35.785124
121
0.669888
omniverse-code/kit/include/omni/structuredlog/JsonTreeSerializer.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 Module for Serializing the @ref omni::structuredlog::JsonNode tree structures. */ #pragma once #include "JsonSerializer.h" #include "BinarySerializer.h" #include "JsonTree.h" namespace omni { namespace structuredlog { /** Default value for the onValidationError template parameter. * @param[in] s The validation error message. This is ignored. */ static inline void ignoreJsonTreeSerializerValidationError(const char* s) { CARB_UNUSED(s); } /** Serialize a scalar type from a JSON tree. * @param[inout] serial The JSON serializer to serialize the data into. * @param[in] root The node in the schema that represents this scalar value. * @param[in] constVal The constant value from the data union of @p root. * This is only read if root is marked as constant. * @param[inout] reader The blob reader, which will be read if @p root is not * marked as constant. * * @returns `true` if no validation error occurred. * @returns `false` if any form of validation error occurred. */ template <bool validate = false, typename T, typename JsonSerializerType = JsonSerializer<false, false, ignoreJsonTreeSerializerValidationError>, typename JsonNodeType = JsonNode, typename BlobReaderType = BlobReader<false, ignoreJsonTreeSerializerValidationError>> static inline bool serializeScalar(JsonSerializerType* serial, const JsonNodeType* root, T constVal, BlobReaderType* reader) { if ((root->flags & JsonNode::fFlagConst) != 0) { return serial->writeValue(constVal); } else { T b = {}; bool result = reader->read(&b); if (validate && !result) return false; return serial->writeValue(b); } } /** Serialize an array type from a JSON tree. * @param[inout] serial The JSON serializer to serialize the data into. * @param[in] root The node in the schema that represents this scalar value. * @param[in] constVal The constant array value from the data union of @p root. * This is only read if root is marked as constant; * in that case, this is of length @p root->len. * @param[inout] reader The blob reader, which will be read if @p root is not * marked as constant. * * @returns `true` if no validation error occurred. * @returns `false` if any form of validation error occurred. */ template <bool validate = false, typename T, typename JsonSerializerType = JsonSerializer<false, false, ignoreJsonTreeSerializerValidationError>, typename JsonNodeType = JsonNode, typename BlobReaderType = BlobReader<false, ignoreJsonTreeSerializerValidationError>> static inline bool serializeArray(JsonSerializerType* serial, const JsonNodeType* root, const T* constVal, BlobReaderType* reader) { bool result = true; result = serial->openArray(); if (validate && !result) return false; if ((root->flags & JsonNode::fFlagConst) != 0) { for (uint16_t i = 0; i < root->len; i++) { result = serial->writeValue(constVal[i]); if (validate && !result) return false; } } else { const T* b = nullptr; uint16_t len = 0; if ((root->flags & JsonNode::fFlagFixedLength) != 0) { len = root->len; result = reader->read(&b, len); if (validate && !result) return false; } else { result = reader->read(&b, &len); if (validate && !result) return false; } for (uint16_t i = 0; i < len; i++) { result = serial->writeValue(b[i]); if (validate && !result) return false; } } return serial->closeArray(); } template <bool validate = false, typename T, typename JsonSerializerType = JsonSerializer<false, false, ignoreJsonTreeSerializerValidationError>, typename JsonNodeType = JsonNode, typename BlobReaderType = BlobReader<false, ignoreJsonTreeSerializerValidationError>> static inline bool serializeEnum(JsonSerializerType* serial, const JsonNodeType* root, T* enumChoices, BlobReaderType* reader) { JsonNode::EnumBase b = {}; bool result = reader->read(&b); if (validate && !result) return false; if (b > root->len) { char tmp[256]; carb::extras::formatString(tmp, sizeof(tmp), "enum value is out of range" " {value = %" PRIu16 ", max = %" PRIu16 "}", b, root->len); serial->m_onValidationError(tmp); return false; } return serial->writeValue(enumChoices[b]); } /** Serialize JSON using a @ref JsonNode as the schema and a binary blob to read data. * * @remarks This overload uses a @ref BlobReader instead of the binary blob * directly, so that the read position from within the blob can be * tracked across recursive calls. * External code should use the other overload. * * @note If you use this overload, you must call @p serial->finish(), since this * is the recursive overload so there's no obvious point to finish at. */ template <bool validate = false, typename JsonSerializerType = JsonSerializer<false, false, ignoreJsonTreeSerializerValidationError>, typename JsonNodeType = JsonNode, typename BlobReaderType = BlobReader<false, ignoreJsonTreeSerializerValidationError>> static inline bool serializeJsonTree(JsonSerializerType* serial, const JsonNodeType* root, BlobReaderType* reader) { bool result = true; if (root->name != nullptr) { result = serial->writeKey(root->name, root->nameLen - 1); if (validate && !result) return false; } switch (root->type) { case NodeType::eNull: return serial->writeValue(); case NodeType::eBool: return serializeScalar<validate>(serial, root, root->data.boolVal, reader); case NodeType::eInt32: return serializeScalar<validate>(serial, root, int32_t(root->data.intVal), reader); case NodeType::eUint32: return serializeScalar<validate>(serial, root, uint32_t(root->data.uintVal), reader); case NodeType::eInt64: return serializeScalar<validate>(serial, root, root->data.intVal, reader); case NodeType::eUint64: return serializeScalar<validate>(serial, root, root->data.uintVal, reader); case NodeType::eFloat32: return serializeScalar<validate>(serial, root, float(root->data.floatVal), reader); case NodeType::eFloat64: return serializeScalar<validate>(serial, root, root->data.floatVal, reader); case NodeType::eBinary: if ((root->flags & JsonNode::fFlagConst) != 0) { return serial->writeValueWithBase64Encoding(root->data.binaryVal, root->len); } else { const uint8_t* b = nullptr; uint16_t len = 0; if ((root->flags & JsonNode::fFlagFixedLength) != 0) { len = root->len; result = reader->read(&b, len); } else { result = reader->read(&b, &len); } if (validate && !result) return false; // null terminator is included in the length return serial->writeValueWithBase64Encoding(b, len); } case NodeType::eBoolArray: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum<validate>(serial, root, root->data.boolArrayVal, reader); else return serializeArray<validate>(serial, root, root->data.boolArrayVal, reader); case NodeType::eInt32Array: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum<validate>(serial, root, root->data.int32ArrayVal, reader); else return serializeArray<validate>(serial, root, root->data.int32ArrayVal, reader); case NodeType::eUint32Array: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum<validate>(serial, root, root->data.uint32ArrayVal, reader); else return serializeArray<validate>(serial, root, root->data.uint32ArrayVal, reader); case NodeType::eInt64Array: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum<validate>(serial, root, root->data.int64ArrayVal, reader); else return serializeArray<validate>(serial, root, root->data.int64ArrayVal, reader); case NodeType::eUint64Array: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum<validate>(serial, root, root->data.uint64ArrayVal, reader); else return serializeArray<validate>(serial, root, root->data.uint64ArrayVal, reader); case NodeType::eFloat32Array: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum<validate>(serial, root, root->data.float32ArrayVal, reader); else return serializeArray<validate>(serial, root, root->data.float32ArrayVal, reader); case NodeType::eFloat64Array: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum(serial, root, root->data.float64ArrayVal, reader); else return serializeArray(serial, root, root->data.float64ArrayVal, reader); case NodeType::eString: if ((root->flags & JsonNode::fFlagConst) != 0) { return serial->writeValue(root->data.strVal, (root->len == 0) ? 0 : root->len - 1); } else { const char* b = nullptr; uint16_t len = 0; if ((root->flags & JsonNode::fFlagFixedLength) != 0) { len = root->len; result = reader->read(&b, len); } else { result = reader->read(&b, &len); } if (validate && !result) return false; // null terminator is included in the length return serial->writeValue(b, (len == 0) ? 0 : len - 1); } case NodeType::eStringArray: if ((root->flags & JsonNode::fFlagEnum) != 0) return serializeEnum<validate>(serial, root, root->data.strArrayVal, reader); result = serial->openArray(); if (validate && !result) return false; if ((root->flags & JsonNode::fFlagConst) != 0) { for (uint16_t i = 0; i < root->len; i++) { result = serial->writeValue(root->data.strArrayVal[i]); if (validate && !result) return false; } } else { const char** b = nullptr; uint16_t len = 0; // fixed length isn't supported here result = reader->read(b, &len, 0); if (validate && !result) return false; // FIXME: dangerous b = static_cast<const char**>(alloca(len * sizeof(*b))); result = reader->read(b, &len, len); if (validate && !result) return false; for (uint16_t i = 0; i < len; i++) { result = serial->writeValue(b[i]); if (validate && !result) return false; } } return serial->closeArray(); case NodeType::eObject: result = serial->openObject(); if (validate && !result) return false; for (uint16_t i = 0; i < root->len; i++) { result = serializeJsonTree<validate>(serial, &root->data.objVal[i], reader); if (validate && !result) return false; } return serial->closeObject(); case NodeType::eObjectArray: result = serial->openArray(); if (validate && !result) return false; if ((root->flags & JsonNode::fFlagFixedLength) != 0) { for (uint16_t i = 0; i < root->len; i++) { result = serializeJsonTree<validate>(serial, &root->data.objVal[i], reader); if (validate && !result) return false; } } else { uint16_t len = 0; // read the array length result = reader->read(&len); if (validate && !result) return false; // a variable length object array uses the same object schema for // each object in the array, so we just pass the 0th element here for (uint16_t i = 0; i < len; i++) { result = serializeJsonTree<validate>(serial, &root->data.objVal[0], reader); if (validate && !result) return false; } } return serial->closeArray(); } return false; } /** Serialize JSON using a @ref JsonNode as the schema and a binary blob to read data. * @param[inout] serial The JSON serializer to serialize the data into. * @param[in] root The JSON tree to use for the data schema. * @param[in] blob The binary blob to read data directly from. * @param[in] blobSize The length of @p blob in bytes. * * @tparam validate If this is true, validation will be performed. * This ensures the output JSON will be valid. * This also will add bounds checking onto @p blob. * If this is false, out of bounds reading is possible * when the blob was generated incorrectly. * @tparam prettyPrint If this is set to false, the output will be printed * with minimal spacing. * Human-readable spacing will be used otherwise. * @tparam onValidationError This callback will be used when a validation error * occurs, so that logging can be performed. * * @returns `true` if no validation error occurred. * @returns `false` if any form of validation error occurred. */ template <bool validate = false, typename JsonSerializerType = JsonSerializer<false, false, ignoreJsonTreeSerializerValidationError>, typename JsonNodeType = JsonNode, typename BlobReaderType = BlobReader<false, ignoreJsonTreeSerializerValidationError>> static inline bool serializeJsonTree(JsonSerializerType* serial, const JsonNodeType* root, const void* blob, size_t blobSize) { BlobReaderType reader(blob, blobSize); return serializeJsonTree<validate>(serial, root, &reader) && serial->finish(); } /* we don't extract static symbols so this breaks exhale somehow */ #ifndef DOXYGEN_SHOULD_SKIP_THIS /** @copydoc serializeJsonSchema */ template <typename JsonSerializerType = JsonSerializer<true, true>, typename JsonNodeType = JsonNode> static inline void serializeJsonSchema_(JsonSerializerType* serial, const JsonNodeType* root) { auto nodeTypeString = [](NodeType n) -> const char* { switch (n) { case NodeType::eNull: return "null"; case NodeType::eBool: return "boolean"; case NodeType::eInt32: return "integer"; case NodeType::eUint32: return "uint32"; case NodeType::eInt64: return "int64"; case NodeType::eUint64: return "uint64"; case NodeType::eFloat32: return "float"; case NodeType::eFloat64: return "double"; case NodeType::eBinary: return "binary"; case NodeType::eBoolArray: return "bool[]"; case NodeType::eInt32Array: return "integer[]"; case NodeType::eUint32Array: return "uint32[]"; case NodeType::eInt64Array: return "int64[]"; case NodeType::eUint64Array: return "uint64[]"; case NodeType::eFloat32Array: return "float[]"; case NodeType::eFloat64Array: return "double[]"; case NodeType::eString: return "string"; case NodeType::eStringArray: return "string[]"; case NodeType::eObject: return "object"; case NodeType::eObjectArray: return "object[]"; } return "unknown"; }; if (root->name != nullptr) { serial->writeKey(root->name, root->nameLen - 1); } serial->openObject(); serial->writeKey("type"); serial->writeValue(nodeTypeString(root->type)); serial->writeKey("flags"); serial->writeValue(root->flags); if ((root->flags & JsonNode::fFlagConst) != 0) { serial->writeKey("const"); switch (root->type) { case NodeType::eNull: serial->writeValue(); break; case NodeType::eBool: serial->writeValue(root->data.boolVal); break; case NodeType::eInt32: serial->writeValue(root->data.intVal); break; case NodeType::eUint32: serial->writeValue(root->data.uintVal); break; case NodeType::eInt64: serial->writeValue(root->data.intVal); break; case NodeType::eUint64: serial->writeValue(root->data.uintVal); break; case NodeType::eFloat32: serial->writeValue(root->data.floatVal); break; case NodeType::eFloat64: serial->writeValue(root->data.floatVal); break; case NodeType::eBinary: serial->writeValueWithBase64Encoding(root->data.binaryVal, root->len); break; case NodeType::eBoolArray: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.boolArrayVal[i]); } serial->closeArray(); break; case NodeType::eInt32Array: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.int32ArrayVal[i]); } serial->closeArray(); break; case NodeType::eUint32Array: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.uint32ArrayVal[i]); } serial->closeArray(); break; case NodeType::eInt64Array: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.int64ArrayVal[i]); } serial->closeArray(); break; case NodeType::eUint64Array: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.uint64ArrayVal[i]); } serial->closeArray(); break; case NodeType::eFloat32Array: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.float32ArrayVal[i]); } serial->closeArray(); break; case NodeType::eFloat64Array: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.float64ArrayVal[i]); } serial->closeArray(); break; case NodeType::eString: serial->writeValue(root->data.strVal, (root->len == 0) ? 0 : root->len - 1); break; case NodeType::eStringArray: serial->openArray(); for (uint16_t i = 0; i < root->len; i++) { serial->writeValue(root->data.strArrayVal[i]); } serial->closeArray(); break; case NodeType::eObject: serial->writeValue(); break; case NodeType::eObjectArray: serial->openArray(); serial->closeArray(); break; } } if ((root->flags & JsonNode::fFlagEnum) != 0) { serial->writeKey("enum"); serial->writeValue(true); } if (root->type == NodeType::eObject || root->type == NodeType::eObjectArray) { serial->writeKey("properties"); serial->openObject(); for (size_t i = 0; i < root->len; i++) { serializeJsonSchema_(serial, &root->data.objVal[i]); } serial->closeObject(); } serial->closeObject(); } /** Serialize a JSON schema to JSON. * @param[in] serial The serializer object to use. * @param[in] root The schema being serialized. * @remarks This function will serialize a JSON schema to JSON. * This is mainly intended to be used for debugging. * serializeJsonTree() can't be used for serializing the schema because * a binary blob is needed for the variable values in the schema. */ template <typename JsonSerializerType = JsonSerializer<true, true>, typename JsonNodeType = JsonNode> static inline void serializeJsonSchema(JsonSerializerType* serial, const JsonNodeType* root) { serializeJsonSchema_(serial, root); serial->finish(); } #endif } // namespace structuredlog } // namespace omni
23,705
C
35.867807
126
0.538789
omniverse-code/kit/include/omni/structuredlog/StructuredLog.Cloud.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. // // DO NOT MODIFY THIS FILE. This is a generated file. // This file was generated from: StructuredLog.Cloud.schema // #pragma once #include <omni/log/ILog.h> #include <omni/structuredlog/IStructuredLog.h> #include <omni/structuredlog/JsonTree.h> #include <omni/structuredlog/BinarySerializer.h> #include <omni/structuredlog/StringView.h> #include <memory> namespace omni { namespace telemetry { /** helper macro to send the 'startup' event. * * @param[in] cloud_link_id_ Parameter from schema at path '/cloud_link_id'. * The UUID of the cloud session that is currently running Kit or * NVStreamer. This is used to link together events across multiple * sessions or instances that are running under the same cloud * session. * @param[in] ident_ Parameter from schema at path '/ident'. * The information of where this pod is running. * @param[in] application_ Parameter from schema at path '/application'. * The information about which app is being run. This is duplicated * information and should be removed eventually. * @returns no return value. * * @remarks This event notes which Kit or NVStreamer based app was launched, * its version, the user, node, and cluster information, and the * cloud session ID that needs to be linked to this telemetry session * ID. * * @sa @ref Schema_omni_carb_cloud_1_0::startup_sendEvent(). * @sa @ref Schema_omni_carb_cloud_1_0::startup_isEnabled(). */ #define OMNI_OMNI_CARB_CLOUD_1_0_STARTUP(cloud_link_id_, ident_, application_) \ OMNI_STRUCTURED_LOG(omni::telemetry::Schema_omni_carb_cloud_1_0::startup, cloud_link_id_, ident_, application_) /** helper macro to send the 'heartbeat' event. * * @param[in] cloud_link_id_ Parameter from schema at path '/cloud_link_id'. * The UUID of the cloud session that is currently running Kit or * NVStreamer. This is used to link together events across multiple * sessions or instances that are running under the same cloud * session. * @returns no return value. * * @remarks This event notes that the app is still running. The intention is * that this event should be emitted periodically to provide a way to * estimate session lengths even in cases where the exit event is not * present (ie: unexpected exit, power loss, process killed by the * user, etc). * * @sa @ref Schema_omni_carb_cloud_1_0::heartbeat_sendEvent(). * @sa @ref Schema_omni_carb_cloud_1_0::heartbeat_isEnabled(). */ #define OMNI_OMNI_CARB_CLOUD_1_0_HEARTBEAT(cloud_link_id_) \ OMNI_STRUCTURED_LOG(omni::telemetry::Schema_omni_carb_cloud_1_0::heartbeat, cloud_link_id_) /** helper macro to send the 'exit' event. * * @param[in] cloud_link_id_ Parameter from schema at path '/cloud_link_id'. * The UUID of the cloud session that is currently running Kit or * NVStreamer. This is used to link together events across multiple * sessions or instances that are running under the same cloud * session. * @param[in] application_ Parameter from schema at path '/application'. * The information about which app is being run. This is duplicated * information and should be removed eventually. * @param[in] exit_abnormally_ Parameter from schema at path '/exit_abnormally'. * A flag indicating whether a crash occurred (true) or if a normal * exit was used (false). * @returns no return value. * * @remarks This event notes which Kit or NVStreamer based app was exited, its * version, whether the exit was clean or not, and the cloud session * ID that needs to be linked to this telemetry session ID. * * @sa @ref Schema_omni_carb_cloud_1_0::exit_sendEvent(). * @sa @ref Schema_omni_carb_cloud_1_0::exit_isEnabled(). */ #define OMNI_OMNI_CARB_CLOUD_1_0_EXIT(cloud_link_id_, application_, exit_abnormally_) \ OMNI_STRUCTURED_LOG( \ omni::telemetry::Schema_omni_carb_cloud_1_0::exit, cloud_link_id_, application_, exit_abnormally_) class Schema_omni_carb_cloud_1_0 { public: /** struct definition for parameter ident of event com.nvidia.omni.carb.cloud.startup. */ struct Struct_startup_ident { /** The identifier of the cluster this pod is running on. */ omni::structuredlog::StringView cluster; /** The identifier of the node this pod is running on. This will be * either a hostname or the IPv4/IPv6 address of the node. */ omni::structuredlog::StringView node; /** Default constructor for @ref Struct_startup_ident. */ Struct_startup_ident() = default; /** Basic constructor for @ref Struct_startup_ident. */ Struct_startup_ident(omni::structuredlog::StringView cluster_, omni::structuredlog::StringView node_) { cluster = cluster_; node = node_; } /** Basic assignment operator for @ref Struct_startup_ident. */ Struct_startup_ident& operator=(const Struct_startup_ident& other) { cluster = other.cluster; node = other.node; return *this; } /** Basic copy constructor for @ref Struct_startup_ident. */ Struct_startup_ident(const Struct_startup_ident& other) { *this = other; } }; /** struct definition for parameter application of event com.nvidia.omni.carb.cloud.startup. */ struct Struct_startup_application { /** The name of the app that is starting up. */ omni::structuredlog::StringView name; /** The version of the app that is starting up. */ omni::structuredlog::StringView version; /** Default constructor for @ref Struct_startup_application. */ Struct_startup_application() = default; /** Basic constructor for @ref Struct_startup_application. */ Struct_startup_application(omni::structuredlog::StringView name_, omni::structuredlog::StringView version_) { name = name_; version = version_; } /** Basic assignment operator for @ref Struct_startup_application. */ Struct_startup_application& operator=(const Struct_startup_application& other) { name = other.name; version = other.version; return *this; } /** Basic copy constructor for @ref Struct_startup_application. */ Struct_startup_application(const Struct_startup_application& other) { *this = other; } }; /** struct definition for parameter application of event com.nvidia.omni.carb.cloud.exit. */ struct Struct_exit_application { /** The name of the app that is starting up. */ omni::structuredlog::StringView name; /** The version of the app that is starting up. */ omni::structuredlog::StringView version; /** Default constructor for @ref Struct_exit_application. */ Struct_exit_application() = default; /** Basic constructor for @ref Struct_exit_application. */ Struct_exit_application(omni::structuredlog::StringView name_, omni::structuredlog::StringView version_) { name = name_; version = version_; } /** Basic assignment operator for @ref Struct_exit_application. */ Struct_exit_application& operator=(const Struct_exit_application& other) { name = other.name; version = other.version; return *this; } /** Basic copy constructor for @ref Struct_exit_application. */ Struct_exit_application(const Struct_exit_application& other) { *this = other; } }; /** the event ID names used to send the events in this schema. These IDs * are used when the schema is first registered, and are passed to the * allocEvent() function when sending the event. */ enum : uint64_t { kStartupEventId = OMNI_STRUCTURED_LOG_EVENT_ID("omni.carb.cloud", "com.nvidia.omni.carb.cloud.startup", "1.0", "0"), kHeartbeatEventId = OMNI_STRUCTURED_LOG_EVENT_ID("omni.carb.cloud", "com.nvidia.omni.carb.cloud.heartbeat", "1.0", "0"), kExitEventId = OMNI_STRUCTURED_LOG_EVENT_ID("omni.carb.cloud", "com.nvidia.omni.carb.cloud.exit", "1.0", "0"), }; Schema_omni_carb_cloud_1_0() = default; /** Register this class with the @ref omni::structuredlog::IStructuredLog interface. * @param[in] flags The flags to pass into @ref omni::structuredlog::IStructuredLog::allocSchema() * This may be zero or more of the @ref omni::structuredlog::SchemaFlags flags. * @returns `true` if the operation succeeded. * @returns `false` if @ref omni::structuredlog::IStructuredLog couldn't be loaded. * @returns `false` if a memory allocation failed. */ static bool registerSchema(omni::structuredlog::IStructuredLog* strucLog) noexcept { return _registerSchema(strucLog); } /** Check whether this structured log schema is enabled. * @param[in] eventId the ID of the event to check the enable state for. * This must be one of the @a k*EventId symbols * defined above. * @returns Whether this client is enabled. */ static bool isEnabled(omni::structuredlog::EventId eventId) noexcept { return _isEnabled(eventId); } /** Enable/disable an event in this schema. * @param[in] eventId the ID of the event to enable or disable. * This must be one of the @a k*EventId symbols * defined above. * @param[in] enabled Whether is enabled or disabled. */ static void setEnabled(omni::structuredlog::EventId eventId, bool enabled) noexcept { _setEnabled(eventId, enabled); } /** Enable/disable this schema. * @param[in] enabled Whether is enabled or disabled. */ static void setEnabled(bool enabled) noexcept { _setEnabled(enabled); } /** event enable check helper functions. * * @param[in] strucLog The structured log object to use to send this event. This * must not be nullptr. It is the caller's responsibility * to ensure that a valid object is passed in. * @returns `true` if the specific event and this schema are both enabled. * @returns `false` if either the specific event or this schema is disabled. * * @remarks These check if an event corresponding to the function name is currently * enabled. These are useful to avoid parameter evaluation before calling * into one of the event emitter functions. These will be called from the * OMNI_STRUCTURED_LOG() macro. These may also be called directly if an event * needs to be emitted manually, but the only effect would be the potential * to avoid parameter evaluation in the *_sendEvent() function. Each * *_sendEvent() function itself will also internally check if the event * is enabled before sending it. * @{ */ static bool startup_isEnabled(omni::structuredlog::IStructuredLog* strucLog) noexcept { return strucLog->isEnabled(kStartupEventId); } static bool heartbeat_isEnabled(omni::structuredlog::IStructuredLog* strucLog) noexcept { return strucLog->isEnabled(kHeartbeatEventId); } static bool exit_isEnabled(omni::structuredlog::IStructuredLog* strucLog) noexcept { return strucLog->isEnabled(kExitEventId); } /** @} */ /** Send the event 'com.nvidia.omni.carb.cloud.startup' * * @param[in] strucLog The global structured log object to use to send * this event. This must not be nullptr. It is the caller's * responsibility to ensure a valid object is passed in. * @param[in] cloud_link_id Parameter from schema at path '/cloud_link_id'. * The UUID of the cloud session that is currently running Kit or * NVStreamer. This is used to link together events across multiple * sessions or instances that are running under the same cloud * session. * @param[in] ident Parameter from schema at path '/ident'. * The information of where this pod is running. * @param[in] application Parameter from schema at path '/application'. * The information about which app is being run. This is duplicated * information and should be removed eventually. * @returns no return value. * * @remarks This event notes which Kit or NVStreamer based app was launched, * its version, the user, node, and cluster information, and the * cloud session ID that needs to be linked to this telemetry session * ID. */ static void startup_sendEvent(omni::structuredlog::IStructuredLog* strucLog, const omni::structuredlog::StringView& cloud_link_id, const Struct_startup_ident& ident, const Struct_startup_application& application) noexcept { _startup_sendEvent(strucLog, cloud_link_id, ident, application); } /** Send the event 'com.nvidia.omni.carb.cloud.heartbeat' * * @param[in] strucLog The global structured log object to use to send * this event. This must not be nullptr. It is the caller's * responsibility to ensure a valid object is passed in. * @param[in] cloud_link_id Parameter from schema at path '/cloud_link_id'. * The UUID of the cloud session that is currently running Kit or * NVStreamer. This is used to link together events across multiple * sessions or instances that are running under the same cloud * session. * @returns no return value. * * @remarks This event notes that the app is still running. The intention is * that this event should be emitted periodically to provide a way to * estimate session lengths even in cases where the exit event is not * present (ie: unexpected exit, power loss, process killed by the * user, etc). */ static void heartbeat_sendEvent(omni::structuredlog::IStructuredLog* strucLog, const omni::structuredlog::StringView& cloud_link_id) noexcept { _heartbeat_sendEvent(strucLog, cloud_link_id); } /** Send the event 'com.nvidia.omni.carb.cloud.exit' * * @param[in] strucLog The global structured log object to use to send * this event. This must not be nullptr. It is the caller's * responsibility to ensure a valid object is passed in. * @param[in] cloud_link_id Parameter from schema at path '/cloud_link_id'. * The UUID of the cloud session that is currently running Kit or * NVStreamer. This is used to link together events across multiple * sessions or instances that are running under the same cloud * session. * @param[in] application Parameter from schema at path '/application'. * The information about which app is being run. This is duplicated * information and should be removed eventually. * @param[in] exit_abnormally Parameter from schema at path '/exit_abnormally'. * A flag indicating whether a crash occurred (true) or if a normal * exit was used (false). * @returns no return value. * * @remarks This event notes which Kit or NVStreamer based app was exited, its * version, whether the exit was clean or not, and the cloud session * ID that needs to be linked to this telemetry session ID. */ static void exit_sendEvent(omni::structuredlog::IStructuredLog* strucLog, const omni::structuredlog::StringView& cloud_link_id, const Struct_exit_application& application, bool exit_abnormally) noexcept { _exit_sendEvent(strucLog, cloud_link_id, application, exit_abnormally); } private: /** This will allow us to disable array length checks in release builds, * since they would have a negative performance impact and only be hit * in unusual circumstances. */ static constexpr bool kValidateLength = CARB_DEBUG; /** body for the registerSchema() public function. */ static bool _registerSchema(omni::structuredlog::IStructuredLog* strucLog) { omni::structuredlog::AllocHandle handle = {}; omni::structuredlog::SchemaResult result; uint8_t* buffer; omni::structuredlog::EventInfo events[3] = {}; size_t bufferSize = 0; size_t total = 0; omni::structuredlog::SchemaFlags flags = 0; if (strucLog == nullptr) { OMNI_LOG_WARN( "no structured log object! The schema " "'Schema_omni_carb_cloud_1_0' " "will be disabled."); return false; } // calculate the tree sizes size_t startup_size = _startup_calculateTreeSize(); size_t heartbeat_size = _heartbeat_calculateTreeSize(); size_t exit_size = _exit_calculateTreeSize(); // calculate the event buffer size bufferSize += startup_size; bufferSize += heartbeat_size; bufferSize += exit_size; // begin schema creation buffer = strucLog->allocSchema("omni.carb.cloud", "1.0", flags, bufferSize, &handle); if (buffer == nullptr) { OMNI_LOG_ERROR("allocSchema failed (size = %zu bytes)", bufferSize); return false; } // register all the events events[0].schema = _startup_buildJsonTree(startup_size, buffer + total); events[0].eventName = "com.nvidia.omni.carb.cloud.startup"; events[0].parserVersion = 0; events[0].eventId = kStartupEventId; total += startup_size; events[1].schema = _heartbeat_buildJsonTree(heartbeat_size, buffer + total); events[1].eventName = "com.nvidia.omni.carb.cloud.heartbeat"; events[1].parserVersion = 0; events[1].eventId = kHeartbeatEventId; total += heartbeat_size; events[2].schema = _exit_buildJsonTree(exit_size, buffer + total); events[2].eventName = "com.nvidia.omni.carb.cloud.exit"; events[2].parserVersion = 0; events[2].eventId = kExitEventId; total += exit_size; result = strucLog->commitSchema(handle, events, CARB_COUNTOF(events)); if (result != omni::structuredlog::SchemaResult::eSuccess && result != omni::structuredlog::SchemaResult::eAlreadyExists) { OMNI_LOG_ERROR( "failed to register structured log events " "{result = %s (%zu)}", getSchemaResultName(result), size_t(result)); return false; } return true; } /** body for the isEnabled() public function. */ static bool _isEnabled(omni::structuredlog::EventId eventId) { omni::structuredlog::IStructuredLog* strucLog = omniGetStructuredLogWithoutAcquire(); return strucLog != nullptr && strucLog->isEnabled(eventId); } /** body for the setEnabled() public function. */ static void _setEnabled(omni::structuredlog::EventId eventId, bool enabled) { omni::structuredlog::IStructuredLog* strucLog = omniGetStructuredLogWithoutAcquire(); if (strucLog == nullptr) return; strucLog->setEnabled(eventId, 0, enabled); } /** body for the setEnabled() public function. */ static void _setEnabled(bool enabled) { omni::structuredlog::IStructuredLog* strucLog = omniGetStructuredLogWithoutAcquire(); if (strucLog == nullptr) return; strucLog->setEnabled(kStartupEventId, omni::structuredlog::fEnableFlagWholeSchema, enabled); } #if OMNI_PLATFORM_WINDOWS # pragma warning(push) # pragma warning(disable : 4127) // warning C4127: conditional expression is constant. #endif /** body for the startup_sendEvent() function. */ static void _startup_sendEvent(omni::structuredlog::IStructuredLog* strucLog, const omni::structuredlog::StringView& cloud_link_id, const Struct_startup_ident& ident, const Struct_startup_application& application) noexcept { omni::structuredlog::AllocHandle handle = {}; // calculate the required buffer size for the event omni::structuredlog::BinaryBlobSizeCalculator calc; { if (kValidateLength && cloud_link_id.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'cloud_link_id' exceeds max value 65535 - " "it will be truncated (size was %zu)", cloud_link_id.length() + 1); } // property cloud_link_id calc.track(cloud_link_id); // property ident { if (kValidateLength && ident.cluster.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'ident.cluster' exceeds max value 65535 - " "it will be truncated (size was %zu)", ident.cluster.length() + 1); } // property ident.cluster calc.track(ident.cluster); if (kValidateLength && ident.node.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'ident.node' exceeds max value 65535 - " "it will be truncated (size was %zu)", ident.node.length() + 1); } // property ident.node calc.track(ident.node); } // property application { if (kValidateLength && application.name.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'application.name' exceeds max value 65535 - " "it will be truncated (size was %zu)", application.name.length() + 1); } // property application.name calc.track(application.name); if (kValidateLength && application.version.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'application.version' exceeds max value 65535 - " "it will be truncated (size was %zu)", application.version.length() + 1); } // property application.version calc.track(application.version); } } // write out the event into the buffer void* buffer = strucLog->allocEvent(0, kStartupEventId, 0, calc.getSize(), &handle); if (buffer == nullptr) { OMNI_LOG_ERROR( "failed to allocate a %zu byte buffer for structured log event " "'com.nvidia.omni.carb.cloud.startup'", calc.getSize()); return; } omni::structuredlog::BlobWriter<CARB_DEBUG, _onStructuredLogValidationError> writer(buffer, calc.getSize()); { // property cloud_link_id writer.copy(cloud_link_id); // property ident { // property ident.cluster writer.copy(ident.cluster); // property ident.node writer.copy(ident.node); } // property application { // property application.name writer.copy(application.name); // property application.version writer.copy(application.version); } } strucLog->commitEvent(handle); } /** body for the heartbeat_sendEvent() function. */ static void _heartbeat_sendEvent(omni::structuredlog::IStructuredLog* strucLog, const omni::structuredlog::StringView& cloud_link_id) noexcept { omni::structuredlog::AllocHandle handle = {}; // calculate the required buffer size for the event omni::structuredlog::BinaryBlobSizeCalculator calc; { if (kValidateLength && cloud_link_id.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'cloud_link_id' exceeds max value 65535 - " "it will be truncated (size was %zu)", cloud_link_id.length() + 1); } // property cloud_link_id calc.track(cloud_link_id); } // write out the event into the buffer void* buffer = strucLog->allocEvent(0, kHeartbeatEventId, 0, calc.getSize(), &handle); if (buffer == nullptr) { OMNI_LOG_ERROR( "failed to allocate a %zu byte buffer for structured log event " "'com.nvidia.omni.carb.cloud.heartbeat'", calc.getSize()); return; } omni::structuredlog::BlobWriter<CARB_DEBUG, _onStructuredLogValidationError> writer(buffer, calc.getSize()); { // property cloud_link_id writer.copy(cloud_link_id); } strucLog->commitEvent(handle); } /** body for the exit_sendEvent() function. */ static void _exit_sendEvent(omni::structuredlog::IStructuredLog* strucLog, const omni::structuredlog::StringView& cloud_link_id, const Struct_exit_application& application, bool exit_abnormally) noexcept { omni::structuredlog::AllocHandle handle = {}; // calculate the required buffer size for the event omni::structuredlog::BinaryBlobSizeCalculator calc; { if (kValidateLength && cloud_link_id.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'cloud_link_id' exceeds max value 65535 - " "it will be truncated (size was %zu)", cloud_link_id.length() + 1); } // property cloud_link_id calc.track(cloud_link_id); // property application { if (kValidateLength && application.name.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'application.name' exceeds max value 65535 - " "it will be truncated (size was %zu)", application.name.length() + 1); } // property application.name calc.track(application.name); if (kValidateLength && application.version.length() + 1 > UINT16_MAX) { OMNI_LOG_ERROR( "length of parameter 'application.version' exceeds max value 65535 - " "it will be truncated (size was %zu)", application.version.length() + 1); } // property application.version calc.track(application.version); } // property exit_abnormally calc.track(exit_abnormally); } // write out the event into the buffer void* buffer = strucLog->allocEvent(0, kExitEventId, 0, calc.getSize(), &handle); if (buffer == nullptr) { OMNI_LOG_ERROR( "failed to allocate a %zu byte buffer for structured log event " "'com.nvidia.omni.carb.cloud.exit'", calc.getSize()); return; } omni::structuredlog::BlobWriter<CARB_DEBUG, _onStructuredLogValidationError> writer(buffer, calc.getSize()); { // property cloud_link_id writer.copy(cloud_link_id); // property application { // property application.name writer.copy(application.name); // property application.version writer.copy(application.version); } // property exit_abnormally writer.copy(exit_abnormally); } strucLog->commitEvent(handle); } #if OMNI_PLATFORM_WINDOWS # pragma warning(pop) #endif /** Calculate JSON tree size for structured log event: com.nvidia.omni.carb.cloud.startup. * @returns The JSON tree size in bytes for this event. */ static size_t _startup_calculateTreeSize() { // calculate the buffer size for the tree omni::structuredlog::JsonTreeSizeCalculator calc; calc.trackRoot(); calc.trackObject(5); // object has 5 properties { // property cloud_link_id calc.trackName("cloud_link_id"); calc.track(static_cast<const char*>(nullptr)); // property ident calc.trackName("ident"); calc.trackObject(2); // object has 2 properties { // property cluster calc.trackName("cluster"); calc.track(static_cast<const char*>(nullptr)); // property node calc.trackName("node"); calc.track(static_cast<const char*>(nullptr)); } // property application calc.trackName("application"); calc.trackObject(2); // object has 2 properties { // property name calc.trackName("name"); calc.track(static_cast<const char*>(nullptr)); // property version calc.trackName("version"); calc.track(static_cast<const char*>(nullptr)); } // property version calc.trackName("version"); calc.track("1", sizeof("1")); // property event calc.trackName("event"); calc.track("cloud-startup", sizeof("cloud-startup")); } return calc.getSize(); } /** Generate the JSON tree for structured log event: com.nvidia.omni.carb.cloud.startup. * @param[in] bufferSize The length of @p buffer in bytes. * @param[inout] buffer The buffer to write the tree into. * @returns The JSON tree for this event. * @returns nullptr if a logic error occurred or @p bufferSize was too small. */ static omni::structuredlog::JsonNode* _startup_buildJsonTree(size_t bufferSize, uint8_t* buffer) { CARB_MAYBE_UNUSED bool result; omni::structuredlog::BlockAllocator alloc(buffer, bufferSize); omni::structuredlog::JsonBuilder builder(&alloc); omni::structuredlog::JsonNode* base = static_cast<omni::structuredlog::JsonNode*>(alloc.alloc(sizeof(*base))); if (base == nullptr) { OMNI_LOG_ERROR( "failed to allocate the base node for event " "'com.nvidia.omni.carb.cloud.startup' " "{alloc size = %zu, buffer size = %zu}", sizeof(*base), bufferSize); return nullptr; } *base = {}; // build the tree result = builder.createObject(base, 5); // object has 5 properties if (!result) { OMNI_LOG_ERROR("failed to create an object node (bad size calculation?)"); return nullptr; } { // property cloud_link_id result = builder.setName(&base->data.objVal[0], "cloud_link_id"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[0], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } // property ident result = builder.setName(&base->data.objVal[1], "ident"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.createObject(&base->data.objVal[1], 2); // object has 2 properties if (!result) { OMNI_LOG_ERROR("failed to create a new object node (bad size calculation?)"); return nullptr; } { // property cluster result = builder.setName(&base->data.objVal[1].data.objVal[0], "cluster"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[1].data.objVal[0], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } // property node result = builder.setName(&base->data.objVal[1].data.objVal[1], "node"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[1].data.objVal[1], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } } // property application result = builder.setName(&base->data.objVal[2], "application"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.createObject(&base->data.objVal[2], 2); // object has 2 properties if (!result) { OMNI_LOG_ERROR("failed to create a new object node (bad size calculation?)"); return nullptr; } { // property name result = builder.setName(&base->data.objVal[2].data.objVal[0], "name"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[2].data.objVal[0], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } // property version result = builder.setName(&base->data.objVal[2].data.objVal[1], "version"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[2].data.objVal[1], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } } // property version result = builder.setName(&base->data.objVal[3], "version"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[3], "1", sizeof("1")); if (!result) { OMNI_LOG_ERROR("failed to copy string '1' (bad size calculation?)"); return nullptr; } result = omni::structuredlog::JsonBuilder::setFlags( &base->data.objVal[3], omni::structuredlog::JsonNode::fFlagConst); if (!result) { OMNI_LOG_ERROR("failed to set flag 'omni::structuredlog::JsonNode::fFlagConst'"); return nullptr; } // property event result = builder.setName(&base->data.objVal[4], "event"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[4], "cloud-startup", sizeof("cloud-startup")); if (!result) { OMNI_LOG_ERROR("failed to copy string 'cloud-startup' (bad size calculation?)"); return nullptr; } result = omni::structuredlog::JsonBuilder::setFlags( &base->data.objVal[4], omni::structuredlog::JsonNode::fFlagConst); if (!result) { OMNI_LOG_ERROR("failed to set flag 'omni::structuredlog::JsonNode::fFlagConst'"); return nullptr; } } return base; } /** Calculate JSON tree size for structured log event: com.nvidia.omni.carb.cloud.heartbeat. * @returns The JSON tree size in bytes for this event. */ static size_t _heartbeat_calculateTreeSize() { // calculate the buffer size for the tree omni::structuredlog::JsonTreeSizeCalculator calc; calc.trackRoot(); calc.trackObject(2); // object has 2 properties { // property cloud_link_id calc.trackName("cloud_link_id"); calc.track(static_cast<const char*>(nullptr)); // property event calc.trackName("event"); calc.track("cloud-heartbeat", sizeof("cloud-heartbeat")); } return calc.getSize(); } /** Generate the JSON tree for structured log event: com.nvidia.omni.carb.cloud.heartbeat. * @param[in] bufferSize The length of @p buffer in bytes. * @param[inout] buffer The buffer to write the tree into. * @returns The JSON tree for this event. * @returns nullptr if a logic error occurred or @p bufferSize was too small. */ static omni::structuredlog::JsonNode* _heartbeat_buildJsonTree(size_t bufferSize, uint8_t* buffer) { CARB_MAYBE_UNUSED bool result; omni::structuredlog::BlockAllocator alloc(buffer, bufferSize); omni::structuredlog::JsonBuilder builder(&alloc); omni::structuredlog::JsonNode* base = static_cast<omni::structuredlog::JsonNode*>(alloc.alloc(sizeof(*base))); if (base == nullptr) { OMNI_LOG_ERROR( "failed to allocate the base node for event " "'com.nvidia.omni.carb.cloud.heartbeat' " "{alloc size = %zu, buffer size = %zu}", sizeof(*base), bufferSize); return nullptr; } *base = {}; // build the tree result = builder.createObject(base, 2); // object has 2 properties if (!result) { OMNI_LOG_ERROR("failed to create an object node (bad size calculation?)"); return nullptr; } { // property cloud_link_id result = builder.setName(&base->data.objVal[0], "cloud_link_id"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[0], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } // property event result = builder.setName(&base->data.objVal[1], "event"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[1], "cloud-heartbeat", sizeof("cloud-heartbeat")); if (!result) { OMNI_LOG_ERROR("failed to copy string 'cloud-heartbeat' (bad size calculation?)"); return nullptr; } result = omni::structuredlog::JsonBuilder::setFlags( &base->data.objVal[1], omni::structuredlog::JsonNode::fFlagConst); if (!result) { OMNI_LOG_ERROR("failed to set flag 'omni::structuredlog::JsonNode::fFlagConst'"); return nullptr; } } return base; } /** Calculate JSON tree size for structured log event: com.nvidia.omni.carb.cloud.exit. * @returns The JSON tree size in bytes for this event. */ static size_t _exit_calculateTreeSize() { // calculate the buffer size for the tree omni::structuredlog::JsonTreeSizeCalculator calc; calc.trackRoot(); calc.trackObject(4); // object has 4 properties { // property cloud_link_id calc.trackName("cloud_link_id"); calc.track(static_cast<const char*>(nullptr)); // property application calc.trackName("application"); calc.trackObject(2); // object has 2 properties { // property name calc.trackName("name"); calc.track(static_cast<const char*>(nullptr)); // property version calc.trackName("version"); calc.track(static_cast<const char*>(nullptr)); } // property exit_abnormally calc.trackName("exit_abnormally"); calc.track(bool(false)); // property event calc.trackName("event"); calc.track("cloud-exit", sizeof("cloud-exit")); } return calc.getSize(); } /** Generate the JSON tree for structured log event: com.nvidia.omni.carb.cloud.exit. * @param[in] bufferSize The length of @p buffer in bytes. * @param[inout] buffer The buffer to write the tree into. * @returns The JSON tree for this event. * @returns nullptr if a logic error occurred or @p bufferSize was too small. */ static omni::structuredlog::JsonNode* _exit_buildJsonTree(size_t bufferSize, uint8_t* buffer) { CARB_MAYBE_UNUSED bool result; omni::structuredlog::BlockAllocator alloc(buffer, bufferSize); omni::structuredlog::JsonBuilder builder(&alloc); omni::structuredlog::JsonNode* base = static_cast<omni::structuredlog::JsonNode*>(alloc.alloc(sizeof(*base))); if (base == nullptr) { OMNI_LOG_ERROR( "failed to allocate the base node for event " "'com.nvidia.omni.carb.cloud.exit' " "{alloc size = %zu, buffer size = %zu}", sizeof(*base), bufferSize); return nullptr; } *base = {}; // build the tree result = builder.createObject(base, 4); // object has 4 properties if (!result) { OMNI_LOG_ERROR("failed to create an object node (bad size calculation?)"); return nullptr; } { // property cloud_link_id result = builder.setName(&base->data.objVal[0], "cloud_link_id"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[0], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } // property application result = builder.setName(&base->data.objVal[1], "application"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.createObject(&base->data.objVal[1], 2); // object has 2 properties if (!result) { OMNI_LOG_ERROR("failed to create a new object node (bad size calculation?)"); return nullptr; } { // property name result = builder.setName(&base->data.objVal[1].data.objVal[0], "name"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[1].data.objVal[0], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } // property version result = builder.setName(&base->data.objVal[1].data.objVal[1], "version"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[1].data.objVal[1], static_cast<const char*>(nullptr)); if (!result) { OMNI_LOG_ERROR("failed to set type 'const char*' (shouldn't be possible)"); return nullptr; } } // property exit_abnormally result = builder.setName(&base->data.objVal[2], "exit_abnormally"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[2], bool(false)); if (!result) { OMNI_LOG_ERROR("failed to set type 'bool' (shouldn't be possible)"); return nullptr; } // property event result = builder.setName(&base->data.objVal[3], "event"); if (!result) { OMNI_LOG_ERROR("failed to set the object name (bad size calculation?)"); return nullptr; } result = builder.setNode(&base->data.objVal[3], "cloud-exit", sizeof("cloud-exit")); if (!result) { OMNI_LOG_ERROR("failed to copy string 'cloud-exit' (bad size calculation?)"); return nullptr; } result = omni::structuredlog::JsonBuilder::setFlags( &base->data.objVal[3], omni::structuredlog::JsonNode::fFlagConst); if (!result) { OMNI_LOG_ERROR("failed to set flag 'omni::structuredlog::JsonNode::fFlagConst'"); return nullptr; } } return base; } /** The callback that is used to report validation errors. * @param[in] s The validation error message. */ static void _onStructuredLogValidationError(const char* s) { OMNI_LOG_ERROR("error sending a structured log event: %s", s); } }; // asserts to ensure that no one's modified our dependencies static_assert(omni::structuredlog::BlobWriter<>::kVersion == 0, "BlobWriter version changed"); static_assert(omni::structuredlog::JsonNode::kVersion == 0, "JsonNode version changed"); static_assert(sizeof(omni::structuredlog::JsonNode) == 24, "unexpected size"); static_assert(std::is_standard_layout<omni::structuredlog::JsonNode>::value, "this type needs to be ABI safe"); static_assert(offsetof(omni::structuredlog::JsonNode, type) == 0, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, flags) == 1, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, len) == 2, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, nameLen) == 4, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, name) == 8, "struct layout changed"); static_assert(offsetof(omni::structuredlog::JsonNode, data) == 16, "struct layout changed"); } // namespace telemetry } // namespace omni OMNI_STRUCTURED_LOG_ADD_SCHEMA(omni::telemetry::Schema_omni_carb_cloud_1_0, omni_carb_cloud, 1_0, 0);
50,954
C
40.225728
120
0.56237
omniverse-code/kit/include/omni/structuredlog/JsonSerializer.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 Module for manually serializing JSON data with low performance overhead. */ #pragma once #include "../../carb/extras/StringSafe.h" #include "../../carb/extras/Utf8Parser.h" #include "../../carb/extras/Base64.h" #include <stdint.h> #include <float.h> namespace omni { namespace structuredlog { /** An interface for consuming the output JSON from the @ref JsonSerializer. */ class JsonConsumer { public: virtual ~JsonConsumer() { } /** The function that will consume strings of JSON. * @param[in] json The string of JSON. * This string's lifetime ends after the return from this call. * @param[in] jsonLen The length of @p json, excluding the null terminator. * The null terminator will be included in the length * when the final call to this writes out a null terminator. * It is possible this may be 0 in some edge cases. * It's possible that @p jsonLen may be used to refer to * a substring of @p json. * @remarks This will be called when the @ref JsonSerializer wants to write * something to the output. * The @ref JsonSerializer will write very small units of text to * this function, so the implementation should plan accordingly. */ virtual void consume(const char* json, size_t jsonLen) noexcept = 0; /** Terminate the output, if needed. * @remarks This will be called to ensure the output is null terminated. */ virtual void terminate() noexcept = 0; }; /** An implementation of @ref JsonConsumer that just counts the length of the * output string. * You may serialize some JSON through this to find the required buffer length, * then allocate the buffer and serialize the JSON again with @ref JsonPrinter * using that allocated buffer. */ class JsonLengthCounter : public JsonConsumer { public: void consume(const char* json, size_t jsonLen) noexcept override { CARB_UNUSED(json); m_count += jsonLen; } void terminate() noexcept override { m_count++; } /** Get the number of bytes that have been consumed so far. * @returns the number of bytes that have been consumed so far. */ size_t getcount() noexcept { return m_count; } private: size_t m_count = 0; }; /** An implementation of @ref JsonConsumer that just prints to a fixed string. */ class JsonPrinter : public JsonConsumer { public: JsonPrinter() { reset(nullptr, 0); } /** Create a printer from a fixed string buffer. * @param[out] output The instance will write to this buffer. * @param[in] outputLen The number of bytes that can be written to @p output. */ JsonPrinter(char* output, size_t outputLen) noexcept { reset(output, outputLen); } /** Reinitialize the printer with a new buffer. * @param[out] output The instance will write to this buffer. * @param[in] outputLen The number of bytes that can be written to @p output. */ void reset(char* output, size_t outputLen) noexcept { m_output = (outputLen == 0) ? nullptr : output; m_left = outputLen; m_overflowed = false; } /** Write a string into the buffer. * @param[in] json The data to write into the buffer. * @param[in] jsonLen The length of @p json, excluding any null terminator. */ void consume(const char* json, size_t jsonLen) noexcept override { size_t w = CARB_MIN(m_left, jsonLen); memcpy(m_output, json, w); m_left -= w; m_output += w; m_overflowed = m_overflowed || w < jsonLen; } void terminate() noexcept override { if (m_output != nullptr) { if (m_left == 0) { m_output[-1] = '\0'; } else { m_output[0] = '\0'; m_output++; m_left--; } } } /** Check whether more data was printed than would fit in the printer's buffer. * @returns `true` if the buffer was too small to fit all the consumed data. * @returns `false` if the buffer was able to fit all the consumed data. */ bool hasOverflowed() noexcept { return m_overflowed; } /** Get the pointer to the next char to be written in the buffer. * @returns The pointer to the next character to be written. * If the buffer has overflowed, this will point past the end of * the buffer. */ char* getNextChar() const noexcept { return m_output; } private: char* m_output; size_t m_left; bool m_overflowed = false; }; /** Anonymous namespace for a helper function */ namespace { void ignoreJsonSerializerValidationError(const char* s) noexcept { CARB_UNUSED(s); } } // namespace /** The prototype of the function to call when a validation error occurs. */ using OnValidationErrorFunc = void (*)(const char*); /** A utility that allows you to easily encode JSON data. * This class won't allocate any memory unless you use an excessive number of scopes. * * @param validate If this is set to true, methods will return false when an * invalid operation is performed. * onValidationError is used for logging because this struct * is used in the logging system, so OMNI_LOG_* cannot be * directly called from within this class. * If this is set to false, methods will assume that all calls * will produce valid JSON data. Invalid calls will write out * invalid JSON data. Methods will only return false if an * unavoidable check failed. * * @tparam prettyPrint If this is set to true, the output will be pretty-printed. * If this is set to false, the output will have no added white space. * * @tparam onValidationError This is a callback that gets executed when a validation * error is triggered, so logging can be called. */ template <bool validate = false, bool prettyPrint = false, OnValidationErrorFunc onValidationError = ignoreJsonSerializerValidationError> class JsonSerializer { public: /** The function that will be called when a validation error occurs. */ OnValidationErrorFunc m_onValidationError = onValidationError; /** Constructor. * @param[in] consumer The object that will consume the output JSON data. * This may not be nullptr. * @param[in] indentLen The number of spaces to indent by when pretty printing is enabled. */ JsonSerializer(JsonConsumer* consumer, size_t indentLen = 4) noexcept { CARB_ASSERT(consumer != nullptr); m_consumer = consumer; m_indentLen = indentLen; } ~JsonSerializer() { // it starts to use heap memory at this point if (m_scopes != m_scopesBuffer) free(m_scopes); } /** Reset the internal state back to where it was after construction. */ void reset() { m_scopesTop = 0; m_firstInScope = true; m_hasKey = false; m_firstPrint = true; m_indentTotal = 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 @p key, excluding the null terminator. * @returns whether or not validation succeeded. */ bool writeKey(const char* key, size_t keyLen) noexcept { if (validate) { if (CARB_UNLIKELY(getCurrentScope() != ScopeType::eObject)) { char tmp[256]; carb::extras::formatString(tmp, sizeof(tmp), "attempted to write a key outside an object" " {key name = '%s', len = %zu}", key, keyLen); onValidationError(tmp); return false; } if (CARB_UNLIKELY(m_hasKey)) { char tmp[256]; carb::extras::formatString(tmp, sizeof(tmp), "attempted to write out two key names in a row" " {key name = '%s', len = %zu}", key, keyLen); onValidationError(tmp); return false; } } if (!m_firstInScope) m_consumer->consume(",", 1); prettyPrintHook(); m_consumer->consume("\"", 1); if (key != nullptr) m_consumer->consume(key, keyLen); m_consumer->consume("\":", 2); m_firstInScope = false; if (validate) m_hasKey = true; return true; } /** 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 { return writeKey(key, key == nullptr ? 0 : strlen(key)); } /** Write out a JSON null value. * @returns whether or not validation succeeded. */ bool writeValue() noexcept { if (CARB_UNLIKELY(!writeValuePrologue())) return false; prettyPrintValueHook(); m_consumer->consume("null", sizeof("null") - 1); if (validate) m_hasKey = false; return true; } /** Write out a JSON boolean value. * @param[in] value The boolean value. * @returns whether or not validation succeeded. */ bool writeValue(bool value) noexcept { const char* val = value ? "true" : "false"; size_t len = (value ? sizeof("true") : sizeof("false")) - 1; if (CARB_UNLIKELY(!writeValuePrologue())) return false; prettyPrintValueHook(); m_consumer->consume(val, len); if (validate) m_hasKey = false; return true; } /** Write out a JSON integer value. * @param[in] value The integer value. * @returns whether or not validation succeeded. */ bool writeValue(int32_t value) noexcept { char buffer[32]; size_t i = 0; if (CARB_UNLIKELY(!writeValuePrologue())) return false; i = carb::extras::formatString(buffer, CARB_COUNTOF(buffer), "%" PRId32, value); prettyPrintValueHook(); m_consumer->consume(buffer, i); if (validate) m_hasKey = false; return true; } /** Write out a JSON integer value. * @param[in] value The integer value. * @returns whether or not validation succeeded. */ bool writeValue(uint32_t value) noexcept { char buffer[32]; size_t i = 0; if (CARB_UNLIKELY(!writeValuePrologue())) return false; i = carb::extras::formatString(buffer, CARB_COUNTOF(buffer), "%" PRIu32, value); prettyPrintValueHook(); m_consumer->consume(buffer, i); if (validate) m_hasKey = false; return true; } /** Write out a JSON integer value. * @param[in] value The integer value. * @returns whether or not validation succeeded. * @note 64 bit integers are stored as double precision floats in JavaScript's * JSON library, so a JSON library with BigInt support should be * used instead when reading 64 bit numbers. */ bool writeValue(int64_t value) noexcept { char buffer[32]; size_t i = 0; if (CARB_UNLIKELY(!writeValuePrologue())) return false; i = carb::extras::formatString(buffer, CARB_COUNTOF(buffer), "%" PRId64, value); prettyPrintValueHook(); m_consumer->consume(buffer, i); if (validate) m_hasKey = false; return true; } /** Write out a JSON integer value. * @param[in] value The integer value. * @returns whether or not validation succeeded. * @note 64 bit integers are stored as double precision floats in JavaScript's * JSON library, so a JSON library with BigInt support should be * used instead when reading 64 bit numbers. */ bool writeValue(uint64_t value) noexcept { char buffer[32]; size_t i = 0; if (CARB_UNLIKELY(!writeValuePrologue())) return false; i = carb::extras::formatString(buffer, CARB_COUNTOF(buffer), "%" PRIu64, value); prettyPrintValueHook(); m_consumer->consume(buffer, i); if (validate) m_hasKey = false; return true; } /** Write out a JSON double (aka number) value. * @param[in] value The double value. * @returns whether or not validation succeeded. */ bool writeValue(double value) noexcept { char buffer[32]; size_t i = 0; if (CARB_UNLIKELY(!writeValuePrologue())) return false; i = carb::extras::formatString( buffer, CARB_COUNTOF(buffer), "%.*g", std::numeric_limits<double>::max_digits10, value); prettyPrintValueHook(); m_consumer->consume(buffer, i); if (validate) m_hasKey = false; return true; } /** Write out a JSON float (aka number) value. * @param[in] value The double value. * @returns whether or not validation succeeded. */ bool writeValue(float value) noexcept { return writeValue(double(value)); } /** 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 writeValue(const char* value, size_t len) noexcept { size_t last = 0; if (CARB_UNLIKELY(!writeValuePrologue())) return false; prettyPrintValueHook(); m_consumer->consume("\"", 1); for (size_t i = 0; i < len;) { const carb::extras::Utf8Parser::CodeByte* next = carb::extras::Utf8Parser::nextCodePoint(value + i, len - i); if (next == nullptr) { m_consumer->consume(value + last, i - last); m_consumer->consume("\\u0000", 6); i++; last = i; continue; } // early out for non-escape characters // multi-byte characters never need to be escaped if (size_t(next - value) > i + 1 || (value[i] > 0x1F && value[i] != '"' && value[i] != '\\')) { i = next - value; continue; } m_consumer->consume(value + last, i - last); switch (value[i]) { case '"': m_consumer->consume("\\\"", 2); break; case '\\': m_consumer->consume("\\\\", 2); break; case '\b': m_consumer->consume("\\b", 2); break; case '\f': m_consumer->consume("\\f", 2); break; case '\n': m_consumer->consume("\\n", 2); break; case '\r': m_consumer->consume("\\r", 2); break; case '\t': m_consumer->consume("\\t", 2); break; default: { char tmp[] = "\\u0000"; tmp[4] = getHexChar(uint8_t(value[i]) >> 4); tmp[5] = getHexChar(value[i] & 0x0F); m_consumer->consume(tmp, CARB_COUNTOF(tmp) - 1); } break; } i++; last = i; } if (len > last) m_consumer->consume(value + last, len - last); m_consumer->consume("\"", 1); if (validate) m_hasKey = false; return true; } /** Write out a JSON string value. * @param[in] value The string value. * This can be nullptr. * @returns whether or not validation succeeded. */ bool writeValue(const char* value) noexcept { return writeValue(value, value == nullptr ? 0 : strlen(value)); } /** 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 string and encode it in base64, then * store that as base64 data in a string. */ bool writeValueWithBase64Encoding(const void* value_, size_t size) { char buffer[4096]; const size_t readSize = carb::extras::Base64::getEncodeInputSize(sizeof(buffer)); const uint8_t* value = static_cast<const uint8_t*>(value_); if (CARB_UNLIKELY(!writeValuePrologue())) return false; m_consumer->consume("\"", 1); for (size_t i = 0; i < size; i += readSize) { size_t written = m_base64Encoder.encode(value + i, CARB_MIN(readSize, size - i), buffer, sizeof(buffer)); m_consumer->consume(buffer, written); } m_consumer->consume("\"", 1); if (validate) m_hasKey = false; return true; } /** Begin a JSON array. * @returns whether or not validation succeeded. * @returns false if a memory allocation failed. */ bool openArray() noexcept { if (CARB_UNLIKELY(!writeValuePrologue())) return false; prettyPrintValueHook(); m_consumer->consume("[", 1); m_firstInScope = true; if (!pushScope(ScopeType::eArray)) return false; prettyPrintOpenScope(); if (validate) m_hasKey = false; return true; } /** Finish writing a JSON array. * @returns whether or not validation succeeded. */ bool closeArray() noexcept { if (validate && CARB_UNLIKELY(getCurrentScope() != ScopeType::eArray)) { onValidationError("attempted to close an array that was never opened"); return false; } popScope(); prettyPrintCloseScope(); prettyPrintHook(); m_consumer->consume("]", 1); m_firstInScope = false; if (validate) m_hasKey = false; return true; } /** Begin a JSON object. * @returns whether or not validation succeeded. * @returns false if a memory allocation failed. */ bool openObject() noexcept { if (CARB_UNLIKELY(!writeValuePrologue())) return false; prettyPrintValueHook(); m_consumer->consume("{", 1); m_firstInScope = true; pushScope(ScopeType::eObject); prettyPrintOpenScope(); if (validate) m_hasKey = false; return true; } /** Finish writing a JSON object. * @returns whether or not validation succeeded. */ bool closeObject() noexcept { if (validate && CARB_UNLIKELY(getCurrentScope() != ScopeType::eObject)) { onValidationError("attempted to close an object that was never opened"); return false; } popScope(); prettyPrintCloseScope(); prettyPrintHook(); m_consumer->consume("}", 1); m_firstInScope = false; if (validate) m_hasKey = false; return true; } /** Finish writing your JSON. * @returns whether or not validation succeeded. */ bool finish() noexcept { bool result = true; // check whether we are ending in the middle of an object/array if (validate && getCurrentScope() != ScopeType::eGlobal) { char tmp[256]; carb::extras::formatString(tmp, sizeof(tmp), "finished writing in the middle of an %s", getCurrentScope() == ScopeType::eArray ? "array" : "object"); onValidationError(tmp); result = false; } if (prettyPrint) m_consumer->consume("\n", 1); m_consumer->terminate(); return result; } private: /** The type of a scope in the scope stack. */ enum class ScopeType : uint8_t { eGlobal, /**< global scope (not in anything). */ eArray, /**< JSON array type. (e.g. []) */ eObject, /**< JSON object type. (e.g. {}) */ }; /** A hook used before JSON elements to perform pretty print formatting. */ void prettyPrintHook() noexcept { if (prettyPrint) { const size_t s = CARB_COUNTOF(m_indent) - 1; if (!m_firstPrint) m_consumer->consume("\n", 1); m_firstPrint = false; for (size_t i = s; i <= m_indentTotal; i += s) m_consumer->consume(m_indent, s); m_consumer->consume(m_indent, m_indentTotal % s); } } /** A hook used before printing a value element to perform pretty print formatting. */ void prettyPrintValueHook() noexcept { if (prettyPrint) { if (getCurrentScope() != ScopeType::eObject) return prettyPrintHook(); else /* if it's in an object, a key preceded this so this should be on the same line */ m_consumer->consume(" ", 1); } } /** Track when a scope was opened for pretty print indenting. */ void prettyPrintOpenScope() noexcept { if (prettyPrint) m_indentTotal += m_indentLen; } /** Track when a scope was closed for pretty print indenting. */ void prettyPrintCloseScope() noexcept { if (prettyPrint) m_indentTotal -= m_indentLen; } /** A common prologue to writeValue() functions. * @returns Whether validation succeeded. */ inline bool writeValuePrologue() noexcept { if (validate) { // the global scope is only allowed to have one item in it if (CARB_UNLIKELY(getCurrentScope() == ScopeType::eGlobal && !m_firstInScope)) { onValidationError("attempted to put multiple values into the global scope"); return false; } // if we're in an object, a key needs to have been written before each value if (CARB_UNLIKELY(getCurrentScope() == ScopeType::eObject && !m_hasKey)) { onValidationError("attempted to write a value without a key inside an object"); return false; } } if (getCurrentScope() == ScopeType::eArray && !m_firstInScope) m_consumer->consume(",", 1); m_firstInScope = false; return true; } bool pushScope(ScopeType s) noexcept { if (m_scopesTop == m_scopesLen) { size_t newLen = m_scopesTop + 64; size_t size = sizeof(*m_scopes) * newLen; void* tmp; if (m_scopes == m_scopesBuffer) tmp = malloc(size); else tmp = realloc(m_scopes, size); if (tmp == nullptr) { char log[256]; carb::extras::formatString(log, sizeof(log), "failed to allocate %zu bytes", size); onValidationError(log); return false; } if (m_scopes == m_scopesBuffer) memcpy(tmp, m_scopes, sizeof(*m_scopes) * m_scopesLen); m_scopes = static_cast<ScopeType*>(tmp); m_scopesLen = newLen; } m_scopes[m_scopesTop++] = s; return true; } void popScope() noexcept { m_scopesTop--; } ScopeType getCurrentScope() noexcept { if (m_scopesTop == 0) return ScopeType::eGlobal; return m_scopes[m_scopesTop - 1]; } char getHexChar(uint8_t c) noexcept { char lookup[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; CARB_ASSERT(c < CARB_COUNTOF(lookup)); return lookup[c]; } ScopeType m_scopesBuffer[8]; ScopeType* m_scopes = m_scopesBuffer; size_t m_scopesLen = CARB_COUNTOF(m_scopesBuffer); size_t m_scopesTop = 0; /** The consumer of the output JSON data. */ JsonConsumer* m_consumer; /** This flag is the current key/value being written is the first one inside * the current scope (this decides comma placement). */ bool m_firstInScope = true; /** This is set when a key has been specified. * This is done for validation. */ bool m_hasKey = false; /** This is true when the first character has not been printed yet. * This is used for pretty printing. */ bool m_firstPrint = true; /** The indent buffer used for pretty printing. */ char m_indent[33] = " "; /** The length into m_indent to print for the pretty-printing indent. */ size_t m_indentTotal = 0; /** The length of an individual indent when pretty-printing. */ size_t m_indentLen = 4; /** The base64 encoder. This is just cached here to improve performance. */ carb::extras::Base64 m_base64Encoder; }; } // namespace structuredlog } // namespace omni
26,725
C
29.474344
137
0.551356
omniverse-code/kit/include/omni/structuredlog/StructuredLogSettingsUtils.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 Utilities for the carb::settings::ISettings settings for structured logging. */ #pragma once #include "IStructuredLog.h" #include "IStructuredLogExtraFields.h" #include "IStructuredLogSettings.h" #include "IStructuredLogSettings2.h" #include "IStructuredLogFromILog.h" #include "../../carb/extras/StringSafe.h" #include "../../carb/settings/ISettings.h" #include "../extras/PrivacySettings.h" #include "../extras/OmniConfig.h" #include "../log/ILog.h" namespace omni { namespace structuredlog { /** Constants for default and minimum values for various settings. * @{ */ /** The default value for the log size limit in bytes. * See IStructuredLogSettings::setLogSizeLimit() for details. */ constexpr int64_t kDefaultLogSizeLimit = 50ll * 1024ll * 1024ll; /** The minimum value that can be set for the log size limit in bytes. * See IStructuredLogSettings::setLogSizeLimit() for details. */ constexpr int64_t kMinLogSizeLimit = 256ll * 1024ll; /** The default log retention setting. * See IStructuredLogSettings::setLogRetentionCount() for details. */ constexpr size_t kDefaultLogRetentionCount = 3; /** The minimum allowed log retention setting. * See IStructuredLogSettings::setLogRetentionCount() for details. */ constexpr size_t kMinLogRetentionCount = 1; /** The default value for the event queue size in bytes. * See IStructuredLogSettings::setEventQueueSize() for details. */ constexpr size_t kDefaultEventQueueSize = 2 * 1024 * 1024; /** The minimum allowed event queue size in bytes. * See IStructuredLogSettings::setEventQueueSize() for details. */ constexpr size_t kMinEventQueueSize = 512 * 1024; /** The maximum allowed event queue size in bytes. * See IStructuredLogSettings::setEventQueueSize() for details. */ constexpr size_t kMaxEventQueueSize = 1024 * 1024 * 1024; /** The default mode for generating event IDs. * See IStructuredLogSettings::setEventIdMode() for details. */ constexpr IdMode kDefaultIdMode = IdMode::eFastSequential; /** The default type of event ID to generate. * See IStructuredLogSettings::setEventIdMode() for details. */ constexpr IdType kDefaultIdType = IdType::eUuid; /** Special value to indicate that the heartbeat event should be disabled. Any other value * will indicate that the heartbeat events will be generated. */ constexpr uint64_t kHeartbeatDisabled = 0; /** The default minimum time between heartbeat events in seconds. This can be * @ref kHeartbeatDisabled to indicate that the heartbeat events are disabled. For more * details, please see IStructuredLogSettings2::setHeartbeatPeriod(). */ constexpr uint64_t kDefaultHeartbeatPeriod = kHeartbeatDisabled; /** The default state for whether headers will be added to each written log file. For * more details, please see IStructuredLogSettings2::setNeedsLogHeaders(). */ constexpr bool kDefaultNeedLogHeaders = true; /** The default state for whether the CloudEvents wrapper will be output with each message. * By default, all messages will be emitted as CloudEvents 1.0 compliant messages. The * omni::structuredlog::IStructuredLogSettings2::setOutputFlags() function or the * @ref kEmitPayloadOnlySettings setting can be used to change this setting. */ constexpr bool kDefaultEmitPayloadOnlySettings = false; /** The default state for whether the cloud heartbeat events will be emitted. For these * events to be emitted, the normal heartbeat event must also be enabled with * @ref kHeartbeatPeriodSetting. These cloud heartbeat events are effectively duplicate * data and are not strictly necessary. */ constexpr bool kDefaultEmitCloudHeartbeat = false; /** @} */ /** Names for various settings that can be used to override some of the default settings. Note * that these will not override any values that are explicitly set by the host app itself. * @{ */ /** Global enable/disable for structured logging. When set to `false`, the structured log system * will be disabled. This will prevent any event messages from being written out unless the * host app explicitly wants them to. When set to `true`, the structured log system will be * enabled and event messages will be emitted normally. This defaults to `false`. */ constexpr const char* kGlobalEnableSetting = "/structuredLog/enable"; /** Specifies the directory that log files should be written to. This is also the directory that * the telemetry transmitter app will check for when enumerating and consuming logs. This must * always be a local path and may be either absolute or relative. The default location is * `$HOME/.nvidia-omniverse/logs/` (where ``$HOME`` is ``%USERPROFILE%`` on Windows and the usual * meaning on POSIX platforms). This setting is mainly intended for testing and the default * directory should be used whenever possible. If this setting is used in a Kit launch (either * on command line or in a config file), it will be passed on to the telemetry transmitter app * when it gets launched. */ constexpr const char* kLogDirectory = "/structuredLog/logDirectory"; /** The default log name to use. If a default log name is set, all events that do not use the * @ref fEventFlagUseLocalLog flag will write their messages to this log file. Events that * do use the @ref fEventFlagUseLocalLog flag will write only to their schema's log file. This * value must be only the log file's name, not including its path. The logs will always be * created in the structured logging system's current log output path. As a special case, this * may also be set to either "/dev/stdout" or "/dev/stderr" (on all platforms) to output all * events directly to stdout or stderr respectively. When one of these log names are used, all * events will be unconditionally written to stdout/stderr regardless of their event or schema * flags. There will also be no log header written out when events are being sent to stdout or * stderr. This defaults to an empty string. */ constexpr const char* kDefaultLogNameSetting = "/structuredLog/defaultLogName"; /** The setting path for the privacy settings file to load. This allows the default location of * the privacy settings file to be overridden. The default location for the privacy settings * file is `$HOME/.nvidia-omniverse/config/privacy.toml` on all platforms, where `$HOME` on * Windows is `%USERPROFILE%). Note that even if this setting is used and it points to a valid * file, the settings from the default `privacy.toml` file will still be loaded first if it * is present. The settings in the file specified here will simply override any settings given * in the default file. This allows any missing settings in the new file to still be provided * by what was present in the default file's location. */ constexpr const char* kPrivacyFileSetting = "/structuredLog/privacySettingsFile"; /** The setting path for the log retention count. This controls how many log files will be * left in the log directory when a log rotation occurs. When a log file reaches its size * limit, it is renamed and a new empty log with the original name is created. A rolling * history of the few most recent logs is maintained after a rotation. This setting controls * exactly how many of each log will be retained after a rotation. This defaults to 3. */ constexpr const char* kLogRetentionCountSetting = "/structuredLog/logRetentionCount"; /** The setting path for the log size limit in megabytes. When a log file reaches this size, * it is rotated out by renaming it and creating a new log file with the original name. If * too many logs exist after this rotation, the oldest one is deleted. This defaults to 50MB. */ constexpr const char* kLogSizeLimitSetting = "/structuredLog/logSizeLimit"; /** The setting path for the size of the event queue buffer in kilobytes. The size of the * event queue controls how many messages can be queued in the message processing queue before * events start to get dropped (or a stall potentially occurs). The event queue can fill up * if the app is emitting messages from multiple threads at a rate that is higher than they * can be processed or written to disk. In general, there should not be a situation where * the app is emitting messages at a rate that causes the queue to fill up. However, this * may be beyond the app's control if (for example) the drive the log is being written to * is particularly slow or extremely busy. This defaults to 2048KB. */ constexpr const char* kEventQueueSizeSetting = "/structuredLog/eventQueueSize"; /** The setting path for the event identifier mode. This controls how event identifiers are * generated. Valid values are 'fast-sequential', `sequential`, and `random`. Each has its * own benefits and drawbacks: * * `sequential` ensures that all generated event IDs are in sequential order. When the * event ID type is set to `UUID`, this will ensure that each generated event ID can be * easily sorted after the previous one. With a UUID type ID, this mode can be expensive * to generate. With a `uint64` ID, this is the most performant to generate. * * `fast-sequential` is only effective when the event ID type is set to 'UUID'. In this * mode, the UUIDs that are generated are sequential, but in memory order, not lexicographical * order. It takes some extra effort to sort these events on the data analysis side, but * they are generated very quickly. When the event ID type is not 'UUID', this mode behaves * in the same way as `sequential`. * * `random` generates a random event ID for each new event. This does not preserve any * kind of order of events. If the app does not require sequential events, this can be * more performant to generate especially for UUIDs. * * This defaults to 'fast-sequential. This setting is not case sensitive. */ constexpr const char* kEventIdModeSetting = "/structuredLog/eventIdMode"; /** The setting path for the event identifier data type. This determines what kind of event * ID will be generated for each new event and how it will be printed out with each message. * The following types are supported: * * `UUID` generates a 128 bit universally unique identifier. The event ID mode determines * how one event ID will be related to the next. This is printed into each event message * in the standard UUID format ("00000000-0000-0000-0000-000000000000"). This type provides * the most uniqueness and room for scaling in large data sets. * * `uint64` generates a 64 bit integer identifier. The event ID mode determines how one * event ID will be related to the next. This is printed into each event message as a * simple decimal integer value. * * This defaults to 'UUID'. This setting is not case sensitive. */ constexpr const char* kEventIdTypeSetting = "/structuredLog/eventIdType"; /** The setting path for the log consumer toggle. This enables or disables the redirection * of normal Carbonite (ie: `CARB_LOG_*()`) and Omni (ie: `OMNI_LOG_*()`) messages as structured * log events as well. The log messages will still go to their original destination (stdout, * stderr, log file, MSVC output window, etc) as well. This defaults to `false`. */ constexpr const char* kEnableLogConsumerSetting = "/structuredLog/enableLogConsumer"; /** The setting path that will contain zero or more keys that will be used to disable schemas * when they are first registered. Each key under this setting will have a name that matches * zero or schema names. From a .schema file, this would match the "name" property. From a * JSON schema file, this would match the @a `#/schemaMeta/clientName` property. The key's * value is expected to be a boolean that indicates whether it is enabled upon registration. * * The names of the keys under this path may either be a schema's full name or a wildcard * string that matches to zero or more schema names. In either version, the case of the * non-wildcard portions of the key name is important. The wildcard characters '*' (match * to zero or more characters) and '?' (match to exactly one character) may be used. This * is only meant to be a simple wildcard filter, not a full regular expression. * * For example, in a TOML file, these settings may be used to disable or enable multiple * schemas: * @rst .. code-block:: toml [structuredLog.state.schemas] "omni.test_schema" = false # disable 'omni.test_schema' on registration. "omni.other_schema" = true # enable 'omni.other_schema' on registration. "carb.*" = false # disable all schemas starting with 'carb.'. @endrst * * @note The keys in this setting path are inherently unordered. If a set of dependent * enable/disable settings is needed, the @ref kSchemasStateArraySetting setting path * should be used instead. This other setting allows an array to be specified that * preserves the order of keys. This is useful for doing things like disabling all * schemas then only enabling a select few. */ constexpr const char* kSchemasStateListSetting = "/structuredLog/state/schemas"; /** The setting path that will contain zero or more keys that will be used to disable events * when they are first registered. Each key under this setting will have a name that matches * zero or event names. From a .schema file, this would match the "namespace" property plus * one of the properties under @a `#/events/`. From a JSON schema file, this would match one * of the event properties under @a `#/definitions/events/`. The key's value is expected to * be a boolean that indicates whether it is enabled upon registration. * * The names of the keys under this path may either be an event's full name or a wildcard * string that matches to zero or more event names. In either version, the case of the * non-wildcard portions of the key name is important. The wildcard characters '*' (match * to zero or more characters) and '?' (match to exactly one character) may be used. This * is only meant to be a simple wildcard filter, not a full regular expression. * * For example, in a TOML file, these settings may be used to disable or enable multiple * events: * @rst .. code-block:: toml [structuredLog.state.events] "com.nvidia.omniverse.fancy_event" = false "com.nvidia.carbonite.*" = false # disable all 'com.nvidia.carbonite' events. @endrst * * @note The keys in this setting path are inherently unordered. If a set of dependent * enable/disable settings is needed, the @ref kEventsStateArraySetting setting path * should be used instead. This other setting allows an array to be specified that * preserves the order of keys. This is useful for doing things like disabling all * events then only enabling a select few. */ constexpr const char* kEventsStateListSetting = "/structuredLog/state/events"; /** The setting path to an array that will contain zero or more values that will be used to * disable or enable schemas when they are first registered. Each value in this array will * have a name that matches zero or more schema names. From a .schema file, this would match the * "name" property. From a JSON schema file, this would match the @a `#/schemaMeta/clientName` * property. The schema name may be optionally prefixed by either '+' or '-' to enable or * disable (respectively) matching schemas. Alternatively, the schema's name may be assigned * a boolean value to indicate whether it is enabled or not. If neither a '+'/'-' prefix nor * a boolean assignment suffix is specified, 'enabled' is assumed. * * The names in this array either be a schema's full name or a wildcard string that matches * to zero or more schema names. In either version, the case of the non-wildcard portions * of the key name is important. The wildcard characters '*' (match to zero or more characters) * and '?' (match to exactly one character) may be used. This is only meant to be a simple * wildcard filter, not a full regular expression. * * For example, in a TOML file, these settings may be used to disable or enable multiple * schemas: * @rst .. code-block:: toml structuredLog.schemaStates = [ "-omni.test_schema", # disable 'omni.test_schema' on registration. "omni.other_schema = true", # enable 'omni.other_schema' on registration. "-carb.*" # disable all schemas starting with 'carb.'. ] @endrst * * @note TOML does not allow static arrays such as above to be appended to with later lines. * Attempting to do so will result in a parsing error. */ constexpr const char* kSchemasStateArraySetting = "/structuredLog/schemaStates"; /** The setting path to an array that will contain zero or more values that will be used to * disable or enable events when they are first registered. Each value in this array will * have a name that matches zero or more event names. From a .schema file, this would match one * of the property names under `#/events/`. From a JSON schema file, this would match one * of the event object names in @a `#/definitions/events/`. The event name may be optionally * prefixed by either '+' or '-' to enable or disable (respectively) matching event(s). * Alternatively, the event's name may be assigned a boolean value to indicate whether it is * enabled or not. If neither a '+'/'-' prefix nor a boolean assignment suffix is specified, * 'enabled' is assumed. * * The names in this array either be an event's full name or a wildcard string that matches * to zero or more event names. In either version, the case of the non-wildcard portions * of the array entry name is important. The wildcard characters '*' (match to zero or more characters) * and '?' (match to exactly one character) may be used. This is only meant to be a simple * wildcard filter, not a full regular expression. * * For example, in a TOML file, these settings may be used to disable or enable multiple * schemas: * @rst .. code-block:: toml structuredLog.schemaStates = [ "-com.nvidia.omniverse.fancy_event", "com.nvidia.carbonite.* = false" # disable all 'com.nvidia.carbonite' events. ] @endrst * * @note that TOML does not allow static arrays such as above to be appended to with later lines. * Attempting to do so will result in a parsing error. */ constexpr const char* kEventsStateArraySetting = "/structuredLog/eventStates"; /** The setting path that will contain the minimum number of seconds between heartbeat events * A heartbeat event is one that is sent periodically to help calculate session lengths even * if the expected 'exit' or 'crash' process lifetime events are missing. These events can * be missing in such unavoidable cases as a power loss, the user killing the process, a blue * screen of death or kernel panic, etc. These situations cannot be assumed as either crashes * or normal exits, but at least these events can help indicate how long the actual session was. * This can be set to 0 to disable the heartbeat messages. By default the heartbeat events are * disabled (ie: set to @ref kHeartbeatDisabled). */ constexpr const char* kHeartbeatPeriodSetting = "/structuredLog/heartbeatPeriod"; /** The setting path that will indicate whether headers will be added to each log file that is * written to disk. Each log file will have one header on the first line that is a JSON object * that indicates the origin of the log and the version of the `omni.structuredlog.plugin` * plugin that created it. This header object is followed by whitespace to allow it to be * modified later as needed without having to rewrite the entire file. The telemetry transmitter * consumes this header object and modifies it to indicate its processing progress. Without * this header, the telemetry transmitter will ignore the log file. This setting defaults to * `true`. */ constexpr const char* kNeedLogHeadersSetting = "/structuredLog/needLogHeaders"; /** The setting path that will indicate whether the CloudEvents wrapper should be added to the * payload of each emitted event. By default, each event will be emitted as a CloudEvent * compliant JSON object. If this setting is enabled, the CloudEvent wrapper will be skipped * and only the schema's defined payload for the event will be emitted. The main payload will * be emitted as the top level object in the JSON output when this setting is enabled. * * Note that when this setting is used, the output will be incompatible with the telemetry * transmitter and the rest of the Omniverse telemetry toolchain. If a host app decides to * use this feature, they will be responsible for including all the relevant information that * would normally be part of the CloudEvents header. This includes fields such as the user * ID, event type, event schema, event ID, etc. This setting defaults to `false`. */ constexpr const char* kEmitPayloadOnlySettings = "/structuredLog/emitPayloadOnly"; /** The setting path that will indicate whether the cloud heartbeat events will be enabled. * These will only be emitted if the normal heartbeat events are also enabled * (with @ref kHeartbeatPeriodSetting). These events are effectively duplicate data and * are not strictly necessary. This defaults to `false`. */ constexpr const char* kEmitCloudHeartbeatSetting = "/structuredLog/emitCloudHeartbeat"; /** The settings branch that will be expected to contain zero or more key/value pairs for extra * fields to be added to each output message. This branch will only be parsed once on startup. * Any extra dynamic fields that need to be added at runtime need to be added or removed * programmatically using the `omni::structuredlog::IStructuredLogExtraFields` interface. * Only string values will be accepted under this branch. By default this settings branch * is expected to be empty and no extra fields will be added. * * Note that the number of extra fields added should be kept to a minimum required count and * size since they can affect both output and transmission performance. */ constexpr const char* kExtraFieldsSettingBranch = "/structuredLog/extraFields"; /** @} */ /** Enables or disables the structured logging log message redirection. * * @param[in] enabled Set to ``true`` to enable structured logging log message redirection. * Set to ``false`` to disable structured logging log message redirection. * @returns ``true`` if logging redirection was successfully enabled. Returns ``false`` * otherwise * * This enables or disables structured logging log message redirection. This system * will monitor log messages and emit them as structured log messages. */ inline bool setStructuredLogLoggingEnabled(bool enabled = true) { omni::core::ObjectPtr<IStructuredLog> strucLog; omni::core::ObjectPtr<IStructuredLogFromILog> log; strucLog = omni::core::borrow(omniGetStructuredLogWithoutAcquire()); if (strucLog.get() == nullptr) return false; log = strucLog.as<IStructuredLogFromILog>(); if (log.get() == nullptr) return false; if (enabled) log->enableLogging(); else log->disableLogging(); return true; } /** Checks the settings registry for structured log settings and makes them active. * * @param[in] settings The settings interface to use to retrieve configuration values. * This may not be `nullptr`. * @returns No return value. * * @remarks This sets appropriate default values for all the structured log related settings then * attempts to retrieve their current values and set them as active. This assumes * that the settings hive has already been loaded from disk and made active in the * main settings registry. * * @thread_safety This call is thread safe. */ inline void configureStructuredLogging(carb::settings::ISettings* settings) { omni::core::ObjectPtr<IStructuredLog> strucLog; omni::core::ObjectPtr<IStructuredLogSettings> ts; omni::core::ObjectPtr<IStructuredLogSettings2> ts2; omni::core::ObjectPtr<IStructuredLogFromILog> log; omni::core::ObjectPtr<IStructuredLogExtraFields> extraFields; const char* value; int64_t count; IdMode idMode = kDefaultIdMode; IdType idType = kDefaultIdType; if (settings == nullptr) return; // ****** set appropriate defaults for each setting ****** settings->setDefaultBool(kGlobalEnableSetting, false); settings->setDefaultString(kLogDirectory, ""); settings->setDefaultString(kDefaultLogNameSetting, ""); settings->setDefaultInt64(kLogRetentionCountSetting, kDefaultLogRetentionCount); settings->setDefaultInt64(kLogSizeLimitSetting, kDefaultLogSizeLimit / 1048576); settings->setDefaultInt64(kEventQueueSizeSetting, kDefaultEventQueueSize / 1024); settings->setDefaultString(kEventIdModeSetting, "fast-sequential"); settings->setDefaultString(kEventIdTypeSetting, "UUID"); settings->setDefaultBool(kEnableLogConsumerSetting, false); settings->setDefaultInt64(kHeartbeatPeriodSetting, kDefaultHeartbeatPeriod); settings->setDefaultBool(kNeedLogHeadersSetting, kDefaultNeedLogHeaders); settings->setDefaultBool(kEmitPayloadOnlySettings, kDefaultEmitPayloadOnlySettings); settings->setDefaultBool(kEmitCloudHeartbeatSetting, kDefaultEmitCloudHeartbeat); // ****** grab the structured log settings object so the config can be set ****** strucLog = omni::core::borrow(omniGetStructuredLogWithoutAcquire()); if (strucLog.get() == nullptr) return; ts = strucLog.as<IStructuredLogSettings>(); if (ts.get() == nullptr) return; // ****** retrieve the settings and make them active ****** strucLog->setEnabled(omni::structuredlog::kBadEventId, omni::structuredlog::fEnableFlagAll, settings->getAsBool(kGlobalEnableSetting)); // set the default log name. value = settings->getStringBuffer(kDefaultLogNameSetting); if (value != nullptr && value[0] != 0) ts->setLogDefaultName(value); value = settings->getStringBuffer(kLogDirectory); if (value != nullptr && value[0] != 0) { ts->setLogOutputPath(value); } else { // This setting needs to be reloaded after ISerializer has been loaded, since it can read // omniverse.toml now in case there are overrides there. extras::OmniConfig config; ts->setLogOutputPath(config.getBaseLogsPath().c_str()); } // set the log retention count. count = settings->getAsInt64(kLogRetentionCountSetting); ts->setLogRetentionCount(count); // set the log size limit. count = settings->getAsInt64(kLogSizeLimitSetting); ts->setLogSizeLimit(count * 1048576); // set the event queue size. count = settings->getAsInt64(kEventQueueSizeSetting); ts->setEventQueueSize(count * 1024); // set the event ID mode. value = settings->getStringBuffer(kEventIdModeSetting); if (carb::extras::compareStringsNoCase(value, "fast-sequential") == 0) idMode = IdMode::eFastSequential; else if (carb::extras::compareStringsNoCase(value, "sequential") == 0) idMode = IdMode::eSequential; else if (carb::extras::compareStringsNoCase(value, "random") == 0) idMode = IdMode::eRandom; else OMNI_LOG_WARN("unknown event ID mode '%s'. Assuming 'fast-sequential'.", value); // set the event ID type. value = settings->getStringBuffer(kEventIdTypeSetting); if (carb::extras::compareStringsNoCase(value, "UUID") == 0) idType = IdType::eUuid; else if (carb::extras::compareStringsNoCase(value, "uint64") == 0) idType = IdType::eUint64; else OMNI_LOG_WARN("unknown event ID type '%s'. Assuming 'UUID'.", value); ts->setEventIdMode(idMode, idType); // load the privacy settings and set the user ID from it. ts->loadPrivacySettings(); // load the enable states for each schema and event. ts->enableSchemasFromSettings(); value = omni::extras::PrivacySettings::getUserId(); if (value != nullptr && value[0] != 0) ts->setUserId(value); // setup the structured log logger. log = strucLog.as<IStructuredLogFromILog>(); if (log.get() == nullptr) return; if (settings->getAsBool(kEnableLogConsumerSetting)) log->enableLogging(); // setup the default heartbeat event period. ts2 = strucLog.as<IStructuredLogSettings2>(); if (ts2 != nullptr) { OutputFlags flags = fOutputFlagNone; count = settings->getAsInt64(kHeartbeatPeriodSetting); ts2->setHeartbeatPeriod(count); if (!settings->getAsBool(kNeedLogHeadersSetting)) flags |= fOutputFlagSkipLogHeaders; if (settings->getAsBool(kEmitPayloadOnlySettings)) flags |= fOutputFlagPayloadOnly; if (settings->getAsBool(kEmitCloudHeartbeatSetting)) flags |= fOutputFlagEmitCloudHeartbeat; ts2->setOutputFlags(flags, 0); } extraFields = strucLog.as<IStructuredLogExtraFields>(); if (extraFields != nullptr) { // walk through the extra fields branch of the settings registry and add an extra field // for each key/value pair in there. In general we don't expect there to be more than // a couple extra fields present. if (settings->isAccessibleAs(carb::dictionary::ItemType::eDictionary, kExtraFieldsSettingBranch)) { carb::dictionary::IDictionary* dictionary = carb::getCachedInterface<carb::dictionary::IDictionary>(); const carb::dictionary::Item* branch = settings->getSettingsDictionary(kExtraFieldsSettingBranch); size_t childCount = dictionary->getItemChildCount(branch); for (size_t i = 0; i < childCount; i++) { const carb::dictionary::Item* item = dictionary->getItemChildByIndex(branch, i); if (item == nullptr) continue; const char* key = dictionary->getItemName(item); value = dictionary->getStringBuffer(item); if (key != nullptr && value != nullptr) { extraFields->setValue(key, value, omni::structuredlog::fExtraFieldFlagNone); } } } } strucLog.release(); } } // namespace structuredlog } // namespace omni
31,314
C
47.400309
114
0.722648
omniverse-code/kit/include/omni/structuredlog/IStructuredLog.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 The core structured logging interface. */ #pragma once #include "StructuredLogCommon.h" #include "../core/BuiltIn.h" #include "../core/IObject.h" #include "../core/Api.h" #ifdef STRUCTUREDLOG_STANDALONE_MODE # include "../../carb/extras/Library.h" #endif #include <vector> namespace omni { /** Structured logging and Telemetry. */ namespace structuredlog { class IStructuredLog; // ******************************* enums, types, and constants ************************************ /** The expected base name for the structured log plugin. This isn't strictly necessary unless * the plugin needs to be explicitly loaded in standalone mode in an special manner. By default * the plugin is expected to be present in the same directory as the main executable. If it is * not in that location, it is the host app's responsibility to load the plugin dynamically * before attempting to call any structured log functions (even `addModuleSchemas()`). If the * module is not loaded before making any calls, all calls will just silently fail and the * structured log functionality will be in a disabled state. * * The structured log plugin can be loading using carb::extras::loadLibrary(). Using the * @ref carb::extras::fLibFlagMakeFullLibName flag will be useful unless the name is being * constructed manually using carb::extras::createLibraryNameForModule(). */ constexpr const char* OMNI_ATTR("no_py") kStructuredLogPluginName = "omni.structuredlog.plugin"; /** Base type for the version of the event payload parser to use. This is used as part of a * versioning scheme for the payload reader and event schema walker. */ using ParserVersion = uint16_t; /** Base type for the handle to an allocated block of memory returned from either the * @ref IStructuredLog::allocSchema() or @ref IStructuredLog::allocEvent() functions. * These handles uniquely identify the allocated block but should be treated as opaque handles. */ using AllocHandle = void*; /** A special string length value to indicate that a string parameter to a generated event * sending function is null terminated and should have its length calculated instead of * passing in an explicit length. */ constexpr size_t kNullTerminatedString = SIZE_MAX; /** The current event payload parser version that will be used in the IStructuredLog interface. * This symbol can be used by the generated code to set versioning information in each * event payload. This may be incremented in the future. */ constexpr ParserVersion kParserVersion = 0; /** Approximate size of the maximum data payload in bytes that a message can contain that can be * transmitted in a single message. This is a matter of the typical size of message that * can be sent to some data servers minus the average additional space needed for the message * body and other identifying information. Note that this is only an approximate guideline * and should not be taken as an exact limit. Also note that this does not account for the * change in size related to data encoding methods such as Base64. If a Base64 encoding is * to be used for the data payload, the @ref kMaxMessageLengthBase64 limit should be used * instead. */ constexpr size_t kMaxMessageLength = (10000000 - 256); /** Approximate size of the maximum data payload in bytes that a message can contain that can be * transmitted in a single message when the payload is encoded in Base64. This is a matter of * the typical message transmission limit for some data servers minus the average additional * space needed for the message body and other identifying information, then converted to * Base64's 6-to-8 bit encoding ratio (ie: every 6 bits of input data converts to 8 bits of * encoded data). Note that this is only an approximate guideline and should not be taken * as an exact limit. */ constexpr size_t kMaxMessageLengthBase64 = (kMaxMessageLength * 6) / 8; /** Base type for flags to control the behavior of the handling of a schema as a whole. A schema * encompasses the settings for a group of events that are all registered in a single call pair * to @ref IStructuredLog::allocSchema() and @ref IStructuredLog::commitSchema(). */ using SchemaFlags OMNI_ATTR("flag, prefix=fSchemaFlag") = uint32_t; /** Flag to indicate that the log file should remain open between messages. By default, each * event message will cause the log file to be opened, the message written, then the log file * closed. This flag can make writing a large number of frequent event messages more efficient * by avoiding the expense of opening and closing the log file repeatedly. However, using this * may also prevent the log file from being moved or deleted while an app is still running. To * work around that, all persistently open log files can be temporarily forced closed using * @ref IStructuredLogControl::closeLog(). */ constexpr SchemaFlags fSchemaFlagKeepLogOpen = 0x00000001; /** Flag to indicate that the log file for this schema should include the process ID in the * filename. Note that using this flag will likely lead to a lot of log files being generated * for an app since each session will create a [somewhat] unique file. This will however * reduce the possibility of potential performance issues related to many processes trying * to lock and access the same file(s) simultaneously. By default, the process ID is not * included in a schema's log filename. */ constexpr SchemaFlags fSchemaFlagLogWithProcessId = 0x00000002; /** Base type for flags to control the behavior of processing a single event. These flags * affect how events are processed and how they affect their log. */ using EventFlags OMNI_ATTR("flag, prefix=fEventFlag") = uint32_t; /** Use the log file specified by the owning event's schema instead of the default log for the * process. This can be controlled at the per-event level and would be specified by either * manually changing the flags in the generated event table or by passing a specific command * line option to the code generator tool that would set this flag on all of the schema's * events in the generated code. This can be useful if an external plugin would like to * have its events go to its own log file instead of the process's default log file. */ constexpr EventFlags fEventFlagUseLocalLog = 0x00000001; /** Flag to indicate that this event is critical to succeed and should potentially block the * calling thread on IStructuredLog::allocEvent() calls if the event queue is full. The call * will block until a buffer of the requested size can be successfully allocated instead of * failing immediately. This flag should be used sparingly since it could result in blocking * the calling thread. */ constexpr EventFlags fEventFlagCriticalEvent = 0x00000002; /** Flag to indicate that this event should be output to the stderr file. If the * @ref fEventFlagSkipLog flag is not also used, this output will be in addition to the * normal output to the schema's log file. If the @ref fEventFlagSkipLog flag is used, * the normal log file will not be written to. The default behavior is to only write the * event to the schema's log file. This can be combined with the @c fSchemaFlagOutputToStderr * and @c fSchemaFlagSkipLog flags. */ constexpr EventFlags fEventFlagOutputToStderr = 0x00000010; /** Flag to indicate that this event should be output to the stdout file. If the * @ref fEventFlagSkipLog flag is not also used, this output will be in addition to the * normal output to the schema's log file. If the @ref fEventFlagSkipLog flag is used, * the normal log file will not be written to. The default behavior is to only write the * event to the schema's log file. This can be combined with the @c fSchemaFlagOutputToStdout * and @c fSchemaFlagSkipLog flags. */ constexpr EventFlags fEventFlagOutputToStdout = 0x00000020; /** Flag to indicate that this event should not be output to the schema's specified log file. * This flag is intended to be used in combination with the @ref fEventFlagOutputToStdout * and @ref fEventFlagOutputToStderr flags to control which destination(s) each event log * message would be written to. The default behavior is to write each event message to * the schema's specified log file. Note that if this flag is used and neither the * @ref fEventFlagOutputToStderr nor @ref fEventFlagOutputToStdout flags are used, it is * effectively the same as disabling the event since there is no set destination for the * message. */ constexpr EventFlags fEventFlagSkipLog = 0x00000040; /** Base type for flags to control how events and schemas are enabled or disabled. These flags * can be passed to the @ref omni::structuredlog::IStructuredLog::setEnabled() function. */ using EnableFlags OMNI_ATTR("flag, prefix=fEnableFlag") = uint32_t; /** Flag to indicate that a call to @ref IStructuredLog::setEnabled() should * affect the entire schema that the named event ID belongs to instead of just the event. When * this flag is used, each of the schema's events will behave as though they are disabled. * However, each event's individual enable state will not be modified. When the schema is * enabled again, the individual events will retain their previous enable states. */ constexpr EnableFlags fEnableFlagWholeSchema = 0x00000002; /** Flag to indicate that the enable state of each event in a schema should be overridden when * the @ref fEnableFlagWholeSchema flag is also used. When this flag is used, the enable state * of each event in the schema will be modified instead of just the enable state of the schema * itself. When this flag is not used, the default behavior is to change the enable state * of just the schema but leave the enable states for its individual events unmodified. */ constexpr EnableFlags fEnableFlagOverrideEnableState = 0x00000004; /** Flag to indicate that an enable state change should affect the entire system, not just * one schema or event. When this flag is used in @ref IStructuredLog::setEnabled(), the @a eventId * parameter must be set to @ref kBadEventId. */ constexpr EnableFlags fEnableFlagAll = 0x00000008; /** Base type for flags to control how new events are allocated. These flags can be passed * to the @ref IStructuredLog::allocEvent() function. */ using AllocFlags OMNI_ATTR("flag, prefix=fAllocFlag") = uint32_t; /** Flag to indicate that the event should only be added to the queue on commit but that the * consumer thread should not be started yet if it is not already running. */ constexpr AllocFlags fAllocFlagOnlyQueue = 0x00000010; /** A descriptor for a single structured log event. This struct should not need to be used * externally but will be used by the generated code in the schema event registration helper * function. A schema consists of a set of one or more of these structs plus some additional * name and version information. The schema metadata is passed to @ref IStructuredLog::allocSchema(). * The array of these event info objects is passed to @ref IStructuredLog::commitSchema(). */ struct EventInfo { /** The fully qualified name of this event. While there is no strict formatting requirement * for this name, this should be an RDNS style name that specifies the full ownership chain * of the event. This should be similar to the following format: * "com.nvidia.omniverse.<appName>.<eventName>" */ const char* eventName; /** Flags controlling the behavior of this event when being generated or processed. Once * registered, these flags may not change. This may be zero or more of the @ref EventFlags * flags. */ EventFlags flags; /** Version of the schema tree building object that is passed in through @ref schema. This * is used to indicate which version of the event payload block helper classes will be used * to create and read the blocks. In general this should be @ref kParserVersion. */ ParserVersion parserVersion; /** The event ID that will be used to identify this event from external callers. This should * be a value that uniquely identifies the event's name, schema's version, and the JSON * parser version (ie: @ref parserVersion above) that will be used. Ideally this should be * a hash of a string containing all of the above information. It is the caller's * responsibility to ensure the event ID is globally unique enough for any given app's usage. */ uint64_t eventId; /** Schema tree object for this event. This tree object is expected to be built in the * block of memory that is returned from @ref IStructuredLog::allocSchema(). Optionally, this may * be nullptr to indicate that the event's payload is intended to be empty (ie: the event * is just intended to be an "I was here" event). */ const void* schema; }; // ********************************* IStructuredLog interface ************************************* /** Main structured log interface. This should be treated internally as a global singleton. Any * attempt to create or acquire this interface will return the same object just with a new * reference taken on it. * * There are three main steps to using this interface: * * Set up the interface. For most app's usage, all of the default settings will suffice. * The default log path will point to the Omniverse logs folder and the default user ID * will be the one read from the current user's privacy settings file (if it exists). If * the default values for these is not sufficient, a new user ID should be set with * @ref omni::structuredlog::IStructuredLogSettings::setUserId() and a log output path should be set with * @ref omni::structuredlog::IStructuredLogSettings::setLogOutputPath(). * If the privacy settings file is not present, * the user name will default to a random number. The other defaults should be sufficient * for most apps. This setup only needs to be performed once by the host app if at all. * The @ref omni::structuredlog::IStructuredLogSettings interface can be acquired either * by casting an @ref omni::structuredlog::IStructuredLog * object to that type or by directly creating the @ref omni::structuredlog::IStructuredLogSettings * object using omni::core::ITypeFactory_abi::createType(). * * Register one or more event schemas. * This is done with @ref omni::structuredlog::IStructuredLog::allocSchema() and * @ref omni::structuredlog::IStructuredLog::commitSchema(). * At least one event must be registered for any events to * be processed. Once a schema has been registered, it will remain valid until the * structured log module is unloaded from the process. There is no way to forcibly * unregister a set of events once registered. * * Send zero or more events. This is done with the @ref omni::structuredlog::IStructuredLog::allocEvent() and * @ref omni::structuredlog::IStructuredLog::commitEvent() functions. * * For the most part, the use of this interface will be dealt with in generated code. This * generated code will come from the 'omni.structuredlog' tool in the form of an inlined header * file. It is the host app's responsibility to call the header's schema registration helper * function at some point on startup before any event helper functions are called. * * All messages generated by this structured log system will be CloudEvents v1.0 compliant. * These should be parsable by any tool that is capable of understanding CloudEvents. * * Before an event can be sent, at least one schema describing at least one event must be * registered. This is done with the @ref omni::structuredlog::IStructuredLog::allocSchema() and * @ref omni::structuredlog::IStructuredLog::commitSchema() functions. * The @ref omni::structuredlog::IStructuredLog::allocSchema() function returns * a handle to a block of memory owned by the structured log system and a pointer to that block's * data. The caller is responsible for both calculating the required size of the buffer before * allocating, and filling it in with the schema data trees for each event that can be sent as * part of that schema. The helper functions in @ref omni::structuredlog::JsonTreeSizeCalculator and * @ref omni::structuredlog::JsonBuilder can be used to build these trees. Once these trees are built, they are * stored in a number of entries in an array of @ref omni::structuredlog::EventInfo objects. This array of event * info objects is then passed to @ref omni::structuredlog::IStructuredLog::commitSchema() to complete the schema * registration process. * * Sending of a message is split into two parts for efficiency. The general idea is that the * caller will allocate a block of memory in the event queue's buffer and write its data directly * there. * The allocation occurs with the @ref omni::structuredlog::IStructuredLog::allocEvent() call. * This will return a * handle to the allocated block and a pointer to the first byte to start writing the payload * data to. The buffer's header will already have been filled in upon return from * @ref omni::structuredlog::IStructuredLog::allocEvent(). * Once the caller has written its event payload information to * the buffer, it will call @ref omni::structuredlog::IStructuredLog::commitEvent() * to commit the message to the queue. At * this point, the message can be consumed by the event processing thread. * * Multiple events may be safely allocated from and written to the queue's buffer simultaneously. * There is no required order that the messages be committed in however. If a buffer is * allocated after one that has not been committed yet, and that newer event is committed first, * the only side effect will be that the event processing thread will be stalled in processing * new events until the first message is also committed. This is important since the events * would still need to be committed to the log in the correct order. * * All events that are processed through this interface will be written to a local log file. The * log file will be periodically consumed by an external process (the Omniverse Transmitter app) * that will send all the approved events to the telemetry servers. Only events that have been * approved by legal will be sent. All other messages will be rejected and only remain in the * log files on the local machine. */ class IStructuredLog_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.structuredlog.IStructuredLog")> { protected: /** Checks whether a specific event or schema is enabled. * * @param[in] eventId The unique ID of the event to check the enable state of. This * is the ID that was originally used to register the event. * @returns `true` if both the requested event and its schema is enabled. * @returns `false` if either the requested event or its schema is disabled. * * @remarks This checks if a named event or its schema is currently enabled in the structured * log system. Individual events or entire schemas may be disabled at any given * time. Both the schema and each event has its own enable state. A schema can be * disabled while still leaving its events' previous enable/disable states * unmodified. When the schema is enabled again, its events will still retain their * previous enable states. Set @ref omni::structuredlog::IStructuredLog::setEnabled() * for more information on how to enable and disable events and schemas. */ virtual bool isEnabled_abi(EventId eventId) noexcept = 0; /** Sets the enable state for a structured log event or schema, or the system globally. * * @param[in] eventId The ID of the event to change the enable state of. This is the ID * that was originally used to register the event. If the * @ref omni::structuredlog::fEnableFlagAll flag is used, this must be * set to @ref omni::structuredlog::kBadEventId. * @param[in] flags Flags to control the behavior of this function. This may be zero or * more of the @ref omni::structuredlog::EnableFlags flags. * If this includes the @ref omni::structuredlog::fEnableFlagAll * flag, @p eventId must be set to @ref omni::structuredlog::kBadEventId. * @param[in] enabled Set to true to enable the named event or schema. Set to false to * disable the named event or schema. If the * @ref omni::structuredlog::fEnableFlagAll flag is used, this sets the * new enable/disable state for the structured log system as a whole. * @returns No return value. * * @remarks This changes the current enable state for an event or schema. The scope of the * enable change depends on the flags that are passed in. When an event is * disabled (directly or from its schema or the structured log system being * disabled), it will also prevent it from being generated manually. In this case, * any attempt to call @ref omni::structuredlog::IStructuredLog::allocEvent() for * that disabled event or schema will simply fail immediately. * * @remarks When a schema is disabled, it effectively disables all of its events. Depending * on the flag usage however (ie: @ref omni::structuredlog::fEnableFlagOverrideEnableState), * disabling the schema may or may not change the enable states of each of its * individual events as well (see @ref omni::structuredlog::fEnableFlagOverrideEnableState * for more information). * * @note The @ref omni::structuredlog::fEnableFlagAll flag should only ever by used by the * main host app since this will affect the behavior of all modules' events regardless * of their own internal state. Disabling the entire system should also only ever be * used sparingly in cases where it is strictly necessary (ie: compliance with local * privacy laws). */ virtual void setEnabled_abi(EventId eventId, EnableFlags flags, bool enabled) noexcept = 0; // ****** schema registration function ****** /** Allocates a block of memory for an event schema. * * @param[in] schemaName The name of the schema being registered. This may not be * nullptr or an empty string. There is no set format for this * schema name, but it should at least convey some information * about the app's name and current release version. This name * will be used to construct the log file name for the schema. * @param[in] schemaVersion The version number for the schema itself. This may not be * nullptr or an empty string. This should be the version number * of the schema itself, not of the app or component. This will * be used to construct the 'dataschema' name that gets passed * along with each CloudEvents message header. * @param[in] flags Flags to control the behavior of the schema. This may be * zero or more of the @ref omni::structuredlog::SchemaFlags flags. * @param[in] size The size of the block to allocate in bytes. If this is 0, a * block will still be allocated, but its actual size cannot be * guaranteed. The @ref omni::structuredlog::JsonTreeSizeCalculator * helper class can be used to calculate the size needs for the new schema. * @param[out] outHandle Receives the handle to the allocated memory block on success. * On failure, this receives nullptr. Each successful call * must pass this handle to @ref omni::structuredlog::IStructuredLog::commitSchema() * even if an intermediate failure occurs. In the case of a schema * tree creation failure, nullptr should be passed for @a events * in the corresponding @ref omni::structuredlog::IStructuredLog::commitSchema() call. * This will allow the allocated block to be cleaned up. * @returns A pointer to the allocated block on success. This block does not need to be * explicitly freed - it will be managed internally. This pointer will point to * the first byte that can be written to by the caller and will be at least @p size * bytes in length. This pointer will always be aligned to the size of a pointer. * @returns `nullptr` if no more memory is available. * @returns `nullptr` if an invalid parameter is passed in. * * @remarks This allocates a block of memory that the schema tree(s) for the event(s) in a * schema can be created and stored in. Pointers to the start of each event schema * within this block are expected to be stored in one of the @ref omni::structuredlog::EventInfo objects * that will later be passed to @ref omni::structuredlog::IStructuredLog::commitSchema(). The caller is * responsible for creating and filling in returned block and the array of * @ref omni::structuredlog::EventInfo objects. * The @ref omni::structuredlog::BlockAllocator helper class may be used to * allocate smaller chunks of memory from the returned block. * * @note This should only be used in generated structured log source code. This should not * be directly except when absolutely necessary. This should also not be used as a * generic allocator. Failure to use this properly will result in memory being * leaked. * * @thread_safety This call is thread safe. */ virtual uint8_t* allocSchema_abi(OMNI_ATTR("c_str, in, not_null") const char* schemaName, OMNI_ATTR("c_str, in, not_null") const char* schemaVersion, SchemaFlags flags, size_t size, OMNI_ATTR("out") AllocHandle* outHandle) noexcept = 0; /** Commits an allocated block and registers events for a single schema. * * @param[in] schemaBlock The block previously returned from * @ref omni::structuredlog::IStructuredLog::allocSchema() * that contains the built event trees for the schema to register. * These trees must be pointed to by the @ref omni::structuredlog::EventInfo::schema * members of the @p events array. * @param[in] events The table of events that belong to this schema. This provides * information about each event such as its name, control flags, * event identifier, and a schema describing how to interpret its * binary blob on the consumer side. This may not be nullptr. Each * of the trees pointed to by @ref omni::structuredlog::EventInfo::schema in this table * must either be set to nullptr or point to an address inside the * allocated schema block @p schemaBlock that was returned from the * corresponding call to @ref omni::structuredlog::IStructuredLog::allocSchema(). * If any of the schema trees point to an address outside of the schema block, * this call will fail. * @param[in] eventCount The total number of events in the @p events table. At least one * event must be registered. This may not be 0. * @retval omni::structuredlog::SchemaResult::eSuccess if the new schema * is successfully registered as a set of unique events. * @retval omni::structuredlog::SchemaResult::eAlreadyExists if the new * schema exactly matches one that has already been successfully registered. * This can be considered a successful result. * In this case, the schema block will be destroyed before return. * @retval omni::structuredlog::SchemaResult::eEventIdCollision if the new schema contains an event whose * identifier matches that of an event that has already been registered with another * schema. This indicates that the name of the event that was used to generate the * identifier was likely not unique enough, or that two different versions of the * same schema are trying to be registered without changing the schema's version * number first. No new events will be registered in this case and the schema * block will be destroyed before return. * @retval omni::structuredlog::SchemaResult::eFlagsDiffer if the new schema exactly matches another schema * that has already been registered except for the schema flags that were used * in the new one. This is not allowed without a version change in the new schema. * No new events will be registered in this case and the schema block will be * destroyed before return. * @returns Another @ref omni::structuredlog::SchemaResult error code for other types of failures. No new events * will be registered in this case and the schema block will be destroyed before * return. * * @remarks This registers a new schema and its events with the structured log system. This * will create a new set of events in the structured log system. These events * cannot be unregistered except by unloading the entire structured log system * altogether. Upon successful registration, the events in the schema can be * emitted using the event identifiers they were registered with. * * @remarks If the new schema matches one that has already been registered, The operation * will succeed with the result @ref omni::structuredlog::SchemaResult::eAlreadyExists. * The existing * schema's name, version, flags, and event table (including order of events) must * match the new one exactly in order to be considered a match. If anything differs * (even the flags for a single event or events out of order but otherwise the same * content), the call will fail. If the schema with the differing flags or event * order is to be used, its version or name must be changed to avoid conflict with * the existing schema. * * @remarks When generating the event identifiers for @ref omni::structuredlog::EventInfo::eventId it is * recommended that a string uniquely identifying the event be created then hashed * using an algorithm such as FNV1. The string should contain the schema's client * name, the event's name, the schema's version, and any other values that may * help to uniquely identify the event. Once hashed, it is very unlikely that * the event identifier will collide with any others. This is the method that the * code generator tool uses to create the unique event identifiers. * * @remarks Up to 65536 (ie: 16-bit index values) events may be registered with the * structured log system. The performance of managing a list of events this large * is unknown and not suggested however. Each module, app, or component should only * register its schema(s) once on startup. This can be a relatively expensive * operation if done frequently and unnecessarily. * * @thread_safety This call is thread safe. */ virtual SchemaResult commitSchema_abi(OMNI_ATTR("in, out, not_null") AllocHandle schemaBlock, OMNI_ATTR("in, *in, count=eventCount, not_null") const EventInfo* events, size_t eventCount) noexcept = 0; // ****** event message generation functions ****** /** Allocates a block of memory to store an event's payload data in. * * @param[in] version The version of the parser that should be used to read this * event's payload data. This should be @ref omni::structuredlog::kParserVersion. * If the structured log system that receives this message does not * support this particular version (ie: a newer module is run * on an old structured log system), the event message will simply * be dropped. * @param[in] eventId the unique ID of the event that is being generated. This ID must * exactly match the event ID that was provided in the * @ref omni::structuredlog::EventInfo::eventId value when the event * was registered. * @param[in] flags Flags to control how the event's block is allocated. This may * be a combination of zero or more of the @ref omni::structuredlog::AllocFlags * flags. * @param[in] payloadSize The total number of bytes needed to store the event's payload * data. The caller is responsible for calculating this ahead * of time. If the event does not have a payload, this should be * 0. The number of bytes should be calculated according to how * the requested event's schema (ie: @ref omni::structuredlog::EventInfo::schema) lays * it out in memory. * @param[out] outHandle Receives the handle to the allocated block of memory. This * must be passed to IStructuredLog::commitEvent() once the caller * has finished writing all of the payload data to the returned * buffer. The IStructuredLog::commitEvent() call acts as the * cleanup function for this handle. * @returns A pointer to the buffer to use for the event's payload data if successfully * allocated. The caller should start writing its payload data at this address * according to the formatting information in the requested event's schema. This * returned pointer will always be aligned to the size of a pointer. * @returns `nullptr` if the requested event, its schema, or the entire system is currently * disabled. * @returns `nullptr` if the event queue's buffer is full and a buffer of the requested * size could not be allocated. In this case, a invalid handle will be returned * in @p outHandle. The IStructuredLog::commitEvent() function does not need to be * called in this case. * @returns `nullptr` if the event queue failed to be created or its processing thread failed * start up. * @returns `nullptr` if the given event ID is not valid. * * @remarks This is the main entry point for creating an event message. This allocates * a block of memory that the caller can fill in with its event payload data. * The caller is expected to fill in this buffer as quickly as possible. Once * the buffer has been filled, its handle must be passed to the * @ref omni::structuredlog::IStructuredLog::commitEvent() function to finalize and send. * Failing to pass a * valid handle to @ref omni::structuredlog::IStructuredLog::commitEvent() will stall the event queue * indefinitely. * * @remarks If the requested event has been marked as 'critical' by using the event flag * @ref omni::structuredlog::fEventFlagCriticalEvent, a blocking allocation will be used here instead. * In this case, this will not fail due to the event queue being out of space. * * @note This call will fail immediately if either the requested event, its schema, or * the entire system has been explicitly disabled. It is the caller's responsibility * to both check the enable state of the event before attempting to send it (ie: to * avoid doing unnecessary work), and to gracefully handle the potential of this * call failing. * * @note It is the caller's responsibility to ensure that no events are generated during * C++ static destruction time for the process during shutdown. Especially on * Windows, doing so could result in an event being allocated but not committed * thereby stalling the event queue. This could lead to a hang on shutdown. * * @thread_safety This call is thread safe. */ virtual uint8_t* allocEvent_abi(ParserVersion version, EventId eventId, AllocFlags flags, size_t payloadSize, OMNI_ATTR("out") AllocHandle* outHandle) noexcept = 0; /** finishes writing a message's payload and queues it for processing. * * @param[in] handle The handle to the queue buffer block to be committed. This must not * be nullptr. This must be the same handle that was returned through * @a outHandle on a recent call to @ref omni::structuredlog::IStructuredLog::allocEvent() * on this same thread. Upon return, this handle will be invalid and should be * discarded by the caller. * @returns No return value. * * @remarks This commits a block that was previously allocated on this thread with * @ref omni::structuredlog::IStructuredLog::allocEvent(). * It is required that the commit call occur on the * same thread that the matching @ref omni::structuredlog::IStructuredLog::allocEvent() * call was made on. * Each successful @ref omni::structuredlog::IStructuredLog::allocEvent() call must * be paired with exactly one * @ref omni::structuredlog::IStructuredLog::commitEvent() call on the same thread. * Failing to do so would result in the event queue thread stalling. * * @thread_safety This call is thread safe. */ virtual void commitEvent_abi(OMNI_ATTR("in, not_null") const AllocHandle handle) noexcept = 0; }; // skipping this because exhale can't handle the function pointer type #ifndef DOXYGEN_SHOULD_SKIP_THIS /** Registration function to install a schema with the structured logging system. * * @param[in] log A pointer to the global singleton structured logging system to install * the schema in. * @returns `true` if the schema is successfully installed or was already installed. * @returns `false` if the schema could not be installed. This may be caused by a lack of * available memory, or too many events have been registered in the system. */ using SchemaAddFn = bool (*)(IStructuredLog*); /** Retrieves the local schema registration list for this module. * * @returns The static list of schemas to register for this module. This is intended to be * a static list that can be built up at compile time to collect schemas to * register. Each module will have its own copy of this list. */ inline std::vector<SchemaAddFn>& getModuleSchemas() { static std::vector<SchemaAddFn> sSchemas; return sSchemas; } #endif } // namespace structuredlog } // namespace omni #ifdef OMNI_COMPILE_AS_DYNAMIC_LIBRARY OMNI_API omni::structuredlog::IStructuredLog* omniGetStructuredLogWithoutAcquire(); #else /** * Retrieves the module's structured log object. omni::core::IObject::acquire() is **not** called on the returned * pointer. * * The global omni::structuredlog::IStructuredLog instance can be configured by passing an * @ref omni::structuredlog::IStructuredLog to omniCoreStart(). * If an instance is not provided, omniCoreStart() attempts to create one. * * @returns the calling module's structured log object. The caller will not own a reference to * the object. If the caller intends to store the object for an extended period, it * must take a reference to it using either a call to acquire() or by borrowing it into * an ObjectPtr<> object. This object must not be released by the caller unless a * reference to it is explicitly taken. */ # ifndef STRUCTUREDLOG_STANDALONE_MODE inline omni::structuredlog::IStructuredLog* omniGetStructuredLogWithoutAcquire() { return static_cast<omni::structuredlog::IStructuredLog*>(omniGetBuiltInWithoutAcquire(OmniBuiltIn::eIStructuredLog)); } # else inline omni::structuredlog::IStructuredLog* omniGetStructuredLogWithoutAcquire() { using GetFunc = omni::structuredlog::IStructuredLog* (*)(); static GetFunc s_get = nullptr; if (s_get == nullptr) { carb::extras::LibraryHandle module = carb::extras::loadLibrary( omni::structuredlog::kStructuredLogPluginName, carb::extras::fLibFlagMakeFullLibName); s_get = carb::extras::getLibrarySymbol<GetFunc>(module, "omniGetStructuredLogWithoutAcquire_"); if (s_get == nullptr) return nullptr; } return s_get(); } # endif #endif #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "IStructuredLog.gen.h" /** Common entry point for sending an event. * * @param event_ The name of the event to send. This is expected to be the 'short' * name for the event as named in its schema's *_sendEvent() function. * This short name will be the portion of the function name before the * '_sendEvent' portion of the name. * @param ... The set of parameters specific to the event to be sent. These are * potentially different for each event. Callers should refer to the * original schema to determine the actual set of parameters to send. * @returns No return value. * * @remarks This is intended to be used to send all structured log events instead of calling the * generated schema class's functions directly. This provides a consistent entry * point into sending event messages and allows parameter evaluation to be delayed * if either the event or schema is disabled. */ #define OMNI_STRUCTURED_LOG(event_, ...) \ do \ { \ auto strucLog__ = omniGetStructuredLogWithoutAcquire(); \ if (strucLog__) \ { \ if (event_##_isEnabled(strucLog__)) \ { \ event_##_sendEvent(strucLog__, ##__VA_ARGS__); \ } \ } \ } while (0) namespace omni { namespace structuredlog { //! A function that registers all schemas within a module. //! //! \note It is not necessary to call this function; it is automatically called by \ref carbOnPluginPreStartup inline void addModulesSchemas() noexcept { auto strucLog = omniGetStructuredLogWithoutAcquire(); if (strucLog == nullptr) return; for (auto& schemaAddFn : getModuleSchemas()) { schemaAddFn(strucLog); } } } // namespace structuredlog } // namespace omni /** @copydoc omni::structuredlog::IStructuredLog_abi */ class omni::structuredlog::IStructuredLog : public omni::core::Generated<omni::structuredlog::IStructuredLog_abi> { }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "IStructuredLog.gen.h"
46,650
C
60.463768
121
0.660815
omniverse-code/kit/include/omni/audio/IAudioPlayer.h
// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // //! @file //! @brief Defines an interface to provide a simple audio player interface. #pragma once #include <carb/Interface.h> #include <carb/audio/IAudioData.h> namespace omni { namespace audio { /** Handle for a created audio player object. This will be `nullptr` to indicate an invalid * audio player object. */ struct AudioPlayer; /** Prototype of a callback function to signal that a sound data log operation completed. * * @param[in] success Set to `true` if the load operation was successful. Set to `false` * otherwise. * @param[in] context The original caller specified context value that was provided when * this callback was registered in either IAudioPlayer::playSound() or * IAudioPlayer::loadSound() families of functions. * @returns No return value. */ using OnLoadedCallback = void (*)(bool success, void* context); /** Prototype of a callback function to signal that a sound completed its playback. * * @param[in] context The original caller specified context value that was provided when * this callback was registered in either IAudioPlayer::playSound() * family of functions. * @returns No return value. */ using OnEndedCallback = void (*)(void* context); /** Base type for flags that can be provided to IAudioPlayer::loadSoundInMemory() or * IAudioPlayer::playSoundInMemory(). * @{ */ using AudioPlayerFlags = uint32_t; /** Flag to indicate that the data blob being passed in only contains the raw PCM data and * no header or format information. When this flag is used, the frame rate, channel count, * and sample data format must also be specified when passing the blob to either * IAudioPlayer::loadSoundInMemory() or IAudioPlayer::playSoundInMemory(). */ constexpr AudioPlayerFlags fPlayerFlagRawData = 0x01; /** Flag to indicate that the data blob should be reloaded even if it is already cached in * the audio player object. */ constexpr AudioPlayerFlags fPlayerFlagForceReload = 0x02; /** @} */ /** The supported PCM formats for loading or playing raw PCM data through the * IAudioPlayer::loadSoundInMemory() or IAudioPlayer::playSoundInMemory() functions. */ enum class RawPcmFormat { ePcm8, ///< unsigned 8-bits per sample integer PCM data. ePcm16, ///< signed 16-bits per sample integer PCM data. ePcm32, ///< signed 32-bits per sample integer PCM data. ePcmFloat, ///< 32-bits per sample floating point PCM data. }; /** The descriptor for IAudioPlayer::drawWaveform(). */ struct DrawWaveformDesc { /** The name for the output image file. * This path supports the standard path aliases (e.g. "${resources}") * The path must point to an existing directory on disk. * This must be nullptr to store the image in @p outputBuffer. */ const char* filename; /** The buffer to store the raw RGBA8888 in. * @p filename must be nullptr for this to be used. * This needs to be at least @p width * @p height * 4 bytes long. */ uint8_t* outputBuffer; /** The width of the output image, in pixels. */ size_t width; /** The height of the output image, in pixels. */ size_t height; /** The foreground color in normalized RGBA color. */ carb::Float4 fgColor; /** The background color in normalized RGBA color. */ carb::Float4 bgColor; }; /** Descriptor of a blob of audio data in memory. This data can either be a full supported sound * file in memory, or just simple raw PCM data. If raw PCM data is provided, the information * about the data format must also be provided. */ struct AudioDataInMemory { /** The name to be used to cache the file data in the audio player. This may be `nullptr` or * an empty string to indicate that it shouldn't be cached. If it is not cached, the sound * is only expected to be played once. If it is played again, it will be reloaded instead of * pulling a cached version that was previously loaded or played. */ const char* name = nullptr; /** The buffer of sound data to be loaded. This is interpreted according to the flags passed * to either IAudioPlayer::loadSoundInMemory() or IAudioPlayer::playSoundInMemory(). If the * flags indicate that raw data is passed in, the frame rate, channel count, and data format * values will also be required. This may not be `nullptr`. */ const void* buffer; /** The size of @ref buffer in bytes. This may not be 0. */ size_t byteCount; /** The frame rate to play the audio data back at. This must be a non-zero value if raw PCM * data is being provided. This is measured in Hertz. Typical values for this are 44100Hz, * or 48000Hz. Any value in the range from 1000Hz to 200000Hz is generally accepted. Though * note that if this value is not correct for the given sound data, it may play back either * to quickly or too slowly. The pitch of the sound will also be affected accordingly. This * value will be ignored if the blob in @ref buffer already contains format information. */ size_t frameRate = 0; /** The number of channels in each frame of data in the sound. This must be a non-zero value * if raw PCM data is being provided. If this is incorrect for the given data, the sound will * play incorrectly. This value will be ignored if the blob in @ref buffer already contains * format information. */ size_t channels = 0; /** The format of the PCM data. This must be a valid value if raw PCM data is being provided. * This must be well known by the caller otherwise the audio data will load incorrectly and * undefined output would be likely to result (it won't be generally problematic except to * the ears of listeners). This value will be ignored if the bob in @ref buffer already * contains format information. */ RawPcmFormat format = RawPcmFormat::ePcm16; }; /** Simple interface to be able to play audio assets. * All of the calls to this interface are internally serialized by a mutex. * This provides an interface for an audio player that has one voice and * allows individual assets to be played. * Multiple audio players can be opened per-process but they all share the same * IAudioPlayer backend which limits the number of simultaneously playing audio * players to 4. */ struct IAudioPlayer { CARB_PLUGIN_INTERFACE("omni::audio::IAudioPlayer", 0, 3); /** Create an audio player instance. * @returns A new audio player if creation succeeded. * @returns nullptr if creation failed. * * @remarks This creates an audio system with 1 voice that can play sound assets. */ AudioPlayer*(CARB_ABI* createAudioPlayer)(); /** Destroy an audio player instance. * @param[in] player The player to destroy. * * @remarks This will stop any audio playing, release all assets and free * the memory of @p player. */ void(CARB_ABI* destroyAudioPlayer)(AudioPlayer* player); /** Play a sound asset. * @param[in] player The player to play this sound on. * @param[in] path The path to the sound asset to play. * This must be an absolute file path to a sound asset. * @param[in] onLoaded A callback to execute once the asset has * loaded and is about to play. * This may be used for something like turning * off a spinner icon to indicate that the * asset has loaded. * The first parameter of this callback indicates * whether the load request succeeded. * The second parameter is @p context. * This may be nullptr if the callback is not needed. * @param[in] onEnded A callback to execute once the asset has finished * playing or has been stopped. * The parameter passed is @p context. * This may be nullptr if the callback is not needed. * @param[in] context The parameter to pass into @p onLoaded and @p onEnded. * @param[in] startTime The time offset into the sound to start playing it * at. This is measured in seconds. * * @remarks This will spawn a task to play this sound asset once it has loaded. * This is intended to be used for auditioning sounds to a user * from something like the content window, to allow them to hear * a sound before they use it in their scene. * * @note If another sound is currently playing, it will be stopped before * playing this sound. * * @note The callbacks are called within an internal static recursive * mutex, so the callbacks must be careful to avoid deadlock if they * need to acquire another lock, such as the python GIL. * * @note Playing the sound will fail if too many other audio players are * playing simultaneously. */ void(CARB_ABI* playSound)(AudioPlayer* player, const char* path, OnLoadedCallback onLoaded, OnEndedCallback onEnded, void* context, double startTime); /** Load a sound asset for future playback * @param[in] player The player to play this sound on. * @param[in] path The path to the sound asset to play. * This must be an absolute file path to a sound asset. * @param[in] onLoaded A callback to execute once the asset has * loaded and is about to play. * This may be used for something like turning * off a spinner icon to indicate that the * asset has loaded. * The first parameter of this callback indicates * whether the load request succeeded. * The second parameter is @p context. * This may be nullptr if the callback is not needed. * @param[in] context The parameter to pass into @p onLoaded and @p onEnded. * * @remarks This will fetch an asset so that the next call to playSound() * can begin playing the sound immediately. * This will also stop the currently playing sound, if any. * This function will also cause getSoundLength() to begin * returning the length of this sound. */ void(CARB_ABI* loadSound)(AudioPlayer* player, const char* path, OnLoadedCallback onLoaded, void* context); /** Stop playing the current sound, if any. * @param[in] player The player to play this sound on. */ void(CARB_ABI* stopSound)(AudioPlayer* player); /** Pause playback of the current sound, if any. * @param[in] player The player to play this sound on. */ void(CARB_ABI* pauseSound)(AudioPlayer* player); /** Unpause playback of the current sound, if any. * @param[in] player The player to play this sound on. */ void(CARB_ABI* unpauseSound)(AudioPlayer* player); /** Get the length of the currently playing sound. * @param[in] player The player to play this sound on. * @returns The length of the currently playing sound in seconds. * @returns 0.0 if there is no playing sound. */ double(CARB_ABI* getSoundLength)(AudioPlayer* player); /** Get the play cursor position in the currently playing sound. * @param[in] player The player to play this sound on. * @returns The play cursor position in the currently playing sound in seconds. * @returns 0.0 if there is no playing sound. */ double(CARB_ABI* getPlayCursor)(AudioPlayer* player); /** Set the cursor in the sound. * @param[in] player The player to use to set the cursor in the sound. * @param[in] onLoaded A callback to execute once the asset has * loaded and is about to play. * This may be used for something like turning * off a spinner icon to indicate that the * asset has loaded. * The first parameter of this callback indicates * whether the load request succeeded. * The second parameter is @p context. * This may be nullptr if the callback is not needed. * @param[in] onEnded A callback to execute once the asset has finished * playing or has been stopped. * The parameter passed is @p context. * This may be nullptr if the callback is not needed. * @param[in] context The parameter to pass into @p onLoaded and @p onEnded. * @param[in] startTime The time offset to set the cursor to. This is measured in seconds. * * @note The previous onEnded() callback that was passed to playSound() will * be called after @p onLoaded() is called. */ void(CARB_ABI* setPlayCursor)(AudioPlayer* player, OnLoadedCallback onLoaded, OnEndedCallback onEnded, void* context, double startTime); /** Render the waveform to an image to a file. * @param[in] player The player whose waveform image will be rendered. * @param[in] desc The descriptor for the waveform to draw. * @return true if the operation was successful. * @returns false if the file could not be generated. * * @note The functionality of writing to a file is a temporary workaround. * This will eventually be changed to output a memory buffer. */ bool(CARB_ABI* drawWaveform)(AudioPlayer* player, const DrawWaveformDesc* desc); /** Play a sound asset from data in memory. * * @param[in] player The player to play this sound on. * @param[in] data The descriptor of the data blob and its required format * information. This must include the format information for the * sound if the @ref fPlayerFlagRawData flag is given in @p flags. * This may not be `nullptr`. * @param[in] onLoaded A callback to execute once the asset has loaded and is about to * play. This may be used for something like turning off a spinner * icon to indicate that the asset has loaded. The first parameter * of this callback indicates whether the load request succeeded. * The second parameter is @p context. This may be `nullptr` if the * callback is not needed. * @param[in] onEnded A callback to execute once the asset has finished playing or has * been stopped. The parameter passed is @p context. This may be * `nullptr` if the callback is not needed. * @param[in] context The parameter to pass into @p onLoaded and @p onEnded. * @param[in] startTime The time offset into the sound to start playing it at. This is * measured in seconds. * @param[in] flags Flags to control how the sound data is loaded and cached. If the * data blob does not contain format information and is just raw PCM * sample data, the @ref fPlayerFlagRawData flag must be specified * and the @a frameRate, @a channels, and @a format values in @p data * must also be given. Without these, the sound data cannot be * properly loaded. * @returns No return value. * * @remarks The sound asset will start playing asynchronously when the asset has loaded. * The asset is given as a data blob in memory. The data may either be a full * file loaded into memory or just raw PCM data. If raw PCM data is given, * additional parameters must be used to specify the sample type, channel count, * and frame rate so that the data can be successfully decoded. * * @note If another sound is currently playing, it will be stopped before * playing this sound. * * @note The callbacks are called within an internal static recursive * mutex, so the callbacks must be careful to avoid deadlock if they * need to acquire another lock, such as the python GIL. * * @note Playing the sound will fail if too many other audio players are * playing simultaneously. */ void(CARB_ABI* playSoundInMemory)(AudioPlayer* player, const AudioDataInMemory* data, OnLoadedCallback onLoaded, OnEndedCallback onEnded, void* context, double startTime, AudioPlayerFlags flags); /** Play a sound asset from data in memory. * * @param[in] player The player to play this sound on. * @param[in] data The descriptor of the data blob and its required format * information. This must include the format information for the * sound if the @ref fPlayerFlagRawData flag is given in @p flags. * This may not be `nullptr`. * @param[in] onLoaded A callback to execute once the asset has loaded and is about to * play. This may be used for something like turning off a spinner * icon to indicate that the asset has loaded. The first parameter * of this callback indicates whether the load request succeeded. * The second parameter is @p context. This may be `nullptr` if the * callback is not needed. * @param[in] context The parameter to pass into @p onLoaded and @p onEnded. * @param[in] flags Flags to control how the sound data is loaded and cached. If the * data blob does not contain format information and is just raw PCM * sample data, the @ref fPlayerFlagRawData flag must be specified * and the @a frameRate, @a channels, and @a format values in @p data * must also be given. Without these, the sound data cannot be * properly loaded. * @returns No return value. * * @remarks This will fetch an asset in memory so that the next call to playSound() can begin * playing the sound immediately. In order for this to be useful, the @a name value * in @p data must be a non-empty string so that the loaded sound is cached. If no * name is given, the operation will just fail immediately. This will also stop the * currently playing sound, if any. This function will also cause getSoundLength() * to begin returning the length of this sound. */ void(CARB_ABI* loadSoundInMemory)(AudioPlayer* player, const AudioDataInMemory* data, OnLoadedCallback onLoaded, void* context, AudioPlayerFlags flags); }; } }
20,840
C
50.080882
111
0.606958
omniverse-code/kit/include/omni/audio/IAudioDeviceEnum.h
// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // //! @file //! @brief Provides an interface that allows the connected audio devices to be enumerated. #pragma once #include <carb/Interface.h> #include <carb/extras/Guid.h> namespace omni { namespace audio { /** The direction to collect device information for. This is passed to most functions in the * IAudioDeviceEnum interface to specify which types of devices are currently interesting. */ enum class Direction { ePlayback, ///< Enumerate audio playback devices only. eCapture, ///< Enumerate audio capture devices only. }; /** Names for the type of sample that an audio device can use. */ enum class SampleType { eUnknown, ///< Could not determine the sample type or an invalid device index was given. ePcmSignedInteger, ///< Signed integer PCM samples. This is usually used for 16-bit an up. ePcmUnsignedInteger, ///< Unsigned integer PCM samples. This is often used for 8-bit samples. ePcmFloat, ///< Single precision floating point PCM samples. eCompressed, ///< A compressed sample format such as ADPCM, MP3, Vorbis, etc. }; /** An interface to provide simple audio device enumeration functionality. This is able to * enumerate all audio devices attached to the system at any given point and collect the * information for each device. This is only intended to collect the device information * needed to display to the user for device selection purposes. If a device is to be * chosen based on certain needs (ie: channel count, frame rate, etc), it should be done * directly through the audio playback or capture context during creation. This is able * to collect information for both playback and capture devices. * * Note that audio devices in the system are generally volatile - they can be added or * removed at any time with no control from this interface. Because of this, it is * highly suggested that device information not be cached, but instead queried each time * it needs to be refreshed. * * Currently this interface does not expose a device change notifier. This is only * available from the `carb::audio::IAudioDevice` interface for the moment. A future * version of this interface may expose an event stream for device change notifications. * The caller may then use those notifications to decide when to refresh the cached * device information in the UI for example. */ struct IAudioDeviceEnum { CARB_PLUGIN_INTERFACE("omni::audio::IAudioDeviceEnum", 0, 1); /** Retrieves the total number of devices attached to the system of a requested type. * * @param[in] dir The audio direction to get the device count for. * @returns The total number of connected audio devices of the requested type. * @returns 0 if no audio devices are connected to the system. */ size_t(CARB_ABI* getDeviceCount)(Direction dir); /** Retrieves a descriptive string for a requested audio device. * * @param[in] dir The audio direction to get the description string for. * @param[in] index The index of the device to retrieve the description for. This * should be between 0 and one less than the most recent return * value of getDeviceCount(). * @param[out] desc Receives the description string for the requested device if * it is still present in the system and its information can be * retrieved. This may not be nullptr. * @param[in] maxLength The maximum number of characters including the null terminator * that can be stored in the output buffer. * @returns `true` if the device description was successfully created. * @returns `false` if the device index was out of range. * * @remarks This retrieves a descriptive string for the requested device. This string is * suitable for display to a user in a menu or selection list. */ bool(CARB_ABI* getDeviceDescription)(Direction dir, size_t index, char* desc, size_t maxLength); /** Retrieves the friendly name of a requested device. * * @param[in] dir The audio direction to get the device name for. * @param[in] index The index of the device to retrieve the name for. This * should be between 0 and one less than the most recent return * value of getDeviceCount(). * @param[out] name Receives the name of the requested device if it could be * retrieved. This may not be nullptr. * @param[in] maxLength The maximum number of characters including the null terminator * that can be stored in the output buffer. * @returns `true` if the device name was successfully retrieved. * @returns `false` if the device index was out of range. */ bool(CARB_ABI* getDeviceName)(Direction dir, size_t index, char* name, size_t maxLength); /** Retrieves the GUID of a requested device. * * @param[in] dir The audio direction to get the device GUID for. * @param[in] index The index of the device to retrieve the GUID for. This * should be between 0 and one less than the most recent return * value of getDeviceCount(). * @param[out] guid Receives the GUID of the requested device if it could be * retrieved. This may not be nullptr. * @returns `true` if the device GUID was successfully retrieved. * @returns `false` if the device index was out of range. */ bool(CARB_ABI* getDeviceGuid)(Direction dir, size_t index, carb::extras::Guid* guid); /** Retrieves the unique identifier for the requested device. * * @param[in] dir The audio direction to get the device name for. * @param[in] index The index of the device to retrieve the identifier for. This * should be between 0 and one less than the most recent return * value of getDeviceCount(). * @param[out] id Receives the identifier of the requested device if it could be * retrieved. This may not be nullptr. * @param[in] maxLength The maximum number of characters including the null terminator * that can be stored in the output buffer. * @returns `true` if the device identifier was successfully retrieved. * @returns `false` if the device index was out of range. */ bool(CARB_ABI* getDeviceId)(Direction dir, size_t index, char* id, size_t maxLength); /** Retrieves the closest matching device index from an identifier. * * @param[in] dir The audio direction to get the device index for. * @param[in] id The identifier of the device to match to the current device list. * @returns The index of the device that matches the given identifier if an exact match * was found. Note that the match may have been made either by the device's * friendly name or by its unique identifier. This should be an identifier * returned from a previous call to getDeviceId() or getDeviceName(). Note * that this identifier may be stored persistently to attempt access to the * same device in a future launch. * @returns 0 if no matching device was found and the system's default device was * chosen instead. * * @remarks This checks the current system device list to find a device that matches * the given identifier. The device identifiers returned from getDeviceId() * contain both the device's friendly name and its unique identifier code. * Matches will first check the unique identifier. If no match is found, * it will compare against the friendly name. If the unique identifier portion * is not present, a match by the friendly name will be attempted instead. Note * that the device's friendly name may not necessarily be unique, even among * different removeable devices. For example, multiple USB headsets may have * their output sides appear to the system as just simply "Speakers". If a * persistent storage of the device identifier is needed, the name returned * from getDeviceId() should be preferred over that of getDeviceName(). */ size_t(CARB_ABI* getDeviceIndexFromId)(Direction dir, const char* id); /** Retrieves the preferred frame rate of a requested device. * * @param[in] dir The audio direction to get the preferred frame rate for. * @param[in] index The index of the device to retrieve the frame rate for. This * should be between 0 and one less than the most recent return * value of getDeviceCount(). * @returns The preferred frame rate of the requested device if it could be retrieved. * @returns 0 if the device index was out of range. * * @remarks This retrieves the preferred frame rate of a requested device. The preferred * frame rate is the rate at which the device natively wants to process audio data. * Using the device at other frame rates may be possible but would require extra * processing time. Using a device at a different frame rate than its preferred * one may also result in degraded quality depending on what the processing versus * preferred frame rate is. * * @note This function will open the audio device to test on some systems. * The caller should ensure that isDirectHardwareBackend() returns * false before calling this. * Calling this on a 'direct hardware' backend could result in this call * taking a substantial amount of time (e.g. 100ms) or failing unexpectedly. */ size_t(CARB_ABI* getDeviceFrameRate)(Direction dir, size_t index); /** Retrieves the maximum channel count for a requested device. * * @param[in] dir The audio direction to get the maximum channel count for. * @param[in] index The index of the device to retrieve the channel count for. * This should be between 0 and one less than the most recent * return value of getDeviceCount(). * @returns The maximum channel count of the requested device if it could be retrieved. * @returns 0 if the device index was out of range. * * @remarks This retrieves the maximum channel count for a requested device. This count * is the maximum number of channels that the device can natively handle without * having to trim or reprocess the data. Using a device with a different channel * count than its maximum is allowed but will result in extra processing time to * upmix or downmix channels in the stream. Note that downmixing channel counts * (ie: 7.1 to stereo) will often result in multiple channels being blended * together and can result in an unexpected final signal in certain cases. * * @note This function will open the audio device to test on some systems. * The caller should ensure that isDirectHardwareBackend() returns * false before calling this. * Calling this on a 'direct hardware' backend could result in this call * taking a substantial amount of time (e.g. 100ms) or failing unexpectedly. */ size_t(CARB_ABI* getDeviceChannelCount)(Direction dir, size_t index); /** Retrieves the native sample size for a requested device. * * @param[in] dir The audio direction to get the native sample size for. * @param[in] index The index of the device to retrieve the sample size for. * This should be between 0 and one less than the most recent * return value of getDeviceCount(). * @returns The native sample size in bits per sample of the requested device if it * could be retrieved. * @returns 0 if the device index was out of range. * * @remarks This retrieves the bits per sample that a requested device prefers to process * its data at. It may be possible to use the device at a different sample size, * but that would likely result in extra processing time. Using a device at a * different sample rate than its native could degrade the quality of the final * signal. * * @note This function will open the audio device to test on some systems. * The caller should ensure that isDirectHardwareBackend() returns * false before calling this. * Calling this on a 'direct hardware' backend could result in this call * taking a substantial amount of time (e.g. 100ms) or failing unexpectedly. */ size_t(CARB_ABI* getDeviceSampleSize)(Direction dir, size_t index); /** Retrieves the native sample data type for a requested device. * * @param[in] dir The audio direction to get the native sample data type for. * @param[in] index The index of the device to retrieve the sample data type for. * This should be between 0 and one less than the most recent * return value of getDeviceCount(). * @returns The native sample data type of the requested device if it could be retrieved. * @returns @ref SampleType::eUnknown if the device index was out of range. * * @remarks This retrieves the sample data type that a requested device prefers to process * its data in. It may be possible to use the device with a different data type, * but that would likely result in extra processing time. Using a device with a * different sample data type than its native could degrade the quality of the * final signal. * * @note This function will open the audio device to test on some systems. * The caller should ensure that isDirectHardwareBackend() returns * false before calling this. * Calling this on a 'direct hardware' backend could result in this call * taking a substantial amount of time (e.g. 100ms) or failing unexpectedly. */ SampleType(CARB_ABI* getDeviceSampleType)(Direction dir, size_t index); /** Check if the audio device backend uses direct hardware access. * @returns `true` if this backend has direct hardware access. * This will be returned when ALSA is in use. * @returns `false` if the backend is an audio mixing server. * This will be returned when Pulse Audio or Window Audio Services * are in use. * * @remarks A direct hardware audio backend is capable of exclusively locking * audio devices, so devices are not guaranteed to open successfully * and opening devices to test their format may be disruptive to the system. * * @remarks ALSA is the only 'direct hardware' backend that's currently supported. * Some devices under ALSA will exclusively lock the audio device; * these may fail to open because they're busy. * Additionally, some devices under ALSA can fail to open because * they're misconfigured (Ubuntu's default ALSA configuration can * contain misconfigured devices). * In addition to this, opening some devices under ALSA can take * a substantial amount of time (over 100ms). * For these reasons, it is important to verify that you are not * using a 'direct hardware' backend if you are going to call certain * functions in this interface. */ bool(CARB_ABI* isDirectHardwareBackend)(); }; } }
16,850
C
58.126316
100
0.651751
omniverse-code/kit/include/omni/audio/AudioSettings.h
// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include <omni/kit/SettingsUtils.h> /** audio setting group names. These provide the starting path to all of the common * audio settings. * @{ */ /** the group name for all playback audio settings in Kit. */ #define AUDIO_SETTING_GROUP_CONTEXT "/audio/context" /** @} */ /** setting leaf names. These must be prefixed by @ref AUDIO_SETTING_GROUP_CONTEXT * to be valid for a settings lookup. * @{ */ #define AUDIO_SETTING_NAME_MAXBUSES "maxBuses" #define AUDIO_SETTING_NAME_SPEAKERMODE "speakerMode" #define AUDIO_SETTING_NAME_STREAMERFILE "streamerFile" #define AUDIO_SETTING_NAME_ENABLESTREAMER "enableStreamer" #define AUDIO_SETTING_NAME_DEVICENAME "deviceName" #define AUDIO_SETTING_NAME_CAPTUREDEVICENAME "captureDeviceName" #define AUDIO_SETTING_NAME_AUTOSTREAM "autoStreamThreshold" #define AUDIO_SETTING_NAME_AUDIO_PLAYER_AUTOSTREAM "audioPlayerAutoStreamThreshold" #define AUDIO_SETTING_NAME_CLOSEONSOUNDSTOP "closeAudioPlayerOnStop" #define AUDIO_SETTING_NAME_MASTERVOLUME "masterVolume" #define AUDIO_SETTING_NAME_USDVOLUME "usdVolume" #define AUDIO_SETTING_NAME_SPATIALVOLUME "spatialVolume" #define AUDIO_SETTING_NAME_NONSPATIALVOLUME "nonSpatialVolume" #define AUDIO_SETTING_NAME_UIVOLUME "uiVolume" /** @} */ /********************************** Audio Settings Paths *****************************************/ namespace omni { namespace audio { /** full path suffixes for the Kit audio settings. For the app preferences settings values * that should persist between launches of Kit, these names should each be prefixed with * @ref PERSISTENT_SETTINGS_PREFIX. If a value should not persist but instead be reset * between launches, it should not have a prefix. * * Each of these settings paths should be created by concatenating an optional persistence * prefix, one AUDIO_SETTING_GROUP_* name, a group separator (ie: @ref SETTING_SEP), and one * AUDIO_SETTING_NAME_* value name. * * @{ */ /** the number of buses to create the main audio playback context with. This will control * the maximum number of simultaneous voices that can be heard during playback. Any playing * voices beyond this count will be 'virtual' and will only be heard when another voice * releases its bus. This defaults to 0 which lets the context decide on creation. */ constexpr const char* const kSettingMaxBuses = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_MAXBUSES; /** the standard speaker layout to use for playback. This defaults to the speaker mode that * most closely corresponds to the device's preferred channel count. */ constexpr const char* const kSettingSpeakerMode = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_SPEAKERMODE; /** the name of the file to stream output to. This will be written as a RIFF wave file in * the same data format that the playback context chooses. The file will not be created * unless audio (even silent audio) is written to it. The file will also only be created * if the @ref AUDIO_SETTING_NAME_ENABLESTREAMER setting is also enabled. This defaults * to an empty string. */ constexpr const char* const kSettingStreamerFile = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_STREAMERFILE; /** boolean option to control whether the streamer is used or not for the current session. * Note that this setting is intentionally not persistent. This should always be disabled * on launch. If it were persistent, it would lead to all audio being recorded even when * not intended, and potentially filling up the local drive. */ constexpr const char* const kSettingEnableStreamer = AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_ENABLESTREAMER; /** the identifier of the device that should be used for audio playback. This name can be * retrieved from the omni::audio::IAudioDeviceEnum interface using the getDeviceId() * function. This name may consist of a device GUID, a friendly device name, or a * combination of both. If a GUID is provided, a connected device using that name will * be chosen if found. If a GUID is not provided or no connected device matches the * given GUID, the device will attempt to match by its friendly name. Note that this * friendly name is not necessarily unique in the system and the wrong device may end * up being selected in this case (if multiple devices with the same friendly name * are connected). This defaults to an empty string indicating that the system's default * device should always be used. */ constexpr const char* const kSettingDeviceName = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_DEVICENAME; /** The identifier of the device that should be used for audio capture. * This functions identically to @ref kSettingDeviceName, except that it's used * to specify the capture device instead of the playback device. */ constexpr const char* const kSettingCaptureDeviceName = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_CAPTUREDEVICENAME; /** the current auto-stream threshold setting in kilobytes. This controls when the audio * data system decides to stream an encoded sound versus decode it fully on load. This * threshold represents the decoded size of a sound above which it will be streamed instead * of decoded. If the decoded size of the sound is less than this threshold, it will be * decoded on load instead. */ constexpr const char* const kSettingAutoStream = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_AUTOSTREAM; /** the current auto-stream threshold setting in kilobytes specifically for the audio player. * This controls when the audio data system decides to stream an encoded sound versus decode it fully on load. * This threshold represents the decoded size of a sound above which it will be streamed instead * of decoded. If the decoded size of the sound is less than this threshold, it will be * decoded on load instead. Note that this setting is only for the audio player. Use @ref kSettingAutoStream * for the Audio Manager's auto stream threshold. */ constexpr const char* const kSettingAudioPlayerAutoStream = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_AUDIO_PLAYER_AUTOSTREAM; /** The option to close the audio player window when the sound is stopped. * If this is enabled, then the audio player will be automatically closed when the user clicks * the stop button or when the sound reaches its natural end. */ constexpr const char* const kSettingCloseOnSoundStop = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_CLOSEONSOUNDSTOP; /** the master volume level setting to use. This master volume affects all audio output * from the USD stage audio manager, UI audio manager, and the audio player interfaces. * This level should be set to 1.0 for full volume and 0.0 for silence. The volume scale * is approximately linear. This defaults to 1.0. */ constexpr const char* const kSettingMasterVolume = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_MASTERVOLUME; /** the master volume for the USD stage audio manager to use. This does not affect the * UI audio manager or the audio player interfaces. This level should be set to 1.0 for * full volume and 0.0 for silence. The volume scale is approximately linear. This * defaults to 1.0. */ constexpr const char* const kSettingUsdVolume = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_USDVOLUME; /** the relative volume level for spatial audio sounds in the USD stage audio manager. This * volume level will effectively be multiplied by the master volume and USD volume levels * above to get the final effective volume level for spatial sounds. This level should be * set to 1.0 for full volume and 0.0 for silence. The volume scale is approximately linear. * This defaults to 1.0. */ constexpr const char* const kSettingSpatialVolume = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_SPATIALVOLUME; /** the relative volume level for non-spatial audio sounds in the USD stage audio manager. This * volume level will effectively be multiplied by the master volume and USD volume levels above * to get the final effective volume level for non-spatial sounds. This level should be set to * 1.0 for full volume and 0.0 for silence. The volume scale is approximately linear. This * defaults to 1.0. */ constexpr const char* const kSettingNonSpatialVolume = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_NONSPATIALVOLUME; /** the master volume level for the UI audio manager. This level should be set to 1.0 for full * volume, and 0.0 for silence. The volume scale is approximately linear. This defaults to * 1.0. */ constexpr const char* const kSettingUiVolume = PERSISTENT_SETTINGS_PREFIX AUDIO_SETTING_GROUP_CONTEXT SETTING_SEP AUDIO_SETTING_NAME_UIVOLUME; /** @} */ } }
9,705
C
52.32967
114
0.766306
omniverse-code/kit/include/omni/audio/IUiAudio.h
// Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include <carb/Interface.h> namespace omni { namespace audio { /** public container for a loaded editor UI sound. These objects are returned from * @ref IUiAudio::createSound(). These objects can be copied as needed. Once destroyed, * the sound itself will only be destroyed if the no other objects refer to it as well. */ class UiSound { public: UiSound() = default; UiSound(const UiSound&) = default; virtual ~UiSound() = default; virtual UiSound& operator=(const UiSound&) = 0; }; /** simple interface to manage editor UI sound objects. This allows new sound objects to be * created (and loaded) from local disk, sounds to be played, stopped, and queried. */ struct IUiAudio { CARB_PLUGIN_INTERFACE("omni::audio::IUiAudio", 0, 1); /** Loads an editor UI sound from local disk. * * @param[in] filename the path to the sound file to load. This should be an absolute * path, but can be a relative path that will be resolved using the * current working directory for the process. This may not be * nullptr. Parts of this path may include some special path * specifiers that will be resolved when trying to open the file. * See the remarks section below for more info. This may not be * nullptr or an empty string. * @return the sound object representing the new loaded sound. This sound can be passed to * playSound() later. Each sound object returned here must be destroyed by * deleting it when it is no longer needed. Note that destroying the sound object * will stop all playing instances of it. However, if more than one reference to * the same sound object still exists, deleting one of the sound objects will not * stop any of the instances from playing. It is best practice to always explicitly * stop a sound before destroying it. * @return nullptr if the file could not be loaded could not be loaded. * * @remarks This loads a sound that can be played with playSound() at a later time. This * sound only needs to be loaded once but can be played as many times as needed. * When no longer needed, the sound should be destroyed by deleting it. * * @remarks File names passed in here may contain special path markers. * * @note This operation is always thread safe. */ UiSound*(CARB_ABI* createSound)(const char* filename); /** Immediately plays the requested UI sound if it is loaded. * * @param[in] sound the name of the UI sound to be played. This may not be nullptr. * @return no return value. * * @remarks This plays a single non-looping instance of a UI sound immediately. The UI sound * must have already been loaded. If the sound resource was missing or couldn't be * loaded, this call will simply be ignored. This will return immediately after * scheduling the sound to play. It will never block for the duration of the sound's * playback. This sound may be prematurely stopped with stopSound(). * * @note This operation is always thread safe. */ void(CARB_ABI* playSound)(UiSound* soundToPlay); /** Queries whether a sound object is currently playing. * * @param[in] sound the sound object to query the playing state for. This may not be * nullptr. * @return true if the sound object is currently playing. * @return false if the sound has either finished playing or has not been played yet. * * @remarks This queries whether a sound is currently playing. If this fails, that may mean * that the sound ended naturally on its own or it was explicitly stopped. Note * that this may continue to return true for a short period after a sound has been * stopped with stopSound() or stopAllSounds(). This period may be up to 10 * milliseconds. */ bool(CARB_ABI* isSoundPlaying)(const UiSound* sound); /** Immediately stops the playback of a sound. * * @param[in] sound the sound object to stop playback for. This may not be nullptr. * @return no return value. * * @remarks This stops the playback of an active sound. If the sound was not playing or had * already naturally stopped on its own, this call is ignored. */ void(CARB_ABI* stopSound)(UiSound* sound); /** Retrieves length of a sound in seconds (if known). * * @param[in] sound the sound to retrieve the length for. This may not be nullptr. * @return the play length of the sound in seconds if the asset is loaded and the length * can be calculated. * @return 0.0 if the sound asset is not available yet or the length could not be properly * calculated. * * @remarks This calculates the length of a UI sound in seconds. This is just the length * of the sound asset in seconds. */ double(CARB_ABI* getSoundLength)(UiSound* sound); }; } }
5,794
C
46.113821
99
0.648602
omniverse-code/kit/include/omni/audio/IAudioRecorder.h
// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include <carb/Interface.h> #include <carb/audio/IAudioCapture.h> namespace omni { namespace audio { /** The audio recorder instance. * This is created to reserve a device that can record audio. */ struct AudioRecorder; /** A callback to read data from the audio device. * @param[in] data The audio data that was recorded. * @param[in] frames The number of frames of audio that are available in @p data. * @param[inout] context A user-defined context that gets passed through to the callback. */ using ReadCallback = void (*)(const void* data, size_t frames, void* context); /** The descriptor used to create a recording session. */ struct AudioRecordDesc { /** Flags for future expansion. * This must be set to 0. */ uint32_t flags = 0; /** The filename to write the output audio to. * This can be nullptr to use @p callback to receive audio instead. */ const char* filename = nullptr; /** The read callback to receive data with. * This will be called periodically when data is available. * This can be nullptr if @ref filename is non-null. * If this is set to non-null and @ref filename is non-null, this callback * will be called after the data has been written to the file (the data may * not have been flushed at this point though). * Note that if this callback takes too long, it can cause a recording overrun. * This callback occurs asynchronously under the recursive mutex of the * @ref AudioRecorder; if a lock is acquired in @ref callback, it is * important to ensure this does not result in the two locks being * acquired in different orders, which could potentially cause deadlock. */ ReadCallback callback = nullptr; /** A parameter that gets passed into the callback. * This is ignored if @ref callback is nullptr. */ void* callbackContext = nullptr; /** The frame rate to capture audio at. * This may be set to 0 to use the default rate for the device. * You can query the device's rate with IAudioRecorder::getDeviceCaps(). * If this is not a frame rate supported by the device, a resampler will be * introduced, which adds a small performance cost. */ size_t frameRate = 0; /** The number of channels that the audio is being captured at. * This may be set to 0 to use the default channel count for the device. * You can query the device's channel count with IAudioRecorder::getDeviceCaps(). * If this is different than the device's channel count an up/downmixing * operation may have to be introduced, which add a small performance cost. * The channel mixing matrices chosen are chosen based on the set of * default speaker modes used by carb.audio for a given channel count; * see carb::audio::getSpeakerModeForCount() for this list of defaults. */ size_t channels = 0; /** The format that data will be produced by the capture device. * This may be @ref carb::audio::SampleFormat::eDefault to use the device's * preferred format. * You can query the device's rate with IAudioRecorder::getDeviceCaps(). * This must be set to a PCM format if @ref callback is non-null. * If this is not a format supported by the device, a format conversion * will be introduced which adds a very small performance cost. */ carb::audio::SampleFormat sampleFormat = carb::audio::SampleFormat::eDefault; /** The format that gets written to the file. * This is only used if @ref filename is non-null. * This can be any valid sample format. * If this is set to @ref carb::audio::SampleFormat::eDefault, @ref sampleFormat * is used. */ carb::audio::SampleFormat outputFormat = carb::audio::SampleFormat::eDefault; /** The length of the recording buffer. * This setting, combined with @ref period will allow you to choose the * recording latency, as well as the tolerance for variance in recording * latency. * It is important to set this to a large enough value that fluctuation * in system timing can be handled without the audio buffer filling up. * The length can be set to 0 to use the device's default buffer length. */ size_t bufferLength = 0; /** The time between read callbacks. * This value can be used to reduce latency without reducing the ability to * handle fluctuations in timing; for example, setting @ref bufferLength to * 64ms and setting @ref period to 8ms will result in roughly 8ms latency * but the ability to tolerate up to 56ms of lag. * The default value is @ref bufferLength / 2. * This will be clamped to the default period if it exceeds the default period. * Two callbacks may be sent for a given period to handle the end of the * ring buffer. * This may send more data than expected for a given period if the system's * timing fluctuates. */ size_t period = 0; /** Describes how @ref bufferLength and @ref period should be interpreted. * This value is ignored if @ref bufferLength and @ref period are 0. Note * that the buffer size will always be rounded up to the next frame * boundary even if the size is specified in bytes. */ carb::audio::UnitType lengthType = carb::audio::UnitType::eFrames; }; /** Simple interface to be able to record audio. */ struct IAudioRecorder { CARB_PLUGIN_INTERFACE("omni::audio::IAudioRecorder", 0, 1); /** Create an audio recorder instance. * @returns A new audio recorder if creation succeeded. * This must be passed to destroyAudioRecorder() when you are * finished with the instance. * @returns nullptr if creation failed. * * @remarks This creates an audio system that can record audio to a file or to a callback. * * @note Each call to createAudioRecorder() opens a connection to the audio * recording device set in the preferences (@ref kSettingCaptureDeviceName). * It is not recommended to open a large number of these connections. */ AudioRecorder*(CARB_ABI* createAudioRecorder)(); /** Destroy an audio recorder instance. * @param[inout] recorder The recorder to destroy. * * @remarks This function frees the memory allocated to the @ref AudioRecorder. * This will stop the recorder if it was recoding audio when this is called. */ void(CARB_ABI* destroyAudioRecorder)(AudioRecorder* recorder); /** Being recording audio. * @param[inout] recorder The audio recorder to begin recording with. * This should not be nullptr. * @param[in] desc The descriptor for how audio should be recorded. * This should not be nullptr. * * @returns true If recording has started. * @returns false if @p recorder or @p desc are nullptr. * @returns false if another error occurred. */ bool(CARB_ABI* beginRecording)(AudioRecorder* recorder, const AudioRecordDesc* desc); /** Stop recording audio. * @param[inout] recorder The audio recorder to stop recording on. * This should not be nullptr. * @param[in] flush Set this to true to flush the rest of the data * that is currently in the capture device's buffer. * Set this to false to discard any remaining queued * data. * * @remarks This should be called when beginRecording() has been previously * called and you want to stop recording. */ void(CARB_ABI* stopRecording)(AudioRecorder* recorder, bool flush); /** Retrieves the sound format for the recorder. * @param[in] recorder The recorder to retrieve the device information for. * This should not be nullptr. * @param[out] format Receives the format. * This should not be nullptr. * If beginRecording() was called, this will return * the current format that is being used for recording. * If beginRecording() has not been called yet, this * will return the default format specified by the device. * @returns true if the device info was successfully retrieved. * @returns false if either parameter was nullptr. * @returns false if the call fails for any other reason. */ bool(CARB_ABI* getFormat)(AudioRecorder* recorder, carb::audio::SoundFormat* format); }; } }
9,209
C
44.594059
95
0.664676
omniverse-code/kit/include/omni/audio/experimental/IAudioCapture.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 /** An individual audio capture stream. */ template <> class omni::core::Generated<omni::audio::experimental::ICaptureStream_abi> : public omni::audio::experimental::ICaptureStream_abi { public: OMNI_PLUGIN_INTERFACE("omni::audio::experimental::ICaptureStream") /** Starts capturing audio data from the stream. * * @param[in] flags Flags to alter the recording behavior. * * @returns @ref carb::audio::AudioResult::eOk if the capture is successfully started. * @returns An @ref AudioResult error code if the stream could not be started. * * @remarks Audio streams are in a stopped state when they're created. * You must call start() to start recording audio. * * @remarks Without @ref fCaptureStreamStartFlagOneShot, the stream will * perform looping capture. This means that once the ring buffer * has been filled, audio will start being recorded from the start * of the buffer again. * * @remarks Looping audio will not overwrite unread parts of the ring buffer. * Only parts of the buffer that have been unlocked can be overwritten * by the audio system. * Data written into the ring buffer must be unlocked periodically * when using looping capture or the ring buffer will fill up and * the device will overrun. * * @thread_safety Calls to this function cannot occur concurrently with * other calls to @ref ICaptureStream_abi::start_abi() or @ref ICaptureStream_abi::stop_abi(). */ omni::audio::experimental::AudioResult start(omni::audio::experimental::CaptureStreamStartFlags flags) noexcept; /** Stop capturing audio data from the stream. * * @param[in] flags Flags to alter the stopping behavior. * * @returns @ref carb::audio::AudioResult::eOk if the capture was successfully stopped. * @returns @ref carb::audio::AudioResult::eNotAllowed if the stream was already stopped. * @returns An @ref AudioResult error code if something else went wrong. * The stream is likely broken in this case. * * @remarks This will stop capturing audio. Any audio data that would have * been captured between this point and the next call to @ref ICaptureStream_abi::start_abi() * will be lost. * * @remarks If there is unread data in the buffer, that data can still be * read with lock() after the stream is stopped. * * @note If fCaptureStreamStopFlagSync was not specified, the stop call will not sync with the * device so you could still receive callbacks after. * * @note CC-1180: You cannot use fCaptureStreamStopFlagSync from a callback. * * @thread_safety Calls to this function cannot occur concurrently with * other calls to @ref ICaptureStream_abi::start_abi() or @ref ICaptureStream_abi::stop_abi(). */ omni::audio::experimental::AudioResult stop(omni::audio::experimental::CaptureStreamStopFlags flags) noexcept; /** Check if the stream is still capturing data. * @returns `true` if the stream is still capturing. * @returns `false` if the stream is stopped. * Callbacks will no longer be sent if `false` was returned unless the strema was * stoped with @ref ICaptureStream_abi::stop_abi() was called without fCaptureStreamStopFlagSync. */ bool isCapturing() noexcept; /** Get the available number of frames to be read. * * @param[out] available The number of frames that can be read from the buffer. * * @returns @ref carb::audio::AudioResult::eOk if the frame count was retrieved successfully. * @returns @ref carb::audio::AudioResult::eOverrun if data has not been read fast enough and * the buffer filled up. * @returns @ref carb::audio::AudioResult::eNotAllowed if callback recording is being used. * @returns An @ref AudioResult error code if the operation fails for any other reason. * * @remarks This will check how much data is available to be read from the buffer. * This call is only valid when polling style recording is in use. */ omni::audio::experimental::AudioResult getAvailableFrames(size_t* available) noexcept; /** Lock the next chunk of the buffer to be read. * * @param[in] request The length of the buffer to lock, in frames. * This may be 0 to lock as much data as possible. * This does not need to be a multiple of the fragment * length. * If you need to convert bytes to frames, you can use * @ref carb::audio::convertUnits() or * @ref carb::audio::framesToBytes() (note that this is * slow due to requiring a division). * @param[out] region Receives the audio data. * This can be `nullptr` to query the available data * in the buffer, rather than locking it. * This buffer can be held until unlock() is called; * after unlock is called, the stream can start writing * into this buffer. * @param[out] received The length of data available in @p buffer, in frames. * This will not exceed @p request. * Due to the fact that a ring buffer is used, you may * have more data in the buffer than is returned in one * call; a second call would be needed to read the full * buffer. * If you need to convert this to bytes, you can use * @ref carb::audio::convertUnits() or * @ref carb::audio::framesToBytes(). * * @returns @ref carb::audio::AudioResult::eOk if the requested region is successfully locked. * @returns @ref carb::audio::AudioResult::eOutOfMemory if there is no audio data available * in the buffer yet. * @returns @ref carb::audio::AudioResult::eNotAllowed if a region is already locked * and needs to be unlocked. * @returns @ref carb::audio::AudioResult::eNotAllowed if the stream is using callback * style recording. * @returns @ref carb::audio::AudioResult::eOverrun if data has not been read fast * enough and the underlying device has overrun. * This will happen on some audio systems (e.g. ALSA) if the * capture buffer fills up. * This can also happen on some audio systems sporadically if the * device's timing characteristics are too aggressive. * @returns an carb::audio::AudioResult::e* error code if the region could not be locked. * * @remarks This is used to get data from the capture stream when polling * style recording is being used (ie: there is no data callback). * When using this style of recording, portions of the buffer must * be periodically locked and unlocked. * * @remarks This retrieves the next portion of the buffer. * This portion of the buffer is considered to be locked until * @ref ICaptureStream_abi::unlock_abi() is called. * Only one region of the buffer can be locked at a time. * When using a looping capture, the caller should ensure that data * is unlocked before the buffer fills up or overruns may occur. */ omni::audio::experimental::AudioResult lock(size_t request, const void** region, size_t* received) noexcept; /** Unlocks a previously locked region of the buffer. * * @param[in] consumed The number of frames in the previous buffer that were consumed. * Any frames that were not consumed will be returned in future * @ref ICaptureStream_abi::lock_abi() calls. * 0 is valid here if you want to have the same locked region * returned on the next lock() call. * * @returns @ref carb::audio::AudioResult::eOk if the region is successfully unlocked. * @returns @ref carb::audio::AudioResult::eOutOfRange if @p consumed was larger than * the locked region. * @returns @ref carb::audio::AudioResult::eNotAllowed if no region is currently locked. * @returns an carb::audio::AudioResult::e* error code if the region could not be unlocked. * * @remarks This unlocks a region of the buffer that was locked with a * previous call to ICaptureStream_abi::lock_abi(). * Now that this region is unlocked, the device can start writing to it, * so the caller should no longer access that region. * Once the buffer is unlocked, a new region may be locked with ICaptureStream_abi::lock_abi(). * * @note If the locked region is not fully unlocked, the part of the region that * was not unlocked will be returned on the next call to ICaptureStream_abi::lock_abi(). * A second call to unlock cannot be made in this situation, it will fail. */ omni::audio::experimental::AudioResult unlock(size_t consumed) noexcept; /** Retrieve the size of the capture buffer. * * @returns The size of the capture buffer, in frames. * You can use @ref ICaptureStream_abi::getSoundFormat_abi() and @ref carb::audio::convertUnits() * to convert to bytes or other units. * * @remarks If your code is dependent on the buffer's actual size, it is * better to retrieve it with this function since the buffer size * used with device creation can be adjusted. */ size_t getBufferSize() noexcept; /** Retrieve the number of fragments used in this stream. * * @returns The number of buffer fragments. * This is the number of regions the recording buffer is divided * into. */ size_t getFragmentCount() noexcept; /** Retrieve the format of the audio being captured. * * @param[out] format The format of the audio being captured. * This may not be `nullptr`. */ void getSoundFormat(omni::audio::experimental::SoundFormat* format) noexcept; /** Clear any data that is currently in the recording buffer. * * @returns @ref carb::audio::AudioResult::eOk if the buffer was successfully cleared. * @returns an carb::audio::AudioResult::e* error code if the buffer could not be cleared. * * @remarks This is a quick way to get rid of any data that is left in the * buffer. * This will also reset the write position on the buffer back to * 0, so the next lock call will return the start of the buffer * (this can be useful if you want to do a one shot capture of the * entire buffer). * * @note If this is called while the capture stream is recording, the stream * will be paused before it is reset. */ omni::audio::experimental::AudioResult reset() noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline omni::audio::experimental::AudioResult omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::start( omni::audio::experimental::CaptureStreamStartFlags flags) noexcept { return start_abi(flags); } inline omni::audio::experimental::AudioResult omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::stop( omni::audio::experimental::CaptureStreamStopFlags flags) noexcept { return stop_abi(flags); } inline bool omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::isCapturing() noexcept { return isCapturing_abi(); } inline omni::audio::experimental::AudioResult omni::core::Generated< omni::audio::experimental::ICaptureStream_abi>::getAvailableFrames(size_t* available) noexcept { return getAvailableFrames_abi(available); } inline omni::audio::experimental::AudioResult omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::lock( size_t request, const void** region, size_t* received) noexcept { return lock_abi(request, region, received); } inline omni::audio::experimental::AudioResult omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::unlock( size_t consumed) noexcept { return unlock_abi(consumed); } inline size_t omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::getBufferSize() noexcept { return getBufferSize_abi(); } inline size_t omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::getFragmentCount() noexcept { return getFragmentCount_abi(); } inline void omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::getSoundFormat( omni::audio::experimental::SoundFormat* format) noexcept { getSoundFormat_abi(format); } inline omni::audio::experimental::AudioResult omni::core::Generated<omni::audio::experimental::ICaptureStream_abi>::reset() noexcept { return reset_abi(); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL static_assert(std::is_standard_layout<omni::audio::experimental::Format>::value, "omni::audio::experimental::Format must be standard layout to be used in ONI ABI"); static_assert(std::is_standard_layout<omni::audio::experimental::CaptureDeviceDesc>::value, "omni::audio::experimental::CaptureDeviceDesc must be standard layout to be used in ONI ABI"); static_assert(std::is_standard_layout<omni::audio::experimental::CaptureInfoData>::value, "omni::audio::experimental::CaptureInfoData must be standard layout to be used in ONI ABI"); static_assert(std::is_standard_layout<omni::audio::experimental::CaptureStreamDesc>::value, "omni::audio::experimental::CaptureStreamDesc must be standard layout to be used in ONI ABI");
15,201
C
48.197411
132
0.649299
omniverse-code/kit/include/omni/audio/experimental/IAudioCapture.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 An updated audio capture interface. */ #pragma once #include <omni/core/BuiltIn.h> #include <omni/core/IObject.h> #include <omni/core/Api.h> #include <omni/log/ILog.h> #include <carb/audio/AudioTypes.h> namespace omni { /** Omniverse audio project. */ namespace audio { /** The omni::audio namespace is part of an audio refresh that is still in the experimental stages. * This currently only contains the IAudioCapture interface, which was created to address a number * of defects in carb::audio::IAudioCapture. * IAudioCapture is currently in beta stage; the interface is complete and unlikely to change * substantially but it has not been tested heavily in a real-world use case yet. * The ABI of IAudioCapture and ICaptureStream are stable and will not be broken without a * deprecation warning given in advance. */ namespace experimental { /******************************** renamed carb::audio types **************************************/ /** @copydoc carb::audio::AudioResult */ using AudioResult = carb::audio::AudioResult; /** @copydoc carb::audio::SpeakerMode */ using SpeakerMode = carb::audio::SpeakerMode; /** @copydoc carb::audio::SampleFormat */ using SampleFormat = carb::audio::SampleFormat; /** @copydoc carb::audio::SoundFormat */ using SoundFormat = carb::audio::SoundFormat; /******************************** typedefs, enums, & macros **************************************/ /** The minimal format needed to interpret an PCM audio stream. * Non-PCM (compressed) audio streams may need different format information or * no format information to interpret. */ struct Format { /** The rate at which this audio stream is intended to be played (number of * audio frames per second). * A frame is a group of @ref channels audio samples taken at a given time point; * this is often referred to as the 'sample rate'. */ size_t frameRate = 0; /** The number of channels in the audio stream. */ size_t channels = 0; /** This specifies the intended usage of each channel in the audio stream. * This will be a combination of one or more of the @ref carb::audio::Speaker names or * a @ref carb::audio::SpeakerMode name. */ SpeakerMode channelMask = carb::audio::kSpeakerModeDefault; /** The data type of each audio sample in this audio stream. */ SampleFormat format = SampleFormat::eDefault; }; /** Flags to indicate some additional behaviour of the device. * No flags are currently defined. */ using CaptureDeviceFlags = uint32_t; /** The parameters to use when opening a capture device. */ struct CaptureDeviceDesc { /** Flags to indicate some additional behaviour of the device. * No flags are currently defined. This should be set to 0. */ CaptureDeviceFlags flags = 0; /** The index of the device to be opened. * Index 0 will always be the system's default capture device. * These indices are the same as the ones used in @ref carb::audio::IAudioDevice, * so that interface should be used to enumerate the system's audio devices. * * This must be less than the return value of the most recent call to @ref * carb::audio::IAudioDevice::getDeviceCount() for capture devices. * Note that since the capture device list can change at any time * asynchronously due to external user action, setting any particular * value here is never guaranteed to be valid. * There is always the possibility the user could remove the device after * its information is collected but before it is opened. * * Additionally, there is always a possibility that a device will fail to * open or the system has no audio capture devices, so code must be able to * handle that possibility. * In particular, it is common to run into misconfigured devices under ALSA; * some distributions automatically configure devices that will not open. */ size_t index = 0; /** The format to use for the capture stream. * Leaving this struct at its default values will cause the audio device's * default format to be used * (This can be queried later with @ref ICaptureStream_abi::getSoundFormat_abi()). * The audio stream will accept any valid PCM format, even if the underlying * device does not support that format. */ Format format = {}; /** The length of the ring buffer to capture data into, in frames. * The buffer length in combination with @ref bufferFragments determines * the minimum possible latency of the audio stream, which the time to * record one fragment of audio. * The buffer length will be automatically adjusted to ensure that its size * is divisible by the fragment count. * * This will not determine the buffer size of the underlying audio device, * but if it is possible, the underlying audio device will be adjusted to * best match this buffer length and fragment combination. * * Setting this to 0 will choose the underlying device's buffer length or * a default value if the underlying device has no buffer. */ size_t bufferLength = 0; /** The number of fragments that the recording buffer is divided into. * When using callback based recording, one fragment of audio will be sent * to each callback. * When using polling based recording, data will become available in one * fragment increments. * One fragment of audio becomes the minimum latency for the audio stream. * Setting an excessive number of fragments will reduce the efficiency of * the audio stream. * * Setting this to 0 will choose the underlying device's fragment count or * a default value if the underlying device doesn't use a ring buffer system. */ size_t bufferFragments = 0; }; class ICaptureStream; /** A callback that's used to receive audio data from an audio capture stream. * @param[inout] stream The stream that this callback was fired from. * @param[in] buffer The audio data that's been captured. * The data in the buffer will be in the format specified * by ICaptureStream::getSoundFormat(). * If the stream was created with @ref fCaptureStreamFlagLowLatency, * this buffer will not be valid once the callback returns; * otherwise, the buffer will be invalidated once ICaptureStream::unlock() * is called for this portion of the buffer. * See the note on unlocking the buffer for more detail on this. * @param[in] frames The length of audio in @p buffer, in frames. * If the stream was created with @ref fCaptureStreamFlagLowLatency, * the frame count passed to each callback may differ; * otherwise, the frame count will be exactly one fragment long. * If you need to convert to bytes, you can use * @ref carb::audio::convertUnits() or * @ref carb::audio::framesToBytes(). * @param[inout] context The user-specified callback data. * * @note If the stream was not created with @ref fCaptureStreamFlagLowLatency, * data returned from this function is considered *locked*. * For data to become unlocked, the caller needs to call * ICaptureStream::unlock() with the number of frames that have been * locked by this call. * If the data is not unlocked, that portion of the buffer cannot be overwritten. * It is not required to release the buffer before the callback ends, but * the data needs to be unlocked eventually otherwise you will stop receiving * data and an overrun may occur. * * @note This callback executes from its own thread, so thread safety will need * to be considered. * This is called on the same thread as CaptureInfoCallback, so these * two calls can access the same data without concurrency issues. * * @note This callback must return as fast as possible, since this is called * directly from the audio capture thread (e.g. under 1ms). * A callback that takes too long could cause capture overruns. * Doing anything that could involve substantial waits (e.g. calling into python) * should be avoided; in those cases you should copy the buffer somewhere else * or use a omni::extras::DataStreamer for a series of asynchronous * data packets. * * @note It is safe to call any @ref ICaptureStream function from within this * callback, but it is not safe to destroy the @ref ICaptureStream object * from within it. */ using CaptureDataCallback = void (*)(ICaptureStream* stream, const void* buffer, size_t frames, void* context); /** The reason that a CaptureInfoCallback was called. */ enum class CaptureInfoType { /** An overrun has occurred. * Overruns occur when data is not captured fast enough from the audio * device, the device's buffer fills up and data is lost. * An overrun can occur because a callback took too long, data was not * unlocked fast enough or the underlying audio device encountered an * overrun for other reasons (e.g. system latency). */ eOverrun, /** The audio device has encountered an unrecoverable issue, such as the * device being unplugged, so capture has stopped. */ eDeviceLost, }; /** Extra data for @ref CaptureInfoCallback. * The union member used is based off of the `type` parameter. */ union CaptureInfoData { /** Data for @ref CaptureInfoType::eOverrun. * Overruns have no additional data. */ struct { } overrun; /** Data for @ref CaptureInfoType::eDeviceLost. * Device lost events have no additional data. */ struct { } deviceLost; /** Size reservation to avoid ABI breaks. */ struct { OMNI_ATTR("no_py") uint8_t x[256]; } reserved; }; /** A callback that's used to signal capture stream events. * @param[inout] stream The stream that this callback was fired from. * @param[in] type What type of event occurred. * @param[in] data Data related to this error. * @param[inout] context The user-specified callback data. * * @remarks This callback is used to signal various events that a capture stream * can encounter. * Overrun events indicate that data from the capture stream has been lost. * The callee should do whatever is appropriate to handle this situation * (e.g. toggle a warning indicator on the UI). * Device lost events indicate that an unrecoverable issue has occurred * with the audio device (such as it being unplugged) and capture cannot * continue. * * @note This callback executes from its own thread, so thread safety will need * to be considered. * This is called on the same thread as @ref CaptureDataCallback, so these * two calls can access the same data without concurrency issues. * * @note Similarly to @ref CaptureDataCallback, this callback should return as * quickly as possible to avoid causing overruns. * After an overrun has occurred, the device will be restarted immediately, * so this callback taking too long could result in another overrun callback * happening immediately after your callback returns. */ using CaptureInfoCallback = void (*)(ICaptureStream* stream, CaptureInfoType type, const CaptureInfoData* data, void* context); /** Flags to indicate some additional behaviour of the stream. */ using CaptureStreamFlags = uint32_t; /** Bypass the stream's capture buffer entirely to minimize audio capture * latency as much as possible. * When this flag is set, audio buffers received from the underlying device * will be passed directly to the capture callback. * * @note In this mode, you are at the mercy of the underlying audio system. * The buffers sent to the callback may vary in size and timing. * The bufferLength and bufferFragments parameters passed to the device * are ignored when using this flag. * Since the buffer size may vary, your callbacks must complete as fast * as possible in case the device sends you very small buffers. * * @note The audio buffer *must* be discarded before the callback returns. * This will also cause @ref ICaptureStream_abi::unlock_abi() to be a noop. * * @note If a format conversion is required, the data will be written to an * intermediate buffer that will be sent to your callback. */ constexpr CaptureStreamFlags fCaptureStreamFlagLowLatency = 0x1; /** The descriptor used to create a new @ref ICaptureStream. */ struct CaptureStreamDesc { /** Flags to indicate some additional behaviour of the stream. */ CaptureStreamFlags flags = 0; /** A callback that can be used to receive captured data. * This can be nullptr if a polling style of capture is desired. * This may not be nullptr if @ref fCaptureStreamFlagLowLatency is specified * in @ref flags. */ CaptureDataCallback dataCallback = nullptr; /** A callback that can be used to receive notifications of when an overrun occurs. * This call be nullptr if these notifications are not needed. * This callback can be used when either polling or callback style recording * are being used. */ CaptureInfoCallback errorCallback = nullptr; /** An opaque context value to be passed to the callback whenever it is performed. * This is passed to @ref dataCallback and @ref errorCallback. */ void* callbackContext = nullptr; /** A descriptor of the capture device to use for this stream. */ CaptureDeviceDesc device; }; /** Flags that alter the behavior of @ref ICaptureStream_abi::start_abi(). */ using CaptureStreamStartFlags = uint32_t; /** This will cause recording to be stopped once the full buffer has been recorded. * This may be useful if you want to capture a fixed length of data without having * to time stopping the device. * After capture has stopped, you can use @ref ICaptureStream_abi::lock_abi() to grab * the whole buffer and just use it directly. */ constexpr CaptureStreamStartFlags fCaptureStreamStartFlagOneShot = 0x1; /** Flags that alter the behavior of @ref ICaptureStream_abi::stop_abi(). */ using CaptureStreamStopFlags = uint32_t; /** If this flag is passed, the call to @ref ICaptureStream_abi::stop_abi() will block * until the capture thread has stopped. * This guarantees that no more data will be captured and no more capture * callbacks will be sent. */ constexpr CaptureStreamStopFlags fCaptureStreamStopFlagSync = 0x1; /********************************** IAudioCapture Interface **************************************/ /** An individual audio capture stream. */ class ICaptureStream_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.audio.ICaptureStream")> { protected: /** Starts capturing audio data from the stream. * * @param[in] flags Flags to alter the recording behavior. * * @returns @ref carb::audio::AudioResult::eOk if the capture is successfully started. * @returns An @ref AudioResult error code if the stream could not be started. * * @remarks Audio streams are in a stopped state when they're created. * You must call start() to start recording audio. * * @remarks Without @ref fCaptureStreamStartFlagOneShot, the stream will * perform looping capture. This means that once the ring buffer * has been filled, audio will start being recorded from the start * of the buffer again. * * @remarks Looping audio will not overwrite unread parts of the ring buffer. * Only parts of the buffer that have been unlocked can be overwritten * by the audio system. * Data written into the ring buffer must be unlocked periodically * when using looping capture or the ring buffer will fill up and * the device will overrun. * * @thread_safety Calls to this function cannot occur concurrently with * other calls to @ref ICaptureStream_abi::start_abi() or @ref ICaptureStream_abi::stop_abi(). */ virtual AudioResult start_abi(CaptureStreamStartFlags flags) noexcept = 0; /** Stop capturing audio data from the stream. * * @param[in] flags Flags to alter the stopping behavior. * * @returns @ref carb::audio::AudioResult::eOk if the capture was successfully stopped. * @returns @ref carb::audio::AudioResult::eNotAllowed if the stream was already stopped. * @returns An @ref AudioResult error code if something else went wrong. * The stream is likely broken in this case. * * @remarks This will stop capturing audio. Any audio data that would have * been captured between this point and the next call to @ref ICaptureStream_abi::start_abi() * will be lost. * * @remarks If there is unread data in the buffer, that data can still be * read with lock() after the stream is stopped. * * @note If fCaptureStreamStopFlagSync was not specified, the stop call will not sync with the * device so you could still receive callbacks after. * * @note CC-1180: You cannot use fCaptureStreamStopFlagSync from a callback. * * @thread_safety Calls to this function cannot occur concurrently with * other calls to @ref ICaptureStream_abi::start_abi() or @ref ICaptureStream_abi::stop_abi(). */ virtual AudioResult stop_abi(CaptureStreamStopFlags flags) noexcept = 0; /** Check if the stream is still capturing data. * @returns `true` if the stream is still capturing. * @returns `false` if the stream is stopped. * Callbacks will no longer be sent if `false` was returned unless the strema was * stoped with @ref ICaptureStream_abi::stop_abi() was called without fCaptureStreamStopFlagSync. */ virtual bool isCapturing_abi() noexcept = 0; /** Get the available number of frames to be read. * * @param[out] available The number of frames that can be read from the buffer. * * @returns @ref carb::audio::AudioResult::eOk if the frame count was retrieved successfully. * @returns @ref carb::audio::AudioResult::eOverrun if data has not been read fast enough and * the buffer filled up. * @returns @ref carb::audio::AudioResult::eNotAllowed if callback recording is being used. * @returns An @ref AudioResult error code if the operation fails for any other reason. * * @remarks This will check how much data is available to be read from the buffer. * This call is only valid when polling style recording is in use. */ virtual AudioResult getAvailableFrames_abi(OMNI_ATTR("out") size_t* available) noexcept = 0; /** Lock the next chunk of the buffer to be read. * * @param[in] request The length of the buffer to lock, in frames. * This may be 0 to lock as much data as possible. * This does not need to be a multiple of the fragment * length. * If you need to convert bytes to frames, you can use * @ref carb::audio::convertUnits() or * @ref carb::audio::framesToBytes() (note that this is * slow due to requiring a division). * @param[out] region Receives the audio data. * This can be `nullptr` to query the available data * in the buffer, rather than locking it. * This buffer can be held until unlock() is called; * after unlock is called, the stream can start writing * into this buffer. * @param[out] received The length of data available in @p buffer, in frames. * This will not exceed @p request. * Due to the fact that a ring buffer is used, you may * have more data in the buffer than is returned in one * call; a second call would be needed to read the full * buffer. * If you need to convert this to bytes, you can use * @ref carb::audio::convertUnits() or * @ref carb::audio::framesToBytes(). * * @returns @ref carb::audio::AudioResult::eOk if the requested region is successfully locked. * @returns @ref carb::audio::AudioResult::eOutOfMemory if there is no audio data available * in the buffer yet. * @returns @ref carb::audio::AudioResult::eNotAllowed if a region is already locked * and needs to be unlocked. * @returns @ref carb::audio::AudioResult::eNotAllowed if the stream is using callback * style recording. * @returns @ref carb::audio::AudioResult::eOverrun if data has not been read fast * enough and the underlying device has overrun. * This will happen on some audio systems (e.g. ALSA) if the * capture buffer fills up. * This can also happen on some audio systems sporadically if the * device's timing characteristics are too aggressive. * @returns an carb::audio::AudioResult::e* error code if the region could not be locked. * * @remarks This is used to get data from the capture stream when polling * style recording is being used (ie: there is no data callback). * When using this style of recording, portions of the buffer must * be periodically locked and unlocked. * * @remarks This retrieves the next portion of the buffer. * This portion of the buffer is considered to be locked until * @ref ICaptureStream_abi::unlock_abi() is called. * Only one region of the buffer can be locked at a time. * When using a looping capture, the caller should ensure that data * is unlocked before the buffer fills up or overruns may occur. */ virtual AudioResult lock_abi(size_t request, OMNI_ATTR("*in, out") const void** region, OMNI_ATTR("out") size_t* received) noexcept = 0; /** Unlocks a previously locked region of the buffer. * * @param[in] consumed The number of frames in the previous buffer that were consumed. * Any frames that were not consumed will be returned in future * @ref ICaptureStream_abi::lock_abi() calls. * 0 is valid here if you want to have the same locked region * returned on the next lock() call. * * @returns @ref carb::audio::AudioResult::eOk if the region is successfully unlocked. * @returns @ref carb::audio::AudioResult::eOutOfRange if @p consumed was larger than * the locked region. * @returns @ref carb::audio::AudioResult::eNotAllowed if no region is currently locked. * @returns an carb::audio::AudioResult::e* error code if the region could not be unlocked. * * @remarks This unlocks a region of the buffer that was locked with a * previous call to ICaptureStream_abi::lock_abi(). * Now that this region is unlocked, the device can start writing to it, * so the caller should no longer access that region. * Once the buffer is unlocked, a new region may be locked with ICaptureStream_abi::lock_abi(). * * @note If the locked region is not fully unlocked, the part of the region that * was not unlocked will be returned on the next call to ICaptureStream_abi::lock_abi(). * A second call to unlock cannot be made in this situation, it will fail. */ virtual AudioResult unlock_abi(size_t consumed) noexcept = 0; /** Retrieve the size of the capture buffer. * * @returns The size of the capture buffer, in frames. * You can use @ref ICaptureStream_abi::getSoundFormat_abi() and @ref carb::audio::convertUnits() * to convert to bytes or other units. * * @remarks If your code is dependent on the buffer's actual size, it is * better to retrieve it with this function since the buffer size * used with device creation can be adjusted. */ virtual size_t getBufferSize_abi() noexcept = 0; /** Retrieve the number of fragments used in this stream. * * @returns The number of buffer fragments. * This is the number of regions the recording buffer is divided * into. */ virtual size_t getFragmentCount_abi() noexcept = 0; /** Retrieve the format of the audio being captured. * * @param[out] format The format of the audio being captured. * This may not be `nullptr`. */ virtual void getSoundFormat_abi(OMNI_ATTR("out") SoundFormat* format) noexcept = 0; /** Clear any data that is currently in the recording buffer. * * @returns @ref carb::audio::AudioResult::eOk if the buffer was successfully cleared. * @returns an carb::audio::AudioResult::e* error code if the buffer could not be cleared. * * @remarks This is a quick way to get rid of any data that is left in the * buffer. * This will also reset the write position on the buffer back to * 0, so the next lock call will return the start of the buffer * (this can be useful if you want to do a one shot capture of the * entire buffer). * * @note If this is called while the capture stream is recording, the stream * will be paused before it is reset. */ virtual AudioResult reset_abi() noexcept = 0; }; /** Low-Level Audio Capture Plugin Interface. * * See these pages for more detail: * @rst * :ref:`carbonite-audio-label` * :ref:`carbonite-audio-capture-label` @endrst */ class IAudioCapture { public: CARB_PLUGIN_INTERFACE("omni::audio::IAudioCapture", 0, 0) /** ABI version of createStream() * * @param[in] desc A descriptor of the settings for the stream. * @param[out] stream The raw stream object. * * @returns @ref carb::audio::AudioResult::eOk on success. @see createStream() for failure codes. */ AudioResult (*internalCreateStream)(const CaptureStreamDesc* desc, ICaptureStream** stream); /** Creates a new audio capture stream. * * @param[in] desc A descriptor of the settings for the stream. * This may be nullptr to create a context that uses the * default capture device in its preferred format. * The device's format information may later be retrieved * with getSoundFormat(). * @param[out] stream The capture stream that is being created. * * @returns @ref carb::audio::AudioResult::eOk if the stream was successfully created. * @returns @ref carb::audio::AudioResult::eInvalidParameter if @p desc is `nullptr`. * @returns @ref carb::audio::AudioResult::eOutOfMemory if the stream's allocation failed. * @returns @ref carb::audio::AudioResult::eOutOfRange if the device's index does not * correspond to a device that exists. * @returns @ref carb::audio::AudioResult::eDeviceLost if the audio device selected fails * to open. */ inline AudioResult createStream(const CaptureStreamDesc* desc, omni::core::ObjectPtr<ICaptureStream>* stream) { if (stream == nullptr) { OMNI_LOG_ERROR("stream was null"); return carb::audio::AudioResult::eInvalidParameter; } ICaptureStream* raw = nullptr; AudioResult res = internalCreateStream(desc, &raw); *stream = omni::core::steal(raw); return res; } }; } // namespace experimental } // namespace audio } // namespace omni #define OMNI_BIND_INCLUDE_INTERFACE_DECL #include "IAudioCapture.gen.h" /** @copydoc omni::audio::experimental::ICaptureStream_abi */ class omni::audio::experimental::ICaptureStream : public omni::core::Generated<omni::audio::experimental::ICaptureStream_abi> { }; #define OMNI_BIND_INCLUDE_INTERFACE_IMPL #include "IAudioCapture.gen.h"
29,753
C
46.079114
118
0.651161
omniverse-code/kit/include/omni/inspect/IInspector.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 <omni/core/IObject.h> namespace omni { using namespace omni::core; } namespace omni { namespace inspect { OMNI_DECLARE_INTERFACE(IInspector); //! Base class for object inspection requests. class IInspector_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("omni.inspect.IInspector")> { protected: /** Set the help information for the current invocation of the inspector. For when behavior == eHelp * @param[in] helpString The help information, describing the configuration of the inspector */ virtual void setHelp_abi(OMNI_ATTR("c_str, not_null")const char* helpString) noexcept = 0; /** Returns the help information currently available on the inspector. Note that this could change * from one invocation to the next so it's important to read it immediately after requesting it. * @returns String containing the help information describing the current configuration of the inspector */ virtual OMNI_ATTR("c_str")const char* helpInformation_abi() noexcept = 0; /** Returns the common flag used to tell the inspection process to put the help information into the * inspector using the setHelp_abi function. Using this approach avoids having every inspector/object * combination add an extra ABI function just for retrieving the help information, as well as providing a * consistent method for requesting it. * @returns String containing the name of the common flag used for help information */ virtual OMNI_ATTR("c_str, not_null")const char* helpFlag_abi() noexcept = 0; /** Enable or disable an inspection flag. It's up to the individual inspection operations or the derived * inspector interfaces to interpret the flag. * @param[in] flagName Name of the flag to set * @param[in] flagState New state for the flag */ virtual void setFlag_abi(OMNI_ATTR("c_str, not_null")const char* flagName, bool flagState) noexcept = 0; /** Checks whether a particular flag is currently set or not. * @param[in] flagName Name of the flag to check * @returns True if the named flag is set, false if not */ virtual bool isFlagSet_abi(OMNI_ATTR("c_str, not_null")const char* flagName) noexcept = 0; }; } // namespace inspect } // namespace omni #include "IInspector.gen.h"
2,794
C
44.819671
109
0.734431
omniverse-code/kit/include/omni/inspect/IInspector.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::IInspector_abi> : public omni::inspect::IInspector_abi { public: OMNI_PLUGIN_INTERFACE("omni::inspect::IInspector") /** Set the help information for the current invocation of the inspector. For when behavior == eHelp * @param[in] helpString The help information, describing the configuration of the inspector */ void setHelp(const char* helpString) noexcept; /** Returns the help information currently available on the inspector. Note that this could change * from one invocation to the next so it's important to read it immediately after requesting it. * @returns String containing the help information describing the current configuration of the inspector */ const char* helpInformation() noexcept; /** Returns the common flag used to tell the inspection process to put the help information into the * inspector using the setHelp_abi function. Using this approach avoids having every inspector/object * combination add an extra ABI function just for retrieving the help information, as well as providing a * consistent method for requesting it. * @returns String containing the name of the common flag used for help information */ const char* helpFlag() noexcept; /** Enable or disable an inspection flag. It's up to the individual inspection operations or the derived * inspector interfaces to interpret the flag. * @param[in] flagName Name of the flag to set * @param[in] flagState New state for the flag */ void setFlag(const char* flagName, bool flagState) noexcept; /** Checks whether a particular flag is currently set or not. * @param[in] flagName Name of the flag to check * @returns True if the named flag is set, false if not */ bool isFlagSet(const char* flagName) noexcept; }; #endif #ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL inline void omni::core::Generated<omni::inspect::IInspector_abi>::setHelp(const char* helpString) noexcept { setHelp_abi(helpString); } inline const char* omni::core::Generated<omni::inspect::IInspector_abi>::helpInformation() noexcept { return helpInformation_abi(); } inline const char* omni::core::Generated<omni::inspect::IInspector_abi>::helpFlag() noexcept { return helpFlag_abi(); } inline void omni::core::Generated<omni::inspect::IInspector_abi>::setFlag(const char* flagName, bool flagState) noexcept { setFlag_abi(flagName, flagState); } inline bool omni::core::Generated<omni::inspect::IInspector_abi>::isFlagSet(const char* flagName) noexcept { return isFlagSet_abi(flagName); } #endif #undef OMNI_BIND_INCLUDE_INTERFACE_DECL #undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
3,578
C
34.79
120
0.734768
omniverse-code/kit/include/omni/inspect/PyIInspector.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 bindIInspector(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::IInspector_abi>, omni::python::detail::PyObjectPtr<omni::core::Generated<omni::inspect::IInspector_abi>>, omni::core::IObject> clsParent(m, "_IInspector"); py::class_<omni::inspect::IInspector, omni::core::Generated<omni::inspect::IInspector_abi>, omni::python::detail::PyObjectPtr<omni::inspect::IInspector>, omni::core::IObject> cls(m, "IInspector", 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::IInspector>(obj.get()); if (!tmp) { throw std::runtime_error("invalid type conversion"); } return tmp; })); cls.def(py::init( []() { auto tmp = omni::core::createType<omni::inspect::IInspector>(); if (!tmp) { throw std::runtime_error("unable to create omni::inspect::IInspector instantiation"); } return tmp; })); cls.def_property( "help", nullptr, [](omni::inspect::IInspector* self, const char* helpString) { self->setHelp(helpString); }); cls.def("help_information", &omni::inspect::IInspector::helpInformation, R"OMNI_BIND_RAW_(Returns the help information currently available on the inspector. Note that this could change from one invocation to the next so it's important to read it immediately after requesting it. @returns String containing the help information describing the current configuration of the inspector)OMNI_BIND_RAW_"); cls.def("help_flag", &omni::inspect::IInspector::helpFlag, R"OMNI_BIND_RAW_(Returns the common flag used to tell the inspection process to put the help information into the inspector using the setHelp_abi function. Using this approach avoids having every inspector/object combination add an extra ABI function just for retrieving the help information, as well as providing a consistent method for requesting it. @returns String containing the name of the common flag used for help information)OMNI_BIND_RAW_"); cls.def("set_flag", [](omni::inspect::IInspector* self, const char* flagName, bool flagState) { self->setFlag(flagName, flagState); }, R"OMNI_BIND_RAW_(Enable or disable an inspection flag. It's up to the individual inspection operations or the derived inspector interfaces to interpret the flag. @param[in] flagName Name of the flag to set @param[in] flagState New state for the flag)OMNI_BIND_RAW_", py::arg("flag_name"), py::arg("flag_state")); cls.def("is_flag_set", [](omni::inspect::IInspector* self, const char* flagName) { auto return_value = self->isFlagSet(flagName); return return_value; }, R"OMNI_BIND_RAW_(Checks whether a particular flag is currently set or not. @param[in] flagName Name of the flag to check @returns True if the named flag is set, false if not)OMNI_BIND_RAW_", py::arg("flag_name")); return omni::python::PyBind<omni::inspect::IInspector>::bind(cls); }
4,234
C
48.823529
129
0.664147
omniverse-code/kit/include/omni/inspect/IInspectMemoryUse.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(IInspectMemoryUse); //! Base class for object inspection requests. class IInspectMemoryUse_abi : public omni::Inherits<omni::inspect::IInspector, OMNI_TYPE_ID("omni.inspect.IInspectMemoryUse")> { protected: /** 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 */ virtual bool useMemory_abi(OMNI_ATTR("in, not_null") const void* ptr, size_t bytesUsed) noexcept = 0; /** Reset the memory usage data to a zero state */ virtual void reset_abi() noexcept = 0; /** @returns the total number of bytes of memory used since creation or the last call to reset(). */ virtual size_t totalUsed_abi() noexcept = 0; }; } // namespace inspect } // namespace oni #include "IInspectMemoryUse.gen.h"
1,558
C
33.644444
105
0.725931
omniverse-code/kit/include/omni/inspect/IInspectSerializer.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(IInspectSerializer); //! Base class for object serialization requests. class IInspectSerializer_abi : public omni::Inherits<omni::inspect::IInspector, OMNI_TYPE_ID("omni.inspect.IInspectSerializer")> { protected: /** Write a fixed string to the serializer output location * * @param[in] toWrite String to be written to the serializer */ virtual void writeString_abi(OMNI_ATTR("c_str, not_null") const char* toWrite) noexcept = 0; /** 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 */ virtual OMNI_ATTR("no_py") void write_abi(OMNI_ATTR("c_str, not_null") const char* fmt, va_list args) noexcept = 0; /** 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 */ 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 Current file path where the output is going. nullptr means the output is going to a string. */ virtual const char* getOutputLocation_abi() noexcept = 0; /** 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. */ 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; }; } // namespace inspect } // namespace omni #include "IInspectSerializer.gen.h"
3,087
C
40.729729
119
0.712666
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"
7,696
C
37.10396
119
0.674636
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
11,325
C
32.410029
128
0.683974
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
5,763
C
39.879432
172
0.699809
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); }
3,319
C
43.864864
136
0.639349
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
2,260
C
29.146666
111
0.695133
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); }
9,338
C
48.412698
139
0.669629
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
4,213
C
32.444444
124
0.715879
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); }
4,010
C
51.090908
135
0.669327
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
1,473
C
26.81132
113
0.716225
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"
1,589
C
35.976743
118
0.750157
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
9,585
C
38.941667
120
0.726552
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
35,819
C
40.362587
124
0.676987
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
2,086
C
31.107692
115
0.733941
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"
1,445
C
34.268292
116
0.731488
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
1,850
C
27.921875
97
0.722703
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
2,310
C
34.015151
119
0.647619
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
3,196
C
30.97
120
0.63423
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_)
11,636
C
24.24295
133
0.636215
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"
6,825
C
38.686046
111
0.669744
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");
8,583
C
49.19883
119
0.655831
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"
2,182
C
34.786885
121
0.718607
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");
7,117
C
37.475675
126
0.682872
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
5,280
C
37.547445
111
0.693182
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
8,724
C
39.581395
115
0.672054
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"
11,529
C
47.445378
113
0.673432
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"
4,517
C
40.833333
119
0.680097
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
2,245
C
34.093749
106
0.714922
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"
12,519
C
48.098039
121
0.672817
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; } }
2,639
C
44.517241
95
0.817355
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 }; } }
890
C
31.999999
89
0.77191
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
2,283
C
29.453333
87
0.701708
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
1,410
C
28.395833
115
0.714894
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
20,845
C
37.603704
124
0.661166
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
3,771
C
30.433333
119
0.700875
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
7,842
C
26.616197
150
0.655573
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
1,085
C
28.351351
102
0.737327
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
4,913
C
33.125
118
0.688988
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
1,429
C
23.237288
93
0.686494
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
1,909
C
27.939394
118
0.682556
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
15,271
C
45.419453
126
0.589549
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
3,270
C
28.205357
80
0.680734
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 \ } \ }
1,918
C
42.613635
120
0.49635
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
1,083
C
13.263158
77
0.558633
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
5,869
C
30.55914
124
0.689385
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
2,676
C
28.417582
116
0.690583
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
936
C
23.657894
101
0.729701
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
1,121
C
31.057142
77
0.748439
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
2,272
C
30.136986
102
0.701144
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
5,119
C
29.658682
125
0.686853
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
2,243
C
27.05
106
0.693268
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
19,654
C
34.161002
124
0.662918
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
1,567
C
22.757575
93
0.67709
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
2,327
C
31.788732
124
0.70434
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
6,340
C
31.352041
146
0.672713
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
1,333
C
24.653846
120
0.714179
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
3,845
C
26.084507
120
0.66762
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
5,159
C
30.851852
117
0.648769
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
1,908
C
27.073529
106
0.694444
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
949
C
23.358974
88
0.710221
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
1,121
C
22.87234
77
0.709188
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
1,108
C
25.404761
79
0.729242
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
4,024
C
22.265896
120
0.622763
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
1,179
C
22.6
77
0.681086
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
634
C
23.423076
77
0.739748
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
15,725
C
35.657343
120
0.571065
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
3,459
C
30.743119
120
0.633998
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
859
C
29.714285
115
0.721769
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
1,116
C
30.027777
112
0.69086
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
19,689
C
67.846154
120
0.429631
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
3,624
C
32.878504
118
0.664459
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
4,459
C
32.037037
124
0.67033
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
4,625
C
34.312977
125
0.697514
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
3,063
C
28.747573
116
0.702579
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
3,294
C
36.022472
120
0.721615
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
2,132
C
25.012195
117
0.668856
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; }; } }
2,566
C
29.2
106
0.72993
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
2,715
C
30.952941
120
0.713076
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
5,635
C
24.273542
122
0.644898
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
3,688
C
30.262712
124
0.664588
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
3,779
C
28.302325
116
0.664197
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
4,061
C
29.772727
125
0.694164
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
11,077
C
35.08469
128
0.435768