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/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtRelationship.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 "Common.h"
#include "IRtProperty.h"
#include <omni/core/IObject.h>
#include <omni/fabric/AttrNameAndType.h>
#include <omni/fabric/IFabric.h>
#include <vector>
namespace usdrt
{
// we must always forward declare each interface that will be referenced here.
OMNI_DECLARE_INTERFACE(IRtRelationship);
// *********************************************************************************************************************
// *********************************************************************************************************************
// *********************************************************************************************************************
//
// ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION
//
// The interfaces within these obnoxious comment blocks are now locked for long-term support.
// Any changes you wish to make should be added in a new interface.
// See this document for more details:
// https://docs.google.com/document/d/1xyONwFtiM-lWXP5HjQt6pkOgl7xF_4b_Jp4wUS3_d3I/edit?usp=sharing
//
// Please do not break our precious ABIs!
//
// ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION
//
// *********************************************************************************************************************
// *********************************************************************************************************************
// *********************************************************************************************************************
class IRtRelationship_abi : public omni::core::Inherits<usdrt::IRtProperty, OMNI_TYPE_ID("usdrt.IRtRelationship")>
{
protected: // all ABI functions must always be 'protected'.
// ---- targets
virtual bool hasAuthoredTargets_abi() noexcept = 0;
// Note: As of this implementation, Fabric does not support
// lists of targets for relationships, so the behavior of some
// of these may diverge from USD until that support is added
virtual bool addTarget_abi(omni::fabric::PathC path, ListPosition position) noexcept = 0;
virtual bool removeTarget_abi(omni::fabric::PathC path) noexcept = 0;
virtual bool OMNI_ATTR("not_prop")
setTargets_abi(OMNI_ATTR("in, count=size") const omni::fabric::PathC* paths, uint32_t size) noexcept = 0;
virtual bool clearTargets_abi() noexcept = 0;
virtual uint32_t numTargets_abi() noexcept = 0;
virtual bool OMNI_ATTR("not_prop")
getTargets_abi(OMNI_ATTR("out, count=size") omni::fabric::PathC* paths, uint32_t size) noexcept = 0;
};
// *********************************************************************************************************************
// *********************************************************************************************************************
// *********************************************************************************************************************
//
// ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION
//
// End of locked interfaces. Enjoy the rest of your day.
//
// ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION ATTENTION
//
// *********************************************************************************************************************
// *********************************************************************************************************************
// *********************************************************************************************************************
} // namespace usdrt
#include "IRtRelationship.gen.h"
| 4,191 |
C
| 50.121951 | 120 | 0.467907 |
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtSchemaRegistry.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 "Common.h"
#include <omni/fabric/IToken.h>
namespace usdrt
{
// we must always forward declare each interface that will be referenced here.
OMNI_DECLARE_INTERFACE(IRtSchemaRegistry);
class IRtSchemaRegistry_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("usdrt.IRtSchemaRegistry")>
{
protected: // all ABI functions must always be 'protected'.
virtual IRtSchemaRegistry* initRegistry_abi() noexcept = 0;
virtual bool isConcrete_abi(omni::fabric::TokenC primTypeC) noexcept = 0;
virtual bool isAppliedAPISchema_abi(omni::fabric::TokenC apiSchemaTypeC) noexcept = 0;
virtual bool isMultipleApplyAPISchema_abi(omni::fabric::TokenC apiSchemaTypeC) noexcept = 0;
virtual bool isA_abi(omni::fabric::TokenC sourceTypeNameC, omni::fabric::TokenC queryTypeNameC) noexcept = 0;
virtual OMNI_ATTR("not_prop") omni::fabric::TokenC getAliasFromName_abi(omni::fabric::TokenC nameC) noexcept = 0;
};
} // namespace usdrt
#include "IRtSchemaRegistry.gen.h"
| 1,455 |
C
| 39.444443 | 119 | 0.770447 |
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/scenegraph/interface/IRtStage105.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/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
template <>
class omni::core::Generated<usdrt::IRtStage105_abi> : public usdrt::IRtStage105_abi
{
public:
OMNI_PLUGIN_INTERFACE("usdrt::IRtStage105")
uint32_t findCount(omni::fabric::TokenC typeName, const omni::fabric::TokenC* apiNames, uint32_t apiNamesSize) noexcept;
bool find(omni::fabric::TokenC typeName,
const omni::fabric::TokenC* apiNames,
uint32_t apiNamesSize,
omni::fabric::PathC* outPaths,
uint32_t outPathCount) noexcept;
bool computeWorldBound(usdrt::GfRange3d* result) noexcept;
omni::core::ObjectPtr<usdrt::IRtAttribute> getAttributeAtPath105(omni::fabric::PathC path,
omni::fabric::TokenC prop) noexcept;
omni::core::ObjectPtr<usdrt::IRtRelationship> getRelationshipAtPath105(omni::fabric::PathC path,
omni::fabric::TokenC prop) noexcept;
bool hasPrimAtPath105(omni::fabric::PathC path, bool excludeTags) noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline uint32_t omni::core::Generated<usdrt::IRtStage105_abi>::findCount(omni::fabric::TokenC typeName,
const omni::fabric::TokenC* apiNames,
uint32_t apiNamesSize) noexcept
{
return findCount_abi(typeName, apiNames, apiNamesSize);
}
inline bool omni::core::Generated<usdrt::IRtStage105_abi>::find(omni::fabric::TokenC typeName,
const omni::fabric::TokenC* apiNames,
uint32_t apiNamesSize,
omni::fabric::PathC* outPaths,
uint32_t outPathCount) noexcept
{
return find_abi(typeName, apiNames, apiNamesSize, outPaths, outPathCount);
}
inline bool omni::core::Generated<usdrt::IRtStage105_abi>::computeWorldBound(usdrt::GfRange3d* result) noexcept
{
return computeWorldBound_abi(result);
}
inline omni::core::ObjectPtr<usdrt::IRtAttribute> omni::core::Generated<usdrt::IRtStage105_abi>::getAttributeAtPath105(
omni::fabric::PathC path, omni::fabric::TokenC prop) noexcept
{
return omni::core::steal(getAttributeAtPath105_abi(path, prop));
}
inline omni::core::ObjectPtr<usdrt::IRtRelationship> omni::core::Generated<usdrt::IRtStage105_abi>::getRelationshipAtPath105(
omni::fabric::PathC path, omni::fabric::TokenC prop) noexcept
{
return omni::core::steal(getRelationshipAtPath105_abi(path, prop));
}
inline bool omni::core::Generated<usdrt::IRtStage105_abi>::hasPrimAtPath105(omni::fabric::PathC path,
bool excludeTags) noexcept
{
return hasPrimAtPath105_abi(path, excludeTags);
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 3,900 |
C
| 36.152381 | 125 | 0.625128 |
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/xformcache/IXformCache.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 <omni/core/IObject.h>
#include <omni/fabric/IFabric.h>
#include <omni/fabric/IPath.h>
#include <omni/fabric/IdTypes.h>
#include <usdrt/gf/matrix.h>
namespace usdrt
{
namespace xformcache
{
OMNI_DECLARE_INTERFACE(IXformCache);
class IXformCache_abi : public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("usdrt.xformcache.IXformCache")>
{
protected:
virtual bool attachToStage_abi(const omni::fabric::UsdStageId stageId) noexcept = 0;
virtual omni::fabric::UsdStageId getStageId_abi() noexcept = 0;
virtual void syncXforms_abi() noexcept = 0;
virtual void syncTargetedXforms_abi(const omni::fabric::PathC targetPath) noexcept = 0;
virtual OMNI_ATTR("not_prop") usdrt::GfMatrix4d getLatestWorldXform_abi(const omni::fabric::PathC path) noexcept = 0;
virtual usdrt::GfMatrix4d computeWorldXform_abi(const omni::fabric::PathC path) noexcept = 0;
};
} // namespace xformcache
} // namespace usdrt
#include "IXformCache.gen.h"
| 1,426 |
C
| 31.431817 | 121 | 0.76087 |
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/xformcache/ISharedXformCache.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 "IXformCache.h"
namespace usdrt
{
namespace xformcache
{
OMNI_DECLARE_INTERFACE(ISharedXformCache);
class ISharedXformCache_abi
: public omni::core::Inherits<omni::core::IObject, OMNI_TYPE_ID("usdrt.xformcache.ISharedXformCache")>
{
protected:
virtual bool hasCache_abi(const omni::fabric::UsdStageId stageId) noexcept = 0;
virtual OMNI_ATTR("no_api") IXformCache* getCache_abi(const omni::fabric::UsdStageId stageId) noexcept = 0;
virtual OMNI_ATTR("no_api") IXformCache* getOrCreateCache_abi(const omni::fabric::UsdStageId stageId) noexcept = 0;
virtual bool clear_abi() noexcept = 0;
};
} // namespace xformcache
} // namespace usdrt
#include "ISharedXformCache.gen.h"
// clang-format off
OMNI_DEFINE_INTERFACE_API(usdrt::xformcache::ISharedXformCache)
{
public:
omni::core::ObjectPtr<usdrt::xformcache::IXformCache> getCache(omni::fabric::UsdStageId stageId) noexcept
{
return omni::core::borrow(getCache_abi(stageId));
}
omni::core::ObjectPtr<usdrt::xformcache::IXformCache> getOrCreateCache(omni::fabric::UsdStageId stageId) noexcept
{
return omni::core::borrow(getOrCreateCache_abi(stageId));
}
};
// clang-format on
| 1,657 |
C
| 29.703703 | 119 | 0.747737 |
omniverse-code/kit/exts/usdrt.scenegraph/include/usdrt/xformcache/IXformCache.gen.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.
//
// --------- 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
template <>
class omni::core::Generated<usdrt::xformcache::IXformCache_abi> : public usdrt::xformcache::IXformCache_abi
{
public:
OMNI_PLUGIN_INTERFACE("usdrt::xformcache::IXformCache")
bool attachToStage(omni::fabric::UsdStageId stageId) noexcept;
omni::fabric::UsdStageId getStageId() noexcept;
void syncXforms() noexcept;
void syncTargetedXforms(omni::fabric::PathC targetPath) noexcept;
usdrt::GfMatrix4d getLatestWorldXform(omni::fabric::PathC path) noexcept;
usdrt::GfMatrix4d computeWorldXform(omni::fabric::PathC path) noexcept;
};
#endif
#ifndef OMNI_BIND_INCLUDE_INTERFACE_DECL
inline bool omni::core::Generated<usdrt::xformcache::IXformCache_abi>::attachToStage(omni::fabric::UsdStageId stageId) noexcept
{
return attachToStage_abi(stageId);
}
inline omni::fabric::UsdStageId omni::core::Generated<usdrt::xformcache::IXformCache_abi>::getStageId() noexcept
{
return getStageId_abi();
}
inline void omni::core::Generated<usdrt::xformcache::IXformCache_abi>::syncXforms() noexcept
{
syncXforms_abi();
}
inline void omni::core::Generated<usdrt::xformcache::IXformCache_abi>::syncTargetedXforms(omni::fabric::PathC targetPath) noexcept
{
syncTargetedXforms_abi(targetPath);
}
inline usdrt::GfMatrix4d omni::core::Generated<usdrt::xformcache::IXformCache_abi>::getLatestWorldXform(
omni::fabric::PathC path) noexcept
{
return getLatestWorldXform_abi(path);
}
inline usdrt::GfMatrix4d omni::core::Generated<usdrt::xformcache::IXformCache_abi>::computeWorldXform(
omni::fabric::PathC path) noexcept
{
return computeWorldXform_abi(path);
}
#endif
#undef OMNI_BIND_INCLUDE_INTERFACE_DECL
#undef OMNI_BIND_INCLUDE_INTERFACE_IMPL
| 2,507 |
C
| 26.260869 | 130 | 0.750698 |
omniverse-code/kit/exts/usdrt.scenegraph/docs/index.rst
|
usdrt.scenegraph: USDRT Scenegraph API for Kit
##############################################
This extension loads the usdrt.scenegraph plugin
and adds the USDRT Python bindings into the Python path
for Kit.
USDRT is developed out of the usdrt repo and delivered
via the usdrt packman package. This extension is the
meant to be the singular load point for the
usdrt.scenegraph plugin within Kit.
Public documentation here:
https://docs.omniverse.nvidia.com/kit/docs/usdrt
.. toctree::
:maxdepth: 1
CHANGELOG
| 523 |
reStructuredText
| 20.833332 | 55 | 0.713193 |
omniverse-code/kit/exts/omni.kit.quicklayout/config/extension.toml
|
[package]
version = "1.1.1"
authors = ["NVIDIA"]
title = "Layout Control Tools"
description = "Set of tools for controlling layout."
readme = "docs/README.md"
repository = ""
category = "Core"
feature = true
keywords = ["layout", "workspace"]
changelog = "docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.svg"
[dependencies]
"omni.kit.mainwindow" = {}
"omni.kit.window.filepicker" = {}
"omni.client" = {}
"omni.ui" = {}
"omni.usd.libs" = {}
"omni.kit.menu.utils" = {}
[[python.module]]
name = "omni.kit.quicklayout"
[settings]
persistent.app.quicklayout.defaultLayout = "$$last_used$$"
persistent.app.quicklayout.lastUsedLayout = "$$none$$"
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
pyCoverageIncludeDependencies = false
dependencies = [
"omni.kit.mainwindow",
"omni.kit.renderer.capture",
"omni.kit.window.preferences",
"omni.kit.menu.utils",
"omni.kit.ui_test",
"omni.kit.test_suite.helpers",
]
| 1,031 |
TOML
| 20.957446 | 58 | 0.668283 |
omniverse-code/kit/exts/omni.kit.quicklayout/omni/kit/quicklayout/quicklayout.py
|
# Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.kit.widget.filebrowser import FileBrowserItem
from omni.kit.window.filepicker import FilePickerDialog
from pathlib import Path
from omni.ui.workspace_utils import CompareDelegate
import carb
import carb.tokens
import json
import omni.client
import omni.ui as ui
import traceback
class QuickLayout:
"""Namespace that has the methods to load and save the layout"""
def __init__(self):
self._dialog = None
def destroy(self): # pragma: no cover
if self._dialog:
self._dialog.destroy()
self._dialog = None
def __on_filter_item(self, item: FileBrowserItem) -> bool:
if not item or item.is_folder:
return True
if self._dialog.current_filter_option == 0:
# Show only files with listed extensions
if item.path.endswith(".json"):
return True
else:
return False
else:
# Show All Files (*)
return True
@staticmethod
def __get_workspace_dir() -> str:
"""Return the workspace file"""
token = carb.tokens.get_tokens_interface()
dir = token.resolve("${data}")
# FilePickerDialog needs the capital drive. In case it's linux, the
# first letter will be / and it's still OK.
dir = dir[:1].upper() + dir[1:]
return dir
@staticmethod
def __get_workspace_file() -> str:
"""Return the workspace file"""
dir = QuickLayout.__get_workspace_dir()
return f"{dir}/user.layout.json"
def __on_apply_save(self, filename: str, dir: str):
"""Called when the user presses the Save button in the dialog"""
# Get the file extension from the filter
if self._dialog.current_filter_option == 0 and not filename.lower().endswith(".json"):
filename += ".json"
self._dialog.hide()
self.save_file(omni.client.combine_urls(dir if dir.endswith("/") else dir+"/", filename))
def __on_apply_load(self, filename, dir):
"""Called when the user presses the Load button in the dialog"""
self._dialog.hide()
self.load_file(omni.client.combine_urls(dir if dir.endswith("/") else dir+"/", filename))
@staticmethod
def save_file(workspace_file: str):
"""Save the layout to the workspace file"""
workspace_dump = ui.Workspace.dump_workspace()
payload = bytes(json.dumps(workspace_dump, sort_keys=True, indent=2).encode("utf-8"))
result = omni.client.write_file(workspace_file, payload)
if result != omni.client.Result.OK: # pragma: no cover
carb.log_error(f"[quicklayout] The workspace cannot be written to {workspace_file}, error code: {result}")
return
carb.log_info(f"[quicklayout] The workspace saved to {workspace_file}")
@staticmethod
def load_file(workspace_file: str, keep_windows_open=False):
"""Load the layout from the workspace file"""
result, _, content = omni.client.read_file(workspace_file)
if result != omni.client.Result.OK: # pragma: no cover
carb.log_error(f"[quicklayout] Can't read the workspace file {workspace_file}, error code: {result}")
return
data = json.loads(memoryview(content).tobytes().decode("utf-8"))
ui.Workspace.restore_workspace(data, keep_windows_open)
carb.log_info(f"[quicklayout] The workspace is loaded from {workspace_file}")
@staticmethod
def compare_file(workspace_file: str, compare_delegate: CompareDelegate=CompareDelegate()):
"""Load the layout from the workspace file"""
result, _, content = omni.client.read_file(workspace_file)
if result != omni.client.Result.OK: # pragma: no cover
carb.log_error(f"[quicklayout] Can't read the workspace file {workspace_file}, error code: {result}")
return
data = json.loads(memoryview(content).tobytes().decode("utf-8"))
result = ui.Workspace.compare_workspace(data, compare_delegate=compare_delegate)
carb.log_info(f"[quicklayout] compared {workspace_file} with workspace")
return result
def save(self, menu: str, value: bool):
"""Save layout with the dialog"""
# Remove previously opened dialog
self.destroy()
self._dialog = FilePickerDialog(
"Select File to Save Layout",
apply_button_label="Save",
current_directory=QuickLayout.__get_workspace_dir(),
click_apply_handler=self.__on_apply_save,
item_filter_options=["JSON Files (*.json)", "All Files (*)"],
item_filter_fn=self.__on_filter_item,
)
def load(self, menu: str, value: bool):
"""Load layout with the dialog"""
# Remove previously opened dialog
self.destroy()
self._dialog = FilePickerDialog(
"Select File to Load Layout",
apply_button_label="Load",
current_directory=QuickLayout.__get_workspace_dir(),
click_apply_handler=self.__on_apply_load,
item_filter_options=["JSON Files (*.json)", "All Files (*)"],
item_filter_fn=self.__on_filter_item,
)
@staticmethod
def quick_save(menu: str, value: bool):
workspace_file = QuickLayout.__get_workspace_file()
QuickLayout.save_file(workspace_file)
@staticmethod
def quick_load(menu: str, value: bool):
workspace_file = QuickLayout.__get_workspace_file()
QuickLayout.load_file(workspace_file)
| 5,988 |
Python
| 38.662251 | 118 | 0.635939 |
omniverse-code/kit/exts/omni.kit.quicklayout/omni/kit/quicklayout/quicklayout_extension.py
|
# Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .quicklayout import QuickLayout
import omni.ext
import omni.kit.ui
class QuickLayoutExtension(omni.ext.IExt):
def on_startup(self, ext_id):
self.__quick_layout = QuickLayout()
editor_menu = omni.kit.ui.get_editor_menu()
if editor_menu:
self._menu_save = editor_menu.add_item("Window/Layout/Save Layout...", self.__quick_layout.save)
self._menu_load = editor_menu.add_item("Window/Layout/Load Layout...", self.__quick_layout.load)
self._menu_quick_save = editor_menu.add_item("Window/Layout/Quick Save", QuickLayout.quick_save)
self._menu_quick_load = editor_menu.add_item("Window/Layout/Quick Load", QuickLayout.quick_load)
def on_shutdown(self): # pragma: no cover
self._menu_save = None
self._menu_load = None
self._menu_quick_save = None
self._menu_quick_load = None
self._menu = None
self.__quick_layout.destroy()
self.__quick_layout = None
| 1,423 |
Python
| 42.151514 | 108 | 0.691497 |
omniverse-code/kit/exts/omni.kit.quicklayout/omni/kit/quicklayout/layout_templates_page.py
|
# Copyright (c) 2018-2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import re
import os
import carb.settings
import omni.kit.app
import omni.ui as ui
from omni.kit.window.preferences import PreferenceBuilder, SettingType, PERSISTENT_SETTINGS_PREFIX
from omni.kit.quicklayout import QuickLayout
class LayoutTemplatesPreferences(PreferenceBuilder):
def __init__(self):
super().__init__("Template Startup")
def build(self):
layout_names = {"Open Last Used Layout": "$$last_used$$"}
for item in QuickLayout.get_default_layouts():
layout_names[item[0]] = item[0]
with ui.VStack(height=0):
with self.add_frame("Default Layout"):
with ui.VStack():
self.create_setting_widget_combo("Default Layout", PERSISTENT_SETTINGS_PREFIX + "/app/quicklayout/defaultLayout", layout_names, setting_is_index=True)
| 1,262 |
Python
| 38.468749 | 170 | 0.722662 |
omniverse-code/kit/exts/omni.kit.quicklayout/omni/kit/quicklayout/tests/test_quicklayout_menu.py
|
## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import os
import carb
import omni.kit.app
from omni.kit.test.async_unittest import AsyncTestCase
import omni.usd
import omni.ui as ui
from omni.kit import ui_test
from pxr import Vt, Gf
from omni.kit.test_suite.helpers import get_test_data_path, arrange_windows
from omni.kit.quicklayout import QuickLayout
from omni.kit.menu.utils import MenuItemDescription, MenuAlignment
from omni.kit.ui_test.query import MenuRef
PERSISTENT_SETTINGS_PREFIX = "/persistent"
class TestQuicklayoutMenu(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
# carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/quicklayout/defaultLayout", "$$last_used$$")
self.assertEqual(QuickLayout.get_default_layouts(), [])
data_path = get_test_data_path(__name__)
self._layout_data = [ ["Test 1", f"{data_path}/layouts/test1.json", carb.input.KeyboardInput.KEY_1],
["Test 2", f"{data_path}/layouts/test2.json", carb.input.KeyboardInput.KEY_2]]
QuickLayout.add_default_layouts(self._layout_data)
# After running each test
async def tearDown(self):
QuickLayout.remove_default_layouts(self._layout_data)
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/quicklayout/defaultLayout", "$$last_used$$")
self.assertEqual(QuickLayout.get_default_layouts(), [])
async def test_layout_menu(self):
# add layout placeholder
menu_placeholder = [MenuItemDescription(name="placeholder", show_fn=lambda: False)]
omni.kit.menu.utils.add_menu_items(menu_placeholder, name="Layout")
await ui_test.human_delay(10)
layout_menu_items = []
def add_layout_menu_entry(name, parameter, key):
item = MenuItemDescription(name=name)
layout_menu_items.append(item)
for item in QuickLayout.get_default_layouts():
add_layout_menu_entry(f"{item[0]}", item[1], item[2])
# add menu
layout_delegate = QuickLayout.LayoutMenuDelegate(read_fn=lambda: "Test 2",
layout_id="Test 2",
text_width=175,
hotkey_width=75)
omni.kit.menu.utils.add_menu_items(layout_menu_items, "Layout", delegate=layout_delegate)
await ui_test.human_delay(10)
# click layout
layout_menu = omni.kit.ui_test.get_menubar().find_menu("Layout")
await layout_menu.click()
await ui_test.human_delay(10)
# verify menu icon status
layout_menu_icons = layout_menu.widget.delegate._layout_menu_icons
self.assertFalse(layout_menu.widget.delegate._layout_menu_icons['Test 1']['selected_image'].enabled)
self.assertTrue(layout_menu.widget.delegate._layout_menu_icons['Test 2']['selected_image'].enabled)
# remove menus
omni.kit.menu.utils.remove_menu_items(layout_menu_items, name="Layout")
omni.kit.menu.utils.remove_menu_items(menu_placeholder, name="Layout")
await ui_test.human_delay(10)
| 3,637 |
Python
| 42.309523 | 121 | 0.659335 |
omniverse-code/kit/exts/omni.kit.quicklayout/omni/kit/quicklayout/tests/test_menus.py
|
## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from omni.ui.tests.test_base import OmniUiTest
import omni.kit
import omni.ui as ui
import omni.kit.ui_test as ui_test
class TestQuickLayoutMenus(OmniUiTest):
async def test_menus(self):
menu_widget = ui_test.get_menubar()
await menu_widget.find_menu("Window").click()
await menu_widget.find_menu("Layout").click()
await menu_widget.find_menu("Quick Save").click()
await ui_test.human_delay(10)
await menu_widget.find_menu("Window").click()
await menu_widget.find_menu("Layout").click()
await menu_widget.find_menu("Quick Load").click()
await ui_test.human_delay(10)
| 1,082 |
Python
| 39.11111 | 77 | 0.719963 |
omniverse-code/kit/exts/omni.kit.quicklayout/omni/kit/quicklayout/tests/quicklayout_test.py
|
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from ..quicklayout import QuickLayout
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
import json
import omni.kit
import omni.ui as ui
import os
import tempfile
from omni.kit.mainwindow import get_main_window
CURRENT_PATH = Path(__file__).parent.joinpath("../../../../data")
ROOT_WINDOW_NAME = "DockSpace"
class TestQuickLayout(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests")
self._dump_workspace = ui.Workspace.dump_workspace()
# After running each test
async def tearDown(self):
self._golden_img_dir = None
ui.Workspace.restore_workspace(self._dump_workspace)
await super().tearDown()
async def test_floating(self):
ui.Workspace.clear()
window_left = ui.Window("Left", width=100, height=100, position_x=10, position_y=10)
window_right = ui.Window("Right", width=100, height=100, position_x=120, position_y=10)
await omni.kit.app.get_app().next_update_async()
temp_file = Path(tempfile.gettempdir()).joinpath("workspace_" + next(tempfile._get_candidate_names()) + ".json")
QuickLayout.save_file(f"{temp_file}")
with open(f"{temp_file}") as json_file:
data = json.load(json_file)
os.remove(f"{temp_file}")
left_pos = 0
right_pos = 0
for win in data:
if "title" in win:
if win["title"] == "Left":
left_pos = win['position_x']
elif win["title"] == "Right":
right_pos = win['position_x']
# self.assertEqual(len(data), 3) # Not true if test_restore is run first
self.assertEqual(left_pos, 10.0)
self.assertEqual(right_pos, 120.0)
async def test_docking(self):
ui.Workspace.clear()
window_left = ui.Window("Left2", width=100, height=100, position_x=10, position_y=10)
window_right = ui.Window("Right2", width=100, height=100, position_x=120, position_y=10)
target_window = ui.Workspace.get_window(ROOT_WINDOW_NAME)
await omni.kit.app.get_app().next_update_async()
window_left.dock_in(target_window, ui.DockPosition.SAME)
window_right.dock_in(window_left, ui.DockPosition.RIGHT, 0.5)
await omni.kit.app.get_app().next_update_async()
temp_file = Path(tempfile.gettempdir()).joinpath("workspace_" + next(tempfile._get_candidate_names()) + ".json")
QuickLayout.save_file(f"{temp_file}")
with open(f"{temp_file}") as json_file:
data = json.load(json_file)
os.remove(f"{temp_file}")
self.assertEqual(len(data[0]["children"]), 2)
self.assertIn(data[0]["children"][0]["position"], ["LEFT", "RIGHT"])
self.assertIn(data[0]["children"][1]["position"], ["LEFT", "RIGHT"])
async def test_restore(self):
data = [
{
"children": [
{
"children": [
{
"dock_id": 1,
"height": 100,
"selected_in_dock": True,
"title": "LeftDocked",
"visible": True,
"width": 100,
}
],
"dock_id": 1,
"position": "LEFT",
},
{
"children": [
{
"dock_id": 2,
"height": 100,
"selected_in_dock": False,
"title": "RightDocked",
"visible": True,
"width": 100,
}
],
"dock_id": 2,
"position": "RIGHT",
},
],
"dock_id": 0,
}
]
await self.create_test_area()
window_left = ui.Window("LeftDocked")
with window_left.frame:
ui.Rectangle(style={"background_color": 0xFFF07E4D})
window_right = ui.Window("RightDocked")
with window_right.frame:
ui.Rectangle(style={"background_color": 0xFF7DF0A6})
await omni.kit.app.get_app().next_update_async()
temp_file = Path(tempfile.gettempdir()).joinpath("workspace_" + next(tempfile._get_candidate_names()) + ".json")
# Save data to json file and open it in QuickLayout
with open(f"{temp_file}", "w") as json_file:
json.dump(data, json_file, sort_keys=True, indent=2)
QuickLayout.load_file(f"{temp_file}")
await omni.kit.app.get_app().next_update_async()
# for code coverage. Real QuickLayout.compare_file test is in omni.kit.test_suite.layout as it needs windows
QuickLayout.compare_file(f"{temp_file}")
# We don't test tab bar
window_left.dock_tab_bar_visible = False
window_right.dock_tab_bar_visible = False
os.remove(f"{temp_file}")
await self.finalize_test(golden_img_dir=self._golden_img_dir)
| 5,838 |
Python
| 35.72327 | 120 | 0.538883 |
omniverse-code/kit/exts/omni.kit.quicklayout/docs/CHANGELOG.md
|
# QUICKLAYOUT CHANGELOG
## [1.1.1] - 2023-01-31
### Changed
- Removed python.module for tests, from extension.toml
- Fixed tests that broke when run in random order
## [1.1.0] - 2023-01-11
### Changed
- Adding default layout template
## [1.0.2] - 2023-01-20
### Changed
- Fixed saving/loading using nucleus paths
## [1.0.1] - 2021-05-25
### Changed
- Using `omni.client` for saving and loading the workspace
## [1.0.0] - 2021-02-02
### Added
- Initial extension that saves/loads the layout to the userdirectory
| 515 |
Markdown
| 22.454544 | 68 | 0.691262 |
omniverse-code/kit/exts/omni.kit.quicklayout/docs/README.md
|
# Layout Control Tools [omni.kit.quicklayout]
Set of tools for controlling layout.
Creates two menu items.
- `Window/Layout/Save Layout`: saves the current layout to the file `"${data}/user.layout.json"`
- `Window/Layout/Load Layout`: loads the layout from the file `"${data}/user.layout.json"`
| 298 |
Markdown
| 32.222219 | 96 | 0.738255 |
omniverse-code/kit/exts/omni.kit.menu.common/config/extension.toml
|
[package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.3"
category = "Internal"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarily for displaying extension info in UI
title = "Common Menu"
description="Implementation of parts of Window and Help menus."
# URL of the extension source repository.
repository = ""
# Keywords for the extension
keywords = ["kit", "ui", "menu"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog = "docs/CHANGELOG.md"
# Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file).
preview_image = "data/preview.png"
[dependencies]
"omni.usd" = {}
"omni.kit.menu.utils" = {}
[[python.module]]
name = "omni.kit.menu.common"
[settings]
# Setting this to false because we also set F11 in this ext.
exts."omni.appwindow".listenF11 = false
exts."omni.kit.menu.common".external_kit_sdk_url = "https://docs.omniverse.nvidia.com/prod_kit/prod_kit/overview.html"
exts."omni.kit.menu.common".internal_kit_sdk_url = "https://omniverse.gitlab-master-pages.nvidia.com/omni-docs/prod_kit/prod_kit/overview.html"
exts."omni.kit.menu.common".external_kit_manual_url = "https://docs.omniverse.nvidia.com/py/kit/index.html"
exts."omni.kit.menu.common".internal_kit_manual_url = "https://omniverse-docs.s3-website-us-east-1.amazonaws.com/kit-manual/index-internal.html"
[[test]]
args = [
"--/renderer/enabled=pxr",
"--/renderer/active=pxr",
"--/renderer/multiGpu/enabled=false",
"--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611
"--/renderer/multiGpu/maxGpuCount=1",
"--/app/asyncRendering=false",
"--/app/file/ignoreUnsavedStage=true",
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--/app/menu/legacy_mode=false",
# "--no-window", # Need window for fullscreen tests
]
dependencies = [
"omni.hydra.pxr",
"omni.kit.renderer.capture",
"omni.kit.mainwindow",
"omni.kit.ui_test",
"omni.kit.material.library",
"omni.kit.viewport.utility",
"omni.kit.hotkeys.core"
]
stdoutFailPatterns.exclude = [
"*HydraRenderer failed to render this frame*", # Can drop a frame or two rendering with OpenGL interop
"*Cannot use omni.hydra.pxr without OpenGL interop*" # Linux TC configs with multi-GPU might not have OpenGL available
]
timeout = 900
| 2,579 |
TOML
| 34.342465 | 144 | 0.714618 |
omniverse-code/kit/exts/omni.kit.menu.common/omni/kit/menu/common/scripts/common.py
|
import omni.ext
import omni.kit.menu.utils
from .legacy_help import HelpExtension
from .legacy_window import WindowExtension
class CommonMenuExtension(omni.ext.IExt):
def on_startup(self, ext_id):
self._legacy_help = HelpExtension()
self._legacy_window = WindowExtension()
def on_shutdown(self):
del self._legacy_help
del self._legacy_window
| 385 |
Python
| 24.733332 | 47 | 0.706494 |
omniverse-code/kit/exts/omni.kit.menu.common/omni/kit/menu/common/scripts/legacy_window.py
|
import carb
import carb.input
import carb.settings
import omni.kit.ui
import omni.appwindow
import omni.kit.menu.utils
import omni.ui as ui
from carb.input import KeyboardInput as Key
class WindowExtension:
def __init__(self):
self._appwindow = omni.appwindow.get_default_app_window()
self._settings = carb.settings.get_settings()
self.WINDOW_UI_TOGGLE_VISIBILITY_MENU = "Window/UI Toggle Visibility"
self.WINDOW_FULLSCREEN_MODE_MENU = "Window/Fullscreen Mode"
self.WINDOW_DPI_SCALE_INCREASE_MENU = "Window/DPI Scale/Increase"
self.WINDOW_DPI_SCALE_DECREASE_MENU = "Window/DPI Scale/Decrease"
self.WINDOW_DPI_SCALE_RESET_MENU = "Window/DPI Scale/Reset"
self.SHOW_DPI_SCALE_MENU_SETTING = "/app/window/showDpiScaleMenu"
self.DPI_SCALE_OVERRIDE_SETTING = "/app/window/dpiScaleOverride"
self.DPI_SCALE_OVERRIDE_DEFAULT = -1.0
self.DPI_SCALE_OVERRIDE_MIN = 0.5
self.DPI_SCALE_OVERRIDE_MAX = 5.0
self.DPI_SCALE_OVERRIDE_STEP = 0.5
self.menus = []
menu = omni.kit.ui.get_editor_menu()
if menu:
window_ui_toggle_visibility_menu = menu.add_item(self.WINDOW_UI_TOGGLE_VISIBILITY_MENU, None, priority=51)
window_ui_toggle_visibility_action = omni.kit.menu.utils.add_action_to_menu(self.WINDOW_UI_TOGGLE_VISIBILITY_MENU, lambda *_: self.on_toggle_ui(), "UiToggle", (0, Key.F7))
self.menus.append((window_ui_toggle_visibility_menu, window_ui_toggle_visibility_action))
window_fullscreen_mode_menu = menu.add_item(self.WINDOW_FULLSCREEN_MODE_MENU, None, priority=52)
window_fullscreen_mode_menu_action = omni.kit.menu.utils.add_action_to_menu(self.WINDOW_FULLSCREEN_MODE_MENU, lambda *_: self.on_fullscreen(), "FullscreenMode", (0, Key.F11))
self.menus.append((window_fullscreen_mode_menu, window_fullscreen_mode_menu_action))
self._settings.set_default_bool(self.SHOW_DPI_SCALE_MENU_SETTING, False)
if self._settings.get_as_bool(self.SHOW_DPI_SCALE_MENU_SETTING):
window_dpi_scale_increase_menu = menu.add_item(self.WINDOW_DPI_SCALE_INCREASE_MENU, None, priority=53)
window_dpi_scale_increase_menu_action = omni.kit.menu.utils.add_action_to_menu(self.WINDOW_DPI_SCALE_INCREASE_MENU, lambda *_: self.on_dpi_scale_increase(), "DPIScaleIncrease", (carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, Key.EQUAL))
self.menus.append((window_dpi_scale_increase_menu, window_dpi_scale_increase_menu_action))
window_dpi_scale_decrease_menu = menu.add_item(self.WINDOW_DPI_SCALE_DECREASE_MENU, None, priority=54)
window_dpi_scale_decrease_menu_action = omni.kit.menu.utils.add_action_to_menu(self.WINDOW_DPI_SCALE_DECREASE_MENU, lambda *_: self.on_dpi_scale_decrease(), "DPIScaleDecrease", (carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, Key.MINUS))
self.menus.append((window_dpi_scale_decrease_menu, window_dpi_scale_decrease_menu_action))
window_dpi_scale_reset_menu = menu.add_item(self.WINDOW_DPI_SCALE_RESET_MENU, None, priority=55)
window_dpi_scale_reset_menu_action = omni.kit.menu.utils.add_action_to_menu(self.WINDOW_DPI_SCALE_RESET_MENU, lambda *_: self.on_dpi_scale_reset(), "DPIScaleReset")
self.menus.append((window_dpi_scale_reset_menu, window_dpi_scale_reset_menu_action))
# Sort top level menus:
menu.set_priority("Window", -6)
def __del__(self):
self.menus = None
def add_menu(self, *argv, **kwargs):
new_menu = omni.kit.ui.get_editor_menu().add_item(*argv, **kwargs)
self.menus.append(new_menu)
return new_menu
def set_ui_hidden(self, hide):
self._settings.set("/app/window/hideUi", hide)
def is_ui_hidden(self):
return self._settings.get("/app/window/hideUi")
def on_toggle_ui(self):
self.set_ui_hidden(not self.is_ui_hidden())
def on_fullscreen(self):
display_mode_lock = self._settings.get(f"/app/window/displayModeLock")
if display_mode_lock:
# Always stay in fullscreen_mode, only hide or show UI.
self.set_ui_hidden(not self.is_ui_hidden())
else:
# Only toggle fullscreen on/off when not display_mode_lock
was_fullscreen = self._appwindow.is_fullscreen()
self._appwindow.set_fullscreen(not was_fullscreen)
# Always hide UI in fullscreen
self.set_ui_hidden(not was_fullscreen)
def step_and_clamp_dpi_scale_override(self, increase):
# Get the current value.
dpi_scale = self._settings.get_as_float(self.DPI_SCALE_OVERRIDE_SETTING)
if dpi_scale == self.DPI_SCALE_OVERRIDE_DEFAULT:
dpi_scale = ui.Workspace.get_dpi_scale()
# Increase or decrease the current value by the setp value.
if increase:
dpi_scale += self.DPI_SCALE_OVERRIDE_STEP
else:
dpi_scale -= self.DPI_SCALE_OVERRIDE_STEP
# Clamp the new value between the min/max values.
dpi_scale = max(min(dpi_scale, self.DPI_SCALE_OVERRIDE_MAX), self.DPI_SCALE_OVERRIDE_MIN)
# Set the new value.
self._settings.set(self.DPI_SCALE_OVERRIDE_SETTING, dpi_scale)
def on_dpi_scale_increase(self):
self.step_and_clamp_dpi_scale_override(True)
def on_dpi_scale_decrease(self):
self.step_and_clamp_dpi_scale_override(False)
def on_dpi_scale_reset(self):
self._settings.set(self.DPI_SCALE_OVERRIDE_SETTING, self.DPI_SCALE_OVERRIDE_DEFAULT)
| 5,631 |
Python
| 48.840708 | 248 | 0.665068 |
omniverse-code/kit/exts/omni.kit.menu.common/omni/kit/menu/common/scripts/legacy_help.py
|
import webbrowser
import os
import carb
import carb.input
import carb.settings
import omni.kit.app
import omni.kit.menu.utils
from carb.input import KeyboardInput as Key
from omni.kit.menu.utils import MenuItemDescription
class HelpExtension:
def __init__(self):
def get_discover_kit_sdk_path(settings):
if omni.kit.app.get_app().is_app_external():
return settings.get("/exts/omni.kit.menu.common/external_kit_sdk_url")
else:
return settings.get("/exts/omni.kit.menu.common/internal_kit_sdk_url")
def get_manual_url_path(settings):
if omni.kit.app.get_app().is_app_external():
return settings.get("/exts/omni.kit.menu.common/external_kit_manual_url")
else:
return settings.get("/exts/omni.kit.menu.common/internal_kit_manual_url")
def get_discover_reference_guide_path(settings):
if omni.kit.app.get_app().is_app_external():
return settings.get("/exts/omni.kit.menu.common/external_reference_guide_url")
else:
return settings.get("/exts/omni.kit.menu.common/internal_reference_guide_url")
settings = carb.settings.get_settings()
discover_reference_guide_path = get_discover_reference_guide_path(settings)
discover_kit_sdk_path = get_discover_kit_sdk_path(settings)
manual_url_path = get_manual_url_path(settings)
self._register_actions("omni.kit.menu.common", discover_reference_guide_path, discover_kit_sdk_path, manual_url_path)
reference_guide_name = settings.get("/exts/omni.kit.menu.common/reference_guide_name")
kit_sdk_name = settings.get("/exts/omni.kit.menu.common/kit_sdk_name")
kit_manual_name = settings.get("/exts/omni.kit.menu.common/kit_manual_name")
self._help_menu = []
if reference_guide_name:
self._help_menu.append(MenuItemDescription(
name=reference_guide_name,
onclick_action=("omni.kit.menu.common", "OpenRefGuide"),
hotkey=(0, Key.F1),
enabled=False if reference_guide_name is None else True
))
if kit_sdk_name:
self._help_menu.append(MenuItemDescription(
name=kit_sdk_name,
onclick_action=("omni.kit.menu.common", "OpenDevKitSDK"),
enabled=False if discover_kit_sdk_path is None else True
))
if kit_manual_name:
self._help_menu.append(MenuItemDescription(
name=kit_manual_name,
onclick_action=("omni.kit.menu.common", "OpenDevManual"),
enabled=False if manual_url_path is None else True
))
if self._help_menu:
omni.kit.menu.utils.add_menu_items(self._help_menu, "Help", 99)
def __del__(self):
omni.kit.menu.utils.remove_menu_items(self._help_menu, "Help")
self._deregister_actions("omni.kit.menu.common")
self.menus = None
def _register_actions(self, extension_id, discover_reference_guide_path, discover_kit_sdk_path, manual_url_path):
action_registry = omni.kit.actions.core.get_action_registry()
actions_tag = "Help Menu Actions"
# actions
action_registry.register_action(
extension_id,
"OpenRefGuide",
lambda: webbrowser.open(discover_reference_guide_path),
display_name="Help->Reference Guide",
description="Reference Guide",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"OpenDevKitSDK",
lambda: webbrowser.open(discover_kit_sdk_path),
display_name="Help->Discover Kit SDK",
description="Discover Kit SDK",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"OpenDevManual",
lambda: webbrowser.open(manual_url_path),
display_name="Help->Developers Manual",
description="Developers Manual",
tag=actions_tag,
)
def _deregister_actions(self, extension_id):
action_registry = omni.kit.actions.core.get_action_registry()
if action_registry:
action_registry.deregister_all_actions_for_extension(extension_id)
| 4,436 |
Python
| 38.616071 | 125 | 0.606402 |
omniverse-code/kit/exts/omni.kit.menu.common/omni/kit/menu/common/scripts/__init__.py
|
from .common import *
| 22 |
Python
| 10.499995 | 21 | 0.727273 |
omniverse-code/kit/exts/omni.kit.menu.common/omni/kit/menu/common/tests/__init__.py
|
from .common_tests import *
| 28 |
Python
| 13.499993 | 27 | 0.75 |
omniverse-code/kit/exts/omni.kit.menu.common/omni/kit/menu/common/tests/test_func_common_window.py
|
import asyncio
import carb
import omni.usd
import omni.ui as ui
from omni.kit import ui_test
from carb.input import KeyboardInput
from omni.kit.menu.utils import MenuItemDescription, MenuLayout
from omni.kit.viewport.utility import get_active_viewport_window, get_num_viewports
DPI_SCALE_OVERRIDE_SETTING = "/app/window/dpiScaleOverride"
def get_hide_ui():
hide_ui = carb.settings.get_settings().get("/app/window/hideUi")
if hide_ui == None:
return False
return hide_ui
async def common_test_func_window_viewport(tester, menu_item = None):
# XXX: Unclear where this API is used, but it originally took an unused menu_item
if menu_item:
carb.log_error("common_test_func_window_new_viewport_window does not use a menu_item")
# Get the default Viewport name, most likely 'Viewport'
default_vp_window_name = carb.settings.get_settings().get("/exts/omni.kit.viewport.window/startup/windowName")
default_vp_window_name = default_vp_window_name or "Viewport"
window_menu = ui_test.get_menubar().find_menu("Window")
tester.assertIsNotNone(window_menu)
# There will always be a "Viewport" menu item, but on legacy it is a single item otherwise a sub-menu container
viewport_menu = window_menu.find_menu("Viewport")
tester.assertIsNotNone(viewport_menu)
# Build up the sub-menu (and full menu-path) that will be used
vp_menu_entry_name = f"{default_vp_window_name} 1"
full_default_vp_menu_path = f"Window/Viewport/{default_vp_window_name} 1"
# If it doesnt't exists as a child of the "Viewport" menu-item, assume legacy
vp_show_menu_entry = viewport_menu.find_menu(vp_menu_entry_name)
if not vp_show_menu_entry:
viewport_menu = window_menu
vp_menu_entry_name = default_vp_window_name
full_default_vp_menu_path = f"Window/{default_vp_window_name}"
vp_show_menu_entry = window_menu.find_menu(vp_menu_entry_name)
# Needs to be valid by now
tester.assertIsNotNone(vp_show_menu_entry)
# Pre-check that the Viewport Window can also be found
viewport_window = get_active_viewport_window(window_name=default_vp_window_name)
tester.assertIsNotNone(viewport_window)
# verify initial visibility and check state
tester.assertTrue(viewport_window.visible)
tester.assertTrue(vp_show_menu_entry.widget.checked)
# use menu
await ui_test.menu_click(full_default_vp_menu_path)
await ui_test.human_delay()
# verify
tester.assertFalse(viewport_window.visible)
tester.assertFalse(vp_show_menu_entry.widget.checked)
# use menu
await ui_test.menu_click(full_default_vp_menu_path)
await ui_test.human_delay()
# verify
tester.assertTrue(viewport_window.visible)
tester.assertTrue(vp_show_menu_entry.widget.checked)
async def common_test_func_window_ui_toggle_visibility(tester, menu_item: MenuItemDescription):
# verify default state
tester.assertTrue(get_hide_ui() == False)
# use menu
await ui_test.menu_click("Window/UI Toggle Visibility")
await ui_test.human_delay(50)
# verify state
tester.assertTrue(get_hide_ui() == True)
# cannot use menu so use hotkey instead
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state
tester.assertTrue(get_hide_ui() == False)
async def common_test_hotkey_func_window_ui_toggle_visibility(tester, menu_item: MenuItemDescription):
# verify default state
tester.assertTrue(get_hide_ui() == False)
# hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state
tester.assertTrue(get_hide_ui() == True)
# hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state
tester.assertTrue(get_hide_ui() == False)
async def common_test_func_window_fullscreen_mode(tester, menu_item: MenuItemDescription):
# verify default state
tester.assertTrue(omni.appwindow.get_default_app_window().is_fullscreen() == False)
# use menu
await ui_test.menu_click("Window/Fullscreen Mode")
await ui_test.human_delay(50)
# verify state
tester.assertTrue(omni.appwindow.get_default_app_window().is_fullscreen() == True)
# cannot use menu so use hotkey instead
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state
tester.assertTrue(omni.appwindow.get_default_app_window().is_fullscreen() == False)
async def common_test_hotkey_func_window_fullscreen_mode(tester, menu_item: MenuItemDescription):
# verify default state
tester.assertTrue(omni.appwindow.get_default_app_window().is_fullscreen() == False)
# hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state
tester.assertTrue(omni.appwindow.get_default_app_window().is_fullscreen() == True)
# hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state
tester.assertTrue(omni.appwindow.get_default_app_window().is_fullscreen() == False)
async def common_test_func_window_new_viewport_window(tester, menu_item = None):
# XXX: Unclear where this API is used, but it originally took an unused menu_item
if menu_item:
carb.log_error("common_test_func_window_new_viewport_window does not use a menu_item")
# verify default state
tester.assertEqual(get_num_viewports(), 1)
# All functionaliyt contained in Window menu
window_menu = ui_test.get_menubar().find_menu("Window")
tester.assertIsNotNone(window_menu)
# There will always be a "Viewport" menu item, but on legacy it is a single item otherwise a sub-menu container
viewport_menu = window_menu.find_menu("Viewport")
tester.assertIsNotNone(viewport_menu)
# use menu
if viewport_menu.find_menu("Viewport 2"):
await ui_test.menu_click("Window/Viewport/Viewport 2")
else:
await ui_test.menu_click("Window/New Viewport Window")
await ui_test.human_delay()
# verify
tester.assertEqual(get_num_viewports(), 2)
# close new viewport window
viewport_window = get_active_viewport_window(window_name="Viewport 2")
if viewport_window:
viewport_window.visible = False
viewport_window.destroy()
del viewport_window
async def common_test_func_window_dpi_scale_increase(tester, menu_item: MenuItemDescription):
# verify default state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0)
# use menu
await ui_test.menu_click("Window/DPI Scale/Increase")
await ui_test.human_delay(50)
# verify state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.5)
# cannot use menu so use hotkey instead
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 2.0)
# reset state
carb.settings.get_settings().set(DPI_SCALE_OVERRIDE_SETTING, 1.0)
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0)
async def common_test_hotkey_func_window_dpi_scale_increase(tester, menu_item: MenuItemDescription):
# verify default state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0)
# hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.5)
# hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 2.0)
# reset state
carb.settings.get_settings().set(DPI_SCALE_OVERRIDE_SETTING, 1.0)
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0)
async def common_test_func_window_dpi_scale_decrease(tester, menu_item: MenuItemDescription):
# verify default state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0)
# use menu
await ui_test.menu_click("Window/DPI Scale/Decrease")
await ui_test.human_delay(50)
# verify state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 0.5)
# cannot use menu so use hotkey instead
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state - still 0.5 because it gets clamped to the min
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 0.5)
# reset state
carb.settings.get_settings().set(DPI_SCALE_OVERRIDE_SETTING, 1.0)
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0)
async def common_test_hotkey_func_window_dpi_scale_decrease(tester, menu_item: MenuItemDescription):
# verify default state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0)
# hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 0.5)
# hotkey
await ui_test.emulate_keyboard_press(menu_item.hotkey[1], menu_item.hotkey[0])
await ui_test.human_delay(50)
# verify state - still 0.5 because it gets clamped to the min
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 0.5)
# reset state
carb.settings.get_settings().set(DPI_SCALE_OVERRIDE_SETTING, 1.0)
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0)
async def common_test_func_window_dpi_scale_reset(tester, menu_item: MenuItemDescription):
# verify default state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0)
# use menu
await ui_test.menu_click("Window/DPI Scale/Reset")
await ui_test.human_delay(50)
# verify state
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), -1.0)
# reset state
carb.settings.get_settings().set(DPI_SCALE_OVERRIDE_SETTING, 1.0)
tester.assertEqual(omni.appwindow.get_default_app_window().get_dpi_scale_override(), 1.0)
| 10,876 |
Python
| 36.506896 | 115 | 0.713406 |
omniverse-code/kit/exts/omni.kit.menu.common/omni/kit/menu/common/tests/test_func_common_help.py
|
import asyncio
import carb
import omni.usd
import omni.ui as ui
from omni.kit import ui_test
from omni.kit.menu.utils import MenuItemDescription, MenuLayout
async def common_test_func_help_usd_reference_guide(tester, menu_item: MenuItemDescription):
carb.log_warn("Help/USD Reference Guide - No test")
# don't know how to test this as it opens a webpage
async def common_test_hotkey_func_help_usd_reference_guide(tester, menu_item: MenuItemDescription):
carb.log_warn("Help/USD Reference Guide - No test")
# don't know how to test this as it opens a webpage
async def common_test_func_help_developers_manual(tester, menu_item: MenuItemDescription):
carb.log_warn("Help/Developers Manual - No test")
# don't know how to test this as it opens a webpage
async def common_test_func_help_discover_kit_sdk(tester, menu_item: MenuItemDescription):
carb.log_warn("Help/Discover Kit SDK - No test")
# don't know how to test this as it opens a webpage
| 983 |
Python
| 34.142856 | 99 | 0.748728 |
omniverse-code/kit/exts/omni.kit.menu.common/docs/CHANGELOG.md
|
# Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.3] - 2022-10-07
### Changes
- Adjust fullscreen test to work with hotkeys.core
- Add listenF11 setting for appwindow
## [1.0.2] - 2022-10-04
### Changes
- Test against new Viewport sub-menu
## [1.0.1] - 2022-05-23
### Changes
- Support legacy and new Viewport API
- Add dependency on omni.kit.viewport.utility
## [1.0.0] - 2021-11-16
### Changes
- Created from python/extensions-bundled/omni/kit/builtin/menu.py
| 518 |
Markdown
| 22.590908 | 80 | 0.698842 |
omniverse-code/kit/exts/omni.kit.menu.common/docs/index.rst
|
omni.kit.menu.common
###########################
Common Menu
.. toctree::
:maxdepth: 1
CHANGELOG
| 111 |
reStructuredText
| 6.466666 | 27 | 0.468468 |
omniverse-code/kit/exts/omni.appwindow/omni/appwindow/__init__.py
|
import carb.events
from ._appwindow import *
| 45 |
Python
| 14.333329 | 25 | 0.777778 |
omniverse-code/kit/exts/omni.appwindow/omni/appwindow/_appwindow.pyi
|
from __future__ import annotations
import omni.appwindow._appwindow
import typing
import carb._carb
import carb.events._events
__all__ = [
"IAppWindow",
"IAppWindowFactory",
"POSITION_CENTERED",
"POSITION_UNSET",
"WindowType",
"acquire_app_window_factory_interface",
"get_default_app_window"
]
class IAppWindow():
def broadcast_input_blocking_state(self, arg0: bool) -> None: ...
def get_action_mapping_set_path(self) -> str: ...
def get_clipboard(self) -> str: ...
def get_cursor_blink(self) -> bool: ...
def get_dpi_scale(self) -> float: ...
def get_dpi_scale_override(self) -> float: ...
@staticmethod
def get_gamepad(*args, **kwargs) -> typing.Any: ...
def get_height(self) -> int: ...
@staticmethod
def get_input_blocking_state(*args, **kwargs) -> typing.Any: ...
@staticmethod
def get_keyboard(*args, **kwargs) -> typing.Any: ...
@staticmethod
def get_mouse(*args, **kwargs) -> typing.Any: ...
def get_position(self) -> carb._carb.Int2: ...
def get_size(self) -> carb._carb.Uint2: ...
def get_title(self) -> str: ...
def get_ui_scale(self) -> float: ...
def get_width(self) -> int: ...
@staticmethod
def get_window(*args, **kwargs) -> typing.Any: ...
def get_window_close_event_stream(self) -> carb.events._events.IEventStream: ...
def get_window_content_scale_event_stream(self) -> carb.events._events.IEventStream: ...
def get_window_drop_event_stream(self) -> carb.events._events.IEventStream: ...
def get_window_focus_event_stream(self) -> carb.events._events.IEventStream: ...
def get_window_minimize_event_stream(self) -> carb.events._events.IEventStream: ...
def get_window_move_event_stream(self) -> carb.events._events.IEventStream: ...
def get_window_resize_event_stream(self) -> carb.events._events.IEventStream: ...
def is_fullscreen(self) -> bool: ...
def is_maximized(self) -> bool: ...
def maximize_window(self) -> None: ...
def move(self, arg0: int, arg1: int) -> None: ...
def resize(self, arg0: int, arg1: int) -> None: ...
def restore_window(self) -> None: ...
def set_clipboard(self, arg0: str) -> None: ...
def set_dpi_scale_override(self, arg0: float) -> None: ...
def set_fullscreen(self, arg0: bool) -> None: ...
@staticmethod
def set_input_blocking_state(*args, **kwargs) -> typing.Any: ...
def shutdown(self) -> bool: ...
def startup(self, name: str = '') -> bool: ...
def startup_with_desc(self, title: str, width: int, height: int, x: int = 18446744073709551614, y: int = 18446744073709551614, decorations: bool = True, resize: bool = True, always_on_top: bool = False, scale_to_monitor: bool = True, dpi_scale_override: float = -1.0, cursor_blink: bool = True) -> None: ...
def update(self, arg0: float) -> None: ...
@property
def ui_scale_multiplier(self) -> float:
"""
:type: float
"""
@ui_scale_multiplier.setter
def ui_scale_multiplier(self, arg1: float) -> None:
pass
pass
class IAppWindowFactory():
def create_window_by_type(self, arg0: WindowType) -> IAppWindow: ...
def create_window_from_settings(self) -> IAppWindow: ...
def create_window_ptr_by_type(self, arg0: WindowType) -> IAppWindow: ...
def create_window_ptr_from_settings(self) -> IAppWindow: ...
def destroy_window_ptr(self, arg0: IAppWindow) -> None: ...
def get_app_window(self) -> IAppWindow: ...
def get_default_window(self) -> IAppWindow: ...
def get_window_at(self, arg0: int) -> IAppWindow: ...
def get_window_count(self) -> int: ...
def get_windows(self) -> tuple: ...
def set_default_window(self, arg0: IAppWindow) -> None: ...
pass
class WindowType():
"""
Members:
OS
VIRTUAL
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
OS: omni.appwindow._appwindow.WindowType # value = <WindowType.OS: 1>
VIRTUAL: omni.appwindow._appwindow.WindowType # value = <WindowType.VIRTUAL: 0>
__members__: dict # value = {'OS': <WindowType.OS: 1>, 'VIRTUAL': <WindowType.VIRTUAL: 0>}
pass
def acquire_app_window_factory_interface(*args, **kwargs) -> typing.Any:
pass
def get_default_app_window(*args, **kwargs) -> typing.Any:
pass
POSITION_CENTERED = 18446744073709551615
POSITION_UNSET = 18446744073709551614
| 4,864 |
unknown
| 38.877049 | 311 | 0.609581 |
omniverse-code/kit/exts/omni.appwindow/omni/appwindow/tests/test_appwindow.py
|
import omni.kit.app
import omni.kit.test
import carb.windowing
import carb.settings
import omni.appwindow
WINDOW_ENABLED_PATH = "/app/window/enabled"
LINUX_WM_LATENCY_MAX = 100
class Test(omni.kit.test.AsyncTestCase):
async def setUp(self):
self._windowing = carb.windowing.acquire_windowing_interface()
self._app_window_factory = omni.appwindow.acquire_app_window_factory_interface()
self._settings = carb.settings.acquire_settings_interface()
async def tearDown(self):
self._app_window_factory = None
def _cmp_vectors_and_delta(self, vec_result, vec_base, delta):
return (vec_result[0] == vec_base[0] + delta[0]) and (vec_result[1] == vec_base[1] + delta[1])
async def test_create_os_window(self):
self._app_window = self._app_window_factory.create_window_from_settings()
self._app_window.startup_with_desc(
title="Test OS window",
width=100,
height=100,
x=omni.appwindow.POSITION_CENTERED,
y=omni.appwindow.POSITION_CENTERED,
decorations=True,
resize=True,
always_on_top=False,
scale_to_monitor=False,
dpi_scale_override=-1.0
)
self._native_app_window = self._app_window.get_window()
self.assertNotEqual(self._native_app_window, None)
self._windowing.show_window(self._native_app_window)
await omni.kit.app.get_app().next_update_async()
self._app_window.shutdown()
self._app_window = None
async def test_create_virtual_window(self):
is_window_enabled = self._settings.get(WINDOW_ENABLED_PATH)
self._settings.set(WINDOW_ENABLED_PATH, False)
self._app_window = self._app_window_factory.create_window_from_settings()
self._app_window.startup_with_desc(
title="Test virtual window",
width=100,
height=100,
x=omni.appwindow.POSITION_CENTERED,
y=omni.appwindow.POSITION_CENTERED,
decorations=True,
resize=True,
always_on_top=False,
scale_to_monitor=False,
dpi_scale_override=-1.0
)
self._native_app_window = self._app_window.get_window()
self.assertEqual(self._native_app_window, None)
await omni.kit.app.get_app().next_update_async()
self._app_window.shutdown()
self._app_window = None
self._settings.set(WINDOW_ENABLED_PATH, is_window_enabled)
async def test_move_os_window(self):
self._app_window = self._app_window_factory.create_window_from_settings()
self._app_window.startup_with_desc(
title="Test OS window",
width=100,
height=100,
x=omni.appwindow.POSITION_CENTERED,
y=omni.appwindow.POSITION_CENTERED,
decorations=True,
resize=True,
always_on_top=False,
scale_to_monitor=False,
dpi_scale_override=-1.0
)
self._native_app_window = self._app_window.get_window()
self.assertNotEqual(self._native_app_window, None)
self._windowing.show_window(self._native_app_window)
move_delta = [10, 20]
pos = self._app_window.get_position()
pos_native = self._windowing.get_window_position(self._native_app_window)
self.assertEqual(pos_native[0], pos[0])
self.assertEqual(pos_native[1], pos[1])
self._app_window.move(pos[0] + move_delta[0], pos[1] + move_delta[1])
for i in range(LINUX_WM_LATENCY_MAX):
await omni.kit.app.get_app().next_update_async()
# This code is needed due to Linux WM latency; window operations do not happen
# immediately, and not deterministically
new_pos = self._app_window.get_position()
move_happened = self._cmp_vectors_and_delta(new_pos, pos, move_delta)
if move_happened:
break
new_pos = self._app_window.get_position()
new_pos_native = self._windowing.get_window_position(self._native_app_window)
self.assertEqual(new_pos[0], pos[0] + move_delta[0])
self.assertEqual(new_pos[1], pos[1] + move_delta[1])
self.assertEqual(new_pos_native[0], new_pos[0])
self.assertEqual(new_pos_native[1], new_pos[1])
self._app_window.shutdown()
self._app_window = None
async def test_resize_os_window(self):
self._app_window = self._app_window_factory.create_window_from_settings()
self._app_window.startup_with_desc(
title="Test OS window",
width=100,
height=100,
x=omni.appwindow.POSITION_CENTERED,
y=omni.appwindow.POSITION_CENTERED,
decorations=True,
resize=True,
always_on_top=False,
scale_to_monitor=False,
dpi_scale_override=-1.0
)
self._native_app_window = self._app_window.get_window()
self.assertNotEqual(self._native_app_window, None)
self._windowing.show_window(self._native_app_window)
resize_delta = [10, 20]
size = self._app_window.get_size()
size_native = [self._windowing.get_window_width(self._native_app_window), self._windowing.get_window_height(self._native_app_window)]
self.assertEqual(size_native[0], size[0])
self.assertEqual(size_native[1], size[1])
self._app_window.resize(size[0] + resize_delta[0], size[1] + resize_delta[1])
for i in range(LINUX_WM_LATENCY_MAX):
await omni.kit.app.get_app().next_update_async()
# This code is needed due to Linux WM latency; window operations do not happen
# immediately, and not deterministically
new_size = self._app_window.get_size()
resize_happened = self._cmp_vectors_and_delta(new_size, size, resize_delta)
if resize_happened:
break
new_size = self._app_window.get_size()
new_size_native = [self._windowing.get_window_width(self._native_app_window), self._windowing.get_window_height(self._native_app_window)]
self.assertEqual(new_size[0], size[0] + resize_delta[0])
self.assertEqual(new_size[1], size[1] + resize_delta[1])
self.assertEqual(new_size_native[0], new_size[0])
self.assertEqual(new_size_native[1], new_size[1])
self._app_window.shutdown()
self._app_window = None
async def test_multiple_os_windows(self):
self._app_window1 = self._app_window_factory.create_window_from_settings()
self._app_window1.startup_with_desc(
title="Test OS window",
width=100,
height=100,
x=omni.appwindow.POSITION_CENTERED,
y=omni.appwindow.POSITION_CENTERED,
decorations=True,
resize=True,
always_on_top=False,
scale_to_monitor=False,
dpi_scale_override=-1.0
)
self._native_app_window1 = self._app_window1.get_window()
self.assertNotEqual(self._native_app_window1, None)
self._windowing.show_window(self._native_app_window1)
self._app_window2 = self._app_window_factory.create_window_from_settings()
self._app_window2.startup_with_desc(
title="Test OS window",
width=100,
height=100,
x=omni.appwindow.POSITION_CENTERED,
y=omni.appwindow.POSITION_CENTERED,
decorations=True,
resize=True,
always_on_top=False,
scale_to_monitor=False,
dpi_scale_override=-1.0
)
self._native_app_window2 = self._app_window2.get_window()
self.assertNotEqual(self._native_app_window2, None)
self._windowing.show_window(self._native_app_window2)
resize_delta = [30, 40]
size = self._app_window1.get_size()
size_native = [self._windowing.get_window_width(self._native_app_window1), self._windowing.get_window_height(self._native_app_window1)]
self.assertEqual(size_native[0], size[0])
self.assertEqual(size_native[1], size[1])
move_delta = [50, 60]
pos = self._app_window2.get_position()
pos_native = self._windowing.get_window_position(self._native_app_window2)
self.assertEqual(pos_native[0], pos[0])
self.assertEqual(pos_native[1], pos[1])
self._app_window1.resize(size[0] + resize_delta[0], size[1] + resize_delta[1])
self._app_window2.move(pos[0] + move_delta[0], pos[1] + move_delta[1])
for i in range(LINUX_WM_LATENCY_MAX):
await omni.kit.app.get_app().next_update_async()
# This code is needed due to Linux WM latency; window operations do not happen
# immediately, and not deterministically
new_size = self._app_window1.get_size()
new_pos = self._app_window2.get_position()
resize_happened = self._cmp_vectors_and_delta(new_size, size, resize_delta)
move_happened = self._cmp_vectors_and_delta(new_pos, pos, move_delta)
if resize_happened and move_happened:
break
new_size = self._app_window1.get_size()
new_size_native = [self._windowing.get_window_width(self._native_app_window1), self._windowing.get_window_height(self._native_app_window1)]
self.assertEqual(new_size[0], size[0] + resize_delta[0])
self.assertEqual(new_size[1], size[1] + resize_delta[1])
self.assertEqual(new_size_native[0], new_size[0])
self.assertEqual(new_size_native[1], new_size[1])
new_pos = self._app_window2.get_position()
new_pos_native = self._windowing.get_window_position(self._native_app_window2)
self.assertEqual(new_pos[0], pos[0] + move_delta[0])
self.assertEqual(new_pos[1], pos[1] + move_delta[1])
self.assertEqual(new_pos_native[0], new_pos[0])
self.assertEqual(new_pos_native[1], new_pos[1])
self._app_window1.shutdown()
self._app_window2.shutdown()
self._app_window1 = None
self._app_window2 = None
async def test_create_no_cursor_blink_window(self):
self._app_window = self._app_window_factory.create_window_from_settings()
self._app_window.startup_with_desc(
title="Test window, no cursor blink set",
width=100,
height=100,
x=omni.appwindow.POSITION_CENTERED,
y=omni.appwindow.POSITION_CENTERED,
decorations=True,
resize=True,
always_on_top=False,
scale_to_monitor=False,
dpi_scale_override=-1.0,
cursor_blink=False
)
self._native_app_window = self._app_window.get_window()
self.assertNotEqual(self._native_app_window, None)
self._windowing.show_window(self._native_app_window)
await omni.kit.app.get_app().next_update_async()
self.assertFalse(self._app_window.get_cursor_blink())
self._app_window.shutdown()
self._app_window = None
| 11,127 |
Python
| 40.992453 | 147 | 0.609329 |
omniverse-code/kit/exts/omni.appwindow/omni/appwindow/tests/__init__.py
|
from .test_appwindow import *
| 30 |
Python
| 14.499993 | 29 | 0.766667 |
omniverse-code/kit/exts/omni.kit.window.stage/config/extension.toml
|
[package]
title = "Kit Stage Window"
description = "Omniverse Kit Stage Window"
version = "2.3.12"
category = "Internal"
feature = true
authors = ["NVIDIA"]
repository = ""
keywords = ["stage", "outliner", "scene"]
changelog = "docs/CHANGELOG.md"
[dependencies]
"omni.ui" = {}
"omni.usd" = {}
"omni.kit.widget.stage" = {}
"omni.kit.widget.stage_icons" = {}
"omni.kit.window.drop_support" = {}
"omni.kit.menu.utils" = {}
[[python.module]]
name = "omni.kit.window.stage"
# Additional python module with tests, to make them discoverable by test system.
[[python.module]]
name = "omni.kit.window.stage.tests"
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.kit.mainwindow",
"omni.kit.renderer.capture",
"omni.kit.ui_test"
]
| 834 |
TOML
| 20.410256 | 80 | 0.659472 |
omniverse-code/kit/exts/omni.kit.window.stage/omni/kit/window/stage/stage_extension.py
|
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["StageExtension"]
import asyncio
import omni.ext
import omni.kit.ui
import omni.ui as ui
from omni.kit.menu.utils import MenuItemDescription
from .stage_window import StageWindow
class StageExtension(omni.ext.IExt):
"""The entry point for Stage Window"""
WINDOW_NAME = "Stage"
MENU_GROUP = "Window"
def on_startup(self):
self._window = None
ui.Workspace.set_show_window_fn(StageExtension.WINDOW_NAME, self.show_window)
self._menu = [MenuItemDescription(
name=StageExtension.WINDOW_NAME,
ticked=True, # menu item is ticked
ticked_fn=self._is_visible, # gets called when the menu needs to get the state of the ticked menu
onclick_fn=self._toggle_window
)]
omni.kit.menu.utils.add_menu_items(self._menu, name=StageExtension.MENU_GROUP)
ui.Workspace.show_window(StageExtension.WINDOW_NAME)
def on_shutdown(self):
omni.kit.menu.utils.remove_menu_items(self._menu, name=StageExtension.MENU_GROUP)
self._menu = None
if self._window:
self._window.destroy()
self._window = None
ui.Workspace.set_show_window_fn(StageExtension.WINDOW_NAME, None)
def _set_menu(self, value):
"""Set the menu to create this window on and off"""
# this only tags test menu to update when menu is opening, so it
# doesn't matter that is called before window has been destroyed
omni.kit.menu.utils.refresh_menu_items(StageExtension.MENU_GROUP)
async def _destroy_window_async(self):
# wait one frame, this is due to the one frame defer
# in Window::_moveToMainOSWindow()
await omni.kit.app.get_app().next_update_async()
if self._window:
self._window.destroy()
self._window = None
def _visiblity_changed_fn(self, visible):
self._set_menu(visible)
if not visible:
# Destroy the window, since we are creating new window
# in show_window
asyncio.ensure_future(self._destroy_window_async())
def show_window(self, value):
if value:
self._window = StageWindow()
self._window.set_visibility_changed_listener(self._visiblity_changed_fn)
elif self._window:
self._window.visible = False
def _is_visible(self) -> bool:
return False if self._window is None else self._window.visible
def _toggle_window(self):
if self._is_visible():
self.show_window(False)
else:
self.show_window(True)
| 3,049 |
Python
| 35.309523 | 109 | 0.654969 |
omniverse-code/kit/exts/omni.kit.window.stage/omni/kit/window/stage/external_drag_drop_helper.py
|
import omni.ui as ui
from typing import List
from pxr import Sdf
from omni.kit.window.drop_support import ExternalDragDrop
external_drag_drop = None
def setup_external_drag_drop(window_name :str, stage_widget):
global external_drag_drop
destroy_external_drag_drop()
external_drag_drop = ExternalDragDrop(window_name=window_name,
drag_drop_fn=lambda e, p, m=stage_widget.get_model(): _on_ext_drag_drop(e, p, m))
def destroy_external_drag_drop():
global external_drag_drop
if external_drag_drop:
external_drag_drop.destroy()
external_drag_drop = None
def _on_ext_drag_drop(edd: ExternalDragDrop, payload: List[str], model: ui.AbstractItemModel):
import omni.usd
default_prim_path = Sdf.Path("/")
stage = omni.usd.get_context().get_stage()
if stage.HasDefaultPrim():
default_prim_path = stage.GetDefaultPrim().GetPath()
target_item = model.find(default_prim_path)
for file_path in edd.expand_payload(payload):
model.drop(target_item, file_path.replace("\\", "/"))
| 1,088 |
Python
| 31.029411 | 123 | 0.674632 |
omniverse-code/kit/exts/omni.kit.window.stage/omni/kit/window/stage/stage_window.py
|
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["StageWindow"]
from .selection_watch import SelectionWatch
from .external_drag_drop_helper import setup_external_drag_drop, destroy_external_drag_drop
from .stage_settings import StageSettings
from omni.kit.widget.stage import StageWidget
from typing import List
from typing import Optional
from typing import Tuple
from pxr import Usd
import carb.events
import carb.settings
import omni.ui as ui
import omni.usd
class CustomizedStageWidget(StageWidget):
@StageWidget.show_prim_display_name.setter
def show_prim_display_name(self, value):
StageWidget.show_prim_display_name.fset(self, value)
StageSettings().show_prim_displayname = value
@StageWidget.children_reorder_supported.setter
def children_reorder_supported(self, value):
StageWidget.children_reorder_supported.fset(self, value)
StageSettings().should_keep_children_order = value
@StageWidget.auto_reload_prims.setter
def auto_reload_prims(self, value):
StageWidget.auto_reload_prims.fset(self, value)
StageSettings().auto_reload_prims = value
def get_treeview(self):
return self._tree_view
def get_delegate(self):
return self._delegate
class StageWindow(ui.Window):
"""The Stage window"""
def __init__(self, usd_context_name: str = ""):
self._usd_context = omni.usd.get_context(usd_context_name)
self._visiblity_changed_listener = None
super().__init__(
"Stage",
width=600,
height=800,
flags=ui.WINDOW_FLAGS_NO_SCROLLBAR,
dockPreference=ui.DockPreference.RIGHT_TOP,
)
self.set_visibility_changed_fn(self._visibility_changed_fn)
# Dock it to the same space where Layers is docked, make it the first tab and the active tab.
self.deferred_dock_in("Layers", ui.DockPolicy.CURRENT_WINDOW_IS_ACTIVE)
self.dock_order = 0
# Get list of columns from settings
self._settings = carb.settings.get_settings()
self._columns_settings_path = "/persistent/exts/omni.kit.window.stage/columns"
columns: Optional[str] = self._settings.get(self._columns_settings_path)
if columns is None:
# By default Visibility and Type are enabled columns
self._columns = ["Visibility","Type"]
else:
self._columns = columns.split("|")
with self.frame:
self._stage_widget = CustomizedStageWidget(
None, columns_enabled=self._columns,
children_reorder_supported=StageSettings().should_keep_children_order,
show_prim_display_name=StageSettings().show_prim_displayname,
auto_reload_prims=StageSettings().auto_reload_prims
)
# The Open/Close Stage logic
self._stage_subscription = self._usd_context.get_stage_event_stream().create_subscription_to_pop(
self._on_usd_context_event, name="Stage Window USD Stage Open/Closing Listening"
)
self._on_stage_opened()
# The selection logic
self._selection = SelectionWatch(usd_context=self._usd_context)
self._stage_widget.set_selection_watch(self._selection)
# Callback when columns are changed or toggled
self._columns_changed_sub = self._stage_widget.subscribe_columns_changed(self._columns_changed)
def _columns_changed(self, columns: List[Tuple[str, bool]]):
"""
Called by StageWidget when columns are changed or toggled.
"""
enabled_columns = [c[0] for c in columns if c[1]]
self._settings.set_string(self._columns_settings_path, "|".join(enabled_columns))
def _visibility_changed_fn(self, visible):
if self._visiblity_changed_listener:
self._visiblity_changed_listener(visible)
if not visible:
if self._selection:
self._selection.destroy()
self._selection = None
else:
self._selection = SelectionWatch(usd_context=self._usd_context)
if self._stage_widget:
self._stage_widget.set_selection_watch(self._selection)
def set_visibility_changed_listener(self, listener):
self._visiblity_changed_listener = listener
def destroy(self):
"""
Called by extension before destroying this object. It doesn't happen automatically.
Without this hot reloading doesn't work.
"""
self._visiblity_changed_listener = None
if self._selection:
self._selection._tree_view = None
self._selection._events = None
self._selection._stage_event_sub = None
self._selection = None
self._stage_widget.destroy()
self._stage_widget = None
self._stage_subscription = None
self._settings = None
self._columns_changed_sub = None
super().destroy()
destroy_external_drag_drop()
def _on_usd_context_event(self, event: carb.events.IEvent):
"""Called on USD Context event"""
if event.type == int(omni.usd.StageEventType.OPENED):
self._on_stage_opened()
elif event.type == int(omni.usd.StageEventType.CLOSING):
self._on_stage_closing()
def _on_stage_opened(self):
"""Called when opening a new stage"""
stage = self._usd_context.get_stage()
if not stage:
return
self._stage_widget.open_stage(stage)
setup_external_drag_drop("Stage", self._stage_widget)
def _on_stage_closing(self):
"""Called when close the stage"""
self._stage_widget.open_stage(None)
setup_external_drag_drop("Stage", self._stage_widget)
def get_widget(self) -> CustomizedStageWidget:
return self._stage_widget
| 6,244 |
Python
| 36.172619 | 105 | 0.653107 |
omniverse-code/kit/exts/omni.kit.window.stage/omni/kit/window/stage/stage_settings.py
|
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
# Selection Watch implementation has been moved omni.kit.widget.stage.
# Import it here for keeping back compatibility.
import carb.settings
import omni.kit.usd.layers as layers
from .singleton import Singleton
SETTINGS_SHOW_PRIM_DISPLAYNAME = "/persistent/ext/omni.kit.widget.stage/show_prim_displayname"
SETTINGS_KEEP_CHILDREN_ORDER = "/persistent/ext/omni.usd/keep_children_order"
@Singleton
class StageSettings:
def __init__(self):
super().__init__()
self._settings = carb.settings.get_settings()
self._settings.set_default_bool(SETTINGS_SHOW_PRIM_DISPLAYNAME, False)
self._settings.set_default_bool(layers.SETTINGS_AUTO_RELOAD_NON_SUBLAYERS, False)
self._settings.set_default_bool(SETTINGS_KEEP_CHILDREN_ORDER, False)
@property
def show_prim_displayname(self):
return self._settings.get_as_bool(SETTINGS_SHOW_PRIM_DISPLAYNAME)
@show_prim_displayname.setter
def show_prim_displayname(self, enabled: bool):
self._settings.set(SETTINGS_SHOW_PRIM_DISPLAYNAME, enabled)
@property
def auto_reload_prims(self):
return self._settings.get_as_bool(layers.SETTINGS_AUTO_RELOAD_NON_SUBLAYERS)
@auto_reload_prims.setter
def auto_reload_prims(self, enabled: bool):
self._settings.set(layers.SETTINGS_AUTO_RELOAD_NON_SUBLAYERS, enabled)
@property
def should_keep_children_order(self):
return self._settings.get_as_bool(SETTINGS_KEEP_CHILDREN_ORDER)
@should_keep_children_order.setter
def should_keep_children_order(self, value):
self._settings.set(SETTINGS_KEEP_CHILDREN_ORDER, value)
| 2,068 |
Python
| 37.314814 | 94 | 0.738878 |
omniverse-code/kit/exts/omni.kit.window.stage/omni/kit/window/stage/tests/stage_window_test.py
|
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
import carb
import omni.kit.app
import omni.ui as ui
import omni.usd
import omni.kit.commands
from omni.kit import ui_test
from unittest.mock import Mock, patch, ANY
from ..stage_window import StageWindow
CURRENT_PATH = Path(__file__).parent.joinpath("../../../../../data")
class TestStageWindow(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
self._golden_img_dir = CURRENT_PATH.absolute().resolve().joinpath("tests")
self._w = ui.Workspace.get_window("Stage")
self._usd_context = omni.usd.get_context()
# After running each test
async def tearDown(self):
self._w = None
self._golden_img_dir = None
await super().tearDown()
async def test_general(self):
# New stage with a sphere
await self._usd_context.new_stage_async()
omni.kit.commands.execute("CreatePrim", prim_path="/Sphere", prim_type="Sphere", select_new_prim=False)
# Loading icon takes time.
# TODO: We need a mode that blocks UI until icons are loaded
await self.wait(10)
await self.docked_test_window(
window=self._w,
width=450,
height=100,
restore_window=ui.Workspace.get_window("Layer"),
restore_position=ui.DockPosition.SAME,
)
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def test_multi_visibility_change(self):
"""Testing visibility of StageWidget"""
await self.docked_test_window(
window=self._w,
width=450,
height=200,
)
# New stage with three prims
await self._usd_context.new_stage_async()
omni.kit.commands.execute("CreatePrim", prim_path="/A", prim_type="Sphere", select_new_prim=False)
omni.kit.commands.execute("CreatePrim", prim_path="/B", prim_type="Sphere", select_new_prim=False)
omni.kit.commands.execute("CreatePrim", prim_path="/C", prim_type="Sphere", select_new_prim=False)
await ui_test.wait_n_updates(5)
# select both A and C
self._usd_context.get_selection().set_selected_prim_paths(["/A", "/C"], True)
# make A invisible
await ui_test.wait_n_updates(5)
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
eye_icon = stage_widget.find_all("**/ToolButton[*]")[0]
await eye_icon.click()
await ui_test.wait_n_updates(5)
# check C will also be invisible
await self.finalize_test(golden_img_dir=self._golden_img_dir)
async def wait(self, n=100):
for i in range(n):
await omni.kit.app.get_app().next_update_async()
async def test_header_columns(self):
from omni.kit import ui_test
await ui_test.find("Stage").focus()
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
name_column = stage_widget.find("**/Label[*].text=='Name (Old to New)'")
self.assertTrue(name_column)
await ui_test.emulate_mouse_move(name_column.center)
await name_column.right_click()
with self.assertRaises(Exception):
await ui_test.select_context_menu("Create")
await self.wait()
await name_column.click()
await self.wait()
name_column = stage_widget.find("**/Label[*].text=='Name (A to Z)'")
self.assertTrue(name_column)
await name_column.click()
await self.wait()
name_column = stage_widget.find("**/Label[*].text=='Name (Z to A)'")
self.assertTrue(name_column)
await name_column.click()
await self.wait()
name_column = stage_widget.find("**/Label[*].text=='Name (New to Old)'")
self.assertTrue(name_column)
await name_column.click()
await self.wait()
name_column = stage_widget.find("**/Label[*].text=='Name (Old to New)'")
self.assertTrue(name_column)
await self.finalize_test_no_image()
async def test_rename_with_context_menu(self):
from omni.kit import ui_test
await ui_test.find("Stage").focus()
stage_widget = ui_test.find("Stage//Frame/**/ScrollingFrame/TreeView[*].visible==True")
# New stage with three prims
await self._usd_context.new_stage_async()
stage = omni.usd.get_context().get_stage()
stage.GetRootLayer().Clear()
await ui_test.wait_n_updates(5)
prim = stage.DefinePrim("/test", "Xform")
await ui_test.wait_n_updates(5)
prim_item = stage_widget.find("**/Label[*].text=='test'")
self.assertTrue(prim_item)
prim_name_field = stage_widget.find("**/StringField[*].identifier=='rename_field'")
self.assertTrue(prim_name_field)
await prim_item.double_click()
self.assertTrue(prim_name_field.widget.selected)
prim_name_field.model.set_value("")
await prim_name_field.input("test2")
await ui_test.input.emulate_keyboard_press(carb.input.KeyboardInput.ENTER)
await ui_test.wait_n_updates(5)
old_prim = stage.GetPrimAtPath("/test")
self.assertFalse(old_prim)
new_prim = stage.GetPrimAtPath("/test2")
self.assertTrue(new_prim)
# Rename with context menu
prim_item = stage_widget.find("**/Label[*].text=='test2'")
self.assertTrue(prim_item)
prim_name_field = stage_widget.find("**/StringField[*].identifier=='rename_field'")
self.assertTrue(prim_name_field)
await prim_item.right_click()
await ui_test.select_context_menu("Rename")
self.assertTrue(prim_name_field.widget.selected)
await prim_name_field.input("test3")
await ui_test.input.emulate_keyboard_press(carb.input.KeyboardInput.ENTER)
await ui_test.wait_n_updates(5)
old_prim = stage.GetPrimAtPath("/test")
self.assertFalse(old_prim)
new_prim = stage.GetPrimAtPath("/test2test3")
self.assertTrue(new_prim)
await self.finalize_test_no_image()
async def test_window_destroyed_when_hidden(self):
"""Test that hiding stage window destroys it, and showing creates a new instance."""
ui.Workspace.show_window("Stage")
self.assertTrue(ui.Workspace.get_window("Stage").visible)
with patch.object(StageWindow, "destroy", autospec=True) as mock_destroy_dialog:
ui.Workspace.show_window("Stage", False)
await ui_test.wait_n_updates(5)
mock_destroy_dialog.assert_called()
self.assertFalse(ui.Workspace.get_window("Stage").visible)
await self.finalize_test_no_image()
| 7,238 |
Python
| 37.505319 | 111 | 0.63664 |
omniverse-code/kit/exts/omni.kit.window.stage/docs/CHANGELOG.md
|
# Changelog
## [2.3.12] - 2023-01-11
### Added
- Move SelectionWatch into omni.kit.widget.stage to provide default implementation.
## [2.3.11] - 2022-11-29
### Added
- Unitests for header of name column.
## [2.3.10] - 2022-11-01
### Added
- Test for renaming prim.
## [2.3.9] - 2022-09-30
### Fixed
- Set the menu checkbox when the window is appearing
## [2.3.8] - 2022-08-04
### Added
- Test for toggling visibility for multiple prims
## [2.3.7] - 2022-05-24
### Changed
- Optimize selection of stage window by reducing allocations of Sdf.Path.
## [2.3.6] - 2022-03-03
### Changed
- Use command for selection in widget so it can be undoable.
## [2.3.5] - 2021-10-20
### Changed
- External drag/drop doesn't use windows slashes
## [2.3.4] - 2021-05-25
### Fixed
- Bug when hide and show the Stage window
## [2.3.3] - 2021-04-27
## Removed
- `omni.stageupdate` is deprecated and doesn't work well with multiple usd
contexts
## [2.3.2] - 2020-11-19
### Changed
- Refusing selection of grayed prims in search mode
## [2.3.1] - 2020-10-22
### Added
- Dependency on omni.kit.widget.stage_icons
## [2.3.0] - 2020-09-16
### Changed
- Split to two parts: omni.kit.widget.stage and omni.kit.window.stage
## [2.2.0] - 2020-09-15
### Changed
- Detached from Editor and using UsdNotice for notifications
| 1,310 |
Markdown
| 21.220339 | 83 | 0.670229 |
omniverse-code/kit/exts/omni.kit.procedural.mesh/config/extension.toml
|
[package]
version = "0.1.0"
title = "Procedural Mesh"
category = "Internal"
# Main module of the python interface
[[python.module]]
name = "omni.kit.procedural.mesh"
# Watch the .ogn files for hot reloading (only works for Python files)
[fswatcher.patterns]
include = ["*.ogn", "*.py"]
exclude = ["Ogn*Database.py"]
# Other extensions that must be loaded before this one
[dependencies]
"omni.usd" = {}
"omni.ui" = {}
"omni.graph" = {}
"omni.graph.tools" = {}
"omni.kit.menu.utils" = {}
[[native.plugin]]
path = "bin/*.plugin"
recursive = false
| 551 |
TOML
| 18.034482 | 70 | 0.669691 |
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/__init__.py
|
from .scripts.extension import *
from .scripts.command import *
| 64 |
Python
| 20.66666 | 32 | 0.78125 |
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/ogn/OgnProceduralMeshSphereDatabase.py
|
"""Support for simplified access to data on nodes of type omni.kit.procedural.mesh.CreateMeshSphere
If necessary, create a new mesh representing a shpere
"""
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
import numpy
class OgnProceduralMeshSphereDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.kit.procedural.mesh.CreateMeshSphere
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.diameter
inputs.latitudeResolution
inputs.longitudeResolution
inputs.parameterCheck
Outputs:
outputs.extent
outputs.faceVertexCounts
outputs.faceVertexIndices
outputs.parameterCheck
outputs.points
outputs.stIndices
outputs.sts
"""
# This is an internal object that provides per-class storage of a per-node data dictionary
PER_NODE_DATA = {}
# This is an internal object that describes unchanging attributes in a generic way
# The values in this list are in no particular order, as a per-attribute tuple
# Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
# Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
# You should not need to access any of this data directly, use the defined database interfaces
INTERFACE = og.Database._get_interface([
('inputs:diameter', 'float', 0, None, 'Sphere diameter', {ogn.MetadataKeys.DEFAULT: '100'}, True, 100, False, ''),
('inputs:latitudeResolution', 'int', 0, None, 'Sphere Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''),
('inputs:longitudeResolution', 'int', 0, None, 'Sphere Resolution', {ogn.MetadataKeys.DEFAULT: '10'}, True, 10, False, ''),
('inputs:parameterCheck', 'int', 0, None, 'Previous crc value', {ogn.MetadataKeys.DEFAULT: '-1'}, True, -1, False, ''),
('outputs:extent', 'float3[]', 0, None, 'Extent of the mesh', {}, True, None, False, ''),
('outputs:faceVertexCounts', 'int[]', 0, None, 'Vertex count of faces', {}, True, None, False, ''),
('outputs:faceVertexIndices', 'int[]', 0, None, 'Vertex indices of faces', {}, True, None, False, ''),
('outputs:parameterCheck', 'int', 0, None, 'Current crc value', {}, True, None, False, ''),
('outputs:points', 'float3[]', 0, None, 'Points', {}, True, None, False, ''),
('outputs:stIndices', 'int[]', 0, None, 'Texture coordinate indices of faces', {}, True, None, False, ''),
('outputs:sts', 'float2[]', 0, None, 'Texture coordinate of vertices', {}, True, None, False, ''),
])
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"diameter", "latitudeResolution", "longitudeResolution", "parameterCheck", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"}
"""Helper class that creates natural hierarchical access to input attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self._batchedReadAttributes = [self._attributes.diameter, self._attributes.latitudeResolution, self._attributes.longitudeResolution, self._attributes.parameterCheck]
self._batchedReadValues = [100, 10, 10, -1]
@property
def diameter(self):
return self._batchedReadValues[0]
@diameter.setter
def diameter(self, value):
self._batchedReadValues[0] = value
@property
def latitudeResolution(self):
return self._batchedReadValues[1]
@latitudeResolution.setter
def latitudeResolution(self, value):
self._batchedReadValues[1] = value
@property
def longitudeResolution(self):
return self._batchedReadValues[2]
@longitudeResolution.setter
def longitudeResolution(self, value):
self._batchedReadValues[2] = value
@property
def parameterCheck(self):
return self._batchedReadValues[3]
@parameterCheck.setter
def parameterCheck(self, value):
self._batchedReadValues[3] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _prefetch(self):
readAttributes = self._batchedReadAttributes
newValues = _og._prefetch_input_attributes_data(readAttributes)
if len(readAttributes) == len(newValues):
self._batchedReadValues = newValues
class ValuesForOutputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"parameterCheck", "_batchedWriteValues"}
"""Helper class that creates natural hierarchical access to output attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
self.extent_size = None
self.faceVertexCounts_size = None
self.faceVertexIndices_size = None
self.points_size = None
self.stIndices_size = None
self.sts_size = None
self._batchedWriteValues = { }
@property
def extent(self):
data_view = og.AttributeValueHelper(self._attributes.extent)
return data_view.get(reserved_element_count=self.extent_size)
@extent.setter
def extent(self, value):
data_view = og.AttributeValueHelper(self._attributes.extent)
data_view.set(value)
self.extent_size = data_view.get_array_size()
@property
def faceVertexCounts(self):
data_view = og.AttributeValueHelper(self._attributes.faceVertexCounts)
return data_view.get(reserved_element_count=self.faceVertexCounts_size)
@faceVertexCounts.setter
def faceVertexCounts(self, value):
data_view = og.AttributeValueHelper(self._attributes.faceVertexCounts)
data_view.set(value)
self.faceVertexCounts_size = data_view.get_array_size()
@property
def faceVertexIndices(self):
data_view = og.AttributeValueHelper(self._attributes.faceVertexIndices)
return data_view.get(reserved_element_count=self.faceVertexIndices_size)
@faceVertexIndices.setter
def faceVertexIndices(self, value):
data_view = og.AttributeValueHelper(self._attributes.faceVertexIndices)
data_view.set(value)
self.faceVertexIndices_size = data_view.get_array_size()
@property
def points(self):
data_view = og.AttributeValueHelper(self._attributes.points)
return data_view.get(reserved_element_count=self.points_size)
@points.setter
def points(self, value):
data_view = og.AttributeValueHelper(self._attributes.points)
data_view.set(value)
self.points_size = data_view.get_array_size()
@property
def stIndices(self):
data_view = og.AttributeValueHelper(self._attributes.stIndices)
return data_view.get(reserved_element_count=self.stIndices_size)
@stIndices.setter
def stIndices(self, value):
data_view = og.AttributeValueHelper(self._attributes.stIndices)
data_view.set(value)
self.stIndices_size = data_view.get_array_size()
@property
def sts(self):
data_view = og.AttributeValueHelper(self._attributes.sts)
return data_view.get(reserved_element_count=self.sts_size)
@sts.setter
def sts(self, value):
data_view = og.AttributeValueHelper(self._attributes.sts)
data_view.set(value)
self.sts_size = data_view.get_array_size()
@property
def parameterCheck(self):
value = self._batchedWriteValues.get(self._attributes.parameterCheck)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.parameterCheck)
return data_view.get()
@parameterCheck.setter
def parameterCheck(self, value):
self._batchedWriteValues[self._attributes.parameterCheck] = value
def __getattr__(self, item: str):
if item in self.LOCAL_PROPERTY_NAMES:
return object.__getattribute__(self, item)
else:
return super().__getattr__(item)
def __setattr__(self, item: str, new_value):
if item in self.LOCAL_PROPERTY_NAMES:
object.__setattr__(self, item, new_value)
else:
super().__setattr__(item, new_value)
def _commit(self):
_og._commit_output_attributes_data(self._batchedWriteValues)
self._batchedWriteValues = { }
class ValuesForState(og.DynamicAttributeAccess):
"""Helper class that creates natural hierarchical access to state attributes"""
def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
"""Initialize simplified access for the attribute data"""
context = node.get_graph().get_default_graph_context()
super().__init__(context, node, attributes, dynamic_attributes)
def __init__(self, node):
super().__init__(node)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
self.inputs = OgnProceduralMeshSphereDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnProceduralMeshSphereDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnProceduralMeshSphereDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 10,957 |
Python
| 46.030043 | 177 | 0.637127 |
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/scripts/extension.py
|
import omni.ext
from ..bindings._omni_kit_procedural_mesh import *
from .menu import *
class PublicExtension(omni.ext.IExt):
def on_startup(self):
self._interface = acquire_interface()
self._menu = Menu()
def on_shutdown(self):
self._menu.on_shutdown()
self._menu = None
release_interface(self._interface)
| 357 |
Python
| 22.866665 | 50 | 0.644258 |
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/scripts/procedural_mesh_omnigraph_utils.py
|
"""
A set of utilities
"""
import omni.kit.app
import omni.usd
from pxr import Sdf, UsdGeom
import omni.graph.core as og
def get_parent(stage, parentPath):
if parentPath:
parentPrim = stage.GetPrimAtPath(parentPath)
if parentPrim:
return parentPrim, False
# fallback to default behavior (creating a parent xform prim)
omni.kit.commands.execute(
"CreatePrimWithDefaultXform",
prim_type="Xform",
prim_path=omni.usd.get_stage_next_free_path(stage, "/" + "ProceduralMeshXform", True),
select_new_prim=True,
create_default_xform=False,
)
paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
for path in paths:
parentPrim = stage.GetPrimAtPath(path)
return parentPrim, True
def create_mesh_computer(stage, prim_name: str, evaluator_name: str, node_type: str, parentPath=None):
parentPrim, isParentOwned = get_parent(stage, parentPath)
omni.kit.commands.execute(
"CreatePrimWithDefaultXform",
prim_type="Mesh",
prim_path=omni.usd.get_stage_next_free_path(
stage, str(parentPrim.GetPath().AppendElementString(prim_name)), False
),
select_new_prim=True,
create_default_xform=False,
)
paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
for path in paths:
mesh = stage.GetPrimAtPath(path)
helper = og.OmniGraphHelper()
computer = helper.create_node(str(mesh.GetPath().AppendElementString(evaluator_name)), node_type)
if isParentOwned:
return parentPrim, mesh, computer
else:
return mesh, mesh, computer
def init_common_attributes(prim):
# parameter check
# sschirm
parameterCheckAttr = prim.CreateAttribute("proceduralMesh:parameterCheck", Sdf.ValueTypeNames.Int)
parameterCheckAttr.Set(0)
# basic attributes
pointsAttr = prim.GetAttribute("points")
faceVertexCountsAttr = prim.GetAttribute("faceVertexCounts")
faceVertexIndicesAttr = prim.GetAttribute("faceVertexIndices")
# extent
extentAttr = prim.GetAttribute("extent")
def connect_common_attributes(prim, computer):
helper = og.OmniGraphHelper()
ognPrim = helper.attach_to_prim(prim)
# connect parameterCheck attribute as in and output
helper.connect(ognPrim, "proceduralMesh:parameterCheck", computer, "inputs:parameterCheck")
helper.connect(computer, "outputs:parameterCheck", ognPrim, "proceduralMesh:parameterCheck")
# connect basic attributes
helper.connect(computer, "outputs:points", ognPrim, "points")
helper.connect(computer, "outputs:faceVertexCounts", ognPrim, "faceVertexCounts")
helper.connect(computer, "outputs:faceVertexIndices", ognPrim, "faceVertexIndices")
# connect to extent
helper.connect(computer, "outputs:extent", ognPrim, "extent")
def init_crease_attributes(prim):
creaseIndicesAttr = prim.GetAttribute("creaseIndices")
creaseLengthsAttr = prim.GetAttribute("creaseLengths")
creaseSharpnessesAttr = prim.GetAttribute("creaseSharpnesses")
def connect_crease_attributes(prim, computer):
helper = og.OmniGraphHelper()
ognPrim = helper.attach_to_prim(prim)
# connect smooth group related attributes
helper.connect(computer, "outputs:creaseIndices", ognPrim, "creaseIndices")
helper.connect(computer, "outputs:creaseLengths", ognPrim, "creaseLengths")
helper.connect(computer, "outputs:creaseSharpnesses", ognPrim, "creaseSharpnesses")
def init_corner_attributes(prim):
cornerIndicesAttr = prim.GetAttribute("cornerIndices")
cornerSharpnessesAttr = prim.GetAttribute("cornerSharpnesses")
def connect_corner_attributes(prim, computer):
helper = og.OmniGraphHelper()
ognPrim = helper.attach_to_prim(prim)
# connect smooth group related attributes
helper.connect(computer, "outputs:cornerIndices", ognPrim, "cornerIndices")
helper.connect(computer, "outputs:cornerSharpnesses", ognPrim, "cornerSharpnesses")
def init_normals_facevarying_attributes(prim):
mesh = UsdGeom.Mesh(prim)
# authored normals only works when subdivision is none
mesh.CreateSubdivisionSchemeAttr("none")
normalsVar = mesh.CreatePrimvar("normals", Sdf.ValueTypeNames.Normal3fArray)
normalsAttr = prim.GetAttribute("primvars:normals")
normalIndicesAttr = prim.CreateAttribute("primvars:normals:indices", Sdf.ValueTypeNames.IntArray, False)
normalsVar.SetInterpolation("faceVarying")
def connect_normals_facevarying_attributes(prim, computer):
helper = og.OmniGraphHelper()
ognPrim = helper.attach_to_prim(prim)
# connect normal related attributes
helper.connect(computer, "outputs:normals", ognPrim, "primvars:normals")
helper.connect(computer, "outputs:normalIndices", ognPrim, "primvars:normals:indices")
def init_texture_coords_facevarying_attributes(prim):
mesh = UsdGeom.Mesh(prim)
# st related attributes
stsVar = mesh.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying)
stsAttr = prim.GetAttribute("primvars:st")
stIndicesAttr = prim.CreateAttribute("primvars:st:indices", Sdf.ValueTypeNames.IntArray, False)
def connect_texture_coords_facevarying_attributes(prim, computer):
helper = og.OmniGraphHelper()
ognPrim = helper.attach_to_prim(prim)
# connect st related attributes
helper.connect(computer, "outputs:sts", ognPrim, "primvars:st")
helper.connect(computer, "outputs:stIndices", ognPrim, "primvars:st:indices")
def init_texture_coords_attributes(prim):
mesh = UsdGeom.Mesh(prim)
# st related attributes
stsVar = mesh.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex)
stsAttr = prim.GetAttribute("primvars:st")
def connect_texture_coords_attributes(prim, computer):
helper = og.OmniGraphHelper()
ognPrim = helper.attach_to_prim(prim)
# connect st related attributes
helper.connect(computer, "outputs:sts", ognPrim, "primvars:st")
def create_procedural_mesh_cube(
stage, parentPath=None, xLength=100, yLength=100, zLength=100, xResolution=10, yResolution=10, zResolution=10
):
root, cube, computer = create_mesh_computer(
stage, "ProceduralMeshCube", "CubeEvaluator", "omni.kit.procedural.mesh.CreateMeshCube", parentPath
)
helper = og.OmniGraphHelper()
# omnigraph node for the mesh init
helper.set_values(
computer,
[
["inputs:xLength", xLength],
["inputs:yLength", yLength],
["inputs:zLength", zLength],
["inputs:xResolution", xResolution],
["inputs:yResolution", xResolution],
["inputs:zResolution", zResolution],
],
)
# setup mesh attributes and node inputs/outputs
init_common_attributes(cube)
init_crease_attributes(cube)
init_normals_facevarying_attributes(cube)
init_texture_coords_facevarying_attributes(cube)
connect_common_attributes(cube, computer)
connect_crease_attributes(cube, computer)
connect_normals_facevarying_attributes(cube, computer)
connect_texture_coords_facevarying_attributes(cube, computer)
return root, cube
def create_procedural_mesh_sphere(stage, parentPath=None, diameter=100, longitudeResolution=10, latitudeResolution=10):
root, sphere, computer = create_mesh_computer(
stage, "ProceduralMeshSphere", "SphereEvaluator", "omni.kit.procedural.mesh.CreateMeshSphere", parentPath
)
helper = og.OmniGraphHelper()
# omnigraph node for the mesh init
helper.set_values(
computer,
[
["inputs:diameter", diameter],
["inputs:longitudeResolution", longitudeResolution],
["inputs:latitudeResolution", latitudeResolution],
],
)
# setup mesh attributes and node inputs/outputs
init_common_attributes(sphere)
init_texture_coords_facevarying_attributes(sphere)
connect_common_attributes(sphere, computer)
connect_texture_coords_facevarying_attributes(sphere, computer)
return root, sphere
def create_procedural_mesh_capsule(
stage,
parentPath=None,
diameter=100,
yLength=200,
longitudeResolution=10,
hemisphereLatitudeResolution=10,
middleLatitudeResolution=10,
):
root, capsule, computer = create_mesh_computer(
stage, "ProceduralMeshCapsule", "CapsuleEvaluator", "omni.kit.procedural.mesh.CreateMeshCapsule", parentPath
)
helper = og.OmniGraphHelper()
# omnigraph node for the mesh init
helper.set_values(
computer,
[
["inputs:diameter", diameter],
["inputs:yLength", yLength],
["inputs:longitudeResolution", longitudeResolution],
["inputs:hemisphereLatitudeResolution", hemisphereLatitudeResolution],
["inputs:middleLatitudeResolution", middleLatitudeResolution],
],
)
# setup mesh attributes and node inputs/outputs
init_common_attributes(capsule)
init_texture_coords_facevarying_attributes(capsule)
connect_common_attributes(capsule, computer)
connect_texture_coords_facevarying_attributes(capsule, computer)
return root, capsule
def create_procedural_mesh_cylinder(
stage, parentPath=None, diameter=100, height=100, longitudeResolution=10, latitudeResolution=10, capResolution=10
):
root, cylinder, computer = create_mesh_computer(
stage, "ProceduralMeshCylinder", "CylinderEvaluator", "omni.kit.procedural.mesh.CreateMeshCylinder", parentPath
)
helper = og.OmniGraphHelper()
# omnigraph node for the mesh init
helper.set_values(
computer,
[
["inputs:diameter", diameter],
["inputs:height", height],
["inputs:longitudeResolution", longitudeResolution],
["inputs:latitudeResolution", latitudeResolution],
["inputs:capResolution", capResolution],
],
)
# setup mesh attributes and node inputs/outputs
init_common_attributes(cylinder)
init_crease_attributes(cylinder)
init_normals_facevarying_attributes(cylinder)
init_texture_coords_facevarying_attributes(cylinder)
connect_common_attributes(cylinder, computer)
connect_crease_attributes(cylinder, computer)
connect_normals_facevarying_attributes(cylinder, computer)
connect_texture_coords_facevarying_attributes(cylinder, computer)
return root, cylinder
def create_procedural_mesh_cone(
stage, parentPath=None, diameter=100, height=100, longitudeResolution=10, latitudeResolution=10, capResolution=10
):
root, cone, computer = create_mesh_computer(
stage, "ProceduralMeshCone", "ConeEvaluator", "omni.kit.procedural.mesh.CreateMeshCone", parentPath
)
helper = og.OmniGraphHelper()
# omnigraph node for the mesh init
helper.set_values(
computer,
[
["inputs:diameter", diameter],
["inputs:height", height],
["inputs:longitudeResolution", longitudeResolution],
["inputs:latitudeResolution", latitudeResolution],
["inputs:capResolution", capResolution],
],
)
# setup mesh attributes and node inputs/outputs
init_common_attributes(cone)
init_crease_attributes(cone)
init_corner_attributes(cone)
init_normals_facevarying_attributes(cone)
init_texture_coords_facevarying_attributes(cone)
connect_common_attributes(cone, computer)
connect_crease_attributes(cone, computer)
connect_corner_attributes(cone, computer)
connect_normals_facevarying_attributes(cone, computer)
connect_texture_coords_facevarying_attributes(cone, computer)
return root, cone
def create_procedural_mesh_torus(
stage, parentPath=None, diameter=200, sectionDiameter=50, sectionTwist=0, loopResolution=10, sectionResolution=10
):
root, torus, computer = create_mesh_computer(
stage, "ProceduralMeshTorus", "TorusEvaluator", "omni.kit.procedural.mesh.CreateMeshTorus", parentPath
)
helper = og.OmniGraphHelper()
# omnigraph node for the mesh init
helper.set_values(
computer,
[
["inputs:diameter", diameter],
["inputs:sectionDiameter", sectionDiameter],
["inputs:sectionTwist", sectionTwist],
["inputs:loopResolution", loopResolution],
["inputs:sectionResolution", sectionResolution],
],
)
# setup mesh attributes and node inputs/outputs
init_common_attributes(torus)
init_texture_coords_facevarying_attributes(torus)
connect_common_attributes(torus, computer)
connect_texture_coords_facevarying_attributes(torus, computer)
return root, torus
def create_procedural_mesh_disk(stage, parentPath=None, diameter=100, longitudeResolution=10, capResolution=10):
root, disk, computer = create_mesh_computer(
stage, "ProceduralMeshDisk", "DiskEvaluator", "omni.kit.procedural.mesh.CreateMeshDisk", parentPath
)
helper = og.OmniGraphHelper()
# omnigraph node for the mesh init
helper.set_values(
computer,
[
["inputs:diameter", diameter],
["inputs:longitudeResolution", longitudeResolution],
["inputs:capResolution", capResolution],
],
)
# setup mesh attributes and node inputs/outputs
init_common_attributes(disk)
init_texture_coords_attributes(disk)
connect_common_attributes(disk, computer)
connect_texture_coords_attributes(disk, computer)
return root, disk
def create_procedural_mesh_plane(stage, parentPath=None, xLength=100, zLength=100, xResolution=10, zResolution=10):
root, plane, computer = create_mesh_computer(
stage, "ProceduralMeshPlane", "PlaneEvaluator", "omni.kit.procedural.mesh.CreateMeshPlane", parentPath
)
helper = og.OmniGraphHelper()
# omnigraph node for the mesh init
helper.set_values(
computer,
[
["inputs:xLength", xLength],
["inputs:zLength", zLength],
["inputs:xResolution", xResolution],
["inputs:zResolution", zResolution],
],
)
# setup mesh attributes and node inputs/outputs
init_common_attributes(plane)
init_texture_coords_attributes(plane)
connect_common_attributes(plane, computer)
connect_texture_coords_attributes(plane, computer)
return root, plane
| 14,417 |
Python
| 33.910412 | 119 | 0.703614 |
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/scripts/menu.py
|
import omni.kit.ui
import omni.usd
# ======================================================================
MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CUBE = (
f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Cube'
)
MENU_CREATE_BUILTIN_PROCEDURAL_MESH_SPHERE = (
f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Sphere'
)
MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CAPSULE = (
f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Capsule'
)
MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CYLINDER = (
f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Cylinder'
)
MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CONE = (
f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Cone'
)
MENU_CREATE_BUILTIN_PROCEDURAL_MESH_TORUS = (
f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Torus'
)
MENU_CREATE_BUILTIN_PROCEDURAL_MESH_PLANE = (
f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Plane'
)
MENU_CREATE_BUILTIN_PROCEDURAL_MESH_DISK = (
f'OmniGraph/{omni.kit.ui.get_custom_glyph_code("${glyphs}/menu_prim.svg")} Procedural Mesh/Disk'
)
class Menu:
def __init__(self):
self.on_startup()
def on_startup(self):
self.menus = []
editor_menu = omni.kit.ui.get_editor_menu()
self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CUBE, self._on_menu_click))
self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_SPHERE, self._on_menu_click))
self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CAPSULE, self._on_menu_click))
self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CYLINDER, self._on_menu_click))
self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CONE, self._on_menu_click))
self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_PLANE, self._on_menu_click))
self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_TORUS, self._on_menu_click))
self.menus.append(editor_menu.add_item(MENU_CREATE_BUILTIN_PROCEDURAL_MESH_DISK, self._on_menu_click))
def _on_menu_click(self, menu_item, value):
if menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CUBE:
omni.kit.commands.execute("CreateProceduralMeshCube")
elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_SPHERE:
omni.kit.commands.execute("CreateProceduralMeshSphere")
elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CAPSULE:
omni.kit.commands.execute("CreateProceduralMeshCapsule")
elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CYLINDER:
omni.kit.commands.execute("CreateProceduralMeshCylinder")
elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_CONE:
omni.kit.commands.execute("CreateProceduralMeshCone")
elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_TORUS:
omni.kit.commands.execute("CreateProceduralMeshTorus")
elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_PLANE:
omni.kit.commands.execute("CreateProceduralMeshPlane")
elif menu_item == MENU_CREATE_BUILTIN_PROCEDURAL_MESH_DISK:
omni.kit.commands.execute("CreateProceduralMeshDisk")
def on_shutdown(self):
self.menus = []
| 3,576 |
Python
| 50.840579 | 114 | 0.694631 |
omniverse-code/kit/exts/omni.kit.procedural.mesh/omni/kit/procedural/mesh/scripts/command.py
|
import omni
from pxr import UsdGeom, Usd, Vt, Kind, Sdf
from .procedural_mesh_omnigraph_utils import (
create_procedural_mesh_cube,
create_procedural_mesh_sphere,
create_procedural_mesh_capsule,
create_procedural_mesh_cylinder,
create_procedural_mesh_cone,
create_procedural_mesh_torus,
create_procedural_mesh_plane,
create_procedural_mesh_disk,
)
class CreateProceduralMeshCommand(omni.kit.commands.Command):
def __init__(self):
self._create = None
self._stage = omni.usd.get_context().get_stage()
self._selection = omni.usd.get_context().get_selection()
def do(self):
xForm, mesh = self._create(self._stage)
self._prim_path = xForm.GetPath()
# set the new prim as the active selection
self._selection.set_prim_path_selected(self._prim_path.pathString, True, False, True, True)
return xForm
def undo(self):
prim = self._stage.GetPrimAtPath(self._prim_path)
if prim:
self._stage.RemovePrim(self._prim_path)
class CreateProceduralMeshCubeCommand(CreateProceduralMeshCommand):
def __init__(self):
super().__init__()
self._create = create_procedural_mesh_cube
class CreateProceduralMeshSphereCommand(CreateProceduralMeshCommand):
def __init__(self):
super().__init__()
self._create = create_procedural_mesh_sphere
class CreateProceduralMeshCapsuleCommand(CreateProceduralMeshCommand):
def __init__(self):
super().__init__()
self._create = create_procedural_mesh_capsule
class CreateProceduralMeshCylinderCommand(CreateProceduralMeshCommand):
def __init__(self):
super().__init__()
self._create = create_procedural_mesh_cylinder
class CreateProceduralMeshConeCommand(CreateProceduralMeshCommand):
def __init__(self):
super().__init__()
self._create = create_procedural_mesh_cone
class CreateProceduralMeshTorusCommand(CreateProceduralMeshCommand):
def __init__(self):
super().__init__()
self._create = create_procedural_mesh_torus
class CreateProceduralMeshPlaneCommand(CreateProceduralMeshCommand):
def __init__(self):
super().__init__()
self._create = create_procedural_mesh_plane
class CreateProceduralMeshDiskCommand(CreateProceduralMeshCommand):
def __init__(self):
super().__init__()
self._create = create_procedural_mesh_disk
omni.kit.commands.register(CreateProceduralMeshCubeCommand)
omni.kit.commands.register(CreateProceduralMeshSphereCommand)
omni.kit.commands.register(CreateProceduralMeshCapsuleCommand)
omni.kit.commands.register(CreateProceduralMeshCylinderCommand)
omni.kit.commands.register(CreateProceduralMeshConeCommand)
omni.kit.commands.register(CreateProceduralMeshTorusCommand)
omni.kit.commands.register(CreateProceduralMeshPlaneCommand)
omni.kit.commands.register(CreateProceduralMeshDiskCommand)
| 2,939 |
Python
| 31.307692 | 99 | 0.714869 |
omniverse-code/kit/exts/omni.kit.gfn/config/extension.toml
|
[package]
title = "NVIDIA GFN Integration"
category = "Streaming"
# Semantic Versioning is used: https://semver.org/
version = "1.1.0"
[dependencies]
#"omni.usd" = {}
[[python.module]]
name = "omni.kit.gfn"
[[native.plugin]]
path = "bin/*.plugin"
recursive = false
[settings]
#exts."omni.kit.gfn".enable = false
[[test]]
waiver = "Tests are in omni.gfn.autoload"
| 369 |
TOML
| 15.086956 | 50 | 0.674797 |
omniverse-code/kit/exts/omni.kit.gfn/omni/kit/gfn/__init__.py
|
from ._kit_gfn import *
# Cached interface instance pointer
def get_geforcenow_interface() -> IGeForceNow:
"""Returns cached :class:`omni.kit.gfn.IGeForceNow` interface"""
if not hasattr(get_geforcenow_interface, "geforcenow"):
get_geforcenow_interface.geforcenow = acquire_geforcenow_interface()
return get_geforcenow_interface.geforcenow
| 362 |
Python
| 35.299996 | 76 | 0.745856 |
omniverse-code/kit/exts/omni.kit.gfn/omni/kit/gfn/_kit_gfn.pyi
|
"""pybind11 omni.kit.gfn bindings"""
from __future__ import annotations
import omni.kit.gfn._kit_gfn
import typing
__all__ = [
"IGeForceNow",
"acquire_geforcenow_interface",
"release_geforcenow_interface"
]
class IGeForceNow():
def get_partner_secure_data(self) -> str: ...
def shutdown(self) -> None: ...
def startup(self, sdk_library_path: str = '') -> None: ...
pass
def acquire_geforcenow_interface(plugin_name: str = None, library_path: str = None) -> IGeForceNow:
pass
def release_geforcenow_interface(arg0: IGeForceNow) -> None:
pass
| 580 |
unknown
| 25.40909 | 99 | 0.668966 |
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/thumbnail_grid.py
|
from functools import partial
from typing import Callable, Dict, List, Optional
import omni.ui as ui
from omni.ui import constant as fl
from .style import ICON_PATH
class ThumbnailItem(ui.AbstractItem):
"""
Data item for a thumbnail.
Args:
thumbnail (str): Url to thumbnail.
url (str): Url to item.
text (str): Display text for this item. Default use file name of url.
"""
def __init__(self, thumbnail: str, url: str, text: Optional[str] = None):
self.thumbnail = thumbnail
self.url = url
self.text = text if text else url.split("/")[-1]
super().__init__()
def execute(self):
pass
class ThumbnailModel(ui.AbstractItemModel):
"""
Data model for thumbnail items.
Args:
items (List[ThumbnailItem]): List of thumbnail items
"""
def __init__(self, items: List[ThumbnailItem]):
super().__init__()
self._items = items
def get_item_children(self, item: Optional[ThumbnailItem] = None) -> List[ThumbnailItem]:
return self._items
class ThumbnailGrid:
"""
Widget to show a grid (thumbnail + label).
Args:
model (ThumbnailModel): Data model.
label_height (int): Height for item label. Default 30.
thumbnail_width (int): Thumbnail width. Default 128.
thumbnail_height (int): Thumbnail height. Default 128.
thumbnail_padding_x (int): X padding between different thumbnail items. Default 2.
thumbnail_padding_y (int): Y padding between different thumbnail items. Default 4.
"""
def __init__(
self,
model: ThumbnailModel,
on_selection_changed: Callable[[Optional[ThumbnailItem]], None] = None,
label_height:int=fl._find("welcome_open_lable_size"),
thumbnail_width: int=fl._find("welcome_open_thumbnail_size"),
thumbnail_height: int=fl._find("welcome_open_thumbnail_size"),
thumbnail_padding_x: int=2,
thumbnail_padding_y: int=4,
):
self._model = model
self._on_selection_changed = on_selection_changed
self._label_height = label_height
self._thumbnail_width = thumbnail_width
self._thumbnail_height = thumbnail_height
self._thumbnail_padding_x = thumbnail_padding_x
self._thumbnail_padding_y = thumbnail_padding_y
self._column_width = self._thumbnail_width + 2 * self._thumbnail_padding_x
self._row_height = self._thumbnail_height + 2 * self._thumbnail_padding_y + self._label_height
self.__selected_thumbnail: Optional[ThumbnailItem] = None
self.__frames: Dict[ThumbnailItem, ui.Frame] = {}
self._build_ui()
@property
def selected(self) -> Optional[ThumbnailItem]:
return self.__selected_thumbnail
@selected.setter
def selected(self, item: Optional[ThumbnailItem]) -> None:
self.select_item(item)
def _build_ui(self):
self._container = ui.ScrollingFrame(
style_type_name_override="ThumbnailGrid.Frame",
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
)
self._refresh()
self._sub_model = self._model.subscribe_item_changed_fn(lambda m, i: self._refresh())
def _refresh(self):
self._container.clear()
with self._container:
self._grid = ui.VGrid(
column_width=self._column_width,
row_hegiht=self._row_height,
content_clipping=True,
)
with self._grid:
children = self._model.get_item_children()
if not children:
return
for item in children:
with ui.VStack():
ui.Spacer(height=self._thumbnail_padding_y)
with ui.HStack():
ui.Spacer(width=self._thumbnail_padding_x)
self.__frames[item] = ui.Frame(
build_fn=lambda i=item: self._build_thumbnail_item(i),
mouse_double_clicked_fn=lambda x, y, a, f, i=item: i.execute(),
mouse_pressed_fn=lambda x, y, a, f, i=item: self.select_item(i),
)
ui.Spacer(width=self._thumbnail_padding_x)
ui.Spacer(height=self._thumbnail_padding_y)
self._grid.set_mouse_pressed_fn(lambda x, y, btn, flag: self.select_item(None))
def _build_thumbnail_item(self, item: ThumbnailItem) -> None:
with ui.ZStack():
with ui.VStack():
self.build_thumbnail(item)
self.build_label(item)
ui.Rectangle(style_type_name_override="ThumbnailGrid.Selection")
def build_thumbnail(self, item: ThumbnailItem) -> None:
def on_image_progress(default_image: ui.Image, thumbnail_image: ui.Image, progress: float):
"""Called when the image loading progress is changed."""
if progress != 1.0:
# We only need to catch the moment when the image is loaded.
return
# Hide the default_image at the back.
default_image.visible = False
# Remove the callback to avoid circular references.
thumbnail_image.set_progress_changed_fn(None)
with ui.ZStack(width=self._thumbnail_width, height=self._thumbnail_height):
# Default image for thumbnail not defined or invalid thumbnail url or download in progress
# Hidden when actually thumbnail downloaded
default_image = ui.Image(f"{ICON_PATH}/usd_stage_256.png", style_type_name_override="ThumbnailGrid.Image")
if item.thumbnail:
thumbnail_image = ui.Image(item.thumbnail, style_type_name_override="ThumbnailGrid.Image")
thumbnail_image.set_progress_changed_fn(partial(on_image_progress, default_image, thumbnail_image))
def build_label(self, item: ThumbnailItem) -> None:
with ui.ZStack():
ui.Rectangle(style_type_name_override="ThumbnailGrid.Item.Background")
ui.Label(
item.text,
height=self._label_height,
word_wrap=True,
elided_text=True,
skip_draw_when_clipped=True,
alignment=ui.Alignment.CENTER,
style_type_name_override="ThumbnailGrid.Item",
)
def select_item(self, item: Optional[ThumbnailItem]) -> None:
if self.__selected_thumbnail:
self.__frames[self.__selected_thumbnail].selected = False
if item:
self.__frames[item].selected = True
self.__selected_thumbnail = item
if self._on_selection_changed:
self._on_selection_changed(item)
def find_item(self, url: str) -> Optional[ThumbnailItem]:
for item in self._model.get_item_children(None):
if item.url == url:
return item
return None
def select_url(self, url: str) -> None:
if url:
item = self.find_item(url)
self.select_item(item)
else:
self.select_item(None)
| 7,367 |
Python
| 38.612903 | 118 | 0.586806 |
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/stage_tab.py
|
from typing import Optional
import carb
import omni.ui as ui
from omni.ui import constant as fl
from omni.kit.welcome.window import show_window as show_welcome_window
from .recent_widget import RecentWidget
from .template_grid import TemplateGrid
from .thumbnail_grid import ThumbnailItem
SETTING_SHOW_TEMPLATES = "/exts/omni.kit.welcome.open/show_templates"
class StageTab:
"""
Tab to show stage content.
"""
def __init__(self):
self._checkpoint_combobox = None
self._build_ui()
def destroy(self):
self._recent_widget.destroy()
def _build_ui(self):
with ui.VStack():
# Templates
if carb.settings.get_settings().get_as_bool(SETTING_SHOW_TEMPLATES):
with ui.HStack(height=0):
ui.Spacer(width=fl._find("welcome_content_padding_x"))
with ui.VStack():
ui.Line(height=2, style_type_name_override="ThumbnailGrid.Separator")
ui.Label("NEW", height=0, style_type_name_override="ThumbnailGrid.Title")
ui.Spacer(height=10)
ui.Spacer(width=fl._find("welcome_content_padding_x"))
with ui.HStack(height=fl._find("welcome_open_thumbnail_size") + fl._find("welcome_open_lable_size") + 60):
ui.Spacer(width=8)
self._template_grid = TemplateGrid(on_selection_changed=self.__on_template_selected)
ui.Spacer(width=8)
# Recent files
with ui.HStack(height=0):
ui.Spacer(width=fl._find("welcome_content_padding_x"))
with ui.VStack():
ui.Line(height=2, style_type_name_override="ThumbnailGrid.Separator")
with ui.HStack(height=20):
ui.Label("RECENT", width=0, style_type_name_override="ThumbnailGrid.Title")
ui.Spacer()
self._mode_image = ui.Image(name="grid", width=20, style_type_name_override="ThumbnailGrid.Mode", mouse_pressed_fn=lambda x, y, b,a: self.__toggle_thumbnail_model())
ui.Spacer(height=10)
ui.Spacer(width=fl._find("welcome_content_padding_x"))
self._recent_widget = RecentWidget(self.__on_recent_selected, self.__on_grid_mode)
# Open widgets
with ui.ZStack(height=26):
ui.Rectangle(style_type_name_override="Stage.Separator")
with ui.VStack():
ui.Spacer(height=2)
with ui.HStack(spacing=2):
self._checkpoint_blank = ui.Rectangle(style_type_name_override="Stage.Blank")
self._checkpoint_frame = ui.Frame(build_fn=self.__build_checkpoints, visible=False)
# Button size/style to be same as omni.kit.window.filepicker.FilePickerWidget
ui.Button("Open File", width=117, style_type_name_override="Stage.Button", mouse_pressed_fn=lambda x, y, a, f:self.__open_file())
ui.Button("Close", width=117, style_type_name_override="Stage.Button", mouse_pressed_fn=lambda x, y, a, f:show_welcome_window(visible=False))
def __toggle_thumbnail_model(self):
if self._mode_image.name == "grid":
self._mode_image.name = "table"
self._recent_widget.show_grid(False)
else:
self._mode_image.name = "grid"
self._recent_widget.show_grid(True)
def __build_checkpoints(self):
try:
import omni.kit.app
manager = omni.kit.app.get_app().get_extension_manager()
manager.set_extension_enabled_immediate("omni.kit.widget.versioning", True)
from omni.kit.widget.versioning import CheckpointCombobox
with ui.HStack(spacing=2):
with ui.ZStack(content_clipping=True, width=0):
ui.Rectangle(style_type_name_override="Stage.Blank")
ui.Label("Checkpoints", width=0, style_type_name_override="Stage.Label")
self._checkpoint_combobox = CheckpointCombobox(
self._recent_widget.selected_url if self._recent_widget.selected_url else "",
None,
width=ui.Fraction(1),
has_pre_spacer=False,
popup_width=0,
modal=True
)
except Exception as e:
carb.log_warn(f"Failed to create checkpoint combobox: {e}")
self._checkpoint_combobox = None
def __on_template_selected(self, item: Optional[ThumbnailItem]):
if item:
# Clear selection in recents
self._recent_widget.selected_url = None
# Hide checkpoint combobox
self._checkpoint_frame.visible = False
self._checkpoint_blank.visible = True
def __on_recent_selected(self, item: Optional[ui.AbstractItem]):
if item:
# Clear selection in templates
self._template_grid.selected = None
if isinstance(item, ThumbnailItem):
# Show checkpoint combobox if selected in recent grid
self._checkpoint_frame.visible = bool(item)
self._checkpoint_blank.visible = not bool(item)
if item and self._checkpoint_combobox:
self._checkpoint_combobox.url = item.url
def __on_grid_mode(self, grid_mode: bool) -> None:
# Show checkpoint combobox in grid mode and recent file selected
if grid_mode:
show_checkpoint = bool(self._recent_widget.selected_url)
self._checkpoint_frame.visible = show_checkpoint
self._checkpoint_blank.visible = not show_checkpoint
else:
self._checkpoint_frame.visible = False
self._checkpoint_blank.visible = True
def __open_file(self) -> None:
selected = self._template_grid.selected
if selected:
carb.log_info(f"Open template: {selected.url}")
selected.execute()
else:
self._recent_widget.open_selected(self._checkpoint_combobox.url if self._checkpoint_combobox else None)
| 6,253 |
Python
| 44.985294 | 189 | 0.58244 |
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/style.py
|
from pathlib import Path
import omni.ui as ui
from omni.ui import color as cl
from omni.ui import constant as fl
CURRENT_PATH = Path(__file__).parent
ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("icons")
fl.welcome_open_thumbnail_size = 145
fl.welcome_open_lable_size = 30
cl.welcome_open_item_selected = cl.shade(cl("#77878A"))
cl.welcome_open_label = cl.shade(cl("#9E9E9E"))
OPEN_PAGE_STYLE = {
"RadioButton": {"background_color": cl.transparent, "stack_direction": ui.Direction.LEFT_TO_RIGHT, "padding": 0, "margin": 0},
"RadioButton.Label": {"font_size": fl.welcome_title_font_size, "color": cl.welcome_label, "alignment": ui.Alignment.LEFT_CENTER},
"RadioButton.Label:checked": {"color": cl.welcome_label_selected},
"RadioButton:checked": {"background_color": cl.transparent},
"RadioButton:hovered": {"background_color": cl.transparent},
"RadioButton:pressed": {"background_color": cl.transparent},
"RadioButton.Image::STAGE": {"image_url": f"{ICON_PATH}/USD.svg"},
"RadioButton.Image::SAMPLES": {"image_url": f"{ICON_PATH}/image.svg"},
"RadioButton.Image::FILE": {"image_url": f"{ICON_PATH}/hdd.svg"},
"RadioButton.Image": {"color": cl.welcome_label, "alignment": ui.Alignment.RIGHT_CENTER},
"RadioButton.Image:checked": {"color": cl.welcome_label_selected},
"ThumbnailGrid.Separator": {"color": cl.welcome_window_background, "border_width": 1.5},
"ThumbnailGrid.Title": {"color": 0xFFCCCCCC, "font_size": fl.welcome_title_font_size},
"ThumbnailGrid.Mode": {"margin": 2},
"ThumbnailGrid.Mode::grid": {"image_url": f"{ICON_PATH}/thumbnail.svg"},
"ThumbnailGrid.Mode::table": {"image_url": f"{ICON_PATH}/list.svg"},
"ThumbnailGrid.Frame": {
"background_color": cl.transparent,
"secondary_color": 0xFF808080,
"border_radius": 0,
"scrollbar_size": 10,
},
"ThumbnailGrid.Selection": {
"background_color": cl.transparent,
},
"ThumbnailGrid.Selection:selected": {
"border_width": 1,
"border_color": cl.welcome_open_item_selected,
"border_radius": 0,
},
"ThumbnailGrid.Item.Background": {
"background_color": cl.transparent,
},
"ThumbnailGrid.Item.Background:selected": {
"background_color": 0xFF525252,
},
"ThumbnailGrid.Item": {
"margin_width": 2,
"color": cl.welcome_label,
},
"Template.Add": {"color": 0xFFFFFFFF},
"Template.Add:hovered": {"color": cl.welcome_label_selected},
"Template.Add:pressed": {"color": cl.welcome_label_selected},
"Template.Add:selected": {"color": cl.welcome_label_selected},
"Stage.Label": {"color": cl.welcome_open_label, "margin_width": 6},
"Stage.Button": {
"background_color": 0xFF23211F,
"selected_color": 0xFF8A8777,
"color": cl.welcome_open_label,
"margin": 0,
"padding": 0
},
"Stage.Button:hovered": {"background_color": 0xFF3A3A3A},
"Stage.Button.Label": {"color": cl.welcome_open_label},
"Stage.Button.Label:disabled": {"color": 0xFF3A3A3A},
"Stage.Separator": {"background_color": cl.welcome_window_background},
"Stage.Blank": {"background_color": cl.welcome_content_background},
}
| 3,242 |
Python
| 41.116883 | 133 | 0.652067 |
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/extension.py
|
from typing import Optional
import omni.ext
import omni.ui as ui
from omni.kit.welcome.window import register_page
from .open_widget import OpenWidget
class OpenPageExtension(omni.ext.IExt):
def on_startup(self, ext_id):
self._widget: Optional[OpenWidget] = None
self.__ext_name = omni.ext.get_extension_name(ext_id)
register_page(self.__ext_name, self.build_ui)
def on_shutdown(self):
if self._widget:
self._widget.destroy()
self._widget = None
def build_ui(self) -> None:
self._widget = OpenWidget()
| 585 |
Python
| 23.416666 | 61 | 0.652991 |
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/recent_widget.py
|
import asyncio
import os
from typing import Callable, List, Optional
import carb.settings
import omni.ui as ui
from .thumbnail_grid import ThumbnailGrid, ThumbnailItem, ThumbnailModel
SETTING_RECENT_FILES = "/persistent/app/file/recentFiles"
class RecentItem(ThumbnailItem):
"""
Data item for recent file.
"""
def __init__(self, url: str):
super().__init__(self.__get_thumbnail(url), url)
def __get_thumbnail(self, url: str):
file_name = os.path.basename(url)
path = os.path.dirname(url)
# Do not check if thumbnail image exists here, leave it to ThumbnailGrid
return f"{path}/.thumbs/256x256/{file_name}.png"
def execute(self, url: Optional[str] = None):
from .open_action import run_open_action
run_open_action("omni.kit.window.file", "open_stage", url if url else self.url)
class RecentModel(ThumbnailModel):
"""
Data model for recent files.
"""
def __init__(self, recent_files: List[str]):
super().__init__([])
self.refresh(recent_files)
def refresh(self, recent_files: List[str]) -> None:
self._items = [RecentItem(recent) for recent in recent_files] if recent_files else []
self._item_changed(None)
class RecentWidget:
"""
Show recents grid and open widgets.
"""
def __init__(self, on_recent_changed_fn: Callable[[Optional[ui.AbstractItem]], None], on_grid_mode_fn: Callable[[bool], None]):
self._settings = carb.settings.get_settings()
self.__get_recent_history()
self._grid_model = RecentModel(self.__recent_files)
self._recent_table: Optional[RecentTable] = None
self.__on_recent_selected_fn = on_recent_changed_fn
self.__on_grid_mode_fn = on_grid_mode_fn
self._build_ui()
def destroy(self):
self._subscription = None
self._event_sub = None
@property
def selected_url(self) -> str:
if self._grid_frame.visible:
return self._recent_grid.selected.url if self._recent_grid.selected else ""
else:
return self._recent_table.selected
@selected_url.setter
def selected_url(self, url: str) -> None:
if self._grid_frame.visible:
self._recent_grid.select_url(url)
else:
self._recent_table.selected = url
def clear_selection(self):
if self._grid_frame.visible:
self._recent_grid.selected = None
else:
self._recent_table.selected = None
def show_grid(self, grid: bool) -> None:
self._grid_frame.visible = grid
self._table_frame.visible = not grid
if grid:
# Set grid selection from table
if self._recent_table:
self._recent_grid.select_url(self._recent_table.selected)
else:
# Set table selection from grid
if self._recent_table:
if self._recent_grid.selected:
self._recent_table.selected = self._recent_grid.selected.url
else:
# Wait for widget create and set selection
async def __delay_select():
await omni.kit.app.get_app().next_update_async()
if self._recent_grid.selected:
self._recent_table.selected = self._recent_grid.selected.url
asyncio.ensure_future(__delay_select())
self.__on_grid_mode_fn(grid)
def open_selected(self, checkpoint_url: Optional[str]) -> None:
def __open_file(url):
carb.log_info(f"Open recent file: {url}")
from .open_action import run_open_action
run_open_action("omni.kit.window.file", "open_stage", url)
if self.selected_url:
if self._grid_frame.visible:
__open_file(checkpoint_url or self.selected_url)
else:
__open_file(self._recent_table.get_filename())
def _build_ui(self):
with ui.ZStack():
self._grid_frame = ui.Frame(build_fn=self._build_grid_ui)
self._table_frame = ui.Frame(build_fn=self._build_table_ui, visible=False)
def _build_table_ui(self):
try:
from .recent_table import RecentTable
self._recent_table = RecentTable(self.__recent_files, on_selection_changed_fn=self.__on_recent_selected_fn)
except Exception as e:
self._recent_table = None
carb.log_error(f"Failed to create recent table: {e}")
def _build_grid_ui(self):
with ui.VStack():
# Recent grid
with ui.HStack():
ui.Spacer(width=8)
self._recent_grid = ThumbnailGrid(self._grid_model, on_selection_changed=self.__on_recent_selected_fn)
ui.Spacer(width=8)
def _on_change(self, item, event_type):
if event_type == carb.settings.ChangeEventType.CHANGED:
self.__recent_files = self._settings.get(SETTING_RECENT_FILES)
self.__rebuild_recents()
def __rebuild_recents_from_event(self) -> None:
from omni.kit.helper.file_utils import get_latest_urls_from_event_queue, asset_types
self.__recent_files = get_latest_urls_from_event_queue(self._max_recent_files, asset_type=asset_types.ASSET_TYPE_USD)
if self._recent_table:
self._recent_table.refresh(self.__recent_files)
self._grid_model.refresh(self.__recent_files)
def __get_recent_history(self):
load_recents_from_event = self._settings.get("/exts/omni.kit.welcome.open/load_recent_from_event")
if load_recents_from_event:
self.__get_recent_from_event()
else:
self.__recent_files = self._settings.get(SETTING_RECENT_FILES)
# If recent files changed, refresh
self._subscription = omni.kit.app.SettingChangeSubscription(SETTING_RECENT_FILES, self._on_change)
def __get_recent_from_event(self) -> None:
import omni.kit.app
manager = omni.kit.app.get_app().get_extension_manager()
manager.set_extension_enabled_immediate("omni.kit.helper.file_utils", True)
from omni.kit.helper.file_utils import get_latest_urls_from_event_queue, asset_types, FILE_EVENT_QUEUE_UPDATED
self._max_recent_files = self._settings.get("exts/omni.kit.menu.file/maxRecentFiles") or 10
self.__recent_files = get_latest_urls_from_event_queue(self._max_recent_files, asset_type=asset_types.ASSET_TYPE_USD)
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
self._event_sub = event_stream.create_subscription_to_pop_by_type(FILE_EVENT_QUEUE_UPDATED, lambda _: self.__rebuild_recents_from_event())
| 6,736 |
Python
| 39.10119 | 146 | 0.614757 |
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/open_action.py
|
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["run_open_action"]
import asyncio
def run_open_action(extension_id: str, action_id: str, *args, **kwargs):
import omni.kit.actions.core
action_registry = omni.kit.actions.core.get_action_registry()
# Setup the viewport (and UI first)
action_registry.execute_action("omni.app.setup", "enable_viewport_rendering")
# Finally hide the Welcome window
from omni.kit.welcome.window import show_window as show_welcome_window
show_welcome_window(visible=False, stage_opened=True)
# Run the action which will open or create a Usd.Stage
async def __execute_action():
import omni.kit.app
# OM-90720: sometimes open stage will popup a prompt to ask if save current stage
# But the prompt is a popup window which will hide immediately if the welcome window (modal) still there
# As a result, the required stage will not be opened
# So here wait a few frames to make sure welcome window is really closed
for _ in range(4):
await omni.kit.app.get_app().next_update_async()
action_registry.execute_action(extension_id, action_id, *args, **kwargs)
asyncio.ensure_future(__execute_action())
| 1,624 |
Python
| 45.42857 | 112 | 0.723522 |
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/open_widget.py
|
from typing import Dict, Optional
import carb
import omni.ui as ui
from omni.kit.welcome.window import show_window as show_welcome_window
from omni.ui import constant as fl
from .stage_tab import StageTab
from .style import OPEN_PAGE_STYLE
class OpenWidget:
"""
Widget for open page.
"""
def __init__(self):
self.__tabs: Dict[str, callable] = {
"STAGE": self.__build_stage,
"SAMPLES": self.__build_sample,
"FILE": self.__build_file,
}
self.__tab_frames: Dict[str, ui.Frame] = {}
self.__stage_tab: Optional[StageTab] = None
self._build_ui()
def destroy(self):
if self.__stage_tab:
self.__stage_tab.destroy()
self.__stage_tab = None
def _build_ui(self):
self._collection = ui.RadioCollection()
with ui.ZStack(style=OPEN_PAGE_STYLE):
# Background
ui.Rectangle(style_type_name_override="Content")
with ui.VStack():
# Tab buttons
with ui.VStack(height=fl._find("welcome_page_title_height")):
ui.Spacer()
with ui.HStack(height=0):
ui.Spacer()
with ui.HStack(spacing=30):
for tab in self.__tabs.keys():
ui.RadioButton(text=tab, width=0, spacing=8, image_width=24, image_height=24, name=tab, radio_collection=self._collection, clicked_fn=lambda t=tab: self._show_tab(t))
ui.Spacer()
ui.Spacer()
# Tab frames
with ui.ZStack():
for tab in self.__tabs.keys():
self.__tab_frames[tab] = ui.Frame(build_fn=lambda t=tab: self.__tabs[t](), visible=tab == "STAGE")
def _show_tab(self, name: str) -> None:
for tab in self.__tabs.keys():
if tab == name:
self.__tab_frames[name].visible = True
else:
self.__tab_frames[tab].visible = False
def __build_stage(self):
self.__stage_tab = StageTab()
def __build_sample(self):
try:
import omni.kit.app
manager = omni.kit.app.get_app().get_extension_manager()
manager.set_extension_enabled_immediate("omni.kit.browser.sample", True)
from omni.kit.browser.sample import get_instance as get_sample_instance
from omni.kit.browser.sample.browser_widget import SampleTreeFolderBrowserWidget
from omni.kit.browser.core import BrowserSearchBar
# Remove options button
class SampleWidget(SampleTreeFolderBrowserWidget):
def _build_search_bar(self):
self._search_bar = BrowserSearchBar(options_menu=None)
# Hack to close welcome window after sample opened
def __open_sample(item):
from .open_action import run_open_action
run_open_action("omni.kit.window.file", "open_stage", item.url)
model = get_sample_instance().get_model()
model.execute = __open_sample
# Sample widget
with ui.ZStack():
ui.Rectangle(style_type_name_override="Stage.Separator")
with ui.VStack():
ui.Spacer(height=4)
with ui.HStack():
ui.Spacer(width=2)
self.__sample_widget = SampleWidget(model)
# Open widgets
with ui.ZStack(height=26):
ui.Rectangle(style_type_name_override="Stage.Separator")
with ui.VStack():
ui.Spacer(height=2)
with ui.HStack(spacing=2):
ui.Rectangle(style_type_name_override="Stage.Blank")
# Button size/style to be same as omni.kit.window.filepicker.FilePickerWidget
ui.Button("Open File", width=117, style_type_name_override="Stage.Button", mouse_pressed_fn=lambda x, y, a, f:self.__open_sample())
ui.Button("Close", width=117, style_type_name_override="Stage.Button", mouse_pressed_fn=lambda x, y, a, f:show_welcome_window(visible=False))
except Exception as e:
carb.log_error(f"Failed to import sample browser widget: {e}")
def __build_file(self):
try:
from omni.kit.window.filepicker import FilePickerWidget
def __open_file(file_name, dir_name):
from .open_action import run_open_action
run_open_action("omni.kit.window.file", "open_stage", dir_name + file_name)
with ui.ZStack():
ui.Rectangle(style_type_name_override="Stage.Separator")
with ui.VStack():
ui.Spacer(height=2)
with ui.HStack():
ui.Spacer(width=2)
FilePickerWidget(
"Welcome",
enable_checkpoints=True,
apply_button_label="Open File",
cancel_button_label="Close",
click_apply_handler=__open_file,
click_cancel_handler=lambda f, d: show_welcome_window(visible=False),
modal=True,
)
except Exception as e:
carb.log_error(f"Failed to import file picker widget: {e}")
def __open_sample(self):
selections = self.__sample_widget.detail_selection
if selections:
self.__sample_widget._browser_model.execute(selections[0])
show_welcome_window(visible=False)
| 5,849 |
Python
| 42.333333 | 198 | 0.526586 |
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/recent_table.py
|
import os
from typing import List, Optional
import omni.client
import omni.ui as ui
from omni.kit.widget.filebrowser import LAYOUT_SINGLE_PANE_LIST, LISTVIEW_PANE, FileBrowserItem, FileBrowserModel
from omni.kit.widget.filebrowser.model import FileBrowserItemFields
from omni.kit.window.filepicker import FilePickerWidget
class RecentTableModel(FileBrowserModel):
def __init__(self, recent_files: List[str]):
super().__init__()
self.refresh(recent_files)
def get_item_children(self, item: FileBrowserItem) -> [FileBrowserItem]:
return self._items
def refresh(self, recent_files: List[str]):
if recent_files:
self._items = [self.__create_file_item(url) for url in recent_files]
else:
self._items = []
self._item_changed(None)
def __create_file_item(self, url: str) -> Optional[FileBrowserItem]:
file_name = os.path.basename(url)
result, entry = omni.client.stat(url)
if result == omni.client.Result.OK:
item = FileBrowserItem(url, FileBrowserItemFields(file_name, entry.modified_time, 0, 0), is_folder=False)
item._models = (ui.SimpleStringModel(item.name), entry.modified_time, ui.SimpleStringModel(""))
return item
else:
return None
class RecentTable:
def __init__(self, recent_files: List[str], on_selection_changed_fn: callable):
self.__recent_files = recent_files
self.__picker: Optional[FilePickerWidget] = None
self.__on_selection_changed_fn = on_selection_changed_fn
self._build_ui()
@property
def selected(self) -> str:
if self.__picker:
selections = self.__picker._view.get_selections(pane=LISTVIEW_PANE)
if selections:
return selections[0].path
else:
return ""
else:
return ""
@selected.setter
def selected(self, url: str) -> None:
if self.__picker:
if url:
for item in self._model.get_item_children(None):
if item.path == url:
selections = [item]
else:
selections = []
self.__picker._view.set_selections(selections, pane=LISTVIEW_PANE)
def refresh(self, recent_files: List[str]):
self._model.refresh(recent_files)
def get_filename(self) -> str:
return self.__picker._api.get_filename() if self.__picker else ""
def _build_ui(self):
with ui.ZStack():
ui.Rectangle(style_type_name_override="Stage.Separator")
with ui.VStack():
ui.Spacer(height=2)
with ui.HStack():
self.__picker = FilePickerWidget(
"Welcome",
enable_tool_bar=False,
layout=LAYOUT_SINGLE_PANE_LIST,
show_grid_view=False,
save_grid_view=False,
enable_checkpoints=True,
enable_zoombar=False,
enable_file_bar=False,
selection_changed_fn=self.__on_selection_changed_fn,
)
self._model = RecentTableModel(self.__recent_files)
self.__picker._view.show_model(self._model)
| 3,377 |
Python
| 35.717391 | 117 | 0.568256 |
omniverse-code/kit/exts/omni.kit.welcome.open/omni/kit/welcome/open/template_grid.py
|
import functools
import locale
from typing import List
import omni.kit.stage_templates
import omni.ui as ui
from omni.kit.welcome.window import show_window
from .style import ICON_PATH
from .thumbnail_grid import ThumbnailGrid, ThumbnailItem, ThumbnailModel
import asyncio
class TemplateItem(ThumbnailItem):
"""
Data item for template.
"""
def __init__(self, template: list):
# TODO: how to get template thumbnail?
stage_name = template[0]
super().__init__("", stage_name)
def execute(self):
from .open_action import run_open_action
run_open_action("omni.kit.stage.templates", self.__get_action_name())
def __get_action_name(self):
return "create_new_stage_" + self.url.lower().replace('-', '_').replace(' ', '_')
class TemplateModel(ThumbnailModel):
"""
Data model for templates.
"""
def __init__(self):
stage_templates = omni.kit.stage_templates.get_stage_template_list()
template_items: List[ThumbnailItem] = []
def sort_cmp(template1, template2):
return locale.strcoll(template1[0], template2[0])
for template_list in stage_templates:
for template in sorted(template_list.items(), key=functools.cmp_to_key(sort_cmp)):
template_items.append(TemplateItem(template))
super().__init__(template_items)
class TemplateGrid(ThumbnailGrid):
"""
Template grid.
"""
def __init__(self, **kwargs):
self._model = TemplateModel()
super().__init__(self._model, **kwargs)
def build_thumbnail(self, item: ThumbnailItem):
padding = 5
with ui.ZStack():
super().build_thumbnail(item)
with ui.VStack():
ui.Spacer()
with ui.HStack(height=20):
ui.Spacer()
ui.Image(
f"{ICON_PATH}/add_dark.svg",
width=20,
style_type_name_override="Template.Add",
mouse_pressed_fn=lambda x, y, a, f, i=item: i.execute()
)
ui.Spacer(width=padding)
ui.Spacer(height=padding)
| 2,216 |
Python
| 29.791666 | 94 | 0.576715 |
omniverse-code/kit/exts/omni.kit.selection/config/extension.toml
|
[package]
version = "0.1.0"
category = "Internal"
[dependencies]
"omni.kit.commands" = {}
"omni.ui" = {}
"omni.usd" = {}
[[python.module]]
name = "omni.kit.selection"
| 169 |
TOML
| 13.166666 | 27 | 0.621302 |
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/selection_actions.py
|
import omni.kit.actions.core
def register_actions(extension_id):
import omni.kit.commands
action_registry = omni.kit.actions.core.get_action_registry()
actions_tag = "Selection Actions"
action_registry.register_action(
extension_id,
"all",
lambda: omni.kit.commands.execute("SelectAll"),
display_name="Select->All",
description="Select all prims.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"none",
lambda: omni.kit.commands.execute("SelectNone"),
display_name="Select->None",
description="Deselect all prims.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"invert",
lambda: omni.kit.commands.execute("SelectInvert"),
display_name="Select->Invert",
description="Deselect all currently unselected prims, and select all currently unselected prims.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"parent",
lambda: omni.kit.commands.execute("SelectParentCommand"),
display_name="Select->Parent",
description="Select the parents of all currently selected prims.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"leaf",
lambda: omni.kit.commands.execute("SelectLeafCommand"),
display_name="Select->Leaf",
description="Select the leafs of all currently selected prims.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"hierarchy",
lambda: omni.kit.commands.execute("SelectHierarchyCommand"),
display_name="Select->Hierarchy",
description="Select the hierachies of all currently selected prims.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"similar",
lambda: omni.kit.commands.execute("SelectSimilarCommand"),
display_name="Select->Similar",
description="Select prims of the same type as any currently selected prim.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"HideUnselected",
lambda: omni.kit.commands.execute("HideUnselected"),
display_name="Select->Hide Unselected",
description="Hide Unselected Prims",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"UnhideAllPrims",
lambda: omni.kit.commands.execute("UnhideAllPrims"),
display_name="Select->Unhide All Prims",
description="Unhide All Prims",
tag=actions_tag,
)
def deregister_actions(extension_id):
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.deregister_all_actions_for_extension(extension_id)
| 2,880 |
Python
| 31.370786 | 106 | 0.639931 |
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/__init__.py
|
from .selection import *
| 25 |
Python
| 11.999994 | 24 | 0.76 |
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/selection.py
|
import omni.kit.commands
from pxr import Usd, Sdf, UsdGeom, Gf, Tf, Trace, Kind
from .selection_actions import register_actions, deregister_actions
class SelectionExtension(omni.ext.IExt):
def on_startup(self, ext_id):
self._ext_name = omni.ext.get_extension_name(ext_id)
register_actions(self._ext_name)
def on_shutdown(self):
deregister_actions(self._ext_name)
class SelectAllCommand(omni.kit.commands.Command):
"""
Select all prims.
Args:
type (Union[str, None]): Specific type name. If it's None, it will select
all prims. If it has type str with value "", it will select all prims without any type.
Otherwise, it will select prims with that type.
"""
def __init__(self, type=None):
self._type = type
self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths()
@Trace.TraceFunction
def do(self):
omni.usd.get_context().get_selection().select_all_prims(self._type)
def undo(self):
if self._prev_selection:
omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True)
else:
omni.usd.get_context().get_selection().clear_selected_prim_paths()
class SelectNoneCommand(omni.kit.commands.Command):
def __init__(self):
self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths()
def do(self):
omni.usd.get_context().get_selection().clear_selected_prim_paths()
def undo(self):
omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True)
class SelectInvertCommand(omni.kit.commands.Command):
def __init__(self):
self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths()
@Trace.TraceFunction
def do(self):
omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True)
omni.usd.get_context().get_selection().select_inverted_prims()
def undo(self):
omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True)
class HideUnselectedCommand(omni.kit.commands.Command):
def get_parent_prims(self, stage, prim):
parent_prims = set([])
while prim.GetParent():
parent_prims.add(prim.GetParent().GetPath())
prim = prim.GetParent()
if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim:
break
return parent_prims
def get_all_children(self, prim):
children_list = set([])
queue = [prim]
while len(queue) > 0:
child_prim = queue.pop()
for child in child_prim.GetAllChildren():
children_list.add(child.GetPath())
queue.append(child)
return children_list
def __init__(self):
stage = omni.usd.get_context().get_stage()
selection = omni.usd.get_context().get_selection().get_selected_prim_paths()
# if selected path as children and none of the children are selected, then all the children are selected..
selected_prims = set([])
for prim_path in selection:
sdf_prim_path = Sdf.Path(prim_path)
prim = stage.GetPrimAtPath(sdf_prim_path)
if prim:
selected_prims.add(sdf_prim_path)
selected_prims.update(self.get_all_children(prim))
## exclude parent prims as visabillity is inherited
all_parent_prims = set([])
for prim_path in selected_prims:
prim = stage.GetPrimAtPath(prim_path)
if prim:
all_parent_prims.update(self.get_parent_prims(stage, prim))
selected_prims.update(all_parent_prims)
all_prims = set([])
children_iterator = iter(stage.TraverseAll())
for prim in children_iterator:
if omni.usd.is_hidden_type(prim):
children_iterator.PruneChildren()
continue
all_prims.add(prim.GetPath())
self._invert_prims = [item for item in all_prims if item not in selected_prims]
self._prev_visabillity = []
for prim_path in self._invert_prims:
prim = stage.GetPrimAtPath(prim_path)
if prim:
if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim:
continue
imageable = UsdGeom.Imageable(prim)
if imageable:
self._prev_visabillity.append([prim, imageable.ComputeVisibility()])
@Trace.TraceFunction
def do(self):
stage = omni.usd.get_context().get_stage()
for prim_path in self._invert_prims:
prim = stage.GetPrimAtPath(prim_path)
if prim:
if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim:
continue
imageable = UsdGeom.Imageable(prim)
if imageable:
imageable.MakeInvisible()
def undo(self):
for prim, state in self._prev_visabillity:
imageable = UsdGeom.Imageable(prim)
if imageable:
if state == UsdGeom.Tokens.invisible:
imageable.MakeInvisible()
else:
imageable.MakeVisible()
class SelectParentCommand(omni.kit.commands.Command):
def __init__(self):
self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths()
def do(self):
stage = omni.usd.get_context().get_stage()
parent_prims = set()
for prim_path in self._prev_selection:
prim = stage.GetPrimAtPath(prim_path)
if prim and prim.GetParent() is not None:
parent_prims.add(prim.GetParent().GetPath().pathString)
omni.usd.get_context().get_selection().set_selected_prim_paths(sorted(list(parent_prims)), True)
def undo(self):
omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True)
class SelectLeafCommand(omni.kit.commands.Command):
def __init__(self):
self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths()
def collect_leafs(self, prim, leaf_set):
prim_children = prim.GetChildren()
if not prim_children:
leaf_set.add(prim.GetPath().pathString)
else:
for child in prim_children:
self.collect_leafs(child, leaf_set)
def do(self):
stage = omni.usd.get_context().get_stage()
leaf_prims = set()
for prim_path in self._prev_selection:
prim = stage.GetPrimAtPath(prim_path)
self.collect_leafs(prim, leaf_prims)
omni.usd.get_context().get_selection().set_selected_prim_paths(sorted(list(leaf_prims)), True)
def undo(self):
omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True)
class SelectHierarchyCommand(omni.kit.commands.Command):
def __init__(self):
self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths()
def collect_hierarchy(self, prim, hierarchy_set):
hierarchy_set.add(prim.GetPath().pathString)
prim_children = prim.GetChildren()
for child in prim_children:
self.collect_hierarchy(child, hierarchy_set)
def do(self):
stage = omni.usd.get_context().get_stage()
heirarchy_prims = set()
for prim_path in self._prev_selection:
prim = stage.GetPrimAtPath(prim_path)
self.collect_hierarchy(prim, heirarchy_prims)
omni.usd.get_context().get_selection().set_selected_prim_paths(sorted(list(heirarchy_prims)), True)
def undo(self):
omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True)
class SelectSimilarCommand(omni.kit.commands.Command):
def __init__(self):
self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths()
def do(self):
stage = omni.usd.get_context().get_stage()
similar_prim_types = set()
for prim_path in self._prev_selection:
prim_type = stage.GetPrimAtPath(prim_path).GetTypeName()
similar_prim_types.add(prim_type)
omni.usd.get_context().get_selection().select_all_prims(sorted(list(similar_prim_types)))
def undo(self):
omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True)
class SelectListCommand(omni.kit.commands.Command):
def __init__(self, **kwargs):
self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths()
self._new_selection = []
if 'selection' in kwargs:
self._new_selection = kwargs['selection']
def do(self):
omni.usd.get_context().get_selection().set_selected_prim_paths(self._new_selection, True)
def undo(self):
omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True)
class SelectKindCommand(omni.kit.commands.Command):
def __init__(self, **kwargs):
self._prev_selection = omni.usd.get_context().get_selection().get_selected_prim_paths()
self._kind = ""
if 'kind' in kwargs:
self._kind = kwargs['kind']
@Trace.TraceFunction
def do(self):
selection = []
for prim in omni.usd.get_context().get_stage().TraverseAll():
model_api = Usd.ModelAPI(prim)
if Kind.Registry.IsA(model_api.GetKind(), self._kind):
selection.append(str(prim.GetPath()))
omni.usd.get_context().get_selection().set_selected_prim_paths(selection, True)
def undo(self):
omni.usd.get_context().get_selection().set_selected_prim_paths(self._prev_selection, True)
| 9,914 |
Python
| 36.415094 | 114 | 0.620637 |
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/tests/create_prims.py
|
import os
import carb
import carb.settings
import omni.kit.commands
from pxr import Usd, Sdf, UsdGeom, Gf, Tf, UsdShade, UsdLux
def create_test_stage():
settings = carb.settings.get_settings()
default_prim_name = settings.get("/persistent/app/stage/defaultPrimName")
rootname = f"/{default_prim_name}"
stage = omni.usd.get_context().get_stage()
kit_folder = carb.tokens.get_tokens_interface().resolve("${kit}")
omni_pbr_mtl = os.path.normpath(kit_folder + "/mdl/core/Base/OmniPBR.mdl")
# create Looks folder
omni.kit.commands.execute(
"CreatePrim", prim_path="{}/Looks".format(rootname), prim_type="Scope", select_new_prim=False
)
# create GroundMat material
mtl_name = "GroundMat"
mtl_path = omni.usd.get_stage_next_free_path(
stage, "{}/Looks/{}".format(rootname, Tf.MakeValidIdentifier(mtl_name)), False
)
omni.kit.commands.execute(
"CreateMdlMaterialPrim", mtl_url=omni_pbr_mtl, mtl_name=mtl_name, mtl_path=mtl_path
)
ground_mat_prim = stage.GetPrimAtPath(mtl_path)
shader = UsdShade.Material(ground_mat_prim).ComputeSurfaceSource("mdl")[0]
shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl")
omni.usd.create_material_input(ground_mat_prim, "reflection_roughness_constant", 0.36, Sdf.ValueTypeNames.Float)
omni.usd.create_material_input(ground_mat_prim, "specular_level", 0.25, Sdf.ValueTypeNames.Float)
omni.usd.create_material_input(
ground_mat_prim, "diffuse_color_constant", Gf.Vec3f(0.08, 0.08, 0.08), Sdf.ValueTypeNames.Color3f
)
omni.usd.create_material_input(ground_mat_prim, "diffuse_tint", Gf.Vec3f(1, 1, 1), Sdf.ValueTypeNames.Color3f)
omni.usd.create_material_input(ground_mat_prim, "diffuse_tint", Gf.Vec3f(1, 1, 1), Sdf.ValueTypeNames.Color3f)
omni.usd.create_material_input(ground_mat_prim, "metallic_constant", 0.0, Sdf.ValueTypeNames.Float)
omni.usd.create_material_input(ground_mat_prim, "reflection_roughness_constant", 0.36, Sdf.ValueTypeNames.Float)
# create BackSideMat
mtl_name = "BackSideMat"
backside_mtl_path = omni.usd.get_stage_next_free_path(
stage, "{}/Looks/{}".format(rootname, Tf.MakeValidIdentifier(mtl_name)), False
)
omni.kit.commands.execute(
"CreateMdlMaterialPrim", mtl_url=omni_pbr_mtl, mtl_name=mtl_name, mtl_path=backside_mtl_path
)
backside_mtl_prim = stage.GetPrimAtPath(backside_mtl_path)
shader = UsdShade.Material(backside_mtl_prim).ComputeSurfaceSource("mdl")[0]
shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl")
omni.usd.create_material_input(
backside_mtl_prim,
"diffuse_color_constant",
Gf.Vec3f(0.11814344, 0.118142255, 0.118142255),
Sdf.ValueTypeNames.Color3f,
)
omni.usd.create_material_input(backside_mtl_prim, "reflection_roughness_constant", 0.27, Sdf.ValueTypeNames.Float)
omni.usd.create_material_input(backside_mtl_prim, "specular_level", 0.163, Sdf.ValueTypeNames.Float)
# create EmissiveMat
mtl_name = "EmissiveMat"
emissive_mtl_path = omni.usd.get_stage_next_free_path(
stage, "{}/Looks/{}".format(rootname, Tf.MakeValidIdentifier(mtl_name)), False
)
omni.kit.commands.execute(
"CreateMdlMaterialPrim", mtl_url=omni_pbr_mtl, mtl_name=mtl_name, mtl_path=emissive_mtl_path
)
emissive_mtl_prim = stage.GetPrimAtPath(emissive_mtl_path)
shader = UsdShade.Material(emissive_mtl_prim).ComputeSurfaceSource("mdl")[0]
shader.SetSourceAssetSubIdentifier("OmniPBR", "mdl")
omni.usd.create_material_input(
emissive_mtl_prim, "diffuse_color_constant", Gf.Vec3f(0, 0, 0), Sdf.ValueTypeNames.Color3f
)
omni.usd.create_material_input(emissive_mtl_prim, "reflection_roughness_constant", 1, Sdf.ValueTypeNames.Float)
omni.usd.create_material_input(emissive_mtl_prim, "specular_level", 0, Sdf.ValueTypeNames.Float)
omni.usd.create_material_input(emissive_mtl_prim, "enable_emission", True, Sdf.ValueTypeNames.Bool)
omni.usd.create_material_input(emissive_mtl_prim, "emissive_color", Gf.Vec3f(1, 1, 1), Sdf.ValueTypeNames.Color3f)
omni.usd.create_material_input(emissive_mtl_prim, "emissive_intensity", 15000, Sdf.ValueTypeNames.Float)
# create studiohemisphere
hemisphere_path = omni.usd.get_stage_next_free_path(stage, "{}/studiohemisphere".format(rootname), False)
omni.kit.commands.execute(
"CreatePrim", prim_path=hemisphere_path, prim_type="Xform", select_new_prim=False, attributes={}
)
hemisphere_prim = stage.GetPrimAtPath(hemisphere_path)
UsdGeom.PrimvarsAPI(hemisphere_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
Usd.ModelAPI(hemisphere_prim).SetKind("group")
# create sphere
hemisphere_sphere_path = omni.usd.get_stage_next_free_path(
stage, "{}/studiohemisphere/Sphere".format(rootname), False
)
omni.kit.commands.execute(
"CreatePrim",
prim_path=hemisphere_sphere_path,
prim_type="Sphere",
select_new_prim=False,
attributes={UsdGeom.Tokens.radius: 100},
)
hemisphere_prim = stage.GetPrimAtPath(hemisphere_sphere_path)
Usd.ModelAPI(hemisphere_prim).SetKind("assembly")
# set transform
hemisphere_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(2500, 2500, 2500))
hemisphere_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:scale"])
UsdGeom.PrimvarsAPI(hemisphere_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
# bind material
omni.kit.commands.execute(
"BindMaterial",
prim_path=hemisphere_sphere_path,
material_path=mtl_path,
strength=UsdShade.Tokens.strongerThanDescendants,
)
# create floor
hemisphere_floor_path = omni.usd.get_stage_next_free_path(
stage, "{}/studiohemisphere/Floor".format(rootname), False
)
omni.kit.commands.execute(
"CreatePrim",
prim_path=hemisphere_floor_path,
prim_type="Cube",
select_new_prim=False,
attributes={UsdGeom.Tokens.size: 100},
)
hemisphere_floor_prim = stage.GetPrimAtPath(hemisphere_floor_path)
# set transform
hemisphere_floor_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(
Gf.Vec3d(2500, 0.1, 2500)
)
hemisphere_floor_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(["xformOp:scale"])
UsdGeom.PrimvarsAPI(hemisphere_floor_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
# bind material
omni.kit.commands.execute(
"BindMaterial",
prim_path=hemisphere_floor_path,
material_path=mtl_path,
strength=UsdShade.Tokens.strongerThanDescendants,
)
# create LightPivot_01
light_pivot1_path = omni.usd.get_stage_next_free_path(stage, "{}/LightPivot_01".format(rootname), False)
omni.kit.commands.execute(
"CreatePrim", prim_path=light_pivot1_path, prim_type="Xform", select_new_prim=False, attributes={}
)
light_pivot1_prim = stage.GetPrimAtPath(light_pivot1_path)
UsdGeom.PrimvarsAPI(light_pivot1_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
# set transform
light_pivot1_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
light_pivot1_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(
Gf.Vec3d(-30.453436397207547, 16.954190666353664, 9.728788165428536)
)
light_pivot1_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(
Gf.Vec3d(0.9999999445969171, 1.000000574567198, 0.9999995086845976)
)
light_pivot1_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(
["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"]
)
# create AreaLight
light_pivot1_al_path = omni.usd.get_stage_next_free_path(
stage, "{}/LightPivot_01/AreaLight".format(rootname), False
)
omni.kit.commands.execute(
"CreatePrim", prim_path=light_pivot1_al_path, prim_type="Xform", select_new_prim=False, attributes={}
)
light_pivot1_al_prim = stage.GetPrimAtPath(light_pivot1_al_path)
UsdGeom.PrimvarsAPI(light_pivot1_al_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
# set transform
light_pivot1_al_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(
Gf.Vec3d(0, 0, 800)
)
light_pivot1_al_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
light_pivot1_al_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(
Gf.Vec3d(4.5, 4.5, 4.5)
)
light_pivot1_al_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(
["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"]
)
# create AreaLight RectLight
light_pivot1_alrl_path = omni.usd.get_stage_next_free_path(
stage, "{}/LightPivot_01/AreaLight/RectLight".format(rootname), False
)
omni.kit.commands.execute(
"CreatePrim",
prim_path=light_pivot1_alrl_path,
prim_type="RectLight",
select_new_prim=False,
attributes={},
)
light_pivot1_alrl_prim = stage.GetPrimAtPath(light_pivot1_alrl_path)
# set values
# https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7
# https://github.com/PixarAnimationStudios/USD/commit/3738719d72e60fb78d1cd18100768a7dda7340a4
if hasattr(UsdLux.Tokens, 'inputsIntensity'):
light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsHeight, Sdf.ValueTypeNames.Float, False).Set(100)
light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsWidth, Sdf.ValueTypeNames.Float, False).Set(100)
light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsIntensity, Sdf.ValueTypeNames.Float, False).Set(15000)
light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsShapingConeAngle, Sdf.ValueTypeNames.Float, False).Set(180)
else:
light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.height, Sdf.ValueTypeNames.Float, False).Set(100)
light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.width, Sdf.ValueTypeNames.Float, False).Set(100)
light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.intensity, Sdf.ValueTypeNames.Float, False).Set(15000)
light_pivot1_alrl_prim.CreateAttribute(UsdLux.Tokens.shapingConeAngle, Sdf.ValueTypeNames.Float, False).Set(180)
# create AreaLight Backside
backside_albs_path = omni.usd.get_stage_next_free_path(
stage, "{}/LightPivot_01/AreaLight/Backside".format(rootname), False
)
omni.kit.commands.execute(
"CreatePrim",
prim_path=backside_albs_path,
prim_type="Cube",
select_new_prim=False,
attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]},
)
backside_albs_prim = stage.GetPrimAtPath(backside_albs_path)
# set values
backside_albs_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 1.1))
backside_albs_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
backside_albs_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02))
backside_albs_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(
["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"]
)
UsdGeom.PrimvarsAPI(backside_albs_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
# bind material
omni.kit.commands.execute(
"BindMaterial",
prim_path=backside_albs_path,
material_path=backside_mtl_path,
strength=UsdShade.Tokens.strongerThanDescendants,
)
# create AreaLight EmissiveSurface
backside_ales_path = omni.usd.get_stage_next_free_path(
stage, "{}/LightPivot_01/AreaLight/EmissiveSurface".format(rootname), False
)
omni.kit.commands.execute(
"CreatePrim",
prim_path=backside_ales_path,
prim_type="Cube",
select_new_prim=False,
attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]},
)
backside_ales_prim = stage.GetPrimAtPath(backside_ales_path)
# set values
backside_ales_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(
Gf.Vec3d(0, 0, 0.002)
)
backside_ales_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
backside_ales_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02))
backside_ales_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(
["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"]
)
UsdGeom.PrimvarsAPI(backside_ales_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
# bind material
omni.kit.commands.execute(
"BindMaterial",
prim_path=backside_ales_path,
material_path=emissive_mtl_path,
strength=UsdShade.Tokens.strongerThanDescendants,
)
# create LightPivot_02
light_pivot2_path = omni.usd.get_stage_next_free_path(stage, "{}/LightPivot_02".format(rootname), False)
omni.kit.commands.execute(
"CreatePrim", prim_path=light_pivot2_path, prim_type="Xform", select_new_prim=False, attributes={}
)
light_pivot2_prim = stage.GetPrimAtPath(light_pivot2_path)
UsdGeom.PrimvarsAPI(light_pivot2_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
# set transform
light_pivot2_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
light_pivot2_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(
Gf.Vec3d(-149.8694695859529, 35.87684189578612, -18.78499937937383)
)
light_pivot2_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(
Gf.Vec3d(0.9999999347425043, 0.9999995656418647, 1.0000001493100235)
)
light_pivot2_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(
["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"]
)
# create AreaLight
light_pivot2_al_path = omni.usd.get_stage_next_free_path(
stage, "{}/LightPivot_02/AreaLight".format(rootname), False
)
omni.kit.commands.execute(
"CreatePrim", prim_path=light_pivot2_al_path, prim_type="Xform", select_new_prim=False, attributes={}
)
light_pivot2_al_prim = stage.GetPrimAtPath(light_pivot2_al_path)
UsdGeom.PrimvarsAPI(light_pivot2_al_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
# set transform
light_pivot2_al_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(
Gf.Vec3d(0, 0, 800)
)
light_pivot2_al_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
light_pivot2_al_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(
Gf.Vec3d(1.5, 1.5, 1.5)
)
light_pivot2_al_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(
["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"]
)
# create AreaLight RectLight
light_pivot2_alrl_path = omni.usd.get_stage_next_free_path(
stage, "{}/LightPivot_02/AreaLight/RectLight".format(rootname), False
)
omni.kit.commands.execute(
"CreatePrim",
prim_path=light_pivot2_alrl_path,
prim_type="RectLight",
select_new_prim=False,
attributes={},
)
light_pivot2_alrl_prim = stage.GetPrimAtPath(light_pivot2_alrl_path)
# set values
# https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7
# https://github.com/PixarAnimationStudios/USD/commit/3738719d72e60fb78d1cd18100768a7dda7340a4
if hasattr(UsdLux.Tokens, 'inputsIntensity'):
light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsHeight, Sdf.ValueTypeNames.Float, False).Set(100)
light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsWidth, Sdf.ValueTypeNames.Float, False).Set(100)
light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsIntensity, Sdf.ValueTypeNames.Float, False).Set(55000)
light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.inputsShapingConeAngle, Sdf.ValueTypeNames.Float, False).Set(180)
else:
light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.height, Sdf.ValueTypeNames.Float, False).Set(100)
light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.width, Sdf.ValueTypeNames.Float, False).Set(100)
light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.intensity, Sdf.ValueTypeNames.Float, False).Set(55000)
light_pivot2_alrl_prim.CreateAttribute(UsdLux.Tokens.shapingConeAngle, Sdf.ValueTypeNames.Float, False).Set(180)
# create AreaLight Backside
backside_albs_path = omni.usd.get_stage_next_free_path(
stage, "{}/LightPivot_02/AreaLight/Backside".format(rootname), False
)
omni.kit.commands.execute(
"CreatePrim",
prim_path=backside_albs_path,
prim_type="Cube",
select_new_prim=False,
attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]},
)
backside_albs_prim = stage.GetPrimAtPath(backside_albs_path)
# set values
backside_albs_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 1.1))
backside_albs_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
backside_albs_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02))
backside_albs_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(
["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"]
)
UsdGeom.PrimvarsAPI(backside_albs_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
# bind material
omni.kit.commands.execute(
"BindMaterial",
prim_path=backside_albs_path,
material_path=backside_mtl_path,
strength=UsdShade.Tokens.strongerThanDescendants,
)
# create AreaLight EmissiveSurface
backside_ales_path = omni.usd.get_stage_next_free_path(
stage, "{}/LightPivot_02/AreaLight/EmissiveSurface".format(rootname), False
)
omni.kit.commands.execute(
"CreatePrim",
prim_path=backside_ales_path,
prim_type="Cube",
select_new_prim=False,
attributes={UsdGeom.Tokens.size: 100, UsdGeom.Tokens.extent: [(-50, -50, -50), (50, 50, 50)]},
)
backside_ales_prim = stage.GetPrimAtPath(backside_ales_path)
# set values
backside_ales_prim.CreateAttribute("xformOp:translate", Sdf.ValueTypeNames.Double3, False).Set(
Gf.Vec3d(0, 0, 0.002)
)
backside_ales_prim.CreateAttribute("xformOp:rotateZYX", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(0, 0, 0))
backside_ales_prim.CreateAttribute("xformOp:scale", Sdf.ValueTypeNames.Double3, False).Set(Gf.Vec3d(1, 1, 0.02))
backside_ales_prim.CreateAttribute("xformOpOrder", Sdf.ValueTypeNames.String, False).Set(
["xformOp:translate", "xformOp:rotateZYX", "xformOp:scale"]
)
UsdGeom.PrimvarsAPI(backside_ales_prim).CreatePrimvar("doNotCastShadows", Sdf.ValueTypeNames.Bool).Set(True)
# bind material
omni.kit.commands.execute(
"BindMaterial",
prim_path=backside_ales_path,
material_path=emissive_mtl_path,
strength=UsdShade.Tokens.strongerThanDescendants,
)
| 20,064 |
Python
| 48.178921 | 126 | 0.707835 |
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/tests/__init__.py
|
from .test_commands import *
from .create_prims import *
| 57 |
Python
| 18.333327 | 28 | 0.754386 |
omniverse-code/kit/exts/omni.kit.selection/omni/kit/selection/tests/test_commands.py
|
import random
import omni.kit.test
import omni.kit.commands
import omni.kit.undo
from pxr import Usd, UsdGeom, Kind
class TestCommands(omni.kit.test.AsyncTestCase):
def check_visibillity(self, visible_set, invisible_set):
context = omni.usd.get_context()
stage = context.get_stage()
for prim in stage.TraverseAll():
if prim and not prim.GetMetadata("hide_in_stage_window"):
if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim:
continue
imageable = UsdGeom.Imageable(prim)
if imageable:
if imageable.ComputeVisibility() == UsdGeom.Tokens.invisible:
self.assertTrue((prim.GetPath().pathString in invisible_set))
else:
self.assertTrue((prim.GetPath().pathString in visible_set))
def get_parent_prims(self, prim):
stage = omni.usd.get_context().get_stage()
parent_prims = []
while prim.GetParent():
parent_prims.append(prim.GetParent().GetPath().pathString)
prim = prim.GetParent()
if stage.HasDefaultPrim() and stage.GetDefaultPrim() == prim:
break
return parent_prims
def get_all_children(self, prim, child_list):
for child in prim.GetAllChildren():
child_list.append(child.GetPath().pathString)
self.get_all_children(child, child_list)
def get_all_prims(self):
all_prims = []
stage = omni.usd.get_context().get_stage()
for prim in stage.TraverseAll():
if not prim.GetMetadata("hide_in_stage_window"):
all_prims.append(prim.GetPath().pathString)
return all_prims
async def setUp(self):
# Disable logging for the time of tests to avoid spewing errors
await omni.usd.get_context().new_stage_async()
omni.kit.selection.tests.create_test_stage()
async def tearDown(self):
pass
async def test_command_select_all(self):
context = omni.usd.get_context()
selection = context.get_selection()
stage = context.get_stage()
all_root_prims = []
all_prims = []
material_prims = []
cube_prims = []
sphere_prims = []
children_iterator = iter(stage.TraverseAll())
for prim in children_iterator:
all_root_prims.append(prim.GetPath().pathString)
children_iterator.PruneChildren()
for prim in stage.TraverseAll():
if prim.GetMetadata("hide_in_stage_window"):
continue
all_prims.append(prim.GetPath().pathString)
if prim.GetTypeName() == "Material":
material_prims.append(prim.GetPath().pathString)
if prim.GetTypeName() == "Cube":
cube_prims.append(prim.GetPath().pathString)
if prim.GetTypeName() == "Sphere":
sphere_prims.append(prim.GetPath().pathString)
subset_count = int(len(all_prims) >> 1)
subset_prims = random.sample(all_prims, subset_count)
# SelectAllCommand Execute and undo
selection.set_selected_prim_paths(subset_prims, True)
omni.kit.commands.execute("SelectAll")
self.assertListEqual(selection.get_selected_prim_paths(), all_root_prims)
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), subset_prims)
# SelectAllCommand "Material" Execute and undo
selection.set_selected_prim_paths(subset_prims, True)
omni.kit.commands.execute("SelectAll", type="Material")
self.assertListEqual(selection.get_selected_prim_paths(), material_prims)
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), subset_prims)
# SelectAllCommand "Cube" Execute and undo
selection.set_selected_prim_paths(subset_prims, True)
omni.kit.commands.execute("SelectAll", type="Cube")
self.assertListEqual(selection.get_selected_prim_paths(), cube_prims)
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), subset_prims)
# SelectAllCommand "Sphere" Execute and undo
selection.set_selected_prim_paths(subset_prims, True)
omni.kit.commands.execute("SelectAll", type="Sphere")
self.assertListEqual(selection.get_selected_prim_paths(), sphere_prims)
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), subset_prims)
# SelectSimilarCommand: "Sphere" and "Cube"
prim_paths = [sphere_prims[0], cube_prims[0]]
selection.set_selected_prim_paths(prim_paths, True)
omni.kit.commands.execute("SelectSimilar")
all_prims = sphere_prims.copy()
all_prims.extend(cube_prims)
self.assertListEqual(selection.get_selected_prim_paths(), all_prims)
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), prim_paths)
async def test_command_select_none(self):
context = omni.usd.get_context()
selection = context.get_selection()
stage = context.get_stage()
all_prims = self.get_all_prims()
subset_count = int(len(all_prims) >> 1)
subset_prims = random.sample(all_prims, subset_count)
inverse_prims = [item for item in all_prims if item not in subset_prims]
# SelectNoneCommand Execute and undo
selection.set_selected_prim_paths(subset_prims, True)
omni.kit.commands.execute("SelectNone")
self.assertListEqual(selection.get_selected_prim_paths(), [])
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), subset_prims)
async def test_command_select_invert(self):
context = omni.usd.get_context()
selection = context.get_selection()
stage = context.get_stage()
all_prims = []
for prim in stage.TraverseAll():
if not prim.GetMetadata("hide_in_stage_window") and stage.HasDefaultPrim() and not stage.GetDefaultPrim() == prim:
all_prims.append(prim.GetPath().pathString)
# if selected path as children and none of the children are selected, then all the children are selected..
subset_count = int(len(all_prims) >> 1)
subset_prims = []
for prim_path in sorted(random.sample(all_prims, subset_count), reverse=True):
prim = stage.GetPrimAtPath(prim_path)
if prim:
subset_prims.append(prim_path)
child_list = []
self.get_all_children(prim, child_list)
if not set(subset_prims).intersection(set(child_list)):
subset_prims += child_list
# SelectInvertCommand Execute and undo
selection.set_selected_prim_paths(subset_prims, True)
omni.kit.commands.execute("SelectInvert")
self.assertListEqual(selection.get_selected_prim_paths(), ['/World'])
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), subset_prims)
async def test_command_hide_unselected(self):
context = omni.usd.get_context()
selection = context.get_selection()
stage = context.get_stage()
all_prims = self.get_all_prims()
# if selected path as children and none of the children are selected, then all the children are selected..
subset_prims = set()
for prim_path in sorted(random.sample(all_prims, 3), reverse=True):
# we need to remove "/World" from the sampled result since it is the parent of all prims
if prim_path == '/World':
continue
prim = stage.GetPrimAtPath(prim_path)
if prim:
subset_prims.add(prim_path)
child_list = []
self.get_all_children(prim, child_list)
subset_prims.update(child_list)
# HideUnselectedCommand Execute and undo
visible_prims = set()
for prim_path in subset_prims:
prim = stage.GetPrimAtPath(prim_path)
if prim:
visible_prims.add(prim.GetPath().pathString)
visible_prims.update(self.get_parent_prims(prim))
invisible_prims = set([item for item in all_prims if item not in visible_prims])
selection.set_selected_prim_paths(list(subset_prims), True)
omni.kit.commands.execute("HideUnselected")
self.check_visibillity(visible_prims, invisible_prims)
omni.kit.undo.undo()
self.check_visibillity(all_prims, [])
async def test_command_select_parent(self):
context = omni.usd.get_context()
selection = context.get_selection()
stage = context.get_stage()
all_prims = self.get_all_prims()
subset_count = int(len(all_prims) >> 1)
subset_prims = random.sample(all_prims, subset_count)
parent_prims = set()
for prim_path in subset_prims:
prim = stage.GetPrimAtPath(prim_path)
if prim and prim.GetParent() is not None:
parent_prims.add(prim.GetParent().GetPath().pathString)
parent_prims = list(parent_prims)
selection.set_selected_prim_paths(subset_prims, True)
omni.kit.commands.execute("SelectParent")
self.assertListEqual(selection.get_selected_prim_paths(), sorted(parent_prims))
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), subset_prims)
async def test_command_select_kind(self):
context = omni.usd.get_context()
selection = context.get_selection()
stage = context.get_stage()
all_prims = []
group_prims = []
for prim in stage.TraverseAll():
if Kind.Registry.IsA(Usd.ModelAPI(prim).GetKind(), "group"):
group_prims.append(prim.GetPath().pathString)
if not prim.GetMetadata("hide_in_stage_window"):
all_prims.append(prim.GetPath().pathString)
subset_count = int(len(all_prims) >> 1)
subset_prims = random.sample(all_prims, subset_count)
selection.set_selected_prim_paths(subset_prims, True)
omni.kit.commands.execute("SelectKind", kind="group")
self.assertListEqual(selection.get_selected_prim_paths(), sorted(group_prims))
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), subset_prims)
async def test_command_select_hierarchy(self):
context = omni.usd.get_context()
selection = context.get_selection()
selection.set_selected_prim_paths(['/World'], True)
omni.kit.commands.execute("SelectHierarchy")
self.assertListEqual(selection.get_selected_prim_paths(), sorted(self.get_all_prims()))
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), ['/World'])
async def test_command_select_list(self):
context = omni.usd.get_context()
selection = context.get_selection()
all_prims = self.get_all_prims()
subset_count = int(len(all_prims) >> 1)
subset_prims = random.sample(all_prims, subset_count)
selection.set_selected_prim_paths(['/World'], True)
self.assertListEqual(selection.get_selected_prim_paths(), ['/World'])
# with no kwargs it should clear the selection
omni.kit.commands.execute("SelectList")
self.assertListEqual(selection.get_selected_prim_paths(), [])
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), ['/World'])
# with kwarg it should swap the selection to the new list
omni.kit.commands.execute("SelectList", selection=subset_prims)
self.assertListEqual(sorted(selection.get_selected_prim_paths()), sorted(subset_prims))
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), ['/World'])
async def test_command_select_leaf(self):
context = omni.usd.get_context()
selection = context.get_selection()
stage = context.get_stage()
selection.set_selected_prim_paths(['/World'], True)
omni.kit.commands.execute("SelectLeaf")
selected = selection.get_selected_prim_paths()
for leaf in selected:
self.assertFalse(stage.GetPrimAtPath(leaf).GetChildren())
omni.kit.undo.undo()
self.assertListEqual(selection.get_selected_prim_paths(), ['/World'])
| 12,583 |
Python
| 41.948805 | 126 | 0.629739 |
omniverse-code/kit/exts/omni.kit.selection/docs/index.rst
|
omni.kit.selection
###########################
Commands for selection of prims
| 80 |
reStructuredText
| 15.199997 | 31 | 0.5375 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/simple_tool_button.py
|
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui
import weakref
from .hotkey import Hotkey
from .widget_group import WidgetGroup
class SimpleToolButton(WidgetGroup):
"""
A helper class to create simple WidgetGroup that contains only one ToolButton.
Args:
name: Name of the ToolButton.
tooltip: Tooltip of the ToolButton.
icon_path: The icon to be used when button is not checked.
icon_checked_path: The icon to be used when button is checked.
hotkey: HotKey to toggle the button (optional).
toggled_fn: Callback function when button is toggled. Signature: on_toggled(checked) (optional).
model: Model for the ToolButton (optional).
additional_style: Additional styling to apply to the ToolButton (optional).
"""
def __init__(
self,
name,
tooltip,
icon_path,
icon_checked_path,
hotkey=None,
toggled_fn=None,
model=None,
additional_style=None,
):
super().__init__()
self._name = name
self._tooltip = tooltip
self._icon_path = icon_path
self._icon_checked_path = icon_checked_path
self._hotkey = hotkey
self._toggled_fn = toggled_fn
self._model = model
self._additional_style = additional_style
self._hotkey = None
if hotkey:
def on_hotkey_changed(hotkey: str):
self._tool_button.tooltip = f"{self._tooltip} ({hotkey})"
self._select_hotkey = Hotkey(
f"{name}::hotkey",
hotkey,
lambda: self._on_hotkey(),
lambda: self._tool_button.enabled and self._is_in_context(),
on_hotkey_changed_fn=lambda hotkey: on_hotkey_changed(hotkey),
)
def clean(self):
super().clean()
self._value_sub = None
self._tool_button = None
if self._select_hotkey:
self._select_hotkey.clean()
self._select_hotkey = None
def get_style(self):
style = {
f"Button.Image::{self._name}": {"image_url": self._icon_path},
f"Button.Image::{self._name}:checked": {"image_url": self._icon_checked_path},
}
if self._additional_style:
style.update(self._additional_style)
return style
def create(self, default_size):
def on_value_changed(model, widget):
widget = widget()
if widget is not None:
if model.get_value_as_bool():
self._acquire_toolbar_context()
else:
self._release_toolbar_context()
widget._toggled_fn(model.get_value_as_bool())
self._tool_button = omni.ui.ToolButton(
name=self._name, model=self._model, tooltip=self._tooltip, width=default_size, height=default_size
)
if self._toggled_fn is not None:
self._value_sub = self._tool_button.model.subscribe_value_changed_fn(
lambda model, widget=weakref.ref(self): on_value_changed(model, widget)
)
# return a dictionary of name -> widget if you want to expose it to other widget_group
return {self._name: self._tool_button}
def get_tool_button(self):
return self._tool_button
def _on_hotkey(self):
self._tool_button.model.set_value(not self._tool_button.model.get_value_as_bool())
| 3,858 |
Python
| 34.081818 | 110 | 0.604458 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/widget_group.py
|
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
from abc import abstractmethod
import omni.kit.widget.toolbar
import omni.kit.app
import omni.ui as ui
from .context_menu import ContextMenuEvent
class WidgetGroup:
"""
Base class to create a group of widgets on Toolbar
"""
def __init__(self):
self._context = ""
self._context_token = None
self._show_menu_task = None
self._toolbar_ext_path = (
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module("omni.kit.widget.toolbar")
)
@abstractmethod
def clean(self):
"""
Clean up function to be called before destorying the object.
"""
if self._context_token:
self._release_toolbar_context()
self._context_token = None
self._context = ""
if self._show_menu_task: # pragma: no cover
self._show_menu_task.cancel()
self._show_menu_task = None
@abstractmethod
def get_style(self) -> dict:
"""
Gets the style of all widgets defined in this Widgets group.
"""
pass # pragma: no cover (Abstract)
@abstractmethod
def create(self, default_size):
"""
Main function to creates widget.
If you want to export widgets and allow external code to fetch and manipulate them, return a Dict[str, Widget] mapping from name to instance at the end of the function.
"""
pass # pragma: no cover (Abstract)
def on_toolbar_context_changed(self, context: str):
"""
Called when toolbar's effective context has changed.
Args:
context: new toolbar context.
"""
pass
def on_added(self, context):
"""
Called when widget is added to toolbar when calling Toolbar.add_widget
Args:
context: the context used to add widget when calling Toolbar.add_widget.
"""
self._context = context
def on_removed(self):
"""
Called when widget is removed from toolbar when calling Toolbar.remove_widget
"""
pass
def _acquire_toolbar_context(self):
"""
Request toolbar to switch to current widget's context.
"""
self._context_token = omni.kit.widget.toolbar.get_instance().acquire_toolbar_context(self._context)
def _release_toolbar_context(self):
"""
Release the ownership of toolbar context and reset to default. If the ownership was preemptively taken by other owner, release does nothing.
"""
omni.kit.widget.toolbar.get_instance().release_toolbar_context(self._context_token)
def _is_in_context(self):
"""
Checks if the Toolbar is in default context or owned by current widget's context.
Override this function if you want to customize the behavior.
Returns:
True if toolbar is either in default context or owned by current widget.
False otherwise.
"""
toolbar_context = omni.kit.widget.toolbar.get_instance().get_context()
return toolbar_context == omni.kit.widget.toolbar.Toolbar.DEFAULT_CONTEXT or self._context == toolbar_context
def _invoke_context_menu(self, button_id: str, min_menu_entries: int = 1):
"""
Function to invoke context menu.
Args:
button_id: button_id of the context menu to be invoked.
min_menu_entries: minimal number of menu entries required for menu to be visible (default 1).
"""
event = ContextMenuEvent()
event.payload["widget_name"] = button_id
event.payload["min_menu_entries"] = min_menu_entries
omni.kit.widget.toolbar.get_instance().context_menu.on_mouse_event(event)
def _on_mouse_pressed(self, button, button_id: str, min_menu_entries: int = 2):
"""
Function to handle flyout menu. Either with LMB long press or RMB click.
Args:
button_id: button_id of the context menu to be invoked.
min_menu_entries: minimal number of menu entries required for menu to be visible (default 1).
"""
self._acquire_toolbar_context()
if button == 1: # Right click, show immediately
self._invoke_context_menu(button_id, min_menu_entries)
elif button == 0: # Schedule a task if hold LMB long enough
self._show_menu_task = asyncio.ensure_future(self._schedule_show_menu(button_id))
def _on_mouse_released(self, button):
if button == 0:
if self._show_menu_task:
self._show_menu_task.cancel()
async def _schedule_show_menu(self, button_id: str, min_menu_entries: int = 2):
await asyncio.sleep(0.3)
self._invoke_context_menu(button_id, min_menu_entries)
self._show_menu_task = None
def _build_flyout_indicator(
self, width, height, index: str, extension_id: str = "omni.kit.widget.toolbar", padding=7, min_menu_count=2
):
import carb
import omni.kit.context_menu
indicator_size = 3
with ui.Placer(offset_x=width - indicator_size - padding, offset_y=height - indicator_size - padding):
indicator = ui.Image(
f"{self._toolbar_ext_path}/data/icon/flyout_indicator_dark.svg",
width=indicator_size,
height=indicator_size,
)
def on_menu_changed(evt: carb.events.IEvent):
try:
menu_list = omni.kit.context_menu.get_menu_dict(index, extension_id)
# because we moved separated the widget from the window extension, we need to still grab the menu from
# the window extension
menu_list_backward_compatible = omni.kit.context_menu.get_menu_dict(index, "omni.kit.window.toolbar")
if menu_list_backward_compatible and evt.payload.get("extension_id", None) == "omni.kit.window.toolbar": # pragma: no cover
omni.kit.app.log_deprecation(
'Adding menu using "add_menu(menu, index, "omni.kit.window.toolbar")" is deprecated. '
'Please use "add_menu(menu, index, "omni.kit.widget.toolbar")"'
)
# TODO check the actual menu entry visibility with show_fn
indicator.visible = len(menu_list + menu_list_backward_compatible) >= min_menu_count
except AttributeError as exc: # pragma: no cover
carb.log_warn(f"on_menu_changed error {exc}")
# Check initial state
on_menu_changed(None)
event_stream = omni.kit.context_menu.get_menu_event_stream()
return event_stream.create_subscription_to_pop(on_menu_changed)
| 7,173 |
Python
| 38.202186 | 176 | 0.625401 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/commands.py
|
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.timeline
import omni.kit.commands
class ToolbarPlayButtonClickedCommand(omni.kit.commands.Command):
"""
On clicked toolbar play button **Command**.
"""
def do(self):
omni.timeline.get_timeline_interface().play()
class ToolbarPauseButtonClickedCommand(omni.kit.commands.Command):
"""
On clicked toolbar pause button **Command**.
"""
def do(self):
omni.timeline.get_timeline_interface().pause()
class ToolbarStopButtonClickedCommand(omni.kit.commands.Command):
"""
On clicked toolbar stop button **Command**.
"""
def do(self):
omni.timeline.get_timeline_interface().stop()
class ToolbarPlayFilterCheckedCommand(omni.kit.commands.Command):
"""
Change settings depending on the status of play filter checkboxes **Command**.
Args:
path: Path to the setting to change.
enabled: New value to change to.
"""
def __init__(self, setting_path, enabled):
self._setting_path = setting_path
self._enabled = enabled
def do(self):
omni.kit.commands.execute("ChangeSetting", path=self._setting_path, value=self._enabled)
def undo(self):
pass # pragma: no cover
class ToolbarPlayFilterSelectAllCommand(omni.kit.commands.Command): # pragma: no cover
"""
Sets all play filter settings to True **Command**.
Args:
settings: Paths to the settings.
"""
def __init__(self, settings):
self._settings = settings
def do(self):
for setting in self._settings:
omni.kit.commands.execute("ChangeSetting", path=setting, value=True)
def undo(self):
pass
omni.kit.commands.register_all_commands_in_module(__name__)
| 2,165 |
Python
| 26.075 | 96 | 0.684988 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/extension.py
|
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb
import omni.ext
from functools import lru_cache
from pathlib import Path
from .toolbar import Toolbar
_toolbar_instance = None
@lru_cache()
def get_data_path() -> Path:
manager = omni.kit.app.get_app().get_extension_manager()
extension_path = manager.get_extension_path_by_module("omni.kit.widget.toolbar")
return Path(extension_path).joinpath("data")
def get_instance():
return _toolbar_instance
class WidgetToolBarExtension(omni.ext.IExt):
"""omni.kit.widget.toolbar ext"""
def on_startup(self, ext_id):
global _toolbar_instance
carb.log_info("[omni.kit.widget.toolbar] Startup")
_toolbar_instance = Toolbar()
def on_shutdown(self):
carb.log_info("[omni.kit.widget.toolbar] Shutdown")
global _toolbar_instance
if _toolbar_instance:
_toolbar_instance.destroy()
_toolbar_instance = None
| 1,338 |
Python
| 29.431818 | 84 | 0.720478 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/__init__.py
|
from .extension import *
from .toolbar import *
from omni.kit.widget.toolbar.simple_tool_button import * # backward compatible
from .widget_group import * # backward compatible
| 179 |
Python
| 34.999993 | 79 | 0.776536 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/context_menu.py
|
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb
import omni.kit.context_menu
from omni import ui
class ContextMenuEvent:
"""The object comatible with ContextMenu"""
def __init__(self):
self.type = 0
self.payload = {}
class ContextMenu:
def on_mouse_event(self, event):
# check its expected event
if event.type != int(omni.kit.ui.MenuEventType.ACTIVATE): # pragma: no cover
return
# get context menu core functionality & check its enabled
context_menu = omni.kit.context_menu.get_instance()
if context_menu is None: # pragma: no cover
carb.log_error("context_menu is disabled!")
return
# setup objects, this is passed to all functions
objects = {}
objects.update(event.payload)
widget_name = objects.get("widget_name", None)
menu_list = omni.kit.context_menu.get_menu_dict(widget_name, "omni.kit.widget.toolbar")
# because we moved separated the widget from the window extension, we need to still grab the menu from
# the window extension
menu_list_backward_compatible = omni.kit.context_menu.get_menu_dict(widget_name, "omni.kit.window.toolbar")
for menu_list_backward in menu_list_backward_compatible: # pragma: no cover
if menu_list_backward not in menu_list:
menu_list.append(menu_list_backward)
# For some tool buttons, the context menu only shows if additional (>1) menu entries are added.
min_menu_entries = event.payload.get("min_menu_entries", 0)
# show menu
context_menu.show_context_menu("toolbar", objects, menu_list, min_menu_entries, delegate=ui.MenuDelegate())
| 2,117 |
Python
| 38.962263 | 115 | 0.683987 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/toolbar.py
|
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import carb
import carb.settings
import omni.kit.app
import omni.ui as ui
import omni.usd
from omni.ui import color as cl
from typing import Callable
from .builtin_tools.builtin_tools import BuiltinTools
from .commands import *
from .context_menu import *
from .widget_group import WidgetGroup # backward compatible
import typing
if typing.TYPE_CHECKING: # pragma: no cover
import weakref
GRAB_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/Grab/enabled"
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class Toolbar:
WINDOW_NAME = "Main ToolBar"
DEFAULT_CONTEXT = ""
DEFAULT_CONTEXT_TOKEN = 0
DEFAULT_SIZE = 38
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def __init__(self):
self._settings = carb.settings.get_settings()
self.__root_frame = None
self._toolbar_widget_groups = []
self._toolbar_widgets = {}
self._toolbar_dirty = False
self._axis = ui.ToolBarAxis.X
self._rebuild_task = None
self._grab_stack = None
self._context_menu = ContextMenu()
self._context_token_pool = 1
self._context = Toolbar.DEFAULT_CONTEXT
self._context_token = Toolbar.DEFAULT_CONTEXT_TOKEN
self._context_token_owner_count = 0
self.__init_shades()
self._builtin_tools = BuiltinTools(self)
def __init_shades(self):
"""Style colors"""
cl.toolbar_button_background = cl.shade(0x0)
cl.toolbar_button_background_checked = cl.shade(0xFF1F2123)
cl.toolbar_button_background_pressed = cl.shade(0xFF4B4B4B)
cl.toolbar_button_background_hovered = cl.shade(0xFF383838)
@property
def context_menu(self):
return self._context_menu
def destroy(self):
if self._rebuild_task is not None: # pragma: no cover
self._rebuild_task.cancel()
self._toolbar_widgets = {}
if self._builtin_tools:
self._builtin_tools.destroy()
self._builtin_tools = None
self._toolbar_widget_groups = []
def add_widget(self, widget_group: "WidgetGroup", priority: int, context: str = ""):
self._toolbar_widget_groups.append((priority, widget_group))
widget_group.on_added(context)
self._set_toolbar_dirty()
def remove_widget(self, widget_group: "WidgetGroup"):
for widget in self._toolbar_widget_groups:
if widget[1] == widget_group:
self._toolbar_widget_groups.remove(widget)
widget_group.on_removed()
self._set_toolbar_dirty()
break
def get_widget(self, name: str):
return self._toolbar_widgets.get(name, None)
def acquire_toolbar_context(self, context: str):
"""
Request toolbar to switch to given context.
It takes the context preemptively even if previous context owner has not release the context.
Args:
context (str): Context to switch to.
Returns:
A token to be used to release_toolbar_context
"""
if self._context == context:
self._context_token_owner_count += 1
return self._context_token
# preemptively take current context, regardless of previous owner/count
self._context = context
if context == Toolbar.DEFAULT_CONTEXT:
self._context_token = Toolbar.DEFAULT_CONTEXT_TOKEN
else:
self._context_token_pool += 1
self._context_token = self._context_token_pool
self._context_token_owner_count = 1
for widget in self._toolbar_widget_groups:
widget[1].on_toolbar_context_changed(context)
return self._context_token
def release_toolbar_context(self, token: int):
"""
Request toolbar to release context associated with token.
If token is expired (already released or context ownership taken by others), this function does nothing.
Args:
token (int): Context token to release.
"""
if token == self._context_token:
self._context_token_owner_count -= 1
else:
carb.log_info("Releasing expired context token, ignoring")
return
if self._context_token_owner_count <= 0:
self._context = Toolbar.DEFAULT_CONTEXT
self._context_token = Toolbar.DEFAULT_CONTEXT_TOKEN
self._context_token_owner_count = 0
for widget in self._toolbar_widget_groups:
widget[1].on_toolbar_context_changed(self._context)
def get_context(self):
return self._context
def _set_toolbar_dirty(self):
self._toolbar_dirty = True
if self._rebuild_task is None:
self._rebuild_task = asyncio.ensure_future(self._delayed_rebuild())
def set_axis(self, axis):
self._axis = axis
# delay rebuild so widgets added within one frame are rebuilt together
@omni.usd.handle_exception
async def _delayed_rebuild(self):
await omni.kit.app.get_app().next_update_async()
if self._toolbar_dirty:
self.rebuild_toolbar()
self._toolbar_dirty = False
self._rebuild_task = None
def rebuild_toolbar(self, root_frame=None):
if root_frame:
self.__root_frame = root_frame
if not self.__root_frame:
carb.log_warn("No root frame specified. Please specify a root frame for this widget")
return
axis = self._axis
self._toolbar_widgets = {}
self._toolbar_widget_groups.sort(key=lambda x: x[0]) # sort by priority
with self.__root_frame:
stack = None
style = {
"Button": {"background_color": cl.toolbar_button_background, "border_radius": 4, "margin": 2, "padding": 3},
"Button:checked": {"background_color": cl.toolbar_button_background_checked},
"Button:pressed": {"background_color": cl.toolbar_button_background_pressed},
"Button:hovered": {"background_color": cl.toolbar_button_background_hovered},
"Button.Image::disabled": {"color": 0x608A8777},
"Line::grab": {"color": 0xFF2E2E2E, "border_width": 2, "margin": 2},
"Line::separator": {"color": 0xFF555555},
"Tooltip": {
"background_color": 0xFFC7F5FC,
"color": 0xFF4B493B,
"border_width": 1,
"margin_width": 2,
"margin_height": 1,
"padding": 1,
},
}
for widget in self._toolbar_widget_groups:
style.update(widget[1].get_style())
default_size = self.DEFAULT_SIZE
if axis == ui.ToolBarAxis.X:
stack = ui.HStack(style=style, height=default_size, width=ui.Percent(100))
else:
stack = ui.VStack(style=style, height=ui.Percent(100), width=default_size)
with stack:
if self._settings.get(GRAB_ENABLED_SETTING_PATH):
self._create_grab(axis)
ui.Spacer(width=3, height=3)
last_priority = None
for widget in self._toolbar_widget_groups:
this_priority = widget[0]
if last_priority is not None and this_priority - last_priority >= 10:
self._create_separator(axis)
public_widgets = widget[1].create(default_size=default_size)
if public_widgets is not None:
self._toolbar_widgets.update(public_widgets)
last_priority = this_priority
def _create_separator(self, axis):
if axis == ui.ToolBarAxis.X:
ui.Line(width=1, name="separator", alignment=ui.Alignment.LEFT)
else:
ui.Line(height=1, name="separator", alignment=ui.Alignment.TOP)
def subscribe_grab_mouse_pressed(self, function: Callable[[int, "weakref.ref"], None]):
if self._grab_stack:
self._grab_stack.set_mouse_pressed_fn(function)
def _create_grab(self, axis):
grab_area_size = 20
if axis == ui.ToolBarAxis.X:
self._grab_stack = ui.HStack(width=grab_area_size)
else:
self._grab_stack = ui.VStack(height=grab_area_size)
with self._grab_stack:
if axis == ui.ToolBarAxis.X:
ui.Spacer(width=5)
ui.Line(name="grab", width=5, alignment=ui.Alignment.LEFT)
ui.Line(name="grab", width=5, alignment=ui.Alignment.LEFT)
ui.Line(name="grab", width=5, alignment=ui.Alignment.LEFT)
ui.Spacer(width=3)
else:
ui.Spacer(height=5)
ui.Line(name="grab", height=5, alignment=ui.Alignment.TOP)
ui.Line(name="grab", height=5, alignment=ui.Alignment.TOP)
ui.Line(name="grab", height=5, alignment=ui.Alignment.TOP)
ui.Spacer(height=3)
def add_custom_select_type(self, entry_name: str, selection_types: list):
self._builtin_tools.add_custom_select_type(entry_name, selection_types)
def remove_custom_select(self, entry_name):
self._builtin_tools.remove_custom_select(entry_name)
| 10,132 |
Python
| 37.973077 | 124 | 0.606001 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/hotkey.py
|
# 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.
#
from __future__ import annotations
from typing import Callable
import carb.events
import carb.input
import omni.appwindow
import omni.kit.actions.core
import omni.kit.app
class Hotkey:
def __init__(
self,
action_name: str,
hotkey: carb.input.KeyboardInput,
on_action_fn: Callable[[], None],
hotkey_enabled_fn: Callable[[], None],
modifiers: int = 0,
on_hotkey_changed_fn: Callable[[str], None] = None,
):
self._action_registry = omni.kit.actions.core.get_action_registry()
self._settings = carb.settings.get_settings()
self._action_name = action_name
self._hotkey = hotkey
self._modifiers = modifiers
self._on_hotkey_changed_fn = on_hotkey_changed_fn
self._registered_hotkey = None
self._manager = omni.kit.app.get_app().get_extension_manager()
self._extension_name = omni.ext.get_extension_name(self._manager.get_extension_id_by_module(__name__))
def action_trigger():
if not hotkey_enabled_fn():
return
if on_action_fn:
on_action_fn()
# Register a test action that invokes a Python function.
self._action = self._action_registry.register_action(
self._extension_name,
action_name,
lambda *_: action_trigger(),
display_name=action_name,
tag="Toolbar",
)
self._hooks = self._manager.subscribe_to_extension_enable(
lambda _: self._register_hotkey(),
lambda _: self._unregister_hotkey(),
ext_name="omni.kit.hotkeys.core",
hook_name=f"toolbar hotkey {action_name} listener",
)
def clean(self):
self._unregister_hotkey()
self._action_registry.deregister_action(self._action)
self._hooks = None
self._on_hotkey_changed_fn = None
def get_as_string(self, default:str):
if self._registered_hotkey:
return self._registered_hotkey.key_text
return default
def _on_hotkey_changed(self, event: carb.events.IEvent):
from omni.kit.hotkeys.core import KeyCombination
if (
event.payload["hotkey_ext_id"] == self._extension_name
and event.payload["action_ext_id"] == self._extension_name
and event.payload["action_id"] == self._action_name
):
new_key = event.payload["key"]
# refresh _registered_hotkey with newly registered key?
hotkey_combo = KeyCombination(new_key)
self._registered_hotkey = self._hotkey_registry.get_hotkey(self._extension_name, hotkey_combo)
if self._on_hotkey_changed_fn:
self._on_hotkey_changed_fn(new_key)
def _register_hotkey(self):
try:
from omni.kit.hotkeys.core import HOTKEY_CHANGED_EVENT, KeyCombination, get_hotkey_registry
self._hotkey_registry = get_hotkey_registry()
hotkey_combo = KeyCombination(self._hotkey, self._modifiers)
self._registered_hotkey = self._hotkey_registry.register_hotkey(
self._extension_name, hotkey_combo, self._extension_name, self._action_name
)
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
self._change_event_sub = event_stream.create_subscription_to_pop_by_type(
HOTKEY_CHANGED_EVENT, self._on_hotkey_changed
)
except ImportError: # pragma: no cover
pass
def _unregister_hotkey(self):
if not self._registered_hotkey or not self._hotkey_registry:
return
try:
self._hotkey_registry.deregister_hotkey(self._registered_hotkey)
self._registered_hotkey = None
self._change_event_sub = None
except Exception: # pragma: no cover
pass
| 4,357 |
Python
| 34.430894 | 110 | 0.620151 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/play_button_group.py
|
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb.dictionary
import carb.settings
import omni.timeline
import omni.ui as ui
from carb.input import KeyboardInput as Key
from omni.kit.commands import execute
from omni.kit.widget.toolbar.hotkey import Hotkey
from omni.kit.widget.toolbar.widget_group import WidgetGroup
from .models.timeline_model import TimelinePlayPauseModel
PLAY_TOOL_NAME = "Play"
PAUSE_TOOL_NAME = "Pause"
class PlayButtonGroup(WidgetGroup):
PLAY_ANIMATIONS_SETTING = "/app/player/playAnimations"
PLAY_AUDIO_SETTING = "/app/player/audio/enabled"
PLAY_SIMULATIONS_SETTING = "/app/player/playSimulations"
PLAY_COMPUTEGRAPH_SETTING = "/app/player/playComputegraph"
all_settings_paths = [
PLAY_ANIMATIONS_SETTING,
PLAY_AUDIO_SETTING,
PLAY_SIMULATIONS_SETTING,
PLAY_COMPUTEGRAPH_SETTING,
]
def __init__(self):
super().__init__()
self._play_button = None
self._play_hotkey = None
self._stop_button = None
self._settings = carb.settings.get_settings()
self._dict = carb.dictionary.get_dictionary()
self._timeline_play_pause_model = TimelinePlayPauseModel()
self._timeline = omni.timeline.get_timeline_interface()
self._settings.set_default_bool(self.PLAY_ANIMATIONS_SETTING, True)
self._settings.set_default_bool(self.PLAY_AUDIO_SETTING, True)
self._settings.set_default_bool(self.PLAY_SIMULATIONS_SETTING, True)
self._settings.set_default_bool(self.PLAY_COMPUTEGRAPH_SETTING, True)
stream = self._timeline.get_timeline_event_stream()
self._sub = stream.create_subscription_to_pop(self._on_timeline_event)
self._register_context_menu()
self._show_menu_task = None
self._visible = True
def clean(self):
super().clean()
self._sub = None
if self._timeline_play_pause_model:
self._timeline_play_pause_model.clean()
self._timeline_play_pause_model = None
self._play_button = None
self._stop_button = None
self._animations_menu = None
self._audio_menu = None
self._simulations_menu = None
self._compute_graph_menu = None
self._play_filter_menu = None
self._filter_menu = None
self._sep_menu = None
self._sep_menu2 = None
self._select_all_menu = None
if self._show_menu_task: # pragma: no cover
self._show_menu_task.cancel()
self._show_menu_task = None
if self._play_hotkey:
self._play_hotkey.clean()
self._play_hotkey = None
self._visible = True
def get_style(self):
style = {
"Button.Image::play": {"image_url": "${glyphs}/toolbar_play.svg"},
"Button.Image::play:checked": {"image_url": "${glyphs}/toolbar_pause.svg"},
"Button.Image::stop": {"image_url": "${glyphs}/toolbar_stop.svg"},
}
return style
def create(self, default_size):
# Build Play button
self._play_button = ui.ToolButton(
model=self._timeline_play_pause_model,
name="play",
tooltip=f"{PLAY_TOOL_NAME} ('Space')",
width=default_size,
height=default_size,
mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "play"),
mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b),
checked=self._timeline_play_pause_model.get_value_as_bool(),
)
def on_play_hotkey_changed(hotkey: str):
if self._play_button:
self._play_button.tooltip = f"{PLAY_TOOL_NAME} ({hotkey})"
# Assign Play button Hotkey
self._play_hotkey = Hotkey(
"toolbar::play",
Key.SPACE,
lambda: self._timeline_play_pause_model.set_value(not self._timeline_play_pause_model.get_value_as_bool()),
lambda: self._play_button is not None and self._play_button.enabled and self._is_in_context(),
on_hotkey_changed_fn=lambda hotkey: on_play_hotkey_changed(hotkey),
)
self._visible = True
def on_stop_clicked(*_):
self._acquire_toolbar_context()
execute("ToolbarStopButtonClicked")
self._stop_button = ui.Button(
name="stop",
tooltip="Stop",
width=default_size,
height=default_size,
visible=False,
clicked_fn=on_stop_clicked,
)
return {"play": self._play_button, "stop": self._stop_button}
def _on_setting_changed(self, item, event_type, menu_item): # pragma: no cover
menu_item.checked = self._dict.get(item)
def _on_timeline_event(self, e):
if e.type == int(omni.timeline.TimelineEventType.PLAY):
if self._play_button:
self._play_button.set_tooltip(f"{PAUSE_TOOL_NAME} ({self._play_hotkey.get_as_string('Space')})")
if self._stop_button:
self._stop_button.visible = self._visible
if e.type == int(omni.timeline.TimelineEventType.PAUSE):
if self._play_button:
self._play_button.set_tooltip(f"{PLAY_TOOL_NAME} ({self._play_hotkey.get_as_string('Space')})")
if e.type == int(omni.timeline.TimelineEventType.STOP):
if self._stop_button:
self._stop_button.visible = False
if self._play_button:
self._play_button.set_tooltip(f"{PLAY_TOOL_NAME} ({self._play_hotkey.get_as_string('Space')})")
if hasattr(omni.timeline.TimelineEventType, 'DIRECTOR_CHANGED') and\
e.type == int(omni.timeline.TimelineEventType.DIRECTOR_CHANGED): # pragma: no cover
self._visible = not e.payload['hasDirector']
if self._stop_button:
self._stop_button.visible = self._visible
if self._play_button:
self._play_button.visible = self._visible
def _on_filter_changed(self, filter_setting, enabled): # pragma: no cover
execute("ToolbarPlayFilterChecked", setting_path=filter_setting, enabled=enabled)
def _select_all(self): # pragma: no cover
execute("ToolbarPlayFilterSelectAll", settings=self.all_settings_paths)
def _register_context_menu(self):
context_menu = omni.kit.context_menu.get_instance()
def is_button(objects: dict, button_name: str): # pragma: no cover
return objects.get("widget_name", None) == button_name
def create_menu_entry(name, setting_path):
menu = {
"name": name,
"show_fn": [lambda object: is_button(object, "play")],
"onclick_fn": lambda object: self._on_filter_changed(
setting_path, not self._settings.get(setting_path)
),
"checked_fn": lambda object: self._settings.get(setting_path),
}
return omni.kit.context_menu.add_menu(menu, "play", "omni.kit.widget.toolbar")
def create_seperator(name=""):
menu = {
"name": name,
"show_fn": [lambda object: is_button(object, "play")],
}
return omni.kit.context_menu.add_menu(menu, "play", "omni.kit.widget.toolbar")
if context_menu:
menu = {
"name": "Filter",
"show_fn": [lambda object: is_button(object, "play")],
"enabled_fn": lambda object: False,
}
self._filter_menu = omni.kit.context_menu.add_menu(menu, "play", "omni.kit.widget.toolbar")
self._sep_menu = create_seperator("sep/")
self._animations_menu = create_menu_entry("Animation", self.PLAY_ANIMATIONS_SETTING)
self._audio_menu = create_menu_entry("Audio", self.PLAY_AUDIO_SETTING)
self._simulations_menu = create_menu_entry("Simulations", self.PLAY_SIMULATIONS_SETTING)
self._compute_graph_menu = create_menu_entry("OmniGraph", self.PLAY_COMPUTEGRAPH_SETTING)
self._sep_menu2 = create_seperator("sep2/")
menu = {
"name": "Select All",
"show_fn": [lambda object: is_button(object, "play")],
"onclick_fn": lambda object: self._select_all(),
}
self._select_all_menu = omni.kit.context_menu.add_menu(menu, "play", "omni.kit.widget.toolbar")
| 8,842 |
Python
| 40.32243 | 119 | 0.604275 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/builtin_tools.py
|
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb.dictionary
import carb.settings
from .select_button_group import SelectButtonGroup
from .snap_button_group import LegacySnapButtonGroup
from .transform_button_group import TransformButtonGroup
from .play_button_group import PlayButtonGroup
import typing
if typing.TYPE_CHECKING: # pragma: no cover
from ..toolbar import Toolbar
SELECT_BUTTON_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/SelectionButton/enabled"
TRANSFORM_BUTTON_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/TransformButton/enabled"
PLAY_BUTTON_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/PlayButton/enabled"
LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW = "/exts/omni.kit.window.toolbar/legacySnapButton/enabled"
LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET = "/exts/omni.kit.widget.toolbar/legacySnapButton/enabled"
class BuiltinTools:
def __init__(self, toolbar: "Toolbar"):
self._dict = carb.dictionary.get_dictionary()
self._settings = carb.settings.get_settings()
self._sub_window = self._settings.subscribe_to_node_change_events(
LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW, self._on_legacy_snap_setting_changed_window
)
self._toolbar = toolbar
self._select_button_group = None
if self._settings.get(SELECT_BUTTON_ENABLED_SETTING_PATH):
self._select_button_group = SelectButtonGroup()
toolbar.add_widget(self._select_button_group, 0)
self._transform_button_group = None
if self._settings.get(TRANSFORM_BUTTON_ENABLED_SETTING_PATH):
self._transform_button_group = TransformButtonGroup()
toolbar.add_widget(self._transform_button_group, 1)
self._snap_button_group = None
if self._settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET):
self._add_snap_button()
self._play_button_group = None
if self._settings.get(PLAY_BUTTON_ENABLED_SETTING_PATH):
self._play_button_group = PlayButtonGroup()
toolbar.add_widget(self._play_button_group, 21)
self._sub_widget = self._settings.subscribe_to_node_change_events(
LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET, self._on_legacy_snap_setting_changed
)
def destroy(self):
if self._select_button_group:
self._toolbar.remove_widget(self._select_button_group)
self._select_button_group.clean()
self._select_button_group = None
if self._transform_button_group:
self._toolbar.remove_widget(self._transform_button_group)
self._transform_button_group.clean()
self._transform_button_group = None
if self._snap_button_group:
self._remove_snap_button()
if self._play_button_group:
self._toolbar.remove_widget(self._play_button_group)
self._play_button_group.clean()
self._play_button_group = None
if self._sub_window:
self._settings.unsubscribe_to_change_events(self._sub_window)
self._sub_window = None
if self._sub_widget:
self._settings.unsubscribe_to_change_events(self._sub_widget)
self._sub_widget = None
def __del__(self):
self.destroy()
def _add_snap_button(self):
self._snap_button_group = LegacySnapButtonGroup()
self._toolbar.add_widget(self._snap_button_group, 11)
def _remove_snap_button(self):
self._toolbar.remove_widget(self._snap_button_group)
self._snap_button_group.clean()
self._snap_button_group = None
def _on_legacy_snap_setting_changed_window(self, *args, **kwargs):
"""
If the old setting is set, we forward it into the new settings.
"""
enabled_legacy_snap = self._settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW)
if enabled_legacy_snap is not None:
carb.log_warn(
'Deprecated, please use "/exts/omni.kit.widget.toolbar/legacySnapButton/enabled" setting'
)
self._settings.set(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET, enabled_legacy_snap)
def _on_legacy_snap_setting_changed(self, *args, **kwargs):
enabled_legacy_snap = self._settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET)
if self._snap_button_group is None and enabled_legacy_snap:
self._add_snap_button()
elif self._snap_button_group is not None and not enabled_legacy_snap:
self._remove_snap_button()
def add_custom_select_type(self, entry_name: str, selection_types: list):
self._select_button_group.add_custom_select_type(entry_name, selection_types)
def remove_custom_select(self, entry_name):
self._select_button_group.remove_custom_select(entry_name)
| 5,263 |
Python
| 41.796748 | 105 | 0.67984 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/transform_button_group.py
|
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb.input
import carb.dictionary
import carb.settings
import omni.kit.context_menu
import omni.ui as ui
from carb.input import KeyboardInput as Key
from omni.kit.widget.toolbar.hotkey import Hotkey
from omni.kit.widget.toolbar.widget_group import WidgetGroup
from .models.transform_mode_model import LocalGlobalTransformModeModel, TransformModeModel
MOVE_TOOL_NAME = "Move"
ROTATE_TOOL_NAME = "Rotate"
SCALE_TOOL_NAME = "Scale"
class TransformButtonGroup(WidgetGroup):
TRANSFORM_MOVE_MODE_SETTING = "/app/transform/moveMode"
TRANSFORM_ROTATE_MODE_SETTING = "/app/transform/rotateMode"
def __init__(self):
super().__init__()
self._input = carb.input.acquire_input_interface()
self._settings = carb.settings.get_settings()
self._settings.set_default_string(TransformModeModel.TRANSFORM_OP_SETTING, TransformModeModel.TRANSFORM_OP_MOVE)
self._settings.set_default_string(
self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL
)
self._settings.set_default_string(
self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL
)
self._move_op_model = LocalGlobalTransformModeModel(
op=TransformModeModel.TRANSFORM_OP_MOVE, op_space_setting_path=self.TRANSFORM_MOVE_MODE_SETTING
)
self._rotate_op_model = LocalGlobalTransformModeModel(
op=TransformModeModel.TRANSFORM_OP_ROTATE, op_space_setting_path=self.TRANSFORM_ROTATE_MODE_SETTING
)
self._scale_op_model = TransformModeModel(TransformModeModel.TRANSFORM_OP_SCALE)
def on_hotkey_changed(hotkey: str, button, tool_name: str):
button.tooltip = f"{tool_name} ({hotkey})"
self._move_hotkey = Hotkey(
"toolbar::move",
Key.W,
lambda: self._move_op_model.set_value(not self._move_op_model.get_value_as_bool()),
lambda: self._move_button.enabled
and self._is_in_context()
and self._input.get_mouse_value(None, carb.input.MouseInput.RIGHT_BUTTON)
== 0, # when RMB is down, it's possible viewport WASD navigation is going on, and don't trigger it if W is pressed
on_hotkey_changed_fn=lambda hotkey: on_hotkey_changed(hotkey, self._move_button, MOVE_TOOL_NAME),
)
self._rotate_hotkey = Hotkey(
"toolbar::rotate",
Key.E,
lambda: self._rotate_op_model.set_value(not self._rotate_op_model.get_value_as_bool()),
lambda: self._rotate_button.enabled and self._is_in_context()
and self._input.get_mouse_value(None, carb.input.MouseInput.RIGHT_BUTTON)
== 0,
on_hotkey_changed_fn=lambda hotkey: on_hotkey_changed(hotkey, self._rotate_button, ROTATE_TOOL_NAME),
)
self._scale_hotkey = Hotkey(
"toolbar::scale",
Key.R,
lambda: self._scale_op_model.set_value(True),
lambda: self._scale_button.enabled and self._is_in_context(),
on_hotkey_changed_fn=lambda hotkey: on_hotkey_changed(hotkey, self._scale_button, SCALE_TOOL_NAME),
)
self._register_context_menu()
def get_style(self):
style = {
"Button.Image::move_op_global": {"image_url": "${glyphs}/toolbar_move_global.svg"},
"Button.Image::move_op_local": {"image_url": "${glyphs}/toolbar_move_local.svg"},
"Button.Image::rotate_op_global": {"image_url": "${glyphs}/toolbar_rotate_global.svg"},
"Button.Image::rotate_op_local": {"image_url": "${glyphs}/toolbar_rotate_local.svg"},
"Button.Image::scale_op": {"image_url": "${glyphs}/toolbar_scale.svg"},
}
return style
def create(self, default_size):
self._sub_move, self._move_button = self._create_local_global_button(
self._move_op_model,
f"{MOVE_TOOL_NAME} ({self._move_hotkey.get_as_string('W')})",
"move_op",
self.TRANSFORM_MOVE_MODE_SETTING,
"move_op_global",
"move_op_local",
default_size,
)
self._sub_rotate, self._rotate_button = self._create_local_global_button(
self._rotate_op_model,
f"{ROTATE_TOOL_NAME} ({self._rotate_hotkey.get_as_string('E')})",
"rotate_op",
self.TRANSFORM_ROTATE_MODE_SETTING,
"rotate_op_global",
"rotate_op_local",
default_size,
)
self._scale_button = ui.ToolButton(
model=self._scale_op_model,
name="scale_op",
tooltip=f"{SCALE_TOOL_NAME} ({self._scale_hotkey.get_as_string('R')})",
width=default_size,
height=default_size,
mouse_pressed_fn=lambda *_: self._acquire_toolbar_context(),
)
return {"move_op": self._move_button, "rotate_op": self._rotate_button, "scale_op": self._scale_button}
def clean(self):
super().clean()
self._move_button = None
self._rotate_button = None
self._scale_button = None
self._sub_move = None
self._sub_rotate = None
self._move_op_model.clean()
self._move_op_model = None
self._rotate_op_model.clean()
self._rotate_op_model = None
self._scale_op_model.clean()
self._scale_op_model = None
self._move_hotkey.clean()
self._move_hotkey = None
self._rotate_hotkey.clean()
self._rotate_hotkey = None
self._scale_hotkey.clean()
self._scale_hotkey = None
self._move_global_menu_entry = None
self._move_local_menu_entry = None
self._rotate_global_menu_entry = None
self._rotate_local_menu_entry = None
def _get_op_button_name(self, model, global_name, local_name):
if model.get_op_space_mode() == LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL:
return global_name
else: # pragma: no cover
return local_name
def _create_local_global_button(
self, op_model, tooltip, button_name, op_setting_path, global_name, local_name, default_size
):
op_button = ui.ToolButton(
name=self._get_op_button_name(op_model, global_name, local_name),
model=op_model,
tooltip=tooltip,
width=default_size,
height=default_size,
mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, button_name),
mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b),
checked=op_model.get_value_as_bool(),
)
def on_op_button_value_change(model):
op_button.name = self._get_op_button_name(model, global_name, local_name)
return op_model.subscribe_value_changed_fn(on_op_button_value_change), op_button
def _register_context_menu(self):
context_menu = omni.kit.context_menu.get_instance()
def is_button(objects: dict, button_name: str): # pragma: no cover
return objects.get("widget_name", None) == button_name
def on_mode(objects: dict, op_setting_path: str, desired_value): # pragma: no cover
self._settings.set(op_setting_path, desired_value)
def checked(objects: dict, op_setting_path: str, desired_value: str): # pragma: no cover
return self._settings.get(op_setting_path) == desired_value
if context_menu:
menu = {
"name": "Global (W)",
"show_fn": [lambda object: is_button(object, "move_op")],
"onclick_fn": lambda object: on_mode(
object, self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL
),
"checked_fn": lambda object: checked(
object, self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL
),
}
self._move_global_menu_entry = omni.kit.context_menu.add_menu(menu, "move_op", "omni.kit.widget.toolbar")
menu = {
"name": "Local (W)",
"show_fn": [lambda object: is_button(object, "move_op")],
"onclick_fn": lambda object: on_mode(
object, self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL
),
"checked_fn": lambda object: checked(
object, self.TRANSFORM_MOVE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL
),
}
self._move_local_menu_entry = omni.kit.context_menu.add_menu(menu, "move_op", "omni.kit.widget.toolbar")
menu = {
"name": "Global (E)",
"show_fn": [lambda object: is_button(object, "rotate_op")],
"onclick_fn": lambda object: on_mode(
object, self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL
),
"checked_fn": lambda object: checked(
object, self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL
),
}
self._rotate_global_menu_entry = omni.kit.context_menu.add_menu(
menu, "rotate_op", "omni.kit.widget.toolbar"
)
menu = {
"name": "Local (E)",
"show_fn": [lambda object: is_button(object, "rotate_op")],
"onclick_fn": lambda object: on_mode(
object, self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL
),
"checked_fn": lambda object: checked(
object, self.TRANSFORM_ROTATE_MODE_SETTING, LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL
),
}
self._rotate_local_menu_entry = omni.kit.context_menu.add_menu(menu, "rotate_op", "omni.kit.widget.toolbar")
| 10,527 |
Python
| 43.8 | 127 | 0.605016 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/snap_button_group.py
|
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb.dictionary
import carb.settings
import omni.kit.context_menu
import omni.ui as ui
from omni.kit.widget.toolbar.widget_group import WidgetGroup
from .models.setting_model import BoolSettingModel, FloatSettingModel
class LegacySnapButtonGroup(WidgetGroup):
SNAP_ENABLED_SETTING = "/app/viewport/snapEnabled"
SNAP_MOVE_X_SETTING = "/persistent/app/viewport/stepMove/x"
SNAP_MOVE_Y_SETTING = "/persistent/app/viewport/stepMove/y"
SNAP_MOVE_Z_SETTING = "/persistent/app/viewport/stepMove/z"
SNAP_ROTATE_SETTING = "/persistent/app/viewport/stepRotate"
SNAP_SCALE_SETTING = "/persistent/app/viewport/stepScale"
SNAP_TO_SURFACE_SETTING = "/persistent/app/viewport/snapToSurface"
def __init__(self):
super().__init__()
self._settings = carb.settings.get_settings()
self._settings.set_default_bool(self.SNAP_ENABLED_SETTING, False)
self._settings.set_default_float(self.SNAP_MOVE_X_SETTING, 50.0)
self._settings.set_default_float(self.SNAP_MOVE_Y_SETTING, 50.0)
self._settings.set_default_float(self.SNAP_MOVE_Z_SETTING, 50.0)
self._settings.set_default_float(self.SNAP_ROTATE_SETTING, 1.0)
self._settings.set_default_float(self.SNAP_SCALE_SETTING, 1.0)
self._dict = carb.dictionary.get_dictionary()
self._snap_setting_model = BoolSettingModel(self.SNAP_ENABLED_SETTING, False)
self._snap_move_x_settings_model = FloatSettingModel(self.SNAP_MOVE_X_SETTING)
self._snap_move_y_settings_model = FloatSettingModel(self.SNAP_MOVE_Y_SETTING)
self._snap_move_z_settings_model = FloatSettingModel(self.SNAP_MOVE_Z_SETTING)
self._snap_rotate_settings_model = FloatSettingModel(self.SNAP_ROTATE_SETTING)
self._snap_scale_settings_model = FloatSettingModel(self.SNAP_SCALE_SETTING)
self._create_snap_increment_setting_window()
self._register_context_menu()
self._show_menu_task = None
self._button = None
def clean(self):
super().clean()
self._snap_setting_model.clean()
self._snap_setting_model = None
# workaround delayed toolbar rebuild after group is destroyed and access null model
if self._button:
self._button.model = ui.SimpleBoolModel()
self._button = None
self._snap_move_x_settings_model.clean()
self._snap_move_x_settings_model = None
self._snap_move_y_settings_model.clean()
self._snap_move_y_settings_model = None
self._snap_move_z_settings_model.clean()
self._snap_move_z_settings_model = None
self._snap_rotate_settings_model.clean()
self._snap_rotate_settings_model = None
self._snap_scale_settings_model.clean()
self._snap_scale_settings_model = None
self._snap_increment_setting_window = None
self._snap_setting_menu = None
self._snap_settings = None
self._snap_to_increment_menu = None
self._snap_to_face_menu = None
if self._show_menu_task: # pragma: no cover
self._show_menu_task.cancel()
self._show_menu_task = None
self._snap_settings_menu_entry = None
self._snap_to_increment_menu_entry = None
self._snap_to_face_menu_entry = None
def get_style(self):
style = {"Button.Image::snap": {"image_url": "${glyphs}/toolbar_snap.svg"}}
return style
def create(self, default_size):
self._button = ui.ToolButton(
model=self._snap_setting_model,
name="snap",
tooltip="Snap",
width=default_size,
height=default_size,
mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "snap"),
mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b),
checked=self._snap_setting_model.get_value_as_bool(),
)
return {"snap": self._button}
def _on_snap_on_off(self, model): # pragma: no cover (Never called anywhere it seems)
self._snap_settings.enabled = self._snap_setting_model.get_value_as_bool()
def _on_snap_setting_change(self, item, event_type): # pragma: no cover (Never called anywhere it seems)
snap_to_face = self._dict.get(item)
self._snap_to_increment_menu.checked = not snap_to_face
self._snap_to_face_menu.checked = snap_to_face
self._snap_settings.enabled = not snap_to_face
def _on_snap_setting_menu_clicked(self, snap_to_face): # pragma: no cover
self._settings.set(self.SNAP_TO_SURFACE_SETTING, snap_to_face)
def _on_show_snap_increment_setting_window(self): # pragma: no cover
self._snap_increment_setting_window.visible = True
def _create_snap_increment_setting_window(self):
self._snap_increment_setting_window = ui.Window(
"Snap Increment Settings Menu",
width=400,
height=0,
flags=ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_SCROLLBAR,
visible=False,
)
with self._snap_increment_setting_window.frame:
with ui.VStack(spacing=8, height=0, name="frame_v_stack"):
ui.Label("Snap Settings - Increments", enabled=False)
ui.Separator()
with ui.HStack():
with ui.HStack(width=120):
ui.Label("Position", width=50)
ui.Spacer()
all_axis = ["X", "Y", "Z"]
all_axis_model = {
"X": self._snap_move_x_settings_model,
"Y": self._snap_move_y_settings_model,
"Z": self._snap_move_z_settings_model,
}
colors = {"X": 0xFF5555AA, "Y": 0xFF76A371, "Z": 0xFFA07D4F}
for axis in all_axis:
with ui.HStack():
with ui.ZStack(width=15):
ui.Rectangle(
width=15,
height=20,
style={
"background_color": colors[axis],
"border_radius": 3,
"corner_flag": ui.CornerFlag.LEFT,
},
)
ui.Label(axis, alignment=ui.Alignment.CENTER)
ui.FloatDrag(model=all_axis_model[axis], min=0, max=1000000, step=0.01)
ui.Circle(width=20, radius=3.5, size_policy=ui.CircleSizePolicy.FIXED)
with ui.HStack():
with ui.HStack(width=120):
ui.Label("Rotation", width=50)
ui.Spacer()
ui.FloatDrag(model=self._snap_rotate_settings_model, min=0, max=1000000, step=0.01)
with ui.HStack():
with ui.HStack(width=120):
ui.Label("Scale", width=50)
ui.Spacer()
ui.FloatDrag(model=self._snap_scale_settings_model, min=0, max=1000000, step=0.01)
def _register_context_menu(self):
context_menu = omni.kit.context_menu.get_instance()
def is_button(objects: dict, button_name: str): # pragma: no cover
return objects.get("widget_name", None) == button_name
if context_menu:
menu = {
"name": f"Snap Settings {ui.get_custom_glyph_code('${glyphs}/cog.svg')}",
"show_fn": [lambda object: is_button(object, "snap")],
"onclick_fn": lambda object: self._on_show_snap_increment_setting_window(),
"enabled_fn": lambda object: not self._settings.get(self.SNAP_TO_SURFACE_SETTING),
}
self._snap_settings_menu_entry = omni.kit.context_menu.add_menu(menu, "snap", "omni.kit.widget.toolbar")
menu = {
"name": "Snap to Increment",
"show_fn": [lambda object: is_button(object, "snap")],
"onclick_fn": lambda object: self._on_snap_setting_menu_clicked(snap_to_face=False),
"checked_fn": lambda object: not self._settings.get(self.SNAP_TO_SURFACE_SETTING),
}
self._snap_to_increment_menu_entry = omni.kit.context_menu.add_menu(menu, "snap", "omni.kit.widget.toolbar")
menu = {
"name": "Snap to Face",
"show_fn": [lambda object: is_button(object, "snap")],
"onclick_fn": lambda object: self._on_snap_setting_menu_clicked(snap_to_face=True),
"checked_fn": lambda object: self._settings.get(self.SNAP_TO_SURFACE_SETTING),
}
self._snap_to_face_menu_entry = omni.kit.context_menu.add_menu(menu, "snap", "omni.kit.widget.toolbar")
| 9,363 |
Python
| 47.518134 | 120 | 0.583574 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/select_button_group.py
|
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb.input
import omni.kit.context_menu
import omni.ui as ui
import pathlib
from pxr import Kind
from carb.input import KeyboardInput as Key
from omni.kit.widget.toolbar.hotkey import Hotkey
from omni.kit.widget.toolbar.widget_group import WidgetGroup
from .models.select_mode_model import SelectModeModel
from .models.select_no_kinds_model import SelectNoKindsModel
from .models.select_include_ref_model import SelectIncludeRefModel
from .models.transform_mode_model import TransformModeModel
SELECT_PRIM_MODE_TOOL_NAME = "Prim"
SELECT_MODEL_MODE_TOOL_NAME = "Model"
SELECT_TOOL_NAME = "Select"
LIGHT_TYPES = "type:CylinderLight;type:DiskLight;type:DistantLight;type:DomeLight;type:GeometryLight;type:Light;type:RectLight;type:SphereLight"
EXTENSION_FOLDER_PATH = pathlib.Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module("omni.kit.widget.toolbar")
)
SELECT_MODE_BUTTON_ENABLED_SETTING_PATH = "/exts/omni.kit.widget.toolbar/SelectionButton/SelectMode/enabled"
class SelectButtonGroup(WidgetGroup):
def __init__(self):
super().__init__()
self._input = carb.input.acquire_input_interface()
self._select_mode_model = SelectModeModel()
self._select_no_kinds_model = SelectNoKindsModel()
self._select_include_ref_model = SelectIncludeRefModel()
self._select_op_model = TransformModeModel(TransformModeModel.TRANSFORM_OP_SELECT)
self._select_op_menu_entry = None
self._custom_types = []
self._settings = carb.settings.get_settings()
self._icon_path = str(EXTENSION_FOLDER_PATH / "data" / "icon")
self._settings = carb.settings.get_settings()
self._select_mode_button = None
self._mode_hotkey = None
if self._settings.get(SELECT_MODE_BUTTON_ENABLED_SETTING_PATH):
def hotkey_change():
current_mode = self._select_mode_model.get_value_as_string()
if current_mode == "models" or current_mode == "kind:model.ALL":
self._select_mode_model.set_value("type:ALL")
else:
self._select_mode_model.set_value("kind:model.ALL")
self._update_selection_mode_button()
def on_select_mode_hotkey_changed(hotkey: str):
self._select_mode_button.tooltip = self._get_select_mode_tooltip()
self._mode_hotkey = Hotkey(
"toolbar::select_mode",
Key.T,
hotkey_change,
lambda: self._select_mode_button.enabled and self._is_in_context(),
on_hotkey_changed_fn=on_select_mode_hotkey_changed,
)
# only replace the tooltip part so that "Paint Select" registered from select brush can still have correct label
def on_select_hotkey_changed(hotkey: str):
self._select_op_button.tooltip = (
self._select_op_button.tooltip.rsplit("(", 1)[0] + f"({self._select_hotkey.get_as_string('Q')})"
)
self._select_hotkey = Hotkey(
"toolbar::select",
Key.Q,
lambda: self._select_op_button.model.set_value(True),
lambda: self._select_op_button.enabled and self._is_in_context()
and self._input.get_mouse_value(None, carb.input.MouseInput.RIGHT_BUTTON)
== 0,
on_hotkey_changed_fn=lambda hotkey: on_select_hotkey_changed(hotkey),
)
self._sub_menu = []
self._register_context_menu()
def get_style(self):
style = {
"Button.Image::select_mode": {"image_url": "${glyphs}/toolbar_select_prim.svg"},
"Button.Image::select_op_models": {"image_url": "${glyphs}/toolbar_select_models.svg"},
"Button.Image::select_op_prims": {"image_url": "${glyphs}/toolbar_select_prims.svg"},
"Button.Image::all_prim_types": {"image_url": f"{self._icon_path}/all_prim_types.svg"},
"Button.Image::meshes": {"image_url": f"{self._icon_path}/meshes.svg"},
"Button.Image::lights": {"image_url": f"{self._icon_path}/lights.svg"},
"Button.Image::cameras": {"image_url": f"{self._icon_path}/cameras.svg"},
"Button.Image::model_kinds": {"image_url": f"{self._icon_path}/model_kinds.svg"},
"Button.Image::assembly": {"image_url": f"{self._icon_path}/assembly.svg"},
"Button.Image::group": {"image_url": f"{self._icon_path}/group.svg"},
"Button.Image::component": {"image_url": f"{self._icon_path}/component.svg"},
"Button.Image::sub_component": {"image_url": f"{self._icon_path}/sub_component.svg"},
"Button.Image::payload_reference": {"image_url": f"{self._icon_path}/payload_reference.svg"},
"Button.Image::custom_kind": {"image_url": f"{self._icon_path}/custom_kind.svg"},
"Button.Image::custom_type": {"image_url": f"{self._icon_path}/custom_type.svg"},
}
return style
def create(self, default_size):
def select_enabled(): # pragma: no cover (Unused, it's commened out below - I am just adding coverage! '^^)
return True
def on_select_mode_change(model):
self._update_selection_mode_button()
result = {}
if self._settings.get(SELECT_MODE_BUTTON_ENABLED_SETTING_PATH):
self._select_mode_button = ui.ToolButton(
model=self._select_mode_model,
name="select_mode",
tooltip=self._get_select_mode_tooltip(),
width=default_size,
height=default_size,
# checked=select_enabled,
mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "select_mode"),
mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b),
)
self._model_changed_sub = self._select_mode_model.subscribe_value_changed_fn(on_select_mode_change)
result["select_mode"] = self._select_mode_button
with ui.ZStack(width=0, height=0):
self._select_op_button = ui.ToolButton(
model=self._select_op_model,
name=self._get_select_op_button_name(self._select_mode_model),
tooltip=self._get_select_tooltip(),
width=default_size,
height=default_size,
checked=self._select_op_model.get_value_as_bool(),
mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "select_op"),
mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b),
)
# Follow the pattern here (ZStack + _build_flyout_indicator) for other buttons if they want dynamic flyout indicator
self._select_op_menu_sub = self._build_flyout_indicator(default_size, default_size, "select_op")
result["select_op"] = self._select_op_button
self._update_selection_mode_button()
return result
def clean(self):
super().clean()
self._select_mode_button = None
self._select_op_button = None
self._select_mode_model.clean()
self._select_mode_model = None
self._select_no_kinds_model.clean()
self._select_no_kinds_model = None
self._select_include_ref_model.clean()
self._select_include_ref_model = None
self._select_op_model.clean()
self._select_op_model = None
self._model_changed_sub = None
if self._mode_hotkey:
self._mode_hotkey.clean()
self._mode_hotkey = None
self._select_hotkey.clean()
self._select_hotkey = None
self._select_mode_menu_entry.release()
self._select_mode_menu_entry = None
if self._select_op_menu_entry:
self._select_op_menu_entry.release()
self._select_op_menu_entry = None
self._select_op_menu_sub = None
for menu in self._sub_menu:
menu.release()
self._sub_menu = []
def _get_select_op_button_name(self, model):
return "select_op_prims" if model.get_value_as_bool() else "select_op_models"
def _get_select_tooltip(self):
return f"{SELECT_TOOL_NAME} ({self._select_hotkey.get_as_string('Q')})"
def _get_select_mode_button_name(self):
mode_name = {
"type:ALL": "all_prim_types",
"type:Mesh": "meshes",
LIGHT_TYPES: "lights",
"type:Camera": "cameras",
"kind:model.ALL": "model_kinds",
"kind:assembly": "assembly",
"kind:group": "group",
"kind:component": "component",
"kind:subcomponent": "sub_component",
"ref:reference;ref:payload": "custom_type",
}
mode = self._select_mode_model.get_value_as_string()
if mode in mode_name:
return mode_name[mode]
else: # pragma: no cover
if mode[:4] == "kind":
return "custom_kind"
else:
return "custom_type"
def _get_select_mode_tooltip(self):
mode_data = {
"type:ALL": "All Prim Types",
"type:Mesh": "Meshes",
LIGHT_TYPES: "Lights",
"type:Camera": "Camera",
"kind:model.ALL": "All Model Kinds",
"kind:assembly": "Assembly",
"kind:group": "Group",
"kind:component": "Component",
"kind:subcomponent": "Subcomponent",
"ref:reference;ref:payload": "Subcomponent",
}
mode = self._select_mode_model.get_value_as_string()
if mode in mode_data:
tooltip = mode_data[mode]
else: # pragma: no cover
if mode[:4] == "kind":
tooltip = "Custom Kind"
else:
tooltip = "Custom type"
return tooltip + f" ({self._mode_hotkey.get_as_string('T')})"
def _usd_kinds(self):
return ["model", "assembly", "group", "component", "subcomponent"]
def _enable_no_kinds_option(self, b): # pragma: no cover
mode = self._select_mode_model.get_value_as_string()
return mode[:4] == "kind"
def _usd_kinds_display(self): # pragma: no cover
return self._usd_kinds()[1:]
def _plugin_kinds(self):
all_kinds = set(Kind.Registry.GetAllKinds())
return all_kinds - set(self._usd_kinds())
def _create_selection_list(self, selections):
results = ""
delimiter = ";"
first_selection = True
for s in selections:
if not first_selection: # pragma: no cover (This seemingly can never happen, since first_selection is initialized with True oO)
first_selection = True
else:
results += delimiter
results += s
return results
def _update_selection_mode_button(self):
if self._select_mode_button:
self._select_mode_button.name = self._get_select_mode_button_name()
self._select_mode_button.tooltip = self._get_select_mode_tooltip()
if self._select_op_button:
self._select_op_button.name = self._get_select_op_button_name(self._select_mode_model)
def _update_select_menu(self):
for menu in self._sub_menu:
menu.release()
self._sub_menu = []
def create_menu_entry(name, value, add_hotkey=False):
menu = {
"name": name,
"onclick_fn": lambda object: self._select_mode_model.set_value(value),
"checked_fn": lambda object, name=name, value=value: self._select_mode_model.get_value_as_string() == value,
"additional_kwargs": {
"style": {"Menu.Item.CheckMark": {"image_url": omni.kit.context_menu.style.get_radio_mark_url()}}
},
}
if add_hotkey:
menu["hotkey"] = (carb.input.KeyboardInput.T)
return omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar")
def create_header(header=""):
menu = {
"header": header,
"name": "",
}
return omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar")
self._sub_menu.append(create_header(header="Select by Type"))
self._sub_menu.append(create_menu_entry("All Prim Types", "type:ALL", True))
self._sub_menu.append(create_menu_entry("Meshes", "type:Mesh"))
self._sub_menu.append(create_menu_entry("Lights", LIGHT_TYPES))
self._sub_menu.append(create_menu_entry("Camera", "type:Camera"))
if self._custom_types:
for name, types in self._custom_types:
self._sub_menu.append(create_menu_entry(name, types))
self._sub_menu.append(create_header(header="Select by Model Kind"))
self._sub_menu.append(create_menu_entry("All Model Kinds", "kind:model.ALL"))
self._sub_menu.append(create_menu_entry("Assembly", "kind:assembly"))
self._sub_menu.append(create_menu_entry("Group", "kind:group"))
self._sub_menu.append(create_menu_entry("Component", "kind:component"))
self._sub_menu.append(create_menu_entry("Subcomponent", "kind:subcomponent"))
plugin_kinds = self._plugin_kinds()
if (len(plugin_kinds)) > 0:
for k in plugin_kinds: # pragma: no cover
self._sub_menu.append(create_menu_entry(str(k), str(key).capitalize(), f"kind:{k}"))
self._sub_menu.append(create_header(header=""))
menu = {
"name": "Include Prims with no Kind",
"onclick_fn": lambda object: self._select_no_kinds_model.set_value(not self._select_no_kinds_model.get_value_as_bool()),
"checked_fn": lambda object: self._select_no_kinds_model.get_value_as_bool(),
"enabled_fn": self._enable_no_kinds_option,
}
self._sub_menu.append(omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar"))
menu = {
"name": "Include References and Payloads",
"onclick_fn": lambda object: self._select_include_ref_model.set_value(not self._select_include_ref_model.get_value_as_bool()),
"checked_fn": lambda object: self._select_include_ref_model.get_value_as_bool(),
"enabled_fn": self._enable_no_kinds_option,
}
self._sub_menu.append(omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar"))
def _register_context_menu(self):
context_menu = omni.kit.context_menu.get_instance()
def is_button(objects: dict, button_name: str): # pragma: no cover
return objects.get("widget_name", None) == button_name
if context_menu:
def on_clicked_select(): # pragma: no cover
self._select_op_model.set_value(True)
self._select_op_button.name = self._get_select_op_button_name(self._select_mode_model)
self._select_op_button.set_tooltip(self._get_select_tooltip())
self._select_op_button.model = self._select_op_model
menu = {
"name": "Select",
"show_fn": [lambda object: is_button(object, "select_op")],
"onclick_fn": lambda object: on_clicked_select(),
"checked_fn": lambda object: self._select_op_button.name == "select_op_prims"
or self._select_op_button.name == "select_op_models",
}
self._select_mode_menu_entry = omni.kit.context_menu.add_menu(menu, "select_op", "omni.kit.widget.toolbar")
if self._settings.get(SELECT_MODE_BUTTON_ENABLED_SETTING_PATH):
menu = {
"name": "Select Mode",
"show_fn": [lambda object: is_button(object, "select_mode")],
}
self._select_op_menu_entry = omni.kit.context_menu.add_menu(menu, "select_mode", "omni.kit.widget.toolbar")
self._update_select_menu()
def add_custom_select_type(self, entry_name: str, selection_types: list):
selection = []
for s in selection_types:
selection.append(f"type:{s}")
selection_string = self._create_selection_list(selection)
self._custom_types.append((entry_name, selection_string))
self._update_select_menu()
def remove_custom_select(self, entry_name):
for index, (entry, selection_string) in enumerate(self._custom_types):
if entry == entry_name:
del self._custom_types[index]
self._update_select_menu()
return
| 17,097 |
Python
| 44.473404 | 144 | 0.592151 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/transform_mode_model.py
|
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
import carb
import carb.dictionary
import carb.settings
class TransformModeModel(ui.AbstractValueModel):
"""The value model that is reimplemented in Python to watch the prim select mode"""
TRANSFORM_OP_SETTING = "/app/transform/operation"
TRANSFORM_OP_SELECT = "select"
TRANSFORM_OP_MOVE = "move"
TRANSFORM_OP_ROTATE = "rotate"
TRANSFORM_OP_SCALE = "scale"
def __init__(self, op):
super().__init__()
self._op = op
self._settings = carb.settings.get_settings()
self._settings.set_default_string(self.TRANSFORM_OP_SETTING, self.TRANSFORM_OP_MOVE)
self._dict = carb.dictionary.get_dictionary()
self._op_sub = self._settings.subscribe_to_node_change_events(self.TRANSFORM_OP_SETTING, self._on_op_change)
self._selected_op = self._settings.get(self.TRANSFORM_OP_SETTING)
def clean(self):
self._settings.unsubscribe_to_change_events(self._op_sub)
def _on_op_change(self, item, event_type):
self._selected_op = self._dict.get(item)
self._value_changed()
def _on_op_space_changed(self, item, event_type): # pragma: no cover (Seems to never be used, is overwritten in the inherited model where it is used.)
self._op_space = self._dict.get(item)
self._value_changed()
def get_value_as_bool(self):
return self._selected_op == self._op
def set_value(self, value):
"""Reimplemented set bool"""
if value:
self._settings.set(self.TRANSFORM_OP_SETTING, self._op)
class LocalGlobalTransformModeModel(TransformModeModel):
TRANSFORM_MODE_GLOBAL = "global"
TRANSFORM_MODE_LOCAL = "local"
def __init__(self, op, op_space_setting_path):
super().__init__(op=op)
self._setting_path = op_space_setting_path
self._op_space_sub = self._settings.subscribe_to_node_change_events(
self._setting_path, self._on_op_space_changed
)
self._op_space = self._settings.get(self._setting_path)
def clean(self):
self._settings.unsubscribe_to_change_events(self._op_space_sub)
super().clean()
def _on_op_space_changed(self, item, event_type):
self._op_space = self._dict.get(item)
self._value_changed()
def get_op_space_mode(self):
return self._op_space
def set_value(self, value):
if not value:
self._settings.set(
self._setting_path,
self.TRANSFORM_MODE_LOCAL
if self._op_space == self.TRANSFORM_MODE_GLOBAL
else self.TRANSFORM_MODE_GLOBAL,
)
super().set_value(value)
| 3,104 |
Python
| 33.5 | 155 | 0.653351 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/setting_model.py
|
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
import carb
import carb.dictionary
import carb.settings
class BoolSettingModel(ui.AbstractValueModel):
"""The value model that is reimplemented in Python to watch a bool setting path"""
def __init__(self, setting_path, inverted):
super().__init__()
self._setting_path = setting_path
self._inverted = inverted
self._settings = carb.settings.get_settings()
self._dict = carb.dictionary.get_dictionary()
self._subscription = self._settings.subscribe_to_node_change_events(self._setting_path, self._on_change)
self._value = self._settings.get(self._setting_path)
if self._inverted:
self._value = not self._value
def clean(self):
self._settings.unsubscribe_to_change_events(self._subscription)
def _on_change(self, item, event_type):
self._value = self._dict.get(item)
if self._inverted:
self._value = not self._value
self._value_changed()
def get_value_as_bool(self):
return self._value
def set_value(self, value):
"""Reimplemented set bool"""
if self._inverted:
value = not value
self._settings.set(self._setting_path, value)
if self._inverted:
self._value = value
class FloatSettingModel(ui.AbstractValueModel):
"""The value model that is reimplemented in Python to watch a float setting path"""
def __init__(self, setting_path):
super().__init__()
self._setting_path = setting_path
self._settings = carb.settings.get_settings()
self._dict = carb.dictionary.get_dictionary()
self._subscription = self._settings.subscribe_to_node_change_events(self._setting_path, self._on_change)
self._value = self._settings.get(self._setting_path)
def clean(self):
self._settings.unsubscribe_to_change_events(self._subscription)
def _on_change(self, item, event_type):
self._value = self._dict.get(item)
self._value_changed()
def get_value_as_float(self):
return self._value
def set_value(self, value):
"""Reimplemented set float"""
self._settings.set(self._setting_path, value)
| 2,654 |
Python
| 34.4 | 112 | 0.662773 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/timeline_model.py
|
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
import carb
import omni.timeline
from omni.kit.commands import execute
class TimelinePlayPauseModel(ui.AbstractValueModel):
"""The value model that is reimplemented in Python to watch a bool setting path"""
def __init__(self):
super().__init__()
self._timeline = omni.timeline.get_timeline_interface()
self._is_playing = self._timeline.is_playing()
self._is_stopped = self._timeline.is_stopped()
stream = self._timeline.get_timeline_event_stream()
self._sub = stream.create_subscription_to_pop(self._on_timeline_event)
def clean(self):
self._sub = None
def get_value_as_bool(self):
return self._is_playing and not self._is_stopped
def set_value(self, value):
"""Reimplemented set bool"""
if value:
execute("ToolbarPlayButtonClicked")
else:
execute("ToolbarPauseButtonClicked")
def _on_timeline_event(self, e):
is_playing = self._timeline.is_playing()
is_stopped = self._timeline.is_stopped()
if is_playing != self._is_playing or is_stopped != self._is_stopped:
self._is_playing = self._timeline.is_playing()
self._is_stopped = self._timeline.is_stopped()
self._value_changed()
| 1,732 |
Python
| 34.367346 | 86 | 0.67552 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/select_mode_model.py
|
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
import carb
import carb.dictionary
import carb.settings
class SelectModeModel(ui.AbstractValueModel):
"""The value model that is reimplemented in Python to watch the prim select mode"""
PICKING_MODE_SETTING = "/persistent/app/viewport/pickingMode"
PICKING_MODE_MODELS = "kind:model.ALL"
PICKING_MODE_PRIMS = "type:ALL"
# new default
PICKING_MODE_DEFAULT = PICKING_MODE_PRIMS
def __init__(self):
super().__init__()
self._settings = carb.settings.get_settings()
self._settings.set_default_string(self.PICKING_MODE_SETTING, self.PICKING_MODE_DEFAULT)
self._dict = carb.dictionary.get_dictionary()
self._subscription = self._settings.subscribe_to_node_change_events(self.PICKING_MODE_SETTING, self._on_change)
self.set_value(self._settings.get(self.PICKING_MODE_SETTING))
def clean(self):
self._settings.unsubscribe_to_change_events(self._subscription)
def _on_change(self, item, event_type):
self._mode = self._dict.get(item)
self._value_changed()
def get_value_as_bool(self):
return self._mode == self.PICKING_MODE_PRIMS
def get_value_as_string(self):
return self._mode
def set_value(self, value):
if isinstance(value, bool):
if value:
self._mode = self.PICKING_MODE_PRIMS
else:
self._mode = self.PICKING_MODE_MODELS
else:
self._mode = value
self._settings.set(self.PICKING_MODE_SETTING, self._mode)
| 1,993 |
Python
| 32.79661 | 119 | 0.67988 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/builtin_tools/models/select_no_kinds_model.py
|
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
import carb
import carb.dictionary
import carb.settings
class SelectNoKindsModel(ui.AbstractValueModel):
"""The value model that is reimplemented in Python to watch the prim select mode"""
PICKING_MODE_NO_KINDS_SETTING = "/persistent/app/viewport/pickingModeNoKinds"
# new default
PICKING_MODE_NO_KINDS_DEFAULT = True
def __init__(self):
super().__init__()
self._settings = carb.settings.get_settings()
self._settings.set_default_bool(self.PICKING_MODE_NO_KINDS_SETTING, self.PICKING_MODE_NO_KINDS_DEFAULT)
self._dict = carb.dictionary.get_dictionary()
self._subscription = self._settings.subscribe_to_node_change_events(self.PICKING_MODE_NO_KINDS_SETTING, self._on_change)
self.set_value(self._settings.get(self.PICKING_MODE_NO_KINDS_SETTING))
def clean(self):
self._settings.unsubscribe_to_change_events(self._subscription)
def _on_change(self, item, event_type):
self._mode = self._dict.get(item)
self._value_changed()
def get_value_as_bool(self):
return self._mode
def set_value(self, value):
self._mode = value
self._settings.set(self.PICKING_MODE_NO_KINDS_SETTING, self._mode)
| 1,680 |
Python
| 34.765957 | 128 | 0.713095 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/tests/helpers.py
|
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb.settings
def reset_toolbar_settings():
settings = carb.settings.get_settings()
vals = {
"/app/transform/operation": "move",
"/persistent/app/viewport/pickingMode": "type:ALL",
"/app/viewport/snapEnabled": False,
}
for key, val in vals.items():
settings.set(key, val)
| 759 |
Python
| 32.043477 | 76 | 0.724638 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/tests/test_api.py
|
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import asyncio
import carb.settings
import omni.appwindow
import omni.kit.app
import omni.kit.test
import omni.timeline
import omni.kit.ui_test as ui_test
import omni.kit.widget.toolbar
import omni.kit.context_menu
import omni.kit.hotkeys.core
import omni.ui as ui
from carb.input import KeyboardInput as Key
from carb.input import KEYBOARD_MODIFIER_FLAG_SHIFT
from omni.kit.ui_test import Vec2
from omni.kit.widget.toolbar import Hotkey, SimpleToolButton, Toolbar, WidgetGroup, get_instance
from .helpers import reset_toolbar_settings
test_message_queue = []
class TestSimpleToolButton(SimpleToolButton):
"""
Test of how to use SimpleToolButton
"""
def __init__(self, icon_path):
def on_toggled(c):
test_message_queue.append(f"Test button toggled {c}")
super().__init__(
name="test_simple_tool_button",
tooltip="Test Simple ToolButton",
icon_path=f"{icon_path}/plus.svg",
icon_checked_path=f"{icon_path}/plus.svg",
hotkey=Key.U,
toggled_fn=on_toggled,
additional_style={"Button": { "color": 0xffffffff }}
)
class TestToolButtonGroup(WidgetGroup):
"""
Test of how to create two ToolButton in one WidgetGroup
"""
def __init__(self, icon_path):
super().__init__()
self._icon_path = icon_path
def clean(self):
self._sub1 = None
self._sub2 = None
self._hotkey.clean()
self._hotkey = None
super().clean()
def get_style(self):
style = {
"Button.Image::test1": {"image_url": f"{self._icon_path}/plus.svg"},
"Button.Image::test1:checked": {"image_url": f"{self._icon_path}/minus.svg"},
"Button.Image::test2": {"image_url": f"{self._icon_path}/minus.svg"},
"Button.Image::test2:checked": {"image_url": f"{self._icon_path}/plus.svg"},
}
return style
def create(self, default_size):
def on_value_changed(index, model):
if model.get_value_as_bool():
self._acquire_toolbar_context()
else:
self._release_toolbar_context()
test_message_queue.append(f"Group button {index} clicked")
self._menu1 = omni.kit.context_menu.add_menu({ "name": "Test 1", "onclick_fn": None }, "test1", "omni.kit.widget.toolbar")
self._menu2 = omni.kit.context_menu.add_menu({ "name": "Test 2", "onclick_fn": None }, "test1", "omni.kit.widget.toolbar")
button1 = ui.ToolButton(
name="test1",
width=default_size,
height=default_size,
mouse_pressed_fn=lambda x, y, b, _: self._on_mouse_pressed(b, "test1"),
mouse_released_fn=lambda x, y, b, _: self._on_mouse_released(b),
)
self._sub1 = button1.model.subscribe_value_changed_fn(lambda model, index=1: on_value_changed(index, model))
button2 = ui.ToolButton(
name="test2",
width=default_size,
height=default_size,
)
self._sub2 = button2.model.subscribe_value_changed_fn(lambda model, index=2: on_value_changed(index, model))
self._hotkey = Hotkey(
"toolbar::test2",
Key.K,
lambda: button2.model.set_value(not button2.model.get_value_as_bool()),
lambda: self._is_in_context(),
)
# return a dictionary of name -> widget if you want to expose it to other widget_group
return {"test1": button1, "test2": button2}
_MAIN_WINDOW_INSTANCE = None
class ToolbarApiTest(omni.kit.test.AsyncTestCase):
WINDOW_NAME = "Main Toolbar Test"
async def setUp(self):
reset_toolbar_settings()
self._icon_path = omni.kit.widget.toolbar.get_data_path().absolute().joinpath("icon").absolute()
self._app = omni.kit.app.get_app()
test_message_queue.clear()
# If the instance doesn't exist, we need to create it for the test
# Create a tmp window with the widget inside, Y axis because the tests are in the Y axis
global _MAIN_WINDOW_INSTANCE
if _MAIN_WINDOW_INSTANCE is None:
_MAIN_WINDOW_INSTANCE = ui.ToolBar(
self.WINDOW_NAME, noTabBar=False, padding_x=3, padding_y=3, margin=5, axis=ui.ToolBarAxis.Y
)
self._widget = get_instance()
self._widget.set_axis(ui.ToolBarAxis.Y)
self._widget.rebuild_toolbar(root_frame=_MAIN_WINDOW_INSTANCE.frame)
await self._app.next_update_async()
await self._app.next_update_async()
self._main_dockspace = ui.Workspace.get_window("DockSpace")
self._toolbar_handle = ui.Workspace.get_window(self.WINDOW_NAME)
self._toolbar_handle.undock()
await self._app.next_update_async()
self._toolbar_handle.dock_in(self._main_dockspace, ui.DockPosition.LEFT)
await self._app.next_update_async()
async def test_api(self):
toolbar: Toolbar = omni.kit.widget.toolbar.get_instance()
widget_simple = TestSimpleToolButton(self._icon_path)
widget = TestToolButtonGroup(self._icon_path)
toolbar.add_widget(widget, -100)
toolbar.add_widget(widget_simple, -200)
await self._app.next_update_async()
self.assertIsNotNone(widget_simple.get_tool_button())
# Check widgets are added and can be fetched
self.assertIsNotNone(toolbar.get_widget("test_simple_tool_button"))
self.assertIsNotNone(toolbar.get_widget("test1"))
self.assertIsNotNone(toolbar.get_widget("test2"))
await self._app.next_update_async()
await self._app.next_update_async()
await self._app.next_update_async()
await self._app.next_update_async()
await self._app.next_update_async()
manager = omni.kit.app.get_app().get_extension_manager()
extension_name = omni.ext.get_extension_name(manager.get_extension_id_by_module(__name__))
hotkey_registry = omni.kit.hotkeys.core.get_hotkey_registry()
hotkey = self._get_hotkey('test_simple_tool_button::hotkey')
self.assertIsNotNone(hotkey)
hotkey_registry.edit_hotkey(hotkey, omni.kit.hotkeys.core.KeyCombination(Key.U, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None)
tool_test_simple_pos = self._get_widget_center(toolbar, "test_simple_tool_button")
tool_test1_pos = self._get_widget_center(toolbar, "test1")
tool_test2_pos = self._get_widget_center(toolbar, "test2")
# Test click on first simple button
await self._emulate_click(tool_test_simple_pos)
await self._app.next_update_async()
# Test hot key on first simple button
await self._emulate_keyboard_press(Key.U, KEYBOARD_MODIFIER_FLAG_SHIFT)
await self._app.next_update_async()
# Test click on 1/2 group button
await self._emulate_click(tool_test1_pos)
await self._app.next_update_async()
# Test click on 2/2 group button
await self._emulate_click(tool_test2_pos)
await self._app.next_update_async()
# Test click on 2/2 group button again
await self._emulate_click(tool_test2_pos)
await self._app.next_update_async()
self.assertIsNone(ui.Menu.get_current())
# Test right click on 1/2 group button
await self._emulate_click(tool_test1_pos, right_click=True)
await self._app.next_update_async()
self.assertIsNotNone(ui.Menu.get_current())
# Test left click on 1/2 group button to close the menu
await self._emulate_click(tool_test1_pos, right_click=False)
await self._app.next_update_async()
self.assertIsNone(ui.Menu.get_current())
# Test hold-left-click click on 1/2 group button
await ui_test.input.emulate_mouse(ui_test.input.MouseEventType.MOVE, Vec2(*tool_test1_pos))
await ui_test.input.emulate_mouse(ui_test.input.MouseEventType.LEFT_BUTTON_DOWN)
await self._app.next_update_async()
await asyncio.sleep(0.4)
await ui_test.input.emulate_mouse(ui_test.input.MouseEventType.LEFT_BUTTON_UP)
await self._app.next_update_async()
self.assertIsNotNone(ui.Menu.get_current())
# Test left click on 1/2 group button to close the menu
await self._emulate_click(tool_test1_pos)
await self._app.next_update_async()
self.assertIsNone(ui.Menu.get_current())
# Making sure all button are triggered by checking the message queue
expected_messages = [
"Test button toggled True",
"Test button toggled False",
"Group button 1 clicked",
"Group button 2 clicked",
"Group button 2 clicked",
]
self.assertEqual(expected_messages, test_message_queue)
test_message_queue.clear()
hotkey_registry.edit_hotkey(hotkey, omni.kit.hotkeys.core.KeyCombination(Key.U, modifiers=0), None)
toolbar.remove_widget(widget)
toolbar.remove_widget(widget_simple)
widget.clean()
widget_simple.clean()
await self._app.next_update_async()
# Check widgets are cleared
self.assertIsNone(toolbar.get_widget("test_simple_tool_button"))
self.assertIsNone(toolbar.get_widget("test1"))
self.assertIsNone(toolbar.get_widget("test2"))
# Change the Hotkey for the Play button
play_hotkey = self._get_hotkey('toolbar::play')
self.assertIsNotNone(play_hotkey)
hotkey_registry.edit_hotkey(play_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.SPACE, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None)
await self._app.next_update_async()
tooltip_after_change = toolbar.get_widget('play').tooltip
hotkey_registry.edit_hotkey(play_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.SPACE, modifiers=0), None)
await self._app.next_update_async()
tooltip_after_revert = toolbar.get_widget('play').tooltip
self.assertEqual(tooltip_after_change, "Play (SHIFT + SPACE)")
self.assertEqual(tooltip_after_revert, "Play (SPACE)")
# Change the Hotkey for the Select Mode button
select_mode_hotkey = self._get_hotkey('toolbar::select_mode')
self.assertIsNotNone(select_mode_hotkey)
hotkey_registry.edit_hotkey(select_mode_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.T, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None)
await self._app.next_update_async()
tooltip_after_change = toolbar.get_widget('select_mode').tooltip
hotkey_registry.edit_hotkey(select_mode_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.T, modifiers=0), None)
await self._app.next_update_async()
tooltip_after_revert = toolbar.get_widget('select_mode').tooltip
self.assertEqual(tooltip_after_change, "All Prim Types (SHIFT + T)")
self.assertEqual(tooltip_after_revert, "All Prim Types (T)")
# Change the Hotkey for the Move button
move_op_hotkey = self._get_hotkey('toolbar::move')
self.assertIsNotNone(move_op_hotkey)
hotkey_registry.edit_hotkey(move_op_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.W, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None)
await self._app.next_update_async()
tooltip_after_change = toolbar.get_widget('move_op').tooltip
hotkey_registry.edit_hotkey(move_op_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.W, modifiers=0), None)
await self._app.next_update_async()
tooltip_after_revert = toolbar.get_widget('move_op').tooltip
from ..builtin_tools.transform_button_group import MOVE_TOOL_NAME
self.assertEqual(tooltip_after_change, f"{MOVE_TOOL_NAME} (SHIFT + W)")
self.assertEqual(tooltip_after_revert, f"{MOVE_TOOL_NAME} (W)")
# Test the Select Mode hotkey button
settings = carb.settings.get_settings()
from ..builtin_tools.models.select_mode_model import SelectModeModel
self.assertEqual(settings.get(SelectModeModel.PICKING_MODE_SETTING), SelectModeModel.PICKING_MODE_PRIMS)
await self._emulate_keyboard_press(Key.T)
await self._app.next_update_async()
self.assertEqual(settings.get(SelectModeModel.PICKING_MODE_SETTING), SelectModeModel.PICKING_MODE_MODELS)
await self._emulate_keyboard_press(Key.T)
await self._app.next_update_async()
self.assertEqual(settings.get(SelectModeModel.PICKING_MODE_SETTING), SelectModeModel.PICKING_MODE_PRIMS)
# Test changing the Select hotkey
select_hotkey = self._get_hotkey('toolbar::select')
self.assertIsNotNone(select_hotkey)
hotkey_registry.edit_hotkey(select_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.Q, modifiers=KEYBOARD_MODIFIER_FLAG_SHIFT), None)
await self._app.next_update_async()
hotkey_registry.edit_hotkey(select_hotkey, omni.kit.hotkeys.core.KeyCombination(Key.Q, modifiers=0), None)
await self._app.next_update_async()
async def test_context(self):
toolbar = omni.kit.widget.toolbar.get_instance()
widget_simple = TestSimpleToolButton(self._icon_path)
widget = TestToolButtonGroup(self._icon_path)
test_context = "test_context"
toolbar.add_widget(widget, -100)
toolbar.add_widget(widget_simple, -200, test_context)
await self._app.next_update_async()
await self._app.next_update_async()
await self._app.next_update_async()
await self._app.next_update_async()
await self._app.next_update_async()
tool_test_simple_pos = self._get_widget_center(toolbar, "test_simple_tool_button")
tool_test1_pos = self._get_widget_center(toolbar, "test1")
# Test click on first simple button
# Add "Test button toggled True" to queue
await self._emulate_click(tool_test_simple_pos)
await self._app.next_update_async()
self.assertEqual(toolbar.get_context(), test_context)
# Test hot key on 2/2 group button
# It should have no effect since it's not "in context"
# Add nothing to queue
await self._emulate_keyboard_press(Key.K)
await self._app.next_update_async()
# Test click on first simple button again, should exit context
# Add "Test button toggled False" to queue
await self._emulate_click(tool_test_simple_pos)
await self._app.next_update_async()
self.assertEqual(toolbar.get_context(), Toolbar.DEFAULT_CONTEXT)
# Test hot key on 2/2 group button again
# It should have effect because it's in default context
# Add "Group button 2 clicked" to queue
await self._emulate_keyboard_press(Key.K)
await self._app.next_update_async()
# Test click on first simple button again
# Add "Test button toggled True" to queue
await self._emulate_click(tool_test_simple_pos)
await self._app.next_update_async()
self.assertEqual(toolbar.get_context(), test_context)
# Test click on 1/2 group button so it takes context by force.
# Add "Group button 1 clicked" to queue
await self._emulate_click(tool_test1_pos)
await self._app.next_update_async()
self.assertEqual(toolbar.get_context(), Toolbar.DEFAULT_CONTEXT)
# Test hot key on first simple button, it should still work on default context.
# Releasing an expired context.
# Add "Test button toggled False" to queue
await self._emulate_keyboard_press(Key.U)
await self._app.next_update_async()
self.assertEqual(toolbar.get_context(), Toolbar.DEFAULT_CONTEXT)
# Test hot key on first simple button, it should still work on default context.
# Add "Test button toggled True" to queue
await self._emulate_keyboard_press(Key.U)
await self._app.next_update_async()
self.assertEqual(toolbar.get_context(), test_context)
expected_messages = [
"Test button toggled True",
"Test button toggled False",
"Group button 2 clicked",
"Test button toggled True",
"Group button 1 clicked",
"Test button toggled False",
"Test button toggled True",
]
self.assertEqual(expected_messages, test_message_queue)
toolbar.remove_widget(widget)
toolbar.remove_widget(widget_simple)
widget.clean()
widget_simple.clean()
await self._app.next_update_async()
def _get_widget_center(self, toolbar, id: str):
return (
toolbar.get_widget(id).screen_position_x + toolbar.get_widget(id).width / 2,
toolbar.get_widget(id).screen_position_y + toolbar.get_widget(id).height / 2,
)
def _get_hotkey(self, action_id: str):
manager = omni.kit.app.get_app().get_extension_manager()
extension_name = omni.ext.get_extension_name(manager.get_extension_id_by_module(__name__))
hotkey_registry = omni.kit.hotkeys.core.get_hotkey_registry()
for hotkey in hotkey_registry.get_all_hotkeys_for_extension(extension_name):
if hotkey.action_id == action_id:
return hotkey
async def _emulate_click(self, pos, right_click: bool = False):
await ui_test.emulate_mouse_move_and_click(Vec2(*pos), right_click=right_click)
async def _emulate_keyboard_press(self, key: Key, modifier: int = 0):
await ui_test.emulate_keyboard_press(key, modifier)
async def test_custom_select_types(self):
toolbar: Toolbar = omni.kit.widget.toolbar.get_instance()
entry_name = 'TestType'
toolbar.add_custom_select_type(entry_name, ['test_type'])
menu_dict = omni.kit.context_menu.get_menu_dict("select_mode", "omni.kit.widget.toolbar")
self.assertIn(entry_name, [item['name'] for item in menu_dict])
toolbar.remove_custom_select(entry_name)
menu_dict = omni.kit.context_menu.get_menu_dict("select_mode", "omni.kit.widget.toolbar")
self.assertNotIn(entry_name, [item['name'] for item in menu_dict])
async def test_toolbar_methods(self):
from ..context_menu import ContextMenu
toolbar: Toolbar = omni.kit.widget.toolbar.get_instance()
self.assertIsInstance(toolbar.context_menu, ContextMenu)
toolbar.set_axis(ui.ToolBarAxis.X)
toolbar.rebuild_toolbar()
await ui_test.human_delay()
toolbar.set_axis(ui.ToolBarAxis.Y)
toolbar.rebuild_toolbar()
await ui_test.human_delay()
toolbar.subscribe_grab_mouse_pressed(None)
async def test_toolbar_play_stop_button(self):
toolbar: Toolbar = omni.kit.widget.toolbar.get_instance()
timeline = omni.timeline.get_timeline_interface()
# Click the stop button
toolbar.get_widget("stop").call_clicked_fn()
await ui_test.human_delay()
self.assertTrue(timeline.is_stopped())
| 19,485 |
Python
| 39.17732 | 146 | 0.651014 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/tests/__init__.py
|
from .test_api import *
from .test_models import *
| 50 |
Python
| 24.499988 | 26 | 0.74 |
omniverse-code/kit/exts/omni.kit.widget.toolbar/omni/kit/widget/toolbar/tests/test_models.py
|
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.kit.app
import omni.kit.test
import omni.timeline
import carb.settings
import omni.kit.commands
from omni.kit import ui_test
class ToolbarTestModels(omni.kit.test.AsyncTestCase):
async def test_setting_pass_through(self):
from ..builtin_tools.builtin_tools import LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW, LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET
settings = carb.settings.get_settings()
orig_value = settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET)
settings.set_bool(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW, True)
self.assertEqual(settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW), settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET))
settings.set_bool(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW, False)
self.assertEqual(settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WINDOW), settings.get(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET))
settings.set_bool(LEGACY_SNAP_BUTTON_ENABLED_SETTING_PATH_WIDGET, orig_value)
async def test_select_include_ref_model(self):
from ..builtin_tools.models.select_include_ref_model import SelectIncludeRefModel
model = SelectIncludeRefModel()
orig_value = model.get_value_as_bool()
model.set_value(not orig_value)
self.assertEqual(model.get_value_as_bool(), not orig_value)
model.set_value(orig_value)
async def test_select_mode_model(self):
from ..builtin_tools.models.select_mode_model import SelectModeModel
model = SelectModeModel()
orig_value = model.get_value_as_string()
model.set_value(True)
self.assertEqual(model.get_value_as_string(), SelectModeModel.PICKING_MODE_PRIMS)
model.set_value(False)
self.assertEqual(model.get_value_as_string(), SelectModeModel.PICKING_MODE_MODELS)
model.set_value(SelectModeModel.PICKING_MODE_PRIMS)
self.assertEqual(model.get_value_as_string(), SelectModeModel.PICKING_MODE_PRIMS)
model.set_value(orig_value)
async def test_select_no_kinds_model(self):
from ..builtin_tools.models.select_no_kinds_model import SelectNoKindsModel
model = SelectNoKindsModel()
orig_value = model.get_value_as_bool()
model.set_value(not orig_value)
self.assertEqual(model.get_value_as_bool(), not orig_value)
model.set_value(orig_value)
async def test_setting_model(self):
from ..builtin_tools.models.setting_model import BoolSettingModel, FloatSettingModel
settings = carb.settings.get_settings()
bool_setting_path = '/exts/omni.kit.widget.toolbar/test/boolSetting'
float_setting_path = '/exts/omni.kit.widget.toolbar/test/floatSetting'
bool_model = BoolSettingModel(bool_setting_path, False)
bool_model.set_value(True)
self.assertEqual(bool_model.get_value_as_bool(), True)
self.assertEqual(settings.get(bool_setting_path), True)
bool_model.set_value(False)
self.assertEqual(bool_model.get_value_as_bool(), False)
self.assertEqual(settings.get(bool_setting_path), False)
inverted_bool_model = BoolSettingModel(bool_setting_path, True)
inverted_bool_model.set_value(True)
self.assertEqual(inverted_bool_model.get_value_as_bool(), not True)
self.assertEqual(settings.get(bool_setting_path), not True)
inverted_bool_model.set_value(False)
self.assertEqual(inverted_bool_model.get_value_as_bool(), not False)
self.assertEqual(settings.get(bool_setting_path), not False)
float_model = FloatSettingModel(float_setting_path)
float_model.set_value(42.0)
self.assertEqual(float_model.get_value_as_float(), 42.0)
self.assertEqual(settings.get(float_setting_path), 42.0)
float_model.set_value(21.0)
self.assertEqual(float_model.get_value_as_float(), 21.0)
self.assertEqual(settings.get(float_setting_path), 21.0)
async def test_timeline_model(self):
from ..builtin_tools.models.timeline_model import TimelinePlayPauseModel
model = TimelinePlayPauseModel()
model.set_value(True)
await ui_test.human_delay()
self.assertTrue(model.get_value_as_bool())
model.set_value(False)
await ui_test.human_delay()
self.assertFalse(model.get_value_as_bool())
async def test_transform_mode_model(self):
from ..builtin_tools.models.transform_mode_model import TransformModeModel, LocalGlobalTransformModeModel
model = TransformModeModel(TransformModeModel.TRANSFORM_OP_MOVE)
model.set_value(True)
self.assertTrue(model.get_value_as_bool())
settings = carb.settings.get_settings()
setting_path = '/exts/omni.kit.widget.toolbar/test/localGlobalTransformOp'
settings.set(setting_path, LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL)
model = LocalGlobalTransformModeModel(TransformModeModel.TRANSFORM_OP_MOVE, setting_path)
model.set_value(False)
self.assertTrue(model.get_op_space_mode() == LocalGlobalTransformModeModel.TRANSFORM_MODE_LOCAL)
model.set_value(False)
self.assertTrue(model.get_op_space_mode() == LocalGlobalTransformModeModel.TRANSFORM_MODE_GLOBAL)
async def test_play_pause_stop_commands(self):
timeline = omni.timeline.get_timeline_interface()
omni.kit.commands.execute("ToolbarPlayButtonClicked")
await ui_test.human_delay()
self.assertTrue(timeline.is_playing())
omni.kit.commands.execute("ToolbarPauseButtonClicked")
await ui_test.human_delay()
self.assertFalse(timeline.is_playing())
omni.kit.commands.execute("ToolbarStopButtonClicked")
await ui_test.human_delay()
self.assertTrue(timeline.is_stopped())
settings = carb.settings.get_settings()
setting_path = '/exts/omni.kit.widget.toolbar/test/playFilter'
omni.kit.commands.execute("ToolbarPlayFilterChecked", setting_path=setting_path, enabled=True)
self.assertTrue(settings.get(setting_path))
| 6,629 |
Python
| 43.496644 | 148 | 0.706291 |
omniverse-code/kit/exts/omni.kit.window.file/config/extension.toml
|
[package]
# Semantic Versioning is used: https://semver.org/
version = "1.3.32"
category = "Internal"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarily for displaying extension info in UI
title = "USD File UI"
description="Provides utility functions to new/open/save/close USD files"
# URL of the extension source repository.
repository = ""
# Keywords for the extension
keywords = ["kit", "usd", "ui"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog = "docs/CHANGELOG.md"
[dependencies]
"omni.client" = {}
"omni.usd" = {}
"omni.kit.stage_templates" = {}
"omni.ui" = {}
"omni.kit.pip_archive" = {} # Pull in pip_archive to make sure psutil is found and not installed
"omni.kit.window.file_importer" = {}
"omni.kit.window.file_exporter" = {}
"omni.kit.widget.versioning" = {}
"omni.kit.widget.nucleus_connector" = {}
"omni.kit.actions.core" = {}
[python.pipapi]
requirements = ["psutil"]
[[python.module]]
name = "omni.kit.window.file"
[settings]
exts."omni.kit.window.file".enable_versioning = true
[[test]]
args = [
"--/renderer/enabled=pxr",
"--/renderer/active=pxr",
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--/app/file/ignoreUnsavedOnExit=true",
"--/persistent/app/omniverse/filepicker/options_menu/show_details=false",
"--no-window"
]
dependencies = [
"omni.hydra.pxr",
"omni.physx.bundle",
"omni.timeline",
"omni.kit.mainwindow",
"omni.kit.menu.file",
"omni.kit.ui_test",
"omni.kit.test_suite.helpers",
]
| 1,741 |
TOML
| 25.8 | 96 | 0.687536 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/prompt_ui.py
|
import urllib
import carb
import carb.settings
import omni.ui as ui
from typing import List
class Prompt:
def __init__(
self, title: str, text: str, button_text: list, button_fn: list, modal: bool = False,
callback_addons: List = [], callback_destroy: List = [], decode_text: bool = True
):
self._title = title
self._text = urllib.parse.unquote(text) if decode_text else text
self._button_list = []
self._modal = modal
self._callback_addons = callback_addons
self._callback_destroy = callback_destroy
self._buttons = []
for name, fn in zip(button_text, button_fn):
self._button_list.append((name, fn))
self._build_ui()
def destroy(self):
self._cancel_button_fn = None
self._ok_button_fn = None
self._button_list = []
if self._window:
self._window.destroy()
del self._window
self._window = None
for button in self._buttons:
button.set_clicked_fn(None)
self._buttons.clear()
self._callback_addons = []
for callback in self._callback_destroy:
if callback and callable(callback):
callback()
self._callback_destroy = []
def __del__(self):
self.destroy()
def __enter__(self):
self.show()
if self._modal:
settings = carb.settings.get_settings()
# Only use first word as a reason (e.g. "Creating, Openning"). URL won't work as a setting key.
operation = self._text.split(" ")[0].lower()
self._hang_detector_disable_key = "/app/hangDetector/disableReasons/{0}".format(operation)
settings.set(self._hang_detector_disable_key, "1")
settings.set("/crashreporter/data/appState", operation)
return self
def __exit__(self, type, value, trace):
self.hide()
if self._modal:
settings = carb.settings.get_settings()
settings.destroy_item(self._hang_detector_disable_key)
settings.set("/crashreporter/data/appState", "started")
def show(self):
self._window.visible = True
def hide(self):
self._window.visible = False
def is_visible(self):
return self._window.visible
def set_text(self, text):
self._text_label.text = text
def _build_ui(self):
self._window = ui.Window(
self._title, visible=False, height=0, dockPreference=ui.DockPreference.DISABLED, raster_policy=ui.RasterPolicy.NEVER
)
self._window.flags = (
ui.WINDOW_FLAGS_NO_COLLAPSE
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_SCROLLBAR
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_MOVE
| ui.WINDOW_FLAGS_NO_CLOSE
)
if self._modal:
self._window.flags |= ui.WINDOW_FLAGS_MODAL
with self._window.frame:
with ui.VStack(height=0):
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer(widht=10, height=0)
self._text_label = ui.Label(
self._text,
width=ui.Percent(100),
height=0,
word_wrap=True,
alignment=ui.Alignment.CENTER,
)
ui.Spacer(widht=10, height=0)
ui.Spacer(width=0, height=10)
with ui.HStack(height=0):
ui.Spacer(height=0)
for name, fn in self._button_list:
if name:
button = ui.Button(name)
if fn:
button.set_clicked_fn(lambda on_fn=fn: (self.hide(), on_fn()))
else:
button.set_clicked_fn(lambda: self.hide())
self._buttons.append(button)
ui.Spacer(height=0)
ui.Spacer(width=0, height=10)
for callback in self._callback_addons:
if callback and callable(callback):
callback()
| 4,295 |
Python
| 32.302325 | 128 | 0.518743 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/share_window.py
|
import carb
import omni.ui as ui
class ShareWindow(ui.Window):
def __init__(self, copy_button_text="Copy Path to Clipboard", copy_button_fn=None, modal=True, url=None):
self._title = "Share Omniverse USD Path"
self._copy_button_text = copy_button_text
self._copy_button_fn = copy_button_fn
self._status_text = "Copy and paste this path to another user to share the location of this USD file."
self._stage_url = url
self._stage_string_box = None
super().__init__(self._title, visible=url is not None, width=600, height=140, dockPreference=ui.DockPreference.DISABLED)
self.flags = (
ui.WINDOW_FLAGS_NO_COLLAPSE
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_SCROLLBAR
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_MOVE
)
if modal:
self.flags = self.flags | ui.WINDOW_FLAGS_MODAL
self.frame.set_build_fn(self._build_ui)
def _build_ui(self):
with self.frame:
with ui.VStack():
ui.Spacer(height=10)
with ui.HStack(height=0):
ui.Spacer()
self._status_label = ui.Label(self._status_text, width=0)
ui.Spacer()
ui.Spacer(height=10)
with ui.HStack(height=0):
ui.Spacer()
self._stage_string_box = ui.StringField(width=550)
self._stage_string_box.model.set_value(self._stage_url)
ui.Spacer()
ui.Spacer(height=5)
with ui.HStack(height=0):
ui.Spacer()
copy_button = ui.Button(self._copy_button_text, width=165)
copy_button.set_clicked_fn(self._on_copy_button_fn)
ui.Spacer()
ui.Spacer(height=10)
def _on_copy_button_fn(self):
self.visible = False
if self._stage_string_box:
try:
import omni.kit.clipboard # type: ignore
try:
omni.kit.clipboard.copy(self._stage_string_box.model.as_string)
except:
carb.log_warn("clipboard copy failed")
except ImportError:
carb.log_warn("Could not import omni.kit.clipboard. Cannot copy scene URL to the clipboard.")
@property
def url(self):
return self._stage_url
@url.setter
def url(self, value: str) -> None:
self._stage_url = value
if self._stage_string_box:
self._stage_string_box.model.set_value(value)
self.visible = True
| 2,688 |
Python
| 37.971014 | 128 | 0.541295 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/save_stage_ui.py
|
import asyncio
import weakref
import urllib
import carb.settings
import omni.client
import omni.ui
from omni.kit.widget.versioning import CheckpointHelper
class CheckBoxStatus:
def __init__(self, checkbox, layer_identifier, layer_is_writable):
self.checkbox = checkbox
self.layer_identifier = layer_identifier
self.layer_is_writable = layer_is_writable
self.is_checking = False
class StageSaveDialog:
WINDOW_WIDTH = 580
MAX_VISIBLE_LAYER_COUNT = 10
def __init__(self, on_save_fn=None, on_dont_save_fn=None, on_cancel_fn=None, enable_dont_save=False):
self._usd_context = omni.usd.get_context()
self._save_fn = on_save_fn
self._dont_save_fn = on_dont_save_fn
self._cancel_fn = on_cancel_fn
self._checkboxes_status = []
self._select_all_checkbox_is_checking = False
self._selected_layers = []
self._checkpoint_marks = {}
flags = (
omni.ui.WINDOW_FLAGS_NO_COLLAPSE
| omni.ui.WINDOW_FLAGS_NO_SCROLLBAR
| omni.ui.WINDOW_FLAGS_MODAL
)
self._window = omni.ui.Window(
"Select Files to Save##file.py",
visible=False,
width=0,
height=0,
flags=flags,
auto_resize=True,
padding_x=10,
dockPreference=omni.ui.DockPreference.DISABLED,
)
with self._window.frame:
with omni.ui.VStack(height=0, width=StageSaveDialog.WINDOW_WIDTH):
self._layers_scroll_frame = omni.ui.ScrollingFrame(height=160)
omni.ui.Spacer(width=0, height=10)
self._checkpoint_comment_frame = omni.ui.Frame()
with self._checkpoint_comment_frame:
with omni.ui.VStack(height=0, spacing=5):
omni.ui.Label("*) File(s) that will be Checkpointed with a comment.")
with omni.ui.ZStack():
self._description_field = omni.ui.StringField(multiline=True, height=60)
self._description_field_hint_label = omni.ui.Label(
" Description", alignment=omni.ui.Alignment.LEFT_TOP, style={"color": 0xFF3F3F3F}
)
self._description_begin_edit_sub = self._description_field.model.subscribe_begin_edit_fn(
self._on_description_begin_edit
)
self._description_end_edit_sub = self._description_field.model.subscribe_end_edit_fn(
self._on_description_end_edit
)
self._checkpoint_comment_spacer = omni.ui.Spacer(width=0, height=10)
with omni.ui.HStack(height=0):
omni.ui.Spacer(height=0)
self._save_selected_button = omni.ui.Button("Save Selected", width=0, height=0)
self._save_selected_button.set_clicked_fn(self._on_save_fn)
omni.ui.Spacer(width=5, height=0)
if enable_dont_save:
self._dont_save_button = omni.ui.Button("Don't Save", width=0, height=0)
self._dont_save_button.set_clicked_fn(self._on_dont_save_fn)
omni.ui.Spacer(width=5, height=0)
self._cancel_button = omni.ui.Button("Cancel", width=0, height=0)
self._cancel_button.set_clicked_fn(self._on_cancel_fn)
omni.ui.Spacer(height=0)
omni.ui.Spacer(height=5)
def destroy(self):
self._usd_context = None
self._save_fn = None
self._dont_save_fn = None
self._cancel_fn = None
self._checkboxes_status = None
self._selected_layers = None
self._checkpoint_marks = None
if self._window:
del self._window
self._window = None
def __del__(self):
self.destroy()
def _on_save_fn(self):
if self._save_fn:
self._save_fn(
self._selected_layers,
comment=self._description_field.model.get_value_as_string()
if self._checkpoint_comment_frame.visible
else "",
)
self._window.visible = False
self._selected_layers = []
def _on_dont_save_fn(self):
if self._dont_save_fn:
self._dont_save_fn(self._description_field.model.get_value_as_string())
self._window.visible = False
self._selected_layers = []
def _on_cancel_fn(self):
if self._cancel_fn:
self._cancel_fn(self._description_field.model.get_value_as_string())
self._window.visible = False
self._selected_layers = []
def _on_select_all_fn(self, model):
if self._select_all_checkbox_is_checking:
return
self._select_all_checkbox_is_checking = True
if model.get_value_as_bool():
for checkbox_status in self._checkboxes_status:
checkbox_status.checkbox.model.set_value(True)
else:
for checkbox_status in self._checkboxes_status:
checkbox_status.checkbox.model.set_value(False)
self._select_all_checkbox_is_checking = False
def _check_and_select_all(self, select_all_check_box):
select_all = True
for checkbox_status in self._checkboxes_status:
if checkbox_status.layer_is_writable and not checkbox_status.checkbox.model.get_value_as_bool():
select_all = False
break
if select_all:
self._select_all_checkbox_is_checking = True
select_all_check_box.model.set_value(True)
self._select_all_checkbox_is_checking = False
def _on_checkbox_fn(self, model, check_box_index, select_all_check_box):
check_box_status = self._checkboxes_status[check_box_index]
if check_box_status.is_checking:
return
check_box_status.is_checking = True
if not check_box_status.layer_is_writable:
model.set_value(False)
elif model.get_value_as_bool():
self._selected_layers.append(check_box_status.layer_identifier)
self._check_and_select_all(select_all_check_box)
else:
self._selected_layers.remove(check_box_status.layer_identifier)
self._select_all_checkbox_is_checking = True
select_all_check_box.model.set_value(False)
self._select_all_checkbox_is_checking = False
check_box_status.is_checking = False
def show(self, layer_identifiers=None):
self._layers_scroll_frame.clear()
self._checkpoint_marks.clear()
self._checkpoint_comment_frame.visible = False
self._checkpoint_comment_spacer.visible = False
settings = carb.settings.get_settings()
enable_versioning = settings.get_as_bool("exts/omni.kit.window.file/enable_versioning") or False
# make a copy
self._selected_layers.extend(layer_identifiers)
self._checkboxes_status = []
#build layers_scroll_frame
self._first_item_stack = None
with self._layers_scroll_frame:
with omni.ui.VStack(height=0):
omni.ui.Spacer(width=0, height=10)
with omni.ui.HStack(height=0):
omni.ui.Spacer(width=20, height=0)
self._select_all_checkbox = omni.ui.CheckBox(width=20, style={"font_size": 16})
self._select_all_checkbox.model.set_value(True)
omni.ui.Label("File Name", alignment=omni.ui.Alignment.LEFT)
omni.ui.Spacer(width=20, height=0)
omni.ui.Spacer(width=0, height=10)
with omni.ui.HStack(height=0):
omni.ui.Spacer(width=20, height=0)
omni.ui.Separator(height=0, style={"color": 0xFF808080})
omni.ui.Spacer(width=20, height=0)
omni.ui.Spacer(width=0, height=5)
for i in range(len(layer_identifiers)):
layer_identifier = layer_identifiers[i]
# TODO Move version related code
if enable_versioning:
# Check if the server support checkpoint
self._check_checkpoint_enabled(layer_identifier)
style = {}
layer_is_writable = omni.usd.is_layer_writable(layer_identifier)
layer_is_locked = omni.usd.is_layer_locked(self._usd_context, layer_identifier)
if not layer_is_writable or layer_is_locked:
self._selected_layers.remove(layer_identifier)
style = {"background_color": 0xFF808080, "color": 0xFF808080}
label_text = urllib.parse.unquote(layer_identifier).replace("\\", "/")
if not layer_is_writable or layer_is_locked:
label_text += " (Read-Only)"
omni.ui.Spacer(width=0, height=5)
stack = omni.ui.HStack(height=0, style=style)
if self._first_item_stack is None:
self._first_item_stack = stack
with stack:
omni.ui.Spacer(width=20, height=0)
checkbox = omni.ui.CheckBox(width=20, style={"font_size": 16})
checkbox.model.set_value(True)
omni.ui.Label(label_text, word_wrap=False, elided_text=True, alignment=omni.ui.Alignment.LEFT)
check_point_label = omni.ui.Label("*", width=3, alignment=omni.ui.Alignment.LEFT, visible=False)
omni.ui.Spacer(width=20, height=0)
self._checkpoint_marks[layer_identifier] = check_point_label
checkbox.model.add_value_changed_fn(
lambda a, b=i, c=self._select_all_checkbox: self._on_checkbox_fn(a, b, c)
)
self._checkboxes_status.append(CheckBoxStatus(checkbox, layer_identifier, layer_is_writable))
self._select_all_checkbox.model.add_value_changed_fn(lambda a: self._on_select_all_fn(a))
self._window.visible = True
async def __delay_adjust_window_size(weak_self):
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
__self = weak_self()
if not __self:
return
y0 = __self._layers_scroll_frame.screen_position_y
y1 = __self._first_item_stack.screen_position_y
fixed_height = y1 - y0 + 5
item_height = __self._first_item_stack.computed_content_height + 5
count = min(StageSaveDialog.MAX_VISIBLE_LAYER_COUNT, len(__self._checkpoint_marks))
scroll_frame_new_height = fixed_height + count * item_height
__self._layers_scroll_frame.height = omni.ui.Pixel(scroll_frame_new_height)
if len(layer_identifiers) > 0:
asyncio.ensure_future(__delay_adjust_window_size(weakref.ref(self)))
def is_visible(self):
return self._window.visible
def _on_description_begin_edit(self, model):
self._description_field_hint_label.visible = False
def _on_description_end_edit(self, model):
if len(model.get_value_as_string()) == 0:
self._description_field_hint_label.visible = True
def _check_checkpoint_enabled(self, url):
async def check_server_support(weak_self, url):
_self = weak_self()
if not _self:
return
if await CheckpointHelper.is_checkpoint_enabled_async(url):
_self._checkpoint_comment_frame.visible = True
_self._checkpoint_comment_spacer.visible = True
label = _self._checkpoint_marks.get(url, None)
if label:
label.visible = True
asyncio.ensure_future(check_server_support(weakref.ref(self), url))
| 12,233 |
Python
| 43.813187 | 120 | 0.563803 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/style.py
|
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import carb
import omni.ui as ui
try:
THEME = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle")
except Exception:
THEME = None
finally:
THEME = THEME or "NvidiaDark"
def get_style():
if THEME == "NvidiaLight": # pragma: no cover
BACKGROUND_COLOR = 0xFF535354
BACKGROUND_SELECTED_COLOR = 0xFF6E6E6E
BACKGROUND_HOVERED_COLOR = 0xFF6E6E6E
FIELD_BACKGROUND_COLOR = 0xFF1F2124
SECONDARY_COLOR = 0xFFE0E0E0
BORDER_COLOR = 0xFF707070
TITLE_COLOR = 0xFF707070
TEXT_COLOR = 0xFF8D760D
TEXT_HINT_COLOR = 0xFFD6D6D6
else:
BACKGROUND_COLOR = 0xFF23211F
BACKGROUND_SELECTED_COLOR = 0xFF8A8777
BACKGROUND_HOVERED_COLOR = 0xFF3A3A3A
SECONDARY_COLOR = 0xFF9E9E9E
BORDER_COLOR = 0xFF8A8777
TITLE_COLOR = 0xFFCECECE
TEXT_COLOR = 0xFF9E9E9E
TEXT_HINT_COLOR = 0xFF7A7A7A
style = {
"Button": {
"background_color": BACKGROUND_COLOR,
"selected_color": BACKGROUND_SELECTED_COLOR,
"color": TEXT_COLOR,
"margin": 0,
"padding": 0
},
"Button:hovered": {"background_color": BACKGROUND_HOVERED_COLOR},
"Button.Label": {"color": TEXT_COLOR},
"Field": {"background_color": BACKGROUND_COLOR, "selected_color": BACKGROUND_SELECTED_COLOR, "color": TEXT_COLOR, "alignment": ui.Alignment.LEFT_CENTER},
"Field.Hint": {"background_color": 0x0, "color": TEXT_HINT_COLOR, "margin_width": 4},
"Label": {"background_color": 0x0, "color": TEXT_COLOR},
"CheckBox": {"alignment": ui.Alignment.CENTER},
}
return style
| 2,126 |
Python
| 36.982142 | 161 | 0.659454 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/__init__.py
|
from .file_window import *
| 27 |
Python
| 12.999994 | 26 | 0.740741 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/file_actions.py
|
import omni.kit.actions.core
from .app_ui import AppUI, DialogOptions
def register_actions(extension_id):
import omni.kit.window.file
action_registry = omni.kit.actions.core.get_action_registry()
actions_tag = "File Actions"
action_registry.register_action(
extension_id,
"new",
omni.kit.window.file.new,
display_name="File->New",
description="Create a new USD stage.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"open",
omni.kit.window.file.open,
display_name="File->Open",
description="Open an existing USD stage.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"open_stage",
omni.kit.window.file.open_stage,
display_name="File->Open Stage",
description="Open an named USD stage.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"reopen",
omni.kit.window.file.reopen,
display_name="File->Reopen",
description="Reopen the currently opened USD stage.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"open_with_new_edit_layer",
omni.kit.window.file.open_with_new_edit_layer,
display_name="File->Open With New Edit Layer",
description="Open an existing USD stage with a new edit layer.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"share",
omni.kit.window.file.share,
display_name="File->Share",
description="Share the currently open USD stage.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"save",
lambda: omni.kit.window.file.save(dialog_options=DialogOptions.HIDE),
display_name="File->Save",
description="Save the currently opened USD stage to file.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"save_with_options",
lambda: omni.kit.window.file.save(dialog_options=DialogOptions.NONE),
display_name="File->Save With Options",
description="Save the currently opened USD stage to file.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"save_as",
lambda: omni.kit.window.file.save_as(False),
display_name="File->Save As",
description="Save the currently opened USD stage to a new file.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"save_as_flattened",
lambda: omni.kit.window.file.save_as(True),
display_name="File->Save As Flattened",
description="Save the currently opened USD stage to a new flattened file.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"add_reference",
lambda: omni.kit.window.file.add_reference(is_payload=False),
display_name="File->Add Reference",
description="Add a reference to a file.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"add_payload",
lambda: omni.kit.window.file.add_reference(is_payload=True),
display_name="File->Add Payload",
description="Add a payload to a file.",
tag=actions_tag,
)
def deregister_actions(extension_id):
action_registry = omni.kit.actions.core.get_action_registry()
action_registry.deregister_all_actions_for_extension(extension_id)
| 3,626 |
Python
| 31.383928 | 83 | 0.621897 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/file_window.py
|
"""USD File interaction for Omniverse Kit.
:mod:`omni.kit.window.file` provides util functions to new/open/save/close USD files. It handles file picking dialog and prompt for unsaved stage.
"""
import os
import time
import traceback
import asyncio
from typing import Awaitable, Callable, List
import carb
import omni.ext
import omni.usd
import omni.kit.app
import omni.kit.helper.file_utils as file_utils
from pathlib import Path
from functools import partial
from omni.kit.helper.file_utils import asset_types
import omni.kit.usd.layers as layers
from omni.kit.window.file_importer import get_file_importer
from omni.kit.window.file_exporter import get_file_exporter
from omni.kit.widget.nucleus_connector import get_nucleus_connector
from .prompt_ui import Prompt
from .read_only_options_window import ReadOnlyOptionsWindow
from .share_window import ShareWindow
from .app_ui import AppUI, DialogOptions, SaveOptionsDelegate, OpenOptionsDelegate
from .file_actions import register_actions, deregister_actions
from pxr import Tf, Sdf, Usd, UsdGeom, UsdUtils
_extension_instance = None
TEST_DATA_PATH = ""
IGNORE_UNSAVED_ON_EXIT_PATH = "/app/file/ignoreUnsavedOnExit"
IGNORE_UNSAVED_STAGE = "/app/file/ignoreUnsavedStage"
LAST_OPENED_DIRECTORY = "/persistent/app/omniverse/lastOpenDirectory"
SHOW_UNSAVED_LAYERS_DIALOG = "/persistent/app/file/save/showUnsavedLayersDialog"
class _CheckpointCommentContext:
def __init__(self, comment: str):
self._comment = comment
def __enter__(self):
try:
import omni.usd_resolver
omni.usd_resolver.set_checkpoint_message(self._comment)
except Exception as e:
carb.log_error(f"Failed to import omni.usd_resolver: {str(e)}.")
return self
def __exit__(self, type, value, trace):
try:
import omni.usd_resolver
omni.usd_resolver.set_checkpoint_message("")
except Exception:
pass
class _CallbackRegistrySubscription:
"""
Simple subscription.
_Event has callback while this object exists.
"""
def __init__(self, callback_list: List, callback: Callable):
"""
Save the callback in the given list.
"""
self.__callback_list: List = callback_list
self.__callback = callback
callback_list.append(callback)
def __del__(self):
"""Called by GC."""
self.__callback_list.remove(self.__callback)
class FileWindowExtension(omni.ext.IExt):
def on_startup(self, ext_id):
global _extension_instance
_extension_instance = self
self._open_stage_callbacks: List = []
self._open_stage_complete_callbacks: List = []
self.ui_handler = None
self._task = None
self._unsaved_stage_prompt = None
self._file_existed_prompt = None
self._open_readonly_usd_prompt = None
self._app = omni.kit.app.get_app()
self._settings = carb.settings.get_settings()
self._settings.set_default_bool(IGNORE_UNSAVED_ON_EXIT_PATH, False)
self.ui_handler = AppUI()
self._save_options = None
self._open_options = None
self._share_window = None
manager = omni.kit.app.get_app().get_extension_manager()
extension_path = manager.get_extension_path(ext_id)
global TEST_DATA_PATH
TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests")
def on_event(e: carb.events.IEvent):
if e.type == omni.kit.app.POST_QUIT_EVENT_TYPE:
ignore_unsaved_file_on_exit = self._settings.get(IGNORE_UNSAVED_ON_EXIT_PATH)
usd_context = omni.usd.get_context()
if not ignore_unsaved_file_on_exit and usd_context.can_close_stage() and usd_context.has_pending_edit():
self._app.try_cancel_shutdown("Interrupting shutdown - closing stage first")
# OM-52366: fast shutdown will not close stage but post quit directly.
fast_shutdown = carb.settings.get_settings().get("/app/fastShutdown")
self.close(lambda *args: omni.kit.app.get_app().post_quit(), fast_shutdown=fast_shutdown)
self._shutdown_subs = self._app.get_shutdown_event_stream().create_subscription_to_pop(
on_event, name="window.file shutdown hook", order=0
)
self._ext_name = omni.ext.get_extension_name(ext_id)
register_actions(self._ext_name)
def on_shutdown(self):
deregister_actions(self._ext_name)
self._shutdown_subs = None
self._save_options = None
self._open_options = None
if self._task:
self._task.cancel()
self._task = None
if self._unsaved_stage_prompt:
self._unsaved_stage_prompt.destroy()
self._unsaved_stage_prompt = None
if self._file_existed_prompt:
self._file_existed_prompt.destroy()
self._file_existed_prompt = None
if self._open_readonly_usd_prompt:
self._open_readonly_usd_prompt.destroy()
self._open_readonly_usd_prompt = None
global _extension_instance
_extension_instance = None
if self.ui_handler:
self.ui_handler.destroy()
self.ui_handler = None
def stop_timeline(self):
try:
import omni.timeline
timeline = omni.timeline.get_timeline_interface()
if timeline:
timeline.stop()
else:
carb.log_warn(f"Failed to stop timeline, get_timeline_interface() return None")
except ModuleNotFoundError:
carb.log_warn(f"Failed to stop timeline, omni.timeline not loaded")
def new(self, template=None):
"""Create a new USD stage. If currently opened stage is dirty, a prompt will show to let you save it."""
self.stop_timeline()
async def new_stage_job():
# FIXME: Delay two frames to center prompt.
await self._app.next_update_async()
await self._app.next_update_async()
with Prompt("Please Wait", "Creating new stage...", [], [], True):
await self._app.next_update_async() # Making sure prompt shows
await omni.kit.stage_templates.new_stage_async(template=template)
await self._app.next_update_async() # Wait anther frame for StageEvent.OPENED to be handled
self.prompt_if_unsaved_stage(lambda *_: self._exclusive_task_wrapper(new_stage_job))
def open(self, open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL):
"""Bring up a file picker to choose a USD file to open. If currently opened stage is dirty, a prompt will show to let you save it."""
self.stop_timeline()
def open_handler(loadset: int, filename: str, dirname: str, selections: List[str]):
if ':/' in filename or filename.startswith('\\\\'):
# Filename is a pasted fullpath. The first test finds paths that start with 'C:/' or 'omniverse://';
# the second finds MS network paths that start like '\\analogfs\VENDORS\...'
path = filename
else:
path = f"{dirname or ''}/{filename}"
if not omni.usd.is_usd_readable_filetype(path):
FileWindowExtension.post_notification(f"Cannot open {path}. No valid stage")
return
result, entry = omni.client.stat(path)
if result != omni.client.Result.OK:
carb.log_warn(f"Failed to stat '{path}', attempting to open in read-only mode.")
read_only = True
else:
# https://nvidia-omniverse.atlassian.net/browse/OM-45124
read_only = entry.access & omni.client.AccessFlags.WRITE == 0
if read_only:
def _open_with_edit_layer():
self.open_with_new_edit_layer(path, open_loadset)
def _open_original_stage():
self.open_stage(path, open_loadset, open_options=self._open_options)
self._show_readonly_usd_prompt(_open_with_edit_layer, _open_original_stage)
else:
self.open_stage(path, open_loadset=loadset, open_options=self._open_options)
file_importer = get_file_importer()
if file_importer:
file_importer.show_window(
title="Open File",
import_button_label="Open File",
import_handler=partial(open_handler, open_loadset),
)
if self._open_options is None:
self._open_options = OpenOptionsDelegate()
file_importer.add_import_options_frame("Options", self._open_options)
def open_stage(self, path, open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL, open_options: OpenOptionsDelegate=None, callback: callable=None):
"""open stage. If the current stage is dirty, a prompt will show to let you save it."""
if not omni.usd.is_usd_readable_filetype(path):
FileWindowExtension.post_notification(f"Cannot open {path}. No valid stage")
if callback:
callback(False)
return
self.stop_timeline()
ui_handler = self.ui_handler
self._settings.set(LAST_OPENED_DIRECTORY, os.path.dirname(path))
checkbox = None
if open_options:
checkbox = open_options.should_load_payload()
if not checkbox: # open with payloads disabled
open_loadset = omni.usd.UsdContextInitialLoadSet.LOAD_NONE
async def open_stage_job():
# FIXME: Delay two frames to center prompt.
await self._app.next_update_async()
await self._app.next_update_async()
prompt = Prompt("Please Wait", f"Opening {path}...", [], [], True, self._open_stage_callbacks, self._open_stage_complete_callbacks)
prompt._window.width = 415
with prompt:
context = omni.usd.get_context()
start_time = time.time()
result, err = await context.open_stage_async(path, open_loadset)
success = True
if not result or context.get_stage_state() != omni.usd.StageState.OPENED:
success = False
carb.log_error(f"Failed to open stage {path}: {err}")
ui_handler.show_open_stage_failed_prompt(path)
else:
stage = context.get_stage()
identifier = stage.GetRootLayer().identifier
if not stage.GetRootLayer().anonymous:
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
message_bus.push(file_utils.FILE_OPENED_EVENT, payload=file_utils.FileEventModel(url=identifier).dict())
open_duration = time.time() - start_time
omni.kit.app.send_telemetry_event("omni.kit.window.file@open_stage", duration=open_duration, data1=path, value1=float(success))
if callback:
callback(False)
async def open_stage_async():
result, _ = await omni.client.stat_async(path)
if result == omni.client.Result.OK:
FileWindowExtension._exclusive_task_wrapper(open_stage_job)
return
# Attempt to connect to nucleus server
broken_url = omni.client.break_url(path)
if broken_url.scheme == 'omniverse':
server_url = omni.client.make_url(scheme='omniverse', host=broken_url.host)
nucleus_connector = get_nucleus_connector()
if nucleus_connector:
nucleus_connector.connect(broken_url.host, server_url,
on_success_fn=lambda *_: FileWindowExtension._exclusive_task_wrapper(open_stage_job),
on_failed_fn=lambda *_: carb.log_error(f"Invalid stage URL: {path}")
)
else:
carb.log_error(f"Invalid stage URL: {path}")
self.prompt_if_unsaved_stage(lambda *_: asyncio.ensure_future(open_stage_async()))
def _show_readonly_usd_prompt(self, ok_fn, middle_fn):
if self._open_readonly_usd_prompt:
self._open_readonly_usd_prompt.destroy()
self._open_readonly_usd_prompt = ReadOnlyOptionsWindow(ok_fn, middle_fn)
self._open_readonly_usd_prompt.show()
def _show_file_existed_prompt(self, path, on_confirm_fn, on_cancel_fn=None):
file_name = os.path.basename(path)
if self._file_existed_prompt:
self._file_existed_prompt.destroy()
self._file_existed_prompt = Prompt(
f'{omni.kit.ui.get_custom_glyph_code("${glyphs}/exclamation.svg")} Overwrite',
f"File {file_name} already exists, do you want to overwrite it?",
["OK", "Cancel"],
[on_confirm_fn, None],
False,
)
self._file_existed_prompt.show()
def open_with_new_edit_layer(self, path: str, open_loadset: int = omni.usd.UsdContextInitialLoadSet.LOAD_ALL, callback: Callable = None):
if not omni.usd.is_usd_readable_filetype(path):
FileWindowExtension.post_notification(f"Cannot open {path}. No valid stage")
return
self.stop_timeline()
def create_handler(stage_path: str, callback: Callable, filename: str, dirname: str,
extension: str = None, selections: List[str] = []):
# Allow incoming directory as /path/to/dir or /path/to/dir/
dirname = dirname.rstrip('/')
edit_layer_path = f"{dirname}/{filename}{extension}"
self.create_stage(edit_layer_path, stage_path, callback=callback)
def create_edit_layer(stage_path: str, callback: Callable):
file_exporter = get_file_exporter()
if file_exporter:
dirname = os.path.dirname(stage_path)
if Sdf.Layer.IsAnonymousLayerIdentifier(stage_path):
basename = Sdf.Layer.GetDisplayNameFromIdentifier(stage_path)
else:
basename = os.path.basename(stage_path)
edit_layer_path = f"{dirname}/{os.path.splitext(basename)[0]}_edit"
file_exporter.show_window(
title="Create Edit Layer",
export_button_label="Save",
export_handler=partial(create_handler, stage_path, callback),
filename_url=edit_layer_path,
)
self.prompt_if_unsaved_stage(lambda: create_edit_layer(path, callback))
def create_stage(self, edit_layer_path: str, file_path: str, callback: Callable = None):
self.stop_timeline()
async def create_stage_async(edit_layer_path: str, stage_path: str, callback: Callable):
edit_layer = Sdf.Layer.FindOrOpen(edit_layer_path)
if edit_layer:
edit_layer.Clear()
else:
edit_layer = Sdf.Layer.CreateNew(edit_layer_path)
if not edit_layer:
carb.log_error(f"open_with_new_edit_layer: failed to create edit layer {edit_layer_path}")
return
# FIXME: Delay two frames to center prompt.
await self._app.next_update_async()
await self._app.next_update_async()
with Prompt("Please Wait", "Creating new stage...", [], [], True):
await self._app.next_update_async() # Making sure prompt shows
root_layer = Sdf.Layer.CreateAnonymous()
root_layer.subLayerPaths.insert(0, file_path)
root_layer.subLayerPaths.insert(0, edit_layer_path)
# Copy all meta
base_layer = Sdf.Layer.FindOrOpen(file_path)
UsdUtils.CopyLayerMetadata(base_layer, root_layer, True)
omni.usd.resolve_paths(base_layer.identifier, root_layer.identifier, False, True)
# Set edit target
stage = Usd.Stage.Open(root_layer)
edit_target = Usd.EditTarget(edit_layer)
stage.SetEditTarget(edit_target)
await omni.usd.get_context().attach_stage_async(stage)
await self._app.next_update_async() # Wait anther frame for StageEvent.OPENED to be handled
if callback:
callback()
async def create_stage_prompt_if_exists(edit_layer_path: str, file_path: str, callback: Callable):
result, _ = await omni.client.stat_async(edit_layer_path)
# File is existed already.
if result == omni.client.Result.OK:
self._show_file_existed_prompt(
edit_layer_path,
lambda: FileWindowExtension._exclusive_task_wrapper(
create_stage_async, edit_layer_path, file_path, callback
)
)
else:
await create_stage_async(edit_layer_path, file_path, callback)
asyncio.ensure_future(create_stage_prompt_if_exists(edit_layer_path, file_path, callback))
def reopen(self):
"""Reopen currently opened stage. If the stage is dirty, a prompt will show to let you save it."""
self.stop_timeline()
async def reopen_stage_job():
context = omni.usd.get_context()
path = context.get_stage_url()
# FIXME: Delay two frames to center prompt.
await self._app.next_update_async()
await self._app.next_update_async()
with Prompt("Please Wait", f"Reopening {path}...", [], [], True):
await self._app.next_update_async() # Making sure prompt shows
result, err = await context.reopen_stage_async()
await self._app.next_update_async() # Wait anther frame for StageEvent.OPENED to be handled
if not result or context.get_stage_state() != omni.usd.StageState.OPENED:
carb.log_error(f"Failed to reopen stage {path}: {err}")
self.ui_handler.show_open_stage_failed_prompt(path)
if not (omni.usd.get_context().get_stage_state() == omni.usd.StageState.OPENED and not omni.usd.get_context().is_new_stage()):
FileWindowExtension.post_notification("Cannot Reopen. No valid stage")
return
self.prompt_if_unsaved_stage(lambda *_: FileWindowExtension._exclusive_task_wrapper(reopen_stage_job))
def share(self):
context = omni.usd.get_context()
if context.get_stage_url().startswith("omniverse://"):
layers_interface = layers.get_layers(context)
live_syncing = layers_interface.get_live_syncing()
current_session = live_syncing.get_current_live_session()
if not current_session:
url = context.get_stage_url()
else:
url = current_session.shared_link
self._share_window = ShareWindow(url=url)
def save(self, callback: Callable, allow_skip_sublayers: bool = False):
"""Save currently opened stage to file. Will call Save As for a newly created stage"""
# Syncs render settings to stage before save so stage could
# get the correct edit state if render settings are changed.
if omni.usd.get_context().get_stage_state() != omni.usd.StageState.OPENED:
FileWindowExtension.post_notification("Cannot Save. No valid stage")
return
self.stop_timeline()
async def save_async(callback: Callable, allow_skip_sublayers: bool):
is_new_stage = omni.usd.get_context().is_new_stage() or \
omni.usd.get_context().get_stage_state() != omni.usd.StageState.OPENED
is_writeable = False
try:
filename_url = omni.usd.get_context().get_stage().GetRootLayer().identifier
result, stat = await omni.client.stat_async(filename_url)
except Exception:
pass
else:
if result == omni.client.Result.OK:
is_writeable = stat.flags & omni.client.ItemFlags.WRITEABLE_FILE
# OM-47514 When saving a checkpoint or read-only file, use save_as instead
if is_new_stage or not is_writeable:
self.save_as(False, callback, allow_skip_sublayers=allow_skip_sublayers)
else:
stage = omni.usd.get_context().get_stage()
dirty_layer_identifiers = omni.usd.get_dirty_layers(stage, True)
self.ui_handler.save_root_and_sublayers("", dirty_layer_identifiers, on_save_done=callback, allow_skip_sublayers=allow_skip_sublayers)
asyncio.ensure_future(save_async(callback, allow_skip_sublayers))
def save_as(self, flatten: bool, callback: Callable, allow_skip_sublayers: bool = False):
"""Bring up a file picker to choose a file to save current stage to."""
self.stop_timeline()
def save_handler(callback: Callable, flatten: bool, filename: str, dirname: str, extension: str = '', selections: List[str] = []):
path = f"{dirname}/{filename}{extension}"
self.save_stage(path, callback=callback, flatten=flatten, save_options=self._save_options, allow_skip_sublayers=allow_skip_sublayers)
if omni.usd.get_context().get_stage_state() != omni.usd.StageState.OPENED:
FileWindowExtension.post_notification("Cannot Save As. No valid stage")
return
file_exporter = get_file_exporter()
if file_exporter:
# OM-48033: Save as should open to latest opened stage path. Solution also covers ...
# OM-58150: Save as should pass in the current file name as default value.
filename_url = file_utils.get_last_url_visited(asset_type=asset_types.ASSET_TYPE_USD)
if filename_url:
# OM-91056: File Save As should not prefill the file name
filename_url = os.path.dirname(filename_url) + "/"
file_exporter.show_window(
title="Save File As...",
export_button_label="Save",
export_handler=partial(save_handler, callback, flatten),
filename_url=filename_url,
# OM-64312: Set save-as dialog to validate file names in file exporter
should_validate=True,
)
if self._save_options is None:
self._save_options = SaveOptionsDelegate()
file_exporter.add_export_options_frame("Save Options", self._save_options)
# OM-55838: Don't show "include sesson layer" for non-flatten save-as.
self._save_options.show_include_session_layer_option = flatten
def save_stage(self, path: str, callback: Callable = None, flatten: bool=False, save_options: SaveOptionsDelegate=None, allow_skip_sublayers: bool=False):
self.stop_timeline()
stage = omni.usd.get_context().get_stage()
save_comment = ""
if save_options:
save_comment = save_options.get_comment()
include_session_layer = False
if save_options and flatten:
include_session_layer = save_options.include_session_layer()
if flatten:
path = path or stage.GetRootLayer().identifier
# TODO: Currently, it's implemented differently for export w/o session layer as
# flatten is a simple operation and we don't want to break the ABI of omni.usd.
if include_session_layer:
omni.usd.get_context().export_as_stage_with_callback(path, callback)
else:
async def flatten_stage_without_session_layer(path, callback):
await self._app.next_update_async()
await self._app.next_update_async()
with Prompt("Please Wait", "Exporting flattened stage...", [], [], True):
await self._app.next_update_async()
usd_context = omni.usd.get_context()
if usd_context.can_save_stage():
stage = usd_context.get_stage()
# Creates empty anon layer.
anon_layer = Sdf.Layer.CreateAnonymous()
temp_stage = Usd.Stage.Open(stage.GetRootLayer(), anon_layer)
success = temp_stage.Export(path)
if callback:
if success:
callback(True, "")
else:
callback(False, f"Error exporting flattened stage to path: {path}.")
else:
error = "Stage busy or another saving task is in progress!!"
CARB_LOG_ERROR(error)
if callback:
callback(False, error)
asyncio.ensure_future(flatten_stage_without_session_layer(path, callback))
else:
async def save_stage_async(path: str, callback: Callable):
if path == stage.GetRootLayer().identifier:
dirty_layer_identifiers = omni.usd.get_dirty_layers(stage, True)
self.ui_handler.save_root_and_sublayers(
"", dirty_layer_identifiers, on_save_done=callback, save_comment=save_comment, allow_skip_sublayers=allow_skip_sublayers)
else:
path = path or stage.GetRootLayer().identifier
dirty_layer_identifiers = omni.usd.get_dirty_layers(stage, False)
save_fn = lambda: self.ui_handler.save_root_and_sublayers(
path, dirty_layer_identifiers, on_save_done=callback, save_comment=save_comment, allow_skip_sublayers=allow_skip_sublayers)
cancel_fn = lambda: self.ui_handler.save_root_and_sublayers(
"", dirty_layer_identifiers, on_save_done=callback, save_comment=save_comment, allow_skip_sublayers=allow_skip_sublayers)
result, _ = await omni.client.stat_async(path)
if result == omni.client.Result.OK:
# Path already exists, prompt to overwrite
self._show_file_existed_prompt(path, save_fn, on_cancel_fn=cancel_fn)
else:
save_fn()
asyncio.ensure_future(save_stage_async(path, callback))
def close(self, on_closed, fast_shutdown=False):
"""Check if current stage is dirty. If it's dirty, it will ask if to save the file, then close stage."""
self.stop_timeline()
async def close_stage_job():
if not fast_shutdown:
# FIXME: Delay two frames to center prompt.
await self._app.next_update_async()
await self._app.next_update_async()
with Prompt("Please Wait", "Closing stage...", [], [], True):
await self._app.next_update_async() # Making sure prompt shows
await omni.usd.get_context().close_stage_async()
await self._app.next_update_async() # Wait anther frame for StageEvent.CLOSED to be handled
else:
# Clear dirty state to allow quit fastly.
omni.usd.get_context().set_pending_edit(False)
if on_closed:
on_closed()
self.prompt_if_unsaved_stage(lambda *_: self._exclusive_task_wrapper(close_stage_job))
def save_layers(self, new_root_path, dirty_layers, on_save_done, create_checkpoint=True, checkpoint_comment=""):
"""Save current layers"""
# Skips if it has no real layers to be saved.
self.stop_timeline()
# It's possible that all layers are not dirty but it has pending edits to be saved,
# like render settings, which needs to be saved into root layer during save.
usd_context = omni.usd.get_context()
has_pending_edit = usd_context.has_pending_edit()
if not new_root_path and not dirty_layers and not has_pending_edit:
if on_save_done:
on_save_done(True, "")
return
try:
async def save_layers_job(*_):
# FIXME: Delay two frames to center prompt.
await self._app.next_update_async()
await self._app.next_update_async()
with Prompt("Please Wait", "Saving layers...", [], [], True):
await self._app.next_update_async() # Making sure prompt shows
await self._app.next_update_async() # Need 2 frames since save happens on mainthread
with _CheckpointCommentContext(checkpoint_comment):
result, err, saved_layers = await usd_context.save_layers_async(new_root_path, dirty_layers)
await self._app.next_update_async() # Wait anther frame for StageEvent.SAVED to be handled
# Clear unique task since it's possible that
# post-call to on_save_done needs to create unique
# instance also.
if _extension_instance and _extension_instance._task:
_extension_instance._task = None
if on_save_done:
on_save_done(result, err)
if result:
message_bus = omni.kit.app.get_app().get_message_bus_event_stream()
message_bus.push(file_utils.FILE_SAVED_EVENT, payload=file_utils.FileEventModel(url=new_root_path).dict())
else:
self.ui_handler.show_save_layers_failed_prompt()
FileWindowExtension._exclusive_task_wrapper(save_layers_job)
except Exception as exc:
carb.log_error(f"save error {exc}")
traceback.print_exc()
def prompt_if_unsaved_stage(self, callback: Callable):
"""Check if current stage is dirty. If it's dirty, ask to save the file, then execute callback. Otherwise runs callback directly."""
def should_show_stage_save_dialog():
# Use settings to control if it needs to show stage save dialog for layers save.
# For application that uses kit and does not want this, it can disable this.
settings = carb.settings.get_settings()
settings.set_default_bool(SHOW_UNSAVED_LAYERS_DIALOG, True)
show_stage_save_dialog = settings.get(SHOW_UNSAVED_LAYERS_DIALOG)
return show_stage_save_dialog
ignore_unsaved = self._settings.get(IGNORE_UNSAVED_STAGE)
if omni.usd.get_context().has_pending_edit() and not ignore_unsaved:
if omni.usd.get_context().is_new_stage() or should_show_stage_save_dialog():
if self._unsaved_stage_prompt:
self._unsaved_stage_prompt.destroy()
self._unsaved_stage_prompt = Prompt(
f'{omni.kit.ui.get_custom_glyph_code("${glyphs}/exclamation.svg")}',
"Would you like to save this stage?",
["Save", "Don't Save", "Cancel"],
[lambda *_: self.save(callback, allow_skip_sublayers=True), lambda *_: callback() if callback else None, None],
modal=True)
self._unsaved_stage_prompt.show()
else:
self.save(callback, allow_skip_sublayers=True)
else:
if callback:
callback()
def add_reference(self, is_payload=False):
self.stop_timeline()
def on_file_picked(is_payload: bool, filename: str, dirname: str, selections: List[str]):
if ':/' in filename or filename.startswith('\\\\'):
# Filename is a pasted fullpath. The first test finds paths that start with 'C:/' or 'omniverse://';
# the second finds MS network paths that start like '\\analogfs\VENDORS\...'
reference_path = filename
else:
reference_path = f"{dirname or ''}/{filename}"
name = os.path.splitext(os.path.basename(reference_path))[0]
stage = omni.usd.get_context().get_stage()
if stage.HasDefaultPrim():
prim_path = omni.usd.get_stage_next_free_path(
stage, stage.GetDefaultPrim().GetPath().pathString + "/" + Tf.MakeValidIdentifier(name), False
)
else:
prim_path = omni.usd.get_stage_next_free_path(stage, "/" + Tf.MakeValidIdentifier(name), False)
if is_payload:
omni.kit.commands.execute(
"CreatePayload", usd_context=omni.usd.get_context(), path_to=prim_path, asset_path=reference_path, instanceable=False
)
else:
omni.kit.commands.execute(
"CreateReference", usd_context=omni.usd.get_context(), path_to=prim_path, asset_path=reference_path, instanceable=False
)
file_importer = get_file_importer()
if file_importer:
file_importer.show_window(
title="Select File",
import_button_label="Add Reference" if not is_payload else "Add Payload",
import_handler=partial(on_file_picked, is_payload))
def register_open_stage_addon(self, callback):
return _CallbackRegistrySubscription(self._open_stage_callbacks, callback)
def register_open_stage_complete(self, callback):
return _CallbackRegistrySubscription(self._open_stage_complete_callbacks, callback)
@staticmethod
def _exclusive_task_wrapper(job: Awaitable, *args):
# Only allow one task to be run
if _extension_instance._task:
carb.log_info("_exclusive_task_wrapper already running. Cancelling")
_extension_instance._task.cancel()
_extension_instance._task = None
async def exclusive_task():
await job(*args)
_extension_instance._task = None
_extension_instance._task = asyncio.ensure_future(exclusive_task())
def post_notification(message: str, info: bool = False, duration: int = 3):
try:
import omni.kit.notification_manager as nm
if info:
type = nm.NotificationStatus.INFO
else:
type = nm.NotificationStatus.WARNING
nm.post_notification(message, status=type, duration=duration)
except ModuleNotFoundError:
carb.log_warn(message)
def get_instance():
return _extension_instance
def new(template=None):
file_window = get_instance()
if file_window:
file_window.new(template)
def open(open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL):
file_window = get_instance()
if file_window:
file_window.open(open_loadset)
def open_stage(path, open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL, callback: callable=None):
file_window = get_instance()
if file_window:
file_window.open_stage(path, open_loadset=open_loadset, callback=callback)
def open_with_new_edit_layer(path, open_loadset=omni.usd.UsdContextInitialLoadSet.LOAD_ALL, callback=None):
file_window = get_instance()
if file_window:
file_window.open_with_new_edit_layer(path, open_loadset, callback)
def reopen():
file_window = get_instance()
if file_window:
file_window.reopen()
def share():
file_window = get_instance()
if file_window:
file_window.share()
def save(on_save_done=None, exit=False, dialog_options=DialogOptions.NONE):
file_window = get_instance()
if file_window:
file_window.save(on_save_done)
def save_as(flatten, on_save_done=None):
file_window = get_instance()
if file_window:
file_window.save_as(flatten, on_save_done)
def close(on_closed=None):
file_window = get_instance()
if file_window:
file_window.close(on_closed)
def save_layers(new_root_path, dirty_layers, on_save_done, create_checkpoint=True, checkpoint_comment=""):
file_window = get_instance()
if file_window:
file_window.save_layers(new_root_path, dirty_layers, on_save_done, create_checkpoint, checkpoint_comment)
def prompt_if_unsaved_stage(job):
file_window = get_instance()
if file_window:
file_window.prompt_if_unsaved_stage(job)
def add_reference(is_payload=False):
file_window = get_instance()
if file_window:
file_window.add_reference(is_payload=is_payload)
def register_open_stage_addon(callback):
file_window = get_instance()
if file_window:
return file_window.register_open_stage_addon(callback)
def register_open_stage_complete(callback):
file_window = get_instance()
if file_window:
return file_window.register_open_stage_complete(callback)
| 37,160 |
Python
| 45.048327 | 158 | 0.598681 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/app_ui.py
|
"""USD File interaction for Omniverse Kit.
:mod:`omni.kit.window.file` provides util functions to new/open/save/close USD files. It handles file picking dialog and prompt
for unsaved stage.
"""
import os
import carb.settings
import omni.ui as ui
import omni.kit.ui
from enum import Enum
from typing import List, Callable
from omni.kit.window.file_exporter import get_file_exporter, ExportOptionsDelegate
from omni.kit.window.file_importer import ImportOptionsDelegate
from omni.kit.widget.versioning import CheckpointHelper
from .prompt_ui import Prompt
from .save_stage_ui import StageSaveDialog
from .style import get_style
class DialogOptions(Enum):
NONE = 0, 'Show dialog using is-required logic'
FORCE = 1, 'Force dialog to show and ignore is-required logic'
HIDE = 2, 'Never show dialog'
class SaveOptionsDelegate(ExportOptionsDelegate):
def __init__(self):
super().__init__(
build_fn=self._build_ui_impl,
selection_changed_fn=lambda *_: self._build_ui_impl(),
filename_changed_fn=lambda *_: self._build_ui_impl(),
destroy_fn=self._destroy_impl
)
self._widget = None
self._comment_model = ui.SimpleStringModel()
self._include_session_layer_checkbox = None
self._hint_container = None
self._sub_begin_edit = None
self._sub_end_edit = None
self._show_include_session_layer_option = False
self._other_options_widget = None
settings = carb.settings.get_settings()
self._versioning_enabled = settings.get_as_bool("exts/omni.kit.window.file/enable_versioning") or False
def get_comment(self):
if self._comment_model:
return self._comment_model.get_value_as_string()
return ""
def include_session_layer(self):
"""
When doing save-as or save-flattened-as, this option
can tell if it needs to keep session layers's change or
flatten session layer's change also.
"""
if self._include_session_layer_checkbox:
return self._include_session_layer_checkbox.model.get_value_as_bool()
return True
@property
def show_include_session_layer_option(self):
return self._show_include_session_layer_option
@show_include_session_layer_option.setter
def show_include_session_layer_option(self, value):
self._show_include_session_layer_option = value
if self._other_options_widget:
self._other_options_widget.visible = value
def _build_ui_impl(self):
if not self._versioning_enabled:
return
folder_url = ""
file_exporter = get_file_exporter()
if file_exporter and file_exporter._dialog:
folder_url = file_exporter._dialog.get_current_directory()
self._widget = ui.Frame()
CheckpointHelper.is_checkpoint_enabled_with_callback(folder_url, self._build_options_box)
def _build_option_checkbox(self, text, default_value, tooltip, identifier):
with ui.VStack():
ui.Spacer()
with ui.HStack(height=0):
checkbox = ui.CheckBox(width=14, height=14, style={"font_size": 16}, identifier=identifier)
checkbox.model.set_value(default_value)
ui.Spacer(width=4)
label = ui.Label(text, alignment=ui.Alignment.LEFT)
label.set_tooltip(tooltip)
ui.Spacer()
return checkbox
def _build_options_box(self, server_url: str, checkpoint_enabled: bool):
with self._widget:
with ui.VStack(height=0, style=get_style()):
if checkpoint_enabled:
ui.Label("Checkpoint comments:", height=20, alignment=ui.Alignment.LEFT_CENTER)
ui.Separator(height=5)
ui.Spacer(height=2)
with ui.ZStack():
with ui.HStack():
ui.StringField(self._comment_model, multiline=True, height=64, style_type_name_override="Field")
self._hint_container = ui.VStack()
with self._hint_container:
with ui.HStack():
ui.Label("Add checkpoint comments here.", height=20, style_type_name_override="Field.Hint")
ui.Spacer()
self._hint_container.visible = False
self._sub_begin_edit = self._comment_model.subscribe_begin_edit_fn(self._on_begin_edit)
self._sub_end_edit = self._comment_model.subscribe_end_edit_fn(self._on_end_edit)
else:
ui.Label("This server does not support checkpoints.", height=20, alignment=ui.Alignment.CENTER, word_wrap=True)
# OM-55838: Add option to support excluding session layer from flattening.
self._other_options_widget = ui.VStack(height=0)
with self._other_options_widget:
ui.Spacer(height=5)
ui.Separator(height=5)
ui.Label("Other Options:", height=20, alignment=ui.Alignment.LEFT_CENTER)
ui.Spacer(height=5)
self._include_session_layer_checkbox = self._build_option_checkbox(
"Include Session Layer", False,
"When this option is checked, it means it will include content\n"
"of session layer into the flattened stage.",
"include_session_layer"
)
self._other_options_widget.visible = self.show_include_session_layer_option
def _on_begin_edit(self, model):
self._hint_container.visible = False
def _on_end_edit(self, model: ui.AbstractValueModel):
if self.get_comment():
self._hint_container.visible = False
else:
self._hint_container.visible = True
def _destroy_impl(self, _):
self._comment_model = None
self._hint_container = None
self._widget = None
self._sub_begin_edit = None
self._sub_end_edit = None
self._include_session_layer_checkbox = None
class OpenOptionsDelegate(ImportOptionsDelegate):
def __init__(self):
super().__init__(
build_fn=self._build_ui_impl,
destroy_fn=self._destroy_impl
)
self._widget = None
self._load_payload_checkbox = None
def should_load_payload(self):
if self._load_payload_checkbox:
return self._load_payload_checkbox.model.get_value_as_bool()
def _build_ui_impl(self):
self._widget = ui.Frame()
with self._widget:
with ui.VStack(height=0, style=get_style()):
ui.Separator(height=5)
ui.Spacer(height=2)
with ui.HStack():
ui.Spacer(width=2)
self._load_payload_checkbox = ui.CheckBox(width=20, style_type_name_override="CheckBox")
self._load_payload_checkbox.model.set_value(True)
ui.Spacer(width=4)
ui.Label("Open Payloads", width=0, height=20, style_type_name_override="Label")
ui.Spacer()
def _destroy_impl(self, _):
self._load_payload_checkbox = None
self._widget = None
class AppUI:
def __init__(self):
self._open_stage_failed_prompt = None
self._save_layers_failed_prompt = None
self._save_stage_prompt = None
def destroy(self):
if self._open_stage_failed_prompt:
self._open_stage_failed_prompt.destroy()
self._open_stage_failed_prompt = None
if self._save_layers_failed_prompt:
self._save_layers_failed_prompt.destroy()
self._save_layers_failed_prompt = None
if self._save_stage_prompt:
self._save_stage_prompt.destroy()
self._save_stage_prompt = None
def save_root_and_sublayers(
self, new_root_path: str,
dirty_sublayers: List[str],
on_save_done: Callable = None,
dialog_options: int = DialogOptions.NONE,
save_comment: str = "",
allow_skip_sublayers: bool = False):
stage = omni.usd.get_context().get_stage()
if not stage:
return
if dialog_options == DialogOptions.HIDE:
self._save_layers(new_root_path, dirty_sublayers, on_save_done=on_save_done)
return
if len(dirty_sublayers) > 0 or dialog_options == DialogOptions.FORCE:
if self._save_stage_prompt:
self._save_stage_prompt.destroy()
self._save_stage_prompt = StageSaveDialog(
enable_dont_save=allow_skip_sublayers,
on_save_fn=lambda layers, comment: self._save_layers(
new_root_path, layers, on_save_done=on_save_done, checkpoint_comment=comment),
on_dont_save_fn=lambda comment: self._dont_save_layers(
new_root_path, on_save_done=on_save_done, checkpoint_comment=comment),
on_cancel_fn=lambda comment: self._cancel_save(new_root_path, checkpoint_comment=comment),
)
self._save_stage_prompt.show(dirty_sublayers)
else:
self._save_layers(new_root_path, [], on_save_done=on_save_done, checkpoint_comment=save_comment)
def _save_layers(
self, new_root_path, dirty_layers, on_save_done=None, create_checkpoint=True, checkpoint_comment=""
):
settings = carb.settings.get_settings()
versioning_enabled = settings.get_as_bool("exts/omni.kit.window.file/enable_versioning") or False
if versioning_enabled and create_checkpoint:
omni.client.create_checkpoint(new_root_path, checkpoint_comment)
def save_done_fn(result, err):
if result:
if versioning_enabled and create_checkpoint:
omni.client.create_checkpoint(new_root_path, checkpoint_comment)
if on_save_done:
on_save_done(result, err)
omni.kit.window.file.save_layers(
new_root_path, dirty_layers, save_done_fn, create_checkpoint, checkpoint_comment
)
def _dont_save_layers(self, new_root_path, on_save_done=None, checkpoint_comment=""):
if new_root_path:
self._save_layers(new_root_path, [], on_save_done=on_save_done, checkpoint_comment=checkpoint_comment)
elif on_save_done:
on_save_done(True, "")
def _cancel_save(self, new_root_path, checkpoint_comment=""):
if new_root_path:
self._save_layers(new_root_path, [], None, checkpoint_comment=checkpoint_comment)
def show_open_stage_failed_prompt(self, path):
if not self._open_stage_failed_prompt:
self._open_stage_failed_prompt = Prompt(
f'{omni.kit.ui.get_custom_glyph_code("${glyphs}/exclamation.svg")} Open Stage Failed',
"",
["OK"],
[None],
)
self._open_stage_failed_prompt.set_text(
f"Failed to open stage {os.path.basename(path)}. Please check console for error."
)
self._open_stage_failed_prompt.show()
return self._open_stage_failed_prompt
def show_save_layers_failed_prompt(self):
if not self._save_layers_failed_prompt:
self._save_layers_failed_prompt = Prompt(
f'{omni.kit.ui.get_custom_glyph_code("${glyphs}/exclamation.svg")} Save Layer(s) Failed',
"Failed to save layers. Please check console for error.",
["OK"],
[None],
)
self._save_layers_failed_prompt.show()
return self._save_layers_failed_prompt
| 11,906 |
Python
| 40.34375 | 131 | 0.592474 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/scripts/read_only_options_window.py
|
import carb
import omni.usd
import omni.ui as ui
from pathlib import Path
CURRENT_PATH = Path(__file__).parent.absolute()
ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("icons")
class ReadOnlyOptionsWindow:
def __init__(self, open_with_new_edit_fn, open_original_fn, modal=False):
self._title = "Opening a Read Only File"
self._modal = modal
self._buttons = []
self._content_buttons = [
("Open With New Edit Layer", "open_edit_layer.svg", open_with_new_edit_fn),
("Open Original File", "pencil.svg", open_original_fn),
]
self._build_ui()
def destroy(self):
for button in self._buttons:
button.set_clicked_fn(None)
self._buttons.clear()
def show(self):
self._window.visible = True
def hide(self):
self._window.visible = False
def is_visible(self):
return self._window.visible
def _build_ui(self):
self._window = ui.Window(
self._title, visible=False, height=0, dockPreference=ui.DockPreference.DISABLED
)
self._window.flags = (
ui.WINDOW_FLAGS_NO_COLLAPSE
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_SCROLLBAR
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_MOVE
)
if self._modal:
self._window.flags = self._window.flags | ui.WINDOW_FLAGS_MODAL
button_style = {
"Button": {"stack_direction": ui.Direction.LEFT_TO_RIGHT},
"Button.Image": {"alignment": ui.Alignment.CENTER},
"Button.Label": {"alignment": ui.Alignment.LEFT_CENTER}
}
def button_cliked_fn(button_fn):
if button_fn:
button_fn()
self.hide()
with self._window.frame:
with ui.VStack(height=0):
ui.Spacer(width=0, height=10)
with ui.VStack(height=0):
ui.Spacer(height=0)
for button in self._content_buttons:
(button_text, button_icon, button_fn) = button
with ui.HStack():
ui.Spacer(width=40)
ui_button = ui.Button(
" " + button_text,
image_url=f"{ICON_PATH}/{button_icon}",
image_width=24,
height=40,
clicked_fn=lambda a=button_fn: button_cliked_fn(a),
style=button_style
)
ui.Spacer(width=40)
ui.Spacer(height=5)
self._buttons.append(ui_button)
ui.Spacer(height=5)
with ui.HStack():
ui.Spacer()
cancel_button = ui.Button("Cancel", width=80, height=0)
cancel_button.set_clicked_fn(lambda: self.hide())
self._buttons.append(cancel_button)
ui.Spacer(width=40)
ui.Spacer(height=0)
ui.Spacer(width=0, height=10)
| 3,269 |
Python
| 34.543478 | 91 | 0.492199 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_stop_animation.py
|
## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import platform
import unittest
import os
import pathlib
import asyncio
import shutil
import tempfile
import omni.kit.app
import omni.usd
import omni.timeline
from omni.kit.test.async_unittest import AsyncTestCase
from omni.kit import ui_test
from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows
from omni.kit.window.file_exporter.test_helper import FileExporterTestHelper
class FileWindowStopAnimation(AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
# wait for material to be preloaded so create menu is complete & menus don't rebuild during tests
await omni.kit.material.library.get_mdl_list_async()
await ui_test.human_delay()
# load stage
await open_stage(get_test_data_path(__name__, "physics_animation.usda"))
# setup events
self._future_test = None
self._required_stage_event = -1
self._stage_event_sub = omni.usd.get_context().get_stage_event_stream().create_subscription_to_pop(self._on_stage_event, name="omni.usd.window.file")
# After running each test
async def tearDown(self):
# free events
self._future_test = None
self._required_stage_event = -1
self._stage_event_sub = None
await wait_stage_loading()
await omni.usd.get_context().new_stage_async()
def _on_stage_event(self, event):
if self._future_test and int(self._required_stage_event) == int(event.type) and not self._future_test.done():
self._future_test.set_result(event.type)
async def reset_stage_event(self, stage_event):
self._required_stage_event = stage_event
self._future_test = asyncio.Future()
async def wait_for_stage_event(self):
async def wait_for_event():
await self._future_test
try:
await asyncio.wait_for(wait_for_event(), timeout=30.0)
except asyncio.TimeoutError:
carb.log_error(f"wait_for_stage_event timeout waiting for {self._required_stage_event}")
self._future_test = None
self._required_stage_event = -1
async def test_l1_stop_animation_save(self):
def get_box_pos():
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath("/World/boxActor")
attr = prim.GetAttribute("xformOp:translate")
return attr.Get()
def play_anim():
timeline = omni.timeline.get_timeline_interface()
if timeline:
timeline.play()
# setup
orig_pos = get_box_pos()
tmpdir = tempfile.mkdtemp()
orig_file = get_test_data_path(__name__, "physics_animation.usda").replace("\\", "/")
new_file = f"{tmpdir}/physics_animation.usd".replace("\\", "/")
# play anim
play_anim()
await ui_test.human_delay(100)
# save as
await self.reset_stage_event(omni.usd.StageEventType.SAVED)
omni.kit.actions.core.get_action_registry().get_action("omni.kit.window.file", "save_as").execute()
await ui_test.human_delay(10)
async with FileExporterTestHelper() as file_export_helper:
await file_export_helper.click_apply_async(filename_url=new_file)
await self.wait_for_stage_event()
# play anim
play_anim()
await ui_test.human_delay(100)
# save
await self.reset_stage_event(omni.usd.StageEventType.SAVED)
omni.kit.actions.core.get_action_registry().get_action("omni.kit.window.file", "save").execute()
await ui_test.human_delay(10)
# check _check_and_select_all and _on_select_all_fn for StageSaveDialog
check_box = ui_test.find("Select Files to Save##file.py//Frame/VStack[0]/ScrollingFrame[0]/VStack[0]/HStack[0]/CheckBox[0]")
await check_box.click(human_delay_speed=10)
await check_box.click(human_delay_speed=10)
await ui_test.human_delay()
await ui_test.find("Select Files to Save##file.py//Frame/**/Button[*].text=='Save Selected'").click()
await ui_test.human_delay()
await self.wait_for_stage_event()
# load saved file
await open_stage(new_file)
# verify boxActor is in same place
new_pos = get_box_pos()
self.assertAlmostEqual(orig_pos[0], new_pos[0], places=5)
self.assertAlmostEqual(orig_pos[1], new_pos[1], places=5)
self.assertAlmostEqual(orig_pos[2], new_pos[2], places=5)
| 5,013 |
Python
| 37.56923 | 157 | 0.655496 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_file_save.py
|
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import carb
import os
import tempfile
import shutil
import omni.kit.app
import omni.kit.commands
import omni.kit.test
from pathlib import Path
from unittest.mock import Mock, patch
from omni.kit.window.file_exporter.test_helper import FileExporterTestHelper
from .. import FileWindowExtension, get_instance as get_window_file
from .test_base import TestFileBase
from pxr import Usd
import unittest
class TestFileSave(TestFileBase):
async def setUp(self):
await super().setUp()
async def tearDown(self):
await super().tearDown()
async def test_file_save(self):
"""Testing that save should write to stage url"""
omni.usd.get_context().new_stage()
omni.usd.get_context().set_pending_edit(False)
test_file = "test_file.usda"
temp_path = os.path.join(tempfile.gettempdir(), test_file)
shutil.copyfile(os.path.join(self._usd_path, test_file), temp_path)
omni.kit.window.file.open_stage(temp_path)
await self.wait_for_update()
mock_callback = Mock()
omni.kit.window.file.save(mock_callback)
await self.wait_for_update()
self.assertEqual(omni.usd.get_context().get_stage_url(), temp_path.replace("\\", "/"))
self.assertTrue(os.path.isfile(temp_path))
mock_callback.assert_called_once()
self.remove_file(temp_path)
async def test_file_save_with_render_setting_changes_only(self):
usd_context = omni.usd.get_context()
await usd_context.new_stage_async()
self.assertFalse(usd_context.has_pending_edit())
with tempfile.TemporaryDirectory() as tmp_dir_name:
await omni.kit.app.get_app().next_update_async()
# save
tmp_file_path = Path(tmp_dir_name) / "tmp.usda"
result = usd_context.save_as_stage(str(tmp_file_path))
self.assertTrue(result)
self.assertFalse(usd_context.has_pending_edit())
# save the file with customized key value
settings = carb.settings.get_settings()
setting_key_ao = "/rtx/post/aa/op"
settings.set_int(setting_key_ao, 3)
await omni.kit.app.get_app().next_update_async()
# After changing render settings, it will be dirty.
self.assertTrue(usd_context.has_pending_edit())
# Saves stage, although no layers are dirty except render settings.
omni.kit.window.file.save(None)
# Waiting for save to be done as it's asynchronous.
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
# Making sure that render settings are saved into root layer.
self.assertFalse(usd_context.has_pending_edit())
# Reloading stage will reload the settings also.
await usd_context.reopen_stage_async()
await omni.kit.app.get_app().next_update_async()
self.assertFalse(usd_context.has_pending_edit())
setting_value_ao = settings.get(setting_key_ao)
self.assertEqual(setting_value_ao, 3)
# New stage to release temp file.
await usd_context.new_stage_async()
async def test_file_save_read_only_file(self):
"""Test saving read-only file calls save_as instead"""
omni.usd.get_context().new_stage()
omni.usd.get_context().set_pending_edit(False)
test_file = "test_file.usda"
temp_path = os.path.join(tempfile.gettempdir(), test_file)
shutil.copyfile(os.path.join(self._usd_path, test_file), temp_path)
omni.kit.window.file.open_stage(temp_path)
await self.wait_for_update()
class ListEntry:
def __init__(self) -> None:
self.flags = 0
mock_callback = Mock()
with patch.object(omni.usd.UsdContext, 'is_new_stage', return_value=False),\
patch.object(omni.client, "stat_async", return_value=(omni.client.Result.OK, ListEntry())),\
patch.object(FileWindowExtension, "save_as") as mock_save_as:
omni.kit.window.file.save(mock_callback)
await self.wait_for_update()
mock_save_as.assert_called_once_with(False, mock_callback, allow_skip_sublayers=False)
self.remove_file(temp_path)
async def test_file_saveas(self):
"""Testing save as"""
omni.usd.get_context().new_stage()
omni.usd.get_context().set_pending_edit(False)
temp_path = self._temp_path.replace('.usda', '.usd')
mock_callback = Mock()
async with FileExporterTestHelper() as file_export_helper:
with patch.object(omni.usd.UsdContext, 'is_new_stage', return_value=False):
omni.kit.window.file.save_as(False, mock_callback)
await self.wait_for_update()
await file_export_helper.click_apply_async(filename_url=temp_path)
await self.wait_for_update()
mock_callback.assert_called_once()
self.assertTrue(os.path.isfile(temp_path))
self.remove_file(temp_path)
async def _test_file_saveas_with_empty_filename(self): # pragma: no cover
"""Testing save as with an empty filename, should not allow saving."""
omni.usd.get_context().new_stage()
omni.usd.get_context().set_pending_edit(False)
temp_path = self._temp_path.replace('.usda', '.usd')
mock_callback = Mock()
async with FileExporterTestHelper() as file_export_helper:
with patch.object(omni.usd.UsdContext, 'is_new_stage', return_value=False):
omni.kit.window.file.save_as(False, mock_callback)
await self.wait_for_update()
await file_export_helper.click_apply_async()
await self.wait_for_update()
mock_callback.assert_not_called()
self.assertFalse(os.path.isfile(temp_path))
async def _test_file_saveas_flattened_internal(self, include_session_layer):
"""Testing save as flatten"""
omni.usd.get_context().new_stage()
omni.usd.get_context().set_pending_edit(False)
mock_callback = Mock()
base, ext = os.path.splitext(self._temp_path)
temp_path = base + str(include_session_layer) + ext
temp_path = self._temp_path.replace('.usda', '.usd')
async with FileExporterTestHelper() as file_export_helper:
with patch.object(omni.usd.UsdContext, 'is_new_stage', return_value=False):
omni.kit.window.file.save_as(True, mock_callback)
await self.wait_for_update()
import omni.kit.ui_test as ui_test
file_picker = ui_test.find("Save File As...")
self.assertTrue(file_picker)
await file_picker.focus()
include_session_layer_checkbox = file_picker.find(
"**/CheckBox[*].identifier=='include_session_layer'"
)
self.assertTrue(include_session_layer_checkbox)
include_session_layer_checkbox.model.set_value(include_session_layer)
await file_export_helper.click_apply_async(filename_url=temp_path)
await self.wait_for_update()
stage = Usd.Stage.Open(temp_path)
prim = stage.GetPrimAtPath("/OmniverseKit_Persp")
if include_session_layer:
self.assertTrue(prim)
else:
self.assertFalse(prim)
stage = None
mock_callback.assert_called_once()
self.assertTrue(os.path.isfile(temp_path))
self.remove_file(temp_path)
@unittest.skip("A.B. temp disable, omni.physx.bundle extension causes issues")
async def test_file_saveas_flattened_with_session_layer(self):
await self._test_file_saveas_flattened_internal(True)
async def test_file_saveas_flattened_without_session_layer(self):
await self._test_file_saveas_flattened_internal(False)
async def test_show_save_layers_failed_prompt(self):
omni.usd.get_context().new_stage()
prompt = get_window_file().ui_handler.show_save_layers_failed_prompt()
await self.wait_for_update()
prompt.hide()
async def test_file_saveas_existed_filename(self):
"""Testing save as with a filename which is already existed, should not allow saving."""
# create an empty stage
await omni.usd.get_context().new_stage_async()
omni.usd.get_context().set_pending_edit(False)
file_name = f"4Lights.usda"
temp_path = os.path.join(tempfile.gettempdir(), file_name)
shutil.copyfile(os.path.join(self._usd_path, file_name), temp_path)
# save the current stage to the temp path where the file name already exists
async with FileExporterTestHelper() as file_export_helper:
with patch.object(omni.usd.UsdContext, 'is_new_stage', return_value=False):
omni.kit.window.file.save_as(False, Mock())
await self.wait_for_update()
await file_export_helper.click_apply_async(filename_url=temp_path)
await self.wait_for_update()
# check 4Lights.usda is not empty, which means saveas didn't happen
stage = Usd.Stage.Open(str(temp_path))
await self.wait_for_update()
prim = stage.GetPrimAtPath("/Stage/SphereLight_01")
self.assertTrue(prim)
self.remove_file(temp_path)
async def test_invalid_save(self):
"""Test no valid stage save"""
if omni.usd.get_context().get_stage():
await omni.usd.get_context().close_stage_async()
mock_callback = Mock()
omni.kit.window.file.save(mock_callback)
mock_callback.assert_not_called()
| 10,185 |
Python
| 39.420635 | 104 | 0.633873 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/test_file_window.py
|
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.window.file
from .test_base import TestFileBase
from unittest.mock import Mock
from omni.kit import ui_test
from omni.kit.window.file import ReadOnlyOptionsWindow
from omni.kit.window.file import register_open_stage_addon, register_open_stage_complete
from omni.kit.window.file_importer import get_file_importer
class TestFileWindow(TestFileBase):
async def setUp(self):
await super().setUp()
# After running each test
async def tearDown(self):
await super().tearDown()
async def test_read_only_options_window(self):
"""Testing read only options window"""
self._readonly_window = ReadOnlyOptionsWindow(None, None, True)
self._readonly_window.show()
self.assertTrue(self._readonly_window.is_visible)
self._readonly_window.destroy()
async def test_stage_register(self):
"""Testing register_open_stage_addon and register_open_stage_complete subscription"""
mock_callback1 = Mock()
mock_callback2 = Mock()
self._addon_subscription = register_open_stage_addon(mock_callback1)
self._complete_subscription = register_open_stage_complete(mock_callback2)
omni.kit.window.file.open_stage(f"{self._usd_path}/test_file.usda")
await self.wait_for_update()
mock_callback1.assert_called_once()
mock_callback2.assert_called_once()
async def test_add_reference(self):
omni.kit.window.file.add_reference(is_payload=False)
await ui_test.human_delay()
file_importer = get_file_importer()
self.assertTrue(file_importer.is_window_visible)
file_importer.click_cancel()
| 2,103 |
Python
| 35.91228 | 93 | 0.717071 |
omniverse-code/kit/exts/omni.kit.window.file/omni/kit/window/file/tests/__init__.py
|
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from .test_file_new import *
from .test_file_open import *
from .test_file_save import *
from .test_prompt_unsaved import *
from .test_stop_animation import *
from .test_file_window import *
from .test_loadstage import *
| 657 |
Python
| 40.124997 | 77 | 0.7793 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.