file_path
stringlengths
22
162
content
stringlengths
19
501k
size
int64
19
501k
lang
stringclasses
1 value
avg_line_length
float64
6.33
100
max_line_length
int64
18
935
alphanum_fraction
float64
0.34
0.93
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
13,385
Python
47.151079
115
0.56526
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
244
Python
60.249985
136
0.848361
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" )
20,438
Python
40.542683
143
0.571974
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
24,184
Python
36.8482
120
0.616606
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
502
Python
34.928569
108
0.750996
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
8,135
Python
35.981818
108
0.588199
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
3,601
Python
35.755102
122
0.663149
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)
3,583
Python
39.727272
83
0.641641
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))
11,993
Python
55.575471
172
0.560994
omniverse-code/kit/exts/omni.kit.pipapi/omni/kit/pipapi/__init__.py
from .pipapi import *
22
Python
10.499995
21
0.727273
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)
14,494
Python
34.26764
208
0.641576
omniverse-code/kit/exts/omni.kit.pipapi/omni/kit/pipapi/tests/__init__.py
from .test_pipapi import *
27
Python
12.999994
26
0.740741
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)
562
Python
28.631577
81
0.669039
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
5,673
Python
34.024691
101
0.599859
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 *
236
Python
58.249985
126
0.771186
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)
5,164
Python
28.514286
118
0.687452
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
27,741
Python
37.854342
165
0.654987
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()
1,044
Python
27.243243
76
0.706897
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()
4,208
Python
29.280575
93
0.477899
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)
1,817
Python
34.647058
77
0.67749
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
1,156
Python
37.566665
88
0.697232
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()
3,308
Python
33.113402
109
0.632709
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
3,041
Python
29.118812
97
0.60046
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()
26,901
Python
32.924338
122
0.562358
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()
974
Python
28.545454
77
0.702259
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()
3,585
Python
39.75
115
0.406974
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()
15,120
Python
37.184343
120
0.543783
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()
3,823
Python
30.089431
77
0.609207
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()
4,158
Python
38.990384
98
0.521164
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()
5,815
Python
34.463414
115
0.478074
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()
6,360
Python
35.348571
110
0.592453
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)
7,198
Python
32.640187
113
0.591831
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()
9,617
Python
36.866142
120
0.569616
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
1,616
Python
39.424999
77
0.830446
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()
4,365
Python
37.982143
115
0.596564
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()
17,748
Python
34.640562
120
0.609984
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()
1,261
Python
32.210525
77
0.605868
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)
9,699
Python
55.069364
130
0.688731
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)
9,059
Python
36.28395
116
0.645546
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()
7,607
Python
35.932039
77
0.411989
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()
13,358
Python
45.224913
117
0.592679
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()
11,688
Python
34.637195
111
0.603867
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()
3,574
Python
41.559523
107
0.629547
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")
20,373
Python
36.246801
123
0.595396
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()
9,464
Python
33.046762
128
0.600803
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)
601
Python
34.411763
77
0.672213
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()
6,215
Python
34.930636
90
0.555591
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()
6,144
Python
33.914773
121
0.551921
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()
14,402
Python
39.119777
155
0.608735
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()
6,774
Python
34.471204
80
0.566873
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)
16,910
Python
41.704545
115
0.626316
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()}")
7,390
Python
37.295337
118
0.672936
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}
4,140
Python
38.066037
163
0.622947
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
1,229
Python
39.999999
92
0.644426
omniverse-code/kit/exts/omni.kit.property.skel/omni/kit/property/skel/scripts/__init__.py
from .extension import * from .command import *
48
Python
15.333328
24
0.75
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}
3,301
Python
40.274999
128
0.653135
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)
1,012
Python
27.138888
60
0.606719
omniverse-code/kit/exts/omni.kit.property.skel/omni/kit/property/skel/tests/__init__.py
from .test_skel import *
25
Python
11.999994
24
0.72
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")
2,284
Python
36.459016
109
0.688704
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
751
Python
31.695651
76
0.753662
omniverse-code/kit/exts/omni.kit.viewport.docs/omni/kit/viewport/docs/__init__.py
from .extension import ViewportDocsExtension
45
Python
21.999989
44
0.888889
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)
1,095
Python
41.153845
115
0.73242
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)
819
Python
31.799999
77
0.741148
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)
8,014
Python
32.67647
132
0.564387
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/scripts/__init__.py
from .create import *
22
Python
10.499995
21
0.727273
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()
7,415
Python
37.827225
156
0.582333
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}")
9,882
Python
34.046099
365
0.699757
omniverse-code/kit/exts/omni.kit.menu.create/omni/kit/menu/create/tests/__init__.py
from .create_tests import * from .test_enable_menu import *
60
Python
19.333327
31
0.75
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)]
3,757
Python
42.697674
111
0.51424
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()
4,545
Python
45.865979
112
0.649725
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()
6,054
Python
36.376543
110
0.623059
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
15,396
Python
39.518421
128
0.637178
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
966
Python
41.043476
85
0.779503
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
4,054
Python
44.561797
143
0.633202
omniverse-code/kit/exts/omni.kit.window.file_exporter/omni/kit/window/file_exporter/tests/test_extension.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 os import omni.kit.test import omni.kit.ui_test as ui_test import asyncio import omni.appwindow from unittest.mock import Mock, patch, ANY from carb.settings import ISettings from omni.kit.window.filepicker import FilePickerDialog from omni.kit.test_suite.helpers import get_test_data_path from .. import get_file_exporter from ..test_helper import FileExporterTestHelper from ..extension import on_export, file_filter_handler, DEFAULT_FILE_POSTFIX_OPTIONS class TestFileExporter(omni.kit.test.AsyncTestCase): """ Testing omni.kit.window.file_exporter extension. NOTE that since the dialog is a singleton, we use an async lock to ensure that only one test runs at a time. In practice, this is not a issue because only one extension is accessing the dialog at any given time. """ __lock = asyncio.Lock() async def setUp(self): self._settings_path = "my_settings" self._test_settings = { "/exts/omni.kit.window.file_exporter/appSettings": self._settings_path, f"{self._settings_path}/directory": "C:/temp/folder", f"{self._settings_path}/filename": "my-file", } async def tearDown(self): pass def _mock_settings_get_string_impl(self, name: str) -> str: return self._test_settings.get(name) def _mock_settings_set_string_impl(self, name: str, value: str): self._test_settings[name] = value async def test_show_window_destroys_previous(self): """Testing show_window destroys previously allocated dialog""" async with self.__lock: under_test = get_file_exporter() with patch.object(FilePickerDialog, "destroy", autospec=True) as mock_destroy_dialog,\ patch("carb.windowing.IWindowing.hide_window"): under_test.show_window(title="first") under_test.show_window(title="second") mock_destroy_dialog.assert_called() dialog = mock_destroy_dialog.call_args[0][0] self.assertEqual(str(dialog._window), "first") async def test_hide_window_destroys_it(self): """Testing that hiding the window destroys it""" async with self.__lock: under_test = get_file_exporter() with patch.object(FilePickerDialog, "destroy", autospec=True) as mock_destroy_dialog: under_test.show_window(title="test") under_test._dialog.hide() # Dialog is destroyed after a couple frames await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() mock_destroy_dialog.assert_called() dialog = mock_destroy_dialog.call_args[0][0] self.assertEqual(str(dialog._window), "test") async def test_hide_window_destroys_detached_window(self): """Testing that hiding the window destroys detached window.""" async with self.__lock: under_test = get_file_exporter() with patch.object(FilePickerDialog, "destroy", autospec=True) as mock_destroy_dialog: under_test.show_window(title="test_detached") await omni.kit.app.get_app().next_update_async() under_test.detach_from_main_window() main_window = omni.appwindow.get_default_app_window().get_window() self.assertFalse(main_window is under_test._dialog._window.app_window.get_window()) under_test.hide_window() # Dialog is destroyed after a couple frames await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() mock_destroy_dialog.assert_called() dialog = mock_destroy_dialog.call_args[0][0] self.assertEqual(str(dialog._window), "test_detached") async def test_load_default_settings(self): """Testing that dialog applies saved settings""" async with self.__lock: under_test = get_file_exporter() with patch('omni.kit.window.file_exporter.extension.FilePickerDialog') as mock_dialog,\ patch.object(ISettings, "get_as_string", side_effect=self._mock_settings_get_string_impl): under_test.show_window(title="test_dialog") # Retrieve keyword args for the constructor (first call), and confirm called with expected values constructor_kwargs = mock_dialog.call_args_list[0][1] self.assertEqual(constructor_kwargs['current_directory'], self._test_settings[f"{self._settings_path}/directory"]) self.assertEqual(constructor_kwargs['current_filename'], "") async def test_override_default_settings(self): """Testing that user values override default settings""" async with self.__lock: test_url = "Omniverse://ov-test/my-folder/my-file.usd" under_test = get_file_exporter() with patch('omni.kit.window.file_exporter.extension.FilePickerDialog') as mock_dialog,\ patch.object(ISettings, "get_as_string", side_effect=self._mock_settings_get_string_impl),\ patch("carb.windowing.IWindowing.hide_window"): under_test.show_window(title="test_dialog", filename_url=test_url) # Retrieve keyword args for the constructor (first call), and confirm called with expected values constructor_kwargs = mock_dialog.call_args_list[0][1] dirname, filename = os.path.split(test_url) self.assertEqual(constructor_kwargs['current_directory'], dirname) self.assertEqual(constructor_kwargs['current_filename'], filename) async def test_save_settings_on_export(self): """Testing that settings are saved on export""" my_settings = { 'filename': "my-file", 'directory': "Omniverse://ov-test/my-folder", } mock_dialog = Mock() with patch.object(ISettings, "get_as_string", side_effect=self._mock_settings_get_string_impl),\ patch.object(ISettings, "set_string", side_effect=self._mock_settings_set_string_impl): on_export(None, mock_dialog, my_settings['filename'], my_settings['directory']) # Retrieve keyword args for the constructor (first call), and confirm called with expected values self.assertEqual(my_settings['filename'], self._test_settings[f"{self._settings_path}/filename"]) self.assertEqual(my_settings['directory'], self._test_settings[f"{self._settings_path}/directory"]) async def test_show_only_folders(self): """Testing show only folders option.""" mock_handler = Mock() async with self.__lock: under_test = get_file_exporter() test_path = get_test_data_path(__name__).replace("\\", '/') async with FileExporterTestHelper() as helper: with patch("carb.windowing.IWindowing.hide_window"): # under normal circumstance, files will be shown and could be selected. # under_test.show_window(title="test", filename_url=test_path) under_test.show_window(title="test", filename_url=test_path + "/") await ui_test.human_delay(10) item = await helper.get_item_async(None, "dummy.usd") self.assertIsNotNone(item) # apply button should be disabled self.assertFalse(under_test._dialog._widget.file_bar._apply_button.enabled) await helper.click_cancel_async() # if shown with show_only_folders, files will not be shown under_test.show_window(title="test", show_only_folders=True, export_handler=mock_handler) await ui_test.human_delay(10) item = await helper.get_item_async(None, "dummy.usd") self.assertIsNone(item) # try selecting a folder selections = await under_test.select_items_async(test_path, filenames=['folder']) self.assertEqual(len(selections), 1) selected = selections[0] # apply button should not be disabled self.assertTrue(under_test._dialog._widget.file_bar._apply_button.enabled) await ui_test.human_delay() await helper.click_apply_async() mock_handler.assert_called_once_with('', selected.path + "/", extension=".usd", selections=[selected.path]) async def test_cancel_handler(self): """Testing cancel handler.""" mock_handler = Mock() async with self.__lock: under_test = get_file_exporter() test_path = get_test_data_path(__name__).replace("\\", '/') async with FileExporterTestHelper() as helper: under_test.show_window("test_cancel_handler", filename_url=test_path + "/") await helper.wait_for_popup() await ui_test.human_delay(10) await helper.click_cancel_async(cancel_handler=mock_handler) await ui_test.human_delay(10) mock_handler.assert_called_once() class TestFileFilterHandler(omni.kit.test.AsyncTestCase): """Testing default_file_filter_handler correctly shows/hides files.""" async def setUp(self): ext_type = { 'usd': "*.usd", 'usda': "*.usda", 'usdc': "*.usdc", 'usdz': "*.usdz", } self.test_filenames = [ ("test.anim.usd", "anim", ext_type['usd'], True), ("test.anim.usdz", "anim", ext_type['usdz'], True), ("test.anim.usdc", "anim", ext_type['usdz'], False), ("test.anim.usda", None, ext_type['usda'], True), ("test.material.", None, ext_type['usda'], False), ("test.materials.usd", "material", ext_type['usd'], False), ] async def tearDown(self): pass async def test_file_filter_handler(self): """Testing file filter handler""" for test_filename in self.test_filenames: filename, postfix, ext, expected = test_filename result = file_filter_handler(filename, postfix, ext) self.assertEqual(result, expected) class TestOnExport(omni.kit.test.AsyncTestCase): """Testing on_export function correctly parses filename parts from dialog.""" async def setUp(self): self.test_sets = [ ("test", "anim", "*.usdc", "test", ".anim.usdc"), ("test.usd", "anim", "*.usdc", "test", ".anim.usdc"), ("test.cache.usdc", "geo", "*.usdz", "test", ".geo.usdz"), ("test.cache.any", "geo", "*.usd", "test.cache.any", ".geo.usd"), ("test.geo.usd", None, "*.usda", "test", ".usda"), ("test.png", "anim", "*.jpg", "test", ".anim.jpg"), ] async def tearDown(self): pass async def test_on_export(self): """Testing file filter handler""" mock_callback = Mock() mock_dialog = Mock() mock_extension_options = [ ('*.usd', 'Can be Binary or Ascii'), ('*.usda', 'Human-readable text format'), ('*.usdc', 'Binary format'), ('*.png', 'test'), ('*.jpg', 'another test') ] for test_set in self.test_sets: filename = test_set[0] mock_dialog.get_file_postfix.return_value = test_set[1] mock_dialog.get_file_extension.return_value = test_set[2] mock_dialog.get_file_postfix_options.return_value = DEFAULT_FILE_POSTFIX_OPTIONS mock_dialog.get_file_extension_options.return_value = mock_extension_options mock_dialog.get_current_selections.return_value = [] on_export(mock_callback, mock_dialog, filename, "C:/temp/test/") expected_basename = test_set[3] expected_extension = test_set[4] mock_callback.assert_called_with(expected_basename, "C:/temp/test/", extension=expected_extension, selections=ANY) async def test_export_filename_validation(self): """Test export with and without validation.""" mock_callback = Mock() mock_dialog = Mock() mock_dialog.get_file_postfix.return_value = None mock_dialog.get_file_extension.return_value = ".usd" mock_dialog.get_file_extension_options.return_value = [('*.usd', 'Can be Binary or Ascii')] on_export(mock_callback, mock_dialog, "", "", should_validate=True) mock_callback.assert_not_called() on_export(mock_callback, mock_dialog, "", "C:/temp/test/", should_validate=False) mock_callback.assert_called_once()
13,329
Python
47.827839
127
0.607998
omniverse-code/kit/exts/omni.kit.property.bundle/omni/kit/property/bundle/widgets.py
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import carb import omni.usd from pathlib import Path from .geom_scheme_delegate import GeomPrimSchemeDelegate from .path_scheme_delegate import PathPrimSchemeDelegate from .material_scheme_delegate import MaterialPrimSchemeDelegate, ShaderPrimSchemeDelegate TEST_DATA_PATH = "" class BundlePropertyWidgets(omni.ext.IExt): def __init__(self): self._registered = False super().__init__() def on_startup(self, ext_id): self._register_widget() manager = omni.kit.app.get_app().get_extension_manager() extension_path = manager.get_extension_path(ext_id) global TEST_DATA_PATH TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests") def on_shutdown(self): self._unregister_widget() def _register_widget(self): import omni.kit.window.property as p w = p.get_window() w.register_scheme_delegate("prim", "xformable_prim", GeomPrimSchemeDelegate()) w.register_scheme_delegate("prim", "path_prim", PathPrimSchemeDelegate()) w.register_scheme_delegate("prim", "material_prim", MaterialPrimSchemeDelegate()) w.register_scheme_delegate("prim", "shade_prim", ShaderPrimSchemeDelegate()) physics_widgets = [ "physics_components", "physics_prim", "joint_prim", "vehicle_prim", "physics_material", "custom_properties", ] anim_graph_widgets = ["anim_graph", "anim_graph_node"] w.set_scheme_delegate_layout( "prim", [ "path_prim", "basis_curves_prim", "point_instancer_prim", "material_prim", "xformable_prim", "shade_prim", "audio_settings", ] + physics_widgets + anim_graph_widgets, ) def _unregister_widget(self): import omni.kit.window.property as p w = p.get_window() w.reset_scheme_delegate_layout("prim") w.unregister_scheme_delegate("prim", "xformable_prim") w.unregister_scheme_delegate("prim", "path_prim") w.unregister_scheme_delegate("prim", "material_prim") w.unregister_scheme_delegate("prim", "shade_prim")
2,730
Python
34.467532
90
0.632234
omniverse-code/kit/exts/omni.kit.property.bundle/omni/kit/property/bundle/material_scheme_delegate.py
import carb import omni.usd from pxr import Sdf, UsdShade from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate class MaterialPrimSchemeDelegate(PropertySchemeDelegate): def get_widgets(self, payload): widgets_to_build = [] if self._should_enable_delegate(payload): widgets_to_build.append("path") widgets_to_build.append("material") return widgets_to_build def get_unwanted_widgets(self, payload): unwanted_widgets_to_build = [] if self._should_enable_delegate(payload): unwanted_widgets_to_build.append("transform") return unwanted_widgets_to_build def _should_enable_delegate(self, payload): stage = payload.get_stage() if stage: for prim_path in payload: prim = stage.GetPrimAtPath(prim_path) if prim: if not prim.IsA(UsdShade.Material): return False return True return False class ShaderPrimSchemeDelegate(PropertySchemeDelegate): def get_widgets(self, payload): widgets_to_build = [] if self._should_enable_delegate(payload): widgets_to_build.append("path") widgets_to_build.append("shader") return widgets_to_build def get_unwanted_widgets(self, payload): unwanted_widgets_to_build = [] if self._should_enable_delegate(payload): unwanted_widgets_to_build.append("transform") return unwanted_widgets_to_build def _should_enable_delegate(self, payload): stage = payload.get_stage() if stage: for prim_path in payload: prim = stage.GetPrimAtPath(prim_path) if prim: if not prim.IsA(UsdShade.Shader): return False return True return False
1,922
Python
32.155172
84
0.60666
omniverse-code/kit/exts/omni.kit.property.bundle/omni/kit/property/bundle/path_scheme_delegate.py
import carb import omni.usd from pxr import Sdf, UsdGeom from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate class PathPrimSchemeDelegate(PropertySchemeDelegate): def get_widgets(self, payload): widgets_to_build = [] if len(payload): widgets_to_build.append("path") return widgets_to_build
367
Python
23.533332
84
0.719346
omniverse-code/kit/exts/omni.kit.property.bundle/omni/kit/property/bundle/geom_scheme_delegate.py
import carb import omni.usd from pxr import Sdf, UsdMedia, OmniAudioSchema, UsdGeom, UsdLux, UsdSkel from omni.kit.window.property.property_scheme_delegate import PropertySchemeDelegate class GeomPrimSchemeDelegate(PropertySchemeDelegate): def get_widgets(self, payload): widgets_to_build = [] anchor_prim = None stage = payload.get_stage() if stage: for prim_path in payload: prim = stage.GetPrimAtPath(prim_path) if prim: if not prim.IsA(UsdGeom.Imageable): return widgets_to_build anchor_prim = prim if anchor_prim is None: return widgets_to_build if ( anchor_prim and anchor_prim.IsA(UsdMedia.SpatialAudio) or anchor_prim.IsA(OmniAudioSchema.OmniSound) or anchor_prim.IsA(OmniAudioSchema.OmniListener) ): widgets_to_build.append("path") widgets_to_build.append("transform") widgets_to_build.append("media") widgets_to_build.append("audio_sound") widgets_to_build.append("audio_listener") widgets_to_build.append("audio_settings") widgets_to_build.append("kind") elif anchor_prim and anchor_prim.IsA(UsdSkel.Root): # pragma: no cover widgets_to_build.append("path") widgets_to_build.append("transform") widgets_to_build.append("character_api") widgets_to_build.append("anim_graph_api") widgets_to_build.append("omni_graph_api") widgets_to_build.append("kind") elif anchor_prim.IsA(UsdSkel.Skeleton): # pragma: no cover widgets_to_build.append("path") widgets_to_build.append("transform") widgets_to_build.append("control_rig") widgets_to_build.append("skel_animation") elif anchor_prim and anchor_prim.IsA(UsdGeom.Camera): widgets_to_build.append("path") widgets_to_build.append("transform") widgets_to_build.append("camera") widgets_to_build.append("geometry_imageable") widgets_to_build.append("kind") # https://github.com/PixarAnimationStudios/USD/commit/7540fdf3b2aa6b6faa0fce8e7b4c72b756286f51 elif anchor_prim and ((hasattr(UsdLux, 'LightAPI') and anchor_prim.HasAPI(UsdLux.LightAPI)) or ((hasattr(UsdLux, 'Light') and anchor_prim.IsA(UsdLux.Light)))): widgets_to_build.append("path") widgets_to_build.append("transform") widgets_to_build.append("light") widgets_to_build.append("geometry_imageable") widgets_to_build.append("kind") elif anchor_prim and anchor_prim.IsA(UsdGeom.Scope): widgets_to_build.append("path") widgets_to_build.append("geometry_imageable") widgets_to_build.append("character_motion_library") widgets_to_build.append("kind") elif anchor_prim and anchor_prim.IsA(UsdGeom.Mesh): widgets_to_build.append("path") widgets_to_build.append("transform") widgets_to_build.append("material_binding") widgets_to_build.append("geometry") widgets_to_build.append("geometry_imageable") widgets_to_build.append("character_interactive_object_api") widgets_to_build.append("mesh_skel_binding") widgets_to_build.append("kind") elif anchor_prim and anchor_prim.IsA(UsdGeom.Xform): widgets_to_build.append("path") widgets_to_build.append("transform") widgets_to_build.append("material_binding") widgets_to_build.append("geometry_imageable") widgets_to_build.append("kind") elif anchor_prim and anchor_prim.IsA(UsdGeom.Xformable): widgets_to_build.append("path") widgets_to_build.append("transform") widgets_to_build.append("material_binding") widgets_to_build.append("geometry") widgets_to_build.append("geometry_imageable") widgets_to_build.append("character_interactive_object_api") widgets_to_build.append("kind") return widgets_to_build def get_unwanted_widgets(self, payload): unwanted_widgets_to_build = [] anchor_prim = None stage = payload.get_stage() if stage: for prim_path in payload: prim = stage.GetPrimAtPath(prim_path) if prim: if not prim.IsA(UsdGeom.Imageable): return unwanted_widgets_to_build anchor_prim = prim if anchor_prim is None: return unwanted_widgets_to_build if anchor_prim and anchor_prim.IsA(UsdGeom.Scope): unwanted_widgets_to_build.append("transform") unwanted_widgets_to_build.append("geometry") unwanted_widgets_to_build.append("kind") # https://github.com/PixarAnimationStudios/USD/commit/7540fdf3b2aa6b6faa0fce8e7b4c72b756286f51 elif anchor_prim and ((hasattr(UsdLux, 'LightAPI') and anchor_prim.HasAPI(UsdLux.LightAPI)) or ((hasattr(UsdLux, 'Light') and anchor_prim.IsA(UsdLux.Light)))): unwanted_widgets_to_build.append("geometry") elif ( anchor_prim and anchor_prim.IsA(UsdMedia.SpatialAudio) or anchor_prim.IsA(OmniAudioSchema.Sound) or anchor_prim.IsA(OmniAudioSchema.Listener) ): unwanted_widgets_to_build.append("geometry_imageable") elif anchor_prim and anchor_prim.IsA(UsdSkel.Skeleton) or anchor_prim.IsA(UsdSkel.Root): unwanted_widgets_to_build.append("geometry") unwanted_widgets_to_build.append("geometry_imageable") return unwanted_widgets_to_build
5,906
Python
41.496403
167
0.614968
omniverse-code/kit/exts/omni.kit.property.bundle/omni/kit/property/bundle/tests/test_bundle.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 platform 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 arrange_windows, wait_stage_loading, get_prims from pxr import Kind, Sdf, Gf import pathlib class TestBundleWidget(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() await arrange_windows() from omni.kit.property.bundle.widgets import TEST_DATA_PATH self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() self._usd_path = TEST_DATA_PATH.absolute() 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_bundle_ui(self): usd_context = omni.usd.get_context() test_file_path = self._usd_path.joinpath("bundle.usda").absolute() await usd_context.open_stage_async(str(test_file_path)) await wait_stage_loading() stage = usd_context.get_stage() for prim_path in ['/World/Cube', '/World/Cone', '/World/OmniSound', '/World/Camera', '/World/DomeLight', '/World/Scope', '/World/Xform']: await self.docked_test_window( window=self._w._window, width=450, height=995, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) # Select the prim. usd_context.get_selection().set_selected_prim_paths([prim_path], True) prim = stage.GetPrimAtPath(prim_path) type = prim.GetTypeName().lower() # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=f"test_bundle_ui_{type}.png") # allow window to be restored to full size await ui_test.human_delay(50)
2,673
Python
37.199999
145
0.66517
omniverse-code/kit/exts/omni.kit.exec.debug/omni/kit/exec/debug/execution_debug_page.py
"""EF Execution Debugging Page""" import omni.ui as ui from omni.kit.exec.core.unstable import dump_graph_topology from omni.kit.window.preferences import PreferenceBuilder, SettingType class ExecutionDebugPage(PreferenceBuilder): """EF Execution Debugging Page""" def __init__(self): super().__init__("Execution") # Setting keys. When changing, make sure to update ExecutionController.cpp as well. self.serial_eg = "/app/execution/debug/forceSerial" self.parallel_eg = "/app/execution/debug/forceParallel" # ID counter for file path write-out. self.id = 0 self.file_name = "ExecutionGraph_" def build(self): """Build the EF execution debugging page""" with ui.VStack(height=0): with self.add_frame("Execution Debugging"): with ui.VStack(): dump_graph_topology_button = ui.Button("Dump execution graph", width=24) dump_graph_topology_button.set_clicked_fn(self._dump_graph_topology) dump_graph_topology_button.set_tooltip( "Writes the execution graph topology out as a GraphViz (.dot) file. File location\n" + "will differ depending on the kit app being run, whether the button was pressed\n" + "in a unit test, etc., but typically it can be found under something like\n" + "kit/_compiler/omni.app.dev; if not, then just search for .dot files containing\n" + "the name ExecutionGraph in the kit directory.\n" ) self.create_setting_widget("Force serial execution", self.serial_eg, SettingType.BOOL) self.create_setting_widget("Force parallel execution", self.parallel_eg, SettingType.BOOL) def _dump_graph_topology(self): """Dump graph topology with incremented file""" dump_graph_topology(self.file_name + str(self.id)) self.id += 1
2,021
Python
46.023255
110
0.617516
omniverse-code/kit/exts/omni.kit.exec.debug/omni/kit/exec/debug/extension.py
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. import omni.ext from omni.kit.window.preferences import register_page, unregister_page from .execution_debug_page import ExecutionDebugPage class ExecutionDebugExtension(omni.ext.IExt): # The entry point for this extension (generates a page within the Preferences # tab with debugging flags for the Execution Framework). def on_startup(self): self.execution_debug_page = ExecutionDebugPage() register_page(self.execution_debug_page) def on_shutdown(self): unregister_page(self.execution_debug_page)
970
Python
39.458332
81
0.778351
omniverse-code/kit/exts/omni.kit.exec.debug/omni/kit/exec/debug/tests/test_exec_debug.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.settings import omni.kit.test from omni.ui.tests.test_base import OmniUiTest from pathlib import Path import omni.kit.app import omni.kit.window.preferences as preferences from omni.kit.viewport.window import ViewportWindow import omni.ui as ui CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") TEST_WIDTH, TEST_HEIGHT = 1280, 600 class TestExecutionDebugWindow(OmniUiTest): """Test the EF Debugging Page""" async def setUp(self): """Test set-up before running each test""" await super().setUp() self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) self._vw = ViewportWindow("TestWindow", width=TEST_WIDTH, height=TEST_HEIGHT) async def tearDown(self): """Test tear-down after running each test""" await super().tearDown() async def test_execution_page(self): """Test the EF Debugging Page""" title = "Execution" for page in preferences.get_page_list(): if page.get_title() == title: # Setting keys for the test. Flag some stuff to be true to make sure toggles work. carb.settings.get_settings().set(page.serial_eg, False) carb.settings.get_settings().set(page.parallel_eg, True) preferences.select_page(page) preferences.show_preferences_window() await omni.kit.app.get_app().next_update_async() pref_window = ui.Workspace.get_window("Preferences") await self.docked_test_window( window=pref_window, width=TEST_WIDTH, height=TEST_HEIGHT, ) await omni.kit.app.get_app().next_update_async() await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name=f"{title}.png")
2,383
Python
36.841269
101
0.68569
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/welcome_page_item.py
from typing import Callable import carb import omni.kit.app import omni.ui as ui class WelcomePageItem(ui.AbstractItem): def __init__(self, raw_data: dict): super().__init__() self.text = raw_data.get("text", "") self.icon = raw_data.get("icon", "") self.active_icon = raw_data.get("active_icon", self.icon) self.extension_id = raw_data.get("extension_id") self.order = raw_data.get("order", 0xFFFFFFFF) self.build_fn: Callable[[None], None] = None carb.log_info(f"Register welcome page: {self}") def build_ui(self) -> None: # Enable page extension and call build_ui manager = omni.kit.app.get_app().get_extension_manager() manager.set_extension_enabled_immediate(self.extension_id, True) try: if self.build_fn: self.build_fn() else: carb.log_error(f"Failed to build page for `{self.text}` because build entry point not defined!") except Exception as e: carb.log_error(f"Failed to build page for `{self.text}`: {e}") def __repr__(self): return f"{self.text}:{self.extension_id}"
1,175
Python
35.749999
112
0.6
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/welcome_window.py
from typing import Dict, List, Optional import carb.settings import omni.ui as ui from omni.ui import constant as fl from .style import WELCOME_STYLE from .welcome_model import WelcomeModel from .welcome_page_item import WelcomePageItem SETTING_SHOW_AT_STARTUP = "/persistent/exts/omni.kit.welcome.window/visible_at_startup" SETTING_SHOW_SAS_CHECKBOX = "/exts/omni.kit.welcome.window/show_sas_checkbox" class WelcomeWindow(ui.Window): """ Window to show welcome content. Args: visible (bool): If visible when window created. """ def __init__(self, model: WelcomeModel, visible: bool=True): self._model = model self._delegates: List[WelcomePageItem] = [] self.__page_frames: Dict[WelcomePageItem, ui.Frame] = {} self.__page_buttons: Dict[WelcomePageItem, ui.Button] = {} self.__selected_page: Optional[WelcomePageItem] = None # TODO: model window? # If model window and open extensions manager, new extensions window unavailable # And if model window, checkpoing combobox does not pop up droplist because it is a popup window flags = (ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_MODAL) super().__init__("Welcome Screen", flags=flags, width=1380, height=780, padding_x=2, padding_y=2, visible=visible) self.frame.set_build_fn(self._build_ui) self.frame.set_style(WELCOME_STYLE) def destroy(self) -> None: super().destroy() self.__page_frames = {} self.visible = False self.__sub_show_at_startup = None def _build_ui(self): self._pages = self._model.get_item_children(None) button_height = fl._find("welcome_page_button_height") with self.frame: with ui.HStack(): # Left for buttons to switch different pages with ui.VStack(width=250, spacing=0): for page in self._pages: self.__page_buttons[page] = ui.Button( page.text.upper(), height=button_height, image_width=button_height, image_height=button_height, spacing=4, image_url=page.icon, clicked_fn=lambda d=page: self.__show_page(d), style_type_name_override="Page.Button" ) ui.Spacer() self.__build_show_at_startup() # Right for page content with ui.ZStack(): for page in self._pages: self.__page_frames[page] = ui.Frame(build_fn=lambda p=page: p.build_ui(), visible=False) # Default always show first page self.__show_page(self._pages[0]) def __build_show_at_startup(self) -> None: settings = carb.settings.get_settings() self.__show_at_startup_model = ui.SimpleBoolModel(settings.get(SETTING_SHOW_AT_STARTUP)) def __on_show_at_startup_changed(model: ui.SimpleBoolModel): settings.set(SETTING_SHOW_AT_STARTUP, model.as_bool) self.__sub_show_at_startup = self.__show_at_startup_model.subscribe_value_changed_fn(__on_show_at_startup_changed) if settings.get_as_bool(SETTING_SHOW_SAS_CHECKBOX): with ui.HStack(height=0, spacing=5): ui.Spacer(width=5) ui.CheckBox(self.__show_at_startup_model, width=0) ui.Label("Show at Startup", width=0) ui.Spacer(height=5) def __show_page(self, page: WelcomePageItem): if self.__selected_page: self.__page_frames[self.__selected_page].visible = False self.__page_buttons[self.__selected_page].selected = False self.__page_buttons[self.__selected_page].image_url = self.__selected_page.icon if page: self.__page_frames[page].visible = True self.__page_buttons[page].selected = True self.__page_buttons[page].image_url = page.active_icon self.__selected_page = page
4,148
Python
42.21875
122
0.592575
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/style.py
from pathlib import Path import omni.ui as ui from omni.ui import color as cl from omni.ui import constant as fl CURRENT_PATH = Path(__file__).parent ICON_PATH = CURRENT_PATH.parent.parent.parent.joinpath("data/icons") cl.welcome_window_background = cl.shade(cl("#363636")) cl.welcome_content_background = cl.shade(cl("#1F2123")) cl.welcome_button_text = cl.shade(cl("#979797")) cl.welcome_button_text_selected = cl.shade(cl("#E3E3E3")) cl.welcome_label = cl.shade(cl("#A1A1A1")) cl.welcome_label_selected = cl.shade(cl("#34C7FF")) fl.welcome_page_button_size = 24 fl.welcome_title_font_size = 18 fl.welcome_page_button_height = 80 fl.welcome_page_title_height = fl._find("welcome_page_button_height") + 8 fl.welcome_content_padding_x = 10 fl.welcome_content_padding_y = 10 WELCOME_STYLE = { "Window": { "background_color": cl.welcome_window_background, "border_width": 0, "padding": 0, "marging" : 0, "padding_width": 0, "margin_width": 0, }, "Page.Button": { "background_color": cl.welcome_window_background, "stack_direction": ui.Direction.LEFT_TO_RIGHT, "padding_x": 10, "margin": 0, }, "Page.Button:hovered": { "background_color": cl.welcome_content_background, }, "Page.Button:pressed": { "background_color": cl.welcome_content_background, }, "Page.Button:selected": { "background_color": cl.welcome_content_background, }, "Page.Button.Label": { "font_size": fl.welcome_page_button_size, "alignment": ui.Alignment.LEFT_CENTER, "color": cl.welcome_button_text, }, "Page.Button.Label:selected": { "color": cl.welcome_button_text_selected, }, "Content": { "background_color": cl.welcome_content_background, }, "Title.Button": { "background_color": cl.transparent, "stack_direction": ui.Direction.RIGHT_TO_LEFT, }, "Title.Button.Label": { "font_size": fl.welcome_title_font_size, }, "Title.Button.Image": { "color": cl.welcome_label_selected, "alignment": ui.Alignment.LEFT_CENTER, }, "Doc.Background": {"background_color": cl.white}, "CheckBox": { "background_color": cl.welcome_button_text, "border_radius": 0, }, "Label": {"color": cl.welcome_button_text}, }
2,375
Python
29.075949
73
0.622737
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/extension.py
import asyncio from typing import Callable, Optional import carb import carb.settings import omni.ext import omni.kit.app import omni.kit.menu.utils import omni.kit.ui import omni.ui as ui from omni.kit.menu.utils import MenuItemDescription from .actions import deregister_actions, register_actions from .welcome_model import WelcomeModel from .welcome_window import WelcomeWindow WELCOME_MENU_ROOT = "File" _extension_instance = None class WelcomeExtension(omni.ext.IExt): def on_startup(self, ext_id): self._ext_name = omni.ext.get_extension_name(ext_id) self.__stage_opened = False # Window self._model = WelcomeModel() visible = carb.settings.get_settings().get("/persistent/exts/omni.kit.welcome.window/visible_at_startup") self._window = WelcomeWindow(self._model, visible=visible) self._window.set_visibility_changed_fn(self.__on_visibility_changed) if visible: self.__center_window() else: # Listen for the app ready event def _on_app_ready(event): self.__on_close() self._app_ready_sub = None startup_event_stream = omni.kit.app.get_app().get_startup_event_stream() self._app_ready_sub = startup_event_stream.create_subscription_to_pop_by_type( omni.kit.app.EVENT_APP_READY, _on_app_ready, name="Welcome window" ) # Menu item self._register_menuitem() global _extension_instance _extension_instance = self # Action register_actions(self._ext_name, _extension_instance) def on_shutdown(self): self._hooks = None self._app_ready_sub = None deregister_actions(self._ext_name) self._model = None if self._menu_list is not None: omni.kit.menu.utils.remove_menu_items(self._menu_list, WELCOME_MENU_ROOT) self._menu_list = None if self._window is not None: self._window.destroy() self._window = None global _extension_instance _extension_instance = self def toggle_window(self): self._window.visible = not self._window.visible def _register_menuitem(self): self._menu_list = [ MenuItemDescription( name="Welcome", glyph="none.svg", ticked=True, ticked_fn=self._on_tick, onclick_action=(self._ext_name, "toggle_window"), appear_after="Open", ) ] omni.kit.menu.utils.add_menu_items(self._menu_list, WELCOME_MENU_ROOT) def _on_tick(self): if self._window: return self._window.visible else: return False def _on_click(self, *args): self._window.visible = not self._window.visible def __on_visibility_changed(self, visible: bool): omni.kit.menu.utils.refresh_menu_items(WELCOME_MENU_ROOT) if visible: # Always center. Cannot use layout file to change window position because window may be invisible when startup self.__center_window() return self.__on_close() def __open_default_stage(self): self.__execute_action("omni.kit.stage.templates", "create_new_stage_empty") def __on_close(self): # When welcome window is closed, setup the Viewport to a complete state settings = carb.settings.get_settings() if settings.get("/exts/omni.kit.welcome.window/autoSetupOnClose"): self.__execute_action("omni.app.setup", "enable_viewport_rendering") # Do not open default stage if stage already opened if not self.__stage_opened and not omni.usd.get_context().get_stage(): self.__open_default_stage() workflow = settings.get("/exts/omni.kit.welcome.window/default_workflow") if workflow: self.__active_workflow(workflow) def __active_workflow(self, workflow: str): carb.log_info(f"Trying to active workflow '{workflow}'...") self.__execute_action("omni.app.setup", "active_workflow", workflow) def __center_window(self): async def __delay_center(): await omni.kit.app.get_app().next_update_async() app_width = ui.Workspace.get_main_window_width() app_height = ui.Workspace.get_main_window_height() self._window.position_x = (app_width - self._window.frame.computed_width) / 2 self._window.position_y = (app_height - self._window.frame.computed_height) / 2 asyncio.ensure_future(__delay_center()) def __execute_action(self, ext_id: str, action_id: str, *args, **kwargs): try: import omni.kit.actions.core action_registry = omni.kit.actions.core.get_action_registry() action_registry.execute_action(ext_id, action_id, *args, **kwargs) except Exception as e: carb.log_error(f"Failed to execute action '{ext_id}::{action_id}': {e}") def register_page(self, ext_id: str, build_fn: Callable[[None], None]) -> bool: return self._model.register_page(ext_id, build_fn) def show_window(self, visible: bool = True, stage_opened: bool = False) -> None: self.__stage_opened = stage_opened or self.__stage_opened self._window.visible = visible def register_page(ext_id: str, build_fn: Callable[[None], None]) -> bool: if _extension_instance: return _extension_instance.register_page(ext_id, build_fn) else: return False def show_window(visible: bool = True, stage_opened: bool = False) -> None: if _extension_instance: _extension_instance.show_window(visible=visible, stage_opened=stage_opened)
5,793
Python
35.670886
122
0.619886
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/welcome_model.py
from typing import Callable, List, Optional import carb import carb.settings import omni.ui as ui from .welcome_page_item import WelcomePageItem SETTING_WELCOME_PAGES = "/app/welcome/page" class WelcomeModel(ui.AbstractItemModel): def __init__(self): super().__init__() self.__settings = carb.settings.get_settings() self._items = [WelcomePageItem(page) for page in self.__settings.get(SETTING_WELCOME_PAGES)] self._items.sort(key=lambda item: item.order) def get_item_children(self, item: Optional[WelcomePageItem]) -> List[WelcomePageItem]: return self._items def register_page(self, ext_id: str, build_fn: Callable[[None], None]) -> bool: for item in self._items: if item.extension_id == ext_id: item.build_fn = build_fn return True carb.log_warn(f"Extension {ext_id} not defined in welcome window.") return False
945
Python
30.533332
100
0.65291
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/actions.py
def register_actions(extension_id, extension_inst): try: import omni.kit.actions.core action_registry = omni.kit.actions.core.get_action_registry() actions_tag = "Welcome" action_registry.register_action( extension_id, "toggle_window", extension_inst.toggle_window, display_name="File->Welcome", description="Show/Hide welcome window", tag=actions_tag, ) except ImportError: pass def deregister_actions(extension_id): try: import omni.kit.actions.core action_registry = omni.kit.actions.core.get_action_registry() action_registry.deregister_all_actions_for_extension(extension_id) except ImportError: pass
777
Python
28.923076
74
0.622909
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/tests/__init__.py
from .test_window import *
26
Python
25.999974
26
0.769231
omniverse-code/kit/exts/omni.kit.welcome.window/omni/kit/welcome/window/tests/test_window.py
from omni.ui.tests.test_base import OmniUiTest from pathlib import Path import omni.ui as ui from ..extension import register_page, _extension_instance as welcome_instance CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") class TestWelcomeWindow(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() # Register page build function register_page("omni.kit.welcome.window", self.__build_ui) # Show window self._window = welcome_instance._window self._window.visible = True # After running each test async def tearDown(self): await super().tearDown() async def test_window(self): await self.docked_test_window(window=self._window, width=1280, height=720, block_devices=False) await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="window.png") def __build_ui(self): with ui.VStack(): ui.Label("PLACE PAGE WIDGETS HERE!", height=0)
1,186
Python
32.914285
103
0.680438
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/share_session_link_window.py
import carb import omni.kit.usd.layers as layers import omni.ui as ui import omni.kit.clipboard from .live_session_model import LiveSessionModel from .layer_icons import LayerIcons class ShareSessionLinkWindow: def __init__(self, layers_interface: layers.Layers, layer_identifier): self._window = None self._layers_interface = layers_interface self._base_layer_identifier = layer_identifier self._buttons = [] self._existing_sessions_combo = None self._existing_sessions_model = LiveSessionModel(self._layers_interface, layer_identifier, False) self._key_functions = { int(carb.input.KeyboardInput.ENTER): self._on_ok_button_fn, int(carb.input.KeyboardInput.ESCAPE): self._on_cancel_button_fn } self._build_ui() def _on_layer_event(event: carb.events.IEvent): payload = layers.get_layer_event_payload(event) if payload.event_type == layers.LayerEventType.LIVE_SESSION_LIST_CHANGED: if self._base_layer_identifier not in payload.identifiers_or_spec_paths: return self._existing_sessions_model.refresh_sessions(force=True) self._update_dialog_states() self._layers_event_subscription = layers_interface.get_event_stream().create_subscription_to_pop( _on_layer_event, name="Session Start Window Events" ) def destroy(self): self._layers_interface = None for button in self._buttons: button.set_clicked_fn(None) self._buttons.clear() if self._window: self._window.visible = False self._window = None if self._existing_sessions_model: self._existing_sessions_model.destroy() self._existing_sessions_model = None self._layers_event_subscription = None self._existing_sessions_combo = None self._existing_sessions_empty_hint = None self._error_label = None @property def visible(self): return self._window and self._window.visible @visible.setter def visible(self, value): if self._window: self._window.visible = value if not self._window.visible: self._existing_sessions_model.stop_channel() def _on_ok_button_fn(self): current_session = self._existing_sessions_model.current_session if not current_session or self._existing_sessions_model.empty(): self._error_label.text = "No Valid Session Selected." return omni.kit.clipboard.copy(current_session.shared_link) self._error_label.text = "" self.visible = False def _on_cancel_button_fn(self): self.visible = False def _on_key_pressed_fn(self, key, mod, pressed): if not pressed: return func = self._key_functions.get(key) if func: func() def _update_dialog_states(self): if self._existing_sessions_model.empty(): self._existing_sessions_empty_hint.visible = True else: self._existing_sessions_empty_hint.visible = False self._error_label.text = "" def _build_ui(self): """Construct the window based on the current parameters""" self._window = ui.Window( "SHARE LIVE SESSION LINK", visible=False, height=0, auto_resize=True, dockPreference=ui.DockPreference.DISABLED ) self._window.flags = ( ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE ) self._window.set_key_pressed_fn(self._on_key_pressed_fn) self._window.flags = self._window.flags | ui.WINDOW_FLAGS_MODAL self._existing_sessions_model.refresh_sessions(True) STYLES = { "Button.Image::confirm_button": { "image_url": LayerIcons.get("link"), "alignment" : ui.Alignment.RIGHT_CENTER }, "Label::copy_link": {"font_size": 14}, "Rectangle::hovering": {"border_radius": 2, "margin": 0, "padding": 0}, "Rectangle::hovering:hovered": {"background_color": 0xCC9E9E9E}, } with self._window.frame: with ui.VStack(height=0, style=STYLES): ui.Spacer(width=0, height=10) with ui.HStack(height=0): ui.Spacer(width=20) self._error_label = ui.Label( "", name="error_label", style={"color": 0xFF0000CC}, alignment=ui.Alignment.LEFT, word_wrap=True ) ui.Spacer(width=20) ui.Spacer(width=0, height=5) with ui.HStack(height=0): ui.Spacer(width=20) with ui.ZStack(height=0): self._existing_sessions_combo = ui.ComboBox( self._existing_sessions_model, width=self._window.width - 40, height=0 ) self._existing_sessions_empty_hint = ui.Label( " No Existing Sessions", alignment=ui.Alignment.LEFT_CENTER, style={"color": 0xFF3F3F3F} ) ui.Spacer(width=20) ui.Spacer(width=0, height=30) with ui.HStack(height=0): ui.Spacer() with ui.ZStack(width=120, height=30): ui.Rectangle(name="hovering") with ui.HStack(): ui.Spacer() ui.Label("Copy Link", width=0, name="copy_link") ui.Spacer(width=8) ui.Image(LayerIcons.get("link"), width=20) ui.Spacer() ok_button = ui.InvisibleButton(name="confirm_button") ok_button.set_clicked_fn(self._on_ok_button_fn) self._buttons.append(ok_button) ui.Spacer() ui.Spacer(width=0, height=20) self._update_dialog_states()
6,306
Python
38.41875
116
0.550428
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/layer_icons.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 pathlib import Path class LayerIcons: """A singleton that scans the icon folder and returns the icon depending on the type""" _icons = {} @staticmethod def on_startup(extension_path): current_path = Path(extension_path) icon_path = current_path.joinpath("icons") # Read all the svg files in the directory LayerIcons._icons = {icon.stem: icon for icon in icon_path.glob("*.svg")} @staticmethod def get(name, default=None): """Checks the icon cache and returns the icon if exists""" found = LayerIcons._icons.get(name) if not found and default: found = LayerIcons._icons.get(default) if found: return str(found) return None
1,194
Python
34.147058
91
0.688442
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/live_session_user_list.py
__all__ = ["LiveSessionUserList"] import carb import omni.usd import omni.client.utils as clientutils import omni.ui as ui import omni.kit.usd.layers as layers import omni.kit.collaboration.presence_layer as pl from .utils import build_live_session_user_layout, is_extension_loaded from omni.ui import color as cl TOOLTIP_STYLE = { "color": cl("#979797"), "Tooltip": {"background_color": 0xEE222222} } PRESENTER_STYLE = {"background_color": 0xff2032dc} # blue alternative: 0xffff851a class LiveSessionUserList: """Widget to build an user list to show all live session users of interested layer.""" def __init__(self, usd_context: omni.usd.UsdContext, base_layer_identifier: str, **kwargs): """ Constructor. Args: usd_context (omni.usd.UsdContext): USD Context instance. base_layer_identifier (str): Interested layer to listen to. follow_user_with_double_click (bool): Whether to enable follow user function of double click. Kwargs: icon_size (int): The width and height of the user icon. 16 pixel by default. spacing (int): The horizonal spacing between two icons. 2 pixel by default. show_myself (int): Whether to show local user or not. True by default show_myself_to_leftmost (bool): Whether to show local user to the left most, or right most otherwise. True by default. maximum_users (int): The maximum users to show, and show others with overflow. Unlimited by default. prim_path (Sdf.Path): Track Live Session for this prim only. """ self.__icon_size = kwargs.get("icon_size", 16) self.__spacing = kwargs.get("spacing", 2) self.__show_myself = kwargs.get("show_myself", True) self.__show_myself_to_leftmost = kwargs.get("show_myself_to_leftmost", True) self.__maximum_count = kwargs.get("maximum_users", None) self.__follow_user_with_double_click = kwargs.get("follow_user_with_double_click", False) timeline_ext_loaded = is_extension_loaded("omni.timeline.live_session") self.__allow_timeline_settings = kwargs.get("allow_timeline_settings", False) and timeline_ext_loaded self.__prim_path = kwargs.get("prim_path", None) self.__base_layer_identifier = base_layer_identifier self.__usd_context = usd_context self.__layers = layers.get_layers(usd_context) self.__live_syncing = layers.get_live_syncing() self.__layers_event_subscriptions = [] self.__main_layout: ui.HStack = ui.HStack(width=0, height=0) self.__all_user_layouts = {} self.__overflow = None self.__overflow_button = None self.__initialize() @property def layout(self) -> ui.HStack: return self.__main_layout def track_layer(self, layer_identifier): """Switches the base layer to listen to.""" if self.__base_layer_identifier != layer_identifier: self.__base_layer_identifier = layer_identifier self.__initialize() def empty(self): return len(self.__all_user_layouts) == 0 def __initialize(self): if not clientutils.is_local_url(self.__base_layer_identifier): for event in [ layers.LayerEventType.LIVE_SESSION_STATE_CHANGED, layers.LayerEventType.LIVE_SESSION_USER_JOINED, layers.LayerEventType.LIVE_SESSION_USER_LEFT, ]: layers_event_subscription = self.__layers.get_event_stream().create_subscription_to_pop_by_type( event, self.__on_layers_event, name=f"omni.kit.widget.live_session_management.LiveSessionUserList {str(event)}" ) self.__layers_event_subscriptions.append(layers_event_subscription) else: self.__layers_event_subscriptions = [] self.__build_ui() def __is_in_session(self): if self.__prim_path: return self.__live_syncing.is_prim_in_live_session(self.__prim_path, self.__base_layer_identifier) else: return self.__live_syncing.is_layer_in_live_session(self.__base_layer_identifier) def __build_myself(self): current_live_session = self.__live_syncing.get_current_live_session(self.__base_layer_identifier) if not current_live_session: return logged_user = current_live_session.logged_user with ui.ZStack(width=0, height=0): with ui.HStack(): ui.Spacer() self.__build_user_layout_or_overflow(current_live_session, logged_user, True, spacing=0) ui.Spacer() if self.__is_presenting(logged_user): with ui.VStack(): ui.Spacer() with ui.HStack(height=2, width=24): ui.Rectangle( height=2, width=12, alignment=ui.Alignment.BOTTOM, style={"background_color": 0xff00b86b} ) ui.Rectangle( height=2, width=12, alignment=ui.Alignment.BOTTOM, style=PRESENTER_STYLE ) else: with ui.VStack(): ui.Spacer() ui.Rectangle( height=2, width=24, alignment=ui.Alignment.BOTTOM, style={"background_color": 0xff00b86b} ) def __build_ui(self): # Destroyed if not self.__main_layout: return self.__overflow = False self.__main_layout.clear() self.__all_user_layouts.clear() self.__overflow_button = None if not self.__is_in_session(): return current_live_session = self.__live_syncing.get_current_live_session(self.__base_layer_identifier) with self.__main_layout: if self.__show_myself and self.__show_myself_to_leftmost: self.__build_myself() for peer_user in current_live_session.peer_users: self.__build_user_layout_or_overflow(current_live_session, peer_user, False, self.__spacing) if self.__overflow: break if self.__show_myself and not self.__show_myself_to_leftmost: ui.Spacer(self.__spacing) self.__build_myself() if self.empty(): self.__main_layout.visible = False else: self.__main_layout.visible = True @carb.profiler.profile def __on_layers_event(self, event): payload = layers.get_layer_event_payload(event) if payload.event_type == layers.LayerEventType.LIVE_SESSION_STATE_CHANGED: if not payload.is_layer_influenced(self.__base_layer_identifier): return if self.__allow_timeline_settings: import omni.timeline.live_session timeline_session = omni.timeline.live_session.get_timeline_session() if timeline_session is not None: timeline_session.add_presenter_changed_fn(self.__on_presenter_changed) self.__build_ui() elif ( payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_JOINED or payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_LEFT ): if not payload.is_layer_influenced(self.__base_layer_identifier): return if not self.__is_in_session(): return current_live_session = self.__live_syncing.get_current_live_session(self.__base_layer_identifier) user_id = payload.user_id if payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_LEFT: self.__all_user_layouts.pop(user_id, None) # FIXME: omni.ui does not support to remove single child. self.__build_ui() else: if user_id in self.__all_user_layouts or self.__overflow: # OMFP-2909: Refresh overflow button to rebuild tooltip. if self.__overflow and self.__overflow_button: self.__overflow_button.set_tooltip_fn(self.__build_tooltip) return user_info = current_live_session.get_peer_user_info(user_id) if not user_info: return self.__main_layout.add_child( self.__build_user_layout_or_overflow(current_live_session, user_info, False, self.__spacing) ) def destroy(self): # pragma: no cover self.__overflow_button = None self.__main_layout = None self.__layers_event_subscriptions = [] self.__layers = None self.__live_syncing = None self.__user_menu = None self.__all_user_layouts.clear() def __on_follow_user( self, x : float, y : float, button : int, modifier, user_info: layers.LiveSessionUser ): if button != int(carb.input.MouseInput.LEFT_BUTTON): # only left MB click return current_live_session = self.__live_syncing.get_current_live_session(self.__base_layer_identifier) if not current_live_session or current_live_session.logged_user_id == user_info.user_id: return presence_layer = pl.get_presence_layer_interface(self.__usd_context) if presence_layer: presence_layer.enter_follow_mode(user_info.user_id) def __on_mouse_clicked( self, x : float, y : float, button : int, modifier, user_info: layers.LiveSessionUser ): if button == int(carb.input.MouseInput.RIGHT_BUTTON): # right click to open menu import omni.timeline.live_session timeline_session = omni.timeline.live_session.get_timeline_session() if timeline_session is not None and timeline_session.am_i_owner(): self.__user_menu = ui.Menu("global_live_timeline_user") show = False with self.__user_menu: if timeline_session.is_presenter(user_info) and not timeline_session.is_owner(user_info): ui.MenuItem( "Withdraw Timeline Presenter", triggered_fn=lambda *args: self.__set_presenter(timeline_session, timeline_session.owner) ) show = True elif not timeline_session.is_presenter(user_info): ui.MenuItem( "Set as Timeline Presenter", triggered_fn=lambda *args: self.__set_presenter(timeline_session, user_info) ) show = True if show: self.__user_menu.show() def __set_presenter(self, timeline_session, user_info: layers.LiveSessionUser): timeline_session.presenter = user_info def __is_presenting(self, user_info: layers.LiveSessionUser) -> bool: if not self.__allow_timeline_settings: return False timeline_session = omni.timeline.live_session.get_timeline_session() return timeline_session.is_presenter(user_info) if timeline_session is not None else False def __on_presenter_changed(self, _): self.__build_ui() def __build_user_layout( self, live_session: layers.LiveSession, user_info: layers.LiveSessionUser, me: bool, spacing=2 ): if me: tooltip = f"{user_info.user_name} - Me" if live_session.merge_permission: tooltip += " (owner)" else: tooltip = f"{user_info.user_name} ({user_info.from_app})" if not live_session.merge_permission and live_session.owner == user_info.user_name: tooltip += " - owner" layout = ui.ZStack(width=0, height=0) with layout: with ui.HStack(): ui.Spacer(width=spacing) user_layout = build_live_session_user_layout( user_info, self.__icon_size, tooltip, self.__on_follow_user if self.__follow_user_with_double_click else None, self.__on_mouse_clicked if self.__allow_timeline_settings else None ) user_layout.set_style(TOOLTIP_STYLE) current_live_session = self.__live_syncing.get_current_live_session(self.__base_layer_identifier) logged_user = current_live_session.logged_user if logged_user.user_id != user_info.user_id and self.__is_presenting(user_info): with ui.VStack(): ui.Spacer() ui.Rectangle( height=2, width=24, alignment=ui.Alignment.BOTTOM, style=PRESENTER_STYLE ) return layout def __build_tooltip(self): # pragma: no cover live_session = self.__live_syncing.get_current_live_session(self.__base_layer_identifier) if not live_session: return total_users = len(live_session.peer_users) if self.__show_myself: total_users += 1 with ui.VStack(): with ui.HStack(style={"color": cl("#757575")}): ui.Spacer() ui.Label(f"{total_users} Users Connected", style={"font_size": 12}) ui.Spacer() ui.Spacer(height=0) ui.Separator(style={"color": cl("#4f4f4f")}) ui.Spacer(height=4) all_users = [] if self.__show_myself: all_users = [live_session.logged_user] all_users.extend(live_session.peer_users) for user in all_users: item_title = f"{user.user_name} ({user.from_app})" if live_session.owner == user.user_name: item_title += " - owner" with ui.HStack(): build_live_session_user_layout( user, self.__icon_size, "", self.__on_follow_user if self.__follow_user_with_double_click else None, self.__on_mouse_clicked if self.__allow_timeline_settings else None ) ui.Spacer(width=4) ui.Label(item_title, style={"font_size": 14}) ui.Spacer(height=2) @carb.profiler.profile def __build_user_layout_or_overflow( self, live_session: layers.LiveSession, user_info: layers.LiveSessionUser, me: bool, spacing=2 ): # pragma: no cover current_count = len(self.__all_user_layouts) if self.__overflow: return None if self.__maximum_count is not None and current_count >= self.__maximum_count: layout = ui.HStack(width=0) with layout: ui.Spacer(width=4) with ui.ZStack(): ui.Label("...", style={"font_size": 16}, aligment=ui.Alignment.V_CENTER) self.__overflow_button = ui.InvisibleButton(style=TOOLTIP_STYLE) self.__overflow_button.set_tooltip_fn(self.__build_tooltip) self.__overflow = True else: layout = self.__build_user_layout(live_session, user_info, me, spacing) self.__all_user_layouts[user_info.user_id] = layout self.__main_layout.visible = True self.__overflow_button = None return layout
15,529
Python
42.379888
130
0.57267
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/live_session_preferences.py
from .utils import QUICK_JOIN_ENABLED from .utils import SESSION_LIST_SELECT, SESSION_LIST_SELECT_DEFAULT_SESSION, SESSION_LIST_SELECT_LAST_SESSION import carb.settings import omni.ui as ui from omni.kit.widget.settings import SettingType from omni.kit.window.preferences import PreferenceBuilder class LiveSessionPreferences(PreferenceBuilder): SETTING_PAGE_NAME = "Live" def __init__(self): super().__init__(LiveSessionPreferences.SETTING_PAGE_NAME) self._settings = carb.settings.get_settings() self._checkbox_quick_join_enabled = None self._combobox_session_list_select = None def destroy(self): self._settings = None self._checkbox_quick_join_enabled = None self._combobox_session_list_select = None def build(self): self._checkbox_quick_join_enabled = None self._combobox_session_list_select = None with ui.VStack(height=0): with self.add_frame("Join"): with ui.VStack(): checkbox = self.create_setting_widget( "Quick Join Enabled", QUICK_JOIN_ENABLED, SettingType.BOOL, tooltip="Quick Join, creates and joins a Default session and bypasses dialogs." ) self._checkbox_quick_join_enabled = checkbox ui.Spacer() combo = self.create_setting_widget_combo( "Session List Select", SESSION_LIST_SELECT, [SESSION_LIST_SELECT_DEFAULT_SESSION, SESSION_LIST_SELECT_LAST_SESSION] ) self._combobox_session_list_select = combo ui.Spacer() ui.Spacer(height=10)
1,823
Python
37.80851
109
0.582556
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/extension.py
__all__ = ["stop_or_show_live_session_widget", "LiveSessionWidgetExtension"] import asyncio import os import carb import omni.ext import omni.kit.app import omni.usd import omni.client import omni.ui as ui import omni.kit.notification_manager as nm import omni.kit.usd.layers as layers import omni.kit.clipboard from typing import Union from enum import Enum from omni.kit.widget.prompt import PromptButtonInfo, PromptManager from .layer_icons import LayerIcons from .live_session_start_window import LiveSessionStartWindow from .live_session_end_window import LiveSessionEndWindow from .utils import is_extension_loaded, join_live_session, is_viewer_only_mode, is_quick_join_enabled from .join_with_session_link_window import JoinWithSessionLinkWindow from .share_session_link_window import ShareSessionLinkWindow from pxr import Sdf from .live_style import Styles _extension_instance = None _debugCollaborationWindow = None class LiveSessionMenuOptions(Enum): QUIT_ONLY = 0 MERGE_AND_QUIT = 1 class LiveSessionWidgetExtension(omni.ext.IExt): def on_startup(self, ext_id): global _extension_instance _extension_instance = self extension_path = omni.kit.app.get_app_interface().get_extension_manager().get_extension_path(ext_id) self._settings = None LayerIcons.on_startup(extension_path) self._live_session_end_window = None self._live_session_start_window = None self._join_with_session_link_window = None self._share_session_link_window = None self._live_session_menu = None self._app = omni.kit.app.get_app() try: from omni.kit.window.preferences import register_page from .live_session_preferences import LiveSessionPreferences self._settings = register_page(LiveSessionPreferences()) except ImportError: # pragma: no cover pass Styles.on_startup() def on_shutdown(self): global _extension_instance _extension_instance = None self._live_session_menu = None if self._live_session_end_window: self._live_session_end_window.destroy() self._live_session_end_window = None if self._live_session_start_window: self._live_session_start_window.destroy() self._live_session_start_window = None if self._join_with_session_link_window: self._join_with_session_link_window.destroy() self._join_with_session_link_window = None if self._share_session_link_window: self._share_session_link_window.destroy() self._share_session_link_window = None if self._settings: try: from omni.kit.window.preferences import unregister_page unregister_page(self._settings) except ImportError: pass self._settings = None @staticmethod def get_instance(): global _extension_instance return _extension_instance def _show_live_session_end_window(self, layers_interface: layers.Layers, layer_identifier): if self._live_session_end_window: self._live_session_end_window.destroy() async def show_dialog(): self._live_session_end_window = LiveSessionEndWindow(layers_interface, layer_identifier) async with self._live_session_end_window: pass asyncio.ensure_future(show_dialog()) def _show_join_with_session_link_window(self, layers_interface): current_session_link = None # Destroys it to center the window. if self._join_with_session_link_window: current_session_link = self._join_with_session_link_window.current_session_link self._join_with_session_link_window.destroy() self._join_with_session_link_window = JoinWithSessionLinkWindow(layers_interface) self._join_with_session_link_window.visible = True if current_session_link: self._join_with_session_link_window.current_session_link = current_session_link def _show_share_session_link_window(self, layers_interface, layer_identifier): # Destroys it to center the window. if self._share_session_link_window: self._share_session_link_window.destroy() self._share_session_link_window = ShareSessionLinkWindow(layers_interface, layer_identifier) self._share_session_link_window.visible = True def _show_live_session_menu_options(self, layers_interface, layer_identifier, is_stage_session, prim_path=None): live_syncing = layers_interface.get_live_syncing() current_session = live_syncing.get_current_live_session(layer_identifier) self._live_session_menu = ui.Menu("global_live_update") is_omniverse_stage = layer_identifier.startswith("omniverse://") is_live_prim = prim_path or live_syncing.is_layer_in_live_session(layer_identifier, live_prim_only=True) with self._live_session_menu: if is_omniverse_stage: if current_session: # If layer is in the live session already, showing `leave` and `end and merge` ui.MenuItem( "Leave Session", triggered_fn=lambda *args: self._on_leave_live_session_menu_options( layers_interface, LiveSessionMenuOptions.QUIT_ONLY, layer_identifier ), ) if not is_viewer_only_mode(): ui.MenuItem( "End and Merge", triggered_fn=lambda *args: self._on_leave_live_session_menu_options( layers_interface, LiveSessionMenuOptions.MERGE_AND_QUIT, layer_identifier ), ) ui.Separator() else: # If it's not in the live session, show `join` and `create`. ui.MenuItem( "Join Session", triggered_fn=lambda *args: self._show_live_session_start_window( layers_interface, layer_identifier, True, prim_path ), ) ui.MenuItem( "Create Session", triggered_fn=lambda *args: self._show_live_session_start_window( layers_interface, layer_identifier, False, prim_path ), ) # Don't show those options for live prim if not is_live_prim: # If layer_identifier is given, it's to show menu options for sublayer. # Show `copy` to copy session link. Otherwise, show share session dialog # to choose session to share. if is_stage_session: ui.Separator() ui.MenuItem( "Share Session Link", triggered_fn=lambda *args: self._show_share_session_link_window( layers_interface, layer_identifier ), ) elif current_session: ui.Separator() ui.MenuItem( "Copy Session Link", triggered_fn=lambda *args: self._copy_session_link(layers_interface), ) # If layer identifier is gven, it will not show `join with session link` menu option. if is_stage_session and not is_live_prim: ui.MenuItem( "Join With Session Link", triggered_fn=lambda *args: self._show_join_with_session_link_window(layers_interface), ) if is_extension_loaded("omni.kit.collaboration.debug_options"): # pragma: no cover ui.Separator() ui.MenuItem( "Open Debug Window", triggered_fn=lambda *args: self._on_open_debug_window(), ) if is_omniverse_stage and current_session and is_extension_loaded("omni.timeline.live_session"): ui.Separator() import omni.timeline.live_session timeline_session = omni.timeline.live_session.get_timeline_session() if timeline_session is not None: session_window = omni.timeline.live_session.get_session_window() ui.MenuItem( "Synchronize Timeline", triggered_fn=lambda *args: self._on_timeline_sync_triggered( layers_interface, layer_identifier, timeline_session ), checkable=True, checked=timeline_session.is_sync_enabled() ) if timeline_session.am_i_owner(): ui.MenuItem( "Set Timeline Owner", triggered_fn=lambda *args: self._on_open_timeline_session_window( layers_interface, layer_identifier, timeline_session, session_window ), ) elif not timeline_session.am_i_presenter(): if not self._requested_timeline_control(timeline_session): ui.MenuItem( "Request Timeline Ownership", triggered_fn=lambda *args: self._on_request_timeline_control(timeline_session), ) else: ui.MenuItem( "Withdraw Timeline Ownership Request", triggered_fn=lambda *args: self._on_withdraw_timeline_control(timeline_session), ) self._live_session_menu.show() def _show_live_session_start_window(self, layers_interface, layer_identifier, join_session=None, prim_path=None): if self._live_session_start_window: self._live_session_start_window.destroy() self._live_session_start_window = LiveSessionStartWindow(layers_interface, layer_identifier, prim_path) self._live_session_start_window.visible = True if join_session is not None: self._live_session_start_window.set_focus(join_session) def _show_session_start_window_or_menu( self, layers_interface: layers.Layers, show_join_options, layer_identifier, is_stage_session, join_session=None, prim_path=None ): if show_join_options: return self._show_live_session_menu_options( layers_interface, layer_identifier, is_stage_session, prim_path ) else: self._show_live_session_start_window(layers_interface, layer_identifier, join_session, prim_path) return None def _requested_timeline_control(self, timeline_session) -> bool: return timeline_session is not None and\ timeline_session.live_session_user in timeline_session.get_request_controls() def _on_request_timeline_control(self, timeline_session): if timeline_session is not None: timeline_session.request_control(True) def _on_withdraw_timeline_control(self, timeline_session): if timeline_session is not None: timeline_session.request_control(False) def _on_timeline_sync_triggered( self, layers_interface: layers.Layers, layer_identifier: str, timeline_session ): timeline_session.enable_sync(not timeline_session.is_sync_enabled()) def _on_open_timeline_session_window( self, layers_interface: layers.Layers, layer_identifier: str, timeline_session, session_window, ): session_window.show() def _on_open_debug_window( self, ): # pragma: no cover import omni.kit.collaboration.debug_options from omni.kit.collaboration.debug_options import CollaborationWindow global _debugCollaborationWindow if _debugCollaborationWindow is None : _debugCollaborationWindow = CollaborationWindow(width=480, height=320) _debugCollaborationWindow.visible = True def _on_leave_live_session_menu_options( self, layers_interface: layers.Layers, options: LiveSessionMenuOptions, layer_identifier: str, ): live_syncing = layers_interface.get_live_syncing() current_session = live_syncing.get_current_live_session(layer_identifier) if current_session: if options == LiveSessionMenuOptions.QUIT_ONLY: if self._can_quit_session_directly(live_syncing, layer_identifier): live_syncing.stop_live_session(layer_identifier) else: PromptManager.post_simple_prompt( "Leave Session", f"You are about to leave '{current_session.name}' session.", PromptButtonInfo("LEAVE", lambda: live_syncing.stop_live_session(layer_identifier)), PromptButtonInfo("CANCEL") ) elif options == LiveSessionMenuOptions.MERGE_AND_QUIT: layers_state = layers_interface.get_layers_state() is_read_only_on_disk = layers_state.is_layer_readonly_on_disk(layer_identifier) if current_session.merge_permission and not is_read_only_on_disk: self._show_live_session_end_window(layers_interface, layer_identifier) else: if is_read_only_on_disk: owner = layers_state.get_layer_owner(layer_identifier) else: owner = current_session.owner logged_user_name = current_session.logged_user_name if logged_user_name == owner and current_session.merge_permission: message = f"You currently do not have merge privileges as base layer is read-only on disk."\ " Do you want to quit this live session?" else: if is_read_only_on_disk: message = f"You currently do not have merge privileges as base layer is read-only on disk."\ f" Please contact '{owner}' to grant you write access. Do you want to quit this live session?" else: message = f"You currently do not have merge privileges, please contact '{owner}'"\ " to merge any changes from the live session. Do you want to quit this live session?" PromptManager.post_simple_prompt( "Permission Denied", message, PromptButtonInfo("YES", lambda: live_syncing.stop_live_session(layer_identifier)), PromptButtonInfo("NO") ) def _can_quit_session_directly(self, live_syncing: layers.LiveSyncing, layer_identifier): current_live_session = live_syncing.get_current_live_session(layer_identifier) if current_live_session: if current_live_session.peer_users: return False layer = Sdf.Find(current_live_session.root) if layer and len(layer.rootPrims) > 0: return False return True def _copy_session_link(self, layers_interface): live_syncing = layers_interface.get_live_syncing() current_session = live_syncing.get_current_live_session() if not current_session: return omni.kit.clipboard.copy(current_session.shared_link) def _stop_or_show_live_session_widget_internal( self, layers_interface: layers.Layers, stop_session_only, stop_session_forcely, show_join_options, layer_identifier, quick_join="", prim_path=None ): usd_context = layers_interface.usd_context stage = usd_context.get_stage() # Skips it if stage is not opened. if not stage: return None # By default, it will join live session of tht root layer. if not layer_identifier: # If layer identifier is not provided, it's to show global # menu that includes share sesison link and join session with link. # Otherwise, it will show menu for the sublayer session only. is_stage_session = True root_layer = stage.GetRootLayer() layer_identifier = root_layer.identifier else: is_stage_session = False layer_handle = Sdf.Find(layer_identifier) if ( not layer_handle or (not prim_path and not stage.HasLocalLayer(layer_handle)) or (prim_path and layer_handle not in stage.GetUsedLayers()) ): nm.post_notification( "Only a layer opened in the current stage can start a live-sync session.", status=nm.NotificationStatus.WARNING ) return None if not layer_identifier.startswith("omniverse://"): if is_stage_session and not prim_path: return self._show_live_session_menu_options(layers_interface, layer_identifier, is_stage_session) else: nm.post_notification( "Only a layer in Nucleus can start a live-sync session.", status=nm.NotificationStatus.WARNING ) return None live_syncing = layers_interface.get_live_syncing() if not live_syncing.is_layer_in_live_session(layer_identifier): if not quick_join and not show_join_options: quick_join = "Default" elif quick_join and show_join_options: show_join_options = False if quick_join: # This runs when the main live button is pressed. live_syncing = layers_interface.get_live_syncing() quick_session = live_syncing.find_live_session_by_name(layer_identifier, quick_join) if is_quick_join_enabled(): if not quick_session: quick_session = live_syncing.create_live_session( layer_identifier=layer_identifier, name=quick_join ) if not quick_session: nm.post_notification( "Cannot create a Live session on a read only location. Please\n" "save root file in a writable location.", status=nm.NotificationStatus.WARNING ) return None join_live_session( layers_interface, layer_identifier, quick_session, prim_path, is_viewer_only_mode() ) return None else: join_session = True if quick_session is not None else False return self._show_session_start_window_or_menu( layers_interface, False, layer_identifier, False, join_session, prim_path ) else: return self._show_session_start_window_or_menu( layers_interface, show_join_options, layer_identifier, is_stage_session, prim_path ) elif stop_session_forcely: live_syncing.stop_live_session(layer_identifier) elif stop_session_only: self._on_leave_live_session_menu_options( layers_interface, LiveSessionMenuOptions.QUIT_ONLY, layer_identifier ) else: return self._show_live_session_menu_options(layers_interface, layer_identifier, is_stage_session, prim_path) return None def stop_or_show_live_session_widget( usd_context: Union[str, omni.usd.UsdContext] = "", stop_session_only: bool = False, stop_session_forcely: bool = False, show_join_options: bool = True, layer_identifier: str = None, quick_join: str = False, prim_path: Union[str, Sdf.Path] = None, ): """Stops current live session or shows widget to join/leave session. If current session is empty, it will show the session start dialog. If current session is not empty, it will stop session directly or show stop session menu. Args: usd_context: The current usd context to operate on. stop_session_only: If it's true, it will ask user to stop session if session is not empty without showing merge options. If it's false, it will show both leave and merge session options. stop_session_forcely: If it's true, it will stop session forcely even if current sesison is not empty. Otherwise, it will show leave session or both leave and merge options that's dependent on if stop_session_only is true or false. show_join_options: If it's true, it will show menu options. If it's false, it will show session dialog directly. This option is only used when layer is not in a live session. If both quick_join and this param have the same value, it will do quick join. layer_identifier: By default, it will join/stop the live session of the root layer. If layer_identifier is not None, it will join/stop the live session for the specific sublayer. quick_join: Quick Join / Leave a session without bringing up a dialog. This option is only used when layer is not in a live session. If both show_join_options and this param have the same value, this param will be True. prim_path: If prim path is specified, it will join live session for the prim instead of sublayers. Only prim with references or payloads supports to join a live session. Prim path is not needed when it's to stop a live session. Returns: It will return the menu widgets created if it needs to create options menu. Otherwise, it will return None. """ instance = LiveSessionWidgetExtension.get_instance() if not instance: # pragma: no cover carb.log_error("omni.kit.widget.live_session_management extension must be enabled.") return layers_interface = layers.get_layers(usd_context) return instance._stop_or_show_live_session_widget_internal( layers_interface, stop_session_only, stop_session_forcely, show_join_options, layer_identifier, quick_join=quick_join, prim_path=prim_path )
23,531
Python
44.34104
135
0.576984
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/__init__.py
from .extension import * from .utils import * from .live_session_user_list import * from .live_session_model import * from .live_session_camera_follower_list import *
166
Python
32.399994
48
0.771084
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/file_picker.py
import omni import carb import os import omni.client import omni.kit.notification_manager as nm from omni.kit.widget.prompt import PromptButtonInfo, PromptManager from .filebrowser import FileBrowserMode, FileBrowserSelectionType, FileBrowserUI class FilePicker: def __init__(self, title, mode, file_type, filter_options, save_extensions=None): self._mode = mode self._ui_handler = None self._app = omni.kit.app.get_app() self._open_handler = None self._cancel_handler = None self._save_extensions = save_extensions self._ui_handler = FileBrowserUI( title, mode, file_type, filter_options, enable_versioning_pane=(mode == FileBrowserMode.OPEN) ) def _show_prompt(self, file_path, file_save_handler): def _on_file_save(): if file_save_handler: file_save_handler(file_path, True) PromptManager.post_simple_prompt( f'{omni.kit.ui.get_custom_glyph_code("${glyphs}/exclamation.svg")} Overwrite', f"File {os.path.basename(file_path)} already exists, do you want to overwrite it?", ok_button_info=PromptButtonInfo("YES", _on_file_save), cancel_button_info=PromptButtonInfo("NO") ) def _save_and_prompt_if_exists(self, file_path, file_save_handler=None): result, _ = omni.client.stat(file_path) if result == omni.client.Result.OK: self._show_prompt(file_path, file_save_handler) elif file_save_handler: file_save_handler(file_path, False) def _on_file_open(self, path, filter_index=-1): if self._mode == FileBrowserMode.SAVE: _, ext = os.path.splitext(path) if ( filter_index >= 0 and self._save_extensions and filter_index < len(self._save_extensions) and ext not in self._save_extensions ): path += self._save_extensions[filter_index] self._save_and_prompt_if_exists(path, self._open_handler) elif self._open_handler: self._open_handler(path, False) def _on_cancel_open(self): if self._cancel_handler: self._cancel_handler() def set_file_selected_fn(self, file_open_handler): self._open_handler = file_open_handler def set_cancel_fn(self, cancel_handler): self._cancel_handler = cancel_handler def show(self, dir=None, filename=None): if self._ui_handler: if dir: self._ui_handler.set_current_directory(dir) if filename: self._ui_handler.set_current_filename(filename) self._ui_handler.open(self._on_file_open, self._on_cancel_open) def hide(self): if self._ui_handler: self._ui_handler.hide() def set_current_directory(self, dir): if self._ui_handler: self._ui_handler.set_current_directory(dir) def set_current_filename(self, filename): if self._ui_handler: self._ui_handler.set_current_filename(filename) def get_current_filename(self): if self._ui_handler: return self._ui_handler.get_current_filename() return None def destroy(self): if self._ui_handler: self._ui_handler.destroy() self._ui_handler = None
3,413
Python
33.836734
105
0.600938
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/utils.py
__all__ = ["build_live_session_user_layout", "is_viewer_only_mode", "VIEWER_ONLY_MODE_SETTING"] import asyncio import carb import os import omni.usd import omni.kit.app import omni.ui as ui import omni.kit.usd.layers as layers from omni.kit.async_engine import run_coroutine from omni.kit.widget.prompt import PromptManager, PromptButtonInfo from pxr import Sdf from typing import Union, List # When this setting is True, it will following the rules: # * When joining a live session, if the user has unsaved changes, # skip the dialog and automatically reload the stage, then join the session. # * When creating a live session, if the user has unsaved changes, # skip the dialog and automatically reload the stage, then create the session. # * When leaving a live session, do not offer to merge changes, # instead reload the stage to its original state VIEWER_ONLY_MODE_SETTING = "/exts/omni.kit.widget.live_session_management/viewer_only_mode" # When this setting is True, it will show the Join/Create Session dialog wqhen the quick live button is pressed. # When this setting if False, it will auto Create Session or Join with no dialog shown. QUICK_JOIN_ENABLED = "/exts/omni.kit.widget.live_session_management/quick_join_enabled" SESSION_LIST_SELECT = "/exts/omni.kit.widget.live_session_management/session_list_select" SESSION_LIST_SELECT_DEFAULT_SESSION = "DefaultSession" SESSION_LIST_SELECT_LAST_SESSION = "LastSession" def is_viewer_only_mode(): return carb.settings.get_settings().get(VIEWER_ONLY_MODE_SETTING) or False def is_quick_join_enabled(): return carb.settings.get_settings().get(QUICK_JOIN_ENABLED) or False def get_session_list_select(): return carb.settings.get_settings().get(SESSION_LIST_SELECT) def join_live_session(layers_interface, layer_identifier, current_session, prim_path=None, force_reload=False): layers_state = layers_interface.get_layers_state() live_syncing = layers_interface.get_live_syncing() layer_handle = Sdf.Find(layer_identifier) def fetch_and_join(layer_identifier): with Sdf.ChangeBlock(): layer = Sdf.Find(layer_identifier) if layer: layer.Reload(True) if layers_state.is_auto_reload_layer(layer_identifier): layers_state.remove_auto_reload_layer(layer_identifier) return live_syncing.join_live_session(current_session, prim_path) async def post_simple_prompt(title, text, ok_button_info, cancel_button_info): await omni.kit.app.get_app().next_update_async() PromptManager.post_simple_prompt( title, text, ok_button_info=ok_button_info, cancel_button_info=cancel_button_info ) is_outdated = layers_state.is_layer_outdated(layer_identifier) if force_reload and (is_outdated or layer_handle.dirty): fetch_and_join(layer_identifier) elif is_outdated: asyncio.ensure_future( post_simple_prompt( "Join Session", "The file you would like to go live on is not up to date, " "a newer version must be fetched for joining a live session. " "Press Fetch to get the most recent version or use Cancel " "if you would like to save a copy first.", ok_button_info=PromptButtonInfo( "Fetch", lambda: fetch_and_join(layer_identifier) ), cancel_button_info=PromptButtonInfo("Cancel") ) ) elif layer_handle.dirty: asyncio.ensure_future( post_simple_prompt( "Join Session", "There are unsaved changes to your file. Joining this live session will discard any unsaved changes.", ok_button_info=PromptButtonInfo( "Join", lambda: fetch_and_join(layer_identifier) ), cancel_button_info=PromptButtonInfo("Cancel") ) ) else: if layers_state.is_auto_reload_layer(layer_identifier): layers_state.remove_auto_reload_layer(layer_identifier) return live_syncing.join_live_session(current_session, prim_path) return True def is_extension_loaded(extansion_name: str) -> bool: """ Returns True if the extension with the given name is loaded. """ def is_ext(id: str, extension_name: str) -> bool: id_name = id.split("-")[0] return id_name == extension_name app = omni.kit.app.get_app_interface() ext_manager = app.get_extension_manager() extensions = ext_manager.get_extensions() loaded = next((ext for ext in extensions if is_ext(ext["id"], extansion_name) and ext["enabled"]), None) return not not loaded def build_live_session_user_layout(user_info: layers.LiveSessionUser, size=16, tooltip = "", on_double_click_fn: callable = None, on_mouse_click_fn: callable = None) -> ui.ZStack: """Builds user icon.""" user_layout = ui.ZStack(width=size, height=size) with user_layout: circle = ui.Circle( style={"background_color": ui.color(*user_info.user_color)} ) if on_double_click_fn: circle.set_mouse_double_clicked_fn(lambda x, y, b, m, user_info_t=user_info: on_double_click_fn( x, y, b, m, user_info_t)) if on_mouse_click_fn: circle.set_mouse_pressed_fn(lambda x, y, b, m, user_info_t=user_info: on_mouse_click_fn( x, y, b, m, user_info_t)) ui.Label( layers.get_short_user_name(user_info.user_name), style={"font_size": size - 5, "color": 0xFFFFFFFF}, alignment=ui.Alignment.CENTER ) if tooltip: user_layout.set_tooltip(tooltip) return user_layout def reload_outdated_layers( layer_identifiers: Union[str, List[str]], usd_context_name_or_instance: Union[str, omni.usd.UsdContext] = None ) -> None: """Reloads outdated layer. It will show prompt to user if layer is in a Live Session.""" if isinstance(usd_context_name_or_instance, str): usd_context = omni.usd.get_context(usd_context_name_or_instance) elif isinstance(usd_context_name_or_instance, omni.usd.UsdContext): usd_context = usd_context_name_or_instance elif not usd_context_name_or_instance: usd_context = omni.usd.get_context() if not usd_context: carb.log_error("Failed to reload layer as usd context is not invalid.") return if isinstance(layer_identifiers, str): layer_identifiers = [layer_identifiers] live_syncing = layers.get_live_syncing(usd_context) layers_state = layers.get_layers_state(usd_context) all_layer_ids = layers_state.get_all_outdated_layer_identifiers() if not all_layer_ids: return layer_identifiers = [layer_id for layer_id in layer_identifiers if layer_id in all_layer_ids] if not layer_identifiers: return count = 0 for layer_identifier in layer_identifiers: if live_syncing.is_layer_in_live_session(layer_identifier): count += 1 if count == 1: title = f"{os.path.basename(layer_identifier)} is in a Live Session" else: title = "Reload Layers In Live Session" def reload_layers(layer_identifiers): async def reload(layer_identifiers): layers.LayerUtils.reload_all_layers(layer_identifiers) run_coroutine(reload(layer_identifiers)) if count != 0: PromptManager.post_simple_prompt( title, "Reloading live layers has performance implications and some live edits may be lost - OK to proceed?", PromptButtonInfo("YES", lambda: reload_layers(layer_identifiers)), PromptButtonInfo("NO") ) else: reload_layers(layer_identifiers)
7,853
Python
36.4
179
0.657328
omniverse-code/kit/exts/omni.kit.widget.live_session_management/omni/kit/widget/live_session_management/join_with_session_link_window.py
__all__ = ["JoinWithSessionLinkWindow"] import asyncio import carb import omni.kit.usd.layers as layers import omni.ui as ui import omni.kit.notification_manager as nm import omni.kit.app import omni.kit.clipboard from pxr import Usd from .layer_icons import LayerIcons class JoinWithSessionLinkWindow: def __init__(self, layers_interface: layers.Layers): self._window = None self._layers_interface = layers_interface self._buttons = [] self._session_link_input_field = None self._session_link_input_hint = None self._error_label = None self._session_link_begin_edit_cb = None self._session_link_end_edit_cb = None self._session_link_edit_cb = None self._key_functions = { int(carb.input.KeyboardInput.ENTER): self._on_ok_button_fn, int(carb.input.KeyboardInput.ESCAPE): self._on_cancel_button_fn } self._build_ui() def destroy(self): self._layers_interface = None for button in self._buttons: button.set_clicked_fn(None) self._buttons.clear() if self._window: self._window.visible = False self._window = None self._session_link_input_hint = None self._session_link_input_field = None self._session_link_begin_edit_cb = None self._session_link_end_edit_cb = None self._session_link_edit_cb = None self._error_label = None @property def visible(self): return self._window and self._window.visible @visible.setter def visible(self, value): if self._window: self._window.visible = value if value: async def focus_field(): await omni.kit.app.get_app().next_update_async() if self._session_link_input_field: self._session_link_input_field.focus_keyboard() asyncio.ensure_future(focus_field()) @property def current_session_link(self): if self._session_link_input_field: return self._session_link_input_field.model.get_value_as_string() return "" @current_session_link.setter def current_session_link(self, value): if self._session_link_input_field: self._session_link_input_field.model.set_value(value) def _validate_session_link(self, str): return str and Usd.Stage.IsSupportedFile(str) def _on_ok_button_fn(self): if not self._update_button_status(): return self._error_label.text = "" self.visible = False session_link = self._session_link_input_field.model.get_value_as_string() session_link = session_link.strip() live_syncing = self._layers_interface.get_live_syncing() async def open_stage_with_live_session(live_syncing, session_link): (success, error) = await live_syncing.open_stage_with_live_session_async(session_link) if not success: nm.post_notification(f"Failed to open stage {session_link} with live session: {error}.") asyncio.ensure_future(open_stage_with_live_session(live_syncing, session_link)) def _on_cancel_button_fn(self): self.visible = False def _on_key_pressed_fn(self, key, mod, pressed): if not pressed: return func = self._key_functions.get(key) if func: func() def _update_button_status(self): if not self._session_link_input_field: return False session_link = self._session_link_input_field.model.get_value_as_string() session_link = session_link.strip() join_button = self._buttons[0] if not self._validate_session_link(session_link): if session_link: self._error_label.text = "The link is not supported for USD." else: self._error_label.text = "" join_button.enabled = False else: self._error_label.text = "" join_button.enabled = True if not session_link: self._session_link_input_hint.visible = True else: self._session_link_input_hint.visible = False return join_button.enabled def _on_session_link_begin_edit(self, model): self._update_button_status() def _on_session_link_end_edit(self, model): self._update_button_status() def _on_session_link_edit(self, model): self._update_button_status() def _on_paste_link_fn(self): link = omni.kit.clipboard.paste() if link: self._session_link_input_field.model.set_value(link) def _build_ui(self): """Construct the window based on the current parameters""" self._window = ui.Window( "JOIN LIVE SESSION WITH LINK", visible=False, width=500, height=0, auto_resize=True, dockPreference=ui.DockPreference.DISABLED ) self._window.flags = ( ui.WINDOW_FLAGS_NO_COLLAPSE | ui.WINDOW_FLAGS_NO_SCROLLBAR | ui.WINDOW_FLAGS_NO_RESIZE | ui.WINDOW_FLAGS_NO_MOVE ) self._window.set_key_pressed_fn(self._on_key_pressed_fn) self._window.flags = self._window.flags | ui.WINDOW_FLAGS_MODAL STYLES = { "Rectangle::hovering": {"background_color": 0x0, "border_radius": 2, "margin": 0, "padding": 0}, "Rectangle::hovering:hovered": {"background_color": 0xFF9E9E9E}, "Button.Image::paste_button": {"image_url": LayerIcons().get("paste"), "color": 0xFFD0D0D0}, "Button::paste_button": {"background_color": 0x0, "margin": 0}, "Button::paste_button:checked": {"background_color": 0x0}, "Button::paste_button:hovered": {"background_color": 0x0}, "Button::paste_button:pressed": {"background_color": 0x0}, } with self._window.frame: with ui.VStack(height=0, style=STYLES): ui.Spacer(width=0, height=10) with ui.HStack(height=0): ui.Spacer(width=20) self._error_label = ui.Label("", name="error_label", style={"color": 0xFF0000CC}, alignment=ui.Alignment.LEFT, word_wrap=True) ui.Spacer(width=20) ui.Spacer(width=0, height=5) with ui.ZStack(height=0): with ui.HStack(height=0): ui.Spacer(width=20) with ui.ZStack(width=20, height=20): ui.Rectangle(name="hovering") paste_link_button = ui.ToolButton(name="paste_button", image_width=20, image_height=20) paste_link_button.set_clicked_fn(self._on_paste_link_fn) ui.Spacer(width=4) with ui.VStack(): ui.Spacer() with ui.ZStack(height=0): self._session_link_input_field = ui.StringField( name="new_session_link_field", width=self._window.width - 40, height=0 ) self._session_link_input_hint = ui.Label( " Paste Live Session Link Here", alignment=ui.Alignment.LEFT_CENTER, style={"color": 0xFF3F3F3F} ) self._session_link_begin_edit_cb = self._session_link_input_field.model.subscribe_begin_edit_fn( self._on_session_link_begin_edit ) self._session_link_end_edit_cb = self._session_link_input_field.model.subscribe_end_edit_fn( self._on_session_link_end_edit ) self._session_link_edit_cb = self._session_link_input_field.model.subscribe_value_changed_fn( self._on_session_link_edit ) ui.Spacer() ui.Spacer(width=20) ui.Spacer(width=0, height=30) with ui.HStack(height=0): ui.Spacer(height=0) ok_button = ui.Button("JOIN", name="confirm_button", width=120, height=0) ok_button.set_clicked_fn(self._on_ok_button_fn) cancel_button = ui.Button("CANCEL", name="cancel_button", width=120, height=0) cancel_button.set_clicked_fn(self._on_cancel_button_fn) self._buttons.append(ok_button) self._buttons.append(cancel_button) ui.Spacer(height=0, width=20) ui.Spacer(width=0, height=20) # 0 for ok button, 0 for cancel button and appends paste link button at last self._buttons.append(paste_link_button) self._update_button_status()
9,226
Python
40.008889
146
0.54574