home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_2643 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  32.9 KB  |  1,082 lines

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