file_path
stringlengths 32
153
| content
stringlengths 0
3.14M
|
---|---|
omniverse-code/kit/exts/omni.kit.widget.settings/config/extension.toml | [package]
title = "Settings Widget"
description = "Settings Widget"
version = "1.0.1"
category = "Internal"
authors = ["NVIDIA"]
repository = ""
keywords = ["settings", "ui"]
changelog = "docs/CHANGELOG.md"
# Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file).
preview_image = "data/preview.png"
[dependencies]
"omni.ui" = {}
"omni.kit.commands" = {}
[[python.module]]
name = "omni.kit.widget.settings"
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.kit.renderer.capture",
]
|
omniverse-code/kit/exts/omni.kit.widget.settings/omni/kit/widget/settings/settings_widget.py | from enum import Enum
from typing import Tuple, Union
import carb
import carb.settings
import omni.ui as ui
from .settings_model import (
SettingModel,
SettingsComboItemModel,
VectorFloatSettingsModel,
VectorIntSettingsModel,
AssetPathSettingsModel,
RadioButtonSettingModel,
)
from .settings_widget_builder import SettingsWidgetBuilder
from omni.kit.widget.searchable_combobox import build_searchable_combo_widget
import omni.kit.app
class SettingType(Enum):
"""
Supported setting types
"""
FLOAT = 0
INT = 1
COLOR3 = 2
BOOL = 3
STRING = 4
DOUBLE3 = 5
INT2 = 6
DOUBLE2 = 7
ASSET = 8
class SettingWidgetType(Enum):
"""
Supported setting UI widget types
"""
FLOAT = 0
INT = 1
COLOR3 = 2
BOOL = 3
STRING = 4
DOUBLE3 = 5
INT2 = 6
DOUBLE2 = 7
ASSET = 8
COMBOBOX = 9
RADIOBUTTON = 10
# This is for backward compatibility - Using deprecated SettingType - omni.kit.widget.settings.deprecated.SettingType
INT_WIDGET_TPYE_MAP = {
0: SettingWidgetType.FLOAT,
1: SettingWidgetType.INT,
2: SettingWidgetType.COLOR3,
3: SettingWidgetType.BOOL,
4: SettingWidgetType.STRING,
5: SettingWidgetType.DOUBLE3,
6: SettingWidgetType.INT2,
7: SettingWidgetType.DOUBLE2,
8: SettingWidgetType.ASSET,
9: SettingWidgetType.COMBOBOX,
10: SettingWidgetType.RADIOBUTTON,
}
# TODO: Section will be moved to some location like omni.ui.settings
# #############################################################################################
def create_setting_widget(
setting_path: str, setting_type: SettingType, range_from=0, range_to=0, speed=1, **kwargs
) -> Tuple[ui.Widget, ui.AbstractValueModel]:
"""
Create a UI widget connected with a setting.
If ``range_from`` >= ``range_to`` there is no limit. Undo/redo operations are also supported, because changing setting
goes through the :mod:`omni.kit.commands` module, using :class:`.ChangeSettingCommand`.
Args:
setting_path: Path to the setting to show and edit.
setting_type: Type of the setting to expect.
range_from: Limit setting value lower bound.
range_to: Limit setting value upper bound.
speed: Range speed
Returns:
:class:`ui.Widget` and :class:`ui.AbstractValueModel` connected with the setting on the path specified.
"""
widget = None
model = None
if isinstance(setting_type, int):
setting_type = INT_WIDGET_TPYE_MAP.get(setting_type)
# The string "ASSET" is for backward compatibility
if not isinstance(setting_type, Enum) and setting_type != "ASSET":
carb.log_warn(f"Unsupported setting widget type {setting_type} for {setting_path}")
return None, None
# Create widget to be used for particular type.
if setting_type == SettingWidgetType.COMBOBOX:
setting_is_index = kwargs.pop("setting_is_index", True)
widget, model = SettingsWidgetBuilder.createComboboxWidget(setting_path, setting_is_index=setting_is_index, additional_widget_kwargs=kwargs)
elif setting_type == SettingWidgetType.RADIOBUTTON:
model = RadioButtonSettingModel(setting_path)
widget = SettingsWidgetBuilder.createRadiobuttonWidget(model, setting_path, additional_widget_kwargs=kwargs)
elif setting_type in [SettingType.INT, SettingWidgetType.INT]:
model = SettingModel(setting_path, draggable=True)
if model.get_value_as_int() is not None:
widget = SettingsWidgetBuilder.createIntWidget(model, range_from, range_to, additional_widget_kwargs=kwargs)
elif setting_type in [SettingType.FLOAT, SettingWidgetType.FLOAT]:
model = SettingModel(setting_path, draggable=True)
if model.get_value_as_float() is not None:
widget = SettingsWidgetBuilder.createFloatWidget(model, range_from, range_to, additional_widget_kwargs=kwargs)
elif setting_type in [SettingType.BOOL, SettingWidgetType.BOOL]:
model = SettingModel(setting_path)
if model.get_value_as_bool() is not None:
widget = SettingsWidgetBuilder.createBoolWidget(model, additional_widget_kwargs=kwargs)
elif setting_type in [SettingType.STRING, SettingWidgetType.STRING]:
model = SettingModel(setting_path)
if model.get_value_as_string() is not None:
widget = ui.StringField(**kwargs)
elif setting_type in [SettingType.COLOR3, SettingWidgetType.COLOR3]:
model = VectorFloatSettingsModel(setting_path, 3)
widget = SettingsWidgetBuilder.createColorWidget(model, comp_count=3, additional_widget_kwargs=kwargs)
elif setting_type in [SettingType.DOUBLE2, SettingWidgetType.DOUBLE2]:
model = VectorFloatSettingsModel(setting_path, 2)
widget = SettingsWidgetBuilder.createDoubleArrayWidget(model, range_from, range_to, comp_count=2, additional_widget_kwargs=kwargs)
elif setting_type in [SettingType.DOUBLE3, SettingWidgetType.DOUBLE3]:
model = VectorFloatSettingsModel(setting_path, 3)
widget = SettingsWidgetBuilder.createDoubleArrayWidget(model, range_from, range_to, comp_count=3, additional_widget_kwargs=kwargs)
elif setting_type in [SettingType.INT2, SettingWidgetType.INT2]:
model = VectorIntSettingsModel(setting_path, 2)
widget = SettingsWidgetBuilder.createIntArrayWidget(model, range_from, range_to, comp_count=2, additional_widget_kwargs=kwargs)
elif setting_type in [SettingType.ASSET, SettingWidgetType.ASSET, "ASSET"]: # The string "ASSET" is for backward compatibility
model = AssetPathSettingsModel(setting_path)
widget = SettingsWidgetBuilder.createAssetWidget(model, additional_widget_kwargs=kwargs)
else: # pragma: no cover
# Convenient way to extend new types of widget creation.
build_widget_func = getattr(SettingsWidgetBuilder, f"create{setting_type.name.capitalize()}Widget", None)
if build_widget_func:
widget, model = build_widget_func(setting_path, additional_widget_kwargs=kwargs)
else:
carb.log_warn(f"Couldn't find widget for {setting_type} - {setting_path}") # Do we have any right now?
return None, None
if widget:
try:
widget.model = model
except Exception: # pragma: no cover
print(widget, "doesn't have model")
if isinstance(widget, ui.Widget) and not widget.identifier:
widget.identifier = setting_path
return widget, model
def create_setting_widget_combo(
setting_path: str, items: Union[list, dict], setting_is_index: bool = True) -> Tuple[SettingsComboItemModel, ui.ComboBox]:
"""
Creating a Combo Setting widget.
This function creates a combo box that shows a provided list of names and it is connected with setting by path
specified. Underlying setting values are used from values of `items` dict.
Args:
setting_path: Path to the setting to show and edit.
items: Can be either :py:obj:`dict` or :py:obj:`list`. For :py:obj:`dict` keys are UI displayed names, values are
actual values set into settings. If it is a :py:obj:`list` UI displayed names are equal to setting values.
setting_is_index:
True - setting_path value is index into items list (default)
False - setting_path value is string in items list
"""
return SettingsWidgetBuilder.createComboboxWidget(setting_path, items=items, setting_is_index=setting_is_index)
class SettingsSearchableCombo:
def __init__(self, setting_path: str, key_value_pairs: dict, default_key: str):
self._path = setting_path
self._items = key_value_pairs
key_index = -1
key_list = sorted(list(self._items.keys()))
self._set_by_ui = False
def on_combo_click(model):
item_key = model.get_value_as_string()
item_value = self._items[item_key]
self._set_by_ui = True
carb.settings.get_settings().set_string(self._path, item_value)
self._component_combo = build_searchable_combo_widget(key_list, key_index, on_combo_click, widget_height=18, default_value=default_key)
self._update_setting = omni.kit.app.SettingChangeSubscription(self._path, self._on_setting_change)
def destroy(self):
self._component_combo.destroy()
self._component_combo = None
self._update_setting = None
def get_key_from_value(self, value):
idx = list(self._items.values()).index(value)
key = list(self._items.keys())[idx]
return key
def get_current_key(self):
current_value = carb.settings.get_settings().get_as_string(self._path)
return self.get_key_from_value(current_value)
def _on_setting_change(owner, item: carb.dictionary.Item, event_type):
if owner._set_by_ui:
owner._set_by_ui = False
else:
key = owner.get_current_key()
owner._component_combo.set_text(new_text=key)
#print(item)
|
omniverse-code/kit/exts/omni.kit.widget.settings/omni/kit/widget/settings/style.py | import carb.settings
import omni.ui as ui
def get_ui_style_name():
return carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark"
def get_style():
KIT_GREEN = 0xFF8A8777
BORDER_RADIUS = 1.5
FONT_SIZE = 14.0
ui_style = get_ui_style_name()
if ui_style == "NvidiaLight": # pragma: no cover
WINDOW_BACKGROUND_COLOR = 0xFF444444
BUTTON_BACKGROUND_COLOR = 0xFF545454
BUTTON_BACKGROUND_HOVERED_COLOR = 0xFF9E9E9E
BUTTON_BACKGROUND_PRESSED_COLOR = 0xC22A8778
BUTTON_LABEL_DISABLED_COLOR = 0xFF606060
BUTTON_LABEL_COLOR = 0x7FD6D6D6
FRAME_TEXT_COLOR = 0xFF545454
FIELD_BACKGROUND = 0xFF545454
FIELD_SECONDARY = 0xFFABABAB
FIELD_TEXT_COLOR = 0xFFD6D6D6
FIELD_TEXT_COLOR_READ_ONLY = 0xFF9C9C9C
FIELD_TEXT_COLOR_HIDDEN = 0x01000000
COLLAPSABLEFRAME_BORDER_COLOR = 0x0
COLLAPSABLEFRAME_BACKGROUND_COLOR = 0x7FD6D6D6
COLLAPSABLEFRAME_TEXT_COLOR = 0xFF545454
COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR = 0xFFC9C9C9
COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR = 0xFFD6D6D6
COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR = 0xFFCCCFBF
COLLAPSABLEFRAME_PRESSED_BACKGROUND_COLOR = 0xFF2E2E2B
COLLAPSABLEFRAME_HOVERED_SECONDARY_COLOR = 0xFFD6D6D6
COLLAPSABLEFRAME_PRESSED_SECONDARY_COLOR = 0xFFE6E6E6
LABEL_VECTORLABEL_COLOR = 0xFFDDDDDD
LABEL_MIXED_COLOR = 0xFFD6D6D6
LIGHT_FONT_SIZE = 14.0
LIGHT_BORDER_RADIUS = 3
style = {
"Window": {"background_color": 0xFFE0E0E0},
"Button": {"background_color": 0xFFE0E0E0, "margin": 0, "padding": 3, "border_radius": 2},
"Button:hovered": {"background_color": BUTTON_BACKGROUND_HOVERED_COLOR},
"Button:pressed": {"background_color": BUTTON_BACKGROUND_PRESSED_COLOR},
"Button.Label:disabled": {"color": BUTTON_LABEL_DISABLED_COLOR},
"Button.Label": {"color": BUTTON_LABEL_COLOR},
"RadioButton": {
"margin": 2,
"border_radius": 2,
"font_size": 16,
"background_color": BUTTON_BACKGROUND_COLOR,
"color": 0xFFFF0000,
},
"RadioButton.Label": {"font_size": 16, "color": 0xFFC8C8C8},
"RadioButton:checked": {"background_color": BUTTON_BACKGROUND_HOVERED_COLOR, "color": 0xFF00FF00},
"RadioButton:pressed": {"background_color": BUTTON_BACKGROUND_HOVERED_COLOR, "color": 0xFF00FF00},
"RadioButton.Label:checked": {"color": 0xFFE8E8E8},
"Triangle::title": {"background_color": BUTTON_BACKGROUND_COLOR},
"ComboBox": {
"font_size": LIGHT_FONT_SIZE,
"color": 0xFFE6E6E6,
"background_color": 0xFF545454,
"secondary_color": 0xFF545454,
"selected_color": 0xFFACACAF,
"border_radius": LIGHT_BORDER_RADIUS * 2,
},
"ComboBox:hovered": {"background_color": 0xFF545454},
"ComboBox:selected": {"background_color": 0xFF545454},
"Field::models": {
"background_color": FIELD_BACKGROUND,
"font_size": LIGHT_FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"border_radius": LIGHT_BORDER_RADIUS,
"secondary_color": FIELD_SECONDARY,
},
"Field::models_readonly": {
"background_color": FIELD_BACKGROUND,
"font_size": LIGHT_FONT_SIZE,
"color": FIELD_TEXT_COLOR_READ_ONLY,
"border_radius": LIGHT_BORDER_RADIUS,
"secondary_color": FIELD_SECONDARY,
},
"Field::models:pressed": {"background_color": 0xFFCECECE},
"Field": {"background_color": 0xFF535354, "color": 0xFFCCCCCC},
"Label": {"font_size": 12, "color": FRAME_TEXT_COLOR},
"Label::RenderLabel": {"font_size": LIGHT_FONT_SIZE, "color": FRAME_TEXT_COLOR},
"Label::label": {
"font_size": LIGHT_FONT_SIZE,
"background_color": FIELD_BACKGROUND,
"color": FRAME_TEXT_COLOR,
},
"Label::title": {
"font_size": LIGHT_FONT_SIZE,
"background_color": FIELD_BACKGROUND,
"color": FRAME_TEXT_COLOR,
},
"Slider::value": {
"font_size": LIGHT_FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"border_radius": LIGHT_BORDER_RADIUS,
"background_color": BUTTON_BACKGROUND_HOVERED_COLOR,
"secondary_color": KIT_GREEN,
},
"CheckBox::greenCheck": {"font_size": 10, "background_color": KIT_GREEN, "color": 0xFF23211F},
"CollapsableFrame": {
"background_color": COLLAPSABLEFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_BACKGROUND_COLOR,
"color": COLLAPSABLEFRAME_TEXT_COLOR,
"border_radius": LIGHT_BORDER_RADIUS,
"border_color": 0x0,
"border_width": 1,
"font_size": LIGHT_FONT_SIZE,
"padding": 6,
},
"CollapsableFrame.Header": {
"font_size": LIGHT_FONT_SIZE,
"background_color": FRAME_TEXT_COLOR,
"color": FRAME_TEXT_COLOR,
},
"CollapsableFrame:hovered": {"secondary_color": COLLAPSABLEFRAME_HOVERED_SECONDARY_COLOR},
"CollapsableFrame:pressed": {"secondary_color": COLLAPSABLEFRAME_PRESSED_SECONDARY_COLOR},
"Label::vector_label": {"font_size": 14, "color": LABEL_VECTORLABEL_COLOR},
"Rectangle::reset_invalid": {"background_color": 0xFF505050, "border_radius": 2},
"Rectangle::reset": {"background_color": 0xFFA07D4F, "border_radius": 2},
"Rectangle::vector_label": {"border_radius": BORDER_RADIUS * 2, "corner_flag": ui.CornerFlag.LEFT},
"Rectangle": {"border_radius": LIGHT_BORDER_RADIUS, "background_color": FIELD_BACKGROUND},
"Line::check_line": {"color": KIT_GREEN},
}
else:
LABEL_COLOR = 0xFF8F8E86
FIELD_BACKGROUND = 0xFF23211F
FIELD_TEXT_COLOR = 0xFFD5D5D5
FIELD_TEXT_COLOR_READ_ONLY = 0xFF5C5C5C
FRAME_TEXT_COLOR = 0xFFCCCCCC
WINDOW_BACKGROUND_COLOR = 0xFF444444
BUTTON_BACKGROUND_COLOR = 0xFF292929
BUTTON_BACKGROUND_HOVERED_COLOR = 0xFF9E9E9E
BUTTON_BACKGROUND_PRESSED_COLOR = 0xC22A8778
BUTTON_LABEL_DISABLED_COLOR = 0xFF606060
LABEL_LABEL_COLOR = 0xFF9E9E9E
LABEL_TITLE_COLOR = 0xFFAAAAAA
LABEL_VECTORLABEL_COLOR = 0xFFDDDDDD
COLORWIDGET_BORDER_COLOR = 0xFF1E1E1E
COMBOBOX_HOVERED_BACKGROUND_COLOR = 0xFF33312F
COLLAPSABLEFRAME_BORDER_COLOR = 0x0
COLLAPSABLEFRAME_BACKGROUND_COLOR = 0xFF343432
COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR = 0xFF23211F
COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR = 0xFF343432
COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR = 0xFF2E2E2B
COLLAPSABLEFRAME_PRESSED_BACKGROUND_COLOR = 0xFF2E2E2B
style = {
"Window": {"background_color": WINDOW_BACKGROUND_COLOR},
"Button": {"background_color": WINDOW_BACKGROUND_COLOR, "margin": 0, "padding": 3, "border_radius": 4},
"RadioButton": {
"margin": 2,
"border_radius": 2,
"font_size": 16,
"background_color": 0xFF212121,
"color": 0xFF444444,
},
"RadioButton.Label": {"font_size": 16, "color": 0xFF777777},
"RadioButton:checked": {"background_color": 0xFF777777, "color": 0xFF222222},
"RadioButton.Label:checked": {"color": 0xFFDDDDDD},
"Button:hovered": {"background_color": BUTTON_BACKGROUND_HOVERED_COLOR},
"Button:pressed": {"background_color": BUTTON_BACKGROUND_PRESSED_COLOR},
"Button.Label:disabled": {"color": BUTTON_LABEL_DISABLED_COLOR},
"Triangle::title": {"background_color": 0xFFCCCCCC},
"Field::models": {
"background_color": FIELD_BACKGROUND,
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"border_radius": BORDER_RADIUS,
},
"Field::models_readonly": {
"background_color": FIELD_BACKGROUND,
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR_READ_ONLY,
"border_radius": BORDER_RADIUS,
},
"Label": {"font_size": 14, "color": LABEL_COLOR},
"Label::label": {"font_size": FONT_SIZE, "color": LABEL_LABEL_COLOR},
"Label::title": {"font_size": FONT_SIZE, "color": LABEL_TITLE_COLOR},
"ComboBox::renderer_choice": {"font_size": 16},
"ComboBox::choices": {
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"background_color": FIELD_BACKGROUND,
"secondary_color": FIELD_BACKGROUND,
"border_radius": BORDER_RADIUS,
},
"ComboBox:hovered:choices": {
"background_color": COMBOBOX_HOVERED_BACKGROUND_COLOR,
"secondary_color": COMBOBOX_HOVERED_BACKGROUND_COLOR,
},
"Slider::value": {
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"border_radius": BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"secondary_color": KIT_GREEN,
},
"Slider::multivalue": {
"font_size": FONT_SIZE,
"color": FIELD_TEXT_COLOR,
"border_radius": BORDER_RADIUS,
"background_color": FIELD_BACKGROUND,
"secondary_color": KIT_GREEN,
"draw_mode": ui.SliderDrawMode.HANDLE,
},
"CheckBox::greenCheck": {
"font_size": 12,
"background_color": LABEL_LABEL_COLOR,
"color": FIELD_BACKGROUND,
"border_radius": BORDER_RADIUS,
},
"CollapsableFrame": {
"background_color": COLLAPSABLEFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_BACKGROUND_COLOR,
"border_radius": BORDER_RADIUS * 2,
"padding": 4,
"color": FRAME_TEXT_COLOR,
},
"CollapsableFrame::groupFrame": {
"background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
"border_radius": BORDER_RADIUS * 2,
"padding": 2,
},
"CollapsableFrame::groupFrame:hovered": {
"background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
},
"CollapsableFrame::groupFrame:pressed": {
"background_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_GROUPFRAME_BACKGROUND_COLOR,
},
"CollapsableFrame::subFrame": {
"background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR,
},
"CollapsableFrame::subFrame:hovered": {
"background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR,
},
"CollapsableFrame::subFrame:pressed": {
"background_color": COLLAPSABLEFRAME_SUBFRAME_BACKGROUND_COLOR,
"secondary_color": COLLAPSABLEFRAME_PRESSED_BACKGROUND_COLOR,
},
"CollapsableFrame.Header": {
"font_size": FONT_SIZE,
"background_color": FRAME_TEXT_COLOR,
"color": FRAME_TEXT_COLOR,
},
"CollapsableFrame:hovered": {"secondary_color": COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR},
"CollapsableFrame:pressed": {"secondary_color": COLLAPSABLEFRAME_PRESSED_BACKGROUND_COLOR},
"ColorWidget": {
"border_radius": BORDER_RADIUS,
"border_color": COLORWIDGET_BORDER_COLOR,
"border_width": 0.5,
},
"Label::RenderLabel": {"font_size": 16, "color": FRAME_TEXT_COLOR},
"Rectangle::TopBar": {
"border_radius": BORDER_RADIUS * 2,
"background_color": COLLAPSABLEFRAME_HOVERED_BACKGROUND_COLOR,
},
"Label::vector_label": {"font_size": 16, "color": LABEL_VECTORLABEL_COLOR},
"Rectangle::vector_label": {"border_radius": BORDER_RADIUS * 2, "corner_flag": ui.CornerFlag.LEFT},
"Rectangle::reset_invalid": {"background_color": 0xFF505050, "border_radius": 2},
"Rectangle::reset": {"background_color": 0xFFA07D4F, "border_radius": 2},
}
return style
|
omniverse-code/kit/exts/omni.kit.widget.settings/omni/kit/widget/settings/__init__.py | from .style import get_style, get_ui_style_name
from .settings_widget import create_setting_widget, create_setting_widget_combo, SettingType, SettingsSearchableCombo, SettingWidgetType
from .settings_widget_builder import SettingsWidgetBuilder
|
omniverse-code/kit/exts/omni.kit.widget.settings/omni/kit/widget/settings/settings_widget_builder.py | import collections
from functools import partial
from pathlib import Path
from typing import Tuple, Union, Any
import carb
import carb.settings
import omni.kit.app
import omni.kit.commands
import omni.ui as ui
from .settings_model import SettingsComboItemModel, RadioButtonSettingModel
LABEL_HEIGHT = 18
HORIZONTAL_SPACING = 4
LABEL_WIDTH = 200
class SettingsWidgetBuilder:
checkbox_alignment = None
checkbox_alignment_set = False
@staticmethod
def _get_setting(setting_path: str, setting_name: str = "", default: Any = None) -> Any:
"""Get the configuration of an UI widget carb.settings. This method assumes the given "setting_path" points
to a value that has the given "setting_name" setting lives aside with it as a sibling.
Args:
setting_path (str): The base setting path.
setting_name (str): The setting name the query.
Kwargs:
default (Any): The value to return if the setting doesn't exist or is None.
Return:
(Any): Setting value.
"""
# setting_path is pointing to the value of the setting, go one level up to get the other settings - e.g. itmes
if setting_name:
setting_path = setting_path.split("/")[:-1]
setting_path.append(setting_name)
setting_path = "/".join(setting_path)
value = carb.settings.get_settings().get(setting_path)
value = default if value is None else value
return value
@classmethod
def get_checkbox_alignment(cls):
if not cls.checkbox_alignment_set:
settings = carb.settings.get_settings()
cls.checkbox_alignment = settings.get("/ext/omni.kit.window.property/checkboxAlignment")
cls.checkbox_alignment_set = True
return cls.checkbox_alignment
label_alignment = None
label_alignment_set = False
@classmethod
def get_label_alignment(cls):
if not cls.label_alignment_set:
settings = carb.settings.get_settings()
cls.label_alignment = settings.get("/ext/omni.kit.window.property/labelAlignment")
cls.label_alignment_set = True
return cls.label_alignment
@classmethod
def _restore_defaults(cls, path: str, button=None) -> None:
omni.kit.commands.execute("RestoreDefaultRenderSetting", path=path)
if button:
button.visible = False
@classmethod
def _build_reset_button(cls, path) -> ui.Rectangle:
with ui.VStack(width=0, height=0):
ui.Spacer()
with ui.ZStack(width=15, height=15):
with ui.HStack(style={"margin_width": 0}):
ui.Spacer()
with ui.VStack(width=0):
ui.Spacer()
ui.Rectangle(width=5, height=5, name="reset_invalid")
ui.Spacer()
ui.Spacer()
btn = ui.Rectangle(width=12, height=12, name="reset", tooltip="Click to reset value", identifier=f"{path}_reset")
btn.visible = False
btn.set_mouse_pressed_fn(lambda x, y, m, w, p=path, b=btn: cls._restore_defaults(path, b))
ui.Spacer()
return btn
@staticmethod
def _create_multi_float_drag_with_labels(model, labels, comp_count, **kwargs) -> None:
RECT_WIDTH = 13
SPACING = 4
with ui.ZStack():
with ui.HStack():
if labels:
ui.Spacer(width=RECT_WIDTH)
widget_kwargs = {"name": "multivalue", "h_spacing": RECT_WIDTH + SPACING}
else:
widget_kwargs = {"name": "multivalue", "h_spacing": 3}
widget_kwargs.update(kwargs)
ui.MultiFloatDragField(model, **widget_kwargs)
with ui.HStack():
if labels:
for i in range(comp_count):
if i != 0:
ui.Spacer(width=SPACING)
label = labels[i]
with ui.ZStack(width=RECT_WIDTH + 1):
ui.Rectangle(name="vector_label", style={"background_color": label[1]})
ui.Label(label[0], name="vector_label", alignment=ui.Alignment.CENTER)
ui.Spacer()
@staticmethod
def _create_multi_int_drag_with_labels(model, labels, comp_count, **kwargs) -> None:
RECT_WIDTH = 13
SPACING = 4
with ui.ZStack():
with ui.HStack():
if labels:
ui.Spacer(width=RECT_WIDTH)
widget_kwargs = {"name": "multivalue", "h_spacing": RECT_WIDTH + SPACING}
else:
widget_kwargs = {"name": "multivalue", "h_spacing": 3}
widget_kwargs.update(kwargs)
ui.MultiIntDragField(model, **widget_kwargs)
with ui.HStack():
if labels:
for i in range(comp_count):
if i != 0:
ui.Spacer(width=SPACING)
label = labels[i]
with ui.ZStack(width=RECT_WIDTH + 1):
ui.Rectangle(name="vector_label", style={"background_color": label[1]})
ui.Label(label[0], name="vector_label", alignment=ui.Alignment.CENTER)
ui.Spacer()
@classmethod
def createColorWidget(cls, model, comp_count=3, additional_widget_kwargs=None) -> ui.HStack:
with ui.HStack(spacing=HORIZONTAL_SPACING) as widget:
widget_kwargs = {"min": 0.0, "max": 1.0}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
# TODO probably need to support "A" if comp_count is 4, but how many assumptions can we make?
with ui.HStack(spacing=4):
cls._create_multi_float_drag_with_labels(
model=model,
labels=[("R", 0xFF5555AA), ("G", 0xFF76A371), ("B", 0xFFA07D4F)],
comp_count=comp_count,
**widget_kwargs,
)
ui.ColorWidget(model, width=30, height=0)
# cls._create_control_state(model)
return widget
@classmethod
def createVecWidget(cls, model, range_min, range_max, comp_count=3, additional_widget_kwargs=None):
widget_kwargs = {"min": range_min, "max": range_max}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
cls._create_multi_float_drag_with_labels(
model=model,
labels=[("X", 0xFF5555AA), ("Y", 0xFF76A371), ("Z", 0xFFA07D4F), ("W", 0xFFFFFFFF)],
comp_count=comp_count,
**widget_kwargs,
)
return model
@classmethod
def createDoubleArrayWidget(cls, model, range_min, range_max, comp_count=3, additional_widget_kwargs=None):
widget_kwargs = {"min": range_min, "max": range_max}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
cls._create_multi_float_drag_with_labels(model=model, labels=None, comp_count=comp_count, **widget_kwargs)
return model
@classmethod
def createIntArrayWidget(cls, model, range_min, range_max, comp_count=3, additional_widget_kwargs=None):
widget_kwargs = {"min": range_min, "max": range_max}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
cls._create_multi_int_drag_with_labels(model=model, labels=None, comp_count=comp_count, **widget_kwargs)
return model
@staticmethod
def _create_drag_or_slider(drag_widget, slider_widget, **kwargs):
'''
A drag_widget lets you click and drag (you can drag as far left or right on the screen as you like)
You can double-click to manually enter a value
A slider_widget lets you click and sets the value to where you clicked.
You don't drag outside the screen space occupied by the widget.
No double click support.
You press Ctrl-Click to manually enter a value
This method will use a slider_widget when the range is <100 and a slider otherwise
'''
if "min" in kwargs and "max" in kwargs:
range_min = kwargs["min"]
range_max = kwargs["max"]
if range_max - range_min < 100:
widget = slider_widget(name="value", **kwargs)
if "hard_range" in kwargs and kwargs['hard_range']:
model = kwargs["model"]
model.set_range(range_min, range_max)
return widget
else:
if "step" not in kwargs:
kwargs["step"] = max(0.1, (range_max - range_min) / 1000.0)
else:
if "step" not in kwargs:
kwargs["step"] = 0.1
# If range is too big or no range, don't use a slider
widget = drag_widget(name="value", **kwargs)
return widget
@classmethod
def _create_label(cls, attr_name, path, tooltip="", additional_label_kwargs=None):
alignment = ui.Alignment.RIGHT if cls.get_label_alignment() == "right" else ui.Alignment.LEFT
label_kwargs = {
"name": "label",
"word_wrap": True,
"width": LABEL_WIDTH,
"height": LABEL_HEIGHT,
"alignment": alignment,
}
# Tooltip always contains setting name. If there's a user-defined one, add that too
label_kwargs["tooltip"] = path
if tooltip:
label_kwargs["tooltip"] = f"{path} : {tooltip}"
if additional_label_kwargs:
label_kwargs.update(additional_label_kwargs)
ui.Label(attr_name, **label_kwargs)
ui.Spacer(width=5)
@classmethod
def createBoolWidget(cls, model, additional_widget_kwargs=None):
widget = None
with ui.HStack():
left_aligned = cls.get_checkbox_alignment() == "left"
if not left_aligned:
ui.Spacer(width=10)
ui.Line(style={"color": 0x338A8777}, width=ui.Fraction(1))
ui.Spacer(width=5)
with ui.VStack(style={"margin_width": 0}, width=10):
ui.Spacer()
widget_kwargs = {"width": 10, "height": 0, "name": "greenCheck", "model": model}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
widget = ui.CheckBox(**widget_kwargs)
ui.Spacer()
if left_aligned:
ui.Spacer(width=10)
ui.Line(style={"color": 0x338A8777}, width=ui.Fraction(1))
return widget
@classmethod
def createFloatWidget(cls, model, range_min, range_max, additional_widget_kwargs=None):
widget_kwargs = {"model": model}
# only set range if range is valid (min < max)
if range_min < range_max:
widget_kwargs["min"] = range_min
widget_kwargs["max"] = range_max
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
widget_kwargs.update(style={"secondary_color": 0xFF444444})
return cls._create_drag_or_slider(ui.FloatDrag, ui.FloatSlider, **widget_kwargs)
@classmethod
def createIntWidget(cls, model, range_min, range_max, additional_widget_kwargs=None):
widget_kwargs = {"model": model} # This passes the model into the widget
# only set range if range is valid (min < max)
if range_min < range_max:
widget_kwargs["min"] = range_min
widget_kwargs["max"] = range_max
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
widget_kwargs.update(style={"secondary_color": 0xFF444444})
return cls._create_drag_or_slider(ui.IntDrag, ui.IntSlider, **widget_kwargs)
@classmethod
def createAssetWidget(cls, model, additional_widget_kwargs=None):
widget = AssetPicker(model)
widget.build_ui(additional_widget_kwargs)
return widget
@classmethod
def createRadiobuttonWidget(
cls, model: RadioButtonSettingModel,
setting_path: str = "", additional_widget_kwargs: dict = None) -> omni.ui.RadioCollection:
"""
Creating a RadioButtons Setting widget.
This function creates a Radio Buttons that shows a list of names that are connected with setting by path
specified - "{setting_path}/items".
Args:
model: A RadioButtonSettingModel instance.
setting_path: Path to the setting to show and edit.
Return:
(omni.ui.RadioCollection): A omni.ui.RadioCollection instance.
"""
def _create_radio_button(_collection):
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
icon_dir = Path(extension_path).joinpath("data").joinpath("icons").absolute()
icon_style = {
"image_url": str(Path(icon_dir, Path("radio_off.svg"))),
":checked": {"image_url": str(Path(icon_dir, Path("radio_on.svg")))},
}
radio_button = omni.ui.RadioButton(
radio_collection=_collection,
width=20,
height=20,
style=icon_style,
**additional_widget_kwargs,
)
omni.ui.Label(f"{item}\t", alignment=omni.ui.Alignment.LEFT)
return radio_button
additional_widget_kwargs = additional_widget_kwargs if additional_widget_kwargs else {}
collection = omni.ui.RadioCollection(model=model)
vertical = cls._get_setting(setting_path, "vertical", False)
for item in model.items:
stack = omni.ui.VStack() if vertical else omni.ui.HStack()
with stack:
_create_radio_button(collection)
return collection
@classmethod
def createComboboxWidget(
cls, setting_path: str, items: Union[list, dict, None] = None, setting_is_index: bool = True, additional_widget_kwargs: dict = None
) -> Tuple[SettingsComboItemModel, ui.ComboBox]:
"""
Creating a Combo Setting widget.
This function creates a combo box that shows a provided list of names and it is connected with setting by path
specified. Underlying setting values are used from values of `items` dict.
Args:
setting_path: Path to the setting to show and edit.
items: Can be either :py:obj:`dict` or :py:obj:`list`. For :py:obj:`dict` keys are UI displayed names, values are
actual values set into settings. If it is a :py:obj:`list` UI displayed names are equal to setting values.
setting_is_index:
True - setting_path value is index into items list (default)
False - setting_path value is string in items list
"""
name_to_value = None
# Get items from toml settings
if items is None:
items = cls._get_setting(setting_path, "items", [])
# if we have a list, we want to synthesize a dict of type label: index
if isinstance(items, list):
# TODO: WE should probably check the type of the target attribute before deciding what to do here
name_to_value = collections.OrderedDict(zip(items, range(0, len(items))))
elif isinstance(items, dict):
name_to_value = items
else:
carb.log_error(f"Unsupported type {type(items)} for items in create_setting_widget_combo")
return None
model = SettingsComboItemModel(setting_path, name_to_value, setting_is_index)
widget = ui.ComboBox(model)
# OM-91518: Fixed double slash in it's xpath as shown in inspector
widget.identifier = setting_path.replace("/", "_")
return widget, model
class AssetPicker:
def _on_file_pick(self, dialog, filename: str, dirname: str):
"""
when a file or folder is selected in the dialog
"""
path = ""
if dirname:
if self.is_folder:
path = f"{dirname}"
else:
path = f"{dirname}/{filename}"
elif filename:
path = filename
self.model.set_value(path)
dialog.hide()
@classmethod
def get_icon_path(cls):
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
icon_path = Path(extension_path).joinpath("data").joinpath("icons")
return icon_path
def __init__(self, model):
self.model = model
self.item_filter_options = ["All Files (*)"]
self.is_folder = False
def on_show_dialog(self, model, item_filter_options):
try:
from omni.kit.window.filepicker import FilePickerDialog
heading = "Select Folder..." if self.is_folder else "Select File.."
dialog = FilePickerDialog(
heading,
apply_button_label="Select",
click_apply_handler=lambda filename, dirname: self._on_file_pick(dialog, filename, dirname),
item_filter_options=item_filter_options,
)
dialog.show()
except:
carb.log_warn(f"Failed to import omni.kit.window.filepicker")
pass
def build_ui(self, additional_widget_kwargs=None):
with ui.HStack():
def assign_value(model, path: omni.ui.WidgetMouseDropEvent):
model.set_value(path.mime_data)
def drop_accept(url: str):
# TODO support filtering by file extension
if "." not in url:
# TODO dragging from stage view also result in a drop, which is a prim path not an asset path
# For now just check if dot presents in the url (indicating file extension).
return False
return True
with ui.ZStack():
widget_kwargs = {"name": "models", "model": self.model}
if additional_widget_kwargs:
widget_kwargs.update(additional_widget_kwargs)
value_widget = ui.StringField(**widget_kwargs)
value_widget.identifier = "AssetPicker_path"
# Drag and Drop behaviour
value_widget.set_accept_drop_fn(drop_accept)
assign_value_p = partial(assign_value, self.model)
value_widget.set_drop_fn(assign_value_p)
ui.Spacer(width=3)
style = {"image_url": str(self.get_icon_path().joinpath("small_folder.png"))}
heading = "Select Folder..." if self.is_folder else "Select File.."
ui.Button(
style=style,
width=20,
tooltip="Browse...",
clicked_fn=lambda model=self.model: self.on_show_dialog(model, self.item_filter_options),
identifier="AssetPicker_select"
)
ui.Spacer(width=3)
# Button to jump to the file in Content Window
def locate_file(model):
print("locate file")
# omni.kit.window.content_browser is an optional dependency
try:
url = model.get_resolved_path()
if len(url) == 0:
print("Returning...")
return
from omni.kit.window.content_browser import get_content_window
instance = get_content_window()
if instance:
instance.navigate_to(url)
else:
carb.log_warn(f"Failed to import omni.kit.window.content_browser")
except Exception as e:
carb.log_warn(f"Failed to locate file: {e}")
style["image_url"] = str(self.get_icon_path().joinpath("find.png"))
ui.Button(
style=style, width=20, tooltip="Locate File", clicked_fn=lambda model=self.model: locate_file(model),
identifier="AssetPicker_locate"
)
|
omniverse-code/kit/exts/omni.kit.widget.settings/omni/kit/widget/settings/settings_model.py | from typing import Any, Dict, Union
import carb
import carb.dictionary
import carb.settings
import omni.kit.commands
import omni.ui as ui
def update_reset_button(settingModel):
"""
work out whether to show the reset button highlighted or not depending on whether the setting
is set to it's default value
"""
if not settingModel._reset_button:
return
# This lookup of rtx-defaults involves some other extension having copied
# the data from /rtx to /rtx-defaults..
default_path = settingModel._path.replace("/rtx/", "/rtx-defaults/")
item = settingModel._settings.get_settings_dictionary(default_path)
if item is not None:
if settingModel._settings.get(settingModel._path) == settingModel._settings.get(default_path):
settingModel._reset_button.visible = False
else:
settingModel._reset_button.visible = True
else: # pragma: no cover
carb.log_info(f"update_reset_button: \"{default_path}\" not found")
class SettingModel(ui.AbstractValueModel):
"""
Model for simple scalar/POD carb.settings
"""
def __init__(self, setting_path: str, draggable: bool = False):
"""
Args:
setting_path: setting_path carb setting to create a model for
draggable: is it a numeric value you will drag in the UI?
"""
ui.AbstractValueModel.__init__(self)
self._settings = carb.settings.get_settings()
self._dictionary = carb.dictionary.get_dictionary()
self._path = setting_path
self.draggable = draggable
self.initialValue = None
self._reset_button = None
self._editing = False
self._range_set = False
self._min = None
self._max = None
self._update_setting = omni.kit.app.SettingChangeSubscription(self._path, self._on_change)
def set_range(self, min_val, max_val):
'''
set the allowable range for the setting. This is more restrictive than the UI min/max setting
which still lets you set out of range values using the keyboard (e.g click and type in slider)
'''
self._range_set = True
self._min = min_val
self._max = max_val
def _on_change(owner, value, event_type) -> None:
if event_type == carb.settings.ChangeEventType.CHANGED:
owner._on_dirty()
if owner._editing == False:
owner._update_reset_button()
def begin_edit(self) -> None:
self._editing = True
ui.AbstractValueModel.begin_edit(self)
self.initialValue = self._settings.get(self._path)
if self.initialValue is None: # pragma: no cover
carb.log_warn(f"a value for setting {self._path} has been requested but is not available")
def end_edit(self) -> None:
ui.AbstractValueModel.end_edit(self)
value = self._settings.get(self._path)
if value is None: # pragma: no cover
carb.log_warn(f"a value for setting {self._path} has been requested but is not available")
omni.kit.commands.execute(
"ChangeSetting", path=self._path, value=value, prev=self.initialValue
)
self._update_reset_button()
self._editing = False
def _get_value(self):
value = self._settings.get(self._path)
if value is None: # pragma: no cover
carb.log_warn(f"a value for setting {self._path} has been requested but is not available")
return value
def get_value(self):
return self._get_value()
def get_value_as_string(self) -> str:
return self._get_value()
def get_value_as_float(self) -> float:
return self._get_value()
def get_value_as_bool(self) -> bool:
return self._get_value()
def get_value_as_int(self) -> int:
return self._get_value()
def set_value(self, value: Any):
if self._range_set and (value < self._min or value > self._max):
#print(f"not changing value to {value} as it's outside the range {self._min}-{self._max}")
return
if not self.draggable:
omni.kit.commands.execute("ChangeSetting", path=self._path, value=value)
update_reset_button(self)
self._on_dirty()
else:
omni.kit.commands.execute("ChangeDraggableSetting", path=self._path, value=value)
def _update_reset_button(self):
update_reset_button(self)
def set_reset_button(self, button: ui.Rectangle):
self._reset_button = button
update_reset_button(self)
def _on_dirty(self):
# Tell the widgets that the model value has changed
self._value_changed()
def destroy(self): # pragma: no cover
self._reset_button = None
self._update_setting = None
class RadioButtonSettingModel(ui.SimpleStringModel):
"""Model for simple RadioButton widget. The setting value and options are strings."""
def __init__(self, setting_path: str):
"""
Args:
setting_path: Carb setting path to create a model for.
RadioButton items are specified in carb.settings "{setting_path}/items"
"""
super().__init__()
self._settings = carb.settings.get_settings()
self._dictionary = carb.dictionary.get_dictionary()
self._setting_path = setting_path
self._items = None
self._reset_button = None
self._editing = False
# This sets the index to the current value of the setting, we can't always assume 0th/first
self._on_setting_change(self, carb.settings.ChangeEventType.CHANGED)
self.add_value_changed_fn(self._value_changed)
self._update_setting = omni.kit.app.SettingChangeSubscription(self.setting_path, self._on_setting_change)
@property
def setting_path(self):
return self._setting_path
@property
def items(self) -> tuple:
return self._items if self._items is not None else self._get_items()
def set_reset_button(self, button: ui.Rectangle):
self._reset_button = button
update_reset_button(self)
def _update_reset_button(self):
update_reset_button(self)
def _execute_kit_change_setting_command(self, value, previous_value=None):
kwargs = {"value": value, "path": self.setting_path}
if isinstance(previous_value, int):
kwargs["prev"] = previous_value
omni.kit.commands.execute("ChangeSetting", **kwargs)
def _on_setting_change(self, _: carb.dictionary.Item, event_type):
"""
This gets called this if:
+ Something else changes the setting (e.g an undo command)
+ We also use as a debugging tool to make sure things were changed..
Args:
_ (carb.dictionary.Item): Not used here.
event_type: use to filter
"""
if event_type != carb.settings.ChangeEventType.CHANGED:
return
value = self._settings.get(self.setting_path)
self.set_value(value, update_setting=False)
self._update_reset_button()
def _value_changed(self, model):
self.set_value(self.get_value_as_string())
def get_value(self) -> str:
"""Return current selected item string/label."""
return self.get_value_as_string()
def set_value(self, value: Union[int, str], update_setting: bool = True):
"""Set given value as current selected
Args:
value (int|str): Value to set. It can be either an int (index) or a string (label)
Kwargs:
update_setting (bool): Update corresponding carb.setting. Default True.
"""
if isinstance(value, int):
value = self.items[value]
super().set_value(value)
if update_setting:
self._execute_kit_change_setting_command(value)
update_reset_button(self)
def get_value_as_int(self) -> int:
"""Return current selected item idx."""
value = self.get_value()
try:
idx = self.items.index(value)
except ValueError:
idx = -1
return idx
def _get_items(self) -> tuple:
"""Return radiobutton items from carb.settings."""
setting_path = self.setting_path.split("/")[:-1]
setting_path.append("items")
setting_path = "/".join(setting_path)
self._itmes = tuple(self._settings.get(setting_path) or [])
return self._itmes
class AssetPathSettingsModel(SettingModel):
def get_resolved_path(self):
# @TODO: do I need to add in some kind of URI Resolution here?
return self.get_value_as_string()
class VectorFloatComponentModel(ui.SimpleFloatModel):
def __init__(self, parent, vec_index, immediate_mode):
super().__init__()
self.parent = parent
self.vec_index = vec_index
self.immediate_mode = immediate_mode
def get_value_as_float(self):
# The SimpleFloatModel class is storing a simple float value which works with get/set, so lets use that
if not self.immediate_mode:
return super().get_value_as_float()
val = self.parent._settings.get(self.parent._path)
# NOTE: Not sure why, but sometimes val can be a 2 float rather than a 3
if val is not None and len(val) > self.vec_index:
return val[self.vec_index]
return 0.0
def set_value(self, val):
super().set_value(val) # If this isn't here, any callbacks won't get called
# As the change occurs, set the setting immediately so any client (e.g the viewport) see it instantly
if self.immediate_mode:
vec = self.parent._settings.get(self.parent._path)
vec[self.vec_index] = val
self.parent._settings.set(self.parent._path, vec)
class VectorIntComponentModel(ui.SimpleIntModel):
def __init__(self, parent, vec_index, immediate_mode):
super().__init__()
self.parent = parent
self.vec_index = vec_index
self.immediate_mode = immediate_mode
def get_value_as_int(self):
# The SimpleIntModel class is storing a simple int value which works with get/set, so lets use that
if not self.immediate_mode:
return super().get_value_as_int()
val = self.parent._settings.get(self.parent._path)
# NOTE: Not sure why, but sometimes val can be a 2 int rather than a 3
if len(val) > self.vec_index:
return val[self.vec_index]
return 0
def set_value(self, val):
super().set_value(val) # If this isn't here, any callbacks won't get called
# As the change occurs, set the setting immediately so any client (e.g the viewport) see it instantly
if self.immediate_mode:
vec = self.parent._settings.get(self.parent._path)
vec[self.vec_index] = val
self.parent._settings.set(self.parent._path, vec)
class VectorSettingsModel(ui.AbstractItemModel):
"""
Model For Color, Vec3 and other multi-component settings
Assumption is the items are draggable, so we only store a command when the dragging has completed.
TODO: Needs testing with component_count = 2,4
"""
def __init__(self, setting_path: str, component_count: int, item_class: ui.AbstractItemModel, immediate_mode: bool):
"""
Args:
setting_path: setting_path carb setting to create a model for
component_count: how many elements does the setting have?
immediate_mode: do we update the underlying setting immediately, or wait for endEdit
"""
ui.AbstractItemModel.__init__(self)
self._comp_count = component_count
self._path = setting_path
self._settings = carb.settings.get_settings()
self._dictionary = carb.dictionary.get_dictionary()
self._dirty = False
self._reset_button = None
class VectorItem(ui.AbstractItem):
def __init__(self, model):
super().__init__()
self.model = model
# Create one model per component
self._items = [VectorItem(item_class(self, i, immediate_mode)) for i in range(self._comp_count)]
for item in self._items:
# Tell the parent model when the submodel changes the value
item.model.add_value_changed_fn(lambda a, item=item: self._item_changed(item))
# These cause the component-wise R,G,B sliders to log a change command
item.model.add_begin_edit_fn(lambda a, item=item: self.begin_edit(item))
item.model.add_end_edit_fn(lambda a, item=item: self.end_edit(item))
def _on_change(owner, item: carb.dictionary._dictionary.Item, event_type: carb.settings.ChangeEventType):
"""
when an undo, reset_to_default or other change to the setting happens outside this model
update the component child models
"""
if event_type == carb.settings.ChangeEventType.CHANGED and not owner._dirty:
owner._item_changed(None)
owner._update_reset_button()
def get_item_children(self, item: ui.AbstractItem = None):
"""
this is called by the widget when it needs the submodel items
"""
if item is None:
return self._items
return super().get_item_children(item)
def get_item_value_model(self, sub_model_item: ui.AbstractItem = None, column_id: int = 0):
"""
this is called by the widget when it needs the submodel item models
(to then get or set them)
"""
if sub_model_item is None:
return self._items[column_id].model
return sub_model_item.model
def begin_edit(self, item: ui.AbstractItem):
"""
TODO: if we don't add even a dummy implementation we get crashes
"""
lambda: None
def set_reset_button(self, button: ui.Rectangle):
self._reset_button = button
update_reset_button(self)
def _update_reset_button(self):
update_reset_button(self)
def end_edit(self, item):
pass
def destroy(self): # pragma: no cover
self._update_setting = None
self._root_model = None
self._on_change = None
self._reset_button = None
def set_value(self, values: Union[tuple, list]):
"""Set list of values to the model."""
for idx, child_item in enumerate(self.get_item_children()):
child_item.model.set_value(values[idx])
class VectorFloatSettingsModel(VectorSettingsModel):
def __init__(self, setting_path: str, component_count: int, immediate_mode: bool = True):
super().__init__(setting_path, component_count, VectorFloatComponentModel, immediate_mode)
# Register change event when the underlying setting changes.. but make sure start off with the correct
# Setting also..
dict1 = carb.dictionary.acquire_dictionary_interface()
arint_item = dict1.create_item(None, "", carb.dictionary.ItemType.DICTIONARY)
value = self._settings.get(self._path)
if value is None:
carb.log_warn(f"a value for setting {self._path} has been requested but is not available")
if value is not None:
dict1.set_float_array(arint_item, value)
self._on_change(arint_item, carb.settings.ChangeEventType.CHANGED)
self._update_setting = omni.kit.app.SettingChangeSubscription(self._path, self._on_change)
def end_edit(self, item):
old_dirty = self._dirty
self._dirty = True # Use to stop _on_change running
vector = [item.model.get_value_as_float() for item in self._items]
if vector:
omni.kit.commands.execute("ChangeSetting", path=self._path, value=vector)
self._update_reset_button()
self._dirty = old_dirty
def get_value(self) -> tuple:
"""Return current float values tuple."""
values = []
for child_item in self.get_item_children():
values.append(child_item.model.get_value_as_float())
return tuple(values)
class VectorIntSettingsModel(VectorSettingsModel):
def __init__(self, setting_path: str, component_count: int, immediate_mode: bool = True):
super().__init__(setting_path, component_count, VectorIntComponentModel, immediate_mode)
# Register change event when the underlying setting changes.. but make sure start off with the correct
# Setting also..
dict1 = carb.dictionary.acquire_dictionary_interface()
arint_item = dict1.create_item(None, "", carb.dictionary.ItemType.DICTIONARY)
value = self._settings.get(self._path)
if value is None:
carb.log_warn(f"a value for setting {self._path} has been requested but is not available")
dict1.set_int_array(arint_item, value)
self._on_change(arint_item, carb.settings.ChangeEventType.CHANGED)
self._update_setting = omni.kit.app.SettingChangeSubscription(self._path, self._on_change)
def end_edit(self, item):
old_dirty = self._dirty
self._dirty = True # Use to stop _on_change running
vector = [item.model.get_value_as_float() for item in self._items]
if vector:
omni.kit.commands.execute("ChangeSetting", path=self._path, value=vector)
self._update_reset_button()
self._dirty = old_dirty
def get_value(self) -> tuple:
"""Return current int values tuple."""
values = []
for child_item in self.get_item_children():
values.append(child_item.model.get_value_as_int())
return tuple(values)
class SettingsComboValueModel(ui.AbstractValueModel):
"""
Model to store a pair (label, value of arbitrary type) for use in a ComboBox
"""
def __init__(self, label: str, value: Any):
"""
Args:
label: what appears in the UI widget
value: the value corresponding to that label
"""
ui.AbstractValueModel.__init__(self)
self.label = label
self.value = value
def __repr__(self):
return f'"SettingsComboValueModel label:{self.label} value:{self.value}"'
def get_value_as_string(self) -> str:
"""
this is called to get the label of the combo box item
"""
return self.label
def get_setting_value(self) -> Union[str, int]:
"""
we call this to get the value of the combo box item
"""
return self.value
class SettingsComboNameValueItem(ui.AbstractItem):
def __init__(self, label: str, value: str):
super().__init__()
self.model = SettingsComboValueModel(label, value)
def __repr__(self):
return f'"SettingsComboNameValueItem {self.model}"'
class SettingsComboItemModel(ui.AbstractItemModel):
"""
Model for a combo box - for each setting we have a dictionary of key, values
"""
def __init__(self, setting_path, key_value_pairs: Dict[str, Any], setting_is_index: bool = True):
super().__init__()
self._settings = carb.settings.get_settings()
self._dictionary = carb.dictionary.get_dictionary()
self._setting_is_index = setting_is_index
self._path = setting_path
self._reset_button = None
self._items = []
for x, y in key_value_pairs.items():
self._items.append(SettingsComboNameValueItem(x, y))
self._current_index = ui.SimpleIntModel()
self._prev_index_val = self._current_index.as_int
# This sets the index to the current value of the setting, we can't always assume 0th/first
self._on_setting_change(self, carb.settings.ChangeEventType.CHANGED)
self._current_index.add_value_changed_fn(self._current_index_changed)
self._update_setting = omni.kit.app.SettingChangeSubscription(self._path, self._on_setting_change)
self._dirty = True
def _update_reset_button(self):
update_reset_button(self)
def _on_setting_change(owner, item: carb.dictionary.Item, event_type):
"""
This gets called this if:
+ Something else changes the setting (e.g an undo command)
+ We also use as a debugging tool to make sure things were changed..
Args:
owner: will be an instance of SettingsComboItemModel
item: ?
event_type: use to filter
"""
# TODO: should be able to extract the value from the item, but not sure how
value = owner._settings.get(owner._path)
if event_type == carb.settings.ChangeEventType.CHANGED:
# We need to back track from the value to the index of the item that contains it
index = -1
for i in range(0, len(owner._items)):
if owner._setting_is_index and owner._items[i].model.value == value:
index = i
elif owner._items[i].model.label == value:
index = i
if index != -1 and owner._current_index.as_int != index:
owner._dirty = False
owner._current_index.set_value(index)
owner._item_changed(None)
owner._dirty = True
owner._update_reset_button()
def _current_index_changed(self, model):
if self._dirty:
self._item_changed(None)
if self._setting_is_index:
new_value = self._items[model.as_int].model.get_setting_value()
old_value = self._items[self._prev_index_val].model.get_setting_value()
else:
new_value = self._items[model.as_int].model.get_value_as_string()
old_value = self._items[self._prev_index_val].model.get_value_as_string()
self._prev_index_val = model.as_int
omni.kit.commands.execute("ChangeSetting", path=self._path, value=new_value, prev=old_value)
self._update_reset_button()
def set_items(self, key_value_pairs: Dict[str, Any]):
self._items.clear()
for x, y in key_value_pairs.items():
self._items.append(SettingsComboNameValueItem(x, y))
self._item_changed(None)
self._dirty = True
def set_reset_button(self, button: ui.Rectangle):
self._reset_button = button
update_reset_button(self)
def get_item_children(self, item: ui.AbstractItem = None):
"""
this is called by the widget when it needs the submodel items
"""
if item is None:
return self._items
return super().get_item_children(item)
def get_item_value_model(self, item: ui.AbstractItem = None, column_id: int = 0):
if item is None:
return self._current_index
return item.model
def get_value_as_int(self) -> int:
"""Get current selected item index
Return:
(int) Current selected item index
"""
return self._current_index.get_value_as_int()
def get_value_as_string(self) -> str:
"""Get current selected item string/label
Return:
(str) Current selected item label string.
"""
return self._items[self.get_value_as_int()].model.get_value_as_string()
def get_value(self) -> Union[int, str]:
"""Get current selected item label string or index value.
Return:
(int|str) Current selected item label string or index value depends
on the self._setting_is_index attribute.
"""
return self.get_value_as_int if self._setting_is_index else self.get_value_as_string()
def set_value(self, value: Union[int, str]):
"""Set current selected to given value
Arg:
value (int|str): The value to set.
"""
value = 0
if not isinstance(value, int):
try:
value = self._items.index(value)
except IndexError:
pass
self._current_index.set_value(value)
def destroy(self): # pragma: no cover
self._update_setting = None
self._reset_button = None
|
omniverse-code/kit/exts/omni.kit.widget.settings/omni/kit/widget/settings/deprecated/__init__.py | """Settings Omniverse Kit API
Module to work with **Settings** in the Kit. It is built on top of ``carb.settings`` generic setting system.
Example code to create :class:`omni.kit.ui.Widget` to show and edit particular setting:
>>> import omni.kit.settings
>>> import omni.kit.ui
>>> widget = omni.kit.settings.create_setting_widget("some/path/to/param", SettingType.FLOAT)
"""
from .ui import SettingType, create_setting_widget, create_setting_widget_combo
from .model import UiModel, get_ui_model
|
omniverse-code/kit/exts/omni.kit.widget.settings/omni/kit/widget/settings/deprecated/model.py | import typing
import carb
import carb.settings
import carb.dictionary
import carb.events
import omni.kit.ui
import omni.kit.commands
import omni.kit.app
class ChangeGroup:
def __init__(self, direct_set=False):
self.path = None
self.value = None
self.info = None
self.direct_set = direct_set
def _set_path(self, path):
if self.path is None:
self.path = path
elif self.path != path:
carb.log_error(f"grouped change with different path: {self.path} != {path}")
return False
return True
def set_array_size(self, path, size, info):
if self._set_path(path):
# add resize
self.value = [None] * size
self.info = info
def set_value(self, path, value, index, info):
if self._set_path(path):
if isinstance(self.value, list):
self.value[index] = value
else:
self.value = value
self.info = info
def apply(self, model):
prev_value = model._settings.get(self.path)
new_value = self.value
if isinstance(new_value, str):
pass
elif hasattr(new_value, "__getitem__"):
new_value = tuple(new_value)
if isinstance(new_value, str) and isinstance(prev_value, int):
try:
new_value = int(new_value)
except ValueError:
pass
if self.info.transient:
if self.path not in model._prev_values:
model._prev_values[self.path] = prev_value
model._settings.set(self.path, new_value)
else:
undo_value = model._prev_values.pop(self.path, prev_value)
if self.direct_set:
model._settings.set(self.path, new_value)
else:
omni.kit.commands.execute("ChangeSetting", path=self.path, value=new_value, prev=undo_value)
class UiModel(omni.kit.ui.Model):
def __init__(self, direct_set=False):
omni.kit.ui.Model.__init__(self)
self._subs = {}
self._prev_values = {}
self._change_group = None
self._settings = carb.settings.get_settings()
self._dictionary = carb.dictionary.get_dictionary()
self._direct_set = direct_set
self._change_group_refcount = 0
self._TYPE_MAPPER = {}
self._TYPE_MAPPER[carb.dictionary.ItemType.BOOL] = omni.kit.ui.ModelNodeType.BOOL
self._TYPE_MAPPER[carb.dictionary.ItemType.INT] = omni.kit.ui.ModelNodeType.NUMBER
self._TYPE_MAPPER[carb.dictionary.ItemType.FLOAT] = omni.kit.ui.ModelNodeType.NUMBER
self._TYPE_MAPPER[carb.dictionary.ItemType.STRING] = omni.kit.ui.ModelNodeType.STRING
self._TYPE_MAPPER[carb.dictionary.ItemType.DICTIONARY] = omni.kit.ui.ModelNodeType.OBJECT
self._TYPE_MAPPER[carb.dictionary.ItemType.COUNT] = omni.kit.ui.ModelNodeType.UNKNOWN
def _get_sanitized_path(self, path):
if path is not None and len(path) > 0 and path[0] == "/":
return path[1:]
return ""
def _is_array(item):
# Hacky way and get_keys() call is slow
if len(item) > 0 and "0" in item.get_keys():
v = item["0"]
return isinstance(v, int) or isinstance(v, float) or isinstance(v, bool) or isinstance(v, str)
return False
def get_type(self, path, meta):
settings_dict = self._settings.get_settings_dictionary("")
path = self._get_sanitized_path(path)
item = self._dictionary.get_item(settings_dict, path)
item_type = self._dictionary.get_item_type(item)
if item_type == carb.dictionary.ItemType.DICTIONARY:
if UiModel._is_array(item):
return omni.kit.ui.ModelNodeType.ARRAY
return self._TYPE_MAPPER[item_type]
def get_array_size(self, path, meta):
settings_dict = self._settings.get_settings_dictionary("")
path = self._get_sanitized_path(path)
item = self._dictionary.get_item(settings_dict, path)
item_type = self._dictionary.get_item_type(item)
if item_type == carb.dictionary.ItemType.DICTIONARY:
if UiModel._is_array(item):
return len(item)
return 0
def get_value(self, path, meta, index, is_time_sampled, time):
if not meta:
value = self._settings.get(path)
if isinstance(value, str):
return value
elif hasattr(value, "__getitem__"):
return value[index]
else:
return value
else:
if meta == omni.kit.ui.MODEL_META_WIDGET_TYPE:
return self._get_widget_type_for_setting(path, index)
if meta == omni.kit.ui.MODEL_META_SERIALIZED_CONTENTS:
settings_item = self._settings.get(path)
return "%s" % (settings_item,)
return None
def begin_change_group(self):
if self._change_group_refcount == 0:
self._change_group = ChangeGroup(direct_set=self._direct_set)
self._change_group_refcount += 1
def end_change_group(self):
if self._change_group:
self._change_group_refcount -= 1
if self._change_group_refcount != 0:
return
self._change_group.apply(self)
self._change_group = None
def set_array_size(self, path, meta, size, is_time_sampled, time, info):
change = self._change_group if self._change_group else ChangeGroup(direct_set=self._direct_set)
change.set_array_size(path, size, info)
if not self._change_group:
change.apply(self)
def set_value(self, path, meta, value, index, is_time_sampled, time, info):
change = self._change_group if self._change_group else ChangeGroup(direct_set=self._direct_set)
change.set_value(path, value, index, info)
if not self._change_group:
change.apply(self)
def on_subscribe_to_change(self, path, meta, stream):
if path in self._subs:
return
def on_change(item, event_type, path=path):
self.signal_change(path)
self._subs[path] = omni.kit.app.SettingChangeSubscription(path, on_change)
def on_unsubscribe_to_change(self, path, meta, stream):
if path in self._subs:
del self._subs[path]
def get_key_count(self, path, meta):
settings_dict = self._settings.get_settings_dictionary("")
if len(path) > 0 and path[0] == "/":
path = path[1:]
parent_item = self._dictionary.get_item(settings_dict, path)
return self._dictionary.get_item_child_count(parent_item)
def get_key(self, path, meta, index):
settings_dict = self._settings.get_settings_dictionary("")
if len(path) > 0 and path[0] == "/":
path = path[1:]
parent_item = self._dictionary.get_item(settings_dict, path)
key_item = self._dictionary.get_item_child_by_index(parent_item, index)
return self._dictionary.get_item_name(key_item)
def _get_widget_type_for_setting(self, path, index):
settings_dict = self._settings.get_settings_dictionary("")
path = self._get_sanitized_path(path)
item = self._dictionary.get_item(settings_dict, path)
if UiModel._is_array(item):
size = len(item)
value = item["0"]
if size == 2 and isinstance(value, int):
return "DragInt2"
elif size == 2 and isinstance(value, float):
return "DragDouble2"
elif size == 3 and isinstance(value, float):
return "DragDouble3"
elif size == 4 and isinstance(value, float):
return "DragDouble4"
elif size == 16 and isinstance(value, float):
return "Transform"
return ""
def get_ui_model() -> UiModel:
"""Returns :class:`UiModel` singleton"""
if not hasattr(get_ui_model, "model"):
get_ui_model.model = UiModel(direct_set=False)
return get_ui_model.model
|
omniverse-code/kit/exts/omni.kit.widget.settings/omni/kit/widget/settings/deprecated/ui.py | import omni.kit.ui
import carb
import carb.dictionary
import carb.settings
import collections
from typing import Union, Callable
from . import model
class SettingType:
"""
Supported setting types
"""
FLOAT = 0
INT = 1
COLOR3 = 2
BOOL = 3
STRING = 4
DOUBLE3 = 5
INT2 = 6
DOUBLE2 = 7
def create_setting_widget(
setting_path: str, setting_type: SettingType, range_from=0, range_to=0, speed=1, **kwargs
) -> omni.kit.ui.Widget:
"""
Create a UI widget connected with a setting.
If ``range_from`` >= ``range_to`` there is no limit. Undo/redo operations are also supported, because changing setting
goes through the :mod:`omni.kit.commands` module, using :class:`.ChangeSettingCommand`.
Args:
setting_path: Path to the setting to show and edit.
setting_type: Type of the setting to expect.
range_from: Limit setting value lower bound.
range_to: Limit setting value upper bound.
Returns:
:class:`omni.kit.ui.Widget` connected with the setting on the path specified.
"""
# Create widget to be used for particular type
if setting_type == SettingType.INT:
widget = omni.kit.ui.DragInt("", min=range_from, max=range_to, drag_speed=speed, **kwargs)
elif setting_type == SettingType.FLOAT:
widget = omni.kit.ui.DragDouble("", min=range_from, max=range_to, drag_speed=speed, **kwargs)
elif setting_type == SettingType.BOOL:
widget = omni.kit.ui.CheckBox(**kwargs)
elif setting_type == SettingType.STRING:
widget = omni.kit.ui.TextBox("", **kwargs)
elif setting_type == SettingType.COLOR3:
widget = omni.kit.ui.ColorRgb("", **kwargs)
elif setting_type == SettingType.DOUBLE3:
widget = omni.kit.ui.DragDouble3("", min=range_from, max=range_to, drag_speed=speed, **kwargs)
elif setting_type == SettingType.INT2:
widget = omni.kit.ui.DragInt2("", min=range_from, max=range_to, drag_speed=speed, **kwargs)
elif setting_type == SettingType.DOUBLE2:
widget = omni.kit.ui.DragDouble2("", min=range_from, max=range_to, drag_speed=speed, **kwargs)
else:
return None
if isinstance(widget, omni.kit.ui.ModelWidget):
widget.set_model(model.get_ui_model(), setting_path)
return widget
def create_setting_widget_combo(setting_path: str, items: Union[list, dict]):
"""
Creating a Combo Setting widget.
This function creates a combo box that shows a provided list of names and it is connected with setting by path
specified. Underlying setting values are used from values of `items` dict.
Args:
setting_path: Path to the setting to show and edit.
items: Can be either :py:obj:`dict` or :py:obj:`list`. For :py:obj:`dict` keys are UI displayed names, values are
actual values set into settings. If it is a :py:obj:`list` UI displayed names are equal to setting values.
"""
if isinstance(items, list):
name_to_value = collections.OrderedDict(zip(items, items))
elif isinstance(items, dict):
name_to_value = items
else:
carb.log_error(f"Unsupported type {type(items)} for items in create_setting_widget_combo")
return None
if isinstance(next(iter(name_to_value.values())), int):
widget = omni.kit.ui.ComboBoxInt("", list(name_to_value.values()), list(name_to_value.keys()))
else:
widget = omni.kit.ui.ComboBox("", list(name_to_value.values()), list(name_to_value.keys()))
widget.set_model(model.get_ui_model(), setting_path)
return widget
|
omniverse-code/kit/exts/omni.kit.widget.settings/omni/kit/widget/settings/tests/test_model.py | import omni.kit.test
import carb.settings
from ..settings_model import VectorFloatSettingsModel, RadioButtonSettingModel
class TestModel(omni.kit.test.AsyncTestCase):
async def test_vector_model(self):
setting_name = "/rtx/pathtracing/maxBlah"
settings = carb.settings.get_settings()
initial_vals = (0.6, 0.7, 0.8)
settings.set(setting_name, initial_vals)
vector_model = VectorFloatSettingsModel(setting_name, 3, True)
# Lets simulate a bit of what the color widget would do when getting values
sub_items = vector_model.get_item_children(None)
for cnt, sub_item in enumerate(sub_items):
sub_model = vector_model.get_item_value_model(sub_item)
val = sub_model.get_value_as_float()
self.assertTrue(val == initial_vals[cnt])
# Lets check if things work when we change the value
new_vals = (0.5, 0.4, 0.3)
settings.set(setting_name, new_vals)
for cnt, sub_item in enumerate(sub_items):
sub_model = vector_model.get_item_value_model(sub_item)
val = sub_model.get_value_as_float()
self.assertTrue(val == new_vals[cnt])
# Let's set the value through the item model
new_vals = [0.1, 0.15, 0.2]
for cnt, sub_item in enumerate(sub_items):
sub_model = vector_model.get_item_value_model(sub_item)
val = sub_model.set_value(new_vals[cnt])
settings_val = settings.get(setting_name)
self.assertTrue(settings_val == new_vals)
# Let's set the value directly through the Vector model
new_vals = [0.2, 0.8, 0.9]
vector_model.set_value(new_vals)
settings_val = settings.get(setting_name)
self.assertTrue(settings_val == new_vals)
# TODO test begin_edit/end_edit
# TODO test other sizes (2, 4 components
# TODO test immediate mode on/off
async def test_radio_button_setting_model(self):
setting_value_path = "/ext/ui/settings/radiobutton/value"
setting_items_path = "/ext/ui/settings/radiobutton/items"
settings = carb.settings.get_settings()
initial_val = "option1"
items = ("option0", "option1", "option2", "option3")
settings.set(setting_value_path, initial_val)
settings.set(setting_items_path, items)
radio_button_model = RadioButtonSettingModel(setting_value_path)
# Lets check the initial_val and items
self.assertEqual(radio_button_model.items, items)
self.assertEqual(radio_button_model.get_value(), initial_val)
self.assertEqual(radio_button_model.get_value_as_int(), 1)
# Lets check if things work when we change the value
# Set as int
new_val = "option0"
radio_button_model.set_value(0)
self.assertEqual(radio_button_model.get_value(), new_val)
self.assertEqual(settings.get(setting_value_path), new_val)
self.assertEqual(radio_button_model.get_value_as_int(), 0)
# Set as str
new_val = "option2"
radio_button_model.set_value(new_val)
self.assertEqual(radio_button_model.get_value(), new_val)
self.assertEqual(settings.get(setting_value_path), new_val)
self.assertEqual(radio_button_model.get_value_as_int(), 2)
# Let's the the value through settings
new_val = "option3"
settings.set(setting_value_path, new_val)
self.assertEqual(radio_button_model.get_value(), new_val)
self.assertEqual(radio_button_model.get_value_as_int(), 3)
|
omniverse-code/kit/exts/omni.kit.widget.settings/omni/kit/widget/settings/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.
##
import os
from .test_settings import TestSettings
from .test_model import TestModel
|
omniverse-code/kit/exts/omni.kit.widget.settings/omni/kit/widget/settings/tests/test_settings.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 omni.kit.app
import omni.kit.test
import omni.ui as ui
import omni.kit.ui_test as ui_test
from omni.ui.tests.test_base import OmniUiTest
from pathlib import Path
from ..settings_widget import create_setting_widget, create_setting_widget_combo, SettingType, SettingsWidgetBuilder, SettingsSearchableCombo, SettingWidgetType
from ..settings_model import VectorFloatSettingsModel
from ..style import get_ui_style_name, get_style
PERSISTENT_SETTINGS_PREFIX = "/persistent"
class TestSettings(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
self._golden_img_dir = Path(extension_path).joinpath("data").joinpath("tests").joinpath("golden_img").absolute()
# create settings
carb.settings.get_settings().set_default_bool(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_bool", True)
carb.settings.get_settings().set_default_float(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_float", 1.0)
carb.settings.get_settings().set_default_int(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_int", 27)
carb.settings.get_settings().set_default_string(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_str", "test-test")
carb.settings.get_settings().set_float_array(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_color3", [1, 2, 3])
carb.settings.get_settings().set_float_array(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_double2", [1.5, 2.7])
carb.settings.get_settings().set_float_array(
PERSISTENT_SETTINGS_PREFIX + "/test/test/test_double3", [2.7, 1.5, 9.2]
)
carb.settings.get_settings().set_int_array(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_int2", [10, 13])
carb.settings.get_settings().set_default_string(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo1", "AAAAAA")
carb.settings.get_settings().set_default_string(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo2", "BBBBBB")
carb.settings.get_settings().set_default_string(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo3", "CCCCCC")
carb.settings.get_settings().set_default_string(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo4", "DDDDDD")
carb.settings.get_settings().set_default_string(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo5", "")
carb.settings.get_settings().set_default_string(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo6", "cheese")
carb.settings.get_settings().set_default_string("/rtx/test_asset", "/home/")
carb.settings.get_settings().set_default_string("/rtx-defaults/test_asset", "/home/")
carb.settings.get_settings().set_default_string(
PERSISTENT_SETTINGS_PREFIX + "/test/test/test_radiobutton/value",
"A"
)
carb.settings.get_settings().set_string_array(
PERSISTENT_SETTINGS_PREFIX + "/test/test/test_radiobutton/items",
["A", "B", "C", "D"]
)
# After running each test
async def tearDown(self):
await super().tearDown()
omni.kit.window.preferences.hide_preferences_window()
def _build_window(self, window):
with window.frame:
with ui.VStack(height=-0, style=get_style()):
with ui.CollapsableFrame(title="create_setting_widget"):
with ui.VStack():
with ui.HStack(height=24):
omni.ui.Label("bool", word_wrap=True, width=ui.Percent(35))
create_setting_widget(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_bool", SettingType.BOOL)
with ui.HStack(height=24):
omni.ui.Label("float", word_wrap=True, width=ui.Percent(35))
create_setting_widget(
PERSISTENT_SETTINGS_PREFIX + "/test/test/test_float", SettingType.FLOAT
)
with ui.HStack(height=24):
omni.ui.Label("int", word_wrap=True, width=ui.Percent(35))
create_setting_widget(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_int", SettingType.FLOAT)
with ui.HStack(height=24):
omni.ui.Label("string", word_wrap=True, width=ui.Percent(35))
create_setting_widget(
PERSISTENT_SETTINGS_PREFIX + "/test/test/test_str", SettingType.STRING
)
with ui.HStack(height=24):
omni.ui.Label("color3", word_wrap=True, width=ui.Percent(35))
create_setting_widget(
PERSISTENT_SETTINGS_PREFIX + "/test/test/test_color3", SettingType.COLOR3
)
with ui.HStack(height=24):
omni.ui.Label("double2", word_wrap=True, width=ui.Percent(35))
create_setting_widget(
PERSISTENT_SETTINGS_PREFIX + "/test/test/test_double2", SettingType.DOUBLE2
)
with ui.HStack(height=24):
omni.ui.Label("double3", word_wrap=True, width=ui.Percent(35))
create_setting_widget(
PERSISTENT_SETTINGS_PREFIX + "/test/test/test_double3", SettingType.DOUBLE3
)
with ui.HStack(height=24):
omni.ui.Label("int2", word_wrap=True, width=ui.Percent(35))
create_setting_widget(PERSISTENT_SETTINGS_PREFIX + "/test/test/test_int2", SettingType.INT2)
with ui.HStack(height=24):
omni.ui.Label("radiobutton", word_wrap=True, width=ui.Percent(35))
create_setting_widget(
PERSISTENT_SETTINGS_PREFIX + "/test/test/test_radiobutton/value",
SettingWidgetType.RADIOBUTTON
)
ui.Spacer(height=20)
with ui.CollapsableFrame(title="create_setting_widget_combo"):
with ui.VStack():
with ui.HStack(height=24):
omni.ui.Label("combo1", word_wrap=True, width=ui.Percent(35))
create_setting_widget_combo(
PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo1",
["AAAAAA", "BBBBBB", "CCCCCC", "DDDDDD"],
)
with ui.HStack(height=24):
omni.ui.Label("combo2", word_wrap=True, width=ui.Percent(35))
create_setting_widget_combo(
PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo2",
["AAAAAA", "BBBBBB", "CCCCCC", "DDDDDD"],
)
with ui.HStack(height=24):
omni.ui.Label("combo3", word_wrap=True, width=ui.Percent(35))
create_setting_widget_combo(
PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo3",
["AAAAAA", "BBBBBB", "CCCCCC", "DDDDDD"],
)
with ui.HStack(height=24):
omni.ui.Label("combo4", word_wrap=True, width=ui.Percent(35))
create_setting_widget_combo(
PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo4",
["AAAAAA", "BBBBBB", "CCCCCC", "DDDDDD"],
)
with ui.HStack(height=24):
omni.ui.Label("combo5", word_wrap=True, width=ui.Percent(35))
create_setting_widget_combo(
PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo5",
["AAAAAA", "BBBBBB", "CCCCCC", "DDDDDD"],
)
ui.Spacer(height=20)
with ui.CollapsableFrame(title="create_setting_widget_asset"):
with ui.VStack():
with ui.HStack(height=24):
path = "/rtx/test_asset"
omni.ui.Label("asset", word_wrap=True, width=ui.Percent(35))
widget, model = create_setting_widget(path, "ASSET")
ui.Spacer(width=4)
button = SettingsWidgetBuilder._build_reset_button(path)
model.set_reset_button(button)
ui.Spacer(height=20)
with ui.CollapsableFrame(title="create_searchable_widget_combo"):
with ui.VStack():
with ui.HStack(height=24):
path = PERSISTENT_SETTINGS_PREFIX + "/test/test/test_combo6"
SettingsWidgetBuilder._create_label("Searchable", path, "Search Me...")
widget = SettingsSearchableCombo(path, {"Whiskey": "whiskey", "Wine": "Wine", "plain": "Plain", "cheese": "Cheese", "juice": "Juice"}, "cheese")
# Test(s)
async def test_widgets_golden(self):
window = await self.create_test_window(width=300, height=600)
self._build_window(window)
await ui_test.human_delay(50)
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_widgets.png")
async def test_widget_ui(self):
window = ui.Window("Test Window", width=600, height=600)
self._build_window(window)
await ui_test.human_delay(10)
widget = ui_test.find("Test Window//Frame/**/StringField[*].identifier=='AssetPicker_path'")
widget.model.set_value("/cheese/")
await ui_test.human_delay(10)
await ui_test.find("Test Window//Frame/**/Rectangle[*].identifier=='/rtx/test_asset_reset'").click()
await ui_test.human_delay(10)
await ui_test.find("Test Window//Frame/**/Button[*].identifier=='AssetPicker_locate'").click()
await ui_test.human_delay(10)
await widget.input("my hovercraft is full of eels")
await ui_test.human_delay(10)
await ui_test.find("Test Window//Frame/**/Rectangle[*].identifier=='/rtx/test_asset_reset'").click()
await ui_test.human_delay(10)
# await ui_test.human_delay(1000)
async def test_show_pages(self):
omni.kit.window.preferences.show_preferences_window()
pages = omni.kit.window.preferences.get_page_list()
for page in pages:
omni.kit.window.preferences.select_page(page)
await ui_test.human_delay(50)
async def test_widget_types(self):
path = PERSISTENT_SETTINGS_PREFIX + "/test/test/test_widget_types"
# This is for catching a case that deprecated SettingType is given
widget, model = create_setting_widget(path, 5) # COLOR3
self.assertTrue(isinstance(model, VectorFloatSettingsModel))
# Test unsupported types
widget, model = create_setting_widget(path, None)
self.assertEqual((widget, model), (None, None))
|
omniverse-code/kit/exts/omni.kit.widget.settings/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.1] - 2022-06-23
### Changed
- Added identifier to create_setting_widget_combo for easier testing
## [1.0.0] - 2021-03-25
### Created
- Created as updated omni.kit.settings
|
omniverse-code/kit/exts/omni.kit.pipapi/omni/kit/pipapi/__init__.py | from .pipapi import *
|
omniverse-code/kit/exts/omni.kit.pipapi/omni/kit/pipapi/pipapi.py | """Pip Omniverse Kit API
Module to enable usage of ``pip install`` in Omniverse Kit environment. It wraps ``pip install`` calls and reroutes package installation into
user specified environment folder.
Package folder is selected from config string at path: `/app/omni.kit.pipapi/archiveDirs` and added into :mod:`sys.path`.
"""
__all__ = ["ExtensionManagerPip", "install", "call_pip", "remove_archive_directory", "add_archive_directory"]
import carb
import carb.profiler
import carb.settings
import carb.tokens
import omni.ext
import omni.kit.app
import importlib
import logging
import typing
import os
import json
import sys
from contextlib import contextmanager
from pathlib import Path
import functools
logger = logging.getLogger(__name__)
DEFAULT_ENV_PATH = "../../target-deps/pip3-envs/default"
CACHE_FILE_NAME = ".install_cache.json"
USE_INTERNAL_PIP = False
ALLOW_ONLINE_INDEX_KEY = "/exts/omni.kit.pipapi/allowOnlineIndex"
_user_env_path = ""
# pip additional dirs/links (pip install --find-links)
_archive_dirs = set()
_install_check_ignore_version = True
# print() instead of carb.log_info when this env var is set:
_debug_log = bool(os.getenv("OMNI_KIT_PIPAPI_DEBUG", default=False))
_attempted_to_upgrade_pip = False
_settings_iface = None
_started = False
# Temporary helper-decorator for profiling
def profile(f=None, mask=1, zone_name=None, add_args=True):
def profile_internal(f):
@functools.wraps(f)
def wrapper(*args, **kwds):
if zone_name is None:
active_zone_name = f.__name__
else:
active_zone_name = zone_name
if add_args:
active_zone_name += str(args) + str(kwds)
carb.profiler.begin(mask, active_zone_name)
try:
r = f(*args, **kwds)
finally:
carb.profiler.end(mask)
return r
return wrapper
if f is None:
return profile_internal
else:
return profile_internal(f)
def _get_setting(path, default=None):
# It can be called at import time during doc generation, enable that `_started` check:
if not _started:
return default
global _settings_iface
if not _settings_iface:
_settings_iface = carb.settings.get_settings()
setting = _settings_iface.get(path)
return setting if setting is not None else default
def _log_info(s):
s = f"[omni.kit.pipapi] {s}"
if _debug_log:
print(s)
else:
carb.log_info(s)
def _log_error(s):
logger.error(s)
@functools.lru_cache()
def _initialize():
env_path = _get_setting("/exts/omni.kit.pipapi/envPath")
env_path = carb.tokens.get_tokens_interface().resolve(env_path)
path = Path(env_path).resolve()
if not path.exists():
path.mkdir(parents=True)
global _user_env_path
_user_env_path = str(path)
import sys
global _install_check_ignore_version
_install_check_ignore_version = _get_setting("/exts/omni.kit.pipapi/installCheckIgnoreVersion", default=True)
global _attempted_to_upgrade_pip
_attempted_to_upgrade_pip = not _get_setting("/exts/omni.kit.pipapi/tryUpgradePipOnFirstUse", default=False)
global _archive_dirs
for archive_dir in _get_setting("/exts/omni.kit.pipapi/archiveDirs", default=[]):
add_archive_directory(archive_dir)
sys.path.append(_user_env_path)
_log_info(f"Python UserEnvPath: {_user_env_path}")
_load_cache()
@contextmanager
def _change_envvar(name: str, value: str):
"""Change environment variable for the execution block and then revert it back.
This function is a context manager.
Example:
.. code-block:: python
with _change_envvar("PYTHONPATH", "C:/hello"):
print(os.environ.get("PYTHONPATH"))
Args:
name (str): Env var to change.
value: new value
"""
old_value = os.environ.get(name, None)
os.environ[name] = value
try:
yield
finally:
if old_value is None:
del os.environ[name]
else:
os.environ[name] = old_value
def call_pip(args, surpress_output=False):
"""Call pip with given arguments.
Args:
args (list): list of arguments to pass to pip
surpress_output (bool): if True, surpress pip output
Returns:
int: return code of pip call"""
if USE_INTERNAL_PIP:
try:
from pip import main as pipmain
except:
from pip._internal import main as pipmain
return pipmain(args)
else:
import subprocess
with _change_envvar("PYTHONPATH", _user_env_path):
python_exe = "python.exe" if sys.platform == "win32" else "bin/python3"
cmd = [sys.prefix + "/" + python_exe, "-m", "pip"] + args
print("calling pip install: {}".format(" ".join(cmd)))
# Capture output and print it only if pip install failed:
p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
output, _ = p.communicate()
output = output.decode(errors="replace").replace("\r\n", "\n").replace("\r", "\n")
message = f"pip install returned {p.returncode}, output:\n{output}"
if p.returncode != 0 and not surpress_output:
print(message)
else:
carb.log_info(message)
return p.returncode
def add_archive_directory(path: str, root: str = None):
"""
Add pip additional dirs/links (for pip install --find-links).
"""
global _archive_dirs
path = carb.tokens.get_tokens_interface().resolve(path)
if not os.path.isabs(path) and root is not None:
path = os.path.join(root, path)
path = os.path.normcase(path)
_log_info(f"Add archive dir: '{path}'")
_archive_dirs.add(path)
def remove_archive_directory(path: str):
"""
Remove pip additional dirs/links.
"""
global _archive_dirs
_archive_dirs.remove(path)
def _try_import(module: str, log_error: bool = False):
try:
importlib.import_module(module)
except ImportError as e:
if log_error:
logger.error(f"Failed to import python module {module}. Error: {e}")
return False
return True
@profile
def install(
package: str,
module: str = None,
ignore_import_check: bool = False,
ignore_cache: bool = False,
version: str = None,
use_online_index: bool = True,
surpress_output: bool = False,
extra_args: typing.List[str] = None,
) -> bool:
"""
Install pacakage using pip into user specified env path. Install calls for particular package name persistently cache
to avoid overhead for future calls when package is already installed. Cache is stored in the `.install_cache.json` file in the user specified env path folder.
Args:
package(str): Package name to install. It is basically a command to pip install, it can include version and other flags.
module(str): Module name to import, by default module assumed to be equal to package.
ignore_import_check(bool, optional): If ``True`` ignore attempt to import module and call to ``pip`` anyway - can be slow.
ignore_cache(bool, optional): If ``True`` ignore caching and call to ``pip`` anyway - can be slow.
version (str, optional): Package version.
use_online_index(bool, optional): If ``True`` and package can't be found in any of archive directories try to use default pip index.
surpress_output(bool, optional): If ``True`` pip process output to stdout and stderr will be surpressed, as well as warning when install failed.
extra_args(List[str], optional): a list of extra arguments to pass to the Pip process
Returns:
``True`` if installation was successfull.
"""
_initialize()
# Support both install("foo==1.2.3") and install("foo", version="1.2.3") syntax
if "==" not in package and version:
package = f"{package}=={version}"
# By default module == package
if module is None:
module = package.split("==")[0]
# Trying to import beforehand saves a lot of time, because pip run takes long time even if package is already installed.
if not ignore_import_check and _try_import(module):
return True
# We have our own cache of install() calls saved into separate json file, that is the fastest early out.
if not ignore_cache and _is_in_cache(package):
return True
# Use now pkg_resources module to check if it was already installed. It checks that it was installed by other means,
# like just zipping packages and adding it to sys.path somewhere. That allows to check for package name instead of
# module (e.g. 'Pillow' instead of 'PIL'). We need to call explicitly on it to initialize and gather packages every time.
# Import it here instead of on the file root because it has long import time.
import pkg_resources
pkg_resources._initialize_master_working_set()
installed = {pkg.key for pkg in pkg_resources.working_set}
package_name = package.lower()
if _install_check_ignore_version:
package_name = package_name.split("==")[0]
if package_name in installed:
return True
# We are about to try installing, lets upgrade pip first (it will be done only once). Flag protects from recursion.
global _attempted_to_upgrade_pip
if not _attempted_to_upgrade_pip:
_attempted_to_upgrade_pip = True
install("--upgrade --no-index pip", ignore_import_check=True, use_online_index=False)
installed = False
common_args = ["--isolated", "install", "--target=" + _user_env_path]
if extra_args:
common_args.extend(extra_args)
common_args.extend(package.split())
for archive_dir in _archive_dirs:
_log_info(f"Attempting to install '{package}' from local acrhive: '{archive_dir}'")
rc = call_pip(
common_args + ["--no-index", f"--find-links={archive_dir}"],
surpress_output=(surpress_output or use_online_index),
)
if rc == 0:
importlib.invalidate_caches()
installed = True
break
if not installed and use_online_index:
allow_online = _get_setting(ALLOW_ONLINE_INDEX_KEY, default=True)
if allow_online:
_log_info(f"Attempting to install '{package}' from online index")
rc = call_pip(common_args, surpress_output=surpress_output)
if rc == 0:
importlib.invalidate_caches()
installed = True
else:
_log_error(
f"Attempting to install '{package}' from online index, while '{ALLOW_ONLINE_INDEX_KEY}' is set to false. That prevents from accidentally going to online index. Enable it if it is intentional."
)
if installed and not ignore_import_check:
installed = _try_import(module, log_error=True)
if installed:
_log_info(f"'{package}' was installed successfully.")
_add_to_cache(package)
else:
if not surpress_output:
logger.warning(f"'{package}' failed to install.")
return installed
_cached_install_calls_file = None
_cached_install_calls = {}
def _load_cache():
global _cached_install_calls
global _cached_install_calls_file
_cached_install_calls_file = Path(_user_env_path, CACHE_FILE_NAME)
try:
with _cached_install_calls_file.open("r") as f:
_cached_install_calls = json.load(f)
except (IOError, ValueError):
_cached_install_calls = {}
def _add_to_cache(package):
_cached_install_calls[package] = True
with _cached_install_calls_file.open("w") as f:
json.dump(_cached_install_calls, f)
def _is_in_cache(package) -> bool:
return package in _cached_install_calls
class ExtensionManagerPip(omni.ext.IExt):
def on_startup(self, ext_id):
# Hook in extension manager in "before extension enable" events if extension specifies "python/pipapi" config key.
manager = omni.kit.app.get_app().get_extension_manager()
self._hook = manager.get_hooks().create_extension_state_change_hook(
ExtensionManagerPip.on_before_ext_enabled,
omni.ext.ExtensionStateChangeType.BEFORE_EXTENSION_ENABLE,
ext_dict_path="python/pipapi",
hook_name="python.pipapi",
)
global _started
_started = True
@staticmethod
@profile(zone_name="pipapi hook", add_args=False)
def on_before_ext_enabled(ext_id: str, *_):
ExtensionManagerPip._process_ext_pipapi_config(ext_id)
@staticmethod
def _process_ext_pipapi_config(ext_id: str):
# Get extension config
manager = omni.kit.app.get_app().get_extension_manager()
d = manager.get_extension_dict(ext_id)
pip_dict = d.get("python", {}).get("pipapi", {})
# Add archive path. Relative path will be resolved relative to extension folder path.
for path in pip_dict.get("archiveDirs", []):
add_archive_directory(path, d["path"])
# Allows module names to be different to package names
modules = pip_dict.get("modules", [])
# Allows extra PIP repositores to be added
extra_args = []
for line in pip_dict.get("repositories", []):
extra_args.extend(["--extra-index-url", line])
# Allow extra args
extra_args += pip_dict.get("extra_args", [])
# Allow to ignore import check
ignore_import_check = pip_dict.get("ignore_import_check", False)
# Install packages (requirements)
use_online_index = pip_dict.get("use_online_index", False)
requirements = pip_dict.get("requirements", [])
if requirements:
# If use_online_index is not set, just ignore those entries. Otherwise they hide slowdowns on pip access for local only
# search, which is not really used currently.
if not use_online_index:
logger.warning(f"extension {ext_id} has a [python.pipapi] entry, but use_online_index=true is not set. It doesn't do anything and can be removed.")
return
for idx, line in enumerate(requirements):
module = modules[idx] if len(modules) > idx else None
install(line, module, extra_args=extra_args, use_online_index=use_online_index, ignore_import_check=ignore_import_check)
|
omniverse-code/kit/exts/omni.kit.pipapi/omni/kit/pipapi/tests/__init__.py | from .test_pipapi import *
|
omniverse-code/kit/exts/omni.kit.pipapi/omni/kit/pipapi/tests/test_pipapi.py | import omni.kit.test
import omni.kit.pipapi
class TestPipApi(omni.kit.test.AsyncTestCase):
async def test_pipapi_install(self):
# Install simple package and import it.
omni.kit.pipapi.install(
"toml", version="0.10.1", ignore_import_check=True, ignore_cache=True
) # SWIPAT filed under: http://nvbugs/3060676
import toml
self.assertIsNotNone(toml)
async def test_pipapi_install_non_existing(self):
res = omni.kit.pipapi.install("weird_package_name_2312515")
self.assertFalse(res)
|
omniverse-code/kit/exts/omni.ui/omni/ui/abstract_shade.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.
#
__all__ = ["AbstractShade"]
from . import _ui as ui
from collections import defaultdict
from typing import Any
from typing import Dict
from typing import Optional
import abc
import weakref
DEFAULT_SHADE = "default"
class AbstractShade(metaclass=abc.ABCMeta):
"""
The implementation of shades for custom style parameter type.
The user has to reimplement methods _store and _find to set/get the value
in the specific store.
"""
class _ShadeName(str):
"""An str-like object with a custom method to edit shade"""
def _keep_as_weak(self, shade: "AbstractShade"):
# Shade here is omni.ui.color or omni.ui.url. Weak pointer prevents
# circular references.
self.__weak_shade = weakref.ref(shade)
def add_shade(self, **kwargs):
"""Explicitly add additional color to the shade"""
shade = self.__weak_shade()
if not shade:
return
# Edit the shade
shade.shade(name=self, **kwargs)
def __init__(self):
# Avoid calling AbstractShade.__setattr__ that sets the color in the Store
super().__setattr__("_current_shade", DEFAULT_SHADE)
super().__setattr__("_shades", defaultdict(dict))
# The list of dependencides. Example `cl.shade(0x0, light="background")`
# makes dependency dict like this:
# `{"background": ("shade:0x0;light=background")}`
# We need it to update the shade once `background` is changed.
# TODO: Clear the dict when the shade is updated. Example: after
# `cl.bg = "red"; cl.bg = "green"` we will have two dependencies.
super().__setattr__("_dependencies", defaultdict(set))
def __getattr__(self, name: str):
# We need it for the syntax `style={"color": cl.bg_color}`
result = AbstractShade._ShadeName(name)
result._keep_as_weak(self)
return result
def __setattr__(self, name: str, value):
if name in self.__dict__:
# We are here because this class has the method variable. Set it.
super().__setattr__(name, value)
return
if isinstance(value, str) and value in self._shades:
# It's a shade. Redirect it to the coresponding method.
self.shade(name=name, **self._shades[value])
else:
# This class doesn't have this method variable. We need to set the
# value in the Store.
self.__set_value(name, {DEFAULT_SHADE: value})
def shade(self, default: Any = None, **kwargs) -> str:
"""Save the given shade, pick the color and apply it to ui.ColorStore."""
mangled_name = self.__mangle_name(default, kwargs, kwargs.pop("name", None))
shade = self._shades[mangled_name]
shade.update(kwargs)
if default is not None:
shade[DEFAULT_SHADE] = default
self.__set_value(mangled_name, shade)
return mangled_name
def set_shade(self, name: Optional[str] = None):
"""Set the default shade."""
if not name:
name = DEFAULT_SHADE
if name == self._current_shade:
return
self._current_shade = name
for value_name, shade in self._shades.items():
self.__set_value(value_name, shade)
def __mangle_name(self, default: Any, values: Dict[str, Any], name: Optional[str] = None) -> str:
"""Convert set of values to the shade name"""
if name:
return name
mangled_name = "shade:"
if isinstance(default, float) or isinstance(default, int):
mangled_name += str(default)
else:
mangled_name += default
for name in sorted(values.keys()):
value = values[name]
if mangled_name:
mangled_name += ";"
if isinstance(value, int):
value = str(value)
mangled_name += f"{name}={value}"
return mangled_name
def __set_value(self, name: str, shade: Dict[str, float]):
"""Pick the color from the given shade and set it to ui.ColorStore"""
# Save dependencies
for dependentName, dependentFloat in shade.items():
if isinstance(dependentFloat, str):
self._dependencies[dependentFloat].add(name)
value = shade.get(self._current_shade, shade.get(DEFAULT_SHADE))
if isinstance(value, str):
# It's named color. We need to resolve it from ColorStore.
found = self._find(value)
if found is not None:
value = found
self._store(name, value)
# Recursively replace all the values that refer to the current name
if name in self._dependencies:
for dependent in self._dependencies[name]:
shade = self._shades.get(dependent, None)
if shade:
value = shade.get(self._current_shade, shade.get(DEFAULT_SHADE))
if value == name:
self.__set_value(dependent, shade)
@abc.abstractmethod
def _find(self, name):
pass
@abc.abstractmethod
def _store(self, name, value):
pass
|
omniverse-code/kit/exts/omni.ui/omni/ui/scene.py | # WAR `import omni.ui.scene` failure when `omni.ui.scene` was not enabled.
# It happends during doc building, when running from python.bat, during stubgen, intellinse - anywhere that is not kit runtime
from omni.ui_scene.scene import *
|
omniverse-code/kit/exts/omni.ui/omni/ui/_ui.pyi | from __future__ import annotations
import omni.ui._ui
import typing
import carb._carb
import numpy
import omni.appwindow._appwindow
import omni.gpu_foundation_factory._gpu_foundation_factory
_Shape = typing.Tuple[int, ...]
__all__ = [
"AbstractField",
"AbstractItem",
"AbstractItemDelegate",
"AbstractItemModel",
"AbstractMultiField",
"AbstractSlider",
"AbstractValueModel",
"Alignment",
"ArrowHelper",
"ArrowType",
"Axis",
"BezierCurve",
"Button",
"ByteImageProvider",
"CanvasFrame",
"CheckBox",
"Circle",
"CircleSizePolicy",
"CollapsableFrame",
"ColorStore",
"ColorWidget",
"ComboBox",
"Container",
"CornerFlag",
"Direction",
"DockPolicy",
"DockPosition",
"DockPreference",
"DockSpace",
"DynamicTextureProvider",
"Ellipse",
"FillPolicy",
"FloatDrag",
"FloatField",
"FloatSlider",
"FloatStore",
"FocusPolicy",
"FontStyle",
"Fraction",
"Frame",
"FreeBezierCurve",
"FreeCircle",
"FreeEllipse",
"FreeLine",
"FreeRectangle",
"FreeTriangle",
"Grid",
"HGrid",
"HStack",
"Image",
"ImageProvider",
"ImageWithProvider",
"Inspector",
"IntDrag",
"IntField",
"IntSlider",
"InvisibleButton",
"ItemModelHelper",
"IwpFillPolicy",
"Label",
"Length",
"Line",
"MainWindow",
"Menu",
"MenuBar",
"MenuDelegate",
"MenuHelper",
"MenuItem",
"MenuItemCollection",
"MultiFloatDragField",
"MultiFloatField",
"MultiIntDragField",
"MultiIntField",
"MultiStringField",
"OffsetLine",
"Percent",
"Pixel",
"Placer",
"Plot",
"ProgressBar",
"RadioButton",
"RadioCollection",
"RasterImageProvider",
"RasterPolicy",
"Rectangle",
"ScrollBarPolicy",
"ScrollingFrame",
"Separator",
"ShadowFlag",
"Shape",
"SimpleBoolModel",
"SimpleFloatModel",
"SimpleIntModel",
"SimpleStringModel",
"SliderDrawMode",
"Spacer",
"Stack",
"StringField",
"StringStore",
"Style",
"ToolBar",
"ToolBarAxis",
"ToolButton",
"TreeView",
"Triangle",
"Type",
"UIntDrag",
"UIntSlider",
"UnitType",
"VGrid",
"VStack",
"ValueModelHelper",
"VectorImageProvider",
"WINDOW_FLAGS_FORCE_HORIZONTAL_SCROLLBAR",
"WINDOW_FLAGS_FORCE_VERTICAL_SCROLLBAR",
"WINDOW_FLAGS_MENU_BAR",
"WINDOW_FLAGS_MODAL",
"WINDOW_FLAGS_NONE",
"WINDOW_FLAGS_NO_BACKGROUND",
"WINDOW_FLAGS_NO_CLOSE",
"WINDOW_FLAGS_NO_COLLAPSE",
"WINDOW_FLAGS_NO_DOCKING",
"WINDOW_FLAGS_NO_FOCUS_ON_APPEARING",
"WINDOW_FLAGS_NO_MOUSE_INPUTS",
"WINDOW_FLAGS_NO_MOVE",
"WINDOW_FLAGS_NO_RESIZE",
"WINDOW_FLAGS_NO_SAVED_SETTINGS",
"WINDOW_FLAGS_NO_SCROLLBAR",
"WINDOW_FLAGS_NO_SCROLL_WITH_MOUSE",
"WINDOW_FLAGS_NO_TITLE_BAR",
"WINDOW_FLAGS_POPUP",
"WINDOW_FLAGS_SHOW_HORIZONTAL_SCROLLBAR",
"Widget",
"WidgetMouseDropEvent",
"Window",
"WindowHandle",
"Workspace",
"ZStack",
"dock_window_in_window",
"get_custom_glyph_code",
"get_main_window_height",
"get_main_window_width"
]
class AbstractField(Widget, ValueModelHelper):
"""
The abstract widget that is base for any field, which is a one-line text editor.
A field allows the user to enter and edit a single line of plain text. It's implemented using the model-view pattern and uses AbstractValueModel as the central component of the system.
"""
def focus_keyboard(self, focus: bool = True) -> None:
"""
Puts cursor to this field or removes focus if
focus
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class AbstractItem():
"""
The object that is associated with the data entity of the AbstractItemModel.
"""
def __init__(self) -> None: ...
pass
class AbstractItemDelegate():
"""
AbstractItemDelegate is used to generate widgets that display and edit data items from a model.
"""
def __init__(self) -> None:
"""
Constructs AbstractItemDelegate.
`kwargs : dict`
See below
### Keyword Arguments:
"""
def build_branch(self, model: AbstractItemModel, item: AbstractItem = None, column_id: int = 0, level: int = 0, expanded: bool = False) -> None:
"""
This pure abstract method must be reimplemented to generate custom collapse/expand button.
"""
def build_header(self, column_id: int = 0) -> None:
"""
This pure abstract method must be reimplemented to generate custom widgets for the header table.
"""
def build_widget(self, model: AbstractItemModel, item: AbstractItem = None, index: int = 0, level: int = 0, expanded: bool = False) -> None:
"""
This pure abstract method must be reimplemented to generate custom widgets for specific item in the model.
"""
pass
class AbstractItemModel():
"""
The central component of the item widget. It is the application's dynamic data structure, independent of the user interface, and it directly manages the nested data. It follows closely model-view pattern. It's abstract, and it defines the standard interface to be able to interoperate with the components of the model-view architecture. It is not supposed to be instantiated directly. Instead, the user should subclass it to create a new model.
The item model doesn't return the data itself. Instead, it returns the value model that can contain any data type and supports callbacks. Thus the client of the model can track the changes in both the item model and any value it holds.
From any item, the item model can get both the value model and the nested items. Therefore, the model is flexible to represent anything from color to complicated tree-table construction.
"""
def __init__(self) -> None:
"""
Constructs AbstractItemModel.
`kwargs : dict`
See below
### Keyword Arguments:
"""
def _item_changed(self, arg0: AbstractItem) -> None: ...
def add_begin_edit_fn(self, arg0: typing.Callable[[AbstractItemModel, AbstractItem], None]) -> int:
"""
Adds the function that will be called every time the user starts the editing.
The id of the callback that is used to remove the callback.
"""
def add_end_edit_fn(self, arg0: typing.Callable[[AbstractItemModel, AbstractItem], None]) -> int:
"""
Adds the function that will be called every time the user finishes the editing.
The id of the callback that is used to remove the callback.
"""
def add_item_changed_fn(self, arg0: typing.Callable[[AbstractItemModel, AbstractItem], None]) -> int:
"""
Adds the function that will be called every time the value changes.
The id of the callback that is used to remove the callback.
"""
def append_child_item(self, parentItem: AbstractItem, model: AbstractValueModel) -> AbstractItem:
"""
Creates a new item from the value model and appends it to the list of the children of the given item.
"""
def begin_edit(self, item: AbstractItem) -> None:
"""
Called when the user starts the editing. If it's a field, this method is called when the user activates the field and places the cursor inside.
"""
def can_item_have_children(self, parentItem: AbstractItem = None) -> bool:
"""
Returns true if the item can have children. In this way the delegate usually draws +/- icon.
### Arguments:
`id :`
The item to request children from. If it's null, the children of root will be returned.
"""
@typing.overload
def drop(self, item_tagget: AbstractItem, item_source: AbstractItem, drop_location: int = -1) -> None:
"""
Called when the user droped one item to another.
Small explanation why the same default value is declared in multiple places. We use the default value to be compatible with the previous API and especially with Stage 2.0. Thr signature in the old Python API is:
def drop(self, target_item, source)
drop(self, target_item, source)
PyAbstractItemModel::drop
AbstractItemModel.drop
pybind11::class_<AbstractItemModel>.def("drop")
AbstractItemModel
Called when the user droped a string to the item.
"""
@typing.overload
def drop(self, item_tagget: AbstractItem, source: str, drop_location: int = -1) -> None: ...
@typing.overload
def drop_accepted(self, item_tagget: AbstractItem, item_source: AbstractItem, drop_location: int = -1) -> bool:
"""
Called to determine if the model can perform drag and drop to the given item. If this method returns false, the widget shouldn't highlight the visual element that represents this item.
Called to determine if the model can perform drag and drop of the given string to the given item. If this method returns false, the widget shouldn't highlight the visual element that represents this item.
"""
@typing.overload
def drop_accepted(self, item_tagget: AbstractItem, source: str, drop_location: int = -1) -> bool: ...
def end_edit(self, item: AbstractItem) -> None:
"""
Called when the user finishes the editing. If it's a field, this method is called when the user presses Enter or selects another field for editing. It's useful for undo/redo.
"""
def get_drag_mime_data(self, item: AbstractItem = None) -> str:
"""
Returns Multipurpose Internet Mail Extensions (MIME) for drag and drop.
"""
def get_item_children(self, parentItem: AbstractItem = None) -> typing.List[AbstractItem]:
"""
Returns the vector of items that are nested to the given parent item.
### Arguments:
`id :`
The item to request children from. If it's null, the children of root will be returned.
"""
def get_item_value_model(self, item: AbstractItem = None, column_id: int = 0) -> AbstractValueModel:
"""
Get the value model associated with this item.
### Arguments:
`item :`
The item to request the value model from. If it's null, the root value model will be returned.
`index :`
The column number to get the value model.
"""
def get_item_value_model_count(self, item: AbstractItem = None) -> int:
"""
Returns the number of columns this model item contains.
"""
def remove_begin_edit_fn(self, arg0: int) -> None:
"""
Remove the callback by its id.
### Arguments:
`id :`
The id that addBeginEditFn returns.
"""
def remove_end_edit_fn(self, arg0: int) -> None:
"""
Remove the callback by its id.
### Arguments:
`id :`
The id that addEndEditFn returns.
"""
def remove_item(self, item: AbstractItem) -> None:
"""
Removes the item from the model.
There is no parent here because we assume that the reimplemented model deals with its data and can figure out how to remove this item.
"""
def remove_item_changed_fn(self, arg0: int) -> None:
"""
Remove the callback by its id.
### Arguments:
`id :`
The id that addValueChangedFn returns.
"""
def subscribe_begin_edit_fn(self, arg0: typing.Callable[[AbstractItemModel, AbstractItem], None]) -> carb._carb.Subscription:
"""
Adds the function that will be called every time the user starts the editing.
The id of the callback that is used to remove the callback.
"""
def subscribe_end_edit_fn(self, arg0: typing.Callable[[AbstractItemModel, AbstractItem], None]) -> carb._carb.Subscription:
"""
Adds the function that will be called every time the user finishes the editing.
The id of the callback that is used to remove the callback.
"""
def subscribe_item_changed_fn(self, arg0: typing.Callable[[AbstractItemModel, AbstractItem], None]) -> carb._carb.Subscription:
"""
Adds the function that will be called every time the value changes.
The id of the callback that is used to remove the callback.
"""
pass
class AbstractMultiField(Widget, ItemModelHelper):
"""
AbstractMultiField is the abstract class that has everything to create a custom widget per model item.
The class that wants to create multiple widgets per item needs to reimplement the method _createField.
"""
@property
def column_count(self) -> int:
"""
The max number of fields in a line.
:type: int
"""
@column_count.setter
def column_count(self, arg1: int) -> None:
"""
The max number of fields in a line.
"""
@property
def h_spacing(self) -> float:
"""
Sets a non-stretchable horizontal space in pixels between child fields.
:type: float
"""
@h_spacing.setter
def h_spacing(self, arg1: float) -> None:
"""
Sets a non-stretchable horizontal space in pixels between child fields.
"""
@property
def v_spacing(self) -> float:
"""
Sets a non-stretchable vertical space in pixels between child fields.
:type: float
"""
@v_spacing.setter
def v_spacing(self, arg1: float) -> None:
"""
Sets a non-stretchable vertical space in pixels between child fields.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class AbstractSlider(Widget, ValueModelHelper):
"""
The abstract widget that is base for drags and sliders.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class AbstractValueModel():
"""
"""
def __init__(self) -> None:
"""
Constructs AbstractValueModel.
`kwargs : dict`
See below
### Keyword Arguments:
"""
def _value_changed(self) -> None:
"""
Called when any data of the model is changed. It will notify the subscribed widgets.
"""
def add_begin_edit_fn(self, arg0: typing.Callable[[AbstractValueModel], None]) -> int:
"""
Adds the function that will be called every time the user starts the editing.
The id of the callback that is used to remove the callback.
"""
def add_end_edit_fn(self, arg0: typing.Callable[[AbstractValueModel], None]) -> int:
"""
Adds the function that will be called every time the user finishes the editing.
The id of the callback that is used to remove the callback.
"""
def add_value_changed_fn(self, arg0: typing.Callable[[AbstractValueModel], None]) -> int:
"""
Adds the function that will be called every time the value changes.
The id of the callback that is used to remove the callback.
"""
def begin_edit(self) -> None:
"""
Called when the user starts the editing. If it's a field, this method is called when the user activates the field and places the cursor inside. This method should be reimplemented.
"""
def end_edit(self) -> None:
"""
Called when the user finishes the editing. If it's a field, this method is called when the user presses Enter or selects another field for editing. It's useful for undo/redo. This method should be reimplemented.
"""
def get_value_as_bool(self) -> bool:
"""
Return the bool representation of the value.
"""
def get_value_as_float(self) -> float:
"""
Return the float representation of the value.
"""
def get_value_as_int(self) -> int:
"""
Return the int representation of the value.
"""
def get_value_as_string(self) -> str:
"""
Return the string representation of the value.
"""
def remove_begin_edit_fn(self, arg0: int) -> None:
"""
Remove the callback by its id.
### Arguments:
`id :`
The id that addBeginEditFn returns.
"""
def remove_end_edit_fn(self, arg0: int) -> None:
"""
Remove the callback by its id.
### Arguments:
`id :`
The id that addEndEditFn returns.
"""
def remove_value_changed_fn(self, arg0: int) -> None:
"""
Remove the callback by its id.
### Arguments:
`id :`
The id that addValueChangedFn returns.
"""
@typing.overload
def set_value(self, value: bool) -> None:
"""
Set the value.
Set the value.
Set the value.
Set the value.
"""
@typing.overload
def set_value(self, value: int) -> None: ...
@typing.overload
def set_value(self, value: float) -> None: ...
@typing.overload
def set_value(self, value: str) -> None: ...
def subscribe_begin_edit_fn(self, arg0: typing.Callable[[AbstractValueModel], None]) -> carb._carb.Subscription:
"""
Adds the function that will be called every time the user starts the editing.
The id of the callback that is used to remove the callback.
"""
def subscribe_end_edit_fn(self, arg0: typing.Callable[[AbstractValueModel], None]) -> carb._carb.Subscription:
"""
Adds the function that will be called every time the user finishes the editing.
The id of the callback that is used to remove the callback.
"""
def subscribe_item_changed_fn(self, arg0: typing.Callable[[AbstractValueModel], None]) -> carb._carb.Subscription: ...
def subscribe_value_changed_fn(self, arg0: typing.Callable[[AbstractValueModel], None]) -> carb._carb.Subscription:
"""
Adds the function that will be called every time the value changes.
The id of the callback that is used to remove the callback.
"""
@property
def as_bool(self) -> bool:
"""
Return the bool representation of the value.
:type: bool
"""
@as_bool.setter
def as_bool(self, arg1: bool) -> None:
"""
Return the bool representation of the value.
"""
@property
def as_float(self) -> float:
"""
Return the float representation of the value.
:type: float
"""
@as_float.setter
def as_float(self, arg1: float) -> None:
"""
Return the float representation of the value.
"""
@property
def as_int(self) -> int:
"""
Return the int representation of the value.
:type: int
"""
@as_int.setter
def as_int(self, arg1: int) -> None:
"""
Return the int representation of the value.
"""
@property
def as_string(self) -> str:
"""
Return the string representation of the value.
:type: str
"""
@as_string.setter
def as_string(self, arg1: str) -> None:
"""
Return the string representation of the value.
"""
pass
class Alignment():
"""
Members:
UNDEFINED
LEFT_TOP
LEFT_CENTER
LEFT_BOTTOM
CENTER_TOP
CENTER
CENTER_BOTTOM
RIGHT_TOP
RIGHT_CENTER
RIGHT_BOTTOM
LEFT
RIGHT
H_CENTER
TOP
BOTTOM
V_CENTER
"""
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
"""
BOTTOM: omni.ui._ui.Alignment # value = <Alignment.BOTTOM: 32>
CENTER: omni.ui._ui.Alignment # value = <Alignment.CENTER: 72>
CENTER_BOTTOM: omni.ui._ui.Alignment # value = <Alignment.CENTER_BOTTOM: 40>
CENTER_TOP: omni.ui._ui.Alignment # value = <Alignment.CENTER_TOP: 24>
H_CENTER: omni.ui._ui.Alignment # value = <Alignment.H_CENTER: 8>
LEFT: omni.ui._ui.Alignment # value = <Alignment.LEFT: 2>
LEFT_BOTTOM: omni.ui._ui.Alignment # value = <Alignment.LEFT_BOTTOM: 34>
LEFT_CENTER: omni.ui._ui.Alignment # value = <Alignment.LEFT_CENTER: 66>
LEFT_TOP: omni.ui._ui.Alignment # value = <Alignment.LEFT_TOP: 18>
RIGHT: omni.ui._ui.Alignment # value = <Alignment.RIGHT: 4>
RIGHT_BOTTOM: omni.ui._ui.Alignment # value = <Alignment.RIGHT_BOTTOM: 36>
RIGHT_CENTER: omni.ui._ui.Alignment # value = <Alignment.RIGHT_CENTER: 68>
RIGHT_TOP: omni.ui._ui.Alignment # value = <Alignment.RIGHT_TOP: 20>
TOP: omni.ui._ui.Alignment # value = <Alignment.TOP: 16>
UNDEFINED: omni.ui._ui.Alignment # value = <Alignment.UNDEFINED: 0>
V_CENTER: omni.ui._ui.Alignment # value = <Alignment.V_CENTER: 64>
__members__: dict # value = {'UNDEFINED': <Alignment.UNDEFINED: 0>, 'LEFT_TOP': <Alignment.LEFT_TOP: 18>, 'LEFT_CENTER': <Alignment.LEFT_CENTER: 66>, 'LEFT_BOTTOM': <Alignment.LEFT_BOTTOM: 34>, 'CENTER_TOP': <Alignment.CENTER_TOP: 24>, 'CENTER': <Alignment.CENTER: 72>, 'CENTER_BOTTOM': <Alignment.CENTER_BOTTOM: 40>, 'RIGHT_TOP': <Alignment.RIGHT_TOP: 20>, 'RIGHT_CENTER': <Alignment.RIGHT_CENTER: 68>, 'RIGHT_BOTTOM': <Alignment.RIGHT_BOTTOM: 36>, 'LEFT': <Alignment.LEFT: 2>, 'RIGHT': <Alignment.RIGHT: 4>, 'H_CENTER': <Alignment.H_CENTER: 8>, 'TOP': <Alignment.TOP: 16>, 'BOTTOM': <Alignment.BOTTOM: 32>, 'V_CENTER': <Alignment.V_CENTER: 64>}
pass
class ArrowHelper():
"""
The ArrowHelper widget provides a colored rectangle to display.
"""
@property
def begin_arrow_height(self) -> float:
"""
This property holds the height of the begin arrow.
:type: float
"""
@begin_arrow_height.setter
def begin_arrow_height(self, arg1: float) -> None:
"""
This property holds the height of the begin arrow.
"""
@property
def begin_arrow_type(self) -> ArrowType:
"""
This property holds the type of the begin arrow can only be eNone or eRrrow. By default, the arrow type is eNone.
:type: ArrowType
"""
@begin_arrow_type.setter
def begin_arrow_type(self, arg1: ArrowType) -> None:
"""
This property holds the type of the begin arrow can only be eNone or eRrrow. By default, the arrow type is eNone.
"""
@property
def begin_arrow_width(self) -> float:
"""
This property holds the width of the begin arrow.
:type: float
"""
@begin_arrow_width.setter
def begin_arrow_width(self, arg1: float) -> None:
"""
This property holds the width of the begin arrow.
"""
@property
def end_arrow_height(self) -> float:
"""
This property holds the height of the end arrow.
:type: float
"""
@end_arrow_height.setter
def end_arrow_height(self, arg1: float) -> None:
"""
This property holds the height of the end arrow.
"""
@property
def end_arrow_type(self) -> ArrowType:
"""
This property holds the type of the end arrow can only be eNone or eRrrow. By default, the arrow type is eNone.
:type: ArrowType
"""
@end_arrow_type.setter
def end_arrow_type(self, arg1: ArrowType) -> None:
"""
This property holds the type of the end arrow can only be eNone or eRrrow. By default, the arrow type is eNone.
"""
@property
def end_arrow_width(self) -> float:
"""
This property holds the width of the end arrow.
:type: float
"""
@end_arrow_width.setter
def end_arrow_width(self, arg1: float) -> None:
"""
This property holds the width of the end arrow.
"""
pass
class ArrowType():
"""
Members:
NONE
ARROW
"""
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
"""
ARROW: omni.ui._ui.ArrowType # value = <ArrowType.ARROW: 1>
NONE: omni.ui._ui.ArrowType # value = <ArrowType.NONE: 0>
__members__: dict # value = {'NONE': <ArrowType.NONE: 0>, 'ARROW': <ArrowType.ARROW: 1>}
pass
class Axis():
"""
Members:
None
X
Y
XY
"""
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
"""
None: omni.ui._ui.Axis # value = <Axis.None: 0>
X: omni.ui._ui.Axis # value = <Axis.X: 1>
XY: omni.ui._ui.Axis # value = <Axis.XY: 3>
Y: omni.ui._ui.Axis # value = <Axis.Y: 2>
__members__: dict # value = {'None': <Axis.None: 0>, 'X': <Axis.X: 1>, 'Y': <Axis.Y: 2>, 'XY': <Axis.XY: 3>}
pass
class BezierCurve(Shape, Widget, ArrowHelper):
"""
Smooth curve that can be scaled infinitely.
"""
def __init__(self, **kwargs) -> None: ...
def call_mouse_hovered_fn(self, arg0: bool) -> None:
"""
Sets the function that will be called when the user use mouse enter/leave on the line. It's the override to prevent Widget from the bounding box logic. The function specification is: void onMouseHovered(bool hovered)
"""
def has_mouse_hovered_fn(self) -> bool:
"""
Sets the function that will be called when the user use mouse enter/leave on the line. It's the override to prevent Widget from the bounding box logic. The function specification is: void onMouseHovered(bool hovered)
"""
def set_mouse_hovered_fn(self, fn: typing.Callable[[bool], None]) -> None:
"""
Sets the function that will be called when the user use mouse enter/leave on the line. It's the override to prevent Widget from the bounding box logic. The function specification is: void onMouseHovered(bool hovered)
"""
@property
def end_tangent_height(self) -> Length:
"""
This property holds the Y coordinate of the end of the curve relative to the width bound of the curve.
:type: Length
"""
@end_tangent_height.setter
def end_tangent_height(self, arg1: Length) -> None:
"""
This property holds the Y coordinate of the end of the curve relative to the width bound of the curve.
"""
@property
def end_tangent_width(self) -> Length:
"""
This property holds the X coordinate of the end of the curve relative to the width bound of the curve.
:type: Length
"""
@end_tangent_width.setter
def end_tangent_width(self, arg1: Length) -> None:
"""
This property holds the X coordinate of the end of the curve relative to the width bound of the curve.
"""
@property
def start_tangent_height(self) -> Length:
"""
This property holds the Y coordinate of the start of the curve relative to the width bound of the curve.
:type: Length
"""
@start_tangent_height.setter
def start_tangent_height(self, arg1: Length) -> None:
"""
This property holds the Y coordinate of the start of the curve relative to the width bound of the curve.
"""
@property
def start_tangent_width(self) -> Length:
"""
This property holds the X coordinate of the start of the curve relative to the width bound of the curve.
:type: Length
"""
@start_tangent_width.setter
def start_tangent_width(self, arg1: Length) -> None:
"""
This property holds the X coordinate of the start of the curve relative to the width bound of the curve.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class Button(InvisibleButton, Widget):
"""
The Button widget provides a command button.
The command button, is perhaps the most commonly used widget in any graphical user interface. Click a button to execute a command. It is rectangular and typically displays a text label describing its action.
"""
def __init__(self, text: str = '', **kwargs) -> None:
"""
Construct a button with a text on it.
### Arguments:
`text :`
The text for the button to use.
`kwargs : dict`
See below
### Keyword Arguments:
`text : str`
This property holds the button's text.
`image_url : str`
This property holds the button's optional image URL.
`image_width : float`
This property holds the width of the image widget. Do not use this function to find the width of the image.
`image_height : float`
This property holds the height of the image widget. Do not use this function to find the height of the image.
`spacing : float`
Sets a non-stretchable space in points between image and text.
`clicked_fn : Callable[[], None]`
Sets the function that will be called when when the button is activated (i.e., pressed down then released while the mouse cursor is inside the button).
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@property
def image_height(self) -> Length:
"""
This property holds the height of the image widget. Do not use this function to find the height of the image.
:type: Length
"""
@image_height.setter
def image_height(self, arg1: Length) -> None:
"""
This property holds the height of the image widget. Do not use this function to find the height of the image.
"""
@property
def image_url(self) -> str:
"""
This property holds the button's optional image URL.
:type: str
"""
@image_url.setter
def image_url(self, arg1: str) -> None:
"""
This property holds the button's optional image URL.
"""
@property
def image_width(self) -> Length:
"""
This property holds the width of the image widget. Do not use this function to find the width of the image.
:type: Length
"""
@image_width.setter
def image_width(self, arg1: Length) -> None:
"""
This property holds the width of the image widget. Do not use this function to find the width of the image.
"""
@property
def spacing(self) -> float:
"""
Sets a non-stretchable space in points between image and text.
:type: float
"""
@spacing.setter
def spacing(self, arg1: float) -> None:
"""
Sets a non-stretchable space in points between image and text.
"""
@property
def text(self) -> str:
"""
This property holds the button's text.
:type: str
"""
@text.setter
def text(self, arg1: str) -> None:
"""
This property holds the button's text.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class ByteImageProvider(ImageProvider):
"""
doc
"""
@typing.overload
def __init__(self) -> None:
"""
doc
doc
"""
@staticmethod
@typing.overload
def __init__(*args, **kwargs) -> typing.Any: ...
@staticmethod
def set_bytes_data(*args, **kwargs) -> typing.Any:
"""
Sets Python sequence as byte data. The image provider will recognize flattened color values, or sequence within sequence and convert it into an image.
"""
def set_bytes_data_from_gpu(self, gpu_bytes: int, sizes: typing.List[int], format: omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat = TextureFormat.RGBA8_UNORM, stride: int = -1) -> None:
"""
Sets byte data from a copy of gpu memory at gpuBytes.
"""
def set_data(self, arg0: typing.List[int], arg1: typing.List[int]) -> None:
"""
[DEPRECATED FUNCTION]
"""
def set_data_array(self, arg0: numpy.ndarray[numpy.uint8], arg1: typing.List[int]) -> None: ...
def set_raw_bytes_data(self, raw_bytes: capsule, sizes: typing.List[int], format: omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat = TextureFormat.RGBA8_UNORM, stride: int = -1) -> None:
"""
Sets byte data that the image provider will turn raw pointer array into an image.
"""
pass
class CanvasFrame(Frame, Container, Widget):
"""
CanvasFrame is the widget that allows the user to pan and zoom its children with a mouse. It has the layout that can be infinitely moved in any direction.
"""
def __init__(self, **kwargs) -> None:
"""
Constructs CanvasFrame.
`kwargs : dict`
See below
### Keyword Arguments:
`pan_x : `
The horizontal offset of the child item.
`pan_y : `
The vertical offset of the child item.
`zoom : `
The zoom minimum of the child item.
`zoom_min : `
The zoom maximum of the child item.
`zoom_max : `
The zoom level of the child item.
`compatibility : `
This boolean property controls the behavior of CanvasFrame. When set to true, the widget will function in the old way. When set to false, the widget will use a newer and faster implementation. This variable is included as a transition period to ensure that the update does not break any existing functionality. Please be aware that the old behavior may be deprecated in the future, so it is recommended to set this variable to false once you have thoroughly tested the new implementation.
`pan_x_changed_fn : `
The horizontal offset of the child item.
`pan_y_changed_fn : `
The vertical offset of the child item.
`zoom_changed_fn : `
The zoom level of the child item.
`draggable : `
Provides a convenient way to make the content draggable and zoomable.
`horizontal_clipping : `
When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for horizontal direction.
`vertical_clipping : `
When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for vertial direction.
`separate_window : `
A special mode where the child is placed to the transparent borderless window. We need it to be able to place the UI to the exact stacking order between other windows.
`raster_policy : `
Determine how the content of the frame should be rasterized.
`build_fn : `
Set the callback that will be called once the frame is visible and the content of the callback will override the frame child. It's useful for lazy load.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
def screen_to_canvas(self, x: float, y: float) -> typing.Tuple[float, float]:
"""
Transforms screen-space coordinates to canvas-space
"""
def screen_to_canvas_x(self, x: float) -> float:
"""
Transforms screen-space X to canvas-space X.
"""
def screen_to_canvas_y(self, y: float) -> float:
"""
Transforms screen-space Y to canvas-space Y.
"""
def set_pan_key_shortcut(self, mouse_button: int, key_flag: int) -> None:
"""
Specify the mouse button and key to pan the canvas.
"""
def set_pan_x_changed_fn(self, fn: typing.Callable[[float], None]) -> None:
"""
The horizontal offset of the child item.
"""
def set_pan_y_changed_fn(self, fn: typing.Callable[[float], None]) -> None:
"""
The vertical offset of the child item.
"""
def set_zoom_changed_fn(self, fn: typing.Callable[[float], None]) -> None:
"""
The zoom level of the child item.
"""
def set_zoom_key_shortcut(self, mouse_button: int, key_flag: int) -> None:
"""
Specify the mouse button and key to zoom the canvas.
"""
@property
def compatibility(self) -> bool:
"""
This boolean property controls the behavior of CanvasFrame. When set to true, the widget will function in the old way. When set to false, the widget will use a newer and faster implementation. This variable is included as a transition period to ensure that the update does not break any existing functionality. Please be aware that the old behavior may be deprecated in the future, so it is recommended to set this variable to false once you have thoroughly tested the new implementation.
:type: bool
"""
@compatibility.setter
def compatibility(self, arg1: bool) -> None:
"""
This boolean property controls the behavior of CanvasFrame. When set to true, the widget will function in the old way. When set to false, the widget will use a newer and faster implementation. This variable is included as a transition period to ensure that the update does not break any existing functionality. Please be aware that the old behavior may be deprecated in the future, so it is recommended to set this variable to false once you have thoroughly tested the new implementation.
"""
@property
def draggable(self) -> bool:
"""
Provides a convenient way to make the content draggable and zoomable.
:type: bool
"""
@draggable.setter
def draggable(self, arg1: bool) -> None:
"""
Provides a convenient way to make the content draggable and zoomable.
"""
@property
def pan_x(self) -> float:
"""
The horizontal offset of the child item.
:type: float
"""
@pan_x.setter
def pan_x(self, arg1: float) -> None:
"""
The horizontal offset of the child item.
"""
@property
def pan_y(self) -> float:
"""
The vertical offset of the child item.
:type: float
"""
@pan_y.setter
def pan_y(self, arg1: float) -> None:
"""
The vertical offset of the child item.
"""
@property
def smooth_zoom(self) -> bool:
"""
When true, zoom is smooth like in Bifrost even if the user is using mouse wheen that doesn't provide smooth scrolling.
:type: bool
"""
@smooth_zoom.setter
def smooth_zoom(self, arg1: bool) -> None:
"""
When true, zoom is smooth like in Bifrost even if the user is using mouse wheen that doesn't provide smooth scrolling.
"""
@property
def zoom(self) -> float:
"""
The zoom level of the child item.
:type: float
"""
@zoom.setter
def zoom(self, arg1: float) -> None:
"""
The zoom level of the child item.
"""
@property
def zoom_max(self) -> float:
"""
The zoom maximum of the child item.
:type: float
"""
@zoom_max.setter
def zoom_max(self, arg1: float) -> None:
"""
The zoom maximum of the child item.
"""
@property
def zoom_min(self) -> float:
"""
The zoom minimum of the child item.
:type: float
"""
@zoom_min.setter
def zoom_min(self, arg1: float) -> None:
"""
The zoom minimum of the child item.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class CheckBox(Widget, ValueModelHelper):
"""
A CheckBox is an option button that can be switched on (checked) or off (unchecked). Checkboxes are typically used to represent features in an application that can be enabled or disabled without affecting others.
The checkbox is implemented using the model-view pattern. The model is the central component of this system. It is the application's dynamic data structure independent of the widget. It directly manages the data, logic, and rules of the checkbox. If the model is not specified, the simple one is created automatically when the object is constructed.
"""
def __init__(self, model: AbstractValueModel = None, **kwargs) -> None:
"""
CheckBox with specified model. If model is not specified, it's using the default one.
`kwargs : dict`
See below
### Keyword Arguments:
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class Circle(Shape, Widget):
"""
The Circle widget provides a colored circle to display.
"""
def __init__(self, **kwargs) -> None:
"""
Constructs Circle.
`kwargs : dict`
See below
### Keyword Arguments:
`alignment :`
This property holds the alignment of the circle when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the circle is centered.
`radius :`
This property holds the radius of the circle when the fill policy is eFixed or eFixedCrop. By default, the circle radius is 0.
`arc :`
This property is the way to draw a half or a quarter of the circle. When it's eLeft, only left side of the circle is rendered. When it's eLeftTop, only left top quarter is rendered.
`size_policy :`
Define what happens when the source image has a different size than the item.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@property
def alignment(self) -> Alignment:
"""
This property holds the alignment of the circle when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the circle is centered.
:type: Alignment
"""
@alignment.setter
def alignment(self, arg1: Alignment) -> None:
"""
This property holds the alignment of the circle when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the circle is centered.
"""
@property
def arc(self) -> Alignment:
"""
This property is the way to draw a half or a quarter of the circle. When it's eLeft, only left side of the circle is rendered. When it's eLeftTop, only left top quarter is rendered.
:type: Alignment
"""
@arc.setter
def arc(self, arg1: Alignment) -> None:
"""
This property is the way to draw a half or a quarter of the circle. When it's eLeft, only left side of the circle is rendered. When it's eLeftTop, only left top quarter is rendered.
"""
@property
def radius(self) -> float:
"""
This property holds the radius of the circle when the fill policy is eFixed or eFixedCrop. By default, the circle radius is 0.
:type: float
"""
@radius.setter
def radius(self, arg1: float) -> None:
"""
This property holds the radius of the circle when the fill policy is eFixed or eFixedCrop. By default, the circle radius is 0.
"""
@property
def size_policy(self) -> CircleSizePolicy:
"""
Define what happens when the source image has a different size than the item.
:type: CircleSizePolicy
"""
@size_policy.setter
def size_policy(self, arg1: CircleSizePolicy) -> None:
"""
Define what happens when the source image has a different size than the item.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class CircleSizePolicy():
"""
Define what happens when the source image has a different size than the item.
Members:
STRETCH
FIXED
"""
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
"""
FIXED: omni.ui._ui.CircleSizePolicy # value = <CircleSizePolicy.FIXED: 1>
STRETCH: omni.ui._ui.CircleSizePolicy # value = <CircleSizePolicy.STRETCH: 0>
__members__: dict # value = {'STRETCH': <CircleSizePolicy.STRETCH: 0>, 'FIXED': <CircleSizePolicy.FIXED: 1>}
pass
class CollapsableFrame(Frame, Container, Widget):
"""
CollapsableFrame is a frame widget that can hide or show its content. It has two states expanded and collapsed. When it's collapsed, it looks like a button. If it's expanded, it looks like a button and a frame with the content. It's handy to group properties, and temporarily hide them to get more space for something else.
"""
def __init__(self, title: str = '', **kwargs) -> None:
"""
Constructs CollapsableFrame.
### Arguments:
`text :`
The text for the caption of the frame.
`kwargs : dict`
See below
### Keyword Arguments:
`collapsed : `
The state of the CollapsableFrame.
`title : `
The header text.
`alignment : `
This property holds the alignment of the label in the default header. By default, the contents of the label are left-aligned and vertically-centered.
`build_header_fn : `
Set dynamic header that will be created dynamiclly when it is needed. The function is called inside a ui.Frame scope that the widget will be parented correctly.
`collapsed_changed_fn : `
The state of the CollapsableFrame.
`horizontal_clipping : `
When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for horizontal direction.
`vertical_clipping : `
When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for vertial direction.
`separate_window : `
A special mode where the child is placed to the transparent borderless window. We need it to be able to place the UI to the exact stacking order between other windows.
`raster_policy : `
Determine how the content of the frame should be rasterized.
`build_fn : `
Set the callback that will be called once the frame is visible and the content of the callback will override the frame child. It's useful for lazy load.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
def call_build_header_fn(self, arg0: bool, arg1: str) -> None:
"""
Set dynamic header that will be created dynamiclly when it is needed. The function is called inside a ui.Frame scope that the widget will be parented correctly.
"""
def has_build_header_fn(self) -> bool:
"""
Set dynamic header that will be created dynamiclly when it is needed. The function is called inside a ui.Frame scope that the widget will be parented correctly.
"""
def set_build_header_fn(self, fn: typing.Callable[[bool, str], None]) -> None:
"""
Set dynamic header that will be created dynamiclly when it is needed. The function is called inside a ui.Frame scope that the widget will be parented correctly.
"""
def set_collapsed_changed_fn(self, fn: typing.Callable[[bool], None]) -> None:
"""
The state of the CollapsableFrame.
"""
@property
def alignment(self) -> Alignment:
"""
This property holds the alignment of the label in the default header. By default, the contents of the label are left-aligned and vertically-centered.
:type: Alignment
"""
@alignment.setter
def alignment(self, arg1: Alignment) -> None:
"""
This property holds the alignment of the label in the default header. By default, the contents of the label are left-aligned and vertically-centered.
"""
@property
def collapsed(self) -> bool:
"""
The state of the CollapsableFrame.
:type: bool
"""
@collapsed.setter
def collapsed(self, arg1: bool) -> None:
"""
The state of the CollapsableFrame.
"""
@property
def title(self) -> str:
"""
The header text.
:type: str
"""
@title.setter
def title(self, arg1: str) -> None:
"""
The header text.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class ColorStore():
"""
A singleton that stores all the UI Style color properties of omni.ui.
"""
@staticmethod
def find(name: str) -> int:
"""
Return the index of the color with specific name.
"""
@staticmethod
def store(name: str, color: int) -> None:
"""
Save the color by name.
"""
pass
class ColorWidget(Widget, ItemModelHelper):
"""
The ColorWidget widget is a button that displays the color from the item model and can open a picker window to change the color.
"""
@typing.overload
def __init__(self, **kwargs) -> None:
"""
Construct ColorWidget.
`kwargs : dict`
See below
### Keyword Arguments:
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@typing.overload
def __init__(self, arg0: AbstractItemModel, **kwargs) -> None: ...
@typing.overload
def __init__(self, arg0: float, arg1: float, arg2: float, **kwargs) -> None: ...
@typing.overload
def __init__(self, arg0: float, arg1: float, arg2: float, arg3: float, **kwargs) -> None: ...
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class ComboBox(Widget, ItemModelHelper):
"""
The ComboBox widget is a combined button and a drop-down list.
A combo box is a selection widget that displays the current item and can pop up a list of selectable items.
The ComboBox is implemented using the model-view pattern. The model is the central component of this system. The root of the item model should contain the index of currently selected items, and the children of the root include all the items of the combo box.
"""
def __init__(self, *args, **kwargs) -> None:
"""
Construct ComboBox.
### Arguments:
`model :`
The model that determines if the button is checked.
`kwargs : dict`
See below
### Keyword Arguments:
`arrow_only : bool`
Determines if it's necessary to hide the text of the ComboBox.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class Container(Widget):
"""
Base class for all UI containers. Container can hold one or many other :class:`omni.ui.Widget` s
"""
def __enter__(self) -> None: ...
def __exit__(self, arg0: object, arg1: object, arg2: object) -> None: ...
def add_child(self, arg0: Widget) -> None:
"""
Adds widget to this container in a manner specific to the container. If it's allowed to have one sub-widget only, it will be overwriten.
"""
def clear(self) -> None:
"""
Removes the container items from the container.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class CornerFlag():
"""
Members:
NONE
TOP_LEFT
TOP_RIGHT
BOTTOM_LEFT
BOTTOM_RIGHT
TOP
BOTTOM
LEFT
RIGHT
ALL
"""
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
"""
ALL: omni.ui._ui.CornerFlag # value = <CornerFlag.ALL: 15>
BOTTOM: omni.ui._ui.CornerFlag # value = <CornerFlag.BOTTOM: 12>
BOTTOM_LEFT: omni.ui._ui.CornerFlag # value = <CornerFlag.BOTTOM_LEFT: 4>
BOTTOM_RIGHT: omni.ui._ui.CornerFlag # value = <CornerFlag.BOTTOM_RIGHT: 8>
LEFT: omni.ui._ui.CornerFlag # value = <CornerFlag.LEFT: 5>
NONE: omni.ui._ui.CornerFlag # value = <CornerFlag.NONE: 0>
RIGHT: omni.ui._ui.CornerFlag # value = <CornerFlag.RIGHT: 10>
TOP: omni.ui._ui.CornerFlag # value = <CornerFlag.TOP: 3>
TOP_LEFT: omni.ui._ui.CornerFlag # value = <CornerFlag.TOP_LEFT: 1>
TOP_RIGHT: omni.ui._ui.CornerFlag # value = <CornerFlag.TOP_RIGHT: 2>
__members__: dict # value = {'NONE': <CornerFlag.NONE: 0>, 'TOP_LEFT': <CornerFlag.TOP_LEFT: 1>, 'TOP_RIGHT': <CornerFlag.TOP_RIGHT: 2>, 'BOTTOM_LEFT': <CornerFlag.BOTTOM_LEFT: 4>, 'BOTTOM_RIGHT': <CornerFlag.BOTTOM_RIGHT: 8>, 'TOP': <CornerFlag.TOP: 3>, 'BOTTOM': <CornerFlag.BOTTOM: 12>, 'LEFT': <CornerFlag.LEFT: 5>, 'RIGHT': <CornerFlag.RIGHT: 10>, 'ALL': <CornerFlag.ALL: 15>}
pass
class Direction():
"""
Members:
LEFT_TO_RIGHT
RIGHT_TO_LEFT
TOP_TO_BOTTOM
BOTTOM_TO_TOP
BACK_TO_FRONT
FRONT_TO_BACK
"""
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
"""
BACK_TO_FRONT: omni.ui._ui.Direction # value = <Direction.BACK_TO_FRONT: 4>
BOTTOM_TO_TOP: omni.ui._ui.Direction # value = <Direction.BOTTOM_TO_TOP: 3>
FRONT_TO_BACK: omni.ui._ui.Direction # value = <Direction.FRONT_TO_BACK: 5>
LEFT_TO_RIGHT: omni.ui._ui.Direction # value = <Direction.LEFT_TO_RIGHT: 0>
RIGHT_TO_LEFT: omni.ui._ui.Direction # value = <Direction.RIGHT_TO_LEFT: 1>
TOP_TO_BOTTOM: omni.ui._ui.Direction # value = <Direction.TOP_TO_BOTTOM: 2>
__members__: dict # value = {'LEFT_TO_RIGHT': <Direction.LEFT_TO_RIGHT: 0>, 'RIGHT_TO_LEFT': <Direction.RIGHT_TO_LEFT: 1>, 'TOP_TO_BOTTOM': <Direction.TOP_TO_BOTTOM: 2>, 'BOTTOM_TO_TOP': <Direction.BOTTOM_TO_TOP: 3>, 'BACK_TO_FRONT': <Direction.BACK_TO_FRONT: 4>, 'FRONT_TO_BACK': <Direction.FRONT_TO_BACK: 5>}
pass
class DockPolicy():
"""
Members:
DO_NOTHING
CURRENT_WINDOW_IS_ACTIVE
TARGET_WINDOW_IS_ACTIVE
"""
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
"""
CURRENT_WINDOW_IS_ACTIVE: omni.ui._ui.DockPolicy # value = <DockPolicy.CURRENT_WINDOW_IS_ACTIVE: 1>
DO_NOTHING: omni.ui._ui.DockPolicy # value = <DockPolicy.DO_NOTHING: 0>
TARGET_WINDOW_IS_ACTIVE: omni.ui._ui.DockPolicy # value = <DockPolicy.TARGET_WINDOW_IS_ACTIVE: 2>
__members__: dict # value = {'DO_NOTHING': <DockPolicy.DO_NOTHING: 0>, 'CURRENT_WINDOW_IS_ACTIVE': <DockPolicy.CURRENT_WINDOW_IS_ACTIVE: 1>, 'TARGET_WINDOW_IS_ACTIVE': <DockPolicy.TARGET_WINDOW_IS_ACTIVE: 2>}
pass
class DockPosition():
"""
Members:
RIGHT
LEFT
TOP
BOTTOM
SAME
"""
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
"""
BOTTOM: omni.ui._ui.DockPosition # value = <DockPosition.BOTTOM: 3>
LEFT: omni.ui._ui.DockPosition # value = <DockPosition.LEFT: 0>
RIGHT: omni.ui._ui.DockPosition # value = <DockPosition.RIGHT: 1>
SAME: omni.ui._ui.DockPosition # value = <DockPosition.SAME: 4>
TOP: omni.ui._ui.DockPosition # value = <DockPosition.TOP: 2>
__members__: dict # value = {'RIGHT': <DockPosition.RIGHT: 1>, 'LEFT': <DockPosition.LEFT: 0>, 'TOP': <DockPosition.TOP: 2>, 'BOTTOM': <DockPosition.BOTTOM: 3>, 'SAME': <DockPosition.SAME: 4>}
pass
class DockPreference():
"""
Members:
DISABLED
MAIN
RIGHT
LEFT
RIGHT_TOP
RIGHT_BOTTOM
LEFT_BOTTOM
"""
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
"""
DISABLED: omni.ui._ui.DockPreference # value = <DockPreference.DISABLED: 0>
LEFT: omni.ui._ui.DockPreference # value = <DockPreference.LEFT: 3>
LEFT_BOTTOM: omni.ui._ui.DockPreference # value = <DockPreference.LEFT_BOTTOM: 6>
MAIN: omni.ui._ui.DockPreference # value = <DockPreference.MAIN: 1>
RIGHT: omni.ui._ui.DockPreference # value = <DockPreference.RIGHT: 2>
RIGHT_BOTTOM: omni.ui._ui.DockPreference # value = <DockPreference.RIGHT_BOTTOM: 5>
RIGHT_TOP: omni.ui._ui.DockPreference # value = <DockPreference.RIGHT_TOP: 4>
__members__: dict # value = {'DISABLED': <DockPreference.DISABLED: 0>, 'MAIN': <DockPreference.MAIN: 1>, 'RIGHT': <DockPreference.RIGHT: 2>, 'LEFT': <DockPreference.LEFT: 3>, 'RIGHT_TOP': <DockPreference.RIGHT_TOP: 4>, 'RIGHT_BOTTOM': <DockPreference.RIGHT_BOTTOM: 5>, 'LEFT_BOTTOM': <DockPreference.LEFT_BOTTOM: 6>}
pass
class DockSpace():
"""
The DockSpace class represents Dock Space for the OS Window.
"""
def __init__(self, arg0: object, **kwargs) -> None:
"""
Construct the main window, add it to the underlying windowing system, and makes it appear.
`kwargs : dict`
See below
### Keyword Arguments:
"""
@property
def dock_frame(self) -> Frame:
"""
This represents Styling opportunity for the Window background.
:type: Frame
"""
pass
class DynamicTextureProvider(ByteImageProvider, ImageProvider):
"""
doc
"""
def __init__(self, arg0: str) -> None:
"""
doc
"""
pass
class Ellipse(Shape, Widget):
"""
Constructs Ellipse.
`kwargs : dict`
See below
### Keyword Arguments:
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
def __init__(self, **kwargs) -> None: ...
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class FillPolicy():
"""
Members:
STRETCH
PRESERVE_ASPECT_FIT
PRESERVE_ASPECT_CROP
"""
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
"""
PRESERVE_ASPECT_CROP: omni.ui._ui.FillPolicy # value = <FillPolicy.PRESERVE_ASPECT_CROP: 2>
PRESERVE_ASPECT_FIT: omni.ui._ui.FillPolicy # value = <FillPolicy.PRESERVE_ASPECT_FIT: 1>
STRETCH: omni.ui._ui.FillPolicy # value = <FillPolicy.STRETCH: 0>
__members__: dict # value = {'STRETCH': <FillPolicy.STRETCH: 0>, 'PRESERVE_ASPECT_FIT': <FillPolicy.PRESERVE_ASPECT_FIT: 1>, 'PRESERVE_ASPECT_CROP': <FillPolicy.PRESERVE_ASPECT_CROP: 2>}
pass
class FloatDrag(FloatSlider, AbstractSlider, Widget, ValueModelHelper):
"""
The drag widget that looks like a field but it's possible to change the value with dragging.
"""
def __init__(self, model: AbstractValueModel = None, **kwargs) -> None:
"""
Construct FloatDrag.
`kwargs : dict`
See below
### Keyword Arguments:
`min : float`
This property holds the slider's minimum value.
`max : float`
This property holds the slider's maximum value.
`step : float`
This property controls the steping speed on the drag.
`format : str`
This property overrides automatic formatting if needed.
`precision : uint32_t`
This property holds the slider value's float precision.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class FloatField(AbstractField, Widget, ValueModelHelper):
"""
The FloatField widget is a one-line text editor with a string model.
"""
def __init__(self, model: AbstractValueModel = None, **kwargs) -> None:
"""
Construct FloatField.
`kwargs : dict`
See below
### Keyword Arguments:
`precision : uint32_t`
This property holds the field value's float precision.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@property
def precision(self) -> int:
"""
This property holds the field value's float precision.
:type: int
"""
@precision.setter
def precision(self, arg1: int) -> None:
"""
This property holds the field value's float precision.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class FloatSlider(AbstractSlider, Widget, ValueModelHelper):
"""
The slider is the classic widget for controlling a bounded value. It lets the user move a slider handle along a horizontal groove and translates the handle's position into a float value within the legal range.
"""
def __init__(self, model: AbstractValueModel = None, **kwargs) -> None:
"""
Construct FloatSlider.
`kwargs : dict`
See below
### Keyword Arguments:
`min : float`
This property holds the slider's minimum value.
`max : float`
This property holds the slider's maximum value.
`step : float`
This property controls the steping speed on the drag.
`format : str`
This property overrides automatic formatting if needed.
`precision : uint32_t`
This property holds the slider value's float precision.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@property
def format(self) -> str:
"""
This property overrides automatic formatting if needed.
:type: str
"""
@format.setter
def format(self, arg1: str) -> None:
"""
This property overrides automatic formatting if needed.
"""
@property
def max(self) -> float:
"""
This property holds the slider's maximum value.
:type: float
"""
@max.setter
def max(self, arg1: float) -> None:
"""
This property holds the slider's maximum value.
"""
@property
def min(self) -> float:
"""
This property holds the slider's minimum value.
:type: float
"""
@min.setter
def min(self, arg1: float) -> None:
"""
This property holds the slider's minimum value.
"""
@property
def precision(self) -> int:
"""
This property holds the slider value's float precision.
:type: int
"""
@precision.setter
def precision(self, arg1: int) -> None:
"""
This property holds the slider value's float precision.
"""
@property
def step(self) -> float:
"""
This property controls the steping speed on the drag.
:type: float
"""
@step.setter
def step(self, arg1: float) -> None:
"""
This property controls the steping speed on the drag.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class FloatStore():
"""
A singleton that stores all the UI Style float properties of omni.ui.
"""
@staticmethod
def find(name: str) -> float:
"""
Return the index of the color with specific name.
"""
@staticmethod
def store(name: str, value: float) -> None:
"""
Save the color by name.
"""
pass
class FocusPolicy():
"""
Members:
DEFAULT
FOCUS_ON_LEFT_MOUSE_DOWN
FOCUS_ON_ANY_MOUSE_DOWN
FOCUS_ON_HOVER
"""
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
"""
DEFAULT: omni.ui._ui.FocusPolicy # value = <FocusPolicy.DEFAULT: 0>
FOCUS_ON_ANY_MOUSE_DOWN: omni.ui._ui.FocusPolicy # value = <FocusPolicy.FOCUS_ON_ANY_MOUSE_DOWN: 1>
FOCUS_ON_HOVER: omni.ui._ui.FocusPolicy # value = <FocusPolicy.FOCUS_ON_HOVER: 2>
FOCUS_ON_LEFT_MOUSE_DOWN: omni.ui._ui.FocusPolicy # value = <FocusPolicy.DEFAULT: 0>
__members__: dict # value = {'DEFAULT': <FocusPolicy.DEFAULT: 0>, 'FOCUS_ON_LEFT_MOUSE_DOWN': <FocusPolicy.DEFAULT: 0>, 'FOCUS_ON_ANY_MOUSE_DOWN': <FocusPolicy.FOCUS_ON_ANY_MOUSE_DOWN: 1>, 'FOCUS_ON_HOVER': <FocusPolicy.FOCUS_ON_HOVER: 2>}
pass
class FontStyle():
"""
Supported font styles.
Members:
NONE
NORMAL
LARGE
SMALL
EXTRA_LARGE
XXL
XXXL
EXTRA_SMALL
XXS
XXXS
ULTRA
"""
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
"""
EXTRA_LARGE: omni.ui._ui.FontStyle # value = <FontStyle.EXTRA_LARGE: 4>
EXTRA_SMALL: omni.ui._ui.FontStyle # value = <FontStyle.EXTRA_SMALL: 7>
LARGE: omni.ui._ui.FontStyle # value = <FontStyle.LARGE: 2>
NONE: omni.ui._ui.FontStyle # value = <FontStyle.NONE: 0>
NORMAL: omni.ui._ui.FontStyle # value = <FontStyle.NORMAL: 1>
SMALL: omni.ui._ui.FontStyle # value = <FontStyle.SMALL: 3>
ULTRA: omni.ui._ui.FontStyle # value = <FontStyle.ULTRA: 10>
XXL: omni.ui._ui.FontStyle # value = <FontStyle.XXL: 5>
XXS: omni.ui._ui.FontStyle # value = <FontStyle.XXS: 8>
XXXL: omni.ui._ui.FontStyle # value = <FontStyle.XXL: 5>
XXXS: omni.ui._ui.FontStyle # value = <FontStyle.XXXS: 9>
__members__: dict # value = {'NONE': <FontStyle.NONE: 0>, 'NORMAL': <FontStyle.NORMAL: 1>, 'LARGE': <FontStyle.LARGE: 2>, 'SMALL': <FontStyle.SMALL: 3>, 'EXTRA_LARGE': <FontStyle.EXTRA_LARGE: 4>, 'XXL': <FontStyle.XXL: 5>, 'XXXL': <FontStyle.XXL: 5>, 'EXTRA_SMALL': <FontStyle.EXTRA_SMALL: 7>, 'XXS': <FontStyle.XXS: 8>, 'XXXS': <FontStyle.XXXS: 9>, 'ULTRA': <FontStyle.ULTRA: 10>}
pass
class Fraction(Length):
"""
Fraction length is made to take the space of the parent widget, divides it up into a row of boxes, and makes each child widget fill one box.
"""
def __init__(self, value: float) -> None:
"""
Construct Fraction.
`kwargs : dict`
See below
### Keyword Arguments:
"""
pass
class Frame(Container, Widget):
"""
The Frame is a widget that can hold one child widget.
Frame is used to crop the contents of a child widget or to draw small widget in a big view. The child widget must be specified with addChild().
"""
def __init__(self, **kwargs) -> None:
"""
Constructs Frame.
`kwargs : dict`
See below
### Keyword Arguments:
`horizontal_clipping : `
When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for horizontal direction.
`vertical_clipping : `
When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for vertial direction.
`separate_window : `
A special mode where the child is placed to the transparent borderless window. We need it to be able to place the UI to the exact stacking order between other windows.
`raster_policy : `
Determine how the content of the frame should be rasterized.
`build_fn : `
Set the callback that will be called once the frame is visible and the content of the callback will override the frame child. It's useful for lazy load.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
def call_build_fn(self) -> None:
"""
Set the callback that will be called once the frame is visible and the content of the callback will override the frame child. It's useful for lazy load.
"""
def has_build_fn(self) -> bool:
"""
Set the callback that will be called once the frame is visible and the content of the callback will override the frame child. It's useful for lazy load.
"""
def invalidate_raster(self) -> None:
"""
This method regenerates the raster image of the widget, even if the widget's content has not changed. This can be used with both the eOnDemand and eAuto raster policies, and is used to update the content displayed in the widget. Note that this operation may be resource-intensive, and should be used sparingly.
"""
def rebuild(self) -> None:
"""
After this method is called, the next drawing cycle build_fn will be called again to rebuild everything.
"""
def set_build_fn(self, fn: typing.Callable[[], None]) -> None:
"""
Set the callback that will be called once the frame is visible and the content of the callback will override the frame child. It's useful for lazy load.
"""
@property
def frozen(self) -> bool:
"""
A special mode where the child is placed to the transparent borderless window. We need it to be able to place the UI to the exact stacking order between other windows.
:type: bool
"""
@frozen.setter
def frozen(self, arg1: bool) -> None:
"""
A special mode where the child is placed to the transparent borderless window. We need it to be able to place the UI to the exact stacking order between other windows.
"""
@property
def horizontal_clipping(self) -> bool:
"""
When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for horizontal direction.
:type: bool
"""
@horizontal_clipping.setter
def horizontal_clipping(self, arg1: bool) -> None:
"""
When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for horizontal direction.
"""
@property
def raster_policy(self) -> RasterPolicy:
"""
Determine how the content of the frame should be rasterized.
:type: RasterPolicy
"""
@raster_policy.setter
def raster_policy(self, arg1: RasterPolicy) -> None:
"""
Determine how the content of the frame should be rasterized.
"""
@property
def separate_window(self) -> bool:
"""
A special mode where the child is placed to the transparent borderless window. We need it to be able to place the UI to the exact stacking order between other windows.
:type: bool
"""
@separate_window.setter
def separate_window(self, arg1: bool) -> None:
"""
A special mode where the child is placed to the transparent borderless window. We need it to be able to place the UI to the exact stacking order between other windows.
"""
@property
def vertical_clipping(self) -> bool:
"""
When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for vertial direction.
:type: bool
"""
@vertical_clipping.setter
def vertical_clipping(self, arg1: bool) -> None:
"""
When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for vertial direction.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class FreeBezierCurve(BezierCurve, Shape, Widget, ArrowHelper):
"""
Smooth curve that can be scaled infinitely.
The free widget is the widget that is independent of the layout. It means it is stuck to other widgets. When initializing, it's necessary to provide two widgets, and the shape is drawn from one widget position to the another.
"""
def __init__(self, arg0: Widget, arg1: Widget, **kwargs) -> None:
"""
Initialize the the shape with bounds limited to the positions of the given widgets.
### Arguments:
`start :`
The bound corder is in the center of this given widget.
`end :`
The bound corder is in the center of this given widget.
`kwargs : dict`
See below
### Keyword Arguments:
start_tangent_width: This property holds the X coordinate of the start of the curve relative to the width bound of the curve.
start_tangent_height: This property holds the Y coordinate of the start of the curve relative to the width bound of the curve.
end_tangent_width: This property holds the X coordinate of the end of the curve relative to the width bound of the curve.
end_tangent_height: This property holds the Y coordinate of the end of the curve relative to the width bound of the curve.
set_mouse_hovered_fn: Sets the function that will be called when the user use mouse enter/leave on the line. It's the override to prevent Widget from the bounding box logic. The function specification is: void onMouseHovered(bool hovered)
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class FreeCircle(Circle, Shape, Widget):
"""
The Circle widget provides a colored circle to display.
The free widget is the widget that is independent of the layout. It means it is stuck to other widgets. When initializing, it's necessary to provide two widgets, and the shape is drawn from one widget position to the another.
"""
def __init__(self, arg0: Widget, arg1: Widget, **kwargs) -> None:
"""
Initialize the the shape with bounds limited to the positions of the given widgets.
### Arguments:
`start :`
The bound corder is in the center of this given widget.
`end :`
The bound corder is in the center of this given widget.
`kwargs : dict`
See below
### Keyword Arguments:
`alignment :`
This property holds the alignment of the circle when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the circle is centered.
`radius :`
This property holds the radius of the circle when the fill policy is eFixed or eFixedCrop. By default, the circle radius is 0.
`arc :`
This property is the way to draw a half or a quarter of the circle. When it's eLeft, only left side of the circle is rendered. When it's eLeftTop, only left top quarter is rendered.
`size_policy :`
Define what happens when the source image has a different size than the item.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class FreeEllipse(Ellipse, Shape, Widget):
"""
The Ellipse widget provides a colored ellipse to display.
The free widget is the widget that is independent of the layout. It means it is stuck to other widgets. When initializing, it's necessary to provide two widgets, and the shape is drawn from one widget position to the another.
"""
def __init__(self, arg0: Widget, arg1: Widget, **kwargs) -> None:
"""
Initialize the the shape with bounds limited to the positions of the given widgets.
### Arguments:
`start :`
The bound corder is in the center of this given widget.
`end :`
The bound corder is in the center of this given widget.
`kwargs : dict`
See below
### Keyword Arguments:
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class FreeLine(Line, Shape, Widget, ArrowHelper):
"""
The Line widget provides a colored line to display.
The free widget is the widget that is independent of the layout. It means it is stuck to other widgets. When initializing, it's necessary to provide two widgets, and the shape is drawn from one widget position to the another.
"""
def __init__(self, arg0: Widget, arg1: Widget, **kwargs) -> None:
"""
Initialize the the shape with bounds limited to the positions of the given widgets.
### Arguments:
`start :`
The bound corder is in the center of this given widget.
`end :`
The bound corder is in the center of this given widget.
`kwargs : dict`
See below
### Keyword Arguments:
`alignment : `
This property holds the alignment of the Line can only LEFT, RIGHT, VCENTER, HCENTER , BOTTOM, TOP. By default, the Line is HCenter.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class FreeRectangle(Rectangle, Shape, Widget):
"""
The Rectangle widget provides a colored rectangle to display.
The free widget is the widget that is independent of the layout. It means it is stuck to other widgets. When initializing, it's necessary to provide two widgets, and the shape is drawn from one widget position to the another.
"""
def __init__(self, arg0: Widget, arg1: Widget, **kwargs) -> None:
"""
Initialize the the shape with bounds limited to the positions of the given widgets.
### Arguments:
`start :`
The bound corder is in the center of this given widget.
`end :`
The bound corder is in the center of this given widget.
`kwargs : dict`
See below
### Keyword Arguments:
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class FreeTriangle(Triangle, Shape, Widget):
"""
The Triangle widget provides a colored triangle to display.
The free widget is the widget that is independent of the layout. It means it is stuck to other widgets. When initializing, it's necessary to provide two widgets, and the shape is drawn from one widget position to the another.
"""
def __init__(self, arg0: Widget, arg1: Widget, **kwargs) -> None:
"""
Initialize the the shape with bounds limited to the positions of the given widgets.
### Arguments:
`start :`
The bound corder is in the center of this given widget.
`end :`
The bound corder is in the center of this given widget.
`kwargs : dict`
See below
### Keyword Arguments:
`alignment : `
This property holds the alignment of the triangle when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the triangle is centered.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class HGrid(Grid, Stack, Container, Widget):
"""
Shortcut for Grid{eLeftToRight}. The grid grows from left to right with the widgets placed.
"""
def __init__(self, **kwargs) -> None:
"""
Construct a grid that grow from left to right with the widgets placed.
`kwargs : dict`
See below
### Keyword Arguments:
`column_width : `
The width of the column. It's only possible to set it if the grid is vertical. Once it's set, the column count depends on the size of the widget.
`row_height : `
The height of the row. It's only possible to set it if the grid is horizontal. Once it's set, the row count depends on the size of the widget.
`column_count : `
The number of columns. It's only possible to set it if the grid is vertical. Once it's set, the column width depends on the widget size.
`row_count : `
The number of rows. It's only possible to set it if the grid is horizontal. Once it's set, the row height depends on the widget size.
`direction : `
This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front.
`content_clipping : `
Determines if the child widgets should be clipped by the rectangle of this Stack.
`spacing : `
Sets a non-stretchable space in pixels between child items of this layout.
`send_mouse_events_to_back : `
When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class Grid(Stack, Container, Widget):
"""
Grid is a container that arranges its child views in a grid. The grid vertical/horizontal direction is the direction the grid size growing with creating more children.
"""
def __init__(self, arg0: Direction, **kwargs) -> None:
"""
Constructor.
### Arguments:
`direction :`
Determines the direction the widget grows when adding more children.
`kwargs : dict`
See below
### Keyword Arguments:
`column_width : `
The width of the column. It's only possible to set it if the grid is vertical. Once it's set, the column count depends on the size of the widget.
`row_height : `
The height of the row. It's only possible to set it if the grid is horizontal. Once it's set, the row count depends on the size of the widget.
`column_count : `
The number of columns. It's only possible to set it if the grid is vertical. Once it's set, the column width depends on the widget size.
`row_count : `
The number of rows. It's only possible to set it if the grid is horizontal. Once it's set, the row height depends on the widget size.
`direction : `
This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front.
`content_clipping : `
Determines if the child widgets should be clipped by the rectangle of this Stack.
`spacing : `
Sets a non-stretchable space in pixels between child items of this layout.
`send_mouse_events_to_back : `
When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@property
def column_count(self) -> int:
"""
The number of columns. It's only possible to set it if the grid is vertical. Once it's set, the column width depends on the widget size.
:type: int
"""
@column_count.setter
def column_count(self, arg1: int) -> None:
"""
The number of columns. It's only possible to set it if the grid is vertical. Once it's set, the column width depends on the widget size.
"""
@property
def column_width(self) -> float:
"""
The width of the column. It's only possible to set it if the grid is vertical. Once it's set, the column count depends on the size of the widget.
:type: float
"""
@column_width.setter
def column_width(self, arg1: float) -> None:
"""
The width of the column. It's only possible to set it if the grid is vertical. Once it's set, the column count depends on the size of the widget.
"""
@property
def row_count(self) -> int:
"""
The number of rows. It's only possible to set it if the grid is horizontal. Once it's set, the row height depends on the widget size.
:type: int
"""
@row_count.setter
def row_count(self, arg1: int) -> None:
"""
The number of rows. It's only possible to set it if the grid is horizontal. Once it's set, the row height depends on the widget size.
"""
@property
def row_height(self) -> float:
"""
The height of the row. It's only possible to set it if the grid is horizontal. Once it's set, the row count depends on the size of the widget.
:type: float
"""
@row_height.setter
def row_height(self, arg1: float) -> None:
"""
The height of the row. It's only possible to set it if the grid is horizontal. Once it's set, the row count depends on the size of the widget.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class HStack(Stack, Container, Widget):
"""
Shortcut for Stack{eLeftToRight}. The widgets are placed in a row, with suitable sizes.
"""
def __init__(self, **kwargs) -> None:
"""
Construct a stack with the widgets placed in a row from left to right.
`kwargs : dict`
See below
### Keyword Arguments:
`direction : `
This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front.
`content_clipping : `
Determines if the child widgets should be clipped by the rectangle of this Stack.
`spacing : `
Sets a non-stretchable space in pixels between child items of this layout.
`send_mouse_events_to_back : `
When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class Image(Widget):
"""
The Image widget displays an image.
The source of the image is specified as a URL using the source property. By default, specifying the width and height of the item causes the image to be scaled to that size. This behavior can be changed by setting the fill_mode property, allowing the image to be stretched or scaled instead. The property alignment controls where to align the scaled image.
"""
@typing.overload
def __init__(self, arg0: str, **kwargs) -> None:
"""
Construct image with given url. If the url is empty, it gets the image URL from styling.
`kwargs : dict`
See below
### Keyword Arguments:
`alignment : `
This property holds the alignment of the image when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the image is centered.
`fill_policy : `
Define what happens when the source image has a different size than the item.
`pixel_aligned : `
Prevents image blurring when it's placed to fractional position (like x=0.5, y=0.5)
`progress_changed_fn : `
The progress of the image loading.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
Construct image with given url. If the url is empty, it gets the image URL from styling.
`kwargs : dict`
See below
### Keyword Arguments:
`alignment : `
This property holds the alignment of the image when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the image is centered.
`fill_policy : `
Define what happens when the source image has a different size than the item.
`pixel_aligned : `
Prevents image blurring when it's placed to fractional position (like x=0.5, y=0.5)
`progress_changed_fn : `
The progress of the image loading.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@typing.overload
def __init__(self, **kwargs) -> None: ...
def set_progress_changed_fn(self, fn: typing.Callable[[float], None]) -> None:
"""
The progress of the image loading.
"""
@property
def alignment(self) -> Alignment:
"""
This property holds the alignment of the image when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the image is centered.
:type: Alignment
"""
@alignment.setter
def alignment(self, arg1: Alignment) -> None:
"""
This property holds the alignment of the image when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the image is centered.
"""
@property
def fill_policy(self) -> FillPolicy:
"""
Define what happens when the source image has a different size than the item.
:type: FillPolicy
"""
@fill_policy.setter
def fill_policy(self, arg1: FillPolicy) -> None:
"""
Define what happens when the source image has a different size than the item.
"""
@property
def pixel_aligned(self) -> bool:
"""
Prevents image blurring when it's placed to fractional position (like x=0.5, y=0.5)
:type: bool
"""
@pixel_aligned.setter
def pixel_aligned(self, arg1: bool) -> None:
"""
Prevents image blurring when it's placed to fractional position (like x=0.5, y=0.5)
"""
@property
def source_url(self) -> str:
"""
This property holds the image URL. It can be an
omni:
file:
:type: str
"""
@source_url.setter
def source_url(self, arg1: str) -> None:
"""
This property holds the image URL. It can be an
omni:
file:
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class ImageProvider():
"""
ImageProvider class, the goal of this class is to provide ImGui reference for the image to be rendered.
"""
def __init__(self, **kwargs) -> None:
"""
doc
"""
def destroy(self) -> None: ...
def get_managed_resource(self) -> omni.gpu_foundation_factory._gpu_foundation_factory.RpResource: ...
@typing.overload
def set_image_data(self, arg0: capsule, arg1: int, arg2: int, arg3: omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat) -> None: ...
@typing.overload
def set_image_data(self, rp_resource: omni.gpu_foundation_factory._gpu_foundation_factory.RpResource, presentation_key: int = 0) -> None: ...
@property
def height(self) -> int:
"""
Gets image height.
:type: int
"""
@property
def is_reference_valid(self) -> bool:
"""
Returns true if ImGui reference is valid, false otherwise.
:type: bool
"""
@property
def width(self) -> int:
"""
Gets image width.
:type: int
"""
pass
class ImageWithProvider(Widget):
"""
The Image widget displays an image.
The source of the image is specified as a URL using the source property. By default, specifying the width and height of the item causes the image to be scaled to that size. This behavior can be changed by setting the fill_mode property, allowing the image to be stretched or scaled instead. The property alignment controls where to align the scaled image.
"""
@typing.overload
def __init__(self, arg0: ImageProvider, **kwargs) -> None:
"""
Construct image with given ImageProvider. If the ImageProvider is nullptr, it gets the image URL from styling.
`kwargs : dict`
See below
### Keyword Arguments:
`alignment : `
This property holds the alignment of the image when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the image is centered.
`fill_policy : `
Define what happens when the source image has a different size than the item.
`pixel_aligned : `
Prevents image blurring when it's placed to fractional position (like x=0.5, y=0.5)
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@typing.overload
def __init__(self, arg0: str, **kwargs) -> None: ...
@typing.overload
def __init__(self, **kwargs) -> None: ...
def prepare_draw(self, width: float, height: float) -> None:
"""
Force call `ImageProvider::prepareDraw` to ensure the next draw call the image is loaded. It can be used to load the image for a hidden widget or to set the rasterization resolution.
"""
@property
def alignment(self) -> Alignment:
"""
This property holds the alignment of the image when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the image is centered.
:type: Alignment
"""
@alignment.setter
def alignment(self, arg1: Alignment) -> None:
"""
This property holds the alignment of the image when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the image is centered.
"""
@property
def fill_policy(self) -> IwpFillPolicy:
"""
Define what happens when the source image has a different size than the item.
:type: IwpFillPolicy
"""
@fill_policy.setter
def fill_policy(self, arg1: IwpFillPolicy) -> None:
"""
Define what happens when the source image has a different size than the item.
"""
@property
def pixel_aligned(self) -> bool:
"""
Prevents image blurring when it's placed to fractional position (like x=0.5, y=0.5)
:type: bool
"""
@pixel_aligned.setter
def pixel_aligned(self, arg1: bool) -> None:
"""
Prevents image blurring when it's placed to fractional position (like x=0.5, y=0.5)
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class Inspector():
"""
Inspector is the helper to check the internal state of the widget. It's not recommended to use it for the routine UI.
"""
@staticmethod
def begin_computed_height_metric() -> None:
"""
Start counting how many times Widget::setComputedHeight is called
"""
@staticmethod
def begin_computed_width_metric() -> None:
"""
Start counting how many times Widget::setComputedWidth is called
"""
@staticmethod
def end_computed_height_metric() -> int:
"""
Start counting how many times Widget::setComputedHeight is called and return the number
"""
@staticmethod
def end_computed_width_metric() -> int:
"""
Start counting how many times Widget::setComputedWidth is called and return the number
"""
@staticmethod
def get_children(widget: Widget) -> typing.List[Widget]:
"""
Get the children of the given Widget.
"""
@staticmethod
def get_resolved_style(*args, **kwargs) -> typing.Any:
"""
Get the resolved style of the given Widget.
"""
@staticmethod
def get_stored_font_atlases() -> typing.List[typing.Tuple[str, int]]:
"""
Provides the information about font atlases
"""
pass
class IntDrag(IntSlider, AbstractSlider, Widget, ValueModelHelper):
"""
The drag widget that looks like a field but it's possible to change the value with dragging.
"""
def __init__(self, model: AbstractValueModel = None, **kwargs) -> None:
"""
Constructs IntDrag.
### Arguments:
`model :`
The widget's model. If the model is not assigned, the default model is created.
`kwargs : dict`
See below
### Keyword Arguments:
`step : `
This property controls the steping speed on the drag, its float to enable slower speed, but of course the value on the Control are still integer.
`min : `
This property holds the slider's minimum value.
`max : `
This property holds the slider's maximum value.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@property
def step(self) -> float:
"""
This property controls the steping speed on the drag, its float to enable slower speed, but of course the value on the Control are still integer.
:type: float
"""
@step.setter
def step(self, arg1: float) -> None:
"""
This property controls the steping speed on the drag, its float to enable slower speed, but of course the value on the Control are still integer.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class IntField(AbstractField, Widget, ValueModelHelper):
"""
The IntField widget is a one-line text editor with a string model.
"""
def __init__(self, model: AbstractValueModel = None, **kwargs) -> None:
"""
Construct IntField.
`kwargs : dict`
See below
### Keyword Arguments:
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class IntSlider(AbstractSlider, Widget, ValueModelHelper):
"""
The slider is the classic widget for controlling a bounded value. It lets the user move a slider handle along a horizontal groove and translates the handle's position into an integer value within the legal range.
"""
def __init__(self, model: AbstractValueModel = None, **kwargs) -> None:
"""
Constructs IntSlider.
### Arguments:
`model :`
The widget's model. If the model is not assigned, the default model is created.
`kwargs : dict`
See below
### Keyword Arguments:
`min : `
This property holds the slider's minimum value.
`max : `
This property holds the slider's maximum value.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@property
def max(self) -> int:
"""
This property holds the slider's maximum value.
:type: int
"""
@max.setter
def max(self, arg1: int) -> None:
"""
This property holds the slider's maximum value.
"""
@property
def min(self) -> int:
"""
This property holds the slider's minimum value.
:type: int
"""
@min.setter
def min(self, arg1: int) -> None:
"""
This property holds the slider's minimum value.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class InvisibleButton(Widget):
"""
The InvisibleButton widget provides a transparent command button.
"""
def __init__(self, **kwargs) -> None:
"""
Constructor.
`kwargs : dict`
See below
### Keyword Arguments:
`clicked_fn : Callable[[], None]`
Sets the function that will be called when when the button is activated (i.e., pressed down then released while the mouse cursor is inside the button).
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
def call_clicked_fn(self) -> None:
"""
Sets the function that will be called when when the button is activated (i.e., pressed down then released while the mouse cursor is inside the button).
"""
def has_clicked_fn(self) -> bool:
"""
Sets the function that will be called when when the button is activated (i.e., pressed down then released while the mouse cursor is inside the button).
"""
def set_clicked_fn(self, fn: typing.Callable[[], None]) -> None:
"""
Sets the function that will be called when when the button is activated (i.e., pressed down then released while the mouse cursor is inside the button).
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class ItemModelHelper():
"""
The ItemModelHelper class provides the basic functionality for item widget classes.
"""
@property
def model(self) -> AbstractItemModel:
"""
Returns the current model.
:type: AbstractItemModel
"""
@model.setter
def model(self, arg1: AbstractItemModel) -> None:
"""
Returns the current model.
"""
pass
class IwpFillPolicy():
"""
Members:
IWP_STRETCH
IWP_PRESERVE_ASPECT_FIT
IWP_PRESERVE_ASPECT_CROP
"""
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
"""
IWP_PRESERVE_ASPECT_CROP: omni.ui._ui.IwpFillPolicy # value = <IwpFillPolicy.IWP_PRESERVE_ASPECT_CROP: 2>
IWP_PRESERVE_ASPECT_FIT: omni.ui._ui.IwpFillPolicy # value = <IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT: 1>
IWP_STRETCH: omni.ui._ui.IwpFillPolicy # value = <IwpFillPolicy.IWP_STRETCH: 0>
__members__: dict # value = {'IWP_STRETCH': <IwpFillPolicy.IWP_STRETCH: 0>, 'IWP_PRESERVE_ASPECT_FIT': <IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT: 1>, 'IWP_PRESERVE_ASPECT_CROP': <IwpFillPolicy.IWP_PRESERVE_ASPECT_CROP: 2>}
pass
class Label(Widget):
"""
The Label widget provides a text to display.
Label is used for displaying text. No additional to Widget user interaction functionality is provided.
"""
def __init__(self, arg0: str, **kwargs) -> None:
"""
Create a label with the given text.
### Arguments:
`text :`
The text for the label.
`kwargs : dict`
See below
### Keyword Arguments:
`alignment : `
This property holds the alignment of the label's contents. By default, the contents of the label are left-aligned and vertically-centered.
`word_wrap : `
This property holds the label's word-wrapping policy If this property is true then label text is wrapped where necessary at word-breaks; otherwise it is not wrapped at all. By default, word wrap is disabled.
`elided_text : `
When the text of a big length has to be displayed in a small area, it can be useful to give the user a visual hint that not all text is visible. Label can elide text that doesn't fit in the area. When this property is true, Label elides the middle of the last visible line and replaces it with "...".
`elided_text_str : `
Customized elidedText string when elidedText is True, default is ....
`hide_text_after_hash : `
Hide anything after a '##' string or not
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@property
def alignment(self) -> Alignment:
"""
This property holds the alignment of the label's contents. By default, the contents of the label are left-aligned and vertically-centered.
:type: Alignment
"""
@alignment.setter
def alignment(self, arg1: Alignment) -> None:
"""
This property holds the alignment of the label's contents. By default, the contents of the label are left-aligned and vertically-centered.
"""
@property
def elided_text(self) -> bool:
"""
When the text of a big length has to be displayed in a small area, it can be useful to give the user a visual hint that not all text is visible. Label can elide text that doesn't fit in the area. When this property is true, Label elides the middle of the last visible line and replaces it with "...".
:type: bool
"""
@elided_text.setter
def elided_text(self, arg1: bool) -> None:
"""
When the text of a big length has to be displayed in a small area, it can be useful to give the user a visual hint that not all text is visible. Label can elide text that doesn't fit in the area. When this property is true, Label elides the middle of the last visible line and replaces it with "...".
"""
@property
def elided_text_str(self) -> str:
"""
Customized elidedText string when elidedText is True, default is ....
:type: str
"""
@elided_text_str.setter
def elided_text_str(self, arg1: str) -> None:
"""
Customized elidedText string when elidedText is True, default is ....
"""
@property
def exact_content_height(self) -> float:
"""
Return the exact height of the content of this label. Computed content height is a size hint and may be bigger than the text in the label.
:type: float
"""
@property
def exact_content_width(self) -> float:
"""
Return the exact width of the content of this label. Computed content width is a size hint and may be bigger than the text in the label.
:type: float
"""
@property
def hide_text_after_hash(self) -> bool:
"""
Hide anything after a '##' string or not
:type: bool
"""
@hide_text_after_hash.setter
def hide_text_after_hash(self, arg1: bool) -> None:
"""
Hide anything after a '##' string or not
"""
@property
def text(self) -> str:
"""
This property holds the label's text.
:type: str
"""
@text.setter
def text(self, arg1: str) -> None:
"""
This property holds the label's text.
"""
@property
def word_wrap(self) -> bool:
"""
This property holds the label's word-wrapping policy If this property is true then label text is wrapped where necessary at word-breaks; otherwise it is not wrapped at all. By default, word wrap is disabled.
:type: bool
"""
@word_wrap.setter
def word_wrap(self, arg1: bool) -> None:
"""
This property holds the label's word-wrapping policy If this property is true then label text is wrapped where necessary at word-breaks; otherwise it is not wrapped at all. By default, word wrap is disabled.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class Length():
"""
OMNI.UI has several different units for expressing a length.
Many widget properties take "Length" values, such as width, height, minWidth, minHeight, etc. Pixel is the absolute length unit. Percent and Fraction are relative length units, and they specify a length relative to the parent length. Relative length units are scaled with the parent.
"""
def __add__(self, value: float) -> float: ...
def __float__(self) -> float: ...
def __iadd__(self, value: float) -> float: ...
def __imul__(self, value: float) -> Length: ...
@staticmethod
@typing.overload
def __init__(*args, **kwargs) -> typing.Any:
"""
Construct Length.
`kwargs : dict`
See below
### Keyword Arguments:
"""
@typing.overload
def __init__(self, arg0: float) -> None: ...
@typing.overload
def __init__(self, arg0: int) -> None: ...
def __isub__(self, value: float) -> float: ...
def __itruediv__(self, value: float) -> Length: ...
def __mul__(self, value: float) -> Length: ...
def __radd__(self, value: float) -> float: ...
def __repr__(self) -> str: ...
def __rmul__(self, value: float) -> Length: ...
def __rsub__(self, value: float) -> float: ...
def __rtruediv__(self, value: float) -> Length: ...
def __str__(self) -> str: ...
def __sub__(self, value: float) -> float: ...
def __truediv__(self, value: float) -> Length: ...
@property
def unit(self) -> omni::ui::UnitType:
"""
(:obj:`.UnitType.`) Unit.
:type: omni::ui::UnitType
"""
@unit.setter
def unit(self, arg0: omni::ui::UnitType) -> None:
"""
(:obj:`.UnitType.`) Unit.
"""
@property
def value(self) -> float:
"""
(float) Value
:type: float
"""
@value.setter
def value(self, arg0: float) -> None:
"""
(float) Value
"""
pass
class Line(Shape, Widget, ArrowHelper):
"""
The Line widget provides a colored line to display.
"""
def __init__(self, **kwargs) -> None:
"""
Constructs Line.
`kwargs : dict`
See below
### Keyword Arguments:
`alignment : `
This property holds the alignment of the Line can only LEFT, RIGHT, VCENTER, HCENTER , BOTTOM, TOP. By default, the Line is HCenter.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@property
def alignment(self) -> Alignment:
"""
This property holds the alignment of the Line can only LEFT, RIGHT, VCENTER, HCENTER , BOTTOM, TOP. By default, the Line is HCenter.
:type: Alignment
"""
@alignment.setter
def alignment(self, arg1: Alignment) -> None:
"""
This property holds the alignment of the Line can only LEFT, RIGHT, VCENTER, HCENTER , BOTTOM, TOP. By default, the Line is HCenter.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class MainWindow():
"""
The MainWindow class represents Main Window for the Application, draw optional MainMenuBar and StatusBar.
"""
def __init__(self, show_foreground: bool = False, **kwargs) -> None:
"""
Construct the main window, add it to the underlying windowing system, and makes it appear.
`kwargs : dict`
See below
### Keyword Arguments:
"""
@property
def cpp_status_bar_enabled(self) -> bool:
"""
Workaround to reserve space for C++ status bar.
:type: bool
"""
@cpp_status_bar_enabled.setter
def cpp_status_bar_enabled(self, arg1: bool) -> None:
"""
Workaround to reserve space for C++ status bar.
"""
@property
def main_frame(self) -> Frame:
"""
This represents Styling opportunity for the Window background.
:type: Frame
"""
@property
def main_menu_bar(self) -> MenuBar:
"""
The main MenuBar for the application.
:type: MenuBar
"""
@property
def show_foreground(self) -> bool:
"""
When show_foreground is True, MainWindow prevents other windows from showing.
:type: bool
"""
@show_foreground.setter
def show_foreground(self, arg1: bool) -> None:
"""
When show_foreground is True, MainWindow prevents other windows from showing.
"""
@property
def status_bar_frame(self) -> Frame:
"""
The StatusBar Frame is empty by default and is meant to be filled by other part of the system.
:type: Frame
"""
pass
class MenuBar(Menu, Stack, Container, Widget, MenuHelper):
"""
The MenuBar class provides a MenuBar at the top of the Window, could also be the MainMenuBar of the MainWindow.
it can only contain Menu, at the moment there is no way to remove item appart from clearing it all together
"""
def __init__(self, **kwargs) -> None:
"""
Construct MenuBar.
`kwargs : dict`
See below
### Keyword Arguments:
`tearable : bool`
The ability to tear the window off.
`shown_changed_fn : `
If the pulldown menu is shown on the screen.
`teared_changed_fn : `
If the window is teared off.
`on_build_fn : `
Called to re-create new children.
`text : str`
This property holds the menu's text.
`hotkey_text : str`
This property holds the menu's hotkey text.
`checkable : bool`
This property holds whether this menu item is checkable. A checkable item is one which has an on/off state.
`hide_on_click : bool`
Hide or keep the window when the user clicked this item.
`delegate : MenuDelegate`
The delegate that generates a widget per menu item.
`triggered_fn : void`
Sets the function that is called when an action is activated by the user; for example, when the user clicks a menu option, or presses an action's shortcut key combination.
`direction : `
This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front.
`content_clipping : `
Determines if the child widgets should be clipped by the rectangle of this Stack.
`spacing : `
Sets a non-stretchable space in pixels between child items of this layout.
`send_mouse_events_to_back : `
When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class MenuItemCollection(Menu, Stack, Container, Widget, MenuHelper):
"""
The MenuItemCollection is the menu that unchecks children when one of them is checked.
"""
def __init__(self, text: str = '', **kwargs) -> None:
"""
Construct MenuItemCollection.
`kwargs : dict`
See below
### Keyword Arguments:
`tearable : bool`
The ability to tear the window off.
`shown_changed_fn : `
If the pulldown menu is shown on the screen.
`teared_changed_fn : `
If the window is teared off.
`on_build_fn : `
Called to re-create new children.
`text : str`
This property holds the menu's text.
`hotkey_text : str`
This property holds the menu's hotkey text.
`checkable : bool`
This property holds whether this menu item is checkable. A checkable item is one which has an on/off state.
`hide_on_click : bool`
Hide or keep the window when the user clicked this item.
`delegate : MenuDelegate`
The delegate that generates a widget per menu item.
`triggered_fn : void`
Sets the function that is called when an action is activated by the user; for example, when the user clicks a menu option, or presses an action's shortcut key combination.
`direction : `
This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front.
`content_clipping : `
Determines if the child widgets should be clipped by the rectangle of this Stack.
`spacing : `
Sets a non-stretchable space in pixels between child items of this layout.
`send_mouse_events_to_back : `
When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class Menu(Stack, Container, Widget, MenuHelper):
"""
The Menu class provides a menu widget for use in menu bars, context menus, and other popup menus.
It can be either a pull-down menu in a menu bar or a standalone context menu. Pull-down menus are shown by the menu bar when the user clicks on the respective item. Context menus are usually invoked by some special keyboard key or by right-clicking.
"""
def __init__(self, text: str = '', **kwargs) -> None:
"""
Construct Menu.
### Arguments:
`text :`
The text for the menu.
`kwargs : dict`
See below
### Keyword Arguments:
`tearable : bool`
The ability to tear the window off.
`shown_changed_fn : `
If the pulldown menu is shown on the screen.
`teared_changed_fn : `
If the window is teared off.
`on_build_fn : `
Called to re-create new children.
`text : str`
This property holds the menu's text.
`hotkey_text : str`
This property holds the menu's hotkey text.
`checkable : bool`
This property holds whether this menu item is checkable. A checkable item is one which has an on/off state.
`hide_on_click : bool`
Hide or keep the window when the user clicked this item.
`delegate : MenuDelegate`
The delegate that generates a widget per menu item.
`triggered_fn : void`
Sets the function that is called when an action is activated by the user; for example, when the user clicks a menu option, or presses an action's shortcut key combination.
`direction : `
This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front.
`content_clipping : `
Determines if the child widgets should be clipped by the rectangle of this Stack.
`spacing : `
Sets a non-stretchable space in pixels between child items of this layout.
`send_mouse_events_to_back : `
When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
def call_on_build_fn(self) -> None:
"""
Called to re-create new children.
"""
@staticmethod
def get_current() -> Menu:
"""
Return the menu that is currently shown.
"""
def has_on_build_fn(self) -> bool:
"""
Called to re-create new children.
"""
def hide(self) -> None:
"""
Close the menu window. It only works for pop-up context menu and for teared off menu.
"""
def invalidate(self) -> None:
"""
Make Menu dirty so onBuild will be executed to replace the children.
"""
def set_on_build_fn(self, fn: typing.Callable[[], None]) -> None:
"""
Called to re-create new children.
"""
def set_shown_changed_fn(self, fn: typing.Callable[[bool], None]) -> None:
"""
If the pulldown menu is shown on the screen.
"""
def set_teared_changed_fn(self, fn: typing.Callable[[bool], None]) -> None:
"""
If the window is teared off.
"""
def show(self) -> None:
"""
Create a popup window and show the menu in it. It's usually used for context menus that are typically invoked by some special keyboard key or by right-clicking.
"""
def show_at(self, arg0: float, arg1: float) -> None:
"""
Create a popup window and show the menu in it. This enable to popup the menu at specific position. X and Y are in points to make it easier to the Python users.
"""
@property
def shown(self) -> bool:
"""
If the pulldown menu is shown on the screen.
:type: bool
"""
@property
def tearable(self) -> bool:
"""
The ability to tear the window off.
:type: bool
"""
@tearable.setter
def tearable(self, arg1: bool) -> None:
"""
The ability to tear the window off.
"""
@property
def teared(self) -> bool:
"""
If the window is teared off.
:type: bool
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class MenuDelegate():
"""
MenuDelegate is used to generate widgets that represent the menu item.
"""
def __init__(self, **kwargs) -> None:
"""
Constructor.
`kwargs : dict`
See below
### Keyword Arguments:
`on_build_item : `
Called to create a new item.
`on_build_title : `
Called to create a new title.
`on_build_status : `
Called to create a new widget on the bottom of the window.
`propagate : `
Determine if Menu children should use this delegate when they don't have the own one.
"""
@staticmethod
def build_item(*args, **kwargs) -> typing.Any:
"""
This method must be reimplemented to generate custom item.
"""
@staticmethod
def build_status(*args, **kwargs) -> typing.Any:
"""
This method must be reimplemented to generate custom widgets on the bottom of the window.
"""
@staticmethod
def build_title(*args, **kwargs) -> typing.Any:
"""
This method must be reimplemented to generate custom title.
"""
@staticmethod
def call_on_build_item_fn(*args, **kwargs) -> typing.Any:
"""
Called to create a new item.
"""
@staticmethod
def call_on_build_status_fn(*args, **kwargs) -> typing.Any:
"""
Called to create a new widget on the bottom of the window.
"""
@staticmethod
def call_on_build_title_fn(*args, **kwargs) -> typing.Any:
"""
Called to create a new title.
"""
def has_on_build_item_fn(self) -> bool:
"""
Called to create a new item.
"""
def has_on_build_status_fn(self) -> bool:
"""
Called to create a new widget on the bottom of the window.
"""
def has_on_build_title_fn(self) -> bool:
"""
Called to create a new title.
"""
@staticmethod
def set_default_delegate(delegate: MenuDelegate) -> None:
"""
Set the default delegate to use it when the item doesn't have a delegate.
"""
@staticmethod
def set_on_build_item_fn(*args, **kwargs) -> typing.Any:
"""
Called to create a new item.
"""
@staticmethod
def set_on_build_status_fn(*args, **kwargs) -> typing.Any:
"""
Called to create a new widget on the bottom of the window.
"""
@staticmethod
def set_on_build_title_fn(*args, **kwargs) -> typing.Any:
"""
Called to create a new title.
"""
@property
def propagate(self) -> bool:
"""
:type: bool
"""
@propagate.setter
def propagate(self, arg1: bool) -> None:
pass
pass
class MenuItem(Widget, MenuHelper):
"""
A MenuItem represents the items the Menu consists of.
MenuItem can be inserted only once in the menu.
"""
def __init__(self, arg0: str, **kwargs) -> None:
"""
Construct MenuItem.
`kwargs : dict`
See below
### Keyword Arguments:
`text : str`
This property holds the menu's text.
`hotkey_text : str`
This property holds the menu's hotkey text.
`checkable : bool`
This property holds whether this menu item is checkable. A checkable item is one which has an on/off state.
`hide_on_click : bool`
Hide or keep the window when the user clicked this item.
`delegate : MenuDelegate`
The delegate that generates a widget per menu item.
`triggered_fn : void`
Sets the function that is called when an action is activated by the user; for example, when the user clicks a menu option, or presses an action's shortcut key combination.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class MenuHelper():
"""
The helper class for the menu that draws the menu line.
"""
def call_triggered_fn(self) -> None:
"""
Sets the function that is called when an action is activated by the user; for example, when the user clicks a menu option, or presses an action's shortcut key combination.
"""
def has_triggered_fn(self) -> bool:
"""
Sets the function that is called when an action is activated by the user; for example, when the user clicks a menu option, or presses an action's shortcut key combination.
"""
def set_triggered_fn(self, fn: typing.Callable[[], None]) -> None:
"""
Sets the function that is called when an action is activated by the user; for example, when the user clicks a menu option, or presses an action's shortcut key combination.
"""
@property
def checkable(self) -> bool:
"""
This property holds whether this menu item is checkable. A checkable item is one which has an on/off state.
:type: bool
"""
@checkable.setter
def checkable(self, arg1: bool) -> None:
"""
This property holds whether this menu item is checkable. A checkable item is one which has an on/off state.
"""
@property
def delegate(self) -> MenuDelegate:
"""
:type: MenuDelegate
"""
@delegate.setter
def delegate(self, arg1: MenuDelegate) -> None:
pass
@property
def hide_on_click(self) -> bool:
"""
Hide or keep the window when the user clicked this item.
:type: bool
"""
@hide_on_click.setter
def hide_on_click(self, arg1: bool) -> None:
"""
Hide or keep the window when the user clicked this item.
"""
@property
def hotkey_text(self) -> str:
"""
This property holds the menu's hotkey text.
:type: str
"""
@hotkey_text.setter
def hotkey_text(self, arg1: str) -> None:
"""
This property holds the menu's hotkey text.
"""
@property
def menu_compatibility(self) -> bool:
"""
:type: bool
"""
@menu_compatibility.setter
def menu_compatibility(self, arg1: bool) -> None:
pass
@property
def text(self) -> str:
"""
This property holds the menu's text.
:type: str
"""
@text.setter
def text(self, arg1: str) -> None:
"""
This property holds the menu's text.
"""
pass
class MultiFloatDragField(AbstractMultiField, Widget, ItemModelHelper):
"""
MultiFloatDragField is the widget that has a sub widget (FloatDrag) per model item.
It's handy to use it for multi-component data, like for example, float3 or color.
"""
@typing.overload
def __init__(self, **kwargs) -> None:
"""
Constructs MultiFloatDragField.
### Arguments:
`model :`
The widget's model. If the model is not assigned, the default model is created.
`kwargs : dict`
See below
### Keyword Arguments:
`min : `
This property holds the drag's minimum value.
`max : `
This property holds the drag's maximum value.
`step : `
This property controls the steping speed on the drag.
`column_count : `
The max number of fields in a line.
`h_spacing : `
Sets a non-stretchable horizontal space in pixels between child fields.
`v_spacing : `
Sets a non-stretchable vertical space in pixels between child fields.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@typing.overload
def __init__(self, arg0: AbstractItemModel, **kwargs) -> None: ...
@typing.overload
def __init__(self, *args, **kwargs) -> None: ...
@property
def max(self) -> float:
"""
This property holds the drag's maximum value.
:type: float
"""
@max.setter
def max(self, arg1: float) -> None:
"""
This property holds the drag's maximum value.
"""
@property
def min(self) -> float:
"""
This property holds the drag's minimum value.
:type: float
"""
@min.setter
def min(self, arg1: float) -> None:
"""
This property holds the drag's minimum value.
"""
@property
def step(self) -> float:
"""
This property controls the steping speed on the drag.
:type: float
"""
@step.setter
def step(self, arg1: float) -> None:
"""
This property controls the steping speed on the drag.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class MultiFloatField(AbstractMultiField, Widget, ItemModelHelper):
"""
MultiFloatField is the widget that has a sub widget (FloatField) per model item.
It's handy to use it for multi-component data, like for example, float3 or color.
"""
@typing.overload
def __init__(self, **kwargs) -> None:
"""
Constructor.
`kwargs : dict`
See below
### Keyword Arguments:
`column_count : `
The max number of fields in a line.
`h_spacing : `
Sets a non-stretchable horizontal space in pixels between child fields.
`v_spacing : `
Sets a non-stretchable vertical space in pixels between child fields.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@typing.overload
def __init__(self, arg0: AbstractItemModel, **kwargs) -> None: ...
@typing.overload
def __init__(self, *args, **kwargs) -> None: ...
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class MultiIntDragField(AbstractMultiField, Widget, ItemModelHelper):
"""
MultiIntDragField is the widget that has a sub widget (IntDrag) per model item.
It's handy to use it for multi-component data, like for example, int3.
"""
@typing.overload
def __init__(self, **kwargs) -> None:
"""
Constructs MultiIntDragField.
### Arguments:
`model :`
The widget's model. If the model is not assigned, the default model is created.
`kwargs : dict`
See below
### Keyword Arguments:
`min : `
This property holds the drag's minimum value.
`max : `
This property holds the drag's maximum value.
`step : `
This property controls the steping speed on the drag.
`column_count : `
The max number of fields in a line.
`h_spacing : `
Sets a non-stretchable horizontal space in pixels between child fields.
`v_spacing : `
Sets a non-stretchable vertical space in pixels between child fields.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@typing.overload
def __init__(self, arg0: AbstractItemModel, **kwargs) -> None: ...
@typing.overload
def __init__(self, *args, **kwargs) -> None: ...
@property
def max(self) -> int:
"""
This property holds the drag's maximum value.
:type: int
"""
@max.setter
def max(self, arg1: int) -> None:
"""
This property holds the drag's maximum value.
"""
@property
def min(self) -> int:
"""
This property holds the drag's minimum value.
:type: int
"""
@min.setter
def min(self, arg1: int) -> None:
"""
This property holds the drag's minimum value.
"""
@property
def step(self) -> float:
"""
This property controls the steping speed on the drag.
:type: float
"""
@step.setter
def step(self, arg1: float) -> None:
"""
This property controls the steping speed on the drag.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class MultiIntField(AbstractMultiField, Widget, ItemModelHelper):
"""
MultiIntField is the widget that has a sub widget (IntField) per model item.
It's handy to use it for multi-component data, like for example, int3.
"""
@typing.overload
def __init__(self, **kwargs) -> None:
"""
Constructor.
`kwargs : dict`
See below
### Keyword Arguments:
`column_count : `
The max number of fields in a line.
`h_spacing : `
Sets a non-stretchable horizontal space in pixels between child fields.
`v_spacing : `
Sets a non-stretchable vertical space in pixels between child fields.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@typing.overload
def __init__(self, arg0: AbstractItemModel, **kwargs) -> None: ...
@typing.overload
def __init__(self, *args, **kwargs) -> None: ...
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class MultiStringField(AbstractMultiField, Widget, ItemModelHelper):
"""
MultiStringField is the widget that has a sub widget (StringField) per model item.
It's handy to use it for string arrays.
"""
@typing.overload
def __init__(self, **kwargs) -> None:
"""
Constructor.
`kwargs : dict`
See below
### Keyword Arguments:
`column_count : `
The max number of fields in a line.
`h_spacing : `
Sets a non-stretchable horizontal space in pixels between child fields.
`v_spacing : `
Sets a non-stretchable vertical space in pixels between child fields.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@typing.overload
def __init__(self, arg0: AbstractItemModel, **kwargs) -> None: ...
@typing.overload
def __init__(self, *args, **kwargs) -> None: ...
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class OffsetLine(FreeLine, Line, Shape, Widget, ArrowHelper):
"""
The free widget is the widget that is independent of the layout. It draws the line stuck to the bounds of other widgets.
"""
def __init__(self, arg0: Widget, arg1: Widget, **kwargs) -> None: ...
@property
def bound_offset(self) -> float:
"""
The offset from the bounds of the widgets this line is stuck to.
:type: float
"""
@bound_offset.setter
def bound_offset(self, arg1: float) -> None:
"""
The offset from the bounds of the widgets this line is stuck to.
"""
@property
def offset(self) -> float:
"""
The offset to the direction of the line normal.
:type: float
"""
@offset.setter
def offset(self, arg1: float) -> None:
"""
The offset to the direction of the line normal.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class Percent(Length):
"""
Percent is the length in percents from the parent widget.
"""
def __init__(self, value: float) -> None:
"""
Construct Percent.
`kwargs : dict`
See below
### Keyword Arguments:
"""
pass
class Pixel(Length):
"""
Pixel length is exact length in pixels.
"""
def __init__(self, value: float) -> None:
"""
Construct Pixel.
`kwargs : dict`
See below
### Keyword Arguments:
"""
pass
class Placer(Container, Widget):
"""
The Placer class place a single widget to a particular position based on the offet.
"""
def __init__(self, **kwargs) -> None:
"""
Construct Placer.
`kwargs : dict`
See below
### Keyword Arguments:
`offset_x : toLength`
offsetX defines the offset placement for the child widget relative to the Placer
`offset_y : toLength`
offsetY defines the offset placement for the child widget relative to the Placer
`draggable : bool`
Provides a convenient way to make an item draggable.
`drag_axis : Axis`
Sets if dragging can be horizontally or vertically.
`stable_size : bool`
The placer size depends on the position of the child when false.
`raster_policy : `
Determine how the content of the frame should be rasterized.
`offset_x_changed_fn : Callable[[ui.Length], None]`
offsetX defines the offset placement for the child widget relative to the Placer
`offset_y_changed_fn : Callable[[ui.Length], None]`
offsetY defines the offset placement for the child widget relative to the Placer
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
def invalidate_raster(self) -> None:
"""
This method regenerates the raster image of the widget, even if the widget's content has not changed. This can be used with both the eOnDemand and eAuto raster policies, and is used to update the content displayed in the widget. Note that this operation may be resource-intensive, and should be used sparingly.
"""
def set_offset_x_changed_fn(self, arg0: typing.Callable[[Length], None]) -> None:
"""
offsetX defines the offset placement for the child widget relative to the Placer
"""
def set_offset_y_changed_fn(self, arg0: typing.Callable[[Length], None]) -> None:
"""
offsetY defines the offset placement for the child widget relative to the Placer
"""
@property
def drag_axis(self) -> Axis:
"""
Sets if dragging can be horizontally or vertically.
:type: Axis
"""
@drag_axis.setter
def drag_axis(self, arg1: Axis) -> None:
"""
Sets if dragging can be horizontally or vertically.
"""
@property
def draggable(self) -> bool:
"""
Provides a convenient way to make an item draggable.
:type: bool
"""
@draggable.setter
def draggable(self, arg1: bool) -> None:
"""
Provides a convenient way to make an item draggable.
"""
@property
def frames_to_start_drag(self) -> int:
"""
The placer size depends on the position of the child when false.
:type: int
"""
@frames_to_start_drag.setter
def frames_to_start_drag(self, arg1: int) -> None:
"""
The placer size depends on the position of the child when false.
"""
@property
def offset_x(self) -> Length:
"""
offsetX defines the offset placement for the child widget relative to the Placer
:type: Length
"""
@offset_x.setter
def offset_x(self, arg1: handle) -> None:
"""
offsetX defines the offset placement for the child widget relative to the Placer
"""
@property
def offset_y(self) -> Length:
"""
offsetY defines the offset placement for the child widget relative to the Placer
:type: Length
"""
@offset_y.setter
def offset_y(self, arg1: handle) -> None:
"""
offsetY defines the offset placement for the child widget relative to the Placer
"""
@property
def raster_policy(self) -> RasterPolicy:
"""
Determine how the content of the frame should be rasterized.
:type: RasterPolicy
"""
@raster_policy.setter
def raster_policy(self, arg1: RasterPolicy) -> None:
"""
Determine how the content of the frame should be rasterized.
"""
@property
def stable_size(self) -> bool:
"""
The placer size depends on the position of the child when false.
:type: bool
"""
@stable_size.setter
def stable_size(self, arg1: bool) -> None:
"""
The placer size depends on the position of the child when false.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class Plot(Widget):
"""
The Plot widget provides a line/histogram to display.
"""
def __init__(self, type: Type = Type.LINE, scale_min: float = 3.4028234663852886e+38, scale_max: float = 3.4028234663852886e+38, *args, **kwargs) -> None:
"""
Construct Plot.
### Arguments:
`type :`
The type of the image, can be line or histogram.
`scaleMin :`
The minimal scale value.
`scaleMax :`
The maximum scale value.
`valueList :`
The list of values to draw the image.
`kwargs : dict`
See below
### Keyword Arguments:
`value_offset : int`
This property holds the value offset. By default, the value is 0.
`value_stride : int`
This property holds the stride to get value list. By default, the value is 1.
`title : str`
This property holds the title of the image.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
def set_data(self, *args) -> None:
"""
Sets the image data value.
"""
def set_data_provider_fn(self, arg0: typing.Callable[[int], float], arg1: int) -> None:
"""
Sets the function that will be called when when data required.
"""
def set_xy_data(self, arg0: typing.List[typing.Tuple[float, float]]) -> None: ...
@property
def scale_max(self) -> float:
"""
This property holds the max scale values. By default, the value is FLT_MAX.
:type: float
"""
@scale_max.setter
def scale_max(self, arg1: float) -> None:
"""
This property holds the max scale values. By default, the value is FLT_MAX.
"""
@property
def scale_min(self) -> float:
"""
This property holds the min scale values. By default, the value is FLT_MAX.
:type: float
"""
@scale_min.setter
def scale_min(self, arg1: float) -> None:
"""
This property holds the min scale values. By default, the value is FLT_MAX.
"""
@property
def title(self) -> str:
"""
This property holds the title of the image.
:type: str
"""
@title.setter
def title(self, arg1: str) -> None:
"""
This property holds the title of the image.
"""
@property
def type(self) -> Type:
"""
This property holds the type of the image, can only be line or histogram. By default, the type is line.
:type: Type
"""
@type.setter
def type(self, arg1: Type) -> None:
"""
This property holds the type of the image, can only be line or histogram. By default, the type is line.
"""
@property
def value_offset(self) -> int:
"""
This property holds the value offset. By default, the value is 0.
:type: int
"""
@value_offset.setter
def value_offset(self, arg1: int) -> None:
"""
This property holds the value offset. By default, the value is 0.
"""
@property
def value_stride(self) -> int:
"""
This property holds the stride to get value list. By default, the value is 1.
:type: int
"""
@value_stride.setter
def value_stride(self, arg1: int) -> None:
"""
This property holds the stride to get value list. By default, the value is 1.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class ProgressBar(Widget, ValueModelHelper):
"""
A progressbar is a classic widget for showing the progress of an operation.
"""
def __init__(self, model: AbstractValueModel = None, **kwargs) -> None:
"""
Construct ProgressBar.
### Arguments:
`model :`
The model that determines if the button is checked.
`kwargs : dict`
See below
### Keyword Arguments:
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class RadioButton(Button, InvisibleButton, Widget):
"""
RadioButton is the widget that allows the user to choose only one of a predefined set of mutually exclusive options.
RadioButtons are arranged in collections of two or more with the class RadioCollection, which is the central component of the system and controls the behavior of all the RadioButtons in the collection.
"""
def __init__(self, **kwargs) -> None:
"""
Constructs RadioButton.
`kwargs : dict`
See below
### Keyword Arguments:
`radio_collection : `
This property holds the button's text.
`text : str`
This property holds the button's text.
`image_url : str`
This property holds the button's optional image URL.
`image_width : float`
This property holds the width of the image widget. Do not use this function to find the width of the image.
`image_height : float`
This property holds the height of the image widget. Do not use this function to find the height of the image.
`spacing : float`
Sets a non-stretchable space in points between image and text.
`clicked_fn : Callable[[], None]`
Sets the function that will be called when when the button is activated (i.e., pressed down then released while the mouse cursor is inside the button).
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@property
def radio_collection(self) -> RadioCollection:
"""
This property holds the button's text.
:type: RadioCollection
"""
@radio_collection.setter
def radio_collection(self, arg1: RadioCollection) -> None:
"""
This property holds the button's text.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class RadioCollection(ValueModelHelper):
"""
Radio Collection is a class that groups RadioButtons and coordinates their state.
It makes sure that the choice is mutually exclusive, it means when the user selects a radio button, any previously selected radio button in the same collection becomes deselected.
"""
def __init__(self, model: AbstractValueModel = None, **kwargs) -> None:
"""
Constructs RadioCollection.
`kwargs : dict`
See below
### Keyword Arguments:
"""
pass
class RasterImageProvider(ImageProvider):
"""
doc
"""
def __init__(self, source_url: str = None, **kwargs) -> None:
"""
doc
"""
@property
def max_mip_levels(self) -> int:
"""
Maximum number of mip map levels allowed
:type: int
"""
@max_mip_levels.setter
def max_mip_levels(self, arg1: int) -> None:
"""
Maximum number of mip map levels allowed
"""
@property
def source_url(self) -> str:
"""
Sets byte data that the image provider will turn into an image.
:type: str
"""
@source_url.setter
def source_url(self, arg1: str) -> None:
"""
Sets byte data that the image provider will turn into an image.
"""
pass
class RasterPolicy():
"""
Used to set the rasterization behaviour.
Members:
NEVER : Do not rasterize the widget at any time.
ON_DEMAND : Rasterize the widget as soon as possible and always use the rasterized version. This means that the widget will only be updated when the user called invalidateRaster.
AUTO : Automatically determine whether to rasterize the widget based on performance considerations. If necessary, the widget will be rasterized and updated when its content changes.
"""
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
"""
AUTO: omni.ui._ui.RasterPolicy # value = <RasterPolicy.AUTO: 2>
NEVER: omni.ui._ui.RasterPolicy # value = <RasterPolicy.NEVER: 0>
ON_DEMAND: omni.ui._ui.RasterPolicy # value = <RasterPolicy.ON_DEMAND: 1>
__members__: dict # value = {'NEVER': <RasterPolicy.NEVER: 0>, 'ON_DEMAND': <RasterPolicy.ON_DEMAND: 1>, 'AUTO': <RasterPolicy.AUTO: 2>}
pass
class Rectangle(Shape, Widget):
"""
The Rectangle widget provides a colored rectangle to display.
"""
def __init__(self, **kwargs) -> None:
"""
Constructs Rectangle.
`kwargs : dict`
See below
### Keyword Arguments:
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class ScrollBarPolicy():
"""
Members:
SCROLLBAR_AS_NEEDED
SCROLLBAR_ALWAYS_OFF
SCROLLBAR_ALWAYS_ON
"""
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
"""
SCROLLBAR_ALWAYS_OFF: omni.ui._ui.ScrollBarPolicy # value = <ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF: 1>
SCROLLBAR_ALWAYS_ON: omni.ui._ui.ScrollBarPolicy # value = <ScrollBarPolicy.SCROLLBAR_ALWAYS_ON: 2>
SCROLLBAR_AS_NEEDED: omni.ui._ui.ScrollBarPolicy # value = <ScrollBarPolicy.SCROLLBAR_AS_NEEDED: 0>
__members__: dict # value = {'SCROLLBAR_AS_NEEDED': <ScrollBarPolicy.SCROLLBAR_AS_NEEDED: 0>, 'SCROLLBAR_ALWAYS_OFF': <ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF: 1>, 'SCROLLBAR_ALWAYS_ON': <ScrollBarPolicy.SCROLLBAR_ALWAYS_ON: 2>}
pass
class ScrollingFrame(Frame, Container, Widget):
"""
The ScrollingFrame class provides the ability to scroll onto another widget.
ScrollingFrame is used to display the contents of a child widget within a frame. If the widget exceeds the size of the frame, the frame can provide scroll bars so that the entire area of the child widget can be viewed. The child widget must be specified with addChild().
"""
def __init__(self, **kwargs) -> None:
"""
Construct ScrollingFrame.
`kwargs : dict`
See below
### Keyword Arguments:
`scroll_x : float`
The horizontal position of the scroll bar. When it's changed, the contents will be scrolled accordingly.
`scroll_x_max : float`
The max position of the horizontal scroll bar.
`scroll_x_changed_fn : Callable[[float], None]`
The horizontal position of the scroll bar. When it's changed, the contents will be scrolled accordingly.
`scroll_y : float`
The vertical position of the scroll bar. When it's changed, the contents will be scrolled accordingly.
`scroll_y_max : float`
The max position of the vertical scroll bar.
`scroll_y_changed_fn : Callable[[float], None]`
The vertical position of the scroll bar. When it's changed, the contents will be scrolled accordingly.
`horizontal_scrollbar_policy : ui.ScrollBarPolicy`
This property holds the policy for the horizontal scroll bar.
`vertical_scrollbar_policy : ui.ScrollBarPolicy`
This property holds the policy for the vertical scroll bar.
`horizontal_clipping : `
When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for horizontal direction.
`vertical_clipping : `
When the content of the frame is bigger than the frame the exceeding part is not drawn if the clipping is on. It only works for vertial direction.
`separate_window : `
A special mode where the child is placed to the transparent borderless window. We need it to be able to place the UI to the exact stacking order between other windows.
`raster_policy : `
Determine how the content of the frame should be rasterized.
`build_fn : `
Set the callback that will be called once the frame is visible and the content of the callback will override the frame child. It's useful for lazy load.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
def set_scroll_x_changed_fn(self, arg0: typing.Callable[[float], None]) -> None:
"""
The horizontal position of the scroll bar. When it's changed, the contents will be scrolled accordingly.
"""
def set_scroll_y_changed_fn(self, arg0: typing.Callable[[float], None]) -> None:
"""
The vertical position of the scroll bar. When it's changed, the contents will be scrolled accordingly.
"""
@property
def horizontal_scrollbar_policy(self) -> ScrollBarPolicy:
"""
This property holds the policy for the horizontal scroll bar.
:type: ScrollBarPolicy
"""
@horizontal_scrollbar_policy.setter
def horizontal_scrollbar_policy(self, arg1: ScrollBarPolicy) -> None:
"""
This property holds the policy for the horizontal scroll bar.
"""
@property
def scroll_x(self) -> float:
"""
The horizontal position of the scroll bar. When it's changed, the contents will be scrolled accordingly.
:type: float
"""
@scroll_x.setter
def scroll_x(self, arg1: float) -> None:
"""
The horizontal position of the scroll bar. When it's changed, the contents will be scrolled accordingly.
"""
@property
def scroll_x_max(self) -> float:
"""
The max position of the horizontal scroll bar.
:type: float
"""
@property
def scroll_y(self) -> float:
"""
The vertical position of the scroll bar. When it's changed, the contents will be scrolled accordingly.
:type: float
"""
@scroll_y.setter
def scroll_y(self, arg1: float) -> None:
"""
The vertical position of the scroll bar. When it's changed, the contents will be scrolled accordingly.
"""
@property
def scroll_y_max(self) -> float:
"""
The max position of the vertical scroll bar.
:type: float
"""
@property
def vertical_scrollbar_policy(self) -> ScrollBarPolicy:
"""
This property holds the policy for the vertical scroll bar.
:type: ScrollBarPolicy
"""
@vertical_scrollbar_policy.setter
def vertical_scrollbar_policy(self, arg1: ScrollBarPolicy) -> None:
"""
This property holds the policy for the vertical scroll bar.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class Separator(Widget, MenuHelper):
"""
The Separator class provides blank space.
Normally, it's used to create separator line in the UI elements
"""
def __init__(self, text: str = '', **kwargs) -> None:
"""
Construct Separator.
`kwargs : dict`
See below
### Keyword Arguments:
`text : str`
This property holds the menu's text.
`hotkey_text : str`
This property holds the menu's hotkey text.
`checkable : bool`
This property holds whether this menu item is checkable. A checkable item is one which has an on/off state.
`hide_on_click : bool`
Hide or keep the window when the user clicked this item.
`delegate : MenuDelegate`
The delegate that generates a widget per menu item.
`triggered_fn : void`
Sets the function that is called when an action is activated by the user; for example, when the user clicks a menu option, or presses an action's shortcut key combination.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class ShadowFlag():
"""
Members:
NONE
CUT_OUT_SHAPE_BACKGROUND
"""
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
"""
CUT_OUT_SHAPE_BACKGROUND: omni.ui._ui.ShadowFlag # value = <ShadowFlag.CUT_OUT_SHAPE_BACKGROUND: 1>
NONE: omni.ui._ui.ShadowFlag # value = <ShadowFlag.NONE: 0>
__members__: dict # value = {'NONE': <ShadowFlag.NONE: 0>, 'CUT_OUT_SHAPE_BACKGROUND': <ShadowFlag.CUT_OUT_SHAPE_BACKGROUND: 1>}
pass
class Shape(Widget):
"""
The Shape widget provides a base class for all the Shape Widget. Currently implemented are Rectangle, Circle, Triangle, Line, Ellipse and BezierCurve.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class SimpleBoolModel(AbstractValueModel):
"""
A very simple bool model.
"""
def __init__(self, default_value: bool = False, **kwargs) -> None: ...
def get_max(self) -> bool: ...
def get_min(self) -> bool: ...
def set_max(self, arg0: bool) -> None: ...
def set_min(self, arg0: bool) -> None: ...
@property
def max(self) -> bool:
"""
This property holds the model's maximum value.
:type: bool
"""
@max.setter
def max(self, arg1: bool) -> None:
"""
This property holds the model's maximum value.
"""
@property
def min(self) -> bool:
"""
This property holds the model's minimum value.
:type: bool
"""
@min.setter
def min(self, arg1: bool) -> None:
"""
This property holds the model's minimum value.
"""
pass
class SimpleFloatModel(AbstractValueModel):
"""
A very simple double model.
"""
def __init__(self, default_value: float = 0.0, **kwargs) -> None: ...
def get_max(self) -> float: ...
def get_min(self) -> float: ...
def set_max(self, arg0: float) -> None: ...
def set_min(self, arg0: float) -> None: ...
@property
def max(self) -> float:
"""
This property holds the model's minimum value.
:type: float
"""
@max.setter
def max(self, arg1: float) -> None:
"""
This property holds the model's minimum value.
"""
@property
def min(self) -> float:
"""
This property holds the model's minimum value.
:type: float
"""
@min.setter
def min(self, arg1: float) -> None:
"""
This property holds the model's minimum value.
"""
pass
class SimpleIntModel(AbstractValueModel):
"""
A very simple Int model.
"""
def __init__(self, default_value: int = 0, **kwargs) -> None: ...
def get_max(self) -> int: ...
def get_min(self) -> int: ...
def set_max(self, arg0: int) -> None: ...
def set_min(self, arg0: int) -> None: ...
@property
def max(self) -> int:
"""
This property holds the model's minimum value.
:type: int
"""
@max.setter
def max(self, arg1: int) -> None:
"""
This property holds the model's minimum value.
"""
@property
def min(self) -> int:
"""
This property holds the model's minimum value.
:type: int
"""
@min.setter
def min(self, arg1: int) -> None:
"""
This property holds the model's minimum value.
"""
pass
class SimpleStringModel(AbstractValueModel):
"""
A very simple value model that holds a single string.
"""
def __init__(self, defaultValue: str = '') -> None: ...
pass
class SliderDrawMode():
"""
Members:
FILLED
HANDLE
DRAG
"""
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
"""
DRAG: omni.ui._ui.SliderDrawMode # value = <SliderDrawMode.DRAG: 2>
FILLED: omni.ui._ui.SliderDrawMode # value = <SliderDrawMode.FILLED: 0>
HANDLE: omni.ui._ui.SliderDrawMode # value = <SliderDrawMode.HANDLE: 1>
__members__: dict # value = {'FILLED': <SliderDrawMode.FILLED: 0>, 'HANDLE': <SliderDrawMode.HANDLE: 1>, 'DRAG': <SliderDrawMode.DRAG: 2>}
pass
class Spacer(Widget):
"""
The Spacer class provides blank space.
Normally, it's used to place other widgets correctly in a layout.
"""
def __init__(self, **kwargs) -> None:
"""
Construct Spacer.
`kwargs : dict`
See below
### Keyword Arguments:
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class Stack(Container, Widget):
"""
The Stack class lines up child widgets horizontally, vertically or sorted in a Z-order.
"""
def __init__(self, arg0: Direction, **kwargs) -> None:
"""
Constructor.
### Arguments:
`direction :`
Determines the orientation of the Stack.
`kwargs : dict`
See below
### Keyword Arguments:
`direction : `
This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front.
`content_clipping : `
Determines if the child widgets should be clipped by the rectangle of this Stack.
`spacing : `
Sets a non-stretchable space in pixels between child items of this layout.
`send_mouse_events_to_back : `
When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@property
def content_clipping(self) -> bool:
"""
Determines if the child widgets should be clipped by the rectangle of this Stack.
:type: bool
"""
@content_clipping.setter
def content_clipping(self, arg1: bool) -> None:
"""
Determines if the child widgets should be clipped by the rectangle of this Stack.
"""
@property
def direction(self) -> Direction:
"""
This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front.
:type: Direction
"""
@direction.setter
def direction(self, arg1: Direction) -> None:
"""
This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front.
"""
@property
def send_mouse_events_to_back(self) -> bool:
"""
When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child.
:type: bool
"""
@send_mouse_events_to_back.setter
def send_mouse_events_to_back(self, arg1: bool) -> None:
"""
When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child.
"""
@property
def spacing(self) -> float:
"""
Sets a non-stretchable space in pixels between child items of this layout.
:type: float
"""
@spacing.setter
def spacing(self, arg1: float) -> None:
"""
Sets a non-stretchable space in pixels between child items of this layout.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class StringField(AbstractField, Widget, ValueModelHelper):
"""
The StringField widget is a one-line text editor with a string model.
"""
def __init__(self, model: AbstractValueModel = None, **kwargs) -> None:
"""
Constructs StringField.
### Arguments:
`model :`
The widget's model. If the model is not assigned, the default model is created.
`kwargs : dict`
See below
### Keyword Arguments:
`password_mode : `
This property holds the password mode. If the field is in the password mode when the entered text is obscured.
`read_only : `
This property holds if the field is read-only.
`multiline : `
Multiline allows to press enter and create a new line.
`allow_tab_input : `
This property holds if the field allows Tab input.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@property
def allow_tab_input(self) -> bool:
"""
This property holds if the field allows Tab input.
:type: bool
"""
@allow_tab_input.setter
def allow_tab_input(self, arg1: bool) -> None:
"""
This property holds if the field allows Tab input.
"""
@property
def multiline(self) -> bool:
"""
Multiline allows to press enter and create a new line.
:type: bool
"""
@multiline.setter
def multiline(self, arg1: bool) -> None:
"""
Multiline allows to press enter and create a new line.
"""
@property
def password_mode(self) -> bool:
"""
This property holds the password mode. If the field is in the password mode when the entered text is obscured.
:type: bool
"""
@password_mode.setter
def password_mode(self, arg1: bool) -> None:
"""
This property holds the password mode. If the field is in the password mode when the entered text is obscured.
"""
@property
def read_only(self) -> bool:
"""
This property holds if the field is read-only.
:type: bool
"""
@read_only.setter
def read_only(self, arg1: bool) -> None:
"""
This property holds if the field is read-only.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class StringStore():
"""
A singleton that stores all the UI Style string properties of omni.ui.
"""
@staticmethod
def find(name: str) -> str:
"""
Return the index of the color with specific name.
"""
@staticmethod
def store(name: str, string: str) -> None:
"""
Save the color by name.
"""
pass
class Style():
"""
A singleton that controls the global style of the session.
"""
@staticmethod
def get_instance() -> Style:
"""
Get the instance of this singleton object.
"""
@property
def default(self) -> object:
"""
Set the default root style. It's the style that is preselected when no alternative is specified.
:type: object
"""
@default.setter
def default(self, arg1: handle) -> None:
"""
Set the default root style. It's the style that is preselected when no alternative is specified.
"""
pass
class ToolBar(Window, WindowHandle):
"""
The ToolBar class represents a window in the underlying windowing system that as some fixed size property.
"""
def __init__(self, title: str, **kwargs) -> None:
"""
Construct ToolBar.
`kwargs : dict`
See below
### Keyword Arguments:
`axis : ui.Axis`
@breif axis for the toolbar
`axis_changed_fn : Callable[[ui.Axis], None]`
@breif axis for the toolbar
`flags : `
This property set the Flags for the Window.
`visible : `
This property holds whether the window is visible.
`title : `
This property holds the window's title.
`padding_x : `
This property set the padding to the frame on the X axis.
`padding_y : `
This property set the padding to the frame on the Y axis.
`width : `
This property holds the window Width.
`height : `
This property holds the window Height.
`position_x : `
This property set/get the position of the window in the X Axis. The default is kWindowFloatInvalid because we send the window position to the underlying system only if the position is explicitly set by the user. Otherwise the underlying system decides the position.
`position_y : `
This property set/get the position of the window in the Y Axis. The default is kWindowFloatInvalid because we send the window position to the underlying system only if the position is explicitly set by the user. Otherwise the underlying system decides the position.
`auto_resize : `
setup the window to resize automatically based on its content
`noTabBar : `
setup the visibility of the TabBar Handle, this is the small triangle at the corner of the view If it is not shown then it is not possible to undock that window and it need to be closed/moved programatically
`raster_policy : `
Determine how the content of the window should be rastered.
`width_changed_fn : `
This property holds the window Width.
`height_changed_fn : `
This property holds the window Height.
`visibility_changed_fn : `
This property holds whether the window is visible.
"""
def set_axis_changed_fn(self, arg0: typing.Callable[[ToolBarAxis], None]) -> None: ...
@property
def axis(self) -> ToolBarAxis:
"""
:type: ToolBarAxis
"""
@axis.setter
def axis(self, arg1: ToolBarAxis) -> None:
pass
pass
class ToolBarAxis():
"""
Members:
X
Y
"""
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
"""
X: omni.ui._ui.ToolBarAxis # value = <ToolBarAxis.X: 0>
Y: omni.ui._ui.ToolBarAxis # value = <ToolBarAxis.Y: 1>
__members__: dict # value = {'X': <ToolBarAxis.X: 0>, 'Y': <ToolBarAxis.Y: 1>}
pass
class ToolButton(Button, InvisibleButton, Widget, ValueModelHelper):
"""
ToolButton is functionally similar to Button, but provides a model that determines if the button is checked. This button toggles between checked (on) and unchecked (off) when the user clicks it.
"""
def __init__(self, model: AbstractValueModel = None, **kwargs) -> None:
"""
Construct a checkable button with the model. If the bodel is not provided, then the default model is created.
### Arguments:
`model :`
The model that determines if the button is checked.
`kwargs : dict`
See below
### Keyword Arguments:
`text : str`
This property holds the button's text.
`image_url : str`
This property holds the button's optional image URL.
`image_width : float`
This property holds the width of the image widget. Do not use this function to find the width of the image.
`image_height : float`
This property holds the height of the image widget. Do not use this function to find the height of the image.
`spacing : float`
Sets a non-stretchable space in points between image and text.
`clicked_fn : Callable[[], None]`
Sets the function that will be called when when the button is activated (i.e., pressed down then released while the mouse cursor is inside the button).
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class TreeView(Widget, ItemModelHelper):
"""
TreeView is a widget that presents a hierarchical view of information. Each item can have a number of subitems. An indentation often visualizes this in a list. An item can be expanded to reveal subitems, if any exist, and collapsed to hide subitems.
TreeView can be used in file manager applications, where it allows the user to navigate the file system directories. They are also used to present hierarchical data, such as the scene object hierarchy.
TreeView uses a model/view pattern to manage the relationship between data and the way it is presented. The separation of functionality gives developers greater flexibility to customize the presentation of items and provides a standard interface to allow a wide range of data sources to be used with other widgets.
TreeView is responsible for the presentation of model data to the user and processing user input. To allow some flexibility in the way the data is presented, the creation of the sub-widgets is performed by the delegate. It provides the ability to customize any sub-item of TreeView.
"""
@typing.overload
def __init__(self, **kwargs) -> None:
"""
Create TreeView with default model.
Create TreeView with the given model.
### Arguments:
`model :`
The given model.
`kwargs : dict`
See below
### Keyword Arguments:
`delegate : `
The Item delegate that generates a widget per item.
`header_visible : `
This property holds if the header is shown or not.
`selection : `
Set current selection.
`expand_on_branch_click : `
This flag allows to prevent expanding when the user clicks the plus icon. It's used in the case the user wants to control how the items expanded or collapsed.
`keep_alive : `
When true, the tree nodes are never destroyed even if they are disappeared from the model. It's useul for the temporary filtering if it's necessary to display thousands of nodes.
`keep_expanded : `
Expand all the nodes and keep them expanded regardless their state.
`drop_between_items : `
When true, the tree nodes can be dropped between items.
`column_widths : `
Widths of the columns. If not set, the width is Fraction(1).
`min_column_widths : `
Minimum widths of the columns. If not set, the width is Pixel(0).
`columns_resizable : `
When true, the columns can be resized with the mouse.
`selection_changed_fn : `
Set the callback that is called when the selection is changed.
`root_expanded : `
The expanded state of the root item. Changing this flag doesn't make the children repopulated.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@typing.overload
def __init__(self, arg0: AbstractItemModel, **kwargs) -> None: ...
def call_hover_changed_fn(self, arg0: AbstractItem, arg1: bool) -> None:
"""
Set the callback that is called when the item hover status is changed.
"""
def call_selection_changed_fn(self, arg0: typing.List[AbstractItem]) -> None:
"""
Set the callback that is called when the selection is changed.
"""
def clear_selection(self) -> None:
"""
Deselects all selected items.
"""
def dirty_widgets(self) -> None:
"""
When called, it will make the delegate to regenerate all visible widgets the next frame.
"""
def extend_selection(self, item: AbstractItem) -> None:
"""
Extends the current selection selecting all the items between currently selected nodes and the given item. It's when user does shift+click.
"""
def has_hover_changed_fn(self) -> bool:
"""
Set the callback that is called when the item hover status is changed.
"""
def has_selection_changed_fn(self) -> bool:
"""
Set the callback that is called when the selection is changed.
"""
def is_expanded(self, item: AbstractItem) -> bool:
"""
Returns true if the given item is expanded.
"""
def set_expanded(self, item: AbstractItem, expanded: bool, recursive: bool) -> None:
"""
Sets the given item expanded or collapsed.
### Arguments:
`item :`
The item to expand or collapse.
`expanded :`
True if it's necessary to expand, false to collapse.
`recursive :`
True if it's necessary to expand children.
"""
def set_hover_changed_fn(self, fn: typing.Callable[[AbstractItem, bool], None]) -> None:
"""
Set the callback that is called when the item hover status is changed.
"""
def set_selection_changed_fn(self, fn: typing.Callable[[typing.List[AbstractItem]], None]) -> None:
"""
Set the callback that is called when the selection is changed.
"""
def toggle_selection(self, item: AbstractItem) -> None:
"""
Switches the selection state of the given item.
"""
@property
def column_widths(self) -> typing.List[Length]:
"""
Widths of the columns. If not set, the width is Fraction(1).
:type: typing.List[Length]
"""
@column_widths.setter
def column_widths(self, arg1: typing.List[Length]) -> None:
"""
Widths of the columns. If not set, the width is Fraction(1).
"""
@property
def columns_resizable(self) -> bool:
"""
When true, the columns can be resized with the mouse.
:type: bool
"""
@columns_resizable.setter
def columns_resizable(self, arg1: bool) -> None:
"""
When true, the columns can be resized with the mouse.
"""
@property
def drop_between_items(self) -> bool:
"""
When true, the tree nodes can be dropped between items.
:type: bool
"""
@drop_between_items.setter
def drop_between_items(self, arg1: bool) -> None:
"""
When true, the tree nodes can be dropped between items.
"""
@property
def expand_on_branch_click(self) -> bool:
"""
This flag allows to prevent expanding when the user clicks the plus icon. It's used in the case the user wants to control how the items expanded or collapsed.
:type: bool
"""
@expand_on_branch_click.setter
def expand_on_branch_click(self, arg1: bool) -> None:
"""
This flag allows to prevent expanding when the user clicks the plus icon. It's used in the case the user wants to control how the items expanded or collapsed.
"""
@property
def header_visible(self) -> bool:
"""
This property holds if the header is shown or not.
:type: bool
"""
@header_visible.setter
def header_visible(self, arg1: bool) -> None:
"""
This property holds if the header is shown or not.
"""
@property
def keep_alive(self) -> bool:
"""
When true, the tree nodes are never destroyed even if they are disappeared from the model. It's useul for the temporary filtering if it's necessary to display thousands of nodes.
:type: bool
"""
@keep_alive.setter
def keep_alive(self, arg1: bool) -> None:
"""
When true, the tree nodes are never destroyed even if they are disappeared from the model. It's useul for the temporary filtering if it's necessary to display thousands of nodes.
"""
@property
def keep_expanded(self) -> bool:
"""
Expand all the nodes and keep them expanded regardless their state.
:type: bool
"""
@keep_expanded.setter
def keep_expanded(self, arg1: bool) -> None:
"""
Expand all the nodes and keep them expanded regardless their state.
"""
@property
def min_column_widths(self) -> typing.List[Length]:
"""
Minimum widths of the columns. If not set, the width is Pixel(0).
:type: typing.List[Length]
"""
@min_column_widths.setter
def min_column_widths(self, arg1: typing.List[Length]) -> None:
"""
Minimum widths of the columns. If not set, the width is Pixel(0).
"""
@property
def root_expanded(self) -> bool:
"""
The expanded state of the root item. Changing this flag doesn't make the children repopulated.
:type: bool
"""
@root_expanded.setter
def root_expanded(self, arg1: bool) -> None:
"""
The expanded state of the root item. Changing this flag doesn't make the children repopulated.
"""
@property
def root_visible(self) -> bool:
"""
This property holds if the root is shown. It can be used to make a single level tree appear like a simple list.
:type: bool
"""
@root_visible.setter
def root_visible(self, arg1: bool) -> None:
"""
This property holds if the root is shown. It can be used to make a single level tree appear like a simple list.
"""
@property
def selection(self) -> typing.List[AbstractItem]:
"""
Set current selection.
:type: typing.List[AbstractItem]
"""
@selection.setter
def selection(self, arg1: typing.List[AbstractItem]) -> None:
"""
Set current selection.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class Triangle(Shape, Widget):
"""
The Triangle widget provides a colored triangle to display.
"""
def __init__(self, **kwargs) -> None:
"""
Constructs Triangle.
`kwargs : dict`
See below
### Keyword Arguments:
`alignment : `
This property holds the alignment of the triangle when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the triangle is centered.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@property
def alignment(self) -> Alignment:
"""
This property holds the alignment of the triangle when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the triangle is centered.
:type: Alignment
"""
@alignment.setter
def alignment(self, arg1: Alignment) -> None:
"""
This property holds the alignment of the triangle when the fill policy is ePreserveAspectFit or ePreserveAspectCrop. By default, the triangle is centered.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class Type():
"""
Members:
LINE
HISTOGRAM
LINE2D
"""
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
"""
HISTOGRAM: omni.ui._ui.Type # value = <Type.HISTOGRAM: 1>
LINE: omni.ui._ui.Type # value = <Type.LINE: 0>
LINE2D: omni.ui._ui.Type # value = <Type.LINE2D: 2>
__members__: dict # value = {'LINE': <Type.LINE: 0>, 'HISTOGRAM': <Type.HISTOGRAM: 1>, 'LINE2D': <Type.LINE2D: 2>}
pass
class UIntDrag(UIntSlider, AbstractSlider, Widget, ValueModelHelper):
"""
"""
def __init__(self, model: AbstractValueModel = None, **kwargs) -> None:
"""
Constructs UIntDrag.
### Arguments:
`model :`
The widget's model. If the model is not assigned, the default model is created.
`kwargs : dict`
See below
### Keyword Arguments:
`step : `
This property controls the steping speed on the drag, its float to enable slower speed, but of course the value on the Control are still integer.
`min : `
This property holds the slider's minimum value.
`max : `
This property holds the slider's maximum value.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@property
def step(self) -> float:
"""
This property controls the steping speed on the drag, its float to enable slower speed, but of course the value on the Control are still integer.
:type: float
"""
@step.setter
def step(self, arg1: float) -> None:
"""
This property controls the steping speed on the drag, its float to enable slower speed, but of course the value on the Control are still integer.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class UIntSlider(AbstractSlider, Widget, ValueModelHelper):
"""
The slider is the classic widget for controlling a bounded value. It lets the user move a slider handle along a horizontal groove and translates the handle's position into an integer value within the legal range.
The difference with IntSlider is that UIntSlider has unsigned min/max.
"""
def __init__(self, model: AbstractValueModel = None, **kwargs) -> None:
"""
Constructs UIntSlider.
### Arguments:
`model :`
The widget's model. If the model is not assigned, the default model is created.
`kwargs : dict`
See below
### Keyword Arguments:
`min : `
This property holds the slider's minimum value.
`max : `
This property holds the slider's maximum value.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
@property
def max(self) -> int:
"""
This property holds the slider's maximum value.
:type: int
"""
@max.setter
def max(self, arg1: int) -> None:
"""
This property holds the slider's maximum value.
"""
@property
def min(self) -> int:
"""
This property holds the slider's minimum value.
:type: int
"""
@min.setter
def min(self, arg1: int) -> None:
"""
This property holds the slider's minimum value.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class UnitType():
"""
Unit types.
Widths, heights or other UI length can be specified in pixels or relative to window (or child window) size.
Members:
PIXEL
PERCENT
FRACTION
"""
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
"""
FRACTION: omni.ui._ui.UnitType # value = <UnitType.FRACTION: 2>
PERCENT: omni.ui._ui.UnitType # value = <UnitType.PERCENT: 1>
PIXEL: omni.ui._ui.UnitType # value = <UnitType.PIXEL: 0>
__members__: dict # value = {'PIXEL': <UnitType.PIXEL: 0>, 'PERCENT': <UnitType.PERCENT: 1>, 'FRACTION': <UnitType.FRACTION: 2>}
pass
class VGrid(Grid, Stack, Container, Widget):
"""
Shortcut for Grid{eTopToBottom}. The grid grows from top to bottom with the widgets placed.
"""
def __init__(self, **kwargs) -> None:
"""
Construct a grid that grows from top to bottom with the widgets placed.
`kwargs : dict`
See below
### Keyword Arguments:
`column_width : `
The width of the column. It's only possible to set it if the grid is vertical. Once it's set, the column count depends on the size of the widget.
`row_height : `
The height of the row. It's only possible to set it if the grid is horizontal. Once it's set, the row count depends on the size of the widget.
`column_count : `
The number of columns. It's only possible to set it if the grid is vertical. Once it's set, the column width depends on the widget size.
`row_count : `
The number of rows. It's only possible to set it if the grid is horizontal. Once it's set, the row height depends on the widget size.
`direction : `
This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front.
`content_clipping : `
Determines if the child widgets should be clipped by the rectangle of this Stack.
`spacing : `
Sets a non-stretchable space in pixels between child items of this layout.
`send_mouse_events_to_back : `
When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class VStack(Stack, Container, Widget):
"""
Shortcut for Stack{eTopToBottom}. The widgets are placed in a column, with suitable sizes.
"""
def __init__(self, **kwargs) -> None:
"""
Construct a stack with the widgets placed in a column from top to bottom.
`kwargs : dict`
See below
### Keyword Arguments:
`direction : `
This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front.
`content_clipping : `
Determines if the child widgets should be clipped by the rectangle of this Stack.
`spacing : `
Sets a non-stretchable space in pixels between child items of this layout.
`send_mouse_events_to_back : `
When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class ValueModelHelper():
"""
The ValueModelHelper class provides the basic functionality for value widget classes. ValueModelHelper class is the base class for every standard widget that uses a AbstractValueModel. ValueModelHelper is an abstract class and itself cannot be instantiated. It provides a standard interface for interoperating with models.
"""
@property
def model(self) -> AbstractValueModel:
"""
:type: AbstractValueModel
"""
@model.setter
def model(self, arg1: AbstractValueModel) -> None:
pass
pass
class VectorImageProvider(ImageProvider):
"""
doc
"""
def __init__(self, source_url: str = None, **kwargs) -> None:
"""
doc
"""
@property
def max_mip_levels(self) -> int:
"""
Maximum number of mip map levels allowed
:type: int
"""
@max_mip_levels.setter
def max_mip_levels(self, arg1: int) -> None:
"""
Maximum number of mip map levels allowed
"""
@property
def source_url(self) -> str:
"""
Sets the vector image URL. Asset loading doesn't happen immediately, but rather is started the next time widget is visible, in prepareDraw call.
:type: str
"""
@source_url.setter
def source_url(self, arg1: str) -> None:
"""
Sets the vector image URL. Asset loading doesn't happen immediately, but rather is started the next time widget is visible, in prepareDraw call.
"""
pass
class Widget():
"""
The Widget class is the base class of all user interface objects.
The widget is the atom of the user interface: it receives mouse, keyboard and other events, and paints a representation of itself on the screen. Every widget is rectangular. A widget is clipped by its parent and by the widgets in front of it.
"""
def __init__(self, **kwargs) -> None: ...
def call_accept_drop_fn(self, arg0: str) -> bool:
"""
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
"""
def call_computed_content_size_changed_fn(self) -> None:
"""
Called when the size of the widget is changed.
"""
def call_drag_fn(self) -> str:
"""
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
"""
def call_drop_fn(self, arg0: WidgetMouseDropEvent) -> None:
"""
Specify that this Widget accepts drops and set the callback to the drop operation.
"""
def call_key_pressed_fn(self, arg0: int, arg1: int, arg2: bool) -> None:
"""
Sets the function that will be called when the user presses the keyboard key when the mouse clicks the widget.
"""
def call_mouse_double_clicked_fn(self, arg0: float, arg1: float, arg2: int, arg3: int) -> None:
"""
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
"""
def call_mouse_hovered_fn(self, arg0: bool) -> None:
"""
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
"""
def call_mouse_moved_fn(self, arg0: float, arg1: float, arg2: int, arg3: bool) -> None:
"""
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
"""
def call_mouse_pressed_fn(self, arg0: float, arg1: float, arg2: int, arg3: int) -> None:
"""
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
"""
def call_mouse_released_fn(self, arg0: float, arg1: float, arg2: int, arg3: int) -> None:
"""
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
"""
def call_mouse_wheel_fn(self, arg0: float, arg1: float, arg2: int) -> None:
"""
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
"""
def call_tooltip_fn(self) -> None:
"""
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
"""
def destroy(self) -> None:
"""
Removes all the callbacks and circular references.
"""
def has_accept_drop_fn(self) -> bool:
"""
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
"""
def has_computed_content_size_changed_fn(self) -> bool:
"""
Called when the size of the widget is changed.
"""
def has_drag_fn(self) -> bool:
"""
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
"""
def has_drop_fn(self) -> bool:
"""
Specify that this Widget accepts drops and set the callback to the drop operation.
"""
def has_key_pressed_fn(self) -> bool:
"""
Sets the function that will be called when the user presses the keyboard key when the mouse clicks the widget.
"""
def has_mouse_double_clicked_fn(self) -> bool:
"""
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
"""
def has_mouse_hovered_fn(self) -> bool:
"""
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
"""
def has_mouse_moved_fn(self) -> bool:
"""
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
"""
def has_mouse_pressed_fn(self) -> bool:
"""
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
"""
def has_mouse_released_fn(self) -> bool:
"""
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
"""
def has_mouse_wheel_fn(self) -> bool:
"""
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
"""
def has_tooltip_fn(self) -> bool:
"""
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
"""
def scroll_here(self, center_ratio_x: float = 0.0, center_ratio_y: float = 0.0) -> None:
"""
Adjust scrolling amount in two axes to make current item visible.
### Arguments:
`centerRatioX :`
0.0: left, 0.5: center, 1.0: right
`centerRatioY :`
0.0: top, 0.5: center, 1.0: bottom
"""
def scroll_here_x(self, center_ratio: float = 0.0) -> None:
"""
Adjust scrolling amount to make current item visible.
### Arguments:
`centerRatio :`
0.0: left, 0.5: center, 1.0: right
"""
def scroll_here_y(self, center_ratio: float = 0.0) -> None:
"""
Adjust scrolling amount to make current item visible.
### Arguments:
`centerRatio :`
0.0: top, 0.5: center, 1.0: bottom
"""
def set_accept_drop_fn(self, fn: typing.Callable[[str], bool]) -> None:
"""
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
"""
def set_checked_changed_fn(self, fn: typing.Callable[[bool], None]) -> None:
"""
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
"""
def set_computed_content_size_changed_fn(self, fn: typing.Callable[[], None]) -> None:
"""
Called when the size of the widget is changed.
"""
def set_drag_fn(self, fn: typing.Callable[[], str]) -> None:
"""
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
"""
def set_drop_fn(self, fn: typing.Callable[[WidgetMouseDropEvent], None]) -> None:
"""
Specify that this Widget accepts drops and set the callback to the drop operation.
"""
def set_key_pressed_fn(self, fn: typing.Callable[[int, int, bool], None]) -> None:
"""
Sets the function that will be called when the user presses the keyboard key when the mouse clicks the widget.
"""
def set_mouse_double_clicked_fn(self, fn: typing.Callable[[float, float, int, int], None]) -> None:
"""
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
"""
def set_mouse_hovered_fn(self, fn: typing.Callable[[bool], None]) -> None:
"""
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
"""
def set_mouse_moved_fn(self, fn: typing.Callable[[float, float, int, bool], None]) -> None:
"""
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
"""
def set_mouse_pressed_fn(self, fn: typing.Callable[[float, float, int, int], None]) -> None:
"""
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
"""
def set_mouse_released_fn(self, fn: typing.Callable[[float, float, int, int], None]) -> None:
"""
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
"""
def set_mouse_wheel_fn(self, fn: typing.Callable[[float, float, int], None]) -> None:
"""
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
"""
def set_style(self, arg0: handle) -> None:
"""
Set the current style. The style contains a description of customizations to the widget's style.
"""
def set_tooltip(self, tooltip_label: str) -> None:
"""
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
"""
def set_tooltip_fn(self, fn: typing.Callable[[], None]) -> None:
"""
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
"""
@property
def checked(self) -> bool:
"""
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
:type: bool
"""
@checked.setter
def checked(self, arg1: bool) -> None:
"""
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
"""
@property
def computed_content_height(self) -> float:
"""
Returns the final computed height of the content of the widget.
It's in puplic section. For the explanation why please see the draw() method.
:type: float
"""
@property
def computed_content_width(self) -> float:
"""
Returns the final computed width of the content of the widget.
It's in puplic section. For the explanation why please see the draw() method.
:type: float
"""
@property
def computed_height(self) -> float:
"""
Returns the final computed height of the widget. It includes margins.
It's in puplic section. For the explanation why please see the draw() method.
:type: float
"""
@property
def computed_width(self) -> float:
"""
Returns the final computed width of the widget. It includes margins.
It's in puplic section. For the explanation why please see the draw() method.
:type: float
"""
@property
def dragging(self) -> bool:
"""
This property holds if the widget is being dragged.
:type: bool
"""
@dragging.setter
def dragging(self, arg1: bool) -> None:
"""
This property holds if the widget is being dragged.
"""
@property
def enabled(self) -> bool:
"""
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
:type: bool
"""
@enabled.setter
def enabled(self, arg1: bool) -> None:
"""
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
"""
@property
def height(self) -> Length:
"""
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
:type: Length
"""
@height.setter
def height(self, arg1: Length) -> None:
"""
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
"""
@property
def identifier(self) -> str:
"""
An optional identifier of the widget we can use to refer to it in queries.
:type: str
"""
@identifier.setter
def identifier(self, arg1: str) -> None:
"""
An optional identifier of the widget we can use to refer to it in queries.
"""
@property
def name(self) -> str:
"""
The name of the widget that user can set.
:type: str
"""
@name.setter
def name(self, arg1: str) -> None:
"""
The name of the widget that user can set.
"""
@property
def opaque_for_mouse_events(self) -> bool:
"""
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
:type: bool
"""
@opaque_for_mouse_events.setter
def opaque_for_mouse_events(self, arg1: bool) -> None:
"""
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
"""
@property
def screen_position_x(self) -> float:
"""
Returns the X Screen coordinate the widget was last draw. This is in Screen Pixel size.
It's a float because we need negative numbers and precise position considering DPI scale factor.
:type: float
"""
@property
def screen_position_y(self) -> float:
"""
Returns the Y Screen coordinate the widget was last draw. This is in Screen Pixel size.
It's a float because we need negative numbers and precise position considering DPI scale factor.
:type: float
"""
@property
def scroll_only_window_hovered(self) -> bool:
"""
When it's false, the scroll callback is called even if other window is hovered.
:type: bool
"""
@scroll_only_window_hovered.setter
def scroll_only_window_hovered(self, arg1: bool) -> None:
"""
When it's false, the scroll callback is called even if other window is hovered.
"""
@property
def selected(self) -> bool:
"""
This property holds a flag that specifies the widget has to use eSelected state of the style.
:type: bool
"""
@selected.setter
def selected(self, arg1: bool) -> None:
"""
This property holds a flag that specifies the widget has to use eSelected state of the style.
"""
@property
def skip_draw_when_clipped(self) -> bool:
"""
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
:type: bool
"""
@skip_draw_when_clipped.setter
def skip_draw_when_clipped(self, arg1: bool) -> None:
"""
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
"""
@property
def style(self) -> object:
"""
The local style. When the user calls
setStyle()
:type: object
"""
@style.setter
def style(self, arg1: handle) -> None:
"""
The local style. When the user calls
setStyle()
"""
@property
def style_type_name_override(self) -> str:
"""
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
:type: str
"""
@style_type_name_override.setter
def style_type_name_override(self, arg1: str) -> None:
"""
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
"""
@property
def tooltip(self) -> str:
"""
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
:type: str
"""
@tooltip.setter
def tooltip(self, arg1: str) -> None:
"""
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
"""
@property
def tooltip_offset_x(self) -> float:
"""
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
:type: float
"""
@tooltip_offset_x.setter
def tooltip_offset_x(self, arg1: float) -> None:
"""
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
"""
@property
def tooltip_offset_y(self) -> float:
"""
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
:type: float
"""
@tooltip_offset_y.setter
def tooltip_offset_y(self, arg1: float) -> None:
"""
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
"""
@property
def visible(self) -> bool:
"""
This property holds whether the widget is visible.
:type: bool
"""
@visible.setter
def visible(self, arg1: bool) -> None:
"""
This property holds whether the widget is visible.
"""
@property
def visible_max(self) -> float:
"""
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
:type: float
"""
@visible_max.setter
def visible_max(self, arg1: float) -> None:
"""
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
"""
@property
def visible_min(self) -> float:
"""
If the current zoom factor and DPI is less than this value, the widget is not visible.
:type: float
"""
@visible_min.setter
def visible_min(self, arg1: float) -> None:
"""
If the current zoom factor and DPI is less than this value, the widget is not visible.
"""
@property
def width(self) -> Length:
"""
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
:type: Length
"""
@width.setter
def width(self, arg1: Length) -> None:
"""
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
class WidgetMouseDropEvent():
"""
Holds the data which is sent when a drag and drop action is completed.
"""
def __repr__(self) -> str: ...
def __str__(self) -> str: ...
@property
def mime_data(self) -> str:
"""
The data that was dropped on the widget.
:type: str
"""
@property
def x(self) -> float:
"""
Position where the drop was made.
:type: float
"""
@property
def y(self) -> float:
"""
Position where the drop was made.
:type: float
"""
pass
class Window(WindowHandle):
"""
The Window class represents a window in the underlying windowing system.
This window is a child window of main Kit window. And it can be docked.
Rasterization
omni.ui generates vertices every frame to render UI elements. One of the features of the framework is the ability to bake a DrawList per window and reuse it if the content has not changed, which can significantly improve performance. However, in some cases, such as the Viewport window and Console window, it may not be possible to detect whether the window content has changed, leading to a frozen window. To address this problem, you can control the rasterization behavior by adjusting RasterPolicy. The RasterPolicy is an enumeration class that defines the rasterization behavior of a window. It has three possible values:
NEVER: Do not rasterize the widget at any time. ON_DEMAND: Rasterize the widget as soon as possible and always use the rasterized version. The widget will only be updated when the user calls invalidateRaster. AUTO: Automatically determine whether to rasterize the widget based on performance considerations. If necessary, the widget will be rasterized and updated when its content changes.
To resolve the frozen window issue, you can manually set the RasterPolicy of the problematic window to Never. This will force the window to rasterize its content and use the rasterized version until the user explicitly calls invalidateRaster to request an update.
window = ui.Window("Test window", raster_policy=ui.RasterPolicy.NEVER)
"""
def __init__(self, title: str, dockPreference: DockPreference = DockPreference.DISABLED, **kwargs) -> None:
"""
Construct the window, add it to the underlying windowing system, and makes it appear.
### Arguments:
`title :`
The window title. It's also used as an internal window ID.
`dockPrefence :`
In the old Kit determines where the window should be docked. In Kit Next it's unused.
`kwargs : dict`
See below
### Keyword Arguments:
`flags : `
This property set the Flags for the Window.
`visible : `
This property holds whether the window is visible.
`title : `
This property holds the window's title.
`padding_x : `
This property set the padding to the frame on the X axis.
`padding_y : `
This property set the padding to the frame on the Y axis.
`width : `
This property holds the window Width.
`height : `
This property holds the window Height.
`position_x : `
This property set/get the position of the window in the X Axis. The default is kWindowFloatInvalid because we send the window position to the underlying system only if the position is explicitly set by the user. Otherwise the underlying system decides the position.
`position_y : `
This property set/get the position of the window in the Y Axis. The default is kWindowFloatInvalid because we send the window position to the underlying system only if the position is explicitly set by the user. Otherwise the underlying system decides the position.
`auto_resize : `
setup the window to resize automatically based on its content
`noTabBar : `
setup the visibility of the TabBar Handle, this is the small triangle at the corner of the view If it is not shown then it is not possible to undock that window and it need to be closed/moved programatically
`raster_policy : `
Determine how the content of the window should be rastered.
`width_changed_fn : `
This property holds the window Width.
`height_changed_fn : `
This property holds the window Height.
`visibility_changed_fn : `
This property holds whether the window is visible.
"""
def call_key_pressed_fn(self, arg0: int, arg1: int, arg2: bool) -> None:
"""
Sets the function that will be called when the user presses the keyboard key on the focused window.
"""
def deferred_dock_in(self, target_window: str, active_window: DockPolicy = DockPolicy.DO_NOTHING) -> None:
"""
Deferred docking. We need it when we want to dock windows before they were actually created. It's helpful when extension initialization, before any window is created.
### Arguments:
`targetWindowTitle :`
Dock to window with this title when it appears.
`activeWindow :`
Make target or this window active when docked.
"""
def destroy(self) -> None:
"""
Removes all the callbacks and circular references.
"""
def dock_in_window(self, title: str, dockPosition: DockPosition, ratio: float = 0.5) -> bool:
"""
place the window in a specific docking position based on a target window name. We will find the target window dock node and insert this window in it, either by spliting on ratio or on top if the window is not found false is return, otherwise true
"""
@staticmethod
def get_window_callback(*args, **kwargs) -> typing.Any:
"""
Returns window set draw callback pointer for the given UI window.
"""
def has_key_pressed_fn(self) -> bool:
"""
Sets the function that will be called when the user presses the keyboard key on the focused window.
"""
def move_to_app_window(self, arg0: omni.appwindow._appwindow.IAppWindow) -> None:
"""
Moves the window to the specific OS window.
"""
def move_to_main_os_window(self) -> None:
"""
Bring back the Window callback to the Main Window and destroy the Current OS Window.
"""
def move_to_new_os_window(self) -> None:
"""
Move the Window Callback to a new OS Window.
"""
def notify_app_window_change(self, arg0: omni.appwindow._appwindow.IAppWindow) -> None:
"""
Notifies the window that window set has changed.
"""
def setPosition(self, x: float, y: float) -> None:
"""
This property set/get the position of the window in both axis calling the property.
"""
def set_docked_changed_fn(self, arg0: typing.Callable[[bool], None]) -> None:
"""
Has true if this window is docked. False otherwise. It's a read-only property.
"""
def set_focused_changed_fn(self, arg0: typing.Callable[[bool], None]) -> None:
"""
Read only property that is true when the window is focused.
"""
def set_height_changed_fn(self, arg0: typing.Callable[[float], None]) -> None:
"""
This property holds the window Height.
"""
def set_key_pressed_fn(self, fn: typing.Callable[[int, int, bool], None]) -> None:
"""
Sets the function that will be called when the user presses the keyboard key on the focused window.
"""
def set_position_x_changed_fn(self, arg0: typing.Callable[[float], None]) -> None:
"""
This property set/get the position of the window in the X Axis. The default is kWindowFloatInvalid because we send the window position to the underlying system only if the position is explicitly set by the user. Otherwise the underlying system decides the position.
"""
def set_position_y_changed_fn(self, arg0: typing.Callable[[float], None]) -> None:
"""
This property set/get the position of the window in the Y Axis. The default is kWindowFloatInvalid because we send the window position to the underlying system only if the position is explicitly set by the user. Otherwise the underlying system decides the position.
"""
def set_selected_in_dock_changed_fn(self, arg0: typing.Callable[[bool], None]) -> None:
"""
Has true if this window is currently selected in the dock. False otherwise. It's a read-only property.
"""
def set_top_modal(self) -> None:
"""
Brings this window to the top level of modal windows.
"""
def set_visibility_changed_fn(self, arg0: typing.Callable[[bool], None]) -> None:
"""
This property holds whether the window is visible.
"""
def set_width_changed_fn(self, arg0: typing.Callable[[float], None]) -> None:
"""
This property holds the window Width.
"""
@property
def app_window(self) -> omni.appwindow._appwindow.IAppWindow:
"""
:type: omni.appwindow._appwindow.IAppWindow
"""
@property
def auto_resize(self) -> bool:
"""
setup the window to resize automatically based on its content
:type: bool
"""
@auto_resize.setter
def auto_resize(self, arg1: bool) -> None:
"""
setup the window to resize automatically based on its content
"""
@property
def detachable(self) -> bool:
"""
If the window is able to be separated from the main application window.
:type: bool
"""
@detachable.setter
def detachable(self, arg1: bool) -> None:
"""
If the window is able to be separated from the main application window.
"""
@property
def docked(self) -> bool:
"""
Has true if this window is docked. False otherwise. It's a read-only property.
:type: bool
"""
@property
def exclusive_keyboard(self) -> bool:
"""
When true, only the current window will receive keyboard events when it's focused. It's useful to override the global key bindings.
:type: bool
"""
@exclusive_keyboard.setter
def exclusive_keyboard(self, arg1: bool) -> None:
"""
When true, only the current window will receive keyboard events when it's focused. It's useful to override the global key bindings.
"""
@property
def flags(self) -> int:
"""
This property set the Flags for the Window.
:type: int
"""
@flags.setter
def flags(self, arg1: int) -> None:
"""
This property set the Flags for the Window.
"""
@property
def focus_policy(self) -> FocusPolicy:
"""
How the Window gains focus.
:type: FocusPolicy
"""
@focus_policy.setter
def focus_policy(self, arg1: FocusPolicy) -> None:
"""
How the Window gains focus.
"""
@property
def focused(self) -> bool:
"""
Read only property that is true when the window is focused.
:type: bool
"""
@property
def frame(self) -> Frame:
"""
The main layout of this window.
:type: Frame
"""
@property
def height(self) -> float:
"""
This property holds the window Height.
:type: float
"""
@height.setter
def height(self, arg1: float) -> None:
"""
This property holds the window Height.
"""
@property
def menu_bar(self) -> MenuBar:
"""
:type: MenuBar
"""
@property
def noTabBar(self) -> bool:
"""
setup the visibility of the TabBar Handle, this is the small triangle at the corner of the view If it is not shown then it is not possible to undock that window and it need to be closed/moved programatically
:type: bool
"""
@noTabBar.setter
def noTabBar(self, arg1: bool) -> None:
"""
setup the visibility of the TabBar Handle, this is the small triangle at the corner of the view If it is not shown then it is not possible to undock that window and it need to be closed/moved programatically
"""
@property
def padding_x(self) -> float:
"""
This property set the padding to the frame on the X axis.
:type: float
"""
@padding_x.setter
def padding_x(self, arg1: float) -> None:
"""
This property set the padding to the frame on the X axis.
"""
@property
def padding_y(self) -> float:
"""
This property set the padding to the frame on the Y axis.
:type: float
"""
@padding_y.setter
def padding_y(self, arg1: float) -> None:
"""
This property set the padding to the frame on the Y axis.
"""
@property
def position_x(self) -> float:
"""
This property set/get the position of the window in the X Axis. The default is kWindowFloatInvalid because we send the window position to the underlying system only if the position is explicitly set by the user. Otherwise the underlying system decides the position.
:type: float
"""
@position_x.setter
def position_x(self, arg1: float) -> None:
"""
This property set/get the position of the window in the X Axis. The default is kWindowFloatInvalid because we send the window position to the underlying system only if the position is explicitly set by the user. Otherwise the underlying system decides the position.
"""
@property
def position_y(self) -> float:
"""
This property set/get the position of the window in the Y Axis. The default is kWindowFloatInvalid because we send the window position to the underlying system only if the position is explicitly set by the user. Otherwise the underlying system decides the position.
:type: float
"""
@position_y.setter
def position_y(self, arg1: float) -> None:
"""
This property set/get the position of the window in the Y Axis. The default is kWindowFloatInvalid because we send the window position to the underlying system only if the position is explicitly set by the user. Otherwise the underlying system decides the position.
"""
@property
def raster_policy(self) -> RasterPolicy:
"""
Determine how the content of the window should be rastered.
:type: RasterPolicy
"""
@raster_policy.setter
def raster_policy(self, arg1: RasterPolicy) -> None:
"""
Determine how the content of the window should be rastered.
"""
@property
def selected_in_dock(self) -> bool:
"""
Has true if this window is currently selected in the dock. False otherwise. It's a read-only property.
:type: bool
"""
@property
def title(self) -> str:
"""
This property holds the window's title.
:type: str
"""
@title.setter
def title(self, arg1: str) -> None:
"""
This property holds the window's title.
"""
@property
def visible(self) -> bool:
"""
This property holds whether the window is visible.
:type: bool
"""
@visible.setter
def visible(self, arg1: bool) -> None:
"""
This property holds whether the window is visible.
"""
@property
def width(self) -> float:
"""
This property holds the window Width.
:type: float
"""
@width.setter
def width(self, arg1: float) -> None:
"""
This property holds the window Width.
"""
pass
class WindowHandle():
"""
WindowHandle is a handle object to control any of the windows in Kit. It can be created any time, and if it's destroyed, the source window doesn't disappear.
"""
def __repr__(self) -> str: ...
def dock_in(self, window: WindowHandle, dock_position: DockPosition, ratio: float = 0.5) -> None:
"""
Dock the window to the existing window. It can split the window to two parts or it can convert the window to a docking tab.
"""
def focus(self) -> None:
"""
Brings the window to the top. If it's a docked window, it makes the window currently visible in the dock.
"""
def is_selected_in_dock(self) -> bool:
"""
Return true is the window is the current window in the docking area.
"""
def notify_app_window_change(self, arg0: omni.appwindow._appwindow.IAppWindow) -> None:
"""
Notifies the UI window that the AppWindow it attached to has changed.
"""
def undock(self) -> None:
"""
Undock the window and make it floating.
"""
@property
def dock_id(self) -> int:
"""
Returns ID of the dock node this window is docked to.
:type: int
"""
@property
def dock_order(self) -> int:
"""
The position of the window in the dock.
:type: int
"""
@dock_order.setter
def dock_order(self, arg1: int) -> None:
"""
The position of the window in the dock.
"""
@property
def dock_tab_bar_enabled(self) -> bool:
"""
Checks if the current docking space is disabled. The disabled docking tab bar can't be shown by the user.
:type: bool
"""
@dock_tab_bar_enabled.setter
def dock_tab_bar_enabled(self, arg1: bool) -> None:
"""
Checks if the current docking space is disabled. The disabled docking tab bar can't be shown by the user.
"""
@property
def dock_tab_bar_visible(self) -> bool:
"""
Checks if the current docking space has the tab bar.
:type: bool
"""
@dock_tab_bar_visible.setter
def dock_tab_bar_visible(self, arg1: bool) -> None:
"""
Checks if the current docking space has the tab bar.
"""
@property
def docked(self) -> bool:
"""
True if this window is docked. False otherwise.
:type: bool
"""
@property
def height(self) -> float:
"""
The height of the window in points.
:type: float
"""
@height.setter
def height(self, arg1: float) -> None:
"""
The height of the window in points.
"""
@property
def position_x(self) -> float:
"""
The position of the window in points.
:type: float
"""
@position_x.setter
def position_x(self, arg1: float) -> None:
"""
The position of the window in points.
"""
@property
def position_y(self) -> float:
"""
The position of the window in points.
:type: float
"""
@position_y.setter
def position_y(self, arg1: float) -> None:
"""
The position of the window in points.
"""
@property
def title(self) -> str:
"""
The title of the window.
:type: str
"""
@property
def visible(self) -> bool:
"""
Returns whether the window is visible.
:type: bool
"""
@visible.setter
def visible(self, arg1: bool) -> None:
"""
Returns whether the window is visible.
"""
@property
def width(self) -> float:
"""
The width of the window in points.
:type: float
"""
@width.setter
def width(self, arg1: float) -> None:
"""
The width of the window in points.
"""
pass
class Workspace():
"""
Workspace object provides access to the windows in Kit.
"""
@staticmethod
def clear() -> None:
"""
Undock all.
"""
@staticmethod
def get_dock_children_id(dock_id: int) -> object:
"""
Get two dock children of the given dock ID.
true if the given dock ID has children
### Arguments:
`dockId :`
the given dock ID
`first :`
output. the first child dock ID
`second :`
output. the second child dock ID
"""
@staticmethod
def get_dock_id_height(dock_id: int) -> float:
"""
Returns the height of the docking node.
It's different from the window height because it considers dock tab bar.
### Arguments:
`dockId :`
the given dock ID
"""
@staticmethod
def get_dock_id_width(dock_id: int) -> float:
"""
Returns the width of the docking node.
### Arguments:
`dockId :`
the given dock ID
"""
@staticmethod
def get_dock_position(dock_id: int) -> DockPosition:
"""
Returns the position of the given dock ID. Left/Right/Top/Bottom.
"""
@staticmethod
def get_docked_neighbours(member: WindowHandle) -> typing.List[WindowHandle]:
"""
Get all the windows that docked with the given widow.
"""
@staticmethod
def get_docked_windows(dock_id: int) -> typing.List[WindowHandle]:
"""
Get all the windows of the given dock ID.
"""
@staticmethod
def get_dpi_scale() -> float:
"""
Returns current DPI Scale.
"""
@staticmethod
def get_main_window_height() -> float:
"""
Get the height in points of the current main window.
"""
@staticmethod
def get_main_window_width() -> float:
"""
Get the width in points of the current main window.
"""
@staticmethod
def get_parent_dock_id(dock_id: int) -> int:
"""
Return the parent Dock Node ID.
### Arguments:
`dockId :`
the child Dock Node ID to get parent
"""
@staticmethod
def get_selected_window_index(dock_id: int) -> int:
"""
Get currently selected window inedx from the given dock id.
"""
@staticmethod
def get_window(title: str) -> WindowHandle:
"""
Find Window by name.
"""
@staticmethod
def get_window_from_callback(*args, **kwargs) -> typing.Any:
"""
Find Window by window callback.
"""
@staticmethod
def get_windows() -> typing.List[WindowHandle]:
"""
Returns the list of windows ordered from back to front.
If the window is a Omni::UI window, it can be upcasted.
"""
@staticmethod
def remove_window_visibility_changed_callback(fn: int) -> None:
"""
Remove the callback that is triggered when window's visibility changed.
"""
@staticmethod
def set_dock_id_height(dock_id: int, height: float) -> None:
"""
Set the height of the dock node.
It also sets the height of parent nodes if necessary and modifies the height of siblings.
### Arguments:
`dockId :`
the given dock ID
`height :`
the given height
"""
@staticmethod
def set_dock_id_width(dock_id: int, width: float) -> None:
"""
Set the width of the dock node.
It also sets the width of parent nodes if necessary and modifies the width of siblings.
### Arguments:
`dockId :`
the given dock ID
`width :`
the given width
"""
@staticmethod
def set_show_window_fn(title: str, fn: typing.Callable[[bool], None]) -> None:
"""
Add the callback to create a window with the given title. When the callback's argument is true, it's necessary to create the window. Otherwise remove.
"""
@staticmethod
def set_window_created_callback(fn: typing.Callable[[WindowHandle], None]) -> None:
"""
Addd the callback that is triggered when a new window is created.
"""
@staticmethod
def set_window_visibility_changed_callback(fn: typing.Callable[[str, bool], None]) -> int:
"""
Add the callback that is triggered when window's visibility changed.
"""
@staticmethod
def show_window(title: str, show: bool = True) -> bool:
"""
Makes the window visible or create the window with the callback provided with set_show_window_fn.
true if the window is already created, otherwise it's necessary to wait one frame
### Arguments:
`title :`
the given window title
`show :`
true to show, false to hide
"""
pass
class ZStack(Stack, Container, Widget):
"""
Shortcut for Stack{eBackToFront}. The widgets are placed sorted in a Z-order in top right corner with suitable sizes.
"""
def __init__(self, **kwargs) -> None:
"""
Construct a stack with the widgets placed in a Z-order with sorting from background to foreground.
`kwargs : dict`
See below
### Keyword Arguments:
`direction : `
This type is used to determine the direction of the layout. If the Stack's orientation is eLeftToRight the widgets are placed in a horizontal row, from left to right. If the Stack's orientation is eRightToLeft the widgets are placed in a horizontal row, from right to left. If the Stack's orientation is eTopToBottom, the widgets are placed in a vertical column, from top to bottom. If the Stack's orientation is eBottomToTop, the widgets are placed in a vertical column, from bottom to top. If the Stack's orientation is eBackToFront, the widgets are placed sorted in a Z-order in top right corner. If the Stack's orientation is eFrontToBack, the widgets are placed sorted in a Z-order in top right corner, the first widget goes to front.
`content_clipping : `
Determines if the child widgets should be clipped by the rectangle of this Stack.
`spacing : `
Sets a non-stretchable space in pixels between child items of this layout.
`send_mouse_events_to_back : `
When children of a Z-based stack overlap mouse events are normally sent to the topmost one. Setting this property true will invert that behavior, sending mouse events to the bottom-most child.
`width : ui.Length`
This property holds the width of the widget relative to its parent. Do not use this function to find the width of a screen.
`height : ui.Length`
This property holds the height of the widget relative to its parent. Do not use this function to find the height of a screen.
`name : str`
The name of the widget that user can set.
`style_type_name_override : str`
By default, we use typeName to look up the style. But sometimes it's necessary to use a custom name. For example, when a widget is a part of another widget. (Label is a part of Button) This property can override the name to use in style.
`identifier : str`
An optional identifier of the widget we can use to refer to it in queries.
`visible : bool`
This property holds whether the widget is visible.
`visibleMin : float`
If the current zoom factor and DPI is less than this value, the widget is not visible.
`visibleMax : float`
If the current zoom factor and DPI is bigger than this value, the widget is not visible.
`tooltip : str`
Set a basic tooltip for the widget, this will simply be a Label, it will follow the Tooltip style
`tooltip_fn : Callable`
Set dynamic tooltip that will be created dynamiclly the first time it is needed. the function is called inside a ui.Frame scope that the widget will be parented correctly.
`tooltip_offset_x : float`
Set the X tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`tooltip_offset_y : float`
Set the Y tooltip offset in points. In a normal state, the tooltip position is linked to the mouse position. If the tooltip offset is non zero, the top left corner of the tooltip is linked to the top left corner of the widget, and this property defines the relative position the tooltip should be shown.
`enabled : bool`
This property holds whether the widget is enabled. In general an enabled widget handles keyboard and mouse events; a disabled widget does not. And widgets display themselves differently when they are disabled.
`selected : bool`
This property holds a flag that specifies the widget has to use eSelected state of the style.
`checked : bool`
This property holds a flag that specifies the widget has to use eChecked state of the style. It's on the Widget level because the button can have sub-widgets that are also should be checked.
`dragging : bool`
This property holds if the widget is being dragged.
`opaque_for_mouse_events : bool`
If the widgets has callback functions it will by default not capture the events if it is the top most widget and setup this option to true, so they don't get routed to the child widgets either
`skip_draw_when_clipped : bool`
The flag that specifies if it's necessary to bypass the whole draw cycle if the bounding box is clipped with a scrolling frame. It's needed to avoid the limitation of 65535 primitives in a single draw list.
`mouse_moved_fn : Callable`
Sets the function that will be called when the user moves the mouse inside the widget. Mouse move events only occur if a mouse button is pressed while the mouse is being moved. void onMouseMoved(float x, float y, int32_t modifier)
`mouse_pressed_fn : Callable`
Sets the function that will be called when the user presses the mouse button inside the widget. The function should be like this: void onMousePressed(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier) Where 'button' is the number of the mouse button pressed. 'modifier' is the flag for the keyboard modifier key.
`mouse_released_fn : Callable`
Sets the function that will be called when the user releases the mouse button if this button was pressed inside the widget. void onMouseReleased(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_double_clicked_fn : Callable`
Sets the function that will be called when the user presses the mouse button twice inside the widget. The function specification is the same as in setMousePressedFn. void onMouseDoubleClicked(float x, float y, int32_t button, carb::input::KeyboardModifierFlags modifier)
`mouse_wheel_fn : Callable`
Sets the function that will be called when the user uses mouse wheel on the focused window. The function specification is the same as in setMousePressedFn. void onMouseWheel(float x, float y, carb::input::KeyboardModifierFlags modifier)
`mouse_hovered_fn : Callable`
Sets the function that will be called when the user use mouse enter/leave on the focused window. function specification is the same as in setMouseHovedFn. void onMouseHovered(bool hovered)
`drag_fn : Callable`
Specify that this Widget is draggable, and set the callback that is attached to the drag operation.
`accept_drop_fn : Callable`
Specify that this Widget can accept specific drops and set the callback that is called to check if the drop can be accepted.
`drop_fn : Callable`
Specify that this Widget accepts drops and set the callback to the drop operation.
`computed_content_size_changed_fn : Callable`
Called when the size of the widget is changed.
"""
FLAG_WANT_CAPTURE_KEYBOARD = 1073741824
pass
def dock_window_in_window(arg0: str, arg1: str, arg2: DockPosition, arg3: float) -> bool:
"""
place a named window in a specific docking position based on a target window name. We will find the target window dock node and insert this named window in it, either by spliting on ratio or on top if the windows is not found false is return, otherwise true
"""
def get_custom_glyph_code(file_path: str, font_style: FontStyle = FontStyle.NORMAL) -> str:
"""
Get glyph code.
Args:
file_path (str): Path to svg file
font_style(:class:`.FontStyle`): font style to use.
"""
def get_main_window_height() -> float:
"""
Get the height in points of the current main window.
"""
def get_main_window_width() -> float:
"""
Get the width in points of the current main window.
"""
WINDOW_FLAGS_FORCE_HORIZONTAL_SCROLLBAR = 32768
WINDOW_FLAGS_FORCE_VERTICAL_SCROLLBAR = 16384
WINDOW_FLAGS_MENU_BAR = 1024
WINDOW_FLAGS_MODAL = 134217728
WINDOW_FLAGS_NONE = 0
WINDOW_FLAGS_NO_BACKGROUND = 128
WINDOW_FLAGS_NO_CLOSE = 2147483648
WINDOW_FLAGS_NO_COLLAPSE = 32
WINDOW_FLAGS_NO_DOCKING = 2097152
WINDOW_FLAGS_NO_FOCUS_ON_APPEARING = 4096
WINDOW_FLAGS_NO_MOUSE_INPUTS = 512
WINDOW_FLAGS_NO_MOVE = 4
WINDOW_FLAGS_NO_RESIZE = 2
WINDOW_FLAGS_NO_SAVED_SETTINGS = 256
WINDOW_FLAGS_NO_SCROLLBAR = 8
WINDOW_FLAGS_NO_SCROLL_WITH_MOUSE = 16
WINDOW_FLAGS_NO_TITLE_BAR = 1
WINDOW_FLAGS_POPUP = 67108864
WINDOW_FLAGS_SHOW_HORIZONTAL_SCROLLBAR = 2048
|
omniverse-code/kit/exts/omni.ui/omni/ui/__init__.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
"""
Omni::UI
--------
Omni::UI is Omniverse's UI toolkit for creating beautiful and flexible graphical user interfaces
in the Kit extensions. Omni::UI provides the basic types necessary to create rich extensions with
a fluid and dynamic user interface in Omniverse Kit. It gives a layout system and includes
widgets for creating visual components, receiving user input, and creating data models. It allows
user interface components to be built around their behavior and enables a declarative flavor of
describing the layout of the application. Omni::UI gives a very flexible styling system that
allows deep customizing the final look of the application.
Typical Example
---------------
Typical example to create a window with two buttons:
.. code-block::
import omni.ui as ui
_window_example = ui.Window("Example Window", width=300, height=300)
with _window_example.frame:
with ui.VStack():
ui.Button("click me")
def move_me(window):
window.setPosition(200, 200)
def size_me(window):
window.width = 300
window.height = 300
ui.Button("Move to (200,200)", clicked_fn=lambda w=self._window_example: move_me(w))
ui.Button("Set size (300,300)", clicked_fn=lambda w=self._window_example: size_me(w))
Detailed Documentation
----------------------
Omni::UI is shipped with the developer documentation that is written with Omni::UI. For detailed documentation, please
see `omni.example.ui` extension. It has detailed descriptions of all the classes, best practices, and real-world usage
examples.
Layout
------
* Arrangement of elements
* :class:`omni.ui.CollapsableFrame`
* :class:`omni.ui.Frame`
* :class:`omni.ui.HStack`
* :class:`omni.ui.Placer`
* :class:`omni.ui.ScrollingFrame`
* :class:`omni.ui.Spacer`
* :class:`omni.ui.VStack`
* :class:`omni.ui.ZStack`
* Lengths
* :class:`omni.ui.Fraction`
* :class:`omni.ui.Percent`
* :class:`omni.ui.Pixel`
Widgets
-------
* Base Widgets
* :class:`omni.ui.Button`
* :class:`omni.ui.Image`
* :class:`omni.ui.Label`
* Shapes
* :class:`omni.ui.Circle`
* :class:`omni.ui.Line`
* :class:`omni.ui.Rectangle`
* :class:`omni.ui.Triangle`
* Menu
* :class:`omni.ui.Menu`
* :class:`omni.ui.MenuItem`
* Model-View Widgets
* :class:`omni.ui.AbstractItemModel`
* :class:`omni.ui.AbstractValueModel`
* :class:`omni.ui.CheckBox`
* :class:`omni.ui.ColorWidget`
* :class:`omni.ui.ComboBox`
* :class:`omni.ui.RadioButton`
* :class:`omni.ui.RadioCollection`
* :class:`omni.ui.TreeView`
* Model-View Fields
* :class:`omni.ui.FloatField`
* :class:`omni.ui.IntField`
* :class:`omni.ui.MultiField`
* :class:`omni.ui.StringField`
* Model-View Drags and Sliders
* :class:`omni.ui.FloatDrag`
* :class:`omni.ui.FloatSlider`
* :class:`omni.ui.IntDrag`
* :class:`omni.ui.IntSlider`
* Model-View ProgressBar
* :class:`omni.ui.ProgressBar`
* Windows
* :class:`omni.ui.ToolBar`
* :class:`omni.ui.Window`
* :class:`omni.ui.Workspace`
* Web
* :class:`omni.ui.WebViewWidget`
"""
import omni.gpu_foundation_factory # carb::graphics::Format used as default argument in BindByteImageProvider.cpp
from ._ui import *
from .color_utils import color
from .constant_utils import constant
from .style_utils import style
from .url_utils import url
from .workspace_utils import dump_workspace
from .workspace_utils import restore_workspace
from .workspace_utils import compare_workspace
from typing import Optional
# Importing TextureFormat here explicitly to maintain backwards compatibility
from omni.gpu_foundation_factory import TextureFormat
def add_to_namespace(module=None, module_locals=locals()):
class AutoRemove:
def __init__(self):
self.__key = module.__name__.split(".")[-1]
module_locals[self.__key] = module
def __del__(self):
module_locals.pop(self.__key, None)
if not module:
return
return AutoRemove()
# Add the static methods to Workspace
setattr(Workspace, "dump_workspace", dump_workspace)
setattr(Workspace, "restore_workspace", restore_workspace)
setattr(Workspace, "compare_workspace", compare_workspace)
del dump_workspace
del restore_workspace
del compare_workspace
def set_shade(shade_name: Optional[str] = None):
color.set_shade(shade_name)
constant.set_shade(shade_name)
url.set_shade(shade_name)
def set_menu_delegate(delegate: MenuDelegate):
"""
Set the default delegate to use it when the item doesn't have a
delegate.
"""
MenuDelegate.set_default_delegate(delegate)
|
omniverse-code/kit/exts/omni.ui/omni/ui/workspace_utils.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""The utilities to capture and restore layout"""
from . import _ui as ui
from typing import Any, Tuple
from typing import Dict
from typing import List
from typing import Optional
import asyncio
import carb
import carb.settings
import functools
import math
import omni.appwindow
import omni.kit.app
import omni.kit.renderer.bind
import traceback
ROOT_WINDOW_NAME = "DockSpace"
SAME = "SAME"
LEFT = "LEFT"
RIGHT = "RIGHT"
TOP = "TOP"
BOTTOM = "BOTTOM"
EXCLUDE_WINDOWS = [
ROOT_WINDOW_NAME,
"Debug##Default",
"Status Bar",
"Select File to Save Layout",
"Select File to Load Layout",
]
# Used to prevent _restore_workspace_async from execution simultaneously
restore_workspace_task_global = None
# Define the settings path for enabling and setting the number of frames for
# draw freeze in UI
SETTING_DRAWFREEZE_ENABLED = "/exts/omni.ui/workpace/draw_freeze/enabled"
SETTING_DRAWFREEZE_FRAMES = "/exts/omni.ui/workpace/draw_freeze/frames"
class CompareDelegate():
def __init__(self):
pass
def failed_get_window(self, error_list: list, target: dict):
if target["visible"]:
error_list.append(f"failed to get window \"{target['title']}\"")
def failed_window_key(self, error_list: list, key: str, target: dict, target_window: ui.Window):
error_list.append(f"{key} not found in {target_window.__class__.__name__} for window \"{target}\"")
def failed_window_value(self, error_list: list, key: str, value, target: dict, target_window: ui.Window):
error_list.append(f"failure for window \"{target['title']}\". Key \"{key}\" expected {target[key]} but has {value}")
def compare_value(self, key:str, value, target):
if type(value) == float:
return math.isclose(value, target[key], abs_tol=1.5)
return bool(value == target[key])
def compare_dock_in_value_position_x(self, key:str, value, target):
# position_x isn't set for docked windows, so skip compare
return True
def compare_dock_in_value_position_y(self, key:str, value, target):
# position_y isn't set for docked windows, so skip compare
return True
def compare_dock_in_value_width(self, key:str, value, target):
# width isn't set for docked windows, so skip compare
return True
def compare_dock_in_value_height(self, key:str, value, target):
# height isn't set for docked windows, so skip compare
return True
def compare_dock_in_value_dock_id(self, key:str, value, target):
# compare dock_id for docked windows - dock_id isn't guarenteed to be same value, so just verify they are docked
return bool(value != int(0) and target[key] != int(0))
def compare_window_value_dock_id(self, key:str, value, target):
# compare dock_id for floating windows - dock_id should be 0
return bool(value == int(0) and target[key] == int(0))
def handle_exception(func):
"""
Decorator to print exception in async functions
"""
@functools.wraps(func)
async def wrapper(*args, **kwargs):
try:
return await func(*args, **kwargs)
except Exception as e:
carb.log_error(f"Exception when async '{func}'")
carb.log_error(f"{e}")
carb.log_error(f"{traceback.format_exc()}")
return wrapper
def _dump_window(window: ui.WindowHandle, window_list: List[str]):
"""Convert WindowHandle to the window description as a dict."""
window_title = window.title
window_list.append(window_title)
selected_in_dock = window.is_selected_in_dock()
result = {
"title": window_title,
"width": window.width,
"height": window.height,
"position_x": window.position_x,
"position_y": window.position_y,
"dock_id": window.dock_id,
"visible": window.visible if type(window) != ui.WindowHandle else False,
"selected_in_dock": selected_in_dock,
}
if selected_in_dock:
result["dock_tab_bar_visible"] = window.dock_tab_bar_visible
result["dock_tab_bar_enabled"] = window.dock_tab_bar_enabled
return result
def _dump_dock_node(dock_id: int, window_list: List[str]):
"""Convert dock id to the node description as a dict."""
result: Dict[str, Any] = {"dock_id": dock_id}
children_docks = ui.Workspace.get_dock_children_id(dock_id)
position = ui.Workspace.get_dock_position(dock_id)
if position != ui.DockPosition.SAME:
result["position"] = position.name
if children_docks:
# Children are docking nodes. Add them recursively.
result["children"] = [
_dump_dock_node(children_docks[0], window_list),
_dump_dock_node(children_docks[1], window_list),
]
else:
# All the children are windows
docked_windows = ui.Workspace.get_docked_windows(dock_id)
children_windows = [_dump_window(window, window_list) for window in docked_windows]
# The size of the unselected window is the size the window was visible.
# We need to get the size of the selected window and set it to all the
# siblings.
selected = [window["selected_in_dock"] for window in children_windows]
try:
selected_id = selected.index(True)
except ValueError:
selected_id = None
if selected_id is not None:
width = children_windows[selected_id]["width"]
height = children_windows[selected_id]["height"]
# Found width/height of selected window. Set it to all children.
for child in children_windows:
child["width"] = width
child["height"] = height
result["children"] = children_windows
return result
def _dock_in(target: dict, source: dict, position: str, ratio: float):
"""
Docks windows together. The difference with ui.WindowHandle.dock_in is that, it takes window descriptions as dicts.
Args:
target: the dictionary with the description of the window it's necessary to dock to source.
source: the dictionary with the description of the window to dock in.
position: "SAME", "LEFT", "RIGHT", "TOP", "BOTTOM".
ratio: when docking side by side, specifies where there will be the border.
"""
# Convert string to DockPosition
# TODO: DockPosition is pybind11 enum and it probably has this conversion
if position == SAME:
dock_position = ui.DockPosition.SAME
elif position == LEFT:
dock_position = ui.DockPosition.LEFT
elif position == RIGHT:
dock_position = ui.DockPosition.RIGHT
elif position == TOP:
dock_position = ui.DockPosition.TOP
elif position == BOTTOM:
dock_position = ui.DockPosition.BOTTOM
else:
raise ValueError(f"{position} is not member of ui.DockPosition")
target_window = ui.Workspace.get_window(target["title"])
source_window = ui.Workspace.get_window(source["title"])
carb.log_verbose(f"Docking window '{target_window}'.dock_in('{source_window}', {dock_position}, {ratio})")
try:
target_window.dock_in(source_window, dock_position, ratio)
except AttributeError:
carb.log_warn(
f"Can't restore {target['title']}. A window with this title could not be found. Make sure that auto-load has been enabled for this extension."
)
# Stop deferred docking
if isinstance(target_window, ui.Window):
target_window.deferred_dock_in("")
def _compare_dock_in(target: dict, error_list: list, compare_delegate: CompareDelegate):
target_window = ui.Workspace.get_window(target["title"])
if not target_window:
return compare_delegate.failed_get_window(error_list, target)
# windows of type ui.WindowHandle are placeholders and values are not necessarily valid
if type(target_window) == ui.WindowHandle:
return
if not target["visible"] and not target_window.visible:
return
elif target["visible"] != target_window.visible:
return compare_delegate.failed_window_value(error_list, "visible", target_window.visible, target, target_window)
selected_in_dock = target["selected_in_dock"]
for key in target:
if not hasattr(target_window, key):
compare_delegate.failed_window_key(error_list, key, target, target_window)
continue
value = getattr(target_window, key)
compare_fn = getattr(compare_delegate, f"compare_dock_in_value_{key}", compare_delegate.compare_value)
if not compare_fn(key, value, target):
compare_delegate.failed_window_value(error_list, key, value, target, target_window)
def _dock_order(target: dict, order: int):
"""Set the position of the window in the dock."""
window = ui.Workspace.get_window(target["title"])
try:
window.dock_order = order
if target.get("selected_in_dock", None):
window.focus()
except AttributeError:
carb.log_warn(
f"Can't set dock order for {target['title']}. A window with this title could not be found. Make sure that auto-load has been enabled for this extension."
)
def _restore_tab_bar(target: dict):
"""Restore dock_tab_bar_visible and dock_tab_bar_enabled"""
window = ui.Workspace.get_window(target["title"])
dock_tab_bar_visible = target.get("dock_tab_bar_visible", None)
if dock_tab_bar_visible is not None:
if window:
window.dock_tab_bar_visible = dock_tab_bar_visible
else:
carb.log_warn(
f"Can't set tab bar visibility for {target['title']}. A window "
"with this title could not be found. Make sure that auto-load "
"has been enabled for this extension."
)
return
dock_tab_bar_enabled = target.get("dock_tab_bar_enabled", None)
if dock_tab_bar_enabled is not None:
if window:
window.dock_tab_bar_enabled = dock_tab_bar_enabled
else:
carb.log_warn(
f"Can't enable tab bar for {target['title']}. A window with "
"this title could not be found. Make sure that auto-load has "
"been enabled for this extension."
)
def _is_dock_node(node: dict):
"""Return True if the dict is a dock node description"""
return isinstance(node, dict) and "children" in node
def _is_window(window: dict):
"""Return True if the dict is a window description"""
return isinstance(window, dict) and "title" in window
def _is_all_windows(windows: list):
"""Return true if all the items of the given list are window descriptions"""
for w in windows:
if not _is_window(w):
return False
return True
def _is_all_docks(children: list):
"""Return true if all the provided children are docking nodes"""
return len(children) == 2 and _is_dock_node(children[0]) and _is_dock_node(children[1])
def _has_children(workspace_description: dict):
"""Return true if the item has valin nonempty children"""
if not _is_dock_node(workspace_description):
# Windows don't have children
return False
for c in workspace_description["children"]:
if _is_window(c) or _has_children(c):
return True
return False
def _get_children(workspace_description: dict):
"""Return nonempty children"""
children = workspace_description["children"]
children = [c for c in children if _is_window(c) or _has_children(c)]
if len(children) == 1 and _is_dock_node(children[0]):
return _get_children(children[0])
return children
def _target(workspace_description: dict):
"""Recursively find the first available window in the dock node"""
children = _get_children(workspace_description)
first = children[0]
if _is_window(first):
return first
return _target(first)
def _restore_workspace(
workspace_description: dict,
root: dict,
dock_order: List[Tuple[Any, int]],
windows_to_set_dock_visibility: List[Dict],
):
"""
Dock all the windows according to the workspace description.
Args:
workspace_description: the given workspace description.
root: the root node to dock everything into.
dock_order: output list of windows to adjust docking order.
windows_to_set_dock_visibility: list of windows that have the info about dock_tab_bar
"""
children = _get_children(workspace_description)
if _is_all_docks(children):
# Children are dock nodes
first = _target(children[0])
second = _target(children[1])
if children[1]["position"] == RIGHT:
first_width = _get_width(children[0])
second_width = _get_width(children[1])
ratio = second_width / (first_width + second_width)
else:
first_height = _get_height(children[0])
second_height = _get_height(children[1])
ratio = second_height / (first_height + second_height)
# Dock the second window to the root
_dock_in(second, root, children[1]["position"], ratio)
# Recursively dock children
_restore_workspace(children[0], first, dock_order, windows_to_set_dock_visibility)
_restore_workspace(children[1], second, dock_order, windows_to_set_dock_visibility)
elif _is_all_windows(children):
# Children are windows. Dock everything to the first window in the list
first = None
children_count = len(children)
for i, w in enumerate(children):
# Save docking order
if children_count > 1:
dock_order.append((w, i))
if w.get("selected_in_dock", None):
windows_to_set_dock_visibility.append(w)
if not first:
first = w
else:
_dock_in(w, first, "SAME", 0.5)
def _compare_workspace(workspace_description: dict, root: dict, error_list: list, compare_delegate: CompareDelegate):
children = _get_children(workspace_description)
if _is_all_docks(children):
# Children are dock nodes
first = _target(children[0])
second = _target(children[1])
if children[1]["position"] == RIGHT:
first_width = _get_width(children[0])
second_width = _get_width(children[1])
ratio = second_width / (first_width + second_width)
else:
first_height = _get_height(children[0])
second_height = _get_height(children[1])
ratio = second_height / (first_height + second_height)
# Verify the second window to the root
_compare_dock_in(second, error_list, compare_delegate)
# Recursively verify children
_compare_workspace(children[0], first, error_list, compare_delegate)
_compare_workspace(children[1], second, error_list, compare_delegate)
elif _is_all_windows(children):
# Children are windows. Verify everything to the first window in the list
first = None
children_count = len(children)
for i, w in enumerate(children):
if not first:
first = w
else:
_compare_dock_in(w, error_list, compare_delegate)
def _get_visible_windows(workspace_description: dict, visible: bool):
result = []
if _is_dock_node(workspace_description):
for w in _get_children(workspace_description):
result += _get_visible_windows(w, visible)
elif _is_window(workspace_description):
visible_flag = workspace_description.get("visible", None)
if visible:
if visible_flag is None or visible_flag:
result.append(workspace_description["title"])
else: # visible == False
# Separate branch because we don't want to add the window with no
# "visible" flag
if not visible_flag:
result.append(workspace_description["title"])
return result
async def _restore_window(window_description: dict):
"""Set the position and the size of the window"""
# Skip invisible windows
visible = window_description.get("visible", None)
if visible is False:
return
# Skip the window that doesn't exist
window = ui.Workspace.get_window(window_description["title"])
if not window:
return
# window could docked, need to undock otherwise position/size may not take effect
# but window.docked is always False and window.dock_id is always 0, so cannot test
window.undock()
await omni.kit.app.get_app().next_update_async()
window.position_x = window_description["position_x"]
window.position_y = window_description["position_y"]
window.width = window_description["width"]
window.height = window_description["height"]
def _compare_window(window_description: dict, error_list: list, compare_delegate: CompareDelegate):
target_window = ui.Workspace.get_window(window_description["title"])
if not target_window:
return compare_delegate.failed_get_window(error_list, window_description)
# windows of type ui.WindowHandle are placeholders and values are not necessarily valid
if type(target_window) == ui.WindowHandle:
return
if not window_description["visible"] and not target_window.visible:
return
elif window_description["visible"] != target_window.visible:
return compare_delegate.failed_window_value(error_list, "visible", target_window.visible, window_description, target_window)
for key in window_description:
if not hasattr(target_window, key):
compare_delegate.failed_window_key(error_list, key, window_description, target_window)
continue
value = getattr(target_window, key)
compare_fn = getattr(compare_delegate, f"compare_window_value_{key}", compare_delegate.compare_value)
if not compare_fn(key, value, window_description):
compare_delegate.failed_window_value(error_list, key, value, window_description, target_window)
def _get_width(node: dict):
"""Compute width of the given dock. It recursively checks the child windows."""
children = _get_children(node)
if _is_all_docks(children):
if children[1]["position"] == BOTTOM or children[1]["position"] == TOP:
return _get_width(children[0])
elif children[1]["position"] == RIGHT or children[1]["position"] == LEFT:
return _get_width(children[0]) + _get_width(children[1])
elif _is_all_windows(children):
return children[0]["width"]
def _get_height(node: dict):
"""Compute height of the given dock. It recursively checks the child windows."""
children = _get_children(node)
if _is_all_docks(children):
if children[1]["position"] == BOTTOM or children[1]["position"] == TOP:
return _get_height(children[0]) + _get_height(children[1])
elif children[1]["position"] == RIGHT or children[1]["position"] == LEFT:
return _get_height(children[0])
elif _is_all_windows(children):
return children[0]["height"]
@handle_exception
async def _restore_workspace_async(
workspace_dump: List[Any],
visible_titles: List[str],
keep_windows_open: bool,
wait_for: Optional[asyncio.Task] = None,
):
"""Dock the windows according to the workspace description"""
if wait_for is not None:
# Wait for another _restore_workspace_async task
await wait_for
# Fetching and reading the settings
settings = carb.settings.get_settings()
draw_freeze_enabled = settings.get(SETTING_DRAWFREEZE_ENABLED)
# Freeze the window drawing if draw freeze is enabled
# This is done to ensure a smooth layout change, without visible updates, if
# draw freeze is enabled
if draw_freeze_enabled:
# Get IRenderer
renderer = omni.kit.renderer.bind.get_renderer_interface()
# Get default IAppWindow
app_window_factory = omni.appwindow.acquire_app_window_factory_interface()
app_window = app_window_factory.get_app_window()
# Draw freeze the window
renderer.draw_freeze_app_window(app_window, True)
ui.Workspace.clear()
visible_titles_set = set(visible_titles)
workspace_visible_windows = set()
workspace_hidden_windows = set()
already_visible = True
for workspace_description in workspace_dump:
visible_windows = _get_visible_windows(workspace_description, True)
hidden_windows = _get_visible_windows(workspace_description, False)
workspace_visible_windows = workspace_visible_windows.union(visible_windows)
workspace_hidden_windows = workspace_hidden_windows.union(hidden_windows)
for window_title in visible_windows:
already_visible = ui.Workspace.show_window(window_title) and already_visible
# The rest of the windows should be closed
hide_windows = []
if keep_windows_open:
# Close the windows with flag "visible=False". Don't close the windows
# that don't have this flag.
hide_windows = visible_titles_set.intersection(workspace_hidden_windows)
for window_title in hide_windows:
ui.Workspace.show_window(window_title, False)
else:
# Close all the widows that don't have flag "visible=True"
hide_windows = visible_titles_set - workspace_visible_windows
for window_title in hide_windows:
ui.Workspace.show_window(window_title, False)
if not already_visible:
# One of the windows is just created. ImGui needs to initialize it
# to dock it. Wait one frame.
await omni.kit.app.get_app().next_update_async()
else:
# Otherwise: RuntimeWarning: coroutine '_restore_workspace_async' was never awaited
await asyncio.sleep(0)
dock_order: List[Tuple[Any, int]] = []
windows_to_set_dock_visibility: List[Dict] = []
for i, workspace_description in enumerate(workspace_dump):
if i == 0:
# The first window in the dump is the root window
root_window_dump = workspace_dump[0]
if not _has_children(root_window_dump):
continue
first_root = _target(root_window_dump)
_dock_in(first_root, {"title": ROOT_WINDOW_NAME}, "SAME", 0.5)
_restore_workspace(root_window_dump, first_root, dock_order, windows_to_set_dock_visibility)
elif _is_window(workspace_description):
# Floating window
await _restore_window(workspace_description)
# TODO: Floating window that is docked to another floating window
if dock_order or windows_to_set_dock_visibility:
# Wait one frame to dock everything
await omni.kit.app.get_app().next_update_async()
if dock_order:
# Restore docking order
for window, position in dock_order:
_dock_order(window, position)
if windows_to_set_dock_visibility:
# Restore dock_tab_bar_visible and dock_tab_bar_enabled
for window in windows_to_set_dock_visibility:
_restore_tab_bar(window)
wait_frames = 1
# If draw freeze is enable we fetch the number of frames we have to wait
if draw_freeze_enabled:
wait_frames = settings.get(SETTING_DRAWFREEZE_FRAMES) or 0
# Let ImGui finish all the layout, by waiting for the specified frames number.
for _ in range(wait_frames):
await omni.kit.app.get_app().next_update_async()
# After workspace processing and the specified number of frames passed, we
# unfreeze the drawing
if draw_freeze_enabled:
renderer.draw_freeze_app_window(app_window, False)
def dump_workspace():
"""
Capture current workspace and return the dict with the description of the
docking state and window size.
"""
dumped_windows: List[str] = []
workspace_dump: List[Any] = []
# Dump the root window
dock_space = ui.Workspace.get_window(ROOT_WINDOW_NAME)
if dock_space:
workspace_dump.append(_dump_dock_node(dock_space.dock_id, dumped_windows))
# Dump the rest
for window in ui.Workspace.get_windows():
title = window.title
if title not in EXCLUDE_WINDOWS and title not in dumped_windows:
workspace_dump.append(_dump_window(window, dumped_windows))
return workspace_dump
def restore_workspace(workspace_dump: List[Any], keep_windows_open=False):
"""
Dock the windows according to the workspace description.
### Arguments
`workspace_dump : List[Any]`
The dictionary with the description of the layout. It's the dict
received from `dump_workspace`.
`keep_windows_open : bool`
Determines if it's necessary to hide the already opened windows that
are not present in `workspace_dump`.
"""
global restore_workspace_task_global
# Visible titles
# `WindowHandle.visible` is different when it's called from `ensure_future`
# because it's called outside of ImGui::Begin/ImGui::End. As result, the
# `Console` window is not in the list of visible windows and it's not
# closed. That's why it's called here and passed to
# `_restore_workspace_async`.
workspace_windows = ui.Workspace.get_windows()
visible_titles = [w.title for w in workspace_windows if w.visible and w.title not in EXCLUDE_WINDOWS]
restore_workspace_task_global = asyncio.ensure_future(
_restore_workspace_async(workspace_dump, visible_titles, keep_windows_open, restore_workspace_task_global)
)
def compare_workspace(workspace_dump: List[Any], compare_delegate: CompareDelegate=CompareDelegate()):
"""
Compare current docked windows according to the workspace description.
### Arguments
`workspace_dump : List[Any]`
The dictionary with the description of the layout. It's the dict
received from `dump_workspace`.
"""
workspace_windows = ui.Workspace.get_windows()
visible_titles = [w.title for w in workspace_windows if w.visible and w.title not in EXCLUDE_WINDOWS]
visible_titles_set = set(visible_titles)
workspace_visible_windows = set()
workspace_hidden_windows = set()
already_visible = True
for workspace_description in workspace_dump:
visible_windows = _get_visible_windows(workspace_description, True)
workspace_visible_windows = workspace_visible_windows.union(visible_windows)
error_list = []
for i, workspace_description in enumerate(workspace_dump):
if i == 0:
# The first window in the dump is the root window
root_window_dump = workspace_dump[0]
if not _has_children(root_window_dump):
continue
first_root = _target(root_window_dump)
_compare_dock_in(first_root, error_list, compare_delegate=compare_delegate)
_compare_workspace(root_window_dump, first_root, error_list, compare_delegate=compare_delegate)
elif _is_window(workspace_description):
# Floating window
_compare_window(workspace_description, error_list, compare_delegate=compare_delegate)
return error_list
|
omniverse-code/kit/exts/omni.ui/omni/ui/url_utils.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 . import _ui as ui
from .singleton import Singleton
from .abstract_shade import AbstractShade
@Singleton
class StringShade(AbstractShade):
"""
The shade functionality for float style parameters.
Usage:
ui.Rectangle(style={"border_width": fl.shade(1, light=0)})
# Make no border
cl.set_shade("light")
# Make border width 1
cl.set_shade("default")
"""
def _find(self, name: str) -> float:
return ui.StringStore.find(name)
def _store(self, name: str, value: str):
return ui.StringStore.store(name, value)
url = StringShade()
|
omniverse-code/kit/exts/omni.ui/omni/ui/color_utils.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 . import _ui as ui
from .abstract_shade import AbstractShade
from .singleton import Singleton
from typing import Optional
from typing import Union
import struct
@Singleton
class ColorShade(AbstractShade):
"""
Usage:
import omni.ui.color as cl
ui.Button(style={"color": cl.kit_bg})
ui.CheckBox(style={"color": cl.kit_bg})
ui.Slider(style={"color": "kit_bg"})
# Make everything light:
cl.kit_bg = (1,1,1)
# Make everything dark:
cl.kit_bg = (0,0,0)
Usage:
ui.Button(
style={
"color": cl.shade(
(0.1, 0.1, 0.1),
light=(1,1,1),
green=(0,0,1))})
ui.CheckBox(
style={
"color": cl.shade(
(0.2, 0.2, 0.2),
light=(1,1,1),
name="my_bg")})
ui.Slider(
style={"color": cl.my_bg})
# Make everything light:
cl.set_shade("light")
# Make everything dark:
cl.set_shade("default")
"""
def _find(self, name: str) -> int:
return ui.ColorStore.find(name)
def _store(self, name: str, value: int):
return ui.ColorStore.store(name, value)
def __call__(
self,
r: Union[str, int, float],
g: Optional[Union[float, int]] = None,
b: Optional[Union[float, int]] = None,
a: Optional[Union[float, int]] = None,
) -> int:
"""
Convert color representation to uint32_t color.
### Supported ways to set color:
- `cl("#CCCCCC")`
- `cl("#CCCCCCFF")`
- `cl(128, 128, 128)`
- `cl(0.5, 0.5, 0.5)`
- `cl(128, 128, 128, 255)`
- `cl(0.5, 0.5, 0.5, 1.0)`
- `cl(128)`
- `cl(0.5)`
"""
# Check if rgb are numeric
allnumeric = True
hasfloat = False
for i in [r, g, b]:
if isinstance(i, int):
pass
elif isinstance(i, float):
hasfloat = True
else:
allnumeric = False
break
if allnumeric:
if hasfloat:
# FLOAT RGBA
if isinstance(a, float) or isinstance(a, int):
alpha = min(255, max(0, int(a * 255)))
else:
alpha = 255
rgba = (
min(255, max(0, int(r * 255))),
min(255, max(0, int(g * 255))),
min(255, max(0, int(b * 255))),
alpha,
)
else:
# INT RGBA
if isinstance(a, int):
alpha = min(255, max(0, a))
else:
alpha = 255
rgba = (min(255, max(0, r)), min(255, max(0, g)), min(255, max(0, b)), alpha)
elif isinstance(r, str) and g is None and b is None and a is None:
# HTML Color
value = r.lstrip("#")
# Add FF alpha if there is no alpha
value += "F" * max(0, 8 - len(value))
rgba = struct.unpack("BBBB", bytes.fromhex(value))
elif isinstance(r, int) and g is None and b is None:
# Single INT
rr = min(255, max(0, r))
rgba = (rr, rr, rr, 255)
elif isinstance(r, float) and g is None and b is None:
# Single FLOAT
rr = min(255, max(0, int(r * 255)))
rgba = (rr, rr, rr, 255)
else:
# TODO: More representations, like HSV
raise ValueError
return (rgba[3] << 24) + (rgba[2] << 16) + (rgba[1] << 8) + (rgba[0] << 0)
color = ColorShade()
|
omniverse-code/kit/exts/omni.ui/omni/ui/constant_utils.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 . import _ui as ui
from .singleton import Singleton
from .abstract_shade import AbstractShade
@Singleton
class FloatShade(AbstractShade):
"""
The shade functionality for float style parameters.
Usage:
ui.Rectangle(style={"border_width": fl.shade(1, light=0)})
# Make no border
cl.set_shade("light")
# Make border width 1
cl.set_shade("default")
"""
def _find(self, name: str) -> float:
return ui.FloatStore.find(name)
def _store(self, name: str, value: float):
return ui.FloatStore.store(name, value)
constant = FloatShade()
|
omniverse-code/kit/exts/omni.ui/omni/ui/style_utils.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 . import _ui as ui
style = ui.Style.get_instance()
|
omniverse-code/kit/exts/omni.ui/omni/ui/singleton.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
def Singleton(class_):
"""A singleton decorator"""
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_overflow.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
from .test_base import OmniUiTest
from pathlib import Path
import asyncio
import sys
import omni.kit.app
import omni.ui as ui
CURRENT_PATH = Path(__file__).parent
DATA_PATH = CURRENT_PATH.parent.parent.parent.joinpath("data")
class TestOverflow(OmniUiTest):
# Testing ui.IntField for overflow exception
async def test_int_overflow(self):
from omni.kit import ui_test
window = ui.Window("IntField", width=450, height=800)
with window.frame:
with ui.VStack():
ui.Spacer(height=10)
ui.IntField(model=ui.SimpleIntModel())
ui.Spacer(height=10)
widget = ui_test.find("IntField//Frame/**/IntField[*]")
await widget.input("99999999999999999999999999999999999999999999")
await ui_test.human_delay(500)
# Testing ui.FloatField for overflow exception
async def test_float_overflow(self):
from omni.kit import ui_test
window = ui.Window("FloatField", width=450, height=800)
with window.frame:
with ui.VStack():
ui.Spacer(height=10)
ui.FloatField(model=ui.SimpleFloatModel())
ui.Spacer(height=10)
widget = ui_test.find("FloatField//Frame/**/FloatField[*]")
await widget.input("1.6704779438076223e-52")
await ui_test.human_delay(500)
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_no_gpu.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
__all__ = ["TestNoGPU"]
import omni.kit.test
import omni.ui as ui
class TestNoGPU(omni.kit.test.AsyncTestCase):
def test_workspace(self):
"""Test using ui.Workspace will not crash if no GPUs are present."""
windows = ui.Workspace.get_windows()
# Pass on release or odder debug builds
self.assertTrue((windows == []) or (f"{windows}" == "[Debug##Default]"))
# Test this call doesn't crash
ui.Workspace.clear()
def test_window(self):
"""Test using ui.Window will not crash if no GPUs are present."""
window = ui.Window("Name", width=512, height=512)
# Test is not that window holds anything of value, just that app has not crashed
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_tooltip.py | ## Copyright (c) 2018-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
from .test_base import OmniUiTest
import omni.kit.app
import omni.ui as ui
import asyncio
class TestTooltip(OmniUiTest):
"""Testing tooltip"""
async def test_general(self):
"""Testing general properties of ui.Label"""
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
with window.frame:
# Simple text
label = ui.Label("Hello world", tooltip="This is a tooltip")
ref = ui_test.WidgetRef(label, "")
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move(ref.center)
await asyncio.sleep(1.0)
await self.finalize_test()
async def test_property(self):
"""Testing general properties of ui.Label"""
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
with window.frame:
# Simple text
label = ui.Label("Hello world")
label.tooltip = "This is a tooltip"
self.assertEqual(label.tooltip, "This is a tooltip")
ref = ui_test.WidgetRef(label, "")
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move(ref.center)
await asyncio.sleep(1.0)
await self.finalize_test()
async def test_delay(self):
"""Testing general properties of ui.Label"""
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
with window.frame:
# Simple text
label = ui.Label("Hello world", tooltip="This is a tooltip")
ref = ui_test.WidgetRef(label, "")
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move(ref.center)
await asyncio.sleep(0.2)
await self.finalize_test()
await ui_test.emulate_mouse_move(ui_test.Vec2(ref.center.x, ref.center.y + 50)) # get rid of tooltip
await asyncio.sleep(0.2)
async def test_tooltip_in_separate_window(self):
"""Testing tooltip on a separate window"""
import omni.kit.ui_test as ui_test
win = await self.create_test_window(block_devices=False)
with win.frame:
with ui.VStack():
ui.Spacer()
# create a new frame which is on a separate window
with ui.Frame(separate_window=True):
style = {"BezierCurve": {"color": omni.ui.color.red, "border_width": 2}}
curve = ui.BezierCurve(style=style, tooltip="This is a tooltip")
ref = ui_test.WidgetRef(curve, "")
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move(ref.center)
await asyncio.sleep(1.0)
await self.finalize_test()
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_separator.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from .test_base import OmniUiTest
import omni.kit.app
import omni.ui as ui
from functools import partial
class TestSeparator(OmniUiTest):
"""Testing ui.Menu"""
async def test_general(self):
"""Testing general properties of ui.Menu"""
window = await self.create_test_window()
with window.frame:
ui.Spacer()
shown = [False, False]
def on_shown(index, s):
shown[index] = s
self.menu_h = ui.Menu("Test Hidden Context Menu", shown_changed_fn=partial(on_shown, 0))
self.menu_v = ui.Menu("Test Visible Context Menu", shown_changed_fn=partial(on_shown, 1))
with self.menu_h:
ui.Separator()
ui.MenuItem("Hidden 1")
ui.Separator("Hidden 1")
ui.MenuItem("Hidden 2")
ui.Separator("Hidden 2")
ui.MenuItem("Hidden 3")
ui.Separator()
with self.menu_v:
ui.Separator()
ui.MenuItem("Test 1")
ui.Separator("Separator 1")
ui.MenuItem("Test 2")
ui.Separator("Separator 2")
ui.MenuItem("Test 3")
ui.Separator()
# No menu is shown
self.assertIsNone(ui.Menu.get_current())
self.menu_h.show_at(0, 0)
self.menu_v.show_at(0, 0)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
# Check the callback is called
self.assertFalse(shown[0])
self.assertTrue(shown[1])
# Check the property
self.assertFalse(self.menu_h.shown)
self.assertTrue(self.menu_v.shown)
# Check the current menu
self.assertEqual(ui.Menu.get_current(), self.menu_v)
await self.finalize_test()
async def test_general_modern(self):
"""Testing general properties of ui.Menu"""
window = await self.create_test_window()
with window.frame:
ui.Spacer()
self.menu_v = ui.Menu("Test Visible Context Menu Modern", menu_compatibility=0)
with self.menu_v:
ui.Separator()
ui.MenuItem("Test 1")
ui.Separator("Separator 1")
ui.MenuItem("Test 2")
ui.Separator("Separator 2")
ui.MenuItem("Test 3")
ui.Separator()
self.menu_v.show_at(0, 0)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
self.menu_v.destroy()
self.menu_v = None
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_menu.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import asyncio
from .test_base import OmniUiTest
import omni.kit.app
import omni.ui as ui
from functools import partial
class TestMenu(OmniUiTest):
"""Testing ui.Menu"""
async def test_general(self):
"""Testing general properties of ui.Menu"""
window = await self.create_test_window()
with window.frame:
ui.Spacer()
shown = [False, False]
def on_shown(index, s):
shown[index] = s
self.menu_h = ui.Menu("Test Hidden Context Menu", shown_changed_fn=partial(on_shown, 0))
self.menu_v = ui.Menu("Test Visible Context Menu", shown_changed_fn=partial(on_shown, 1))
with self.menu_h:
ui.MenuItem("Hidden 1")
ui.MenuItem("Hidden 2")
ui.MenuItem("Hidden 3")
with self.menu_v:
ui.MenuItem("Test 1")
ui.MenuItem("Test 2")
ui.MenuItem("Test 3")
# No menu is shown
self.assertIsNone(ui.Menu.get_current())
self.menu_h.show_at(0, 0)
self.menu_v.show_at(0, 0)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
# Check the callback is called
self.assertFalse(shown[0])
self.assertTrue(shown[1])
# Check the property
self.assertFalse(self.menu_h.shown)
self.assertTrue(self.menu_v.shown)
# Check the current menu
self.assertEqual(ui.Menu.get_current(), self.menu_v)
await self.finalize_test()
# Remove menus for later tests
self.menu_h.destroy()
self.menu_v.destroy()
async def test_modern(self):
"""Testing general properties of ui.Menu"""
window = await self.create_test_window()
with window.frame:
ui.Spacer()
shown = [False, False]
def on_shown(index, s):
shown[index] = s
self.menu_h = ui.Menu(
"Test Hidden Context Menu Modern", shown_changed_fn=partial(on_shown, 0), menu_compatibility=0
)
self.menu_v = ui.Menu(
"Test Visible Context Menu Modern", shown_changed_fn=partial(on_shown, 1), menu_compatibility=0
)
with self.menu_h:
ui.MenuItem("Hidden 1")
ui.MenuItem("Hidden 2")
ui.MenuItem("Hidden 3")
with self.menu_v:
ui.MenuItem("Test 1")
ui.MenuItem("Test 2")
ui.MenuItem("Test 3")
self.menu_h.show_at(0, 0)
self.menu_v.show_at(0, 0)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
# Check the callback is called
self.assertFalse(shown[0])
self.assertTrue(shown[1])
# Check the property
self.assertFalse(self.menu_h.shown)
self.assertTrue(self.menu_v.shown)
# Check the current menu
self.assertEqual(ui.Menu.get_current(), self.menu_v)
await self.finalize_test()
# Remove menus for later tests
self.menu_h.destroy()
self.menu_v.destroy()
self.menu_h = None
self.menu_v = None
async def test_modern_visibility(self):
import omni.kit.ui_test as ui_test
triggered = []
def on_triggered():
triggered.append(True)
window = await self.create_test_window(block_devices=False)
with window.frame:
ui.Spacer()
menu = ui.Menu("Test Visibility Context Menu Modern", menu_compatibility=0)
with menu:
ui.MenuItem("Hidden 1")
ui.MenuItem("Hidden 2")
ui.MenuItem("Hidden 3")
invis = ui.MenuItem("Invisible", triggered_fn=on_triggered)
invis.visible = False
ui.MenuItem("Another Invisible", visible=False)
menu.show_at(0, 0)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
invis.visible = True
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
ref_invis = ui_test.WidgetRef(invis, "")
await ui_test.emulate_mouse_move_and_click(ref_invis.center)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
# Check the callback is called
self.assertTrue(triggered)
await self.finalize_test_no_image()
async def test_modern_horizontal(self):
"""Testing general properties of ui.Menu"""
window = await self.create_test_window()
with window.frame:
with ui.Menu(height=0, menu_compatibility=0, direction=ui.Direction.LEFT_TO_RIGHT):
with ui.Menu("File"):
ui.MenuItem("Hidden 1")
ui.MenuItem("Hidden 2")
ui.MenuItem("Hidden 3")
with ui.Menu("Edit"):
ui.MenuItem("Test 1")
ui.MenuItem("Test 2")
ui.MenuItem("Test 3")
await self.finalize_test()
async def test_modern_horizontal_right(self):
"""Testing general properties of ui.Menu"""
window = await self.create_test_window()
with window.frame:
with ui.Menu(height=0, menu_compatibility=0, direction=ui.Direction.LEFT_TO_RIGHT):
with ui.Menu("File"):
ui.MenuItem("Hidden 1")
ui.MenuItem("Hidden 2")
ui.MenuItem("Hidden 3")
ui.Spacer()
with ui.Menu("Edit"):
ui.MenuItem("Test 1")
ui.MenuItem("Test 2")
ui.MenuItem("Test 3")
await self.finalize_test()
async def test_modern_delegate(self):
"""Testing general properties of ui.Menu"""
window = await self.create_test_window()
with window.frame:
ui.Spacer()
class Delegate(ui.MenuDelegate):
def build_item(self, item):
if item.text[0] == "#":
ui.Rectangle(height=20, style={"background_color": ui.color(item.text)})
def build_title(self, item):
ui.Label(item.text)
def build_status(self, item):
ui.Label("Status is also here")
self.menu = ui.Menu("Test Modern Delegate", menu_compatibility=0, delegate=Delegate())
with self.menu:
ui.MenuItem("#ff6600")
ui.MenuItem("#00ff66")
ui.MenuItem("#0066ff")
ui.MenuItem("#66ff00")
ui.MenuItem("#6600ff")
ui.MenuItem("#ff0066")
self.menu.show_at(0, 0)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
# Remove menu for later tests
self.menu.destroy()
self.menu = None
async def test_modern_checked(self):
"""Testing general properties of ui.Menu"""
window = await self.create_test_window()
with window.frame:
ui.Spacer()
called = [False, False]
checked = [False, False]
self.menu_v = ui.Menu("Test Visible Context Menu Modern", menu_compatibility=0)
def checked_changed(i, c):
called[i] = True
checked[i] = c
with self.menu_v:
item1 = ui.MenuItem("Test 1", checked=False, checkable=True)
item1.set_checked_changed_fn(partial(checked_changed, 0))
item2 = ui.MenuItem("Test 2", checked=False, checkable=True, checked_changed_fn=partial(checked_changed, 1))
ui.MenuItem("Test 3", checked=True, checkable=True)
ui.MenuItem("Test 4", checked=False, checkable=True)
ui.MenuItem("Test 5")
item1.checked = True
item2.checked = True
self.menu_v.show_at(0, 0)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
# Check the callback is called
self.assertTrue(called[0])
self.assertTrue(checked[0])
self.assertTrue(called[1])
self.assertTrue(checked[1])
await self.finalize_test()
self.menu_v.destroy()
self.menu_v = None
async def test_radio(self):
"""Testing radio collections"""
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
with window.frame:
ui.Spacer()
called = [False, False]
checked = [False, False]
self.menu = ui.Menu("Test Visible Context Menu Modern", menu_compatibility=0)
def checked_changed(i, c):
called[i] = True
checked[i] = c
with self.menu:
collection = ui.MenuItemCollection("Collection")
with collection:
m1 = ui.MenuItem("Test 1", checked=False, checkable=True)
m2 = ui.MenuItem("Test 2", checked=False, checkable=True)
m3 = ui.MenuItem("Test 3", checked=False, checkable=True)
m4 = ui.MenuItem("Test 4", checked=False, checkable=True)
m2.checked = True
m3.checked = True
self.menu.show_at(0, 0)
ref = ui_test.WidgetRef(collection, "")
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move(ref.center)
await omni.kit.app.get_app().next_update_async()
# Check the checked states
self.assertFalse(m1.checked)
self.assertFalse(m2.checked)
self.assertTrue(m3.checked)
self.assertFalse(m4.checked)
await self.finalize_test()
self.menu.destroy()
self.menu = None
async def test_modern_click(self):
"""Click the menu bar"""
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
with window.frame:
with ui.Menu(height=0, menu_compatibility=0, direction=ui.Direction.LEFT_TO_RIGHT):
file = ui.Menu("File")
with file:
ui.MenuItem("File 1")
ui.MenuItem("File 2")
ui.MenuItem("File 3")
with ui.Menu("Edit"):
ui.MenuItem("Edit 1")
ui.MenuItem("Edit 2")
ui.MenuItem("Edit 3")
ref = ui_test.WidgetRef(file, "")
# Click the File item
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move_and_click(ref.center)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_modern_click_click(self):
"""Click the menu bar, wait, click again"""
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
with window.frame:
with ui.Menu(height=0, menu_compatibility=0, direction=ui.Direction.LEFT_TO_RIGHT):
file = ui.Menu("File")
with file:
ui.MenuItem("File 1")
ui.MenuItem("File 2")
ui.MenuItem("File 3")
with ui.Menu("Edit"):
ui.MenuItem("Edit 1")
ui.MenuItem("Edit 2")
ui.MenuItem("Edit 3")
ref = ui_test.WidgetRef(file, "")
# Click the File item
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move_and_click(ref.center)
await asyncio.sleep(0.5)
# Click the File item one more time
await ui_test.emulate_mouse_move_and_click(ref.center)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_modern_click_move(self):
"""Click the menu bar, move to another item"""
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
with window.frame:
with ui.Menu(height=0, menu_compatibility=0, direction=ui.Direction.LEFT_TO_RIGHT):
file = ui.Menu("File")
with file:
ui.MenuItem("File 1")
ui.MenuItem("File 2")
ui.MenuItem("File 3")
edit = ui.Menu("Edit")
with edit:
ui.MenuItem("Edit 1")
ui.MenuItem("Edit 2")
ui.MenuItem("Edit 3")
refFile = ui_test.WidgetRef(file, "")
refEdit = ui_test.WidgetRef(edit, "")
# Click the File item
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move_and_click(refFile.center)
await asyncio.sleep(0.5)
# Hover the Edit item
await ui_test.emulate_mouse_move(refEdit.center)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_modern_click_submenu(self):
"""Click the menu bar, wait, click again"""
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
with window.frame:
with ui.Menu(height=0, menu_compatibility=0, direction=ui.Direction.LEFT_TO_RIGHT):
file = ui.Menu("File")
with file:
ui.MenuItem("File 1")
sub = ui.Menu("Sub")
with sub:
ui.MenuItem("File 2")
mid = ui.MenuItem("Middle")
ui.MenuItem("File 4")
ui.MenuItem("File 5")
with ui.Menu("Edit"):
ui.MenuItem("Edit 1")
ui.MenuItem("Edit 2")
ui.MenuItem("Edit 3")
refFile = ui_test.WidgetRef(file, "")
refSub = ui_test.WidgetRef(sub, "")
refMid = ui_test.WidgetRef(mid, "")
# Click the File item
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move_and_click(refFile.center)
# Hover the Sub item
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move(refSub.center)
# Hover the Middle item
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move(refMid.center)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_modern_tearoff(self):
"""Click the menu bar, wait, click again"""
import omni.kit.ui_test as ui_test
shown_times = [0, 0]
def on_shown(shown, shown_times=shown_times):
"""Called when the file menu is opened"""
if shown:
# It will show if it's opened or closed
shown_times[0] += 1
else:
shown_times[0] -= 1
# Could times it's called
shown_times[1] += 1
await self.create_test_area(block_devices=False)
ui_main_window = ui.MainWindow()
ui_main_window.main_menu_bar.visible = False
window = ui.Window(
"test_modern_tearoff",
flags=ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE,
)
window.frame.set_style({"Window": {"background_color": 0xFF000000, "border_color": 0x0, "border_radius": 0}})
await omni.kit.app.get_app().next_update_async()
main_dockspace = ui.Workspace.get_window("DockSpace")
window.dock_in(main_dockspace, ui.DockPosition.SAME)
window.dock_tab_bar_visible = False
with window.frame:
with ui.Menu(height=0, menu_compatibility=0, direction=ui.Direction.LEFT_TO_RIGHT):
file = ui.Menu("File", shown_changed_fn=on_shown)
with file:
ui.MenuItem("File 1")
ui.MenuItem("File 2")
ui.MenuItem("File 5")
with ui.Menu("Edit"):
ui.MenuItem("Edit 1")
ui.MenuItem("Edit 2")
ui.MenuItem("Edit 3")
refFile = ui_test.WidgetRef(file, "")
# Click the File item
for _ in range(2):
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move_and_click(refFile.center)
# Move the menu window to the middle of the screen
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_drag_and_drop(
ui_test.Vec2(refFile.center.x, refFile.center.y + 15), ui_test.Vec2(128, 128)
)
await omni.kit.app.get_app().next_update_async()
# Menu should be torn off
self.assertTrue(file.teared)
# But the pull-down portion of the menu is not shown
self.assertFalse(file.shown)
# Click the File item
for _ in range(2):
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move_and_click(refFile.center)
await omni.kit.app.get_app().next_update_async()
# It should be 1 to indicate that the menu is opened
self.assertEqual(shown_times[0], 1)
# It was called three times:
# - To open menu
# - To tear off, the menu is closed
# - Opened again to make a screenshot
self.assertEqual(shown_times[1], 3)
# Menu should be torn off
self.assertTrue(file.teared)
# But the pull-down portion of the menu is not shown
self.assertTrue(file.shown)
await self.finalize_test()
async def test_modern_tearoff_submenu(self):
"""Click the menu bar, wait, click again"""
import omni.kit.ui_test as ui_test
await self.create_test_area(block_devices=False)
ui_main_window = ui.MainWindow()
ui_main_window.main_menu_bar.visible = False
window = ui.Window(
"test_modern_tearoff",
flags=ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE,
)
window.frame.set_style({"Window": {"background_color": 0xFF000000, "border_color": 0x0, "border_radius": 0}})
await omni.kit.app.get_app().next_update_async()
main_dockspace = ui.Workspace.get_window("DockSpace")
window.dock_in(main_dockspace, ui.DockPosition.SAME)
window.dock_tab_bar_visible = False
with window.frame:
with ui.Menu(height=0, menu_compatibility=0, direction=ui.Direction.LEFT_TO_RIGHT):
file = ui.Menu("File")
with file:
ui.MenuItem("File 1")
sub = ui.Menu("Sub")
with sub:
ui.MenuItem("File 2")
ui.MenuItem("File 3")
ui.MenuItem("File 4")
ui.MenuItem("File 5")
with ui.Menu("Edit"):
ui.MenuItem("Edit 1")
ui.MenuItem("Edit 2")
ui.MenuItem("Edit 3")
refFile = ui_test.WidgetRef(file, "")
refSub = ui_test.WidgetRef(sub, "")
# Click the File item
for _ in range(2):
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move_and_click(refFile.center)
# Hover the Sub item
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move(refSub.center)
# Move the menu window to the middle of the screen
for _ in range(2):
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_drag_and_drop(
ui_test.Vec2(refSub.position.x + refSub.size.x + 10, refSub.center.y - 10), ui_test.Vec2(128, 128)
)
# Click the File item
for _ in range(2):
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move_and_click(refFile.center)
# Hover the Sub item
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move(refSub.center)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_modern_button(self):
"""Click the menu bar"""
import omni.kit.ui_test as ui_test
clicked = []
class Delegate(ui.MenuDelegate):
def build_item(self, item):
with ui.HStack(width=200):
ui.Label(item.text)
with ui.VStack(content_clipping=1, width=0):
ui.Button("Button", clicked_fn=lambda: clicked.append(True))
delegate = Delegate()
window = await self.create_test_window(block_devices=False)
with window.frame:
with ui.Menu(height=0, menu_compatibility=0, direction=ui.Direction.LEFT_TO_RIGHT):
file = ui.Menu("File")
with file:
child = ui.MenuItem("File 1", delegate=delegate)
ui.MenuItem("File 2", delegate=delegate)
ui.MenuItem("File 3", delegate=delegate)
with ui.Menu("Edit"):
ui.MenuItem("Edit 1", delegate=delegate)
ui.MenuItem("Edit 2", delegate=delegate)
ui.MenuItem("Edit 3", delegate=delegate)
ref_file = ui_test.WidgetRef(file, "")
ref_child = ui_test.WidgetRef(child, "")
# Click the File item
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move_and_click(ref_file.center)
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move_and_click(
ui_test.Vec2(ref_child.position.x + ref_child.size.x - 10, ref_child.center.y)
)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(len(clicked), 1)
await self.finalize_test()
async def test_modern_enabled(self):
"""Click the menu bar"""
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
with window.frame:
with ui.Menu(height=0, menu_compatibility=0, direction=ui.Direction.LEFT_TO_RIGHT):
file = ui.Menu("File")
with file:
ui.MenuItem("File 1")
ui.MenuItem("File 2", enabled=False)
f3 = ui.MenuItem("File 3")
f4 = ui.MenuItem("File 4", enabled=False)
with ui.Menu("Edit"):
ui.MenuItem("Edit 1")
ui.MenuItem("Edit 2")
ui.MenuItem("Edit 3")
ref = ui_test.WidgetRef(file, "")
# Click the File item
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move_and_click(ref.center)
await omni.kit.app.get_app().next_update_async()
# Changed enabled runtime while the menu is open
f3.enabled = False
f4.enabled = True
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_modern_submenu_disabled(self):
"""Test sub-menu items when parent si disabled"""
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
with window.frame:
with ui.Menu(height=0, menu_compatibility=0, direction=ui.Direction.LEFT_TO_RIGHT):
file = ui.Menu("File")
with file:
file_1 = ui.Menu("File 1", enabled=True)
with file_1:
ui.MenuItem("File 1a")
ui.MenuItem("File 1b")
file_2 = ui.Menu("File 2", enabled=False)
with file_2:
ui.MenuItem("File 2a")
ui.MenuItem("File 2b")
ref = ui_test.WidgetRef(file, "")
ref_1 = ui_test.WidgetRef(file_1, "")
ref_2 = ui_test.WidgetRef(file_2, "")
# Click the File item
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move_and_click(ref.center)
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move(ref_1.center)
for _ in range(3):
await omni.kit.app.get_app().next_update_async()
await self.capture_and_compare(golden_img_name="omni.ui_scene.tests.TestMenu.test_modern_submenu_disabled_on.png")
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move(ref_2.center)
for _ in range(3):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test(golden_img_name="omni.ui_scene.tests.TestMenu.test_modern_submenu_disabled_off.png")
async def test_window(self):
"""Check we can create a window from menu"""
import omni.kit.ui_test as ui_test
menu = ui.Menu("menu", name="this")
dialogs = []
def _build_message_popup():
dialogs.append(ui.Window("Message", width=100, height=50))
def _show_context_menu(x, y, button, modifier):
if button != 1:
return
menu.clear()
with menu:
ui.MenuItem("Create Pop-up", triggered_fn=_build_message_popup)
menu.show()
window = await self.create_test_window(block_devices=False)
with window.frame:
button = ui.Button("context menu", width=0, height=0, mouse_pressed_fn=_show_context_menu)
await omni.kit.app.get_app().next_update_async()
ref = ui_test.WidgetRef(button, "")
await ui_test.emulate_mouse_move_and_click(ref.center, right_click=True)
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move_and_click(
ui_test.Vec2(ref.position.x + ref.size.x, ref.position.y + ref.size.y)
)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_namespace.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from .test_base import OmniUiTest
import omni.ui as ui
def one():
return 1
class TestNamespace(OmniUiTest):
"""Testing ui.Workspace"""
async def test_namespace(self):
"""Testing window selection callback"""
subscription = ui.add_to_namespace(one)
self.assertIn("one", dir(ui))
self.assertEqual(ui.one(), 1)
del subscription
subscription = None
self.assertNotIn("one", dir(ui))
# Testing module=None
ui.add_to_namespace()
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_rectangle.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from .test_base import OmniUiTest
import omni.ui as ui
class TestRectangle(OmniUiTest):
"""Testing ui.Rectangle"""
async def test_general(self):
"""Testing general properties of ui.Rectangle"""
window = await self.create_test_window()
with window.frame:
with ui.VStack():
with ui.HStack():
ui.Rectangle()
ui.Rectangle(style={"background_color": 0xFFFF0000})
ui.Rectangle(style={"Rectangle": {"background_color": 0x66FF0000}})
with ui.HStack():
ui.Rectangle(
style={"background_color": 0x0, "border_color": 0xFF00FFFF, "border_width": 1, "margin": 5}
)
ui.Rectangle(
style={
"background_color": 0x0,
"border_color": 0xFFFFFF00,
"border_width": 2,
"border_radius": 20,
"margin_width": 5,
}
)
ui.Rectangle(
style={
"background_color": 0xFF00FFFF,
"border_color": 0xFFFFFF00,
"border_width": 2,
"border_radius": 5,
"margin_height": 5,
}
)
with ui.HStack():
ui.Rectangle(
style={
"background_color": 0xFF00FFFF,
"border_color": 0xFFFFFF00,
"border_width": 1,
"border_radius": 10,
"corner_flag": ui.CornerFlag.LEFT,
}
)
ui.Rectangle(
style={
"background_color": 0xFFFF00FF,
"border_color": 0xFF00FF00,
"border_width": 1,
"border_radius": 10,
"corner_flag": ui.CornerFlag.RIGHT,
}
)
ui.Rectangle(
style={
"background_color": 0xFFFFFF00,
"border_color": 0xFFFF0000,
"border_width": 1,
"border_radius": 10,
"corner_flag": ui.CornerFlag.TOP,
}
)
ui.Rectangle(
style={
"background_color": 0xFF666666,
"border_color": 0xFF0000FF,
"border_width": 1,
"border_radius": 10,
"corner_flag": ui.CornerFlag.BOTTOM,
}
)
await self.finalize_test()
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_canvasframe.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import unittest
from .test_base import OmniUiTest
from functools import partial
import omni.kit.app
import omni.ui as ui
WINDOW_STYLE = {"Window": {"background_color": 0xFF303030, "border_color": 0x0, "border_width": 0, "border_radius": 0}}
TEXT = (
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut "
"labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco "
"laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in "
"voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat "
"non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
)
class TestCanvasFrame(OmniUiTest):
"""Testing ui.CanvasFrame"""
async def test_general(self):
"""Testing general properties of ui.CanvasFrame"""
window = await self.create_test_window()
with window.frame:
with ui.CanvasFrame():
with ui.VStack(height=0):
# Simple text
ui.Label("Hello world")
# Word wrap
ui.Label(TEXT, word_wrap=True)
# Gray button
ui.Button(
"Button",
style={
"Button": {"background_color": 0xFF666666, "margin": 0, "padding": 4, "border_radius": 0}
},
)
await self.finalize_test()
@unittest.skip("Disabling temporarily to avoid failure due to bold 'l' on linux font")
async def test_zoom(self):
"""Testing zoom of ui.CanvasFrame"""
window = await self.create_test_window()
with window.frame:
with ui.CanvasFrame(zoom=0.5):
with ui.VStack(height=0):
# Simple text
ui.Label("Hello world")
# Word wrap
ui.Label(TEXT, word_wrap=True)
# Gray button
ui.Button(
"Button",
style={
"Button": {"background_color": 0xFF666666, "margin": 0, "padding": 8, "border_radius": 0}
},
)
await self.finalize_test()
async def test_pan(self):
"""Testing zoom of ui.CanvasFrame"""
window = await self.create_test_window()
with window.frame:
with ui.CanvasFrame(pan_x=64, pan_y=128):
with ui.VStack(height=0):
# Simple text
ui.Label("Hello world")
# Word wrap
ui.Label(TEXT, word_wrap=True)
# Gray button
ui.Button(
"Button",
style={
"Button": {"background_color": 0xFF666666, "margin": 0, "padding": 4, "border_radius": 0}
},
)
await self.finalize_test()
async def test_space(self):
"""Testing transforming screen space to canvas space of ui.CanvasFrame"""
window = await self.create_test_window()
with window.frame:
frame = ui.CanvasFrame(pan_x=512, pan_y=1024)
with frame:
placer = ui.Placer()
with placer:
# Gray button
ui.Button(
"Button",
width=0,
height=0,
style={
"Button": {"background_color": 0xFF666666, "margin": 0, "padding": 4, "border_radius": 0}
},
)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
placer.offset_x = frame.screen_to_canvas_x(frame.screen_position_x + 128)
placer.offset_y = frame.screen_to_canvas_y(frame.screen_position_y + 128)
await self.finalize_test()
async def test_navigation_pan(self):
"""Test how CanvasFrame interacts with mouse"""
import omni.kit.ui_test as ui_test
pan = [0, 0]
def pan_changed(axis, value):
pan[axis] = value
window = await self.create_test_window(block_devices=False)
with window.frame:
canvas = ui.CanvasFrame(smooth_zoom=False)
canvas.set_pan_key_shortcut(0, 0)
canvas.set_pan_x_changed_fn(partial(pan_changed, 0))
canvas.set_pan_y_changed_fn(partial(pan_changed, 1))
with canvas:
with ui.VStack(height=0):
# Simple text
ui.Label("Hello world")
# Word wrap
ui.Label(TEXT, word_wrap=True)
# Button
ui.Button("Button")
ref = ui_test.WidgetRef(window.frame, "")
for i in range(2):
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move(ref.center)
await ui_test.emulate_mouse_drag_and_drop(ref.center, ref.center * 0.8, human_delay_speed=1)
for i in range(2):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
self.assertEqual(pan[0], -26)
self.assertEqual(pan[1], -26)
async def test_navigation_zoom(self):
"""Test how CanvasFrame interacts with mouse zoom"""
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
with window.frame:
canvas = ui.CanvasFrame(smooth_zoom=False)
canvas.set_zoom_key_shortcut(1, 0)
self.assertEqual(canvas.zoom, 1.0)
ref = ui_test.WidgetRef(window.frame, "")
for i in range(2):
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move(ref.center)
await ui_test.emulate_mouse_drag_and_drop(ref.center, ref.center * 0.5, right_click=True, human_delay_speed=1)
for i in range(2):
await omni.kit.app.get_app().next_update_async()
# check the zoom is changed with the key_index press and right click
self.assertAlmostEqual(canvas.zoom, 0.8950250148773193, 1)
await self.finalize_test_no_image()
async def test_zoom_with_limits(self):
"""Testing zoom is limited by the zoom_min and zoom_max"""
window = await self.create_test_window()
with window.frame:
frame = ui.CanvasFrame(zoom=2.5, zoom_max=2.0, zoom_min=0.5)
with frame:
with ui.HStack():
ui.Spacer()
with ui.VStack():
ui.Spacer()
ui.Rectangle(width=50, height=50, style={"background_color": 0xFF000066})
ui.Spacer()
ui.Spacer()
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
# check the zoom is limited by zoom_max = 2.0
self.assertEqual(frame.screen_position_x, 2.0)
self.assertEqual(frame.screen_position_y, 2.0)
async def test_compatibility(self):
"""Testing zoom of ui.CanvasFrame"""
window = await self.create_test_window()
with window.frame:
with ui.CanvasFrame(zoom=0.5, pan_x=64, pan_y=64, compatibility=False):
with ui.VStack(height=0):
# Simple text
ui.Label("NVIDIA")
# Word wrap
ui.Label(TEXT, word_wrap=True)
# Gray button
ui.Button(
"Button",
style={
"Button": {"background_color": 0xFF666666, "margin": 0, "padding": 8, "border_radius": 0}
},
)
await self.finalize_test()
async def test_compatibility_text(self):
"""Testing zoom of ui.CanvasFrame"""
window = await self.create_test_window()
with window.frame:
with ui.CanvasFrame(zoom=4.0, compatibility=False):
with ui.VStack(height=0):
# Simple text
ui.Label("NVIDIA")
# Word wrap
ui.Label(TEXT, word_wrap=True)
# Gray button
ui.Button(
"Button",
style={
"Button": {"background_color": 0xFF666666, "margin": 0, "padding": 8, "border_radius": 0}
},
)
# Make sure we only have one font cached
for _ in range(2):
await omni.kit.app.get_app().next_update_async()
self.assertEqual(len(ui.Inspector.get_stored_font_atlases()), 1)
await self.finalize_test()
async def test_compatibility_clipping(self):
window = await self.create_test_window()
with window.frame:
with ui.CanvasFrame(compatibility=0):
with ui.Placer(draggable=1, width=50, height=50, offset_x=5, offset_y=50):
ui.Circle(
width=50,
height=50,
style={"background_color": ui.color.white},
arc=ui.Alignment.RIGHT_BOTTOM,
)
await self.finalize_test()
async def test_compatibility_clipping_2(self):
# Create a backgroud window
window = await self.create_test_window()
# Create a new UI window
window1 = ui.Window("clip 2", width=100, height=100, position_x=10, position_y=10)
# Begin drawing contents inside window1
with window1.frame:
# Create a canvas frame with compatibility mode off
canvas_frame = ui.CanvasFrame(compatibility=0, name="my")
with canvas_frame:
with ui.Frame():
with ui.ZStack(content_clipping=1):
# Add a blue rectangle inside the ZStack
ui.Rectangle(width=50, height=50, style={"background_color": ui.color.blue})
with ui.Placer(draggable=True, width=10, height=10):
ui.Rectangle(style={"background_color": 0xff123456})
# Wait for the next update cycle of the application
await omni.kit.app.get_app().next_update_async()
# Pan the canvas frame to the specified coordinates
canvas_frame.pan_x = 100
canvas_frame.pan_y = 80
# Finalize and clean up the test
await self.finalize_test()
async def test_compatibility_pan(self):
"""test pan is working when compatibility=0"""
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
with window.frame:
canvas = ui.CanvasFrame(compatibility=0)
canvas.set_pan_key_shortcut(0, 0)
with canvas:
with ui.VStack(height=0):
# Simple text
ui.Label("Hello world")
# Word wrap
ui.Label(TEXT, word_wrap=True)
# Button
ui.Button("Button")
ref = ui_test.WidgetRef(window.frame, "")
await ui_test.wait_n_updates(2)
await ui_test.emulate_mouse_move(ref.center)
await ui_test.emulate_mouse_drag_and_drop(ref.center, ref.center * 0.8, human_delay_speed=1)
await ui_test.wait_n_updates(2)
await self.finalize_test()
async def test_pan_no_leak(self):
"""test pan from one canvasFrame is not leaking to another canvasFrame """
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False, height=600)
with window.frame:
with ui.VStack():
with ui.Frame(height=300):
canvas1 = ui.CanvasFrame(style={"background_color": omni.ui.color.red})
canvas1.set_pan_key_shortcut(1, 0)
with canvas1:
ui.Label("HELLO WORLD")
with ui.Frame(height=300):
canvas2 = ui.CanvasFrame(style={"background_color": omni.ui.color.blue})
canvas2.set_pan_key_shortcut(1, 0)
with canvas2:
ui.Label("NVIDIA")
ref1 = ui_test.WidgetRef(canvas1, "")
ref2 = ui_test.WidgetRef(canvas2, "")
await ui_test.wait_n_updates(2)
# pan from the first canvas to second canvas, we should only see first canvas panned, but not the second one
await ui_test.emulate_mouse_move(ref1.center)
await ui_test.emulate_mouse_drag_and_drop(ref1.center, ref2.center, right_click=True, human_delay_speed=1)
await ui_test.wait_n_updates(2)
await self.finalize_test()
async def test_zoom_no_leak(self):
"""test zoom from one canvasFrame is not leaking to another canvasFrame """
import omni.kit.ui_test as ui_test
from omni.kit.ui_test.vec2 import Vec2
window = await self.create_test_window(block_devices=False, height=600)
with window.frame:
with ui.VStack():
with ui.Frame(height=300):
canvas1 = ui.CanvasFrame(compatibility=0, style={"background_color": omni.ui.color.red})
canvas1.set_zoom_key_shortcut(1, 0)
with canvas1:
ui.Label("HELLO WORLD")
with ui.Frame(height=300):
canvas2 = ui.CanvasFrame(compatibility=0, style={"background_color": omni.ui.color.blue})
canvas2.set_zoom_key_shortcut(1, 0)
with canvas2:
ui.Label("NVIDIA")
ref1 = ui_test.WidgetRef(canvas1, "")
ref2 = ui_test.WidgetRef(canvas2, "")
await ui_test.wait_n_updates(2)
# zoom from the second canvas to first canvas, we should only see second canvas zoomed, but not the first one
await ui_test.emulate_mouse_move(ref2.center)
await ui_test.emulate_mouse_drag_and_drop(ref2.center, ref1.center * 0.5, right_click=True, human_delay_speed=1)
self.assertEqual(canvas1.zoom, 1.0)
self.assertNotEqual(canvas2.zoom, 1.0)
await self.finalize_test_no_image()
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_field.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
import omni.ui as ui
import omni.kit.app
from .test_base import OmniUiTest
STYLE = {
"Field": {
"background_color": 0xFF000000,
"color": 0xFFFFFFFF,
"border_color": 0xFFFFFFFF,
"background_selected_color": 0xFFFF6600,
"border_width": 1,
"border_radius": 0,
}
}
class TestField(OmniUiTest):
"""Testing fields"""
async def test_general(self):
"""Testing general properties of ui.StringField"""
window = await self.create_test_window()
with window.frame:
with ui.VStack(height=0, style=STYLE, spacing=2):
# Simple field
ui.StringField()
ui.StringField().model.set_value("Hello World")
await self.finalize_test()
async def test_focus(self):
"""Testing the ability to focus in ui.StringField"""
window = await self.create_test_window()
with window.frame:
with ui.VStack(height=0, style=STYLE, spacing=2):
# Simple field
ui.StringField()
field = ui.StringField()
field.model.set_value("Hello World")
field.focus_keyboard()
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_defocus(self):
"""Testing the ability to defocus in ui.StringField"""
window = await self.create_test_window()
with window.frame:
with ui.VStack(height=0, style=STYLE, spacing=2):
# Simple field
ui.StringField()
field = ui.StringField()
field.model.set_value("Hello World")
field.focus_keyboard()
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
field.focus_keyboard(False)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_change_when_editing(self):
"""Testing the ability to defocus in ui.StringField"""
window = await self.create_test_window()
with window.frame:
with ui.VStack(height=0, style=STYLE, spacing=2):
# Simple field
ui.StringField()
field = ui.StringField()
field.model.set_value("Hello World")
field.focus_keyboard()
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
field.model.set_value("Data Change")
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_multifield_resize(self):
"""Testing general properties of ui.StringField"""
window = await self.create_test_window(256, 64)
with window.frame:
stack = ui.VStack(height=0, width=100, style=STYLE, spacing=2)
with stack:
# Simple field
ui.MultiFloatField(1.0, 1.0, 1.0)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
stack.width = ui.Fraction(1)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_slider.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from .test_base import OmniUiTest
import omni.ui as ui
import omni.kit.app
from omni.ui import color as cl
class TestSlider(OmniUiTest):
"""Testing ui.Frame"""
async def test_general(self):
"""Testing general properties of ui.Slider"""
window = await self.create_test_window()
with window.frame:
with ui.VStack(height=0, spacing=2):
ui.FloatSlider(style={"draw_mode": ui.SliderDrawMode.HANDLE}).model.set_value(0.5)
ui.IntSlider(style={"draw_mode": ui.SliderDrawMode.HANDLE}).model.set_value(15)
ui.FloatSlider(
style={
"draw_mode": ui.SliderDrawMode.FILLED,
"background_color": 0xFF333333,
"secondary_color": 0xFF666666,
}
).model.set_value(0.25)
ui.IntSlider(
style={
"draw_mode": ui.SliderDrawMode.FILLED,
"background_color": 0xFF333333,
"secondary_color": 0xFF666666,
}
).model.set_value(10)
ui.FloatSlider(
style={
"draw_mode": ui.SliderDrawMode.FILLED,
"background_color": 0xFF333333,
"secondary_color": 0xFF666666,
"secondary_color": 0xFF666666,
"border_color": 0xFFFFFFFF,
"border_width": 1,
"border_radius": 20,
}
).model.set_value(0.4375)
# 0.015625 will be rounded differently on linux and windows
# See https://stackoverflow.com/questions/4649554 for details
# To fix it, add something small
ui.FloatSlider(
style={
"draw_mode": ui.SliderDrawMode.FILLED,
"background_color": 0xFF333333,
"secondary_color": 0xFF666666,
"secondary_color": 0xFF666666,
"border_color": 0xFFFFFFFF,
"border_width": 1,
"border_radius": 20,
}
).model.set_value(0.015625 + 1e-10)
ui.FloatDrag().model.set_value(0.375)
ui.IntDrag().model.set_value(25)
await self.finalize_test()
async def test_padding(self):
"""Testing slider's padding"""
style = {
"background_color": cl.grey,
"draw_mode": ui.SliderDrawMode.FILLED,
"border_width": 1,
"border_color": cl.black,
"border_radius": 0,
"font_size": 16,
"padding": 0,
}
window = await self.create_test_window()
with window.frame:
with ui.VStack(height=0):
for i in range(8):
style["padding"] = i * 2
with ui.HStack(height=0):
ui.FloatSlider(style=style, height=0)
ui.FloatField(style=style, height=0)
await self.finalize_test()
async def test_float_slider_precision(self):
window = await self.create_test_window()
with window.frame:
with ui.VStack(height=0):
ui.FloatSlider(precision=7, height=0).model.set_value(0.00041233)
ui.FloatDrag(precision=8, height=0).model.set_value(0.00041233)
ui.FloatField(precision=5, height=0).model.set_value(0.00041233)
await self.finalize_test()
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_shapes.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.
##
__all__ = ["TestShapes"]
import omni.kit.test
from .test_base import OmniUiTest
import omni.ui as ui
from omni.ui import color as cl
class TestShapes(OmniUiTest):
"""Testing ui.Shape"""
async def test_offsetline(self):
"""Testing general properties of ui.OffsetLine"""
window = await self.create_test_window()
with window.frame:
with ui.ZStack(
style={
"Rectangle": {"background_color": cl(0, 0, 0, 0), "border_color": cl.white, "border_width": 1},
"OffsetLine": {"color": cl.white, "border_width": 1},
}
):
with ui.VStack():
with ui.HStack(height=32):
rect1 = ui.Rectangle(width=32)
ui.Spacer()
ui.Spacer()
with ui.HStack(height=32):
ui.Spacer()
rect2 = ui.Rectangle(width=32)
ui.OffsetLine(
rect1,
rect2,
alignment=ui.Alignment.UNDEFINED,
begin_arrow_type=ui.ArrowType.ARROW,
offset=7,
bound_offset=20,
)
ui.OffsetLine(
rect2,
rect1,
alignment=ui.Alignment.UNDEFINED,
begin_arrow_type=ui.ArrowType.ARROW,
offset=7,
bound_offset=20,
)
await self.finalize_test()
async def test_freebezier(self):
"""Testing general properties of ui.OffsetLine"""
window = await self.create_test_window()
with window.frame:
with ui.ZStack(
style={
"Rectangle": {"background_color": cl(0, 0, 0, 0), "border_color": cl.white, "border_width": 1},
"FreeBezierCurve": {"color": cl.white, "border_width": 1},
}
):
with ui.VStack():
with ui.HStack(height=32):
rect1 = ui.Rectangle(width=32)
ui.Spacer()
ui.Spacer()
with ui.HStack(height=32):
ui.Spacer()
rect2 = ui.Rectangle(width=32)
# Default tangents
ui.FreeBezierCurve(rect1, rect2, style={"color": cl.chartreuse})
# 0 tangents
ui.FreeBezierCurve(
rect1,
rect2,
start_tangent_width=0,
start_tangent_height=0,
end_tangent_width=0,
end_tangent_height=0,
style={"color": cl.darkslategrey},
)
# Fraction tangents
ui.FreeBezierCurve(
rect1,
rect2,
start_tangent_width=0,
start_tangent_height=ui.Fraction(2),
end_tangent_width=0,
end_tangent_height=ui.Fraction(-2),
style={"color": cl.dodgerblue},
)
# Percent tangents
ui.FreeBezierCurve(
rect1,
rect2,
start_tangent_width=0,
start_tangent_height=ui.Percent(100),
end_tangent_width=0,
end_tangent_height=ui.Percent(-100),
style={"color": cl.peru},
)
# Super big tangents
ui.FreeBezierCurve(
rect1,
rect2,
start_tangent_width=0,
start_tangent_height=1e8,
end_tangent_width=0,
end_tangent_height=-1e8,
style={"color": cl.indianred},
)
await self.finalize_test()
async def test_freeshape_hover(self):
"""Testing freeshape mouse hover"""
import omni.kit.ui_test as ui_test
is_hovered = False
def mouse_hover(hovered):
nonlocal is_hovered
is_hovered = hovered
window = await self.create_test_window(block_devices=False)
with window.frame:
with ui.ZStack():
# Four draggable rectangles that represent the control points
with ui.Placer(draggable=True, offset_x=0, offset_y=0):
control1 = ui.Circle(width=10, height=10)
with ui.Placer(draggable=True, offset_x=150, offset_y=150):
control2 = ui.Circle(width=10, height=10)
# The rectangle that fits to the control points
shape = ui.FreeRectangle(
control1,
control2,
mouse_hovered_fn=mouse_hover,
)
try:
await ui_test.human_delay()
self.assertFalse(is_hovered)
shape_ref = ui_test.WidgetRef(shape, "")
await ui_test.emulate_mouse_move(shape_ref.center)
await ui_test.human_delay()
self.assertTrue(is_hovered)
finally:
await self.finalize_test_no_image()
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_frame.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from functools import partial
from .test_base import OmniUiTest
import omni.ui as ui
import omni.kit.app
class TestFrame(OmniUiTest):
"""Testing ui.Frame"""
async def test_general(self):
"""Testing general properties of ui.Frame"""
window = await self.create_test_window()
with window.frame:
with ui.VStack():
with ui.Frame(width=0, height=0):
ui.Label("Label in Frame")
with ui.Frame(width=0, height=0):
ui.Label("First label, should not be displayed")
ui.Label("Second label, should be displayed")
with ui.Frame(height=0):
ui.Label("Long Label in Frame. " * 10, word_wrap=True)
with ui.Frame(horizontal_clipping=True, width=ui.Percent(50), height=0):
ui.Label("This should be clipped horizontally. " * 10)
with ui.Frame(vertical_clipping=True, height=20):
ui.Label("This should be clipped vertically. " * 10, word_wrap=True)
await self.finalize_test()
async def test_deferred(self):
"""Testing deferred population of ui.Frame"""
window = await self.create_test_window()
def two_labels():
ui.Label("First label, should not be displayed")
ui.Label("Second label, should be displayed")
with window.frame:
with ui.VStack():
ui.Frame(height=0, build_fn=lambda: ui.Label("Label in Frame"))
ui.Frame(height=0, build_fn=two_labels)
ui.Frame(height=0, build_fn=lambda: ui.Label("Long text " * 15, word_wrap=True))
ui.Frame(
horizontal_clipping=True,
width=ui.Percent(50),
height=0,
build_fn=lambda: ui.Label("horizontal clipping " * 15),
)
frame = ui.Frame(height=0)
with frame:
ui.Label("A deferred function will override this widget")
frame.set_build_fn(lambda: ui.Label("This widget should be displayed"))
# Wait two frames to let Frame create deferred children. The first
# frame the window is Appearing.
await omni.kit.app.get_app().next_update_async()
# The second frame build_fn is called
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_deferred_first_frame(self):
"""Testing the first frame of deferred population of ui.Frame"""
window = await self.create_test_window()
# The first frame the window is initializing its size.
await omni.kit.app.get_app().next_update_async()
with window.frame:
with ui.VStack():
ui.Frame(height=0, build_fn=lambda: ui.Label("Label in the first frame"))
await self.finalize_test()
async def test_deferred_rebuild(self):
"""Testing deferred rebuild of ui.Frame"""
window = await self.create_test_window()
self._rebuild_counter = 0
def label_counter(self):
self._rebuild_counter += 1
ui.Label(f"Rebuild was called {self._rebuild_counter} times")
window.frame.set_build_fn(lambda s=self: label_counter(s))
# Wait two frames to let Frame create deferred children. The first
# frame the window is Appearing.
await omni.kit.app.get_app().next_update_async()
# The second frame build_fn is called
await omni.kit.app.get_app().next_update_async()
# Rebuild everything so build_fn should be called
window.frame.rebuild()
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_scroll(self):
import omni.kit.ui_test as ui_test
first = []
second = []
def scroll(flag, x, y, mod):
flag.append(x)
window = await self.create_test_window(block_devices=False)
# Empty window
window1 = ui.Window("Test1", width=100, height=100, position_x=10, position_y=10)
with window1.frame:
with ui.ZStack():
spacer = ui.Spacer(
mouse_wheel_fn=partial(scroll, first), scroll_only_window_hovered=1, mouse_pressed_fn=None
)
with ui.ZStack(content_clipping=1):
ui.Spacer()
await omni.kit.app.get_app().next_update_async()
ref = ui_test.WidgetRef(spacer, "")
await ui_test.emulate_mouse_move(ref.center)
await ui_test.emulate_mouse_scroll(ui_test.Vec2(1, 0))
await omni.kit.app.get_app().next_update_async()
self.assertTrue(len(first) == 0)
await self.finalize_test_no_image()
async def test_scroll_only_window_hovered(self):
import omni.kit.ui_test as ui_test
first = []
second = []
def scroll(flag, x, y, mod):
flag.append(x)
window = await self.create_test_window(block_devices=False)
# Empty window
window1 = ui.Window("Test1", width=100, height=100, position_x=10, position_y=10)
with window1.frame:
with ui.ZStack():
spacer = ui.Spacer(
mouse_wheel_fn=partial(scroll, first), scroll_only_window_hovered=0, mouse_pressed_fn=None
)
with ui.ZStack(content_clipping=1):
ui.Spacer()
await omni.kit.app.get_app().next_update_async()
ref = ui_test.WidgetRef(spacer, "")
await ui_test.emulate_mouse_move(ref.center)
await ui_test.emulate_mouse_scroll(ui_test.Vec2(1, 0))
await omni.kit.app.get_app().next_update_async()
self.assertTrue(len(first) == 1)
await self.finalize_test_no_image() |
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_abuse.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.ui as ui
import omni.kit.app
from .test_base import OmniUiTest
# *************** WARNING ***************
#
# NONE OF THE API USAGE OR PATTERNS IN THIS FILE SHOULD BE CONSIDERED GOOD
# THESE ARE TESTS ONLY THAT THAT APPLICATION WILL NOT CRASH WHEN APIS MISUSED
#
class SimpleIntModel(ui.SimpleIntModel):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def set_value(self, *args, **kwargs):
super().set_value(*args, **kwargs)
super()._value_changed()
class SimpleItem(ui.AbstractItem):
def __init__(self, value: str, *args, **kwargs):
super().__init__(*args, **kwargs)
self.name_model = ui.SimpleStringModel(value)
class SimpleItemModel(ui.AbstractItemModel):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__items = []
def destroy(self):
self.__items = []
def get_item_children(self, item: SimpleItem):
if item is None:
return self.__items
return []
def add_item(self, item: SimpleItem):
self.__items.append(item)
super()._item_changed(None)
def get_item_value_model_count(self, item: SimpleItem):
return 1
def get_item_value_model(self, item: SimpleItem, column_id: int):
return item.name_model if item else None
class TestAbuse(OmniUiTest):
"""Testing omni.ui callbacks do not crash"""
async def __cleanup_window(self, window: omni.ui.Window):
window.visible = False
window.destroy()
await self.finalize_test_no_image()
return None
async def test_empty_models_1(self):
"""Test that setting an empty model on ui objects does not crash"""
window = await self.create_test_window(block_devices=False)
app = omni.kit.app.get_app()
with window.frame:
with ui.VStack():
items = [
ui.CheckBox(),
ui.ComboBox(),
ui.FloatField(),
ui.FloatSlider(),
ui.IntField(),
ui.IntSlider(),
ui.ProgressBar(),
ui.StringField(),
ui.ToolButton(),
]
for _ in range(5):
await app.next_update_async()
for item in items:
item.model = None
for _ in range(5):
await app.next_update_async()
window = await self.__cleanup_window(window)
async def test_empty_models_2(self):
"""Test that setting an empty model on ui objects does not crash"""
window = await self.create_test_window()
app = omni.kit.app.get_app()
model = ui.SimpleBoolModel()
with window.frame:
with ui.VStack():
items = [
ui.ToolButton(model=model),
ui.CheckBox(model=model),
ui.ComboBox(model=model),
ui.FloatField(model=model),
ui.FloatSlider(model=model),
ui.IntField(model=model),
ui.IntSlider(model=model),
ui.ProgressBar(model=model),
ui.StringField(model=model),
]
model.set_value(True)
for _ in range(5):
await app.next_update_async()
def check_changed(*args):
# This slice is important to keep another crash from occuring by keeping at least on subscriber alive
for i in range(1, len(items)):
items[i].model = None
items[0].set_checked_changed_fn(check_changed)
model.set_value(False)
for _ in range(5):
await app.next_update_async()
window = await self.__cleanup_window(window)
async def test_workspace_window_visibility_changed(self):
"""Test that subscribe and unsubscribe to window visiblity will not crash"""
await self.create_test_area()
sub_1, sub_2 = None, None
def window_visibility_callback_2(*args, **kwargs):
nonlocal sub_1, sub_2
ui.Workspace.remove_window_visibility_changed_callback(sub_1)
ui.Workspace.remove_window_visibility_changed_callback(sub_2)
def window_visibility_callback_1(*args, **kwargs):
nonlocal sub_2
if sub_2 is None:
sub_2 = ui.Workspace.set_window_visibility_changed_callback(window_visibility_callback_2)
sub_1 = ui.Workspace.set_window_visibility_changed_callback(window_visibility_callback_1)
self.assertIsNotNone(sub_1)
window_1 = ui.Window("window_1", width=100, height=100)
self.assertIsNotNone(window_1)
self.assertIsNotNone(sub_2)
window_1.visible = False
# Test against unsubscibing multiple times
for _ in range(10):
ui.Workspace.remove_window_visibility_changed_callback(sub_1)
ui.Workspace.remove_window_visibility_changed_callback(sub_2)
for idx in range(64):
ui.Workspace.remove_window_visibility_changed_callback(idx)
window_1 = await self.__cleanup_window(window_1)
async def test_value_model_changed_subscriptions(self):
"""Test that subscribe and unsubscribe to ui.AbstractValueModel will not crash"""
def null_callback(*args, **kwargs):
pass
model_a = SimpleIntModel()
model_a.remove_value_changed_fn(64)
sub_id = model_a.add_value_changed_fn(null_callback)
for _ in range(4):
model_a.remove_value_changed_fn(sub_id)
model_a.remove_begin_edit_fn(64)
sub_id = model_a.add_begin_edit_fn(null_callback)
for _ in range(4):
model_a.remove_begin_edit_fn(sub_id)
model_a.remove_end_edit_fn(64)
sub_id = model_a.add_end_edit_fn(null_callback)
for _ in range(4):
model_a.remove_end_edit_fn(sub_id)
async def test_item_model_changed_subscriptions(self):
"""Test that subscribe and unsubscribe to ui.AbstractItemModel will not crash"""
def null_callback(*args, **kwargs):
pass
model_a = SimpleItemModel()
model_a.remove_item_changed_fn(64)
sub_id = model_a.add_item_changed_fn(null_callback)
for _ in range(4):
model_a.remove_item_changed_fn(sub_id)
model_a.remove_begin_edit_fn(64)
sub_id = model_a.add_begin_edit_fn(null_callback)
for _ in range(4):
model_a.remove_begin_edit_fn(sub_id)
model_a.remove_end_edit_fn(64)
sub_id = model_a.add_end_edit_fn(null_callback)
for _ in range(4):
model_a.remove_end_edit_fn(sub_id)
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_style.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 .test_base import OmniUiTest
from omni.ui import color as cl
from omni.ui import style as st
from omni.ui import url
from pathlib import Path
import omni.kit.app
import omni.ui as ui
CURRENT_PATH = Path(__file__).parent
DATA_PATH = CURRENT_PATH.parent.parent.parent.joinpath("data")
STYLE = {
"MyRect": {"background_color": 0xFFEDB51A},
"MyRect::test": {"background_color": 0xFFD6D50D},
"MyRect:disabled": {"background_color": 0xFFB6F70F},
"Rectangle": {"background_color": 0xFFF73F0F},
"Rectangle::test": {"background_color": 0xFFD66C0D},
"Rectangle:disabled": {"background_color": 0xFFD99C38},
"Window": {"background_color": 0xFF000000, "border_color": 0x0, "border_radius": 0},
}
STYLE_SHADE = {
"MyRect": {"background_color": cl.shade(0xFFEDB51A, light=cl("#DB6737"))},
"MyRect::test": {"background_color": cl.shade(0xFFD6D50D, light=cl("#F24E30"))},
"MyRect:disabled": {"background_color": cl.shade(0xFFB6F70F, light=cl("#E8302E"))},
"Rectangle": {"background_color": cl.shade(0xFFF73F0F, light=cl("#E8A838"))},
"Rectangle::test": {"background_color": cl.shade(0xFFD66C0D, light=cl("#F2983A"))},
"Rectangle:disabled": {"background_color": cl.shade(0xFFD99C38, light=cl("#DB7940"))},
"Window": {"background_color": 0xFF000000, "border_color": 0x0, "border_radius": 0},
}
class TestStyle(OmniUiTest):
"""Testing ui.Rectangle"""
async def test_default(self):
"""Testing using of st.default"""
buffer = st.default
window = await self.create_test_window()
with window.frame:
with ui.HStack():
ui.Rectangle()
ui.Rectangle(name="test")
ui.Rectangle(enabled=False)
ui.Rectangle(style_type_name_override="MyRect")
ui.Rectangle(style_type_name_override="MyRect", name="test")
ui.Rectangle(style_type_name_override="MyRect", enabled=False)
st.default = STYLE
await self.finalize_test()
st.default = buffer
async def test_window(self):
"""Testing using of window style"""
window = await self.create_test_window()
with window.frame:
with ui.HStack():
ui.Rectangle()
ui.Rectangle(name="test")
ui.Rectangle(enabled=False)
ui.Rectangle(style_type_name_override="MyRect")
ui.Rectangle(style_type_name_override="MyRect", name="test")
ui.Rectangle(style_type_name_override="MyRect", enabled=False)
window.frame.style = STYLE
await self.finalize_test()
async def test_stack(self):
"""Testing using of stack style"""
window = await self.create_test_window()
with window.frame:
with ui.HStack(style=STYLE):
ui.Rectangle()
ui.Rectangle(name="test")
ui.Rectangle(enabled=False)
ui.Rectangle(style_type_name_override="MyRect")
ui.Rectangle(style_type_name_override="MyRect", name="test")
ui.Rectangle(style_type_name_override="MyRect", enabled=False)
await self.finalize_test()
async def test_leaf(self):
"""Testing using of leaf children style"""
window = await self.create_test_window()
with window.frame:
with ui.HStack():
ui.Rectangle(style=STYLE)
ui.Rectangle(name="test", style=STYLE)
ui.Rectangle(enabled=False, style=STYLE)
ui.Rectangle(style_type_name_override="MyRect", style=STYLE)
ui.Rectangle(style_type_name_override="MyRect", name="test", style=STYLE)
ui.Rectangle(style_type_name_override="MyRect", enabled=False, style=STYLE)
await self.finalize_test()
async def test_shade(self):
"""Testing default shade"""
window = await self.create_test_window()
ui.set_shade()
with window.frame:
with ui.HStack():
ui.Rectangle()
ui.Rectangle(name="test")
ui.Rectangle(enabled=False)
ui.Rectangle(style_type_name_override="MyRect")
ui.Rectangle(style_type_name_override="MyRect", name="test")
ui.Rectangle(style_type_name_override="MyRect", enabled=False)
window.frame.style = STYLE_SHADE
await self.finalize_test()
async def test_named_shade(self):
"""Testing named shade"""
window = await self.create_test_window()
ui.set_shade()
with window.frame:
with ui.HStack():
ui.Rectangle()
ui.Rectangle(name="test")
ui.Rectangle(enabled=False)
ui.Rectangle(style_type_name_override="MyRect")
ui.Rectangle(style_type_name_override="MyRect", name="test")
ui.Rectangle(style_type_name_override="MyRect", enabled=False)
window.frame.style = STYLE_SHADE
ui.set_shade("light")
await self.finalize_test()
# Return it back to default
ui.set_shade()
async def test_named_colors(self):
"""Testing named shade"""
window = await self.create_test_window()
ui.set_shade()
cl.test = cl("#74B9AF")
cl.common = cl("#F24E30")
with window.frame:
with ui.HStack():
ui.Rectangle(style={"background_color": "DarkSlateGrey"})
ui.Rectangle(style={"background_color": "DarkCyan"})
ui.Rectangle(style={"background_color": "test"})
ui.Rectangle(style={"background_color": cl.shade(cl.test, light=cl.common, name="shade_name")})
ui.Rectangle(style={"background_color": cl.shade_name})
window.frame.style = STYLE_SHADE
ui.set_shade("light")
# Checking read-only colors
cl.DarkCyan = cl("#000000")
# Checking changing of colors by name
cl.common = cl("#9FDBCB")
await self.finalize_test()
# Return it back to default
ui.set_shade()
async def test_named_shade_append(self):
"""Testing named shade"""
window = await self.create_test_window()
ui.set_shade()
cl.test_named_shade = cl.shade(cl("#000000"), red=cl("#FF0000"), blue=cl("#0000FF"))
# Append blue to the existing shade. Two shades should be the same.
cl.test_named_shade_append = cl.shade(cl("#000000"), red=cl("#FF0000"))
cl.test_named_shade_append.add_shade(blue=cl("#0000FF"))
with window.frame:
with ui.HStack():
ui.Rectangle(style={"background_color": cl.test_named_shade})
ui.Rectangle(style={"background_color": cl.test_named_shade_append})
ui.set_shade("blue")
await self.finalize_test()
# Return it back to default
ui.set_shade()
async def test_named_urls(self):
"""Testing named shade"""
loaded = [0]
def track_progress(progress):
if progress == 1.0:
loaded[0] += 1
window = await self.create_test_window()
ui.set_shade()
# Wrong colors
url.test_red = f"{DATA_PATH}/tests/blue.png"
url.test_green = f"{DATA_PATH}/tests/red.png"
url.test_blue = f"{DATA_PATH}/tests/green.png"
with window.frame:
with ui.VStack():
with ui.HStack():
ui.Image(style={"image_url": url.test_red}, progress_changed_fn=track_progress)
ui.Image(style={"image_url": "test_green"}, progress_changed_fn=track_progress)
ui.Image(style={"image_url": url.test_blue}, progress_changed_fn=track_progress)
with ui.HStack():
ui.Image(
style={"image_url": url.shade(f"{DATA_PATH}/tests/red.png")}, progress_changed_fn=track_progress
)
ui.Image(
style={
"image_url": url.shade(
f"{DATA_PATH}/tests/blue.png", test_url=f"{DATA_PATH}/tests/green.png"
)
},
progress_changed_fn=track_progress,
)
ui.Image(
style={
"image_url": url.shade(
f"{DATA_PATH}/tests/blue.png", test_url_light=f"{DATA_PATH}/tests/green.png"
)
},
progress_changed_fn=track_progress,
)
# Correct colors
url.test_red = f"{DATA_PATH}/tests/red.png"
url.test_green = f"{DATA_PATH}/tests/green.png"
url.test_blue = f"{DATA_PATH}/tests/blue.png"
# Change shade
ui.set_shade("test_url")
while loaded[0] < 6:
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
# Return it back to default
ui.set_shade()
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/__init__.py | ## Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from .test_canvasframe import TestCanvasFrame
from .test_collapsableframe import TestCollapsableFrame
from .test_combobox import TestComboBox
from .test_configuration import ConfigurationTest
from .test_field import TestField
from .test_frame import TestFrame
from .test_grid import TestGrid
from .test_image import TestImage
from .test_label import TestLabel
from .test_layout import TestLayout
from .test_menu import TestMenu
from .test_namespace import TestNamespace
from .test_placer import TestPlacer
from .test_present import TestPresent
from .test_raster import TestRaster
from .test_rectangle import TestRectangle
from .test_scrollingframe import TestScrollingFrame
from .test_separator import TestSeparator
from .test_shapes import TestShapes
from .test_shadows import TestShadows
from .test_slider import TestSlider
from .test_style import TestStyle
from .test_tooltip import TestTooltip
from .test_treeview import TestTreeView
from .test_window import TestWindow
from .test_workspace import TestWorkspace
from .test_overflow import TestOverflow
from .test_abuse import TestAbuse
from .test_compare_utils import TestCompareUtils
from .test_no_gpu import TestNoGPU
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_scrollingframe.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from .test_base import OmniUiTest
import omni.ui as ui
import omni.kit.app
STYLE = {
"ScrollingFrame": {"background_color": 0xFF000000, "secondary_color": 0xFFFFFFFF, "scrollbar_size": 10},
"Label": {"color", 0xFFFFFFFF},
}
class TestScrollingFrame(OmniUiTest):
"""Testing ui.ScrollingFrame"""
async def test_general(self):
"""Testing general properties of ui.ScrollingFrame"""
window = await self.create_test_window()
with window.frame:
with ui.ScrollingFrame(
style=STYLE,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
):
with ui.VStack():
for i in range(50):
ui.Label(f"Label in ScrollingFrame {i}")
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_scroll(self):
"""Testing precize scroll position"""
window = await self.create_test_window()
with window.frame:
with ui.ScrollingFrame(
style=STYLE,
scroll_y=256,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
):
with ui.VStack():
for i in range(50):
ui.Label(f"Label in ScrollingFrame {i}")
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_size(self):
"""Testing size of child"""
window = await self.create_test_window()
with window.frame:
with ui.VStack(style=STYLE):
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
):
ui.Rectangle(style={"background_color": "black", "border_color": "red", "border_width": 1})
with ui.HStack():
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
):
ui.Rectangle(style={"background_color": "black", "border_color": "red", "border_width": 1})
with ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
):
ui.Rectangle(style={"background_color": "black", "border_color": "red", "border_width": 1})
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_scroll_end(self):
"""Testing max scroll x/y of ui.ScrollingFrame"""
window = await self.create_test_window()
with window.frame:
scrolling_frame = ui.ScrollingFrame(
style=STYLE,
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with scrolling_frame:
with ui.VStack():
for i in range(50):
ui.Label(f"Label in ScrollingFrame {i}")
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
scrolling_frame.scroll_y = scrolling_frame.scroll_y_max
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_treeview.py | ## Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from .test_base import OmniUiTest
from carb.input import MouseEventType
import omni.kit.app
import omni.ui as ui
STYLE = {
"TreeView:selected": {"background_color": 0x66FFFFFF},
"TreeView.Item": {"color": 0xFFCCCCCC},
"TreeView.Item:selected": {"color": 0xFFCCCCCC},
"TreeView.Header": {"background_color": 0xFF000000},
}
class ListItem(ui.AbstractItem):
"""Single item of the model"""
def __init__(self, text):
super().__init__()
self.name_model = ui.SimpleStringModel(text)
class ListModel(ui.AbstractItemModel):
"""
Represents the model for lists. It's very easy to initialize it
with any string list:
string_list = ["Hello", "World"]
model = ListModel(*string_list)
ui.TreeView(model)
"""
def __init__(self, *args):
super().__init__()
self._children = [ListItem(t) for t in args]
def get_item_children(self, item):
"""Returns all the children when the widget asks it."""
if item is not None:
# Since we are doing a flat list, we return the children of root only.
# If it's not root we return.
return []
return self._children
def get_item_value_model_count(self, item):
"""The number of columns"""
return 1
def get_item_value_model(self, item, column_id):
"""
Return value model.
It's the object that tracks the specific value.
In our case we use ui.SimpleStringModel.
"""
return item.name_model
class ListModelDND(ListModel):
def __init__(self, *args):
super().__init__(*args)
self.dropped = []
def get_drag_mime_data(self, item):
"""Returns Multipurpose Internet Mail Extensions (MIME) data for be able to drop this item somewhere"""
# As we don't do Drag and Drop to the operating system, we return the string.
return item.name_model.as_string
def drop_accepted(self, target_item, source, drop_location=-1):
return True
def drop(self, target_item, source, drop_location=-1):
self.dropped.append(source.name_model.as_string)
class TreeItem(ListItem):
"""Single item of the model"""
def __init__(self, text):
super().__init__(text)
self.children = None
def get_children(self):
if self.children is None:
self.children = [TreeItem(f"{i}") for i in range(3)]
return self.children
class InfinityModel(ui.AbstractItemModel):
def __init__(self, crash_test=False):
super().__init__()
self._children = [TreeItem("Root")]
self._crash_test = crash_test
self._dummy_model = ui.SimpleStringModel("NONE")
def get_item_children(self, item):
if item is None:
return self._children
if not hasattr(item, "get_children"):
return []
children = item.get_children()
if self._crash_test:
# Destroy children to see if treeview will crash
item.children = []
return children
def get_item_value_model_count(self, item):
return 1
def get_item_value_model(self, item, column_id):
if hasattr(item, "name_model"):
return item.name_model
return self._dummy_model
class InfinityModelTwoColumns(InfinityModel):
def get_item_value_model_count(self, item):
return 2
class ListDelegate(ui.AbstractItemDelegate):
"""A very simple delegate"""
def __init__(self):
super().__init__()
def build_branch(self, model, item, column_id, level, expanded):
"""Create a branch widget that opens or closes subtree"""
pass
def build_widget(self, model, item, column_id, level, expanded):
"""Create a widget per column per item"""
value_model = model.get_item_value_model(item, column_id)
label = value_model.as_string
ui.Label(label, name=label)
def build_header(self, column_id):
"""Create a widget for the header"""
label = f"Header {column_id}"
ui.Label(label, alignment=ui.Alignment.CENTER, name=label)
class TreeDelegate(ListDelegate):
def build_branch(self, model, item, column_id, level, expanded):
label = f"{'- ' if expanded else '+ '}"
ui.Label(label, width=(level + 1) * 10, alignment=ui.Alignment.RIGHT_CENTER, name=label)
class TestTreeView(OmniUiTest):
"""Testing ui.TreeView"""
async def test_general(self):
"""Testing default view of ui.TreeView"""
window = await self.create_test_window()
self._list_model = ListModel("Simplest", "List", "Of", "Strings")
with window.frame:
tree_view = ui.TreeView(self._list_model, root_visible=False, header_visible=False, style=STYLE)
# Wait one frame to let TreeView initialize the cache.
await omni.kit.app.get_app().next_update_async()
# Simulate Shift+Click on the second item when the selection is empty.
tree_view.extend_selection(self._list_model.get_item_children(None)[1])
await self.finalize_test()
async def test_scrolling_header(self):
"""Testing how the ui.TreeView behaves when scrolling"""
window = await self.create_test_window()
self._list_model = ListModel(*[f"Item {i}" for i in range(500)])
self._list_delegate = ListDelegate()
with window.frame:
scrolling = ui.ScrollingFrame(
horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON,
)
with scrolling:
tree_view = ui.TreeView(
self._list_model, delegate=self._list_delegate, root_visible=False, header_visible=True, style=STYLE
)
# Wait one frame to let TreeView initialize the cache.
await omni.kit.app.get_app().next_update_async()
scrolling.scroll_y = 1024
# Wait one frame for ScrollingFrame
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_tree(self):
"""Testing how the ui.TreeView show trees"""
window = await self.create_test_window()
self._tree_model = InfinityModel(crash_test=False)
self._tree_delegate = TreeDelegate()
with window.frame:
tree_view = ui.TreeView(
self._tree_model, delegate=self._tree_delegate, root_visible=False, header_visible=False, style=STYLE
)
# Wait one frame to let TreeView initialize the cache.
await omni.kit.app.get_app().next_update_async()
# Expand
root = self._tree_model.get_item_children(None)[0]
first_level = self._tree_model.get_item_children(root)[0]
tree_view.set_expanded(root, True, False)
await omni.kit.app.get_app().next_update_async()
tree_view.set_expanded(first_level, True, False)
await self.finalize_test()
async def test_inspector(self):
"""Testing how the ui.TreeView show trees"""
window = await self.create_test_window()
self._tree_model = InfinityModelTwoColumns()
self._tree_delegate = TreeDelegate()
with window.frame:
tree_view = ui.TreeView(
self._tree_model, delegate=self._tree_delegate, root_visible=False, header_visible=True, style=STYLE
)
# Wait one frame to let TreeView initialize the cache.
await omni.kit.app.get_app().next_update_async()
# Expand
root = self._tree_model.get_item_children(None)[0]
first_level = self._tree_model.get_item_children(root)[0]
tree_view.set_expanded(root, True, False)
tree_view.set_expanded(first_level, True, False)
children = ui.Inspector.get_children(tree_view)
# Check all the children one by one
self.assertEqual(len(children), 30)
for child in children:
self.assertIsInstance(child, ui.Label)
self.assertEqual(child.name, child.text)
self.assertEqual(children[0].text, "Header 0")
self.assertEqual(children[1].text, "Header 1")
self.assertEqual(children[2].text, "+ ")
self.assertEqual(children[3].text, "Root")
self.assertEqual(children[4].text, "+ ")
self.assertEqual(children[5].text, "Root")
self.assertEqual(children[6].text, "- ")
self.assertEqual(children[7].text, "0")
self.assertEqual(children[8].text, "- ")
self.assertEqual(children[9].text, "0")
self.assertEqual(children[10].text, "+ ")
self.assertEqual(children[11].text, "0")
self.assertEqual(children[12].text, "+ ")
self.assertEqual(children[13].text, "0")
self.assertEqual(children[14].text, "+ ")
self.assertEqual(children[15].text, "1")
self.assertEqual(children[16].text, "+ ")
self.assertEqual(children[17].text, "1")
self.assertEqual(children[18].text, "+ ")
self.assertEqual(children[19].text, "2")
self.assertEqual(children[20].text, "+ ")
self.assertEqual(children[21].text, "2")
self.assertEqual(children[22].text, "+ ")
self.assertEqual(children[23].text, "1")
self.assertEqual(children[24].text, "+ ")
self.assertEqual(children[25].text, "1")
self.assertEqual(children[26].text, "+ ")
self.assertEqual(children[27].text, "2")
self.assertEqual(children[28].text, "+ ")
self.assertEqual(children[29].text, "2")
await self.finalize_test()
async def test_query(self):
"""
Testing if ui.TreeView crashing when querying right after
initialization.
"""
window = await self.create_test_window()
self._tree_model = InfinityModel()
self._tree_delegate = TreeDelegate()
with window.frame:
tree_view = ui.TreeView(
self._tree_model, delegate=self._tree_delegate, root_visible=False, header_visible=True, style=STYLE
)
# Don't wait one frame and don't let TreeView initialize the cache.
# Trigger dirty
tree_view.style = {"Label": {"font_size": 14}}
# Query children and make sure it doesn't crash.
children = ui.Inspector.get_children(tree_view)
self.assertEqual(len(children), 3)
self.assertEqual(children[0].text, "Header 0")
self.assertEqual(children[1].text, "+ ")
self.assertEqual(children[2].text, "Root")
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_lost_items(self):
"""Testing how the ui.TreeView behaves when the items are destroyed"""
window = await self.create_test_window()
self._tree_model = InfinityModel(crash_test=True)
self._tree_delegate = TreeDelegate()
with window.frame:
tree_view = ui.TreeView(
self._tree_model, delegate=self._tree_delegate, root_visible=False, header_visible=False, style=STYLE
)
# Wait one frame to let TreeView initialize the cache.
await omni.kit.app.get_app().next_update_async()
# Expand
tree_view.set_expanded(self._tree_model.get_item_children(None)[0], True, False)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_dnd(self):
"""Testing drag and drop multiple items in ui.TreeView"""
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
item_names = [f"Item {i}" for i in range(10)]
_list_model = ListModelDND(*item_names)
with window.frame:
tree_view = ui.TreeView(_list_model, root_visible=False, header_visible=False, style=STYLE)
# Wait one frame to let TreeView initialize the cache.
await omni.kit.app.get_app().next_update_async()
item0 = ui_test.find(f"{window.title}//Frame/**/Label[*].text=='Item 0'")
item1 = ui_test.find(f"{window.title}//Frame/**/Label[*].text=='Item 1'")
# Select items [1..9]
tree_view.extend_selection(_list_model.get_item_children(None)[1])
tree_view.extend_selection(_list_model.get_item_children(None)[len(item_names) - 1])
await ui_test.emulate_mouse_move(item1.center)
await ui_test.emulate_mouse_drag_and_drop(item1.center, item0.center)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
# Check we received the drop events for all the selection
for dropped, reference in zip(_list_model.dropped, item_names[1:]):
self.assertEqual(dropped, reference)
async def test_dnd_delegate_callbacks(self):
moved = [0]
pressed = [0]
released = [0]
class TestDelegate(ui.AbstractItemDelegate):
def build_widget(self, model, item, column_id, level, expanded):
if item is None:
return
if column_id == 0:
with ui.HStack(
mouse_pressed_fn=lambda x, y, b, m: self._on_item_mouse_pressed(item),
mouse_released_fn=lambda x, y, b, m: self._on_item_mouse_released(item),
mouse_moved_fn=lambda x, y, m, t: self._on_item_mouse_moved(x, y),
):
ui.Label(item.name_model.as_string)
def _on_item_mouse_moved(self, x, y):
moved[0] += 1
def _on_item_mouse_pressed(self, item):
pressed[0] += 1
def _on_item_mouse_released(self, item):
released[0] += 1
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
_model = ListModel("Test 1", "Test 2", "Test 3", "Test 4", "Test 5")
_delegate = TestDelegate()
with window.frame:
ui.TreeView(_model, delegate=_delegate, root_visible=False)
# Wait one frame to let TreeView initialize the cache.
await omni.kit.app.get_app().next_update_async()
item1 = ui_test.find(f"{window.title}//Frame/**/Label[*].text=='Test 1'")
item5 = ui_test.find(f"{window.title}//Frame/**/Label[*].text=='Test 5'")
await ui_test.emulate_mouse_move(item1.center)
await ui_test.input.emulate_mouse(MouseEventType.LEFT_BUTTON_DOWN)
await ui_test.human_delay(5)
# Check pressed is called
self.assertEqual(pressed[0], 1)
self.assertEqual(moved[0], 0)
await ui_test.input.emulate_mouse_slow_move(item1.center, item5.center)
await ui_test.human_delay(5)
# We have not released the mouse yet
self.assertEqual(released[0], 0)
self.assertTrue(moved[0] > 0)
await ui_test.input.emulate_mouse(MouseEventType.LEFT_BUTTON_UP)
await ui_test.human_delay(5)
# Checked release is called
self.assertEqual(released[0], 1)
await self.finalize_test_no_image()
async def test_item_hovered_callback(self):
"""Testing hover items in ui.TreeView"""
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
item_names = [f"Item {i}" for i in range(10)]
_list_model = ListModelDND(*item_names)
with window.frame:
tree_view = ui.TreeView(_list_model, root_visible=False, header_visible=False, style=STYLE)
# Wait one frame to let TreeView initialize the cache.
await omni.kit.app.get_app().next_update_async()
item0 = ui_test.find(f"{window.title}//Frame/**/Label[*].text=='Item 0'")
item1 = ui_test.find(f"{window.title}//Frame/**/Label[*].text=='Item 1'")
# initialize mouse outside of list, so it doesn't accidentally hover on the wrong thing at the start
await ui_test.emulate_mouse_move(ui_test.Vec2(0,0))
hover_status = {}
def __item_hovered(item: ui.AbstractItem, hovered: bool):
if item not in hover_status:
hover_status[item] = {
"enter": 0,
"leave": 0
}
if hovered:
hover_status[item]["enter"] += 1
else:
hover_status[item]["leave"] += 1
tree_view.set_hover_changed_fn(__item_hovered)
# Hover items [0]
await ui_test.emulate_mouse_move(item0.center)
await omni.kit.app.get_app().next_update_async()
# Hover items [1]
await ui_test.emulate_mouse_move(item1.center)
await omni.kit.app.get_app().next_update_async()
# Check we received the hover callbacks
self.assertEqual(len(hover_status), 2)
items = _list_model.get_item_children(None)
self.assertEqual(hover_status[items[0]]["enter"], 1)
self.assertEqual(hover_status[items[0]]["leave"], 1)
self.assertEqual(hover_status[items[1]]["enter"], 1)
self.assertEqual(hover_status[items[1]]["leave"], 0)
await self.finalize_test_no_image()
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_combobox.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from .test_base import OmniUiTest
import omni.kit.app
import omni.ui as ui
from omni.ui import color as cl
class TestComboBox(OmniUiTest):
"""Testing ui.ComboBox"""
async def test_general(self):
"""Testing general look of ui.ComboBox"""
window = await self.create_test_window()
with window.frame:
with ui.VStack():
# Simple combo box
style = {
"background_color": cl.black,
"border_color": cl.white,
"border_width": 1,
"padding": 0,
}
for i in range(8):
style["padding"] = i * 2
ui.ComboBox(0, f"{i}", "B", style=style, height=0)
await self.finalize_test()
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_compare_utils.py | import os
from pathlib import Path
import omni.kit.test
from .compare_utils import GOLDEN_DIR, OUTPUTS_DIR, CompareMetric, compare
from .test_base import OmniUiTest
class TestCompareUtils(omni.kit.test.AsyncTestCase):
async def setUp(self):
self.test_name = "omni.ui.tests.test_compare_utils.TestCompareUtils"
def cleanupTestFile(self, target: str):
try:
os.remove(target)
except FileNotFoundError:
pass
async def test_compare_rgb(self):
image1 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgb_golden.png")
image2 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgb_modified.png")
image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image1).stem}.diffmap.png")
# mean error
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR)
self.assertAlmostEqual(diff, 40.4879, places=3)
# mean error squared
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR_SQUARED)
self.assertAlmostEqual(diff, 0.031937, places=5)
# pixel count
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.PIXEL_COUNT)
self.assertEqual(diff, 262144)
async def test_compare_rgba(self):
image1 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgba_golden.png")
image2 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgba_modified.png")
image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image1).stem}.diffmap.png")
# mean error
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR)
self.assertAlmostEqual(diff, 0.4000, places=3)
# mean error squared
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR_SQUARED)
self.assertAlmostEqual(diff, 0.001466, places=5)
# pixel count
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.PIXEL_COUNT)
self.assertEqual(diff, 1961)
async def test_compare_rgb_itself(self):
image1 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgb_golden.png")
image2 = image1
image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image1).stem}.diffmap.png")
# mean error
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR)
self.assertEqual(diff, 0)
# mean error squared
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR_SQUARED)
self.assertEqual(diff, 0)
# pixel count
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.PIXEL_COUNT)
self.assertEqual(diff, 0)
async def test_compare_grayscale(self):
image1 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_grayscale_golden.png")
image2 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_grayscale_modified.png")
image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image1).stem}.diffmap.png")
# mean error
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR)
self.assertAlmostEqual(diff, 39.3010, places=3)
# mean error squared
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR_SQUARED)
self.assertAlmostEqual(diff, 0.030923, places=5)
# pixel count
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.PIXEL_COUNT)
self.assertEqual(diff, 260827)
async def test_compare_rgb_black_to_white(self):
image1 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgb_black.png")
image2 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgb_white.png")
image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image1).stem}.diffmap.png")
# mean error
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR)
self.assertEqual(diff, 255.0)
# mean error squared
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR_SQUARED)
self.assertEqual(diff, 1.0)
# pixel count
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.PIXEL_COUNT)
self.assertEqual(diff, 4096)
async def test_compare_rgba_black_to_white(self):
image1 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgba_black.png")
image2 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgba_white.png")
image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image1).stem}.diffmap.png")
# mean error
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR)
self.assertEqual(diff, 191.25)
# mean error squared
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR_SQUARED)
self.assertEqual(diff, 0.75)
# pixel count
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.PIXEL_COUNT)
self.assertEqual(diff, 4096)
async def test_compare_rgb_gray(self):
image1 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgb_gray.png")
image2 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgb_gray_modified.png")
image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image1).stem}.diffmap.png")
# mean error
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR)
self.assertEqual(diff, 48)
# mean error squared
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR_SQUARED)
self.assertAlmostEqual(diff, 0.094486, places=5)
# pixel count
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.PIXEL_COUNT)
self.assertEqual(diff, 2048)
async def test_compare_rgb_gray_pixel(self):
image1 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgb_gray_pixel.png")
image2 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_rgb_gray_pixel_modified.png")
image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image1).stem}.diffmap.png")
# mean error
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR)
self.assertAlmostEqual(diff, 0.0468, places=3)
# mean error squared
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR_SQUARED)
self.assertAlmostEqual(diff, 0.000092, places=5)
# pixel count
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.PIXEL_COUNT)
self.assertEqual(diff, 2)
async def test_compare_threshold(self):
image1 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_grayscale_golden.png")
image2 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_grayscale_modified.png")
image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image1).stem}.diffmap.png")
expected_diff = 39.30104446411133
# diff is below threshold (39.301 < 40) -> image_diffmap saved to disk
diff = compare(image1, image2, image_diffmap, threshold=40)
self.assertAlmostEqual(diff, expected_diff, places=3)
self.assertTrue(os.path.exists(image_diffmap))
self.cleanupTestFile(image_diffmap)
# diff is below threshold but threshold is above by 2 order of magnitude (39.301 < 4000/10) -> no image_diffmap
diff = compare(image1, image2, image_diffmap, threshold=4000)
self.assertAlmostEqual(diff, expected_diff, places=3)
self.assertFalse(os.path.exists(image_diffmap))
# no file cleanup to do here
# diff is above threshold (39.301 > 39) -> image_diffmap saved to disk
diff = compare(image1, image2, image_diffmap, threshold=39)
self.assertAlmostEqual(diff, expected_diff, places=3)
self.assertTrue(os.path.exists(image_diffmap))
self.cleanupTestFile(image_diffmap)
# diff is above threshold but threshold is below by 2 order of magnitude (39.301 > 3900/10) -> image_diffmap saved to disk
diff = compare(image1, image2, image_diffmap, threshold=3900)
self.assertAlmostEqual(diff, expected_diff, places=3)
self.assertTrue(os.path.exists(image_diffmap))
self.cleanupTestFile(image_diffmap)
async def test_default_threshold(self):
"""This test will give an example of an image comparison just above the default threshold"""
image1 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_threshold.png")
image2 = GOLDEN_DIR.joinpath(f"{self.test_name}.test_compare_threshold_modified.png")
image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image1).stem}.diffmap.png")
# mean error default threshold is 0.01
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR)
self.assertAlmostEqual(diff, OmniUiTest.MEAN_ERROR_THRESHOLD, places=2)
# mean error squared default threshold is 1e-5 (0.00001)
diff = compare(image1, image2, image_diffmap, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR_SQUARED)
self.assertAlmostEqual(diff, OmniUiTest.MEAN_ERROR_SQUARED_THRESHOLD, places=5)
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_present.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from .test_base import OmniUiTest
from functools import partial
import asyncio
import carb.settings
import csv
import omni.appwindow
import omni.kit.app
import omni.kit.renderer
import omni.ui as ui
import os
color = 0xFF123456
color_settings_path = "/exts/omni.kit.renderer.core/imgui/csvDump/vertexColor"
dump_settings_path = "/exts/omni.kit.renderer.core/imgui/csvDump/path"
enabled_settings_path = "/exts/omni.kit.renderer.core/present/enabled"
present_settings_path = "/app/runLoops/present/rateLimitFrequency"
main_settings_path = "/app/runLoops/main/rateLimitFrequency"
busy_present_settings_path = "/app/runLoops/present/rateLimitUseBusyLoop"
busy_main_settings_path = "/app/runLoops/main/rateLimitUseBusyLoop"
sync_settings_path = "/app/runLoops/main/syncToPresent"
global_sync_settings_path = "/app/runLoopsGlobal/syncToPresent"
async def _moving_rect(window, description: str):
"""
Setups moving rect in the given window. Setups csv dump from imgui. Reads
the dump and returns computed FPS for the current (from ImGui renderer point
of view present) and the main thread.
"""
rect_size = 50
speed = 0.02
max_counter = 1.0
settings = carb.settings.get_settings()
# Get a path to dump csv in the _testoutput directory
temp_path = os.path.join(omni.kit.test.get_test_output_path(), f"moving_rect-{description}.csv")
# remove any existing file (it's creation will be waited on below)
try:
os.remove(temp_path)
except FileNotFoundError:
pass
# pre-roll some frames for UI (to deal with test window resizing)
for _ in range(90):
await omni.kit.app.get_app().next_update_async()
with window.frame:
with ui.VStack():
ui.Spacer()
with ui.HStack(height=rect_size):
left = ui.Spacer(width=0)
ui.Rectangle(width=rect_size, style={"background_color": color})
right = ui.Spacer()
ui.Spacer()
# pre-roll even more frames after the UI was built
for _ in range(90):
await omni.kit.app.get_app().next_update_async()
settings.set(color_settings_path, color)
settings.set(dump_settings_path, temp_path)
# Move the rect
counter = 0.0
while counter <= max_counter:
await omni.kit.app.get_app().next_update_async()
counter += speed
normalized = counter % 2.0
if normalized > 1.0:
normalized = 2.0 - normalized
left.width = ui.Fraction(normalized)
right.width = ui.Fraction(1.0 - normalized)
# this is actually going to trigger the dump to temp_path
settings.set(dump_settings_path, "")
# now wait for temp_path to be generated
while not os.path.isfile(temp_path):
await omni.kit.app.get_app().next_update_async()
# file should be atomically swapped into place fully written
# but wait one frame before reading just in case
await omni.kit.app.get_app().next_update_async()
with open(temp_path, "r") as f:
reader = csv.reader(f)
data = [row for row in reader]
keys, values = zip(*data)
min_key = int(keys[0])
keys = [float((int(x) - min_key) / 10000) for x in keys]
values = [float(x) for x in values]
time_delta = [keys[i] - keys[i - 1] for i in range(1, len(keys))]
values = [values[i] - values[i - 1] for i in range(1, len(values))]
keys = keys[1:]
min_value, max_value = min(values), max(values)
margin = (max_value - min_value) * 0.1
min_value -= margin
max_value += margin
min_time = min(time_delta)
max_time = max(time_delta)
fps_current = 1000.0 / (sum(time_delta) / len(time_delta))
fps_main = 1000.0 / (keys[-1] / (max_counter / speed))
return fps_current, fps_main
def _on_present(future: asyncio.Future, counter, frames_to_wait, event):
"""
Sets result of the future after `frames_to_wait` calls.
"""
if not future.done():
if counter[0] < frames_to_wait:
counter[0] += 1
else:
future.set_result(True)
async def next_update_present_async(frames_to_wait):
"""
Warms up the present thread because it takes long time to enable it the
first time. It enables it and waits `frames_to_wait` frames of present
thread. `next_update_async` doesn't work here because it's related to the
main thread.
"""
_app_window_factory = omni.appwindow.acquire_app_window_factory_interface()
_app_window = _app_window_factory.get_windows()[0]
_renderer = omni.kit.renderer.bind.acquire_renderer_interface()
_stream = _renderer.get_post_present_frame_buffer_event_stream(_app_window)
counter = [0]
f = asyncio.Future()
_subscription = _stream.create_subscription_to_push(
partial(_on_present, f, counter, frames_to_wait), 0, "omni.ui Test"
)
await f
await omni.kit.app.get_app().next_update_async()
class TestPresent(OmniUiTest):
"""
Testing how the present thread works and how main thread is synchronized to
the present thread.
"""
async def setup_fps_test(
self, set_main: float, set_present: float, expect_main: float, expect_present: float, threshold: float = 0.1
):
"""
Set environment and fps for present and main thread and runs the
rectangle test. Compares the computed FPS with the given values.
Threshold is the number FPS can be different from expected.
"""
window = await self.create_test_window()
# Save the environment
settings = carb.settings.get_settings()
buffer_enabled = settings.get(enabled_settings_path)
buffer_present_fps = settings.get(present_settings_path)
buffer_main_fps = settings.get(main_settings_path)
buffer_present_busy = settings.get(busy_present_settings_path)
buffer_main_busy = settings.get(busy_main_settings_path)
buffer_sync = settings.get(sync_settings_path)
buffer_global_sync = settings.get(global_sync_settings_path)
finalized = False
try:
# Modify the environment
settings.set(present_settings_path, set_present)
settings.set(main_settings_path, set_main)
settings.set(busy_present_settings_path, True)
settings.set(busy_main_settings_path, True)
settings.set(sync_settings_path, True)
settings.set(global_sync_settings_path, True)
settings.set(enabled_settings_path, True)
for _ in range(2):
await omni.kit.app.get_app().next_update_async()
await next_update_present_async(10)
fps_current, fps_main = await _moving_rect(
window, f"{set_main}-{set_present}-{expect_main}-{expect_present}"
)
await self.finalize_test_no_image()
finalized = True
for _ in range(2):
await omni.kit.app.get_app().next_update_async()
# Check the result
self.assertTrue(abs(1.0 - expect_present / fps_current) < threshold)
self.assertTrue(abs(1.0 - expect_main / fps_main) < threshold)
finally:
# Restore the environment
settings.set(present_settings_path, buffer_present_fps)
settings.set(main_settings_path, buffer_main_fps)
settings.set(busy_present_settings_path, buffer_present_busy)
settings.set(busy_main_settings_path, buffer_main_busy)
settings.set(sync_settings_path, buffer_sync)
settings.set(global_sync_settings_path, buffer_global_sync)
settings.set(enabled_settings_path, buffer_enabled)
settings.set(dump_settings_path, "")
settings.set(color_settings_path, "")
if not finalized:
await self.finalize_test_no_image()
async def test_general_30_30(self):
# Set main 30; present: 30
# Expect after sync: main 30; present: 30
await self.setup_fps_test(30.0, 30.0, 30.0, 30.0)
async def test_general_60_30(self):
# Set main 60; present: 30
# Expect after sync: main 60; present: 30
await self.setup_fps_test(60.0, 30.0, 60.0, 30.0)
async def test_general_40_30(self):
# Set main 40; present: 30
# Expect after sync: main 60; present: 30
await self.setup_fps_test(40.0, 30.0, 30.0, 30.0)
async def test_general_20_30(self):
# Set main 20; present: 30
# Expect after sync: main 30; present: 30
await self.setup_fps_test(20.0, 30.0, 15.0, 30.0)
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_shadows.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
__all__ = ["TestShadows"]
import omni.kit.test
from .test_base import OmniUiTest
import omni.ui as ui
from omni.ui import color as cl
class TestShadows(OmniUiTest):
"""Testing shadow for ui.Shape"""
async def test_rectangle(self):
"""Testing rectangle shadow"""
window = await self.create_test_window()
with window.frame:
with ui.HStack():
ui.Spacer()
with ui.VStack():
ui.Spacer()
ui.Rectangle(
width=100,
height=100,
style={
"background_color": cl.transparent,
"shadow_flag": 1, "shadow_color": cl.blue,
"shadow_thickness": 20,
"shadow_offset_x": 3,
"shadow_offset_y": 3,
"border_width": 0,
"border_color": 0x22FFFF00,
"border_radius": 20,
"corner_flag": ui.CornerFlag.RIGHT})
ui.Spacer()
ui.Spacer()
await self.finalize_test()
async def test_circle(self):
"""Testing circle shadow"""
window = await self.create_test_window()
with window.frame:
with ui.HStack():
ui.Spacer()
with ui.VStack():
ui.Spacer()
ui.Circle(
width=60,
height=70,
alignment=ui.Alignment.RIGHT_BOTTOM,
style={
"background_color": cl.yellow,
"shadow_color": cl.blue,
"shadow_thickness": 20,
"shadow_offset_x": 6,
"shadow_offset_y": -6,
"border_width": 20,
"border_color": cl.blue})
ui.Spacer()
ui.Spacer()
await self.finalize_test()
async def test_triangle(self):
"""Testing triangle shadow"""
window = await self.create_test_window()
with window.frame:
with ui.HStack():
ui.Spacer()
with ui.VStack():
ui.Spacer()
ui.Triangle(
width=100,
height=80,
alignment=ui.Alignment.RIGHT_TOP,
style={
"background_color": cl.red,
"shadow_color": cl.blue,
"shadow_thickness": 10,
"shadow_offset_x": -8,
"shadow_offset_y": 5})
ui.Spacer()
ui.Spacer()
await self.finalize_test()
async def test_line(self):
"""Testing line shadow"""
window = await self.create_test_window()
with window.frame:
with ui.HStack():
ui.Spacer()
with ui.VStack():
ui.Spacer()
ui.Line(
alignment=ui.Alignment.LEFT,
style={
"color": cl.red,
"shadow_color": cl.green,
"shadow_thickness": 15,
"shadow_offset_x": 3,
"shadow_offset_y": 3,
"border_width": 10})
ui.Spacer()
ui.Spacer()
await self.finalize_test()
async def test_ellipse(self):
"""Testing ellipse shadow"""
window = await self.create_test_window()
with window.frame:
with ui.HStack():
ui.Spacer(width=15)
with ui.VStack():
ui.Spacer(height=35)
ui.Ellipse(
style={
"background_color": cl.green,
"shadow_color": cl.red,
"shadow_thickness": 20,
"shadow_offset_x": 5,
"shadow_offset_y": -5,
"border_width": 5,
"border_color": cl.blue})
ui.Spacer(height=35)
ui.Spacer(width=15)
await self.finalize_test()
async def test_freeshape(self):
"""Testing freeshap with shadow"""
window = await self.create_test_window()
with window.frame:
with ui.ZStack():
# Four draggable rectangles that represent the control points
with ui.Placer(draggable=True, offset_x=0, offset_y=0):
control1 = ui.Circle(width=10, height=10)
with ui.Placer(draggable=True, offset_x=150, offset_y=150):
control2 = ui.Circle(width=10, height=10)
# The rectangle that fits to the control points
ui.FreeRectangle(
control1,
control2,
style={
"background_color": cl(0.6),
"border_color": cl(0.1),
"border_width": 1.0,
"border_radius": 8.0,
"shadow_color": cl.red,
"shadow_thickness": 20,
"shadow_offset_x": 5,
"shadow_offset_y": 5})
await self.finalize_test()
async def test_buttons(self):
"""Testing button with shadow"""
window = await self.create_test_window()
with window.frame:
with ui.VStack(spacing=10):
ui.Button(
"One",
height=30,
style={
"shadow_flag": 1,
"shadow_color": cl.blue,
"shadow_thickness": 13,
"shadow_offset_x": 3,
"shadow_offset_y": 3,
"border_width": 3,
"border_color": cl.green,
"border_radius": 3})
ui.Button(
"Two",
height=30,
style={
"shadow_flag": 1,
"shadow_color": cl.red,
"shadow_thickness": 10,
"shadow_offset_x": 2,
"shadow_offset_y": 2,
"border_radius": 3})
ui.Button(
"Three",
height=30,
style={
"shadow_flag": 1,
"shadow_color": cl.green,
"shadow_thickness": 5,
"shadow_offset_x": 4,
"shadow_offset_y": 4})
await self.finalize_test()
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_label.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from .test_base import OmniUiTest
import omni.kit.app
import omni.ui as ui
class TestLabel(OmniUiTest):
"""Testing ui.Label"""
async def test_general(self):
"""Testing general properties of ui.Label"""
window = await self.create_test_window()
with window.frame:
with ui.VStack(height=0):
# Simple text
ui.Label("Hello world")
# Word wrap
ui.Label(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut "
"labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco "
"laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in "
"voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat "
"non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
word_wrap=True,
)
# Computing text size
with ui.HStack(width=0):
ui.Label("A")
ui.Label("BC")
ui.Label("DEF")
ui.Label("GHIjk")
ui.Label("lmnopq")
ui.Label("rstuvwxyz")
# Styling
ui.Label("Red", style={"color": 0xFF0000FF})
ui.Label("Green", style={"Label": {"color": 0xFF00FF00}})
ui.Label("Blue", style_type_name_override="TreeView", style={"TreeView": {"color": 0xFFFF0000}})
await self.finalize_test()
async def test_alignment(self):
"""Testing alignment of ui.Label"""
window = await self.create_test_window()
with window.frame:
with ui.ZStack():
ui.Label("Left Top", alignment=ui.Alignment.LEFT_TOP)
ui.Label("Center Top", alignment=ui.Alignment.CENTER_TOP)
ui.Label("Right Top", alignment=ui.Alignment.RIGHT_TOP)
ui.Label("Left Center", alignment=ui.Alignment.LEFT_CENTER)
ui.Label("Center", alignment=ui.Alignment.CENTER)
ui.Label("Right Center", alignment=ui.Alignment.RIGHT_CENTER)
ui.Label("Left Bottom", alignment=ui.Alignment.LEFT_BOTTOM)
ui.Label("Center Bottom", alignment=ui.Alignment.CENTER_BOTTOM)
ui.Label("Right Bottom", alignment=ui.Alignment.RIGHT_BOTTOM)
await self.finalize_test()
async def test_wrap_alignment(self):
"""Testing alignment of ui.Label with word_wrap"""
window = await self.create_test_window()
with window.frame:
ui.Label(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut "
"labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco "
"laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in "
"voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat "
"non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
word_wrap=True,
style={"Label": {"alignment": ui.Alignment.CENTER}},
)
await self.finalize_test()
async def test_elide(self):
"""Testing ui.Label with elided_text"""
window = await self.create_test_window()
with window.frame:
with ui.VStack():
ui.Label(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut "
"labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco "
"laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in "
"voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat "
"non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
elided_text=True,
height=0,
)
ui.Label(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut "
"labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco "
"laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in "
"voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat "
"non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
word_wrap=True,
elided_text=True,
)
ui.Label(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut "
"labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco "
"laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in "
"voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat "
"non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
alignment=ui.Alignment.CENTER,
word_wrap=True,
elided_text=True,
)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_change_size(self):
"""Testing how ui.Label dynamically changes size"""
window = await self.create_test_window()
with window.frame:
with ui.VStack(style={"Rectangle": {"background_color": 0xFFFFFFFF}}):
with ui.HStack(height=0):
with ui.Frame(width=0):
line1 = ui.Label("Test")
ui.Rectangle()
with ui.HStack(height=0):
with ui.Frame(width=0):
line2 = ui.Label("Test")
ui.Rectangle()
with ui.Frame(height=0):
line3 = ui.Label("Test", word_wrap=True)
ui.Rectangle()
for i in range(2):
await omni.kit.app.get_app().next_update_async()
# Change the text
line1.text = "Bigger than before"
line2.text = "a"
line3.text = (
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut "
"labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco "
"laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in "
"voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat "
"non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_font(self):
window = await self.create_test_window()
with window.frame:
ui.Label(
"The quick brown fox jumps over the lazy dog",
style={"font_size": 55, "font": "${fonts}/OpenSans-SemiBold.ttf", "alignment": ui.Alignment.CENTER},
word_wrap=True,
)
await self.finalize_test()
async def test_invalid_font(self):
window = await self.create_test_window()
with window.frame:
ui.Label(
"The quick brown fox jumps over the lazy dog",
style={"font_size": 55, "font": "${fonts}/IDoNotExist.ttf", "alignment": ui.Alignment.CENTER},
word_wrap=True,
)
await self.finalize_test()
async def test_mouse_released_fn(self):
"""Test mouse_released_fn only triggers on widget which was pressed"""
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
release_count = [0, 0]
def release(i):
release_count[i] += 1
with window.frame:
with ui.VStack():
label1 = ui.Label("1", mouse_released_fn=lambda *_: release(0))
label2 = ui.Label("2", mouse_released_fn=lambda *_: release(1))
try:
await omni.kit.app.get_app().next_update_async()
refLabel1 = ui_test.WidgetRef(label1, "")
refLabel2 = ui_test.WidgetRef(label2, "")
await omni.kit.app.get_app().next_update_async()
# Left button
await ui_test.emulate_mouse_drag_and_drop(refLabel1.center, refLabel2.center)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(release_count[0], 1)
self.assertEqual(release_count[1], 0)
# Right button
release_count = [0, 0]
await ui_test.emulate_mouse_drag_and_drop(refLabel1.center, refLabel2.center, right_click=True)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(release_count[0], 1)
self.assertEqual(release_count[1], 0)
finally:
await self.finalize_test_no_image()
async def test_exact_content_size(self):
"""Test the exact content width/height properties"""
CHAR_WIDTH = 7
CHAR_HEIGHT = 14
window = await self.create_test_window()
with window.frame:
with ui.VStack(height=0):
with ui.HStack():
label1 = ui.Label("1")
label10 = ui.Label("10")
label1234 = ui.Label("1234")
label_wrap = ui.Label(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut "
"labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco "
"laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in "
"voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat "
"non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
word_wrap=True,
)
label_elided = ui.Label(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut "
"labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco "
"laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in "
"voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat "
"non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
elided_text=True,
)
await omni.kit.app.get_app().next_update_async()
# Verify width of text
self.assertEqual(label1.exact_content_width, CHAR_WIDTH)
self.assertEqual(label10.exact_content_width, CHAR_WIDTH*2)
self.assertEqual(label1234.exact_content_width, CHAR_WIDTH*4)
self.assertEqual(label_wrap.exact_content_width, CHAR_WIDTH*35)
self.assertAlmostEqual(label_elided.computed_content_width, 248.0, 3)
# Verify height
self.assertEqual(label1.exact_content_height, CHAR_HEIGHT)
self.assertEqual(label10.exact_content_height, CHAR_HEIGHT)
self.assertEqual(label1234.exact_content_height, CHAR_HEIGHT)
self.assertEqual(label_wrap.exact_content_height, CHAR_HEIGHT*11)
self.assertEqual(label_elided.exact_content_height, CHAR_HEIGHT)
# Change the text
label1.text = "12345"
await omni.kit.app.get_app().next_update_async()
self.assertEqual(label1.exact_content_width, CHAR_WIDTH*5)
self.assertEqual(label1.exact_content_height, CHAR_HEIGHT)
# Change text (no word wrap), should just resize the label
label10.text = (
"1234567890"
"1234567890"
"1234567890"
)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(label10.exact_content_width, CHAR_WIDTH*30)
self.assertEqual(label10.exact_content_height, CHAR_HEIGHT)
await self.finalize_test_no_image()
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_raster.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from functools import partial
from .test_base import OmniUiTest
import omni.ui as ui
import omni.kit.app
class TestRaster(OmniUiTest):
"""Testing ui.Frame"""
async def test_general(self):
import omni.kit.ui_test as ui_test
from carb.input import MouseEventType
window = await self.create_test_window(block_devices=False)
with window.frame:
with ui.HStack():
left_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
right_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
with left_frame:
ui.Rectangle(style={"background_color": ui.color.grey})
with right_frame:
ui.Rectangle(style={"background_color": ui.color.grey})
left_frame_ref = ui_test.WidgetRef(left_frame, "")
right_frame_ref = ui_test.WidgetRef(right_frame, "")
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse_move(right_frame_ref.center)
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse_move(left_frame_ref.center)
await ui_test.input.wait_n_updates_internal()
await self.finalize_test()
async def test_edit(self):
import omni.kit.ui_test as ui_test
from carb.input import MouseEventType
window = await self.create_test_window(block_devices=False)
with window.frame:
with ui.HStack():
left_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
right_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
with left_frame:
ui.Rectangle(style={"background_color": ui.color.grey})
with right_frame:
with ui.ZStack():
ui.Rectangle(style={"background_color": ui.color.grey})
with ui.VStack():
ui.Spacer()
field = ui.StringField(height=0)
ui.Spacer()
left_frame_ref = ui_test.WidgetRef(left_frame, "")
field_ref = ui_test.WidgetRef(field, "")
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse_move_and_click(field_ref.center)
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse_move(left_frame_ref.center)
await ui_test.input.wait_n_updates_internal()
await self.finalize_test()
async def test_dnd(self):
import omni.kit.ui_test as ui_test
from carb.input import MouseEventType
window = await self.create_test_window(
block_devices=False,
window_flags=ui.WINDOW_FLAGS_NO_SCROLLBAR
| ui.WINDOW_FLAGS_NO_TITLE_BAR
| ui.WINDOW_FLAGS_NO_RESIZE
| ui.WINDOW_FLAGS_NO_MOVE,
)
with window.frame:
with ui.HStack():
left_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
right_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
with left_frame:
ui.Rectangle(style={"background_color": ui.color.grey})
with right_frame:
ui.Rectangle(style={"background_color": ui.color.grey})
left_frame_ref = ui_test.WidgetRef(left_frame, "")
right_frame_ref = ui_test.WidgetRef(right_frame, "")
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse(MouseEventType.MOVE, left_frame_ref.center)
await ui_test.input.emulate_mouse(MouseEventType.LEFT_BUTTON_DOWN)
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse_slow_move(left_frame_ref.center, right_frame_ref.center)
await self.finalize_test()
await ui_test.input.emulate_mouse(MouseEventType.LEFT_BUTTON_UP)
async def test_update(self):
import omni.kit.ui_test as ui_test
from carb.input import MouseEventType
window = await self.create_test_window(block_devices=False)
with window.frame:
with ui.HStack():
left_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
right_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
with left_frame:
ui.Rectangle(style={"background_color": ui.color.grey})
with right_frame:
ui.Rectangle(style={"background_color": ui.color.grey})
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse_move(ui_test.input.Vec2(0, 0))
with right_frame:
ui.Rectangle(style={"background_color": ui.color.beige})
await ui_test.input.wait_n_updates_internal(update_count=4)
await self.finalize_test()
async def test_model(self):
import omni.kit.ui_test as ui_test
from carb.input import MouseEventType
window = await self.create_test_window(block_devices=False)
with window.frame:
with ui.HStack():
left_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
right_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
with left_frame:
ui.Rectangle(style={"background_color": ui.color.grey})
with right_frame:
with ui.ZStack():
ui.Rectangle(style={"background_color": ui.color.grey})
with ui.VStack():
ui.Spacer()
field = ui.StringField(height=0)
ui.Spacer()
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse_move(ui_test.input.Vec2(0, 0))
field.model.as_string = "NVIDIA"
await ui_test.input.wait_n_updates_internal(update_count=4)
await self.finalize_test()
async def test_on_demand(self):
import omni.kit.ui_test as ui_test
from carb.input import MouseEventType
window = await self.create_test_window(block_devices=False)
with window.frame:
with ui.HStack():
right_frame = ui.Frame(raster_policy=ui.RasterPolicy.ON_DEMAND)
with right_frame:
with ui.ZStack():
ui.Rectangle(style={"background_color": ui.color.grey})
with ui.VStack():
ui.Spacer()
field = ui.StringField(height=0)
ui.Spacer()
right_frame_ref = ui_test.WidgetRef(right_frame, "")
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse_move(right_frame_ref.center)
field.model.as_string = "NVIDIA"
await ui_test.input.wait_n_updates_internal(update_count=4)
await self.finalize_test()
async def test_on_demand_invalidate(self):
import omni.kit.ui_test as ui_test
from carb.input import MouseEventType
window = await self.create_test_window(block_devices=False)
with window.frame:
with ui.HStack():
right_frame = ui.Frame(raster_policy=ui.RasterPolicy.ON_DEMAND)
with right_frame:
with ui.ZStack():
ui.Rectangle(style={"background_color": ui.color.grey})
with ui.VStack():
ui.Spacer()
field = ui.StringField(height=0)
ui.Spacer()
right_frame_ref = ui_test.WidgetRef(right_frame, "")
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse_move(right_frame_ref.center)
field.model.as_string = "NVIDIA"
await ui_test.input.wait_n_updates_internal(update_count=4)
right_frame.invalidate_raster()
await ui_test.input.wait_n_updates_internal(update_count=4)
await self.finalize_test()
async def test_child_window(self):
"""Testing rasterization when mouse hovers child window"""
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
small_window = ui.Window("small", width=100, height=100, position_x=0, position_y=0)
with small_window.frame:
with ui.VStack():
with ui.Frame(raster_policy=ui.RasterPolicy.AUTO):
with ui.VStack():
ui.Label("NVIDIA")
with ui.Frame(raster_policy=ui.RasterPolicy.AUTO):
with ui.VStack():
ui.Spacer()
combo = ui.ComboBox(1, "one", "two", "three", "four", height=0)
await ui_test.input.wait_n_updates_internal(update_count=2)
# Clicking the combo box in the small window
combo_ref = ui_test.WidgetRef(combo, "")
await ui_test.input.emulate_mouse_move_and_click(combo_ref.center)
await ui_test.input.wait_n_updates_internal(update_count=2)
# Moving the mouse over the combo box and outside the window
await ui_test.input.emulate_mouse_move(ui_test.input.Vec2(combo_ref.center.x, combo_ref.center.y + 80))
await ui_test.input.wait_n_updates_internal(update_count=6)
await self.finalize_test()
async def test_label(self):
import omni.kit.ui_test as ui_test
window = await self.create_test_window()
with window.frame:
with ui.HStack():
left_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
right_frame = ui.Frame(raster_policy=ui.RasterPolicy.AUTO)
with left_frame:
l = ui.Label("Left")
with right_frame:
r = ui.Label("Right")
await ui_test.input.wait_n_updates_internal()
l.text = "NVIDIA"
r.text = "Omniverse"
await ui_test.input.wait_n_updates_internal(update_count=4)
await self.finalize_test()
async def test_canvasframe_lod(self):
import omni.kit.ui_test as ui_test
window = await self.create_test_window()
with window.frame:
with ui.Frame(raster_policy=ui.RasterPolicy.AUTO):
canvas = ui.CanvasFrame()
with canvas:
with ui.ZStack():
p1 = ui.Placer(stable_size=1, draggable=1)
with p1:
with ui.Frame(raster_policy=ui.RasterPolicy.AUTO):
ui.Rectangle(style={"background_color": ui.color.blue}, visible_min=0.5)
p2 = ui.Placer(stable_size=1, draggable=1)
with p2:
with ui.Frame(raster_policy=ui.RasterPolicy.AUTO):
ui.Rectangle(style={"background_color": ui.color.green}, visible_max=0.5)
await ui_test.input.wait_n_updates_internal(update_count=4)
canvas.zoom = 0.25
await ui_test.input.wait_n_updates_internal(update_count=4)
canvas.zoom = 1.0
await ui_test.input.wait_n_updates_internal(update_count=4)
p2.offset_x = 300
p2.offset_y = 300
await ui_test.input.wait_n_updates_internal(update_count=4)
canvas.zoom = 0.25
await ui_test.input.wait_n_updates_internal(update_count=4)
await self.finalize_test()
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_placer.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from .test_base import OmniUiTest
import omni.ui as ui
import omni.kit.app
RECT_SIZE = 10
RECT_STYLE = {"background_color": 0xFFFFFFFF}
RECT_TRANSPARENT_STYLE = {"background_color": 0x66FFFFFF, "border_color": 0xFFFFFFFF, "border_width": 1}
class TestPlacer(OmniUiTest):
"""Testing ui.Placer"""
async def test_general(self):
"""Testing general properties of ui.Placer"""
window = await self.create_test_window()
with window.frame:
with ui.ZStack():
with ui.Placer(offset_x=10, offset_y=10):
ui.Rectangle(width=RECT_SIZE, height=RECT_SIZE, style=RECT_STYLE)
with ui.Placer(offset_x=90, offset_y=10):
ui.Rectangle(width=RECT_SIZE, height=RECT_SIZE, style=RECT_STYLE)
with ui.Placer(offset_x=90, offset_y=90):
ui.Rectangle(width=RECT_SIZE, height=RECT_SIZE, style=RECT_STYLE)
with ui.Placer(offset_x=10, offset_y=90):
ui.Rectangle(width=RECT_SIZE, height=RECT_SIZE, style=RECT_STYLE)
await self.finalize_test()
async def test_percents(self):
"""Testing ability to offset in percents of ui.Placer"""
window = await self.create_test_window()
with window.frame:
with ui.ZStack():
with ui.Placer(offset_x=ui.Percent(10), offset_y=ui.Percent(10)):
ui.Rectangle(width=RECT_SIZE, height=RECT_SIZE, style=RECT_STYLE)
with ui.Placer(offset_x=ui.Percent(90), offset_y=ui.Percent(10)):
ui.Rectangle(width=RECT_SIZE, height=RECT_SIZE, style=RECT_STYLE)
with ui.Placer(offset_x=ui.Percent(90), offset_y=ui.Percent(90)):
ui.Rectangle(width=RECT_SIZE, height=RECT_SIZE, style=RECT_STYLE)
with ui.Placer(offset_x=ui.Percent(10), offset_y=ui.Percent(90)):
ui.Rectangle(width=RECT_SIZE, height=RECT_SIZE, style=RECT_STYLE)
await self.finalize_test()
async def test_child_percents(self):
"""Testing ability to offset in percents of ui.Placer"""
window = await self.create_test_window()
with window.frame:
with ui.ZStack():
with ui.Placer(offset_x=ui.Percent(10), offset_y=ui.Percent(10)):
ui.Rectangle(width=ui.Percent(80), height=ui.Percent(80), style=RECT_TRANSPARENT_STYLE)
with ui.Placer(offset_x=ui.Percent(50), offset_y=ui.Percent(50)):
ui.Rectangle(width=ui.Percent(50), height=ui.Percent(50), style=RECT_TRANSPARENT_STYLE)
await self.finalize_test()
async def test_resize(self):
window = await self.create_test_window()
with window.frame:
placer = ui.Placer(width=200)
with placer:
ui.Rectangle(height=100, style={"background_color": omni.ui.color.red})
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
placer.width = ui.Percent(5)
await self.finalize_test()
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_window.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from .test_base import OmniUiTest
import omni.ui as ui
import omni.kit.app
from functools import partial
import omni.kit.test
WINDOW_STYLE = {"Window": {"background_color": 0xFF303030, "border_color": 0x0, "border_width": 0, "border_radius": 0}}
MODAL_WINDOW_STYLE = {
"Window": {
"background_color": 0xFFFF0000,
"border_color": 0x0,
"border_width": 0,
"border_radius": 0,
"secondary_background_color": 0,
}
}
class TestWindow(OmniUiTest):
"""Testing ui.Window"""
async def test_general(self):
"""Testing general properties of ui.Windows"""
window = await self.create_test_window()
# Empty window
window1 = ui.Window(
"Test1", width=100, height=100, position_x=10, position_y=10, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR
)
window1.frame.set_style(WINDOW_STYLE)
# Window with Label
window2 = ui.Window(
"Test2", width=100, height=100, position_x=120, position_y=10, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR
)
window2.frame.set_style(WINDOW_STYLE)
with window2.frame:
ui.Label("Hello world")
# Window with layout
window3 = ui.Window(
"Test3", width=100, height=100, position_x=10, position_y=120, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR
)
window3.frame.set_style(WINDOW_STYLE)
with window3.frame:
with ui.VStack():
ui.Spacer()
with ui.HStack(height=0):
ui.Spacer()
ui.Label("Hello world", width=0)
await self.finalize_test()
async def test_imgui_visibility(self):
"""Testing general properties of ui.Windows"""
window = await self.create_test_window()
# Empty window
window1 = ui.Window("Test1", width=100, height=100, position_x=10, position_y=10)
window1.frame.set_style(WINDOW_STYLE)
await omni.kit.app.get_app().next_update_async()
# Remove window
window1 = None
await omni.kit.app.get_app().next_update_async()
# It's still at ImGui cache
window1 = ui.Workspace.get_window("Test1")
window1.visible = False
await omni.kit.app.get_app().next_update_async()
# Create another one
window1 = ui.Window("Test1", width=100, height=100, position_x=10, position_y=10)
window1.frame.set_style(WINDOW_STYLE)
with window1.frame:
ui.Label("Hello world")
await omni.kit.app.get_app().next_update_async()
# It should be visible
await self.finalize_test()
async def test_overlay(self):
"""Testing the ability to overlay of ui.Windows"""
window = await self.create_test_window()
# Creating to windows with the same title. It should be displayed as
# one window with the elements of both windows.
window1 = ui.Window("Test", width=100, height=100, position_x=10, position_y=10)
window1.frame.set_style(WINDOW_STYLE)
with window1.frame:
with ui.VStack():
ui.Label("Hello world", height=0)
window3 = ui.Window("Test")
window3.frame.set_style(WINDOW_STYLE)
with window3.frame:
with ui.VStack():
ui.Spacer()
ui.Label("Hello world", height=0)
await self.finalize_test()
async def test_popup1(self):
"""Testing WINDOW_FLAGS_POPUP"""
window = await self.create_test_window()
# General popup
window1 = ui.Window(
"test_popup1",
width=100,
height=100,
position_x=10,
position_y=10,
flags=ui.WINDOW_FLAGS_POPUP | ui.WINDOW_FLAGS_NO_TITLE_BAR,
)
window1.frame.set_style(WINDOW_STYLE)
with window1.frame:
with ui.VStack():
ui.Label("Hello world", height=0)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_popup2(self):
"""Testing WINDOW_FLAGS_POPUP"""
window = await self.create_test_window()
# Two popups
window1 = ui.Window(
"test_popup2_0",
width=100,
height=100,
position_x=10,
position_y=10,
flags=ui.WINDOW_FLAGS_POPUP | ui.WINDOW_FLAGS_NO_TITLE_BAR,
)
window1.frame.set_style(WINDOW_STYLE)
with window1.frame:
with ui.VStack():
ui.Label("Hello world", height=0)
# Wait one frame and create second window.
await omni.kit.app.get_app().next_update_async()
window2 = ui.Window(
"test_popup2_1",
position_x=10,
position_y=10,
auto_resize=True,
flags=ui.WINDOW_FLAGS_POPUP | ui.WINDOW_FLAGS_NO_TITLE_BAR,
)
window2.frame.set_style(WINDOW_STYLE)
with window2.frame:
with ui.VStack():
ui.Label("Second popup", height=0)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_popup3(self):
"""Testing WINDOW_FLAGS_POPUP"""
window = await self.create_test_window()
with window.frame:
with ui.VStack():
field = ui.StringField(style={"background_color": 0x0})
field.model.set_value("This is StringField")
# General popup
window1 = ui.Window(
"test_popup3",
width=100,
height=100,
position_x=10,
position_y=10,
flags=ui.WINDOW_FLAGS_POPUP | ui.WINDOW_FLAGS_NO_TITLE_BAR,
)
window1.frame.set_style(WINDOW_STYLE)
with window1.frame:
with ui.VStack():
ui.Label("Hello world", height=0)
# Wait one frame and focus field
await omni.kit.app.get_app().next_update_async()
field.focus_keyboard()
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_modal1(self):
"""Testing WINDOW_FLAGS_MODAL"""
window = await self.create_test_window()
# General popup
window1 = ui.Window(
"test_modal1",
width=100,
height=100,
position_x=10,
position_y=10,
flags=ui.WINDOW_FLAGS_MODAL | ui.WINDOW_FLAGS_NO_TITLE_BAR,
)
window1.frame.set_style(WINDOW_STYLE)
with window1.frame:
with ui.VStack():
ui.Label("Hello world", height=0)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_modal2(self):
"""Testing WINDOW_FLAGS_MODAL with transparent dim background"""
window = await self.create_test_window()
# General popup
window1 = ui.Window(
"test_modal2",
width=100,
height=100,
position_x=10,
position_y=10,
flags=ui.WINDOW_FLAGS_MODAL | ui.WINDOW_FLAGS_NO_TITLE_BAR,
)
window1.frame.set_style(MODAL_WINDOW_STYLE)
with window1.frame:
with ui.VStack():
ui.Label("Hello world", height=0)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_menubar(self):
"""Testing general properties of ui.MenuBar"""
window = await self.create_test_window()
# Empty window
window1 = ui.Window(
"Test1",
width=100,
height=100,
position_x=10,
position_y=10,
flags=ui.WINDOW_FLAGS_MENU_BAR | ui.WINDOW_FLAGS_NO_SCROLLBAR,
)
window1.frame.set_style(WINDOW_STYLE)
with window1.menu_bar:
with ui.Menu("File"):
ui.MenuItem("Open")
with window1.frame:
ui.Label("Hello world")
# Window with Label
window2 = ui.Window(
"Test2",
width=100,
height=100,
position_x=120,
position_y=10,
flags=ui.WINDOW_FLAGS_MENU_BAR | ui.WINDOW_FLAGS_NO_SCROLLBAR,
)
window2.frame.set_style(WINDOW_STYLE)
window2.menu_bar.style = {"MenuBar": {"background_color": 0xFFEDB51A}}
with window2.menu_bar:
with ui.Menu("File"):
ui.MenuItem("Open")
with window2.frame:
ui.Label("Hello world")
# Window with layout
window3 = ui.Window(
"Test3",
width=100,
height=100,
position_x=10,
position_y=120,
flags=ui.WINDOW_FLAGS_MENU_BAR | ui.WINDOW_FLAGS_NO_SCROLLBAR,
)
window3.frame.style = {**WINDOW_STYLE, **{"Window": {"background_color": 0xFFEDB51A}}}
with window3.menu_bar:
with ui.Menu("File"):
ui.MenuItem("Open")
with window3.frame:
ui.Label("Hello world")
await self.finalize_test()
async def test_docked(self):
ui_main_window = ui.MainWindow()
win = ui.Window("first", width=100, height=100)
await omni.kit.app.get_app().next_update_async()
self.assertFalse(win.docked)
main_dockspace = ui.Workspace.get_window("DockSpace")
win.dock_in(main_dockspace, ui.DockPosition.SAME)
await omni.kit.app.get_app().next_update_async()
self.assertTrue(win.docked)
async def test_is_selected_in_dock(self):
ui_main_window = ui.MainWindow()
window1 = ui.Window("First", width=100, height=100)
window2 = ui.Window("Second", width=100, height=100)
window3 = ui.Window("Thrid", width=100, height=100)
await omni.kit.app.get_app().next_update_async()
main_dockspace = ui.Workspace.get_window("DockSpace")
window1.dock_in(main_dockspace, ui.DockPosition.SAME)
window2.dock_in(main_dockspace, ui.DockPosition.SAME)
window3.dock_in(main_dockspace, ui.DockPosition.SAME)
await omni.kit.app.get_app().next_update_async()
window2.focus()
await omni.kit.app.get_app().next_update_async()
self.assertFalse(window1.is_selected_in_dock())
self.assertTrue(window2.is_selected_in_dock())
self.assertFalse(window3.is_selected_in_dock())
async def test_mainwindow_resize(self):
"""Testing resizing of mainwindow"""
await self.create_test_area(128, 128)
main_window = ui.MainWindow()
main_window.main_menu_bar.clear()
main_window.main_menu_bar.visible = True
main_window.main_menu_bar.menu_compatibility = False
with main_window.main_menu_bar:
with ui.Menu("NVIDIA"):
ui.MenuItem("Item 1")
ui.MenuItem("Item 2")
ui.MenuItem("Item 3")
ui.Spacer()
with ui.Menu("Omniverse"):
ui.MenuItem("Item 1")
ui.MenuItem("Item 2")
ui.MenuItem("Item 3")
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
main_dockspace = ui.Workspace.get_window("DockSpace")
window1 = ui.Window("Viewport")
with window1.frame:
ui.Label("Window", alignment=ui.Alignment.CENTER)
await omni.kit.app.get_app().next_update_async()
window1.dock_in(main_dockspace, ui.DockPosition.SAME)
await omni.kit.app.get_app().next_update_async()
window1.dock_tab_bar_enabled = False
app_window = omni.appwindow.get_default_app_window()
app_window.resize(256, 128)
for i in range(2):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
main_window = None
window1.dock_tab_bar_enabled = True # Turn back on for other tests
for i in range(2):
await omni.kit.app.get_app().next_update_async()
class WindowCallbacks(OmniUiTest):
def _focus_callback(self, state_dict, name, focus_state: bool) -> None:
state_dict[name] = focus_state
async def test_window_focus_callback(self):
"""test window focus callback"""
focus_values = {}
window1 = ui.Window("First", width=100, height=100)
window1.set_focused_changed_fn(partial(self._focus_callback, focus_values, "window1"))
window2 = ui.Window("Second", width=100, height=100)
window1.set_focused_changed_fn(partial(self._focus_callback, focus_values, "window2"))
await omni.kit.app.get_app().next_update_async()
#Looks like setting focus on 1 window doesn't set if off on the others?
window1.focus()
self.assertTrue(focus_values['window1']==True)
await omni.kit.app.get_app().next_update_async()
window2.focus()
self.assertTrue(focus_values['window2']==True)
async def __test_window_focus_policy(self, focus_policy: ui.FocusPolicy, mouse_event: str, focus_changes: bool = True):
import omni.kit.ui_test as ui_test
from carb.input import MouseEventType
width, height = 100, 100
start_pos = ui_test.Vec2(width, height)
window0_center = ui_test.Vec2(width/2, height/2)
window1_center = window0_center + ui_test.Vec2(width, 0)
mouse_types = {
"left": (MouseEventType.LEFT_BUTTON_DOWN, MouseEventType.LEFT_BUTTON_UP),
"middle": (MouseEventType.MIDDLE_BUTTON_DOWN, MouseEventType.MIDDLE_BUTTON_UP),
"right": (MouseEventType.RIGHT_BUTTON_DOWN, MouseEventType.RIGHT_BUTTON_UP),
}.get(mouse_event)
# Get the list of expected eulsts based on FocusPolicy
if focus_changes:
if focus_policy != ui.FocusPolicy.FOCUS_ON_HOVER:
focus_tests = [
(False, True), # Initial state
(False, True), # After mouse move to window 0
(False, True), # After mouse move to window 1
(True, False), # After mouse click in window 0
(False, True), # After mouse click in window 1
]
else:
focus_tests = [
(False, True), # Initial state
(True, False), # After mouse move to window 0
(False, True), # After mouse move to window 1
(True, False), # After mouse click in window 0
(False, True), # After mouse click in window 1
]
else:
# Default focus test that never changes focus
focus_tests = [
(False, True), # Initial state
(False, True), # After mouse move to window 0
(False, True), # After mouse move to window 1
(False, True), # After mouse click in window 0
(False, True), # After mouse click in window 1
]
await self.create_test_area(width*2, height, block_devices=False)
window0 = ui.Window("0", width=width, height=height, position_y=0, position_x=0)
window1 = ui.Window("1", width=width, height=height, position_y=0, position_x=width)
# Test initial focus state
if focus_policy != ui.FocusPolicy.DEFAULT:
self.assertNotEqual(window0.focus_policy, focus_policy)
window0.focus_policy = focus_policy
self.assertNotEqual(window1.focus_policy, focus_policy)
window1.focus_policy = focus_policy
self.assertEqual(window0.focus_policy, focus_policy)
self.assertEqual(window1.focus_policy, focus_policy)
# Test the individual focus state and move to next state test
focus_test_idx = 0
async def test_focused_windows():
nonlocal focus_test_idx
expected_focus_state = focus_tests[focus_test_idx]
focus_test_idx = focus_test_idx + 1
window0_focused, window1_focused = window0.focused, window1.focused
expected_window0_focus, expected_window1_focus = expected_focus_state[0], expected_focus_state[1]
# Build a more specifc failure message
fail_msg = f"Testing {focus_policy} with mouse '{mouse_event}' (focus_test_idx: {focus_test_idx-1})"
fail_msg_0 = f"{fail_msg}: Window 0 expected focus: {expected_window0_focus}, had focus {window0_focused}."
fail_msg_1 = f"{fail_msg}: Window 1 expected focus: {expected_window1_focus}, had focus {window1_focused}."
self.assertEqual(expected_window0_focus, window0_focused, msg=fail_msg_0)
self.assertEqual(expected_window1_focus, window1_focused, msg=fail_msg_1)
# Move mouse
await ui_test.input.emulate_mouse_move(start_pos)
# Test the current focus state
await test_focused_windows()
# Move mouse
await ui_test.input.emulate_mouse_move(window0_center)
# Test the current focus state on both windows
await test_focused_windows()
# Move mouse
await ui_test.input.emulate_mouse_move(window1_center)
# Test the current focus state on both windows
await test_focused_windows()
# Move mouse to Window 0
await ui_test.emulate_mouse_move(window0_center)
# Do mouse click: down and up event
await ui_test.input.emulate_mouse(mouse_types[0])
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse(mouse_types[1])
await ui_test.input.wait_n_updates_internal()
# Test the current focus state on both windows
await test_focused_windows()
# Move mouse to Window 1
await ui_test.emulate_mouse_move(window1_center)
# Do mouse click: down and up event
await ui_test.input.emulate_mouse(mouse_types[0])
await ui_test.input.wait_n_updates_internal()
await ui_test.input.emulate_mouse(mouse_types[1])
await ui_test.input.wait_n_updates_internal()
# Test the current focus state on both windows
await test_focused_windows()
async def test_window_focus_policy_left_mouse(self):
"""test Window focus policy based on mouse events on left click"""
# Left click should change focus
await self.__test_window_focus_policy(ui.FocusPolicy.FOCUS_ON_LEFT_MOUSE_DOWN, "left")
# Middle click should not change focus
await self.__test_window_focus_policy(ui.FocusPolicy.FOCUS_ON_LEFT_MOUSE_DOWN, "middle", False)
# Right click should not change focus
await self.__test_window_focus_policy(ui.FocusPolicy.FOCUS_ON_LEFT_MOUSE_DOWN, "right", False)
async def test_window_focus_policy_any_mouse(self):
"""test Window focus policy based on mouse events on any click"""
# Left click should change focus
await self.__test_window_focus_policy(ui.FocusPolicy.FOCUS_ON_ANY_MOUSE_DOWN, "left")
# Middle click should change focus
await self.__test_window_focus_policy(ui.FocusPolicy.FOCUS_ON_ANY_MOUSE_DOWN, "middle")
# Right click should change focus
await self.__test_window_focus_policy(ui.FocusPolicy.FOCUS_ON_ANY_MOUSE_DOWN, "right")
async def test_window_focus_policy_hover_mouse(self):
"""test Window focus policy based on mouse events hover"""
# Left click should change focus
await self.__test_window_focus_policy(ui.FocusPolicy.FOCUS_ON_HOVER, "left")
# Middle click should not change focus
await self.__test_window_focus_policy(ui.FocusPolicy.FOCUS_ON_HOVER, "middle")
# Right click should not change focus
await self.__test_window_focus_policy(ui.FocusPolicy.FOCUS_ON_HOVER, "right")
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_image.py | ## Copyright (c) 2019-2021, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from .test_base import OmniUiTest
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from functools import partial
from pathlib import Path
import asyncio
import carb
import omni.kit.app
import omni.ui as ui
import os
import unittest
CURRENT_PATH = Path(__file__).parent
DATA_PATH = CURRENT_PATH.parent.parent.parent.joinpath("data")
class TestImage(OmniUiTest):
"""Testing ui.Image"""
async def test_general(self):
"""Testing general properties of ui.Image"""
window = await self.create_test_window()
f = asyncio.Future()
def on_image_progress(future: asyncio.Future, progress):
if progress >= 1:
if not future.done():
future.set_result(None)
with window.frame:
ui.Image(f"{DATA_PATH}/tests/red.png", progress_changed_fn=partial(on_image_progress, f))
# Wait the image to be loaded
await f
await self.finalize_test()
async def test_broken_svg(self):
"""Testing ui.Image doesn't crash when the image is broken."""
window = await self.create_test_window()
def build():
ui.Image(f"{DATA_PATH}/tests/broken.svg")
window.frame.set_build_fn(build)
# Call build
await omni.kit.app.get_app().next_update_async()
# Attempts to load the broken file. The error message is "Failed to load the texture:"
await omni.kit.app.get_app().next_update_async()
# Recall build
window.frame.rebuild()
await omni.kit.app.get_app().next_update_async()
# Second attempt to load the broken file. Second error message is expected.
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_imagewithprovider(self):
# Because PIL works differently in Windows and Liniux.
# TODO: Use something else for the rasterization of the text
return
"""Testing ui.Image doesn't crash when the image is broken."""
window = await self.create_test_window()
image_width = 256
image_height = 256
upscale = 2
black = (0, 0, 0, 255)
white = (255, 255, 255, 255)
font_path = os.path.normpath(
carb.tokens.get_tokens_interface().resolve("${kit}/resources/fonts/roboto_medium.ttf")
)
font_size = 25
font = ImageFont.truetype(font_path, font_size)
image = Image.new("RGBA", (image_width * upscale, image_height * upscale), white)
draw = ImageDraw.Draw(image)
# draw.fontmode = "RGB"
draw.text(
(0, image_height),
"The quick brown fox jumps over the lazy dog",
fill=black,
font=font,
)
# Convert image to Image Provider
pixels = [int(c) for p in image.getdata() for c in p]
image_provider = ui.ByteImageProvider()
image_provider.set_bytes_data(pixels, [image_width * upscale, image_height * upscale])
with window.frame:
with ui.HStack():
ui.Spacer(width=0.5)
ui.ImageWithProvider(
image_provider,
fill_policy=ui.IwpFillPolicy.IWP_STRETCH,
width=image_width,
height=image_height,
pixel_aligned=True,
)
# Second attempt to load the broken file. Second error message is expected.
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_imagewithprovider_with_no_valid_style(self):
"""This is to test ImageWithProvider is not crash when style is not defined and image_url is not defined"""
window = await self.create_test_window()
with window.frame:
ui.ImageWithProvider(
height=200,
width=200,
fill_policy=ui.IwpFillPolicy.IWP_PRESERVE_ASPECT_FIT,
style_type_name_override="Graph.Node.Port")
for _ in range(2):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test_no_image()
async def test_destroy(self):
"""Testing creating and destroying ui.Image"""
window = await self.create_test_window()
with window.frame:
ui.Image(f"{DATA_PATH}/tests/red.png")
# It will immediately kill ui.Image
ui.Spacer()
# Several frames to make sure it doesn't crash
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
# Another way to destroy it
with window.frame:
# The image is destroyed, but we hold it to make sure it doesn't
# crash
ui.Image(f"{DATA_PATH}/tests/red.png").destroy()
# Several frames to make sure it doesn't crash
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
await self.finalize_test_no_image()
async def test_byteimageprovider(self):
"""Testing creating ui.ByteImageProvider"""
window = await self.create_test_window()
bytes = [0, 0, 0, 255, 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255]
resolution = [2, 2]
with window.frame:
ui.ImageWithProvider(
ui.ByteImageProvider(bytes, resolution),
fill_policy=ui.IwpFillPolicy.IWP_STRETCH,
)
await self.finalize_test()
async def test_dynamictextureprovider(self):
"""Testing creating ui.DynamicTextureProvider"""
window = await self.create_test_window()
bytes = [0, 0, 0, 255, 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255]
resolution = [2, 2]
textureprovider = ui.DynamicTextureProvider("textureX")
textureprovider.set_bytes_data(bytes, resolution)
with window.frame:
ui.ImageWithProvider(
textureprovider,
fill_policy=ui.IwpFillPolicy.IWP_STRETCH,
)
resource = textureprovider.get_managed_resource()
self.assertIsNotNone(resource)
await self.finalize_test()
def _warpAvailable():
try:
import warp as wp
return True
except ModuleNotFoundError:
return False
@unittest.skipIf(not _warpAvailable(), "warp module not found")
async def test_byteimageprovider_from_warp(self):
"""Testing creating ui.ByteImageProvider with bytes from gpu"""
window = await self.create_test_window()
import warp as wp
@wp.kernel
def checkerboard(pixels: wp.array(dtype=wp.uint8, ndim=3), size_x: wp.int32, size_y: wp.int32, num_channels: wp.int32):
x, y, c = wp.tid()
value = wp.uint8(0)
if (x / 4) % 2 == (y / 4) % 2:
value = wp.uint8(255)
pixels[x, y, c] = value
size_x = 256
size_y = 256
num_channels = 4
texture_array = wp.zeros(shape=(size_x, size_y, num_channels), dtype=wp.uint8)
wp.launch(kernel=checkerboard, dim=(size_x, size_y, num_channels), inputs=[texture_array, size_x, size_y, num_channels])
provider = ui.ByteImageProvider()
# Test switching between host and gpu source data
provider.set_bytes_data([128 for _ in range(size_x * size_y * num_channels)], [size_x, size_y])
provider.set_bytes_data_from_gpu(texture_array.ptr, [size_x, size_y])
with window.frame:
ui.ImageWithProvider(
provider,
fill_policy=ui.IwpFillPolicy.IWP_STRETCH,
)
await self.finalize_test()
async def test_imageprovider_single_channel(self):
"""Test single channel image with attempt to use unsupported mipmapping"""
window = await self.create_test_window()
provider = ui.RasterImageProvider()
provider.source_url = DATA_PATH.joinpath("tests", "single_channel.jpg").as_posix()
provider.max_mip_levels = 2
with window.frame:
ui.ImageWithProvider(
provider,
fill_policy=ui.IwpFillPolicy.IWP_STRETCH,
)
# wait for image to load
await asyncio.sleep(2)
await self.finalize_test()
async def test_image_rasterization(self):
"""Testing ui.Image while rasterization is turned on"""
window = await self.create_test_window()
f = asyncio.Future()
def on_image_progress(future: asyncio.Future, progress):
if progress >= 1:
if not future.done():
future.set_result(None)
with window.frame:
with ui.Frame(raster_policy=ui.RasterPolicy.AUTO):
ui.Image(f"{DATA_PATH}/tests/red.png", progress_changed_fn=partial(on_image_progress, f))
# Wait the image to be loaded
await f
await self.finalize_test()
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_configuration.py | import glob, os
import omni.kit.test
import omni.kit.app
class ConfigurationTest(omni.kit.test.AsyncTestCase):
async def test_pyi_file_present(self):
# Check that omni.ui extension has _ui.pyi file generated
manager = omni.kit.app.get_app().get_extension_manager()
ext_id = manager.get_enabled_extension_id("omni.ui")
self.assertIsNotNone(ext_id)
ext_path = manager.get_extension_path(ext_id)
self.assertIsNotNone(ext_path)
pyi_files = list(glob.glob(ext_path + "/**/_ui.pyi", recursive=True))
self.assertEqual(len(pyi_files), 1)
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_collapsableframe.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from .test_base import OmniUiTest
import omni.ui as ui
import omni.kit.app
STYLE = {
"CollapsableFrame": {
"background_color": 0xFF383838,
"secondary_color": 0xFF4D4D4D,
"color": 0xFFFFFFFF,
"border_radius": 3,
"margin": 1,
"padding": 3,
}
}
class TestCollapsableFrame(OmniUiTest):
"""Testing ui.CollapsableFrame"""
async def test_general(self):
"""Testing general properties of ui.CollapsableFrame"""
window = await self.create_test_window()
with window.frame:
with ui.VStack(style=STYLE, height=0, spacing=3):
with ui.CollapsableFrame("Frame1"):
ui.Label("Label in CollapsableFrame")
with ui.CollapsableFrame("Frame2"):
ui.Label("First label, should not be displayed")
ui.Label("Second label, should be displayed")
with ui.CollapsableFrame("Frame3"):
ui.Label("Long Label in CollapsableFrame. " * 9, word_wrap=True)
await self.finalize_test()
async def test_collapsing(self):
"""Testing the collapsing behaviour of ui.CollapsableFrame"""
window = await self.create_test_window()
with window.frame:
with ui.VStack(style=STYLE, height=0, spacing=3):
frame1 = ui.CollapsableFrame("Frame1")
with frame1:
ui.Label("Label in CollapsableFrame")
frame2 = ui.CollapsableFrame("Frame2")
with frame2:
ui.Label("Label in CollapsableFrame")
frame3 = ui.CollapsableFrame("Frame3")
with frame3:
ui.Label("Label in CollapsableFrame")
frame4 = ui.CollapsableFrame("Frame4", collapsed=True)
with frame4:
ui.Label("Label in CollapsableFrame")
frame5 = ui.CollapsableFrame("Frame5")
with frame5:
ui.Label("Label in CollapsableFrame")
frame1.collapsed = True
await omni.kit.app.get_app().next_update_async()
frame2.collapsed = True
frame3.collapsed = True
await omni.kit.app.get_app().next_update_async()
frame3.collapsed = False
await self.finalize_test()
async def test_collapsing_build_fn(self):
"""Testing the collapsing behaviour of ui.CollapsableFrame and delayed ui.Frame"""
window = await self.create_test_window()
def content():
ui.Label("Label in CollapsableFrame")
with window.frame:
with ui.VStack(style=STYLE, height=0, spacing=3):
frame1 = ui.CollapsableFrame("Frame1")
with frame1:
ui.Frame(build_fn=content)
frame2 = ui.CollapsableFrame("Frame2")
with frame2:
ui.Frame(build_fn=content)
frame3 = ui.CollapsableFrame("Frame3")
with frame3:
ui.Frame(build_fn=content)
frame4 = ui.CollapsableFrame("Frame4", collapsed=True)
with frame4:
ui.Frame(build_fn=content)
frame5 = ui.CollapsableFrame("Frame5")
with frame5:
ui.Frame(build_fn=content)
frame1.collapsed = True
await omni.kit.app.get_app().next_update_async()
frame2.collapsed = True
frame3.collapsed = True
await omni.kit.app.get_app().next_update_async()
frame3.collapsed = False
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_nested(self):
"""Testing the collapsing behaviour of nested ui.CollapsableFrame"""
window = await self.create_test_window()
with window.frame:
with ui.VStack(style=STYLE, height=0, spacing=3):
frame1 = ui.CollapsableFrame("Frame1")
with frame1:
with ui.VStack(height=0, spacing=3):
ui.Label("Label in CollapsableFrame 1")
frame2 = ui.CollapsableFrame("Frame2")
with frame2:
with ui.VStack(height=0, spacing=3):
ui.Label("Label in CollapsableFrame 2")
frame3 = ui.CollapsableFrame("Frame3")
with frame3:
ui.Label("Label in CollapsableFrame 3")
frame4 = ui.CollapsableFrame("Frame4", collapsed=True)
with frame4:
with ui.VStack(height=0, spacing=3):
ui.Label("Label in CollapsableFrame 4")
frame5 = ui.CollapsableFrame("Frame5")
with frame5:
ui.Label("Label in CollapsableFrame 5")
frame6 = ui.CollapsableFrame("Frame6", collapsed=True)
with frame6:
ui.Label("Label in CollapsableFrame 6")
frame7 = ui.CollapsableFrame("Frame7")
with frame7:
ui.Label("Label in CollapsableFrame 7")
frame1.collapsed = True
frame6.collapsed = False
frame7.collapsed = True
await omni.kit.app.get_app().next_update_async()
frame1.collapsed = False
frame2.collapsed = True
frame3.collapsed = True
frame4.collapsed = False
frame5.collapsed = True
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_grid.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from unittest import skip
import omni.kit.test
import omni.ui as ui
from .test_base import OmniUiTest
import omni.kit.app
class TestGrid(OmniUiTest):
"""Testing ui.HGrid and ui.VGrid"""
async def test_v_size(self):
"""Testing fixed width of ui.VGrid"""
window = await self.create_test_window()
with window.frame:
with ui.VGrid(column_width=20, row_height=20):
for i in range(200):
ui.Label(f"{i}", style={"color": 0xFFFFFFFF})
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_v_number(self):
"""Testing varying width of ui.VGrid"""
window = await self.create_test_window()
with window.frame:
with ui.VGrid(column_count=10, row_height=20):
for i in range(200):
ui.Label(f"{i}", style={"color": 0xFFFFFFFF})
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_v_length(self):
"""Testing varying height of ui.VGrid"""
window = await self.create_test_window()
with window.frame:
with ui.VGrid(column_width=30):
for i in range(200):
if i == 50:
ui.Label(f"{i}", style={"color": 0xFF0033FF, "font_size": 22}, alignment=ui.Alignment.CENTER)
else:
ui.Label(f"{i}", style={"color": 0xFFFFFFFF}, alignment=ui.Alignment.CENTER)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_length_resize(self):
"""Testing varying height of ui.VGrid"""
window = await self.create_test_window()
with window.frame:
grid = ui.VGrid(column_width=64)
with grid:
for i in range(300):
with ui.Frame(height=16):
with ui.HStack():
with ui.VStack():
ui.Spacer()
ui.Rectangle(style={"background_color": ui.color.white})
with ui.VStack():
ui.Rectangle(style={"background_color": ui.color.white})
ui.Spacer()
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
grid.column_width = 16
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_h_size(self):
"""Testing fixed height of ui.HGrid"""
window = await self.create_test_window()
with window.frame:
with ui.HGrid(column_width=20, row_height=20):
for i in range(200):
ui.Label(f"{i}", style={"color": 0xFFFFFFFF})
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_h_number(self):
"""Testing varying height of ui.VGrid"""
window = await self.create_test_window()
with window.frame:
with ui.HGrid(row_count=10, column_width=20):
for i in range(200):
ui.Label(f"{i}", style={"color": 0xFFFFFFFF})
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_h_length(self):
"""Testing varying height of ui.VGrid"""
window = await self.create_test_window()
with window.frame:
with ui.HGrid(row_height=30):
for i in range(200):
if i == 50:
ui.Label(
f"{i}",
style={"color": 0xFF0033FF, "font_size": 22, "margin": 3},
alignment=ui.Alignment.CENTER,
)
else:
ui.Label(f"{i}", style={"color": 0xFFFFFFFF, "margin": 3}, alignment=ui.Alignment.CENTER)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_v_inspector(self):
"""Testing how inspector opens nested frames"""
window = await self.create_test_window()
with window.frame:
with ui.VGrid(column_width=30):
for i in range(200):
ui.Frame(
build_fn=lambda i=i: ui.Label(f"{i}", style={"color": 0xFFFFFFFF}, alignment=ui.Alignment.CENTER)
)
grid = ui.Inspector.get_children(window.frame)[0]
self.assertIsInstance(grid, ui.VGrid)
counter = 0
frames = ui.Inspector.get_children(grid)
for frame in frames:
self.assertIsInstance(frame, ui.Frame)
label = ui.Inspector.get_children(frame)[0]
self.assertIsInstance(label, ui.Label)
self.assertEqual(label.text, f"{counter}")
counter += 1
self.assertEqual(counter, 200)
await self.finalize_test()
@skip("TC crash on this test in linux")
async def test_nested_grid(self):
"""Testing nested grid without setting height and width and not crash (OM-70184)"""
window = await self.create_test_window()
with window.frame:
with ui.VGrid():
with ui.CollapsableFrame("Main Frame"):
with ui.VGrid():
ui.CollapsableFrame("Sub Frame")
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_base.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
__all__ = ["OmniUiTest"]
"""The base class for all the visual tests in omni.ui"""
from .compare_utils import capture_and_compare, CompareMetric
import carb
import carb.input
import carb.windowing
import omni.appwindow
import omni.kit.test
import omni.ui as ui
import pathlib
from carb.input import MouseEventType
DEVICE_TO_BLOCK = [carb.input.DeviceType.GAMEPAD, carb.input.DeviceType.KEYBOARD, carb.input.DeviceType.MOUSE]
async def next_resize_async():
"""
Wait for the next event in the resize event stream of IAppWindow::getWindowResizeEventStream.
We need it because the window resize event stream is independent of IApp::getUpdateEventStream. Without this
function it's possible that resize happens several updates after. It's reproducible on Linux Release build.
"""
return await omni.appwindow.get_default_app_window().get_window_resize_event_stream().next_event()
class OmniUiTest(omni.kit.test.AsyncTestCase):
"""
Base class for testing Omni::UI.
Has methods to initialize/return window and compare images.
"""
# Maximum allowed difference when comparing two images, default compare metric is mean error.
# Set a default threshold that is enough to filter out the artifacts of antialiasing on the different systems.
MEAN_ERROR_THRESHOLD = 0.01
MEAN_ERROR_SQUARED_THRESHOLD = 1e-5
THRESHOLD = MEAN_ERROR_THRESHOLD # default threshold
def __init__(self, tests=()):
super().__init__(tests)
self._saved_width = None
self._saved_height = None
self._restore_window = None
self._restore_position = None
self._restore_dock_window = None
self._need_finalize = False
self.__device_state = [None for _ in DEVICE_TO_BLOCK]
async def setUp(self):
"""Before running each test"""
self._need_finalize = False
async def tearDown(self):
"""After running each test"""
if self._need_finalize: # keep track of whether we get our closing finalize function
carb.log_warn(
"After a create_test_area, create_test_window, or docked_test_window call, finish the test with a finalize_test or finalize_test_no_image "
"call, to restore the window and settings."
)
self._need_finalize = False
async def wait_n_updates(self, n_frames: int = 3):
app = omni.kit.app.get_app()
for _ in range(n_frames):
await app.next_update_async()
@property
def __test_name(self) -> str:
"""
The full name of the test.
It has the name of the module, class and the current test function
"""
return f"{self.__module__}.{self.__class__.__name__}.{self._testMethodName}"
def __get_golden_img_name(self, golden_img_name: str, golden_img_dir: str, test_name: str):
if not golden_img_name:
golden_img_name = f"{test_name}.png"
# Test name includes a module, which makes it long. Filepath length can exceed path limit on windows.
# We want to trim it, but for backward compatibility by default keep golden image name the same. But when
# golden image does not exist and generated first time use shorter name.
if golden_img_dir and not golden_img_dir.joinpath(golden_img_name).exists():
# Example: omni.example.ui.tests.example_ui_test.TestExampleUi.test_ScrollingFrame -> test_ScrollingFrame
pos = test_name.rfind(".test_")
if pos > 0:
test_name = test_name[(pos + 1) :]
golden_img_name = f"{test_name}.png"
return golden_img_name
def __block_devices(self, app_window):
# Save the state
self.__device_state = [app_window.get_input_blocking_state(device) for device in DEVICE_TO_BLOCK]
# Set the new state
for device in DEVICE_TO_BLOCK:
app_window.set_input_blocking_state(device, True)
def __restore_devices(self, app_window):
for device, state in zip(DEVICE_TO_BLOCK, self.__device_state):
if state is not None:
app_window.set_input_blocking_state(device, state)
self.__device_state = [None for _ in DEVICE_TO_BLOCK]
async def create_test_area(
self,
width: int = 256,
height: int = 256,
block_devices: bool = True,
):
"""Resize the main window"""
app_window = omni.appwindow.get_default_app_window()
dpi_scale = ui.Workspace.get_dpi_scale()
# requested size scaled with dpi
width_with_dpi = int(width * dpi_scale)
height_with_dpi = int(height * dpi_scale)
# Current main window size
current_width = app_window.get_width()
current_height = app_window.get_height()
# If the main window is already has requested size, do nothing
if width_with_dpi == current_width and height_with_dpi == current_height:
self._saved_width = None
self._saved_height = None
else:
# Save the size of the main window to be able to restore it at the end of the test
self._saved_width = current_width
self._saved_height = current_height
app_window.resize(width_with_dpi, height_with_dpi)
# Wait for getWindowResizeEventStream
await next_resize_async()
windowing = carb.windowing.acquire_windowing_interface()
os_window = app_window.get_window()
# Move the cursor away to avoid hovering on element and trigger tooltips that break the tests
if block_devices:
input_provider = carb.input.acquire_input_provider()
mouse = app_window.get_mouse()
input_provider.buffer_mouse_event(mouse, MouseEventType.MOVE, (0, 0), 0, (0, 0))
windowing.set_cursor_position(os_window, (0, 0))
# One frame to move mouse cursor
await omni.kit.app.get_app().next_update_async()
if block_devices:
self.__block_devices(app_window)
self._restore_window = None
self._restore_position = None
self._restore_dock_window = None
self._need_finalize = True # keep track of whether we get our closing finalize function
async def create_test_window(
self, width: int = 256, height: int = 256, block_devices: bool = True, window_flags=None
) -> ui.Window:
"""
Resize the main window and create a window with the given resolution.
Returns:
ui.Window with black background, expended to fill full main window and ready for testing.
"""
await self.create_test_area(width, height, block_devices=block_devices)
if window_flags is None:
window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE
window = ui.Window(
f"{self.__test_name} Test",
dockPreference=ui.DockPreference.DISABLED,
flags=window_flags,
width=width,
height=height,
position_x=0,
position_y=0,
)
# Override default background
window.frame.set_style({"Window": {"background_color": 0xFF000000, "border_color": 0x0, "border_radius": 0}})
return window
async def docked_test_window(
self,
window: ui.Window,
width: int = 256,
height: int = 256,
restore_window: ui.Window = None,
restore_position: ui.DockPosition = ui.DockPosition.SAME,
block_devices: bool = True,
) -> None:
"""
Resize the main window and use docked window with the given resolution.
"""
window.undock()
# Wait for the window to be undocked
await omni.kit.app.get_app().next_update_async()
window.focus()
app_window = omni.appwindow.get_default_app_window()
dpi_scale = ui.Workspace.get_dpi_scale()
# requested size scaled with dpi
width_with_dpi = int(width * dpi_scale)
height_with_dpi = int(height * dpi_scale)
# Current main window size
current_width = app_window.get_width()
current_height = app_window.get_height()
# If the main window is already has requested size, do nothing
if width_with_dpi == current_width and height_with_dpi == current_height:
self._saved_width = None
self._saved_height = None
else:
# Save the size of the main window to be able to restore it at the end of the test
self._saved_width = current_width
self._saved_height = current_height
app_window.resize(width_with_dpi, height_with_dpi)
# Wait for getWindowResizeEventStream
await app_window.get_window_resize_event_stream().next_event()
if isinstance(window, ui.Window):
window.flags = ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_TITLE_BAR | ui.WINDOW_FLAGS_NO_RESIZE
window.width = width
window.height = height
window.position_x = 0
window.position_y = 0
windowing = carb.windowing.acquire_windowing_interface()
os_window = app_window.get_window()
# Move the cursor away to avoid hovering on element and trigger tooltips that break the tests
if block_devices:
input_provider = carb.input.acquire_input_provider()
mouse = app_window.get_mouse()
input_provider.buffer_mouse_event(mouse, MouseEventType.MOVE, (0, 0), 0, (0, 0))
windowing.set_cursor_position(os_window, (0, 0))
# One frame to move mouse cursor
await omni.kit.app.get_app().next_update_async()
if block_devices:
self.__block_devices(app_window)
self._restore_dock_window = window
self._restore_window = restore_window
self._restore_position = restore_position
self._need_finalize = True # keep track of whether we get our closing finalize function
async def finalize_test_no_image(self):
"""Restores the main window once a test is complete."""
# Restore main window resolution if it was saved
if self._saved_width is not None and self._saved_height is not None:
app_window = omni.appwindow.get_default_app_window()
app_window.resize(self._saved_width, self._saved_height)
# Wait for getWindowResizeEventStream
await next_resize_async()
if self._restore_dock_window and self._restore_window:
self._restore_dock_window.dock_in(self._restore_window, self._restore_position)
self._restore_window = None
self._restore_position = None
self._restore_dock_window = None
app_window = omni.appwindow.get_default_app_window()
self.__restore_devices(app_window)
self._need_finalize = False
async def capture_and_compare(
self,
threshold=None,
golden_img_dir: pathlib.Path = None,
golden_img_name=None,
use_log: bool = True,
cmp_metric=CompareMetric.MEAN_ERROR,
test_name: str = None,
hide_menu_bar: bool = True
):
"""Capture current frame and compare it with the golden image. Assert if the diff is more than given threshold."""
test_name = test_name or f"{self.__test_name}"
golden_img_name = self.__get_golden_img_name(golden_img_name, golden_img_dir, test_name)
menu_bar = None
old_visible = None
try:
try:
from omni.kit.mainwindow import get_main_window
main_window = get_main_window()
menu_bar = main_window.get_main_menu_bar()
old_visible = menu_bar.visible
if hide_menu_bar:
menu_bar.visible = False
except ImportError:
pass
# set default threshold for each compare metric
if threshold is None:
if cmp_metric == CompareMetric.MEAN_ERROR:
threshold = self.MEAN_ERROR_THRESHOLD
elif cmp_metric == CompareMetric.MEAN_ERROR_SQUARED:
threshold = self.MEAN_ERROR_SQUARED_THRESHOLD
elif cmp_metric == CompareMetric.PIXEL_COUNT:
threshold = 10 # arbitrary number
diff = await capture_and_compare(
golden_img_name, threshold, golden_img_dir, use_log=use_log, cmp_metric=cmp_metric
)
if diff != 0:
carb.log_warn(f"[{test_name}] the generated image has difference {diff}")
self.assertTrue(
(diff is not None and diff < threshold),
msg=f"The image for test '{test_name}' doesn't match the golden one. Difference of {diff} is is not less than threshold of {threshold}.",
)
finally:
if menu_bar:
menu_bar.visible = old_visible
async def finalize_test(
self,
threshold=None,
golden_img_dir: pathlib.Path = None,
golden_img_name=None,
use_log: bool = True,
cmp_metric=CompareMetric.MEAN_ERROR,
test_name: str = None,
hide_menu_bar: bool = True
):
try:
test_name = test_name or f"{self.__test_name}"
golden_img_name = self.__get_golden_img_name(golden_img_name, golden_img_dir, test_name)
await self.capture_and_compare(threshold,
golden_img_dir,
golden_img_name,
use_log,
cmp_metric,
test_name,
hide_menu_bar)
finally:
await self.finalize_test_no_image()
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_layout.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import omni.kit.test
from .test_base import OmniUiTest
import omni.kit.app
import omni.ui as ui
class TestLayout(OmniUiTest):
"""Testing the layout"""
async def test_general(self):
"""Testing general layout and number of calls of setComputedWidth"""
window = await self.create_test_window()
with window.frame:
with ui.VStack():
with ui.HStack():
ui.Button("NVIDIA")
ui.Button("Omniverse")
bottom_stack = ui.HStack()
with bottom_stack:
ui.Button("omni")
button = ui.Button("ui")
await omni.kit.app.get_app().next_update_async()
# 21 is because the window looks like this:
# MenuBar
# Frame
# VStack
# HStack
# Button
# Stack
# Label
# Rectangle
# Button
# Stack
# Label
# Rectangle
# HStack
# Button
# Stack
# Label
# Rectangle
# Button
# Stack
# Label
# Rectangle
should_be_called = [21] + [0] * 20
for i in should_be_called:
ui.Inspector.begin_computed_width_metric()
ui.Inspector.begin_computed_height_metric()
await omni.kit.app.get_app().next_update_async()
width_calls = ui.Inspector.end_computed_width_metric()
height_calls = ui.Inspector.end_computed_height_metric()
self.assertEqual(width_calls, i)
self.assertEqual(height_calls, i)
button.height = ui.Pixel(25)
# 11 becuse we changed the height of the button and this is the list of
# changed widgets:
# 4 Button
# 4 Neighbour button because it's Fraction(1)
# 1 HStack becuase min size could change
# 1 VStack becuase min size could change
# 1 Frame becuase min size could change
should_be_called = [11] + [0] * 20
for i in range(10):
ui.Inspector.begin_computed_width_metric()
ui.Inspector.begin_computed_height_metric()
await omni.kit.app.get_app().next_update_async()
width_calls = ui.Inspector.end_computed_width_metric()
height_calls = ui.Inspector.end_computed_height_metric()
bottom_stack.height = ui.Pixel(50)
# 16 because 20 (total wingets minus MenuBar) - 4 (Button is in pixels,
# the size of pixels don't change if parent changes) and we only changed
# heights and width should not be called
should_be_called = [16] + [0] * 20
for i in should_be_called:
ui.Inspector.begin_computed_width_metric()
ui.Inspector.begin_computed_height_metric()
await omni.kit.app.get_app().next_update_async()
width_calls = ui.Inspector.end_computed_width_metric()
height_calls = ui.Inspector.end_computed_height_metric()
self.assertEqual(width_calls, 0)
self.assertEqual(height_calls, i)
button.width = ui.Pixel(25)
# 20 because everything except MenuBar could change:
# Neighbour button is changed
# Stack could change if button.width is very big
# Neighbour stack could change if current stack is changed
# Parent stack
# Root frame
#
# Height shouldn't change
should_be_called = [20] + [0] * 20
for i in should_be_called:
ui.Inspector.begin_computed_width_metric()
ui.Inspector.begin_computed_height_metric()
await omni.kit.app.get_app().next_update_async()
width_calls = ui.Inspector.end_computed_width_metric()
height_calls = ui.Inspector.end_computed_height_metric()
self.assertEqual(width_calls, i)
self.assertEqual(height_calls, 0)
await self.finalize_test()
async def test_send_mouse_events_to_back(self):
"""Testing send_mouse_events_to_back of ui.ZStack"""
import omni.kit.ui_test as ui_test
window = await self.create_test_window(block_devices=False)
clicked = [0, 0]
def clicked_fn(i):
clicked[i] += 1
with window.frame:
stack = ui.ZStack()
with stack:
ui.Button(clicked_fn=lambda: clicked_fn(0))
button = ui.Button(clicked_fn=lambda: clicked_fn(1))
await omni.kit.app.get_app().next_update_async()
refButton = ui_test.WidgetRef(button, "")
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move_and_click(refButton.center)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(clicked[0], 1)
stack.send_mouse_events_to_back = False
await omni.kit.app.get_app().next_update_async()
await ui_test.emulate_mouse_move_and_click(refButton.center)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(clicked[1], 1)
await self.finalize_test_no_image()
async def test_visibility(self):
window = await self.create_test_window()
with window.frame:
with ui.HStack(height=32):
with ui.VStack(width=80):
ui.Spacer(height=10)
c1 = ui.ComboBox(0, "NVIDIA", "OMNIVERSE", width=100)
with ui.VStack(width=80):
ui.Spacer(height=10)
ui.ComboBox(0, "NVIDIA", "OMNIVERSE", width=100)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
c1.visible = not c1.visible
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
c1.visible = not c1.visible
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/test_workspace.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from .test_base import OmniUiTest
import carb.settings
import omni.appwindow
import omni.kit.app
import omni.kit.renderer
import omni.kit.test
import omni.ui as ui
class TestWorkspace(OmniUiTest):
"""Testing ui.Workspace"""
async def test_window_selection(self):
"""Testing window selection callback"""
ui.Workspace.clear()
self.text = "null"
def update_selection(selected):
self.text = "Selected" if selected else "UnSelected"
ui_main_window = ui.MainWindow()
window1 = ui.Window("First Selection", width=100, height=100)
window2 = ui.Window("Second Selection", width=100, height=100)
window3 = ui.Window("Third Selection", width=100, height=100)
await omni.kit.app.get_app().next_update_async()
main_dockspace = ui.Workspace.get_window("DockSpace")
window1.dock_in(main_dockspace, ui.DockPosition.SAME)
window2.dock_in(main_dockspace, ui.DockPosition.SAME)
window3.dock_in(main_dockspace, ui.DockPosition.SAME)
await omni.kit.app.get_app().next_update_async()
# add callback function to window2 to subscribe selection change in windows
window2.set_selected_in_dock_changed_fn(lambda value: update_selection(value))
await omni.kit.app.get_app().next_update_async()
# select window2 to check if the callback is triggered
window2.focus()
await omni.kit.app.get_app().next_update_async()
self.assertEqual(self.text, "Selected")
await omni.kit.app.get_app().next_update_async()
# select window1 to check if the callback is triggered
window1.focus()
await omni.kit.app.get_app().next_update_async()
self.assertEqual(self.text, "UnSelected")
async def test_workspace_nohide(self):
"""Testing window layout without hiding the windows"""
ui.Workspace.clear()
await self.create_test_area(256, 256)
ui_main_window = ui.MainWindow()
ui_main_window.main_menu_bar.visible = False
window1 = ui.Window("First", width=100, height=100)
window2 = ui.Window("Second", width=100, height=100)
await omni.kit.app.get_app().next_update_async()
main_dockspace = ui.Workspace.get_window("DockSpace")
window1.dock_in(main_dockspace, ui.DockPosition.SAME)
window2.dock_in(window1, ui.DockPosition.BOTTOM)
await omni.kit.app.get_app().next_update_async()
# Save the layout
layout = ui.Workspace.dump_workspace()
# Reference. Don't check directly because `dock_id` is random.
# [
# {
# "dock_id": 3358485147,
# "children": [
# {
# "dock_id": 1,
# "position": "TOP",
# "children": [
# {
# "title": "First",
# "width": 100.0,
# "height": 100.0,
# "position_x": 78.0,
# "position_y": 78.0,
# "dock_id": 1,
# "visible": True,
# "selected_in_dock": False,
# }
# ],
# },
# {
# "dock_id": 2,
# "position": "BOTTOM",
# "children": [
# {
# "title": "Second",
# "width": 100.0,
# "height": 100.0,
# "position_x": 78.0,
# "position_y": 78.0,
# "dock_id": 2,
# "visible": True,
# "selected_in_dock": False,
# }
# ],
# },
# ],
# }
# ]
self.assertEqual(layout[0]["children"][0]["children"][0]["title"], "First")
self.assertEqual(layout[0]["children"][1]["children"][0]["title"], "Second")
window3 = ui.Window("Third", width=100, height=100)
await omni.kit.app.get_app().next_update_async()
window3.dock_in(window1, ui.DockPosition.LEFT)
ui.Workspace.restore_workspace(layout, True)
window3.position_x = 78
window3.position_y = 78
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_workspace_nohide_invisible(self):
"""Testing window layout without hiding the windows"""
ui.Workspace.clear()
await self.create_test_area(256, 256)
ui_main_window = ui.MainWindow()
ui_main_window.main_menu_bar.visible = False
window1 = ui.Window(
"First Vis", width=100, height=100, position_x=0, position_y=0, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR
)
window2 = ui.Window(
"Second Invis", width=100, height=100, position_x=100, position_y=0, flags=ui.WINDOW_FLAGS_NO_SCROLLBAR
)
await omni.kit.app.get_app().next_update_async()
window2.visible = False
await omni.kit.app.get_app().next_update_async()
# Save the layout
layout = ui.Workspace.dump_workspace()
# We have first window visible, the second is not visible
window3 = ui.Window("Third Absent", width=100, height=100, position_x=0, position_y=100)
await omni.kit.app.get_app().next_update_async()
ui.Workspace.restore_workspace(layout, True)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_dock_node_size(self):
ui.Workspace.clear()
await self.create_test_area(256, 256)
ui_main_window = ui.MainWindow()
ui_main_window.main_menu_bar.visible = False
window1 = ui.Window("1", width=100, height=100)
window2 = ui.Window("2", width=100, height=100)
window3 = ui.Window("3", width=100, height=100)
window4 = ui.Window("4", width=100, height=100)
await omni.kit.app.get_app().next_update_async()
main_dockspace = ui.Workspace.get_window("DockSpace")
window1.dock_in(main_dockspace, ui.DockPosition.SAME)
window2.dock_in(window1, ui.DockPosition.RIGHT)
window3.dock_in(window1, ui.DockPosition.BOTTOM)
window4.dock_in(window2, ui.DockPosition.BOTTOM)
await omni.kit.app.get_app().next_update_async()
self.assertEqual(ui.Workspace.get_dock_id_width(window1.dock_id), 126)
self.assertEqual(ui.Workspace.get_dock_id_width(window2.dock_id), 126)
self.assertEqual(ui.Workspace.get_dock_id_width(window3.dock_id), 126)
self.assertEqual(ui.Workspace.get_dock_id_width(window4.dock_id), 126)
self.assertEqual(ui.Workspace.get_dock_id_height(window1.dock_id), 124)
self.assertEqual(ui.Workspace.get_dock_id_height(window2.dock_id), 124)
self.assertEqual(ui.Workspace.get_dock_id_height(window3.dock_id), 124)
self.assertEqual(ui.Workspace.get_dock_id_height(window4.dock_id), 124)
ui.Workspace.set_dock_id_width(window1.dock_id, 50)
ui.Workspace.set_dock_id_height(window1.dock_id, 50)
ui.Workspace.set_dock_id_height(window4.dock_id, 50)
await self.finalize_test()
ui.Workspace.clear()
def _window_visibility_callback(self, title, visible) -> None:
self._visibility_changed_window_title = title
self._visibility_changed_window_visible = visible
def _window_visibility_callback2(self, title, visible) -> None:
self._visibility_changed_window_title2 = title
self._visibility_changed_window_visible2 = visible
def _window_visibility_callback3(self, title, visible) -> None:
self._visibility_changed_window_title3 = title
self._visibility_changed_window_visible3 = visible
async def test_workspace_window_visibility_callback(self):
"""Testing window visibility changed callback"""
# test window create
ui.Workspace.clear()
self._visibility_changed_window_title = None
self._visibility_changed_window_visible = False
self._visibility_changed_window_title2 = None
self._visibility_changed_window_visible2 = False
self._visibility_changed_window_title3 = None
self._visibility_changed_window_visible3 = False
id1 = ui.Workspace.set_window_visibility_changed_callback(self._window_visibility_callback)
id2 = ui.Workspace.set_window_visibility_changed_callback(self._window_visibility_callback2)
id3 = ui.Workspace.set_window_visibility_changed_callback(self._window_visibility_callback3)
window2 = ui.Window("visible_change", width=100, height=100)
self.assertTrue(self._visibility_changed_window_title=="visible_change")
self.assertTrue(self._visibility_changed_window_visible==True)
# test window visible change to False
self._visibility_changed_window_title = None
self._visibility_changed_window_visible = True
window2.visible = False
await omni.kit.app.get_app().next_update_async()
self.assertTrue(self._visibility_changed_window_title=="visible_change")
self.assertTrue(self._visibility_changed_window_visible==False)
# test window visible change to true
self._visibility_changed_window_title = None
self._visibility_changed_window_visible = False
window2.visible = True
await omni.kit.app.get_app().next_update_async()
self.assertTrue(self._visibility_changed_window_title=="visible_change")
self.assertTrue(self._visibility_changed_window_visible==True)
# test another callback function change to false
self._visibility_changed_window_title2 = None
self._visibility_changed_window_visible2 = True
window2.visible = False
await omni.kit.app.get_app().next_update_async()
self.assertTrue(self._visibility_changed_window_title2=="visible_change")
self.assertTrue(self._visibility_changed_window_visible2==False)
# test another callback function change change to true
self._visibility_changed_window_title2 = None
self._visibility_changed_window_visible2 = False
window2.visible = True
await omni.kit.app.get_app().next_update_async()
self.assertTrue(self._visibility_changed_window_title2=="visible_change")
self.assertTrue(self._visibility_changed_window_visible2==True)
# Add more window visible change to true and wait more frames
self._visibility_changed_window_title = None
self._visibility_changed_window_visible = False
window3 = ui.Window("visible_change3", width=100, height=100)
for i in range(10):
await omni.kit.app.get_app().next_update_async()
self.assertTrue(self._visibility_changed_window_title=="visible_change3")
self.assertTrue(self._visibility_changed_window_visible==True)
# Add more window visible change to False
self._visibility_changed_window_title = None
self._visibility_changed_window_visible = False
window3.visible = False
for i in range(10):
await omni.kit.app.get_app().next_update_async()
self.assertTrue(self._visibility_changed_window_title=="visible_change3")
self.assertTrue(self._visibility_changed_window_visible==False)
# test remove_window_visibility_changed_callback
self._visibility_changed_window_title = None
self._visibility_changed_window_visible = True
self._visibility_changed_window_title2 = None
self._visibility_changed_window_visible2 = True
ui.Workspace.remove_window_visibility_changed_callback(id1)
window2.visible = False
await omni.kit.app.get_app().next_update_async()
self.assertTrue(self._visibility_changed_window_title==None)
self.assertTrue(self._visibility_changed_window_visible==True)
self.assertTrue(self._visibility_changed_window_title2=="visible_change")
self.assertTrue(self._visibility_changed_window_visible2==False)
# OM-60640: Notice that remove one change callback not effect other callbacks
self._visibility_changed_window_visible = False
self._visibility_changed_window_title2 = None
self._visibility_changed_window_visible2 = False
self._visibility_changed_window_title3 = None
self._visibility_changed_window_visible3 = False
window2.visible = True
await omni.kit.app.get_app().next_update_async()
self.assertTrue(self._visibility_changed_window_title==None)
self.assertTrue(self._visibility_changed_window_visible==False)
self.assertTrue(self._visibility_changed_window_title2=="visible_change")
self.assertTrue(self._visibility_changed_window_visible2==True)
self.assertTrue(self._visibility_changed_window_title3=="visible_change")
self.assertTrue(self._visibility_changed_window_visible3==True)
ui.Workspace.remove_window_visibility_changed_callback(id2)
ui.Workspace.remove_window_visibility_changed_callback(id3)
async def test_workspace_deferred_dock_in(self):
"""Testing window layout without hiding the windows"""
ui.Workspace.clear()
await self.create_test_area(256, 256)
ui_main_window = ui.MainWindow()
ui_main_window.main_menu_bar.visible = False
window1 = ui.Window("First", width=100, height=100)
window2 = ui.Window("Second", width=100, height=100)
await omni.kit.app.get_app().next_update_async()
main_dockspace = ui.Workspace.get_window("DockSpace")
window1.dock_in(main_dockspace, ui.DockPosition.SAME)
window2.dock_in(window1, ui.DockPosition.BOTTOM)
await omni.kit.app.get_app().next_update_async()
# Save the layout
layout = ui.Workspace.dump_workspace()
window2.deferred_dock_in("First")
# Restore_workspace should reset deferred_dock_in
ui.Workspace.restore_workspace(layout, True)
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
async def test_freeze(self):
PRESENT_THREAD = "/exts/omni.kit.renderer.core/present/enabled"
settings = carb.settings.get_settings()
present_thread_enabled = settings.get(PRESENT_THREAD)
settings.set(PRESENT_THREAD, True)
window = await self.create_test_window()
with window.frame:
ui.Label("NVIDIA Omniverse")
# Get IRenderer
renderer = omni.kit.renderer.bind.get_renderer_interface()
# Get default IAppWindow
app_window_factory = omni.appwindow.acquire_app_window_factory_interface()
app_window = app_window_factory.get_app_window()
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
# Draw freeze the window
renderer.draw_freeze_app_window(app_window, True)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
with window.frame:
ui.Label("Something Else")
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
await self.finalize_test()
renderer.draw_freeze_app_window(app_window, False)
await omni.kit.app.get_app().next_update_async()
settings.set(PRESENT_THREAD, present_thread_enabled)
await omni.kit.app.get_app().next_update_async()
class WorkspaceCallbacks(omni.kit.test.AsyncTestCase):
def _window_created_callback(self, w) -> None:
self._created = w
async def test_window_creation_callback(self):
"""Testing window creation callback"""
self._created = None
ui.Workspace.set_window_created_callback(self._window_created_callback)
window1 = ui.Window("First", width=100, height=100)
await omni.kit.app.get_app().next_update_async()
self.assertTrue(self._created == window1)
|
omniverse-code/kit/exts/omni.ui/omni/ui/tests/compare_utils.py | ## Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
"""The utilities for image comparison"""
from pathlib import Path
import os
import platform
import carb
import carb.tokens
import sys
import traceback
import omni.kit.test
from omni.kit.test.teamcity import teamcity_publish_image_artifact
OUTPUTS_DIR = Path(omni.kit.test.get_test_output_path())
KIT_ROOT = Path(carb.tokens.get_tokens_interface().resolve("${kit}")).parent.parent.parent
GOLDEN_DIR = KIT_ROOT.joinpath("data/tests/omni.ui.tests")
def Singleton(class_):
"""
A singleton decorator.
TODO: It's also available in omni.kit.widget.stage. Do we have a utility extension where we can put the utilities
like this?
"""
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = class_(*args, **kwargs)
return instances[class_]
return getinstance
class CompareError(Exception):
pass
class CompareMetric:
MEAN_ERROR = "mean_error"
MEAN_ERROR_SQUARED = "mean_error_squared"
PIXEL_COUNT = "pixel_count"
def compare(image1: Path, image2: Path, image_diffmap: Path, threshold=None, cmp_metric=CompareMetric.MEAN_ERROR):
"""
Compares two images and return a value that indicates the difference based on the metric used.
Types of comparison: mean error (default), mean error squared, and pixel count.
Mean Error (mean absolute error):
Average pixel level for each channel in the image, return a number between [0, 255]
This is the default method in UI compare tests - it gives a nice range of numbers.
Mean Error Squared (mean squared error):
Measures the average of the squares of the errors, return a number between [0, 1]
This is the default method used in Kit Rendering, see `meanErrorSquaredMetric`
Pixel Count:
Return the number of pixels that are different
It uses Pillow for image read.
Args:
image1, image2: images to compare
image_diffmap: the difference map image will be saved if there is any difference between given images
threshold: the threshold value (int or float)
cmp_metric: comparison method
"""
if not image1.exists():
raise CompareError(f"File image1 {image1} does not exist")
if not image2.exists():
raise CompareError(f"File image2 {image2} does not exist")
# OMFP-1891: Cease use of pip install
if "PIL" not in sys.modules.keys():
raise CompareError("Cannot import PIL from Pillow, image comparison failed.")
from PIL import Image, ImageChops, ImageStat
original = Image.open(str(image1))
contrast = Image.open(str(image2))
if original.size != contrast.size:
raise CompareError(
f"[omni.ui.test] Can't compare different resolutions\n\n"
f"{image1} {original.size[0]}x{original.size[1]}\n"
f"{image2} {contrast.size[0]}x{contrast.size[1]}\n\n"
f"It's possible that your monitor DPI is not 100%.\n\n"
)
if original.mode != contrast.mode:
raise CompareError(
f"[omni.ui.test] Can't compare images with different mode (channels).\n\n"
f"{image1} {original.mode}\n"
f"{image2} {contrast.mode}\n\n"
)
img_diff = ImageChops.difference(original, contrast)
stat = ImageStat.Stat(img_diff)
if cmp_metric == CompareMetric.MEAN_ERROR:
# Calculate average difference between two images
diff = sum(stat.mean) / len(stat.mean)
elif cmp_metric == CompareMetric.MEAN_ERROR_SQUARED:
# Measure the average of the squares of the errors between two images
# Errors are calculated from 0 to 255 (squared), divide by 255^2 to have a range between [0, 1]
errors = [x / stat.count[i] for i, x in enumerate(stat.sum2)]
diff = sum(errors) / len(stat.sum2) / 255**2
elif cmp_metric == CompareMetric.PIXEL_COUNT:
# Count of different pixels - on single channel image the value of getpixel is an int instead of a tuple
if isinstance(img_diff.getpixel((0, 0)), int):
diff = sum([img_diff.getpixel((j, i)) > 0 for i in range(img_diff.height) for j in range(img_diff.width)])
else:
diff = sum(
[sum(img_diff.getpixel((j, i))) > 0 for i in range(img_diff.height) for j in range(img_diff.width)]
)
# only save image diff if needed (2 order of magnitude near threshold)
if diff > 0 and threshold and diff > threshold / 100:
# Images are different
# Multiply image by 255
img_diff = img_diff.convert("RGB").point(lambda i: min(i * 255, 255))
img_diff.save(str(image_diffmap))
return diff
async def capture_and_compare(
image_name: str,
threshold,
golden_img_dir: Path = None,
use_log: bool = True,
cmp_metric=CompareMetric.MEAN_ERROR,
):
"""
Captures frame and compares it with the golden image.
Args:
image_name: the image name of the image and golden image.
threshold: the max threshold to collect TC artifacts.
golden_img_dir: the directory path that stores the golden image. Leave it to None to use default dir.
cmp_metric: comparison metric (mean error, mean error squared, pixel count)
Returns:
A diff value based on the comparison metric used.
"""
if not golden_img_dir:
golden_img_dir = GOLDEN_DIR
image1 = OUTPUTS_DIR.joinpath(image_name)
image2 = golden_img_dir.joinpath(image_name)
image_diffmap = OUTPUTS_DIR.joinpath(f"{Path(image_name).stem}.diffmap.png")
alt_image2 = golden_img_dir.joinpath(f"{platform.system().lower()}/{image_name}")
if os.path.exists(alt_image2):
image2 = alt_image2
if use_log:
carb.log_info(f"[omni.ui.tests.compare] Capturing {image1} and comparing with {image2}.")
import omni.renderer_capture
capture_next_frame = omni.renderer_capture.acquire_renderer_capture_interface().capture_next_frame_swapchain
wait_async_capture = omni.renderer_capture.acquire_renderer_capture_interface().wait_async_capture
capture_next_frame(str(image1))
await omni.kit.app.get_app().next_update_async()
wait_async_capture()
try:
diff = compare(image1, image2, image_diffmap, threshold, cmp_metric)
if diff >= threshold:
golden_path = Path("golden").joinpath(OUTPUTS_DIR.name)
results_path = Path("results").joinpath(OUTPUTS_DIR.name)
teamcity_publish_image_artifact(image2, golden_path, "Reference")
teamcity_publish_image_artifact(image1, results_path, "Generated")
teamcity_publish_image_artifact(image_diffmap, results_path, "Diff")
return diff
except CompareError as e:
carb.log_error(f"[omni.ui.tests.compare] Failed to compare images for {image_name}. Error: {e}")
carb.log_error(f"[omni.ui.tests.compare] Traceback:\n{traceback.format_exc()}")
|
omniverse-code/kit/exts/omni.kit.property.skel/PACKAGE-LICENSES/omni.kit.property.skel-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. |
omniverse-code/kit/exts/omni.kit.property.skel/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.1"
category = "Internal"
feature = true
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarly for displaying extension info in UI
title = "Skeleton Animation Property Widget"
description="View and Edit Skeleton Animation Property Values"
# URL of the extension source repository.
repository = ""
# Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file).
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
# Keywords for the extension
keywords = ["kit", "usd", "property", "skel", "skeleton", "animation"]
# 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"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
[dependencies]
"omni.usd" = {}
"omni.ui" = {}
"omni.kit.window.property" = {}
"omni.kit.property.usd" = {}
"omni.kit.commands" = {}
"omni.kit.usd_undo" = {}
[[python.module]]
name = "omni.kit.property.skel"
[[test]]
args = [
"--/renderer/enabled=pxr",
"--/renderer/active=pxr",
"--/renderer/multiGpu/enabled=false",
"--/renderer/multiGpu/autoEnable=false", # Disable mGPU with PXR due to OM-51026, OM-53611
"--/renderer/multiGpu/maxGpuCount=1",
"--/app/asyncRendering=false",
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.hydra.pxr",
"omni.kit.renderer.capture",
"omni.kit.mainwindow",
"omni.kit.ui_test",
"omni.kit.test_suite.helpers"
]
stdoutFailPatterns.exclude = [
"*HydraRenderer failed to render this frame*", # Can drop a frame or two rendering with OpenGL interop
"*Failed to acquire interface*while unloading all plugins*",
"*Cannot use omni.hydra.pxr without OpenGL interop*" # Linux TC configs with multi-GPU might not have OpenGL available
]
|
omniverse-code/kit/exts/omni.kit.property.skel/omni/kit/property/skel/__init__.py | from .scripts import *
|
omniverse-code/kit/exts/omni.kit.property.skel/omni/kit/property/skel/scripts/skel_animation_widget.py | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
import omni.usd
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidget
from omni.kit.property.usd.prim_selection_payload import PrimSelectionPayload
from pxr import Sdf, Usd, UsdSkel
from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutProperty
from .command import *
class SkelAnimationAttributesWidget(UsdPropertiesWidget):
def __init__(self, title: str):
super().__init__(title, collapsed=False)
self._title = title
from omni.kit.property.usd import PrimPathWidget
self._add_button_menus = []
self._add_button_menus.append(
PrimPathWidget.add_button_menu_entry(
"Animation/Skeletal Animation",
show_fn=self.on_show,
onclick_fn=self.on_click
)
)
def destroy(self):
for menu_entry in self._add_button_menus:
PrimPathWidget.remove_button_menu_entry(menu_entry)
def on_show(self, objects: dict):
if "prim_list" not in objects or "stage" not in objects:
return False
stage = objects["stage"]
if not stage:
return False
prim_list = objects["prim_list"]
if len(prim_list) < 1:
return False
for item in prim_list:
if isinstance(item, Sdf.Path):
prim = stage.GetPrimAtPath(item)
elif isinstance(item, Usd.Prim):
prim = item
if not prim.HasAPI(UsdSkel.BindingAPI) and prim.IsA(UsdSkel.Skeleton):
return True
return False
def on_click(self, payload: PrimSelectionPayload):
if payload is None:
return Sdf.Path.emptyPath
payload_paths = payload.get_paths()
omni.kit.commands.execute("ApplySkelBindingAPICommand", paths=payload_paths)
def on_new_payload(self, payload):
if not super().on_new_payload(payload):
return False
if not self._payload or len(self._payload) == 0:
return False
for prim_path in payload:
prim = self._get_prim(prim_path)
if not prim:
return False
if prim.HasAPI(UsdSkel.BindingAPI) and (prim.IsA(UsdSkel.Skeleton) or prim.IsA(UsdSkel.Root)):
return True
return False
def _filter_props_to_build(self, props):
return [prop for prop in props if prop.GetName() == "skel:animationSource"]
def _customize_props_layout(self, props):
frame = CustomLayoutFrame(hide_extra=True)
def spacer_build_fn(*args):
ui.Spacer(height=2)
with frame:
CustomLayoutProperty("skel:animationSource", "Animation Source")
CustomLayoutProperty(None, None, build_fn=spacer_build_fn)
return frame.apply(props)
def get_additional_kwargs(self, ui_attr):
random_prim = Usd.Prim()
prim_same_type = True
if self._payload:
prim_paths = self._payload.get_paths()
for prim_path in prim_paths:
prim = self._get_prim(prim_path)
if not prim:
continue
if not random_prim:
random_prim = prim
elif random_prim.GetTypeName() != prim.GetTypeName():
prim_same_type = False
break
if ui_attr.prop_name == "skel:animationSource" and prim_same_type and random_prim and (random_prim.IsA(UsdSkel.Skeleton) or random_prim.IsA(UsdSkel.Root)):
return None, {"target_picker_filter_type_list": [UsdSkel.Animation], "targets_limit": 1}
return None, {"targets_limit": 0}
|
omniverse-code/kit/exts/omni.kit.property.skel/omni/kit/property/skel/scripts/extension.py | import omni.ext
from .skel_animation_widget import SkelAnimationAttributesWidget
from .mesh_skel_binding_widget import MeshSkelBindingAttributesWidget
class SkelPropertyExtension(omni.ext.IExt):
def __init__(self):
self._skel_widget = None
def on_startup(self, ext_id):
import omni.kit.window.property as p
self._skel_animation_widget = SkelAnimationAttributesWidget("Skeletal Animation")
self._mesh_skel_binding_widget = MeshSkelBindingAttributesWidget("Skeletal Binding")
w = p.get_window()
if w:
w.register_widget("prim", "skel_animation", self._skel_animation_widget)
w.register_widget("prim", "mesh_skel_binding", self._mesh_skel_binding_widget)
def on_shutdown(self):
if self._skel_widget is not None:
import omni.kit.window.property as p
w = p.get_window()
if w:
w.unregister_widget("prim", "skel_animation")
w.unregister_widget("prim", "mesh_skel_binding")
self._skel_animation_widget.destroy()
self._skel_animation_widget = None
self._mesh_skel_binding_widget.destroy()
self._mesh_skel_binding_widget = None
|
omniverse-code/kit/exts/omni.kit.property.skel/omni/kit/property/skel/scripts/__init__.py | from .extension import *
from .command import *
|
omniverse-code/kit/exts/omni.kit.property.skel/omni/kit/property/skel/scripts/mesh_skel_binding_widget.py | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
import omni.ui as ui
import omni.usd
from omni.kit.property.usd.usd_property_widget import UsdPropertiesWidget, UsdPropertyUiEntry
from omni.kit.property.usd.prim_selection_payload import PrimSelectionPayload
from pxr import Usd, UsdSkel, UsdGeom
from omni.kit.property.usd.custom_layout_helper import CustomLayoutFrame, CustomLayoutGroup, CustomLayoutProperty
from .command import *
MESH_ATTRS = ["skel:skeleton", "skel:skinningMethod", "skel:blendShapeTargets"]
class MeshSkelBindingAttributesWidget(UsdPropertiesWidget):
def __init__(self, title: str):
super().__init__(title, collapsed=False)
self._title = title
def destroy(self):
pass
def on_new_payload(self, payload):
if not super().on_new_payload(payload):
return False
if not self._payload or len(self._payload) == 0:
return False
for prim_path in payload:
prim = self._get_prim(prim_path)
if not prim:
return False
if prim.HasAPI(UsdSkel.BindingAPI) and prim.IsA(UsdGeom.Mesh):
return True
return False
def _filter_props_to_build(self, props):
return [prop for prop in props if prop.GetName() in MESH_ATTRS]
def _customize_props_layout(self, props):
frame = CustomLayoutFrame(hide_extra=True)
def spacer_build_fn(*args):
ui.Spacer(height=10)
with frame:
CustomLayoutProperty("skel:skeleton", "Skeleton")
CustomLayoutProperty(None, None, build_fn=spacer_build_fn)
CustomLayoutProperty("skel:skinningMethod", "Skinning Method")
CustomLayoutProperty(None, None, build_fn=spacer_build_fn)
CustomLayoutProperty("skel:blendShapeTargets", "Blendshape Targets")
return frame.apply(props)
def get_additional_kwargs(self, ui_attr):
random_prim = Usd.Prim()
prim_same_type = True
if self._payload:
prim_paths = self._payload.get_paths()
for prim_path in prim_paths:
prim = self._get_prim(prim_path)
if not prim:
continue
if not random_prim:
random_prim = prim
elif random_prim.GetTypeName() != prim.GetTypeName():
prim_same_type = False
break
if ui_attr.prop_name == "skel:skeleton" and prim_same_type and random_prim and random_prim.IsA(UsdGeom.Mesh):
return None, {"target_picker_filter_type_list": [UsdSkel.Skeleton], "targets_limit": 1}
elif ui_attr.prop_name == "skel:blendShapeTargets" and prim_same_type and random_prim and random_prim.IsA(UsdGeom.Mesh):
return None, {"target_picker_filter_type_list": [UsdSkel.BlendShape], "targets_limit": 0}
return None, {"targets_limit": 0}
|
omniverse-code/kit/exts/omni.kit.property.skel/omni/kit/property/skel/scripts/command.py | import carb
import omni
import omni.kit.commands
from pxr import Sdf, UsdGeom, Usd, UsdSkel
from omni.kit.usd_undo import UsdLayerUndo
from typing import List
class ApplySkelBindingAPICommand(omni.kit.commands.Command):
def __init__(
self,
layer: Sdf.Layer = None,
paths: List[Sdf.Path] = []
):
self._usd_undo = None
self._layer = layer
self._paths = paths
def do(self):
stage = omni.usd.get_context().get_stage()
if self._layer is None:
self._layer = stage.GetEditTarget().GetLayer()
self._usd_undo = UsdLayerUndo(self._layer)
for path in self._paths:
prim = stage.GetPrimAtPath(path)
if not prim.HasAPI(UsdSkel.BindingAPI):
self._usd_undo.reserve(path)
UsdSkel.BindingAPI.Apply(prim)
def undo(self):
if self._usd_undo is not None:
self._usd_undo.undo()
omni.kit.commands.register(ApplySkelBindingAPICommand)
|
omniverse-code/kit/exts/omni.kit.property.skel/omni/kit/property/skel/tests/__init__.py | from .test_skel import *
|
omniverse-code/kit/exts/omni.kit.property.skel/omni/kit/property/skel/tests/test_skel.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
import pathlib
import omni.kit.app
import omni.kit.commands
import omni.kit.test
import omni.ui as ui
from omni.ui.tests.test_base import OmniUiTest
from omni.kit import ui_test
from omni.kit.test_suite.helpers import wait_stage_loading
from pxr import Kind, Sdf, Gf
class TestSkeletonWidget(OmniUiTest):
# Before running each test
async def setUp(self):
await super().setUp()
ext_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
self._golden_img_dir = pathlib.Path(ext_path).joinpath("data/tests/golden_img")
self._usd_path = pathlib.Path(ext_path).joinpath("data/tests/")
from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget
import omni.kit.window.property as p
self._w = p.get_window()
# After running each test
async def tearDown(self):
await super().tearDown()
# Test(s)
async def test_skeleton_ui(self):
usd_context = omni.usd.get_context()
await self.docked_test_window(
window=self._w._window,
width=450,
height=650,
restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"),
restore_position = ui.DockPosition.BOTTOM)
test_file_path = self._usd_path.joinpath("boy_skel.usd").absolute()
await usd_context.open_stage_async(str(test_file_path))
await wait_stage_loading()
# Select the prim.
usd_context.get_selection().set_selected_prim_paths(["/Root/SkelRoot/Head_old"], True)
# Need to wait for an additional frames for omni.ui rebuild to take effect
await ui_test.human_delay(10)
# verify image
await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_skeleton_ui.png")
|
omniverse-code/kit/exts/omni.kit.property.skel/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.0] - 2021-05-31
### Changes
- Created
## [1.0.1] - 2022-01-18
### Changes
- Switch some API from AnimationSchema to RetargetingSchema |
omniverse-code/kit/exts/omni.kit.property.skel/docs/README.md | # omni.kit.property.skel
## Introduction
Property window extensions are for viewing and editing Usd Prim Attributes
## This extension supports editing of these Usd Types;
- UsdSkel.Root
- UsdSkel.Skeleton
- UsdSkel.SkelAnimation
- UsdSkel.BlendShape
### and supports editing of these Usd APIs;
- UsdSkel.BindingAPI
|
omniverse-code/kit/exts/omni.kit.property.skel/docs/index.rst | omni.kit.property.skel
###########################
Property Skeleton Animation Values
.. toctree::
:maxdepth: 1
CHANGELOG
|
omniverse-code/kit/exts/omni.kit.viewport.docs/PACKAGE-LICENSES/omni.kit.viewport.docs-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. |
omniverse-code/kit/exts/omni.kit.viewport.docs/config/extension.toml | [package]
version = "104.0.2"
authors = ["NVIDIA"]
title = "omni.kit Viewport API Documentation"
description="The documentation for the next Viewport API in Kit "
readme = "docs/README.md"
repository = ""
category = "Documentation"
keywords = ["ui", "example", "viewport", "renderer", "docs", "documentation"]
changelog="docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[dependencies]
"omni.ui" = {}
"omni.kit.documentation.builder" = {}
[[python.module]]
name = "omni.kit.viewport.docs"
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--/app/window/width=640",
"--/app/window/height=480",
"--no-window"
]
dependencies = [
"omni.kit.mainwindow",
"omni.kit.ui_test"
]
[documentation]
pages = [
"docs/overview.md",
"docs/camera_manipulator.md",
"docs/capture.md",
"docs/viewport_api.md",
"docs/widget.md",
"docs/window.md",
"docs/CHANGELOG.md",
]
|
omniverse-code/kit/exts/omni.kit.viewport.docs/omni/kit/viewport/docs/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.
#
import omni.ext
from .window import ViewportDocsWindow
__all__ = ["ViewportDocsExtension"]
class ViewportDocsExtension(omni.ext.IExt):
def on_startup(self, ext_id):
self._window = ViewportDocsWindow("Viewport Doc")
def on_shutdown(self):
self._window.destroy()
self._window = None
|
omniverse-code/kit/exts/omni.kit.viewport.docs/omni/kit/viewport/docs/__init__.py | from .extension import ViewportDocsExtension
|
omniverse-code/kit/exts/omni.kit.viewport.docs/omni/kit/viewport/docs/window.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.documentation.builder import DocumentationBuilderWindow
from pathlib import Path
__all__ = ["ViewportDocsWindow"]
class ViewportDocsWindow(DocumentationBuilderWindow):
"""The window with the documentation"""
def __init__(self, title: str, **kwargs):
module_root = Path(__file__).parent
docs_root = module_root.parent.parent.parent.parent.joinpath("docs")
pages = ['overview.md', 'window.md', 'widget.md', 'viewport_api.md', 'capture.md', 'camera_manipulator.md']
filenames = [f'{docs_root.joinpath(page_source)}' for page_source in pages]
super().__init__(title, filenames=filenames, **kwargs)
|
omniverse-code/kit/exts/omni.kit.viewport.docs/omni/kit/viewport/docs/tests/__init__.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
from omni.ui.tests.test_base import OmniUiTest
import omni.kit.ui_test
class TestViewportDocsWindow(OmniUiTest):
async def setUp(self):
await super().setUp()
async def tearDown(self):
await super().tearDown()
async def test_just_opened(self):
win = omni.kit.ui_test.find("Viewport Doc")
self.assertIsNotNone(win)
|
omniverse-code/kit/exts/omni.kit.viewport.docs/docs/camera_manipulator.md | # Camera Manipulator
Mouse interaction with the Viewport is handled with classes from `omni.kit.manipulator.camera`, which is built on top of the `omni.ui.scene` framework.
We've created an `omni.ui.scene.SceneView` to host the manipulator, and by simply assigning the camera manipulators model
into the SceneView's model, all of the edits to the Camera's transform will be pushed through to the `SceneView`.
```
# And finally add the camera-manipulator into that view
with self.__scene_view.scene:
self.__camera_manip = ViewportCameraManipulator(self.viewport_api)
# Push the camera manipulator's model into the SceneView so it'lll auto-update
self.__scene_view.model = self.__camera_manip.model
```
The `omni.ui.scene.SceneView` only understands two values: 'view' and 'projection'. Our CameraManipulator's model will push
out those values as edits are made; however, it supports a larger set of values to control the manipulator itself.
## Operations and Values
The CameraManipulator model store's the amount of movement according to three modes, applied in this order:
1. Tumble
2. Look
3. Move (Pan)
4. Fly (FlightMode / WASD navigation)
### tumble
Tumble values are specified in degrees as the amount to rotate around the current up-axis.
These values should be pre-scaled with any speed before setting into the model.
This allows for different manipulators/gestures to interpret speed differently, rather than lock to a constant speed.
```python
# Tumble by 180 degrees around Y (as a movement across ui X would cause)
model.set_floats('tumble', [0, 180, 0])
```
### look
Look values are specified in degrees as the amount to rotate around the current up-axis.
These values should be pre-scaled with any speed before setting into the model.
This allows for different manipulators/gestures to interpret speed differently, rather than lock to a constant speed.
```python
# Look by 90 degrees around X (as a movement across ui Y would cause)
# i.e Look straight up
model.set_floats('look', [90, 0, 0])
```
### move
Move values are specified in world units and the amount to move the camera by.
Move is applied after rotation, so the X, Y, Z are essentially left, right, back.
These values should be pre-scaled with any speed before setting into the model.
This allows for different manipulators/gestures to interpret speed differently, rather than lock to a constant speed.
```python
# Move left by 30 units, up by 60 and back by 90
model.set_floats('move', [30, 60, 90])
```
### fly
Fly values are the direction of flight in X, Y, Z.
Fly is applied after rotation, so the X, Y, Z are essentially left, right, back.
These values will be scaled with `fly_speed` before aplication.
Because fly is a direction with `fly_speed` automatically applied, if a gesture/manipulator wants to fly slower
without changing `fly_speed` globally, it must apply whatever factor is required before setting.
```python
# Move left
model.set_floats('fly', [1, 0, 0])
# Move up
model.set_floats('fly', [0, 1, 0])
```
## Speed
By default the Camera manipulator will map a full mouse move across the viewport as follows:
- Pan: A full translation of the center-of-interest across the Viewport.
- Tumble: A 180 degree rotation across X or Y.
- Look: A 180 degree rotation across X and a 90 degree rotation across Y.
These speed can be adjusted by setting float values into the model.
### world_speed
The Pan and Zoom speed can be adjusted with three floats set into the model as 'world_speed'.
```python
# Half the movement speed for both Pan and Zoom
pan_speed_x = 0.5, pan_speed_y = 0.5, zoom_speed_z = 0.5
model.set_floats('world_speed', [pan_speed_x, pan_speed_y, zoom_speed_z])
```
### rotation_speed
The Tumble and Look speed can be adjusted with either a scalar value for all rotation axes or per component.
```python
# Half the rotation speed for both Tumble and Look
rot_speed_both = 0.5
model.set_floats('rotation_speed', [rot_speed_both])
# Half the rotation speed for both Tumble and Look in X and quarter if for Y
rot_speed_x = 0.5, rot_speed_y = 0.25
model.set_floats('rotation_speed', [rot_speed_x, rot_speed_y])
```
### tumble_speed
Tumble can be adjusted separately with either a scalar value for all rotation axes or per component.
The final speed of Tumble operation is `rotation_speed * tumble_speed`
```python
# Half the rotation speed for Tumble
rot_speed_both = 0.5
model.set_floats('tumble_speed', [rot_speed_both])
# Half the rotation speed for Tumble in X and quarter if for Y
rot_speed_x = 0.5, rot_speed_y = 0.25
model.set_floats('tumble_speed', [rot_speed_x, rot_speed_y])
```
### look_speed
Look can be adjusted separately with either a scalar value for all rotation axes or per component.
The final speed of a Look operation is `rotation_speed * tumble_speed`
```python
# Half the rotation speed for Look
rot_speed_both = 0.5
model.set_floats('look_speed', [rot_speed_both])
# Half the rotation speed for Tumble in X and quarter if for Y
rot_speed_x = 0.5, rot_speed_y = 0.25
model.set_floats('look_speed', [rot_speed_x, rot_speed_y])
```
### fly_speed
The speed at which FlightMode (WASD navigation) will fly through the scene.
FlightMode speed can be adjusted separately with either a scalar value for all axes or per component.
```python
# Half the speed in all directions
fly_speed = 0.5
model.set_floats('fly_speed', [fly_speed])
# Half the speed when moving in X or Y, but double it moving in Z
fly_speed_x_y = 0.5, fly_speed_z = 2
model.set_floats('fly_speed', [fly_speed_x_y, fly_speed_x_y, fly_speed_z])
```
## Undo
Because we're operating on a unique `omni.usd.UsdContext` we don't want movement in the preview-window to affect the undo-stack.
To accomplish that, we'll set the 'disable_undo' value to an array of 1 int; essentially saying `disable_undo=True`.
```python
# Let's disable any undo for these movements as we're a preview-window
model.set_ints('disable_undo', [1])
```
## Disabling operations
By default the manipulator will allow Pan, Zoom, Tumble, and Look operations on a perspective camera, but only allow
Pan and Zoom on an orthographic one. If we want to explicitly disable any operations again we set int values as booleans
into the model.
### disable_tumble
```python
# Disable the Tumble manipulation
model.set_ints('disable_tumble', [1])
```
### disable_look
```python
# Disable the Look manipulation
model.set_ints('disable_look', [1])
```
### disable_pan
```python
# Disable the Pan manipulation.
model.set_ints('disable_pan', [1])
```
### disable_zoom
```python
# Disable the Zoom manipulation.
model.set_ints('disable_zoom', [1])
```
|
omniverse-code/kit/exts/omni.kit.viewport.docs/docs/widget.md | # Stage Preview Widget
The `StagePreviewWidget` is comprised of a few `omni.ui` objects which are stacked on top of one-another.
So first an `omni.ui.ZStack` container is instantiated and using the `omni.ui` with syntax, the remaining objects
are created in its scope:
```python
self.__ui_container = ui.ZStack()
with self.__ui_container:
```
## Background
First we create an `omni.ui.Rectangle` that will fill the entire frame with a constant color, using black as the default.
We add a few additional style arguments so that the background color can be controlled easily from calling code.
```python
# Add a background Rectangle that is black by default, but can change with a set_style
ui.Rectangle(style_type_name_override='ViewportBackgroundColor', style={'ViewportBackgroundColor': {'background_color': 0xff000000}})
```
## ViewportWidget
Next the `omni.kit.widget.viewport.ViewportWidget` is created, directly above the background Rectangle.
In the `stage_preview` example, the `ViewportWidget` is actually created to always fill the parent frame by
passing `resolution='fill_frame'`, which will essentially make it so the black background never seen.
If a constant resolution was requested by passing a tuple `resolution=(640, 480)`; however, the rendered image would be
locked to that resolution and causing the background rect to be seen if the Widget was wider or taller than the texture's
resolution.
```python
self.__vp_widget = ViewportWidget(usd_context_name=usd_context_name, camera_path=camera_path, resolution=resolution, *ui_args, **ui_kw_args)
```
## SceneView
The final `omni.ui` element we are going to create is an `omni.ui.scene.SceneView`. We are creating it primarily to
host our camera-manipulators which are written for the `omni.ui.scene` framework, but it could also be used to insert
additional drawing on top of the `ViewportWidget` in 3D space.
```python
# Add the omni.ui.scene.SceneView that is going to host the camera-manipulator
self.__scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.STRETCH)
# And finally add the camera-manipulator into that view
with self.__scene_view.scene:
```
## Full code
```python
class StagePreviewWidget:
def __init__(self, usd_context_name: str = '', camera_path: str = None, resolution: Union[tuple, str] = None, *ui_args ,**ui_kw_args):
"""StagePreviewWidget contructor
Args:
usd_context_name (str): The name of a UsdContext the Viewport will be viewing.
camera_path (str): The path of the initial camera to render to.
resolution (x, y): The resolution of the backing texture, or 'fill_frame' to match the widget's ui-size
*ui_args, **ui_kw_args: Additional arguments to pass to the ViewportWidget's parent frame
"""
# Put the Viewport in a ZStack so that a background rectangle can be added underneath
self.__ui_container = ui.ZStack()
with self.__ui_container:
# Add a background Rectangle that is black by default, but can change with a set_style
ui.Rectangle(style_type_name_override='ViewportBackgroundColor', style={'ViewportBackgroundColor': {'background_color': 0xff000000}})
# Create the ViewportWidget, forwarding all of the arguments to this constructor
self.__vp_widget = ViewportWidget(usd_context_name=usd_context_name, camera_path=camera_path, resolution=resolution, *ui_args, **ui_kw_args)
# Add the omni.ui.scene.SceneView that is going to host the camera-manipulator
self.__scene_view = sc.SceneView(aspect_ratio_policy=sc.AspectRatioPolicy.STRETCH)
# And finally add the camera-manipulator into that view
with self.__scene_view.scene:
self.__camera_manip = ViewportCameraManipulator(self.viewport_api)
model = self.__camera_manip.model
# Let's disable any undo for these movements as we're a preview-window
model.set_ints('disable_undo', [1])
# We'll also let the Viewport automatically push view and projection changes into our scene-view
self.viewport_api.add_scene_view(self.__scene_view)
def __del__(self):
self.destroy()
def destroy(self):
self.__view_change_sub = None
if self.__camera_manip:
self.__camera_manip.destroy()
self.__camera_manip = None
if self.__scene_view:
self.__scene_view.destroy()
self.__scene_view = None
if self.__vp_widget:
self.__vp_widget.destroy()
self.__vp_widget = None
if self.__ui_container:
self.__ui_container.destroy()
self.__ui_container = None
@property
def viewport_api(self):
# Access to the underying ViewportAPI object to control renderer, resolution
return self.__vp_widget.viewport_api
@property
def scene_view(self):
# Access to the omni.ui.scene.SceneView
return self.__scene_view
def set_style(self, *args, **kwargs):
# Give some styling access
self.__ui_container.set_style(*args, **kwargs)
```
|
omniverse-code/kit/exts/omni.kit.viewport.docs/docs/CHANGELOG.md | # Changelog
Documentation for the next Viewport
## [104.0.2] - 2022-05-04
### Changed
- Imported to kit repro and bump version to match Kit SDK
## [1.0.2] - 2022-02-09
### Changed
- Updated documentation to include latest changes and Viewport capturing
## [1.0.1] - 2021-12-22
### Changed
- Add documentation for add_scene_view and remove_scene_view methods.
## [1.0.0] - 2021-12-20
### Changed
- Initial release
|
omniverse-code/kit/exts/omni.kit.viewport.docs/docs/overview.md | # Overview
Viewport Next is a preview of the next generation of Kit's Viewport. It was
designed to be as light as possible, providing a way to isolate features and
compose them as needed to create unique experiences.
This documentation will walk through a few simple examples using this technology,
as well as how it can be used in tandem with the `omni.ui.scene` framework.
## What is a Viewport
Exactly what a viewport is can be a bit ill-defined and dependent on what you are
trying to accomplish, so it's best to define some terms up front and explain what
this documentation is targeting.

At a very high level a Viewport is a way for a user to visualize (and often
interact with) a Renderer's output of a scene. When you create a "Viewport Next"
instance via Kit's Window menu, you are actually creating a hierarchy of objects.

The three objects of interest in this hierarchy are:
1. The `ViewportWindow`, which we will be re-implementing as `StagePreviewWindow`
2. The `ViewportWidget`, one of which we will be instantiating.
3. The `ViewportTexture`, which is created and owned by the `ViewportWidget`.
While we will be using (or re-implementing) all three of those objects, this documentation is primarily
targeted towards understanding the `ViewportWidget` and it's usage in the `omni.kit.viewport.stage_preview`.
After creating a Window and instance of a `ViewportWidget`, we will finally add a camera manipulator built
with `omni.ui.scene` to interact with the `Usd.Stage`, as well as control aspects of the
Renderer's output to the underlying `ViewportTexture`.
Even though the `ViewportWidget` is our main focus, it is good to understand the backing `ViewportTexture` is independent
of the `ViewportWidget`, and that a texture's resolution may not neccessarily match the size of the `ViewportWidget`
it is contained in. This is particularly import for world-space queries or other advanced usage.
## Enabling the extension
To enable the extension and open a "Viewport Next" window, go to the "Extensions" tab
and enable the "Viewport Window" extension (`omni.kit.viewport.window`).

## Simplest example
The `omni.kit.viewport.stage_preview` adds additional features that make may make a first read of the code a bit harder.
So before stepping through that example, lets take a moment to reduce it to an even simpler case where we create
a single Window and add only a Viewport which is tied to the default `UsdContext` and `Usd.Stage`.
We won't be able to interact with the Viewport other than through Python, but because we are associated with the
default `UsdContext`: any changes in the `Usd.Stage` (from navigation or editing in another Viewport or adding a `Usd.Prim`
from the Create menu) will be reflected in our new view.
```python
from omni.kit.widget.viewport import ViewportWidget
viewport_window = omni.ui.Window('SimpleViewport', width=1280, height=720+20) # Add 20 for the title-bar
with viewport_window.frame:
viewport_widget = ViewportWidget(resolution = (1280, 720))
# Control of the ViewportTexture happens through the object held in the viewport_api property
viewport_api = viewport_widget.viewport_api
# We can reduce the resolution of the render easily
viewport_api.resolution = (640, 480)
# We can also switch to a different camera if we know the path to one that exists
viewport_api.camera_path = '/World/Camera'
# And inspect
print(viewport_api.projection)
print(viewport_api.transform)
# Don't forget to destroy the objects when done with them
# viewport_widget.destroy()
# viewport_window.destroy()
# viewport_window, viewport_widget = None, None
```

|
omniverse-code/kit/exts/omni.kit.viewport.docs/docs/window.md | # Stage Preview Window
In order to display the Renderer's output, we'll need to have an `omni.ui.window`
that will host our widget. We're interested in this level primarily to demonstrate the
ability to create a `ViewportWidget` that isn't tied to the application's main `UsdContext`;
rather you can provide a usd_context_name string argument and the `StagePreviewWindow` will
either reuse an existing `UsdContext` with that name, or create a new one.
Keep in mind a `ViewportWidget` is currently tied to exactly one `UsdContext` for its lifetime.
If you wanted to change the `UsdContext` you are viewing, you would need to hide and show a new `ViewportWidget` based
on which context you want to be displayed.

## Context creation
The first step we take is to check whether the named `UsdContext` exists, and if not, create it.
```python
# We may be given an already valid context, or we'll be creating and managing it ourselves
usd_context = omni.usd.get_context(usd_context_name)
if not usd_context:
self.__usd_context_name = usd_context_name
self.__usd_context = omni.usd.create_context(usd_context_name)
else:
self.__usd_context_name = None
self.__usd_context = None
```
## Viewport creation
Once we know a valid context with usd_context_name exists, we create the `omni.ui.Window` passing along
the window size and window flags. The `omni.ui` documentation has more in depth description of what an `omni.ui.Window`
is and the arguments for it's creation.
After the `omni.ui.Window` has been created, we'll finally be able to create the `StagePreviewWidget`, passing along
the `usd_context_name`. We do this within the context of the `omni.ui.Window.frame` property, and forward any
additional arguments to the `StagePreviewWidget` constructor.
```python
super().__init__(title, width=window_width, height=window_height, flags=flags)
with self.frame:
self.__preview_viewport = StagePreviewWidget(usd_context_name, *vp_args, **vp_kw_args)
```
## Full code
```python
class StagePreviewWindow(ui.Window):
def __init__(self, title: str, usd_context_name: str = '', window_width: int = 1280, window_height: int = 720 + 20, flags: int = ui.WINDOW_FLAGS_NO_SCROLLBAR, *vp_args, **vp_kw_args):
"""StagePreviewWindow contructor
Args:
title (str): The name of the Window.
usd_context_name (str): The name of a UsdContext this Viewport will be viewing.
window_width(int): The width of the Window.
window_height(int): The height of the Window.
flags(int): ui.WINDOW flags to use for the Window.
*vp_args, **vp_kw_args: Additional arguments to pass to the StagePreviewWidget
"""
# We may be given an already valid context, or we'll be creating and managing it ourselves
usd_context = omni.usd.get_context(usd_context_name)
if not usd_context:
self.__usd_context_name = usd_context_name
self.__usd_context = omni.usd.create_context(usd_context_name)
else:
self.__usd_context_name = None
self.__usd_context = None
super().__init__(title, width=window_width, height=window_height, flags=flags)
with self.frame:
self.__preview_viewport = StagePreviewWidget(usd_context_name, *vp_args, **vp_kw_args)
def __del__(self):
self.destroy()
@property
def preview_viewport(self):
return self.__preview_viewport
def open_stage(self, file_path: str):
# Reach into the StagePreviewWidget and get the viewport where we can retrieve the usd_context or usd_context_name
self.__preview_viewport.viewport_api.usd_context.open_stage(file_path)
# the Viewport doesn't have any idea of omni.ui.scene so give the models a sync after open (camera may have changed)
self.__preview_viewport.sync_models()
def destroy(self):
if self.__preview_viewport:
self.__preview_viewport.destroy()
self.__preview_viewport = None
if self.__usd_context:
# We can't fully tear down everything yet, so just clear out any active stage
self.__usd_context.remove_all_hydra_engines()
# self.__usd_context = None
# omni.usd.destroy_context(self.__usd_context_name)
super().destroy()
```
|
omniverse-code/kit/exts/omni.kit.viewport.docs/docs/viewport_api.md | # Viewport API
The ViewportAPI object is used to access and control aspects of the render, who will then push images into the backing texture.
It is accessed via the `ViewportWidget.viewport_api` property which returns a Python `weakref.proxy` object.
The use of a weakref is done in order to make sure that a Renderer and Texture aren't kept alive because client code
is keeping a reference to one of these objects. That is: the lifetime of a Viewport is controlled by the creator of the Viewport and
cannot be extended beyond the usage they expect.
With our simple `omni.kit.viewport.stage_preview` example, we'll now run through some cases of directly controlling the render,
similar to what the Content context-menu does.
```python
from omni.kit.viewport.stage_preview.window import StagePreviewWindow
# Viewport widget can be setup to fill the frame with 'fill_frame', or to a constant resolution (x, y).
resolution = 'fill_frame' or (640, 480) # Will use 'fill_frame'
# Give the Window a unique name, the window-size, and forward the resolution to the Viewport itself
preview_window = StagePreviewWindow('My Stage Preview', usd_context_name='MyStagePreviewWindowContext',
window_width=640, window_height=480, resolution=resolution)
# Open a USD file in the UsdContext that the preview_window is using
preview_window.open_stage('http://omniverse-content-production.s3-us-west-2.amazonaws.com/Samples/Astronaut/Astronaut.usd')
# Save an easy-to-use reference to the ViewportAPI object
viewport_api = preview_window.preview_viewport.viewport_api
```
## Camera
The camera being used to render the image is controlled with the `camera_path` property.
It will return and is settable with a an `Sdf.Path`.
The property will also accept a string, but it is slightly more efficient to set with an `Sdf.Path` if you have one available.
```python
print(viewport_api.camera_path)
# => '/Root/LongView'
# Change the camera to view through the implicit Top camera
viewport_api.camera_path = '/OmniverseKit_Front'
# Change the camera to view through the implicit Perspective camera
viewport_api.camera_path = '/OmniverseKit_Persp'
```
## Filling the canvas
Control whether the texture-resolution should be adjusted based on the parent objects ui-size with the `fill_frame` property.
It will return and is settable with a bool.
```python
print('viewport_api.fill_frame)
# => True
# Disable the automatic resolution
viewport_api.fill_frame = False
# And give it an explicit resolution
viewport_api.resolution = (640, 480)
```
## Resolution
Resolution of the underlying `ViewportTexture` can be queried and set via the `resolution` property.
It will return and is settable with a tuple representing the (x, y) resolution of the rendered image.
```python
print(viewport_api.resolution)
# => (640, 480)
# Change the render output resolution to a 512 x 512 texture
viewport_api.resolution = (512, 512)
```
## SceneView
For simplicity, the ViewportAPI can push both view and projection matrices into an `omni.ui.scene.SceneView.model`.
The use of these methods are not required, rather provided a convenient way to
auto-manage their relationship (particularly for stage independent camera, resolution, and widget size changes),
while also providing room for future expansion where a `SceneView` may be locked
to last delivered rendered frame versus the current implementation that pushes changes
into the Renderer and the `SceneView` simultaneously.
### add_scene_view
Add an `omni.ui.scene.SceneView` to the list of models that the Viewport will notify with changes to view and projection matrices.
The Viewport will only retain a weak-reference to the provided `SceneView` to avoid extending the lifetime of the `SceneView` itself.
A `remove_scene_view` is available if the need to dynamically change the list of models to be notified is necessary.
```python
scene_view = omni.ui.scene.SceneView()
# Pass the real object, as a weak-reference will be retained
viewport_api.add_scene_view(scene_view)
```
### remove_scene_view
Remove the `omni.ui.scene.SceneView` from the list of models that the Viewport will notify from changes to view and projection matrices.
Because the Viewport only retains a weak-reference to the `SceneView`, calling this explicitly isn't mandatory, but can be
used to dynamically change the list of `SceneView` objects whose model should be updated.
```python
viewport_api.remove_scene_view(scene_view)
```
## Additional Accessors
The `ViewportAPI` provides a few additional read-only accessors for convenience:
### usd_context_name
```python
viewport_api.usd_context_name => str
# Returns the name of the UsdContext the Viewport is bound to.
```
### usd_context
```python
viewport_api.usd_context => omni.usd.UsdContext
# Returns the actual UsdContext the Viewport is bound to, essentially `omni.usd.get_context(self.usd_context_name)`.
```
### stage
```python
viewport_api.stage => Usd.Stage
# Returns the `Usd.Stage` the ViewportAPI is bound to, essentially: `omni.usd.get_context(self.usd_context_name).get_stage()`.
```
### projection
```python
viewport_api.projection=> Gf.Matrix4d
# Returns the Gf.Matrix4d of the projection. This may differ than the projection of the `Usd.Camera` based on how the Viewport is placed in the parent widget.
```
### transform
```python
viewport_api.transform => Gf.Matrix4d
# Return the Gf.Matrix4d of the transform for the `Usd.Camera` in world-space.
```
### view
```python
viewport_api.view => Gf.Matrix4d
# Return the Gf.Matrix4d of the inverse-transform for the `Usd.Camera` in world-space.
```
### time
```python
viewport_api.time => Usd.TimeCode
# Return the Usd.TimeCode that the Viewport is using.
```
## Space Mapping
The `ViewportAPI` natively uses NDC coordinates to interop with the payloads from `omni.ui.scene` gestures.
To understand where these coordinates are in 3D-space for the `ViewportTexture`, two properties will
can be used to get a `Gf.Matrix4d` to convert to and from NDC-space to World-space.
```python
origin = (0, 0, 0)
origin_screen = viewport_api.world_to_ndc.Transform(origin)
print('Origin is at {origin_screen}, in screen-space')
origin = viewport_api.ndc_to_world.Transform(origin_screen)
print('Converted back to world-space, origin is {origin}')
```
### world_to_ndc
```python
viewport_api.world_to_ndc => Gf.Matrix4d
# Returns a Gf.Matrix4d to move from World/Scene space into NDC space
```
### ndc_to_world
```python
viewport_api.ndc_to_world => Gf.Matrix4d
# Returns a Gf.Matrix4d to move from NDC space into World/Scene space
```
## World queries
While it is useful being able to move through these spaces is useful, for the most part what we'll be more interested
in using this to inspect the scene that is being rendered. What that means is that we'll need to move from an NDC coordinate
into pixel-space of our rendered image.
A quick breakdown of the three spaces in use:
The native NDC space that works with `omni.ui.scene` gestures can be thought of as a cartesian space centered on the rendered image.

We can easily move to a 0.0 - 1.0 uv space on the rendered image.

And finally expand that 0.0 - 1.0 uv space into pixel space.

Now that we know how to map between the ui and texture space, we can use it to convert between screen and 3D-space.
More importantly, we can use it to actually query the backing `ViewportTexture` about objects and locations in the scene.
### request_query
```python
viewport_api.request_query(pixel_coordinate: (x, y), query_completed: callable) => None
# Query a pixel co-ordinate with a callback to be executed when the query completes
# Get the mouse position from within an omni.ui.scene gesture
mouse_ndc = self.sender.gesture_payload.mouse
# Convert the ndc-mouse to pixel-space in our ViewportTexture
mouse, in_viewport = viewport_api.map_ndc_to_texture_pixel(mouse_ndc)
# We know immediately if the mapping is outside the ViewportTexture
if not in_viewport:
return
# Inside the ViewportTexture, create a callback and query the 3D world
def query_completed(path, pos, *args):
if not path:
print('No object')
else:
print(f"Object '{path}' hit at {pos}")
viewport_api.request_query(mouse, query_completed)
```
## Asynchronous waiting
Some properties and API calls of the Viewport won't take effect immediately after control-flow has returned to the caller.
For example, setting the camera-path or resolution won't immediately deliver frames from that Camera at the new resolution.
There are two methods available to asynchrnously wait for the changes to make their way through the pipeline.
### wait_for_render_settings_change
Asynchronously wait until a render-settings change has been ansorbed by the backend.
This can be useful after changing the camera, resolution, or render-product.
```python
my_custom_product = '/Render/CutomRenderProduct'
viewport_api.render_product_path = my_custom_product
settings_changed = await viewport_api.wait_for_render_settings_change()
print('settings_changed', settings_changed)
```
### wait_for_rendered_frames
Asynchronously wait until a number of frames have been delivered.
Default behavior is to wait for deivery of 1 frame, but the function accepts an optional argument for an additional number of frames to wait on.
```python
await viewport_api.wait_for_rendered_frames(10)
print('Waited for 10 frames')
```
## Capturing Viewport frames
To access the state of the Viewport's next frame and any AOVs it may be rendering, you can schedule a capture with the `schedule_capture` method.
There are a variety of default Capturing delegates in the `omni.kit.widget.viewport.capture` that can handle writing to disk or accesing the AOV's buffer.
Because capture is asynchronous, it will likely not have occured when control-flow has returned to the caller of `schedule_capture`.
To wait until it has completed, the returned object has a `wait_for_result` method that can be used.
### schedule_capture
```python
viewport_api.schedule_capture(capture_delegate: Capture): -> Capture
```
```python
from omni.kit.widget.viewport.capture import FileCapture
capture = viewport_api.schedule_capture(FileCapture(image_path))
captured_aovs = await capture.wait_for_result()
if captured_aovs:
print(f'AOV "{captured_aovs[0]}" was written to "{image_path}"')
else:
print(f'No image was written to "{image_path}"')
```
|
omniverse-code/kit/exts/omni.kit.viewport.docs/docs/capture.md | # Capture
`omni.kit.widget.viewport.capture` is the interface to a capture a Viewport's state and AOVs.
It provides a few convenient implementations that will write AOV(s) to disk or pass CPU buffers for pixel access.
## FileCapture
A simple delegate to capture a single AOV to a single file.
It can be used as is, or subclassed to access additional information/meta-data to be written.
By default it will capture a color AOV, but accepts an explicit AOV-name to capture instead.
```python
from omni.kit.widget.viewport.capture import FileCapture
capture = viewport_api.schedule_capture(FileCapture(image_path))
captured_aovs = await capture.wait_for_result()
if captured_aovs:
print(f'AOV "{captured_aovs[0]}" was written to "{image_path}"')
else:
print(f'No image was written to "{image_path}"')
```
A sample subclass implementation to write additional data.
```python
from omni.kit.widget.viewport.capture import FileCapture
SideCarWriter(FileCapture):
def __init__(self, image_path, aov_name=''):
super().__init__(image_path, aov_name)
def capture_aov(self, file_path, aov):
# Call the default file-saver
self.save_aov_to_file(file_path, aov)
# Possibly append data to a custom image
print(f'Wrote AOV "{aov['name']}" to "{file_path}")
print(f' with view: {self.view}")
print(f' with projection: {self.projection}")
capture = viewport_api.schedule_capture(SideCarWriter(image_path))
captured_aovs = await capture.wait_for_result()
if captured_aovs:
print(f'AOV "{captured_aovs[0]}" was written to "{image_path}"')
else:
print(f'No image was written to "{image_path}"')
```
## ByteCapture
A simple delegate to capture a single AOV and deliver it as CPU pixel data.
It can be used as is with a free-standing function, or subclassed to access additional information/meta-data.
By default it will capture a color AOV, but accepts an explicit AOV-name to capture instead.
```python
from omni.kit.widget.viewport.capture import ByteCapture
def on_capture_completed(buffer, buffer_size, width, height, format):
print(f'PixelData resolution: {width} x {height}')
print(f'PixelData format: {format}')
capture = viewport_api.schedule_capture(ByteCapture(on_capture_completed))
captured_aovs = await capture.wait_for_result()
if captured_aovs:
print(f'AOV "{captured_aovs[0]}" was written to "{image_path}"')
print(f'It had a camera view of {capture.view}')
else:
print(f'No image was written to "{image_path}"')
```
A sample subclass implementation to write additional data.
```python
from omni.kit.widget.viewport.capture import ByteCapture
SideCarData(ByteCapture):
def __init__(self, image_path, aov_name=''):
super().__init__(image_path, aov_name)
def on_capture_completed(self, buffer, buffer_size, width, height, format):
print(f'PixelData resolution: {width} x {height}')
print(f'PixelData format: {format}')
print(f'PixelData has a camera view of {self.view}')
capture = viewport_api.schedule_capture(SideCarData(image_path))
captured_aovs = await capture.wait_for_result()
if captured_aovs:
print(f'AOV "{captured_aovs[0]}" was written to "{image_path}"')
else:
print(f'No image was written to "{image_path}"')
```
|
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/__init__.py | from .scripts import *
|
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/scripts/create_actions.py | import omni.usd
import omni.kit.actions.core
from pxr import Usd, UsdGeom, UsdLux, OmniAudioSchema
def get_action_name(name):
return name.lower().replace('-', '_').replace(' ', '_')
def get_geometry_standard_prim_list(usd_context=None):
if not usd_context:
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
if stage:
meters_per_unit = UsdGeom.GetStageMetersPerUnit(stage)
else:
meters_per_unit = 0.01
geom_base = 0.5 / meters_per_unit
geom_base_double = geom_base * 2
geom_base_half = geom_base / 2
all_shapes = sorted([
(
"Cube",
{
UsdGeom.Tokens.size: geom_base_double,
UsdGeom.Tokens.extent: [(-geom_base, -geom_base, -geom_base), (geom_base, geom_base, geom_base)],
},
),
(
"Sphere",
{
UsdGeom.Tokens.radius: geom_base,
UsdGeom.Tokens.extent: [(-geom_base, -geom_base, -geom_base), (geom_base, geom_base, geom_base)],
},
),
(
"Cylinder",
{
UsdGeom.Tokens.radius: geom_base,
UsdGeom.Tokens.height: geom_base_double,
UsdGeom.Tokens.extent: [(-geom_base, -geom_base, -geom_base), (geom_base, geom_base, geom_base)],
},
),
(
"Capsule",
{
UsdGeom.Tokens.radius: geom_base_half,
UsdGeom.Tokens.height: geom_base,
# Create extent with command dynamically since it's different in different up-axis.
},
),
(
"Cone",
{
UsdGeom.Tokens.radius: geom_base,
UsdGeom.Tokens.height: geom_base_double,
UsdGeom.Tokens.extent: [(-geom_base, -geom_base, -geom_base), (geom_base, geom_base, geom_base)],
},
),
])
shape_attrs = {}
for name, attrs in all_shapes:
shape_attrs[name] = attrs
return shape_attrs
def get_audio_prim_list():
return [
("Spatial Sound", "OmniSound", {}),
(
"Non-Spatial Sound",
"OmniSound",
{OmniAudioSchema.Tokens.auralMode: OmniAudioSchema.Tokens.nonSpatial}
),
("Listener", "OmniListener", {})
]
def get_light_prim_list(usd_context=None):
if not usd_context:
usd_context = omni.usd.get_context()
stage = usd_context.get_stage()
if stage:
meters_per_unit = UsdGeom.GetStageMetersPerUnit(stage)
else:
meters_per_unit = 0.01
geom_base = 0.5 / meters_per_unit
geom_base_double = geom_base * 2
# https://github.com/PixarAnimationStudios/USD/commit/b5d3809c943950cd3ff6be0467858a3297df0bb7
if hasattr(UsdLux.Tokens, 'inputsIntensity'):
return sorted([
("Distant Light", "DistantLight", {UsdLux.Tokens.inputsAngle: 1.0, UsdLux.Tokens.inputsIntensity: 3000}),
("Sphere Light", "SphereLight", {UsdLux.Tokens.inputsRadius: geom_base, UsdLux.Tokens.inputsIntensity: 30000}),
(
"Rect Light",
"RectLight",
{
UsdLux.Tokens.inputsWidth: geom_base_double,
UsdLux.Tokens.inputsHeight: geom_base_double,
UsdLux.Tokens.inputsIntensity: 15000,
},
),
("Disk Light", "DiskLight", {UsdLux.Tokens.inputsRadius: geom_base, UsdLux.Tokens.inputsIntensity: 60000}),
(
"Cylinder Light",
"CylinderLight",
{UsdLux.Tokens.inputsLength: geom_base_double, UsdLux.Tokens.inputsRadius: 5, UsdLux.Tokens.inputsIntensity: 30000},
),
(
"Dome Light",
"DomeLight",
{UsdLux.Tokens.inputsIntensity: 1000, UsdLux.Tokens.inputsTextureFormat: UsdLux.Tokens.latlong},
),
])
return sorted([
("Distant Light", "DistantLight", {UsdLux.Tokens.angle: 1.0, UsdLux.Tokens.intensity: 3000}),
("Sphere Light", "SphereLight", {UsdLux.Tokens.radius: geom_base, UsdLux.Tokens.intensity: 30000}),
(
"Rect Light",
"RectLight",
{
UsdLux.Tokens.width: geom_base_double,
UsdLux.Tokens.height: geom_base_double,
UsdLux.Tokens.intensity: 15000,
},
),
("Disk Light", "DiskLight", {UsdLux.Tokens.radius: geom_base, UsdLux.Tokens.intensity: 60000}),
(
"Cylinder Light",
"CylinderLight",
{UsdLux.Tokens.length: geom_base_double, UsdLux.Tokens.radius: 5, UsdLux.Tokens.intensity: 30000},
),
(
"Dome Light",
"DomeLight",
{UsdLux.Tokens.intensity: 1000, UsdLux.Tokens.textureFormat: UsdLux.Tokens.latlong},
),
])
def register_actions(extension_id, cls, get_self_fn):
actions_tag = "Create Menu Actions"
# actions
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
"create_prim",
cls.on_create_prim,
display_name="Create->Create Prim",
description="Create Prim",
tag=actions_tag
)
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
"create_prim_camera",
lambda: cls.on_create_prim("Camera", {}),
display_name="Create->Create Camera Prim",
description="Create Camera Prim",
tag=actions_tag
)
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
"create_prim_scope",
lambda: cls.on_create_prim("Scope", {}),
display_name="Create->Create Scope",
description="Create Scope",
tag=actions_tag
)
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
"create_prim_xform",
lambda: cls.on_create_prim("Xform", {}),
display_name="Create->Create Xform",
description="Create Xform",
tag=actions_tag
)
def on_create_shape(shape_name):
shape_attrs = get_geometry_standard_prim_list()
cls.on_create_prim(shape_name, shape_attrs[shape_name])
for prim in get_geometry_standard_prim_list().keys():
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
f"create_prim_{prim.lower()}",
lambda p=prim: on_create_shape(p),
display_name=f"Create->Create Prim {prim}",
description=f"Create Prim {prim}",
tag=actions_tag
)
for name, prim, attrs in get_light_prim_list():
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
f"create_prim_{get_action_name(name)}",
lambda p=prim, a=attrs: cls.on_create_light(p, a),
display_name=f"Create->Create Prim {name}",
description=f"Create Prim {name}",
tag=actions_tag
)
for name, prim, attrs in get_audio_prim_list():
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
f"create_prim_{get_action_name(name)}",
lambda p=prim, a=attrs: cls.on_create_prim(p, a),
display_name=f"Create->Create Prim {name}",
description=f"Create Prim {name}",
tag=actions_tag
)
omni.kit.actions.core.get_action_registry().register_action(
extension_id,
"high_quality_option_toggle",
get_self_fn()._high_quality_option_toggle,
display_name="Create->High Quality Option Toggle",
description="Create High Quality Option Toggle",
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)
|
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/scripts/__init__.py | from .create import *
|
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/scripts/create.py | import os
import functools
import carb.input
import omni.ext
import omni.kit.ui
import omni.kit.menu.utils
from functools import partial
from omni.kit.menu.utils import MenuItemDescription, MenuItemOrder
from .create_actions import register_actions, deregister_actions, get_action_name, get_geometry_standard_prim_list, get_audio_prim_list, get_light_prim_list
_extension_instance = None
_extension_path = None
PERSISTENT_SETTINGS_PREFIX = "/persistent"
class CreateMenuExtension(omni.ext.IExt):
def __init__(self):
super().__init__()
omni.kit.menu.utils.set_default_menu_proirity("Create", -8)
def on_startup(self, ext_id):
global _extension_instance
_extension_instance = self
global _extension_path
_extension_path = omni.kit.app.get_app_interface().get_extension_manager().get_extension_path(ext_id)
self._settings = carb.settings.get_settings()
self._settings.set_default_bool(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality", True)
self._create_menu_list = None
self._build_create_menu()
self._ext_name = omni.ext.get_extension_name(ext_id)
register_actions(self._ext_name, CreateMenuExtension, lambda: _extension_instance)
def on_shutdown(self):
global _extension_instance
deregister_actions(self._ext_name)
_extension_instance = None
omni.kit.menu.utils.remove_menu_items(self._create_menu_list, "Create")
def _rebuild_menus(self):
omni.kit.menu.utils.remove_menu_items(self._create_menu_list, "Create")
self._build_create_menu()
def _high_quality_option_toggle(self):
enabled = self._settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality")
self._settings.set(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality", not enabled)
def _build_create_menu(self):
def is_create_type_enabled(type: str):
settings = carb.settings.get_settings()
if type == "Shape":
if settings.get("/app/primCreation/hideShapes") == True or \
settings.get("/app/primCreation/enableMenuShape") == False:
return False
return True
enabled = settings.get(f"/app/primCreation/enableMenu{type}")
if enabled == True or enabled == False:
return enabled
return True
# setup menus
self._create_menu_list = []
# Shapes
if is_create_type_enabled("Shape"):
sub_menu = []
for prim in get_geometry_standard_prim_list().keys():
sub_menu.append(
MenuItemDescription(name=prim, onclick_action=("omni.kit.menu.create", f"create_prim_{prim.lower()}"))
)
def on_high_quality_option_select():
enabled = self._settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality")
self._settings.set(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality", not enabled)
def on_high_quality_option_checked():
enabled = self._settings.get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality")
return enabled
sub_menu.append(MenuItemDescription())
sub_menu.append(
MenuItemDescription(
name="High Quality",
onclick_action=("omni.kit.menu.create", "high_quality_option_toggle"),
ticked_fn=lambda: on_high_quality_option_checked()
)
)
self._create_menu_list.append(
MenuItemDescription(name="Shape", glyph="menu_prim.svg", appear_after=["Mesh", MenuItemOrder.FIRST], sub_menu=sub_menu)
)
# Lights
if is_create_type_enabled("Light"):
sub_menu = []
for name, prim, attrs in get_light_prim_list():
sub_menu.append(
MenuItemDescription(name=name, onclick_action=("omni.kit.menu.create", f"create_prim_{get_action_name(name)}")
)
)
if is_create_type_enabled("Shape"):
appear_after="Shape"
else:
appear_after="Mesh"
self._create_menu_list.append(
MenuItemDescription(name="Light", glyph="menu_light.svg", appear_after=appear_after, sub_menu=sub_menu)
)
# Audio
if is_create_type_enabled("Audio"):
sub_menu = []
for name, prim, attrs in get_audio_prim_list():
sub_menu.append(
MenuItemDescription(
name=name, onclick_action=("omni.kit.menu.create", f"create_prim_{get_action_name(name)}")
)
)
self._create_menu_list.append(
MenuItemDescription(name="Audio", glyph="menu_audio.svg", appear_after="Light", sub_menu=sub_menu)
)
# Camera
if is_create_type_enabled("Camera"):
self._create_menu_list.append(
MenuItemDescription(
name="Camera",
glyph="menu_camera.svg",
appear_after="Audio",
onclick_action=("omni.kit.menu.create", "create_prim_camera"),
)
)
# Scope
if is_create_type_enabled("Scope"):
self._create_menu_list.append(
MenuItemDescription(
name="Scope",
glyph="menu_scope.svg",
appear_after="Camera",
onclick_action=("omni.kit.menu.create", "create_prim_scope"),
)
)
# Xform
if is_create_type_enabled("Xform"):
self._create_menu_list.append(
MenuItemDescription(
name="Xform",
glyph="menu_xform.svg",
appear_after="Scope",
onclick_action=("omni.kit.menu.create", "create_prim_xform"),
)
)
if self._create_menu_list:
omni.kit.menu.utils.add_menu_items(self._create_menu_list, "Create", -8)
def on_create_prim(prim_type, attributes, use_settings: bool = False):
usd_context = omni.usd.get_context()
with omni.kit.usd.layers.active_authoring_layer_context(usd_context):
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type=prim_type, attributes=attributes)
def on_create_light(light_type, attributes):
usd_context = omni.usd.get_context()
with omni.kit.usd.layers.active_authoring_layer_context(usd_context):
omni.kit.commands.execute("CreatePrim", prim_type=light_type, attributes=attributes)
def on_create_prims():
usd_context = omni.usd.get_context()
with omni.kit.usd.layers.active_authoring_layer_context(usd_context):
omni.kit.commands.execute("CreatePrims", prim_types=["Cone", "Cylinder", "Cone"])
def get_extension_path(sub_directory):
global _extension_path
path = _extension_path
if sub_directory:
path = os.path.normpath(os.path.join(path, sub_directory))
return path
def rebuild_menus():
if _extension_instance:
_extension_instance._rebuild_menus()
|
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/tests/test_func_create_prims.py | import asyncio
import os
import carb
import omni.usd
import omni.ui as ui
from omni.kit import ui_test
from omni.kit.menu.utils import MenuItemDescription, MenuLayout
from omni.kit.test_suite.helpers import get_test_data_path, wait_stage_loading, get_prims, select_prims, wait_for_window
from omni.kit.material.library.test_helper import MaterialLibraryTestHelper
from pxr import Sdf, UsdShade
PERSISTENT_SETTINGS_PREFIX = "/persistent"
async def create_test_func_create_camera(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Camera")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Camera'])
# Test creation with typed-defaults
settings = carb.settings.get_settings()
try:
focal_len_key = '/persistent/app/primCreation/typedDefaults/camera/focalLength'
settings.set(focal_len_key, 48)
await ui_test.menu_click("Create/Camera")
cam_prim = omni.usd.get_context().get_stage().GetPrimAtPath('/Camera_01')
tester.assertIsNotNone(cam_prim)
tester.assertEqual(cam_prim.GetAttribute('focalLength').Get(), 48)
finally:
# Delete the change now for any other tests
settings.destroy_item(focal_len_key)
async def create_test_func_create_scope(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Scope")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Scope'])
async def create_test_func_create_xform(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Xform")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Xform'])
async def create_test_func_create_shape_capsule(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Shape/Capsule")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Capsule'])
async def create_test_func_create_shape_cone(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Shape/Cone")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Cone'])
async def create_test_func_create_shape_cube(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Shape/Cube")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Cube'])
async def create_test_func_create_shape_cylinder(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Shape/Cylinder")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Cylinder'])
async def create_test_func_create_shape_sphere(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Shape/Sphere")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Sphere'])
async def create_test_func_create_shape_high_quality(tester, menu_item: MenuItemDescription):
carb.settings.get_settings().set(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality", False)
# use menu
await ui_test.menu_click("Create/Shape/High Quality")
# verify
tester.assertTrue(carb.settings.get_settings().get(PERSISTENT_SETTINGS_PREFIX + "/app/primCreation/highQuality"))
async def create_test_func_create_light_cylinder_light(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Light/Cylinder Light")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/CylinderLight'])
async def create_test_func_create_light_disk_light(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Light/Disk Light")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/DiskLight'])
async def create_test_func_create_light_distant_light(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Light/Distant Light")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/DistantLight'])
async def create_test_func_create_light_dome_light(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Light/Dome Light")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/DomeLight'])
async def create_test_func_create_light_rect_light(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Light/Rect Light")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/RectLight'])
async def create_test_func_create_light_sphere_light(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Light/Sphere Light")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/SphereLight'])
async def create_test_func_create_audio_spatial_sound(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Audio/Spatial Sound")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/OmniSound'])
async def create_test_func_create_audio_non_spatial_sound(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Audio/Non-Spatial Sound")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/OmniSound'])
async def create_test_func_create_audio_listener(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Audio/Listener")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/OmniListener'])
async def create_test_func_create_mesh_cone(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Cone")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Cone'])
async def create_test_func_create_mesh_cube(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Cube")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Cube'])
async def create_test_func_create_mesh_cylinder(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Cylinder")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Cylinder'])
async def create_test_func_create_mesh_disk(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Disk")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Disk'])
async def create_test_func_create_mesh_plane(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Plane")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Plane'])
async def create_test_func_create_mesh_sphere(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Sphere")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Sphere'])
async def create_test_func_create_mesh_torus(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Torus")
# verify
tester.assertTrue(tester.get_stage_prims() == ['/Torus'])
async def create_test_func_create_mesh_settings(tester, menu_item: MenuItemDescription):
# use menu
await ui_test.menu_click("Create/Mesh/Settings")
await wait_for_window("Mesh Generation Settings")
ui_test.find("Mesh Generation Settings").widget.visible = False
async def create_test_func_create_material(tester, material_name: str):
mdl_name = material_name.split('/')[-1].replace(" ", "_")
stage = omni.usd.get_context().get_stage()
if mdl_name == "Add_MDL_File":
# click on menu item
await ui_test.menu_click(material_name)
await ui_test.human_delay()
# use add material dialog
async with MaterialLibraryTestHelper() as material_test_helper:
await material_test_helper.handle_add_material_dialog(get_test_data_path(__name__, "mdl/TESTEXPORT.mdl"), "TESTEXPORT.mdl")
# wait for material to load & UI to refresh
await wait_stage_loading()
# verify
shader = UsdShade.Shader(stage.GetPrimAtPath("/Looks/Material/Shader"))
identifier = shader.GetSourceAssetSubIdentifier("mdl")
tester.assertTrue(identifier == "Material")
return
if mdl_name == "USD_Preview_Surface":
await ui_test.menu_click(material_name)
tester.assertTrue(tester.get_stage_prims() == ['/Looks', '/Looks/PreviewSurface', '/Looks/PreviewSurface/Shader'])
elif mdl_name == "USD_Preview_Surface_Texture":
await ui_test.menu_click(material_name)
tester.assertTrue(tester.get_stage_prims() == ['/Looks', '/Looks/PreviewSurfaceTexture', '/Looks/PreviewSurfaceTexture/PreviewSurfaceTexture', '/Looks/PreviewSurfaceTexture/st', '/Looks/PreviewSurfaceTexture/diffuseColorTex', '/Looks/PreviewSurfaceTexture/metallicTex', '/Looks/PreviewSurfaceTexture/roughnessTex', '/Looks/PreviewSurfaceTexture/normalTex'])
else:
# create sphere, select & create material
omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere")
await select_prims(["/Sphere"])
await ui_test.menu_click(material_name)
# verify material is created
tester.assertTrue(tester.get_stage_prims() == ["/Sphere", "/Looks", f"/Looks/{mdl_name}", f"/Looks/{mdl_name}/Shader"])
prim = stage.GetPrimAtPath(f"/Looks/{mdl_name}/Shader")
asset_path = prim.GetAttribute("info:mdl:sourceAsset").Get()
tester.assertFalse(os.path.isabs(asset_path.path))
tester.assertTrue(os.path.isabs(asset_path.resolvedPath))
# verify /Sphere is bound to material
prim = stage.GetPrimAtPath("/Sphere")
bound_material, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
tester.assertEqual(bound_material.GetPath().pathString, f"/Looks/{mdl_name}")
|
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/tests/__init__.py | from .create_tests import *
from .test_enable_menu import *
|
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/tests/create_tests.py | import sys
import re
import asyncio
import unittest
import carb
import omni.kit.test
from .test_func_create_prims import *
class TestMenuCreate(omni.kit.test.AsyncTestCase):
async def setUp(self):
pass
async def tearDown(self):
pass
async def test_create_menus(self):
import omni.kit.material.library
# 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()
material_list = []
menus = omni.kit.menu.utils.get_merged_menus()
prefix = "create_test"
to_test = []
this_module = sys.modules[__name__]
for key in menus.keys():
# create menu only
if key.startswith("Create"):
for item in menus[key]['items']:
if item.name != "" and item.has_action():
key_name = re.sub('\W|^(?=\d)','_', key.lower())
func_name = re.sub('\W|^(?=\d)','_', item.name.replace("${kit}/", "").lower())
while key_name and key_name[-1] == "_":
key_name = key_name[:-1]
while func_name and func_name[-1] == "_":
func_name = func_name[:-1]
test_fn = f"{prefix}_func_{key_name}_{func_name}"
try:
to_call = getattr(this_module, test_fn)
to_test.append((to_call, test_fn, item))
except AttributeError:
if test_fn.startswith("create_test_func_create_material_"):
material_list.append(f"{key.replace('_', '/')}/{item.name}")
else:
carb.log_error(f"test function \"{test_fn}\" not found")
if item.original_menu_item and item.original_menu_item.hotkey:
test_fn = f"{prefix}_hotkey_func_{key_name}_{func_name}"
try:
to_call = getattr(this_module, test_fn)
to_test.append((to_call, test_fn, item.original_menu_item))
except AttributeError:
carb.log_error(f"test function \"{test_fn}\" not found")
for to_call, test_fn, menu_item in to_test:
await omni.usd.get_context().new_stage_async()
omni.kit.menu.utils.refresh_menu_items("Create")
await ui_test.human_delay()
print(f"Running test {test_fn}")
try:
await to_call(self, menu_item)
except Exception as exc:
carb.log_error(f"error {test_fn} failed - {exc}")
import traceback
traceback.print_exc(file=sys.stdout)
for material_name in material_list:
await omni.usd.get_context().new_stage_async()
omni.kit.menu.utils.refresh_menu_items("Create")
await ui_test.human_delay()
print(f"Running test create_test_func_create_material {material_name}")
try:
await create_test_func_create_material(self, material_name)
except Exception as exc:
carb.log_error(f"error create_test_func_create_material failed - {exc}")
import traceback
traceback.print_exc(file=sys.stdout)
def get_stage_prims(self):
stage = omni.usd.get_context().get_stage()
return [prim.GetPath().pathString for prim in stage.TraverseAll() if not omni.usd.is_hidden_type(prim)]
|
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/tests/test_enable_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 carb
import omni.kit.app
import omni.kit.test
import omni.usd
import omni.ui as ui
from omni.ui.tests.test_base import OmniUiTest
from omni.kit import ui_test
from omni.kit.test_suite.helpers import wait_stage_loading, arrange_windows
class TestEnableCreateMenu(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
await arrange_windows()
await omni.usd.get_context().new_stage_async()
await wait_stage_loading()
# Test(s)
async def test_enable_create_menu(self):
settings = carb.settings.get_settings()
def reset_prim_creation():
settings.set("/app/primCreation/hideShapes", False)
settings.set("/app/primCreation/enableMenuShape", True)
settings.set("/app/primCreation/enableMenuLight", True)
settings.set("/app/primCreation/enableMenuAudio", True)
settings.set("/app/primCreation/enableMenuCamera", True)
settings.set("/app/primCreation/enableMenuScope", True)
settings.set("/app/primCreation/enableMenuXform", True)
def verify_menu(mesh:bool, shape:bool, light:bool, audio:bool, camera:bool, scope:bool, xform:bool):
menu_widget = ui_test.get_menubar()
menu_widgets = []
for w in menu_widget.find_all("**/"):
if isinstance(w.widget, (ui.Menu, ui.MenuItem)) and w.widget.text.strip() != "placeholder":
menu_widgets.append(w.widget.text)
self.assertEqual("Mesh" in menu_widgets, mesh)
self.assertEqual("Shape" in menu_widgets, shape)
self.assertEqual("Light" in menu_widgets, light)
self.assertEqual("Audio" in menu_widgets, audio)
self.assertEqual("Camera" in menu_widgets, camera)
self.assertEqual("Scope" in menu_widgets, scope)
self.assertEqual("Xform" in menu_widgets, xform)
async def test_menu(mesh:bool, shape:bool, light:bool, audio:bool, camera:bool, scope:bool, xform:bool):
omni.kit.menu.create.rebuild_menus()
verify_menu(mesh, shape, light, audio, camera, scope, xform)
try:
# verify default
reset_prim_creation()
await test_menu(mesh=True, shape=True, light=True, audio=True, camera=True, scope=True, xform=True)
# verify hide shapes
reset_prim_creation()
settings.set("/app/primCreation/hideShapes", True)
await test_menu(mesh=True, shape=False, light=True, audio=True, camera=True, scope=True, xform=True)
reset_prim_creation()
settings.set("/app/primCreation/enableMenuShape", False)
await test_menu(mesh=True, shape=False, light=True, audio=True, camera=True, scope=True, xform=True)
# verify hide light
reset_prim_creation()
settings.set("/app/primCreation/enableMenuLight", False)
await test_menu(mesh=True, shape=True, light=False, audio=True, camera=True, scope=True, xform=True)
# verify hide audio
reset_prim_creation()
settings.set("/app/primCreation/enableMenuAudio", False)
await test_menu(mesh=True, shape=True, light=True, audio=False, camera=True, scope=True, xform=True)
# verify hide camera
reset_prim_creation()
settings.set("/app/primCreation/enableMenuCamera", False)
await test_menu(mesh=True, shape=True, light=True, audio=True, camera=False, scope=True, xform=True)
# verify hide scope
reset_prim_creation()
settings.set("/app/primCreation/enableMenuScope", False)
await test_menu(mesh=True, shape=True, light=True, audio=True, camera=True, scope=False, xform=True)
# verify hide xform
reset_prim_creation()
settings.set("/app/primCreation/enableMenuXform", False)
await test_menu(mesh=True, shape=True, light=True, audio=True, camera=True, scope=True, xform=False)
finally:
reset_prim_creation()
|
omniverse-code/kit/exts/omni.kit.window.file_exporter/PACKAGE-LICENSES/omni.kit.window.file_exporter-LICENSE.md | Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited. |
omniverse-code/kit/exts/omni.kit.window.file_exporter/scripts/demo_file_exporter.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 os
import asyncio
import omni.ui as ui
from typing import List
from omni.kit.window.file_exporter import get_file_exporter, ExportOptionsDelegate
# BEGIN-DOC-export_options
class MyExportOptionsDelegate(ExportOptionsDelegate):
def __init__(self):
super().__init__(build_fn=self._build_ui_impl, destroy_fn=self._destroy_impl)
self._widget = None
def _build_ui_impl(self):
self._widget = ui.Frame()
with self._widget:
with ui.VStack(style={"background_color": 0xFF23211F}):
ui.Label("Checkpoint Description", alignment=ui.Alignment.CENTER)
ui.Separator(height=5)
model = ui.StringField(multiline=True, height=80).model
model.set_value("This is my new checkpoint.")
def _destroy_impl(self, _):
if self._widget:
self._widget.destroy()
self._widget = None
# END-DOC-export_options
# BEGIN-DOC-tagging_options
class MyTaggingOptionsDelegate(ExportOptionsDelegate):
def __init__(self):
super().__init__(
build_fn=self._build_ui_impl,
filename_changed_fn=self._filename_changed_impl,
selection_changed_fn=self._selection_changed_impl,
destroy_fn=self._destroy_impl
)
self._widget = None
def _build_ui_impl(self, file_type: str=''):
self._widget = ui.Frame()
with self._widget:
with ui.VStack():
ui.Button(f"Tags for {file_type or 'unknown'} type", height=24)
def _filename_changed_impl(self, filename: str):
if filename:
_, ext = os.path.splitext(filename)
self._build_ui_impl(file_type=ext)
def _selection_changed_impl(self, selections: List[str]):
if len(selections) == 1:
_, ext = os.path.splitext(selections[0])
self._build_ui_impl(file_type=ext)
def _destroy_impl(self, _):
if self._widget:
self._widget.destroy()
self._widget = None
# END-DOC-tagging_options
class DemoFileExporterDialog:
"""
Example that demonstrates how to invoke the file exporter dialog.
"""
def __init__(self):
self._app_window: ui.Window = None
self._export_options = ExportOptionsDelegate = None
self._tag_options = ExportOptionsDelegate = None
self.build_ui()
def build_ui(self):
""" """
window_flags = ui.WINDOW_FLAGS_NO_SCROLLBAR
self._app_window = ui.Window("File Exporter", width=1000, height=500, flags=window_flags)
with self._app_window.frame:
with ui.VStack(spacing=10):
with ui.HStack(height=30):
ui.Spacer()
button = ui.RadioButton(text="Export File", width=120)
button.set_clicked_fn(self._show_dialog)
ui.Spacer()
asyncio.ensure_future(self._dock_window("File Exporter", ui.DockPosition.TOP))
def _show_dialog(self):
# BEGIN-DOC-get_instance
# Get the singleton extension object, but as weakref to guard against the extension being removed.
file_exporter = get_file_exporter()
if not file_exporter:
return
# END-DOC-get_instance
# BEGIN-DOC-show_window
file_exporter.show_window(
title="Export As ...",
export_button_label="Save",
export_handler=self.export_handler,
filename_url="omniverse://ov-rc/NVIDIA/Samples/Marbles/foo",
show_only_folders=True,
enable_filename_input=False,
)
# END-DOC-show_window
# BEGIN-DOC-add_tagging_options
self._tagging_options = MyTaggingOptionsDelegate()
file_exporter.add_export_options_frame("Tagging Options", self._tagging_options)
# END-DOC-add_tagging_options
# BEGIN-DOC-add_export_options
self._export_options = MyExportOptionsDelegate()
file_exporter.add_export_options_frame("Export Options", self._export_options)
# END-DOC-add_export_options
def _hide_dialog(self):
# Get the Content extension object. Same as: omni.kit.window.file_exporter.get_extension()
# Keep as weakref to guard against the extension being removed at any time. If it is removed,
# then invoke appropriate handler; in this case the destroy method.
file_exporter = get_file_exporter()
if file_exporter:
file_exporter.hide()
# BEGIN-DOC-export_handler
def export_handler(self, filename: str, dirname: str, extension: str = "", selections: List[str] = []):
# NOTE: Get user inputs from self._export_options, if needed.
print(f"> Export As '{filename}{extension}' to '{dirname}' with additional selections '{selections}'")
# END-DOC-export_handler
async def _dock_window(self, window_title: str, position: ui.DockPosition, ratio: float = 1.0):
frames = 3
while frames > 0:
if ui.Workspace.get_window(window_title):
break
frames = frames - 1
await omni.kit.app.get_app().next_update_async()
window = ui.Workspace.get_window(window_title)
dockspace = ui.Workspace.get_window("DockSpace")
if window and dockspace:
window.dock_in(dockspace, position, ratio=ratio)
window.dock_tab_bar_visible = False
def destroy(self):
if self._app_window:
self._app_window.destroy()
self._app_window = None
if __name__ == "__main__":
view = DemoFileExporterDialog()
|
omniverse-code/kit/exts/omni.kit.window.file_exporter/config/extension.toml | [package]
title = "File Exporter"
version = "1.0.10"
category = "core"
feature = true
description = "A dialog for exporting files"
authors = ["NVIDIA"]
slackids = ["UQY4RMR3N"]
repository = ""
keywords = ["kit", "ui"]
readme = "docs/README.md"
changelog = "docs/CHANGELOG.md"
preview_image = "data/preview.png"
icon = "data/icon.png"
[dependencies]
"omni.ui" = {}
"omni.usd" = {}
"omni.kit.window.filepicker" = {}
[[python.module]]
name = "omni.kit.window.file_exporter"
[settings]
exts."omni.kit.window.file_exporter".appSettings = "/persistent/app/file_exporter"
[[python.scriptFolder]]
path = "scripts"
[[test]]
dependencies = [
"omni.kit.renderer.core"
]
[documentation]
pages = [
"docs/Overview.md",
"docs/CHANGELOG.md",
]
|
omniverse-code/kit/exts/omni.kit.window.file_exporter/omni/kit/window/file_exporter/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 os
import asyncio
import omni.ext
import omni.kit.app
import carb.settings
import carb.windowing
from typing import List, Tuple, Callable, Dict
from functools import partial
from carb import log_warn, events
from omni.kit.window.filepicker import FilePickerDialog, UI_READY_EVENT
from omni.kit.widget.filebrowser import FileBrowserItem
from . import ExportOptionsDelegate
g_singleton = None
WINDOW_NAME = "File Exporter"
# BEGIN-DOC-file_postfix_options
DEFAULT_FILE_POSTFIX_OPTIONS = [
None,
"anim",
"cache",
"curveanim",
"geo",
"material",
"project",
"seq",
"skel",
"skelanim",
]
# END-DOC-file_postfix_options
# BEGIN-DOC-file_extension_types
DEFAULT_FILE_EXTENSION_TYPES = [
("*.usd", "Can be Binary or Ascii"),
("*.usda", "Human-readable text format"),
("*.usdc", "Binary format"),
]
# END-DOC-file_extension_types
def on_filter_item(dialog: FilePickerDialog, show_only_folders: True, item: FileBrowserItem) -> bool:
if item and not item.is_folder:
if show_only_folders:
return False
else:
return file_filter_handler(item.path or '', dialog.get_file_postfix(), dialog.get_file_extension())
return True
def on_export(
export_fn: Callable[[str, str, str, List[str]], None],
dialog: FilePickerDialog,
filename: str,
dirname: str,
should_validate: bool = False,
):
# OM-64312: should only perform validation when specified, default to not validate
if should_validate:
# OM-58150: should not allow saving with a empty filename
if not _filename_validation_handler(filename):
return
file_postfix = dialog.get_file_postfix()
file_extension = dialog.get_file_extension()
_save_default_settings({'directory': dirname})
selections = dialog.get_current_selections() or []
dialog.hide()
def normalize_filename_parts(filename, file_postfix, file_extension) -> Tuple[str, str]:
splits = filename.split('.')
keep = len(splits) - 1
# leaving the dynamic writable usd file exts strip logic here, in case writable exts are loaded at runtime
try:
import omni.usd
if keep > 0 and splits[keep] in omni.usd.writable_usd_file_exts():
keep -= 1
except Exception:
pass
# OM-84454: strip out file extensions from filename if the current filename ends with any of the file extensions
# available in the current instance of dialog
available_options = [item.lstrip("*.") for item, _ in dialog.get_file_extension_options()]
if keep > 0 and splits[keep] in available_options:
keep -= 1
# strip out postfix from filename
if keep > 0 and splits[keep] in dialog.get_file_postfix_options():
keep -= 1
basename = '.'.join(splits[:keep+1]) if keep >= 0 else ""
extension = ""
if file_postfix:
extension += f".{file_postfix}"
if file_extension:
extension += f"{file_extension.strip('*')}"
return basename, extension
if export_fn:
basename, extension = normalize_filename_parts(filename, file_postfix, file_extension)
export_fn(basename, dirname, extension=extension, selections=selections)
def file_filter_handler(filename: str, filter_postfix: str, filter_ext: str) -> bool:
if not filename:
return True
if not filter_ext:
return True
filter_ext = filter_ext.replace('*', '')
# Show only files whose names end with: *<postfix>.<ext>
if not filter_ext:
filename = os.path.splitext(filename)[0]
elif filename.endswith(filter_ext):
filename = filename[:-len(filter_ext)].strip('.')
else:
return False
if not filter_postfix or filename.endswith(filter_postfix):
return True
return False
def _save_default_settings(default_settings: Dict):
settings = carb.settings.get_settings()
default_settings_path = settings.get_as_string("/exts/omni.kit.window.file_exporter/appSettings")
settings.set_string(f"{default_settings_path}/directory", default_settings['directory'] or "")
def _filename_validation_handler(filename):
"""Validates the filename being exported. Currently only checking if it's empty."""
if not filename:
msg = "Filename is empty! Please specify the filename first."
try:
import omni.kit.notification_manager as nm
nm.post_notification(msg, status=nm.NotificationStatus.WARNING)
except ModuleNotFoundError:
import carb
carb.log_warn(msg)
return False
return True
# 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 FileExporterExtension(omni.ext.IExt):
"""A Standardized file export dialog."""
def __init__(self):
super().__init__()
self._dialog = None
self._title = None
self._ui_ready = False
self._ui_ready_event_sub = None
def on_startup(self, ext_id):
# Save away this instance as singleton for the editor window
global g_singleton
g_singleton = self
# Listen for filepicker events
event_stream = omni.kit.app.get_app().get_message_bus_event_stream()
self._ui_ready_event_sub = event_stream.create_subscription_to_pop_by_type(UI_READY_EVENT, self._on_ui_ready)
self._destroy_dialog_task = None
def show_window(
self,
title: str = None,
width: int = 1080,
height: int = 450,
show_only_collections: List[str] = None,
show_only_folders: bool = False,
file_postfix_options: List[str] = None,
file_extension_types: List[Tuple[str, str]] = None,
export_button_label: str = "Export",
export_handler: Callable[[str, str, str, List[str]], None] = None,
filename_url: str = None,
file_postfix: str = None,
file_extension: str = None,
should_validate: bool = False,
enable_filename_input: bool = True,
focus_filename_input: bool = True, # OM-91056: file exporter should focus filename input field
):
"""
Displays the export dialog with the specified settings.
Keyword Args:
title (str): The name of the dialog
width (int): Width of the window (Default=1250)
height (int): Height of the window (Default=450)
show_only_collections (List[str]): Which of these collections, ["bookmarks", "omniverse", "my-computer"] to display.
show_only_folders (bool): Show only folders in the list view.
file_postfix_options (List[str]): A list of filename postfix options. Nvidia defaults.
file_extension_types (List[Tuple[str, str]]): A list of filename extension options. Each list
element is a (extension name, description) pair, e.g. (".usdc", "Binary format"). Nvidia defaults.
export_button_label (str): Label for the export button (Default="Export")
export_handler (Callable): The callback to handle the export. Function signature is
export_handler(filename: str, dirname: str, extension: str, selections: List[str]) -> None
filename_url (str): Url of the target file, excluding filename extension.
file_postfix (str): Sets selected postfix to this value if specified.
file_extension (str): Sets selected extension to this value if specified.
should_validate (bool): Whether filename validation should be performed.
enable_filename_input (bool): Whether filename field input is enabled, default to True.
"""
if self._dialog:
self.destroy_dialog()
# Load saved settings as defaults
default_settings = self._load_default_settings()
basename = ""
directory = default_settings.get('directory')
if filename_url:
dirname, filename = os.path.split(filename_url)
basename = os.path.basename(filename)
# override directory name only if explicitly given from filename_url
if dirname:
directory = dirname
file_postfix_options = file_postfix_options or DEFAULT_FILE_POSTFIX_OPTIONS
file_extension_types = file_extension_types or DEFAULT_FILE_EXTENSION_TYPES
self._title = title or WINDOW_NAME
self._dialog = FilePickerDialog(
self._title,
width=width,
height=height,
splitter_offset=260,
enable_file_bar=True,
enable_filename_input=enable_filename_input,
enable_checkpoints=False,
show_detail_view=True,
show_only_collections=show_only_collections or [],
file_postfix_options=file_postfix_options,
file_extension_options=file_extension_types,
filename_changed_handler=partial(self._on_filename_changed, show_only_folders=show_only_folders),
apply_button_label=export_button_label,
current_directory=directory,
current_filename=basename,
current_file_postfix=file_postfix,
current_file_extension=file_extension,
focus_filename_input=focus_filename_input,
)
self._dialog.set_item_filter_fn(partial(on_filter_item, self._dialog, show_only_folders))
self._dialog.set_click_apply_handler(
partial(on_export, export_handler, self._dialog, should_validate=should_validate)
)
self._dialog.set_visibility_changed_listener(self._visibility_changed_fn)
# don't disable apply button if we are showing folders only
self._dialog._widget.file_bar.enable_apply_button(enable=show_only_folders)
self._dialog.show()
def _visibility_changed_fn(self, visible: bool):
async def destroy_dialog_async():
# wait one frame, this is due to the one frame defer
# in Window::_moveToMainOSWindow()
try:
await omni.kit.app.get_app().next_update_async()
if self._dialog:
self._dialog.destroy()
self._dialog = None
finally:
self._destroy_dialog_task = None
if not visible:
# Destroy the window, since we are creating new window in show_window
if not self._destroy_dialog_task or self._destroy_dialog_task.done():
self._destroy_dialog_task = asyncio.ensure_future(
destroy_dialog_async()
)
def _load_default_settings(self) -> Dict:
settings = carb.settings.get_settings()
default_settings_path = settings.get_as_string("/exts/omni.kit.window.file_exporter/appSettings")
default_settings = {}
default_settings['directory'] = settings.get_as_string(f"{default_settings_path}/directory")
return default_settings
def _on_filename_changed(self, filename, show_only_folders=False):
# OM-78341: Disable apply button if no file is selected, if we are not showing only folders
if self._dialog and self._dialog._widget and not show_only_folders:
self._dialog._widget.file_bar.enable_apply_button(enable=bool(filename))
def _on_ui_ready(self, event: events.IEvent):
try:
payload = event.payload.get_dict()
title = payload.get('title', None)
except Exception:
return
if event.type == UI_READY_EVENT and title == self._title:
self._ui_ready = True
@property
def is_ui_ready(self) -> bool:
return self._ui_ready
@property
def is_window_visible(self) -> bool:
if self._dialog and self._dialog._window:
return self._dialog._window.visible
return False
def hide_window(self):
"""Hides and destroys the dialog window."""
self.destroy_dialog()
def add_export_options_frame(self, name: str, delegate: ExportOptionsDelegate):
"""
Adds a set of export options to the dialog. Should be called after show_window.
Args:
name (str): Title of the options box.
delegate (ExportOptionsDelegate): Subclasses specified delegate and overrides the
_build_ui_impl method to provide a custom widget for getting user input.
"""
if self._dialog:
self._dialog.add_detail_frame_from_controller(name, delegate)
def click_apply(self, filename_url: str = None, postfix: str = None, extension: str = None):
"""Helper function to progammatically execute the apply callback. Useful in unittests"""
if self._dialog:
if filename_url:
dirname, filename = os.path.split(filename_url)
self._dialog.set_current_directory(dirname)
self._dialog.set_filename(filename)
if postfix:
self._dialog.set_file_postfix(postfix)
if extension:
self._dialog.self_file_extension(extension)
self._dialog._widget._file_bar._on_apply()
def click_cancel(self, cancel_handler: Callable[[str, str], None] = None):
"""Helper function to progammatically execute the cancel callback. Useful in unittests"""
if cancel_handler:
self._dialog._widget._file_bar._click_cancel_handler = cancel_handler
self._dialog._widget._file_bar._on_cancel()
async def select_items_async(self, url: str, filenames: List[str] = []) -> List[FileBrowserItem]:
"""Helper function to programatically select multiple items in filepicker. Useful in unittests."""
if self._dialog:
return await self._dialog._widget.api.select_items_async(url, filenames=filenames)
return []
def detach_from_main_window(self):
"""Detach the current file importer dialog from main window."""
if self._dialog:
self._dialog._window.move_to_new_os_window()
def destroy_dialog(self):
# handles the case for detached window
if self._dialog and self._dialog._window:
carb.windowing.acquire_windowing_interface().hide_window(self._dialog._window.app_window.get_window())
if self._dialog:
self._dialog.destroy()
self._dialog = None
self._ui_ready = False
if self._destroy_dialog_task:
self._destroy_dialog_task.cancel()
self._destroy_dialog_task = None
def on_shutdown(self):
self.destroy_dialog()
self._ui_ready_event_sub = None
global g_singleton
g_singleton = None
def get_instance():
return g_singleton
|
omniverse-code/kit/exts/omni.kit.window.file_exporter/omni/kit/window/file_exporter/__init__.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
"""A standardized dialog for exporting files"""
__all__ = ['FileExporterExtension', 'get_file_exporter']
from carb import log_warn
from omni.kit.window.filepicker import DetailFrameController as ExportOptionsDelegate
from .extension import FileExporterExtension, get_instance
def get_file_exporter() -> FileExporterExtension:
"""Returns the singleton file_exporter extension instance"""
instance = get_instance()
if instance is None:
log_warn("File exporter extension is no longer alive.")
return instance
|
omniverse-code/kit/exts/omni.kit.window.file_exporter/omni/kit/window/file_exporter/test_helper.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 omni.kit.app
import omni.kit.ui_test as ui_test
from .extension import get_instance
from typing import List, Callable
from omni.kit.widget.filebrowser import FileBrowserItem, LISTVIEW_PANE, TREEVIEW_PANE
class FileExporterTestHelper:
"""Test helper for the file export dialog"""
# NOTE Since the file dialog is a singleton, use an async lock to ensure mutex access in unit tests.
# During run-time, this is not a issue because the dialog is effectively modal.
__async_lock = asyncio.Lock()
async def __aenter__(self):
await self.__async_lock.acquire()
return self
async def __aexit__(self, *args):
self.__async_lock.release()
async def wait_for_popup(self, timeout_frames: int = 20):
"""Waits for dialog to be ready"""
file_exporter = get_instance()
if file_exporter:
for _ in range(timeout_frames):
if file_exporter.is_ui_ready:
for _ in range(4):
# Wait a few extra frames to settle before returning
await omni.kit.app.get_app().next_update_async()
return
await omni.kit.app.get_app().next_update_async()
raise Exception("Error: The file export window did not open.")
async def click_apply_async(self, filename_url: str = None):
"""Helper function to progammatically execute the apply callback. Useful in unittests"""
file_exporter = get_instance()
if file_exporter:
file_exporter.click_apply(filename_url=filename_url)
await omni.kit.app.get_app().next_update_async()
async def click_cancel_async(self, cancel_handler: Callable[[str, str], None] = None):
"""Helper function to progammatically execute the cancel callback. Useful in unittests"""
file_exporter = get_instance()
if file_exporter:
file_exporter.click_cancel(cancel_handler=cancel_handler)
await omni.kit.app.get_app().next_update_async()
async def select_items_async(self, dir_url: str, names: List[str]) -> List[FileBrowserItem]:
file_exporter = get_instance()
selections = []
if file_exporter:
selections = await file_exporter.select_items_async(dir_url, names)
return selections
async def get_item_async(self, treeview_identifier: str, name: str, pane: int = LISTVIEW_PANE):
# Return item from the specified pane, handles both tree and grid views
file_exporter = get_instance()
if not file_exporter:
return
if name:
pane_widget = None
if pane == TREEVIEW_PANE:
pane_widget = ui_test.find_all(f"{file_exporter._title}//Frame/**/TreeView[*].identifier=='{treeview_identifier}_folder_view'")
elif file_exporter._dialog._widget._view.filebrowser.show_grid_view:
# LISTVIEW selected + showing grid view
pane_widget = ui_test.find_all(f"{file_exporter._title}//Frame/**/VGrid[*].identifier=='{treeview_identifier}_grid_view'")
else:
# LISTVIEW selected + showing tree view
pane_widget = ui_test.find_all(f"{file_exporter._title}//Frame/**/TreeView[*].identifier=='{treeview_identifier}'")
if pane_widget:
widget = pane_widget[0].find(f"**/Label[*].text=='{name}'")
if widget:
widget.widget.scroll_here(0.5, 0.5)
await ui_test.human_delay(4)
return widget
return None
|
Subsets and Splits