Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

policy.py 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  1. """Policies
  2. Note that Dispatchers are now implemented in "dispatcher.py", but
  3. are still documented here.
  4. Policies
  5. A policy is an object which manages the interaction between a public
  6. Python object, and COM . In simple terms, the policy object is the
  7. object which is actually called by COM, and it invokes the requested
  8. method, fetches/sets the requested property, etc. See the
  9. @win32com.server.policy.CreateInstance@ method for a description of
  10. how a policy is specified or created.
  11. Exactly how a policy determines which underlying object method/property
  12. is obtained is up to the policy. A few policies are provided, but you
  13. can build your own. See each policy class for a description of how it
  14. implements its policy.
  15. There is a policy that allows the object to specify exactly which
  16. methods and properties will be exposed. There is also a policy that
  17. will dynamically expose all Python methods and properties - even those
  18. added after the object has been instantiated.
  19. Dispatchers
  20. A Dispatcher is a level in front of a Policy. A dispatcher is the
  21. thing which actually receives the COM calls, and passes them to the
  22. policy object (which in turn somehow does something with the wrapped
  23. object).
  24. It is important to note that a policy does not need to have a dispatcher.
  25. A dispatcher has the same interface as a policy, and simply steps in its
  26. place, delegating to the real policy. The primary use for a Dispatcher
  27. is to support debugging when necessary, but without imposing overheads
  28. when not (ie, by not using a dispatcher at all).
  29. There are a few dispatchers provided - "tracing" dispatchers which simply
  30. prints calls and args (including a variation which uses
  31. win32api.OutputDebugString), and a "debugger" dispatcher, which can
  32. invoke the debugger when necessary.
  33. Error Handling
  34. It is important to realise that the caller of these interfaces may
  35. not be Python. Therefore, general Python exceptions and tracebacks aren't
  36. much use.
  37. In general, there is an Exception class that should be raised, to allow
  38. the framework to extract rich COM type error information.
  39. The general rule is that the **only** exception returned from Python COM
  40. Server code should be an Exception instance. Any other Python exception
  41. should be considered an implementation bug in the server (if not, it
  42. should be handled, and an appropriate Exception instance raised). Any
  43. other exception is considered "unexpected", and a dispatcher may take
  44. special action (see Dispatchers above)
  45. Occasionally, the implementation will raise the policy.error error.
  46. This usually means there is a problem in the implementation that the
  47. Python programmer should fix.
  48. For example, if policy is asked to wrap an object which it can not
  49. support (because, eg, it does not provide _public_methods_ or _dynamic_)
  50. then policy.error will be raised, indicating it is a Python programmers
  51. problem, rather than a COM error.
  52. """
  53. __author__ = "Greg Stein and Mark Hammond"
  54. import sys
  55. import types
  56. import pythoncom
  57. import pywintypes
  58. import win32api
  59. import win32con
  60. import winerror
  61. # Import a few important constants to speed lookups.
  62. from pythoncom import (
  63. DISPATCH_METHOD,
  64. DISPATCH_PROPERTYGET,
  65. DISPATCH_PROPERTYPUT,
  66. DISPATCH_PROPERTYPUTREF,
  67. DISPID_COLLECT,
  68. DISPID_CONSTRUCTOR,
  69. DISPID_DESTRUCTOR,
  70. DISPID_EVALUATE,
  71. DISPID_NEWENUM,
  72. DISPID_PROPERTYPUT,
  73. DISPID_STARTENUM,
  74. DISPID_UNKNOWN,
  75. DISPID_VALUE,
  76. )
  77. S_OK = 0
  78. # Few more globals to speed things.
  79. IDispatchType = pythoncom.TypeIIDs[pythoncom.IID_IDispatch]
  80. IUnknownType = pythoncom.TypeIIDs[pythoncom.IID_IUnknown]
  81. from .exception import COMException
  82. error = __name__ + " error"
  83. regSpec = "CLSID\\%s\\PythonCOM"
  84. regPolicy = "CLSID\\%s\\PythonCOMPolicy"
  85. regDispatcher = "CLSID\\%s\\PythonCOMDispatcher"
  86. regAddnPath = "CLSID\\%s\\PythonCOMPath"
  87. def CreateInstance(clsid, reqIID):
  88. """Create a new instance of the specified IID
  89. The COM framework **always** calls this function to create a new
  90. instance for the specified CLSID. This function looks up the
  91. registry for the name of a policy, creates the policy, and asks the
  92. policy to create the specified object by calling the _CreateInstance_ method.
  93. Exactly how the policy creates the instance is up to the policy. See the
  94. specific policy documentation for more details.
  95. """
  96. # First see is sys.path should have something on it.
  97. try:
  98. addnPaths = win32api.RegQueryValue(
  99. win32con.HKEY_CLASSES_ROOT, regAddnPath % clsid
  100. ).split(";")
  101. for newPath in addnPaths:
  102. if newPath not in sys.path:
  103. sys.path.insert(0, newPath)
  104. except win32api.error:
  105. pass
  106. try:
  107. policy = win32api.RegQueryValue(win32con.HKEY_CLASSES_ROOT, regPolicy % clsid)
  108. policy = resolve_func(policy)
  109. except win32api.error:
  110. policy = DefaultPolicy
  111. try:
  112. dispatcher = win32api.RegQueryValue(
  113. win32con.HKEY_CLASSES_ROOT, regDispatcher % clsid
  114. )
  115. if dispatcher:
  116. dispatcher = resolve_func(dispatcher)
  117. except win32api.error:
  118. dispatcher = None
  119. if dispatcher:
  120. retObj = dispatcher(policy, None)
  121. else:
  122. retObj = policy(None)
  123. return retObj._CreateInstance_(clsid, reqIID)
  124. class BasicWrapPolicy:
  125. """The base class of policies.
  126. Normally not used directly (use a child class, instead)
  127. This policy assumes we are wrapping another object
  128. as the COM server. This supports the delegation of the core COM entry points
  129. to either the wrapped object, or to a child class.
  130. This policy supports the following special attributes on the wrapped object
  131. _query_interface_ -- A handler which can respond to the COM 'QueryInterface' call.
  132. _com_interfaces_ -- An optional list of IIDs which the interface will assume are
  133. valid for the object.
  134. _invoke_ -- A handler which can respond to the COM 'Invoke' call. If this attribute
  135. is not provided, then the default policy implementation is used. If this attribute
  136. does exist, it is responsible for providing all required functionality - ie, the
  137. policy _invoke_ method is not invoked at all (and nor are you able to call it!)
  138. _getidsofnames_ -- A handler which can respond to the COM 'GetIDsOfNames' call. If this attribute
  139. is not provided, then the default policy implementation is used. If this attribute
  140. does exist, it is responsible for providing all required functionality - ie, the
  141. policy _getidsofnames_ method is not invoked at all (and nor are you able to call it!)
  142. IDispatchEx functionality:
  143. _invokeex_ -- Very similar to _invoke_, except slightly different arguments are used.
  144. And the result is just the _real_ result (rather than the (hresult, argErr, realResult)
  145. tuple that _invoke_ uses.
  146. This is the new, prefered handler (the default _invoke_ handler simply called _invokeex_)
  147. _getdispid_ -- Very similar to _getidsofnames_, except slightly different arguments are used,
  148. and only 1 property at a time can be fetched (which is all we support in getidsofnames anyway!)
  149. This is the new, prefered handler (the default _invoke_ handler simply called _invokeex_)
  150. _getnextdispid_- uses self._name_to_dispid_ to enumerate the DISPIDs
  151. """
  152. def __init__(self, object):
  153. """Initialise the policy object
  154. Params:
  155. object -- The object to wrap. May be None *iff* @BasicWrapPolicy._CreateInstance_@ will be
  156. called immediately after this to setup a brand new object
  157. """
  158. if object is not None:
  159. self._wrap_(object)
  160. def _CreateInstance_(self, clsid, reqIID):
  161. """Creates a new instance of a **wrapped** object
  162. This method looks up a "@win32com.server.policy.regSpec@" % clsid entry
  163. in the registry (using @DefaultPolicy@)
  164. """
  165. try:
  166. classSpec = win32api.RegQueryValue(
  167. win32con.HKEY_CLASSES_ROOT, regSpec % clsid
  168. )
  169. except win32api.error:
  170. raise error(
  171. "The object is not correctly registered - %s key can not be read"
  172. % (regSpec % clsid)
  173. )
  174. myob = call_func(classSpec)
  175. self._wrap_(myob)
  176. try:
  177. return pythoncom.WrapObject(self, reqIID)
  178. except pythoncom.com_error as xxx_todo_changeme:
  179. (hr, desc, exc, arg) = xxx_todo_changeme.args
  180. from win32com.util import IIDToInterfaceName
  181. desc = (
  182. "The object '%r' was created, but does not support the "
  183. "interface '%s'(%s): %s"
  184. % (myob, IIDToInterfaceName(reqIID), reqIID, desc)
  185. )
  186. raise pythoncom.com_error(hr, desc, exc, arg)
  187. def _wrap_(self, object):
  188. """Wraps up the specified object.
  189. This function keeps a reference to the passed
  190. object, and may interogate it to determine how to respond to COM requests, etc.
  191. """
  192. # We "clobber" certain of our own methods with ones
  193. # provided by the wrapped object, iff they exist.
  194. self._name_to_dispid_ = {}
  195. ob = self._obj_ = object
  196. if hasattr(ob, "_query_interface_"):
  197. self._query_interface_ = ob._query_interface_
  198. if hasattr(ob, "_invoke_"):
  199. self._invoke_ = ob._invoke_
  200. if hasattr(ob, "_invokeex_"):
  201. self._invokeex_ = ob._invokeex_
  202. if hasattr(ob, "_getidsofnames_"):
  203. self._getidsofnames_ = ob._getidsofnames_
  204. if hasattr(ob, "_getdispid_"):
  205. self._getdispid_ = ob._getdispid_
  206. # Allow for override of certain special attributes.
  207. if hasattr(ob, "_com_interfaces_"):
  208. self._com_interfaces_ = []
  209. # Allow interfaces to be specified by name.
  210. for i in ob._com_interfaces_:
  211. if type(i) != pywintypes.IIDType:
  212. # Prolly a string!
  213. if i[0] != "{":
  214. i = pythoncom.InterfaceNames[i]
  215. else:
  216. i = pythoncom.MakeIID(i)
  217. self._com_interfaces_.append(i)
  218. else:
  219. self._com_interfaces_ = []
  220. # "QueryInterface" handling.
  221. def _QueryInterface_(self, iid):
  222. """The main COM entry-point for QueryInterface.
  223. This checks the _com_interfaces_ attribute and if the interface is not specified
  224. there, it calls the derived helper _query_interface_
  225. """
  226. if iid in self._com_interfaces_:
  227. return 1
  228. return self._query_interface_(iid)
  229. def _query_interface_(self, iid):
  230. """Called if the object does not provide the requested interface in _com_interfaces_,
  231. and does not provide a _query_interface_ handler.
  232. Returns a result to the COM framework indicating the interface is not supported.
  233. """
  234. return 0
  235. # "Invoke" handling.
  236. def _Invoke_(self, dispid, lcid, wFlags, args):
  237. """The main COM entry-point for Invoke.
  238. This calls the _invoke_ helper.
  239. """
  240. # Translate a possible string dispid to real dispid.
  241. if type(dispid) == type(""):
  242. try:
  243. dispid = self._name_to_dispid_[dispid.lower()]
  244. except KeyError:
  245. raise COMException(
  246. scode=winerror.DISP_E_MEMBERNOTFOUND, desc="Member not found"
  247. )
  248. return self._invoke_(dispid, lcid, wFlags, args)
  249. def _invoke_(self, dispid, lcid, wFlags, args):
  250. # Delegates to the _invokeex_ implementation. This allows
  251. # a custom policy to define _invokeex_, and automatically get _invoke_ too.
  252. return S_OK, -1, self._invokeex_(dispid, lcid, wFlags, args, None, None)
  253. # "GetIDsOfNames" handling.
  254. def _GetIDsOfNames_(self, names, lcid):
  255. """The main COM entry-point for GetIDsOfNames.
  256. This checks the validity of the arguments, and calls the _getidsofnames_ helper.
  257. """
  258. if len(names) > 1:
  259. raise COMException(
  260. scode=winerror.DISP_E_INVALID,
  261. desc="Cannot support member argument names",
  262. )
  263. return self._getidsofnames_(names, lcid)
  264. def _getidsofnames_(self, names, lcid):
  265. ### note: lcid is being ignored...
  266. return (self._getdispid_(names[0], 0),)
  267. # IDispatchEx support for policies. Most of the IDispathEx functionality
  268. # by default will raise E_NOTIMPL. Thus it is not necessary for derived
  269. # policies to explicitely implement all this functionality just to not implement it!
  270. def _GetDispID_(self, name, fdex):
  271. return self._getdispid_(name, fdex)
  272. def _getdispid_(self, name, fdex):
  273. try:
  274. ### TODO - look at the fdex flags!!!
  275. return self._name_to_dispid_[name.lower()]
  276. except KeyError:
  277. raise COMException(scode=winerror.DISP_E_UNKNOWNNAME)
  278. # "InvokeEx" handling.
  279. def _InvokeEx_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider):
  280. """The main COM entry-point for InvokeEx.
  281. This calls the _invokeex_ helper.
  282. """
  283. # Translate a possible string dispid to real dispid.
  284. if type(dispid) == type(""):
  285. try:
  286. dispid = self._name_to_dispid_[dispid.lower()]
  287. except KeyError:
  288. raise COMException(
  289. scode=winerror.DISP_E_MEMBERNOTFOUND, desc="Member not found"
  290. )
  291. return self._invokeex_(dispid, lcid, wFlags, args, kwargs, serviceProvider)
  292. def _invokeex_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider):
  293. """A stub for _invokeex_ - should never be called.
  294. Simply raises an exception.
  295. """
  296. # Base classes should override this method (and not call the base)
  297. raise error("This class does not provide _invokeex_ semantics")
  298. def _DeleteMemberByName_(self, name, fdex):
  299. return self._deletememberbyname_(name, fdex)
  300. def _deletememberbyname_(self, name, fdex):
  301. raise COMException(scode=winerror.E_NOTIMPL)
  302. def _DeleteMemberByDispID_(self, id):
  303. return self._deletememberbydispid(id)
  304. def _deletememberbydispid_(self, id):
  305. raise COMException(scode=winerror.E_NOTIMPL)
  306. def _GetMemberProperties_(self, id, fdex):
  307. return self._getmemberproperties_(id, fdex)
  308. def _getmemberproperties_(self, id, fdex):
  309. raise COMException(scode=winerror.E_NOTIMPL)
  310. def _GetMemberName_(self, dispid):
  311. return self._getmembername_(dispid)
  312. def _getmembername_(self, dispid):
  313. raise COMException(scode=winerror.E_NOTIMPL)
  314. def _GetNextDispID_(self, fdex, dispid):
  315. return self._getnextdispid_(fdex, dispid)
  316. def _getnextdispid_(self, fdex, dispid):
  317. ids = list(self._name_to_dispid_.values())
  318. ids.sort()
  319. if DISPID_STARTENUM in ids:
  320. ids.remove(DISPID_STARTENUM)
  321. if dispid == DISPID_STARTENUM:
  322. return ids[0]
  323. else:
  324. try:
  325. return ids[ids.index(dispid) + 1]
  326. except ValueError: # dispid not in list?
  327. raise COMException(scode=winerror.E_UNEXPECTED)
  328. except IndexError: # No more items
  329. raise COMException(scode=winerror.S_FALSE)
  330. def _GetNameSpaceParent_(self):
  331. return self._getnamespaceparent()
  332. def _getnamespaceparent_(self):
  333. raise COMException(scode=winerror.E_NOTIMPL)
  334. class MappedWrapPolicy(BasicWrapPolicy):
  335. """Wraps an object using maps to do its magic
  336. This policy wraps up a Python object, using a number of maps
  337. which translate from a Dispatch ID and flags, into an object to call/getattr, etc.
  338. It is the responsibility of derived classes to determine exactly how the
  339. maps are filled (ie, the derived classes determine the map filling policy.
  340. This policy supports the following special attributes on the wrapped object
  341. _dispid_to_func_/_dispid_to_get_/_dispid_to_put_ -- These are dictionaries
  342. (keyed by integer dispid, values are string attribute names) which the COM
  343. implementation uses when it is processing COM requests. Note that the implementation
  344. uses this dictionary for its own purposes - not a copy - which means the contents of
  345. these dictionaries will change as the object is used.
  346. """
  347. def _wrap_(self, object):
  348. BasicWrapPolicy._wrap_(self, object)
  349. ob = self._obj_
  350. if hasattr(ob, "_dispid_to_func_"):
  351. self._dispid_to_func_ = ob._dispid_to_func_
  352. else:
  353. self._dispid_to_func_ = {}
  354. if hasattr(ob, "_dispid_to_get_"):
  355. self._dispid_to_get_ = ob._dispid_to_get_
  356. else:
  357. self._dispid_to_get_ = {}
  358. if hasattr(ob, "_dispid_to_put_"):
  359. self._dispid_to_put_ = ob._dispid_to_put_
  360. else:
  361. self._dispid_to_put_ = {}
  362. def _getmembername_(self, dispid):
  363. if dispid in self._dispid_to_func_:
  364. return self._dispid_to_func_[dispid]
  365. elif dispid in self._dispid_to_get_:
  366. return self._dispid_to_get_[dispid]
  367. elif dispid in self._dispid_to_put_:
  368. return self._dispid_to_put_[dispid]
  369. else:
  370. raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND)
  371. class DesignatedWrapPolicy(MappedWrapPolicy):
  372. """A policy which uses a mapping to link functions and dispid
  373. A MappedWrappedPolicy which allows the wrapped object to specify, via certain
  374. special named attributes, exactly which methods and properties are exposed.
  375. All a wrapped object need do is provide the special attributes, and the policy
  376. will handle everything else.
  377. Attributes:
  378. _public_methods_ -- Required, unless a typelib GUID is given -- A list
  379. of strings, which must be the names of methods the object
  380. provides. These methods will be exposed and callable
  381. from other COM hosts.
  382. _public_attrs_ A list of strings, which must be the names of attributes on the object.
  383. These attributes will be exposed and readable and possibly writeable from other COM hosts.
  384. _readonly_attrs_ -- A list of strings, which must also appear in _public_attrs. These
  385. attributes will be readable, but not writable, by other COM hosts.
  386. _value_ -- A method that will be called if the COM host requests the "default" method
  387. (ie, calls Invoke with dispid==DISPID_VALUE)
  388. _NewEnum -- A method that will be called if the COM host requests an enumerator on the
  389. object (ie, calls Invoke with dispid==DISPID_NEWENUM.)
  390. It is the responsibility of the method to ensure the returned
  391. object conforms to the required Enum interface.
  392. _typelib_guid_ -- The GUID of the typelibrary with interface definitions we use.
  393. _typelib_version_ -- A tuple of (major, minor) with a default of 1,1
  394. _typelib_lcid_ -- The LCID of the typelib, default = LOCALE_USER_DEFAULT
  395. _Evaluate -- Dunno what this means, except the host has called Invoke with dispid==DISPID_EVALUATE!
  396. See the COM documentation for details.
  397. """
  398. def _wrap_(self, ob):
  399. # If we have nominated universal interfaces to support, load them now
  400. tlb_guid = getattr(ob, "_typelib_guid_", None)
  401. if tlb_guid is not None:
  402. tlb_major, tlb_minor = getattr(ob, "_typelib_version_", (1, 0))
  403. tlb_lcid = getattr(ob, "_typelib_lcid_", 0)
  404. from win32com import universal
  405. # XXX - what if the user wants to implement interfaces from multiple
  406. # typelibs?
  407. # Filter out all 'normal' IIDs (ie, IID objects and strings starting with {
  408. interfaces = [
  409. i
  410. for i in getattr(ob, "_com_interfaces_", [])
  411. if type(i) != pywintypes.IIDType and not i.startswith("{")
  412. ]
  413. universal_data = universal.RegisterInterfaces(
  414. tlb_guid, tlb_lcid, tlb_major, tlb_minor, interfaces
  415. )
  416. else:
  417. universal_data = []
  418. MappedWrapPolicy._wrap_(self, ob)
  419. if not hasattr(ob, "_public_methods_") and not hasattr(ob, "_typelib_guid_"):
  420. raise error(
  421. "Object does not support DesignatedWrapPolicy, as it does not have either _public_methods_ or _typelib_guid_ attributes."
  422. )
  423. # Copy existing _dispid_to_func_ entries to _name_to_dispid_
  424. for dispid, name in self._dispid_to_func_.items():
  425. self._name_to_dispid_[name.lower()] = dispid
  426. for dispid, name in self._dispid_to_get_.items():
  427. self._name_to_dispid_[name.lower()] = dispid
  428. for dispid, name in self._dispid_to_put_.items():
  429. self._name_to_dispid_[name.lower()] = dispid
  430. # Patch up the universal stuff.
  431. for dispid, invkind, name in universal_data:
  432. self._name_to_dispid_[name.lower()] = dispid
  433. if invkind == DISPATCH_METHOD:
  434. self._dispid_to_func_[dispid] = name
  435. elif invkind in (DISPATCH_PROPERTYPUT, DISPATCH_PROPERTYPUTREF):
  436. self._dispid_to_put_[dispid] = name
  437. elif invkind == DISPATCH_PROPERTYGET:
  438. self._dispid_to_get_[dispid] = name
  439. else:
  440. raise ValueError("unexpected invkind: %d (%s)" % (invkind, name))
  441. # look for reserved methods
  442. if hasattr(ob, "_value_"):
  443. self._dispid_to_get_[DISPID_VALUE] = "_value_"
  444. self._dispid_to_put_[DISPID_PROPERTYPUT] = "_value_"
  445. if hasattr(ob, "_NewEnum"):
  446. self._name_to_dispid_["_newenum"] = DISPID_NEWENUM
  447. self._dispid_to_func_[DISPID_NEWENUM] = "_NewEnum"
  448. if hasattr(ob, "_Evaluate"):
  449. self._name_to_dispid_["_evaluate"] = DISPID_EVALUATE
  450. self._dispid_to_func_[DISPID_EVALUATE] = "_Evaluate"
  451. next_dispid = self._allocnextdispid(999)
  452. # note: funcs have precedence over attrs (install attrs first)
  453. if hasattr(ob, "_public_attrs_"):
  454. if hasattr(ob, "_readonly_attrs_"):
  455. readonly = ob._readonly_attrs_
  456. else:
  457. readonly = []
  458. for name in ob._public_attrs_:
  459. dispid = self._name_to_dispid_.get(name.lower())
  460. if dispid is None:
  461. dispid = next_dispid
  462. self._name_to_dispid_[name.lower()] = dispid
  463. next_dispid = self._allocnextdispid(next_dispid)
  464. self._dispid_to_get_[dispid] = name
  465. if name not in readonly:
  466. self._dispid_to_put_[dispid] = name
  467. for name in getattr(ob, "_public_methods_", []):
  468. dispid = self._name_to_dispid_.get(name.lower())
  469. if dispid is None:
  470. dispid = next_dispid
  471. self._name_to_dispid_[name.lower()] = dispid
  472. next_dispid = self._allocnextdispid(next_dispid)
  473. self._dispid_to_func_[dispid] = name
  474. self._typeinfos_ = None # load these on demand.
  475. def _build_typeinfos_(self):
  476. # Can only ever be one for now.
  477. tlb_guid = getattr(self._obj_, "_typelib_guid_", None)
  478. if tlb_guid is None:
  479. return []
  480. tlb_major, tlb_minor = getattr(self._obj_, "_typelib_version_", (1, 0))
  481. tlb = pythoncom.LoadRegTypeLib(tlb_guid, tlb_major, tlb_minor)
  482. typecomp = tlb.GetTypeComp()
  483. # Not 100% sure what semantics we should use for the default interface.
  484. # Look for the first name in _com_interfaces_ that exists in the typelib.
  485. for iname in self._obj_._com_interfaces_:
  486. try:
  487. type_info, type_comp = typecomp.BindType(iname)
  488. if type_info is not None:
  489. return [type_info]
  490. except pythoncom.com_error:
  491. pass
  492. return []
  493. def _GetTypeInfoCount_(self):
  494. if self._typeinfos_ is None:
  495. self._typeinfos_ = self._build_typeinfos_()
  496. return len(self._typeinfos_)
  497. def _GetTypeInfo_(self, index, lcid):
  498. if self._typeinfos_ is None:
  499. self._typeinfos_ = self._build_typeinfos_()
  500. if index < 0 or index >= len(self._typeinfos_):
  501. raise COMException(scode=winerror.DISP_E_BADINDEX)
  502. return 0, self._typeinfos_[index]
  503. def _allocnextdispid(self, last_dispid):
  504. while 1:
  505. last_dispid = last_dispid + 1
  506. if (
  507. last_dispid not in self._dispid_to_func_
  508. and last_dispid not in self._dispid_to_get_
  509. and last_dispid not in self._dispid_to_put_
  510. ):
  511. return last_dispid
  512. def _invokeex_(self, dispid, lcid, wFlags, args, kwArgs, serviceProvider):
  513. ### note: lcid is being ignored...
  514. if wFlags & DISPATCH_METHOD:
  515. try:
  516. funcname = self._dispid_to_func_[dispid]
  517. except KeyError:
  518. if not wFlags & DISPATCH_PROPERTYGET:
  519. raise COMException(
  520. scode=winerror.DISP_E_MEMBERNOTFOUND
  521. ) # not found
  522. else:
  523. try:
  524. func = getattr(self._obj_, funcname)
  525. except AttributeError:
  526. # May have a dispid, but that doesnt mean we have the function!
  527. raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND)
  528. # Should check callable here
  529. try:
  530. return func(*args)
  531. except TypeError as v:
  532. # Particularly nasty is "wrong number of args" type error
  533. # This helps you see what 'func' and 'args' actually is
  534. if str(v).find("arguments") >= 0:
  535. print(
  536. "** TypeError %s calling function %r(%r)" % (v, func, args)
  537. )
  538. raise
  539. if wFlags & DISPATCH_PROPERTYGET:
  540. try:
  541. name = self._dispid_to_get_[dispid]
  542. except KeyError:
  543. raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND) # not found
  544. retob = getattr(self._obj_, name)
  545. if type(retob) == types.MethodType: # a method as a property - call it.
  546. retob = retob(*args)
  547. return retob
  548. if wFlags & (DISPATCH_PROPERTYPUT | DISPATCH_PROPERTYPUTREF): ### correct?
  549. try:
  550. name = self._dispid_to_put_[dispid]
  551. except KeyError:
  552. raise COMException(scode=winerror.DISP_E_MEMBERNOTFOUND) # read-only
  553. # If we have a method of that name (ie, a property get function), and
  554. # we have an equiv. property set function, use that instead.
  555. if (
  556. type(getattr(self._obj_, name, None)) == types.MethodType
  557. and type(getattr(self._obj_, "Set" + name, None)) == types.MethodType
  558. ):
  559. fn = getattr(self._obj_, "Set" + name)
  560. fn(*args)
  561. else:
  562. # just set the attribute
  563. setattr(self._obj_, name, args[0])
  564. return
  565. raise COMException(scode=winerror.E_INVALIDARG, desc="invalid wFlags")
  566. class EventHandlerPolicy(DesignatedWrapPolicy):
  567. """The default policy used by event handlers in the win32com.client package.
  568. In addition to the base policy, this provides argument conversion semantics for
  569. params
  570. * dispatch params are converted to dispatch objects.
  571. * Unicode objects are converted to strings (1.5.2 and earlier)
  572. NOTE: Later, we may allow the object to override this process??
  573. """
  574. def _transform_args_(self, args, kwArgs, dispid, lcid, wFlags, serviceProvider):
  575. ret = []
  576. for arg in args:
  577. arg_type = type(arg)
  578. if arg_type == IDispatchType:
  579. import win32com.client
  580. arg = win32com.client.Dispatch(arg)
  581. elif arg_type == IUnknownType:
  582. try:
  583. import win32com.client
  584. arg = win32com.client.Dispatch(
  585. arg.QueryInterface(pythoncom.IID_IDispatch)
  586. )
  587. except pythoncom.error:
  588. pass # Keep it as IUnknown
  589. ret.append(arg)
  590. return tuple(ret), kwArgs
  591. def _invokeex_(self, dispid, lcid, wFlags, args, kwArgs, serviceProvider):
  592. # transform the args.
  593. args, kwArgs = self._transform_args_(
  594. args, kwArgs, dispid, lcid, wFlags, serviceProvider
  595. )
  596. return DesignatedWrapPolicy._invokeex_(
  597. self, dispid, lcid, wFlags, args, kwArgs, serviceProvider
  598. )
  599. class DynamicPolicy(BasicWrapPolicy):
  600. """A policy which dynamically (ie, at run-time) determines public interfaces.
  601. A dynamic policy is used to dynamically dispatch methods and properties to the
  602. wrapped object. The list of objects and properties does not need to be known in
  603. advance, and methods or properties added to the wrapped object after construction
  604. are also handled.
  605. The wrapped object must provide the following attributes:
  606. _dynamic_ -- A method that will be called whenever an invoke on the object
  607. is called. The method is called with the name of the underlying method/property
  608. (ie, the mapping of dispid to/from name has been resolved.) This name property
  609. may also be '_value_' to indicate the default, and '_NewEnum' to indicate a new
  610. enumerator is requested.
  611. """
  612. def _wrap_(self, object):
  613. BasicWrapPolicy._wrap_(self, object)
  614. if not hasattr(self._obj_, "_dynamic_"):
  615. raise error("Object does not support Dynamic COM Policy")
  616. self._next_dynamic_ = self._min_dynamic_ = 1000
  617. self._dyn_dispid_to_name_ = {
  618. DISPID_VALUE: "_value_",
  619. DISPID_NEWENUM: "_NewEnum",
  620. }
  621. def _getdispid_(self, name, fdex):
  622. # TODO - Look at fdex flags.
  623. lname = name.lower()
  624. try:
  625. return self._name_to_dispid_[lname]
  626. except KeyError:
  627. dispid = self._next_dynamic_ = self._next_dynamic_ + 1
  628. self._name_to_dispid_[lname] = dispid
  629. self._dyn_dispid_to_name_[dispid] = name # Keep case in this map...
  630. return dispid
  631. def _invoke_(self, dispid, lcid, wFlags, args):
  632. return S_OK, -1, self._invokeex_(dispid, lcid, wFlags, args, None, None)
  633. def _invokeex_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider):
  634. ### note: lcid is being ignored...
  635. ### note: kwargs is being ignored...
  636. ### note: serviceProvider is being ignored...
  637. ### there might be assigned DISPID values to properties, too...
  638. try:
  639. name = self._dyn_dispid_to_name_[dispid]
  640. except KeyError:
  641. raise COMException(
  642. scode=winerror.DISP_E_MEMBERNOTFOUND, desc="Member not found"
  643. )
  644. return self._obj_._dynamic_(name, lcid, wFlags, args)
  645. DefaultPolicy = DesignatedWrapPolicy
  646. def resolve_func(spec):
  647. """Resolve a function by name
  648. Given a function specified by 'module.function', return a callable object
  649. (ie, the function itself)
  650. """
  651. try:
  652. idx = spec.rindex(".")
  653. mname = spec[:idx]
  654. fname = spec[idx + 1 :]
  655. # Dont attempt to optimize by looking in sys.modules,
  656. # as another thread may also be performing the import - this
  657. # way we take advantage of the built-in import lock.
  658. module = _import_module(mname)
  659. return getattr(module, fname)
  660. except ValueError: # No "." in name - assume in this module
  661. return globals()[spec]
  662. def call_func(spec, *args):
  663. """Call a function specified by name.
  664. Call a function specified by 'module.function' and return the result.
  665. """
  666. return resolve_func(spec)(*args)
  667. def _import_module(mname):
  668. """Import a module just like the 'import' statement.
  669. Having this function is much nicer for importing arbitrary modules than
  670. using the 'exec' keyword. It is more efficient and obvious to the reader.
  671. """
  672. __import__(mname)
  673. # Eeek - result of _import_ is "win32com" - not "win32com.a.b.c"
  674. # Get the full module from sys.modules
  675. return sys.modules[mname]
  676. #######
  677. #
  678. # Temporary hacks until all old code moves.
  679. #
  680. # These have been moved to a new source file, but some code may
  681. # still reference them here. These will end up being removed.
  682. try:
  683. from .dispatcher import DispatcherTrace, DispatcherWin32trace
  684. except ImportError: # Quite likely a frozen executable that doesnt need dispatchers
  685. pass