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.iray.settings.core/omni/iray/settings/core/widgets/heatmap_bar.py
import omni.ui as ui import carb.settings as settings class IrayHeatmapBarWidget: def __init__(self, parent_widget, width = 400, height = 20, steps = 4, type = "illumination"): self._settings = settings.get_settings() if type == "illumination": self._unit = "Lux" self._rangeMinSetting = "/iray/illuminanceMin" self._rangeMaxSetting = "/iray/illuminanceMax" self._rangeUserMinSetting = "/rtx/iray/illuminanceUserMin" self._rangeUserMaxSetting = "/rtx/iray/illuminanceUserMax" self._valueSetting = "/iray/illuminanceVal" self._rangeAutoRangeSetting = "/rtx/iray/illuminanceAutoRange" elif type == "lumination": self._unit = "Nits" self._rangeMinSetting = "/iray/luminanceMin" self._rangeMaxSetting = "/iray/luminanceMax" self._rangeUserMinSetting = "/rtx/iray/luminanceUserMin" self._rangeUserMaxSetting = "/rtx/iray/luminanceUserMax" self._valueSetting = "/iray/luminanceVal" self._rangeAutoRangeSetting = "/rtx/iray/luminanceAutoRange" else: raise Exception("Unsupported heatmap type " + type) self._parent_widget = parent_widget self._width = width self._height = height self._labels = [] self._steps = steps self._illum_min = 0.0 self._illum_max = 0.0 self._illum_value = 0.0 self._illum_value_str = "0.0 " + self._unit self._illum_value_fraction = 0.0 self._update_values() with ui.Frame(): with ui.VStack(): p = ui.Percent((100/self._steps) * 0.5) # current illuminance value with ui.HStack(height=20): self._illum_value_spacer_l = ui.Spacer() self._illum_value_label = ui.Label("0.0", alignment=ui.Alignment.CENTER, width=ui.Percent(p*2)) self._illum_value_spacer_r = ui.Spacer() self._update_value() # color bar with ui.HStack(height=20): ui.Spacer(width=ui.Percent(p)) pixels = [0] * width * height * 4 self._color_bar = ui.ByteImageProvider() self._color_bar.set_bytes_data(pixels, [width, height]) ui.ImageWithProvider(self._color_bar, fill_policy=ui.IwpFillPolicy.IWP_STRETCH) self._fill_color_bar(self._illum_value_fraction) ui.Spacer(width=ui.Percent(p)) # ticks bar with ui.HStack(height=10): ui.Spacer(width=ui.Percent(p)) self._ticks_bar = ui.ByteImageProvider() self._ticks_bar.set_bytes_data(pixels, [width, height]) ui.ImageWithProvider(self._ticks_bar, fill_policy=ui.IwpFillPolicy.IWP_STRETCH, ) self._fill_ticks_bar(0.0) ui.Spacer(width=ui.Percent(p)) with ui.HStack(height=20): for i in range(steps): self._labels.append(ui.Label(str(i), alignment=ui.Alignment.CENTER)) self._update_legend() self._settings.subscribe_to_node_change_events(self._rangeMinSetting, self._update_cb) self._settings.subscribe_to_node_change_events(self._rangeMaxSetting, self._update_cb) self._settings.subscribe_to_node_change_events(self._rangeUserMinSetting, self._update_cb) self._settings.subscribe_to_node_change_events(self._rangeUserMaxSetting, self._update_cb) self._settings.subscribe_to_node_change_events(self._rangeAutoRangeSetting, self._update_cb) self._settings.subscribe_to_node_change_events(self._valueSetting, self._update_cb) def _fill_ticks_bar(self, val): pixels = [0] * self._width * self._height * 4 l = int(self._width * val) r = int((self._width) / (self._steps - 1)) for x in range(self._width): for y in range(self._height): p = y * self._width * 4 + x * 4 if x % r < 2 or x >= self._width - 2: pixels[p + 0] = 255 pixels[p + 1] = 255 pixels[p + 2] = 255 pixels[p + 3] = 255 self._ticks_bar.set_bytes_data(pixels, [self._width, self._height]) def _fill_color_bar(self, val): def get_color(t): c = [255,255,255] if t < 0.25: c[0] = 0 c[1] = int(4.0 * t * 255) elif t < 0.5: c[0] = 0 c[2] = int((1.0 + 4.0 * (0.25 * 1.0 - t)) * 255) elif t < 0.75: c[0] = int(4.0 * (t - 0.5) * 255) c[2] = 0 else: c[1] = int((1.0 + 4.0 * (0.75 - t)) * 255) c[2] = 0 return c pixels = [255] * self._width * self._height * 4 l = int(self._width * val) for x in range(self._width): for y in range(self._height): p = y * self._width * 4 + x * 4 if x >= l-1 and x <= l+1: c = [255] * 4 else: c = get_color(x / self._width) pixels[p + 0] = c[0] pixels[p + 1] = c[1] pixels[p + 2] = c[2] self._color_bar.set_bytes_data(pixels, [self._width, self._height]) def _update_values(self): self._illum_min = float(self._settings.get(self._get_range_min_name()) or 0.0) self._illum_max = float(self._settings.get(self._get_range_max_name()) or 10000.0) if self._illum_max <= 0.0: self._illum_max = 10000 self._illum_value_str = settings.get_settings().get(self._valueSetting) or "0.0 " + self._unit try: self._illum_value = float(self._illum_value_str.split()[0]) except: self._illum_value = 0.0 d = self._illum_max - self._illum_min if d == 0.0: d = 1.0 if self._illum_value > self._illum_max:# can happen with user-range self._illum_value = self._illum_max if self._illum_value < self._illum_min:# can happen with user-range self._illum_value = self._illum_min self._illum_value_fraction = (self._illum_value - self._illum_min) / d def _update_cb(self, item, event_type): self._update_values() self._update_legend() self._update_value() self._fill_color_bar(self._illum_value_fraction) def _update_legend(self): incr = (self._illum_max - self._illum_min) / (self._steps - 1) for i in range(self._steps): self._labels[i].text = "%.1f" % (self._illum_min + i * incr) def _update_value(self): w1 = 1/ (1 /self._steps + 1) self._illum_value_label.text = self._illum_value_str p = 0#ui.Percent((100/self._steps) * 0.5) p0 = self._illum_value_fraction * w1 * 100 if p0-p <= 0: p0 = 0 self._illum_value_spacer_l.width = ui.Percent(p0-p) def _get_range_min_name(self): auto_range = settings.get_settings().get(self._rangeAutoRangeSetting) if auto_range: return self._rangeMinSetting return self._rangeUserMinSetting def _get_range_max_name(self): auto_range = settings.get_settings().get(self._rangeAutoRangeSetting) if auto_range: return self._rangeMaxSetting return self._rangeUserMaxSetting def __del__(self): self._settings.unsubscribe_to_change_events(self._update_cb)
8,098
Python
39.90404
115
0.508644
omniverse-code/kit/exts/omni.iray.settings.core/omni/iray/settings/core/tests/__init__.py
from .test_settings import TestIRaySettingsUI
45
Python
44.999955
45
0.888889
omniverse-code/kit/exts/omni.iray.settings.core/omni/iray/settings/core/tests/test_settings.py
import carb import omni.kit.test import omni.usd from omni.kit import ui_test settings = carb.settings.get_settings() class TestIRaySettingsUI(omni.kit.test.AsyncTestCase): async def setUp(self): super().setUp() # We need to trigger Iray load to get the default render-settings values written to carb.settings # Viewports state is valid without any open stage, and only loads renderer when stage is opened. await omni.usd.get_context().new_stage_async() await omni.kit.app.get_app().next_update_async() def get_render_setings_window(self): render_settings_window = ui_test.find("Render Settings") render_settings_window.widget.height = 600 render_settings_window.widget.width = 600 render_settings_window.widget.visible = True return render_settings_window async def test_bool_checkbox_setting(self): render_settings_window = self.get_render_setings_window() self.assertTrue(render_settings_window) setting_name = "/iray/device/cpuEnabled" #We don't have to set the renderer as we assume only IRay is loaded # Set initial value of the setting settings.set(setting_name, False) await omni.kit.app.get_app().next_update_async() #choose the "Iray" tab in tthe render settings main combo button = render_settings_window.find("Frame/VStack[0]/VStack[0]/ScrollingFrame[0]/ZStack[0]/CommonIRaySettingStack") self.assertTrue(button) await button.click() #Get the collapsable frame for Device Settings and open it collapsable_frame = render_settings_window.find("**/Device Settings") self.assertTrue(collapsable_frame) collapsable_frame.widget.collapsed = False await omni.kit.app.get_app().next_update_async() setting_hstack = collapsable_frame.find("/**/HStack_CPU_Enabled") self.assertTrue(isinstance(setting_hstack.widget, omni.ui.HStack)) check_box = setting_hstack.find("**/CheckBox[0]") self.assertTrue(isinstance(check_box.widget, omni.ui.CheckBox)) await check_box.click(human_delay_speed=10) setting_value = settings.get(setting_name) self.assertTrue(setting_value) await check_box.click(human_delay_speed=10) setting_value = settings.get(setting_name) self.assertFalse(setting_value) async def test_combo_box_setting(self): render_settings_window = self.get_render_setings_window() setting_name = "/rtx/iray/canvasType" #We don't have to set the renderer as we assume only IRay is loaded # Set initial value settings.set(setting_name, "result") await omni.kit.app.get_app().next_update_async() #choose the "Iray" tab in each case button = render_settings_window.find("Frame/VStack[0]/VStack[0]/ScrollingFrame[0]/ZStack[0]/CommonIRaySettingStack") await button.click() #Get the collapsable frame for Device Settings and open it collapsable_frame = render_settings_window.find("**/Render Settings") collapsable_frame.widget.collapsed = False await omni.kit.app.get_app().next_update_async() setting_hstack = collapsable_frame.find("/**/HStack_Canvas") self.assertTrue(isinstance(setting_hstack.widget, omni.ui.HStack)) combo_box = setting_hstack.find("ComboBox[0]") self.assertTrue(isinstance(combo_box.widget, omni.ui.ComboBox)) combo_box.model.get_item_value_model(None, 0).set_value(1) await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await omni.kit.app.get_app().next_update_async() await ui_test.human_delay(50) value = settings.get(setting_name) self.assertTrue(value == "diffuse", f"value is {value}") async def test_int_setting(self): render_settings_window = self.get_render_setings_window() setting_name = "/rtx/iray/progressive_rendering_max_samples" #We don't have to set the renderer as we assume only IRay is loaded # Set initial value settings.set(setting_name, 100) await omni.kit.app.get_app().next_update_async() await ui_test.human_delay(50) #choose the "Iray" tab in each case button = render_settings_window.find("Frame/VStack[0]/VStack[0]/ScrollingFrame[0]/ZStack[0]/CommonIRaySettingStack") await button.click() #Get the collapsable frame for Device Settings and open it collapsable_frame = render_settings_window.find("**/Scheduler Settings") collapsable_frame.widget.collapsed = False await omni.kit.app.get_app().next_update_async() setting_hstack = collapsable_frame.find("**/HStack_Samples_Limit") self.assertTrue(isinstance(setting_hstack.widget, omni.ui.HStack)) slider = setting_hstack.find("IntDrag[0]") self.assertTrue(slider) self.assertTrue(isinstance(slider.widget, omni.ui.IntDrag)) await ui_test.human_delay(50) await slider.input("200") setting_value = settings.get(setting_name) self.assertEqual(setting_value, 200)
5,220
Python
40.436508
124
0.67318
omniverse-code/kit/exts/omni.stats/omni/stats/__init__.py
"""This module contains bindings to C++ carb::stats::IStats interface. All the function are in omni.stats.IStats class, to get it use get_editor_interface method, which caches acquire interface call: >>> import omni.stats >>> e = omni.stats.get_stats_interface() >>> print(f"Is UI hidden: {e.is_ui_hidden()}") """ from ._stats import * # Cached stats instance pointer def get_stats_interface() -> IStats: """Returns cached :class:` omni.stats.IStats` interface""" if not hasattr(get_stats_interface, "stats"): get_stats_interface.stats = acquire_stats_interface() return get_stats_interface.stats
634
Python
30.749998
104
0.694006
omniverse-code/kit/exts/omni.kit.viewport.registry/omni/kit/viewport/registry/registry.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['_make_registry'] from typing import Callable, Sequence class _Factory: def __init__(self, factory: Callable, factory_id: str = None): self.__factory = factory self.__factory_id = factory_id if factory_id else factory.__class__.__name__ def __call__(self, *args, **kwargs): return self.__factory(*args, **kwargs) def __repr__(self) -> str: return f'<class {self.__class__.__name__} {self.__factory_id}>' @property def factory_id(self): return self.__factory_id def _make_registry(): def invoke_load_callback(callback, recorded_known, factories): for fac_object in factories: if fac_object not in recorded_known: recorded_known.add(fac_object) callback(fac_object, True) class _Registry(): """Class to register and de-register viewport factories""" __g_registered_factories = [] __g_registered_callbacks = {} @classmethod def add_notifier(cls, callback): # Invoke the callback for all currently registered scenes cls.__g_registered_callbacks[callback] = set() invoke_load_callback(callback, cls.__g_registered_callbacks[callback], cls.__g_registered_factories) @classmethod def remove_notifier(cls, callback): try: del cls.__g_registered_callbacks[callback] except KeyError: pass @classmethod def ordered_factories(cls, order: Sequence[str], append_unkown: bool = True, ignore_unknown: Sequence[str] = tuple()): ordered = [] known = set() def find_factory(factory_id): known.add(factory_id) for fact_obj in cls.__g_registered_factories: if fact_obj.factory_id == factory_id: return fact_obj return None for factory_id in order: ordered.append((factory_id, find_factory(factory_id))) if append_unkown: for fact_obj in cls.__g_registered_factories: if (fact_obj.factory_id not in known) and (fact_obj.factory_id not in ignore_unknown): ordered.append((fact_obj.factory_id, fact_obj)) return ordered def __init__(self, factory, factory_id: str = None): # Save the types for de-registration self.__factory = _Factory(factory, factory_id) # Record them in the global-list for notifiers registered later self.__g_registered_factories.append(self.__factory) # Invoke all callbacks for new items for callback, recorded_known in self.__g_registered_callbacks.items(): invoke_load_callback(callback, recorded_known, [self.__factory]) def destroy(self): fac_object = self.__factory self.__factory = None try: self.__g_registered_factories.remove(fac_object) except (ValueError, KeyError): pass for callback, recorded_known in self.__g_registered_callbacks.items(): if fac_object in recorded_known: recorded_known.remove(fac_object) try: callback(fac_object, False) except Exception: import carb import traceback carb.log_error(f"Error unloading {fac_object.factory_id} with {callback}. Traceback:\n{traceback.format_exc()}") def __del__(self): self.destroy() return _Registry
4,143
Python
38.094339
136
0.583635
omniverse-code/kit/exts/omni.kit.viewport.registry/omni/kit/viewport/registry/__init__.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ['RegisterScene', 'RegisterViewportLayer'] from .registry import _make_registry RegisterScene = _make_registry() RegisterViewportLayer = _make_registry()
599
Python
38.999997
76
0.792988
omniverse-code/kit/exts/omni.kit.viewport.registry/omni/kit/viewport/registry/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. ## __all__ = ['TestRegistry'] import omni.kit.test from omni.kit.test import AsyncTestCase from .. import RegisterScene, RegisterViewportLayer def _make_factory(id_str_in: str): class _EmptyFactoy(): def __init__(self, id_str: str = id_str_in): self.factory_id = id_str return _EmptyFactoy class TestRegistry(AsyncTestCase): def setUp(self): self.__scenes = {} self.__layers = {} super().setUp() # After running each test def tearDown(self): self.__scenes = {} self.__layers = {} super().tearDown() def ___scene_type_notification(self, factory, loading): if loading: self.__scenes[factory().factory_id] = None else: del self.__scenes[factory().factory_id] def ___layer_type_notification(self, factory, loading): if loading: self.__layers[factory().factory_id] = None else: del self.__layers[factory().factory_id] def __build_unique_ids(self, base_id: str, n: int = 10): for i in range(n): yield f'omni.kit.viewport.registry.{base_id}.factory_{i}' async def test_add_remove_notifier(self): RegisterScene.add_notifier(self.___scene_type_notification) RegisterViewportLayer.add_notifier(self.___layer_type_notification) RegisterScene.remove_notifier(self.___scene_type_notification) RegisterViewportLayer.remove_notifier(self.___layer_type_notification) async def test_factory_auto_destruct_scope(self): RegisterScene.add_notifier(self.___scene_type_notification) RegisterViewportLayer.add_notifier(self.___layer_type_notification) # Register a bunch of factories for sid in self.__build_unique_ids('scene'): RegisterScene(_make_factory(sid), sid) # Those factories are already out of scope, so they should have been de-regsitered self.assertEqual(self.__scenes, {}) self.assertEqual(self.__layers, {}) # Register a bunch of factories for lid in self.__build_unique_ids('layer'): RegisterViewportLayer(_make_factory(lid), lid) # Those factories are already out of scope, so they should have been de-regsitered self.assertEqual(self.__scenes, {}) self.assertEqual(self.__layers, {}) RegisterScene.remove_notifier(self.___scene_type_notification) RegisterViewportLayer.remove_notifier(self.___layer_type_notification) async def test_factory_registration(self): RegisterScene.add_notifier(self.___scene_type_notification) RegisterViewportLayer.add_notifier(self.___layer_type_notification) # Register a bunch of scene-factories, saving the returned subscription scene_subs = {} for sid in self.__build_unique_ids('scene'): scene_subs[sid] = RegisterScene(_make_factory(sid), sid) # Scenes should have been registered self.assertEqual([sid for sid in self.__build_unique_ids('scene')], [sid for sid, fact in self.__scenes.items()]) # Layers should be empty self.assertEqual([], [lid for lid, fact in self.__layers.items()]) # Register a bunch of layer-factories, saving the returned subscription layer_subs = {} for lid in self.__build_unique_ids('layer'): layer_subs[lid] = RegisterViewportLayer(_make_factory(lid), lid) # Layers should now have been registered self.assertEqual([lid for lid in self.__build_unique_ids('layer')], [lid for lid, fact in self.__layers.items()]) # Scenes should have stayed the same self.assertEqual([sid for sid in self.__build_unique_ids('scene')], [sid for sid, fact in self.__scenes.items()]) layer_subs = {} # Layers should now have been all deregistered self.assertEqual([], [lid for lid, fact in self.__layers.items()]) scene_subs = {} # Scenes should now have been all deregistered self.assertEqual([], [sid for sid, fact in self.__scenes.items()]) RegisterScene.remove_notifier(self.___scene_type_notification) RegisterViewportLayer.remove_notifier(self.___layer_type_notification) async def test_factory_ordering(self): RegisterScene.add_notifier(self.___scene_type_notification) # Register a bunch of scene-factories, saving the returned subscription scene_subs = {} for sid in self.__build_unique_ids('scene'): scene_subs[sid] = RegisterScene(_make_factory(sid), sid) # Scenes should have been registered self.assertEqual([sid for sid in self.__build_unique_ids('scene')], [sid for sid, fact in self.__scenes.items()]) # Layers should be empty self.assertEqual([], [lid for lid, fact in self.__layers.items()]) scene_ids = [sid for sid in self.__build_unique_ids('scene', 10)] scene_ids_a = scene_ids[:5] scene_ids_b = scene_ids[5:] # Get ordered_factories, not including those not requested appened to end: [0-4] self.assertEqual([sid for sid, fact in RegisterScene.ordered_factories(scene_ids_a, append_unkown=False)], scene_ids_a) # Get ordered_factories, not including those not requested appened to end: [5-9] self.assertEqual([sid for sid, fact in RegisterScene.ordered_factories(scene_ids_b, append_unkown=False)], scene_ids_b) # Get ordered_factories, including those not requested appened to end: [0-4] + [5-9] self.assertEqual([sid for sid, fact in RegisterScene.ordered_factories(scene_ids_a)], scene_ids_a + scene_ids_b) # Get ordered_factories, including those not requested appened to end: [5-9] + [0-4] self.assertEqual([sid for sid, fact in RegisterScene.ordered_factories(scene_ids_b)], scene_ids_b + scene_ids_a) # Get ordered_factories, including those not requested appened to end, ignoring 9: [0-4] + [5-8] self.assertEqual([sid for sid, fact in RegisterScene.ordered_factories(scene_ids_a, ignore_unknown=['omni.kit.viewport.registry.scene.factory_9'])], scene_ids_a + scene_ids_b[:-1]) # Get ordered_factories, including those not requested appened to end, ignoring 0: [5-9] + [1-4] self.assertEqual([sid for sid, fact in RegisterScene.ordered_factories(scene_ids_b, ignore_unknown=['omni.kit.viewport.registry.scene.factory_0'])], scene_ids_b + scene_ids_a[1:]) RegisterScene.remove_notifier(self.___scene_type_notification)
6,950
Python
47.270833
188
0.662014
omniverse-code/kit/exts/omni.kit.test_suite.layer_window/omni/kit/test_suite/layer_window/tests/__init__.py
from .select_bound_objects_layer import *
43
Python
13.666662
41
0.767442
omniverse-code/kit/exts/omni.kit.test_suite.layer_window/omni/kit/test_suite/layer_window/tests/select_bound_objects_layer.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 import platform import os import unittest import omni.kit.app import omni.usd from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from omni.kit.test_suite.helpers import open_stage, get_test_data_path, select_prims, wait_stage_loading, arrange_windows class SelectBoundObjectsLayer(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows("Layer") await open_stage(get_test_data_path(__name__, "bound_shapes.usda")) # After running each test async def tearDown(self): await wait_stage_loading() DATA = [ ("/World/Looks/OmniPBR", {"/World/Cone", "/World/Cylinder"}), ("/World/Looks/OmniGlass", {"/World/Cube", "/World/Sphere"}), ] async def test_l1_select_bound_objects_layer(self): await ui_test.find("Layer").focus() usd_context = omni.usd.get_context() for to_select, to_verify in self.DATA: # select prim await select_prims([to_select]) # wait for material to load & UI to refresh await wait_stage_loading() # right click on prim await ui_test.find("Layer//Frame/**/TreeView[*]").find(f"**/Label[*].text=='{os.path.basename(to_select)}'").right_click() # select context menu "Select Bound Objects" await ui_test.select_context_menu("Select Bound Objects") # get new selection selected = usd_context.get_selection().get_selected_prim_paths() # verify meshes are selected self.assertSetEqual(set(selected), to_verify)
2,085
Python
36.249999
134
0.671463
omniverse-code/kit/exts/omni.ui_query/omni/ui_query/query.py
from typing import Optional, Union, List, Tuple import omni.ui as ui import carb class OmniUIQuery: def __init__(self) -> None: pass @classmethod def _child_widget(cls, widget: ui.Widget, path_segment: str, show_warnings=True) -> Union[ui.Widget, None]: """ Find a widget from a path given a starting widget """ # print ("looking for", path_segment, "child of, ", widget) adjusted_path_segment = path_segment # when we don't have index we assume it is the first one index = None if "[" in adjusted_path_segment: index = int(adjusted_path_segment.split("[")[-1].split("]")[0]) adjusted_path_segment = adjusted_path_segment.split("[")[0] children = ui.Inspector.get_children(widget) counter = 0 for a_child in children: if not a_child: continue # NOTE: Wait until we have identifier support before activating this if adjusted_path_segment == a_child.identifier and index == None: return a_child elif adjusted_path_segment == a_child.__class__.__name__: if index == counter: return a_child else: counter += 1 if not widget.__class__.__name__ == adjusted_path_segment: if show_warnings: carb.log_warn(f"Widget {widget} does not match path segment {adjusted_path_segment}") return None if not index: index = 0 if index >= len(children): if show_warnings: carb.log_warn(f"Widget {widget} only has {len(children)} children, asked for index {index}") return None return children[index] @classmethod def _find_children_by_type(cls, widget: ui.Widget, path_segment: str) -> List[ui.Widget]: """ given a starting widget, look at it's children to find the path segment requested, where the path segment index has a wildcard (e.g [*]) Assumes input path_segment is like "Type[*]" """ adjusted_path_segment = path_segment[: path_segment.find("[")] children = ui.Inspector.get_children(widget) children_of_type = [c for c in children if c.__class__.__name__ == adjusted_path_segment] return children_of_type @classmethod def get_widget_path(cls, window: ui.Window, widget: ui.Widget) -> Union[str, None]: """ given a Window and a Widget in that window, get it's path """ def traverse_widget_tree_for_match( starting_widget: ui.Widget, current_path: str, searched_widget: ui.Widget ) -> Union[str, None]: current_index = 0 current_children = ui.Inspector.get_children(starting_widget) current_children = [c for c in current_children if c] type_frequencies = dict(zip([a.__class__ for a in current_children], [0] * len(current_children))) for a_child in current_children: class_name = a_child.__class__.__name__ current_index = type_frequencies[a_child.__class__] widget_name = a_child.identifier or f"{class_name}[{current_index}]" type_frequencies[a_child.__class__] += 1 if a_child == searched_widget: p = f"{current_path}/{widget_name}" return p if isinstance(a_child, ui.Container) or isinstance(a_child, ui.TreeView): path = traverse_widget_tree_for_match(a_child, f"{current_path}/{widget_name}", searched_widget) if path: return path return None if window: start_path = f"{window.title}//Frame" return traverse_widget_tree_for_match(window.frame, start_path, widget) else: return None @classmethod def find_menu_item(cls, query: str) -> Optional[ui.Widget]: """ TODO: This may now be legacy functionality after https://gitlab-master.nvidia.com/omniverse/kit/-/merge_requests/10402 is merged so need to see if it's actually being used on 102 tests etc """ from omni.kit.mainwindow import get_main_window main_menu_bar = get_main_window().get_main_menu_bar() if not main_menu_bar: carb.log_warn("Current App doesn't have a MainMenuBar") return None tokens = query.split("/") print(tokens) current_children = main_menu_bar for i in range(1, len(tokens)): last = i == len(tokens) - 1 print(tokens[i]) child = cls._child_widget(current_children, tokens[i]) if not child != 1: carb.log_warn(f"find_menu_item: Failed to find Child Widget at level {tokens[i]}") return None current_children = child return current_children @classmethod def _parse_input(cls, query: str) -> Tuple[bool, Union[ui.Widget, None], List[str], str]: """ parse and validate the input. return widge tokens only ie sans window """ # TODO Replace w regex tokens = query.split("//") window_name = tokens[0] if len(tokens) > 1 else None widget_predicate = "" widget_part = tokens[1] if len(tokens) > 1 else tokens[0] widget_part_list = widget_part.split(".", maxsplit=1) widget_path = widget_part_list[0] if len(widget_part_list) > 1: widget_predicate = widget_part_list[1] window = None if window_name: windows = ui.Workspace.get_windows() window_list = [] for window in windows: if window.title == window_name: window_list.append(window) if not window_list: carb.log_warn(f'Failed to find window: "{window_name}"') return False, None, [], widget_predicate if len(window_list) == 1: window = window_list[0] else: carb.log_warn( f'found {len(window_list)} windows named "{window_name}". Using first visible window found' ) window = None for win in window_list: if win.visible: window = win break if not window: carb.log_warn(f'Failed to find visible window: "{window_name}"') return False, None, [], widget_predicate if not isinstance(window, ui.Window) and not isinstance(window, ui.ToolBar): carb.log_warn(f"window: {window_name} is not a ui.Window, query only works on ui.Window") return False, None, [], widget_predicate widget_tokens = widget_path.split("/") if window and not (widget_tokens[0] == "Frame" or widget_tokens[0] == "Frame[0]"): carb.log_warn("Query with a window currently only supports '<WindowName>//Frame/* type query") return False, None, [], widget_predicate if widget_tokens[-1] == "": widget_tokens = widget_tokens[:-1] return True, window, widget_tokens, widget_predicate @classmethod def find_widgets(cls, query: str, root_widgets=[]) -> List[ui.Widget]: """ find a set of widgets that match our query. """ def _get_descendants(widget: ui.Widget): kids = [] local_kids = ui.Inspector.get_children(widget) kids.extend(local_kids) for k in local_kids: child_kids = _get_descendants(k) kids.extend(child_kids) return kids validate_status, window, widget_tokens, predicate = cls._parse_input(query) if not validate_status: return [] if root_widgets: curr_kids = root_widgets else: curr_kids = [window.frame] if window else [] if not curr_kids: return [] curr_kids_tmp = [] for i in range(0, len(widget_tokens)): # Skip only parent frame if widget_tokens[i] == "Frame": continue curr_kids_tmp = [] for current_child in curr_kids: if isinstance(current_child, ui.Window): current_child = current_child.frame if widget_tokens[i] == "*": curr_kids_tmp += ui.Inspector.get_children(current_child) elif widget_tokens[i].find("[*]") != -1: curr_kids_tmp += cls._find_children_by_type(current_child, widget_tokens[i]) elif widget_tokens[i] == "**": curr_kids_tmp += _get_descendants(current_child) else: child = cls._child_widget(current_child, widget_tokens[i], show_warnings=False) if child: curr_kids_tmp += [child] # Filter out any leaf node widgets as we're not on the last pass and last pass deals with them curr_kids = [kid for kid in curr_kids_tmp if len(ui.Inspector.get_children(kid)) > 0] # Remove None(s) curr_kids_tmp = [w for w in curr_kids_tmp if w is not None] if predicate: curr_kids_tmp = [w for w in curr_kids_tmp if eval("w." + predicate)] return curr_kids_tmp @classmethod def find_widget(cls, query: str) -> Union[ui.Widget, None]: """ find a single widget given a full widget path """ validate_status, window, widget_tokens, _ = cls._parse_input(query) if not validate_status: return None if len(widget_tokens) == 1: return window.frame current_child = window.frame for i in range(1, len(widget_tokens)): child = cls._child_widget(current_child, widget_tokens[i]) if not child: carb.log_warn(f'find_widget: from query "{query}" Failed to widget {widget_tokens[i]}') actual_kids = ui.Inspector.get_children(current_child) names = [a.identifier or f"{a.__class__.__name__}" for a in actual_kids] carb.log_warn(f"find_widget: did find widgets {names}") return None current_child = child return current_child
10,563
Python
36.863799
126
0.548802
omniverse-code/kit/exts/omni.ui_query/omni/ui_query/__init__.py
import omni.ui from .query import OmniUIQuery
46
Python
14.666662
30
0.826087
omniverse-code/kit/exts/omni.ui_query/omni/ui_query/tests/__init__.py
from .test_query import TestQuery
34
Python
16.499992
33
0.823529
omniverse-code/kit/exts/omni.ui_query/omni/ui_query/tests/test_query.py
from ..query import OmniUIQuery import omni.kit.test import omni.ui class TestQuery(omni.kit.test.AsyncTestCase): def test_create_test_widget1(self): _window = omni.ui.Window("the window with space") button = None with _window.frame: # the frame can only have 1 widget under it with omni.ui.HStack(): with omni.ui.VStack(): omni.ui.Label("Test2") with omni.ui.VStack(width=150): with omni.ui.HStack(height=30): omni.ui.Label("Test1") omni.ui.StringField() button = omni.ui.Button("TestButton") button_path = OmniUIQuery.get_widget_path(_window, button) self.assertTrue( "the window with space//Frame/HStack[0]/VStack[1]/HStack[0]/Button[0]" == button_path, "was actually %s" % (button_path), ) def test_create_test_widget2(self): _window = omni.ui.Window("the_window") hstack1 = None with _window.frame as frame1: hstack1 = omni.ui.HStack() with hstack1: vstack1 = omni.ui.VStack() with vstack1: label1 = omni.ui.Label("Test2") vstack2 = omni.ui.VStack(width=150) with vstack2: hstack2 = omni.ui.HStack(height=30) with hstack2: label2 = omni.ui.Label("Test1") string1 = omni.ui.StringField() button1 = omni.ui.Button() button1.identifier = "The_Button1" button2 = omni.ui.Button("TestButton") button3 = omni.ui.Button(name="Button3") # NOTE: we can't look for the frame.. # widget_path = OmniUIQuery.get_widget_path(_window, frame1) # self.assertTrue('the_window//Frame'== widget_path, "was actually %s"%(widget_path)) widget_path = OmniUIQuery.get_widget_path(_window, hstack1) self.assertTrue("the_window//Frame/HStack[0]" == widget_path, "was actually %s" % (widget_path)) found_widget = OmniUIQuery.find_widget(widget_path) self.assertTrue(found_widget == hstack1) widget_path = OmniUIQuery.get_widget_path(_window, vstack1) self.assertTrue("the_window//Frame/HStack[0]/VStack[0]" == widget_path, "was actually %s" % (widget_path)) found_widget = OmniUIQuery.find_widget(widget_path) self.assertTrue(found_widget == vstack1) widget_path = OmniUIQuery.get_widget_path(_window, label1) self.assertTrue( "the_window//Frame/HStack[0]/VStack[0]/Label[0]" == widget_path, "was actually %s" % (widget_path) ) found_widget = OmniUIQuery.find_widget(widget_path) self.assertTrue(found_widget == label1) widget_path = OmniUIQuery.get_widget_path(_window, vstack2) self.assertTrue("the_window//Frame/HStack[0]/VStack[1]" == widget_path, "was actually %s" % (widget_path)) found_widget = OmniUIQuery.find_widget(widget_path) self.assertTrue(found_widget == vstack2) widget_path = OmniUIQuery.get_widget_path(_window, hstack2) self.assertTrue( "the_window//Frame/HStack[0]/VStack[1]/HStack[0]" == widget_path, "was actually %s" % (widget_path) ) found_widget = OmniUIQuery.find_widget(widget_path) self.assertTrue(found_widget == hstack2) widget_path = OmniUIQuery.get_widget_path(_window, button2) self.assertTrue( "the_window//Frame/HStack[0]/VStack[1]/HStack[0]/Button[1]" == widget_path, "was actually %s" % (widget_path), ) found_widget = OmniUIQuery.find_widget(widget_path) self.assertTrue(found_widget == button2) # Test where we reference with a name rather than a type. #TODO: reactivate when we have identifier support widget_path = OmniUIQuery.get_widget_path(_window, button1) self.assertTrue( "the_window//Frame/HStack[0]/VStack[1]/HStack[0]/The_Button1" == widget_path, "was actually %s" % (widget_path), ) found_widget = OmniUIQuery.find_widget(widget_path) self.assertTrue(found_widget == button1) def test_wildcards(self): _window = omni.ui.Window("the_window") hstack1 = None with _window.frame as frame1: hstack1 = omni.ui.HStack() with hstack1: vstack1 = omni.ui.VStack() with vstack1: label1 = omni.ui.Label("Test2") vstack2 = omni.ui.VStack(width=150) with vstack2: hstack2 = omni.ui.HStack(height=30) with hstack2: label2 = omni.ui.Label("Test1") string1 = omni.ui.StringField() button1 = omni.ui.Button() button1.identifier = "TheButton_1" button2 = omni.ui.Button("TestButton") button3 = omni.ui.Button(name="Button3.dot.separated") # Run all tests in 2 modes: # 1. Full path including window # 2. Find subwidget first (Frame) and search from it for full_path in [True, False]: def find(path): if full_path: return OmniUIQuery.find_widgets(f"the_window//Frame/{path}") else: frame = OmniUIQuery.find_widget("the_window//Frame") return OmniUIQuery.find_widgets(path, root_widgets=[frame]) # Find every immediate child beneath the first HStack widgets = find("HStack[0]/*") self.assertTrue(widgets[0] == vstack1) self.assertTrue(widgets[1] == vstack2) self.assertTrue(len(widgets) == 2) # Find every immediate child beneath the first HStack Vstack combo widgets = find("HStack[0]/VStack[0]/*") self.assertTrue(len(widgets) == 1) self.assertTrue(widgets[0] == label1) # Index/Type - Find every immediate Vstack child widgets = find("HStack[0]/VStack[*]") self.assertTrue(widgets[0] == vstack1) self.assertTrue(widgets[1] == vstack2) self.assertTrue(len(widgets) == 2) # Recursion - Find every child beneath the Frame - recursively widgets = find("**") self.assertTrue(len(widgets) == 10) widgets = find("HStack[0]/**") self.assertTrue(len(widgets) == 9) # Recursion - with a specific type/indexed entry at the end widgets = find("HStack[0]/**/Button[0]") self.assertTrue(len(widgets) == 1) self.assertTrue(button1 in widgets) # Recursion - with a specific name at the end widgets = find("HStack[0]/**/TheButton_1") self.assertTrue(len(widgets) == 1, "actually %s" % (len(widgets))) self.assertTrue(button1 in widgets) # Recursion - find all the buttons widgets = find("**/Button[*]") self.assertTrue(len(widgets) == 3) self.assertTrue(button1 in widgets) self.assertTrue(button2 in widgets) self.assertTrue(button3 in widgets) widgets = find("*/VStack[*]") self.assertTrue(len(widgets) == 2) self.assertTrue(vstack1 in widgets) self.assertTrue(vstack2 in widgets) # Recursion - what's directly under the 2 vstacks vstack1 and vstack2? widgets = find("HStack[0]/VStack[*]/*") self.assertTrue(len(widgets) == 2) self.assertTrue(label1 in widgets) self.assertTrue(hstack2 in widgets) # We should be able to get the same result using recursion and non-recursion on a set of leaf nodes widgets = find("HStack[0]/VStack[1]/HStack[0]/*") self.assertTrue(len(widgets) == 5) widgets = find("HStack[0]/VStack[1]/HStack[0]/**") self.assertTrue(len(widgets) == 5) # Can we treat a standard path as am explicit query with no wildcard that returns a single result? widgets = find("HStack[0]/VStack[1]/HStack[0]/Button[0]") self.assertTrue(len(widgets) == 1) self.assertTrue(button1 in widgets) # #Can we treat a standard path as am explicit query with no wildcard that returns a single result? widgets = find("HStack[0]/VStack[1]/HStack[0]/TheButton_1") self.assertTrue(len(widgets) == 1) self.assertTrue(button1 in widgets) # Predicates widgets = find("**/Button[*].text=='TestButton'") self.assertTrue(button2 in widgets) self.assertTrue(len(widgets) == 1) widgets = find("**/Button[*].name=='Button3.dot.separated'") self.assertTrue(button3 in widgets) self.assertTrue(len(widgets) == 1) def test_bad_inputs(self): _window = omni.ui.Window("the_window2") with _window.frame: # TODO Check - can the frame only have 1 widget under it? with omni.ui.HStack(): with omni.ui.VStack(): omni.ui.Label("Test2") # check bad window widget_path = OmniUIQuery.find_widget("bad_window//Frame/HStack[0]/*") self.assertTrue(widget_path == None) # check pre-omniui window widget_path = OmniUIQuery.find_widget("Viewport//Frame/HStack[0]/*") self.assertTrue(widget_path == None) # check bad frame widget_path = OmniUIQuery.find_widget("the_window2//B/HStack[0]/*") self.assertTrue(widget_path == None) # bad first widget widget_path = OmniUIQuery.find_widget("the_window2//Frame/GStack[0]") self.assertTrue(widget_path == None) # wildcard query widgets = OmniUIQuery.find_widgets("blah") self.assertTrue(widgets == []) widgets = OmniUIQuery.find_widgets("blah/*") self.assertTrue(widgets == []) def test_with_real_widget(self): """ This introduces a dependency on render settings and the renderer core We might want to abandon it if the dependency is too painful """ windows = omni.ui.Workspace.get_windows() found_button = False for w in windows: if w.title == "Render Settings": the_path = f"{w.title}//Frame/**" widgets = OmniUIQuery.find_widgets(the_path) for w in widgets: if isinstance(w, omni.ui.Button): found_button = True self.assertTrue(found_button) def test_frame_query(self): # Test to validate whether we are able to query widget having Frames excludint parent frame in path _window = omni.ui.Window("Window") with _window.frame: # the frame can only have 1 widget under it with omni.ui.HStack(): child_frame1 = omni.ui.Frame(name="Frame1") child_frame2 = omni.ui.Frame() with child_frame1: label = omni.ui.Label("Label1") with child_frame2: button = omni.ui.Button() single_frame_path = "Window//Frame/HStack[0]/Frame[0]" multiple_frame_path = "Window//Frame/HStack[0]/Frame[*]" widget_inside_frame_path = "Window//Frame/HStack[0]/Frame[1]/Button[0]" frame_with_text_path = "Window//Frame/HStack[0]/Frame[*].name=='Frame1'" # Finding a single frame found_widget = OmniUIQuery.find_widgets(single_frame_path)[0] self.assertTrue(found_widget == child_frame1) # Finding multiple frames found_widget = OmniUIQuery.find_widgets(multiple_frame_path) self.assertTrue(found_widget[0] == child_frame1) self.assertTrue(found_widget[1] == child_frame2) # Finding widget inside Frame with multiple Frame[0] in query found_widget = OmniUIQuery.find_widgets(widget_inside_frame_path) self.assertTrue(found_widget[0] == button) # Finding frame using the text found_widget = OmniUIQuery.find_widgets(frame_with_text_path) self.assertTrue(found_widget[0] == child_frame1)
12,479
Python
41.739726
115
0.573203
omniverse-code/kit/exts/omni.hydra.scene_api/omni/hydra/scene_api/__init__.py
import omni.ext from .bindings._omni_hydra_scene_api import *
62
Python
19.999993
45
0.774194
omniverse-code/kit/exts/omni.hydra.scene_api/omni/hydra/scene_api/tests/__init__.py
import sys # Temporarily disable all omni.rtx.tests cases until they are stable on Linux with # a driver common to all TC agents if sys.platform == "win32": from .test_backgroundloadingscenedelegate import TestBackgroundLoadingSceneDelegate
245
Python
39.999993
87
0.808163
omniverse-code/kit/exts/omni.hydra.scene_api/omni/hydra/scene_api/tests/test_backgroundloadingscenedelegate.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test from omni.hydra.scene_api import * import omni.kit.app import omni.kit.commands import omni.kit.undo from omni.rtx.tests import RtxTest, testSettings, postLoadTestSettings from pxr import Gf, Usd, UsdGeom import pathlib EXTENSION_FOLDER_PATH = pathlib.Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)) USD_DIR = EXTENSION_FOLDER_PATH.joinpath("omni/hydra/scene_api/tests/data/usd") GOLDEN_DIR = EXTENSION_FOLDER_PATH.joinpath("omni/hydra/scene_api/tests/data/golden") class TestBackgroundLoadingSceneDelegate(RtxTest): """ An RtxTest that verifies we can load several scene delegates and they are all rendered. """ # override resolution WINDOW_SIZE = (512, 512) # override diff threshold. Seeing some lighting diffs on teamcity that trip the # default threshold. All we care about is whether the item loaded, so we can have # a pretty flexible threshold. The default is 1e-5 currently. THRESHOLD = 1e-4 async def setUp(self): await super().setUp() self.set_settings(testSettings) # Create a main stage in the usd_context. This is to be like a normal run, # where there would be a stage. We'll also put a light on it. omni.usd.get_context().new_stage() self.add_dir_light() await omni.kit.app.get_app().next_update_async() # Wait stage loading self.set_settings(postLoadTestSettings) async def _pause(self): await omni.rtx.tests.test_common.wait_for_update(self.ctx, 5) # Wait 5 frames before capture. async def test_addAndRemove(self): path = USD_DIR.joinpath('wonky-cylinder.usda') x = add_background_loading_hydra_scene_delegate('testDelegate', str(path)) self.assertTrue(x, f'Failed to add stage {path}') await self._pause() await self.screenshot_and_diff(GOLDEN_DIR, output_subdir="omni.hydra.scene_api", golden_img_name="added_cylinder.png") x = remove_hydra_scene_delegate('testDelegate') self.assertTrue(x, f'Failed to remove delegate {path}') await self._pause() await self.screenshot_and_diff(GOLDEN_DIR, output_subdir="omni.hydra.scene_api", golden_img_name="removed_cylinder.png") async def test_addSameTwice(self): path = USD_DIR.joinpath('bunny.obj.usda') x = add_background_loading_hydra_scene_delegate('testDelegate', str(path)) self.assertTrue(x, f'Failed to add stage {path}') x = add_background_loading_hydra_scene_delegate('testDelegate', str(path)) self.assertFalse(x, f'second add with the same name should fail') x = remove_hydra_scene_delegate('testDelegate') self.assertTrue(x, f'Failed to remove delegate {path}') async def test_add_grid(self): path00 = USD_DIR.joinpath('cylinder00.usda') path01 = USD_DIR.joinpath('cylinder01.usda') path10 = USD_DIR.joinpath('cylinder10.usda') path11 = USD_DIR.joinpath('cylinder11.usda') x = add_background_loading_hydra_scene_delegate('cylinder00', str(path00)) self.assertTrue(x, f'Failed to add stage {path00}') await self._pause() await self.screenshot_and_diff(GOLDEN_DIR, output_subdir="omni.hydra.scene_api", golden_img_name="added_cylinder00.png") x = add_background_loading_hydra_scene_delegate('cylinder01', str(path01)) self.assertTrue(x, f'Failed to add stage {path01}') await self._pause() await self.screenshot_and_diff(GOLDEN_DIR, output_subdir="omni.hydra.scene_api", golden_img_name="added_cylinder01.png") x = add_background_loading_hydra_scene_delegate('cylinder10', str(path10)) self.assertTrue(x, f'Failed to add stage {path10}') await self._pause() await self.screenshot_and_diff(GOLDEN_DIR, output_subdir="omni.hydra.scene_api", golden_img_name="added_cylinder10.png") x = add_background_loading_hydra_scene_delegate('cylinder11', str(path11)) self.assertTrue(x, f'Failed to add stage {path11}') await self._pause() await self.screenshot_and_diff(GOLDEN_DIR, output_subdir="omni.hydra.scene_api", golden_img_name="added_cylinder11.png") x = remove_hydra_scene_delegate('cylinder00') self.assertTrue(x, f'Failed to remove delegate {path00}') await self._pause() await self.screenshot_and_diff(GOLDEN_DIR, output_subdir="omni.hydra.scene_api", golden_img_name="removed_cylinder00.png") x = remove_hydra_scene_delegate('cylinder01') self.assertTrue(x, f'Failed to remove delegate {path01}') await self._pause() await self.screenshot_and_diff(GOLDEN_DIR, output_subdir="omni.hydra.scene_api", golden_img_name="removed_cylinder01.png") x = remove_hydra_scene_delegate('cylinder10') self.assertTrue(x, f'Failed to remove delegate {path10}') await self._pause() await self.screenshot_and_diff(GOLDEN_DIR, output_subdir="omni.hydra.scene_api", golden_img_name="removed_cylinder10.png") x = remove_hydra_scene_delegate('cylinder11') self.assertTrue(x, f'Failed to remove delegate {path11}') await self._pause() await self.screenshot_and_diff(GOLDEN_DIR, output_subdir="omni.hydra.scene_api", golden_img_name="removed_cylinder11.png") async def test_parallel_load(self): path00 = USD_DIR.joinpath('cylinder00.usda') path01 = USD_DIR.joinpath('cylinder01.usda') path10 = USD_DIR.joinpath('cylinder10.usda') path11 = USD_DIR.joinpath('cylinder11.usda') add_background_loading_hydra_scene_delegate('cylinder00', str(path00)) add_background_loading_hydra_scene_delegate('cylinder01', str(path01)) add_background_loading_hydra_scene_delegate('cylinder10', str(path10)) add_background_loading_hydra_scene_delegate('cylinder11', str(path11)) await self._pause() await self.screenshot_and_diff(GOLDEN_DIR, output_subdir="omni.hydra.scene_api", golden_img_name="parallel_load.png", threshold=1e-4) x = remove_hydra_scene_delegate('cylinder00') x = remove_hydra_scene_delegate('cylinder01') x = remove_hydra_scene_delegate('cylinder10') x = remove_hydra_scene_delegate('cylinder11') await self._pause() await self.screenshot_and_diff(GOLDEN_DIR, output_subdir="omni.hydra.scene_api", golden_img_name="parallel_unload.png") def _convert_mat(self, xf): """Convert a Gf.Matrix4d into an array of row values""" row0 = xf.GetRow(0) row1 = xf.GetRow(1) row2 = xf.GetRow(2) row3 = xf.GetRow(3) return [ row0[0], row0[1], row0[2], row0[3], row1[0], row1[1], row1[2], row1[3], row2[0], row2[1], row2[2], row2[3], row3[0], row3[1], row3[2], row3[3], ] async def test_set_root_transform(self): path00 = USD_DIR.joinpath("cylinder00.usda") path01 = USD_DIR.joinpath("cylinder01.usda") add_background_loading_hydra_scene_delegate("cylinder00", str(path00)) add_background_loading_hydra_scene_delegate("cylinder01", str(path01)) # initial state await self._pause() await self.screenshot_and_diff( GOLDEN_DIR, output_subdir="omni.hydra.scene_api", golden_img_name="transform_initial.png", threshold=1e-4 ) # move one cylinder over xf = Gf.Matrix4d(1).SetTranslate(Gf.Vec3d(300, 200, 0)) x = set_scene_delegate_root_transform("cylinder00", self._convert_mat(xf)) self.assertTrue(x, f"Expected to set xform on cylinder00") await self._pause() await self.screenshot_and_diff( GOLDEN_DIR, output_subdir="omni.hydra.scene_api", golden_img_name="transform_move.png", threshold=1e-4 ) # rotate and scale one cylinder, move the other a second time xf = Gf.Matrix4d(1).SetScale(Gf.Vec3d(2.5, 2.5, 2.5)).SetRotateOnly(Gf.Rotation(Gf.Vec3d(0, 1, 0), 45.0)) x = set_scene_delegate_root_transform("cylinder01", self._convert_mat(xf)) self.assertTrue(x, f"Expected to set xform on cylinder01") xf = Gf.Matrix4d(1).SetTranslate(Gf.Vec3d(0, 0, 300)) x = set_scene_delegate_root_transform("cylinder00", self._convert_mat(xf)) self.assertTrue(x, f"Expected to set xform on cylinder00") await self._pause() await self.screenshot_and_diff( GOLDEN_DIR, output_subdir="omni.hydra.scene_api", golden_img_name="transform_scale_rotate_move.png", threshold=1e-4, ) # cleanup x = remove_hydra_scene_delegate("cylinder00") x = remove_hydra_scene_delegate("cylinder01") await self._pause() await self.screenshot_and_diff( GOLDEN_DIR, output_subdir="omni.hydra.scene_api", golden_img_name="transform_unload.png" ) async def test_set_bounding_box(self): path = USD_DIR.joinpath("bbox.usda") add_background_loading_hydra_scene_delegate("bbox", str(path)) set_scene_delegate_root_transform("bbox", (1.,0.,0.,0., 0.,1.,0.,0., 0.,0.,1.,0., 100.,0.,0.,0.)) await self._pause() bbox = compute_scene_delegate_world_bounding_box("bbox") compare_to = [50, -50, -50, 150, 50, 50, 100, 0, 0, 100, 100, 100] for i in range(len(compare_to)): self.assertEqual(compare_to[i], round(bbox[i]))
10,378
Python
50.128079
123
0.633648
omniverse-code/kit/exts/omni.kit.window.provide_feedback/omni/kit/window/provide_feedback.py
import carb import omni.ext import webbrowser class Extension(omni.ext.IExt): def on_startup(self): import omni.kit.ui def provide_feedback_func(a, b): url = carb.settings.get_settings().get(f"/exts/omni.kit.window.provide_feedback/url") webbrowser.open(url) self._menuEntry = omni.kit.ui.get_editor_menu().add_item(f'Help/Provide Feedback', provide_feedback_func) omni.kit.ui.get_editor_menu().set_priority("Help/Provide Feedback", -11)
509
Python
30.874998
113
0.660118
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/viewport_layer.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["MenuBarViewportLayer"] from .viewport_menu_model import ViewportMenuModel from .menu_item.viewport_menu_item import ViewportMenuItem from .menu_item.viewport_menubar_item import ViewportMenubar from .style import VIEWPORT_MENUBAR_STYLE import omni.ui as ui import weakref class MenuBarViewportLayer: def __init__(self, factory_args, *ui_args, **ui_kwargs): self._model = ViewportMenuModel() self._sub = self._model.subscribe_item_changed_fn(self._menu_changed) super().__init__() # Store the factory arguments (we are passed a unique copy that is ours to mutate) self.__factory_args = factory_args ui_kwargs["build_fn"] = self._build_fn # Remove height = 0 to make bottom alignment work self.__ui_frame = ui.Frame(*ui_args, **ui_kwargs) self.__factory_args['root_menu_layer'] = weakref.proxy(self.__ui_frame) def destroy(self): if self.__ui_frame: self.__ui_frame.destroy() self.__ui_frame = None self._sub = None def _build_fn(self): menubar_items = self._model.get_item_children() with ui.ZStack(): # Create menubars for item in menubar_items: if isinstance(item, ViewportMenubar): if not item.visible_model.as_bool: continue menu_items = self._model.get_item_children(item) item.build_fn(menu_items, self.__factory_args) def _menu_changed(self, model: ViewportMenuModel, item: ViewportMenuItem) -> None: if self.__ui_frame is not None: self.__ui_frame.rebuild() @property def name(self): return "Menubar" @property def categories(self): return ("menubar", "menu") @property def layers(self): return tuple() @property def visible(self): return self.__ui_frame.visible if self.__ui_frame else False @visible.setter def visible(self, visible: bool): if self.__ui_frame: self.__ui_frame.visible = bool(visible)
2,549
Python
33
90
0.640643
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/style.py
import omni.ui as ui from omni.ui import color as cl, constant as fl from pathlib import Path __all__ = ["VIEWPORT_MENUBAR_STYLE", "VIEWPORT_PREFERENCE_STYLE"] # Name of default menubar DEFAULT_MENUBAR_NAME = "__DEFAULT__MENUBAR__" CURRENT_PATH = Path(__file__).parent ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.joinpath("data").joinpath("icons") VIEWPORT_MENUBAR_STYLE = { "Menu.Title": {"color": cl.viewport_menubar_title, "background_color": cl.viewport_menubar_title_background}, "Menu.Title:hovered": { "background_color": cl.viewport_menubar_selection, "border_width": 1, "border_color": cl.viewport_menubar_selection_border, }, "Menu.Title:pressed": {"background_color": cl.viewport_menubar_selection}, "Menu.Item": { "color": cl.viewport_menubar_light, "margin_width": fl.viewport_menubar_item_margin, "margin_height": fl.viewport_menubar_item_margin_height, }, "MenuBar.Window": { "background_color": cl.viewport_menubar_background, "border_width": 0, "border_radius": 0, }, "MenuBar.Item": { "color": cl.viewport_menubar_light, "padding": 0, "margin_width": fl.viewport_menubar_item_margin, "margin_height": fl.viewport_menubar_item_margin, }, "MenuBar.Item::menubar": { "color": cl.viewport_menubar_light, "padding": 0, "margin_width": 0, "margin_height": 0, }, "MenuBar.Item.Background": { "background_color": cl.viewport_menubar_background, "border_radius": cl.viewport_menubar_border_radius, "padding": 1, "margin": 2, }, "Menu.Item.Background": { "background_color": cl.viewport_menubar_background, "border_radius": cl.viewport_menubar_border_radius, "padding": 0, "margin_width": 0, "margin_height": 2, }, "Menu.Item.CloseMark": { "color": 0x0, }, "Menu.Item.CloseMark:checked": { "color": cl.viewport_menubar_light, }, "MenuBar.Item.Triangle": {"background_color": cl.viewport_menubar_light}, "Menu.Separator": { "color": cl.viewport_menubar_medium, "margin_height": fl.viewport_menubar_item_margin_height, "border_width": 1.5, }, "Menu.Item.Separator": { "color": cl.viewport_menubar_medium, "margin_height": fl.viewport_menubar_item_margin_height, "border_width": 20, }, "Menu.Window": { "background_color": cl.viewport_menubar_background, "border_width": 0, "border_radius": 0, "background_selected_color": cl.viewport_menubar_selection, "secondary_padding": 1, "secondary_selected_color": cl.viewport_menubar_selection_border, "margin": 2, }, "MenuItem": { "background_selected_color": cl.viewport_menubar_selection, "secondary_padding": 1, "secondary_selected_color": cl.viewport_menubar_selection_border, }, "Slider": { "border_radius": 100, "border_width": 1, "border_color": cl.viewport_menubar_medium, "background_color": cl(1, 1, 1, 0), "color": cl.viewport_menubar_light, "secondary_color": cl.viewport_menubar_medium, "draw_mode": ui.SliderDrawMode.FILLED, "padding": 0, }, "Slider:disabled": {"color": cl.viewport_menubar_medium}, "Menu.Item.Label": {"color": cl.viewport_menubar_light, "margin_width": fl.viewport_menubar_item_margin}, "Menu.Item.Label:disabled": {"color": cl.viewport_menubar_medium}, "Menu.Item.Text": {"color": cl.viewport_menubar_light}, "Menu.Item.Text:disabled": {"color": cl.viewport_menubar_medium}, "Menu.Item.Icon": { "image_url": f"{ICON_PATH}/none.svg", "color": 0xFFD6D6D6, "padding": 0, "margin_width": 2, "margin_height": 2, }, "Menu.Item.Icon:selected": {"image_url": f"{ICON_PATH}/check_solid.svg"}, "Menu.Item.RadioMark": { "image_url": f"{ICON_PATH}/radiomark.svg", "color": cl.viewport_menubar_selection_border, "margin_width": fl.viewport_menubar_item_margin, }, "Menu.Item.Status": { "image_url": f"{ICON_PATH}/none.svg", "color": cl.viewport_menubar_selection_border, "margin_width": fl.viewport_menubar_item_margin, }, "Menu.Item.Status:checked": {"image_url": f"{ICON_PATH}/radiomark.svg"}, "Menu.Item.Status:selected": {"image_url": f"{ICON_PATH}/check_solid.svg"}, "Menu.Item.Status::Category.None": {"image_url": f"{ICON_PATH}/none.svg"}, "Menu.Item.Status::Category.All": {"image_url": f"{ICON_PATH}/check_solid.svg"}, "Menu.Item.Status::Category.Mixed": {"image_url": f"{ICON_PATH}/mixed_checkbox.svg", "margin_width": 2}, "ComboBox": { "background_color": 0x0, "secondary_color": 0x0, "color": cl.viewport_menubar_light, "secondary_selected_color": cl.viewport_menubar_light, "secondary_background_color": cl.viewport_menubar_background, "selected_color": cl.viewport_menubar_selection, "padding": 4, "font_size": 14, }, "ComboBox:disabled": {"color": cl.viewport_menubar_medium}, "CheckBox": {"border_radius": 1}, "CheckBox:disabled": {"background_color": cl.viewport_menubar_medium}, "Label": {"color": cl.viewport_menubar_light}, "Menu.Button": { "color": cl.viewport_menubar_selection_border, "background_color": 0, "padding": 0, "margin_width": fl.viewport_menubar_item_margin, "margin_height": fl.viewport_menubar_item_margin_height, "stack_direction": ui.Direction.LEFT_TO_RIGHT, }, "Menubar.Hover": { "background_color": 0, "padding": 1, "margin": 1, }, "Menubar.Hover:hovered": { "background_color": cl.viewport_menubar_selection, "border_color": cl.viewport_menubar_selection_border_button, "border_width": 1.5 }, "Menubar.Hover:pressed": { "background_color": cl.viewport_menubar_selection, "border_color": cl.viewport_menubar_selection_border_button, "border_width": 1.5 }, "Rectangle::reset_invalid": {"background_color": 0xFF505050, "border_radius": 2}, "Rectangle::reset": {"background_color": 0xFFA07D4F, "border_radius": 2}, } VIEWPORT_PREFERENCE_STYLE = { "TreeView.Frame": {"background_color": 0xFF343432, "padding": 10}, "TreeView.Item.Label": {"color": 0xFF9E9E9E}, "TreeView.Item.Line": {"color": 0x338A8777}, "TreeView.Item.CheckBox": {"font_size": 10, "background_color": 0xFF9E9E9E, "color": 0xFF23211F, "border_radius": 0}, "TreeView.Item.ComboBox": {"color": 0xFF9E9E9E, "secondary_color": 0xFF23211F, "border_radius": 0}, "TreeView.Item.Alignment::left": {"image_url": f"{ICON_PATH}/align_left.svg"}, "TreeView.Item.Alignment::left:checked": {"image_url": f"{ICON_PATH}/align_disabled_left.svg"}, "TreeView.Item.Alignment::right": {"image_url": f"{ICON_PATH}/align_right.svg"}, "TreeView.Item.Alignment::right:checked": {"image_url": f"{ICON_PATH}/align_disabled_right.svg"}, "TreeView:drop": {"border_color": 0xFFC5911A, "background_selected_color": 0x0}, }
7,277
Python
38.770492
121
0.620036
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/extension.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ViewportMenuBarExtension"] from .menu_item.viewport_menu_spacer import ViewportMenuSpacer from .menu_item.viewport_menubar_item import ViewportMenubar from .utils.usd_watch import start as usd_watch_start from .utils.usd_watch import stop as usd_watch_stop from .viewport_layer import MenuBarViewportLayer from .viewport_menu_model import destroy as destroy_menu_model, ViewportMenuModel, AbstractViewportMenubarItem from .preference.menubar_page import ViewportMenubarPage from .style import DEFAULT_MENUBAR_NAME from omni.kit.viewport.registry import RegisterViewportLayer from omni.kit.window.preferences import register_page, unregister_page from omni.ui import color as cl from omni.ui import constant as fl from typing import List, Optional import omni.ext _extension_instance = None class ViewportMenuBarExtension(omni.ext.IExt): """The Entry Point for the Viewport Menu Bar""" def init_shades(self): """Style colors""" # https://confluence.nvidia.com/pages/viewpage.action?spaceKey=OMNIVERSE&title=Viewport+Toolbar cl.viewport_menubar_title = cl.shade(cl("#25282A")) cl.viewport_menubar_title_background = cl.shade(cl("#191A1B")) cl.viewport_menubar_background = cl.shade(cl("#25282ACC")) cl.viewport_menubar_medium = cl.shade(cl("#6E6E6E")) cl.viewport_menubar_light = cl.shade(cl("#D6D6D6")) cl.viewport_menubar_selection = cl.shade(cl("#34C7FF3B")) cl.viewport_menubar_selection_border = cl.shade(cl("#34C7FF")) cl.viewport_menubar_selection_border_button = cl.shade(cl("#2B87AA")) fl.viewport_menubar_item_margin = fl.shade(5) fl.viewport_menubar_item_margin_height = fl.shade(3) fl.viewport_menubar_height = fl.shade(30) fl.viewport_menubar_icon_size = fl.shade(30) fl.viewport_menubar_control_height = fl.shade(18) fl.viewport_menubar_border_radius = fl.shade(6) def on_startup(self, ext_id): self._model = ViewportMenuModel() # Default menubar self._top_bar_item = ViewportMenubar(DEFAULT_MENUBAR_NAME) # Preference page self._page = ViewportMenubarPage(self._model) register_page(self._page) # Start USD Watch usd_watch_start() self.init_shades() # And then the viewport-layer itself (what will build all the menu-items / widgets above) # Entry point for the custom widget in the viewport self.__viewport_layer = RegisterViewportLayer(MenuBarViewportLayer, "omni.kit.viewport.menubar.MenuBarLayer") # Register the menus ViewportMenuSpacer() global _extension_instance _extension_instance = self def on_shutdown(self): global _extension_instance _extension_instance = None self._top_bar_item.destroy() self._page.destroy() unregister_page(self._page) self._page = None self._model.destroy() # Destroy every item in the model and release them destroy_menu_model() self.__viewport_layer.destroy() self.__viewport_layer = None # Stop USD Watch usd_watch_stop() def get_menubars(self) -> List[AbstractViewportMenubarItem]: return self._model.get_item_children() def get_menubar(self, name: str) -> Optional[AbstractViewportMenubarItem]: for item in self.get_menubars(): if item.name == name: return item else: return None def get_instance(): global _extension_instance return _extension_instance
4,030
Python
36.324074
117
0.6933
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/__init__.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # ''' ### WIP TBD ### PROBLEM: David has a very good menu:: self._edit_menu_list = [ MenuItemDescription( name="Undo", glyph="none.svg", enable_fn=lambda: omni.kit.undo.can_undo(), onclick_fn=omni.kit.undo.undo, hotkey=(carb.input.KEYBOARD_MODIFIER_FLAG_CONTROL, carb.input.KeyboardInput.Z), ) ] omni.kit.menu.utils.add_menu_items(self._edit_menu_list, "Edit", -9) # Also: set_default_menu_proirity # Also: remove_menu_items # Also: add_hook # Also: remove_hook # Also: add_layout # Also: remove_layout # Pros: # - Lots of features # - Lots of callbacks # - Easy to read # Cons: # - Limited with ImGui Menu # - No support of widgets # - MenuItemDescription per menu item ### GOAL ### # https://confluence.nvidia.com/pages/viewpage.action?spaceKey=OMNIVERSE&title=Viewport+Toolbar # - Reuse the MenuItemDescription experience # - Leverage new menu # - Flexibility # - Decentralization # - MVP: Viewport menu # - Ability to evolve to the universal menu framework ### SIMPLE CASE EXAMPLE ### Example:: class SliderMenuDelegate(ui.MenuDelegate): """A menu delegate that draws the Label and the Slider""" def __init__(self, model): self._model = model def build_item(self, item): ui.Label(item.text, width=200) ui.FloatSlider(self._model) # Put the menu item to the "Camera" menu with omni.kit.viewport.menubar.get_menu_item("Camera"): # Just declare, ViewportMenuItem will be stored in the model ViewportMenuItem(name="Camera Speed", parent="Camera", delegate=SliderMenuDelegate(self._speed_model)) ViewportMenuItem( name="Camera Speed Scaller", parent="Camera", delegate=SliderMenuDelegate(self._speed_scale_model) ) ADVANCED CASE EXAMPLE:: class HudMenu(ViewportMenuItem): def build_fn(self): # Not limited with one item per class with ui.Menu("Hud Status"): ui.MenuItem("FPS", checkable=True, checked=fps_checked) ui.MenuItem("GPU Memory", checkable=True, checked=gpu_checked) ui.MenuItem("Host Memory", checkable=True, checked=host_checked) ui.MenuItem("Resolution", checkable=True, checked=res_checked) API:: class ViewportMenu: def __init__(self, name: str = "", icon: str = "", appear_after: Union[list, str] = "", hotkey: Tuple[int, int] = None, onclick_fn: Callable = None, delegate: ui.MenuDelegate = None # ): # Adds self to the registry ... def build_fn(self): """ Called by the parent. Everything that is here is added to the parent ui.Menu. """ # Ability to reimplement # By default it creates a single ui.MenuItem only ... def invalidate(self): ... ''' from .extension import ViewportMenuBarExtension, get_instance from .viewport_menu_model import get_item as get_menu_item, MenuDisplayStatus from .menu_item.viewport_menu_container import ViewportMenuContainer from .menu_item.viewport_menu_item import ViewportMenuItem from .menu_item.viewport_menu_separator import ViewportMenuSeparator from .menu_item.color_menu_item import AbstractColorMenuItem, FloatArraySettingColorMenuItem from .menu_item.radio_menu_collection import RadioMenuCollection from .menu_item.selectable_menu_item import SelectableMenuItem from .menu_item.category_menu_collection import CategoryMenuCollection, CategoryStatus from .menu_item.category_menu_container import CategoryMenuContainer from .menu_item.viewport_button_item import ViewportButtonItem from .menu_item.viewport_menubar_item import ViewportMenubar from .menu_item.viewport_menu_spacer import ViewportMenuSpacer from .delegate.icon_menu_delegate import IconMenuDelegate from .delegate.slider_menu_delegate import SliderMenuDelegate from .delegate.checkbox_menu_delegate import CheckboxMenuDelegate from .delegate.category_menu_delegate import CategoryMenuDelegate from .delegate.color_menu_delegate import ColorMenuDelegate from .delegate.combobox_menu_delegate import ComboBoxMenuDelegate from .delegate.spinner_menu_delegate import SpinnerMenuDelegate from .delegate.viewport_menu_delegate import ViewportMenuDelegate from .delegate.category_menu_delegate import CategoryMenuDelegate from .delegate.separator_menu_delegate import SeparatorDelegate from .delegate.label_menu_delegate import LabelMenuDelegate from .delegate.abstract_widget_menu_delegate import AbstractWidgetMenuDelegate from .model.setting_model import SettingModel, SettingModelWithDefaultValue from .model.usd_attribute_model import USDAttributeModel, USDBoolAttributeModel, USDIntAttributeModel, USDFloatAttributeModel, USDStringAttributeModel from .model.usd_metadata_model import USDMetadataModel from .model.combobox_model import ComboBoxItem, ComboBoxModel, SettingComboBoxModel from .model.list_model import SimpleListItem, SimpleListModel from .model.category_model import SimpleCategoryModel, CategoryCollectionItem, CategoryStateItem, CategoryCustomItem, BaseCategoryItem from .model.reset_button import ResetButton, ResetHelper from .utils import menu_is_tearable from .style import DEFAULT_MENUBAR_NAME, VIEWPORT_MENUBAR_STYLE
5,907
Python
37.363636
150
0.716269
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/viewport_menu_model.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["AbstractViewportMenuItem", "AbstractViewportMenubarItem", "ViewportMenuModel", "register", "deregister", "get_items", "get_item", "push_to_scope", "pop_from_scope", "destroy"] from collections import defaultdict from typing import Dict, List, Optional, Union, TYPE_CHECKING import weakref import abc from numpy import isin import carb import omni.ui as ui from .model.setting_model import SettingModelWithDefaultPath from .style import DEFAULT_MENUBAR_NAME class MenuDisplayStatus: MIN = 0 LABEL = 1 EXPAND = 2 MAX = 3 def Singleton(class_): """A singleton decorator""" instances = {} def getinstance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return getinstance class AbstractViewportMenuItem(ui.AbstractItem): """ Represent menu item. Kwargs: name (str): Name of menu item. Default "" to use self. visible_setting_path (Optional[str]): Setting path for visibility. Default None. order_setting_path (Optional[str]): Setting path for order. Default None. Order < 0 means in left of menubar. Order > 0 means in right of menubar. exapnd_setting_path (Optional[str]): Setting path for expand status. Default None. """ def __init__( self, name: str = "", visible_setting_path: Optional[str] = None, order_setting_path: Optional[str] = None, expand_setting_path: Optional[str] = None ): self._name = name or str(self) if visible_setting_path: self.visible_model = SettingModelWithDefaultPath(visible_setting_path) else: self.visible_model = ui.SimpleBoolModel(True) if order_setting_path: self.order_model = SettingModelWithDefaultPath(order_setting_path) else: self.order_model = ui.SimpleIntModel(-1) if expand_setting_path: self.expand_model = SettingModelWithDefaultPath(expand_setting_path) else: self.expand_model = None # Put it to registry self._parent = register(self) self.clip_level = MenuDisplayStatus.MIN super().__init__() def destroy(self): # Remove from registry deregister(self) @property def name(self): """Item name""" return self._name @property def parent(self): """Parent item""" return self._parent def get_display_status(self, factory_args: dict) -> MenuDisplayStatus: """ Menu item display status. """ return MenuDisplayStatus.MIN def get_require_size(self, factory_args: dict, expand: bool = False) -> float: """ Required size for menu item. kwargs: expand (bool): True for menu item to expand. False for menu item in current display status. """ return 0 def expand(self, factory_args: dict) -> None: """ Expand display of menu item. """ pass def can_contract(self, factory_args: dict) -> bool: """ If menu item could contract to smaller size. Default False. """ return False def contract(self, factory_args: dict) -> None: """ Contract menu item to smaller size. """ return class AbstractViewportMenubarItem(AbstractViewportMenuItem): """ Represent a menubar. """ @abc.abstractmethod def build_fn(self, menu_items: List[AbstractViewportMenuItem], factory: Dict): """ Build menubar. Args: menu_items (List[AbstractViewportMenuItem]): Menu items to display on the menubar """ pass @Singleton class ViewportMenuModel(ui.AbstractItemModel): def __init__(self): super().__init__() def destroy(self): pass """General functions of ui.AbstractItemMode""" def get_item_children(self, parent_item: Union[AbstractViewportMenuItem, AbstractViewportMenubarItem, None] = None) -> List[AbstractViewportMenuItem]: if parent_item is None: # Retreive all menubar items items = get_items() elif isinstance(parent_item, AbstractViewportMenubarItem): # Retreive menu items for a menubar items = get_items(parent_item.name) else: items = [] if items: items.sort(key=lambda item: item.order_model.as_int) return items else: return [] def get_item_value_model_count(self, item: AbstractViewportMenuItem): """The number of columns""" return 1 def get_item_value_model(self, item: AbstractViewportMenuItem, column_id: int): if item and column_id == 0: return ui.SimpleStringModel(item.name) return ui.SimpleStringModel("") """Enable drag and drop""" 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 def drop_accepted(self, target_item, source, drop_location=-1): """Reimplemented from AbstractItemModel. Called to highlight target when drag and drop.""" if isinstance(source, AbstractViewportMenuItem) and target_item: return True else: return False def drop(self, target_item, source, drop_location=-1): """Reimplemented from AbstractItemModel. Called when dropping something to the item.""" if isinstance(source, AbstractViewportMenuItem): self._drop_item(target_item, source, drop_location) def _drop_item(self, target: AbstractViewportMenuItem, source: AbstractViewportMenuItem, drop_location=-1): items = self.get_item_children() source_index = items.index(source) target_index = items.index(target) if source_index > target_index: # Drop forward, source in front of target if target.order_model.as_int < 0: # Left, make order of source smaller than target source.order_model.set_value(target.order_model.as_int - 1) # Make sure other items in front of source has smaller order last = source for item in reversed(items[0 : target_index]): if item.order_model.as_int >= last.order_model.as_int: item.order_model.set_value(last.order_model.as_int - 1) last = item else: break else: # Right, replace order of source with target source.order_model.set_value(target.order_model.as_int) # Make sure other items behind source (include target) bas bigger order last = source for item in items[target_index:]: if item.order_model.as_int <= last.order_model.as_int: item.order_model.set_value(last.order_model.as_int + 1) last = item else: break else: # Drop backward, source behind of target if target.order_model.as_int < 0: # Left, replace order of source with target source.order_model.set_value(target.order_model.as_int) # Make sure items bwtween source and target has smaller order last = source for item in reversed(items[source_index + 1 : target_index + 1]): if item.order_model.as_int >= last.order_model.as_int: item.order_model.set_value(last.order_model.as_int - 1) break else: # Right, make order of next items bigger source.order_model.set_value(target.order_model.as_int + 1) last = source for item in items[target_index + 1:]: if item.order_model.as_int <= last.order_model.as_int: item.order_model.set_value(last.order_model.as_int + 1) last = item else: break self._item_changed(source) self._item_changed(None) _parentname_to_name = defaultdict(list) _name_to_menuitem: Dict[str, AbstractViewportMenuItem] = {} _scope_stack: List[AbstractViewportMenuItem] = [] def register(menu_item: Union[AbstractViewportMenuItem, AbstractViewportMenubarItem]) -> "weakref.ProxyType[AbstractViewportMenuItem]": """ Register the item in the storage. It keeps the item, so to destroy it, it's necessary to use `deregister` or `destroy`. It's called in the constructor of `ViewportMenuItem`, so once the item is created, it automatically registers here. Returns the proxy with the parent, so the child stores it and avoids circular reference. """ # Name is the unique identifier name = menu_item.name # Get parent if _scope_stack: parent = _scope_stack[-1] parent_name = parent.name elif isinstance(menu_item, AbstractViewportMenubarItem): # For menubar, register to root by default parent = None parent_name = None elif isinstance(menu_item, AbstractViewportMenuItem): # For menu item, register to default menubar by default parent = get_item(DEFAULT_MENUBAR_NAME) parent_name = DEFAULT_MENUBAR_NAME else: parent = None parent_name = None carb.log_info(f"register {name}, order: {menu_item.order_model.as_int}, parent: {parent_name}") # Save it. We keep the object, it means we need to explicitly delete it when # shutdown. _parentname_to_name[parent_name].append(name) _name_to_menuitem[name] = menu_item if parent is None or isinstance(parent, AbstractViewportMenubarItem): # Now only care about root menus and menubar items ViewportMenuModel()._item_changed(parent) # Return parent proxy to avoid circular references. if parent: return weakref.proxy(parent) else: return None def deregister(menu_item: AbstractViewportMenuItem): """Remove item from the storage""" name = menu_item.name parent = None parent_name = None # parent is weakref.proxy and underlying object may already not exists import contextlib with contextlib.suppress(ReferenceError): if menu_item.parent: parent = menu_item.parent parent_name = parent.name carb.log_info(f"deregister {name} from {parent_name}") if parent_name in _parentname_to_name and name in _parentname_to_name[parent_name]: _parentname_to_name[parent_name].remove(name) if name in _parentname_to_name: _parentname_to_name.pop(name) if name in _name_to_menuitem: _name_to_menuitem.pop(name) if parent is None or isinstance(parent, AbstractViewportMenubarItem): # Now only care about root menus and items in root menus # Here parent maybe a weakproxy, always use None instead ViewportMenuModel()._item_changed(None) def get_items(parent_name: Optional[str] = None) -> List[AbstractViewportMenuItem]: """Get the list of items by parent name""" return [_name_to_menuitem[name] for name in _parentname_to_name[parent_name]] def get_item(name: Optional[str] = None) -> AbstractViewportMenuItem: """Get the items by name""" return _name_to_menuitem.get(name, None) def push_to_scope(menu_container: "ViewportMenuContainer"): """ Called from `__enter__` when using `with` statement. Puts the container to the stack so the children know their parents. """ _scope_stack.append(menu_container) def pop_from_scope(): """Called from `__exit__` when using `with` statement.""" _scope_stack.pop() def destroy(): """Clear items""" _parentname_to_name.clear() _name_to_menuitem.clear() _scope_stack.clear()
12,645
Python
34.030471
187
0.623013
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/preference/model.py
import omni.ui as ui from ..viewport_menu_model import ViewportMenuModel, AbstractViewportMenuItem from ..menu_item.viewport_menubar_item import ViewportMenubar from ..style import DEFAULT_MENUBAR_NAME __all__ = ["PreferenceModel"] class PreferenceModel(ui.AbstractItemModel): """ Wrapper model for preference page. Only show default menubar in preference page. So using this wrapper to get menu items for default menubar only. """ def __init__(self, model: ViewportMenuModel): self._model = model self.__sub_menubar_changed = self._model.subscribe_item_changed_fn(self.__on_menuabr_changed) super().__init__() def destroy(self): self.__sub_menubar_changed = None def get_item_children(self, parent_item=None): if parent_item is None: for item in self._model.get_item_children(): if item.name == DEFAULT_MENUBAR_NAME: # Only show default menubar return self._model.get_item_children(item) return [] def get_item_value_model_count(self, item: AbstractViewportMenuItem): """The number of columns""" return 1 def get_item_value_model(self, item: AbstractViewportMenuItem, column_id: int): if item and column_id == 0: return ui.SimpleStringModel(item.name) return ui.SimpleStringModel("") """Enable drag and drop""" 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 def drop_accepted(self, target_item, source, drop_location=-1): """Reimplemented from AbstractItemModel. Called to highlight target when drag and drop.""" if isinstance(source, AbstractViewportMenuItem) and target_item: return True else: return False def drop(self, target_item, source, drop_location=-1): """Reimplemented from AbstractItemModel. Called when dropping something to the item.""" if isinstance(source, AbstractViewportMenuItem): self._drop_item(target_item, source, drop_location) def _drop_item(self, target: AbstractViewportMenuItem, source: AbstractViewportMenuItem, drop_location=-1): items = self.get_item_children() source_index = items.index(source) target_index = items.index(target) if source_index > target_index: # Drop forward, source in front of target if target.order_model.as_int < 0: # Left, make order of source smaller than target source.order_model.set_value(target.order_model.as_int - 1) # Make sure other items in front of source has smaller order last = source for item in reversed(items[0 : target_index]): if item.order_model.as_int >= last.order_model.as_int: item.order_model.set_value(last.order_model.as_int - 1) last = item else: break else: # Right, replace order of source with target source.order_model.set_value(target.order_model.as_int) # Make sure other items behind source (include target) bas bigger order last = source for item in items[target_index:]: if item.order_model.as_int <= last.order_model.as_int: item.order_model.set_value(last.order_model.as_int + 1) last = item else: break else: # Drop backward, source behind of target if target.order_model.as_int < 0: # Left, replace order of source with target source.order_model.set_value(target.order_model.as_int) # Make sure items bwtween source and target has smaller order last = source for item in reversed(items[source_index + 1 : target_index + 1]): if item.order_model.as_int >= last.order_model.as_int: item.order_model.set_value(last.order_model.as_int - 1) break else: # Right, make order of next items bigger source.order_model.set_value(target.order_model.as_int + 1) last = source for item in items[target_index + 1:]: if item.order_model.as_int <= last.order_model.as_int: item.order_model.set_value(last.order_model.as_int + 1) last = item else: break self._model._item_changed(source) self._model._item_changed(None) self._item_changed(source) self._item_changed(None) def __on_menuabr_changed(self, model: ui.AbstractItemModel, item: ui.AbstractItem): # OM-77174: update preference treeview when # menubar item changed # Item is None means menubar item is removed if item is None or isinstance(item, ViewportMenubar): self._item_changed(None)
5,347
Python
43.941176
115
0.588741
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/preference/menubar_treeview_delegate.py
import omni.ui as ui from typing import Dict, Callable from ..menu_item.viewport_menu_item import ViewportMenuItem from ..viewport_menu_model import ViewportMenuModel from ..model.combobox_model import SettingComboBoxModel from ..model.reset_button import ResetButton __all__ = ["AlignmentImages", "MenubarTreeViewDelegate"] class AlignmentImages(): def __init__(self, left: bool, on_alignment_changed: Callable[[bool], None], icon_size: int = 20): self._on_alignment_clicked = on_alignment_changed with ui.VStack(width=0): ui.Spacer() with ui.HStack(spacing=10, height=0): self._left = ui.ImageWithProvider(width=icon_size, height=icon_size, style_type_name_override="TreeView.Item.Alignment", name="left", checked=not left) self._right = ui.ImageWithProvider(width=icon_size, height=icon_size, style_type_name_override="TreeView.Item.Alignment", name="right", checked=left) ui.Spacer() if left: self._right.set_mouse_pressed_fn(lambda x, y, b, a: on_alignment_changed(False)) else: self._left.set_mouse_pressed_fn(lambda x, y, b, a: on_alignment_changed(True)) class MenubarTreeViewDelegate(ui.AbstractItemDelegate): """ Delegate is the representation layer. TreeView calls the methods of the delegate to create custom widgets for each item. """ def __init__(self): super().__init__() self._widgets: Dict[ViewportMenuItem, ui.Widget] = {} def destroy(self): self._widgets.clear() 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: ViewportMenuModel, item: ViewportMenuItem, column_id, level, expanded): """Create a widget per column per item""" if "ViewportMenuSpacer" in item.name: # Do not show spacer here return if column_id == 0: self._widgets[item] = ui.HStack(height=20) with self._widgets[item]: # NAME name_model = model.get_item_value_model(item, 0) ui.Label(name_model.as_string, style_type_name_override="TreeView.Item.Label") ui.Spacer() with ui.HStack(spacing=10, width=ui.Percent(60)): # Visible with ui.VStack(width=0): ui.Spacer() ui.CheckBox(item.visible_model, width=10, height=0, style_type_name_override="TreeView.Item.CheckBox") ui.Spacer() # Alignment AlignmentImages(item.order_model.as_int < 0, lambda l, m=model, i=item: self._on_alignment_changed(m, i, l)) # Expand if item.expand_model: expand_combox_model = SettingComboBoxModel(item.expand_model.path, ["Expanded", "Collapsed"], values=[True, False]) ui.ComboBox(expand_combox_model, style_type_name_override="TreeView.Item.ComboBox") # Line ui.Line(width=ui.Fraction(1), style_type_name_override="TreeView.Item.Line") # Reset button models = [item.visible_model, item.order_model] if item.expand_model: models.append(item.expand_model) reset_btn = ResetButton(models, on_reset_fn=lambda m=model, i=item: self._on_reset(m, i)) item.visible_model.set_reset_button(reset_btn) item.order_model.set_reset_button(reset_btn) if item.expand_model: item.expand_model.set_reset_button(reset_btn) def _on_alignment_changed(self, model: ViewportMenuModel, item: ViewportMenuItem, left: bool): item.order_model.set_value(-item.order_model.as_int) # Need to update both item and whole treeview model._item_changed(item) model._item_changed(None) def _on_reset(self, model: ViewportMenuModel, item: ViewportMenuItem): # Need to update both item and whole treeview model._item_changed(item) model._item_changed(None)
4,296
Python
42.40404
167
0.600093
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/preference/menubar_page.py
from omni.kit.window.preferences import PreferenceBuilder import omni.ui as ui from typing import Optional from .menubar_treeview_delegate import MenubarTreeViewDelegate from .model import PreferenceModel from ..viewport_menu_model import ViewportMenuModel from ..style import VIEWPORT_PREFERENCE_STYLE __all__ = ["ViewportMenubarPage"] class ViewportMenubarPage(PreferenceBuilder): """ Represent a pereference page to show and edit viewport menubar settings. """ def __init__(self, model: ViewportMenuModel): super().__init__("Viewport") self._model = PreferenceModel(model) self._tree_view: Optional[ui.TreeView] = None def destroy(self): if self._tree_view: self._delegate.destroy() self._tree_view.destroy() self._tree_view = None self._model.destroy() def build(self): self._delegate = MenubarTreeViewDelegate() with self.add_frame("Viewport Toolbar"): with ui.ScrollingFrame(style_type_name_override="TreeView.Frame", style=VIEWPORT_PREFERENCE_STYLE): self._tree_view = ui.TreeView(self._model, delegate=self._delegate, root_visible=False)
1,196
Python
35.272726
111
0.686455
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/menu_item/color_menu_item.py
from ..delegate.color_menu_delegate import ColorMenuDelegate from ..model.list_model import ColorModel from .viewport_menu_item import ViewportMenuItem from typing import List, Optional import carb.settings import omni.kit.app import omni.ui as ui import asyncio __all__ = ["AbstractColorMenuItem", "FloatArraySettingColorMenuItem"] class AbstractColorMenuItem(ui.MenuItem): def __init__(self, colors: List[float], name: str = "", default: Optional[List[float]] = None, has_reset: bool = False): self.model = ColorModel(colors, default=default, on_color_changed_fn=self.on_color_changed) super().__init__(name, delegate=ColorMenuDelegate(model=self.model, has_reset=has_reset), hide_on_click=False) def destroy(self): if self.model: self.model.destroy() self.model = None def on_color_changed(self, colors: List[float]) -> None: pass def reset(self) -> None: pass class FloatArraySettingColorMenuItem(AbstractColorMenuItem): def __init__(self, setting_path: str, default: List[float], name: str = "", start_index: int = 0, has_reset: bool = False): self._settings = carb.settings.get_settings() self.__path = setting_path self.__start_index = start_index self.__default = default self.__color_size = len(default) # Future used to collapse carb-settings change events for individual color components self.__future = None # Fill in default color if the setting key does not exists at all color_array = self._settings.get(self.__path) if color_array is None: color_array = [0] * (start_index + self.__color_size) for index, value in enumerate(self.__default): color_array[start_index + index] = value self._settings.set(self.__path, color_array) self.__color_subs = None self.__create_color_subs() super().__init__(self._get_color(), default=self.__default, name=name, has_reset=has_reset) def __del__(self): self.destroy() def destroy(self): self.__color_subs = None super().destroy() def __get_color_paths(self): for i in range(self.__start_index, self.__start_index + self.__color_size): yield f"{self.__path}/{i}" def __create_color_subs(self): # Create the carb-settings event watchers on the individual color components self.__color_subs = [omni.kit.app.SettingChangeSubscription(path, self.__on_change) for path in self.__get_color_paths()] def __on_change(self, item: carb.dictionary.Item, event_type: carb.settings.ChangeEventType) -> None: # Since the value is a color (3/4 elements), batch the model updated into a single call # Skip any event thats not a change if event_type != carb.settings.ChangeEventType.CHANGED: return # Check if an operation is already waiting to run if self.__future and not self.__future.done(): return # Create the Future to signal the model is up to date self.__future = asyncio.Future() async def update_model(): if not self.__future.done(): self.__future.set_result(True) colors = self._get_color() if colors != self.model.colors: self.model.colors = colors asyncio.ensure_future(update_model()) def _get_color(self) -> List[float]: return [self._settings.get(path) for path in self.__get_color_paths()] def destroy(self): self.__color_subs = None super().destroy() def on_color_changed(self, colors: List[float]) -> None: setting_colors = self._settings.get(self.__path) if setting_colors is None: # TODO: create default here? or required be filled outside return if setting_colors[self.__start_index : self.__start_index + self.__color_size] != colors: for index, value in enumerate(colors): setting_colors[self.__start_index + index] = value # Kill the change subscription before the carb.settings.set call. # This is to optimize the array change, which will delete and recreate elemetns individually. # This is particularly noticable for large arrays (1000+), but since colors are arrays of 4 do it always. try: self.__color_subs = None self._settings.set(self.__path, setting_colors) finally: self.__create_color_subs() def reset(self) -> None: self.model.restore_default()
4,660
Python
38.5
129
0.623176
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/menu_item/viewport_menu_container.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ViewportMenuContainer"] from ..viewport_menu_model import get_items, deregister from ..viewport_menu_model import pop_from_scope from ..viewport_menu_model import push_to_scope from ..viewport_menu_model import ViewportMenuModel from .viewport_menu_item import ViewportMenuItem from typing import Dict import omni.ui as ui class ViewportMenuContainer(ViewportMenuItem): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # When visible and order changed, trigger UI updates self._visible_sub = self.visible_model.subscribe_value_changed_fn(lambda m: self._invalidate()) self._order_sub = self.order_model.subscribe_value_changed_fn(lambda m: self._invalidate()) def destroy(self): self._visible_sub = None self._order_sub = None # Clean children self._clean() super().destroy() def build_fn(self, factory: Dict): """Reimplement it to have own customized item""" children = self._children # TODO: Lazy menu with ui.Menu(self.name, delegate=self._delegate, style=self._style): for child in children: child.build_fn(factory) def __enter__(self): # Clean all existing child items # For multiple viewport window, menu contrainer may build multiple times # Make sure child items not duplicated self._clean() push_to_scope(self) def __exit__(self, exc_type, exc_value, traceback): pop_from_scope() @property def _children(self): # TODO: Sorting code return get_items(self.name) def _invalidate(self) -> None: ViewportMenuModel()._item_changed(None) def _clean(self): for child in self._children: child.destroy()
2,244
Python
32.507462
103
0.67246
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/menu_item/viewport_menu_item.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ViewportMenuItem"] from ..viewport_menu_model import AbstractViewportMenuItem from typing import Callable, Dict, Optional import omni.ui as ui class ViewportMenuItem(AbstractViewportMenuItem): def __init__( self, name: str = "", icon: str = "", # glyph? hide_on_click: bool = True, appear_after: str = "", # order/priority? onclick_fn: Callable = None, delegate: ui.MenuDelegate = None, visible_setting_path: Optional[str] = None, order_setting_path: Optional[str] = None, expand_setting_path: Optional[str] = None, style: Dict = {}, order: int = None # deprecated legacy interface ): self._icon = icon self._hide_on_click = hide_on_click self._appear_after = appear_after self._onclick_fn = onclick_fn self._delegate = delegate self._style = style self._menu_item: Optional[ui.MenuItem] = None super().__init__( name, visible_setting_path=visible_setting_path, order_setting_path=order_setting_path, expand_setting_path=expand_setting_path, ) if (order_setting_path is None) and (order is not None): import carb carb.log_warn(f"ViewportMenuItem order argument is deprecated, use order_setting_path") self.order_model = ui.SimpleIntModel(order) def destroy(self): self._onclick_fn = None self._delegate = None super().destroy() @property def visible(self) -> bool: return self.visible_model.as_bool @visible.setter def visible(self, value: bool) -> None: self.visible_model.set_value(value) if self._menu_item: self._menu_item.visible = value @property def menu_item(self) -> ui.MenuItem: return self._menu_item def build_fn(self, factory: Dict): """Reimplement it to have own customized item""" self._menu_item = ui.MenuItem( self.name, triggered_fn=self._onclick_fn, delegate=self._delegate, hide_on_click=self._hide_on_click, visible=self.visible_model.as_bool, style=self._style, ) def invalidate(self): pass
2,752
Python
31.773809
99
0.619549
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/menu_item/selectable_menu_item.py
from typing import Callable from ..delegate.viewport_menu_delegate import ViewportMenuDelegate from omni import ui __all__ = ["SelectableMenuItem"] class SelectableMenuItem(ui.MenuItem): """Menu item could be selected and show icon when selected. kwargs: model (ui.AbstractValueModel): Model for selected status. Defaults to a ui.SimpleBoolModel when not provided. toggle (bool): Whether this item can be toggled to (on/off) or always triggers on For other kwargs, please refer to ui.MenuItem """ def __init__(self, name: str, model: ui.AbstractValueModel = None, delegate: ui.MenuDelegate = None, hide_on_click: bool = False, toggle: bool = True, triggered_fn: Callable = None, trigger_will_set_model: bool = False, **kwargs): if model is None: model = ui.SimpleBoolModel() if delegate is None: delegate = ViewportMenuDelegate() self._triggered_fn = triggered_fn self.__trigger_will_set_model = trigger_will_set_model kwargs['triggered_fn'] = self._on_triggered if toggle: kwargs['selected'] = kwargs.get('selected', model.as_bool) else: kwargs['checkable'] = kwargs.get('checkable', True) kwargs['checked'] = kwargs.get('checked', model.as_bool) super().__init__( name, delegate=delegate, hide_on_click=hide_on_click, **kwargs ) self._sub = model.subscribe_value_changed_fn(self._on_value_changed) self.model = model self.__toggle = toggle def __del__(self): self.destroy() def destroy(self) -> None: self.set_triggered_fn(None) model, self.model, self._sub = self.model, None, None if model: if hasattr(model, 'destroy'): model.destroy() super().destroy() def _on_triggered(self) -> None: if not self.__trigger_will_set_model: if self.__toggle: self.model.set_value(not self.model.as_bool) else: self.model.set_value(True) if self._triggered_fn: self._triggered_fn() def _on_value_changed(self, model: ui.AbstractValueModel) -> None: # When value changed, update selected status value = model.as_bool attr_name = 'selected' if self.__toggle else 'checked' if getattr(self.delegate, attr_name) != value: setattr(self.delegate, attr_name, value)
2,635
Python
33.233766
117
0.576471
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/menu_item/viewport_menu_separator.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ViewportMenuSeparator"] from .viewport_menu_item import ViewportMenuItem from typing import Dict import omni.ui as ui class ViewportMenuSeparator(ViewportMenuItem): """A simple separator""" def build_fn(self, factory: Dict): ui.Separator( delegate=ui.MenuDelegate( on_build_item=lambda _: ui.Line( height=0, alignment=ui.Alignment.V_CENTER, style_type_name_override="Menu.Separator" ) ) )
938
Python
33.777777
104
0.702559
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/menu_item/category_menu_collection.py
import omni.kit.app from omni import ui from ..model.category_model import SimpleCategoryModel, CategoryStateItem, CategoryCollectionItem, CategoryCustomItem from ..delegate.category_menu_delegate import CategoryMenuDelegate, CategoryStatus from ..utils import menu_is_tearable from .selectable_menu_item import SelectableMenuItem from typing import Callable, Dict, Optional __all__ = ["CategoryMenuCollection"] class CategoryMenuCollection(ui.MenuItemCollection): """ A Menu with ratio sub menu items. Args: text (str): Menu text model (SimpleCategoryModel): Model for sub menu items item (CategoryCollectionItem): Item for this collection """ def __init__(self, model: SimpleCategoryModel, item: CategoryCollectionItem, identifier: str = None, trigger_fns: Optional[Dict[str, Callable]] = None): # XXX: trigger_fns is a workaround for omni.kit.viewport.menubar.display # do not expect it will always exists! self.__trigger_fns: Optional[Dict[str, Callable]] = trigger_fns self.__identifier = identifier self._model = model self._item = item self._delegate = CategoryMenuDelegate(item.status, icon_clicked_fn=self._on_icon_clicked) self._sub = self._item.status_model.subscribe_value_changed_fn(self._on_status_changed) super().__init__(item.text, delegate=self._delegate, on_build_fn=self._build_menu_items, hide_on_click=False, tearable=menu_is_tearable(identifier), shown_changed_fn=item.shown_changed_fn) def destroy(self) -> None: self._sub = None if self._item: self._item.destroy() self._item = None self.__trigger_fns = None super().destroy() def _build_menu_items(self): custom_items = [] def attach_trigger_fn(item, name: str): if self.__trigger_fns and item and name: # Try to pull a triggered_fn from the ones provided trigger_fn = self.__trigger_fns.get(name) if trigger_fn: item.set_triggered_fn(trigger_fn) show_separator = False for item in self._model.get_item_children(self._item): name: str = getattr(item, "text", "") if isinstance(item, CategoryStateItem): item = SelectableMenuItem(item.text, model=item.value_model) show_separator = True if isinstance(item, CategoryCollectionItem): item = CategoryMenuCollection(self._model, item) show_separator = True elif isinstance(item, CategoryCustomItem): item = custom_items.append(item) attach_trigger_fn(item, name) if custom_items: # Custom items have different states from other category items # Show a separator here if required if show_separator: ui.Separator() for item in custom_items: name: str = getattr(item, "text", "") item = item.build_fn() attach_trigger_fn(item, name) def _on_status_changed(self, model: ui.AbstractValueModel) -> None: self._delegate.status = self._item.status def _on_icon_clicked(self, x, y, button, modifiers) -> None: import carb if button != int(carb.input.MouseInput.LEFT_BUTTON): return # XXX: trigger_fns workaround to avoid status-model subscriptions firing multiple times. # # There is a checken-egg problem here, where if the trigger_fn is run first the it must know about # all-items current state to follow the all, empty, mixed model...but if run after then, the trigger_fn # has no idea of what item transitioned to what state. Opting to deal with the first issue as this is # only used for "Show By Type" where the bigger win is performance from batching all state transition into # one UsdStage Traversal. # But that means the status must be saved first, as triggered_fn may change child item state, which would affect # how the models urrent state is chosen when it is run afterward. cur_status = self._delegate.status if cur_status == CategoryStatus.EMPTY or cur_status == CategoryStatus.MIXED: cur_status = CategoryStatus.ALL else: cur_status = CategoryStatus.EMPTY if self.__trigger_fns: trigger_fn = self.__trigger_fns.get(self.__identifier) if trigger_fn: trigger_fn() self._item.status = cur_status
4,729
Python
42
120
0.621062
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/menu_item/viewport_menu_spacer.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ViewportMenuSpacer"] from .viewport_menu_item import ViewportMenuItem from typing import Dict import omni.ui as ui class ViewportMenuSpacer(ViewportMenuItem): """A simple spacer""" def __init__(self): self.__spacer: Dict[int, ui.Spacer] = {} super().__init__(order_setting_path="/exts/omni.kit.viewport.menubar.core/spacer/order") def build_fn(self, factory_args: Dict): viewport_api_id = factory_args['viewport_api'].id self.__spacer[viewport_api_id] = ui.Spacer() def get_computed_width(self, factory_args: Dict) -> float: viewport_api_id = factory_args['viewport_api'].id return self.__spacer[viewport_api_id].computed_width if viewport_api_id in self.__spacer else 0
1,185
Python
39.89655
103
0.720675
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/menu_item/category_menu_container.py
from ..model.category_model import CategoryCustomItem, SimpleCategoryModel, CategoryStateItem, CategoryCollectionItem, CategoryStatus from .category_menu_collection import CategoryMenuCollection from .selectable_menu_item import SelectableMenuItem from typing import Callable, Dict, Optional __all__ = ["CategoryMenuContainer"] class CategoryMenuContainer: def __init__(self, model: SimpleCategoryModel, identifier: Optional[str] = None, trigger_fns: Optional[Dict[str, Callable]] = None): self._model = model self.__identifier = identifier self.build(trigger_fns) def build(self, trigger_fns: Optional[Dict[str, Callable]] = None): # XXX: trigger_fns is a workaround for omni.kit.viewport.menubar.display # do not expect it will always exists! for item in self._model.get_item_children(): name: str = getattr(item, "text", "") if isinstance(item, CategoryCollectionItem): identifier = f"{self.__identifier}.{name}" if self.__identifier else None item = CategoryMenuCollection(self._model, item, identifier=identifier, trigger_fns=trigger_fns) elif isinstance(item, CategoryStateItem): item = SelectableMenuItem(name=name, model=item.value_model) elif isinstance(item, CategoryCustomItem): item = item.build_fn() # Try to pull a triggered_fn from the ones provided if trigger_fns and item and name: trigger_fn = trigger_fns.get(name) if trigger_fn: item.set_triggered_fn(trigger_fn)
1,650
Python
46.171427
133
0.65697
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/menu_item/viewport_menubar_item.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ViewportMenubar"] import asyncio from dataclasses import dataclass, fields, field from functools import partial from ..viewport_menu_model import AbstractViewportMenuItem, AbstractViewportMenubarItem, ViewportMenuModel, push_to_scope, pop_from_scope, MenuDisplayStatus from .viewport_menu_spacer import ViewportMenuSpacer from typing import Callable, Dict, Optional, List import omni.kit.app import omni.ui as ui from ..style import VIEWPORT_MENUBAR_STYLE @dataclass class MenubarContext: frame: ui.Frame = None background_rectangle: ui.Rectangle = None resize_future: asyncio.Future = None spacer_width: float = -1 sub_menu_expand: Dict = field(default_factory=dict) def __init__(self, **kwargs): names = set([f.name for f in fields(self)]) for k, v in kwargs.items(): if k in names: setattr(self, k, v) if not hasattr(self, "sub_menu_expand"): self.sub_menu_expand = {} class ViewportMenubar(AbstractViewportMenubarItem): """" Default viewport menubar, at the top of viewport. Args: name (str): Name of viewport menubar. direction (ui.Direction): Layout direction of menu items in this menubar. Default ui.Direction.LEFT_TO_RIGHT. spacing (ui.Length): Spacing between items. Default 10 pixles. background_visible (bool): Show background for menu bar. Default False. """ def __init__(self, name: str="", direction: ui.Direction=ui.Direction.LEFT_TO_RIGHT, spacing: ui.Length = 10, style: Dict = {}, background_visible: bool = False, visible_setting_path: Optional[str] = None, ): self._direction = direction self.__spacing = spacing self._style = VIEWPORT_MENUBAR_STYLE.copy() self._style.update(style) self.__background_visible: bool = background_visible self.__show_separator: bool = False self.__context: Dict[int, MenubarContext] = {} super().__init__(name=name, visible_setting_path=visible_setting_path) @property def visible(self) -> bool: return self.visible_model.as_bool @visible.setter def visible(self, value: bool) -> None: old_value = self.visible_model.as_bool if old_value != value: self.visible_model.set_value(value) ViewportMenuModel()._item_changed(None) @property def background_visible(self) -> bool: return self.__background_visible @background_visible.setter def background_visible(self, visible: bool) -> None: self.__background_visible = visible for context in self.__context.values(): context.background_rectangle.visible = self.__background_visible @property def style(self) -> Dict: return self._style @property def spacing(self) -> ui.Length: return self.__spacing @spacing.setter def spacing(self, value: ui.Length) -> None: self.__spacing == value for context in self.__context.values(): context.frame.rebuild() @property def show_separator(self) -> bool: return self.__show_separator @show_separator.setter def show_separator(self, visible: bool) -> None: self.__show_separator = visible for context in self.__context.values(): context.frame.rebuild() def destroy(self): for context in self.__context.values(): if context.resize_future and not context.resize_future.done(): context.resize_future.cancel() self.__context = {} super().destroy() def build_fn(self, menu_items: List[AbstractViewportMenuItem], factory_args: Dict, content_clipping=True): # Using Frame with horizontal_clipping to prevent expanding of widgets when the menu bar is big extra_kwargs = {} if self._direction == ui.Direction.LEFT_TO_RIGHT: extra_kwargs = {"height": 0} elif self._direction == ui.Direction.TOP_TO_BOTTOM: extra_kwargs = {"width": 0} viewport_api_id = factory_args['viewport_api'].id self.__context[viewport_api_id] = MenubarContext() with ui.ZStack(style=self._style, height=0): self.__context[viewport_api_id].background_rectangle = ui.Rectangle(style_type_name_override="MenuBar.Window", visible=self.__background_visible) self.__context[viewport_api_id].frame = ui.Frame(horizontal_clipping=True, **extra_kwargs) with self.__context[viewport_api_id].frame: self._build_menubar(menu_items, factory_args, content_clipping=content_clipping) self.__menu_items = menu_items self.__available_clip_levels = [MenuDisplayStatus.EXPAND, MenuDisplayStatus.LABEL] self.__clip_level = MenuDisplayStatus.MIN self.__clip_size = {} for level in self.__available_clip_levels: self.__clip_size[level] = {} self.__context[viewport_api_id].frame.set_computed_content_size_changed_fn(partial(self.__resize_menubar, factory_args)) def _build_menubar(self, menu_items: List[AbstractViewportMenuItem], factory_args: Dict, content_clipping=True): viewport_api_id = factory_args['viewport_api'].id # Filter out all hidden children visible_menu_items = [item for item in menu_items if item.visible_model.as_bool] # If all that remains is an empty list or a list of only ViewportMenuSpacer, then no menu if sum(1 for item in visible_menu_items if (not isinstance(item, ViewportMenuSpacer))) == 0: self.__context[viewport_api_id].frame.clear() return with ui.Menu(direction=self._direction, menu_compatibility=False, content_clipping=content_clipping): first = True for item in visible_menu_items: if not first: if self.__show_separator: ui.Separator( delegate=ui.MenuDelegate( on_build_item=lambda _: ui.Line( width=0, alignment=ui.Alignment.H_CENTER, style_type_name_override="Menu.Separator", ) ) ) else: if self._direction == ui.Direction.LEFT_TO_RIGHT: ui.Spacer(width=self.__spacing) else: ui.Spacer(height=self.__spacing) first = False item.build_fn(factory_args) if item.expand_model: self.__context[viewport_api_id].sub_menu_expand[item] = item.expand_model.subscribe_value_changed_fn(lambda _, f=factory_args: self.__on_menu_expand_changed(f)) def invalidate(self): pass def __enter__(self): # Clean all existing child items # For multiple viewport window, menu contrainer may build multiple times # Make sure child items not duplicated # self._clean() push_to_scope(self) def __exit__(self, exc_type, exc_value, traceback): pop_from_scope() def __resize_menubar(self, factory_args: dict) -> None: viewport_api_id = factory_args['viewport_api'].id if self.__context[viewport_api_id].resize_future and not self.__context[viewport_api_id].resize_future.done(): return self.__context[viewport_api_id].resize_future = asyncio.ensure_future(self.__resize_menubar_async(factory_args)) async def __resize_menubar_async(self, factory_args: dict) -> None: viewport_api_id = factory_args['viewport_api'].id menu_items = [item for item in self.__menu_items if item.visible_model.as_bool and not isinstance(item, ViewportMenuSpacer)] # We need to know spacer size to check if items need resize # Here use the default spacer item spacer_items = [item for item in self.__menu_items if isinstance(item, ViewportMenuSpacer) and item.order_model.as_int == 0] if spacer_items: spacer_item = spacer_items[0] else: return resize_again = True while resize_again: spacer_width = spacer_item.get_computed_width(factory_args) resize_again = False if spacer_width == 0: # No more space left, check if something need to contract resize_again = self.__check_contract(menu_items, factory_args) elif spacer_width < self.__context[viewport_api_id].spacer_width or self.__context[viewport_api_id].spacer_width < 0: # Spacer becomes small, check contract # Some menu items such as Camera settings, maybe not expanded but need to check if enough space for expand settings # Otherwise need to hide expand button require_size = 0 for item in menu_items: require_size += item.get_require_size(factory_args, expand=False) if require_size > spacer_width: resize_again = self.__check_contract(menu_items, factory_args) elif spacer_width > self.__context[viewport_api_id].spacer_width: # Spacer becomes bigger, check if we can expand menu items require_size = 0 expand_items: List[AbstractViewportMenuItem] = [] for item in menu_items: require_size += item.get_require_size(factory_args, expand=True) expand_items.append(item) if require_size < spacer_width: for item in expand_items: item.expand(factory_args) resize_again = True self.__context[viewport_api_id].spacer_width = spacer_width if resize_again: # Already resized, wait for menubar updated # Need at least 2 frames for a new Viewport window for i in range(2): await omni.kit.app.get_app().next_update_async() def __check_contract(self, menu_items: List[AbstractViewportMenuItem], factory_args: dict) -> bool: contract_items: Dict[MenuDisplayStatus, List[AbstractViewportMenuItem]] = {} # Figure how to contract # Since there are different display status for different menu items # Contract expand first and lable next max_contract_status = MenuDisplayStatus.MIN for item in menu_items: display_status = item.get_display_status(factory_args) if display_status == MenuDisplayStatus.MIN: # Already in min display status, nothing to contract continue else: if item.can_contract(factory_args): # Record items can contract here but contract later if display_status not in contract_items: contract_items[display_status] = [] contract_items[display_status].append(item) max_contract_status = max(display_status, max_contract_status) contracted = False # Only contract for one status: expand or label if max_contract_status != MenuDisplayStatus.MIN: for item in contract_items[max_contract_status]: item.contract(factory_args) contracted = True return contracted def __on_menu_expand_changed(self, factory_args: Dict): # OM-64798: Menu item expand status changed, need to reset saved spacer width viewport_api_id = factory_args['viewport_api'].id spacer_items = [item for item in self.__menu_items if isinstance(item, ViewportMenuSpacer) and item.order_model.as_int == 0] if spacer_items: spacer_item = spacer_items[0] async def __update_spacer_width(): await omni.kit.app.get_app().next_update_async() self.__context[viewport_api_id].spacer_width = spacer_item.get_computed_width(factory_args) asyncio.ensure_future(__update_spacer_width()) else: return
12,770
Python
42.736301
180
0.61206
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/menu_item/radio_menu_collection.py
from omni import ui from ..model.combobox_model import ComboBoxModel from ..delegate.viewport_menu_delegate import ViewportMenuDelegate from ..utils import menu_is_tearable from .viewport_menu_separator import ViewportMenuSeparator __all__ = ["RadioMenuCollection"] class RadioMenuCollection(ui.MenuItemCollection): """ A Menu with ratio sub menu items. Args: text (str): Menu text model (ComboBoxModel): Model for sub menu items hide_on_click (bool): Whether to hide the menu when an item is clicked can_toggle_off (bool): Whether clicking an already selected item will togle it to off delegate (ui.MenuDelegate): Delegate to show this menu collection """ def __init__( self, text: str, model: ComboBoxModel, identifier: str = None, hide_on_click: bool = False, can_toggle_off: bool = False, delegate: ui.MenuDelegate = None ): self._model = model self._hide_on_click = hide_on_click self.__menu_items = [] self.__in_triggered = False self.__can_toggle_off = can_toggle_off super().__init__(text, delegate=delegate, on_build_fn=self._build_menu_items, tearable=menu_is_tearable(identifier)) def __destroy_menu_items(self, value=None): if self.__menu_items: for menu_item in self.__menu_items: menu_item.destroy() self.__menu_items = value def destroy(self) -> None: model, self._model, self._sub = self._model, None, None if model and hasattr(model, 'destroy'): model.destroy() self.__destroy_menu_items(None) super().destroy() def _build_menu_items(self): self.__destroy_menu_items([]) with self: for index, item in enumerate(self._model.get_item_children(None)): menu_item = self.build_menu_item(item) if not isinstance(menu_item, ViewportMenuSeparator): menu_item.checkable = True menu_item.checked=index == self._model.current_index.as_int menu_item.set_triggered_fn(lambda i=index: self._item_chosen(i)) menu_item.hide_on_click=self._hide_on_click # Only need to save the menu-item if cannot toggle to off if not bool(self.__can_toggle_off): self.__menu_items.append(menu_item) # When current is changed outside, update menu items self._sub = self._model.current_index.subscribe_value_changed_fn(self._on_current_changed) self._sub_model = self._model.subscribe_item_changed_fn(self._on_item_changed) def build_menu_item(self, item: ui.AbstractItem) -> ui.MenuItem: return ui.MenuItem( item.model.as_string, delegate=ViewportMenuDelegate(), ) def _item_chosen(self, index: int): try: self.__in_triggered = True # Set the current index if it has changed current_index = self._model.current_index.as_int if (self._model and self._model.current_index) else None if current_index != index: self._model.current_index.set_value(index) elif (not bool(self.__can_toggle_off)) and self.__menu_items and index < len(self.__menu_items): # Force the check state on in the case that it hasn't import asyncio async def force_checked_state(index: int, checked: bool): self.__menu_items[index].checked = checked asyncio.ensure_future(force_checked_state(index, True)) finally: self.__in_triggered = False def _on_current_changed(self, model: ui.AbstractValueModel): if not self.__in_triggered: self.invalidate() def _on_item_changed(self, model: ui.AbstractValueModel, item: ui.AbstractItem): self.invalidate()
3,965
Python
40.3125
124
0.607818
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/menu_item/viewport_button_item.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ViewportButtonItem"] from ..viewport_menu_model import AbstractViewportMenuItem, ViewportMenuModel import asyncio from typing import Callable, Dict, Optional, List import omni.kit.app import omni.ui as ui from ..style import VIEWPORT_MENUBAR_STYLE class ViewportButtonItem(AbstractViewportMenuItem): """ Build a button in viewport menubar: Left click: toggle Right click: flyout window or menu options Kwargs: build_menu_fn (Callable[[None], List[ui.MenuItem]]): Callback to create flyout menu when right click build_window_fn (Callable[[None], ui.Window]): Callback to create flyout window when right click alignment (ui.Alignment): How flyout window/menu align with button. """ def __init__( self, text: str = "", name: str = "", onclick_fn: Callable = None, build_menu_fn: Callable[[None], List[ui.MenuItem]] = None, build_window_fn: Callable[[None], ui.Window] = None, visible_setting_path: Optional[str] = None, order_setting_path: Optional[str] = None, expand_setting_path: Optional[str] = None, alignment: ui.Alignment = ui.Alignment.RIGHT_BOTTOM, enabled: bool = True, has_triangle: bool = False, triangle_size: float = 6, style: Dict = {}, ): self._text = text self._onclick_fn = onclick_fn self._build_menu_fn = build_menu_fn self._build_window_fn = build_window_fn self._style = style self._alignment = alignment self._enabled = enabled self._selected = False self._checked = False self._has_triangle = has_triangle self._triangle_size = triangle_size self._menu: Optional[ui.MenuItem] = None self._window: Optional[ui.Window] = None self._button: Optional[ui.Button] = None super().__init__( name, visible_setting_path=visible_setting_path, order_setting_path=order_setting_path, expand_setting_path=expand_setting_path, ) # When visible and order changed, trigger UI updates self._visible_sub = self.visible_model.subscribe_value_changed_fn(lambda m: self._invalidate()) self._order_sub = self.order_model.subscribe_value_changed_fn(lambda m: self._invalidate()) def destroy(self): self._visible_sub = None self._order_sub = None self._onclick_fn = None if self._menu: self._menu.hide() self._menu = None if self._window: self._window.visible = False self._window = None super().destroy() @property def visible(self) -> bool: return self.visible_model.as_bool @visible.setter def visible(self, value: bool) -> None: self.visible_model.set_value(value) if self._menu: self._menu.hide() @property def menu_item(self) -> ui.Menu: return self._menu @property def window(self) -> ui.Window: return self._window @property def name(self) -> str: return self._name @name.setter def name(self, value: str) -> None: self._name = value if self._button: self._button.name = value @property def enabled(self) -> bool: return self._enabled @enabled.setter def enabled(self, value: bool) -> None: self._enabled = value if self._button: self._button.enabled = value @property def selected(self) -> bool: return self._selected @selected.setter def selected(self, value: bool) -> None: self._selected = value if self._button: self._button.selected = value @property def checked(self) -> bool: return self._checked @checked.setter def checked(self, value: bool) -> None: self._checked = value if self._button: self._button.checked = value def build_fn(self, factory: Dict): """Reimplement it to have own customized item""" self._container = ui.ZStack(width=0) with self._container: if self._has_triangle: with ui.VStack(): with ui.HStack(): ui.Spacer() with ui.VStack(width=self._triangle_size): ui.Spacer() ui.Triangle( width=self._triangle_size, height=self._triangle_size, alignment=ui.Alignment.RIGHT_TOP, style_type_name_override="MenuBar.Item.Triangle", ) ui.Spacer(width=2) ui.Spacer(height=2) ui.Rectangle(style_type_name_override="MenuBar.Item.Background") self._button = ui.Button( self._text, name=self.name, enabled=self._enabled, selected=self._selected, checked=self._checked, width=0, image_width=20, visible=self.visible_model.as_bool, style=self._style, style_type_name_override="Menu.Button", ) ui.Rectangle(style_type_name_override="Menubar.Hover") self._container.set_mouse_pressed_fn(lambda x, y, b, a: self._on_mouse_clicked_fn(b)) def _build_menu(self): style = VIEWPORT_MENUBAR_STYLE.copy() style.update(self._style) self._menu = ui.Menu("Button_Menu_" + str(hash(self)), menu_compatibility=False, style=style) with self._menu: self._menu_items = self._build_menu_fn() def invalidate(self): if self._menu: self._menu.invalidate() def _on_mouse_clicked_fn(self, button): if button == 1: self.on_right_clicked_fn() elif button == 0: if self._onclick_fn: self._onclick_fn() def on_right_clicked_fn(self): """Show flyout window/menu""" if self._build_menu_fn: self._show_menu() elif self._build_window_fn: self._show_window() def _show_menu(self): if self._menu is None: self._build_menu() (x, y) = (0, 0) if self._alignment == ui.Alignment.RIGHT_BOTTOM: x = self._container.screen_position_x + self._container.computed_content_width y = self._container.screen_position_y + self._container.computed_content_height if self._menu_items: menu_window_width = self._menu_items[0].computed_content_width if menu_window_width <= 0: self._menu.show_at(-500, -100) self._menu.hide() async def __delay_change_menu_window_position(x, y): await omni.kit.app.get_app().next_update_async() x -= self._menu_items[0].computed_content_width self._menu.show_at(x, y) asyncio.ensure_future(__delay_change_menu_window_position(x, y)) return else: x -= self._menu_items[0].computed_content_width elif self._alignment == ui.Alignment.LEFT_BOTTOM: x = self._container.screen_position_x y = self._container.screen_position_y + self._container.computed_content_height self._menu.show_at(x, y) def _show_window(self): if self._window is None: self._window = self._build_window_fn() (x, y) = (0, 0) if self._alignment == ui.Alignment.RIGHT_BOTTOM: x = self._container.screen_position_x + self._container.computed_content_width y = self._container.screen_position_y + self._container.computed_content_height if self._window: window_width = self._window.frame.computed_width if window_width <= 0: self._window.position_x = -500 self._window.position_y = -100 self._window.visible = True async def __delay_change_window_position(x, y): while self._window.frame.computed_width <= 0: await omni.kit.app.get_app().next_update_async() x -= self._window.frame.computed_width self._window.position_x = x self._window.position_y = y self._window.visible = True asyncio.ensure_future(__delay_change_window_position(x, y)) return else: x -= window_width elif self._alignment == ui.Alignment.LEFT_BOTTOM: x = self._container.screen_position_x y = self._container.screen_position_y + self._container.computed_content_height self._window.position_x = x self._window.position_y = y self._window.visible = True def _invalidate(self) -> None: ViewportMenuModel()._item_changed(None)
9,718
Python
35.130111
108
0.557625
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/delegate/spinner_menu_delegate.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["SpinnerMenuDelegate"] from typing import Union, Optional import omni.ui as ui from omni.ui import color as cl, constant as fl from omni.kit.widget.spinner import FloatSpinner SPINNER_STYLE = { "Spinner.Field": {"background_color": 0, "color": cl.viewport_menubar_light}, "Spinner.Field:disabled": {"color": cl.viewport_menubar_medium}, "Spinner.Arrow": {"background_color": cl.viewport_menubar_light}, "Spinner.Arrow:disabled": {"background_color": cl.viewport_menubar_medium}, } class SpinnerMenuDelegate(ui.MenuDelegate): """Example of menu item with the spinner""" def __init__( self, model=None, tooltip=None, width=ui.Fraction(1), height=0, min: Union[float, int, None] = None, max: Union[float, int, None] = None, step: Union[float, int] = 1, enabled: bool = True, text: bool = True, icon_name: Optional[str] = None, icon_width: ui.Length = 30, icon_height: ui.Length = 30, use_in_menubar: bool = False, ): super().__init__() self.__width = width self.__height = height self.__spinner_width = 60 self.__model = model self.__tooltip = tooltip or "" self._min = min self._max = max self._step = step self.__enabled = enabled self.__frame: Optional[ui.Widget] = None self.__text = text self.__icon_name = icon_name self.__icon_width = icon_width self.__icon_height = icon_height self.__use_in_menubar = use_in_menubar def __del__(self): self.destroy() def destroy(self): self.__model = None @property def enabled(self) -> bool: return self.__enabled @enabled.setter def enabled(self, value) -> None: self.__enabled = value if self.__frame: self.__frame.enabled = value self.__frame.enabled = value def build_item(self, item): extra_kwargs = {"style_type_name_override": "Menu.Item"} if not self.__use_in_menubar else {} self.__frame = ui.Frame(width=self.__width, enabled=self.__enabled, **extra_kwargs) with self.__frame: with ui.HStack(height=self.__height): if self.__icon_name: ui.ImageWithProvider(style_type_name_override="Menu.Item.Icon", tooltip=self.__tooltip, name=self.__icon_name, width=self.__icon_width, height=self.__icon_height) if self.__text: ui.Label(item.text, tooltip=self.__tooltip, style_type_name_override="Menu.Item.Label") with ui.VStack(width=self.__spinner_width): ui.Spacer() self.__spinner = FloatSpinner( self.__model, min=self._min, max=self._max, step=self._step, style=SPINNER_STYLE ) ui.Spacer() ui.Spacer(width=5) self.__spinner.enabled = self.__enabled
3,463
Python
34.71134
182
0.595437
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/delegate/slider_menu_delegate.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["SliderMenuDelegate"] from typing import Optional, Union import omni.ui as ui from .abstract_widget_menu_delegate import AbstractWidgetMenuDelegate class SliderMenuDelegate(AbstractWidgetMenuDelegate): """ Example of menu item with the slider kwargs: model (Optional[ui.AbstractValueModel]): Slider data model, default None min (Union[float, int, None]): Min value of slider, default None max (Union[float, int, None]): Max value of slider, default None tooltip (Optional[str]): Tooltip of slider, default None width (int): Width of slider, in pixles, default 270 slider_class (Union[ui.FloatSlider, ui.IntSlider]): Slider class, default ui.FloatSlider show_checkbox_if_min (bool): Show checkbox instead of slider if value == min. default_value_on (Union[float, int, None]): When checkbox is ON, value to display in slider. Default None """ def __init__( self, model: Optional[ui.AbstractValueModel] = None, min: Union[float, int, None] = None, max: Union[float, int, None] = None, tooltip: Optional[str] = None, width: int = 300, slider_class: Union[ui.FloatSlider, ui.IntSlider] = ui.FloatSlider, show_checkbox_if_min: bool = False, default_value_on: Union[float, int, None] = None, enabled: bool = True, reserve_status: bool = False, has_reset: bool = False, step: Union[float, int, None] = None, ): super().__init__(model=model, enabled=enabled, reserve_status=reserve_status, has_reset=has_reset) self.__width = width self.__space = 5 self.__slider_width = 90 self.__min = min self.__max = max self.__tooltip = tooltip or "" self.__slider_class = slider_class self.__show_checkbox_if_min = show_checkbox_if_min self.__default_value_on = default_value_on self.__slider = None self.__step = step def __del__(self): self.destroy() def destroy(self): self._model = None def build_widget(self, item: ui.MenuHelper): ui.Label(item.text, tooltip=self.__tooltip, style_type_name_override="Menu.Item.Label") ui.Spacer(width=self.__space) with ui.ZStack(content_clipping=True, width=0): if self.__show_checkbox_if_min and self.__min is not None: self.__checkbox = ui.CheckBox(width=self.__slider_width, visible=False) self.__checkbox.model.add_value_changed_fn(self.__on_checkbox_changed) self.__slider_container = ui.VStack(width=self.__slider_width) with self.__slider_container: ui.Spacer() kwargs = {"height": 0} use_drag = False min_value, max_value = self.__min, self.__max # If only one of min/max ws provided, warn as the slider might be odd if (min_value is None) != (max_value is None): import carb carb.log_warn("SliderMenuDelegate with only one of min/max provided") if min_value is not None and self.__max is not None: kwargs["min"] = min_value kwargs["max"] = max_value if max_value - min_value > 100: use_drag = True else: use_drag = True if min_value is not None: kwargs["min"] = min_value if max_value is not None: kwargs["max"] = max_value if self.__step is not None: kwargs["step"] = self.__step elif (self.__slider_class == ui.FloatSlider) and (min_value is not None) and (max_value is not None): kwargs["step"] = self.calculate_step(min_value, max_value, None) kwargs["precision"] = 3 if use_drag: if self.__slider_class == ui.FloatSlider: slider_class = ui.FloatDrag if self.__slider_class == ui.IntSlider: slider_class = ui.IntDrag else: slider_class = self.__slider_class self.__slider = slider_class(self._model, **kwargs) if self.__show_checkbox_if_min and self.__min is not None: self.__slider.model.add_value_changed_fn(self.__on_slider_changed) value = self.__slider.model.as_float if value == self.__min: self.__checkbox.visible = True self.__slider.visible = False ui.Spacer() @property def min(self) -> Union[float, int]: return self.__min @min.setter def min(self, value: Union[float, int]) -> None: self.__min = value if self.__slider: self.__slider.min = value @property def max(self) -> Union[float, int]: return self.__max @max.setter def max(self, value: Union[float, int]) -> None: self.__max = value if self.__slider: self.__slider.max = value def calculate_step(self, min: float, max: float, slider: ui.Widget): # TODO: Flag to normalize against slider.computed_width import math exponent = math.floor(math.log10(abs(max - min))) return (10 ** exponent) / 100 def set_range(self, min: float, max: float): self.__min, self.__max = min, max slider = self.__slider if slider: slider.min = self.__min slider.max = self.__max # Auto compute step based on range and width if self.__step is None: slider.step = self.calculate_step(min, max, slider) def __on_checkbox_changed(self, model: ui.AbstractValueModel) -> None: if model.as_bool: self.__checkbox.visible = False self.__slider.visible = True if self.__default_value_on is not None: self.__slider.model.set_value(self.__default_value_on) def __on_slider_changed(self, model: ui.AbstractValueModel) -> None: if self.__min is not None: if model.as_float == self.__min: self.__checkbox.visible = True self.__checkbox.model.set_value(False) self.__slider.visible = False
6,945
Python
38.465909
117
0.565731
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/delegate/icon_menu_delegate.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["IconMenuDelegate"] from typing import Optional, Callable import omni.ui as ui class IconMenuDelegate(ui.MenuDelegate): """ The menu delegate that draws in the menu bar the given icon and optionally the text. """ def __init__( self, name: str, text: bool = False, width: ui.Length = 30, height: ui.Length = 30, has_triangle: bool = True, triangle_size: float = 6, checked: bool = False, enabled: bool = True, triggered_fn: Callable[[None], None] = None, right_clicked_fn: Callable[[None], None] = None, tooltip: Optional[str] = None, build_custom_widgets: Callable[[ui.MenuItem], None] = None ): super().__init__(propagate=False) self._name = name self._text = text self._width = width self._icon_width = width self._height = height self._has_triangle = has_triangle self._triangle_size = triangle_size self._checked = checked self._enabled = enabled self.__label = None self.__tooltip = tooltip or "" self._triggered_fn = triggered_fn self._right_clicked_fn = right_clicked_fn self._container: Optional[ui.Widget] = None self.__label_size = 0 self.__build_custom_widgets = build_custom_widgets def build_item(self, item: ui.MenuItem): icon_type = "Menu.Item.Icon" self._container = ui.ZStack(checked=self._checked, height=self._height) with self._container: if self._has_triangle: with ui.VStack(): with ui.HStack(): ui.Spacer() with ui.VStack(width=self._triangle_size): ui.Spacer() ui.Triangle( width=self._triangle_size, height=self._triangle_size, alignment=ui.Alignment.RIGHT_TOP, style_type_name_override="MenuBar.Item.Triangle", ) ui.Spacer(width=2) ui.Spacer(height=2) ui.Rectangle(style_type_name_override="MenuBar.Item.Background") spacer_width = 4 with ui.HStack(height=self._height, spacing=spacer_width): self.icon = self._build_icon() if self._text: self.__label_container = ui.HStack(spacing=4) with self.__label_container: self.__label = ui.Label(item.text, height=self._height) if self.__build_custom_widgets: self.__build_custom_widgets(item) ui.Spacer(width=4) def __label_size_changed(menu_item): if self.__label_container.computed_width + spacer_width > self.__label_size: self.__label_size = self.__label_container.computed_width + spacer_width self.__label_container.set_computed_content_size_changed_fn(lambda m=item: __label_size_changed(m)) ui.Rectangle(style_type_name_override="Menubar.Hover") if self._triggered_fn or self._right_clicked_fn: self._container.set_mouse_released_fn(lambda x, y, b, a: self._on_mouse_released(b)) @property def text_size(self) -> float: """ Size of text displayed. """ return self.__label_size @property def text_visible(self) -> bool: return self._text @text_visible.setter def text_visible(self, value: bool) -> None: # Here only set status but need menu invilidate outside to refresh self._text = value @property def checked(self) -> bool: return self._container.checked if self._container else self._checked @checked.setter def checked(self, value) -> None: self._checked = value if self._container: self._container.checked = value @property def enabled(self) -> bool: return self._enabled @enabled.setter def enabled(self, value) -> None: self._enabled = value if self._container: self._container.enabled = value @property def text(self): return self.__label.text if self.__label else '' @text.setter def text(self, txt: str): if self.__label: self.__label.text = str(txt) def destroy(self): self.__build_custom_widgets = None def _on_mouse_released(self, button: int) -> None: if button == 0: if self._triggered_fn: self._triggered_fn() elif button == 1: if self._right_clicked_fn: self._right_clicked_fn() def _build_icon(self): return ui.ImageWithProvider( style_type_name_override="Menu.Item.Icon", name=self._name, width=self._icon_width, height=self._height, tooltip=self.__tooltip, )
5,594
Python
33.96875
119
0.556489
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/delegate/viewport_menu_delegate.py
from typing import Union, Optional, Callable, List import omni.ui as ui STATUS_ICON_WIDTH = 20 MENU_ARROW_SIZE = 8 __all__ = ["OptionBoxStyle", "ViewportMenuDelegate"] class ViewportMenuDelegate(ui.MenuDelegate): """The menu delegate that draws in the menu or menuitem the given status. kwargs: icon_name (str): Show icon after menu text. Default "" to do not show. icon_width (int): Menu icon width. Defautl 16 reserve_status (bool): Reserve space for status icon. Default True. force_checked (bool): Force to show checked status. It is strange that when a menu is checked, sub menu items checked flag will be cleared. Use this flag to show correct sub menu item status. """ def __init__( self, icon_name: str = "", icon_width: int = 16, reserve_status: bool = True, force_checked: bool = False, icon_clicked_fn: Callable[[None], None] = None, build_custom_widgets: Callable[[ui.MenuDelegate, Union[ui.MenuItem, ui.Menu]], None] = None ): self._icon_name = icon_name self._icon_width = icon_width self._reserve_status = reserve_status self._force_checked = force_checked self._icon_clicked_fn = icon_clicked_fn self.icon: Optional[ui.Widget] = None self._container: Optional[ui.Widget] = None self._build_custom_widgets = build_custom_widgets super().__init__(propagate=False) def __icon_clicked(self, x, y, *arg, **kwargs): if self._icon_clicked_fn is None or self.icon is None: return left = self.icon.screen_position_x top = self.icon.screen_position_y if (x < left) or (y < top): return right = left + self.icon.computed_width bottom = top + self.icon.computed_height if (x > right) or (y > bottom): return self._icon_clicked_fn(x, y, *arg, **kwargs) def build_item(self, item: Union[ui.MenuItem, ui.Menu]): icon_type = "Menu.Item.Status" if self._force_checked: item.checked = self._force_checked self._container = ui.HStack( style_type_name_override="MenuBar.Item", selected=item.selected, checked=(item.checkable and item.checked) ) with self._container: selected = item.selected or (item.checkable and item.checked) # Status icon before menu text if selected or self._reserve_status: self.icon = ui.ImageWithProvider(style_type_name_override=icon_type, width=STATUS_ICON_WIDTH, mouse_released_fn=self.__icon_clicked) # Text ui.Label(item.text, style_type_name_override="Menu.Item.Text") if self._icon_name or self._build_custom_widgets or isinstance(item, ui.Menu): ui.Spacer() # Icon after menu text if self._icon_name: ui.Spacer(width=10) ui.ImageWithProvider( style_type_name_override="Menu.Item.Icon", name=self._icon_name, width=self._icon_width ) if self._build_custom_widgets: self._build_custom_widgets(self, item) if isinstance(item, ui.Menu): # For menu, show arrow for children ui.Spacer(width=10) with ui.VStack(width=MENU_ARROW_SIZE / 2): ui.Spacer() ui.Triangle( height=MENU_ARROW_SIZE, alignment=ui.Alignment.RIGHT_CENTER, style_type_name_override="MenuBar.Item.Triangle", ) ui.Spacer() ui.Spacer(width=3) def get_selected(self) -> bool: return self._container.selected if self._container else False def set_selected(self, value: bool) -> bool: '''Set the 'selected' state and return whether it changed or not.''' value = bool(value) if self._container and (self.get_selected() != value): self._container.selected = value return True return False def get_checked(self) -> bool: return self._container.checked if self._container else False def set_checked(self, value: bool) -> bool: '''Set the 'checked' state and return whether it changed or not.''' value = bool(value) if self._container and (self.get_checked() != value): self._container.checked = value return True return False def __on_additional_btn_clicked(self, button: ui.Button) -> None: if self._on_additional_btn_clicked_fn: self._on_additional_btn_clicked_fn(button) @property def selected(self) -> bool: return self.get_selected() @selected.setter def selected(self, value: bool) -> None: self.set_selected(value) @property def checked(self) -> bool: return self.get_checked() @checked.setter def checked(self, value: bool) -> None: self.set_checked(value)
5,113
Python
36.057971
148
0.587326
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/delegate/separator_menu_delegate.py
import omni.ui as ui class SeparatorDelegate(ui.MenuDelegate): """Generic menu delegate with separator between menu items""" def __init__(self): super().__init__() def __del__(self): self.destroy() def destroy(self): pass def build_item(self, item): self.__frame = ui.Frame(style_type_name_override="Menu.Item") with self.__frame: ui.Line(width=2, alignment=ui.Alignment.V_CENTER, style_type_name_override="Menu.Item.Separator")
507
Python
24.399999
109
0.619329
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/delegate/category_menu_delegate.py
from typing import Callable from .viewport_menu_delegate import ViewportMenuDelegate from ..model.category_model import CategoryStatus import omni.ui as ui import carb.windowing __all__ = ["CategoryMenuDelegate"] class CategoryMenuDelegate(ViewportMenuDelegate): def __init__(self, status: CategoryStatus, icon_clicked_fn: Callable[[None], None]=None): self._status = status super().__init__(icon_clicked_fn=icon_clicked_fn) def build_item(self, item: ui.MenuItem): # icons required super().build_item(item) if self.icon: self.icon.name = self._status self.icon.set_mouse_hovered_fn(self._on_icon_hovered) @property def status(self) -> CategoryStatus: return self._status @status.setter def status(self, value: CategoryStatus) -> None: self._status = value if self.icon: self.icon.name = self._status def _on_icon_hovered(self, hovered): try: import omni.kit.window.cursor main_curosr = omni.kit.window.cursor.get_main_window_cursor() if main_curosr: if hovered: main_curosr.override_cursor_shape(carb.windowing.CursorStandardShape.HAND) else: main_curosr.clear_overridden_cursor_shape() except ImportError: carb.log_info("omni.kit.window.cursor not available, omni.kit.viewport.menubar cursor won't be changed") pass
1,500
Python
33.906976
116
0.632
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/delegate/color_menu_delegate.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ColorMenuDelegate"] import omni.ui as ui from .abstract_widget_menu_delegate import AbstractWidgetMenuDelegate class ColorMenuDelegate(AbstractWidgetMenuDelegate): """Example of menu item with color widget""" def __init__(self, model=None, tooltip=None, has_reset: bool = False): super().__init__(model=model, width=210 + 90, has_reset=has_reset) self.__color_widget_width = 20 self.__model = model self.__tooltip = tooltip or "" def __del__(self): self.destroy() def destroy(self): self.__model = None def build_widget(self, item: ui.MenuHelper): ui.Label(item.text, tooltip=self.__tooltip, style_type_name_override="Menu.Item.Label") ui.ColorWidget(self.__model, width=self.__color_widget_width, height=0) ui.Spacer(width=70)
1,271
Python
37.545453
95
0.70417
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/delegate/checkbox_menu_delegate.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["CheckboxMenuDelegate"] from typing import Optional import omni.ui as ui from .abstract_widget_menu_delegate import AbstractWidgetMenuDelegate class CheckboxMenuDelegate(AbstractWidgetMenuDelegate): """Example of menu item with the slider""" def __init__( self, model=None, tooltip=None, width: int = 300, height=0, enabled: bool = True, use_in_menubar: bool = False, has_reset: bool = False, ): super().__init__(model, width=width, height=height, enabled=enabled, has_reset=has_reset, use_in_menubar=use_in_menubar) self.__checkbox_width = 90 if width > 90 else 0 self.__model = model self.__tooltip = tooltip or "" def __del__(self): self.destroy() def destroy(self): self.__model = None def build_widget(self, item: ui.MenuHelper): ui.Label(item.text, tooltip=self.__tooltip, style_type_name_override="Menu.Item.Label") with ui.VStack(width=self.__checkbox_width): ui.Spacer() ui.CheckBox(self.__model, height=0) ui.Spacer()
1,568
Python
32.382978
128
0.663265
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/delegate/abstract_widget_menu_delegate.py
import abc import omni.ui as ui from typing import Optional from ..model.reset_button import ResetButton MENU_ARROW_SIZE = 8 class AbstractWidgetMenuDelegate(ui.MenuDelegate): def __init__( self, model = None, width: ui.Length = ui.Fraction(1), height: ui.Length = ui.Fraction(1), enabled: bool = True, has_reset: bool = False, reserve_status: bool = False, use_in_menubar: bool = False, content_clipping: bool = True, visible: bool = True, ): super().__init__() self._model = model self.__width = width self.__height = height self.__enabled = enabled self.__has_reset = has_reset self.__reserve_status = reserve_status self.__use_in_menubar = use_in_menubar self.__content_clipping = content_clipping self.__visible = visible self.__frame: Optional[ui.Widget] = None def destroy(self): pass def build_item(self, item): extra_kwargs = {"style_type_name_override": "Menu.Item"} if not self.__use_in_menubar else {} self.__frame = ui.Frame(width=self.__width, enabled=self.__enabled, visible=self.__visible, **extra_kwargs) with self.__frame: with ui.HStack(height=self.__height, content_clipping=self.__content_clipping): if self.__reserve_status: ui.Spacer(width=16) self.build_widget(item) if isinstance(item, ui.Menu): # For menu, show arrow for children ui.Spacer(width=10) with ui.VStack(width=MENU_ARROW_SIZE / 2): ui.Spacer() ui.Triangle( height=MENU_ARROW_SIZE, alignment=ui.Alignment.RIGHT_CENTER, style_type_name_override="MenuBar.Item.Triangle", ) ui.Spacer() ui.Spacer(width=3) if self.__has_reset: ui.Spacer(width=4) with ui.VStack(width=0): ui.Spacer(height=2) self._reset_button = ResetButton([self._model]) self._model.set_reset_button(self._reset_button) ui.Spacer() @abc.abstractmethod def build_widget(self, item: ui.MenuHelper): pass @property def visible(self) -> bool: return self.__frame.visible if self.__frame else self.__visible @visible.setter def visible(self, value: bool) -> None: self.__visible = value if self.__frame: self.__frame.visible = value @property def enabled(self) -> bool: return self.__enabled @enabled.setter def enabled(self, value) -> None: self.__enabled = value if self.__frame: self.__frame.enabled = value
3,006
Python
32.043956
115
0.524285
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/delegate/label_menu_delegate.py
import omni.ui as ui class LabelMenuDelegate(ui.MenuDelegate): """ The menu delegate that show menu item text as a label. kwargs: enable (bool): Label enabled or not. Default True. width (ui.Length): Label width. Default ui.Fraction(1). height (ui.Length): Label height. Default 26 pixels. alignment (ui.Alignment): Label alignment. Default ui.Alignment.CENTER. """ def __init__( self, enabled: bool = True, width: ui.Length = ui.Fraction(1), height: ui.Length = 26, alignment: ui.Alignment = ui.Alignment.LEFT ): super().__init__(propagate=False) self.__enabled = enabled self.__height = height self.__width = width self.__alignment = alignment def build_item(self, item: ui.MenuItem): self.__frame = ui.Frame(width=self.__width, height=self.__height, style_type_name_override="Menu.Item", enabled=self.__enabled) with self.__frame: ui.Label(item.text, style_type_name_override="Menu.Item.Label", alignment=self.__alignment)
1,105
Python
35.866665
135
0.61448
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/delegate/combobox_menu_delegate.py
from typing import Optional from attr import has from omni import ui from omni.ui import constant as fl from ..model.combobox_model import ComboBoxModel from .abstract_widget_menu_delegate import AbstractWidgetMenuDelegate __all__ = ["ComboBoxMenuDelegate"] class ComboBoxMenuDelegate(AbstractWidgetMenuDelegate): """Generic menu delegate with combo box""" def __init__( self, model: Optional[ComboBoxModel] = None, height=0, width=300, enabled: bool = True, text: bool = True, icon_name: Optional[str] = None, icon_width: ui.Length = 30, icon_height: ui.Length = 30, tooltip: Optional[str] = None, use_in_menubar: bool = False, has_reset: bool = False, ): super().__init__( model=model, height=height, width=width, enabled=enabled, has_reset=has_reset, use_in_menubar=use_in_menubar ) self.__combo_width = 90 self.__text = text self.__icon_name = icon_name self.__icon_width = icon_width self.__icon_height = icon_height self.__tooltip = tooltip def __del__(self): if self._model: self._model.destroy() self.destroy() def destroy(self): # TODO: We don't have to destroy the model here. We should do it in the # object created the model. But since the model is not stored anywhere, # it's destroyed here. if self._model: self._model.destroy() self._model = None super().destroy() def build_widget(self, item: ui.MenuHelper): if self.__icon_name: ui.ImageWithProvider( style_type_name_override="Menu.Item.Icon", tooltip=self.__tooltip, name=self.__icon_name, width=self.__icon_width, height=self.__icon_height, ) if self.__text: ui.Label(item.text, style_type_name_override="Menu.Item.Label") with ui.VStack(width=self.__combo_width): ui.Spacer() ui.ComboBox(self._model, height=0) ui.Spacer()
2,166
Python
30.405797
120
0.575716
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/tests/test_button_item.py
from pathlib import Path import omni.ui as ui from omni.ui.tests.test_base import OmniUiTest from omni.kit.viewport.utility import get_active_viewport_and_window from omni.kit.ui_test.query import MenuRef, WidgetRef, WindowStub import omni.kit.app from ..viewport_menu_model import ViewportMenuModel from .style import UI_STYLE from .example_button import ButtonExample CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") TEST_WIDTH, TEST_HEIGHT = 600, 400 class TestButtonItem(OmniUiTest): async def setUp(self): self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT, block_devices=False) _, viewport_window = get_active_viewport_and_window() await self.docked_test_window(viewport_window, width=TEST_WIDTH, height=TEST_HEIGHT, block_devices=False) self._btn_menu_1 = ButtonExample(id=1, name="General", text="General") self._btn_menu_2 = ButtonExample(id=2, name="has_triangle", text="has_triangle", has_triangle=True) self._btn_menu_3 = ButtonExample(id=3, name="invisible", text="invisible") self._btn_menu_4 = ButtonExample(id=4, name="disabled", text="disabled") self._btn_menu_5 = ButtonExample(id=5, name="selected", text="selected") def _build_window(): window = ui.Window("Button Menu Window", width=200, height=200) with window.frame: ui.Label("This is a test") return window self._btn_menu_6 = ButtonExample(id=8, name="window left", text="window left", build_window_fn=_build_window, alignment=ui.Alignment.LEFT_BOTTOM) self._btn_menu_7 = ButtonExample(id=6, name="window", text="window", build_window_fn=_build_window) self._btn_menu_8 = ButtonExample(id=7, name="left alignment", text="left alignment", alignment=ui.Alignment.LEFT_BOTTOM) for _ in range(4): await omni.kit.app.get_app().next_update_async() # After running each test async def tearDown(self): self._btn_menu_3.visible = True self._btn_menu_1.destroy() self._btn_menu_1 = None self._btn_menu_2.destroy() self._btn_menu_2 = None self._btn_menu_3.destroy() self._btn_menu_3 = None self._btn_menu_4.destroy() self._btn_menu_4 = None self._btn_menu_5.destroy() self._btn_menu_5 = None self._btn_menu_6.destroy() self._btn_menu_6 = None self._btn_menu_7.destroy() self._btn_menu_7 = None self._btn_menu_8.destroy() self._btn_menu_8 = None await super().tearDown() async def test_item(self): self.assertEqual(self._btn_menu_1.name, "General") self.assertFalse(self._btn_menu_2.checked) self._btn_menu_2.checked = True self.assertTrue(self._btn_menu_3.visible) self._btn_menu_3.visible = False self.assertTrue(self._btn_menu_4.enabled) self._btn_menu_4.enabled = False self.assertFalse(self._btn_menu_5.selected) self._btn_menu_5.selected = True for _ in range(4): await omni.kit.app.get_app().next_update_async() widget_ref = WidgetRef(self._btn_menu_8._button, "", window=WindowStub()) self.assertFalse(self._btn_menu_8._clicked) await widget_ref.click() self.assertTrue(self._btn_menu_8._clicked) await widget_ref.click(right_click=True) self.assertIsNotNone(self._btn_menu_8.menu_item) await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="menubar_button_item_left_alignment.png" ) widget_ref = WidgetRef(self._btn_menu_7._button, "", window=WindowStub()) await widget_ref.click(right_click=True) self.assertIsNotNone(self._btn_menu_7.window) await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="menubar_button_item_window.png" ) widget_ref = WidgetRef(self._btn_menu_6._button, "", window=WindowStub()) await widget_ref.click(right_click=True) await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="menubar_button_item_window_left_alignment.png" )
4,424
Python
39.972222
153
0.643761
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/tests/abstract_test_container.py
__all__ = ["AbstractTestContainer"] import copy from typing import Dict import carb from omni.kit.viewport.menubar.core import ViewportMenuContainer, IconMenuDelegate import omni.ui as ui from ..style import VIEWPORT_MENUBAR_STYLE from .style import UI_STYLE class AbstractTestContainer(ViewportMenuContainer): def __init__(self): self._settings = carb.settings.get_settings() self._settings.set("/exts/omni.kit.viewport.menubar.delegate/visible", True) self._settings.set("/exts/omni.kit.viewport.menubar.delegate/order", -100) self._triggered = 0 self._right_clicked = 0 TEST_UI_STYLE = copy.copy(VIEWPORT_MENUBAR_STYLE) TEST_UI_STYLE.update(UI_STYLE) super().__init__( name="Icon", delegate=IconMenuDelegate("Sample", triggered_fn=self._on_trigger, right_clicked_fn=self._on_right_click), visible_setting_path="/exts/omni.kit.viewport.menubar.delegate/visible", order_setting_path="/exts/omni.kit.viewport.menubar.delegate/order", style=TEST_UI_STYLE ) self._settings = carb.settings.get_settings() def destroy(self): self._delegate.destroy() super().destroy() def _on_trigger(self) -> None: self._triggered += 1 def _on_right_click(self) -> None: self._right_clicked += 1 def build_fn(self, factory: Dict): self._root_menu = ui.Menu( self.name, delegate=self._delegate, on_build_fn=self._build_menu_items, style=self._style ) def _build_menu_items(self): pass
1,610
Python
30.588235
118
0.643478
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/tests/test_viewport_menu_model.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. ## __all__ = ['TestViewportMenuModel'] from omni.kit.test import AsyncTestCase from omni.kit.viewport.menubar.core import ViewportMenuSpacer, ViewportMenubar from ..viewport_menu_model import ViewportMenuModel from .left_example_menu_container import LeftExampleMenuContainer from .right_example_menu_container import RightExampleMenuContainer from .example_button import ButtonExample class ViewportBottomBar(ViewportMenubar): def __init__(self): super().__init__("BOTTOM_BAR") def build_fn(self, menu_items, factory): pass class TestViewportMenuModel(AsyncTestCase): async def setUp(self): pass async def tearDown(self): pass def get_setting_path(self, setting): return f'/app/test/omni.kit.viewport.menubar.core/test_root/{setting}' async def test_model(self): model = ViewportMenuModel() self.assertEqual(model.get_item_value_model_count(None), 1) self._bottom_bar = ViewportBottomBar() self._left_menu = LeftExampleMenuContainer() self._right_menu = RightExampleMenuContainer() self._button_menu = ButtonExample() menubar_items = model.get_item_children(None) # One default menubar + bottom bar self.assertEqual(len(menubar_items), 2) self.assertEqual(menubar_items[1].name, self._bottom_bar.name) default_bar_item = menubar_items[0] bottom_bar_item = menubar_items[1] items = model.get_item_children(menubar_items[0]) # Actually there are 4 items (left+button+spacer+right) in default bat self.assertEqual(len(items), 4) self.assertEqual(items[0].name, self._left_menu.name) self.assertEqual(items[1].name, self._button_menu.name) self.assertTrue(isinstance(items[2], ViewportMenuSpacer)) self.assertEqual(items[3].name, self._right_menu.name) self.assertEqual(model.get_drag_mime_data(bottom_bar_item), self._bottom_bar.name) drop_accepted = model.drop_accepted(bottom_bar_item, default_bar_item) self.assertTrue(drop_accepted) drop_accepted = model.drop_accepted(None, default_bar_item) self.assertFalse(drop_accepted) # Drop default to behind bottom bar model.drop(bottom_bar_item, default_bar_item) menubar_items = model.get_item_children(None) self.assertEqual(menubar_items[0], bottom_bar_item) self.assertEqual(menubar_items[1], default_bar_item) # Drop default to in front of bottom bar model.drop(bottom_bar_item, default_bar_item) menubar_items = model.get_item_children(None) self.assertEqual(menubar_items[0], default_bar_item) self.assertEqual(menubar_items[1], bottom_bar_item)
3,198
Python
36.197674
90
0.698874
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/tests/example_button.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["ButtonExample"] from omni.kit.viewport.menubar.core import ( ViewportMenuDelegate, ViewportButtonItem, ) from .style import UI_STYLE import copy from typing import Dict, List, Optional from functools import partial import carb import carb.settings import omni.ui as ui import omni.kit.app import omni.usd from ..style import VIEWPORT_MENUBAR_STYLE from .style import UI_STYLE class ButtonExample(ViewportButtonItem): """The button for screenshot""" def __init__(self, id: int = 0, **kwargs): self._settings = carb.settings.get_settings() setting_root = f"/exts/omni.kit.viewport.menubar.example/button/{id}" setting_visible = f"{setting_root}/visible" setting_order = f"{setting_root}/order" self._settings.set(setting_visible, True) self._settings.set(setting_order, -90) self._clicked = False TEST_UI_STYLE = copy.copy(VIEWPORT_MENUBAR_STYLE) TEST_UI_STYLE.update(UI_STYLE) super().__init__( text=kwargs.pop("text", None) or f"Button With Flyout Menu", name=kwargs.pop("name", None) or f"Sample", visible_setting_path=setting_visible, order_setting_path=setting_order, onclick_fn=self._on_click, build_menu_fn=self._build_menu_items if not kwargs.get("build_window_fn", None) else None, style=TEST_UI_STYLE, **kwargs, ) def destroy(self): super().destroy() def _build_menu_items(self) -> List[ui.MenuItem]: return [ ui.MenuItem( "Button Menu Item 0", delegate=ViewportMenuDelegate(), ), ui.MenuItem( "Button Menu Item 1", delegate=ViewportMenuDelegate(), ), ] def _on_click(self): self._clicked = True
2,332
Python
29.697368
103
0.63765
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/tests/style.py
from pathlib import Path CURRENT_PATH = Path(__file__).parent ICON_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") UI_STYLE = { "Menu.Item.Icon::Sample": {"image_url": f"{ICON_PATH}/preferences_dark.svg"}, "Menu.Button.Image::Sample": {"image_url": f"{ICON_PATH}/preferences_dark.svg"}, }
348
Python
33.899997
101
0.695402
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/tests/test_radio_collection.py
from pathlib import Path from omni.kit.viewport.menubar.core import RadioMenuCollection, ComboBoxModel import omni.ui as ui from omni.ui.tests.test_base import OmniUiTest from omni.kit.viewport.utility import get_active_viewport_and_window from omni.kit.ui_test.query import MenuRef import omni.kit.app from .abstract_test_container import AbstractTestContainer CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") TEST_WIDTH, TEST_HEIGHT = 600, 400 class RadioContainer(AbstractTestContainer): def _build_menu_items(self): self._radio_menu = RadioMenuCollection( "Radio Collection", ComboBoxModel(["First", "Second", "Third"], current_value="Second"), ) def destroy(self): self._radio_menu.destroy() super().destroy() class TestRadioContainer(OmniUiTest): async def setUp(self): self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT, block_devices=False) _, viewport_window = get_active_viewport_and_window() await self.docked_test_window(viewport_window, width=TEST_WIDTH, height=TEST_HEIGHT, block_devices=False) self._menu = RadioContainer() await omni.kit.app.get_app().next_update_async() # After running each test async def tearDown(self): self._menu.destroy() self._menu = None await super().tearDown() async def test_delegate(self): menu_ref = MenuRef(self._menu._root_menu, "") await menu_ref.click() menu_ref = MenuRef(self._menu._radio_menu, "") await menu_ref.click() for _ in range(4): await omni.kit.app.get_app().next_update_async() await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="menubar_radio_collection.png" ) self.assertEqual(self._menu._radio_menu._model.current_index.as_int, 1) first_ref = menu_ref.find_menu("First") await first_ref.click() self.assertEqual(self._menu._radio_menu._model.current_index.as_int, 0) await self.finalize_test_no_image()
2,299
Python
31.857142
113
0.664202
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/tests/left_example_menu_container.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["LeftExampleMenuContainer"] from omni.kit.viewport.menubar.core import ( IconMenuDelegate, SliderMenuDelegate, CheckboxMenuDelegate, ViewportMenuContainer, ViewportMenuItem, ViewportMenuSeparator, FloatArraySettingColorMenuItem, ComboBoxMenuDelegate, SpinnerMenuDelegate, ComboBoxModel, CategoryMenuDelegate, CategoryStatus, ) from .style import UI_STYLE import carb import carb.settings import omni.ui as ui from typing import Dict class LeftExampleMenuContainer(ViewportMenuContainer): """The menu aligned to left""" def __init__(self): self._settings = carb.settings.get_settings() self._settings.set("/exts/omni.kit.viewport.menubar.example/left/visible", True) self._settings.set("/exts/omni.kit.viewport.menubar.example/left/order", -100) super().__init__( name="Left Samples Menu", delegate=IconMenuDelegate("Sample"), visible_setting_path="/exts/omni.kit.viewport.menubar.example/left/visible", order_setting_path="/exts/omni.kit.viewport.menubar.example/left/order", style=UI_STYLE ) self._settings = carb.settings.get_settings() def build_fn(self, factory: Dict): ui.Menu( self.name, delegate=self._delegate, on_build_fn=self._build_menu_items, style=self._style ) def _build_menu_items(self): ui.MenuItem("Text only with clickable", hide_on_click=False, onclick_fn=lambda: print("Text Menu clicked")) ui.MenuItem( "Icon", delegate=IconMenuDelegate("Sample", text=True, has_triangle=False), hide_on_click=False, onclick_fn=lambda: print("Icon Menu clicked") ) ui.Separator() ui.MenuItem( "Float Slider", hide_on_click=False, delegate=SliderMenuDelegate( model=ui.SimpleFloatModel(0.5), min=0.0, max=1.0, tooltip="Float slider Sample", ), ) ui.MenuItem( "Int Slider", hide_on_click=False, delegate=SliderMenuDelegate( model=ui.SimpleIntModel(5), min=1, max=15, slider_class=ui.IntSlider, tooltip="Int slider Sample", ), ) ui.Separator() ui.MenuItem( "CheckBox", hide_on_click=False, delegate=CheckboxMenuDelegate( model=ui.SimpleBoolModel(True), tooltip="CheckBox Sample", ), ) ui.Separator() ui.MenuItem( "ComboBox", delegate=ComboBoxMenuDelegate( model=ComboBoxModel(["This", "is", "a", "test", "combobox"], values=[0, 1, 2, 3, 4]) ), hide_on_click=False, ) ui.Separator() ui.MenuItem( "Spinner", delegate=SpinnerMenuDelegate( model=ui.SimpleIntModel(80), min=50, max=100, ), hide_on_click=False, ) ui.Separator() FloatArraySettingColorMenuItem( "/exts/omni.kit.viewport.menubar.example/left/color", [0.1, 0.2, 0.3], name="Selection Color", start_index=0 ) ui.Separator() ui.MenuItem( "Category All", delegate=CategoryMenuDelegate(CategoryStatus.ALL) ) ui.MenuItem( "Category Mixed", delegate=CategoryMenuDelegate(CategoryStatus.MIXED) ) ui.MenuItem( "Category Empty", delegate=CategoryMenuDelegate(CategoryStatus.EMPTY) )
4,218
Python
28.921986
115
0.583926
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/tests/__init__.py
from .test_abstract_delegate import * from .test_button_item import * from .test_icon_delegate import * from .test_models import * from .test_more_menubars import * from .test_radio_collection import * from .test_slider_delegate import * from .test_preference import * from .test_ui import * from .test_viewport_menu_model import *
334
Python
24.769229
39
0.760479
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/tests/test_ui.py
import omni.kit.test from re import I from omni.ui.tests.test_base import OmniUiTest from omni.kit.viewport.utility import get_active_viewport_and_window from .left_example_menu_container import LeftExampleMenuContainer from .right_example_menu_container import RightExampleMenuContainer from .example_button import ButtonExample import omni.kit.ui_test as ui_test from omni.kit.ui_test import Vec2 import omni.usd import omni.kit.app from pathlib import Path import carb.input import asyncio CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") TEST_WIDTH, TEST_HEIGHT = 600, 400 class TestExampleMenuWindow(OmniUiTest): async def setUp(self): self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT) _, viewport_window = get_active_viewport_and_window() await self.docked_test_window(viewport_window, width=TEST_WIDTH, height=TEST_HEIGHT, block_devices=False) self._left_menu = LeftExampleMenuContainer() self._right_menu = RightExampleMenuContainer() self._button_menu = ButtonExample() await omni.kit.app.get_app().next_update_async() # After running each test async def tearDown(self): self._left_menu.destroy() self._left_menu = None self._right_menu.destroy() self._right_menu = None self._button_menu.destroy() self._button_menu = None await super().tearDown() async def test_left(self): await self._show_popup_menu() await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="menubar_example_left.png" ) async def test_right(self): await self._show_popup_menu(pos=Vec2(540, 20)) await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="menubar_example_right.png" ) async def test_button(self): await self._show_popup_menu(pos=Vec2(60, 20), right_click=True) await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="menubar_example_button.png" ) async def _show_popup_menu(self, pos=Vec2(20, 20), right_click=False): # Enable mouse input app_window = omni.appwindow.get_default_app_window() for device in [carb.input.DeviceType.MOUSE]: app_window.set_input_blocking_state(device, None) await ui_test.emulate_mouse_move(pos) await ui_test.emulate_mouse_click(right_click=right_click) await omni.kit.app.get_app().next_update_async()
2,722
Python
34.828947
113
0.683688
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/tests/test_more_menubars.py
import omni.kit.test from re import I from omni.ui.tests.test_base import OmniUiTest from omni.kit.viewport.utility import get_active_viewport_and_window from omni.kit.viewport.menubar.core import ViewportMenubar, ViewportMenuSpacer, get_instance as get_menubar_instance from .left_example_menu_container import LeftExampleMenuContainer from .right_example_menu_container import RightExampleMenuContainer from .example_button import ButtonExample import omni.kit.ui_test as ui_test from omni.kit.ui_test import Vec2 import omni.usd import omni.kit.app from pathlib import Path import carb.input import omni.ui as ui import asyncio CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") TEST_WIDTH, TEST_HEIGHT = 600, 400 class ViewportBottomBar(ViewportMenubar): def __init__(self): super().__init__("BOTTOM_BAR") def build_fn(self, menu_items, factory): with ui.VStack(): ui.Spacer() super().build_fn(menu_items, factory) class TestMoreMenubars(OmniUiTest): async def setUp(self): self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() _, viewport_window = get_active_viewport_and_window() await self.docked_test_window(viewport_window, width=TEST_WIDTH, height=TEST_HEIGHT) self._bottom_bar = None self._left_bar = None # After running each test async def tearDown(self): self._left_menu.destroy() self._left_menu = None self._right_menu.destroy() self._right_menu = None self._button_menu.destroy() self._button_menu = None if self._bottom_bar is not None: self._bottom_bar.destroy() self._bottom_bar = None if self._left_bar is not None: self._left_bar.destroy() self._left_bar = None await super().tearDown() async def test_bottom_bar(self): self._bottom_bar = ViewportBottomBar() with self._bottom_bar: self._left_menu = LeftExampleMenuContainer() self._right_menu = RightExampleMenuContainer() self._button_menu = ButtonExample() bottom_bar = get_menubar_instance().get_menubar("BOTTOM_BAR") with bottom_bar: ViewportMenuSpacer() await omni.kit.app.get_app().next_update_async() await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="viewport_bottombar.png" ) async def test_left_bar(self): self._left_bar = ViewportMenubar(name="LEFT_BAR", direction=ui.Direction.TOP_TO_BOTTOM) with self._left_bar: self._left_menu = LeftExampleMenuContainer() self._right_menu = RightExampleMenuContainer() self._button_menu = ButtonExample() await omni.kit.app.get_app().next_update_async() await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="viewport_leftbar.png", threshold=.015 )
3,100
Python
31.989361
116
0.659677
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/tests/test_models.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. ## __all__ = ['TestModels'] import omni.kit.test from omni.kit.test import AsyncTestCase import omni.usd from pxr import Sdf, UsdGeom import omni.kit.undo import omni.ui as ui import carb from ..model.setting_model import SettingModel from ..model.usd_attribute_model import USDAttributeModel, USDBoolAttributeModel, USDIntAttributeModel, USDFloatAttributeModel, USDStringAttributeModel from ..model.usd_metadata_model import USDMetadataModel from ..model.reset_button import ResetHelper, ResetButton from ..model.combobox_model import ComboBoxModel, SettingComboBoxModel from ..model.list_model import ColorModel, SimpleListModel from ..model.category_model import SimpleCategoryModel, CategoryStateItem, CategoryCustomItem, CategoryStatus class TestModels(AsyncTestCase): async def setUp(self): self.usd_context_name = '' self.usd_context = omni.usd.get_context(self.usd_context_name) await self.usd_context.new_stage_async() self.stage = self.usd_context.get_stage() self.stage.SetDefaultPrim(UsdGeom.Xform.Define(self.stage, '/World').GetPrim()) async def tearDown(self): self.usd_context = None self.stage = None def get_setting_path(self, setting): return f'/app/test/omni.kit.viewport.menubar.core/test_root/{setting}' async def test_setting_model_bool(self): setting = self.get_setting_path('bool_value') settings = carb.settings.get_settings() model = SettingModel(setting) self.assertEqual(model.path, setting) # Should start as None and False self.assertEqual(model.get_value_as_bool(), bool(settings.get(setting))) # Test model -> carb.setting model.set_value(True) self.assertEqual(model.get_value_as_bool(), settings.get(setting)) model.set_value(False) self.assertEqual(model.get_value_as_bool(), settings.get(setting)) # Test carb.setting -> model settings.set(setting, True) self.assertEqual(model.get_value_as_bool(), settings.get(setting)) settings.set(setting, False) self.assertEqual(model.get_value_as_bool(), settings.get(setting)) model.begin_edit() self.assertTrue(model._editing) model.end_edit() self.assertFalse(model._editing) model.destroy() async def test_setting_model_int(self): setting = self.get_setting_path('int_value') settings = carb.settings.get_settings() model = SettingModel(setting) # Test model -> carb.setting model.set_value(1) self.assertEqual(model.get_value_as_int(), settings.get(setting)) model.set_value(2) self.assertEqual(model.get_value_as_int(), settings.get(setting)) # Test carb.setting -> model settings.set(setting, 3) self.assertEqual(model.get_value_as_int(), settings.get(setting)) settings.set(setting, 4) self.assertEqual(model.get_value_as_int(), settings.get(setting)) model.destroy() async def test_setting_model_float(self): setting = self.get_setting_path('float_value') settings = carb.settings.get_settings() model = SettingModel(setting) # Test model -> carb.setting model.set_value(123.0) self.assertEqual(model.get_value_as_float(), settings.get(setting)) model.set_value(456.0) self.assertEqual(model.get_value_as_float(), settings.get(setting)) # Test carb.setting -> model settings.set(setting, 789.0) self.assertEqual(model.get_value_as_float(), settings.get(setting)) settings.set(setting, 101112.0) self.assertEqual(model.get_value_as_float(), settings.get(setting)) model.destroy() async def test_setting_model_string(self): setting = self.get_setting_path('string_value') settings = carb.settings.get_settings() model = SettingModel(setting) # Test model -> carb.setting model.set_value('A') self.assertEqual(model.get_value_as_string(), settings.get(setting)) model.set_value('B') self.assertEqual(model.get_value_as_string(), settings.get(setting)) # Test carb.setting -> model settings.set(setting, 'C') self.assertEqual(model.get_value_as_string(), settings.get(setting)) settings.set(setting, 'D') self.assertEqual(model.get_value_as_string(), settings.get(setting)) model.destroy() async def test_implicit_bool_attribute_model(self): prim = self.stage.GetPrimAtPath('/World') model = USDAttributeModel(self.stage, prim.GetPath(), 'implicicit_bool') model.set_value(True) prop = prim.GetProperty('implicicit_bool') self.assertEqual(prop.Get(), True) model.set_value(False) self.assertEqual(prop.Get(), False) self.assertEqual(prop.Get(), model.get_value_as_bool()) prop.Set(True) self.assertEqual(model.get_value_as_bool(), True) self.assertEqual(prop.Get(), model.get_value_as_bool()) prop.Set(False) self.assertEqual(model.get_value_as_bool(), False) self.assertEqual(prop.Get(), model.get_value_as_bool()) async def test_implicit_int_attribute_model(self): prim = self.stage.GetPrimAtPath('/World') model = USDAttributeModel(self.stage, prim.GetPath(), 'implicicit_int') model.set_value(1) prop = prim.GetProperty('implicicit_int') self.assertEqual(prop.Get(), 1) model.set_value(2) self.assertEqual(prop.Get(), 2) self.assertEqual(prop.Get(), model.get_value_as_int()) prop.Set(3) self.assertEqual(model.get_value_as_int(), 3) self.assertEqual(prop.Get(), model.get_value_as_int()) prop.Set(4) self.assertEqual(model.get_value_as_int(), 4) self.assertEqual(prop.Get(), model.get_value_as_int()) async def test_implicit_float_attribute_model(self): prim = self.stage.GetPrimAtPath('/World') model = USDAttributeModel(self.stage, prim.GetPath(), 'implicicit_float') model.set_value(123.4) prop = prim.GetProperty('implicicit_float') self.assertAlmostEqual(prop.Get(), 123.4, 2) model.set_value(234.5) self.assertAlmostEqual(prop.Get(), 234.5, 1) self.assertAlmostEqual(prop.Get(), model.get_value_as_float(), 2) prop.Set(345.6) self.assertAlmostEqual(model.get_value_as_float(), 345.6, 2) self.assertAlmostEqual(prop.Get(), model.get_value_as_float(), 2) prop.Set(456.7) self.assertAlmostEqual(model.get_value_as_float(), 456.7, 2) self.assertAlmostEqual(prop.Get(), model.get_value_as_float(), 2) async def test_implicit_string_attribute_model(self): prim = self.stage.GetPrimAtPath('/World') model = USDAttributeModel(self.stage, prim.GetPath(), 'implicicit_string') model.set_value('A') prop = prim.GetProperty('implicicit_string') self.assertEqual(prop.Get(), 'A') model.set_value('B') self.assertEqual(prop.Get(), 'B') self.assertEqual(prop.Get(), model.get_value_as_string()) prop.Set('C') self.assertEqual(model.get_value_as_string(), 'C') self.assertEqual(prop.Get(), model.get_value_as_string()) prop.Set('D') self.assertEqual(model.get_value_as_string(), 'D') self.assertEqual(prop.Get(), model.get_value_as_string()) async def test_explicit_bool_attribute_model(self): prim = self.stage.GetPrimAtPath('/World') model = USDBoolAttributeModel(self.stage, prim.GetPath(), 'explicit_bool') model.set_value(True) prop = prim.GetProperty('explicit_bool') self.assertEqual(prop.Get(), True) self.assertEqual(prop.Get(), model.get_value_as_bool()) model.set_value(False) self.assertEqual(prop.Get(), False) self.assertEqual(prop.Get(), model.get_value_as_bool()) prop.Set(True) self.assertEqual(model.get_value_as_bool(), True) self.assertEqual(prop.Get(), model.get_value_as_bool()) prop.Set(False) self.assertEqual(model.get_value_as_bool(), False) self.assertEqual(prop.Get(), model.get_value_as_bool()) # Test undo works and collapses back to original value omni.kit.undo.undo() self.assertEqual(prop.Get(), True) self.assertEqual(prop.Get(), model.get_value_as_bool()) async def test_explicit_int_attribute_model(self): prim = self.stage.GetPrimAtPath('/World') model = USDIntAttributeModel(self.stage, prim.GetPath(), 'explicit_int') model.set_value(1) prop = prim.GetProperty('explicit_int') self.assertEqual(prop.Get(), 1) self.assertEqual(prop.Get(), model.get_value_as_int()) model.set_value(2) self.assertEqual(prop.Get(), 2) self.assertEqual(prop.Get(), model.get_value_as_int()) prop.Set(3) self.assertEqual(model.get_value_as_int(), 3) self.assertEqual(prop.Get(), model.get_value_as_int()) prop.Set(4) self.assertEqual(model.get_value_as_int(), 4) self.assertEqual(prop.Get(), model.get_value_as_int()) # Test undo works and collapses back to original value omni.kit.undo.undo() self.assertEqual(prop.Get(), 1) self.assertEqual(prop.Get(), model.get_value_as_int()) async def test_explicit_float_attribute_model(self): prim = self.stage.GetPrimAtPath('/World') model = USDFloatAttributeModel(self.stage, prim.GetPath(), 'explicit_float') model.set_value(123.4) prop = prim.GetProperty('explicit_float') self.assertAlmostEqual(prop.Get(), 123.4, 2) self.assertAlmostEqual(prop.Get(), model.get_value_as_float(), 2) model.set_value(234.5) self.assertAlmostEqual(prop.Get(), 234.5, 1) self.assertAlmostEqual(prop.Get(), model.get_value_as_float(), 2) prop.Set(345.6) self.assertAlmostEqual(model.get_value_as_float(), 345.6, 2) self.assertAlmostEqual(prop.Get(), model.get_value_as_float(), 2) prop.Set(456.7) self.assertAlmostEqual(model.get_value_as_float(), 456.7, 2) self.assertAlmostEqual(prop.Get(), model.get_value_as_float(), 2) # Test undo works and collapses back to original value omni.kit.undo.undo() self.assertAlmostEqual(prop.Get(), 123.4, 2) self.assertEqual(prop.Get(), model.get_value_as_float()) async def test_explicit_string_attribute_model(self): prim = self.stage.GetPrimAtPath('/World') model = USDStringAttributeModel(self.stage, prim.GetPath(), 'explicit_string') model.set_value('A') prop = prim.GetProperty('explicit_string') self.assertEqual(prop.Get(), 'A') self.assertEqual(prop.Get(), model.get_value_as_string()) model.set_value('B') self.assertEqual(prop.Get(), 'B') self.assertEqual(prop.Get(), model.get_value_as_string()) prop.Set('C') self.assertEqual(model.get_value_as_string(), 'C') self.assertEqual(prop.Get(), model.get_value_as_string()) prop.Set('D') self.assertEqual(model.get_value_as_string(), 'D') self.assertEqual(prop.Get(), model.get_value_as_string()) # Test undo works and collapses back to original value omni.kit.undo.undo() self.assertEqual(model.get_value_as_string(), 'A') self.assertEqual(prop.Get(), model.get_value_as_string()) async def test_prim_metadata_model(self): prim = self.stage.GetPrimAtPath('/World') model = USDMetadataModel(self.stage, prim.GetPath(), 'active') model.set_value(True) self.assertEqual(prim.GetMetadata('active'), True) self.assertEqual(prim.GetMetadata('active'), model.get_value_as_bool()) model = USDMetadataModel(self.stage, prim.GetPath(), 'instanceable') model.set_value(False) self.assertEqual(prim.GetMetadata('instanceable'), False) self.assertEqual(prim.GetMetadata('instanceable'), model.get_value_as_bool()) async def test_reset_button(self): class SimpleResetHelper(ResetHelper): def __init__(self, default: bool) -> None: self.value = default self._default = default super().__init__() def get_default(self): return self._default def restore_default(self): self.value = self.get_default() def get_value(self): return self.value def on_reset(): self.__reset = True true_helper = SimpleResetHelper(True) false_helper = SimpleResetHelper(False) reset_btn = ResetButton([true_helper], on_reset_fn=on_reset) reset_btn.add_setting_model(false_helper) self.assertFalse(reset_btn._reset_button.visible) true_helper.value = False reset_btn.refresh() self.assertTrue(reset_btn._reset_button.visible) reset_btn._restore_defaults() self.assertFalse(reset_btn._reset_button.visible) self.assertTrue(true_helper.value) self.assertTrue(self.__reset) async def test_combobox_model(self): model = ComboBoxModel(["First", "Second"], current_value="First") self.assertEqual(model.current_index.as_int, 0) def on_model_changed(model): self._combobox_changed = True model.current_index.subscribe_value_changed_fn(on_model_changed) model.current_index.set_value(1) async def test_setting_combobox_model(self): setting_path = self.get_setting_path('combobox_value') settings = carb.settings.get_settings() settings.set(setting_path, "Second") model = SettingComboBoxModel(setting_path, ["First", "Second"]) self.assertEqual(model.current_index.as_int, 1) model.current_index.set_value(0) self.assertEqual(settings.get(setting_path), "First") model.destroy() async def test_list_model(self): values = [ui.SimpleStringModel("model"), 0.5, 1, "text"] texts = ["model", "float", "int", "string"] model = SimpleListModel(values, texts=texts) self.assertEqual(model.get_item_value_model_count(), 1) items = model.get_item_children() self.assertEqual(len(items), 4) self.assertEqual(model.get_item_value_model(items[0], 0), values[0]) self.assertEqual(model.get_item_value_model(items[1], 0).as_float, values[1]) self.assertEqual(model.get_item_value_model(items[2], 0).as_int, values[2]) self.assertEqual(model.get_item_value_model(items[3], 0).as_string, values[3]) for i in range(4): self.assertEqual(items[i].model.as_string, texts[i]) model.destroy() async def test_color_model(self): def _on_color_changed(color): self.__color = color colors = [0.1, 0.2, 0.3] default = [0, 0, 0] model = ColorModel(colors, default=default, on_color_changed_fn=_on_color_changed) self.assertEqual(model.colors, colors) colors.reverse() model.colors = colors self.assertEqual(model.colors, colors) self.assertEqual(self.__color, colors) self.assertEqual(model.get_default(), default) self.assertEqual(model.get_value(), model.colors) model.restore_default() self.assertEqual(model.colors, default) model.destroy() async def test_category_model(self): setting_path = self.get_setting_path("category_state") settings = carb.settings.get_settings() settings.set(setting_path, True) model = SimpleCategoryModel( "Category Model Test", [ CategoryStateItem("State Setting", setting_path=setting_path), CategoryStateItem("State Model", value_model=ui.SimpleBoolModel(True)), CategoryStateItem("State Empty"), ] ) def _build_fn(): pass # pragma: no cover model.add_item(CategoryCustomItem("Custom", build_fn=_build_fn)) collection_items = model.get_item_children(None) self.assertEqual(len(collection_items), 1) children = model.get_item_children(collection_items[0]) self.assertEqual(len(children), 4) empty = model.get_item_children(children[0]) self.assertEqual(len(empty), 0) empty = model.get_item_children(children[3]) self.assertEqual(len(empty), 0) # Status root = model._root self.assertTrue(children[0].checked) self.assertTrue(children[1].checked) self.assertFalse(children[2].checked) self.assertEqual(root.status, CategoryStatus.MIXED) children[2].checked = True self.assertEqual(root.status, CategoryStatus.ALL) root.status = CategoryStatus.EMPTY self.assertFalse(children[0].checked) self.assertFalse(children[1].checked) self.assertFalse(children[2].checked) root.status = CategoryStatus.ALL self.assertTrue(children[0].checked) self.assertTrue(children[1].checked) self.assertTrue(children[2].checked) model.destroy()
17,929
Python
36.906977
151
0.638407
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/tests/test_icon_delegate.py
import copy from pathlib import Path from typing import Dict from omni.kit.viewport.menubar.core import ViewportMenuContainer, AbstractWidgetMenuDelegate, IconMenuDelegate import omni.ui as ui from omni.ui.tests.test_base import OmniUiTest from omni.kit.viewport.utility import get_active_viewport_and_window from omni.kit.ui_test.query import MenuRef import omni.kit.app import carb.settings from ..style import VIEWPORT_MENUBAR_STYLE from .style import UI_STYLE from ..model.reset_button import ResetHelper CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") TEST_WIDTH, TEST_HEIGHT = 600, 400 class IconMenuDelegateContainer(ViewportMenuContainer): def __init__(self): self._settings = carb.settings.get_settings() self._settings.set("/exts/omni.kit.viewport.menubar.delegate/visible", True) self._settings.set("/exts/omni.kit.viewport.menubar.delegate/order", -100) self._triggered = 0 self._right_clicked = 0 TEST_UI_STYLE = copy.copy(VIEWPORT_MENUBAR_STYLE) TEST_UI_STYLE.update(UI_STYLE) super().__init__( name="Icon", delegate=IconMenuDelegate("Sample", triggered_fn=self._on_trigger, right_clicked_fn=self._on_right_click), visible_setting_path="/exts/omni.kit.viewport.menubar.delegate/visible", order_setting_path="/exts/omni.kit.viewport.menubar.delegate/order", style=TEST_UI_STYLE ) self._settings = carb.settings.get_settings() def destroy(self): self._delegate.destroy() super().destroy() def _on_trigger(self) -> None: self._triggered += 1 def _on_right_click(self) -> None: self._right_clicked += 1 def build_fn(self, factory: Dict): self._root_menu = ui.Menu( self.name, delegate=self._delegate, on_build_fn=self._build_menu_items, style=self._style ) def _build_menu_items(self): ui.MenuItem( "Icon", delegate=IconMenuDelegate("Sample", text=True, build_custom_widgets=self._build_custom_widgets, has_triangle=False), ) def _build_custom_widgets(self, item: ui.MenuItem): ui.Label("custom widget") class TestIconDelegate(OmniUiTest): async def setUp(self): self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT, block_devices=False) _, viewport_window = get_active_viewport_and_window() await self.docked_test_window(viewport_window, width=TEST_WIDTH, height=TEST_HEIGHT, block_devices=False) self._menu = IconMenuDelegateContainer() await omni.kit.app.get_app().next_update_async() # After running each test async def tearDown(self): self._menu.destroy() self._menu = None await super().tearDown() async def test_delegate(self): root_delegate = self._menu._root_menu.delegate self.assertFalse(root_delegate.text_visible) self.assertFalse(root_delegate.checked) self.assertTrue(root_delegate.enabled) self.assertEqual(root_delegate.text, "") menu_ref = MenuRef(self._menu._root_menu, "") await menu_ref.click() await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="menubar_icon_delegate.png" ) self.assertEqual(self._menu._triggered, 1) self.assertEqual(self._menu._right_clicked, 0) await menu_ref.click(right_click=True) self.assertEqual(self._menu._triggered, 1) self.assertEqual(self._menu._right_clicked, 1) root_delegate.text = "Test" root_delegate.text_visible = True root_delegate.checked = True root_delegate.enabled = False await self.finalize_test_no_image()
3,992
Python
34.026315
128
0.658567
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/tests/test_preference.py
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 from omni.kit.viewport.window import ViewportWindow import omni.ui as ui from omni.kit.viewport.menubar.core import get_instance, ViewportMenuSpacer from .left_example_menu_container import LeftExampleMenuContainer from .right_example_menu_container import RightExampleMenuContainer from .example_button import ButtonExample CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") TEST_WIDTH, TEST_HEIGHT = 1280, 600 class TestPreference(OmniUiTest): # Before running each test async def setUp(self): 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, block_devices=False) self._vw = ViewportWindow('TestWindow', width=TEST_WIDTH, height=TEST_HEIGHT) self._left_menu = LeftExampleMenuContainer() self._right_menu = RightExampleMenuContainer() self._button_menu = ButtonExample() # After running each test async def tearDown(self): self._left_menu.destroy() self._left_menu = None self._right_menu.destroy() self._right_menu = None self._button_menu.destroy() self._button_menu = None self._vw.destroy() self._vw = None await super().tearDown() async def test_viewport_preference(self): await self._test_preference_page("Viewport") async def _test_preference_page(self, title: str): for page in omni.kit.window.preferences.get_page_list(): if page.get_title() == title: omni.kit.window.preferences.select_page(page) omni.kit.window.preferences.rebuild_pages() omni.kit.window.preferences.show_preferences_window() await omni.kit.app.get_app().next_update_async() w = ui.Workspace.get_window("Preferences") await self.docked_test_window( window=w, width=1280, height=600, ) 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") async def test_preference_model(self): inst = get_instance() page = inst._page model = page._model items = model.get_item_children(None) self.assertEqual(len(items), 4) self.assertEqual(items[0].name, self._left_menu.name) self.assertEqual(items[1].name, self._button_menu.name) self.assertTrue(isinstance(items[2], ViewportMenuSpacer)) self.assertEqual(items[3].name, self._right_menu.name) left_item = items[0] button_item = items[1] self.assertEqual(model.get_drag_mime_data(left_item), self._left_menu.name) drop_accepted = model.drop_accepted(button_item, left_item) self.assertTrue(drop_accepted) drop_accepted = model.drop_accepted(None, left_item) self.assertFalse(drop_accepted) # Drop left to behind button model.drop(button_item, left_item) items = model.get_item_children(None) self.assertEqual(items[0], button_item) self.assertEqual(items[1], left_item) # Drop left to in front of button model.drop(left_item, button_item) items = model.get_item_children(None) self.assertEqual(items[0], left_item) self.assertEqual(items[1], button_item) await self.finalize_test_no_image()
3,703
Python
33.296296
106
0.662706
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/tests/test_abstract_delegate.py
import copy from pathlib import Path from typing import Dict from omni.kit.viewport.menubar.core import ViewportMenuContainer, AbstractWidgetMenuDelegate, IconMenuDelegate import omni.ui as ui from omni.ui.tests.test_base import OmniUiTest from omni.kit.viewport.utility import get_active_viewport_and_window from omni.kit.ui_test.query import MenuRef import omni.kit.app import carb.settings from ..style import VIEWPORT_MENUBAR_STYLE from ..model.reset_button import ResetHelper from ..viewport_menu_model import ViewportMenuModel from .style import UI_STYLE CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") TEST_WIDTH, TEST_HEIGHT = 600, 400 class SimpleTextDelegate(AbstractWidgetMenuDelegate): def build_widget(self, item: ui.MenuHelper): ui.Label(item.text) class SimpleResetHelper(ResetHelper): def __init__(self, value: bool) -> None: self._value = value super().__init__() def get_default(self): return True def restore_default(self): self._value = self.get_default() def get_value(self): return self._value class AbstractMenuDelegateContainer(ViewportMenuContainer): def __init__(self): self._settings = carb.settings.get_settings() self._settings.set("/exts/omni.kit.viewport.menubar.delegate/visible", True) self._settings.set("/exts/omni.kit.viewport.menubar.delegate/order", -100) TEST_UI_STYLE = copy.copy(VIEWPORT_MENUBAR_STYLE) TEST_UI_STYLE.update(UI_STYLE) super().__init__( name="", delegate=IconMenuDelegate("Sample"), visible_setting_path="/exts/omni.kit.viewport.menubar.delegate/visible", order_setting_path="/exts/omni.kit.viewport.menubar.delegate/order", style=TEST_UI_STYLE ) self._settings = carb.settings.get_settings() def build_fn(self, factory: Dict): self._root_menu = ui.Menu( self.name, delegate=self._delegate, on_build_fn=self._build_menu_items, style=self._style ) def _build_menu_items(self): ui.MenuItem( "General", delegate=SimpleTextDelegate(), ) ui.MenuItem( "Reserve Status", delegate=SimpleTextDelegate(reserve_status=True), ) ui.MenuItem( "Reset Button (True)", delegate=SimpleTextDelegate(model=SimpleResetHelper(True), has_reset=True), ) ui.MenuItem( "Reset Button (False)", delegate=SimpleTextDelegate(model=SimpleResetHelper(False), has_reset=True), ) ui.Menu( "Menu", delegate=SimpleTextDelegate(), ) self._invisible_menuitem = ui.MenuItem( "Invisible", delegate=SimpleTextDelegate(visible=False), ) self._disabled_menuitem = ui.MenuItem( "Disabled", delegate= SimpleTextDelegate(enabled=False), ) class TestAbstractDelegate(OmniUiTest): async def setUp(self): self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT, block_devices=False) _, viewport_window = get_active_viewport_and_window() await self.docked_test_window(viewport_window, width=TEST_WIDTH, height=TEST_HEIGHT, block_devices=False) self._menu = AbstractMenuDelegateContainer() await omni.kit.app.get_app().next_update_async() # After running each test async def tearDown(self): self._menu.destroy() self._menu = None await super().tearDown() async def test_delegate(self): menu_ref = MenuRef(self._menu._root_menu, "") await menu_ref.click() self.assertFalse(self._menu._invisible_menuitem.delegate.visible) self.assertFalse(self._menu._disabled_menuitem.delegate.enabled) await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="menubar_abstract_delegate.png" )
4,180
Python
31.92126
113
0.650478
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/tests/right_example_menu_container.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["RightExampleMenuContainer"] from omni.kit.viewport.menubar.core import ( IconMenuDelegate, ViewportMenuContainer, ViewportMenuDelegate, ) from .style import UI_STYLE import carb import carb.settings import omni.ui as ui from typing import Dict from functools import partial class RightExampleMenuContainer(ViewportMenuContainer): """The menu aligned to right""" def __init__(self): self._settings = carb.settings.get_settings() self._settings.set("/exts/omni.kit.viewport.menubar.example/right/visible", True) self._settings.set("/exts/omni.kit.viewport.menubar.example/right/order", 100) super().__init__( name="Right Samples Menu", delegate=IconMenuDelegate("Sample", text=True), visible_setting_path="/exts/omni.kit.viewport.menubar.example/right/visible", order_setting_path="/exts/omni.kit.viewport.menubar.example/right/order", style=UI_STYLE ) self._settings = carb.settings.get_settings() def build_fn(self, factory: Dict): """Entry point for the menu bar""" self.__root_menu = ui.Menu( self.name, delegate=self._delegate, on_build_fn=partial(self._build_menu_items, factory), style=UI_STYLE ) def _build_menu_items(self, factory): ui.MenuItem( "Normal", checkable=False, delegate=ViewportMenuDelegate(), ) ui.MenuItem( "Checked", checkable=True, checked=True, delegate=ViewportMenuDelegate(), ) ui.MenuItem( "Disabled", enabled=False, delegate=ViewportMenuDelegate(), ) ui.MenuItem( "Icon on the right", delegate=ViewportMenuDelegate(icon_name="Sample") ) ui.Separator() with ui.Menu( "Sub menuitems without icon", delegate=ViewportMenuDelegate() ): for i in range(5): ui.MenuItem(f"Sub item {i}", delegate=ViewportMenuDelegate(),) with ui.Menu( "Sub menuitems with icon", delegate=ViewportMenuDelegate(icon_name="Sample"), ): for i in range(5): ui.MenuItem(f"Sub item {i}", delegate=ViewportMenuDelegate(),)
2,837
Python
29.847826
116
0.616849
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/tests/test_slider_delegate.py
from pathlib import Path from omni.kit.viewport.menubar.core import SliderMenuDelegate import omni.ui as ui from omni.ui.tests.test_base import OmniUiTest from omni.kit.viewport.utility import get_active_viewport_and_window from omni.kit.ui_test.query import MenuRef import omni.kit.app from .abstract_test_container import AbstractTestContainer CURRENT_PATH = Path(__file__).parent TEST_DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.parent.parent.joinpath("data").joinpath("tests") TEST_WIDTH, TEST_HEIGHT = 600, 400 class SliderMenuDelegateContainer(AbstractTestContainer): def _build_menu_items(self): ui.MenuItem( "General", delegate=SliderMenuDelegate(), ) ui.MenuItem( "Int Slider", delegate=SliderMenuDelegate(slider_class=ui.IntSlider), ) self._checkbox_item_model = ui.SimpleIntModel(0) self._checkbox_item = ui.MenuItem( "Show checkbox with value is min", delegate=SliderMenuDelegate(model=self._checkbox_item_model, show_checkbox_if_min=True, min=0, max=10), ) ui.MenuItem( "Hide Checkbox", delegate=SliderMenuDelegate(model=ui.SimpleIntModel(3), show_checkbox_if_min=True, min=0, max=10), ) self._drag_min = -100 self._drag_max = 1000 self._drag_step = 10 self._drag_item = ui.MenuItem( "Drag", delegate=SliderMenuDelegate(min=self._drag_min, max=self._drag_max, step=self._drag_step), ) self._drag_item = ui.MenuItem( "Int Drag", delegate=SliderMenuDelegate(min=self._drag_min, max=self._drag_max, step=self._drag_step, slider_class=ui.IntSlider), ) class TestSliderDelegate(OmniUiTest): async def setUp(self): self._golden_img_dir = TEST_DATA_PATH.absolute().joinpath("golden_img").absolute() await self.create_test_area(width=TEST_WIDTH, height=TEST_HEIGHT, block_devices=False) _, viewport_window = get_active_viewport_and_window() await self.docked_test_window(viewport_window, width=TEST_WIDTH, height=TEST_HEIGHT, block_devices=False) self._menu = SliderMenuDelegateContainer() await omni.kit.app.get_app().next_update_async() # After running each test async def tearDown(self): self._menu.destroy() self._menu = None await super().tearDown() async def test_delegate(self): menu_ref = MenuRef(self._menu._root_menu, "") await menu_ref.click() for _ in range(4): await omni.kit.app.get_app().next_update_async() slider_delegate = self._menu._drag_item.delegate self.assertEqual(slider_delegate.min, self._menu._drag_min) self.assertEqual(slider_delegate.max, self._menu._drag_max) self._menu._checkbox_item_model.set_value(5) checkbox_delegate = self._menu._checkbox_item.delegate checkbox_delegate.min = 5 checkbox_delegate.max = 50 self.assertEqual(checkbox_delegate.min, 5) self.assertEqual(checkbox_delegate.max, 50) checkbox_delegate.set_range(-10, 10) self.assertEqual(checkbox_delegate.min, -10) self.assertEqual(checkbox_delegate.max, 10) self._menu._checkbox_item_model.set_value(-10) await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="menubar_slider_delegate.png" )
3,510
Python
34.11
129
0.645299
omniverse-code/kit/exts/omni.kit.viewport.menubar.core/omni/kit/viewport/menubar/core/utils/usd_watch.py
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["start", "stop", "subscribe"] from collections import defaultdict from dataclasses import dataclass from functools import partial from pxr import Sdf from pxr import Tf from pxr import Trace from pxr import Usd from typing import Callable from typing import Dict from typing import List from typing import Optional, Union import asyncio import omni.kit.app from omni.kit.async_engine import run_coroutine import weakref import concurrent.futures # The watch object is one per session __watch: Optional["_USDWatch"] = None def start(): """Starts watch""" global __watch if not __watch: __watch = _USDWatch() def stop(): """Stops watch""" global __watch if __watch: __watch.destroy() __watch = None def subscribe(stage: Usd.Stage, path: Sdf.Path, callback: Callable[[], None]): """ Lets execute the callback when the given attribute is changed. The callback will be executed while the returned object is alive. If returned object is None, the watch is not started. """ global __watch if __watch: return __watch.subscribe(stage, path, callback) class _USDWatch: """ The object that holds a single Tf.Notice.Listener and executes callbacks when specific attribute is changed. """ @dataclass class _USDWatchCallbackHandler: """Holds the callbacks""" changed_fn: Callable[[], None] def __init__(self): self.__listener: Optional[Tf.Notice.Listener] = None # The storage with all registered callbacks self.__callbacks: Dict[Usd.Stage, Dict[Sdf.Path, Callable[[], None]]] = defaultdict(dict) # The storage with all dirty attributes self.__dirty_attr_paths: Dict[Usd.Stage, List[Sdf.Path]] = defaultdict(list) # The task where the dirty attributes are computed self.__prim_changed_task_or_future: Union[asyncio.Task, concurrent.futures.Future, None] = None def destroy(self): """Should be executed before the object is killed""" self.clear_all() def clear_all(self): """Stop Tf.Notice and clear callbacks""" if self.__listener: self.__listener.Revoke() self.__listener = None self.__callbacks.clear() def subscribe(self, stage: Usd.Stage, path: Sdf.Path, callback: Callable[[], None]): """ Lets execute the callback when the given attribute is changed. The callback will be executed while the returned object is alive. """ if not self.__listener: self.__listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._on_usd_changed, None) handler = self._USDWatchCallbackHandler(callback) self.__callbacks[stage][path] = weakref.proxy(handler, partial(self._unsubscribe, stage, path)) return handler def _unsubscribe(self, stage: Usd.Stage, path: Sdf.Path, dead): """Stop the subscription of the given attribute""" callbacks = self.__callbacks.get(stage, None) if callbacks is None: return callbacks.pop(path) if not callbacks: # Remove the stage if empty self.__callbacks.pop(stage) if not self.__callbacks: # Stop the USD listener if there are no callbacks self.clear_all() def _update_dirty(self): """ Execute the callbacks for the dirty items that was collected from TfNotice. It can be called any time to pump changes. """ dirty_attr_paths = self.__dirty_attr_paths self.__dirty_attr_paths = defaultdict(list) for stage, dirty_paths in dirty_attr_paths.items(): callbacks = self.__callbacks.get(stage, None) if not callbacks: continue for path in set(dirty_paths): callback = callbacks.get(path, None) if callback: callback.changed_fn() @Trace.TraceFunction def _on_usd_changed(self, notice: Tf.Notice, stage: Usd.Stage): """Called by Usd.Notice.ObjectsChanged""" if stage not in self.__callbacks: return dirty_prims_paths: List[Sdf.Path] = [] for p in notice.GetChangedInfoOnlyPaths(): if p.IsPropertyPath(): dirty_prims_paths.append(p) elif p.IsPrimPath(): dirty_prims_paths.append(p) for p in notice.GetResyncedPaths(): if p.IsPropertyPath(): dirty_prims_paths.append(p) elif p.IsPrimPath(): dirty_prims_paths.append(p) if not dirty_prims_paths: return self.__dirty_attr_paths[stage] += dirty_prims_paths # Update in the next frame. We need it because we want to accumulate the affected prims if self.__prim_changed_task_or_future is None or self.__prim_changed_task_or_future.done(): self.__prim_changed_task_or_future = run_coroutine(self.__delayed_prim_changed()) @Trace.TraceFunction async def __delayed_prim_changed(self): await omni.kit.app.get_app().next_update_async() # Pump the changes to the camera list. self._update_dirty() self.__prim_changed_task_or_future = None
5,738
Python
31.607954
103
0.636633
omniverse-code/kit/exts/omni.kit.property.file/omni/kit/property/file/file_widget.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 weakref import carb import omni.client import omni.ui as ui from omni.kit.window.property.templates import SimplePropertyWidget class FileWidget(SimplePropertyWidget): def __init__(self): super().__init__(title="File Info", collapsed=False) self._stat_task = None self._created_by_model = ui.SimpleStringModel() self._created_time_model = ui.SimpleStringModel() self._modified_by_model = ui.SimpleStringModel() self._modified_time_model = ui.SimpleStringModel() self._file_size_model = ui.SimpleStringModel() def clean(self): super().clean() self._created_by_model = None self._created_time_model = None self._modified_by_model = None self._modified_time_model = None self._file_size_model = None def on_new_payload(self, payload): if not super().on_new_payload(payload): return False # Only support one selected path if len(payload) != 1: return False return True def reset(self): if self._stat_task: self._stat_task.cancel() self._stat_task = None if self._created_by_model: self._created_by_model.set_value("") if self._created_time_model: self._created_time_model.set_value("") if self._modified_by_model: self._modified_by_model.set_value("") if self._modified_time_model: self._modified_time_model.set_value("") if self._file_size_model: self._file_size_model.set_value("") super().reset() async def _stat_file_async(self): result, entry = await omni.client.stat_async(self._payload[0].path) if not result or not entry: return if result == omni.client.Result.OK: self._created_by_model.set_value(entry.created_by) self._created_time_model.set_value(entry.created_time.strftime("%x %X")) self._modified_by_model.set_value(entry.modified_by) self._modified_time_model.set_value(entry.modified_time.strftime("%x %X")) self._file_size_model.set_value(f"{entry.size:,} " + ("Bytes" if entry.size > 1 else "Byte")) else: carb.log_warn(f"Failed to get file info for {self._payload[0].path}") self._stat_task = None def _stat_file(self): self._stat_task = asyncio.ensure_future(self._stat_file_async()) def build_items(self): self._stat_file() self.add_item_with_model("Date Created", self._created_time_model, identifier="created_time") self.add_item_with_model("Created by", self._created_by_model, identifier="created_by") self.add_item_with_model("Date Modified", self._modified_time_model, identifier="modified_time") self.add_item_with_model("Modified by", self._modified_by_model, identifier="modified_by") self.add_item_with_model("File Size", self._file_size_model, identifier="file_size")
3,469
Python
37.988764
105
0.640819
omniverse-code/kit/exts/omni.kit.property.file/omni/kit/property/file/extension.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.ext import weakref from omni.kit.window.content_browser import get_content_window from .file_widget import FileWidget class FilePropertyWidgets(omni.ext.IExt): def __init__(self): self._registered = False self._selection_notifiers = [] self._content_browser_notifier = None super().__init__() def on_startup(self, ext_id): manager = omni.kit.app.get_app().get_extension_manager() self._hooks = manager.subscribe_to_extension_enable( lambda _: self._add_selection_notifier(), lambda _: self._remove_selection_notifier(), ext_name="omni.kit.window.content_browser", hook_name="file property widget listener", ) self._register_widget() def on_shutdown(self): self._hooks = None for notifier in self._selection_notifiers: notifier.destroy() self._selection_notifiers.clear() if self._registered: self._unregister_widget() def _add_selection_notifier(self): try: self._content_browser_notifier = SelectionNotifier() self._selection_notifiers.append(self._content_browser_notifier) except Exception as e: carb.log_info(f"Could not add file selection notifier: {e}") def _remove_selection_notifier(self): if self._content_browser_notifier: self._selection_notifiers.remove(self._content_browser_notifier) self._content_browser_notifier.destroy() self._content_browser_notifier = None def _register_widget(self): import omni.kit.window.property as p w = p.get_window() if w: w.register_widget("file", "stat", FileWidget()) for notifier in self._selection_notifiers: notifier.start() notifier._notify_property_window([]) # force a refresh self._registered = True def _unregister_widget(self): try: import omni.kit.window.property as p w = p.get_window() if w: for notifier in self._selection_notifiers: notifier.stop() w.unregister_widget("file", "stat") self._registered = False except: pass class SelectionNotifier: def __init__(self, property_window_context_id=""): from omni.kit.window.content_browser import get_content_window self._content_browser_ref = weakref.ref(get_content_window(), lambda ref: self.destroy()) self._property_window_context_id = property_window_context_id def start(self): content_browser = self._content_browser_ref() if content_browser: self._sub = content_browser.subscribe_selection_changed(self._on_content_selection_changed) def stop(self): self._sub = None def destroy(self): self.stop() def _on_content_selection_changed(self, pane: int, selections): self._notify_property_window(selections) def _notify_property_window(self, selections): import omni.kit.window.property as p # TODO _property_window_context_id w = p.get_window() if w: w.notify("file", selections)
3,726
Python
33.19266
103
0.630435
omniverse-code/kit/exts/omni.kit.property.file/omni/kit/property/file/tests/__init__.py
from .test_file import *
25
Python
11.999994
24
0.72
omniverse-code/kit/exts/omni.kit.property.file/omni/kit/property/file/tests/test_file.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 import omni.client from omni.kit.test.async_unittest import AsyncTestCase from omni.kit import ui_test from omni.kit.test_suite.helpers import get_test_data_path, arrange_windows from omni.kit.window.content_browser.test_helper import ContentBrowserTestHelper class HardRangeUI(AsyncTestCase): # Before running each test async def setUp(self): await arrange_windows("Stage", 64) # After running each test async def tearDown(self): pass async def test_fileinfo_ui(self): await ui_test.find("Content").focus() await ui_test.find("Property").focus() # select file to show info dir_url = get_test_data_path(__name__, "..") async with ContentBrowserTestHelper() as content_browser_helper: await content_browser_helper.select_items_async(dir_url, names=["icon.png"]) await ui_test.human_delay(4) # get file info file_path = f"{dir_url}/icon.png" result, entry = await omni.client.stat_async(str(file_path)) self.assertEqual(result, omni.client.Result.OK) self.assertTrue(entry != None) # get file strings created_by = entry.created_by created_time = entry.created_time.strftime("%x %X") modified_by = entry.modified_by modified_time = entry.modified_time.strftime("%x %X") file_size = f"{entry.size:,} " + ("Bytes" if entry.size > 1 else "Byte") # verify ui strings # widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='created_time'") # self.assertEqual(widget.model.get_value_as_string(), created_time) widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='created_by'") self.assertEqual(widget.model.get_value_as_string(), created_by) # widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='modified_time'") # self.assertEqual(widget.model.get_value_as_string(), modified_time) widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='modified_by'") self.assertEqual(widget.model.get_value_as_string(), modified_by) widget = ui_test.find("Property//Frame/**/StringField[*].identifier=='file_size'") self.assertEqual(widget.model.get_value_as_string(), file_size)
2,770
Python
40.984848
96
0.677978
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_version.py
# This file was generated by 'versioneer.py' (0.23) from # revision-control system data, or from the parent directory name of an # unpacked source archive. Distribution tarballs contain a pre-generated copy # of this file. import json version_json = ''' { "date": "2023-01-05T13:27:00-0800", "dirty": false, "error": null, "full-revisionid": "6c3dca7918333b21ed91da9e3da42acebd1026d1", "version": "1.6.5" } ''' # END VERSION_JSON def get_versions(): return json.loads(version_json)
497
Python
21.636363
77
0.712274
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/public_api.py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See LICENSE in the project root # for license information. from __future__ import annotations import functools import typing from debugpy import _version # Expose debugpy.server API from subpackage, but do not actually import it unless # and until a member is invoked - we don't want the server package loaded in the # adapter, the tests, or setup.py. # Docstrings for public API members must be formatted according to PEP 8 - no more # than 72 characters per line! - and must be readable when retrieved via help(). Endpoint = typing.Tuple[str, int] def _api(cancelable=False): def apply(f): @functools.wraps(f) def wrapper(*args, **kwargs): from debugpy.server import api wrapped = getattr(api, f.__name__) return wrapped(*args, **kwargs) if cancelable: def cancel(*args, **kwargs): from debugpy.server import api wrapped = getattr(api, f.__name__) return wrapped.cancel(*args, **kwargs) wrapper.cancel = cancel return wrapper return apply @_api() def log_to(__path: str) -> None: """Generate detailed debugpy logs in the specified directory. The directory must already exist. Several log files are generated, one for every process involved in the debug session. """ @_api() def configure(__properties: dict[str, typing.Any] | None = None, **kwargs) -> None: """Sets debug configuration properties that cannot be set in the "attach" request, because they must be applied as early as possible in the process being debugged. For example, a "launch" configuration with subprocess debugging disabled can be defined entirely in JSON:: { "request": "launch", "subProcess": false, ... } But the same cannot be done with "attach", because "subProcess" must be known at the point debugpy starts tracing execution. Thus, it is not available in JSON, and must be omitted:: { "request": "attach", ... } and set from within the debugged process instead:: debugpy.configure(subProcess=False) debugpy.listen(...) Properties to set can be passed either as a single dict argument, or as separate keyword arguments:: debugpy.configure({"subProcess": False}) """ @_api() def listen( __endpoint: Endpoint | int, *, in_process_debug_adapter: bool = False ) -> Endpoint: """Starts a debug adapter debugging this process, that listens for incoming socket connections from clients on the specified address. `__endpoint` must be either a (host, port) tuple as defined by the standard `socket` module for the `AF_INET` address family, or a port number. If only the port is specified, host is "127.0.0.1". `in_process_debug_adapter`: by default a separate python process is spawned and used to communicate with the client as the debug adapter. By setting the value of `in_process_debug_adapter` to True a new python process is not spawned. Note: the con of setting `in_process_debug_adapter` to True is that subprocesses won't be automatically debugged. Returns the interface and the port on which the debug adapter is actually listening, in the same format as `__endpoint`. This may be different from address if port was 0 in the latter, in which case the adapter will pick some unused ephemeral port to listen on. This function does't wait for a client to connect to the debug adapter that it starts. Use `wait_for_client` to block execution until the client connects. """ @_api() def connect(__endpoint: Endpoint | int, *, access_token: str | None = None) -> Endpoint: """Tells an existing debug adapter instance that is listening on the specified address to debug this process. `__endpoint` must be either a (host, port) tuple as defined by the standard `socket` module for the `AF_INET` address family, or a port number. If only the port is specified, host is "127.0.0.1". `access_token` must be the same value that was passed to the adapter via the `--server-access-token` command-line switch. This function does't wait for a client to connect to the debug adapter that it connects to. Use `wait_for_client` to block execution until the client connects. """ @_api(cancelable=True) def wait_for_client() -> None: """If there is a client connected to the debug adapter that is debugging this process, returns immediately. Otherwise, blocks until a client connects to the adapter. While this function is waiting, it can be canceled by calling `wait_for_client.cancel()` from another thread. """ @_api() def is_client_connected() -> bool: """True if a client is connected to the debug adapter that is debugging this process. """ @_api() def breakpoint() -> None: """If a client is connected to the debug adapter that is debugging this process, pauses execution of all threads, and simulates a breakpoint being hit at the line following the call. It is also registered as the default handler for builtins.breakpoint(). """ @_api() def debug_this_thread() -> None: """Makes the debugger aware of the current thread. Must be called on any background thread that is started by means other than the usual Python APIs (i.e. the "threading" module), in order for breakpoints to work on that thread. """ @_api() def trace_this_thread(__should_trace: bool): """Tells the debug adapter to enable or disable tracing on the current thread. When the thread is traced, the debug adapter can detect breakpoints being hit, but execution is slower, especially in functions that have any breakpoints set in them. Disabling tracing when breakpoints are not anticipated to be hit can improve performance. It can also be used to skip breakpoints on a particular thread. Tracing is automatically disabled for all threads when there is no client connected to the debug adapter. """ __version__: str = _version.get_versions()["version"]
6,320
Python
31.415384
88
0.682753
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/__init__.py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See LICENSE in the project root # for license information. """An implementation of the Debug Adapter Protocol (DAP) for Python. https://microsoft.github.io/debug-adapter-protocol/ """ # debugpy stable public API consists solely of members of this module that are # enumerated below. __all__ = [ # noqa "__version__", "breakpoint", "configure", "connect", "debug_this_thread", "is_client_connected", "listen", "log_to", "trace_this_thread", "wait_for_client", ] import sys assert sys.version_info >= (3, 7), ( "Python 3.6 and below is not supported by this version of debugpy; " "use debugpy 1.5.1 or earlier." ) # Actual definitions are in a separate file to work around parsing issues causing # SyntaxError on Python 2 and preventing the above version check from executing. from debugpy.public_api import * # noqa from debugpy.public_api import __version__ del sys
1,018
Python
25.128204
81
0.699411
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/__main__.py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See LICENSE in the project root # for license information. import sys if __name__ == "__main__": # debugpy can also be invoked directly rather than via -m. In this case, the first # entry on sys.path is the one added automatically by Python for the directory # containing this file. This means that import debugpy will not work, since we need # the parent directory of debugpy/ to be in sys.path, rather than debugpy/ itself. # # The other issue is that many other absolute imports will break, because they # will be resolved relative to debugpy/ - e.g. `import debugger` will then try # to import debugpy/debugger.py. # # To fix both, we need to replace the automatically added entry such that it points # at parent directory of debugpy/ instead of debugpy/ itself, import debugpy with that # in sys.path, and then remove the first entry entry altogether, so that it doesn't # affect any further imports we might do. For example, suppose the user did: # # python /foo/bar/debugpy ... # # At the beginning of this script, sys.path will contain "/foo/bar/debugpy" as the # first entry. What we want is to replace it with "/foo/bar', then import debugpy # with that in effect, and then remove the replaced entry before any more # code runs. The imported debugpy module will remain in sys.modules, and thus all # future imports of it or its submodules will resolve accordingly. if "debugpy" not in sys.modules: # Do not use dirname() to walk up - this can be a relative path, e.g. ".". sys.path[0] = sys.path[0] + "/../" import debugpy # noqa del sys.path[0] from debugpy.server import cli cli.main()
1,829
Python
44.749999
90
0.690541
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/_pydevd_packaging.py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See LICENSE in the project root # for license information. from . import VENDORED_ROOT from ._util import cwd, iter_all_files INCLUDES = [ 'setup_pydevd_cython.py', ] def iter_files(): # From the root of pydevd repo, we want only scripts and # subdirectories that constitute the package itself (not helper # scripts, tests etc). But when walking down into those # subdirectories, we want everything below. with cwd(VENDORED_ROOT): return iter_all_files('pydevd', prune_dir, exclude_file) def prune_dir(dirname, basename): if basename == '__pycache__': return True elif dirname != 'pydevd': return False elif basename.startswith('pydev'): return False elif basename.startswith('_pydev'): return False return True def exclude_file(dirname, basename): if dirname == 'pydevd': if basename in INCLUDES: return False elif not basename.endswith('.py'): return True elif 'pydev' not in basename: return True return False if basename.endswith('.pyc'): return True return False
1,245
Python
24.428571
67
0.648193
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/__init__.py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See LICENSE in the project root # for license information. import contextlib from importlib import import_module import os import sys from . import _util VENDORED_ROOT = os.path.dirname(os.path.abspath(__file__)) # TODO: Move the "pydevd" git submodule to the debugpy/_vendored directory # and then drop the following fallback. if "pydevd" not in os.listdir(VENDORED_ROOT): VENDORED_ROOT = os.path.dirname(VENDORED_ROOT) def list_all(resolve=False): """Return the list of vendored projects.""" # TODO: Derive from os.listdir(VENDORED_ROOT)? projects = ["pydevd"] if not resolve: return projects return [project_root(name) for name in projects] def project_root(project): """Return the path the root dir of the vendored project. If "project" is an empty string then the path prefix for vendored projects (e.g. "debugpy/_vendored/") will be returned. """ if not project: project = "" return os.path.join(VENDORED_ROOT, project) def iter_project_files(project, relative=False, **kwargs): """Yield (dirname, basename, filename) for all files in the project.""" if relative: with _util.cwd(VENDORED_ROOT): for result in _util.iter_all_files(project, **kwargs): yield result else: root = project_root(project) for result in _util.iter_all_files(root, **kwargs): yield result def iter_packaging_files(project): """Yield the filenames for all files in the project. The filenames are relative to "debugpy/_vendored". This is most useful for the "package data" in a setup.py. """ # TODO: Use default filters? __pycache__ and .pyc? prune_dir = None exclude_file = None try: mod = import_module("._{}_packaging".format(project), __name__) except ImportError: pass else: prune_dir = getattr(mod, "prune_dir", prune_dir) exclude_file = getattr(mod, "exclude_file", exclude_file) results = iter_project_files( project, relative=True, prune_dir=prune_dir, exclude_file=exclude_file ) for _, _, filename in results: yield filename def prefix_matcher(*prefixes): """Return a module match func that matches any of the given prefixes.""" assert prefixes def match(name, module): for prefix in prefixes: if name.startswith(prefix): return True else: return False return match def check_modules(project, match, root=None): """Verify that only vendored modules have been imported.""" if root is None: root = project_root(project) extensions = [] unvendored = {} for modname, mod in list(sys.modules.items()): if not match(modname, mod): continue try: filename = getattr(mod, "__file__", None) except: # In theory it's possible that any error is raised when accessing __file__ filename = None if not filename: # extension module extensions.append(modname) elif not filename.startswith(root): unvendored[modname] = filename return unvendored, extensions @contextlib.contextmanager def vendored(project, root=None): """A context manager under which the vendored project will be imported.""" if root is None: root = project_root(project) # Add the vendored project directory, so that it gets tried first. sys.path.insert(0, root) try: yield root finally: sys.path.remove(root) def preimport(project, modules, **kwargs): """Import each of the named modules out of the vendored project.""" with vendored(project, **kwargs): for name in modules: import_module(name)
3,878
Python
29.543307
91
0.645436
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/force_pydevd.py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See LICENSE in the project root # for license information. from importlib import import_module import os import warnings from . import check_modules, prefix_matcher, preimport, vendored # Ensure that pydevd is our vendored copy. _unvendored, _ = check_modules('pydevd', prefix_matcher('pydev', '_pydev')) if _unvendored: _unvendored = sorted(_unvendored.values()) msg = 'incompatible copy of pydevd already imported' # raise ImportError(msg) warnings.warn(msg + ':\n {}'.format('\n '.join(_unvendored))) # If debugpy logging is enabled, enable it for pydevd as well if "DEBUGPY_LOG_DIR" in os.environ: os.environ[str("PYDEVD_DEBUG")] = str("True") os.environ[str("PYDEVD_DEBUG_FILE")] = os.environ["DEBUGPY_LOG_DIR"] + str("/debugpy.pydevd.log") # Constants must be set before importing any other pydevd module # # due to heavy use of "from" in them. with vendored('pydevd'): pydevd_constants = import_module('_pydevd_bundle.pydevd_constants') # We limit representation size in our representation provider when needed. pydevd_constants.MAXIMUM_VARIABLE_REPRESENTATION_SIZE = 2 ** 32 # Now make sure all the top-level modules and packages in pydevd are # loaded. Any pydevd modules that aren't loaded at this point, will # be loaded using their parent package's __path__ (i.e. one of the # following). preimport('pydevd', [ '_pydev_bundle', '_pydev_runfiles', '_pydevd_bundle', '_pydevd_frame_eval', 'pydev_ipython', 'pydevd_plugins', 'pydevd', ]) # When pydevd is imported it sets the breakpoint behavior, but it needs to be # overridden because by default pydevd will connect to the remote debugger using # its own custom protocol rather than DAP. import pydevd # noqa import debugpy # noqa def debugpy_breakpointhook(): debugpy.breakpoint() pydevd.install_breakpointhook(debugpy_breakpointhook) # Ensure that pydevd uses JSON protocol from _pydevd_bundle import pydevd_constants from _pydevd_bundle import pydevd_defaults pydevd_defaults.PydevdCustomization.DEFAULT_PROTOCOL = pydevd_constants.HTTP_JSON_PROTOCOL
2,216
Python
34.190476
101
0.726986
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/_util.py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See LICENSE in the project root # for license information. import contextlib import os @contextlib.contextmanager def cwd(dirname): """A context manager for operating in a different directory.""" orig = os.getcwd() os.chdir(dirname) try: yield orig finally: os.chdir(orig) def iter_all_files(root, prune_dir=None, exclude_file=None): """Yield (dirname, basename, filename) for each file in the tree. This is an alternative to os.walk() that flattens out the tree and with filtering. """ pending = [root] while pending: dirname = pending.pop(0) for result in _iter_files(dirname, pending, prune_dir, exclude_file): yield result def iter_tree(root, prune_dir=None, exclude_file=None): """Yield (dirname, files) for each directory in the tree. The list of files is actually a list of (basename, filename). This is an alternative to os.walk() with filtering.""" pending = [root] while pending: dirname = pending.pop(0) files = [] for _, b, f in _iter_files(dirname, pending, prune_dir, exclude_file): files.append((b, f)) yield dirname, files def _iter_files(dirname, subdirs, prune_dir, exclude_file): for basename in os.listdir(dirname): filename = os.path.join(dirname, basename) if os.path.isdir(filename): if prune_dir is not None and prune_dir(dirname, basename): continue subdirs.append(filename) else: # TODO: Use os.path.isfile() to narrow it down? if exclude_file is not None and exclude_file(dirname, basename): continue yield dirname, basename, filename
1,840
Python
29.683333
78
0.636413
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_app_engine_debug_startup.py
if False: config = None # See: https://docs.google.com/document/d/1CCSaRiIWCLgbD3OwmuKsRoHHDfBffbROWyVWWL0ZXN4/edit if ':' not in config.version_id: # The default server version_id does not contain ':' import json import os import sys startup = config.python_config.startup_args if not startup: raise AssertionError('Expected --python_startup_args to be passed from the pydev debugger.') setup = json.loads(startup) pydevd_path = setup['pydevd'] sys.path.append(os.path.dirname(pydevd_path)) import pydevd pydevd.settrace(setup['client'], port=setup['port'], suspend=False, trace_only_current_thread=False)
691
Python
30.454544
104
0.683068
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_pysrc.py
'''An empty file in pysrc that can be imported (from sitecustomize) to find the location of pysrc'''
100
Python
99.9999
100
0.76
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_tracing.py
from _pydevd_bundle.pydevd_constants import get_frame, IS_CPYTHON, IS_64BIT_PROCESS, IS_WINDOWS, \ IS_LINUX, IS_MAC, DebugInfoHolder, LOAD_NATIVE_LIB_FLAG, \ ENV_FALSE_LOWER_VALUES, ForkSafeLock from _pydev_bundle._pydev_saved_modules import thread, threading from _pydev_bundle import pydev_log, pydev_monkey import os.path import platform import ctypes from io import StringIO import sys import traceback _original_settrace = sys.settrace class TracingFunctionHolder: '''This class exists just to keep some variables (so that we don't keep them in the global namespace). ''' _original_tracing = None _warn = True _traceback_limit = 1 _warnings_shown = {} def get_exception_traceback_str(): exc_info = sys.exc_info() s = StringIO() traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], file=s) return s.getvalue() def _get_stack_str(frame): msg = '\nIf this is needed, please check: ' + \ '\nhttp://pydev.blogspot.com/2007/06/why-cant-pydev-debugger-work-with.html' + \ '\nto see how to restore the debug tracing back correctly.\n' if TracingFunctionHolder._traceback_limit: s = StringIO() s.write('Call Location:\n') traceback.print_stack(f=frame, limit=TracingFunctionHolder._traceback_limit, file=s) msg = msg + s.getvalue() return msg def _internal_set_trace(tracing_func): if TracingFunctionHolder._warn: frame = get_frame() if frame is not None and frame.f_back is not None: filename = frame.f_back.f_code.co_filename.lower() if not filename.endswith('threading.py') and not filename.endswith('pydevd_tracing.py'): message = \ '\nPYDEV DEBUGGER WARNING:' + \ '\nsys.settrace() should not be used when the debugger is being used.' + \ '\nThis may cause the debugger to stop working correctly.' + \ '%s' % _get_stack_str(frame.f_back) if message not in TracingFunctionHolder._warnings_shown: # only warn about each message once... TracingFunctionHolder._warnings_shown[message] = 1 sys.stderr.write('%s\n' % (message,)) sys.stderr.flush() if TracingFunctionHolder._original_tracing: TracingFunctionHolder._original_tracing(tracing_func) _last_tracing_func_thread_local = threading.local() def SetTrace(tracing_func): _last_tracing_func_thread_local.tracing_func = tracing_func if tracing_func is not None: if set_trace_to_threads(tracing_func, thread_idents=[thread.get_ident()], create_dummy_thread=False) == 0: # If we can use our own tracer instead of the one from sys.settrace, do it (the reason # is that this is faster than the Python version because we don't call # PyFrame_FastToLocalsWithError and PyFrame_LocalsToFast at each event! # (the difference can be huge when checking line events on frames as the # time increases based on the number of local variables in the scope) # See: InternalCallTrampoline (on the C side) for details. return # If it didn't work (or if it was None), use the Python version. set_trace = TracingFunctionHolder._original_tracing or sys.settrace set_trace(tracing_func) def reapply_settrace(): try: tracing_func = _last_tracing_func_thread_local.tracing_func except AttributeError: return else: SetTrace(tracing_func) def replace_sys_set_trace_func(): if TracingFunctionHolder._original_tracing is None: TracingFunctionHolder._original_tracing = sys.settrace sys.settrace = _internal_set_trace def restore_sys_set_trace_func(): if TracingFunctionHolder._original_tracing is not None: sys.settrace = TracingFunctionHolder._original_tracing TracingFunctionHolder._original_tracing = None _lock = ForkSafeLock() def _load_python_helper_lib(): try: # If it's already loaded, just return it. return _load_python_helper_lib.__lib__ except AttributeError: pass with _lock: try: return _load_python_helper_lib.__lib__ except AttributeError: pass lib = _load_python_helper_lib_uncached() _load_python_helper_lib.__lib__ = lib return lib def get_python_helper_lib_filename(): # Note: we have an independent (and similar -- but not equal) version of this method in # `add_code_to_python_process.py` which should be kept synchronized with this one (we do a copy # because the `pydevd_attach_to_process` is mostly independent and shouldn't be imported in the # debugger -- the only situation where it's imported is if the user actually does an attach to # process, through `attach_pydevd.py`, but this should usually be called from the IDE directly # and not from the debugger). libdir = os.path.join(os.path.dirname(__file__), 'pydevd_attach_to_process') arch = '' if IS_WINDOWS: # prefer not using platform.machine() when possible (it's a bit heavyweight as it may # spawn a subprocess). arch = os.environ.get("PROCESSOR_ARCHITEW6432", os.environ.get('PROCESSOR_ARCHITECTURE', '')) if not arch: arch = platform.machine() if not arch: pydev_log.info('platform.machine() did not return valid value.') # This shouldn't happen... return None if IS_WINDOWS: extension = '.dll' suffix_64 = 'amd64' suffix_32 = 'x86' elif IS_LINUX: extension = '.so' suffix_64 = 'amd64' suffix_32 = 'x86' elif IS_MAC: extension = '.dylib' suffix_64 = 'x86_64' suffix_32 = 'x86' else: pydev_log.info('Unable to set trace to all threads in platform: %s', sys.platform) return None if arch.lower() not in ('amd64', 'x86', 'x86_64', 'i386', 'x86'): # We don't support this processor by default. Still, let's support the case where the # user manually compiled it himself with some heuristics. # # Ideally the user would provide a library in the format: "attach_<arch>.<extension>" # based on the way it's currently compiled -- see: # - windows/compile_windows.bat # - linux_and_mac/compile_linux.sh # - linux_and_mac/compile_mac.sh try: found = [name for name in os.listdir(libdir) if name.startswith('attach_') and name.endswith(extension)] except: if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1: # There is no need to show this unless debug tracing is enabled. pydev_log.exception('Error listing dir: %s', libdir) return None expected_name = 'attach_' + arch + extension expected_name_linux = 'attach_linux_' + arch + extension filename = None if expected_name in found: # Heuristic: user compiled with "attach_<arch>.<extension>" filename = os.path.join(libdir, expected_name) elif IS_LINUX and expected_name_linux in found: # Heuristic: user compiled with "attach_linux_<arch>.<extension>" filename = os.path.join(libdir, expected_name_linux) elif len(found) == 1: # Heuristic: user removed all libraries and just left his own lib. filename = os.path.join(libdir, found[0]) else: # Heuristic: there's one additional library which doesn't seem to be our own. Find the odd one. filtered = [name for name in found if not name.endswith((suffix_64 + extension, suffix_32 + extension))] if len(filtered) == 1: # If more than one is available we can't be sure... filename = os.path.join(libdir, found[0]) if filename is None: pydev_log.info( 'Unable to set trace to all threads in arch: %s (did not find a %s lib in %s).', arch, expected_name, libdir ) return None pydev_log.info('Using %s lib in arch: %s.', filename, arch) else: # Happy path for which we have pre-compiled binaries. if IS_64BIT_PROCESS: suffix = suffix_64 else: suffix = suffix_32 if IS_WINDOWS or IS_MAC: # just the extension changes prefix = 'attach_' elif IS_LINUX: # prefix = 'attach_linux_' # historically it has a different name else: pydev_log.info('Unable to set trace to all threads in platform: %s', sys.platform) return None filename = os.path.join(libdir, '%s%s%s' % (prefix, suffix, extension)) if not os.path.exists(filename): pydev_log.critical('Expected: %s to exist.', filename) return None return filename def _load_python_helper_lib_uncached(): if (not IS_CPYTHON or sys.version_info[:2] > (3, 11) or hasattr(sys, 'gettotalrefcount') or LOAD_NATIVE_LIB_FLAG in ENV_FALSE_LOWER_VALUES): pydev_log.info('Helper lib to set tracing to all threads not loaded.') return None try: filename = get_python_helper_lib_filename() if filename is None: return None # Load as pydll so that we don't release the gil. lib = ctypes.pydll.LoadLibrary(filename) pydev_log.info('Successfully Loaded helper lib to set tracing to all threads.') return lib except: if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1: # Only show message if tracing is on (we don't have pre-compiled # binaries for all architectures -- i.e.: ARM). pydev_log.exception('Error loading: %s', filename) return None def set_trace_to_threads(tracing_func, thread_idents=None, create_dummy_thread=True): assert tracing_func is not None ret = 0 # Note: use sys._current_frames() keys to get the thread ids because it'll return # thread ids created in C/C++ where there's user code running, unlike the APIs # from the threading module which see only threads created through it (unless # a call for threading.current_thread() was previously done in that thread, # in which case a dummy thread would've been created for it). if thread_idents is None: thread_idents = set(sys._current_frames().keys()) for t in threading.enumerate(): # PY-44778: ignore pydevd threads and also add any thread that wasn't found on # sys._current_frames() as some existing threads may not appear in # sys._current_frames() but may be available through the `threading` module. if getattr(t, 'pydev_do_not_trace', False): thread_idents.discard(t.ident) else: thread_idents.add(t.ident) curr_ident = thread.get_ident() curr_thread = threading._active.get(curr_ident) if curr_ident in thread_idents and len(thread_idents) != 1: # The current thread must be updated first (because we need to set # the reference to `curr_thread`). thread_idents = list(thread_idents) thread_idents.remove(curr_ident) thread_idents.insert(0, curr_ident) for thread_ident in thread_idents: # If that thread is not available in the threading module we also need to create a # dummy thread for it (otherwise it'll be invisible to the debugger). if create_dummy_thread: if thread_ident not in threading._active: class _DummyThread(threading._DummyThread): def _set_ident(self): # Note: Hack to set the thread ident that we want. self._ident = thread_ident t = _DummyThread() # Reset to the base class (don't expose our own version of the class). t.__class__ = threading._DummyThread if thread_ident == curr_ident: curr_thread = t with threading._active_limbo_lock: # On Py2 it'll put in active getting the current indent, not using the # ident that was set, so, we have to update it (should be harmless on Py3 # so, do it always). threading._active[thread_ident] = t threading._active[curr_ident] = curr_thread if t.ident != thread_ident: # Check if it actually worked. pydev_log.critical('pydevd: creation of _DummyThread with fixed thread ident did not succeed.') # Some (ptvsd) tests failed because of this, so, leave it always disabled for now. # show_debug_info = 1 if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1 else 0 show_debug_info = 0 # Hack to increase _Py_TracingPossible. # See comments on py_custom_pyeval_settrace.hpp proceed = thread.allocate_lock() proceed.acquire() def dummy_trace(frame, event, arg): return dummy_trace def increase_tracing_count(): set_trace = TracingFunctionHolder._original_tracing or sys.settrace set_trace(dummy_trace) proceed.release() start_new_thread = pydev_monkey.get_original_start_new_thread(thread) start_new_thread(increase_tracing_count, ()) proceed.acquire() # Only proceed after the release() is done. proceed = None # Note: The set_trace_func is not really used anymore in the C side. set_trace_func = TracingFunctionHolder._original_tracing or sys.settrace lib = _load_python_helper_lib() if lib is None: # This is the case if it's not CPython. pydev_log.info('Unable to load helper lib to set tracing to all threads (unsupported python vm).') ret = -1 else: try: result = lib.AttachDebuggerTracing( ctypes.c_int(show_debug_info), ctypes.py_object(set_trace_func), ctypes.py_object(tracing_func), ctypes.c_uint(thread_ident), ctypes.py_object(None), ) except: if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1: # There is no need to show this unless debug tracing is enabled. pydev_log.exception('Error attaching debugger tracing') ret = -1 else: if result != 0: pydev_log.info('Unable to set tracing for existing thread. Result: %s', result) ret = result return ret
14,804
Python
38.375
122
0.613753
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/setup_pydevd_cython.py
''' A simpler setup version just to compile the speedup module. It should be used as: python setup_pydevd_cython build_ext --inplace Note: the .c file and other generated files are regenerated from the .pyx file by running "python build_tools/build.py" ''' import os import sys from setuptools import setup os.chdir(os.path.dirname(os.path.abspath(__file__))) IS_PY36_OR_GREATER = sys.version_info > (3, 6) TODO_PY311 = sys.version_info > (3, 11) def process_args(): extension_folder = None target_pydevd_name = None target_frame_eval = None force_cython = False for i, arg in enumerate(sys.argv[:]): if arg == '--build-lib': extension_folder = sys.argv[i + 1] # It shouldn't be removed from sys.argv (among with --build-temp) because they're passed further to setup() if arg.startswith('--target-pyd-name='): sys.argv.remove(arg) target_pydevd_name = arg[len('--target-pyd-name='):] if arg.startswith('--target-pyd-frame-eval='): sys.argv.remove(arg) target_frame_eval = arg[len('--target-pyd-frame-eval='):] if arg == '--force-cython': sys.argv.remove(arg) force_cython = True return extension_folder, target_pydevd_name, target_frame_eval, force_cython def process_template_lines(template_lines): # Create 2 versions of the template, one for Python 3.8 and another for Python 3.9 for version in ('38', '39'): yield '### WARNING: GENERATED CODE, DO NOT EDIT!' yield '### WARNING: GENERATED CODE, DO NOT EDIT!' yield '### WARNING: GENERATED CODE, DO NOT EDIT!' for line in template_lines: if version == '38': line = line.replace('get_bytecode_while_frame_eval(PyFrameObject * frame_obj, int exc)', 'get_bytecode_while_frame_eval_38(PyFrameObject * frame_obj, int exc)') line = line.replace('CALL_EvalFrameDefault', 'CALL_EvalFrameDefault_38(frame_obj, exc)') else: # 3.9 line = line.replace('get_bytecode_while_frame_eval(PyFrameObject * frame_obj, int exc)', 'get_bytecode_while_frame_eval_39(PyThreadState* tstate, PyFrameObject * frame_obj, int exc)') line = line.replace('CALL_EvalFrameDefault', 'CALL_EvalFrameDefault_39(tstate, frame_obj, exc)') yield line yield '### WARNING: GENERATED CODE, DO NOT EDIT!' yield '### WARNING: GENERATED CODE, DO NOT EDIT!' yield '### WARNING: GENERATED CODE, DO NOT EDIT!' yield '' yield '' def process_template_file(contents): ret = [] template_lines = [] append_to = ret for line in contents.splitlines(keepends=False): if line.strip() == '### TEMPLATE_START': append_to = template_lines elif line.strip() == '### TEMPLATE_END': append_to = ret for line in process_template_lines(template_lines): ret.append(line) else: append_to.append(line) return '\n'.join(ret) def build_extension(dir_name, extension_name, target_pydevd_name, force_cython, extended=False, has_pxd=False, template=False): pyx_file = os.path.join(os.path.dirname(__file__), dir_name, "%s.pyx" % (extension_name,)) if template: pyx_template_file = os.path.join(os.path.dirname(__file__), dir_name, "%s.template.pyx" % (extension_name,)) with open(pyx_template_file, 'r') as stream: contents = stream.read() contents = process_template_file(contents) with open(pyx_file, 'w') as stream: stream.write(contents) if target_pydevd_name != extension_name: # It MUST be there in this case! # (otherwise we'll have unresolved externals because the .c file had another name initially). import shutil # We must force cython in this case (but only in this case -- for the regular setup in the user machine, we # should always compile the .c file). force_cython = True new_pyx_file = os.path.join(os.path.dirname(__file__), dir_name, "%s.pyx" % (target_pydevd_name,)) new_c_file = os.path.join(os.path.dirname(__file__), dir_name, "%s.c" % (target_pydevd_name,)) shutil.copy(pyx_file, new_pyx_file) pyx_file = new_pyx_file if has_pxd: pxd_file = os.path.join(os.path.dirname(__file__), dir_name, "%s.pxd" % (extension_name,)) new_pxd_file = os.path.join(os.path.dirname(__file__), dir_name, "%s.pxd" % (target_pydevd_name,)) shutil.copy(pxd_file, new_pxd_file) assert os.path.exists(pyx_file) try: c_files = [os.path.join(dir_name, "%s.c" % target_pydevd_name), ] if force_cython: for c_file in c_files: try: os.remove(c_file) except: pass from Cython.Build import cythonize # @UnusedImport # Generate the .c files in cythonize (will not compile at this point). target = "%s/%s.pyx" % (dir_name, target_pydevd_name,) cythonize([target]) # Workarounds needed in CPython 3.8 and 3.9 to access PyInterpreterState.eval_frame. for c_file in c_files: with open(c_file, 'r') as stream: c_file_contents = stream.read() if '#include "internal/pycore_gc.h"' not in c_file_contents: c_file_contents = c_file_contents.replace('#include "Python.h"', '''#include "Python.h" #if PY_VERSION_HEX >= 0x03090000 #include "internal/pycore_gc.h" #include "internal/pycore_interp.h" #endif ''') if '#include "internal/pycore_pystate.h"' not in c_file_contents: c_file_contents = c_file_contents.replace('#include "pystate.h"', '''#include "pystate.h" #if PY_VERSION_HEX >= 0x03080000 #include "internal/pycore_pystate.h" #endif ''') # We want the same output on Windows and Linux. c_file_contents = c_file_contents.replace('\r\n', '\n').replace('\r', '\n') c_file_contents = c_file_contents.replace(r'_pydevd_frame_eval\\release_mem.h', '_pydevd_frame_eval/release_mem.h') c_file_contents = c_file_contents.replace(r'_pydevd_frame_eval\\pydevd_frame_evaluator.pyx', '_pydevd_frame_eval/pydevd_frame_evaluator.pyx') c_file_contents = c_file_contents.replace(r'_pydevd_bundle\\pydevd_cython.pxd', '_pydevd_bundle/pydevd_cython.pxd') c_file_contents = c_file_contents.replace(r'_pydevd_bundle\\pydevd_cython.pyx', '_pydevd_bundle/pydevd_cython.pyx') with open(c_file, 'w') as stream: stream.write(c_file_contents) # Always compile the .c (and not the .pyx) file (which we should keep up-to-date by running build_tools/build.py). from distutils.extension import Extension extra_compile_args = [] extra_link_args = [] if 'linux' in sys.platform: # Enabling -flto brings executable from 4MB to 0.56MB and -Os to 0.41MB # Profiling shows an execution around 3-5% slower with -Os vs -O3, # so, kept only -flto. extra_compile_args = ["-flto", "-O3"] extra_link_args = extra_compile_args[:] # Note: also experimented with profile-guided optimization. The executable # size became a bit smaller (from 0.56MB to 0.5MB) but this would add an # extra step to run the debugger to obtain the optimizations # so, skipped it for now (note: the actual benchmarks time was in the # margin of a 0-1% improvement, which is probably not worth it for # speed increments). # extra_compile_args = ["-flto", "-fprofile-generate"] # ... Run benchmarks ... # extra_compile_args = ["-flto", "-fprofile-use", "-fprofile-correction"] elif 'win32' in sys.platform: pass # uncomment to generate pdbs for visual studio. # extra_compile_args=["-Zi", "/Od"] # extra_link_args=["-debug"] kwargs = {} if extra_link_args: kwargs['extra_link_args'] = extra_link_args if extra_compile_args: kwargs['extra_compile_args'] = extra_compile_args ext_modules = [ Extension( "%s%s.%s" % (dir_name, "_ext" if extended else "", target_pydevd_name,), c_files, **kwargs )] # This is needed in CPython 3.8 to be able to include internal/pycore_pystate.h # (needed to set PyInterpreterState.eval_frame). for module in ext_modules: module.define_macros = [('Py_BUILD_CORE_MODULE', '1')] setup( name='Cythonize', ext_modules=ext_modules ) finally: if target_pydevd_name != extension_name: try: os.remove(new_pyx_file) except: import traceback traceback.print_exc() try: os.remove(new_c_file) except: import traceback traceback.print_exc() if has_pxd: try: os.remove(new_pxd_file) except: import traceback traceback.print_exc() extension_folder, target_pydevd_name, target_frame_eval, force_cython = process_args() extension_name = "pydevd_cython" if target_pydevd_name is None: target_pydevd_name = extension_name build_extension("_pydevd_bundle", extension_name, target_pydevd_name, force_cython, extension_folder, True) if IS_PY36_OR_GREATER and not TODO_PY311: extension_name = "pydevd_frame_evaluator" if target_frame_eval is None: target_frame_eval = extension_name build_extension("_pydevd_frame_eval", extension_name, target_frame_eval, force_cython, extension_folder, True, template=True) if extension_folder: os.chdir(extension_folder) for folder in [file for file in os.listdir(extension_folder) if file != 'build' and os.path.isdir(os.path.join(extension_folder, file))]: file = os.path.join(folder, "__init__.py") if not os.path.exists(file): open(file, 'a').close()
10,410
Python
40.478087
199
0.592219
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd.py
''' Entry point module (keep at root): This module starts the debugger. ''' import sys # @NoMove if sys.version_info[:2] < (3, 6): raise RuntimeError('The PyDev.Debugger requires Python 3.6 onwards to be run. If you need to use an older Python version, use an older version of the debugger.') import os try: # Just empty packages to check if they're in the PYTHONPATH. import _pydev_bundle except ImportError: # On the first import of a pydevd module, add pydevd itself to the PYTHONPATH # if its dependencies cannot be imported. sys.path.append(os.path.dirname(os.path.abspath(__file__))) import _pydev_bundle # Import this first as it'll check for shadowed modules and will make sure that we import # things as needed for gevent. from _pydevd_bundle import pydevd_constants import atexit import dis import io from collections import defaultdict from contextlib import contextmanager from functools import partial import itertools import traceback import weakref import getpass as getpass_mod import functools import pydevd_file_utils from _pydev_bundle import pydev_imports, pydev_log from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding from _pydev_bundle.pydev_is_thread_alive import is_thread_alive from _pydev_bundle.pydev_override import overrides from _pydev_bundle._pydev_saved_modules import threading, time, thread from _pydevd_bundle import pydevd_extension_utils, pydevd_frame_utils from _pydevd_bundle.pydevd_filtering import FilesFiltering, glob_matches_path from _pydevd_bundle import pydevd_io, pydevd_vm_type from _pydevd_bundle import pydevd_utils from _pydevd_bundle import pydevd_runpy from _pydev_bundle.pydev_console_utils import DebugConsoleStdIn from _pydevd_bundle.pydevd_additional_thread_info import set_additional_thread_info from _pydevd_bundle.pydevd_breakpoints import ExceptionBreakpoint, get_exception_breakpoint from _pydevd_bundle.pydevd_comm_constants import (CMD_THREAD_SUSPEND, CMD_STEP_INTO, CMD_SET_BREAK, CMD_STEP_INTO_MY_CODE, CMD_STEP_OVER, CMD_SMART_STEP_INTO, CMD_RUN_TO_LINE, CMD_SET_NEXT_STATEMENT, CMD_STEP_RETURN, CMD_ADD_EXCEPTION_BREAK, CMD_STEP_RETURN_MY_CODE, CMD_STEP_OVER_MY_CODE, constant_to_str, CMD_STEP_INTO_COROUTINE) from _pydevd_bundle.pydevd_constants import (get_thread_id, get_current_thread_id, DebugInfoHolder, PYTHON_SUSPEND, STATE_SUSPEND, STATE_RUN, get_frame, clear_cached_thread_id, INTERACTIVE_MODE_AVAILABLE, SHOW_DEBUG_INFO_ENV, NULL, NO_FTRACE, IS_IRONPYTHON, JSON_PROTOCOL, IS_CPYTHON, HTTP_JSON_PROTOCOL, USE_CUSTOM_SYS_CURRENT_FRAMES_MAP, call_only_once, ForkSafeLock, IGNORE_BASENAMES_STARTING_WITH, EXCEPTION_TYPE_UNHANDLED, SUPPORT_GEVENT, PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING, PYDEVD_IPYTHON_CONTEXT) from _pydevd_bundle.pydevd_defaults import PydevdCustomization # Note: import alias used on pydev_monkey. from _pydevd_bundle.pydevd_custom_frames import CustomFramesContainer, custom_frames_container_init from _pydevd_bundle.pydevd_dont_trace_files import DONT_TRACE, PYDEV_FILE, LIB_FILE, DONT_TRACE_DIRS from _pydevd_bundle.pydevd_extension_api import DebuggerEventHandler from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, remove_exception_from_frame from _pydevd_bundle.pydevd_net_command_factory_xml import NetCommandFactory from _pydevd_bundle.pydevd_trace_dispatch import ( trace_dispatch as _trace_dispatch, global_cache_skips, global_cache_frame_skips, fix_top_level_trace_and_get_trace_func) from _pydevd_bundle.pydevd_utils import save_main_module, is_current_thread_main_thread, \ import_attr_from_module from _pydevd_frame_eval.pydevd_frame_eval_main import ( frame_eval_func, dummy_trace_dispatch) import pydev_ipython # @UnusedImport from _pydevd_bundle.pydevd_source_mapping import SourceMapping from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_concurrency_logger import ThreadingLogger, AsyncioLogger, send_concurrency_message, cur_time from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_thread_wrappers import wrap_threads from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame, NORM_PATHS_AND_BASE_CONTAINER from pydevd_file_utils import get_fullname, get_package_dir from os.path import abspath as os_path_abspath import pydevd_tracing from _pydevd_bundle.pydevd_comm import (InternalThreadCommand, InternalThreadCommandForAnyThread, create_server_socket, FSNotifyThread) from _pydevd_bundle.pydevd_comm import(InternalConsoleExec, _queue, ReaderThread, GetGlobalDebugger, get_global_debugger, set_global_debugger, WriterThread, start_client, start_server, InternalGetBreakpointException, InternalSendCurrExceptionTrace, InternalSendCurrExceptionTraceProceeded) from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread, mark_as_pydevd_daemon_thread from _pydevd_bundle.pydevd_process_net_command_json import PyDevJsonCommandProcessor from _pydevd_bundle.pydevd_process_net_command import process_net_command from _pydevd_bundle.pydevd_net_command import NetCommand, NULL_NET_COMMAND from _pydevd_bundle.pydevd_breakpoints import stop_on_unhandled_exception from _pydevd_bundle.pydevd_collect_bytecode_info import collect_try_except_info, collect_return_info, collect_try_except_info_from_source from _pydevd_bundle.pydevd_suspended_frames import SuspendedFramesManager from socket import SHUT_RDWR from _pydevd_bundle.pydevd_api import PyDevdAPI from _pydevd_bundle.pydevd_timeout import TimeoutTracker from _pydevd_bundle.pydevd_thread_lifecycle import suspend_all_threads, mark_thread_suspended pydevd_gevent_integration = None if SUPPORT_GEVENT: try: from _pydevd_bundle import pydevd_gevent_integration except: pydev_log.exception( 'pydevd: GEVENT_SUPPORT is set but gevent is not available in the environment.\n' 'Please unset GEVENT_SUPPORT from the environment variables or install gevent.') else: pydevd_gevent_integration.log_gevent_debug_info() if USE_CUSTOM_SYS_CURRENT_FRAMES_MAP: from _pydevd_bundle.pydevd_constants import constructed_tid_to_last_frame __version_info__ = (2, 8, 0) __version_info_str__ = [] for v in __version_info__: __version_info_str__.append(str(v)) __version__ = '.'.join(__version_info_str__) # IMPORTANT: pydevd_constants must be the 1st thing defined because it'll keep a reference to the original sys._getframe def install_breakpointhook(pydevd_breakpointhook=None): if pydevd_breakpointhook is None: def pydevd_breakpointhook(*args, **kwargs): hookname = os.getenv('PYTHONBREAKPOINT') if ( hookname is not None and len(hookname) > 0 and hasattr(sys, '__breakpointhook__') and sys.__breakpointhook__ != pydevd_breakpointhook ): sys.__breakpointhook__(*args, **kwargs) else: settrace(*args, **kwargs) if sys.version_info[0:2] >= (3, 7): # There are some choices on how to provide the breakpoint hook. Namely, we can provide a # PYTHONBREAKPOINT which provides the import path for a method to be executed or we # can override sys.breakpointhook. # pydevd overrides sys.breakpointhook instead of providing an environment variable because # it's possible that the debugger starts the user program but is not available in the # PYTHONPATH (and would thus fail to be imported if PYTHONBREAKPOINT was set to pydevd.settrace). # Note that the implementation still takes PYTHONBREAKPOINT in account (so, if it was provided # by someone else, it'd still work). sys.breakpointhook = pydevd_breakpointhook else: if sys.version_info[0] >= 3: import builtins as __builtin__ # Py3 noqa else: import __builtin__ # noqa # In older versions, breakpoint() isn't really available, so, install the hook directly # in the builtins. __builtin__.breakpoint = pydevd_breakpointhook sys.__breakpointhook__ = pydevd_breakpointhook # Install the breakpoint hook at import time. install_breakpointhook() from _pydevd_bundle.pydevd_plugin_utils import PluginManager threadingEnumerate = threading.enumerate threadingCurrentThread = threading.current_thread try: 'dummy'.encode('utf-8') # Added because otherwise Jython 2.2.1 wasn't finding the encoding (if it wasn't loaded in the main thread). except: pass _global_redirect_stdout_to_server = False _global_redirect_stderr_to_server = False file_system_encoding = getfilesystemencoding() _CACHE_FILE_TYPE = {} pydev_log.debug('Using GEVENT_SUPPORT: %s', pydevd_constants.SUPPORT_GEVENT) pydev_log.debug('Using GEVENT_SHOW_PAUSED_GREENLETS: %s', pydevd_constants.GEVENT_SHOW_PAUSED_GREENLETS) pydev_log.debug('pydevd __file__: %s', os.path.abspath(__file__)) pydev_log.debug('Using PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING: %s', pydevd_constants.PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING) if pydevd_constants.PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING: pydev_log.debug('PYDEVD_IPYTHON_CONTEXT: %s', pydevd_constants.PYDEVD_IPYTHON_CONTEXT) #======================================================================================================================= # PyDBCommandThread #======================================================================================================================= class PyDBCommandThread(PyDBDaemonThread): def __init__(self, py_db): PyDBDaemonThread.__init__(self, py_db) self._py_db_command_thread_event = py_db._py_db_command_thread_event self.name = 'pydevd.CommandThread' @overrides(PyDBDaemonThread._on_run) def _on_run(self): # Delay a bit this initialization to wait for the main program to start. self._py_db_command_thread_event.wait(0.3) if self._kill_received: return try: while not self._kill_received: try: self.py_db.process_internal_commands() except: pydev_log.info('Finishing debug communication...(2)') self._py_db_command_thread_event.clear() self._py_db_command_thread_event.wait(0.3) except: try: pydev_log.debug(sys.exc_info()[0]) except: # In interpreter shutdown many things can go wrong (any module variables may # be None, streams can be closed, etc). pass # only got this error in interpreter shutdown # pydev_log.info('Finishing debug communication...(3)') @overrides(PyDBDaemonThread.do_kill_pydev_thread) def do_kill_pydev_thread(self): PyDBDaemonThread.do_kill_pydev_thread(self) # Set flag so that it can exit before the usual timeout. self._py_db_command_thread_event.set() #======================================================================================================================= # CheckAliveThread # Non-daemon thread: guarantees that all data is written even if program is finished #======================================================================================================================= class CheckAliveThread(PyDBDaemonThread): def __init__(self, py_db): PyDBDaemonThread.__init__(self, py_db) self.name = 'pydevd.CheckAliveThread' self.daemon = False self._wait_event = threading.Event() @overrides(PyDBDaemonThread._on_run) def _on_run(self): py_db = self.py_db def can_exit(): with py_db._main_lock: # Note: it's important to get the lock besides checking that it's empty (this # means that we're not in the middle of some command processing). writer = py_db.writer writer_empty = writer is not None and writer.empty() return not py_db.has_user_threads_alive() and writer_empty try: while not self._kill_received: self._wait_event.wait(0.3) if can_exit(): break py_db.check_output_redirect() if can_exit(): pydev_log.debug("No threads alive, finishing debug session") py_db.dispose_and_kill_all_pydevd_threads() except: pydev_log.exception() def join(self, timeout=None): # If someone tries to join this thread, mark it to be killed. # This is the case for CherryPy when auto-reload is turned on. self.do_kill_pydev_thread() PyDBDaemonThread.join(self, timeout=timeout) @overrides(PyDBDaemonThread.do_kill_pydev_thread) def do_kill_pydev_thread(self): PyDBDaemonThread.do_kill_pydev_thread(self) # Set flag so that it can exit before the usual timeout. self._wait_event.set() class AbstractSingleNotificationBehavior(object): ''' The basic usage should be: # Increment the request time for the suspend. single_notification_behavior.increment_suspend_time() # Notify that this is a pause request (when a pause, not a breakpoint). single_notification_behavior.on_pause() # Mark threads to be suspended. set_suspend(...) # On do_wait_suspend, use notify_thread_suspended: def do_wait_suspend(...): with single_notification_behavior.notify_thread_suspended(thread_id): ... ''' __slots__ = [ '_last_resume_notification_time', '_last_suspend_notification_time', '_lock', '_next_request_time', '_suspend_time_request', '_suspended_thread_ids', '_pause_requested', '_py_db', ] NOTIFY_OF_PAUSE_TIMEOUT = .5 def __init__(self, py_db): self._py_db = weakref.ref(py_db) self._next_request_time = partial(next, itertools.count()) self._last_suspend_notification_time = -1 self._last_resume_notification_time = -1 self._suspend_time_request = self._next_request_time() self._lock = thread.allocate_lock() self._suspended_thread_ids = set() self._pause_requested = False def send_suspend_notification(self, thread_id, stop_reason): raise AssertionError('abstract: subclasses must override.') def send_resume_notification(self, thread_id): raise AssertionError('abstract: subclasses must override.') def increment_suspend_time(self): with self._lock: self._suspend_time_request = self._next_request_time() def on_pause(self): # Upon a pause, we should force sending new suspend notifications # if no notification is sent after some time and there's some thread already stopped. with self._lock: self._pause_requested = True global_suspend_time = self._suspend_time_request py_db = self._py_db() if py_db is not None: py_db.timeout_tracker.call_on_timeout( self.NOTIFY_OF_PAUSE_TIMEOUT, self._notify_after_timeout, kwargs={'global_suspend_time': global_suspend_time} ) def _notify_after_timeout(self, global_suspend_time): with self._lock: if self._suspended_thread_ids: if global_suspend_time > self._last_suspend_notification_time: self._last_suspend_notification_time = global_suspend_time # Notify about any thread which is currently suspended. pydev_log.info('Sending suspend notification after timeout.') self.send_suspend_notification(next(iter(self._suspended_thread_ids)), CMD_THREAD_SUSPEND) def on_thread_suspend(self, thread_id, stop_reason): with self._lock: pause_requested = self._pause_requested if pause_requested: # When a suspend notification is sent, reset the pause flag. self._pause_requested = False self._suspended_thread_ids.add(thread_id) # CMD_THREAD_SUSPEND should always be a side-effect of a break, so, only # issue for a CMD_THREAD_SUSPEND if a pause is pending. if stop_reason != CMD_THREAD_SUSPEND or pause_requested: if self._suspend_time_request > self._last_suspend_notification_time: pydev_log.info('Sending suspend notification.') self._last_suspend_notification_time = self._suspend_time_request self.send_suspend_notification(thread_id, stop_reason) else: pydev_log.info( 'Suspend not sent (it was already sent). Last suspend % <= Last resume %s', self._last_suspend_notification_time, self._last_resume_notification_time, ) else: pydev_log.info( 'Suspend not sent because stop reason is thread suspend and pause was not requested.', ) def on_thread_resume(self, thread_id): # on resume (step, continue all): with self._lock: self._suspended_thread_ids.remove(thread_id) if self._last_resume_notification_time < self._last_suspend_notification_time: pydev_log.info('Sending resume notification.') self._last_resume_notification_time = self._last_suspend_notification_time self.send_resume_notification(thread_id) else: pydev_log.info( 'Resume not sent (it was already sent). Last resume %s >= Last suspend %s', self._last_resume_notification_time, self._last_suspend_notification_time, ) @contextmanager def notify_thread_suspended(self, thread_id, stop_reason): self.on_thread_suspend(thread_id, stop_reason) try: yield # At this point the thread must be actually suspended. finally: self.on_thread_resume(thread_id) class ThreadsSuspendedSingleNotification(AbstractSingleNotificationBehavior): __slots__ = AbstractSingleNotificationBehavior.__slots__ + [ 'multi_threads_single_notification', '_callbacks', '_callbacks_lock'] def __init__(self, py_db): AbstractSingleNotificationBehavior.__init__(self, py_db) # If True, pydevd will send a single notification when all threads are suspended/resumed. self.multi_threads_single_notification = False self._callbacks_lock = threading.Lock() self._callbacks = [] def add_on_resumed_callback(self, callback): with self._callbacks_lock: self._callbacks.append(callback) @overrides(AbstractSingleNotificationBehavior.send_resume_notification) def send_resume_notification(self, thread_id): py_db = self._py_db() if py_db is not None: py_db.writer.add_command(py_db.cmd_factory.make_thread_resume_single_notification(thread_id)) with self._callbacks_lock: callbacks = self._callbacks self._callbacks = [] for callback in callbacks: callback() @overrides(AbstractSingleNotificationBehavior.send_suspend_notification) def send_suspend_notification(self, thread_id, stop_reason): py_db = self._py_db() if py_db is not None: py_db.writer.add_command(py_db.cmd_factory.make_thread_suspend_single_notification(py_db, thread_id, stop_reason)) @overrides(AbstractSingleNotificationBehavior.notify_thread_suspended) @contextmanager def notify_thread_suspended(self, thread_id, stop_reason): if self.multi_threads_single_notification: with AbstractSingleNotificationBehavior.notify_thread_suspended(self, thread_id, stop_reason): yield else: yield class _Authentication(object): __slots__ = ['access_token', 'client_access_token', '_authenticated', '_wrong_attempts'] def __init__(self): # A token to be send in the command line or through the settrace api -- when such token # is given, the first message sent to the IDE must pass the same token to authenticate. # Note that if a disconnect is sent, the same message must be resent to authenticate. self.access_token = None # This token is the one that the client requires to accept a connection from pydevd # (it's stored here and just passed back when required, it's not used internally # for anything else). self.client_access_token = None self._authenticated = None self._wrong_attempts = 0 def is_authenticated(self): if self._authenticated is None: return self.access_token is None return self._authenticated def login(self, access_token): if self._wrong_attempts >= 10: # A user can fail to authenticate at most 10 times. return self._authenticated = access_token == self.access_token if not self._authenticated: self._wrong_attempts += 1 else: self._wrong_attempts = 0 def logout(self): self._authenticated = None self._wrong_attempts = 0 class PyDB(object): """ Main debugging class Lots of stuff going on here: PyDB starts two threads on startup that connect to remote debugger (RDB) The threads continuously read & write commands to RDB. PyDB communicates with these threads through command queues. Every RDB command is processed by calling process_net_command. Every PyDB net command is sent to the net by posting NetCommand to WriterThread queue Some commands need to be executed on the right thread (suspend/resume & friends) These are placed on the internal command queue. """ # Direct child pids which should not be terminated when terminating processes. # Note: class instance because it should outlive PyDB instances. dont_terminate_child_pids = set() def __init__(self, set_as_global=True): if set_as_global: pydevd_tracing.replace_sys_set_trace_func() self.authentication = _Authentication() self.reader = None self.writer = None self._fsnotify_thread = None self.created_pydb_daemon_threads = {} self._waiting_for_connection_thread = None self._on_configuration_done_event = threading.Event() self.check_alive_thread = None self.py_db_command_thread = None self.quitting = None self.cmd_factory = NetCommandFactory() self._cmd_queue = defaultdict(_queue.Queue) # Key is thread id or '*', value is Queue self.suspended_frames_manager = SuspendedFramesManager() self._files_filtering = FilesFiltering() self.timeout_tracker = TimeoutTracker(self) # Note: when the source mapping is changed we also have to clear the file types cache # (because if a given file is a part of the project or not may depend on it being # defined in the source mapping). self.source_mapping = SourceMapping(on_source_mapping_changed=self._clear_filters_caches) # Determines whether we should terminate child processes when asked to terminate. self.terminate_child_processes = True # These are the breakpoints received by the PyDevdAPI. They are meant to store # the breakpoints in the api -- its actual contents are managed by the api. self.api_received_breakpoints = {} # These are the breakpoints meant to be consumed during runtime. self.breakpoints = {} self.function_breakpoint_name_to_breakpoint = {} # Set communication protocol PyDevdAPI().set_protocol(self, 0, PydevdCustomization.DEFAULT_PROTOCOL) self.variable_presentation = PyDevdAPI.VariablePresentation() # mtime to be raised when breakpoints change self.mtime = 0 self.file_to_id_to_line_breakpoint = {} self.file_to_id_to_plugin_breakpoint = {} # Note: breakpoints dict should not be mutated: a copy should be created # and later it should be assigned back (to prevent concurrency issues). self.break_on_uncaught_exceptions = {} self.break_on_caught_exceptions = {} self.break_on_user_uncaught_exceptions = {} self.ready_to_run = False self._main_lock = thread.allocate_lock() self._lock_running_thread_ids = thread.allocate_lock() self._lock_create_fs_notify = thread.allocate_lock() self._py_db_command_thread_event = threading.Event() if set_as_global: CustomFramesContainer._py_db_command_thread_event = self._py_db_command_thread_event self.pydb_disposed = False self._wait_for_threads_to_finish_called = False self._wait_for_threads_to_finish_called_lock = thread.allocate_lock() self._wait_for_threads_to_finish_called_event = threading.Event() self.terminate_requested = False self._disposed_lock = thread.allocate_lock() self.signature_factory = None self.SetTrace = pydevd_tracing.SetTrace self.skip_on_exceptions_thrown_in_same_context = False self.ignore_exceptions_thrown_in_lines_with_ignore_exception = True # Suspend debugger even if breakpoint condition raises an exception. # May be changed with CMD_PYDEVD_JSON_CONFIG. self.skip_suspend_on_breakpoint_exception = () # By default suspend on any Exception. self.skip_print_breakpoint_exception = () # By default print on any Exception. # By default user can step into properties getter/setter/deleter methods self.disable_property_trace = False self.disable_property_getter_trace = False self.disable_property_setter_trace = False self.disable_property_deleter_trace = False # this is a dict of thread ids pointing to thread ids. Whenever a command is passed to the java end that # acknowledges that a thread was created, the thread id should be passed here -- and if at some time we do not # find that thread alive anymore, we must remove it from this list and make the java side know that the thread # was killed. self._running_thread_ids = {} # Note: also access '_enable_thread_notifications' with '_lock_running_thread_ids' self._enable_thread_notifications = False self._set_breakpoints_with_id = False # This attribute holds the file-> lines which have an @IgnoreException. self.filename_to_lines_where_exceptions_are_ignored = {} # working with plugins (lazily initialized) self.plugin = None self.has_plugin_line_breaks = False self.has_plugin_exception_breaks = False self.thread_analyser = None self.asyncio_analyser = None # The GUI event loop that's going to run. # Possible values: # matplotlib - Whatever GUI backend matplotlib is using. # 'wx'/'qt'/'none'/... - GUI toolkits that have bulitin support. See pydevd_ipython/inputhook.py:24. # Other - A custom function that'll be imported and run. self._gui_event_loop = 'matplotlib' self._installed_gui_support = False self.gui_in_use = False # GUI event loop support in debugger self.activate_gui_function = None # matplotlib support in debugger and debug console self.mpl_hooks_in_debug_console = False self.mpl_modules_for_patching = {} self._filename_to_not_in_scope = {} self.first_breakpoint_reached = False self._exclude_filters_enabled = self._files_filtering.use_exclude_filters() self._is_libraries_filter_enabled = self._files_filtering.use_libraries_filter() self.is_files_filter_enabled = self._exclude_filters_enabled or self._is_libraries_filter_enabled self.show_return_values = False self.remove_return_values_flag = False self.redirect_output = False # Note that besides the `redirect_output` flag, we also need to consider that someone # else is already redirecting (i.e.: debugpy). self.is_output_redirected = False # this flag disables frame evaluation even if it's available self.use_frame_eval = True # If True, pydevd will send a single notification when all threads are suspended/resumed. self._threads_suspended_single_notification = ThreadsSuspendedSingleNotification(self) # If True a step command will do a step in one thread and will also resume all other threads. self.stepping_resumes_all_threads = False self._local_thread_trace_func = threading.local() self._server_socket_ready_event = threading.Event() self._server_socket_name = None # Bind many locals to the debugger because upon teardown those names may become None # in the namespace (and thus can't be relied upon unless the reference was previously # saved). if IS_IRONPYTHON: # A partial() cannot be used in IronPython for sys.settrace. def new_trace_dispatch(frame, event, arg): return _trace_dispatch(self, frame, event, arg) self.trace_dispatch = new_trace_dispatch else: self.trace_dispatch = partial(_trace_dispatch, self) self.fix_top_level_trace_and_get_trace_func = fix_top_level_trace_and_get_trace_func self.frame_eval_func = frame_eval_func self.dummy_trace_dispatch = dummy_trace_dispatch # Note: this is different from pydevd_constants.thread_get_ident because we want Jython # to be None here because it also doesn't have threading._active. try: self.threading_get_ident = threading.get_ident # Python 3 self.threading_active = threading._active except: try: self.threading_get_ident = threading._get_ident # Python 2 noqa self.threading_active = threading._active except: self.threading_get_ident = None # Jython self.threading_active = None self.threading_current_thread = threading.currentThread self.set_additional_thread_info = set_additional_thread_info self.stop_on_unhandled_exception = stop_on_unhandled_exception self.collect_return_info = collect_return_info self.get_exception_breakpoint = get_exception_breakpoint self._dont_trace_get_file_type = DONT_TRACE.get self._dont_trace_dirs_get_file_type = DONT_TRACE_DIRS.get self.PYDEV_FILE = PYDEV_FILE self.LIB_FILE = LIB_FILE self._in_project_scope_cache = {} self._exclude_by_filter_cache = {} self._apply_filter_cache = {} self._ignore_system_exit_codes = set() # DAP related self._dap_messages_listeners = [] if set_as_global: # Set as the global instance only after it's initialized. set_global_debugger(self) # Stop the tracing as the last thing before the actual shutdown for a clean exit. atexit.register(stoptrace) def collect_try_except_info(self, code_obj): filename = code_obj.co_filename try: if os.path.exists(filename): pydev_log.debug('Collecting try..except info from source for %s', filename) try_except_infos = collect_try_except_info_from_source(filename) if try_except_infos: # Filter for the current function max_line = -1 min_line = sys.maxsize for _, line in dis.findlinestarts(code_obj): if line > max_line: max_line = line if line < min_line: min_line = line try_except_infos = [x for x in try_except_infos if min_line <= x.try_line <= max_line] return try_except_infos except: pydev_log.exception('Error collecting try..except info from source (%s)', filename) pydev_log.debug('Collecting try..except info from bytecode for %s', filename) return collect_try_except_info(code_obj) def setup_auto_reload_watcher(self, enable_auto_reload, watch_dirs, poll_target_time, exclude_patterns, include_patterns): try: with self._lock_create_fs_notify: # When setting up, dispose of the previous one (if any). if self._fsnotify_thread is not None: self._fsnotify_thread.do_kill_pydev_thread() self._fsnotify_thread = None if not enable_auto_reload: return exclude_patterns = tuple(exclude_patterns) include_patterns = tuple(include_patterns) def accept_directory(absolute_filename, cache={}): try: return cache[absolute_filename] except: if absolute_filename and absolute_filename[-1] not in ('/', '\\'): # I.e.: for directories we always end with '/' or '\\' so that # we match exclusions such as "**/node_modules/**" absolute_filename += os.path.sep # First include what we want for include_pattern in include_patterns: if glob_matches_path(absolute_filename, include_pattern): cache[absolute_filename] = True return True # Then exclude what we don't want for exclude_pattern in exclude_patterns: if glob_matches_path(absolute_filename, exclude_pattern): cache[absolute_filename] = False return False # By default track all directories not excluded. cache[absolute_filename] = True return True def accept_file(absolute_filename, cache={}): try: return cache[absolute_filename] except: # First include what we want for include_pattern in include_patterns: if glob_matches_path(absolute_filename, include_pattern): cache[absolute_filename] = True return True # Then exclude what we don't want for exclude_pattern in exclude_patterns: if glob_matches_path(absolute_filename, exclude_pattern): cache[absolute_filename] = False return False # By default don't track files not included. cache[absolute_filename] = False return False self._fsnotify_thread = FSNotifyThread(self, PyDevdAPI(), watch_dirs) watcher = self._fsnotify_thread.watcher watcher.accept_directory = accept_directory watcher.accept_file = accept_file watcher.target_time_for_single_scan = poll_target_time watcher.target_time_for_notification = poll_target_time self._fsnotify_thread.start() except: pydev_log.exception('Error setting up auto-reload.') def get_arg_ppid(self): try: setup = SetupHolder.setup if setup: return int(setup.get('ppid', 0)) except: pydev_log.exception('Error getting ppid.') return 0 def wait_for_ready_to_run(self): while not self.ready_to_run: # busy wait until we receive run command self.process_internal_commands() self._py_db_command_thread_event.clear() self._py_db_command_thread_event.wait(0.1) def on_initialize(self): ''' Note: only called when using the DAP (Debug Adapter Protocol). ''' self._on_configuration_done_event.clear() def on_configuration_done(self): ''' Note: only called when using the DAP (Debug Adapter Protocol). ''' self._on_configuration_done_event.set() self._py_db_command_thread_event.set() def is_attached(self): return self._on_configuration_done_event.is_set() def on_disconnect(self): ''' Note: only called when using the DAP (Debug Adapter Protocol). ''' self.authentication.logout() self._on_configuration_done_event.clear() def set_ignore_system_exit_codes(self, ignore_system_exit_codes): assert isinstance(ignore_system_exit_codes, (list, tuple, set)) self._ignore_system_exit_codes = set(ignore_system_exit_codes) def ignore_system_exit_code(self, system_exit_exc): if hasattr(system_exit_exc, 'code'): return system_exit_exc.code in self._ignore_system_exit_codes else: return system_exit_exc in self._ignore_system_exit_codes def block_until_configuration_done(self, cancel=None): if cancel is None: cancel = NULL while not cancel.is_set(): if self._on_configuration_done_event.is_set(): cancel.set() # Set cancel to prevent reuse return self.process_internal_commands() self._py_db_command_thread_event.clear() self._py_db_command_thread_event.wait(1 / 15.) def add_fake_frame(self, thread_id, frame_id, frame): self.suspended_frames_manager.add_fake_frame(thread_id, frame_id, frame) def handle_breakpoint_condition(self, info, pybreakpoint, new_frame): condition = pybreakpoint.condition try: if pybreakpoint.handle_hit_condition(new_frame): return True if not condition: return False return eval(condition, new_frame.f_globals, new_frame.f_locals) except Exception as e: if not isinstance(e, self.skip_print_breakpoint_exception): stack_trace = io.StringIO() etype, value, tb = sys.exc_info() traceback.print_exception(etype, value, tb.tb_next, file=stack_trace) msg = 'Error while evaluating expression in conditional breakpoint: %s\n%s' % ( condition, stack_trace.getvalue()) api = PyDevdAPI() api.send_error_message(self, msg) if not isinstance(e, self.skip_suspend_on_breakpoint_exception): try: # add exception_type and stacktrace into thread additional info etype, value, tb = sys.exc_info() error = ''.join(traceback.format_exception_only(etype, value)) stack = traceback.extract_stack(f=tb.tb_frame.f_back) # On self.set_suspend(thread, CMD_SET_BREAK) this info will be # sent to the client. info.conditional_breakpoint_exception = \ ('Condition:\n' + condition + '\n\nError:\n' + error, stack) except: pydev_log.exception() return True return False finally: etype, value, tb = None, None, None def handle_breakpoint_expression(self, pybreakpoint, info, new_frame): try: try: val = eval(pybreakpoint.expression, new_frame.f_globals, new_frame.f_locals) except: val = sys.exc_info()[1] finally: if val is not None: info.pydev_message = str(val) def _internal_get_file_type(self, abs_real_path_and_basename): basename = abs_real_path_and_basename[-1] if ( basename.startswith(IGNORE_BASENAMES_STARTING_WITH) or abs_real_path_and_basename[0].startswith(IGNORE_BASENAMES_STARTING_WITH) ): # Note: these are the files that are completely ignored (they aren't shown to the user # as user nor library code as it's usually just noise in the frame stack). return self.PYDEV_FILE file_type = self._dont_trace_get_file_type(basename) if file_type is not None: return file_type if basename.startswith('__init__.py'): # i.e.: ignore the __init__ files inside pydevd (the other # files are ignored just by their name). abs_path = abs_real_path_and_basename[0] i = max(abs_path.rfind('/'), abs_path.rfind('\\')) if i: abs_path = abs_path[0:i] i = max(abs_path.rfind('/'), abs_path.rfind('\\')) if i: dirname = abs_path[i + 1:] # At this point, something as: # "my_path\_pydev_runfiles\__init__.py" # is now "_pydev_runfiles". return self._dont_trace_dirs_get_file_type(dirname) return None def dont_trace_external_files(self, abs_path): ''' :param abs_path: The result from get_abs_path_real_path_and_base_from_file or get_abs_path_real_path_and_base_from_frame. :return True : If files should NOT be traced. False: If files should be traced. ''' # By default all external files are traced. Note: this function is expected to # be changed for another function in PyDevdAPI.set_dont_trace_start_end_patterns. return False def get_file_type(self, frame, abs_real_path_and_basename=None, _cache_file_type=_CACHE_FILE_TYPE): ''' :param abs_real_path_and_basename: The result from get_abs_path_real_path_and_base_from_file or get_abs_path_real_path_and_base_from_frame. :return _pydevd_bundle.pydevd_dont_trace_files.PYDEV_FILE: If it's a file internal to the debugger which shouldn't be traced nor shown to the user. _pydevd_bundle.pydevd_dont_trace_files.LIB_FILE: If it's a file in a library which shouldn't be traced. None: If it's a regular user file which should be traced. ''' if abs_real_path_and_basename is None: try: # Make fast path faster! abs_real_path_and_basename = NORM_PATHS_AND_BASE_CONTAINER[frame.f_code.co_filename] except: abs_real_path_and_basename = get_abs_path_real_path_and_base_from_frame(frame) # Note 1: we have to take into account that we may have files as '<string>', and that in # this case the cache key can't rely only on the filename. With the current cache, there's # still a potential miss if 2 functions which have exactly the same content are compiled # with '<string>', but in practice as we only separate the one from python -c from the rest # this shouldn't be a problem in practice. # Note 2: firstlineno added to make misses faster in the first comparison. # Note 3: this cache key is repeated in pydevd_frame_evaluator.pyx:get_func_code_info (for # speedups). cache_key = (frame.f_code.co_firstlineno, abs_real_path_and_basename[0], frame.f_code) try: return _cache_file_type[cache_key] except: if abs_real_path_and_basename[0] == '<string>': # Consider it an untraceable file unless there's no back frame (ignoring # internal files and runpy.py). f = frame.f_back while f is not None: if (self.get_file_type(f) != self.PYDEV_FILE and pydevd_file_utils.basename(f.f_code.co_filename) not in ('runpy.py', '<string>')): # We found some back frame that's not internal, which means we must consider # this a library file. # This is done because we only want to trace files as <string> if they don't # have any back frame (which is the case for python -c ...), for all other # cases we don't want to trace them because we can't show the source to the # user (at least for now...). # Note that we return as a LIB_FILE and not PYDEV_FILE because we still want # to show it in the stack. _cache_file_type[cache_key] = LIB_FILE return LIB_FILE f = f.f_back else: # This is a top-level file (used in python -c), so, trace it as usual... we # still won't be able to show the sources, but some tests require this to work. _cache_file_type[cache_key] = None return None file_type = self._internal_get_file_type(abs_real_path_and_basename) if file_type is None: if self.dont_trace_external_files(abs_real_path_and_basename[0]): file_type = PYDEV_FILE _cache_file_type[cache_key] = file_type return file_type def is_cache_file_type_empty(self): return not _CACHE_FILE_TYPE def get_cache_file_type(self, _cache=_CACHE_FILE_TYPE): # i.e.: Make it local. return _cache def get_thread_local_trace_func(self): try: thread_trace_func = self._local_thread_trace_func.thread_trace_func except AttributeError: thread_trace_func = self.trace_dispatch return thread_trace_func def enable_tracing(self, thread_trace_func=None, apply_to_all_threads=False): ''' Enables tracing. If in regular mode (tracing), will set the tracing function to the tracing function for this thread -- by default it's `PyDB.trace_dispatch`, but after `PyDB.enable_tracing` is called with a `thread_trace_func`, the given function will be the default for the given thread. :param bool apply_to_all_threads: If True we'll set the tracing function in all threads, not only in the current thread. If False only the tracing for the current function should be changed. In general apply_to_all_threads should only be true if this is the first time this function is called on a multi-threaded program (either programmatically or attach to pid). ''' if pydevd_gevent_integration is not None: pydevd_gevent_integration.enable_gevent_integration() if self.frame_eval_func is not None: self.frame_eval_func() pydevd_tracing.SetTrace(self.dummy_trace_dispatch) if IS_CPYTHON and apply_to_all_threads: pydevd_tracing.set_trace_to_threads(self.dummy_trace_dispatch) return if apply_to_all_threads: # If applying to all threads, don't use the local thread trace function. assert thread_trace_func is not None else: if thread_trace_func is None: thread_trace_func = self.get_thread_local_trace_func() else: self._local_thread_trace_func.thread_trace_func = thread_trace_func pydevd_tracing.SetTrace(thread_trace_func) if IS_CPYTHON and apply_to_all_threads: pydevd_tracing.set_trace_to_threads(thread_trace_func) def disable_tracing(self): pydevd_tracing.SetTrace(None) def on_breakpoints_changed(self, removed=False): ''' When breakpoints change, we have to re-evaluate all the assumptions we've made so far. ''' if not self.ready_to_run: # No need to do anything if we're still not running. return self.mtime += 1 if not removed: # When removing breakpoints we can leave tracing as was, but if a breakpoint was added # we have to reset the tracing for the existing functions to be re-evaluated. self.set_tracing_for_untraced_contexts() def set_tracing_for_untraced_contexts(self): # Enable the tracing for existing threads (because there may be frames being executed that # are currently untraced). if IS_CPYTHON: # Note: use sys._current_frames instead of threading.enumerate() because this way # we also see C/C++ threads, not only the ones visible to the threading module. tid_to_frame = sys._current_frames() ignore_thread_ids = set( t.ident for t in threadingEnumerate() if getattr(t, 'is_pydev_daemon_thread', False) or getattr(t, 'pydev_do_not_trace', False) ) for thread_id, frame in tid_to_frame.items(): if thread_id not in ignore_thread_ids: self.set_trace_for_frame_and_parents(frame) else: try: threads = threadingEnumerate() for t in threads: if getattr(t, 'is_pydev_daemon_thread', False) or getattr(t, 'pydev_do_not_trace', False): continue additional_info = set_additional_thread_info(t) frame = additional_info.get_topmost_frame(t) try: if frame is not None: self.set_trace_for_frame_and_parents(frame) finally: frame = None finally: frame = None t = None threads = None additional_info = None @property def multi_threads_single_notification(self): return self._threads_suspended_single_notification.multi_threads_single_notification @multi_threads_single_notification.setter def multi_threads_single_notification(self, notify): self._threads_suspended_single_notification.multi_threads_single_notification = notify @property def threads_suspended_single_notification(self): return self._threads_suspended_single_notification def get_plugin_lazy_init(self): if self.plugin is None: self.plugin = PluginManager(self) return self.plugin def in_project_scope(self, frame, absolute_filename=None): ''' Note: in general this method should not be used (apply_files_filter should be used in most cases as it also handles the project scope check). :param frame: The frame we want to check. :param absolute_filename: Must be the result from get_abs_path_real_path_and_base_from_frame(frame)[0] (can be used to speed this function a bit if it's already available to the caller, but in general it's not needed). ''' try: if absolute_filename is None: try: # Make fast path faster! abs_real_path_and_basename = NORM_PATHS_AND_BASE_CONTAINER[frame.f_code.co_filename] except: abs_real_path_and_basename = get_abs_path_real_path_and_base_from_frame(frame) absolute_filename = abs_real_path_and_basename[0] cache_key = (frame.f_code.co_firstlineno, absolute_filename, frame.f_code) return self._in_project_scope_cache[cache_key] except KeyError: cache = self._in_project_scope_cache try: abs_real_path_and_basename # If we've gotten it previously, use it again. except NameError: abs_real_path_and_basename = get_abs_path_real_path_and_base_from_frame(frame) # pydevd files are never considered to be in the project scope. file_type = self.get_file_type(frame, abs_real_path_and_basename) if file_type == self.PYDEV_FILE: cache[cache_key] = False elif absolute_filename == '<string>': # Special handling for '<string>' if file_type == self.LIB_FILE: cache[cache_key] = False else: cache[cache_key] = True elif self.source_mapping.has_mapping_entry(absolute_filename): cache[cache_key] = True else: cache[cache_key] = self._files_filtering.in_project_roots(absolute_filename) return cache[cache_key] def in_project_roots_filename_uncached(self, absolute_filename): return self._files_filtering.in_project_roots(absolute_filename) def _clear_filters_caches(self): self._in_project_scope_cache.clear() self._exclude_by_filter_cache.clear() self._apply_filter_cache.clear() self._exclude_filters_enabled = self._files_filtering.use_exclude_filters() self._is_libraries_filter_enabled = self._files_filtering.use_libraries_filter() self.is_files_filter_enabled = self._exclude_filters_enabled or self._is_libraries_filter_enabled def clear_dont_trace_start_end_patterns_caches(self): # When start/end patterns are changed we must clear all caches which would be # affected by a change in get_file_type() and reset the tracing function # as places which were traced may no longer need to be traced and vice-versa. self.on_breakpoints_changed() _CACHE_FILE_TYPE.clear() self._clear_filters_caches() self._clear_skip_caches() def _exclude_by_filter(self, frame, absolute_filename): ''' :return: True if it should be excluded, False if it should be included and None if no rule matched the given file. :note: it'll be normalized as needed inside of this method. ''' cache_key = (absolute_filename, frame.f_code.co_name, frame.f_code.co_firstlineno) try: return self._exclude_by_filter_cache[cache_key] except KeyError: cache = self._exclude_by_filter_cache # pydevd files are always filtered out if self.get_file_type(frame) == self.PYDEV_FILE: cache[cache_key] = True else: module_name = None if self._files_filtering.require_module: module_name = frame.f_globals.get('__name__', '') cache[cache_key] = self._files_filtering.exclude_by_filter(absolute_filename, module_name) return cache[cache_key] def apply_files_filter(self, frame, original_filename, force_check_project_scope): ''' Should only be called if `self.is_files_filter_enabled == True` or `force_check_project_scope == True`. Note that it covers both the filter by specific paths includes/excludes as well as the check which filters out libraries if not in the project scope. :param original_filename: Note can either be the original filename or the absolute version of that filename. :param force_check_project_scope: Check that the file is in the project scope even if the global setting is off. :return bool: True if it should be excluded when stepping and False if it should be included. ''' cache_key = (frame.f_code.co_firstlineno, original_filename, force_check_project_scope, frame.f_code) try: return self._apply_filter_cache[cache_key] except KeyError: if self.plugin is not None and (self.has_plugin_line_breaks or self.has_plugin_exception_breaks): # If it's explicitly needed by some plugin, we can't skip it. if not self.plugin.can_skip(self, frame): pydev_log.debug_once('File traced (included by plugins): %s', original_filename) self._apply_filter_cache[cache_key] = False return False if self._exclude_filters_enabled: absolute_filename = pydevd_file_utils.absolute_path(original_filename) exclude_by_filter = self._exclude_by_filter(frame, absolute_filename) if exclude_by_filter is not None: if exclude_by_filter: # ignore files matching stepping filters pydev_log.debug_once('File not traced (excluded by filters): %s', original_filename) self._apply_filter_cache[cache_key] = True return True else: pydev_log.debug_once('File traced (explicitly included by filters): %s', original_filename) self._apply_filter_cache[cache_key] = False return False if (self._is_libraries_filter_enabled or force_check_project_scope) and not self.in_project_scope(frame): # ignore library files while stepping self._apply_filter_cache[cache_key] = True if force_check_project_scope: pydev_log.debug_once('File not traced (not in project): %s', original_filename) else: pydev_log.debug_once('File not traced (not in project - force_check_project_scope): %s', original_filename) return True if force_check_project_scope: pydev_log.debug_once('File traced: %s (force_check_project_scope)', original_filename) else: pydev_log.debug_once('File traced: %s', original_filename) self._apply_filter_cache[cache_key] = False return False def exclude_exception_by_filter(self, exception_breakpoint, trace): if not exception_breakpoint.ignore_libraries and not self._exclude_filters_enabled: return False if trace is None: return True ignore_libraries = exception_breakpoint.ignore_libraries exclude_filters_enabled = self._exclude_filters_enabled if (ignore_libraries and not self.in_project_scope(trace.tb_frame)) \ or (exclude_filters_enabled and self._exclude_by_filter( trace.tb_frame, pydevd_file_utils.absolute_path(trace.tb_frame.f_code.co_filename))): return True return False def set_project_roots(self, project_roots): self._files_filtering.set_project_roots(project_roots) self._clear_skip_caches() self._clear_filters_caches() def set_exclude_filters(self, exclude_filters): self._files_filtering.set_exclude_filters(exclude_filters) self._clear_skip_caches() self._clear_filters_caches() def set_use_libraries_filter(self, use_libraries_filter): self._files_filtering.set_use_libraries_filter(use_libraries_filter) self._clear_skip_caches() self._clear_filters_caches() def get_use_libraries_filter(self): return self._files_filtering.use_libraries_filter() def get_require_module_for_filters(self): return self._files_filtering.require_module def has_user_threads_alive(self): for t in pydevd_utils.get_non_pydevd_threads(): if isinstance(t, PyDBDaemonThread): pydev_log.error_once( 'Error in debugger: Found PyDBDaemonThread not marked with is_pydev_daemon_thread=True.\n') if is_thread_alive(t): if not t.daemon or hasattr(t, "__pydevd_main_thread"): return True return False def initialize_network(self, sock, terminate_on_socket_close=True): assert sock is not None try: sock.settimeout(None) # infinite, no timeouts from now on - jython does not have it except: pass curr_reader = getattr(self, 'reader', None) curr_writer = getattr(self, 'writer', None) if curr_reader: curr_reader.do_kill_pydev_thread() if curr_writer: curr_writer.do_kill_pydev_thread() self.writer = WriterThread(sock, self, terminate_on_socket_close=terminate_on_socket_close) self.reader = ReaderThread( sock, self, PyDevJsonCommandProcessor=PyDevJsonCommandProcessor, process_net_command=process_net_command, terminate_on_socket_close=terminate_on_socket_close ) self.writer.start() self.reader.start() time.sleep(0.1) # give threads time to start def connect(self, host, port): if host: s = start_client(host, port) else: s = start_server(port) self.initialize_network(s) def create_wait_for_connection_thread(self): if self._waiting_for_connection_thread is not None: raise AssertionError('There is already another thread waiting for a connection.') self._server_socket_ready_event.clear() self._waiting_for_connection_thread = self._WaitForConnectionThread(self) self._waiting_for_connection_thread.start() def set_server_socket_ready(self): self._server_socket_ready_event.set() def wait_for_server_socket_ready(self): self._server_socket_ready_event.wait() @property def dap_messages_listeners(self): return self._dap_messages_listeners def add_dap_messages_listener(self, listener): self._dap_messages_listeners.append(listener) class _WaitForConnectionThread(PyDBDaemonThread): def __init__(self, py_db): PyDBDaemonThread.__init__(self, py_db) self._server_socket = None def run(self): host = SetupHolder.setup['client'] port = SetupHolder.setup['port'] self._server_socket = create_server_socket(host=host, port=port) self.py_db._server_socket_name = self._server_socket.getsockname() self.py_db.set_server_socket_ready() while not self._kill_received: try: s = self._server_socket if s is None: return s.listen(1) new_socket, _addr = s.accept() if self._kill_received: pydev_log.info("Connection (from wait_for_attach) accepted but ignored as kill was already received.") return pydev_log.info("Connection (from wait_for_attach) accepted.") reader = getattr(self.py_db, 'reader', None) if reader is not None: # This is needed if a new connection is done without the client properly # sending a disconnect for the previous connection. api = PyDevdAPI() api.request_disconnect(self.py_db, resume_threads=False) self.py_db.initialize_network(new_socket, terminate_on_socket_close=False) except: if DebugInfoHolder.DEBUG_TRACE_LEVEL > 0: pydev_log.exception() pydev_log.debug("Exiting _WaitForConnectionThread: %s\n", port) def do_kill_pydev_thread(self): PyDBDaemonThread.do_kill_pydev_thread(self) s = self._server_socket if s is not None: try: s.close() except: pass self._server_socket = None def get_internal_queue(self, thread_id): """ returns internal command queue for a given thread. if new queue is created, notify the RDB about it """ if thread_id.startswith('__frame__'): thread_id = thread_id[thread_id.rfind('|') + 1:] return self._cmd_queue[thread_id] def post_method_as_internal_command(self, thread_id, method, *args, **kwargs): if thread_id == '*': internal_cmd = InternalThreadCommandForAnyThread(thread_id, method, *args, **kwargs) else: internal_cmd = InternalThreadCommand(thread_id, method, *args, **kwargs) self.post_internal_command(internal_cmd, thread_id) if thread_id == '*': # Notify so that the command is handled as soon as possible. self._py_db_command_thread_event.set() def post_internal_command(self, int_cmd, thread_id): """ if thread_id is *, post to the '*' queue""" queue = self.get_internal_queue(thread_id) queue.put(int_cmd) def enable_output_redirection(self, redirect_stdout, redirect_stderr): global _global_redirect_stdout_to_server global _global_redirect_stderr_to_server _global_redirect_stdout_to_server = redirect_stdout _global_redirect_stderr_to_server = redirect_stderr self.redirect_output = redirect_stdout or redirect_stderr if _global_redirect_stdout_to_server: _init_stdout_redirect() if _global_redirect_stderr_to_server: _init_stderr_redirect() def check_output_redirect(self): global _global_redirect_stdout_to_server global _global_redirect_stderr_to_server if _global_redirect_stdout_to_server: _init_stdout_redirect() if _global_redirect_stderr_to_server: _init_stderr_redirect() def init_matplotlib_in_debug_console(self): # import hook and patches for matplotlib support in debug console from _pydev_bundle.pydev_import_hook import import_hook_manager if is_current_thread_main_thread(): for module in list(self.mpl_modules_for_patching): import_hook_manager.add_module_name(module, self.mpl_modules_for_patching.pop(module)) def init_gui_support(self): if self._installed_gui_support: return self._installed_gui_support = True # enable_gui and enable_gui_function in activate_matplotlib should be called in main thread. Unlike integrated console, # in the debug console we have no interpreter instance with exec_queue, but we run this code in the main # thread and can call it directly. class _ReturnGuiLoopControlHelper: _return_control_osc = False def return_control(): # Some of the input hooks (e.g. Qt4Agg) check return control without doing # a single operation, so we don't return True on every # call when the debug hook is in place to allow the GUI to run _ReturnGuiLoopControlHelper._return_control_osc = not _ReturnGuiLoopControlHelper._return_control_osc return _ReturnGuiLoopControlHelper._return_control_osc from pydev_ipython.inputhook import set_return_control_callback, enable_gui set_return_control_callback(return_control) if self._gui_event_loop == 'matplotlib': # prepare debugger for matplotlib integration with GUI event loop from pydev_ipython.matplotlibtools import activate_matplotlib, activate_pylab, activate_pyplot, do_enable_gui self.mpl_modules_for_patching = {"matplotlib": lambda: activate_matplotlib(do_enable_gui), "matplotlib.pyplot": activate_pyplot, "pylab": activate_pylab } else: self.activate_gui_function = enable_gui def _activate_gui_if_needed(self): if self.gui_in_use: return if len(self.mpl_modules_for_patching) > 0: if is_current_thread_main_thread(): # Note that we call only in the main thread. for module in list(self.mpl_modules_for_patching): if module in sys.modules: activate_function = self.mpl_modules_for_patching.pop(module, None) if activate_function is not None: activate_function() self.gui_in_use = True if self.activate_gui_function: if is_current_thread_main_thread(): # Only call enable_gui in the main thread. try: # First try to activate builtin GUI event loops. self.activate_gui_function(self._gui_event_loop) self.activate_gui_function = None self.gui_in_use = True except ValueError: # The user requested a custom GUI event loop, try to import it. from pydev_ipython.inputhook import set_inputhook try: inputhook_function = import_attr_from_module(self._gui_event_loop) set_inputhook(inputhook_function) self.gui_in_use = True except Exception as e: pydev_log.debug("Cannot activate custom GUI event loop {}: {}".format(self._gui_event_loop, e)) finally: self.activate_gui_function = None def _call_input_hook(self): try: from pydev_ipython.inputhook import get_inputhook inputhook = get_inputhook() if inputhook: inputhook() except: pass def notify_skipped_step_in_because_of_filters(self, frame): self.writer.add_command(self.cmd_factory.make_skipped_step_in_because_of_filters(self, frame)) def notify_thread_created(self, thread_id, thread, use_lock=True): if self.writer is None: # Protect about threads being created before the communication structure is in place # (note that they will appear later on anyways as pydevd does reconcile live/dead threads # when processing internal commands, albeit it may take longer and in general this should # not be usual as it's expected that the debugger is live before other threads are created). return with self._lock_running_thread_ids if use_lock else NULL: if not self._enable_thread_notifications: return if thread_id in self._running_thread_ids: return additional_info = set_additional_thread_info(thread) if additional_info.pydev_notify_kill: # After we notify it should be killed, make sure we don't notify it's alive (on a racing condition # this could happen as we may notify before the thread is stopped internally). return self._running_thread_ids[thread_id] = thread self.writer.add_command(self.cmd_factory.make_thread_created_message(thread)) def notify_thread_not_alive(self, thread_id, use_lock=True): """ if thread is not alive, cancel trace_dispatch processing """ if self.writer is None: return with self._lock_running_thread_ids if use_lock else NULL: if not self._enable_thread_notifications: return thread = self._running_thread_ids.pop(thread_id, None) if thread is None: return additional_info = set_additional_thread_info(thread) was_notified = additional_info.pydev_notify_kill if not was_notified: additional_info.pydev_notify_kill = True self.writer.add_command(self.cmd_factory.make_thread_killed_message(thread_id)) def set_enable_thread_notifications(self, enable): with self._lock_running_thread_ids: if self._enable_thread_notifications != enable: self._enable_thread_notifications = enable if enable: # As it was previously disabled, we have to notify about existing threads again # (so, clear the cache related to that). self._running_thread_ids = {} def process_internal_commands(self): ''' This function processes internal commands. ''' # If this method is being called before the debugger is ready to run we should not notify # about threads and should only process commands sent to all threads. ready_to_run = self.ready_to_run dispose = False with self._main_lock: program_threads_alive = {} if ready_to_run: self.check_output_redirect() all_threads = threadingEnumerate() program_threads_dead = [] with self._lock_running_thread_ids: reset_cache = not self._running_thread_ids for t in all_threads: if getattr(t, 'is_pydev_daemon_thread', False): pass # I.e.: skip the DummyThreads created from pydev daemon threads elif isinstance(t, PyDBDaemonThread): pydev_log.error_once('Error in debugger: Found PyDBDaemonThread not marked with is_pydev_daemon_thread=True.') elif is_thread_alive(t): if reset_cache: # Fix multiprocessing debug with breakpoints in both main and child processes # (https://youtrack.jetbrains.com/issue/PY-17092) When the new process is created, the main # thread in the new process already has the attribute 'pydevd_id', so the new thread doesn't # get new id with its process number and the debugger loses access to both threads. # Therefore we should update thread_id for every main thread in the new process. clear_cached_thread_id(t) thread_id = get_thread_id(t) program_threads_alive[thread_id] = t self.notify_thread_created(thread_id, t, use_lock=False) # Compute and notify about threads which are no longer alive. thread_ids = list(self._running_thread_ids.keys()) for thread_id in thread_ids: if thread_id not in program_threads_alive: program_threads_dead.append(thread_id) for thread_id in program_threads_dead: self.notify_thread_not_alive(thread_id, use_lock=False) cmds_to_execute = [] # Without self._lock_running_thread_ids if len(program_threads_alive) == 0 and ready_to_run: dispose = True else: # Actually process the commands now (make sure we don't have a lock for _lock_running_thread_ids # acquired at this point as it could lead to a deadlock if some command evaluated tried to # create a thread and wait for it -- which would try to notify about it getting that lock). curr_thread_id = get_current_thread_id(threadingCurrentThread()) if ready_to_run: process_thread_ids = (curr_thread_id, '*') else: process_thread_ids = ('*',) for thread_id in process_thread_ids: queue = self.get_internal_queue(thread_id) # some commands must be processed by the thread itself... if that's the case, # we will re-add the commands to the queue after executing. cmds_to_add_back = [] try: while True: int_cmd = queue.get(False) if not self.mpl_hooks_in_debug_console and isinstance(int_cmd, InternalConsoleExec) and not self.gui_in_use: # add import hooks for matplotlib patches if only debug console was started try: self.init_matplotlib_in_debug_console() self.gui_in_use = True except: pydev_log.debug("Matplotlib support in debug console failed", traceback.format_exc()) self.mpl_hooks_in_debug_console = True if int_cmd.can_be_executed_by(curr_thread_id): cmds_to_execute.append(int_cmd) else: pydev_log.verbose("NOT processing internal command: %s ", int_cmd) cmds_to_add_back.append(int_cmd) except _queue.Empty: # @UndefinedVariable # this is how we exit for int_cmd in cmds_to_add_back: queue.put(int_cmd) if dispose: # Note: must be called without the main lock to avoid deadlocks. self.dispose_and_kill_all_pydevd_threads() else: # Actually execute the commands without the main lock! for int_cmd in cmds_to_execute: pydev_log.verbose("processing internal command: %s", int_cmd) try: int_cmd.do_it(self) except: pydev_log.exception('Error processing internal command.') def consolidate_breakpoints(self, canonical_normalized_filename, id_to_breakpoint, file_to_line_to_breakpoints): break_dict = {} for _breakpoint_id, pybreakpoint in id_to_breakpoint.items(): break_dict[pybreakpoint.line] = pybreakpoint file_to_line_to_breakpoints[canonical_normalized_filename] = break_dict self._clear_skip_caches() def _clear_skip_caches(self): global_cache_skips.clear() global_cache_frame_skips.clear() def add_break_on_exception( self, exception, condition, expression, notify_on_handled_exceptions, notify_on_unhandled_exceptions, notify_on_user_unhandled_exceptions, notify_on_first_raise_only, ignore_libraries=False ): try: eb = ExceptionBreakpoint( exception, condition, expression, notify_on_handled_exceptions, notify_on_unhandled_exceptions, notify_on_user_unhandled_exceptions, notify_on_first_raise_only, ignore_libraries ) except ImportError: pydev_log.critical("Error unable to add break on exception for: %s (exception could not be imported).", exception) return None if eb.notify_on_unhandled_exceptions: cp = self.break_on_uncaught_exceptions.copy() cp[exception] = eb if DebugInfoHolder.DEBUG_TRACE_BREAKPOINTS > 0: pydev_log.critical("Exceptions to hook on terminate: %s.", cp) self.break_on_uncaught_exceptions = cp if eb.notify_on_handled_exceptions: cp = self.break_on_caught_exceptions.copy() cp[exception] = eb if DebugInfoHolder.DEBUG_TRACE_BREAKPOINTS > 0: pydev_log.critical("Exceptions to hook always: %s.", cp) self.break_on_caught_exceptions = cp if eb.notify_on_user_unhandled_exceptions: cp = self.break_on_user_uncaught_exceptions.copy() cp[exception] = eb if DebugInfoHolder.DEBUG_TRACE_BREAKPOINTS > 0: pydev_log.critical("Exceptions to hook on user uncaught code: %s.", cp) self.break_on_user_uncaught_exceptions = cp return eb def set_suspend(self, thread, stop_reason, suspend_other_threads=False, is_pause=False, original_step_cmd=-1): ''' :param thread: The thread which should be suspended. :param stop_reason: Reason why the thread was suspended. :param suspend_other_threads: Whether to force other threads to be suspended (i.e.: when hitting a breakpoint with a suspend all threads policy). :param is_pause: If this is a pause to suspend all threads, any thread can be considered as the 'main' thread paused. :param original_step_cmd: If given we may change the stop reason to this. ''' self._threads_suspended_single_notification.increment_suspend_time() if is_pause: self._threads_suspended_single_notification.on_pause() info = mark_thread_suspended(thread, stop_reason, original_step_cmd=original_step_cmd) if is_pause: # Must set tracing after setting the state to suspend. frame = info.get_topmost_frame(thread) if frame is not None: try: self.set_trace_for_frame_and_parents(frame) finally: frame = None # If conditional breakpoint raises any exception during evaluation send the details to the client. if stop_reason == CMD_SET_BREAK and info.conditional_breakpoint_exception is not None: conditional_breakpoint_exception_tuple = info.conditional_breakpoint_exception info.conditional_breakpoint_exception = None self._send_breakpoint_condition_exception(thread, conditional_breakpoint_exception_tuple) if not suspend_other_threads and self.multi_threads_single_notification: # In the mode which gives a single notification when all threads are # stopped, stop all threads whenever a set_suspend is issued. suspend_other_threads = True if suspend_other_threads: # Suspend all except the current one (which we're currently suspending already). suspend_all_threads(self, except_thread=thread) def _send_breakpoint_condition_exception(self, thread, conditional_breakpoint_exception_tuple): """If conditional breakpoint raises an exception during evaluation send exception details to java """ thread_id = get_thread_id(thread) # conditional_breakpoint_exception_tuple - should contain 2 values (exception_type, stacktrace) if conditional_breakpoint_exception_tuple and len(conditional_breakpoint_exception_tuple) == 2: exc_type, stacktrace = conditional_breakpoint_exception_tuple int_cmd = InternalGetBreakpointException(thread_id, exc_type, stacktrace) self.post_internal_command(int_cmd, thread_id) def send_caught_exception_stack(self, thread, arg, curr_frame_id): """Sends details on the exception which was caught (and where we stopped) to the java side. arg is: exception type, description, traceback object """ thread_id = get_thread_id(thread) int_cmd = InternalSendCurrExceptionTrace(thread_id, arg, curr_frame_id) self.post_internal_command(int_cmd, thread_id) def send_caught_exception_stack_proceeded(self, thread): """Sends that some thread was resumed and is no longer showing an exception trace. """ thread_id = get_thread_id(thread) int_cmd = InternalSendCurrExceptionTraceProceeded(thread_id) self.post_internal_command(int_cmd, thread_id) self.process_internal_commands() def send_process_created_message(self): """Sends a message that a new process has been created. """ if self.writer is None or self.cmd_factory is None: return cmd = self.cmd_factory.make_process_created_message() self.writer.add_command(cmd) def send_process_about_to_be_replaced(self): """Sends a message that a new process has been created. """ if self.writer is None or self.cmd_factory is None: return cmd = self.cmd_factory.make_process_about_to_be_replaced_message() if cmd is NULL_NET_COMMAND: return sent = [False] def after_sent(*args, **kwargs): sent[0] = True cmd.call_after_send(after_sent) self.writer.add_command(cmd) timeout = 5 # Wait up to 5 seconds initial_time = time.time() while not sent[0]: time.sleep(.05) if (time.time() - initial_time) > timeout: pydev_log.critical('pydevd: Sending message related to process being replaced timed-out after %s seconds', timeout) break def set_next_statement(self, frame, event, func_name, next_line): stop = False response_msg = "" old_line = frame.f_lineno if event == 'line' or event == 'exception': # If we're already in the correct context, we have to stop it now, because we can act only on # line events -- if a return was the next statement it wouldn't work (so, we have this code # repeated at pydevd_frame). curr_func_name = frame.f_code.co_name # global context is set with an empty name if curr_func_name in ('?', '<module>'): curr_func_name = '' if func_name == '*' or curr_func_name == func_name: line = next_line frame.f_trace = self.trace_dispatch frame.f_lineno = line stop = True else: response_msg = "jump is available only within the bottom frame" return stop, old_line, response_msg def cancel_async_evaluation(self, thread_id, frame_id): with self._main_lock: try: all_threads = threadingEnumerate() for t in all_threads: if getattr(t, 'is_pydev_daemon_thread', False) and hasattr(t, 'cancel_event') and t.thread_id == thread_id and \ t.frame_id == frame_id: t.cancel_event.set() except: pydev_log.exception() def find_frame(self, thread_id, frame_id): """ returns a frame on the thread that has a given frame_id """ return self.suspended_frames_manager.find_frame(thread_id, frame_id) def do_wait_suspend(self, thread, frame, event, arg, exception_type=None): # @UnusedVariable """ busy waits until the thread state changes to RUN it expects thread's state as attributes of the thread. Upon running, processes any outstanding Stepping commands. :param exception_type: If pausing due to an exception, its type. """ if USE_CUSTOM_SYS_CURRENT_FRAMES_MAP: constructed_tid_to_last_frame[thread.ident] = sys._getframe() self.process_internal_commands() thread_id = get_current_thread_id(thread) # print('do_wait_suspend %s %s %s %s %s %s (%s)' % (frame.f_lineno, frame.f_code.co_name, frame.f_code.co_filename, event, arg, constant_to_str(thread.additional_info.pydev_step_cmd), constant_to_str(thread.additional_info.pydev_original_step_cmd))) # print('--- stack ---') # print(traceback.print_stack(file=sys.stdout)) # print('--- end stack ---') # Send the suspend message message = thread.additional_info.pydev_message suspend_type = thread.additional_info.trace_suspend_type thread.additional_info.trace_suspend_type = 'trace' # Reset to trace mode for next call. stop_reason = thread.stop_reason frames_list = None if arg is not None and event == 'exception': # arg must be the exception info (tuple(exc_type, exc, traceback)) exc_type, exc_desc, trace_obj = arg if trace_obj is not None: frames_list = pydevd_frame_utils.create_frames_list_from_traceback(trace_obj, frame, exc_type, exc_desc, exception_type=exception_type) if frames_list is None: frames_list = pydevd_frame_utils.create_frames_list_from_frame(frame) if DebugInfoHolder.DEBUG_TRACE_LEVEL > 2: pydev_log.debug( 'PyDB.do_wait_suspend\nname: %s (line: %s)\n file: %s\n event: %s\n arg: %s\n step: %s (original step: %s)\n thread: %s, thread id: %s, id(thread): %s', frame.f_code.co_name, frame.f_lineno, frame.f_code.co_filename, event, arg, constant_to_str(thread.additional_info.pydev_step_cmd), constant_to_str(thread.additional_info.pydev_original_step_cmd), thread, thread_id, id(thread), ) for f in frames_list: pydev_log.debug(' Stack: %s, %s, %s', f.f_code.co_filename, f.f_code.co_name, f.f_lineno) with self.suspended_frames_manager.track_frames(self) as frames_tracker: frames_tracker.track(thread_id, frames_list) cmd = frames_tracker.create_thread_suspend_command(thread_id, stop_reason, message, suspend_type) self.writer.add_command(cmd) with CustomFramesContainer.custom_frames_lock: # @UndefinedVariable from_this_thread = [] for frame_custom_thread_id, custom_frame in CustomFramesContainer.custom_frames.items(): if custom_frame.thread_id == thread.ident: frames_tracker.track(thread_id, pydevd_frame_utils.create_frames_list_from_frame(custom_frame.frame), frame_custom_thread_id=frame_custom_thread_id) # print('Frame created as thread: %s' % (frame_custom_thread_id,)) self.writer.add_command(self.cmd_factory.make_custom_frame_created_message( frame_custom_thread_id, custom_frame.name)) self.writer.add_command( frames_tracker.create_thread_suspend_command(frame_custom_thread_id, CMD_THREAD_SUSPEND, "", suspend_type)) from_this_thread.append(frame_custom_thread_id) with self._threads_suspended_single_notification.notify_thread_suspended(thread_id, stop_reason): keep_suspended = self._do_wait_suspend(thread, frame, event, arg, suspend_type, from_this_thread, frames_tracker) frames_list = None if keep_suspended: # This means that we should pause again after a set next statement. self._threads_suspended_single_notification.increment_suspend_time() self.do_wait_suspend(thread, frame, event, arg, exception_type) if DebugInfoHolder.DEBUG_TRACE_LEVEL > 2: pydev_log.debug('Leaving PyDB.do_wait_suspend: %s (%s) %s', thread, thread_id, id(thread)) def _do_wait_suspend(self, thread, frame, event, arg, suspend_type, from_this_thread, frames_tracker): info = thread.additional_info info.step_in_initial_location = None keep_suspended = False with self._main_lock: # Use lock to check if suspended state changed activate_gui = info.pydev_state == STATE_SUSPEND and not self.pydb_disposed in_main_thread = is_current_thread_main_thread() if activate_gui and in_main_thread: # before every stop check if matplotlib modules were imported inside script code # or some GUI event loop needs to be activated self._activate_gui_if_needed() while True: with self._main_lock: # Use lock to check if suspended state changed if info.pydev_state != STATE_SUSPEND or (self.pydb_disposed and not self.terminate_requested): # Note: we can't exit here if terminate was requested while a breakpoint was hit. break if in_main_thread and self.gui_in_use: # call input hooks if only GUI is in use self._call_input_hook() self.process_internal_commands() time.sleep(0.01) self.cancel_async_evaluation(get_current_thread_id(thread), str(id(frame))) # process any stepping instructions if info.pydev_step_cmd in (CMD_STEP_INTO, CMD_STEP_INTO_MY_CODE): info.step_in_initial_location = (frame, frame.f_lineno) if frame.f_code.co_flags & 0x80: # CO_COROUTINE = 0x80 # When in a coroutine we switch to CMD_STEP_INTO_COROUTINE. info.pydev_step_cmd = CMD_STEP_INTO_COROUTINE info.pydev_step_stop = frame self.set_trace_for_frame_and_parents(frame) else: info.pydev_step_stop = None self.set_trace_for_frame_and_parents(frame) elif info.pydev_step_cmd in (CMD_STEP_OVER, CMD_STEP_OVER_MY_CODE, CMD_SMART_STEP_INTO): info.pydev_step_stop = frame self.set_trace_for_frame_and_parents(frame) elif info.pydev_step_cmd == CMD_RUN_TO_LINE or info.pydev_step_cmd == CMD_SET_NEXT_STATEMENT: info.pydev_step_stop = None self.set_trace_for_frame_and_parents(frame) stop = False response_msg = "" try: stop, _old_line, response_msg = self.set_next_statement(frame, event, info.pydev_func_name, info.pydev_next_line) except ValueError as e: response_msg = "%s" % e finally: seq = info.pydev_message cmd = self.cmd_factory.make_set_next_stmnt_status_message(seq, stop, response_msg) self.writer.add_command(cmd) info.pydev_message = '' if stop: # Uninstall the current frames tracker before running it. frames_tracker.untrack_all() cmd = self.cmd_factory.make_thread_run_message(get_current_thread_id(thread), info.pydev_step_cmd) self.writer.add_command(cmd) info.pydev_state = STATE_SUSPEND thread.stop_reason = CMD_SET_NEXT_STATEMENT keep_suspended = True else: # Set next did not work... info.pydev_original_step_cmd = -1 info.pydev_step_cmd = -1 info.pydev_state = STATE_SUSPEND thread.stop_reason = CMD_THREAD_SUSPEND # return to the suspend state and wait for other command (without sending any # additional notification to the client). return self._do_wait_suspend(thread, frame, event, arg, suspend_type, from_this_thread, frames_tracker) elif info.pydev_step_cmd in (CMD_STEP_RETURN, CMD_STEP_RETURN_MY_CODE): back_frame = frame.f_back force_check_project_scope = info.pydev_step_cmd == CMD_STEP_RETURN_MY_CODE if force_check_project_scope or self.is_files_filter_enabled: while back_frame is not None: if self.apply_files_filter(back_frame, back_frame.f_code.co_filename, force_check_project_scope): frame = back_frame back_frame = back_frame.f_back else: break if back_frame is not None: # steps back to the same frame (in a return call it will stop in the 'back frame' for the user) info.pydev_step_stop = frame self.set_trace_for_frame_and_parents(frame) else: # No back frame?!? -- this happens in jython when we have some frame created from an awt event # (the previous frame would be the awt event, but this doesn't make part of 'jython', only 'java') # so, if we're doing a step return in this situation, it's the same as just making it run info.pydev_step_stop = None info.pydev_original_step_cmd = -1 info.pydev_step_cmd = -1 info.pydev_state = STATE_RUN if PYDEVD_IPYTHON_COMPATIBLE_DEBUGGING: info.pydev_use_scoped_step_frame = False if info.pydev_step_cmd in ( CMD_STEP_OVER, CMD_STEP_OVER_MY_CODE, CMD_STEP_INTO, CMD_STEP_INTO_MY_CODE ): # i.e.: We're stepping: check if the stepping should be scoped (i.e.: in ipython # each line is executed separately in a new frame, in which case we need to consider # the next line as if it was still in the same frame). f = frame.f_back if f and f.f_code.co_name == PYDEVD_IPYTHON_CONTEXT[1]: f = f.f_back if f and f.f_code.co_name == PYDEVD_IPYTHON_CONTEXT[2]: info.pydev_use_scoped_step_frame = True pydev_log.info('Using (ipython) scoped stepping.') del f del frame cmd = self.cmd_factory.make_thread_run_message(get_current_thread_id(thread), info.pydev_step_cmd) self.writer.add_command(cmd) with CustomFramesContainer.custom_frames_lock: # The ones that remained on last_running must now be removed. for frame_id in from_this_thread: # print('Removing created frame: %s' % (frame_id,)) self.writer.add_command(self.cmd_factory.make_thread_killed_message(frame_id)) return keep_suspended def do_stop_on_unhandled_exception(self, thread, frame, frames_byid, arg): pydev_log.debug("We are stopping in unhandled exception.") try: add_exception_to_frame(frame, arg) self.send_caught_exception_stack(thread, arg, id(frame)) try: self.set_suspend(thread, CMD_ADD_EXCEPTION_BREAK) self.do_wait_suspend(thread, frame, 'exception', arg, EXCEPTION_TYPE_UNHANDLED) except: self.send_caught_exception_stack_proceeded(thread) except: pydev_log.exception("We've got an error while stopping in unhandled exception: %s.", arg[0]) finally: remove_exception_from_frame(frame) frame = None def set_trace_for_frame_and_parents(self, frame, **kwargs): disable = kwargs.pop('disable', False) assert not kwargs while frame is not None: # Don't change the tracing on debugger-related files file_type = self.get_file_type(frame) if file_type is None: if disable: pydev_log.debug('Disable tracing of frame: %s - %s', frame.f_code.co_filename, frame.f_code.co_name) if frame.f_trace is not None and frame.f_trace is not NO_FTRACE: frame.f_trace = NO_FTRACE elif frame.f_trace is not self.trace_dispatch: pydev_log.debug('Set tracing of frame: %s - %s', frame.f_code.co_filename, frame.f_code.co_name) frame.f_trace = self.trace_dispatch else: pydev_log.debug('SKIP set tracing of frame: %s - %s', frame.f_code.co_filename, frame.f_code.co_name) frame = frame.f_back del frame def _create_pydb_command_thread(self): curr_pydb_command_thread = self.py_db_command_thread if curr_pydb_command_thread is not None: curr_pydb_command_thread.do_kill_pydev_thread() new_pydb_command_thread = self.py_db_command_thread = PyDBCommandThread(self) new_pydb_command_thread.start() def _create_check_output_thread(self): curr_output_checker_thread = self.check_alive_thread if curr_output_checker_thread is not None: curr_output_checker_thread.do_kill_pydev_thread() check_alive_thread = self.check_alive_thread = CheckAliveThread(self) check_alive_thread.start() def start_auxiliary_daemon_threads(self): self._create_pydb_command_thread() self._create_check_output_thread() def __wait_for_threads_to_finish(self, timeout): try: with self._wait_for_threads_to_finish_called_lock: wait_for_threads_to_finish_called = self._wait_for_threads_to_finish_called self._wait_for_threads_to_finish_called = True if wait_for_threads_to_finish_called: # Make sure that we wait for the previous call to be finished. self._wait_for_threads_to_finish_called_event.wait(timeout=timeout) else: try: def get_pydb_daemon_threads_to_wait(): pydb_daemon_threads = set(self.created_pydb_daemon_threads) pydb_daemon_threads.discard(self.check_alive_thread) pydb_daemon_threads.discard(threading.current_thread()) return pydb_daemon_threads pydev_log.debug("PyDB.dispose_and_kill_all_pydevd_threads waiting for pydb daemon threads to finish") started_at = time.time() # Note: we wait for all except the check_alive_thread (which is not really a daemon # thread and it can call this method itself). while time.time() < started_at + timeout: if len(get_pydb_daemon_threads_to_wait()) == 0: break time.sleep(1 / 10.) else: thread_names = [t.name for t in get_pydb_daemon_threads_to_wait()] if thread_names: pydev_log.debug("The following pydb threads may not have finished correctly: %s", ', '.join(thread_names)) finally: self._wait_for_threads_to_finish_called_event.set() except: pydev_log.exception() def dispose_and_kill_all_pydevd_threads(self, wait=True, timeout=.5): ''' When this method is called we finish the debug session, terminate threads and if this was registered as the global instance, unregister it -- afterwards it should be possible to create a new instance and set as global to start a new debug session. :param bool wait: If True we'll wait for the threads to be actually finished before proceeding (based on the available timeout). Note that this must be thread-safe and if one thread is waiting the other thread should also wait. ''' try: back_frame = sys._getframe().f_back pydev_log.debug( 'PyDB.dispose_and_kill_all_pydevd_threads (called from: File "%s", line %s, in %s)', back_frame.f_code.co_filename, back_frame.f_lineno, back_frame.f_code.co_name ) back_frame = None with self._disposed_lock: disposed = self.pydb_disposed self.pydb_disposed = True if disposed: if wait: pydev_log.debug("PyDB.dispose_and_kill_all_pydevd_threads (already disposed - wait)") self.__wait_for_threads_to_finish(timeout) else: pydev_log.debug("PyDB.dispose_and_kill_all_pydevd_threads (already disposed - no wait)") return pydev_log.debug("PyDB.dispose_and_kill_all_pydevd_threads (first call)") # Wait until a time when there are no commands being processed to kill the threads. started_at = time.time() while time.time() < started_at + timeout: with self._main_lock: writer = self.writer if writer is None or writer.empty(): pydev_log.debug("PyDB.dispose_and_kill_all_pydevd_threads no commands being processed.") break else: pydev_log.debug("PyDB.dispose_and_kill_all_pydevd_threads timed out waiting for writer to be empty.") pydb_daemon_threads = set(self.created_pydb_daemon_threads) for t in pydb_daemon_threads: if hasattr(t, 'do_kill_pydev_thread'): pydev_log.debug("PyDB.dispose_and_kill_all_pydevd_threads killing thread: %s", t) t.do_kill_pydev_thread() if wait: self.__wait_for_threads_to_finish(timeout) else: pydev_log.debug("PyDB.dispose_and_kill_all_pydevd_threads: no wait") py_db = get_global_debugger() if py_db is self: set_global_debugger(None) except: pydev_log.debug("PyDB.dispose_and_kill_all_pydevd_threads: exception") try: if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 3: pydev_log.exception() except: pass finally: pydev_log.debug("PyDB.dispose_and_kill_all_pydevd_threads: finished") def prepare_to_run(self): ''' Shared code to prepare debugging by installing traces and registering threads ''' self.patch_threads() self.start_auxiliary_daemon_threads() def patch_threads(self): try: # not available in jython! threading.settrace(self.trace_dispatch) # for all future threads except: pass from _pydev_bundle.pydev_monkey import patch_thread_modules patch_thread_modules() def run(self, file, globals=None, locals=None, is_module=False, set_trace=True): module_name = None entry_point_fn = '' if is_module: # When launching with `python -m <module>`, python automatically adds # an empty path to the PYTHONPATH which resolves files in the current # directory, so, depending how pydevd itself is launched, we may need # to manually add such an entry to properly resolve modules in the # current directory (see: https://github.com/Microsoft/ptvsd/issues/1010). if '' not in sys.path: sys.path.insert(0, '') file, _, entry_point_fn = file.partition(':') module_name = file filename = get_fullname(file) if filename is None: mod_dir = get_package_dir(module_name) if mod_dir is None: sys.stderr.write("No module named %s\n" % file) return else: filename = get_fullname("%s.__main__" % module_name) if filename is None: sys.stderr.write("No module named %s\n" % file) return else: file = filename else: file = filename mod_dir = os.path.dirname(filename) main_py = os.path.join(mod_dir, '__main__.py') main_pyc = os.path.join(mod_dir, '__main__.pyc') if filename.endswith('__init__.pyc'): if os.path.exists(main_pyc): filename = main_pyc elif os.path.exists(main_py): filename = main_py elif filename.endswith('__init__.py'): if os.path.exists(main_pyc) and not os.path.exists(main_py): filename = main_pyc elif os.path.exists(main_py): filename = main_py sys.argv[0] = filename if os.path.isdir(file): new_target = os.path.join(file, '__main__.py') if os.path.isfile(new_target): file = new_target m = None if globals is None: m = save_main_module(file, 'pydevd') globals = m.__dict__ try: globals['__builtins__'] = __builtins__ except NameError: pass # Not there on Jython... if locals is None: locals = globals # Predefined (writable) attributes: __name__ is the module's name; # __doc__ is the module's documentation string, or None if unavailable; # __file__ is the pathname of the file from which the module was loaded, # if it was loaded from a file. The __file__ attribute is not present for # C modules that are statically linked into the interpreter; for extension modules # loaded dynamically from a shared library, it is the pathname of the shared library file. # I think this is an ugly hack, bug it works (seems to) for the bug that says that sys.path should be the same in # debug and run. if sys.path[0] != '' and m is not None and m.__file__.startswith(sys.path[0]): # print >> sys.stderr, 'Deleting: ', sys.path[0] del sys.path[0] if not is_module: # now, the local directory has to be added to the pythonpath # sys.path.insert(0, os.getcwd()) # Changed: it's not the local directory, but the directory of the file launched # The file being run must be in the pythonpath (even if it was not before) sys.path.insert(0, os.path.split(os_path_abspath(file))[0]) if set_trace: self.wait_for_ready_to_run() # call prepare_to_run when we already have all information about breakpoints self.prepare_to_run() t = threadingCurrentThread() thread_id = get_current_thread_id(t) if self.thread_analyser is not None: wrap_threads() self.thread_analyser.set_start_time(cur_time()) send_concurrency_message("threading_event", 0, t.name, thread_id, "thread", "start", file, 1, None, parent=thread_id) if self.asyncio_analyser is not None: # we don't have main thread in asyncio graph, so we should add a fake event send_concurrency_message("asyncio_event", 0, "Task", "Task", "thread", "stop", file, 1, frame=None, parent=None) try: if INTERACTIVE_MODE_AVAILABLE: self.init_gui_support() except: pydev_log.exception("Matplotlib support in debugger failed") if hasattr(sys, 'exc_clear'): # we should clean exception information in Python 2, before user's code execution sys.exc_clear() # Notify that the main thread is created. self.notify_thread_created(thread_id, t) # Note: important: set the tracing right before calling _exec. if set_trace: self.enable_tracing() return self._exec(is_module, entry_point_fn, module_name, file, globals, locals) def _exec(self, is_module, entry_point_fn, module_name, file, globals, locals): ''' This function should have frames tracked by unhandled exceptions (the `_exec` name is important). ''' if not is_module: globals = pydevd_runpy.run_path(file, globals, '__main__') else: # treat ':' as a separator between module and entry point function # if there is no entry point we run we same as with -m switch. Otherwise we perform # an import and execute the entry point if entry_point_fn: mod = __import__(module_name, level=0, fromlist=[entry_point_fn], globals=globals, locals=locals) func = getattr(mod, entry_point_fn) func() else: # Run with the -m switch globals = pydevd_runpy._run_module_as_main(module_name, alter_argv=False) return globals def wait_for_commands(self, globals): self._activate_gui_if_needed() thread = threading.current_thread() from _pydevd_bundle import pydevd_frame_utils frame = pydevd_frame_utils.Frame(None, -1, pydevd_frame_utils.FCode("Console", os.path.abspath(os.path.dirname(__file__))), globals, globals) thread_id = get_current_thread_id(thread) self.add_fake_frame(thread_id, id(frame), frame) cmd = self.cmd_factory.make_show_console_message(self, thread_id, frame) if self.writer is not None: self.writer.add_command(cmd) while True: if self.gui_in_use: # call input hooks if only GUI is in use self._call_input_hook() self.process_internal_commands() time.sleep(0.01) class IDAPMessagesListener(object): def before_send(self, message_as_dict): ''' Called just before a message is sent to the IDE. :type message_as_dict: dict ''' def after_receive(self, message_as_dict): ''' Called just after a message is received from the IDE. :type message_as_dict: dict ''' def add_dap_messages_listener(dap_messages_listener): ''' Adds a listener for the DAP (debug adapter protocol) messages. :type dap_messages_listener: IDAPMessagesListener :note: messages from the xml backend are not notified through this API. :note: the notifications are sent from threads and they are not synchronized (so, it's possible that a message is sent and received from different threads at the same time). ''' py_db = get_global_debugger() if py_db is None: raise AssertionError('PyDB is still not setup.') py_db.add_dap_messages_listener(dap_messages_listener) def send_json_message(msg): ''' API to send some custom json message. :param dict|pydevd_schema.BaseSchema msg: The custom message to be sent. :return bool: True if the message was added to the queue to be sent and False otherwise. ''' py_db = get_global_debugger() if py_db is None: return False writer = py_db.writer if writer is None: return False cmd = NetCommand(-1, 0, msg, is_json=True) writer.add_command(cmd) return True def set_debug(setup): setup['DEBUG_RECORD_SOCKET_READS'] = True setup['DEBUG_TRACE_BREAKPOINTS'] = 1 setup['DEBUG_TRACE_LEVEL'] = 3 def enable_qt_support(qt_support_mode): from _pydev_bundle import pydev_monkey_qt pydev_monkey_qt.patch_qt(qt_support_mode) def start_dump_threads_thread(filename_template, timeout, recurrent): ''' Helper to dump threads after a timeout. :param filename_template: A template filename, such as 'c:/temp/thread_dump_%s.txt', where the %s will be replaced by the time for the dump. :param timeout: The timeout (in seconds) for the dump. :param recurrent: If True we'll keep on doing thread dumps. ''' assert filename_template.count('%s') == 1, \ 'Expected one %%s to appear in: %s' % (filename_template,) def _threads_on_timeout(): try: while True: time.sleep(timeout) filename = filename_template % (time.time(),) try: os.makedirs(os.path.dirname(filename)) except Exception: pass with open(filename, 'w') as stream: dump_threads(stream) if not recurrent: return except Exception: pydev_log.exception() t = threading.Thread(target=_threads_on_timeout) mark_as_pydevd_daemon_thread(t) t.start() def dump_threads(stream=None): ''' Helper to dump thread info (default is printing to stderr). ''' pydevd_utils.dump_threads(stream) def usage(doExit=0): sys.stdout.write('Usage:\n') sys.stdout.write('pydevd.py --port N [(--client hostname) | --server] --file executable [file_options]\n') if doExit: sys.exit(0) def _init_stdout_redirect(): pydevd_io.redirect_stream_to_pydb_io_messages(std='stdout') def _init_stderr_redirect(): pydevd_io.redirect_stream_to_pydb_io_messages(std='stderr') def _enable_attach( address, dont_trace_start_patterns=(), dont_trace_end_patterns=(), patch_multiprocessing=False, access_token=None, client_access_token=None, ): ''' Starts accepting connections at the given host/port. The debugger will not be initialized nor configured, it'll only start accepting connections (and will have the tracing setup in this thread). Meant to be used with the DAP (Debug Adapter Protocol) with _wait_for_attach(). :param address: (host, port) :type address: tuple(str, int) ''' host = address[0] port = int(address[1]) if SetupHolder.setup is not None: if port != SetupHolder.setup['port']: raise AssertionError('Unable to listen in port: %s (already listening in port: %s)' % (port, SetupHolder.setup['port'])) settrace( host=host, port=port, suspend=False, wait_for_ready_to_run=False, block_until_connected=False, dont_trace_start_patterns=dont_trace_start_patterns, dont_trace_end_patterns=dont_trace_end_patterns, patch_multiprocessing=patch_multiprocessing, access_token=access_token, client_access_token=client_access_token, ) py_db = get_global_debugger() py_db.wait_for_server_socket_ready() return py_db._server_socket_name def _wait_for_attach(cancel=None): ''' Meant to be called after _enable_attach() -- the current thread will only unblock after a connection is in place and the DAP (Debug Adapter Protocol) sends the ConfigurationDone request. ''' py_db = get_global_debugger() if py_db is None: raise AssertionError('Debugger still not created. Please use _enable_attach() before using _wait_for_attach().') py_db.block_until_configuration_done(cancel=cancel) def _is_attached(): ''' Can be called any time to check if the connection was established and the DAP (Debug Adapter Protocol) has sent the ConfigurationDone request. ''' py_db = get_global_debugger() return (py_db is not None) and py_db.is_attached() #======================================================================================================================= # settrace #======================================================================================================================= def settrace( host=None, stdout_to_server=False, stderr_to_server=False, port=5678, suspend=True, trace_only_current_thread=False, overwrite_prev_trace=False, patch_multiprocessing=False, stop_at_frame=None, block_until_connected=True, wait_for_ready_to_run=True, dont_trace_start_patterns=(), dont_trace_end_patterns=(), access_token=None, client_access_token=None, notify_stdin=True, **kwargs ): '''Sets the tracing function with the pydev debug function and initializes needed facilities. :param host: the user may specify another host, if the debug server is not in the same machine (default is the local host) :param stdout_to_server: when this is true, the stdout is passed to the debug server :param stderr_to_server: when this is true, the stderr is passed to the debug server so that they are printed in its console and not in this process console. :param port: specifies which port to use for communicating with the server (note that the server must be started in the same port). @note: currently it's hard-coded at 5678 in the client :param suspend: whether a breakpoint should be emulated as soon as this function is called. :param trace_only_current_thread: determines if only the current thread will be traced or all current and future threads will also have the tracing enabled. :param overwrite_prev_trace: deprecated :param patch_multiprocessing: if True we'll patch the functions which create new processes so that launched processes are debugged. :param stop_at_frame: if passed it'll stop at the given frame, otherwise it'll stop in the function which called this method. :param wait_for_ready_to_run: if True settrace will block until the ready_to_run flag is set to True, otherwise, it'll set ready_to_run to True and this function won't block. Note that if wait_for_ready_to_run == False, there are no guarantees that the debugger is synchronized with what's configured in the client (IDE), the only guarantee is that when leaving this function the debugger will be already connected. :param dont_trace_start_patterns: if set, then any path that starts with one fo the patterns in the collection will not be traced :param dont_trace_end_patterns: if set, then any path that ends with one fo the patterns in the collection will not be traced :param access_token: token to be sent from the client (i.e.: IDE) to the debugger when a connection is established (verified by the debugger). :param client_access_token: token to be sent from the debugger to the client (i.e.: IDE) when a connection is established (verified by the client). :param notify_stdin: If True sys.stdin will be patched to notify the client when a message is requested from the IDE. This is done so that when reading the stdin the client is notified. Clients may need this to know when something that is being written should be interpreted as an input to the process or as a command to be evaluated. Note that parallel-python has issues with this (because it tries to assert that sys.stdin is of a given type instead of just checking that it has what it needs). ''' stdout_to_server = stdout_to_server or kwargs.get('stdoutToServer', False) # Backward compatibility stderr_to_server = stderr_to_server or kwargs.get('stderrToServer', False) # Backward compatibility # Internal use (may be used to set the setup info directly for subprocesess). __setup_holder__ = kwargs.get('__setup_holder__') with _set_trace_lock: _locked_settrace( host, stdout_to_server, stderr_to_server, port, suspend, trace_only_current_thread, patch_multiprocessing, stop_at_frame, block_until_connected, wait_for_ready_to_run, dont_trace_start_patterns, dont_trace_end_patterns, access_token, client_access_token, __setup_holder__=__setup_holder__, notify_stdin=notify_stdin, ) _set_trace_lock = ForkSafeLock() def _locked_settrace( host, stdout_to_server, stderr_to_server, port, suspend, trace_only_current_thread, patch_multiprocessing, stop_at_frame, block_until_connected, wait_for_ready_to_run, dont_trace_start_patterns, dont_trace_end_patterns, access_token, client_access_token, __setup_holder__, notify_stdin, ): if patch_multiprocessing: try: from _pydev_bundle import pydev_monkey except: pass else: pydev_monkey.patch_new_process_functions() if host is None: from _pydev_bundle import pydev_localhost host = pydev_localhost.get_localhost() global _global_redirect_stdout_to_server global _global_redirect_stderr_to_server py_db = get_global_debugger() if __setup_holder__: SetupHolder.setup = __setup_holder__ if py_db is None: py_db = PyDB() pydevd_vm_type.setup_type() if SetupHolder.setup is None: setup = { 'client': host, # dispatch expects client to be set to the host address when server is False 'server': False, 'port': int(port), 'multiprocess': patch_multiprocessing, 'skip-notify-stdin': not notify_stdin, } SetupHolder.setup = setup if access_token is not None: py_db.authentication.access_token = access_token SetupHolder.setup['access-token'] = access_token if client_access_token is not None: py_db.authentication.client_access_token = client_access_token SetupHolder.setup['client-access-token'] = client_access_token if block_until_connected: py_db.connect(host, port) # Note: connect can raise error. else: # Create a dummy writer and wait for the real connection. py_db.writer = WriterThread(NULL, py_db, terminate_on_socket_close=False) py_db.create_wait_for_connection_thread() if dont_trace_start_patterns or dont_trace_end_patterns: PyDevdAPI().set_dont_trace_start_end_patterns(py_db, dont_trace_start_patterns, dont_trace_end_patterns) _global_redirect_stdout_to_server = stdout_to_server _global_redirect_stderr_to_server = stderr_to_server if _global_redirect_stdout_to_server: _init_stdout_redirect() if _global_redirect_stderr_to_server: _init_stderr_redirect() if notify_stdin: patch_stdin() t = threadingCurrentThread() additional_info = set_additional_thread_info(t) if not wait_for_ready_to_run: py_db.ready_to_run = True py_db.wait_for_ready_to_run() py_db.start_auxiliary_daemon_threads() try: if INTERACTIVE_MODE_AVAILABLE: py_db.init_gui_support() except: pydev_log.exception("Matplotlib support in debugger failed") if trace_only_current_thread: py_db.enable_tracing() else: # Trace future threads. py_db.patch_threads() py_db.enable_tracing(py_db.trace_dispatch, apply_to_all_threads=True) # As this is the first connection, also set tracing for any untraced threads py_db.set_tracing_for_untraced_contexts() py_db.set_trace_for_frame_and_parents(get_frame().f_back) with CustomFramesContainer.custom_frames_lock: # @UndefinedVariable for _frameId, custom_frame in CustomFramesContainer.custom_frames.items(): py_db.set_trace_for_frame_and_parents(custom_frame.frame) else: # ok, we're already in debug mode, with all set, so, let's just set the break if access_token is not None: py_db.authentication.access_token = access_token if client_access_token is not None: py_db.authentication.client_access_token = client_access_token py_db.set_trace_for_frame_and_parents(get_frame().f_back) t = threadingCurrentThread() additional_info = set_additional_thread_info(t) if trace_only_current_thread: py_db.enable_tracing() else: # Trace future threads. py_db.patch_threads() py_db.enable_tracing(py_db.trace_dispatch, apply_to_all_threads=True) # Suspend as the last thing after all tracing is in place. if suspend: if stop_at_frame is not None: # If the step was set we have to go to run state and # set the proper frame for it to stop. additional_info.pydev_state = STATE_RUN additional_info.pydev_original_step_cmd = CMD_STEP_OVER additional_info.pydev_step_cmd = CMD_STEP_OVER additional_info.pydev_step_stop = stop_at_frame additional_info.suspend_type = PYTHON_SUSPEND else: # Ask to break as soon as possible. py_db.set_suspend(t, CMD_SET_BREAK) def stoptrace(): pydev_log.debug("pydevd.stoptrace()") pydevd_tracing.restore_sys_set_trace_func() sys.settrace(None) try: # not available in jython! threading.settrace(None) # for all future threads except: pass from _pydev_bundle.pydev_monkey import undo_patch_thread_modules undo_patch_thread_modules() # Either or both standard streams can be closed at this point, # in which case flush() will fail. try: sys.stdout.flush() except: pass try: sys.stderr.flush() except: pass py_db = get_global_debugger() if py_db is not None: py_db.dispose_and_kill_all_pydevd_threads() class Dispatcher(object): def __init__(self): self.port = None def connect(self, host, port): self.host = host self.port = port self.client = start_client(self.host, self.port) self.reader = DispatchReader(self) self.reader.pydev_do_not_trace = False # we run reader in the same thread so we don't want to loose tracing self.reader.run() def close(self): try: self.reader.do_kill_pydev_thread() except: pass class DispatchReader(ReaderThread): def __init__(self, dispatcher): self.dispatcher = dispatcher ReaderThread.__init__( self, get_global_debugger(), self.dispatcher.client, PyDevJsonCommandProcessor=PyDevJsonCommandProcessor, process_net_command=process_net_command, ) @overrides(ReaderThread._on_run) def _on_run(self): dummy_thread = threading.current_thread() dummy_thread.is_pydev_daemon_thread = False return ReaderThread._on_run(self) @overrides(PyDBDaemonThread.do_kill_pydev_thread) def do_kill_pydev_thread(self): if not self._kill_received: ReaderThread.do_kill_pydev_thread(self) try: self.sock.shutdown(SHUT_RDWR) except: pass try: self.sock.close() except: pass def process_command(self, cmd_id, seq, text): if cmd_id == 99: self.dispatcher.port = int(text) self._kill_received = True DISPATCH_APPROACH_NEW_CONNECTION = 1 # Used by PyDev DISPATCH_APPROACH_EXISTING_CONNECTION = 2 # Used by PyCharm DISPATCH_APPROACH = DISPATCH_APPROACH_NEW_CONNECTION def dispatch(): setup = SetupHolder.setup host = setup['client'] port = setup['port'] if DISPATCH_APPROACH == DISPATCH_APPROACH_EXISTING_CONNECTION: dispatcher = Dispatcher() try: dispatcher.connect(host, port) port = dispatcher.port finally: dispatcher.close() return host, port def settrace_forked(setup_tracing=True): ''' When creating a fork from a process in the debugger, we need to reset the whole debugger environment! ''' from _pydevd_bundle.pydevd_constants import GlobalDebuggerHolder py_db = GlobalDebuggerHolder.global_dbg if py_db is not None: py_db.created_pydb_daemon_threads = {} # Just making sure we won't touch those (paused) threads. py_db = None GlobalDebuggerHolder.global_dbg = None threading.current_thread().additional_info = None # Make sure that we keep the same access tokens for subprocesses started through fork. setup = SetupHolder.setup if setup is None: setup = {} else: # i.e.: Get the ppid at this point as it just changed. # If we later do an exec() it should remain the same ppid. setup[pydevd_constants.ARGUMENT_PPID] = PyDevdAPI().get_ppid() access_token = setup.get('access-token') client_access_token = setup.get('client-access-token') if setup_tracing: from _pydevd_frame_eval.pydevd_frame_eval_main import clear_thread_local_info host, port = dispatch() import pydevd_tracing pydevd_tracing.restore_sys_set_trace_func() if setup_tracing: if port is not None: custom_frames_container_init() if clear_thread_local_info is not None: clear_thread_local_info() settrace( host, port=port, suspend=False, trace_only_current_thread=False, overwrite_prev_trace=True, patch_multiprocessing=True, access_token=access_token, client_access_token=client_access_token, ) @contextmanager def skip_subprocess_arg_patch(): ''' May be used to skip the monkey-patching that pydevd does to skip changing arguments to embed the debugger into child processes. i.e.: with pydevd.skip_subprocess_arg_patch(): subprocess.call(...) ''' from _pydev_bundle import pydev_monkey with pydev_monkey.skip_subprocess_arg_patch(): yield def add_dont_terminate_child_pid(pid): ''' May be used to ask pydevd to skip the termination of some process when it's asked to terminate (debug adapter protocol only). :param int pid: The pid to be ignored. i.e.: process = subprocess.Popen(...) pydevd.add_dont_terminate_child_pid(process.pid) ''' py_db = get_global_debugger() if py_db is not None: py_db.dont_terminate_child_pids.add(pid) class SetupHolder: setup = None def apply_debugger_options(setup_options): """ :type setup_options: dict[str, bool] """ default_options = {'save-signatures': False, 'qt-support': ''} default_options.update(setup_options) setup_options = default_options debugger = get_global_debugger() if setup_options['save-signatures']: if pydevd_vm_type.get_vm_type() == pydevd_vm_type.PydevdVmType.JYTHON: sys.stderr.write("Collecting run-time type information is not supported for Jython\n") else: # Only import it if we're going to use it! from _pydevd_bundle.pydevd_signature import SignatureFactory debugger.signature_factory = SignatureFactory() if setup_options['qt-support']: enable_qt_support(setup_options['qt-support']) @call_only_once def patch_stdin(): _internal_patch_stdin(None, sys, getpass_mod) def _internal_patch_stdin(py_db=None, sys=None, getpass_mod=None): ''' Note: don't use this function directly, use `patch_stdin()` instead. (this function is only meant to be used on test-cases to avoid patching the actual globals). ''' # Patch stdin so that we notify when readline() is called. original_sys_stdin = sys.stdin debug_console_stdin = DebugConsoleStdIn(py_db, original_sys_stdin) sys.stdin = debug_console_stdin _original_getpass = getpass_mod.getpass @functools.wraps(_original_getpass) def getpass(*args, **kwargs): with DebugConsoleStdIn.notify_input_requested(debug_console_stdin): try: curr_stdin = sys.stdin if curr_stdin is debug_console_stdin: sys.stdin = original_sys_stdin return _original_getpass(*args, **kwargs) finally: sys.stdin = curr_stdin getpass_mod.getpass = getpass # Dispatch on_debugger_modules_loaded here, after all primary py_db modules are loaded for handler in pydevd_extension_utils.extensions_of_type(DebuggerEventHandler): handler.on_debugger_modules_loaded(debugger_version=__version__) #======================================================================================================================= # main #======================================================================================================================= def main(): # parse the command line. --file is our last argument that is required pydev_log.debug("Initial arguments: %s", (sys.argv,)) pydev_log.debug("Current pid: %s", os.getpid()) try: from _pydevd_bundle.pydevd_command_line_handling import process_command_line setup = process_command_line(sys.argv) SetupHolder.setup = setup except ValueError: pydev_log.exception() usage(1) if setup['print-in-debugger-startup']: try: pid = ' (pid: %s)' % os.getpid() except: pid = '' sys.stderr.write("pydev debugger: starting%s\n" % pid) pydev_log.debug("Executing file %s", setup['file']) pydev_log.debug("arguments: %s", (sys.argv,)) pydevd_vm_type.setup_type(setup.get('vm_type', None)) if SHOW_DEBUG_INFO_ENV: set_debug(setup) DebugInfoHolder.DEBUG_RECORD_SOCKET_READS = setup.get('DEBUG_RECORD_SOCKET_READS', DebugInfoHolder.DEBUG_RECORD_SOCKET_READS) DebugInfoHolder.DEBUG_TRACE_BREAKPOINTS = setup.get('DEBUG_TRACE_BREAKPOINTS', DebugInfoHolder.DEBUG_TRACE_BREAKPOINTS) DebugInfoHolder.DEBUG_TRACE_LEVEL = setup.get('DEBUG_TRACE_LEVEL', DebugInfoHolder.DEBUG_TRACE_LEVEL) port = setup['port'] host = setup['client'] f = setup['file'] fix_app_engine_debug = False debugger = get_global_debugger() if debugger is None: debugger = PyDB() try: from _pydev_bundle import pydev_monkey except: pass # Not usable on jython 2.1 else: if setup['multiprocess']: # PyDev pydev_monkey.patch_new_process_functions() elif setup['multiproc']: # PyCharm pydev_log.debug("Started in multiproc mode\n") global DISPATCH_APPROACH DISPATCH_APPROACH = DISPATCH_APPROACH_EXISTING_CONNECTION dispatcher = Dispatcher() try: dispatcher.connect(host, port) if dispatcher.port is not None: port = dispatcher.port pydev_log.debug("Received port %d\n", port) pydev_log.info("pydev debugger: process %d is connecting\n" % os.getpid()) try: pydev_monkey.patch_new_process_functions() except: pydev_log.exception("Error patching process functions.") else: pydev_log.critical("pydev debugger: couldn't get port for new debug process.") finally: dispatcher.close() else: try: pydev_monkey.patch_new_process_functions_with_warning() except: pydev_log.exception("Error patching process functions.") # Only do this patching if we're not running with multiprocess turned on. if f.find('dev_appserver.py') != -1: if os.path.basename(f).startswith('dev_appserver.py'): appserver_dir = os.path.dirname(f) version_file = os.path.join(appserver_dir, 'VERSION') if os.path.exists(version_file): try: stream = open(version_file, 'r') try: for line in stream.read().splitlines(): line = line.strip() if line.startswith('release:'): line = line[8:].strip() version = line.replace('"', '') version = version.split('.') if int(version[0]) > 1: fix_app_engine_debug = True elif int(version[0]) == 1: if int(version[1]) >= 7: # Only fix from 1.7 onwards fix_app_engine_debug = True break finally: stream.close() except: pydev_log.exception() try: # In the default run (i.e.: run directly on debug mode), we try to patch stackless as soon as possible # on a run where we have a remote debug, we may have to be more careful because patching stackless means # that if the user already had a stackless.set_schedule_callback installed, he'd loose it and would need # to call it again (because stackless provides no way of getting the last function which was registered # in set_schedule_callback). # # So, ideally, if there's an application using stackless and the application wants to use the remote debugger # and benefit from stackless debugging, the application itself must call: # # import pydevd_stackless # pydevd_stackless.patch_stackless() # # itself to be able to benefit from seeing the tasklets created before the remote debugger is attached. from _pydevd_bundle import pydevd_stackless pydevd_stackless.patch_stackless() except: # It's ok not having stackless there... try: if hasattr(sys, 'exc_clear'): sys.exc_clear() # the exception information should be cleaned in Python 2 except: pass is_module = setup['module'] if not setup['skip-notify-stdin']: patch_stdin() if setup[pydevd_constants.ARGUMENT_JSON_PROTOCOL]: PyDevdAPI().set_protocol(debugger, 0, JSON_PROTOCOL) elif setup[pydevd_constants.ARGUMENT_HTTP_JSON_PROTOCOL]: PyDevdAPI().set_protocol(debugger, 0, HTTP_JSON_PROTOCOL) elif setup[pydevd_constants.ARGUMENT_HTTP_PROTOCOL]: PyDevdAPI().set_protocol(debugger, 0, pydevd_constants.HTTP_PROTOCOL) elif setup[pydevd_constants.ARGUMENT_QUOTED_LINE_PROTOCOL]: PyDevdAPI().set_protocol(debugger, 0, pydevd_constants.QUOTED_LINE_PROTOCOL) access_token = setup['access-token'] if access_token: debugger.authentication.access_token = access_token client_access_token = setup['client-access-token'] if client_access_token: debugger.authentication.client_access_token = client_access_token if fix_app_engine_debug: sys.stderr.write("pydev debugger: google app engine integration enabled\n") curr_dir = os.path.dirname(__file__) app_engine_startup_file = os.path.join(curr_dir, 'pydev_app_engine_debug_startup.py') sys.argv.insert(1, '--python_startup_script=' + app_engine_startup_file) import json setup['pydevd'] = __file__ sys.argv.insert(2, '--python_startup_args=%s' % json.dumps(setup),) sys.argv.insert(3, '--automatic_restart=no') sys.argv.insert(4, '--max_module_instances=1') # Run the dev_appserver debugger.run(setup['file'], None, None, is_module, set_trace=False) else: if setup['save-threading']: debugger.thread_analyser = ThreadingLogger() if setup['save-asyncio']: debugger.asyncio_analyser = AsyncioLogger() apply_debugger_options(setup) try: debugger.connect(host, port) except: sys.stderr.write("Could not connect to %s: %s\n" % (host, port)) pydev_log.exception() sys.exit(1) globals = debugger.run(setup['file'], None, None, is_module) if setup['cmd-line']: debugger.wait_for_commands(globals) if __name__ == '__main__': main()
144,860
Python
41.184333
257
0.600152
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevd_file_utils.py
r''' This module provides utilities to get the absolute filenames so that we can be sure that: - The case of a file will match the actual file in the filesystem (otherwise breakpoints won't be hit). - Providing means for the user to make path conversions when doing a remote debugging session in one machine and debugging in another. To do that, the PATHS_FROM_ECLIPSE_TO_PYTHON constant must be filled with the appropriate paths. @note: in this context, the server is where your python process is running and the client is where eclipse is running. E.g.: If the server (your python process) has the structure /user/projects/my_project/src/package/module1.py and the client has: c:\my_project\src\package\module1.py the PATHS_FROM_ECLIPSE_TO_PYTHON would have to be: PATHS_FROM_ECLIPSE_TO_PYTHON = [(r'c:\my_project\src', r'/user/projects/my_project/src')] alternatively, this can be set with an environment variable from the command line: set PATHS_FROM_ECLIPSE_TO_PYTHON=[['c:\my_project\src','/user/projects/my_project/src']] @note: DEBUG_CLIENT_SERVER_TRANSLATION can be set to True to debug the result of those translations @note: the case of the paths is important! Note that this can be tricky to get right when one machine uses a case-independent filesystem and the other uses a case-dependent filesystem (if the system being debugged is case-independent, 'normcase()' should be used on the paths defined in PATHS_FROM_ECLIPSE_TO_PYTHON). @note: all the paths with breakpoints must be translated (otherwise they won't be found in the server) @note: to enable remote debugging in the target machine (pydev extensions in the eclipse installation) import pydevd;pydevd.settrace(host, stdoutToServer, stderrToServer, port, suspend) see parameter docs on pydevd.py @note: for doing a remote debugging session, all the pydevd_ files must be on the server accessible through the PYTHONPATH (and the PATHS_FROM_ECLIPSE_TO_PYTHON only needs to be set on the target machine for the paths that'll actually have breakpoints). ''' from _pydev_bundle import pydev_log from _pydevd_bundle.pydevd_constants import DebugInfoHolder, IS_WINDOWS, IS_JYTHON, \ DISABLE_FILE_VALIDATION, is_true_in_env from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding from _pydevd_bundle.pydevd_comm_constants import file_system_encoding, filesystem_encoding_is_utf8 from _pydev_bundle.pydev_log import error_once import json import os.path import sys import itertools import ntpath from functools import partial _nt_os_normcase = ntpath.normcase os_path_basename = os.path.basename os_path_exists = os.path.exists join = os.path.join try: FileNotFoundError except NameError: FileNotFoundError = IOError # noqa try: os_path_real_path = os.path.realpath # @UndefinedVariable except: # jython does not support os.path.realpath # realpath is a no-op on systems without islink support os_path_real_path = os.path.abspath def _get_library_dir(): library_dir = None try: import sysconfig library_dir = sysconfig.get_path('purelib') except ImportError: pass # i.e.: Only 2.7 onwards if library_dir is None or not os_path_exists(library_dir): for path in sys.path: if os_path_exists(path) and os.path.basename(path) == 'site-packages': library_dir = path break if library_dir is None or not os_path_exists(library_dir): library_dir = os.path.dirname(os.__file__) return library_dir # Note: we can't call sysconfig.get_path from _apply_func_and_normalize_case (it deadlocks on Python 2.7) so, we # need to get the library dir during module loading. _library_dir = _get_library_dir() # defined as a list of tuples where the 1st element of the tuple is the path in the client machine # and the 2nd element is the path in the server machine. # see module docstring for more details. try: PATHS_FROM_ECLIPSE_TO_PYTHON = json.loads(os.environ.get('PATHS_FROM_ECLIPSE_TO_PYTHON', '[]')) except Exception: pydev_log.critical('Error loading PATHS_FROM_ECLIPSE_TO_PYTHON from environment variable.') pydev_log.exception() PATHS_FROM_ECLIPSE_TO_PYTHON = [] else: if not isinstance(PATHS_FROM_ECLIPSE_TO_PYTHON, list): pydev_log.critical('Expected PATHS_FROM_ECLIPSE_TO_PYTHON loaded from environment variable to be a list.') PATHS_FROM_ECLIPSE_TO_PYTHON = [] else: # Converting json lists to tuple PATHS_FROM_ECLIPSE_TO_PYTHON = [tuple(x) for x in PATHS_FROM_ECLIPSE_TO_PYTHON] # example: # PATHS_FROM_ECLIPSE_TO_PYTHON = [ # (r'd:\temp\temp_workspace_2\test_python\src\yyy\yyy', # r'd:\temp\temp_workspace_2\test_python\src\hhh\xxx') # ] convert_to_long_pathname = lambda filename:filename convert_to_short_pathname = lambda filename:filename get_path_with_real_case = lambda filename:filename if sys.platform == 'win32': try: import ctypes from ctypes.wintypes import MAX_PATH, LPCWSTR, LPWSTR, DWORD GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW # noqa GetLongPathName.argtypes = [LPCWSTR, LPWSTR, DWORD] GetLongPathName.restype = DWORD GetShortPathName = ctypes.windll.kernel32.GetShortPathNameW # noqa GetShortPathName.argtypes = [LPCWSTR, LPWSTR, DWORD] GetShortPathName.restype = DWORD def _convert_to_long_pathname(filename): buf = ctypes.create_unicode_buffer(MAX_PATH) rv = GetLongPathName(filename, buf, MAX_PATH) if rv != 0 and rv <= MAX_PATH: filename = buf.value return filename def _convert_to_short_pathname(filename): buf = ctypes.create_unicode_buffer(MAX_PATH) rv = GetShortPathName(filename, buf, MAX_PATH) if rv != 0 and rv <= MAX_PATH: filename = buf.value return filename # Note that we have a cache for previous list dirs... the only case where this may be an # issue is if the user actually changes the case of an existing file on windows while # the debugger is executing (as this seems very unlikely and the cache can save a # reasonable time -- especially on mapped drives -- it seems nice to have it). _listdir_cache = {} def _resolve_listing(resolved, iter_parts, cache=_listdir_cache): while True: # Note: while True to make iterative and not recursive try: resolve_lowercase = next(iter_parts) # must be lowercase already except StopIteration: return resolved resolved_lower = resolved.lower() resolved_joined = cache.get((resolved_lower, resolve_lowercase)) if resolved_joined is None: dir_contents = cache.get(resolved_lower) if dir_contents is None: dir_contents = cache[resolved_lower] = os.listdir(resolved) for filename in dir_contents: if filename.lower() == resolve_lowercase: resolved_joined = os.path.join(resolved, filename) cache[(resolved_lower, resolve_lowercase)] = resolved_joined break else: raise FileNotFoundError('Unable to find: %s in %s' % ( resolve_lowercase, resolved)) resolved = resolved_joined def _get_path_with_real_case(filename): # Note: this previously made: # convert_to_long_pathname(convert_to_short_pathname(filename)) # but this is no longer done because we can't rely on getting the shortname # consistently (there are settings to disable it on Windows). # So, using approach which resolves by listing the dir. if '~' in filename: filename = convert_to_long_pathname(filename) if filename.startswith('<') or not os_path_exists(filename): return filename # Not much we can do. drive, parts = os.path.splitdrive(os.path.normpath(filename)) drive = drive.upper() while parts.startswith(os.path.sep): parts = parts[1:] drive += os.path.sep parts = parts.lower().split(os.path.sep) try: if parts == ['']: return drive return _resolve_listing(drive, iter(parts)) except FileNotFoundError: _listdir_cache.clear() # Retry once after clearing the cache we have. try: return _resolve_listing(drive, iter(parts)) except FileNotFoundError: if os_path_exists(filename): # This is really strange, ask the user to report as error. pydev_log.critical( 'pydev debugger: critical: unable to get real case for file. Details:\n' 'filename: %s\ndrive: %s\nparts: %s\n' '(please create a ticket in the tracker to address this).', filename, drive, parts ) pydev_log.exception() # Don't fail, just return the original file passed. return filename # Check that it actually works _get_path_with_real_case(__file__) except: # Something didn't quite work out, leave no-op conversions in place. if DebugInfoHolder.DEBUG_TRACE_LEVEL > 2: pydev_log.exception() else: convert_to_long_pathname = _convert_to_long_pathname convert_to_short_pathname = _convert_to_short_pathname get_path_with_real_case = _get_path_with_real_case elif IS_JYTHON and IS_WINDOWS: def get_path_with_real_case(filename): from java.io import File # noqa f = File(filename) ret = f.getCanonicalPath() return ret if IS_JYTHON: def _normcase_windows(filename): return filename.lower() else: def _normcase_windows(filename): # `normcase` doesn't lower case on Python 2 for non-English locale, so we should do it manually. if '~' in filename: filename = convert_to_long_pathname(filename) filename = _nt_os_normcase(filename) return filename.lower() def _normcase_linux(filename): return filename # no-op _filename_normalization = os.environ.get('PYDEVD_FILENAME_NORMALIZATION', '').lower() if _filename_normalization == 'lower': # Note: this is mostly for testing (forcing to always lower-case all contents # internally -- used to mimick Windows normalization on Linux). def _normcase_lower(filename): return filename.lower() _default_normcase = _normcase_lower elif _filename_normalization == 'none': # Disable any filename normalization may be an option on Windows if the # user is having issues under some circumstances. _default_normcase = _normcase_linux elif IS_WINDOWS: _default_normcase = _normcase_windows else: _default_normcase = _normcase_linux def normcase(s, NORMCASE_CACHE={}): try: return NORMCASE_CACHE[s] except: normalized = NORMCASE_CACHE[s] = _default_normcase(s) return normalized _ide_os = 'WINDOWS' if IS_WINDOWS else 'UNIX' _normcase_from_client = normcase def normcase_from_client(s): return _normcase_from_client(s) DEBUG_CLIENT_SERVER_TRANSLATION = os.environ.get('DEBUG_PYDEVD_PATHS_TRANSLATION', 'False').lower() in ('1', 'true') def set_ide_os(os): ''' We need to set the IDE os because the host where the code is running may be actually different from the client (and the point is that we want the proper paths to translate from the client to the server). :param os: 'UNIX' or 'WINDOWS' ''' global _ide_os global _normcase_from_client prev = _ide_os if os == 'WIN': # Apparently PyCharm uses 'WIN' (https://github.com/fabioz/PyDev.Debugger/issues/116) os = 'WINDOWS' assert os in ('WINDOWS', 'UNIX') if DEBUG_CLIENT_SERVER_TRANSLATION: print('pydev debugger: client OS: %s' % (os,)) _normcase_from_client = normcase if os == 'WINDOWS': # Client in Windows and server in Unix, we need to normalize the case. if not IS_WINDOWS: _normcase_from_client = _normcase_windows else: # Client in Unix and server in Windows, we can't normalize the case. if IS_WINDOWS: _normcase_from_client = _normcase_linux if prev != os: _ide_os = os # We need to (re)setup how the client <-> server translation works to provide proper separators. setup_client_server_paths(_last_client_server_paths_set) # Caches filled as requested during the debug session. NORM_PATHS_CONTAINER = {} NORM_PATHS_AND_BASE_CONTAINER = {} def canonical_normalized_path(filename): ''' This returns a filename that is canonical and it's meant to be used internally to store information on breakpoints and see if there's any hit on it. Note that this version is only internal as it may not match the case and may have symlinks resolved (and thus may not match what the user expects in the editor). ''' return get_abs_path_real_path_and_base_from_file(filename)[1] def absolute_path(filename): ''' Provides a version of the filename that's absolute (and NOT normalized). ''' return get_abs_path_real_path_and_base_from_file(filename)[0] def basename(filename): ''' Provides the basename for a file. ''' return get_abs_path_real_path_and_base_from_file(filename)[2] # Returns tuple of absolute path and real path for given filename def _abs_and_canonical_path(filename, NORM_PATHS_CONTAINER=NORM_PATHS_CONTAINER): try: return NORM_PATHS_CONTAINER[filename] except: if filename.__class__ != str: raise AssertionError('Paths passed to _abs_and_canonical_path must be str. Found: %s (%s)' % (filename, type(filename))) if os is None: # Interpreter shutdown return filename, filename os_path = os.path if os_path is None: # Interpreter shutdown return filename, filename os_path_abspath = os_path.abspath os_path_isabs = os_path.isabs if os_path_abspath is None or os_path_isabs is None or os_path_real_path is None: # Interpreter shutdown return filename, filename isabs = os_path_isabs(filename) if _global_resolve_symlinks: os_path_abspath = os_path_real_path normalize = False abs_path = _apply_func_and_normalize_case(filename, os_path_abspath, isabs, normalize) normalize = True real_path = _apply_func_and_normalize_case(filename, os_path_real_path, isabs, normalize) # cache it for fast access later NORM_PATHS_CONTAINER[filename] = abs_path, real_path return abs_path, real_path def _get_relative_filename_abs_path(filename, func, os_path_exists=os_path_exists): # If we have a relative path and the file does not exist when made absolute, try to # resolve it based on the sys.path entries. for p in sys.path: r = func(os.path.join(p, filename)) if os_path_exists(r): return r # We couldn't find the real file for the relative path. Resolve it as if it was in # a library (so that it's considered a library file and not a project file). r = func(os.path.join(_library_dir, filename)) return r def _apply_func_and_normalize_case(filename, func, isabs, normalize_case, os_path_exists=os_path_exists, join=join): if filename.startswith('<'): # Not really a file, rather a synthetic name like <string> or <ipython-...>; # shouldn't be normalized. return filename r = func(filename) if not isabs: if not os_path_exists(r): r = _get_relative_filename_abs_path(filename, func) ind = r.find('.zip') if ind == -1: ind = r.find('.egg') if ind != -1: ind += 4 zip_path = r[:ind] inner_path = r[ind:] if inner_path.startswith('!'): # Note (fabioz): although I can replicate this by creating a file ending as # .zip! or .egg!, I don't really know what's the real-world case for this # (still kept as it was added by @jetbrains, but it should probably be reviewed # later on). # Note 2: it goes hand-in-hand with 'exists'. inner_path = inner_path[1:] zip_path = zip_path + '!' if inner_path.startswith('/') or inner_path.startswith('\\'): inner_path = inner_path[1:] if inner_path: if normalize_case: r = join(normcase(zip_path), inner_path) else: r = join(zip_path, inner_path) return r if normalize_case: r = normcase(r) return r _ZIP_SEARCH_CACHE = {} _NOT_FOUND_SENTINEL = object() def exists(filename): if os_path_exists(filename): return True if not os.path.isabs(filename): filename = _get_relative_filename_abs_path(filename, os.path.abspath) if os_path_exists(filename): return True ind = filename.find('.zip') if ind == -1: ind = filename.find('.egg') if ind != -1: ind += 4 zip_path = filename[:ind] inner_path = filename[ind:] if inner_path.startswith("!"): # Note (fabioz): although I can replicate this by creating a file ending as # .zip! or .egg!, I don't really know what's the real-world case for this # (still kept as it was added by @jetbrains, but it should probably be reviewed # later on). # Note 2: it goes hand-in-hand with '_apply_func_and_normalize_case'. inner_path = inner_path[1:] zip_path = zip_path + '!' zip_file_obj = _ZIP_SEARCH_CACHE.get(zip_path, _NOT_FOUND_SENTINEL) if zip_file_obj is None: return False elif zip_file_obj is _NOT_FOUND_SENTINEL: try: import zipfile zip_file_obj = zipfile.ZipFile(zip_path, 'r') _ZIP_SEARCH_CACHE[zip_path] = zip_file_obj except: _ZIP_SEARCH_CACHE[zip_path] = _NOT_FOUND_SENTINEL return False try: if inner_path.startswith('/') or inner_path.startswith('\\'): inner_path = inner_path[1:] _info = zip_file_obj.getinfo(inner_path.replace('\\', '/')) return join(zip_path, inner_path) except KeyError: return False else: pydev_log.debug('os.path.exists(%r) returned False.', filename) return False try: report = pydev_log.critical if DISABLE_FILE_VALIDATION: report = pydev_log.debug try: code = os_path_real_path.func_code except AttributeError: code = os_path_real_path.__code__ if code.co_filename.startswith('<frozen'): # See: https://github.com/fabioz/PyDev.Debugger/issues/213 report('Debugger warning: It seems that frozen modules are being used, which may') report('make the debugger miss breakpoints. Please pass -Xfrozen_modules=off') report('to python to disable frozen modules.') report('Note: Debugging will proceed. Set PYDEVD_DISABLE_FILE_VALIDATION=1 to disable this validation.') elif not os.path.isabs(code.co_filename): report('Debugger warning: The os.path.realpath.__code__.co_filename (%s)', code.co_filename) report('is not absolute, which may make the debugger miss breakpoints.') report('Note: Debugging will proceed. Set PYDEVD_DISABLE_FILE_VALIDATION=1 to disable this validation.') elif not exists(code.co_filename): # Note: checks for files inside .zip containers. report('Debugger warning: It seems the debugger cannot find os.path.realpath.__code__.co_filename (%s).', code.co_filename) report('This may make the debugger miss breakpoints in the standard library.') report('Note: Debugging will proceed. Set PYDEVD_DISABLE_FILE_VALIDATION=1 to disable this validation.') except: # Don't fail if there's something not correct here -- but at least print it to the user so that we can correct that pydev_log.exception() # Note: as these functions may be rebound, users should always import # pydevd_file_utils and then use: # # pydevd_file_utils.map_file_to_client # pydevd_file_utils.map_file_to_server # # instead of importing any of those names to a given scope. def _path_to_expected_str(filename): if isinstance(filename, bytes): filename = filename.decode(file_system_encoding) return filename def _original_file_to_client(filename, cache={}): try: return cache[filename] except KeyError: translated = _path_to_expected_str(get_path_with_real_case(absolute_path(filename))) cache[filename] = (translated, False) return cache[filename] def _original_map_file_to_server(filename): # By default just mapping to the server does nothing if there are no mappings (usually # afterwards the debugger must do canonical_normalized_path to get a normalized version). return filename map_file_to_client = _original_file_to_client map_file_to_server = _original_map_file_to_server def _fix_path(path, sep, add_end_sep=False): if add_end_sep: if not path.endswith('/') and not path.endswith('\\'): path += '/' else: if path.endswith('/') or path.endswith('\\'): path = path[:-1] if sep != '/': path = path.replace('/', sep) return path _last_client_server_paths_set = [] _source_reference_to_frame_id = {} _source_reference_to_server_filename = {} _line_cache_source_reference_to_server_filename = {} _client_filename_in_utf8_to_source_reference = {} _next_source_reference = partial(next, itertools.count(1)) def get_client_filename_source_reference(client_filename): return _client_filename_in_utf8_to_source_reference.get(client_filename, 0) def get_server_filename_from_source_reference(source_reference): return _source_reference_to_server_filename.get(source_reference, '') def create_source_reference_for_linecache(server_filename): source_reference = _next_source_reference() pydev_log.debug('Created linecache id source reference: %s for server filename: %s', source_reference, server_filename) _line_cache_source_reference_to_server_filename[source_reference] = server_filename return source_reference def get_source_reference_filename_from_linecache(source_reference): return _line_cache_source_reference_to_server_filename.get(source_reference) def create_source_reference_for_frame_id(frame_id, original_filename): source_reference = _next_source_reference() pydev_log.debug('Created frame id source reference: %s for frame id: %s (%s)', source_reference, frame_id, original_filename) _source_reference_to_frame_id[source_reference] = frame_id return source_reference def get_frame_id_from_source_reference(source_reference): return _source_reference_to_frame_id.get(source_reference) _global_resolve_symlinks = is_true_in_env('PYDEVD_RESOLVE_SYMLINKS') def set_resolve_symlinks(resolve_symlinks): global _global_resolve_symlinks _global_resolve_symlinks = resolve_symlinks def setup_client_server_paths(paths): '''paths is the same format as PATHS_FROM_ECLIPSE_TO_PYTHON''' global map_file_to_client global map_file_to_server global _last_client_server_paths_set global _next_source_reference _last_client_server_paths_set = paths[:] _source_reference_to_server_filename.clear() _client_filename_in_utf8_to_source_reference.clear() _next_source_reference = partial(next, itertools.count(1)) # Work on the client and server slashes. python_sep = '\\' if IS_WINDOWS else '/' eclipse_sep = '\\' if _ide_os == 'WINDOWS' else '/' norm_filename_to_server_container = {} norm_filename_to_client_container = {} initial_paths = [] initial_paths_with_end_sep = [] paths_from_eclipse_to_python = [] paths_from_eclipse_to_python_with_end_sep = [] # Apply normcase to the existing paths to follow the os preferences. for i, (path0, path1) in enumerate(paths): force_only_slash = path0.endswith(('/', '\\')) and path1.endswith(('/', '\\')) if not force_only_slash: path0 = _fix_path(path0, eclipse_sep, False) path1 = _fix_path(path1, python_sep, False) initial_paths.append((path0, path1)) paths_from_eclipse_to_python.append((_normcase_from_client(path0), normcase(path1))) # Now, make a version with a slash in the end. path0 = _fix_path(path0, eclipse_sep, True) path1 = _fix_path(path1, python_sep, True) initial_paths_with_end_sep.append((path0, path1)) paths_from_eclipse_to_python_with_end_sep.append((_normcase_from_client(path0), normcase(path1))) # Fix things so that we always match the versions with a slash in the end first. initial_paths = initial_paths_with_end_sep + initial_paths paths_from_eclipse_to_python = paths_from_eclipse_to_python_with_end_sep + paths_from_eclipse_to_python if not paths_from_eclipse_to_python: # no translation step needed (just inline the calls) map_file_to_client = _original_file_to_client map_file_to_server = _original_map_file_to_server return # only setup translation functions if absolutely needed! def _map_file_to_server(filename, cache=norm_filename_to_server_container): # Eclipse will send the passed filename to be translated to the python process # So, this would be 'NormFileFromEclipseToPython' try: return cache[filename] except KeyError: if eclipse_sep != python_sep: # Make sure that the separators are what we expect from the IDE. filename = filename.replace(python_sep, eclipse_sep) # used to translate a path from the client to the debug server translated = filename translated_normalized = _normcase_from_client(filename) for eclipse_prefix, server_prefix in paths_from_eclipse_to_python: if translated_normalized.startswith(eclipse_prefix): found_translation = True if DEBUG_CLIENT_SERVER_TRANSLATION: pydev_log.critical('pydev debugger: replacing to server: %s', filename) translated = server_prefix + filename[len(eclipse_prefix):] if DEBUG_CLIENT_SERVER_TRANSLATION: pydev_log.critical('pydev debugger: sent to server: %s - matched prefix: %s', translated, eclipse_prefix) break else: found_translation = False # Note that when going to the server, we do the replace first and only later do the norm file. if eclipse_sep != python_sep: translated = translated.replace(eclipse_sep, python_sep) if found_translation: # Note: we don't normalize it here, this must be done as a separate # step by the caller. translated = absolute_path(translated) else: if not os_path_exists(translated): if not translated.startswith('<'): # This is a configuration error, so, write it always so # that the user can fix it. error_once('pydev debugger: unable to find translation for: "%s" in [%s] (please revise your path mappings).\n', filename, ', '.join(['"%s"' % (x[0],) for x in paths_from_eclipse_to_python])) else: # It's possible that we had some round trip (say, we sent /usr/lib and received # it back, so, having no translation is ok too). # Note: we don't normalize it here, this must be done as a separate # step by the caller. translated = absolute_path(translated) cache[filename] = translated return translated def _map_file_to_client(filename, cache=norm_filename_to_client_container): # The result of this method will be passed to eclipse # So, this would be 'NormFileFromPythonToEclipse' try: return cache[filename] except KeyError: abs_path = absolute_path(filename) translated_proper_case = get_path_with_real_case(abs_path) translated_normalized = normcase(abs_path) path_mapping_applied = False if translated_normalized.lower() != translated_proper_case.lower(): if DEBUG_CLIENT_SERVER_TRANSLATION: pydev_log.critical( 'pydev debugger: translated_normalized changed path (from: %s to %s)', translated_proper_case, translated_normalized) for i, (eclipse_prefix, python_prefix) in enumerate(paths_from_eclipse_to_python): if translated_normalized.startswith(python_prefix): if DEBUG_CLIENT_SERVER_TRANSLATION: pydev_log.critical('pydev debugger: replacing to client: %s', translated_normalized) # Note: use the non-normalized version. eclipse_prefix = initial_paths[i][0] translated = eclipse_prefix + translated_proper_case[len(python_prefix):] if DEBUG_CLIENT_SERVER_TRANSLATION: pydev_log.critical('pydev debugger: sent to client: %s - matched prefix: %s', translated, python_prefix) path_mapping_applied = True break else: if DEBUG_CLIENT_SERVER_TRANSLATION: pydev_log.critical('pydev debugger: to client: unable to find matching prefix for: %s in %s', translated_normalized, [x[1] for x in paths_from_eclipse_to_python]) translated = translated_proper_case if eclipse_sep != python_sep: translated = translated.replace(python_sep, eclipse_sep) translated = _path_to_expected_str(translated) # The resulting path is not in the python process, so, we cannot do a normalize the path here, # only at the beginning of this method. cache[filename] = (translated, path_mapping_applied) if translated not in _client_filename_in_utf8_to_source_reference: if path_mapping_applied: source_reference = 0 else: source_reference = _next_source_reference() pydev_log.debug('Created source reference: %s for untranslated path: %s', source_reference, filename) _client_filename_in_utf8_to_source_reference[translated] = source_reference _source_reference_to_server_filename[source_reference] = filename return (translated, path_mapping_applied) map_file_to_server = _map_file_to_server map_file_to_client = _map_file_to_client setup_client_server_paths(PATHS_FROM_ECLIPSE_TO_PYTHON) # For given file f returns tuple of its absolute path, real path and base name def get_abs_path_real_path_and_base_from_file( filename, NORM_PATHS_AND_BASE_CONTAINER=NORM_PATHS_AND_BASE_CONTAINER): try: return NORM_PATHS_AND_BASE_CONTAINER[filename] except: f = filename if not f: # i.e.: it's possible that the user compiled code with an empty string (consider # it as <string> in this case). f = '<string>' if f.startswith('<'): return f, normcase(f), f if _abs_and_canonical_path is None: # Interpreter shutdown i = max(f.rfind('/'), f.rfind('\\')) return (f, f, f[i + 1:]) if f is not None: if f.endswith('.pyc'): f = f[:-1] elif f.endswith('$py.class'): f = f[:-len('$py.class')] + '.py' abs_path, canonical_normalized_filename = _abs_and_canonical_path(f) try: base = os_path_basename(canonical_normalized_filename) except AttributeError: # Error during shutdown. i = max(f.rfind('/'), f.rfind('\\')) base = f[i + 1:] ret = abs_path, canonical_normalized_filename, base NORM_PATHS_AND_BASE_CONTAINER[filename] = ret return ret def get_abs_path_real_path_and_base_from_frame(frame, NORM_PATHS_AND_BASE_CONTAINER=NORM_PATHS_AND_BASE_CONTAINER): try: return NORM_PATHS_AND_BASE_CONTAINER[frame.f_code.co_filename] except: # This one is just internal (so, does not need any kind of client-server translation) f = frame.f_code.co_filename if f is not None and f.startswith (('build/bdist.', 'build\\bdist.')): # files from eggs in Python 2.7 have paths like build/bdist.linux-x86_64/egg/<path-inside-egg> f = frame.f_globals['__file__'] if get_abs_path_real_path_and_base_from_file is None: # Interpreter shutdown if not f: # i.e.: it's possible that the user compiled code with an empty string (consider # it as <string> in this case). f = '<string>' i = max(f.rfind('/'), f.rfind('\\')) return f, f, f[i + 1:] ret = get_abs_path_real_path_and_base_from_file(f) # Also cache based on the frame.f_code.co_filename (if we had it inside build/bdist it can make a difference). NORM_PATHS_AND_BASE_CONTAINER[frame.f_code.co_filename] = ret return ret def get_fullname(mod_name): import pkgutil try: loader = pkgutil.get_loader(mod_name) except: return None if loader is not None: for attr in ("get_filename", "_get_filename"): meth = getattr(loader, attr, None) if meth is not None: return meth(mod_name) return None def get_package_dir(mod_name): for path in sys.path: mod_path = join(path, mod_name.replace('.', '/')) if os.path.isdir(mod_path): return mod_path return None
35,201
Python
37.598684
136
0.626431
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydevconsole.py
''' Entry point module to start the interactive console. ''' from _pydev_bundle._pydev_saved_modules import thread, _code from _pydevd_bundle.pydevd_constants import IS_JYTHON start_new_thread = thread.start_new_thread from _pydevd_bundle.pydevconsole_code import InteractiveConsole compile_command = _code.compile_command InteractiveInterpreter = _code.InteractiveInterpreter import os import sys from _pydev_bundle._pydev_saved_modules import threading from _pydevd_bundle.pydevd_constants import INTERACTIVE_MODE_AVAILABLE import traceback from _pydev_bundle import pydev_log from _pydevd_bundle import pydevd_save_locals from _pydev_bundle.pydev_imports import Exec, _queue import builtins as __builtin__ from _pydev_bundle.pydev_console_utils import BaseInterpreterInterface, BaseStdIn # @UnusedImport from _pydev_bundle.pydev_console_utils import CodeFragment class Command: def __init__(self, interpreter, code_fragment): """ :type code_fragment: CodeFragment :type interpreter: InteractiveConsole """ self.interpreter = interpreter self.code_fragment = code_fragment self.more = None def symbol_for_fragment(code_fragment): if code_fragment.is_single_line: symbol = 'single' else: if IS_JYTHON: symbol = 'single' # Jython doesn't support exec else: symbol = 'exec' return symbol symbol_for_fragment = staticmethod(symbol_for_fragment) def run(self): text = self.code_fragment.text symbol = self.symbol_for_fragment(self.code_fragment) self.more = self.interpreter.runsource(text, '<input>', symbol) try: from _pydev_bundle.pydev_imports import execfile __builtin__.execfile = execfile except: pass # Pull in runfile, the interface to UMD that wraps execfile from _pydev_bundle.pydev_umd import runfile, _set_globals_function if sys.version_info[0] >= 3: __builtin__.runfile = runfile else: __builtin__.runfile = runfile #======================================================================================================================= # InterpreterInterface #======================================================================================================================= class InterpreterInterface(BaseInterpreterInterface): ''' The methods in this class should be registered in the xml-rpc server. ''' def __init__(self, host, client_port, mainThread, connect_status_queue=None): BaseInterpreterInterface.__init__(self, mainThread, connect_status_queue) self.client_port = client_port self.host = host self.namespace = {} self.interpreter = InteractiveConsole(self.namespace) self._input_error_printed = False def do_add_exec(self, codeFragment): command = Command(self.interpreter, codeFragment) command.run() return command.more def get_namespace(self): return self.namespace def getCompletions(self, text, act_tok): try: from _pydev_bundle._pydev_completer import Completer completer = Completer(self.namespace, None) return completer.complete(act_tok) except: pydev_log.exception() return [] def close(self): sys.exit(0) def get_greeting_msg(self): return 'PyDev console: starting.\n' class _ProcessExecQueueHelper: _debug_hook = None _return_control_osc = False def set_debug_hook(debug_hook): _ProcessExecQueueHelper._debug_hook = debug_hook def activate_mpl_if_already_imported(interpreter): if interpreter.mpl_modules_for_patching: for module in list(interpreter.mpl_modules_for_patching): if module in sys.modules: activate_function = interpreter.mpl_modules_for_patching.pop(module) activate_function() def init_set_return_control_back(interpreter): from pydev_ipython.inputhook import set_return_control_callback def return_control(): ''' A function that the inputhooks can call (via inputhook.stdin_ready()) to find out if they should cede control and return ''' if _ProcessExecQueueHelper._debug_hook: # Some of the input hooks check return control without doing # a single operation, so we don't return True on every # call when the debug hook is in place to allow the GUI to run # XXX: Eventually the inputhook code will have diverged enough # from the IPython source that it will be worthwhile rewriting # it rather than pretending to maintain the old API _ProcessExecQueueHelper._return_control_osc = not _ProcessExecQueueHelper._return_control_osc if _ProcessExecQueueHelper._return_control_osc: return True if not interpreter.exec_queue.empty(): return True return False set_return_control_callback(return_control) def init_mpl_in_console(interpreter): init_set_return_control_back(interpreter) if not INTERACTIVE_MODE_AVAILABLE: return activate_mpl_if_already_imported(interpreter) from _pydev_bundle.pydev_import_hook import import_hook_manager for mod in list(interpreter.mpl_modules_for_patching): import_hook_manager.add_module_name(mod, interpreter.mpl_modules_for_patching.pop(mod)) if sys.platform != 'win32': if not hasattr(os, 'kill'): # Jython may not have it. def pid_exists(pid): return True else: def pid_exists(pid): # Note that this function in the face of errors will conservatively consider that # the pid is still running (because we'll exit the current process when it's # no longer running, so, we need to be 100% sure it actually exited). import errno if pid == 0: # According to "man 2 kill" PID 0 has a special meaning: # it refers to <<every process in the process group of the # calling process>> so we don't want to go any further. # If we get here it means this UNIX platform *does* have # a process with id 0. return True try: os.kill(pid, 0) except OSError as err: if err.errno == errno.ESRCH: # ESRCH == No such process return False elif err.errno == errno.EPERM: # EPERM clearly means there's a process to deny access to return True else: # According to "man 2 kill" possible error values are # (EINVAL, EPERM, ESRCH) therefore we should never get # here. If we do, although it's an error, consider it # exists (see first comment in this function). return True else: return True else: def pid_exists(pid): # Note that this function in the face of errors will conservatively consider that # the pid is still running (because we'll exit the current process when it's # no longer running, so, we need to be 100% sure it actually exited). import ctypes kernel32 = ctypes.windll.kernel32 PROCESS_QUERY_INFORMATION = 0x0400 PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 ERROR_INVALID_PARAMETER = 0x57 STILL_ACTIVE = 259 process = kernel32.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) if not process: err = kernel32.GetLastError() if err == ERROR_INVALID_PARAMETER: # Means it doesn't exist (pid parameter is wrong). return False # There was some unexpected error (such as access denied), so # consider it exists (although it could be something else, but we don't want # to raise any errors -- so, just consider it exists). return True try: zero = ctypes.c_int(0) exit_code = ctypes.pointer(zero) exit_code_suceeded = kernel32.GetExitCodeProcess(process, exit_code) if not exit_code_suceeded: # There was some unexpected error (such as access denied), so # consider it exists (although it could be something else, but we don't want # to raise any errors -- so, just consider it exists). return True elif bool(exit_code.contents.value) and int(exit_code.contents.value) != STILL_ACTIVE: return False finally: kernel32.CloseHandle(process) return True def process_exec_queue(interpreter): init_mpl_in_console(interpreter) from pydev_ipython.inputhook import get_inputhook try: kill_if_pid_not_alive = int(os.environ.get('PYDEV_ECLIPSE_PID', '-1')) except: kill_if_pid_not_alive = -1 while 1: if kill_if_pid_not_alive != -1: if not pid_exists(kill_if_pid_not_alive): exit() # Running the request may have changed the inputhook in use inputhook = get_inputhook() if _ProcessExecQueueHelper._debug_hook: _ProcessExecQueueHelper._debug_hook() if inputhook: try: # Note: it'll block here until return_control returns True. inputhook() except: pydev_log.exception() try: try: code_fragment = interpreter.exec_queue.get(block=True, timeout=1 / 20.) # 20 calls/second except _queue.Empty: continue if callable(code_fragment): # It can be a callable (i.e.: something that must run in the main # thread can be put in the queue for later execution). code_fragment() else: more = interpreter.add_exec(code_fragment) except KeyboardInterrupt: interpreter.buffer = None continue except SystemExit: raise except: pydev_log.exception('Error processing queue on pydevconsole.') exit() if 'IPYTHONENABLE' in os.environ: IPYTHON = os.environ['IPYTHONENABLE'] == 'True' else: # By default, don't use IPython because occasionally changes # in IPython break pydevd. IPYTHON = False try: try: exitfunc = sys.exitfunc except AttributeError: exitfunc = None if IPYTHON: from _pydev_bundle.pydev_ipython_console import InterpreterInterface if exitfunc is not None: sys.exitfunc = exitfunc else: try: delattr(sys, 'exitfunc') except: pass except: IPYTHON = False pass #======================================================================================================================= # _DoExit #======================================================================================================================= def do_exit(*args): ''' We have to override the exit because calling sys.exit will only actually exit the main thread, and as we're in a Xml-rpc server, that won't work. ''' try: import java.lang.System java.lang.System.exit(1) except ImportError: if len(args) == 1: os._exit(args[0]) else: os._exit(0) #======================================================================================================================= # start_console_server #======================================================================================================================= def start_console_server(host, port, interpreter): try: if port == 0: host = '' # I.e.: supporting the internal Jython version in PyDev to create a Jython interactive console inside Eclipse. from _pydev_bundle.pydev_imports import SimpleXMLRPCServer as XMLRPCServer # @Reimport try: server = XMLRPCServer((host, port), logRequests=False, allow_none=True) except: sys.stderr.write('Error starting server with host: "%s", port: "%s", client_port: "%s"\n' % (host, port, interpreter.client_port)) sys.stderr.flush() raise # Tell UMD the proper default namespace _set_globals_function(interpreter.get_namespace) server.register_function(interpreter.execLine) server.register_function(interpreter.execMultipleLines) server.register_function(interpreter.getCompletions) server.register_function(interpreter.getFrame) server.register_function(interpreter.getVariable) server.register_function(interpreter.changeVariable) server.register_function(interpreter.getDescription) server.register_function(interpreter.close) server.register_function(interpreter.interrupt) server.register_function(interpreter.handshake) server.register_function(interpreter.connectToDebugger) server.register_function(interpreter.hello) server.register_function(interpreter.getArray) server.register_function(interpreter.evaluate) server.register_function(interpreter.ShowConsole) server.register_function(interpreter.loadFullValue) # Functions for GUI main loop integration server.register_function(interpreter.enableGui) if port == 0: (h, port) = server.socket.getsockname() print(port) print(interpreter.client_port) while True: try: server.serve_forever() except: # Ugly code to be py2/3 compatible # https://sw-brainwy.rhcloud.com/tracker/PyDev/534: # Unhandled "interrupted system call" error in the pydevconsol.py e = sys.exc_info()[1] retry = False try: retry = e.args[0] == 4 # errno.EINTR except: pass if not retry: raise # Otherwise, keep on going return server except: pydev_log.exception() # Notify about error to avoid long waiting connection_queue = interpreter.get_connect_status_queue() if connection_queue is not None: connection_queue.put(False) def start_server(host, port, client_port): # replace exit (see comments on method) # note that this does not work in jython!!! (sys method can't be replaced). sys.exit = do_exit interpreter = InterpreterInterface(host, client_port, threading.current_thread()) start_new_thread(start_console_server, (host, port, interpreter)) process_exec_queue(interpreter) def get_ipython_hidden_vars(): if IPYTHON and hasattr(__builtin__, 'interpreter'): interpreter = get_interpreter() return interpreter.get_ipython_hidden_vars_dict() def get_interpreter(): try: interpreterInterface = getattr(__builtin__, 'interpreter') except AttributeError: interpreterInterface = InterpreterInterface(None, None, threading.current_thread()) __builtin__.interpreter = interpreterInterface sys.stderr.write(interpreterInterface.get_greeting_msg()) sys.stderr.flush() return interpreterInterface def get_completions(text, token, globals, locals): interpreterInterface = get_interpreter() interpreterInterface.interpreter.update(globals, locals) return interpreterInterface.getCompletions(text, token) #=============================================================================== # Debugger integration #=============================================================================== def exec_code(code, globals, locals, debugger): interpreterInterface = get_interpreter() interpreterInterface.interpreter.update(globals, locals) res = interpreterInterface.need_more(code) if res: return True interpreterInterface.add_exec(code, debugger) return False class ConsoleWriter(InteractiveInterpreter): skip = 0 def __init__(self, locals=None): InteractiveInterpreter.__init__(self, locals) def write(self, data): # if (data.find("global_vars") == -1 and data.find("pydevd") == -1): if self.skip > 0: self.skip -= 1 else: if data == "Traceback (most recent call last):\n": self.skip = 1 sys.stderr.write(data) def showsyntaxerror(self, filename=None): """Display the syntax error that just occurred.""" # Override for avoid using sys.excepthook PY-12600 type, value, tb = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb if filename and type is SyntaxError: # Work hard to stuff the correct filename in the exception try: msg, (dummy_filename, lineno, offset, line) = value.args except ValueError: # Not the format we expect; leave it alone pass else: # Stuff in the right filename value = SyntaxError(msg, (filename, lineno, offset, line)) sys.last_value = value list = traceback.format_exception_only(type, value) sys.stderr.write(''.join(list)) def showtraceback(self, *args, **kwargs): """Display the exception that just occurred.""" # Override for avoid using sys.excepthook PY-12600 try: type, value, tb = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb tblist = traceback.extract_tb(tb) del tblist[:1] lines = traceback.format_list(tblist) if lines: lines.insert(0, "Traceback (most recent call last):\n") lines.extend(traceback.format_exception_only(type, value)) finally: tblist = tb = None sys.stderr.write(''.join(lines)) def console_exec(thread_id, frame_id, expression, dbg): """returns 'False' in case expression is partially correct """ frame = dbg.find_frame(thread_id, frame_id) is_multiline = expression.count('@LINE@') > 1 expression = str(expression.replace('@LINE@', '\n')) # Not using frame.f_globals because of https://sourceforge.net/tracker2/?func=detail&aid=2541355&group_id=85796&atid=577329 # (Names not resolved in generator expression in method) # See message: http://mail.python.org/pipermail/python-list/2009-January/526522.html updated_globals = {} updated_globals.update(frame.f_globals) updated_globals.update(frame.f_locals) # locals later because it has precedence over the actual globals if IPYTHON: need_more = exec_code(CodeFragment(expression), updated_globals, frame.f_locals, dbg) if not need_more: pydevd_save_locals.save_locals(frame) return need_more interpreter = ConsoleWriter() if not is_multiline: try: code = compile_command(expression) except (OverflowError, SyntaxError, ValueError): # Case 1 interpreter.showsyntaxerror() return False if code is None: # Case 2 return True else: code = expression # Case 3 try: Exec(code, updated_globals, frame.f_locals) except SystemExit: raise except: interpreter.showtraceback() else: pydevd_save_locals.save_locals(frame) return False #======================================================================================================================= # main #======================================================================================================================= if __name__ == '__main__': # Important: don't use this module directly as the __main__ module, rather, import itself as pydevconsole # so that we don't get multiple pydevconsole modules if it's executed directly (otherwise we'd have multiple # representations of its classes). # See: https://sw-brainwy.rhcloud.com/tracker/PyDev/446: # 'Variables' and 'Expressions' views stopped working when debugging interactive console import pydevconsole sys.stdin = pydevconsole.BaseStdIn(sys.stdin) port, client_port = sys.argv[1:3] from _pydev_bundle import pydev_localhost if int(port) == 0 and int(client_port) == 0: (h, p) = pydev_localhost.get_socket_name() client_port = p pydevconsole.start_server(pydev_localhost.get_localhost(), int(port), int(client_port))
21,094
Python
33.925497
142
0.589504
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_run_in_console.py
''' Entry point module to run a file in the interactive console. ''' import os import sys import traceback from pydevconsole import InterpreterInterface, process_exec_queue, start_console_server, init_mpl_in_console from _pydev_bundle._pydev_saved_modules import threading, _queue from _pydev_bundle import pydev_imports from _pydevd_bundle.pydevd_utils import save_main_module from _pydev_bundle.pydev_console_utils import StdIn from pydevd_file_utils import get_fullname def run_file(file, globals=None, locals=None, is_module=False): module_name = None entry_point_fn = None if is_module: file, _, entry_point_fn = file.partition(':') module_name = file filename = get_fullname(file) if filename is None: sys.stderr.write("No module named %s\n" % file) return else: file = filename if os.path.isdir(file): new_target = os.path.join(file, '__main__.py') if os.path.isfile(new_target): file = new_target if globals is None: m = save_main_module(file, 'pydev_run_in_console') globals = m.__dict__ try: globals['__builtins__'] = __builtins__ except NameError: pass # Not there on Jython... if locals is None: locals = globals if not is_module: sys.path.insert(0, os.path.split(file)[0]) print('Running %s' % file) try: if not is_module: pydev_imports.execfile(file, globals, locals) # execute the script else: # treat ':' as a seperator between module and entry point function # if there is no entry point we run we same as with -m switch. Otherwise we perform # an import and execute the entry point if entry_point_fn: mod = __import__(module_name, level=0, fromlist=[entry_point_fn], globals=globals, locals=locals) func = getattr(mod, entry_point_fn) func() else: # Run with the -m switch from _pydevd_bundle import pydevd_runpy pydevd_runpy._run_module_as_main(module_name) except: traceback.print_exc() return globals def skip_successful_exit(*args): """ System exit in file shouldn't kill interpreter (i.e. in `timeit`)""" if len(args) == 1 and args[0] in (0, None): pass else: raise SystemExit(*args) def process_args(argv): setup_args = {'file': '', 'module': False} setup_args['port'] = argv[1] del argv[1] setup_args['client_port'] = argv[1] del argv[1] module_flag = "--module" if module_flag in argv: i = argv.index(module_flag) if i != -1: setup_args['module'] = True setup_args['file'] = argv[i + 1] del sys.argv[i] else: setup_args['file'] = argv[1] del argv[0] return setup_args #======================================================================================================================= # main #======================================================================================================================= if __name__ == '__main__': setup = process_args(sys.argv) port = setup['port'] client_port = setup['client_port'] file = setup['file'] is_module = setup['module'] from _pydev_bundle import pydev_localhost if int(port) == 0 and int(client_port) == 0: (h, p) = pydev_localhost.get_socket_name() client_port = p host = pydev_localhost.get_localhost() # replace exit (see comments on method) # note that this does not work in jython!!! (sys method can't be replaced). sys.exit = skip_successful_exit connect_status_queue = _queue.Queue() interpreter = InterpreterInterface(host, int(client_port), threading.current_thread(), connect_status_queue=connect_status_queue) server_thread = threading.Thread(target=start_console_server, name='ServerThread', args=(host, int(port), interpreter)) server_thread.daemon = True server_thread.start() sys.stdin = StdIn(interpreter, host, client_port, sys.stdin) init_mpl_in_console(interpreter) try: success = connect_status_queue.get(True, 60) if not success: raise ValueError() except: sys.stderr.write("Console server didn't start\n") sys.stderr.flush() sys.exit(1) globals = run_file(file, None, None, is_module) interpreter.get_namespace().update(globals) interpreter.ShowConsole() process_exec_queue(interpreter)
4,709
Python
29.584415
133
0.568061
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/pydev_coverage.py
''' Entry point module to run code-coverage. ''' def is_valid_py_file(path): ''' Checks whether the file can be read by the coverage module. This is especially needed for .pyx files and .py files with syntax errors. ''' import os is_valid = False if os.path.isfile(path) and not os.path.splitext(path)[1] == '.pyx': try: with open(path, 'rb') as f: compile(f.read(), path, 'exec') is_valid = True except: pass return is_valid def execute(): import os import sys files = None if 'combine' not in sys.argv: if '--pydev-analyze' in sys.argv: # Ok, what we want here is having the files passed through stdin (because # there may be too many files for passing in the command line -- we could # just pass a dir and make the find files here, but as that's already # given in the java side, let's just gather that info here). sys.argv.remove('--pydev-analyze') s = input() s = s.replace('\r', '') s = s.replace('\n', '') files = [] invalid_files = [] for v in s.split('|'): if is_valid_py_file(v): files.append(v) else: invalid_files.append(v) if invalid_files: sys.stderr.write('Invalid files not passed to coverage: %s\n' % ', '.join(invalid_files)) # Note that in this case we'll already be in the working dir with the coverage files, # so, the coverage file location is not passed. else: # For all commands, the coverage file is configured in pydev, and passed as the first # argument in the command line, so, let's make sure this gets to the coverage module. os.environ['COVERAGE_FILE'] = sys.argv[1] del sys.argv[1] try: import coverage # @UnresolvedImport except: sys.stderr.write('Error: coverage module could not be imported\n') sys.stderr.write('Please make sure that the coverage module ' '(http://nedbatchelder.com/code/coverage/)\n') sys.stderr.write('is properly installed in your interpreter: %s\n' % (sys.executable,)) import traceback;traceback.print_exc() return if hasattr(coverage, '__version__'): version = tuple(map(int, coverage.__version__.split('.')[:2])) if version < (4, 3): sys.stderr.write('Error: minimum supported coverage version is 4.3.' '\nFound: %s\nLocation: %s\n' % ('.'.join(str(x) for x in version), coverage.__file__)) sys.exit(1) else: sys.stderr.write('Warning: Could not determine version of python module coverage.' '\nEnsure coverage version is >= 4.3\n') from coverage.cmdline import main # @UnresolvedImport if files is not None: sys.argv.append('xml') sys.argv += files main() if __name__ == '__main__': execute()
3,200
Python
32.694736
97
0.545312
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles_parallel.py
import unittest from _pydev_bundle._pydev_saved_modules import thread import queue as Queue from _pydev_runfiles import pydev_runfiles_xml_rpc import time import os import threading import sys #======================================================================================================================= # flatten_test_suite #======================================================================================================================= def flatten_test_suite(test_suite, ret): if isinstance(test_suite, unittest.TestSuite): for t in test_suite._tests: flatten_test_suite(t, ret) elif isinstance(test_suite, unittest.TestCase): ret.append(test_suite) #======================================================================================================================= # execute_tests_in_parallel #======================================================================================================================= def execute_tests_in_parallel(tests, jobs, split, verbosity, coverage_files, coverage_include): ''' @param tests: list(PydevTestSuite) A list with the suites to be run @param split: str Either 'module' or the number of tests that should be run in each batch @param coverage_files: list(file) A list with the files that should be used for giving coverage information (if empty, coverage information should not be gathered). @param coverage_include: str The pattern that should be included in the coverage. @return: bool Returns True if the tests were actually executed in parallel. If the tests were not executed because only 1 should be used (e.g.: 2 jobs were requested for running 1 test), False will be returned and no tests will be run. It may also return False if in debug mode (in which case, multi-processes are not accepted) ''' try: from _pydevd_bundle.pydevd_comm import get_global_debugger if get_global_debugger() is not None: return False except: pass # Ignore any error here. # This queue will receive the tests to be run. Each entry in a queue is a list with the tests to be run together When # split == 'tests', each list will have a single element, when split == 'module', each list will have all the tests # from a given module. tests_queue = [] queue_elements = [] if split == 'module': module_to_tests = {} for test in tests: lst = [] flatten_test_suite(test, lst) for test in lst: key = (test.__pydev_pyfile__, test.__pydev_module_name__) module_to_tests.setdefault(key, []).append(test) for key, tests in module_to_tests.items(): queue_elements.append(tests) if len(queue_elements) < jobs: # Don't create jobs we will never use. jobs = len(queue_elements) elif split == 'tests': for test in tests: lst = [] flatten_test_suite(test, lst) for test in lst: queue_elements.append([test]) if len(queue_elements) < jobs: # Don't create jobs we will never use. jobs = len(queue_elements) else: raise AssertionError('Do not know how to handle: %s' % (split,)) for test_cases in queue_elements: test_queue_elements = [] for test_case in test_cases: try: test_name = test_case.__class__.__name__ + "." + test_case._testMethodName except AttributeError: # Support for jython 2.1 (__testMethodName is pseudo-private in the test case) test_name = test_case.__class__.__name__ + "." + test_case._TestCase__testMethodName test_queue_elements.append(test_case.__pydev_pyfile__ + '|' + test_name) tests_queue.append(test_queue_elements) if jobs < 2: return False sys.stdout.write('Running tests in parallel with: %s jobs.\n' % (jobs,)) queue = Queue.Queue() for item in tests_queue: queue.put(item, block=False) providers = [] clients = [] for i in range(jobs): test_cases_provider = CommunicationThread(queue) providers.append(test_cases_provider) test_cases_provider.start() port = test_cases_provider.port if coverage_files: clients.append(ClientThread(i, port, verbosity, coverage_files.pop(0), coverage_include)) else: clients.append(ClientThread(i, port, verbosity)) for client in clients: client.start() client_alive = True while client_alive: client_alive = False for client in clients: # Wait for all the clients to exit. if not client.finished: client_alive = True time.sleep(.2) break for provider in providers: provider.shutdown() return True #======================================================================================================================= # CommunicationThread #======================================================================================================================= class CommunicationThread(threading.Thread): def __init__(self, tests_queue): threading.Thread.__init__(self) self.daemon = True self.queue = tests_queue self.finished = False from _pydev_bundle.pydev_imports import SimpleXMLRPCServer from _pydev_bundle import pydev_localhost # Create server server = SimpleXMLRPCServer((pydev_localhost.get_localhost(), 0), logRequests=False) server.register_function(self.GetTestsToRun) server.register_function(self.notifyStartTest) server.register_function(self.notifyTest) server.register_function(self.notifyCommands) self.port = server.socket.getsockname()[1] self.server = server def GetTestsToRun(self, job_id): ''' @param job_id: @return: list(str) Each entry is a string in the format: filename|Test.testName ''' try: ret = self.queue.get(block=False) return ret except: # Any exception getting from the queue (empty or not) means we finished our work on providing the tests. self.finished = True return [] def notifyCommands(self, job_id, commands): # Batch notification. for command in commands: getattr(self, command[0])(job_id, *command[1], **command[2]) return True def notifyStartTest(self, job_id, *args, **kwargs): pydev_runfiles_xml_rpc.notifyStartTest(*args, **kwargs) return True def notifyTest(self, job_id, *args, **kwargs): pydev_runfiles_xml_rpc.notifyTest(*args, **kwargs) return True def shutdown(self): if hasattr(self.server, 'shutdown'): self.server.shutdown() else: self._shutdown = True def run(self): if hasattr(self.server, 'shutdown'): self.server.serve_forever() else: self._shutdown = False while not self._shutdown: self.server.handle_request() #======================================================================================================================= # Client #======================================================================================================================= class ClientThread(threading.Thread): def __init__(self, job_id, port, verbosity, coverage_output_file=None, coverage_include=None): threading.Thread.__init__(self) self.daemon = True self.port = port self.job_id = job_id self.verbosity = verbosity self.finished = False self.coverage_output_file = coverage_output_file self.coverage_include = coverage_include def _reader_thread(self, pipe, target): while True: target.write(pipe.read(1)) def run(self): try: from _pydev_runfiles import pydev_runfiles_parallel_client # TODO: Support Jython: # # For jython, instead of using sys.executable, we should use: # r'D:\bin\jdk_1_5_09\bin\java.exe', # '-classpath', # 'D:/bin/jython-2.2.1/jython.jar', # 'org.python.util.jython', args = [ sys.executable, pydev_runfiles_parallel_client.__file__, str(self.job_id), str(self.port), str(self.verbosity), ] if self.coverage_output_file and self.coverage_include: args.append(self.coverage_output_file) args.append(self.coverage_include) import subprocess if False: proc = subprocess.Popen(args, env=os.environ, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) thread.start_new_thread(self._reader_thread, (proc.stdout, sys.stdout)) thread.start_new_thread(target=self._reader_thread, args=(proc.stderr, sys.stderr)) else: proc = subprocess.Popen(args, env=os.environ, shell=False) proc.wait() finally: self.finished = True
9,472
Python
34.347015
122
0.537162
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles_xml_rpc.py
import sys import threading import traceback import warnings from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding from _pydev_bundle.pydev_imports import xmlrpclib, _queue from _pydevd_bundle.pydevd_constants import Null Queue = _queue.Queue # This may happen in IronPython (in Python it shouldn't happen as there are # 'fast' replacements that are used in xmlrpclib.py) warnings.filterwarnings( 'ignore', 'The xmllib module is obsolete.*', DeprecationWarning) file_system_encoding = getfilesystemencoding() #======================================================================================================================= # _ServerHolder #======================================================================================================================= class _ServerHolder: ''' Helper so that we don't have to use a global here. ''' SERVER = None #======================================================================================================================= # set_server #======================================================================================================================= def set_server(server): _ServerHolder.SERVER = server #======================================================================================================================= # ParallelNotification #======================================================================================================================= class ParallelNotification(object): def __init__(self, method, args): self.method = method self.args = args def to_tuple(self): return self.method, self.args #======================================================================================================================= # KillServer #======================================================================================================================= class KillServer(object): pass #======================================================================================================================= # ServerFacade #======================================================================================================================= class ServerFacade(object): def __init__(self, notifications_queue): self.notifications_queue = notifications_queue def notifyTestsCollected(self, *args): self.notifications_queue.put_nowait(ParallelNotification('notifyTestsCollected', args)) def notifyConnected(self, *args): self.notifications_queue.put_nowait(ParallelNotification('notifyConnected', args)) def notifyTestRunFinished(self, *args): self.notifications_queue.put_nowait(ParallelNotification('notifyTestRunFinished', args)) def notifyStartTest(self, *args): self.notifications_queue.put_nowait(ParallelNotification('notifyStartTest', args)) def notifyTest(self, *args): new_args = [] for arg in args: new_args.append(_encode_if_needed(arg)) args = tuple(new_args) self.notifications_queue.put_nowait(ParallelNotification('notifyTest', args)) #======================================================================================================================= # ServerComm #======================================================================================================================= class ServerComm(threading.Thread): def __init__(self, notifications_queue, port, daemon=False): threading.Thread.__init__(self) self.setDaemon(daemon) # If False, wait for all the notifications to be passed before exiting! self.finished = False self.notifications_queue = notifications_queue from _pydev_bundle import pydev_localhost # It is necessary to specify an encoding, that matches # the encoding of all bytes-strings passed into an # XMLRPC call: "All 8-bit strings in the data structure are assumed to use the # packet encoding. Unicode strings are automatically converted, # where necessary." # Byte strings most likely come from file names. encoding = file_system_encoding if encoding == "mbcs": # Windos symbolic name for the system encoding CP_ACP. # We need to convert it into a encoding that is recognized by Java. # Unfortunately this is not always possible. You could use # GetCPInfoEx and get a name similar to "windows-1251". Then # you need a table to translate on a best effort basis. Much to complicated. # ISO-8859-1 is good enough. encoding = "ISO-8859-1" self.server = xmlrpclib.Server('http://%s:%s' % (pydev_localhost.get_localhost(), port), encoding=encoding) def run(self): while True: kill_found = False commands = [] command = self.notifications_queue.get(block=True) if isinstance(command, KillServer): kill_found = True else: assert isinstance(command, ParallelNotification) commands.append(command.to_tuple()) try: while True: command = self.notifications_queue.get(block=False) # No block to create a batch. if isinstance(command, KillServer): kill_found = True else: assert isinstance(command, ParallelNotification) commands.append(command.to_tuple()) except: pass # That's OK, we're getting it until it becomes empty so that we notify multiple at once. if commands: try: self.server.notifyCommands(commands) except: traceback.print_exc() if kill_found: self.finished = True return #======================================================================================================================= # initialize_server #======================================================================================================================= def initialize_server(port, daemon=False): if _ServerHolder.SERVER is None: if port is not None: notifications_queue = Queue() _ServerHolder.SERVER = ServerFacade(notifications_queue) _ServerHolder.SERVER_COMM = ServerComm(notifications_queue, port, daemon) _ServerHolder.SERVER_COMM.start() else: # Create a null server, so that we keep the interface even without any connection. _ServerHolder.SERVER = Null() _ServerHolder.SERVER_COMM = Null() try: _ServerHolder.SERVER.notifyConnected() except: traceback.print_exc() #======================================================================================================================= # notifyTest #======================================================================================================================= def notifyTestsCollected(tests_count): assert tests_count is not None try: _ServerHolder.SERVER.notifyTestsCollected(tests_count) except: traceback.print_exc() #======================================================================================================================= # notifyStartTest #======================================================================================================================= def notifyStartTest(file, test): ''' @param file: the tests file (c:/temp/test.py) @param test: the test ran (i.e.: TestCase.test1) ''' assert file is not None if test is None: test = '' # Could happen if we have an import error importing module. try: _ServerHolder.SERVER.notifyStartTest(file, test) except: traceback.print_exc() def _encode_if_needed(obj): # In the java side we expect strings to be ISO-8859-1 (org.python.pydev.debug.pyunit.PyUnitServer.initializeDispatches().new Dispatch() {...}.getAsStr(Object)) if isinstance(obj, str): # Unicode in py3 return xmlrpclib.Binary(obj.encode('ISO-8859-1', 'xmlcharrefreplace')) elif isinstance(obj, bytes): try: return xmlrpclib.Binary(obj.decode(sys.stdin.encoding).encode('ISO-8859-1', 'xmlcharrefreplace')) except: return xmlrpclib.Binary(obj) # bytes already return obj #======================================================================================================================= # notifyTest #======================================================================================================================= def notifyTest(cond, captured_output, error_contents, file, test, time): ''' @param cond: ok, fail, error @param captured_output: output captured from stdout @param captured_output: output captured from stderr @param file: the tests file (c:/temp/test.py) @param test: the test ran (i.e.: TestCase.test1) @param time: float with the number of seconds elapsed ''' assert cond is not None assert captured_output is not None assert error_contents is not None assert file is not None if test is None: test = '' # Could happen if we have an import error importing module. assert time is not None try: captured_output = _encode_if_needed(captured_output) error_contents = _encode_if_needed(error_contents) _ServerHolder.SERVER.notifyTest(cond, captured_output, error_contents, file, test, time) except: traceback.print_exc() #======================================================================================================================= # notifyTestRunFinished #======================================================================================================================= def notifyTestRunFinished(total_time): assert total_time is not None try: _ServerHolder.SERVER.notifyTestRunFinished(total_time) except: traceback.print_exc() #======================================================================================================================= # force_server_kill #======================================================================================================================= def force_server_kill(): _ServerHolder.SERVER_COMM.notifications_queue.put_nowait(KillServer())
10,594
Python
40.065891
163
0.46885
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles.py
from __future__ import nested_scopes import fnmatch import os.path from _pydev_runfiles.pydev_runfiles_coverage import start_coverage_support from _pydevd_bundle.pydevd_constants import * # @UnusedWildImport import re import time #======================================================================================================================= # Configuration #======================================================================================================================= class Configuration: def __init__( self, files_or_dirs='', verbosity=2, include_tests=None, tests=None, port=None, files_to_tests=None, jobs=1, split_jobs='tests', coverage_output_dir=None, coverage_include=None, coverage_output_file=None, exclude_files=None, exclude_tests=None, include_files=None, django=False, ): self.files_or_dirs = files_or_dirs self.verbosity = verbosity self.include_tests = include_tests self.tests = tests self.port = port self.files_to_tests = files_to_tests self.jobs = jobs self.split_jobs = split_jobs self.django = django if include_tests: assert isinstance(include_tests, (list, tuple)) if exclude_files: assert isinstance(exclude_files, (list, tuple)) if exclude_tests: assert isinstance(exclude_tests, (list, tuple)) self.exclude_files = exclude_files self.include_files = include_files self.exclude_tests = exclude_tests self.coverage_output_dir = coverage_output_dir self.coverage_include = coverage_include self.coverage_output_file = coverage_output_file def __str__(self): return '''Configuration - files_or_dirs: %s - verbosity: %s - tests: %s - port: %s - files_to_tests: %s - jobs: %s - split_jobs: %s - include_files: %s - include_tests: %s - exclude_files: %s - exclude_tests: %s - coverage_output_dir: %s - coverage_include_dir: %s - coverage_output_file: %s - django: %s ''' % ( self.files_or_dirs, self.verbosity, self.tests, self.port, self.files_to_tests, self.jobs, self.split_jobs, self.include_files, self.include_tests, self.exclude_files, self.exclude_tests, self.coverage_output_dir, self.coverage_include, self.coverage_output_file, self.django, ) #======================================================================================================================= # parse_cmdline #======================================================================================================================= def parse_cmdline(argv=None): """ Parses command line and returns test directories, verbosity, test filter and test suites usage: runfiles.py -v|--verbosity <level> -t|--tests <Test.test1,Test2> dirs|files Multiprocessing options: jobs=number (with the number of jobs to be used to run the tests) split_jobs='module'|'tests' if == module, a given job will always receive all the tests from a module if == tests, the tests will be split independently of their originating module (default) --exclude_files = comma-separated list of patterns with files to exclude (fnmatch style) --include_files = comma-separated list of patterns with files to include (fnmatch style) --exclude_tests = comma-separated list of patterns with test names to exclude (fnmatch style) Note: if --tests is given, --exclude_files, --include_files and --exclude_tests are ignored! """ if argv is None: argv = sys.argv verbosity = 2 include_tests = None tests = None port = None jobs = 1 split_jobs = 'tests' files_to_tests = {} coverage_output_dir = None coverage_include = None exclude_files = None exclude_tests = None include_files = None django = False from _pydev_bundle._pydev_getopt import gnu_getopt optlist, dirs = gnu_getopt( argv[1:], "", [ "verbosity=", "tests=", "port=", "config_file=", "jobs=", "split_jobs=", "include_tests=", "include_files=", "exclude_files=", "exclude_tests=", "coverage_output_dir=", "coverage_include=", "django=" ] ) for opt, value in optlist: if opt in ("-v", "--verbosity"): verbosity = value elif opt in ("-p", "--port"): port = int(value) elif opt in ("-j", "--jobs"): jobs = int(value) elif opt in ("-s", "--split_jobs"): split_jobs = value if split_jobs not in ('module', 'tests'): raise AssertionError('Expected split to be either "module" or "tests". Was :%s' % (split_jobs,)) elif opt in ("-d", "--coverage_output_dir",): coverage_output_dir = value.strip() elif opt in ("-i", "--coverage_include",): coverage_include = value.strip() elif opt in ("-I", "--include_tests"): include_tests = value.split(',') elif opt in ("-E", "--exclude_files"): exclude_files = value.split(',') elif opt in ("-F", "--include_files"): include_files = value.split(',') elif opt in ("-e", "--exclude_tests"): exclude_tests = value.split(',') elif opt in ("-t", "--tests"): tests = value.split(',') elif opt in ("--django",): django = value.strip() in ['true', 'True', '1'] elif opt in ("-c", "--config_file"): config_file = value.strip() if os.path.exists(config_file): f = open(config_file, 'r') try: config_file_contents = f.read() finally: f.close() if config_file_contents: config_file_contents = config_file_contents.strip() if config_file_contents: for line in config_file_contents.splitlines(): file_and_test = line.split('|') if len(file_and_test) == 2: file, test = file_and_test if file in files_to_tests: files_to_tests[file].append(test) else: files_to_tests[file] = [test] else: sys.stderr.write('Could not find config file: %s\n' % (config_file,)) if type([]) != type(dirs): dirs = [dirs] ret_dirs = [] for d in dirs: if '|' in d: # paths may come from the ide separated by | ret_dirs.extend(d.split('|')) else: ret_dirs.append(d) verbosity = int(verbosity) if tests: if verbosity > 4: sys.stdout.write('--tests provided. Ignoring --exclude_files, --exclude_tests and --include_files\n') exclude_files = exclude_tests = include_files = None config = Configuration( ret_dirs, verbosity, include_tests, tests, port, files_to_tests, jobs, split_jobs, coverage_output_dir, coverage_include, exclude_files=exclude_files, exclude_tests=exclude_tests, include_files=include_files, django=django, ) if verbosity > 5: sys.stdout.write(str(config) + '\n') return config #======================================================================================================================= # PydevTestRunner #======================================================================================================================= class PydevTestRunner(object): """ finds and runs a file or directory of files as a unit test """ __py_extensions = ["*.py", "*.pyw"] __exclude_files = ["__init__.*"] # Just to check that only this attributes will be written to this file __slots__ = [ 'verbosity', # Always used 'files_to_tests', # If this one is given, the ones below are not used 'files_or_dirs', # Files or directories received in the command line 'include_tests', # The filter used to collect the tests 'tests', # Strings with the tests to be run 'jobs', # Integer with the number of jobs that should be used to run the test cases 'split_jobs', # String with 'tests' or 'module' (how should the jobs be split) 'configuration', 'coverage', ] def __init__(self, configuration): self.verbosity = configuration.verbosity self.jobs = configuration.jobs self.split_jobs = configuration.split_jobs files_to_tests = configuration.files_to_tests if files_to_tests: self.files_to_tests = files_to_tests self.files_or_dirs = list(files_to_tests.keys()) self.tests = None else: self.files_to_tests = {} self.files_or_dirs = configuration.files_or_dirs self.tests = configuration.tests self.configuration = configuration self.__adjust_path() def __adjust_path(self): """ add the current file or directory to the python path """ path_to_append = None for n in range(len(self.files_or_dirs)): dir_name = self.__unixify(self.files_or_dirs[n]) if os.path.isdir(dir_name): if not dir_name.endswith("/"): self.files_or_dirs[n] = dir_name + "/" path_to_append = os.path.normpath(dir_name) elif os.path.isfile(dir_name): path_to_append = os.path.dirname(dir_name) else: if not os.path.exists(dir_name): block_line = '*' * 120 sys.stderr.write('\n%s\n* PyDev test runner error: %s does not exist.\n%s\n' % (block_line, dir_name, block_line)) return msg = ("unknown type. \n%s\nshould be file or a directory.\n" % (dir_name)) raise RuntimeError(msg) if path_to_append is not None: # Add it as the last one (so, first things are resolved against the default dirs and # if none resolves, then we try a relative import). sys.path.append(path_to_append) def __is_valid_py_file(self, fname): """ tests that a particular file contains the proper file extension and is not in the list of files to exclude """ is_valid_fname = 0 for invalid_fname in self.__class__.__exclude_files: is_valid_fname += int(not fnmatch.fnmatch(fname, invalid_fname)) if_valid_ext = 0 for ext in self.__class__.__py_extensions: if_valid_ext += int(fnmatch.fnmatch(fname, ext)) return is_valid_fname > 0 and if_valid_ext > 0 def __unixify(self, s): """ stupid windows. converts the backslash to forwardslash for consistency """ return os.path.normpath(s).replace(os.sep, "/") def __importify(self, s, dir=False): """ turns directory separators into dots and removes the ".py*" extension so the string can be used as import statement """ if not dir: dirname, fname = os.path.split(s) if fname.count('.') > 1: # if there's a file named xxx.xx.py, it is not a valid module, so, let's not load it... return imp_stmt_pieces = [dirname.replace("\\", "/").replace("/", "."), os.path.splitext(fname)[0]] if len(imp_stmt_pieces[0]) == 0: imp_stmt_pieces = imp_stmt_pieces[1:] return ".".join(imp_stmt_pieces) else: # handle dir return s.replace("\\", "/").replace("/", ".") def __add_files(self, pyfiles, root, files): """ if files match, appends them to pyfiles. used by os.path.walk fcn """ for fname in files: if self.__is_valid_py_file(fname): name_without_base_dir = self.__unixify(os.path.join(root, fname)) pyfiles.append(name_without_base_dir) def find_import_files(self): """ return a list of files to import """ if self.files_to_tests: pyfiles = self.files_to_tests.keys() else: pyfiles = [] for base_dir in self.files_or_dirs: if os.path.isdir(base_dir): for root, dirs, files in os.walk(base_dir): # Note: handling directories that should be excluded from the search because # they don't have __init__.py exclude = {} for d in dirs: for init in ['__init__.py', '__init__.pyo', '__init__.pyc', '__init__.pyw', '__init__$py.class']: if os.path.exists(os.path.join(root, d, init).replace('\\', '/')): break else: exclude[d] = 1 if exclude: new = [] for d in dirs: if d not in exclude: new.append(d) dirs[:] = new self.__add_files(pyfiles, root, files) elif os.path.isfile(base_dir): pyfiles.append(base_dir) if self.configuration.exclude_files or self.configuration.include_files: ret = [] for f in pyfiles: add = True basename = os.path.basename(f) if self.configuration.include_files: add = False for pat in self.configuration.include_files: if fnmatch.fnmatchcase(basename, pat): add = True break if not add: if self.verbosity > 3: sys.stdout.write('Skipped file: %s (did not match any include_files pattern: %s)\n' % (f, self.configuration.include_files)) elif self.configuration.exclude_files: for pat in self.configuration.exclude_files: if fnmatch.fnmatchcase(basename, pat): if self.verbosity > 3: sys.stdout.write('Skipped file: %s (matched exclude_files pattern: %s)\n' % (f, pat)) elif self.verbosity > 2: sys.stdout.write('Skipped file: %s\n' % (f,)) add = False break if add: if self.verbosity > 3: sys.stdout.write('Adding file: %s for test discovery.\n' % (f,)) ret.append(f) pyfiles = ret return pyfiles def __get_module_from_str(self, modname, print_exception, pyfile): """ Import the module in the given import path. * Returns the "final" module, so importing "coilib40.subject.visu" returns the "visu" module, not the "coilib40" as returned by __import__ """ try: mod = __import__(modname) for part in modname.split('.')[1:]: mod = getattr(mod, part) return mod except: if print_exception: from _pydev_runfiles import pydev_runfiles_xml_rpc from _pydevd_bundle import pydevd_io buf_err = pydevd_io.start_redirect(keep_original_redirection=True, std='stderr') buf_out = pydevd_io.start_redirect(keep_original_redirection=True, std='stdout') try: import traceback;traceback.print_exc() sys.stderr.write('ERROR: Module: %s could not be imported (file: %s).\n' % (modname, pyfile)) finally: pydevd_io.end_redirect('stderr') pydevd_io.end_redirect('stdout') pydev_runfiles_xml_rpc.notifyTest( 'error', buf_out.getvalue(), buf_err.getvalue(), pyfile, modname, 0) return None def remove_duplicates_keeping_order(self, seq): seen = set() seen_add = seen.add return [x for x in seq if not (x in seen or seen_add(x))] def find_modules_from_files(self, pyfiles): """ returns a list of modules given a list of files """ # let's make sure that the paths we want are in the pythonpath... imports = [(s, self.__importify(s)) for s in pyfiles] sys_path = [os.path.normpath(path) for path in sys.path] sys_path = self.remove_duplicates_keeping_order(sys_path) system_paths = [] for s in sys_path: system_paths.append(self.__importify(s, True)) ret = [] for pyfile, imp in imports: if imp is None: continue # can happen if a file is not a valid module choices = [] for s in system_paths: if imp.startswith(s): add = imp[len(s) + 1:] if add: choices.append(add) # sys.stdout.write(' ' + add + ' ') if not choices: sys.stdout.write('PYTHONPATH not found for file: %s\n' % imp) else: for i, import_str in enumerate(choices): print_exception = i == len(choices) - 1 mod = self.__get_module_from_str(import_str, print_exception, pyfile) if mod is not None: ret.append((pyfile, mod, import_str)) break return ret #=================================================================================================================== # GetTestCaseNames #=================================================================================================================== class GetTestCaseNames: """Yes, we need a class for that (cannot use outer context on jython 2.1)""" def __init__(self, accepted_classes, accepted_methods): self.accepted_classes = accepted_classes self.accepted_methods = accepted_methods def __call__(self, testCaseClass): """Return a sorted sequence of method names found within testCaseClass""" testFnNames = [] className = testCaseClass.__name__ if className in self.accepted_classes: for attrname in dir(testCaseClass): # If a class is chosen, we select all the 'test' methods' if attrname.startswith('test') and hasattr(getattr(testCaseClass, attrname), '__call__'): testFnNames.append(attrname) else: for attrname in dir(testCaseClass): # If we have the class+method name, we must do a full check and have an exact match. if className + '.' + attrname in self.accepted_methods: if hasattr(getattr(testCaseClass, attrname), '__call__'): testFnNames.append(attrname) # sorted() is not available in jython 2.1 testFnNames.sort() return testFnNames def _decorate_test_suite(self, suite, pyfile, module_name): import unittest if isinstance(suite, unittest.TestSuite): add = False suite.__pydev_pyfile__ = pyfile suite.__pydev_module_name__ = module_name for t in suite._tests: t.__pydev_pyfile__ = pyfile t.__pydev_module_name__ = module_name if self._decorate_test_suite(t, pyfile, module_name): add = True return add elif isinstance(suite, unittest.TestCase): return True else: return False def find_tests_from_modules(self, file_and_modules_and_module_name): """ returns the unittests given a list of modules """ # Use our own suite! from _pydev_runfiles import pydev_runfiles_unittest import unittest unittest.TestLoader.suiteClass = pydev_runfiles_unittest.PydevTestSuite loader = unittest.TestLoader() ret = [] if self.files_to_tests: for pyfile, m, module_name in file_and_modules_and_module_name: accepted_classes = {} accepted_methods = {} tests = self.files_to_tests[pyfile] for t in tests: accepted_methods[t] = t loader.getTestCaseNames = self.GetTestCaseNames(accepted_classes, accepted_methods) suite = loader.loadTestsFromModule(m) if self._decorate_test_suite(suite, pyfile, module_name): ret.append(suite) return ret if self.tests: accepted_classes = {} accepted_methods = {} for t in self.tests: splitted = t.split('.') if len(splitted) == 1: accepted_classes[t] = t elif len(splitted) == 2: accepted_methods[t] = t loader.getTestCaseNames = self.GetTestCaseNames(accepted_classes, accepted_methods) for pyfile, m, module_name in file_and_modules_and_module_name: suite = loader.loadTestsFromModule(m) if self._decorate_test_suite(suite, pyfile, module_name): ret.append(suite) return ret def filter_tests(self, test_objs, internal_call=False): """ based on a filter name, only return those tests that have the test case names that match """ import unittest if not internal_call: if not self.configuration.include_tests and not self.tests and not self.configuration.exclude_tests: # No need to filter if we have nothing to filter! return test_objs if self.verbosity > 1: if self.configuration.include_tests: sys.stdout.write('Tests to include: %s\n' % (self.configuration.include_tests,)) if self.tests: sys.stdout.write('Tests to run: %s\n' % (self.tests,)) if self.configuration.exclude_tests: sys.stdout.write('Tests to exclude: %s\n' % (self.configuration.exclude_tests,)) test_suite = [] for test_obj in test_objs: if isinstance(test_obj, unittest.TestSuite): # Note: keep the suites as they are and just 'fix' the tests (so, don't use the iter_tests). if test_obj._tests: test_obj._tests = self.filter_tests(test_obj._tests, True) if test_obj._tests: # Only add the suite if we still have tests there. test_suite.append(test_obj) elif isinstance(test_obj, unittest.TestCase): try: testMethodName = test_obj._TestCase__testMethodName except AttributeError: # changed in python 2.5 testMethodName = test_obj._testMethodName add = True if self.configuration.exclude_tests: for pat in self.configuration.exclude_tests: if fnmatch.fnmatchcase(testMethodName, pat): if self.verbosity > 3: sys.stdout.write('Skipped test: %s (matched exclude_tests pattern: %s)\n' % (testMethodName, pat)) elif self.verbosity > 2: sys.stdout.write('Skipped test: %s\n' % (testMethodName,)) add = False break if add: if self.__match_tests(self.tests, test_obj, testMethodName): include = True if self.configuration.include_tests: include = False for pat in self.configuration.include_tests: if fnmatch.fnmatchcase(testMethodName, pat): include = True break if include: test_suite.append(test_obj) else: if self.verbosity > 3: sys.stdout.write('Skipped test: %s (did not match any include_tests pattern %s)\n' % ( testMethodName, self.configuration.include_tests,)) return test_suite def iter_tests(self, test_objs): # Note: not using yield because of Jython 2.1. import unittest tests = [] for test_obj in test_objs: if isinstance(test_obj, unittest.TestSuite): tests.extend(self.iter_tests(test_obj._tests)) elif isinstance(test_obj, unittest.TestCase): tests.append(test_obj) return tests def list_test_names(self, test_objs): names = [] for tc in self.iter_tests(test_objs): try: testMethodName = tc._TestCase__testMethodName except AttributeError: # changed in python 2.5 testMethodName = tc._testMethodName names.append(testMethodName) return names def __match_tests(self, tests, test_case, test_method_name): if not tests: return 1 for t in tests: class_and_method = t.split('.') if len(class_and_method) == 1: # only class name if class_and_method[0] == test_case.__class__.__name__: return 1 elif len(class_and_method) == 2: if class_and_method[0] == test_case.__class__.__name__ and class_and_method[1] == test_method_name: return 1 return 0 def __match(self, filter_list, name): """ returns whether a test name matches the test filter """ if filter_list is None: return 1 for f in filter_list: if re.match(f, name): return 1 return 0 def run_tests(self, handle_coverage=True): """ runs all tests """ sys.stdout.write("Finding files... ") files = self.find_import_files() if self.verbosity > 3: sys.stdout.write('%s ... done.\n' % (self.files_or_dirs)) else: sys.stdout.write('done.\n') sys.stdout.write("Importing test modules ... ") if handle_coverage: coverage_files, coverage = start_coverage_support(self.configuration) file_and_modules_and_module_name = self.find_modules_from_files(files) sys.stdout.write("done.\n") all_tests = self.find_tests_from_modules(file_and_modules_and_module_name) all_tests = self.filter_tests(all_tests) from _pydev_runfiles import pydev_runfiles_unittest test_suite = pydev_runfiles_unittest.PydevTestSuite(all_tests) from _pydev_runfiles import pydev_runfiles_xml_rpc pydev_runfiles_xml_rpc.notifyTestsCollected(test_suite.countTestCases()) start_time = time.time() def run_tests(): executed_in_parallel = False if self.jobs > 1: from _pydev_runfiles import pydev_runfiles_parallel # What may happen is that the number of jobs needed is lower than the number of jobs requested # (e.g.: 2 jobs were requested for running 1 test) -- in which case execute_tests_in_parallel will # return False and won't run any tests. executed_in_parallel = pydev_runfiles_parallel.execute_tests_in_parallel( all_tests, self.jobs, self.split_jobs, self.verbosity, coverage_files, self.configuration.coverage_include) if not executed_in_parallel: # If in coverage, we don't need to pass anything here (coverage is already enabled for this execution). runner = pydev_runfiles_unittest.PydevTextTestRunner(stream=sys.stdout, descriptions=1, verbosity=self.verbosity) sys.stdout.write('\n') runner.run(test_suite) if self.configuration.django: get_django_test_suite_runner()(run_tests).run_tests([]) else: run_tests() if handle_coverage: coverage.stop() coverage.save() total_time = 'Finished in: %.2f secs.' % (time.time() - start_time,) pydev_runfiles_xml_rpc.notifyTestRunFinished(total_time) DJANGO_TEST_SUITE_RUNNER = None def get_django_test_suite_runner(): global DJANGO_TEST_SUITE_RUNNER if DJANGO_TEST_SUITE_RUNNER: return DJANGO_TEST_SUITE_RUNNER try: # django >= 1.8 import django from django.test.runner import DiscoverRunner class MyDjangoTestSuiteRunner(DiscoverRunner): def __init__(self, on_run_suite): django.setup() DiscoverRunner.__init__(self) self.on_run_suite = on_run_suite def build_suite(self, *args, **kwargs): pass def suite_result(self, *args, **kwargs): pass def run_suite(self, *args, **kwargs): self.on_run_suite() except: # django < 1.8 try: from django.test.simple import DjangoTestSuiteRunner except: class DjangoTestSuiteRunner: def __init__(self): pass def run_tests(self, *args, **kwargs): raise AssertionError("Unable to run suite with django.test.runner.DiscoverRunner nor django.test.simple.DjangoTestSuiteRunner because it couldn't be imported.") class MyDjangoTestSuiteRunner(DjangoTestSuiteRunner): def __init__(self, on_run_suite): DjangoTestSuiteRunner.__init__(self) self.on_run_suite = on_run_suite def build_suite(self, *args, **kwargs): pass def suite_result(self, *args, **kwargs): pass def run_suite(self, *args, **kwargs): self.on_run_suite() DJANGO_TEST_SUITE_RUNNER = MyDjangoTestSuiteRunner return DJANGO_TEST_SUITE_RUNNER #======================================================================================================================= # main #======================================================================================================================= def main(configuration): PydevTestRunner(configuration).run_tests()
31,550
Python
35.772727
180
0.513217
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles_coverage.py
import os.path import sys from _pydevd_bundle.pydevd_constants import Null #======================================================================================================================= # get_coverage_files #======================================================================================================================= def get_coverage_files(coverage_output_dir, number_of_files): base_dir = coverage_output_dir ret = [] i = 0 while len(ret) < number_of_files: while True: f = os.path.join(base_dir, '.coverage.%s' % i) i += 1 if not os.path.exists(f): ret.append(f) break #Break only inner for. return ret #======================================================================================================================= # start_coverage_support #======================================================================================================================= def start_coverage_support(configuration): return start_coverage_support_from_params( configuration.coverage_output_dir, configuration.coverage_output_file, configuration.jobs, configuration.coverage_include, ) #======================================================================================================================= # start_coverage_support_from_params #======================================================================================================================= def start_coverage_support_from_params(coverage_output_dir, coverage_output_file, jobs, coverage_include): coverage_files = [] coverage_instance = Null() if coverage_output_dir or coverage_output_file: try: import coverage #@UnresolvedImport except: sys.stderr.write('Error: coverage module could not be imported\n') sys.stderr.write('Please make sure that the coverage module (http://nedbatchelder.com/code/coverage/)\n') sys.stderr.write('is properly installed in your interpreter: %s\n' % (sys.executable,)) import traceback;traceback.print_exc() else: if coverage_output_dir: if not os.path.exists(coverage_output_dir): sys.stderr.write('Error: directory for coverage output (%s) does not exist.\n' % (coverage_output_dir,)) elif not os.path.isdir(coverage_output_dir): sys.stderr.write('Error: expected (%s) to be a directory.\n' % (coverage_output_dir,)) else: n = jobs if n <= 0: n += 1 n += 1 #Add 1 more for the current process (which will do the initial import). coverage_files = get_coverage_files(coverage_output_dir, n) os.environ['COVERAGE_FILE'] = coverage_files.pop(0) coverage_instance = coverage.coverage(source=[coverage_include]) coverage_instance.start() elif coverage_output_file: #Client of parallel run. os.environ['COVERAGE_FILE'] = coverage_output_file coverage_instance = coverage.coverage(source=[coverage_include]) coverage_instance.start() return coverage_files, coverage_instance
3,499
Python
44.454545
124
0.452415
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles_parallel_client.py
from _pydev_bundle.pydev_imports import xmlrpclib, _queue Queue = _queue.Queue import traceback import sys from _pydev_runfiles.pydev_runfiles_coverage import start_coverage_support_from_params import threading #======================================================================================================================= # ParallelNotification #======================================================================================================================= class ParallelNotification(object): def __init__(self, method, args, kwargs): self.method = method self.args = args self.kwargs = kwargs def to_tuple(self): return self.method, self.args, self.kwargs #======================================================================================================================= # KillServer #======================================================================================================================= class KillServer(object): pass #======================================================================================================================= # ServerComm #======================================================================================================================= class ServerComm(threading.Thread): def __init__(self, job_id, server): self.notifications_queue = Queue() threading.Thread.__init__(self) self.setDaemon(False) #Wait for all the notifications to be passed before exiting! assert job_id is not None assert port is not None self.job_id = job_id self.finished = False self.server = server def run(self): while True: kill_found = False commands = [] command = self.notifications_queue.get(block=True) if isinstance(command, KillServer): kill_found = True else: assert isinstance(command, ParallelNotification) commands.append(command.to_tuple()) try: while True: command = self.notifications_queue.get(block=False) #No block to create a batch. if isinstance(command, KillServer): kill_found = True else: assert isinstance(command, ParallelNotification) commands.append(command.to_tuple()) except: pass #That's OK, we're getting it until it becomes empty so that we notify multiple at once. if commands: try: #Batch notification. self.server.lock.acquire() try: self.server.notifyCommands(self.job_id, commands) finally: self.server.lock.release() except: traceback.print_exc() if kill_found: self.finished = True return #======================================================================================================================= # ServerFacade #======================================================================================================================= class ServerFacade(object): def __init__(self, notifications_queue): self.notifications_queue = notifications_queue def notifyTestsCollected(self, *args, **kwargs): pass #This notification won't be passed def notifyTestRunFinished(self, *args, **kwargs): pass #This notification won't be passed def notifyStartTest(self, *args, **kwargs): self.notifications_queue.put_nowait(ParallelNotification('notifyStartTest', args, kwargs)) def notifyTest(self, *args, **kwargs): self.notifications_queue.put_nowait(ParallelNotification('notifyTest', args, kwargs)) #======================================================================================================================= # run_client #======================================================================================================================= def run_client(job_id, port, verbosity, coverage_output_file, coverage_include): job_id = int(job_id) from _pydev_bundle import pydev_localhost server = xmlrpclib.Server('http://%s:%s' % (pydev_localhost.get_localhost(), port)) server.lock = threading.Lock() server_comm = ServerComm(job_id, server) server_comm.start() try: server_facade = ServerFacade(server_comm.notifications_queue) from _pydev_runfiles import pydev_runfiles from _pydev_runfiles import pydev_runfiles_xml_rpc pydev_runfiles_xml_rpc.set_server(server_facade) #Starts None and when the 1st test is gotten, it's started (because a server may be initiated and terminated #before receiving any test -- which would mean a different process got all the tests to run). coverage = None try: tests_to_run = [1] while tests_to_run: #Investigate: is it dangerous to use the same xmlrpclib server from different threads? #It seems it should be, as it creates a new connection for each request... server.lock.acquire() try: tests_to_run = server.GetTestsToRun(job_id) finally: server.lock.release() if not tests_to_run: break if coverage is None: _coverage_files, coverage = start_coverage_support_from_params( None, coverage_output_file, 1, coverage_include) files_to_tests = {} for test in tests_to_run: filename_and_test = test.split('|') if len(filename_and_test) == 2: files_to_tests.setdefault(filename_and_test[0], []).append(filename_and_test[1]) configuration = pydev_runfiles.Configuration( '', verbosity, None, None, None, files_to_tests, 1, #Always single job here None, #The coverage is handled in this loop. coverage_output_file=None, coverage_include=None, ) test_runner = pydev_runfiles.PydevTestRunner(configuration) sys.stdout.flush() test_runner.run_tests(handle_coverage=False) finally: if coverage is not None: coverage.stop() coverage.save() except: traceback.print_exc() server_comm.notifications_queue.put_nowait(KillServer()) #======================================================================================================================= # main #======================================================================================================================= if __name__ == '__main__': if len(sys.argv) -1 == 3: job_id, port, verbosity = sys.argv[1:] coverage_output_file, coverage_include = None, None elif len(sys.argv) -1 == 5: job_id, port, verbosity, coverage_output_file, coverage_include = sys.argv[1:] else: raise AssertionError('Could not find out how to handle the parameters: '+sys.argv[1:]) job_id = int(job_id) port = int(port) verbosity = int(verbosity) run_client(job_id, port, verbosity, coverage_output_file, coverage_include)
7,722
Python
34.92093
120
0.460891
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles_pytest2.py
from _pydev_runfiles import pydev_runfiles_xml_rpc import pickle import zlib import base64 import os from pydevd_file_utils import canonical_normalized_path import pytest import sys import time from pathlib import Path #========================================================================= # Load filters with tests we should skip #========================================================================= py_test_accept_filter = None def _load_filters(): global py_test_accept_filter if py_test_accept_filter is None: py_test_accept_filter = os.environ.get('PYDEV_PYTEST_SKIP') if py_test_accept_filter: py_test_accept_filter = pickle.loads( zlib.decompress(base64.b64decode(py_test_accept_filter))) # Newer versions of pytest resolve symlinks, so, we # may need to filter with a resolved path too. new_dct = {} for filename, value in py_test_accept_filter.items(): new_dct[canonical_normalized_path(str(Path(filename).resolve()))] = value py_test_accept_filter.update(new_dct) else: py_test_accept_filter = {} def is_in_xdist_node(): main_pid = os.environ.get('PYDEV_MAIN_PID') if main_pid and main_pid != str(os.getpid()): return True return False connected = False def connect_to_server_for_communication_to_xml_rpc_on_xdist(): global connected if connected: return connected = True if is_in_xdist_node(): port = os.environ.get('PYDEV_PYTEST_SERVER') if not port: sys.stderr.write( 'Error: no PYDEV_PYTEST_SERVER environment variable defined.\n') else: pydev_runfiles_xml_rpc.initialize_server(int(port), daemon=True) PY2 = sys.version_info[0] <= 2 PY3 = not PY2 class State: start_time = time.time() buf_err = None buf_out = None def start_redirect(): if State.buf_out is not None: return from _pydevd_bundle import pydevd_io State.buf_err = pydevd_io.start_redirect(keep_original_redirection=True, std='stderr') State.buf_out = pydevd_io.start_redirect(keep_original_redirection=True, std='stdout') def get_curr_output(): buf_out = State.buf_out buf_err = State.buf_err return buf_out.getvalue() if buf_out is not None else '', buf_err.getvalue() if buf_err is not None else '' def pytest_unconfigure(): if is_in_xdist_node(): return # Only report that it finished when on the main node (we don't want to report # the finish on each separate node). pydev_runfiles_xml_rpc.notifyTestRunFinished( 'Finished in: %.2f secs.' % (time.time() - State.start_time,)) def pytest_collection_modifyitems(session, config, items): # A note: in xdist, this is not called on the main process, only in the # secondary nodes, so, we'll actually make the filter and report it multiple # times. connect_to_server_for_communication_to_xml_rpc_on_xdist() _load_filters() if not py_test_accept_filter: pydev_runfiles_xml_rpc.notifyTestsCollected(len(items)) return # Keep on going (nothing to filter) new_items = [] for item in items: f = canonical_normalized_path(str(item.parent.fspath)) name = item.name if f not in py_test_accept_filter: # print('Skip file: %s' % (f,)) continue # Skip the file i = name.find('[') name_without_parametrize = None if i > 0: name_without_parametrize = name[:i] accept_tests = py_test_accept_filter[f] if item.cls is not None: class_name = item.cls.__name__ else: class_name = None for test in accept_tests: if test == name: # Direct match of the test (just go on with the default # loading) new_items.append(item) break if name_without_parametrize is not None and test == name_without_parametrize: # This happens when parameterizing pytest tests on older versions # of pytest where the test name doesn't include the fixture name # in it. new_items.append(item) break if class_name is not None: if test == class_name + '.' + name: new_items.append(item) break if name_without_parametrize is not None and test == class_name + '.' + name_without_parametrize: new_items.append(item) break if class_name == test: new_items.append(item) break else: pass # print('Skip test: %s.%s. Accept: %s' % (class_name, name, accept_tests)) # Modify the original list items[:] = new_items pydev_runfiles_xml_rpc.notifyTestsCollected(len(items)) try: """ pytest > 5.4 uses own version of TerminalWriter based on py.io.TerminalWriter and assumes there is a specific method TerminalWriter._write_source so try load pytest version first or fallback to default one """ from _pytest._io import TerminalWriter except ImportError: from py.io import TerminalWriter def _get_error_contents_from_report(report): if report.longrepr is not None: try: tw = TerminalWriter(stringio=True) stringio = tw.stringio except TypeError: import io stringio = io.StringIO() tw = TerminalWriter(file=stringio) tw.hasmarkup = False report.toterminal(tw) exc = stringio.getvalue() s = exc.strip() if s: return s return '' def pytest_collectreport(report): error_contents = _get_error_contents_from_report(report) if error_contents: report_test('fail', '<collect errors>', '<collect errors>', '', error_contents, 0.0) def append_strings(s1, s2): if s1.__class__ == s2.__class__: return s1 + s2 # Prefer str if isinstance(s1, bytes): s1 = s1.decode('utf-8', 'replace') if isinstance(s2, bytes): s2 = s2.decode('utf-8', 'replace') return s1 + s2 def pytest_runtest_logreport(report): if is_in_xdist_node(): # When running with xdist, we don't want the report to be called from the node, only # from the main process. return report_duration = report.duration report_when = report.when report_outcome = report.outcome if hasattr(report, 'wasxfail'): if report_outcome != 'skipped': report_outcome = 'passed' if report_outcome == 'passed': # passed on setup/teardown: no need to report if in setup or teardown # (only on the actual test if it passed). if report_when in ('setup', 'teardown'): return status = 'ok' elif report_outcome == 'skipped': status = 'skip' else: # It has only passed, skipped and failed (no error), so, let's consider # error if not on call. if report_when in ('setup', 'teardown'): status = 'error' else: # any error in the call (not in setup or teardown) is considered a # regular failure. status = 'fail' # This will work if pytest is not capturing it, if it is, nothing will # come from here... captured_output, error_contents = getattr(report, 'pydev_captured_output', ''), getattr(report, 'pydev_error_contents', '') for type_section, value in report.sections: if value: if type_section in ('err', 'stderr', 'Captured stderr call'): error_contents = append_strings(error_contents, value) else: captured_output = append_strings(error_contents, value) filename = getattr(report, 'pydev_fspath_strpath', '<unable to get>') test = report.location[2] if report_outcome != 'skipped': # On skipped, we'll have a traceback for the skip, which is not what we # want. exc = _get_error_contents_from_report(report) if exc: if error_contents: error_contents = append_strings(error_contents, '----------------------------- Exceptions -----------------------------\n') error_contents = append_strings(error_contents, exc) report_test(status, filename, test, captured_output, error_contents, report_duration) def report_test(status, filename, test, captured_output, error_contents, duration): ''' @param filename: 'D:\\src\\mod1\\hello.py' @param test: 'TestCase.testMet1' @param status: fail, error, ok ''' time_str = '%.2f' % (duration,) pydev_runfiles_xml_rpc.notifyTest( status, captured_output, error_contents, filename, test, time_str) if not hasattr(pytest, 'hookimpl'): raise AssertionError('Please upgrade pytest (the current version of pytest: %s is unsupported)' % (pytest.__version__,)) @pytest.hookimpl(hookwrapper=True) def pytest_runtest_makereport(item, call): outcome = yield report = outcome.get_result() report.pydev_fspath_strpath = item.fspath.strpath report.pydev_captured_output, report.pydev_error_contents = get_curr_output() @pytest.mark.tryfirst def pytest_runtest_setup(item): ''' Note: with xdist will be on a secondary process. ''' # We have our own redirection: if xdist does its redirection, we'll have # nothing in our contents (which is OK), but if it does, we'll get nothing # from pytest but will get our own here. start_redirect() filename = item.fspath.strpath test = item.location[2] pydev_runfiles_xml_rpc.notifyStartTest(filename, test)
9,845
Python
31.071661
139
0.600914
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles_unittest.py
import unittest as python_unittest from _pydev_runfiles import pydev_runfiles_xml_rpc import time from _pydevd_bundle import pydevd_io import traceback from _pydevd_bundle.pydevd_constants import * # @UnusedWildImport from io import StringIO #======================================================================================================================= # PydevTextTestRunner #======================================================================================================================= class PydevTextTestRunner(python_unittest.TextTestRunner): def _makeResult(self): return PydevTestResult(self.stream, self.descriptions, self.verbosity) _PythonTextTestResult = python_unittest.TextTestRunner()._makeResult().__class__ #======================================================================================================================= # PydevTestResult #======================================================================================================================= class PydevTestResult(_PythonTextTestResult): def addSubTest(self, test, subtest, err): """Called at the end of a subtest. 'err' is None if the subtest ended successfully, otherwise it's a tuple of values as returned by sys.exc_info(). """ _PythonTextTestResult.addSubTest(self, test, subtest, err) if err is not None: subdesc = subtest._subDescription() error = (test, self._exc_info_to_string(err, test)) self._reportErrors([error], [], '', '%s %s' % (self.get_test_name(test), subdesc)) def startTest(self, test): _PythonTextTestResult.startTest(self, test) self.buf = pydevd_io.start_redirect(keep_original_redirection=True, std='both') self.start_time = time.time() self._current_errors_stack = [] self._current_failures_stack = [] try: test_name = test.__class__.__name__ + "." + test._testMethodName except AttributeError: # Support for jython 2.1 (__testMethodName is pseudo-private in the test case) test_name = test.__class__.__name__ + "." + test._TestCase__testMethodName pydev_runfiles_xml_rpc.notifyStartTest( test.__pydev_pyfile__, test_name) def get_test_name(self, test): try: try: test_name = test.__class__.__name__ + "." + test._testMethodName except AttributeError: # Support for jython 2.1 (__testMethodName is pseudo-private in the test case) try: test_name = test.__class__.__name__ + "." + test._TestCase__testMethodName # Support for class/module exceptions (test is instance of _ErrorHolder) except: test_name = test.description.split()[1][1:-1] + ' <' + test.description.split()[0] + '>' except: traceback.print_exc() return '<unable to get test name>' return test_name def stopTest(self, test): end_time = time.time() pydevd_io.end_redirect(std='both') _PythonTextTestResult.stopTest(self, test) captured_output = self.buf.getvalue() del self.buf error_contents = '' test_name = self.get_test_name(test) diff_time = '%.2f' % (end_time - self.start_time) skipped = False outcome = getattr(test, '_outcome', None) if outcome is not None: skipped = bool(getattr(outcome, 'skipped', None)) if skipped: pydev_runfiles_xml_rpc.notifyTest( 'skip', captured_output, error_contents, test.__pydev_pyfile__, test_name, diff_time) elif not self._current_errors_stack and not self._current_failures_stack: pydev_runfiles_xml_rpc.notifyTest( 'ok', captured_output, error_contents, test.__pydev_pyfile__, test_name, diff_time) else: self._reportErrors(self._current_errors_stack, self._current_failures_stack, captured_output, test_name) def _reportErrors(self, errors, failures, captured_output, test_name, diff_time=''): error_contents = [] for test, s in errors + failures: if type(s) == type((1,)): # If it's a tuple (for jython 2.1) sio = StringIO() traceback.print_exception(s[0], s[1], s[2], file=sio) s = sio.getvalue() error_contents.append(s) sep = '\n' + self.separator1 error_contents = sep.join(error_contents) if errors and not failures: try: pydev_runfiles_xml_rpc.notifyTest( 'error', captured_output, error_contents, test.__pydev_pyfile__, test_name, diff_time) except: file_start = error_contents.find('File "') file_end = error_contents.find('", ', file_start) if file_start != -1 and file_end != -1: file = error_contents[file_start + 6:file_end] else: file = '<unable to get file>' pydev_runfiles_xml_rpc.notifyTest( 'error', captured_output, error_contents, file, test_name, diff_time) elif failures and not errors: pydev_runfiles_xml_rpc.notifyTest( 'fail', captured_output, error_contents, test.__pydev_pyfile__, test_name, diff_time) else: # Ok, we got both, errors and failures. Let's mark it as an error in the end. pydev_runfiles_xml_rpc.notifyTest( 'error', captured_output, error_contents, test.__pydev_pyfile__, test_name, diff_time) def addError(self, test, err): _PythonTextTestResult.addError(self, test, err) # Support for class/module exceptions (test is instance of _ErrorHolder) if not hasattr(self, '_current_errors_stack') or test.__class__.__name__ == '_ErrorHolder': # Not in start...end, so, report error now (i.e.: django pre/post-setup) self._reportErrors([self.errors[-1]], [], '', self.get_test_name(test)) else: self._current_errors_stack.append(self.errors[-1]) def addFailure(self, test, err): _PythonTextTestResult.addFailure(self, test, err) if not hasattr(self, '_current_failures_stack'): # Not in start...end, so, report error now (i.e.: django pre/post-setup) self._reportErrors([], [self.failures[-1]], '', self.get_test_name(test)) else: self._current_failures_stack.append(self.failures[-1]) class PydevTestSuite(python_unittest.TestSuite): pass
6,685
Python
43.278145
120
0.551832
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydev_runfiles/pydev_runfiles_nose.py
from nose.plugins.multiprocess import MultiProcessTestRunner # @UnresolvedImport from nose.plugins.base import Plugin # @UnresolvedImport import sys from _pydev_runfiles import pydev_runfiles_xml_rpc import time from _pydev_runfiles.pydev_runfiles_coverage import start_coverage_support from contextlib import contextmanager from io import StringIO import traceback #======================================================================================================================= # PydevPlugin #======================================================================================================================= class PydevPlugin(Plugin): def __init__(self, configuration): self.configuration = configuration Plugin.__init__(self) def begin(self): # Called before any test is run (it's always called, with multiprocess or not) self.start_time = time.time() self.coverage_files, self.coverage = start_coverage_support(self.configuration) def finalize(self, result): # Called after all tests are run (it's always called, with multiprocess or not) self.coverage.stop() self.coverage.save() pydev_runfiles_xml_rpc.notifyTestRunFinished('Finished in: %.2f secs.' % (time.time() - self.start_time,)) #=================================================================================================================== # Methods below are not called with multiprocess (so, we monkey-patch MultiProcessTestRunner.consolidate # so that they're called, but unfortunately we loose some info -- i.e.: the time for each test in this # process). #=================================================================================================================== class Sentinel(object): pass @contextmanager def _without_user_address(self, test): # #PyDev-1095: Conflict between address in test and test.address() in PydevPlugin().report_cond() user_test_instance = test.test user_address = self.Sentinel user_class_address = self.Sentinel try: if 'address' in user_test_instance.__dict__: user_address = user_test_instance.__dict__.pop('address') except: # Just ignore anything here. pass try: user_class_address = user_test_instance.__class__.address del user_test_instance.__class__.address except: # Just ignore anything here. pass try: yield finally: if user_address is not self.Sentinel: user_test_instance.__dict__['address'] = user_address if user_class_address is not self.Sentinel: user_test_instance.__class__.address = user_class_address def _get_test_address(self, test): try: if hasattr(test, 'address'): with self._without_user_address(test): address = test.address() # test.address() is something as: # ('D:\\workspaces\\temp\\test_workspace\\pytesting1\\src\\mod1\\hello.py', 'mod1.hello', 'TestCase.testMet1') # # and we must pass: location, test # E.g.: ['D:\\src\\mod1\\hello.py', 'TestCase.testMet1'] address = address[0], address[2] else: # multiprocess try: address = test[0], test[1] except TypeError: # It may be an error at setup, in which case it's not really a test, but a Context object. f = test.context.__file__ if f.endswith('.pyc'): f = f[:-1] elif f.endswith('$py.class'): f = f[:-len('$py.class')] + '.py' address = f, '?' except: sys.stderr.write("PyDev: Internal pydev error getting test address. Please report at the pydev bug tracker\n") traceback.print_exc() sys.stderr.write("\n\n\n") address = '?', '?' return address def report_cond(self, cond, test, captured_output, error=''): ''' @param cond: fail, error, ok ''' address = self._get_test_address(test) error_contents = self.get_io_from_error(error) try: time_str = '%.2f' % (time.time() - test._pydev_start_time) except: time_str = '?' pydev_runfiles_xml_rpc.notifyTest(cond, captured_output, error_contents, address[0], address[1], time_str) def startTest(self, test): test._pydev_start_time = time.time() file, test = self._get_test_address(test) pydev_runfiles_xml_rpc.notifyStartTest(file, test) def get_io_from_error(self, err): if type(err) == type(()): if len(err) != 3: if len(err) == 2: return err[1] # multiprocess s = StringIO() etype, value, tb = err if isinstance(value, str): return value traceback.print_exception(etype, value, tb, file=s) return s.getvalue() return err def get_captured_output(self, test): if hasattr(test, 'capturedOutput') and test.capturedOutput: return test.capturedOutput return '' def addError(self, test, err): self.report_cond( 'error', test, self.get_captured_output(test), err, ) def addFailure(self, test, err): self.report_cond( 'fail', test, self.get_captured_output(test), err, ) def addSuccess(self, test): self.report_cond( 'ok', test, self.get_captured_output(test), '', ) PYDEV_NOSE_PLUGIN_SINGLETON = None def start_pydev_nose_plugin_singleton(configuration): global PYDEV_NOSE_PLUGIN_SINGLETON PYDEV_NOSE_PLUGIN_SINGLETON = PydevPlugin(configuration) return PYDEV_NOSE_PLUGIN_SINGLETON original = MultiProcessTestRunner.consolidate #======================================================================================================================= # new_consolidate #======================================================================================================================= def new_consolidate(self, result, batch_result): ''' Used so that it can work with the multiprocess plugin. Monkeypatched because nose seems a bit unsupported at this time (ideally the plugin would have this support by default). ''' ret = original(self, result, batch_result) parent_frame = sys._getframe().f_back # addr is something as D:\pytesting1\src\mod1\hello.py:TestCase.testMet4 # so, convert it to what report_cond expects addr = parent_frame.f_locals['addr'] i = addr.rindex(':') addr = [addr[:i], addr[i + 1:]] output, testsRun, failures, errors, errorClasses = batch_result if failures or errors: for failure in failures: PYDEV_NOSE_PLUGIN_SINGLETON.report_cond('fail', addr, output, failure) for error in errors: PYDEV_NOSE_PLUGIN_SINGLETON.report_cond('error', addr, output, error) else: PYDEV_NOSE_PLUGIN_SINGLETON.report_cond('ok', addr, output) return ret MultiProcessTestRunner.consolidate = new_consolidate
7,549
Python
35.298077
126
0.527355
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydev_bundle/pydev_override.py
def overrides(method): ''' Meant to be used as class B: @overrides(A.m1) def m1(self): pass ''' def wrapper(func): if func.__name__ != method.__name__: msg = "Wrong @override: %r expected, but overwriting %r." msg = msg % (func.__name__, method.__name__) raise AssertionError(msg) if func.__doc__ is None: func.__doc__ = method.__doc__ return func return wrapper def implements(method): def wrapper(func): if func.__name__ != method.__name__: msg = "Wrong @implements: %r expected, but implementing %r." msg = msg % (func.__name__, method.__name__) raise AssertionError(msg) if func.__doc__ is None: func.__doc__ = method.__doc__ return func return wrapper
872
Python
23.942856
72
0.497706
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydev_bundle/pydev_umd.py
""" The UserModuleDeleter and runfile methods are copied from Spyder and carry their own license agreement. http://code.google.com/p/spyderlib/source/browse/spyderlib/widgets/externalshell/sitecustomize.py Spyder License Agreement (MIT License) -------------------------------------- Copyright (c) 2009-2012 Pierre Raybaut Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import sys import os from _pydev_bundle._pydev_execfile import execfile # The following classes and functions are mainly intended to be used from # an interactive Python session class UserModuleDeleter: """ User Module Deleter (UMD) aims at deleting user modules to force Python to deeply reload them during import pathlist [list]: ignore list in terms of module path namelist [list]: ignore list in terms of module name """ def __init__(self, namelist=None, pathlist=None): if namelist is None: namelist = [] self.namelist = namelist if pathlist is None: pathlist = [] self.pathlist = pathlist try: # ignore all files in org.python.pydev/pysrc import pydev_pysrc, inspect self.pathlist.append(os.path.dirname(pydev_pysrc.__file__)) except: pass self.previous_modules = list(sys.modules.keys()) def is_module_ignored(self, modname, modpath): for path in [sys.prefix] + self.pathlist: if modpath.startswith(path): return True else: return set(modname.split('.')) & set(self.namelist) def run(self, verbose=False): """ Del user modules to force Python to deeply reload them Do not del modules which are considered as system modules, i.e. modules installed in subdirectories of Python interpreter's binary Do not del C modules """ log = [] modules_copy = dict(sys.modules) for modname, module in modules_copy.items(): if modname == 'aaaaa': print(modname, module) print(self.previous_modules) if modname not in self.previous_modules: modpath = getattr(module, '__file__', None) if modpath is None: # *module* is a C module that is statically linked into the # interpreter. There is no way to know its path, so we # choose to ignore it. continue if not self.is_module_ignored(modname, modpath): log.append(modname) del sys.modules[modname] if verbose and log: print("\x1b[4;33m%s\x1b[24m%s\x1b[0m" % ("UMD has deleted", ": " + ", ".join(log))) __umd__ = None _get_globals_callback = None def _set_globals_function(get_globals): global _get_globals_callback _get_globals_callback = get_globals def _get_globals(): """Return current Python interpreter globals namespace""" if _get_globals_callback is not None: return _get_globals_callback() else: try: from __main__ import __dict__ as namespace except ImportError: try: # The import fails on IronPython import __main__ namespace = __main__.__dict__ except: namespace shell = namespace.get('__ipythonshell__') if shell is not None and hasattr(shell, 'user_ns'): # IPython 0.12+ kernel return shell.user_ns else: # Python interpreter return namespace return namespace def runfile(filename, args=None, wdir=None, namespace=None): """ Run filename args: command line arguments (string) wdir: working directory """ try: if hasattr(filename, 'decode'): filename = filename.decode('utf-8') except (UnicodeError, TypeError): pass global __umd__ if os.environ.get("PYDEV_UMD_ENABLED", "").lower() == "true": if __umd__ is None: namelist = os.environ.get("PYDEV_UMD_NAMELIST", None) if namelist is not None: namelist = namelist.split(',') __umd__ = UserModuleDeleter(namelist=namelist) else: verbose = os.environ.get("PYDEV_UMD_VERBOSE", "").lower() == "true" __umd__.run(verbose=verbose) if args is not None and not isinstance(args, (bytes, str)): raise TypeError("expected a character buffer object") if namespace is None: namespace = _get_globals() if '__file__' in namespace: old_file = namespace['__file__'] else: old_file = None namespace['__file__'] = filename sys.argv = [filename] if args is not None: for arg in args.split(): sys.argv.append(arg) if wdir is not None: try: if hasattr(wdir, 'decode'): wdir = wdir.decode('utf-8') except (UnicodeError, TypeError): pass os.chdir(wdir) execfile(filename, namespace) sys.argv = [''] if old_file is None: del namespace['__file__'] else: namespace['__file__'] = old_file
6,279
Python
33.696132
97
0.607262
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydev_bundle/pydev_import_hook.py
import sys import traceback from types import ModuleType from _pydevd_bundle.pydevd_constants import DebugInfoHolder import builtins class ImportHookManager(ModuleType): def __init__(self, name, system_import): ModuleType.__init__(self, name) self._system_import = system_import self._modules_to_patch = {} def add_module_name(self, module_name, activate_function): self._modules_to_patch[module_name] = activate_function def do_import(self, name, *args, **kwargs): module = self._system_import(name, *args, **kwargs) try: activate_func = self._modules_to_patch.pop(name, None) if activate_func: activate_func() # call activate function except: if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 2: traceback.print_exc() # Restore normal system importer to reduce performance impact # of calling this method every time an import statement is invoked if not self._modules_to_patch: builtins.__import__ = self._system_import return module import_hook_manager = ImportHookManager(__name__ + '.import_hook', builtins.__import__) builtins.__import__ = import_hook_manager.do_import sys.modules[import_hook_manager.__name__] = import_hook_manager
1,322
Python
31.268292
87
0.652799
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydev_bundle/pydev_localhost.py
from _pydev_bundle._pydev_saved_modules import socket import sys IS_JYTHON = sys.platform.find('java') != -1 _cache = None def get_localhost(): ''' Should return 127.0.0.1 in ipv4 and ::1 in ipv6 localhost is not used because on windows vista/windows 7, there can be issues where the resolving doesn't work properly and takes a lot of time (had this issue on the pyunit server). Using the IP directly solves the problem. ''' # TODO: Needs better investigation! global _cache if _cache is None: try: for addr_info in socket.getaddrinfo("localhost", 80, 0, 0, socket.SOL_TCP): config = addr_info[4] if config[0] == '127.0.0.1': _cache = '127.0.0.1' return _cache except: # Ok, some versions of Python don't have getaddrinfo or SOL_TCP... Just consider it 127.0.0.1 in this case. _cache = '127.0.0.1' else: _cache = 'localhost' return _cache def get_socket_names(n_sockets, close=False): socket_names = [] sockets = [] for _ in range(n_sockets): if IS_JYTHON: # Although the option which would be pure java *should* work for Jython, the socket being returned is still 0 # (i.e.: it doesn't give the local port bound, only the original port, which was 0). from java.net import ServerSocket sock = ServerSocket(0) socket_name = get_localhost(), sock.getLocalPort() else: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((get_localhost(), 0)) socket_name = sock.getsockname() sockets.append(sock) socket_names.append(socket_name) if close: for s in sockets: s.close() return socket_names def get_socket_name(close=False): return get_socket_names(1, close)[0] if __name__ == '__main__': print(get_socket_name())
2,070
Python
29.455882
121
0.591304
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydev_bundle/pydev_is_thread_alive.py
from _pydev_bundle._pydev_saved_modules import threading # Hack for https://www.brainwy.com/tracker/PyDev/363 (i.e.: calling is_alive() can throw AssertionError under some # circumstances). # It is required to debug threads started by start_new_thread in Python 3.4 _temp = threading.Thread() if hasattr(_temp, '_is_stopped'): # Python 3.x has this def is_thread_alive(t): return not t._is_stopped elif hasattr(_temp, '_Thread__stopped'): # Python 2.x has this def is_thread_alive(t): return not t._Thread__stopped else: # Jython wraps a native java thread and thus only obeys the public API. def is_thread_alive(t): return t.is_alive() del _temp
696
Python
28.041665
114
0.688218
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydev_bundle/_pydev_tipper_common.py
import inspect import re def do_find(f, mod): import linecache if inspect.ismodule(mod): return f, 0, 0 lines = linecache.getlines(f) if inspect.isclass(mod): name = mod.__name__ pat = re.compile(r'^\s*class\s*' + name + r'\b') for i in range(len(lines)): if pat.match(lines[i]): return f, i, 0 return f, 0, 0 if inspect.ismethod(mod): mod = mod.im_func if inspect.isfunction(mod): try: mod = mod.func_code except AttributeError: mod = mod.__code__ # python 3k if inspect.istraceback(mod): mod = mod.tb_frame if inspect.isframe(mod): mod = mod.f_code if inspect.iscode(mod): if not hasattr(mod, 'co_filename'): return None, 0, 0 if not hasattr(mod, 'co_firstlineno'): return mod.co_filename, 0, 0 lnum = mod.co_firstlineno pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') while lnum > 0: if pat.match(lines[lnum]): break lnum -= 1 return f, lnum, 0 raise RuntimeError('Do not know about: ' + f + ' ' + str(mod))
1,227
Python
22.169811
72
0.509372
omniverse-code/kit/exts/omni.kit.debug.python/debugpy/_vendored/pydevd/_pydev_bundle/_pydev_saved_modules.py
import sys import os def find_in_pythonpath(module_name): # Check all the occurrences where we could match the given module/package in the PYTHONPATH. # # This is a simplistic approach, but probably covers most of the cases we're interested in # (i.e.: this may fail in more elaborate cases of import customization or .zip imports, but # this should be rare in general). found_at = [] parts = module_name.split('.') # split because we need to convert mod.name to mod/name for path in sys.path: target = os.path.join(path, *parts) target_py = target + '.py' if os.path.isdir(target): found_at.append(target) if os.path.exists(target_py): found_at.append(target_py) return found_at class DebuggerInitializationError(Exception): pass class VerifyShadowedImport(object): def __init__(self, import_name): self.import_name = import_name def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is not None: if exc_type == DebuggerInitializationError: return False # It's already an error we generated. # We couldn't even import it... found_at = find_in_pythonpath(self.import_name) if len(found_at) <= 1: # It wasn't found anywhere or there was just 1 occurrence. # Let's just return to show the original error. return False # We found more than 1 occurrence of the same module in the PYTHONPATH # (the user module and the standard library module). # Let's notify the user as it seems that the module was shadowed. msg = self._generate_shadowed_import_message(found_at) raise DebuggerInitializationError(msg) def _generate_shadowed_import_message(self, found_at): msg = '''It was not possible to initialize the debugger due to a module name conflict. i.e.: the module "%(import_name)s" could not be imported because it is shadowed by: %(found_at)s Please rename this file/folder so that the original module from the standard library can be imported.''' % { 'import_name': self.import_name, 'found_at': found_at[0]} return msg def check(self, module, expected_attributes): msg = '' for expected_attribute in expected_attributes: try: getattr(module, expected_attribute) except: msg = self._generate_shadowed_import_message([module.__file__]) break if msg: raise DebuggerInitializationError(msg) with VerifyShadowedImport('threading') as verify_shadowed: import threading; verify_shadowed.check(threading, ['Thread', 'settrace', 'setprofile', 'Lock', 'RLock', 'current_thread']) with VerifyShadowedImport('time') as verify_shadowed: import time; verify_shadowed.check(time, ['sleep', 'time', 'mktime']) with VerifyShadowedImport('socket') as verify_shadowed: import socket; verify_shadowed.check(socket, ['socket', 'gethostname', 'getaddrinfo']) with VerifyShadowedImport('select') as verify_shadowed: import select; verify_shadowed.check(select, ['select']) with VerifyShadowedImport('code') as verify_shadowed: import code as _code; verify_shadowed.check(_code, ['compile_command', 'InteractiveInterpreter']) with VerifyShadowedImport('_thread') as verify_shadowed: import _thread as thread; verify_shadowed.check(thread, ['start_new_thread', 'start_new', 'allocate_lock']) with VerifyShadowedImport('queue') as verify_shadowed: import queue as _queue; verify_shadowed.check(_queue, ['Queue', 'LifoQueue', 'Empty', 'Full', 'deque']) with VerifyShadowedImport('xmlrpclib') as verify_shadowed: import xmlrpc.client as xmlrpclib; verify_shadowed.check(xmlrpclib, ['ServerProxy', 'Marshaller', 'Server']) with VerifyShadowedImport('xmlrpc.server') as verify_shadowed: import xmlrpc.server as xmlrpcserver; verify_shadowed.check(xmlrpcserver, ['SimpleXMLRPCServer']) with VerifyShadowedImport('http.server') as verify_shadowed: import http.server as BaseHTTPServer; verify_shadowed.check(BaseHTTPServer, ['BaseHTTPRequestHandler']) # If set, this is a version of the threading.enumerate that doesn't have the patching to remove the pydevd threads. # Note: as it can't be set during execution, don't import the name (import the module and access it through its name). pydevd_saved_threading_enumerate = None
4,573
Python
40.207207
130
0.674393