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