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

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.2)
  3.  
  4. '''genpy.py - The worker for makepy.  See makepy.py for more details
  5.  
  6. This code was moved simply to speed Python in normal circumstances.  As the makepy.py
  7. is normally run from the command line, it reparses the code each time.  Now makepy
  8. is nothing more than the command line handler and public interface.
  9.  
  10. The makepy command line etc handling is also getting large enough in its own right!
  11. '''
  12. import os
  13. import sys
  14. import string
  15. import time
  16. import win32com
  17. import pythoncom
  18. import build
  19. error = 'makepy.error'
  20. makepy_version = '0.4.1'
  21. GEN_FULL = 'full'
  22. GEN_DEMAND_BASE = 'demand(base)'
  23. GEN_DEMAND_CHILD = 'demand(child)'
  24. mapVTToTypeString = {
  25.     pythoncom.VT_I2: 'types.IntType',
  26.     pythoncom.VT_I4: 'types.IntType',
  27.     pythoncom.VT_R4: 'types.FloatType',
  28.     pythoncom.VT_R8: 'types.FloatType',
  29.     pythoncom.VT_BSTR: 'types.StringType',
  30.     pythoncom.VT_BOOL: 'types.IntType',
  31.     pythoncom.VT_VARIANT: 'types.TypeType',
  32.     pythoncom.VT_I1: 'types.IntType',
  33.     pythoncom.VT_UI1: 'types.IntType',
  34.     pythoncom.VT_UI2: 'types.IntType',
  35.     pythoncom.VT_UI4: 'types.IntType',
  36.     pythoncom.VT_I8: 'types.LongType',
  37.     pythoncom.VT_UI8: 'types.LongType',
  38.     pythoncom.VT_INT: 'types.IntType',
  39.     pythoncom.VT_DATE: 'pythoncom.PyTimeType',
  40.     pythoncom.VT_UINT: 'types.IntType' }
  41.  
  42. def MakeDefaultArgsForPropertyPut(argsDesc):
  43.     ret = []
  44.     for desc in argsDesc[1:]:
  45.         default = build.MakeDefaultArgRepr(desc)
  46.         if default is None:
  47.             break
  48.         
  49.         ret.append(default)
  50.     
  51.     return tuple(ret)
  52.  
  53.  
  54. def MakeMapLineEntry(dispid, wFlags, retType, argTypes, user, resultCLSID):
  55.     argTypes = tuple(map((lambda what: what[:2]), argTypes))
  56.     return '(%s, %d, %s, %s, "%s", %s)' % (dispid, wFlags, retType[:2], argTypes, user, resultCLSID)
  57.  
  58.  
  59. def MakeEventMethodName(eventName):
  60.     if eventName[:2] == 'On':
  61.         return eventName
  62.     else:
  63.         return 'On' + eventName
  64.  
  65.  
  66. def WriteSinkEventMap(obj):
  67.     print '\t_dispid_to_func_ = {'
  68.     for name, entry in obj.propMapGet.items() + obj.propMapPut.items() + obj.mapFuncs.items():
  69.         fdesc = entry.desc
  70.         print '\t\t%9d : "%s",' % (entry.desc[0], MakeEventMethodName(entry.names[0]))
  71.     
  72.     print '\t\t}'
  73.  
  74.  
  75. class WritableItem:
  76.     
  77.     def __cmp__(self, other):
  78.         '''Compare for sorting'''
  79.         ret = cmp(self.order, other.order)
  80.         if ret == 0 and self.doc:
  81.             ret = cmp(self.doc[0], other.doc[0])
  82.         
  83.         return ret
  84.  
  85.     
  86.     def __repr__(self):
  87.         return 'OleItem: doc=%s, order=%d' % (`self.doc`, self.order)
  88.  
  89.  
  90.  
  91. class RecordItem(build.OleItem, WritableItem):
  92.     order = 9
  93.     typename = 'RECORD'
  94.     
  95.     def __init__(self, typeInfo, typeAttr, doc = None, bForUser = 1):
  96.         build.OleItem.__init__(self, doc)
  97.         self.clsid = typeAttr[0]
  98.  
  99.     
  100.     def WriteClass(self, generator):
  101.         pass
  102.  
  103.  
  104.  
  105. def WriteAliasesForItem(item, aliasItems):
  106.     for alias in aliasItems.values():
  107.         if item.doc and alias.aliasDoc and alias.aliasDoc[0] == item.doc[0]:
  108.             alias.WriteAliasItem(aliasItems)
  109.         
  110.     
  111.  
  112.  
  113. class AliasItem(build.OleItem, WritableItem):
  114.     order = 2
  115.     typename = 'ALIAS'
  116.     
  117.     def __init__(self, typeinfo, attr, doc = None, bForUser = 1):
  118.         build.OleItem.__init__(self, doc)
  119.         ai = attr[14]
  120.         self.attr = attr
  121.         if type(ai) == type(()) and type(ai[1]) == type(0):
  122.             href = ai[1]
  123.             alinfo = typeinfo.GetRefTypeInfo(href)
  124.             self.aliasDoc = alinfo.GetDocumentation(-1)
  125.             self.aliasAttr = alinfo.GetTypeAttr()
  126.         else:
  127.             self.aliasDoc = None
  128.             self.aliasAttr = None
  129.  
  130.     
  131.     def WriteAliasItem(self, aliasDict):
  132.         if self.bWritten:
  133.             return None
  134.         
  135.         if self.aliasDoc:
  136.             depName = self.aliasDoc[0]
  137.             if aliasDict.has_key(depName):
  138.                 aliasDict[depName].WriteAliasItem(aliasDict)
  139.             
  140.             print self.doc[0] + ' = ' + depName
  141.         else:
  142.             ai = self.attr[14]
  143.             if type(ai) == type(0):
  144.                 
  145.                 try:
  146.                     typeStr = mapVTToTypeString[ai]
  147.                     print '# %s=%s' % (self.doc[0], typeStr)
  148.                 except KeyError:
  149.                     print self.doc[0] + " = None # Can't convert alias info " + str(ai)
  150.  
  151.             
  152.         print 
  153.         self.bWritten = 1
  154.  
  155.  
  156.  
  157. class EnumerationItem(build.OleItem, WritableItem):
  158.     order = 1
  159.     typename = 'ENUMERATION'
  160.     
  161.     def __init__(self, typeinfo, attr, doc = None, bForUser = 1):
  162.         build.OleItem.__init__(self, doc)
  163.         self.clsid = attr[0]
  164.         self.mapVars = { }
  165.         typeFlags = attr[11]
  166.         if not typeFlags & pythoncom.TYPEFLAG_FHIDDEN:
  167.             pass
  168.         self.hidden = typeFlags & pythoncom.TYPEFLAG_FRESTRICTED
  169.         for j in range(attr[7]):
  170.             vdesc = typeinfo.GetVarDesc(j)
  171.             name = typeinfo.GetNames(vdesc[0])[0]
  172.             self.mapVars[name] = build.MapEntry(vdesc)
  173.         
  174.  
  175.     
  176.     def WriteEnumerationItems(self):
  177.         enumName = self.doc[0]
  178.         names = self.mapVars.keys()
  179.         names.sort()
  180.         for name in names:
  181.             entry = self.mapVars[name]
  182.             vdesc = entry.desc
  183.             if vdesc[4] == pythoncom.VAR_CONST:
  184.                 if type(vdesc[1]) == type(0):
  185.                     if vdesc[1] == -2147483648:
  186.                         use = '0x80000000'
  187.                     else:
  188.                         use = hex(vdesc[1])
  189.                 else:
  190.                     use = repr(str(vdesc[1]))
  191.                 print '\t%-30s=%-10s # from enum %s' % (build.MakePublicAttributeName(name), use, enumName)
  192.             
  193.         
  194.  
  195.  
  196.  
  197. class VTableItem(build.VTableItem, WritableItem):
  198.     order = 4
  199.     
  200.     def WriteClass(self, generator):
  201.         self.WriteVTableMap(generator)
  202.         self.bWritten = 1
  203.  
  204.     
  205.     def WriteVTableMap(self, generator):
  206.         print '%s_vtables_dispatch_ = %d' % (self.python_name, self.bIsDispatch)
  207.         print '%s_vtables_ = [' % (self.python_name,)
  208.         for v in self.vtableFuncs:
  209.             chunks = []
  210.             (name, dispid, arg_desc, ret_desc, named_params) = v
  211.             chunks.append('\t(%s, %d, (' % (repr(name), dispid))
  212.             for arg in arg_desc:
  213.                 chunks.append('(%d,%d,' % (arg[0], arg[1]))
  214.                 defval = build.MakeDefaultArgRepr(arg)
  215.                 if defval is None:
  216.                     chunks.append('None), ')
  217.                 else:
  218.                     chunks.append(defval + '), ')
  219.             
  220.             chunks.append('), %s, %s),' % (repr(ret_desc), repr(named_params)))
  221.             print ''.join(chunks)
  222.         
  223.         print ']'
  224.         print 
  225.  
  226.  
  227.  
  228. class DispatchItem(build.DispatchItem, WritableItem):
  229.     order = 3
  230.     
  231.     def __init__(self, typeinfo, attr, doc = None):
  232.         build.DispatchItem.__init__(self, typeinfo, attr, doc)
  233.         self.type_attr = attr
  234.  
  235.     
  236.     def WriteClass(self, generator):
  237.         if not (self.bIsDispatch) and not (self.type_attr.typekind == pythoncom.TKIND_DISPATCH):
  238.             return None
  239.         
  240.         if self.bIsSink:
  241.             self.WriteEventSinkClassHeader(generator)
  242.             self.WriteCallbackClassBody(generator)
  243.         else:
  244.             self.WriteClassHeader(generator)
  245.             self.WriteClassBody(generator)
  246.         print 
  247.         self.bWritten = 1
  248.  
  249.     
  250.     def WriteClassHeader(self, generator):
  251.         generator.checkWriteDispatchBaseClass()
  252.         doc = self.doc
  253.         print 'class ' + self.python_name + '(DispatchBaseClass):'
  254.         if doc[1]:
  255.             print '\t' + build._safeQuotedString(doc[1])
  256.         
  257.         
  258.         try:
  259.             progId = pythoncom.ProgIDFromCLSID(self.clsid)
  260.             print "\t# This class is creatable by the name '%s'" % progId
  261.         except pythoncom.com_error:
  262.             pass
  263.  
  264.         clsidStr = str(self.clsid)
  265.         print "\tCLSID = pythoncom.MakeIID('" + clsidStr + "')"
  266.         print 
  267.         self.bWritten = 1
  268.  
  269.     
  270.     def WriteEventSinkClassHeader(self, generator):
  271.         generator.checkWriteEventBaseClass()
  272.         doc = self.doc
  273.         print 'class ' + self.python_name + ':'
  274.         if doc[1]:
  275.             print '\t' + build._safeQuotedString(doc[1])
  276.         
  277.         
  278.         try:
  279.             progId = pythoncom.ProgIDFromCLSID(self.clsid)
  280.             print "\t# This class is creatable by the name '%s'" % progId
  281.         except pythoncom.com_error:
  282.             pass
  283.  
  284.         clsidStr = str(self.clsid)
  285.         print "\tCLSID = CLSID_Sink = pythoncom.MakeIID('" + clsidStr + "')"
  286.         print '\t_public_methods_ = [] # For COM Server support'
  287.         WriteSinkEventMap(self)
  288.         print 
  289.         print '\tdef __init__(self, oobj = None):'
  290.         print '\t\tif oobj is None:'
  291.         print '\t\t\tself._olecp = None'
  292.         print '\t\telse:'
  293.         print '\t\t\timport win32com.server.util'
  294.         print '\t\t\tfrom win32com.server.policy import EventHandlerPolicy'
  295.         print '\t\t\tcpc=oobj._oleobj_.QueryInterface(pythoncom.IID_IConnectionPointContainer)'
  296.         print '\t\t\tcp=cpc.FindConnectionPoint(self.CLSID_Sink)'
  297.         print '\t\t\tcookie=cp.Advise(win32com.server.util.wrap(self, usePolicy=EventHandlerPolicy))'
  298.         print '\t\t\tself._olecp,self._olecp_cookie = cp,cookie'
  299.         print '\tdef __del__(self):'
  300.         print '\t\ttry:'
  301.         print '\t\t\tself.close()'
  302.         print '\t\texcept pythoncom.com_error:'
  303.         print '\t\t\tpass'
  304.         print '\tdef close(self):'
  305.         print '\t\tif self._olecp is not None:'
  306.         print '\t\t\tcp,cookie,self._olecp,self._olecp_cookie = self._olecp,self._olecp_cookie,None,None'
  307.         print '\t\t\tcp.Unadvise(cookie)'
  308.         print '\tdef _query_interface_(self, iid):'
  309.         print '\t\timport win32com.server.util'
  310.         print '\t\tif iid==self.CLSID_Sink: return win32com.server.util.wrap(self)'
  311.         print 
  312.         self.bWritten = 1
  313.  
  314.     
  315.     def WriteCallbackClassBody(self, generator):
  316.         print '\t# Handlers for the control'
  317.         print '\t# If you create handlers, they should have the following prototypes:'
  318.         for name, entry in self.propMapGet.items() + self.propMapPut.items() + self.mapFuncs.items():
  319.             fdesc = entry.desc
  320.             methName = MakeEventMethodName(entry.names[0])
  321.             print '#\tdef ' + methName + '(self' + build.BuildCallList(fdesc, entry.names, 'defaultNamedOptArg', 'defaultNamedNotOptArg', 'defaultUnnamedArg') + '):'
  322.             if entry.doc and entry.doc[1]:
  323.                 print '#\t\t' + build._safeQuotedString(entry.doc[1])
  324.             
  325.         
  326.         print 
  327.         self.bWritten = 1
  328.  
  329.     
  330.     def WriteClassBody(self, generator):
  331.         names = self.mapFuncs.keys()
  332.         names.sort()
  333.         specialItems = {
  334.             'count': None,
  335.             'item': None,
  336.             'value': None,
  337.             '_newenum': None }
  338.         itemCount = None
  339.         for name in names:
  340.             entry = self.mapFuncs[name]
  341.             if entry.desc[3] != pythoncom.FUNC_DISPATCH:
  342.                 continue
  343.             
  344.             if entry.desc[0] == pythoncom.DISPID_VALUE:
  345.                 lkey = 'value'
  346.             elif entry.desc[0] == pythoncom.DISPID_NEWENUM:
  347.                 specialItems['_newenum'] = (entry, entry.desc[4], None)
  348.                 continue
  349.             else:
  350.                 lkey = string.lower(name)
  351.             if specialItems.has_key(lkey) and specialItems[lkey] is None:
  352.                 specialItems[lkey] = (entry, entry.desc[4], None)
  353.             
  354.             if generator.bBuildHidden or not (entry.hidden):
  355.                 if entry.GetResultName():
  356.                     print '\t# Result is of type ' + entry.GetResultName()
  357.                 
  358.                 if entry.wasProperty:
  359.                     print '\t# The method %s is actually a property, but must be used as a method to correctly pass the arguments' % name
  360.                 
  361.                 ret = self.MakeFuncMethod(entry, build.MakePublicAttributeName(name))
  362.                 for line in ret:
  363.                     print line
  364.                 
  365.             
  366.         
  367.         print '\t_prop_map_get_ = {'
  368.         names = self.propMap.keys()
  369.         names.sort()
  370.         for key in names:
  371.             entry = self.propMap[key]
  372.             if generator.bBuildHidden or not (entry.hidden):
  373.                 resultName = entry.GetResultName()
  374.                 if resultName:
  375.                     print "\t\t# Property '%s' is an object of type '%s'" % (key, resultName)
  376.                 
  377.                 lkey = string.lower(key)
  378.                 details = entry.desc
  379.                 resultDesc = details[2]
  380.                 argDesc = ()
  381.                 mapEntry = MakeMapLineEntry(details[0], pythoncom.DISPATCH_PROPERTYGET, resultDesc, argDesc, key, entry.GetResultCLSIDStr())
  382.                 if entry.desc[0] == pythoncom.DISPID_VALUE:
  383.                     lkey = 'value'
  384.                 elif entry.desc[0] == pythoncom.DISPID_NEWENUM:
  385.                     specialItems['_newenum'] = (entry, pythoncom.DISPATCH_METHOD, mapEntry)
  386.                     continue
  387.                 else:
  388.                     lkey = string.lower(key)
  389.                 if specialItems.has_key(lkey) and specialItems[lkey] is None:
  390.                     specialItems[lkey] = (entry, pythoncom.DISPATCH_PROPERTYGET, mapEntry)
  391.                 
  392.                 print '\t\t"%s": %s,' % (key, mapEntry)
  393.             
  394.         
  395.         names = self.propMapGet.keys()
  396.         names.sort()
  397.         for key in names:
  398.             entry = self.propMapGet[key]
  399.             if generator.bBuildHidden or not (entry.hidden):
  400.                 if entry.GetResultName():
  401.                     print "\t\t# Method '%s' returns object of type '%s'" % (key, entry.GetResultName())
  402.                 
  403.                 details = entry.desc
  404.                 lkey = string.lower(key)
  405.                 argDesc = details[2]
  406.                 resultDesc = details[8]
  407.                 mapEntry = MakeMapLineEntry(details[0], pythoncom.DISPATCH_PROPERTYGET, resultDesc, argDesc, key, entry.GetResultCLSIDStr())
  408.                 if entry.desc[0] == pythoncom.DISPID_VALUE:
  409.                     lkey = 'value'
  410.                 elif entry.desc[0] == pythoncom.DISPID_NEWENUM:
  411.                     specialItems['_newenum'] = (entry, pythoncom.DISPATCH_METHOD, mapEntry)
  412.                     continue
  413.                 else:
  414.                     lkey = string.lower(key)
  415.                 if specialItems.has_key(lkey) and specialItems[lkey] is None:
  416.                     specialItems[lkey] = (entry, pythoncom.DISPATCH_PROPERTYGET, mapEntry)
  417.                 
  418.                 print '\t\t"%s": %s,' % (key, mapEntry)
  419.             
  420.         
  421.         print '\t}'
  422.         print '\t_prop_map_put_ = {'
  423.         names = self.propMap.keys()
  424.         names.sort()
  425.         for key in names:
  426.             entry = self.propMap[key]
  427.             if generator.bBuildHidden or not (entry.hidden):
  428.                 lkey = string.lower(key)
  429.                 details = entry.desc
  430.                 defArgDesc = build.MakeDefaultArgRepr(details[2])
  431.                 if defArgDesc is None:
  432.                     defArgDesc = ''
  433.                 else:
  434.                     defArgDesc = defArgDesc + ','
  435.                 print '\t\t"%s" : ((%s, LCID, %d, 0),(%s)),' % (key, details[0], pythoncom.DISPATCH_PROPERTYPUT, defArgDesc)
  436.             
  437.         
  438.         names = self.propMapPut.keys()
  439.         names.sort()
  440.         for key in names:
  441.             entry = self.propMapPut[key]
  442.             if generator.bBuildHidden or not (entry.hidden):
  443.                 details = entry.desc
  444.                 defArgDesc = MakeDefaultArgsForPropertyPut(details[2])
  445.                 print '\t\t"%s": ((%s, LCID, %d, 0),%s),' % (key, details[0], details[4], defArgDesc)
  446.             
  447.         
  448.         print '\t}'
  449.         if specialItems['value']:
  450.             (entry, invoketype, propArgs) = specialItems['value']
  451.             if propArgs is None:
  452.                 typename = 'method'
  453.                 ret = self.MakeFuncMethod(entry, '__call__')
  454.             else:
  455.                 typename = 'property'
  456.                 ret = [
  457.                     '\tdef __call__(self):\n\t\treturn apply(self._ApplyTypes_, %s )' % propArgs]
  458.             print "\t# Default %s for this class is '%s'" % (typename, entry.names[0])
  459.             for line in ret:
  460.                 print line
  461.             
  462.             print '\t# str(ob) and int(ob) will use __call__'
  463.             print '\tdef __unicode__(self, *args):'
  464.             print '\t\ttry:'
  465.             print '\t\t\treturn unicode(apply( self.__call__, args))'
  466.             print '\t\texcept pythoncom.com_error:'
  467.             print '\t\t\treturn repr(self)'
  468.             print '\tdef __str__(self, *args):'
  469.             print '\t\treturn str(apply(self.__unicode__, args))'
  470.             print '\tdef __int__(self, *args):'
  471.             print '\t\treturn int(apply( self.__call__, args))'
  472.         
  473.         if specialItems['_newenum']:
  474.             (enumEntry, invoketype, propArgs) = specialItems['_newenum']
  475.             resultCLSID = enumEntry.GetResultCLSIDStr()
  476.             if resultCLSID == 'None' and self.mapFuncs.has_key('Item'):
  477.                 resultCLSID = self.mapFuncs['Item'].GetResultCLSIDStr()
  478.             
  479.             print '\tdef _NewEnum(self):'
  480.             print '\t\t"Create an enumerator from this object"'
  481.             print '\t\treturn win32com.client.util.WrapEnum(self._oleobj_.InvokeTypes(%d,LCID,%d,(13, 10),()),%s)' % (pythoncom.DISPID_NEWENUM, enumEntry.desc[4], resultCLSID)
  482.             print '\tdef __getitem__(self, index):'
  483.             print '\t\t"Allow this class to be accessed as a collection"'
  484.             print "\t\tif not self.__dict__.has_key('_enum_'):"
  485.             print '\t\t\timport win32com.client.util'
  486.             print "\t\t\tself.__dict__['_enum_'] = self._NewEnum()"
  487.             print '\t\treturn self._enum_.__getitem__(index)'
  488.         elif specialItems['item']:
  489.             (entry, invoketype, propArgs) = specialItems['item']
  490.             print '\t#This class has Item property/method which may take args - allow indexed access'
  491.             print '\tdef __getitem__(self, item):'
  492.             print '\t\treturn self._get_good_object_(apply(self._oleobj_.Invoke, (0x%x, LCID, %d, 1, item)), "Item")' % (entry.desc[0], invoketype)
  493.         
  494.         if specialItems['count']:
  495.             (entry, invoketype, propArgs) = specialItems['count']
  496.             if propArgs is None:
  497.                 typename = 'method'
  498.                 ret = self.MakeFuncMethod(entry, '__len__')
  499.             else:
  500.                 typename = 'property'
  501.                 ret = [
  502.                     '\tdef __len__(self):\n\t\treturn apply(self._ApplyTypes_, %s )' % propArgs]
  503.             print '\t#This class has Count() %s - allow len(ob) to provide this' % typename
  504.             for line in ret:
  505.                 print line
  506.             
  507.             print "\t#This class has a __len__ - this is needed so 'if object:' always returns TRUE."
  508.             print '\tdef __nonzero__(self):'
  509.             print '\t\treturn 1'
  510.         
  511.  
  512.  
  513.  
  514. class CoClassItem(build.OleItem, WritableItem):
  515.     order = 5
  516.     typename = 'COCLASS'
  517.     
  518.     def __init__(self, typeinfo, attr, doc = None, sources = [], interfaces = [], bForUser = 1):
  519.         build.OleItem.__init__(self, doc)
  520.         self.clsid = attr[0]
  521.         self.sources = sources
  522.         self.interfaces = interfaces
  523.         self.bIsDispatch = 1
  524.  
  525.     
  526.     def WriteClass(self, generator):
  527.         generator.checkWriteCoClassBaseClass()
  528.         doc = self.doc
  529.         if generator.generate_type == GEN_DEMAND_CHILD:
  530.             referenced_items = []
  531.             for ref, flag in self.sources:
  532.                 referenced_items.append(ref)
  533.             
  534.             for ref, flag in self.interfaces:
  535.                 referenced_items.append(ref)
  536.             
  537.             print 'import sys'
  538.             for ref in referenced_items:
  539.                 print "__import__('%s.%s')" % (generator.base_mod_name, ref.python_name)
  540.                 print "%s = sys.modules['%s.%s'].%s" % (ref.python_name, generator.base_mod_name, ref.python_name, ref.python_name)
  541.             
  542.         
  543.         
  544.         try:
  545.             progId = pythoncom.ProgIDFromCLSID(self.clsid)
  546.             print "# This CoClass is known by the name '%s'" % progId
  547.         except pythoncom.com_error:
  548.             pass
  549.  
  550.         print 'class %s(CoClassBaseClass): # A CoClass' % self.python_name
  551.         if doc and doc[1]:
  552.             print '\t# ' + doc[1]
  553.         
  554.         clsidStr = str(self.clsid)
  555.         print '\tCLSID = pythoncom.MakeIID("%s")' % clsidStr
  556.         print '\tcoclass_sources = ['
  557.         defItem = None
  558.         for item, flag in self.sources:
  559.             if flag & pythoncom.IMPLTYPEFLAG_FDEFAULT:
  560.                 defItem = item
  561.             
  562.             if item.bIsDispatch:
  563.                 key = item.python_name
  564.             else:
  565.                 key = repr(str(item.clsid))
  566.             print '\t\t%s,' % key
  567.         
  568.         print '\t]'
  569.         if defItem:
  570.             if defItem.bIsDispatch:
  571.                 defName = defItem.python_name
  572.             else:
  573.                 defName = repr(str(defItem.clsid))
  574.             print '\tdefault_source = %s' % (defName,)
  575.         
  576.         print '\tcoclass_interfaces = ['
  577.         defItem = None
  578.         for item, flag in self.interfaces:
  579.             if flag & pythoncom.IMPLTYPEFLAG_FDEFAULT:
  580.                 defItem = item
  581.             
  582.             if item.bIsDispatch:
  583.                 key = item.python_name
  584.             else:
  585.                 key = repr(str(item.clsid))
  586.             print '\t\t%s,' % (key,)
  587.         
  588.         print '\t]'
  589.         if defItem:
  590.             if defItem.bIsDispatch:
  591.                 defName = defItem.python_name
  592.             else:
  593.                 defName = repr(str(defItem.clsid))
  594.             print '\tdefault_interface = %s' % (defName,)
  595.         
  596.         self.bWritten = 1
  597.         print 
  598.  
  599.  
  600.  
  601. class GeneratorProgress:
  602.     
  603.     def __init__(self):
  604.         pass
  605.  
  606.     
  607.     def Starting(self, tlb_desc):
  608.         '''Called when the process starts.
  609.         '''
  610.         self.tlb_desc = tlb_desc
  611.  
  612.     
  613.     def Finished(self):
  614.         '''Called when the process is complete.
  615.         '''
  616.         pass
  617.  
  618.     
  619.     def SetDescription(self, desc, maxticks = None):
  620.         '''We are entering a major step.  If maxticks, then this
  621.         is how many ticks we expect to make until finished
  622.         '''
  623.         pass
  624.  
  625.     
  626.     def Tick(self, desc = None):
  627.         '''Minor progress step.  Can provide new description if necessary
  628.         '''
  629.         pass
  630.  
  631.     
  632.     def VerboseProgress(self, desc):
  633.         '''Verbose/Debugging output.
  634.         '''
  635.         pass
  636.  
  637.     
  638.     def LogWarning(self, desc):
  639.         '''If a warning is generated
  640.         '''
  641.         pass
  642.  
  643.     
  644.     def LogBeginGenerate(self, filename):
  645.         pass
  646.  
  647.     
  648.     def Close(self):
  649.         pass
  650.  
  651.  
  652.  
  653. class Generator:
  654.     
  655.     def __init__(self, typelib, sourceFilename, progressObject, bBuildHidden = 1, bUnicodeToString = 0):
  656.         self.bHaveWrittenDispatchBaseClass = 0
  657.         self.bHaveWrittenCoClassBaseClass = 0
  658.         self.bHaveWrittenEventBaseClass = 0
  659.         self.typelib = typelib
  660.         self.sourceFilename = sourceFilename
  661.         self.bBuildHidden = bBuildHidden
  662.         self.bUnicodeToString = bUnicodeToString
  663.         self.progress = progressObject
  664.         self.file = None
  665.  
  666.     
  667.     def BuildOleItemsFromType(self, look_name = None):
  668.         if not __debug__ and self.bBuildHidden:
  669.             raise AssertionError, 'This code doesnt look at the hidden flag - I thought everyone set it true!?!?!'
  670.         oleItems = { }
  671.         enumItems = { }
  672.         recordItems = { }
  673.         vtableItems = { }
  674.         for i in xrange(self.typelib.GetTypeInfoCount()):
  675.             info = self.typelib.GetTypeInfo(i)
  676.             infotype = self.typelib.GetTypeInfoType(i)
  677.             doc = self.typelib.GetDocumentation(i)
  678.             attr = info.GetTypeAttr()
  679.             if infotype == pythoncom.TKIND_ENUM or infotype == pythoncom.TKIND_MODULE:
  680.                 if look_name is not None:
  681.                     continue
  682.                 
  683.                 newItem = EnumerationItem(info, attr, doc)
  684.                 enumItems[newItem.doc[0]] = newItem
  685.             elif infotype in [
  686.                 pythoncom.TKIND_DISPATCH,
  687.                 pythoncom.TKIND_INTERFACE]:
  688.                 if look_name is not None and doc[0] != look_name:
  689.                     continue
  690.                 
  691.                 if infotype == pythoncom.TKIND_DISPATCH:
  692.                     if not oleItems.has_key(attr[0]):
  693.                         newItem = DispatchItem(info, attr, doc)
  694.                         oleItems[newItem.clsid] = newItem
  695.                     
  696.                     if not (attr.wTypeFlags & pythoncom.TYPEFLAG_FDUAL):
  697.                         continue
  698.                     
  699.                     refhtype = info.GetRefTypeOfImplType(-1)
  700.                     info = info.GetRefTypeInfo(refhtype)
  701.                     attr = info.GetTypeAttr()
  702.                 
  703.                 if vtableItems.has_key(attr[0]):
  704.                     continue
  705.                 
  706.                 newItem = VTableItem(info, attr, doc)
  707.                 vtableItems[newItem.clsid] = newItem
  708.             elif infotype == pythoncom.TKIND_RECORD or infotype == pythoncom.TKIND_UNION:
  709.                 if look_name is not None:
  710.                     continue
  711.                 
  712.                 newItem = RecordItem(info, attr, doc)
  713.                 recordItems[newItem.clsid] = newItem
  714.             elif infotype == pythoncom.TKIND_ALIAS:
  715.                 continue
  716.             elif infotype == pythoncom.TKIND_COCLASS:
  717.                 if look_name is not None and look_name != doc[0]:
  718.                     continue
  719.                 
  720.                 sources = []
  721.                 interfaces = []
  722.                 for j in range(attr[8]):
  723.                     flags = info.GetImplTypeFlags(j)
  724.                     refType = info.GetRefTypeInfo(info.GetRefTypeOfImplType(j))
  725.                     refAttr = refType.GetTypeAttr()
  726.                     if refAttr.typekind == pythoncom.TKIND_DISPATCH:
  727.                         if oleItems.has_key(refAttr[0]):
  728.                             dispItem = oleItems[refAttr[0]]
  729.                         else:
  730.                             dispItem = DispatchItem(refType, refAttr, refType.GetDocumentation(-1))
  731.                             oleItems[dispItem.clsid] = dispItem
  732.                         if flags & pythoncom.IMPLTYPEFLAG_FSOURCE:
  733.                             dispItem.bIsSink = 1
  734.                             sources.append((dispItem, flags))
  735.                         else:
  736.                             interfaces.append((dispItem, flags))
  737.                         if not (refAttr[11] & pythoncom.TYPEFLAG_FDUAL):
  738.                             continue
  739.                         
  740.                         refType = refType.GetRefTypeInfo(refType.GetRefTypeOfImplType(-1))
  741.                         refAttr = refType.GetTypeAttr()
  742.                     
  743.                     if not __debug__ and refAttr.typekind == pythoncom.TKIND_INTERFACE:
  744.                         raise AssertionError, 'must be interface bynow!'
  745.                     if refAttr.typekind == pythoncom.TKIND_DISPATCH:
  746.                         if vtableItems.has_key(refAttr[0]):
  747.                             dispItem = vtableItems[refAttr[0]]
  748.                         else:
  749.                             dispItem = VTableItem(refType, refAttr, refType.GetDocumentation(-1))
  750.                             vtableItems[dispItem.clsid] = dispItem
  751.                         if flags & pythoncom.IMPLTYPEFLAG_FSOURCE:
  752.                             dispItem.bIsSink = 1
  753.                             sources.append((dispItem, flags))
  754.                         else:
  755.                             interfaces.append((dispItem, flags))
  756.                     
  757.                 
  758.                 newItem = CoClassItem(info, attr, doc, sources, interfaces)
  759.                 oleItems[newItem.clsid] = newItem
  760.             else:
  761.                 self.progress.LogWarning('Unknown TKIND found: %d' % infotype)
  762.         
  763.         return (oleItems, enumItems, recordItems, vtableItems)
  764.  
  765.     
  766.     def generate(self, file, is_for_demand = 0):
  767.         if is_for_demand:
  768.             self.generate_type = GEN_DEMAND_BASE
  769.         else:
  770.             self.generate_type = GEN_FULL
  771.         self.file = file
  772.         oldOut = sys.stdout
  773.         sys.stdout = file
  774.         
  775.         try:
  776.             self.do_generate()
  777.         finally:
  778.             sys.stdout = oldOut
  779.             self.file = None
  780.             self.progress.Finished()
  781.  
  782.  
  783.     
  784.     def do_gen_file_header(self):
  785.         la = self.typelib.GetLibAttr()
  786.         moduleDoc = self.typelib.GetDocumentation(-1)
  787.         docDesc = ''
  788.         if moduleDoc[1]:
  789.             docDesc = moduleDoc[1]
  790.         
  791.         print '# Created by makepy.py version %s' % (makepy_version,)
  792.         print '# By python version %s' % (sys.version,)
  793.         if self.sourceFilename:
  794.             print "# From type library '%s'" % (os.path.split(self.sourceFilename)[1],)
  795.         
  796.         print '# On %s' % time.ctime(time.time())
  797.         print '"""' + docDesc + '"""'
  798.         print 'makepy_version =', `makepy_version`
  799.         
  800.         try:
  801.             print 'python_version = 0x%x' % (sys.hexversion,)
  802.         except AttributeError:
  803.             print 'python_version = 0x0 # Presumably Python 1.5.2 - 0x0 is not a problem'
  804.  
  805.         print 
  806.         print 'import win32com.client.CLSIDToClass, pythoncom'
  807.         print 
  808.         print '# The following 3 lines may need tweaking for the particular server'
  809.         print '# Candidates are pythoncom.Missing and pythoncom.Empty'
  810.         print 'defaultNamedOptArg=pythoncom.Missing'
  811.         print 'defaultNamedNotOptArg=pythoncom.Missing'
  812.         print 'defaultUnnamedArg=pythoncom.Missing'
  813.         print 
  814.         print "CLSID = pythoncom.MakeIID('" + str(la[0]) + "')"
  815.         print 'MajorVersion = ' + str(la[3])
  816.         print 'MinorVersion = ' + str(la[4])
  817.         print 'LibraryFlags = ' + str(la[5])
  818.         print 'LCID = ' + hex(la[1])
  819.         print 
  820.  
  821.     
  822.     def do_generate(self):
  823.         moduleDoc = self.typelib.GetDocumentation(-1)
  824.         docDesc = ''
  825.         if moduleDoc[1]:
  826.             docDesc = moduleDoc[1]
  827.         
  828.         self.progress.Starting(docDesc)
  829.         self.progress.SetDescription('Building definitions from type library...')
  830.         self.do_gen_file_header()
  831.         (oleItems, enumItems, recordItems, vtableItems) = self.BuildOleItemsFromType()
  832.         self.progress.SetDescription('Generating...', len(oleItems) + len(enumItems) + len(vtableItems))
  833.         if enumItems:
  834.             print 'class constants:'
  835.             list = enumItems.values()
  836.             list.sort()
  837.             for oleitem in list:
  838.                 oleitem.WriteEnumerationItems()
  839.                 self.progress.Tick()
  840.             
  841.             print 
  842.         
  843.         if self.generate_type == GEN_FULL:
  844.             list = oleItems.values()
  845.             list.sort()
  846.             for oleitem in list:
  847.                 self.progress.Tick()
  848.                 oleitem.WriteClass(self)
  849.             
  850.             list = vtableItems.values()
  851.             list.sort()
  852.             for oleitem in list:
  853.                 self.progress.Tick()
  854.                 oleitem.WriteClass(self)
  855.             
  856.         else:
  857.             self.progress.Tick(len(oleItems) + len(vtableItems))
  858.         print 'RecordMap = {'
  859.         list = recordItems.values()
  860.         for record in list:
  861.             if str(record.clsid) == pythoncom.IID_NULL:
  862.                 print "\t###%s: %s, # Typedef disabled because it doesn't have a non-null GUID" % (`record.doc[0]`, `str(record.clsid)`)
  863.             else:
  864.                 print '\t%s: %s,' % (`record.doc[0]`, `str(record.clsid)`)
  865.         
  866.         print '}'
  867.         print 
  868.         if self.generate_type == GEN_FULL:
  869.             print 'CLSIDToClassMap = {'
  870.             for item in oleItems.values():
  871.                 if item.bWritten and item.bIsDispatch:
  872.                     print "\t'%s' : %s," % (str(item.clsid), item.python_name)
  873.                 
  874.             
  875.             print '}'
  876.             print 'CLSIDToPackageMap = {}'
  877.             print 'win32com.client.CLSIDToClass.RegisterCLSIDsFromDict( CLSIDToClassMap )'
  878.             print 'VTablesToPackageMap = {}'
  879.             print 'VTablesToClassMap = {'
  880.             for item in vtableItems.values():
  881.                 if not (item.bIsDispatch):
  882.                     print "\t'%s' : '%s'," % (item.clsid, item.python_name)
  883.                 
  884.             
  885.             print '}'
  886.             print 
  887.         else:
  888.             print 'CLSIDToClassMap = {}'
  889.             print 'CLSIDToPackageMap = {'
  890.             for item in oleItems.values():
  891.                 print "\t'%s' : %s," % (str(item.clsid), `item.python_name`)
  892.             
  893.             print '}'
  894.             print 'VTablesToClassMap = {}'
  895.             print 'VTablesToPackageMap = {'
  896.             for item in vtableItems.values():
  897.                 if not (item.bIsDispatch):
  898.                     print "\t'%s' : '%s'," % (item.clsid, item.python_name)
  899.                 
  900.             
  901.             print '}'
  902.             print 
  903.         print 
  904.         print 'VTablesNamesToCLSIDMap = {'
  905.         for item in vtableItems.values():
  906.             print "\t'%s' : '%s'," % (item.python_name, item.clsid)
  907.         
  908.         print '}'
  909.         print 
  910.         if enumItems:
  911.             print 'win32com.client.constants.__dicts__.append(constants.__dict__)'
  912.         
  913.         print 
  914.  
  915.     
  916.     def generate_child(self, child, dir):
  917.         '''Generate a single child.  May force a few children to be built as we generate deps'''
  918.         self.generate_type = GEN_DEMAND_CHILD
  919.         oldOut = sys.stdout
  920.         la = self.typelib.GetLibAttr()
  921.         lcid = la[1]
  922.         clsid = la[0]
  923.         major = la[3]
  924.         minor = la[4]
  925.         self.base_mod_name = 'win32com.gen_py.' + str(clsid)[1:-1] + 'x%sx%sx%s' % (lcid, major, minor)
  926.         
  927.         try:
  928.             (oleItems, enumItems, recordItems, vtableItems) = self.BuildOleItemsFromType(child)
  929.             if __debug__:
  930.                 if not len(enumItems) == 0 and len(recordItems) == 0:
  931.                     raise AssertionError, 'Not expecting anything other than dispatch/interface items'
  932.             if __debug__:
  933.                 if not len(oleItems) > 0 or len(vtableItems) > 0:
  934.                     raise AssertionError, "Could not find the name '%s'" % (child,)
  935.             items = { }
  936.             for key, value in oleItems.items():
  937.                 items[key] = (value, None)
  938.             
  939.             for key, value in vtableItems.items():
  940.                 existing = items.get(key, None)
  941.                 if existing is not None:
  942.                     new_val = (existing[0], value)
  943.                 else:
  944.                     new_val = (None, value)
  945.                 items[key] = new_val
  946.             
  947.             self.progress.SetDescription('Generating...', len(items))
  948.             for oleitem, vtableitem in items.values():
  949.                 if not oleitem:
  950.                     pass
  951.                 an_item = vtableitem
  952.                 self.file = open(os.path.join(dir, an_item.python_name) + '.py', 'w')
  953.                 sys.stdout = self.file
  954.                 
  955.                 try:
  956.                     if oleitem is not None:
  957.                         self.do_gen_child_item(oleitem)
  958.                     
  959.                     if vtableitem is not None:
  960.                         self.do_gen_child_item(vtableitem)
  961.                     
  962.                     self.progress.Tick()
  963.                 finally:
  964.                     sys.stdout = oldOut
  965.                     self.file.close()
  966.                     self.file = None
  967.  
  968.         finally:
  969.             sys.stdout = oldOut
  970.             self.progress.Finished()
  971.  
  972.  
  973.     
  974.     def do_gen_child_item(self, oleitem):
  975.         moduleDoc = self.typelib.GetDocumentation(-1)
  976.         docDesc = ''
  977.         if moduleDoc[1]:
  978.             docDesc = moduleDoc[1]
  979.         
  980.         self.progress.Starting(docDesc)
  981.         self.progress.SetDescription('Building definitions from type library...')
  982.         self.do_gen_file_header()
  983.         oleitem.WriteClass(self)
  984.         if oleitem.bIsDispatch:
  985.             print 'win32com.client.CLSIDToClass.RegisterCLSID( "%s", %s )' % (oleitem.clsid, oleitem.python_name)
  986.         
  987.  
  988.     
  989.     def checkWriteDispatchBaseClass(self):
  990.         if not (self.bHaveWrittenDispatchBaseClass):
  991.             print 'from win32com.client import DispatchBaseClass'
  992.             self.bHaveWrittenDispatchBaseClass = 1
  993.         
  994.  
  995.     
  996.     def checkWriteCoClassBaseClass(self):
  997.         if not (self.bHaveWrittenCoClassBaseClass):
  998.             print 'class CoClassBaseClass:'
  999.             print '\tdef __init__(self, oobj=None):'
  1000.             print '\t\tif oobj is None: oobj = pythoncom.new(self.CLSID)'
  1001.             print '\t\tself.__dict__["_dispobj_"] = self.default_interface(oobj)'
  1002.             print '\tdef __repr__(self):'
  1003.             print '\t\treturn "<win32com.gen_py.%s.%s>" % (__doc__, self.__class__.__name__)'
  1004.             print 
  1005.             print '\tdef __getattr__(self, attr):'
  1006.             print '\t\td=self.__dict__["_dispobj_"]'
  1007.             print '\t\tif d is not None: return getattr(d, attr)'
  1008.             print '\t\traise AttributeError, attr'
  1009.             print '\tdef __setattr__(self, attr, value):'
  1010.             print '\t\tif self.__dict__.has_key(attr): self.__dict__[attr] = value; return'
  1011.             print '\t\ttry:'
  1012.             print '\t\t\td=self.__dict__["_dispobj_"]'
  1013.             print '\t\t\tif d is not None:'
  1014.             print '\t\t\t\td.__setattr__(attr, value)'
  1015.             print '\t\t\t\treturn'
  1016.             print '\t\texcept AttributeError:'
  1017.             print '\t\t\tpass'
  1018.             print '\t\tself.__dict__[attr] = value'
  1019.             print 
  1020.             self.bHaveWrittenCoClassBaseClass = 1
  1021.         
  1022.  
  1023.     
  1024.     def checkWriteEventBaseClass(self):
  1025.         if not (self.bHaveWrittenEventBaseClass):
  1026.             self.bHaveWrittenEventBaseClass = 1
  1027.         
  1028.  
  1029.  
  1030. if __name__ == '__main__':
  1031.     print 'This is a worker module.  Please use makepy to generate Python files.'
  1032.  
  1033.