home *** CD-ROM | disk | FTP | other *** search
/ PC World 2002 May / PCWorld_2002-05_cd.bin / Software / TemaCD / activepython / ActivePython-2.1.1.msi / Python21_win32com_server_policy.py < prev    next >
Encoding:
Python Source  |  2001-07-26  |  26.5 KB  |  657 lines

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