policy.py 30 KB

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