From eb67eb781d55f20b8959631ce03b0ce79b078e28 Mon Sep 17 00:00:00 2001 From: Sylvain <15435472+duposyl@users.noreply.github.com> Date: Tue, 8 Nov 2022 18:49:04 -0500 Subject: [PATCH 1/4] Documentation improvements 1) Fixed ansys.stk.core.stkengine.stkengine by renaming stkengine.py to __init__,py 2) Moved the Windows platform checks in stkdesktop.py to be at the method level instead of at the file level, so the api doc gets generated even when the doc build is running on Linux. 3) Revisited issue with * in docstrings. Only issue is with *. (star character followed by period). So the reverted the previous change when that pattern was not used. Where it was used, mostly file extensions, for instance used .txt instead of *.txt --- src/ansys/stk/core/stkdesktop.py | 297 +++++++++--------- src/ansys/stk/core/stkengine/__init__.py | 204 +++++++++++- src/ansys/stk/core/stkobjects/__init__.py | 44 +-- src/ansys/stk/core/stkobjects/astrogator.py | 8 +- .../stk/core/stkobjects/aviator/__init__.py | 4 +- src/ansys/stk/core/vgt.py | 6 +- 6 files changed, 390 insertions(+), 173 deletions(-) diff --git a/src/ansys/stk/core/stkdesktop.py b/src/ansys/stk/core/stkdesktop.py index 2632bd9bc5..ad604e5dc9 100644 --- a/src/ansys/stk/core/stkdesktop.py +++ b/src/ansys/stk/core/stkdesktop.py @@ -7,171 +7,186 @@ import os from ctypes import byref -if os.name !="nt": - raise RuntimeError("STKDesktop is only available on Windows. Use STKEngine.") -else: - from .internal.comutil import * - from .internal.coclassutil import attach_to_stk_by_pid - from .internal.eventutil import EventSubscriptionManager - from .utilities.exceptions import * - from .graphics import * - from .stkobjects import * - from .stkobjects.astrogator import * - from .stkobjects.aviator import * - from .stkutil import * - from .uiapplication import * - from .uicore import * - from .vgt import * +from .internal.comutil import * +from .internal.coclassutil import attach_to_stk_by_pid +from .internal.eventutil import EventSubscriptionManager +from .utilities.exceptions import * +from .graphics import * +from .stkobjects import * +from .stkobjects.astrogator import * +from .stkobjects.aviator import * +from .stkutil import * +from .uiapplication import * +from .uicore import * +from .vgt import * - class ThreadMarshaller(object): - _iid_IUnknown = GUID(IUnknown._guid) - def __init__(self, obj): - if not hasattr(obj, "_pUnk"): - raise STKRuntimeError("Invalid object to passed to ThreadMarshaller.") - self._obj = obj - self._obj_type = type(obj) - self._pStream = PVOID() - if not Succeeded(CoMarshalInterThreadInterfaceInStream(byref(ThreadMarshaller._iid_IUnknown), obj._pUnk.p, byref(self._pStream))): - raise STKRuntimeError("ThreadMarshaller failed to initialize.") +class ThreadMarshaller(object): + _iid_IUnknown = GUID(IUnknown._guid) + def __init__(self, obj): + if os.name != "nt": + raise RuntimeError("ThreadMarshaller is only available on Windows.") + if not hasattr(obj, "_pUnk"): + raise STKRuntimeError("Invalid object to passed to ThreadMarshaller.") + self._obj = obj + self._obj_type = type(obj) + self._pStream = PVOID() + if not Succeeded(CoMarshalInterThreadInterfaceInStream(byref(ThreadMarshaller._iid_IUnknown), obj._pUnk.p, byref(self._pStream))): + raise STKRuntimeError("ThreadMarshaller failed to initialize.") - def __del__(self): - if self._pStream is not None: - CoReleaseMarshalData(self._pStream) - del(self._obj) + def __del__(self): + if self._pStream is not None: + CoReleaseMarshalData(self._pStream) + del(self._obj) - def GetMarshalledToCurrentThread(self) -> typing.Any: - """Returns an instance of the original stk_object that may be used on the current thread. May only be called once.""" - if self._pStream is None: - raise STKRuntimeError(f"{self._obj_type} object has already been marshalled to a thread.") - pUnk_raw = PVOID() - hr = CoGetInterfaceAndReleaseStream(self._pStream, byref(ThreadMarshaller._iid_IUnknown), byref(pUnk_raw)) - self._pStream = None - if not Succeeded(hr): - if hr == CO_E_NOTINITIALIZED: - raise STKRuntimeError("Thread not initialized. Call InitializeThread() before the call to GetMarshalledToCurrentThread().") - else: - raise STKRuntimeError("Could not marshall to thread.") - pUnk = IUnknown() - pUnk.p = pUnk_raw - marshalled_obj = self._obj_type() - marshalled_obj._private_init(pUnk) - del(pUnk) - return marshalled_obj + def GetMarshalledToCurrentThread(self) -> typing.Any: + """Returns an instance of the original stk_object that may be used on the current thread. May only be called once.""" + if self._pStream is None: + raise STKRuntimeError(f"{self._obj_type} object has already been marshalled to a thread.") + pUnk_raw = PVOID() + hr = CoGetInterfaceAndReleaseStream(self._pStream, byref(ThreadMarshaller._iid_IUnknown), byref(pUnk_raw)) + self._pStream = None + if not Succeeded(hr): + if hr == CO_E_NOTINITIALIZED: + raise STKRuntimeError("Thread not initialized. Call InitializeThread() before the call to GetMarshalledToCurrentThread().") + else: + raise STKRuntimeError("Could not marshall to thread.") + pUnk = IUnknown() + pUnk.p = pUnk_raw + marshalled_obj = self._obj_type() + marshalled_obj._private_init(pUnk) + del(pUnk) + return marshalled_obj - def InitializeThread(self) -> None: - """Must be called on the destination thread prior to calling GetMarshalledToCurrentThread().""" - CoInitializeEx(None, COINIT_APARTMENTTHREADED) + def InitializeThread(self) -> None: + """Must be called on the destination thread prior to calling GetMarshalledToCurrentThread().""" + CoInitializeEx(None, COINIT_APARTMENTTHREADED) - def ReleaseThread(self) -> None: - """Call in the destination thread after all calls to STK are finished.""" - CoUninitialize() + def ReleaseThread(self) -> None: + """Call in the destination thread after all calls to STK are finished.""" + CoUninitialize() - class STKDesktopApplication(AgUiApplication): - """ - Interact with an STK Desktop application. Use STKDesktop.StartApplication() or - STKDesktop.AttachToApplication() to obtain an initialized STKDesktopApplication object. - """ - def __init__(self): - self.__dict__["_pUnk"] = None - AgUiApplication.__init__(self) - self.__dict__["_initialized"] = False - self.__dict__["_root"] = None +class STKDesktopApplication(AgUiApplication): + """ + Interact with an STK Desktop application. Use STKDesktop.StartApplication() or + STKDesktop.AttachToApplication() to obtain an initialized STKDesktopApplication object. + """ + def __init__(self): + if os.name != "nt": + raise RuntimeError("STKDesktopApplication is only available on Windows. Use STKEngine.") + self.__dict__["_pUnk"] = None + AgUiApplication.__init__(self) + self.__dict__["_initialized"] = False + self.__dict__["_root"] = None - def _private_init(self, pUnk:IUnknown): - self.__dict__["_pUnk"] = pUnk - AgUiApplication._private_init(self, pUnk) - self.__dict__["_initialized"] = True + def _private_init(self, pUnk:IUnknown): + self.__dict__["_pUnk"] = pUnk + AgUiApplication._private_init(self, pUnk) + self.__dict__["_initialized"] = True - def __del__(self): - if self.__dict__["_initialized"]: - CoInitializeManager.uninitialize() + def __del__(self): + if self.__dict__["_initialized"]: + CoInitializeManager.uninitialize() - @property - def Root(self) -> AgStkObjectRoot: - """Get the object model root associated with this instance of STK Desktop application.""" - if not self.__dict__["_initialized"]: - raise RuntimeError("STKDesktopApplication has not been properly initialized. Use StartApplication() or AttachToApplication() to obtain the STKDesktopApplication object.") - if self.__dict__["_root"] is not None: - return self.__dict__["_root"] - if self.__dict__["_pUnk"] is not None: - self.__dict__["_root"] = self.Personality2 - return self.__dict__["_root"] + @property + def Root(self) -> AgStkObjectRoot: + """Get the object model root associated with this instance of STK Desktop application.""" + if not self.__dict__["_initialized"]: + raise RuntimeError("STKDesktopApplication has not been properly initialized. Use StartApplication() or AttachToApplication() to obtain the STKDesktopApplication object.") + if self.__dict__["_root"] is not None: + return self.__dict__["_root"] + if self.__dict__["_pUnk"] is not None: + self.__dict__["_root"] = self.Personality2 + return self.__dict__["_root"] - def ShutDown(self) -> None: - """Close this STK Desktop instance (or detach if the instance was obtained through STKDesktop.AttachToApplication()).""" - if self.__dict__["_pUnk"] is not None: - if self.__dict__["_root"] is not None: - self.__dict__["_root"].CloseScenario() - self.Quit() - self.__dict__["_root"] = None - self.__dict__["_pUnk"] = None + def ShutDown(self) -> None: + """Close this STK Desktop instance (or detach if the instance was obtained through STKDesktop.AttachToApplication()).""" + if self.__dict__["_pUnk"] is not None: + if self.__dict__["_root"] is not None: + self.__dict__["_root"].CloseScenario() + self.Quit() + self.__dict__["_root"] = None + self.__dict__["_pUnk"] = None - class STKDesktop(object): - """Create, initialize, and manage STK Desktop application instances.""" +class STKDesktop(object): + """Create, initialize, and manage STK Desktop application instances.""" - @staticmethod - def StartApplication(visible:bool=False, userControl:bool=False) -> STKDesktopApplication: - """ - Create a new STK Desktop application instance. - Specify visible = True to show the application window. - Specify userControl = True to return the application to the user's control - (the application remains open) after terminating the Python API connection. - """ - CoInitializeManager.initialize() + @staticmethod + def StartApplication(visible:bool=False, userControl:bool=False) -> STKDesktopApplication: + """ + Create a new STK Desktop application instance. + Specify visible = True to show the application window. + Specify userControl = True to return the application to the user's control + (the application remains open) after terminating the Python API connection. + + Only available on Windows. + """ + if os.name != "nt": + raise RuntimeError("STKDesktop is only available on Windows. Use STKEngine.") + + CoInitializeManager.initialize() + CLSID_AgUiApplication = GUID() + if Succeeded(CLSIDFromString("STK12.Application", CLSID_AgUiApplication)): + pUnk = IUnknown() + IID_IUnknown = GUID(IUnknown._guid) + if Succeeded(CoCreateInstance(byref(CLSID_AgUiApplication), None, CLSCTX_LOCAL_SERVER, byref(IID_IUnknown), byref(pUnk.p))): + pUnk.TakeOwnership(isApplication=True) + app = STKDesktopApplication() + app._private_init(pUnk) + app.Visible = visible + app.UserControl = userControl + return app + raise STKInitializationError("Failed to create STK Desktop application. Check for successful install and registration.") + + @staticmethod + def AttachToApplication(pid:int=None) -> STKDesktopApplication: + """ + Attach to an existing STK Desktop instance. + Specify the Process ID (PID) in case multiple processes are open. + Specify userControl = True to return the application to the user's control + (the application remains open) after terminating the Python API connection. + + Only available on Windows. + """ + if os.name != "nt": + raise RuntimeError("STKDesktop is only available on Windows. Use STKEngine.") + + CoInitializeManager.initialize() + if pid is None: CLSID_AgUiApplication = GUID() if Succeeded(CLSIDFromString("STK12.Application", CLSID_AgUiApplication)): pUnk = IUnknown() IID_IUnknown = GUID(IUnknown._guid) - if Succeeded(CoCreateInstance(byref(CLSID_AgUiApplication), None, CLSCTX_LOCAL_SERVER, byref(IID_IUnknown), byref(pUnk.p))): + if Succeeded(GetActiveObject(byref(CLSID_AgUiApplication), None, byref(pUnk.p))): pUnk.TakeOwnership(isApplication=True) - app = STKDesktopApplication() - app._private_init(pUnk) - app.Visible = visible - app.UserControl = userControl - return app - raise STKInitializationError("Failed to create STK Desktop application. Check for successful install and registration.") - - @staticmethod - def AttachToApplication(pid:int=None) -> STKDesktopApplication: - """ - Attach to an existing STK Desktop instance. - Specify the Process ID (PID) in case multiple processes are open. - Specify userControl = True to return the application to the user's control - (the application remains open) after terminating the Python API connection. - """ - CoInitializeManager.initialize() - if pid is None: - CLSID_AgUiApplication = GUID() - if Succeeded(CLSIDFromString("STK12.Application", CLSID_AgUiApplication)): - pUnk = IUnknown() - IID_IUnknown = GUID(IUnknown._guid) - if Succeeded(GetActiveObject(byref(CLSID_AgUiApplication), None, byref(pUnk.p))): - pUnk.TakeOwnership(isApplication=True) - app = STKDesktopApplication() - app._private_init(pUnk) - return app - else: - raise STKInitializationError("Failed to attach to an active STK 12 Application instance.") - else: - pUnk = attach_to_stk_by_pid(pid) - if pUnk is not None: app = STKDesktopApplication() app._private_init(pUnk) return app else: - raise STKInitializationError("Failed to attach to STK with pid " + str(pid) + ".") + raise STKInitializationError("Failed to attach to an active STK 12 Application instance.") + else: + pUnk = attach_to_stk_by_pid(pid) + if pUnk is not None: + app = STKDesktopApplication() + app._private_init(pUnk) + return app + else: + raise STKInitializationError("Failed to attach to STK with pid " + str(pid) + ".") - @staticmethod - def ReleaseAll() -> None: - """Releases all handles from Python to STK Desktop applications.""" - EventSubscriptionManager.UnsubscribeAll() - ObjectLifetimeManager.ReleaseAll() + @staticmethod + def ReleaseAll() -> None: + """Releases all handles from Python to STK Desktop applications.""" + if os.name != "nt": + raise RuntimeError("STKDesktop is only available on Windows.") + EventSubscriptionManager.UnsubscribeAll() + ObjectLifetimeManager.ReleaseAll() - @staticmethod - def CreateThreadMarshaller(stk_object:typing.Any) -> ThreadMarshaller: - """Returns a ThreadMarshaller instance capable of marshalling the stk_object argument to a new thread.""" - return ThreadMarshaller(stk_object) + @staticmethod + def CreateThreadMarshaller(stk_object:typing.Any) -> ThreadMarshaller: + """Returns a ThreadMarshaller instance capable of marshalling the stk_object argument to a new thread.""" + if os.name != "nt": + raise RuntimeError("STKDesktop is only available on Windows.") + return ThreadMarshaller(stk_object) ################################################################################ diff --git a/src/ansys/stk/core/stkengine/__init__.py b/src/ansys/stk/core/stkengine/__init__.py index 2eb79032dc..634856f539 100644 --- a/src/ansys/stk/core/stkengine/__init__.py +++ b/src/ansys/stk/core/stkengine/__init__.py @@ -1 +1,203 @@ -from .stkengine import * \ No newline at end of file +################################################################################ +# Copyright 2020-2020, Analytical Graphics, Inc. +################################################################################ + +__all__ = ["STKEngine", "STKEngineApplication", "STKEngineTimerType"] + +import os +from ctypes import byref +from enum import IntEnum +from ..internal.timerutil import * + +if os.name != "nt": + from ctypes import CFUNCTYPE, cdll + from ctypes.util import find_library + +from ..internal.comutil import CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, GUID +from ..internal.comutil import CLSIDFromString, CoCreateInstance, CoInitializeManager, IUnknown, ObjectLifetimeManager, Succeeded +from ..internal.eventutil import EventSubscriptionManager +from ..internal.stkxinitialization import * +from ..utilities.exceptions import * +from ..graphics import * +from ..stkobjects import * +from ..stkobjects.astrogator import * +from ..stkobjects.aviator import * +from ..stkutil import * +from ..stkx import * +from ..vgt import * + +class STKEngineTimerType(IntEnum): + DisableTimers = 1 + TkinterMainloop = 2 + InteractivePython = 3 + SigAlarm = 4 + SigRt = 5 + +class STKEngineApplication(AgSTKXApplication): + """ + Interact with STK Engine. + Use STKEngine.StartApplication() to obtain an initialized STKEngineApplication object. + """ + def __init__(self): + AgSTKXApplication.__init__(self) + self.__dict__["_stk_install_dir"] = None + self.__dict__["_stk_config_dir"] = None + self.__dict__["_initialized"] = False + + def _private_init(self, pUnk:IUnknown, stk_install_dir, stk_config_dir, noGraphics): + AgSTKXApplication._private_init(self, pUnk) + self.__dict__["_stk_install_dir"] = stk_install_dir + self.__dict__["_stk_config_dir"] = stk_config_dir + self._STKXInitialize() + self._STKXInitializeTimer(noGraphics) + self.__dict__["_initialized"] = True + + def __del__(self): + self.ShutDown() + + def _STKXInitialize(self): + if os.name=="nt": + return + CLSID_AgSTKXInitialize = GUID() + if Succeeded(CLSIDFromString("{3B85901D-FC82-4733-97E6-5BB25CE69379}", CLSID_AgSTKXInitialize)): + IID_IUnknown = GUID(IUnknown._guid) + stkxinit_unk = IUnknown() + if Succeeded(CoCreateInstance(byref(CLSID_AgSTKXInitialize), None, CLSCTX_INPROC_SERVER, byref(IID_IUnknown), byref(stkxinit_unk.p))): + stkxinit_unk.TakeOwnership() + pInit = IAgSTKXInitialize() + pInit._private_init(stkxinit_unk) + install_dir = self.__dict__["_stk_install_dir"] if self.__dict__["_stk_install_dir"] is not None else os.getenv("STK_INSTALL_DIR") + if install_dir is None: + raise STKInitializationError("Please set a valid STK_INSTALL_DIR environment variable.") + config_dir = self.__dict__["_stk_config_dir"] if self.__dict__["_stk_config_dir"] is not None else os.getenv("STK_CONFIG_DIR") + if config_dir is None: + raise STKInitializationError("Please set a valid STK_CONFIG_DIR environment variable.") + pInit.InitializeData(install_dir, config_dir) + + @staticmethod + def _get_signo(sigrtmin_offset): + if os.name=="nt": + return None + libc = cdll.LoadLibrary(find_library("c")) + __libc_current_sigrtmin = CFUNCTYPE(c_int)(("__libc_current_sigrtmin", libc)) + return __libc_current_sigrtmin() + sigrtmin_offset + + def _set_timer_type_from_env(self): + timer_type = int(os.getenv("STK_PYTHONAPI_TIMERTYPE", "4")) + if os.name=="nt" or timer_type == STKEngineTimerType.DisableTimers: + self.__dict__["_timer_impl"] = NullTimer() + elif timer_type == STKEngineTimerType.TkinterMainloop or timer_type == STKEngineTimerType.InteractivePython: + self.__dict__["_timer_impl"] = TclTimer() + elif timer_type == STKEngineTimerType.SigAlarm: + self.__dict__["_timer_impl"] = SigAlarmTimer() + elif timer_type == STKEngineTimerType.SigRt: + sigrtmin_offset = int(os.getenv("STK_PYTHONAPI_TIMERTYPE5_SIGRTMIN_OFFSET", "0")) + signo = STKEngineApplication._get_signo(sigrtmin_offset) + self.__dict__["_timer_impl"] = SigRtTimer(signo) + + def _user_override_timer_type(self) -> bool: + return ("STK_PYTHONAPI_TIMERTYPE" in os.environ) + + def _STKXInitializeTimer(self, noGraphics): + if os.name=="nt": + #Timers are not implemented on Windows, use a placeholder. + self.__dict__["_timer_impl"] = NullTimer() + elif noGraphics: + self._set_timer_type_from_env() + else: + #default to Tkinter mainloop in graphics applications, but allow the user to override + #e.g. if controls are not being used, the SigAlarm timer might be desired. + if self._user_override_timer_type(): + self._set_timer_type_from_env() + else: + self.__dict__["_timer_impl"] = TclTimer() + + def NewObjectRoot(self) -> AgStkObjectRoot: + """Create a new object model root for the STK Engine application.""" + if not self.__dict__["_initialized"]: + raise RuntimeError("STKEngineApplication has not been properly initialized. Use StartApplication() to obtain the STKEngineApplication object.") + CLSID_AgStkObjectRoot = GUID() + if Succeeded(CLSIDFromString("{96C1CE4E-C61D-4657-99CB-8581E12693FE}", CLSID_AgStkObjectRoot)): + IID_IUnknown = GUID(IUnknown._guid) + root_unk = IUnknown() + CoCreateInstance(byref(CLSID_AgStkObjectRoot), None, CLSCTX_INPROC_SERVER, byref(IID_IUnknown), byref(root_unk.p)) + root_unk.TakeOwnership() + root = AgStkObjectRoot() + root._private_init(root_unk) + return root + + def ShutDown(self) -> None: + """Shut down the STK Engine application.""" + if self._initialized: + EventSubscriptionManager.UnsubscribeAll() + self._timer_impl.Terminate() + ObjectLifetimeManager.ReleaseAll(releaseApplication=False) + self.Terminate() + ObjectLifetimeManager.ReleaseAll(releaseApplication=True) + CoInitializeManager.uninitialize() + self.__dict__["_initialized"] = False + + +class STKEngine(object): + """Initialize and manage the STK Engine application.""" + _is_engine_running = False + _stk_config_dir = None + _stk_install_dir = None + + @staticmethod + def _initX11(noGraphics): + if noGraphics or os.name=="nt": + return + try: + x11lib = cdll.LoadLibrary(find_library("X11")) + XInitThreads = CFUNCTYPE(None)(("XInitThreads", x11lib)) + XInitThreads() + except: + raise STKRuntimeError("Failed attempting to run graphics mode without X11.") + + @staticmethod + def StartApplication(noGraphics:bool=True) -> STKEngineApplication: + """ + Initialize STK Engine in-process and return the instance. + Must only be used once per Python process. + """ + if STKEngine._is_engine_running: + raise RuntimeError("Only one STKEngine instance is allowed per Python process.") + CoInitializeManager.initialize() + CLSID_AgSTKXApplication = GUID() + if Succeeded(CLSIDFromString("{062AB565-B121-45B5-A9A9-B412CEFAB6A9}", CLSID_AgSTKXApplication)): + pUnk = IUnknown() + IID_IUnknown = GUID(IUnknown._guid) + if Succeeded(CoCreateInstance(byref(CLSID_AgSTKXApplication), None, CLSCTX_INPROC_SERVER, byref(IID_IUnknown), byref(pUnk.p))): + pUnk.TakeOwnership(isApplication=True) + STKEngine._is_engine_running = True + STKEngine._initX11(noGraphics) + engine = STKEngineApplication() + engine._private_init(pUnk, STKEngine._stk_install_dir, STKEngine._stk_config_dir, noGraphics) + engine.NoGraphics = noGraphics + return engine + raise STKInitializationError("Failed to create STK Engine application. Check for successful install and registration.") + + if os.name != "nt": + @staticmethod + def SetSTKInstallDir(stkInstallDir:str) -> None: + """ + Setting the install directory using this method will override the STK_INSTALL_DIR environment variable. + If this method is not called, STK_INSTALL_DIR will be used instead. This method must be called before + StartApplication(). + """ + STKEngine._stk_install_dir = stkInstallDir + + @staticmethod + def SetSTKConfigDir(stkConfigDir:str) -> None: + """ + Setting the config directory using this method will override the STK_CONFIG_DIR environment variable. + If this method is not called, STK_CONFIG_DIR will be used instead. This method must be called before + StartApplication(). + """ + STKEngine._stk_config_dir = stkConfigDir + + +################################################################################ +# Copyright 2020-2020, Analytical Graphics, Inc. +################################################################################ diff --git a/src/ansys/stk/core/stkobjects/__init__.py b/src/ansys/stk/core/stkobjects/__init__.py index a0e725530d..ef630548b9 100644 --- a/src/ansys/stk/core/stkobjects/__init__.py +++ b/src/ansys/stk/core/stkobjects/__init__.py @@ -708,7 +708,7 @@ class AgEAnimationDirections(IntEnum): class AgEAzElMaskType(IntEnum): """Obscura types of the facility, place or target for AzElMask definition.""" - # Use data in an exernal azimuth-elevation mask (*.aem) file. + # Use data in an exernal azimuth-elevation mask (.aem) file. eMaskFile = 0x0, # Use terrain data specified at the scenario level to define the azimuth-elevation mask. eTerrainData = 0x1, @@ -1025,7 +1025,7 @@ class AgEVOLabelSwapDistance(IntEnum): class AgEPlPositionSourceType(IntEnum): """Options for defining a planet.""" - # Use a planetary ephemeris (*.pe) file to define the planet. + # Use a planetary ephemeris (.pe) file to define the planet. ePosFile = 0x0, # Specify the name of a central body to define the planet. ePosCentralBody = 0x1 @@ -1038,7 +1038,7 @@ class AgEEphemSourceType(IntEnum): eEphemAnalytic = 0x0, # Default: use STK's internal definition of the Central Body to generate ephemeris. By default, STK's internal definition uses the DE file if available. eEphemDefault = 0x2, - # SPICE: use the SPICE toolkit to generate ephemeris. Available only if a SPICE ephemeris file (*.bsp) has been loaded for the selected planet. + # SPICE: use the SPICE toolkit to generate ephemeris. Available only if a SPICE ephemeris file (.bsp) has been loaded for the selected planet. eEphemSpice = 0x3, # Default JPL DE file. eEphemJPLDE = 0x4 @@ -2799,7 +2799,7 @@ class AgEDataSaveMode(IntEnum): class AgECvBounds(IntEnum): """Coverage bounds options: values of the enumeration represent polymorphic object types.""" - # Creates a grid within regions specified by a combination of user-selected area targets, region list files (*.rl) and/or ArcView shapefiles (*.shp). + # Creates a grid within regions specified by a combination of user-selected area targets, region list files (.rl) and/or ArcView shapefiles (.shp). eBoundsCustomRegions = 0, # Creates a grid that covers the entire globe. eBoundsGlobal = 1, @@ -14179,7 +14179,7 @@ def MeanRadius(self) -> float: @property def VolumetricRadius(self) -> float: - """A volumetric radius of the central body (a\\*b\\*c)^(1/3).""" + """A volumetric radius of the central body (a*b*c)^(1/3).""" with agmarshall.DOUBLE_arg() as arg_pRetVal: agcls.evaluate_hresult(self.__dict__["_GetVolumetricRadius"](byref(arg_pRetVal.COM_val))) return arg_pRetVal.python_val @@ -14260,7 +14260,7 @@ def Vgt(self) -> "IAgCrdnProvider": @property def GravitationalParameter(self) -> float: - """The gravitational parameter of the central body in distance units cubed per time units squared (i.e. m^3\\*s^-2)""" + """The gravitational parameter of the central body in distance units cubed per time units squared (i.e. m^3*s^-2)""" with agmarshall.DOUBLE_arg() as arg_pRetVal: agcls.evaluate_hresult(self.__dict__["_GetGravitationalParameter"](byref(arg_pRetVal.COM_val))) return arg_pRetVal.python_val @@ -22127,7 +22127,7 @@ def AscNode(self) -> "IAgOrientationAscNode": agcls.AgTypeNameMap["IAgClassicalOrientation"] = IAgClassicalOrientation class IAgClassicalLocation(object): - """Base Interface of all IAgClassicalLocation\\* interfaces.""" + """Base Interface of all IAgClassicalLocation* interfaces.""" _uuid = "{3FA6B2AF-DD45-4D5D-957B-3DF6DDE2530D}" _num_methods = 0 _vtable_offset = IUnknown._vtable_offset + IUnknown._num_methods @@ -33043,7 +33043,7 @@ def __setattr__(self, attrname, value): @property def Filename(self) -> str: - """Path and file name of the sensor pointing (\\*.sp) file.""" + """Path and file name of the sensor pointing (.sp) file.""" with agmarshall.BSTR_arg() as arg_pVal: agcls.evaluate_hresult(self.__dict__["_GetFilename"](byref(arg_pVal.COM_val))) return arg_pVal.python_val @@ -33336,7 +33336,7 @@ def __setattr__(self, attrname, value): @property def Filename(self) -> str: - """Path and filename of Az-El mask file (\\*.aem) or body mask file (\\*.bmsk).""" + """Path and filename of Az-El mask file (.aem) or body mask file (.bmsk).""" with agmarshall.BSTR_arg() as arg_pVal: agcls.evaluate_hresult(self.__dict__["_GetFilename"](byref(arg_pVal.COM_val))) return arg_pVal.python_val @@ -73156,21 +73156,21 @@ def __setattr__(self, attrname, value): @property def Epoch(self) -> typing.Any: - """The almanac reference date for all almanacs in the (\\*.al3) file per ICD-GPS-200.""" + """The almanac reference date for all almanacs in the (.al3) file per ICD-GPS-200.""" with agmarshall.VARIANT_arg() as arg_pRetVal: agcls.evaluate_hresult(self.__dict__["_GetEpoch"](byref(arg_pRetVal.COM_val))) return arg_pRetVal.python_val @property def Week(self) -> int: - """The almanac reference week (VINA) for all almanacs in this (\\*.al3) file per the ICD-GPS-200.""" + """The almanac reference week (VINA) for all almanacs in this (.al3) file per the ICD-GPS-200.""" with agmarshall.LONG_arg() as arg_pRetVal: agcls.evaluate_hresult(self.__dict__["_GetWeek"](byref(arg_pRetVal.COM_val))) return arg_pRetVal.python_val @property def TimeOfAlmanac(self) -> float: - """The almanac reference time (Time of Appilcability) for all almanacs in the (\\*.al3) file per ICD-GPS-200.""" + """The almanac reference time (Time of Appilcability) for all almanacs in the (.al3) file per ICD-GPS-200.""" with agmarshall.DOUBLE_arg() as arg_pRetVal: agcls.evaluate_hresult(self.__dict__["_GetTimeOfAlmanac"](byref(arg_pRetVal.COM_val))) return arg_pRetVal.python_val @@ -74778,7 +74778,7 @@ def __setattr__(self, attrname, value): @property def File(self) -> str: - """Name of gravity (\\*.grv) file, an ASCII file containing the Central Body geopotential model coefficients.""" + """Name of gravity (.grv) file, an ASCII file containing the Central Body geopotential model coefficients.""" with agmarshall.BSTR_arg() as arg_pVal: agcls.evaluate_hresult(self.__dict__["_GetFile"](byref(arg_pVal.COM_val))) return arg_pVal.python_val @@ -83365,7 +83365,7 @@ def UseTorqueFile(self, useTorqueFile:bool) -> None: @property def TorqueFile(self) -> str: - """Name of external torque (\\*.tq) file. Torque files define a time-ordered list of body-fixed torques to be applied to the satellite.""" + """Name of external torque (.tq) file. Torque files define a time-ordered list of body-fixed torques to be applied to the satellite.""" with agmarshall.BSTR_arg() as arg_pVal: agcls.evaluate_hresult(self.__dict__["_GetTorqueFile"](byref(arg_pVal.COM_val))) return arg_pVal.python_val @@ -85072,7 +85072,7 @@ def Profile(self) -> "IAgVeAttProfile": agcls.AgTypeNameMap["IAgVeStandardBasic"] = IAgVeStandardBasic class IAgVeAttExternal(object): - """Interface for using an external attitude (\\*.a) file.""" + """Interface for using an external attitude (.a) file.""" _uuid = "{5C077C16-4BF0-4C42-9D13-247E6B1C41FE}" _num_methods = 13 _vtable_offset = IUnknown._vtable_offset + IUnknown._num_methods @@ -85151,7 +85151,7 @@ def StopTime(self) -> typing.Any: @property def Filename(self) -> str: - """External (\\*.a) file name containing attitude data.""" + """External (.a) file name containing attitude data.""" with agmarshall.BSTR_arg() as arg_pVal: agcls.evaluate_hresult(self.__dict__["_GetFilename"](byref(arg_pVal.COM_val))) return arg_pVal.python_val @@ -85171,7 +85171,7 @@ def Disable(self) -> None: @property def FilePath(self) -> str: - """External (\\*.a) full file name and path containing attitude data.""" + """External (.a) full file name and path containing attitude data.""" with agmarshall.BSTR_arg() as arg_pVal: agcls.evaluate_hresult(self.__dict__["_GetFilePath"](byref(arg_pVal.COM_val))) return arg_pVal.python_val @@ -88703,7 +88703,7 @@ def IsPenumbraUmbraVisible(self, isPenumbraUmbraVisible:bool) -> None: @property def IsSolarSpecularReflectionPointVisible(self) -> bool: - """Opt whether to draw the solar specular reflection point on the surface of the globe as a white \\*.""" + """Opt whether to draw the solar specular reflection point on the surface of the globe as a white '*'.""" with agmarshall.VARIANT_BOOL_arg() as arg_pVal: agcls.evaluate_hresult(self.__dict__["_GetIsSolarSpecularReflectionPointVisible"](byref(arg_pVal.COM_val))) return arg_pVal.python_val @@ -110514,7 +110514,7 @@ def GroundAltitude(self, inVal:float) -> None: @property def PointAltitudeMethod(self) -> "AgECvPointAltitudeMethod": - """Custom point altitude method specifies whether to use the altitude values in the point file (.\\*pt) or override them using the altitude at a point on terrain.""" + """Custom point altitude method specifies whether to use the altitude values in the point file (.*pt) or override them using the altitude at a point on terrain.""" with agmarshall.AgEnum_arg(AgECvPointAltitudeMethod) as arg_pRetVal: agcls.evaluate_hresult(self.__dict__["_GetPointAltitudeMethod"](byref(arg_pRetVal.COM_val))) return arg_pRetVal.python_val @@ -116175,14 +116175,14 @@ def Dissipation(self, dissipation:float) -> None: @property def CrossSectionalArea(self) -> float: - """Area used in thermal model. For plate, equals its surface area; for spehere, equals pi\\*radius^2. Uses SmallArea Dimension.""" + """Area used in thermal model. For plate, equals its surface area; for spehere, equals pi*radius^2. Uses SmallArea Dimension.""" with agmarshall.DOUBLE_arg() as arg_pVal: agcls.evaluate_hresult(self.__dict__["_GetCrossSectionalArea"](byref(arg_pVal.COM_val))) return arg_pVal.python_val @CrossSectionalArea.setter def CrossSectionalArea(self, crossSectionalArea:float) -> None: - """Area used in thermal model. For plate, equals its surface area; for spehere, equals pi\\*radius^2. Uses SmallArea Dimension.""" + """Area used in thermal model. For plate, equals its surface area; for spehere, equals pi*radius^2. Uses SmallArea Dimension.""" with agmarshall.DOUBLE_arg(crossSectionalArea) as arg_crossSectionalArea: agcls.evaluate_hresult(self.__dict__["_SetCrossSectionalArea"](arg_crossSectionalArea.COM_val)) @@ -126502,7 +126502,7 @@ def __setattr__(self, attrname, value): class AgVeAttExternal(IAgVeAttExternal): - """External attitude (\\*.a) file.""" + """External attitude (.a) file.""" def __init__(self, sourceObject=None): IAgVeAttExternal.__init__(self, sourceObject) def _private_init(self, pUnk:IUnknown): diff --git a/src/ansys/stk/core/stkobjects/astrogator.py b/src/ansys/stk/core/stkobjects/astrogator.py index 0cab562d4e..06dea06154 100644 --- a/src/ansys/stk/core/stkobjects/astrogator.py +++ b/src/ansys/stk/core/stkobjects/astrogator.py @@ -1769,13 +1769,13 @@ class AgEVACbEphemeris(IntEnum): """The central body ephemeris types.""" # Specified values and rates of change for the classical orbital elements. eVACbEphemerisAnalyticOrbit = 0, - # An external ephemeris (*.e) file. + # An external ephemeris (.e) file. eVACbEphemerisFile = 1, # Ephemerides from the Jet Propulsion Laboratory's JPL DE set are used. eVACbEphemerisJPLDE = 2, # The SPICE propagator reads ephemeris from binary files that are in a standard format produced by the Jet Propulsion Laboratory for ephemeris for celestial bodies but can be used for spacecraft. eVACbEphemerisJPLSPICE = 3, - # A planetary ephemeris (*.pe) file. + # A planetary ephemeris (.pe) file. eVACbEphemerisPlanetary = 4 agcls.AgTypeNameMap["AgEVACbEphemeris"] = AgEVACbEphemeris @@ -9887,7 +9887,7 @@ def RAAN(self, newVal:typing.Any) -> None: @property def DelaunayL(self) -> float: - """Related to the two-body orbital energy. Defined as sqrt(GM \\* a). Uses AreaRate Dimension.""" + """Related to the two-body orbital energy. Defined as sqrt(GM * a). Uses AreaRate Dimension.""" with agmarshall.DOUBLE_arg() as arg_pVal: agcls.evaluate_hresult(self.__dict__["_GetDelaunayL"](byref(arg_pVal.COM_val))) return arg_pVal.python_val @@ -9911,7 +9911,7 @@ def SemiMajorAxis(self, newVal:float) -> None: @property def DelaunayG(self) -> float: - """The magnitude of the orbital angular momentum. Defined as sqrt(GM \\* p). Uses AreaRate Dimension.""" + """The magnitude of the orbital angular momentum. Defined as sqrt(GM * p). Uses AreaRate Dimension.""" with agmarshall.DOUBLE_arg() as arg_pVal: agcls.evaluate_hresult(self.__dict__["_GetDelaunayG"](byref(arg_pVal.COM_val))) return arg_pVal.python_val diff --git a/src/ansys/stk/core/stkobjects/aviator/__init__.py b/src/ansys/stk/core/stkobjects/aviator/__init__.py index 8878d4446e..741c348a6f 100644 --- a/src/ansys/stk/core/stkobjects/aviator/__init__.py +++ b/src/ansys/stk/core/stkobjects/aviator/__init__.py @@ -10558,14 +10558,14 @@ def PropellantSpecificHeatRatio(self, newVal:float) -> None: @property def PropellantCharacteristicVelocity(self) -> float: - """The propellant's characteristic velocity (Chamber Pressure \\* Throat Area / Mass Flow Rate of the engine).""" + """The propellant's characteristic velocity (Chamber Pressure * Throat Area / Mass Flow Rate of the engine).""" with agmarshall.DOUBLE_arg() as arg_pVal: agcls.evaluate_hresult(self.__dict__["_GetPropellantCharacteristicVelocity"](byref(arg_pVal.COM_val))) return arg_pVal.python_val @PropellantCharacteristicVelocity.setter def PropellantCharacteristicVelocity(self, newVal:float) -> None: - """The propellant's characteristic velocity (Chamber Pressure \\* Throat Area / Mass Flow Rate of the engine).""" + """The propellant's characteristic velocity (Chamber Pressure * Throat Area / Mass Flow Rate of the engine).""" with agmarshall.DOUBLE_arg(newVal) as arg_newVal: agcls.evaluate_hresult(self.__dict__["_SetPropellantCharacteristicVelocity"](arg_newVal.COM_val)) diff --git a/src/ansys/stk/core/vgt.py b/src/ansys/stk/core/vgt.py index 570b03d835..a4f7fcc833 100644 --- a/src/ansys/stk/core/vgt.py +++ b/src/ansys/stk/core/vgt.py @@ -17967,7 +17967,7 @@ def ReferenceAxes(self) -> "IAgCrdnAxesRefTo": @property def Filename(self) -> str: - """Can be MATLAB (\\*.m or \\*.dll), VB Script (\\*.vbs) or Perl (\\*.pl) script file.""" + """Can be MATLAB (.m or .dll), VB Script (.vbs) or Perl (.pl) script file.""" with agmarshall.BSTR_arg() as arg_pRetVal: agcls.evaluate_hresult(self.__dict__["_GetFilename"](byref(arg_pRetVal.COM_val))) return arg_pRetVal.python_val @@ -22500,7 +22500,7 @@ def ScaleFactor(self, scaleFactor:float) -> None: agcls.AgTypeNameMap["IAgCrdnVectorReflection"] = IAgCrdnVectorReflection class IAgCrdnVectorRotationVector(object): - """Rotation vector representing the rotation of one axes relative to reference axes, expressed as angle\\*rotationAxis.""" + """Rotation vector representing the rotation of one axes relative to reference axes, expressed as angle*rotationAxis.""" _uuid = "{2dc152fa-f029-4bc6-bc47-f27d92219a32}" _num_methods = 4 _vtable_offset = IUnknown._vtable_offset + IUnknown._num_methods @@ -33820,7 +33820,7 @@ def __setattr__(self, attrname, value): class AgCrdnVectorRotationVector(IAgCrdnVectorRotationVector, IAgCrdnVector, IAgCrdnTimeProperties, IAgCrdn): - """Rotation vector representing the rotation of one axes relative to reference axes, expressed as angle\\*rotationAxis.""" + """Rotation vector representing the rotation of one axes relative to reference axes, expressed as angle*rotationAxis.""" def __init__(self, sourceObject=None): IAgCrdnVectorRotationVector.__init__(self, sourceObject) IAgCrdnVector.__init__(self, sourceObject) From b8b4d710fc2e5ad84dd001753e3607ee2dbbafcb Mon Sep 17 00:00:00 2001 From: Sylvain <15435472+duposyl@users.noreply.github.com> Date: Tue, 8 Nov 2022 19:57:39 -0500 Subject: [PATCH 2/4] Stub out attach_to_stk_by_pid on Linux to be able to generate the API documentation for STKDesktop --- src/ansys/stk/core/internal/coclassutil.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/ansys/stk/core/internal/coclassutil.py b/src/ansys/stk/core/internal/coclassutil.py index dccabde6b4..39ab4dd1cd 100644 --- a/src/ansys/stk/core/internal/coclassutil.py +++ b/src/ansys/stk/core/internal/coclassutil.py @@ -433,4 +433,8 @@ def attach_to_stk_by_pid(pid:int) -> IUnknown: del(runningObjectTable) else: raise RuntimeError("Failed to retrieve the Running Object Table.") - +else: + def attach_to_stk_by_pid(pid:int) -> IUnknown: + if os.name != "nt": + raise RuntimeError("STKDesktop is only available on Windows. Use STKEngine.") + From 99ae367635b1e0336664569cfd1b783223d0bce6 Mon Sep 17 00:00:00 2001 From: Sylvain <15435472+duposyl@users.noreply.github.com> Date: Tue, 8 Nov 2022 20:31:55 -0500 Subject: [PATCH 3/4] Avoid more file level platform checks. --- src/ansys/stk/core/internal/coclassutil.py | 294 +++++++++++---------- 1 file changed, 151 insertions(+), 143 deletions(-) diff --git a/src/ansys/stk/core/internal/coclassutil.py b/src/ansys/stk/core/internal/coclassutil.py index 39ab4dd1cd..8d57551ec3 100644 --- a/src/ansys/stk/core/internal/coclassutil.py +++ b/src/ansys/stk/core/internal/coclassutil.py @@ -288,153 +288,161 @@ def IUnknown_from_IDispatch(pdisp:PVOID) -> IUnknown: ############################################################################### # attach_to_stk_by_pid (Windows-only) ############################################################################### -if os.name=="nt": + +class _ole32lib: CreateClassMoniker = WINFUNCTYPE(HRESULT, GUID, POINTER(LPVOID))(("CreateClassMoniker", ole32lib), ((1, "rclsid"), (1, "ppmk"))) GetRunningObjectTable = WINFUNCTYPE(HRESULT, DWORD, POINTER(LPVOID))(("GetRunningObjectTable", ole32lib), ((1, "dwReserved"), (1, "pprot"))) CreateBindCtx = WINFUNCTYPE(HRESULT, DWORD, POINTER(LPVOID))(("CreateBindCtx", ole32lib), ((1, "dwReserved"), (1, "ppbc"))) CoGetMalloc = WINFUNCTYPE(HRESULT, DWORD, POINTER(LPVOID))(("CoGetMalloc", ole32lib), ((1, "dwMemContext"), (1, "ppMalloc"))) - class _IRunningObjectTable(object): - guid = "{00000010-0000-0000-C000-000000000046}" - def __init__(self, pUnk): - self.gettingAnApplication = True - IID__IRunningObjectTable = GUID(_IRunningObjectTable.guid) - vtable_offset = IUnknown._num_methods - 1 - #RegisterIndex = 1 (skipping Register as it is not needed) - #RevokeIndex = 2 (skipping Revoke as it is not needed) - #IsRunningIndex = 3 (skipping IsRunning as it is not needed) - GetObjectIndex = 4 - #NoteChangeTimeIndex = 5 (skipping NoteChangeTime as it is not needed) - #GetTimeOfLastChangeIndex = 6 (skipping GetTimeOfLastChange as it is not needed) - EnumRunningIndex = 7 - self._GetObject = IAGFUNCTYPE(pUnk, IID__IRunningObjectTable, vtable_offset + GetObjectIndex, PVOID, POINTER(PVOID)) - self._EnumRunning = IAGFUNCTYPE(pUnk, IID__IRunningObjectTable, vtable_offset + EnumRunningIndex, POINTER(PVOID)) - def GetObject(self, pmkObjectName:"IMoniker") -> "IUnknown": - ppunkObject = IUnknown() - self._GetObject(pmkObjectName.pUnk.p, byref(ppunkObject.p)) - ppunkObject.TakeOwnership(isApplication=self.gettingAnApplication) - return ppunkObject - def EnumRunning(self) -> "_IEnumMoniker": - ppenumMoniker = IUnknown() - self._EnumRunning(byref(ppenumMoniker.p)) - ppenumMoniker.TakeOwnership() - iEnumMon = _IEnumMoniker(ppenumMoniker) - del(ppenumMoniker) - return iEnumMon - - class _IEnumMoniker(object): - guid = "{00000102-0000-0000-C000-000000000046}" - def __init__(self, pUnk): - IID__IEnumMoniker = GUID(_IEnumMoniker.guid) - vtable_offset = IUnknown._num_methods - 1 - NextIndex = 1 - #SkipIndex = 2 (skipping Skip as it is not needed) - ResetIndex = 3 - #CloneIndex = 4 (skipping Clone as it is not needed) - self._Next = IAGFUNCTYPE(pUnk, IID__IEnumMoniker, vtable_offset + NextIndex, ULONG, POINTER(PVOID), POINTER(ULONG)) - self._Reset = IAGFUNCTYPE(pUnk, IID__IEnumMoniker, vtable_offset + ResetIndex) - def Next(self) -> "_IMoniker": - one_obj = ULONG(1) - num_fetched = ULONG(0) - pUnk = IUnknown() - CLSID_AgUiApplication = GUID() - CLSIDFromString("STK12.Application", CLSID_AgUiApplication) - CreateClassMoniker(CLSID_AgUiApplication, byref(pUnk.p)) - pUnk.TakeOwnership() - self._Next(one_obj, byref(pUnk.p), byref(num_fetched)) - if num_fetched.value == 1: - iMon = _IMoniker(pUnk) - del(pUnk) - return iMon - def Reset(self): - self._Reset() - - class _IMalloc(object): - guid = "{00000002-0000-0000-C000-000000000046}" - def __init__(self, pUnk): - IID__IMalloc = GUID(_IMalloc.guid) - vtable_offset = IUnknown._num_methods - 1 - #AllocIndex = 1 (skipping Alloc as it is not needed) - #ReallocIndex = 2 (skipping Realloc as it is not needed) - FreeIndex = 3 - #GetSizeIndex = 4 (skipping GetSize as it is not needed) - #DidAllocIndex = 5 (skipping DidAlloc as it is not needed) - #HeapMinimizeIndex = 6 (skipping HeapMinimize as it is not needed) - self._Free = IAGFUNCTYPE(pUnk, IID__IMalloc, vtable_offset + FreeIndex, PVOID) - def Free(self, pv): - self._Free(pv) - - class _IMoniker(object): - guid = "{0000000f-0000-0000-C000-000000000046}" - def __init__(self, pUnk): - self.pUnk = pUnk - IID__IMoniker = GUID(_IMoniker.guid) - IPersist_num_methods = 1 - IPersistStream_num_methods = 4 - vtable_offset = IUnknown._num_methods + IPersist_num_methods + IPersistStream_num_methods - 1 - #BindToObjectIndex = 1 (skipping BindToObject as it is not needed) - #BindToStorageIndex = 2 (skipping BindToStorage as it is not needed) - #ReduceIndex = 3 (skipping Reduce as it is not needed) - #ComposeWithIndex = 4 (skipping ComposeWith as it is not needed) - #EnumIndex = 5 (skipping Enum as it is not needed) - #IsEqualIndex = 6 (skipping IsEqual as it is not needed) - #HashIndex = 7 (skipping Hash as it is not needed) - #IsRunningIndex = 8 (skipping IsRunning as it is not needed) - #GetTimeOfLastChangeIndex = 9 (skipping GetTimeOfLastChange as it is not needed) - #InverseIndex = 10 (skipping Inverse as it is not needed) - #CommonPrefixWithIndex = 11 (skipping CommonPrefixWith as it is not needed) - #RelativePathToIndex = 12 (skipping RelativePathTo as it is not needed) - GetDisplayNameIndex = 13 - #ParseDisplayNameIndex = 14 (skipping ParseDisplayName as it is not needed) - #IsSystemMonikerIndex = 15 (skipping IsSystemMoniker as it is not needed) - self._GetDisplayName = IAGFUNCTYPE(pUnk, IID__IMoniker, vtable_offset + GetDisplayNameIndex, PVOID, PVOID, POINTER(BSTR)) - def _FreeDisplayName(self, ppszDisplayName): - pMalloc = IUnknown() - CoGetMalloc(DWORD(1), byref(pMalloc.p)) - pMalloc.TakeOwnership() - iMalloc = _IMalloc(pMalloc) - iMalloc.Free(ppszDisplayName) - del(iMalloc) - del(pMalloc) - def GetDisplayName(self) -> str: - pbc = IUnknown() - pmkToLeft = IUnknown() - CreateBindCtx(DWORD(0), byref(pbc.p)) - pbc.TakeOwnership() - ppszDisplayName = BSTR() - self._GetDisplayName(pbc.p, pmkToLeft.p, byref(ppszDisplayName)) - display_name = ppszDisplayName.value - self._FreeDisplayName(ppszDisplayName) - del(pmkToLeft) - del(pbc) - return display_name - - def attach_to_stk_by_pid(pid:int) -> IUnknown: - runningObjectTable = IUnknown() - str_prog_id = "!STK.Application:" + str(pid) - if Succeeded(GetRunningObjectTable(DWORD(0), byref(runningObjectTable.p))): - runningObjectTable.TakeOwnership() - runningObjectTable = _IRunningObjectTable(runningObjectTable) - enumMoniker = runningObjectTable.EnumRunning() - enumMoniker.Reset() - moniker = enumMoniker.Next() - while moniker is not None: - instanceName = moniker.GetDisplayName() - if instanceName == str_prog_id: - ret = runningObjectTable.GetObject(moniker) - del(moniker) - del(enumMoniker) - del(runningObjectTable) - return ret - else: - moniker = enumMoniker.Next() - del(moniker) - del(enumMoniker) - del(runningObjectTable) - else: - raise RuntimeError("Failed to retrieve the Running Object Table.") -else: - def attach_to_stk_by_pid(pid:int) -> IUnknown: +class _IRunningObjectTable(object): + guid = "{00000010-0000-0000-C000-000000000046}" + def __init__(self, pUnk): if os.name != "nt": raise RuntimeError("STKDesktop is only available on Windows. Use STKEngine.") - + self.gettingAnApplication = True + IID__IRunningObjectTable = GUID(_IRunningObjectTable.guid) + vtable_offset = IUnknown._num_methods - 1 + #RegisterIndex = 1 (skipping Register as it is not needed) + #RevokeIndex = 2 (skipping Revoke as it is not needed) + #IsRunningIndex = 3 (skipping IsRunning as it is not needed) + GetObjectIndex = 4 + #NoteChangeTimeIndex = 5 (skipping NoteChangeTime as it is not needed) + #GetTimeOfLastChangeIndex = 6 (skipping GetTimeOfLastChange as it is not needed) + EnumRunningIndex = 7 + self._GetObject = IAGFUNCTYPE(pUnk, IID__IRunningObjectTable, vtable_offset + GetObjectIndex, PVOID, POINTER(PVOID)) + self._EnumRunning = IAGFUNCTYPE(pUnk, IID__IRunningObjectTable, vtable_offset + EnumRunningIndex, POINTER(PVOID)) + def GetObject(self, pmkObjectName: "_IMoniker") -> "IUnknown": + ppunkObject = IUnknown() + self._GetObject(pmkObjectName.pUnk.p, byref(ppunkObject.p)) + ppunkObject.TakeOwnership(isApplication=self.gettingAnApplication) + return ppunkObject + def EnumRunning(self) -> "_IEnumMoniker": + ppenumMoniker = IUnknown() + self._EnumRunning(byref(ppenumMoniker.p)) + ppenumMoniker.TakeOwnership() + iEnumMon = _IEnumMoniker(ppenumMoniker) + del(ppenumMoniker) + return iEnumMon + +class _IEnumMoniker(object): + guid = "{00000102-0000-0000-C000-000000000046}" + def __init__(self, pUnk): + if os.name != "nt": + raise RuntimeError("STKDesktop is only available on Windows. Use STKEngine.") + IID__IEnumMoniker = GUID(_IEnumMoniker.guid) + vtable_offset = IUnknown._num_methods - 1 + NextIndex = 1 + #SkipIndex = 2 (skipping Skip as it is not needed) + ResetIndex = 3 + #CloneIndex = 4 (skipping Clone as it is not needed) + self._Next = IAGFUNCTYPE(pUnk, IID__IEnumMoniker, vtable_offset + NextIndex, ULONG, POINTER(PVOID), POINTER(ULONG)) + self._Reset = IAGFUNCTYPE(pUnk, IID__IEnumMoniker, vtable_offset + ResetIndex) + def Next(self) -> "_IMoniker": + one_obj = ULONG(1) + num_fetched = ULONG(0) + pUnk = IUnknown() + CLSID_AgUiApplication = GUID() + CLSIDFromString("STK12.Application", CLSID_AgUiApplication) + _ole32lib.CreateClassMoniker(CLSID_AgUiApplication, byref(pUnk.p)) + pUnk.TakeOwnership() + self._Next(one_obj, byref(pUnk.p), byref(num_fetched)) + if num_fetched.value == 1: + iMon = _IMoniker(pUnk) + del(pUnk) + return iMon + def Reset(self): + self._Reset() + +class _IMalloc(object): + guid = "{00000002-0000-0000-C000-000000000046}" + def __init__(self, pUnk): + if os.name != "nt": + raise RuntimeError("STKDesktop is only available on Windows. Use STKEngine.") + IID__IMalloc = GUID(_IMalloc.guid) + vtable_offset = IUnknown._num_methods - 1 + #AllocIndex = 1 (skipping Alloc as it is not needed) + #ReallocIndex = 2 (skipping Realloc as it is not needed) + FreeIndex = 3 + #GetSizeIndex = 4 (skipping GetSize as it is not needed) + #DidAllocIndex = 5 (skipping DidAlloc as it is not needed) + #HeapMinimizeIndex = 6 (skipping HeapMinimize as it is not needed) + self._Free = IAGFUNCTYPE(pUnk, IID__IMalloc, vtable_offset + FreeIndex, PVOID) + def Free(self, pv): + self._Free(pv) + +class _IMoniker(object): + guid = "{0000000f-0000-0000-C000-000000000046}" + def __init__(self, pUnk): + if os.name != "nt": + raise RuntimeError("STKDesktop is only available on Windows. Use STKEngine.") + self.pUnk = pUnk + IID__IMoniker = GUID(_IMoniker.guid) + IPersist_num_methods = 1 + IPersistStream_num_methods = 4 + vtable_offset = IUnknown._num_methods + IPersist_num_methods + IPersistStream_num_methods - 1 + #BindToObjectIndex = 1 (skipping BindToObject as it is not needed) + #BindToStorageIndex = 2 (skipping BindToStorage as it is not needed) + #ReduceIndex = 3 (skipping Reduce as it is not needed) + #ComposeWithIndex = 4 (skipping ComposeWith as it is not needed) + #EnumIndex = 5 (skipping Enum as it is not needed) + #IsEqualIndex = 6 (skipping IsEqual as it is not needed) + #HashIndex = 7 (skipping Hash as it is not needed) + #IsRunningIndex = 8 (skipping IsRunning as it is not needed) + #GetTimeOfLastChangeIndex = 9 (skipping GetTimeOfLastChange as it is not needed) + #InverseIndex = 10 (skipping Inverse as it is not needed) + #CommonPrefixWithIndex = 11 (skipping CommonPrefixWith as it is not needed) + #RelativePathToIndex = 12 (skipping RelativePathTo as it is not needed) + GetDisplayNameIndex = 13 + #ParseDisplayNameIndex = 14 (skipping ParseDisplayName as it is not needed) + #IsSystemMonikerIndex = 15 (skipping IsSystemMoniker as it is not needed) + self._GetDisplayName = IAGFUNCTYPE(pUnk, IID__IMoniker, vtable_offset + GetDisplayNameIndex, PVOID, PVOID, POINTER(BSTR)) + def _FreeDisplayName(self, ppszDisplayName): + pMalloc = IUnknown() + _ole32lib.CoGetMalloc(DWORD(1), byref(pMalloc.p)) + pMalloc.TakeOwnership() + iMalloc = _IMalloc(pMalloc) + iMalloc.Free(ppszDisplayName) + del(iMalloc) + del(pMalloc) + def GetDisplayName(self) -> str: + pbc = IUnknown() + pmkToLeft = IUnknown() + _ole32lib.CreateBindCtx(DWORD(0), byref(pbc.p)) + pbc.TakeOwnership() + ppszDisplayName = BSTR() + self._GetDisplayName(pbc.p, pmkToLeft.p, byref(ppszDisplayName)) + display_name = ppszDisplayName.value + self._FreeDisplayName(ppszDisplayName) + del(pmkToLeft) + del(pbc) + return display_name + +def attach_to_stk_by_pid(pid:int) -> IUnknown: + if os.name != "nt": + raise RuntimeError("STKDesktop is only available on Windows. Use STKEngine.") + runningObjectTable = IUnknown() + str_prog_id = "!STK.Application:" + str(pid) + if Succeeded(_ole32lib.GetRunningObjectTable(DWORD(0), byref(runningObjectTable.p))): + runningObjectTable.TakeOwnership() + runningObjectTable = _IRunningObjectTable(runningObjectTable) + enumMoniker = runningObjectTable.EnumRunning() + enumMoniker.Reset() + moniker = enumMoniker.Next() + while moniker is not None: + instanceName = moniker.GetDisplayName() + if instanceName == str_prog_id: + ret = runningObjectTable.GetObject(moniker) + del(moniker) + del(enumMoniker) + del(runningObjectTable) + return ret + else: + moniker = enumMoniker.Next() + del(moniker) + del(enumMoniker) + del(runningObjectTable) + else: + raise RuntimeError("Failed to retrieve the Running Object Table.") + + \ No newline at end of file From 9e09f9ebcb93b927fa2baf21cdd3699110cfa987 Mon Sep 17 00:00:00 2001 From: Sylvain <15435472+duposyl@users.noreply.github.com> Date: Tue, 8 Nov 2022 20:55:42 -0500 Subject: [PATCH 4/4] Removing file that is no longer needed. --- src/ansys/stk/core/stkengine/stkengine.py | 203 ---------------------- 1 file changed, 203 deletions(-) delete mode 100644 src/ansys/stk/core/stkengine/stkengine.py diff --git a/src/ansys/stk/core/stkengine/stkengine.py b/src/ansys/stk/core/stkengine/stkengine.py deleted file mode 100644 index c7e325e04d..0000000000 --- a/src/ansys/stk/core/stkengine/stkengine.py +++ /dev/null @@ -1,203 +0,0 @@ -################################################################################ -# Copyright 2020-2020, Analytical Graphics, Inc. -################################################################################ - -__all__ = ["STKEngine", "STKEngineApplication", "STKEngineTimerType"] - -import os -from ctypes import byref -from enum import IntEnum -from ..internal.timerutil import * - -if os.name != "nt": - from ctypes import CFUNCTYPE, cdll - from ctypes.util import find_library - -from ..internal.comutil import CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, GUID -from ..internal.comutil import CLSIDFromString, CoCreateInstance, CoInitializeManager, IUnknown, ObjectLifetimeManager, Succeeded -from ..internal.eventutil import EventSubscriptionManager -from ..internal.stkxinitialization import * -from ..utilities.exceptions import * -from ..graphics import * -from ..stkobjects import * -from ..stkobjects.astrogator import * -from ..stkobjects.aviator import * -from ..stkutil import * -from ..stkx import * -from ..vgt import * - -class STKEngineTimerType(IntEnum): - DisableTimers = 1 - TkinterMainloop = 2 - InteractivePython = 3 - SigAlarm = 4 - SigRt = 5 - -class STKEngineApplication(AgSTKXApplication): - """ - Interact with STK Engine. - Use STKEngine.StartApplication() to obtain an initialized STKEngineApplication object. - """ - def __init__(self): - AgSTKXApplication.__init__(self) - self.__dict__["_stk_install_dir"] = None - self.__dict__["_stk_config_dir"] = None - self.__dict__["_initialized"] = False - - def _private_init(self, pUnk:IUnknown, stk_install_dir, stk_config_dir, noGraphics): - AgSTKXApplication._private_init(self, pUnk) - self.__dict__["_stk_install_dir"] = stk_install_dir - self.__dict__["_stk_config_dir"] = stk_config_dir - self._STKXInitialize() - self._STKXInitializeTimer(noGraphics) - self.__dict__["_initialized"] = True - - def __del__(self): - self.ShutDown() - - def _STKXInitialize(self): - if os.name=="nt": - return - CLSID_AgSTKXInitialize = GUID() - if Succeeded(CLSIDFromString("{3B85901D-FC82-4733-97E6-5BB25CE69379}", CLSID_AgSTKXInitialize)): - IID_IUnknown = GUID(IUnknown._guid) - stkxinit_unk = IUnknown() - if Succeeded(CoCreateInstance(byref(CLSID_AgSTKXInitialize), None, CLSCTX_INPROC_SERVER, byref(IID_IUnknown), byref(stkxinit_unk.p))): - stkxinit_unk.TakeOwnership() - pInit = IAgSTKXInitialize() - pInit._private_init(stkxinit_unk) - install_dir = self.__dict__["_stk_install_dir"] if self.__dict__["_stk_install_dir"] is not None else os.getenv("STK_INSTALL_DIR") - if install_dir is None: - raise STKInitializationError("Please set a valid STK_INSTALL_DIR environment variable.") - config_dir = self.__dict__["_stk_config_dir"] if self.__dict__["_stk_config_dir"] is not None else os.getenv("STK_CONFIG_DIR") - if config_dir is None: - raise STKInitializationError("Please set a valid STK_CONFIG_DIR environment variable.") - pInit.InitializeData(install_dir, config_dir) - - @staticmethod - def _get_signo(sigrtmin_offset): - if os.name=="nt": - return None - libc = cdll.LoadLibrary(find_library("c")) - __libc_current_sigrtmin = CFUNCTYPE(c_int)(("__libc_current_sigrtmin", libc)) - return __libc_current_sigrtmin() + sigrtmin_offset - - def _set_timer_type_from_env(self): - timer_type = int(os.getenv("STK_PYTHONAPI_TIMERTYPE", "4")) - if os.name=="nt" or timer_type == STKEngineTimerType.DisableTimers: - self.__dict__["_timer_impl"] = NullTimer() - elif timer_type == STKEngineTimerType.TkinterMainloop or timer_type == STKEngineTimerType.InteractivePython: - self.__dict__["_timer_impl"] = TclTimer() - elif timer_type == STKEngineTimerType.SigAlarm: - self.__dict__["_timer_impl"] = SigAlarmTimer() - elif timer_type == STKEngineTimerType.SigRt: - sigrtmin_offset = int(os.getenv("STK_PYTHONAPI_TIMERTYPE5_SIGRTMIN_OFFSET", "0")) - signo = STKEngineApplication._get_signo(sigrtmin_offset) - self.__dict__["_timer_impl"] = SigRtTimer(signo) - - def _user_override_timer_type(self) -> bool: - return ("STK_PYTHONAPI_TIMERTYPE" in os.environ) - - def _STKXInitializeTimer(self, noGraphics): - if os.name=="nt": - #Timers are not implemented on Windows, use a placeholder. - self.__dict__["_timer_impl"] = NullTimer() - elif noGraphics: - self._set_timer_type_from_env() - else: - #default to Tkinter mainloop in graphics applications, but allow the user to override - #e.g. if controls are not being used, the SigAlarm timer might be desired. - if self._user_override_timer_type(): - self._set_timer_type_from_env() - else: - self.__dict__["_timer_impl"] = TclTimer() - - def NewObjectRoot(self) -> AgStkObjectRoot: - """Create a new object model root for the STK Engine application.""" - if not self.__dict__["_initialized"]: - raise RuntimeError("STKEngineApplication has not been properly initialized. Use StartApplication() to obtain the STKEngineApplication object.") - CLSID_AgStkObjectRoot = GUID() - if Succeeded(CLSIDFromString("{96C1CE4E-C61D-4657-99CB-8581E12693FE}", CLSID_AgStkObjectRoot)): - IID_IUnknown = GUID(IUnknown._guid) - root_unk = IUnknown() - CoCreateInstance(byref(CLSID_AgStkObjectRoot), None, CLSCTX_INPROC_SERVER, byref(IID_IUnknown), byref(root_unk.p)) - root_unk.TakeOwnership() - root = AgStkObjectRoot() - root._private_init(root_unk) - return root - - def ShutDown(self) -> None: - """Shut down the STK Engine application.""" - if self._initialized: - EventSubscriptionManager.UnsubscribeAll() - self._timer_impl.Terminate() - ObjectLifetimeManager.ReleaseAll(releaseApplication=False) - self.Terminate() - ObjectLifetimeManager.ReleaseAll(releaseApplication=True) - CoInitializeManager.uninitialize() - self.__dict__["_initialized"] = False - - -class STKEngine(object): - """Initialize and manage the STK Engine application.""" - _is_engine_running = False - _stk_config_dir = None - _stk_install_dir = None - - @staticmethod - def _initX11(noGraphics): - if noGraphics or os.name=="nt": - return - try: - x11lib = cdll.LoadLibrary(find_library("X11")) - XInitThreads = CFUNCTYPE(None)(("XInitThreads", x11lib)) - XInitThreads() - except: - raise STKRuntimeError("Failed attempting to run graphics mode without X11.") - - @staticmethod - def StartApplication(noGraphics:bool=True) -> STKEngineApplication: - """ - Initialize STK Engine in-process and return the instance. - Must only be used once per Python process. - """ - if STKEngine._is_engine_running: - raise RuntimeError("Only one STKEngine instance is allowed per Python process.") - CoInitializeManager.initialize() - CLSID_AgSTKXApplication = GUID() - if Succeeded(CLSIDFromString("{062AB565-B121-45B5-A9A9-B412CEFAB6A9}", CLSID_AgSTKXApplication)): - pUnk = IUnknown() - IID_IUnknown = GUID(IUnknown._guid) - if Succeeded(CoCreateInstance(byref(CLSID_AgSTKXApplication), None, CLSCTX_INPROC_SERVER, byref(IID_IUnknown), byref(pUnk.p))): - pUnk.TakeOwnership(isApplication=True) - STKEngine._is_engine_running = True - STKEngine._initX11(noGraphics) - engine = STKEngineApplication() - engine._private_init(pUnk, STKEngine._stk_install_dir, STKEngine._stk_config_dir, noGraphics) - engine.NoGraphics = noGraphics - return engine - raise STKInitializationError("Failed to create STK Engine application. Check for successful install and registration.") - - if os.name != "nt": - @staticmethod - def SetSTKInstallDir(stkInstallDir:str) -> None: - """ - Setting the install directory using this method will override the STK_INSTALL_DIR environment variable. - If this method is not called, STK_INSTALL_DIR will be used instead. This method must be called before - StartApplication(). - """ - STKEngine._stk_install_dir = stkInstallDir - - @staticmethod - def SetSTKConfigDir(stkConfigDir:str) -> None: - """ - Setting the config directory using this method will override the STK_CONFIG_DIR environment variable. - If this method is not called, STK_CONFIG_DIR will be used instead. This method must be called before - StartApplication(). - """ - STKEngine._stk_config_dir = stkConfigDir - - -################################################################################ -# Copyright 2020-2020, Analytical Graphics, Inc. -################################################################################