PageRenderTime 52ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/site-packages/win32com/server/policy.py

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