home *** CD-ROM | disk | FTP | other *** search
/ One Click 11 / OneClick11.iso / Bancos de Dados / Conversao / Mysql2Excel / Setup.exe / Mysql2Excel.exe / win32com / client / dynamic.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2003-06-23  |  22.5 KB  |  573 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.2)
  3.  
  4. '''Support for dynamic COM client support.
  5.  
  6. Introduction
  7.  Dynamic COM client support is the ability to use a COM server without
  8.  prior knowledge of the server.  This can be used to talk to almost all
  9.  COM servers, including much of MS Office.
  10.  
  11.  In general, you should not use this module directly - see below.
  12.  
  13. Example
  14.  >>> import win32com.client
  15.  >>> xl = win32com.client.Dispatch("Excel.Application")
  16.  # The line above invokes the functionality of this class.
  17.  # xl is now an object we can use to talk to Excel.
  18.  >>> xl.Visible = 1 # The Excel window becomes visible.
  19.  
  20. '''
  21. import traceback
  22. import string
  23. import new
  24. import pythoncom
  25. import winerror
  26. import build
  27. from types import StringType, IntType, TupleType, ListType
  28. from pywintypes import UnicodeType, IIDType
  29. import win32com.client as win32com
  30. from win32com.client import NeedUnicodeConversions
  31. debugging = 0
  32. debugging_attr = 0
  33. LCID = 0
  34. ERRORS_BAD_CONTEXT = [
  35.     winerror.DISP_E_MEMBERNOTFOUND,
  36.     winerror.DISP_E_BADPARAMCOUNT,
  37.     winerror.DISP_E_PARAMNOTOPTIONAL,
  38.     winerror.DISP_E_TYPEMISMATCH,
  39.     winerror.E_INVALIDARG]
  40.  
  41. def debug_print(*args):
  42.     if debugging:
  43.         for arg in args:
  44.             print arg,
  45.         
  46.         print 
  47.     
  48.  
  49.  
  50. def debug_attr_print(*args):
  51.     if debugging_attr:
  52.         for arg in args:
  53.             print arg,
  54.         
  55.         print 
  56.     
  57.  
  58. dispatchType = pythoncom.TypeIIDs[pythoncom.IID_IDispatch]
  59. iunkType = pythoncom.TypeIIDs[pythoncom.IID_IUnknown]
  60. _StringOrUnicodeType = [
  61.     StringType,
  62.     UnicodeType]
  63. _GoodDispatchType = [
  64.     StringType,
  65.     IIDType,
  66.     UnicodeType]
  67. _defaultDispatchItem = build.DispatchItem
  68.  
  69. def _GetGoodDispatch(IDispatch, clsctx = pythoncom.CLSCTX_SERVER):
  70.     if type(IDispatch) in _GoodDispatchType:
  71.         
  72.         try:
  73.             IDispatch = pythoncom.connect(IDispatch)
  74.         except pythoncom.ole_error:
  75.             IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
  76.  
  77.     
  78.     return IDispatch
  79.  
  80.  
  81. def _GetGoodDispatchAndUserName(IDispatch, userName, clsctx):
  82.     if userName is None:
  83.         if type(IDispatch) in _StringOrUnicodeType:
  84.             userName = IDispatch
  85.         else:
  86.             userName = '<unknown>'
  87.     
  88.     return (_GetGoodDispatch(IDispatch, clsctx), userName)
  89.  
  90.  
  91. def Dispatch(IDispatch, userName = None, createClass = None, typeinfo = None, UnicodeToString = NeedUnicodeConversions, clsctx = pythoncom.CLSCTX_SERVER):
  92.     (IDispatch, userName) = _GetGoodDispatchAndUserName(IDispatch, userName, clsctx)
  93.     if createClass is None:
  94.         createClass = CDispatch
  95.     
  96.     lazydata = None
  97.     
  98.     try:
  99.         if typeinfo is None:
  100.             typeinfo = IDispatch.GetTypeInfo()
  101.         
  102.         
  103.         try:
  104.             typecomp = typeinfo.GetTypeComp()
  105.             lazydata = (typeinfo, typecomp)
  106.         except pythoncom.com_error:
  107.             pass
  108.  
  109.     except pythoncom.com_error:
  110.         typeinfo = None
  111.  
  112.     olerepr = MakeOleRepr(IDispatch, typeinfo, lazydata)
  113.     return createClass(IDispatch, olerepr, userName, UnicodeToString, lazydata)
  114.  
  115.  
  116. def MakeOleRepr(IDispatch, typeinfo, typecomp):
  117.     olerepr = None
  118.     if typeinfo is not None:
  119.         
  120.         try:
  121.             attr = typeinfo.GetTypeAttr()
  122.             if attr[5] == pythoncom.TKIND_INTERFACE and attr[11] & pythoncom.TYPEFLAG_FDUAL:
  123.                 href = typeinfo.GetRefTypeOfImplType(-1)
  124.                 typeinfo = typeinfo.GetRefTypeInfo(href)
  125.                 attr = typeinfo.GetTypeAttr()
  126.             
  127.             if typecomp is None:
  128.                 olerepr = build.DispatchItem(typeinfo, attr, None, 0)
  129.             else:
  130.                 olerepr = build.LazyDispatchItem(attr, None)
  131.         except pythoncom.ole_error:
  132.             pass
  133.  
  134.     
  135.     if olerepr is None:
  136.         olerepr = build.DispatchItem()
  137.     
  138.     return olerepr
  139.  
  140.  
  141. def DumbDispatch(IDispatch, userName = None, createClass = None, UnicodeToString = NeedUnicodeConversions, clsctx = pythoncom.CLSCTX_SERVER):
  142.     '''Dispatch with no type info'''
  143.     (IDispatch, userName) = _GetGoodDispatchAndUserName(IDispatch, userName, clsctx)
  144.     if createClass is None:
  145.         createClass = CDispatch
  146.     
  147.     return createClass(IDispatch, build.DispatchItem(), userName, UnicodeToString)
  148.  
  149.  
  150. class CDispatch:
  151.     
  152.     def __init__(self, IDispatch, olerepr, userName = None, UnicodeToString = NeedUnicodeConversions, lazydata = None):
  153.         if userName is None:
  154.             userName = '<unknown>'
  155.         
  156.         self.__dict__['_oleobj_'] = IDispatch
  157.         self.__dict__['_username_'] = userName
  158.         self.__dict__['_olerepr_'] = olerepr
  159.         self.__dict__['_mapCachedItems_'] = { }
  160.         self.__dict__['_builtMethods_'] = { }
  161.         self.__dict__['_enum_'] = None
  162.         self.__dict__['_unicode_to_string_'] = UnicodeToString
  163.         self.__dict__['_lazydata_'] = lazydata
  164.  
  165.     
  166.     def __call__(self, *args):
  167.         """Provide 'default dispatch' COM functionality - allow instance to be called"""
  168.         if self._olerepr_.defaultDispatchName:
  169.             (invkind, dispid) = self._find_dispatch_type_(self._olerepr_.defaultDispatchName)
  170.         else:
  171.             (invkind, dispid) = (pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET, pythoncom.DISPID_VALUE)
  172.         if invkind is not None:
  173.             allArgs = (dispid, LCID, invkind, 1) + args
  174.             return self._get_good_object_(apply(self._oleobj_.Invoke, allArgs), self._olerepr_.defaultDispatchName, None)
  175.         
  176.         raise TypeError, 'This dispatch object does not define a default method'
  177.  
  178.     
  179.     def __nonzero__(self):
  180.         return 1
  181.  
  182.     
  183.     def __repr__(self):
  184.         return '<COMObject %s>' % self._username_
  185.  
  186.     
  187.     def __str__(self):
  188.         
  189.         try:
  190.             return str(self.__call__())
  191.         except pythoncom.com_error:
  192.             details = None
  193.             if details[0] not in ERRORS_BAD_CONTEXT:
  194.                 raise 
  195.             
  196.             return self.__repr__()
  197.  
  198.  
  199.     
  200.     def __cmp__(self, other):
  201.         other = getattr(other, '_oleobj_', other)
  202.         return cmp(self._oleobj_, other)
  203.  
  204.     
  205.     def __int__(self):
  206.         return int(self.__call__())
  207.  
  208.     
  209.     def __len__(self):
  210.         (invkind, dispid) = self._find_dispatch_type_('Count')
  211.         if invkind:
  212.             return self._oleobj_.Invoke(dispid, LCID, invkind, 1)
  213.         
  214.         raise TypeError, 'This dispatch object does not define a Count method'
  215.  
  216.     
  217.     def _NewEnum(self):
  218.         (invkind, dispid) = self._find_dispatch_type_('_NewEnum')
  219.         if invkind is None:
  220.             return None
  221.         
  222.         enum = self._oleobj_.InvokeTypes(pythoncom.DISPID_NEWENUM, LCID, invkind, (13, 10), ())
  223.         import util
  224.         return util.WrapEnum(enum, None)
  225.  
  226.     
  227.     def __getitem__(self, index):
  228.         if isinstance(index, IntType):
  229.             if self.__dict__['_enum_'] is None:
  230.                 self.__dict__['_enum_'] = self._NewEnum()
  231.             
  232.             if self.__dict__['_enum_'] is not None:
  233.                 return self._get_good_object_(self._enum_.__getitem__(index))
  234.             
  235.         
  236.         (invkind, dispid) = self._find_dispatch_type_('Item')
  237.         if invkind is not None:
  238.             return self._get_good_object_(self._oleobj_.Invoke(dispid, LCID, invkind, 1, index))
  239.         
  240.         raise TypeError, 'This object does not support enumeration'
  241.  
  242.     
  243.     def __setitem__(self, index, *args):
  244.         if self._olerepr_.defaultDispatchName:
  245.             (invkind, dispid) = self._find_dispatch_type_(self._olerepr_.defaultDispatchName)
  246.         else:
  247.             (invkind, dispid) = (pythoncom.DISPATCH_PROPERTYPUT | pythoncom.DISPATCH_PROPERTYPUTREF, pythoncom.DISPID_VALUE)
  248.         if invkind is not None:
  249.             allArgs = (dispid, LCID, invkind, 0, index) + args
  250.             return self._get_good_object_(apply(self._oleobj_.Invoke, allArgs), self._olerepr_.defaultDispatchName, None)
  251.         
  252.         raise TypeError, 'This dispatch object does not define a default method'
  253.  
  254.     
  255.     def _find_dispatch_type_(self, methodName):
  256.         if self._olerepr_.mapFuncs.has_key(methodName):
  257.             item = self._olerepr_.mapFuncs[methodName]
  258.             return (item.desc[4], item.dispid)
  259.         
  260.         if self._olerepr_.propMapGet.has_key(methodName):
  261.             item = self._olerepr_.propMapGet[methodName]
  262.             return (item.desc[4], item.dispid)
  263.         
  264.         
  265.         try:
  266.             dispid = self._oleobj_.GetIDsOfNames(0, methodName)
  267.         except:
  268.             return (None, None)
  269.  
  270.         return (pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET, dispid)
  271.  
  272.     
  273.     def _ApplyTypes_(self, dispid, wFlags, retType, argTypes, user, resultCLSID, *args):
  274.         result = apply(self._oleobj_.InvokeTypes, (dispid, LCID, wFlags, retType, argTypes) + args)
  275.         return self._get_good_object_(result, user, resultCLSID)
  276.  
  277.     
  278.     def _wrap_dispatch_(self, ob, userName = None, returnCLSID = None, UnicodeToString = NeedUnicodeConversions):
  279.         return Dispatch(ob, userName, UnicodeToString = UnicodeToString)
  280.  
  281.     
  282.     def _get_good_single_object_(self, ob, userName = None, ReturnCLSID = None):
  283.         if iunkType == type(ob):
  284.             
  285.             try:
  286.                 ob = ob.QueryInterface(pythoncom.IID_IDispatch)
  287.             except pythoncom.com_error:
  288.                 pass
  289.  
  290.         
  291.         if dispatchType == type(ob):
  292.             return self._wrap_dispatch_(ob, userName, ReturnCLSID)
  293.         elif self._unicode_to_string_ and UnicodeType == type(ob):
  294.             return str(ob)
  295.         else:
  296.             return ob
  297.  
  298.     
  299.     def _get_good_object_(self, ob, userName = None, ReturnCLSID = None):
  300.         '''Given an object (usually the retval from a method), make it a good object to return.
  301. \t\t   Basically checks if it is a COM object, and wraps it up.
  302. \t\t   Also handles the fact that a retval may be a tuple of retvals'''
  303.         if ob is None:
  304.             return None
  305.         elif type(ob) == TupleType:
  306.             return tuple(map((lambda o, s = self, oun = userName, rc = ReturnCLSID: s._get_good_single_object_(o, oun, rc)), ob))
  307.         else:
  308.             return self._get_good_single_object_(ob)
  309.  
  310.     
  311.     def _make_method_(self, name):
  312.         '''Make a method object - Assumes in olerepr funcmap'''
  313.         methodName = build.MakePublicAttributeName(name)
  314.         methodCodeList = self._olerepr_.MakeFuncMethod(self._olerepr_.mapFuncs[name], methodName, 0)
  315.         methodCode = string.join(methodCodeList, '\n')
  316.         
  317.         try:
  318.             codeObject = compile(methodCode, '<COMObject %s>' % self._username_, 'exec')
  319.             tempNameSpace = { }
  320.             exec codeObject in globals(), tempNameSpace
  321.             name = methodName
  322.             fn = self._builtMethods_[name] = tempNameSpace[name]
  323.             newMeth = new.instancemethod(fn, self, self.__class__)
  324.             return newMeth
  325.         except:
  326.             debug_print('Error building OLE definition for code ', methodCode)
  327.             traceback.print_exc()
  328.  
  329.         return None
  330.  
  331.     
  332.     def _Release_(self):
  333.         """Cleanup object - like a close - to force cleanup when you dont 
  334. \t\t   want to rely on Python's reference counting."""
  335.         for childCont in self._mapCachedItems_.values():
  336.             childCont._Release_()
  337.         
  338.         self._mapCachedItems_ = { }
  339.         if self._oleobj_:
  340.             self._oleobj_.Release()
  341.             self.__dict__['_oleobj_'] = None
  342.         
  343.         if self._olerepr_:
  344.             self.__dict__['_olerepr_'] = None
  345.         
  346.         self._enum_ = None
  347.  
  348.     
  349.     def _proc_(self, name, *args):
  350.         '''Call the named method as a procedure, rather than function.
  351. \t\t   Mainly used by Word.Basic, which whinges about such things.'''
  352.         
  353.         try:
  354.             item = self._olerepr_.mapFuncs[name]
  355.             dispId = item.dispid
  356.             return self._get_good_object_(apply(self._oleobj_.Invoke, (dispId, LCID, item.desc[4], 0) + args))
  357.         except KeyError:
  358.             raise AttributeError, name
  359.  
  360.  
  361.     
  362.     def _print_details_(self):
  363.         '''Debug routine - dumps what it knows about an object.'''
  364.         print 'AxDispatch container', self._username_
  365.         
  366.         try:
  367.             print 'Methods:'
  368.             for method in self._olerepr_.mapFuncs.keys():
  369.                 print '\t', method
  370.             
  371.             print 'Props:'
  372.             for prop, entry in self._olerepr_.propMap.items():
  373.                 print '\t%s = 0x%x - %s' % (prop, entry.dispid, `entry`)
  374.             
  375.             print 'Get Props:'
  376.             for prop, entry in self._olerepr_.propMapGet.items():
  377.                 print '\t%s = 0x%x - %s' % (prop, entry.dispid, `entry`)
  378.             
  379.             print 'Put Props:'
  380.             for prop, entry in self._olerepr_.propMapPut.items():
  381.                 print '\t%s = 0x%x - %s' % (prop, entry.dispid, `entry`)
  382.         except:
  383.             traceback.print_exc()
  384.  
  385.  
  386.     
  387.     def __LazyMap__(self, attr):
  388.         
  389.         try:
  390.             if self._LazyAddAttr_(attr):
  391.                 debug_attr_print('%s.__LazyMap__(%s) added something' % (self._username_, attr))
  392.                 return 1
  393.         except AttributeError:
  394.             return 0
  395.  
  396.  
  397.     
  398.     def _LazyAddAttr_(self, attr):
  399.         if self._lazydata_ is None:
  400.             return 0
  401.         
  402.         res = 0
  403.         i = 0
  404.         (typeinfo, typecomp) = self._lazydata_
  405.         olerepr = self._olerepr_
  406.         
  407.         try:
  408.             (x, t) = typecomp.Bind(attr, i)
  409.             if x == 1:
  410.                 r = olerepr._AddFunc_(typeinfo, t, 0)
  411.             elif x == 2:
  412.                 r = olerepr._AddVar_(typeinfo, t, 0)
  413.             else:
  414.                 r = None
  415.             if not (r is None):
  416.                 (key, map) = (r[0], r[1])
  417.                 item = map[key]
  418.                 if map == olerepr.propMapPut:
  419.                     olerepr._propMapPutCheck_(key, item)
  420.                 elif map == olerepr.propMapGet:
  421.                     olerepr._propMapGetCheck_(key, item)
  422.                 
  423.                 res = 1
  424.         except:
  425.             pass
  426.  
  427.         return res
  428.  
  429.     
  430.     def _FlagAsMethod(self, *methodNames):
  431.         '''Flag these attribute names as being methods.
  432. \t\tSome objects do not correctly differentiate methods and
  433. \t\tproperties, leading to problems when calling these methods.
  434.  
  435. \t\tSpecifically, trying to say: ob.SomeFunc()
  436. \t\tmay yield an exception "None object is not callable"
  437. \t\tIn this case, an attempt to fetch the *property*has worked
  438. \t\tand returned None, rather than indicating it is really a method.
  439. \t\tCalling: ob._FlagAsMethod("SomeFunc")
  440. \t\tshould then allow this to work.
  441. \t\t'''
  442.         for name in methodNames:
  443.             details = build.MapEntry(self.__AttrToID__(name), (name,))
  444.             self._olerepr_.mapFuncs[name] = details
  445.         
  446.  
  447.     
  448.     def __AttrToID__(self, attr):
  449.         debug_attr_print('Calling GetIDsOfNames for property %s in Dispatch container %s' % (attr, self._username_))
  450.         return self._oleobj_.GetIDsOfNames(0, attr)
  451.  
  452.     
  453.     def __getattr__(self, attr):
  454.         if attr[0] == '_' and attr[-1] == '_':
  455.             raise AttributeError, attr
  456.         
  457.         
  458.         try:
  459.             return new.instancemethod(self._builtMethods_[attr], self, self.__class__)
  460.         except KeyError:
  461.             pass
  462.  
  463.         if self._olerepr_.mapFuncs.has_key(attr):
  464.             return self._make_method_(attr)
  465.         
  466.         retEntry = None
  467.         if self._olerepr_ and self._oleobj_:
  468.             if self._olerepr_.propMap.has_key(attr):
  469.                 retEntry = self._olerepr_.propMap[attr]
  470.             
  471.             if retEntry is None and self._olerepr_.propMapGet.has_key(attr):
  472.                 retEntry = self._olerepr_.propMapGet[attr]
  473.             
  474.             if retEntry is None:
  475.                 
  476.                 try:
  477.                     if self.__LazyMap__(attr):
  478.                         if self._olerepr_.mapFuncs.has_key(attr):
  479.                             return self._make_method_(attr)
  480.                         
  481.                         if self._olerepr_.propMap.has_key(attr):
  482.                             retEntry = self._olerepr_.propMap[attr]
  483.                         
  484.                         if retEntry is None and self._olerepr_.propMapGet.has_key(attr):
  485.                             retEntry = self._olerepr_.propMapGet[attr]
  486.                         
  487.                     
  488.                     if retEntry is None:
  489.                         retEntry = build.MapEntry(self.__AttrToID__(attr), (attr,))
  490.                 except pythoncom.ole_error:
  491.                     pass
  492.  
  493.             
  494.         
  495.         if not (retEntry is None):
  496.             
  497.             try:
  498.                 ret = self._mapCachedItems_[retEntry.dispid]
  499.                 debug_attr_print('Cached items has attribute!', ret)
  500.                 return ret
  501.             except (KeyError, AttributeError):
  502.                 debug_attr_print('Attribute %s not in cache' % attr)
  503.  
  504.         
  505.         if not (retEntry is None):
  506.             debug_attr_print('Getting property Id 0x%x from OLE object' % retEntry.dispid)
  507.             
  508.             try:
  509.                 ret = self._oleobj_.Invoke(retEntry.dispid, 0, pythoncom.DISPATCH_PROPERTYGET, 1)
  510.             except pythoncom.com_error:
  511.                 details = None
  512.                 if details[0] in ERRORS_BAD_CONTEXT:
  513.                     self._olerepr_.mapFuncs[attr] = retEntry
  514.                     return self._make_method_(attr)
  515.                 
  516.                 raise pythoncom.com_error, details
  517.  
  518.             self._olerepr_.propMap[attr] = retEntry
  519.             debug_attr_print('OLE returned ', ret)
  520.             return self._get_good_object_(ret)
  521.         
  522.         raise AttributeError, '%s.%s' % (self._username_, attr)
  523.  
  524.     
  525.     def __setattr__(self, attr, value):
  526.         if self.__dict__.has_key(attr):
  527.             self.__dict__[attr] = value
  528.             return None
  529.         
  530.         debug_attr_print('SetAttr called for %s.%s=%s on DispatchContainer' % (self._username_, attr, `value`))
  531.         if self._olerepr_:
  532.             if self._olerepr_.propMap.has_key(attr):
  533.                 self._oleobj_.Invoke(self._olerepr_.propMap[attr].dispid, 0, pythoncom.DISPATCH_PROPERTYPUT, 0, value)
  534.                 return None
  535.             
  536.             if self._olerepr_.propMapPut.has_key(attr):
  537.                 self._oleobj_.Invoke(self._olerepr_.propMapPut[attr].dispid, 0, pythoncom.DISPATCH_PROPERTYPUT, 0, value)
  538.                 return None
  539.             
  540.         
  541.         if self._oleobj_:
  542.             if self.__LazyMap__(attr):
  543.                 if self._olerepr_.propMap.has_key(attr):
  544.                     self._oleobj_.Invoke(self._olerepr_.propMap[attr].dispid, 0, pythoncom.DISPATCH_PROPERTYPUT, 0, value)
  545.                     return None
  546.                 
  547.                 if self._olerepr_.propMapPut.has_key(attr):
  548.                     self._oleobj_.Invoke(self._olerepr_.propMapPut[attr].dispid, 0, pythoncom.DISPATCH_PROPERTYPUT, 0, value)
  549.                     return None
  550.                 
  551.             
  552.             
  553.             try:
  554.                 entry = build.MapEntry(self.__AttrToID__(attr), (attr,))
  555.             except pythoncom.com_error:
  556.                 entry = None
  557.  
  558.             if entry is not None:
  559.                 
  560.                 try:
  561.                     self._oleobj_.Invoke(entry.dispid, 0, pythoncom.DISPATCH_PROPERTYPUT, 0, value)
  562.                     self._olerepr_.propMap[attr] = entry
  563.                     debug_attr_print('__setattr__ property %s (id=0x%x) in Dispatch container %s' % (attr, entry.dispid, self._username_))
  564.                     return None
  565.                 except pythoncom.com_error:
  566.                     pass
  567.  
  568.             
  569.         
  570.         raise AttributeError, "Property '%s.%s' can not be set." % (self._username_, attr)
  571.  
  572.  
  573.