genpy.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  1. """genpy.py - The worker for makepy. See makepy.py for more details
  2. This code was moved simply to speed Python in normal circumstances. As the makepy.py
  3. is normally run from the command line, it reparses the code each time. Now makepy
  4. is nothing more than the command line handler and public interface.
  5. The makepy command line etc handling is also getting large enough in its own right!
  6. """
  7. # NOTE - now supports a "demand" mechanism - the top-level is a package, and
  8. # each class etc can be made individually.
  9. # This should eventually become the default.
  10. # Then the old non-package technique should be removed.
  11. # There should be no b/w compat issues, and will just help clean the code.
  12. # This will be done once the new "demand" mechanism gets a good workout.
  13. import os
  14. import sys
  15. import time
  16. import win32com
  17. import pythoncom
  18. from . import build
  19. error = "makepy.error"
  20. makepy_version = "0.5.01" # Written to generated file.
  21. GEN_FULL="full"
  22. GEN_DEMAND_BASE = "demand(base)"
  23. GEN_DEMAND_CHILD = "demand(child)"
  24. # This map is used purely for the users benefit -it shows the
  25. # raw, underlying type of Alias/Enums, etc. The COM implementation
  26. # does not use this map at runtime - all Alias/Enum have already
  27. # been translated.
  28. mapVTToTypeString = {
  29. pythoncom.VT_I2: 'types.IntType',
  30. pythoncom.VT_I4: 'types.IntType',
  31. pythoncom.VT_R4: 'types.FloatType',
  32. pythoncom.VT_R8: 'types.FloatType',
  33. pythoncom.VT_BSTR: 'types.StringType',
  34. pythoncom.VT_BOOL: 'types.IntType',
  35. pythoncom.VT_VARIANT: 'types.TypeType',
  36. pythoncom.VT_I1: 'types.IntType',
  37. pythoncom.VT_UI1: 'types.IntType',
  38. pythoncom.VT_UI2: 'types.IntType',
  39. pythoncom.VT_UI4: 'types.IntType',
  40. pythoncom.VT_I8: 'types.LongType',
  41. pythoncom.VT_UI8: 'types.LongType',
  42. pythoncom.VT_INT: 'types.IntType',
  43. pythoncom.VT_DATE: 'pythoncom.PyTimeType',
  44. pythoncom.VT_UINT: 'types.IntType',
  45. }
  46. # Given a propget function's arg desc, return the default parameters for all
  47. # params bar the first. Eg, then Python does a:
  48. # object.Property = "foo"
  49. # Python can only pass the "foo" value. If the property has
  50. # multiple args, and the rest have default values, this allows
  51. # Python to correctly pass those defaults.
  52. def MakeDefaultArgsForPropertyPut(argsDesc):
  53. ret = []
  54. for desc in argsDesc[1:]:
  55. default = build.MakeDefaultArgRepr(desc)
  56. if default is None:
  57. break
  58. ret.append(default)
  59. return tuple(ret)
  60. def MakeMapLineEntry(dispid, wFlags, retType, argTypes, user, resultCLSID):
  61. # Strip the default value
  62. argTypes = tuple([what[:2] for what in argTypes])
  63. return '(%s, %d, %s, %s, "%s", %s)' % \
  64. (dispid, wFlags, retType[:2], argTypes, user, resultCLSID)
  65. def MakeEventMethodName(eventName):
  66. if eventName[:2]=="On":
  67. return eventName
  68. else:
  69. return "On"+eventName
  70. def WriteSinkEventMap(obj, stream):
  71. print('\t_dispid_to_func_ = {', file=stream)
  72. for name, entry in list(obj.propMapGet.items()) + list(obj.propMapPut.items()) + list(obj.mapFuncs.items()):
  73. fdesc = entry.desc
  74. print('\t\t%9d : "%s",' % (fdesc.memid, MakeEventMethodName(entry.names[0])), file=stream)
  75. print('\t\t}', file=stream)
  76. # MI is used to join my writable helpers, and the OLE
  77. # classes.
  78. class WritableItem:
  79. # __cmp__ used for sorting in py2x...
  80. def __cmp__(self, other):
  81. "Compare for sorting"
  82. ret = cmp(self.order, other.order)
  83. if ret==0 and self.doc: ret = cmp(self.doc[0], other.doc[0])
  84. return ret
  85. # ... but not used in py3k - __lt__ minimum needed there
  86. def __lt__(self, other): # py3k variant
  87. if self.order == other.order:
  88. return self.doc < other.doc
  89. return self.order < other.order
  90. def __repr__(self):
  91. return "OleItem: doc=%s, order=%d" % (repr(self.doc), self.order)
  92. class RecordItem(build.OleItem, WritableItem):
  93. order = 9
  94. typename = "RECORD"
  95. def __init__(self, typeInfo, typeAttr, doc=None, bForUser=1):
  96. ## sys.stderr.write("Record %s: size %s\n" % (doc,typeAttr.cbSizeInstance))
  97. ## sys.stderr.write(" cVars = %s\n" % (typeAttr.cVars,))
  98. ## for i in range(typeAttr.cVars):
  99. ## vdesc = typeInfo.GetVarDesc(i)
  100. ## sys.stderr.write(" Var %d has value %s, type %d, desc=%s\n" % (i, vdesc.value, vdesc.varkind, vdesc.elemdescVar))
  101. ## sys.stderr.write(" Doc is %s\n" % (typeInfo.GetDocumentation(vdesc.memid),))
  102. build.OleItem.__init__(self, doc)
  103. self.clsid = typeAttr[0]
  104. def WriteClass(self, generator):
  105. pass
  106. # Given an enum, write all aliases for it.
  107. # (no longer necessary for new style code, but still used for old code.
  108. def WriteAliasesForItem(item, aliasItems, stream):
  109. for alias in aliasItems.values():
  110. if item.doc and alias.aliasDoc and (alias.aliasDoc[0]==item.doc[0]):
  111. alias.WriteAliasItem(aliasItems, stream)
  112. class AliasItem(build.OleItem, WritableItem):
  113. order = 2
  114. typename = "ALIAS"
  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 \
  120. type(ai[1])==type(0): # XXX - This is a hack - why tuples? Need to resolve?
  121. href = ai[1]
  122. alinfo = typeinfo.GetRefTypeInfo(href)
  123. self.aliasDoc = alinfo.GetDocumentation(-1)
  124. self.aliasAttr = alinfo.GetTypeAttr()
  125. else:
  126. self.aliasDoc = None
  127. self.aliasAttr = None
  128. def WriteAliasItem(self, aliasDict, stream):
  129. # we could have been written as part of an alias dependency
  130. if self.bWritten:
  131. return
  132. if self.aliasDoc:
  133. depName = self.aliasDoc[0]
  134. if depName in aliasDict:
  135. aliasDict[depName].WriteAliasItem(aliasDict, stream)
  136. print(self.doc[0] + " = " + depName, file=stream)
  137. else:
  138. ai = self.attr[14]
  139. if type(ai) == type(0):
  140. try:
  141. typeStr = mapVTToTypeString[ai]
  142. print("# %s=%s" % (self.doc[0], typeStr), file=stream)
  143. except KeyError:
  144. print(self.doc[0] + " = None # Can't convert alias info " + str(ai), file=stream)
  145. print(file=stream)
  146. self.bWritten = 1
  147. class EnumerationItem(build.OleItem, WritableItem):
  148. order = 1
  149. typename = "ENUMERATION"
  150. def __init__(self, typeinfo, attr, doc=None, bForUser=1):
  151. build.OleItem.__init__(self, doc)
  152. self.clsid = attr[0]
  153. self.mapVars = {}
  154. typeFlags = attr[11]
  155. self.hidden = typeFlags & pythoncom.TYPEFLAG_FHIDDEN or \
  156. typeFlags & pythoncom.TYPEFLAG_FRESTRICTED
  157. for j in range(attr[7]):
  158. vdesc = typeinfo.GetVarDesc(j)
  159. name = typeinfo.GetNames(vdesc[0])[0]
  160. self.mapVars[name] = build.MapEntry(vdesc)
  161. ## def WriteEnumerationHeaders(self, aliasItems, stream):
  162. ## enumName = self.doc[0]
  163. ## print >> stream "%s=constants # Compatibility with previous versions." % (enumName)
  164. ## WriteAliasesForItem(self, aliasItems)
  165. def WriteEnumerationItems(self, stream):
  166. num = 0
  167. enumName = self.doc[0]
  168. # Write in name alpha order
  169. names = list(self.mapVars.keys())
  170. names.sort()
  171. for name in names:
  172. entry = self.mapVars[name]
  173. vdesc = entry.desc
  174. if vdesc[4] == pythoncom.VAR_CONST:
  175. val = vdesc[1]
  176. use = repr(val)
  177. # Make sure the repr of the value is valid python syntax
  178. # still could cause an error on import if it contains a module or type name
  179. # not available in the global namespace
  180. try:
  181. compile(use, '<makepy>', 'eval')
  182. except SyntaxError:
  183. # At least add the repr as a string, so it can be investigated further
  184. # Sanitize it, in case the repr contains its own quotes. (??? line breaks too ???)
  185. use = use.replace('"',"'")
  186. use = '"' + use + '"' + ' # This VARIANT type cannot be converted automatically'
  187. print("\t%-30s=%-10s # from enum %s" % \
  188. (build.MakePublicAttributeName(name, True), use, enumName), file=stream)
  189. num += 1
  190. return num
  191. class VTableItem(build.VTableItem, WritableItem):
  192. order = 4
  193. def WriteClass(self, generator):
  194. self.WriteVTableMap(generator)
  195. self.bWritten = 1
  196. def WriteVTableMap(self, generator):
  197. stream = generator.file
  198. print("%s_vtables_dispatch_ = %d" % (self.python_name, self.bIsDispatch), file=stream)
  199. print("%s_vtables_ = [" % (self.python_name, ), file=stream)
  200. for v in self.vtableFuncs:
  201. names, dispid, desc = v
  202. assert(desc.desckind == pythoncom.DESCKIND_FUNCDESC)
  203. arg_reprs = []
  204. # more hoops so we don't generate huge lines.
  205. item_num = 0
  206. print("\t((", end=' ', file=stream)
  207. for name in names:
  208. print(repr(name), ",", end=' ', file=stream)
  209. item_num = item_num + 1
  210. if item_num % 5 == 0:
  211. print("\n\t\t\t", end=' ', file=stream)
  212. print("), %d, (%r, %r, [" % (dispid, desc.memid, desc.scodeArray), end=' ', file=stream)
  213. for arg in desc.args:
  214. item_num = item_num + 1
  215. if item_num % 5 == 0:
  216. print("\n\t\t\t", end=' ', file=stream)
  217. defval = build.MakeDefaultArgRepr(arg)
  218. if arg[3] is None:
  219. arg3_repr = None
  220. else:
  221. arg3_repr = repr(arg[3])
  222. print(repr((arg[0], arg[1], defval, arg3_repr)), ",", end=' ', file=stream)
  223. print("],", end=' ', file=stream)
  224. print(repr(desc.funckind), ",", end=' ', file=stream)
  225. print(repr(desc.invkind), ",", end=' ', file=stream)
  226. print(repr(desc.callconv), ",", end=' ', file=stream)
  227. print(repr(desc.cParamsOpt), ",", end=' ', file=stream)
  228. print(repr(desc.oVft), ",", end=' ', file=stream)
  229. print(repr(desc.rettype), ",", end=' ', file=stream)
  230. print(repr(desc.wFuncFlags), ",", end=' ', file=stream)
  231. print(")),", file=stream)
  232. print("]", file=stream)
  233. print(file=stream)
  234. class DispatchItem(build.DispatchItem, WritableItem):
  235. order = 3
  236. def __init__(self, typeinfo, attr, doc=None):
  237. build.DispatchItem.__init__(self, typeinfo, attr, doc)
  238. self.type_attr = attr
  239. self.coclass_clsid = None
  240. def WriteClass(self, generator):
  241. if not self.bIsDispatch and not self.type_attr.typekind == pythoncom.TKIND_DISPATCH:
  242. return
  243. # This is pretty screwey - now we have vtable support we
  244. # should probably rethink this (ie, maybe write both sides for sinks, etc)
  245. if self.bIsSink:
  246. self.WriteEventSinkClassHeader(generator)
  247. self.WriteCallbackClassBody(generator)
  248. else:
  249. self.WriteClassHeader(generator)
  250. self.WriteClassBody(generator)
  251. print(file=generator.file)
  252. self.bWritten = 1
  253. def WriteClassHeader(self, generator):
  254. generator.checkWriteDispatchBaseClass()
  255. doc = self.doc
  256. stream = generator.file
  257. print('class ' + self.python_name + '(DispatchBaseClass):', file=stream)
  258. if doc[1]: print('\t' + build._makeDocString(doc[1]), file=stream)
  259. try:
  260. progId = pythoncom.ProgIDFromCLSID(self.clsid)
  261. print("\t# This class is creatable by the name '%s'" % (progId), file=stream)
  262. except pythoncom.com_error:
  263. pass
  264. print("\tCLSID = " + repr(self.clsid), file=stream)
  265. if self.coclass_clsid is None:
  266. print("\tcoclass_clsid = None", file=stream)
  267. else:
  268. print("\tcoclass_clsid = " + repr(self.coclass_clsid), file=stream)
  269. print(file=stream)
  270. self.bWritten = 1
  271. def WriteEventSinkClassHeader(self, generator):
  272. generator.checkWriteEventBaseClass()
  273. doc = self.doc
  274. stream = generator.file
  275. print('class ' + self.python_name + ':', file=stream)
  276. if doc[1]: print('\t' + build._makeDocString(doc[1]), file=stream)
  277. try:
  278. progId = pythoncom.ProgIDFromCLSID(self.clsid)
  279. print("\t# This class is creatable by the name '%s'" % (progId), file=stream)
  280. except pythoncom.com_error:
  281. pass
  282. print('\tCLSID = CLSID_Sink = ' + repr(self.clsid), file=stream)
  283. if self.coclass_clsid is None:
  284. print("\tcoclass_clsid = None", file=stream)
  285. else:
  286. print("\tcoclass_clsid = " + repr(self.coclass_clsid), file=stream)
  287. print('\t_public_methods_ = [] # For COM Server support', file=stream)
  288. WriteSinkEventMap(self, stream)
  289. print(file=stream)
  290. print('\tdef __init__(self, oobj = None):', file=stream)
  291. print("\t\tif oobj is None:", file=stream)
  292. print("\t\t\tself._olecp = None", file=stream)
  293. print("\t\telse:", file=stream)
  294. print('\t\t\timport win32com.server.util', file=stream)
  295. print('\t\t\tfrom win32com.server.policy import EventHandlerPolicy', file=stream)
  296. print('\t\t\tcpc=oobj._oleobj_.QueryInterface(pythoncom.IID_IConnectionPointContainer)', file=stream)
  297. print('\t\t\tcp=cpc.FindConnectionPoint(self.CLSID_Sink)', file=stream)
  298. print('\t\t\tcookie=cp.Advise(win32com.server.util.wrap(self, usePolicy=EventHandlerPolicy))', file=stream)
  299. print('\t\t\tself._olecp,self._olecp_cookie = cp,cookie', file=stream)
  300. print('\tdef __del__(self):', file=stream)
  301. print('\t\ttry:', file=stream)
  302. print('\t\t\tself.close()', file=stream)
  303. print('\t\texcept pythoncom.com_error:', file=stream)
  304. print('\t\t\tpass', file=stream)
  305. print('\tdef close(self):', file=stream)
  306. print('\t\tif self._olecp is not None:', file=stream)
  307. print('\t\t\tcp,cookie,self._olecp,self._olecp_cookie = self._olecp,self._olecp_cookie,None,None', file=stream)
  308. print('\t\t\tcp.Unadvise(cookie)', file=stream)
  309. print('\tdef _query_interface_(self, iid):', file=stream)
  310. print('\t\timport win32com.server.util', file=stream)
  311. print('\t\tif iid==self.CLSID_Sink: return win32com.server.util.wrap(self)', file=stream)
  312. print(file=stream)
  313. self.bWritten = 1
  314. def WriteCallbackClassBody(self, generator):
  315. stream = generator.file
  316. print("\t# Event Handlers", file=stream)
  317. print("\t# If you create handlers, they should have the following prototypes:", file=stream)
  318. for name, entry in list(self.propMapGet.items()) + list(self.propMapPut.items()) + list(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", "pythoncom.Missing", is_comment = True) + '):', file=stream)
  322. if entry.doc and entry.doc[1]:
  323. print('#\t\t' + build._makeDocString(entry.doc[1]), file=stream)
  324. print(file=stream)
  325. self.bWritten = 1
  326. def WriteClassBody(self, generator):
  327. stream = generator.file
  328. # Write in alpha order.
  329. names = list(self.mapFuncs.keys())
  330. names.sort()
  331. specialItems = {"count":None, "item":None,"value":None,"_newenum":None} # If found, will end up with (entry, invoke_tupe)
  332. itemCount = None
  333. for name in names:
  334. entry=self.mapFuncs[name]
  335. assert(entry.desc.desckind == pythoncom.DESCKIND_FUNCDESC)
  336. # skip [restricted] methods, unless it is the
  337. # enumerator (which, being part of the "system",
  338. # we know about and can use)
  339. dispid = entry.desc.memid
  340. if entry.desc.wFuncFlags & pythoncom.FUNCFLAG_FRESTRICTED and \
  341. dispid != pythoncom.DISPID_NEWENUM:
  342. continue
  343. # If not accessible via IDispatch, then we can't use it here.
  344. if entry.desc.funckind != pythoncom.FUNC_DISPATCH:
  345. continue
  346. if dispid==pythoncom.DISPID_VALUE:
  347. lkey = "value"
  348. elif dispid==pythoncom.DISPID_NEWENUM:
  349. specialItems["_newenum"] = (entry, entry.desc.invkind, None)
  350. continue # Dont build this one now!
  351. else:
  352. lkey = name.lower()
  353. if lkey in specialItems and specialItems[lkey] is None: # remember if a special one.
  354. specialItems[lkey] = (entry, entry.desc.invkind, None)
  355. if generator.bBuildHidden or not entry.hidden:
  356. if entry.GetResultName():
  357. print('\t# Result is of type ' + entry.GetResultName(), file=stream)
  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, file=stream)
  360. ret = self.MakeFuncMethod(entry,build.MakePublicAttributeName(name))
  361. for line in ret:
  362. print(line, file=stream)
  363. print("\t_prop_map_get_ = {", file=stream)
  364. names = list(self.propMap.keys()); names.sort()
  365. for key in names:
  366. entry = self.propMap[key]
  367. if generator.bBuildHidden or not entry.hidden:
  368. resultName = entry.GetResultName()
  369. if resultName:
  370. print("\t\t# Property '%s' is an object of type '%s'" % (key, resultName), file=stream)
  371. lkey = key.lower()
  372. details = entry.desc
  373. resultDesc = details[2]
  374. argDesc = ()
  375. mapEntry = MakeMapLineEntry(details.memid, pythoncom.DISPATCH_PROPERTYGET, resultDesc, argDesc, key, entry.GetResultCLSIDStr())
  376. if details.memid==pythoncom.DISPID_VALUE:
  377. lkey = "value"
  378. elif details.memid==pythoncom.DISPID_NEWENUM:
  379. lkey = "_newenum"
  380. else:
  381. lkey = key.lower()
  382. if lkey in specialItems and specialItems[lkey] is None: # remember if a special one.
  383. specialItems[lkey] = (entry, pythoncom.DISPATCH_PROPERTYGET, mapEntry)
  384. # All special methods, except _newenum, are written
  385. # "normally". This is a mess!
  386. if details.memid==pythoncom.DISPID_NEWENUM:
  387. continue
  388. print('\t\t"%s": %s,' % (build.MakePublicAttributeName(key), mapEntry), file=stream)
  389. names = list(self.propMapGet.keys()); names.sort()
  390. for key in names:
  391. entry = self.propMapGet[key]
  392. if generator.bBuildHidden or not entry.hidden:
  393. if entry.GetResultName():
  394. print("\t\t# Method '%s' returns object of type '%s'" % (key, entry.GetResultName()), file=stream)
  395. details = entry.desc
  396. assert(details.desckind == pythoncom.DESCKIND_FUNCDESC)
  397. lkey = key.lower()
  398. argDesc = details[2]
  399. resultDesc = details[8]
  400. mapEntry = MakeMapLineEntry(details[0], pythoncom.DISPATCH_PROPERTYGET, resultDesc, argDesc, key, entry.GetResultCLSIDStr())
  401. if details.memid==pythoncom.DISPID_VALUE:
  402. lkey = "value"
  403. elif details.memid==pythoncom.DISPID_NEWENUM:
  404. lkey = "_newenum"
  405. else:
  406. lkey = key.lower()
  407. if lkey in specialItems and specialItems[lkey] is None: # remember if a special one.
  408. specialItems[lkey]=(entry, pythoncom.DISPATCH_PROPERTYGET, mapEntry)
  409. # All special methods, except _newenum, are written
  410. # "normally". This is a mess!
  411. if details.memid==pythoncom.DISPID_NEWENUM:
  412. continue
  413. print('\t\t"%s": %s,' % (build.MakePublicAttributeName(key), mapEntry), file=stream)
  414. print("\t}", file=stream)
  415. print("\t_prop_map_put_ = {", file=stream)
  416. # These are "Invoke" args
  417. names = list(self.propMap.keys()); names.sort()
  418. for key in names:
  419. entry = self.propMap[key]
  420. if generator.bBuildHidden or not entry.hidden:
  421. lkey=key.lower()
  422. details = entry.desc
  423. # If default arg is None, write an empty tuple
  424. defArgDesc = build.MakeDefaultArgRepr(details[2])
  425. if defArgDesc is None:
  426. defArgDesc = ""
  427. else:
  428. defArgDesc = defArgDesc + ","
  429. print('\t\t"%s" : ((%s, LCID, %d, 0),(%s)),' % (build.MakePublicAttributeName(key), details[0], pythoncom.DISPATCH_PROPERTYPUT, defArgDesc), file=stream)
  430. names = list(self.propMapPut.keys()); names.sort()
  431. for key in names:
  432. entry = self.propMapPut[key]
  433. if generator.bBuildHidden or not entry.hidden:
  434. details = entry.desc
  435. defArgDesc = MakeDefaultArgsForPropertyPut(details[2])
  436. print('\t\t"%s": ((%s, LCID, %d, 0),%s),' % (build.MakePublicAttributeName(key), details[0], details[4], defArgDesc), file=stream)
  437. print("\t}", file=stream)
  438. if specialItems["value"]:
  439. entry, invoketype, propArgs = specialItems["value"]
  440. if propArgs is None:
  441. typename = "method"
  442. ret = self.MakeFuncMethod(entry,'__call__')
  443. else:
  444. typename = "property"
  445. ret = [ "\tdef __call__(self):\n\t\treturn self._ApplyTypes_(*%s)" % propArgs]
  446. print("\t# Default %s for this class is '%s'" % (typename, entry.names[0]), file=stream)
  447. for line in ret:
  448. print(line, file=stream)
  449. print("\tdef __str__(self, *args):", file=stream)
  450. print("\t\treturn str(self.__call__(*args))", file=stream)
  451. print("\tdef __int__(self, *args):", file=stream)
  452. print("\t\treturn int(self.__call__(*args))", file=stream)
  453. # _NewEnum (DISPID_NEWENUM) does not appear in typelib for many office objects,
  454. # but it can still be retrieved at runtime, so always create __iter__.
  455. # Also, some of those same objects use 1-based indexing, causing the old-style
  456. # __getitem__ iteration to fail for index 0 where the dynamic iteration succeeds.
  457. if specialItems["_newenum"]:
  458. enumEntry, invoketype, propArgs = specialItems["_newenum"]
  459. assert(enumEntry.desc.desckind == pythoncom.DESCKIND_FUNCDESC)
  460. invkind = enumEntry.desc.invkind
  461. # ??? Wouldn't this be the resultCLSID for the iterator itself, rather than the resultCLSID
  462. # for the result of each Next() call, which is what it's used for ???
  463. resultCLSID = enumEntry.GetResultCLSIDStr()
  464. else:
  465. invkind = pythoncom.DISPATCH_METHOD | pythoncom.DISPATCH_PROPERTYGET
  466. resultCLSID = "None"
  467. # If we dont have a good CLSID for the enum result, assume it is the same as the Item() method.
  468. if resultCLSID == "None" and "Item" in self.mapFuncs:
  469. resultCLSID = self.mapFuncs["Item"].GetResultCLSIDStr()
  470. print('\tdef __iter__(self):', file=stream)
  471. print('\t\t"Return a Python iterator for this object"', file=stream)
  472. print('\t\ttry:', file=stream)
  473. print('\t\t\tob = self._oleobj_.InvokeTypes(%d,LCID,%d,(13, 10),())' % (pythoncom.DISPID_NEWENUM, invkind), file=stream)
  474. print('\t\texcept pythoncom.error:', file=stream)
  475. print('\t\t\traise TypeError("This object does not support enumeration")', file=stream)
  476. # Iterator is wrapped as PyIEnumVariant, and each result of __next__ is Dispatch'ed if necessary
  477. print('\t\treturn win32com.client.util.Iterator(ob, %s)' %resultCLSID, file=stream)
  478. if specialItems["item"]:
  479. entry, invoketype, propArgs = specialItems["item"]
  480. resultCLSID = entry.GetResultCLSIDStr()
  481. print('\t#This class has Item property/method which allows indexed access with the object[key] syntax.', file=stream)
  482. print('\t#Some objects will accept a string or other type of key in addition to integers.', file=stream)
  483. print('\t#Note that many Office objects do not use zero-based indexing.', file=stream)
  484. print('\tdef __getitem__(self, key):', file=stream)
  485. print('\t\treturn self._get_good_object_(self._oleobj_.Invoke(*(%d, LCID, %d, 1, key)), "Item", %s)' \
  486. % (entry.desc.memid, invoketype, resultCLSID), file=stream)
  487. if specialItems["count"]:
  488. entry, invoketype, propArgs = specialItems["count"]
  489. if propArgs is None:
  490. typename = "method"
  491. ret = self.MakeFuncMethod(entry,'__len__')
  492. else:
  493. typename = "property"
  494. ret = [ "\tdef __len__(self):\n\t\treturn self._ApplyTypes_(*%s)" % propArgs]
  495. print("\t#This class has Count() %s - allow len(ob) to provide this" % (typename), file=stream)
  496. for line in ret:
  497. print(line, file=stream)
  498. # Also include a __nonzero__
  499. print("\t#This class has a __len__ - this is needed so 'if object:' always returns TRUE.", file=stream)
  500. print("\tdef __nonzero__(self):", file=stream)
  501. print("\t\treturn True", file=stream)
  502. class CoClassItem(build.OleItem, WritableItem):
  503. order = 5
  504. typename = "COCLASS"
  505. def __init__(self, typeinfo, attr, doc=None, sources = [], interfaces = [], bForUser=1):
  506. build.OleItem.__init__(self, doc)
  507. self.clsid = attr[0]
  508. self.sources = sources
  509. self.interfaces = interfaces
  510. self.bIsDispatch = 1 # Pretend it is so it is written to the class map.
  511. def WriteClass(self, generator):
  512. generator.checkWriteCoClassBaseClass()
  513. doc = self.doc
  514. stream = generator.file
  515. if generator.generate_type == GEN_DEMAND_CHILD:
  516. # Some special imports we must setup.
  517. referenced_items = []
  518. for ref, flag in self.sources:
  519. referenced_items.append(ref)
  520. for ref, flag in self.interfaces:
  521. referenced_items.append(ref)
  522. print("import sys", file=stream)
  523. for ref in referenced_items:
  524. print("__import__('%s.%s')" % (generator.base_mod_name, ref.python_name), file=stream)
  525. print("%s = sys.modules['%s.%s'].%s" % (ref.python_name, generator.base_mod_name, ref.python_name, ref.python_name), file=stream)
  526. # And pretend we have written it - the name is now available as if we had!
  527. ref.bWritten = 1
  528. try:
  529. progId = pythoncom.ProgIDFromCLSID(self.clsid)
  530. print("# This CoClass is known by the name '%s'" % (progId), file=stream)
  531. except pythoncom.com_error:
  532. pass
  533. print('class %s(CoClassBaseClass): # A CoClass' % (self.python_name), file=stream)
  534. if doc and doc[1]: print('\t# ' + doc[1], file=stream)
  535. print('\tCLSID = %r' % (self.clsid,), file=stream)
  536. print('\tcoclass_sources = [', file=stream)
  537. defItem = None
  538. for item, flag in self.sources:
  539. if flag & pythoncom.IMPLTYPEFLAG_FDEFAULT:
  540. defItem = item
  541. # If we have written a Python class, reference the name -
  542. # otherwise just the IID.
  543. if item.bWritten: key = item.python_name
  544. else: key = repr(str(item.clsid)) # really the iid.
  545. print('\t\t%s,' % (key), file=stream)
  546. print('\t]', file=stream)
  547. if defItem:
  548. if defItem.bWritten: defName = defItem.python_name
  549. else: defName = repr(str(defItem.clsid)) # really the iid.
  550. print('\tdefault_source = %s' % (defName,), file=stream)
  551. print('\tcoclass_interfaces = [', file=stream)
  552. defItem = None
  553. for item, flag in self.interfaces:
  554. if flag & pythoncom.IMPLTYPEFLAG_FDEFAULT: # and dual:
  555. defItem = item
  556. # If we have written a class, reference its name, otherwise the IID
  557. if item.bWritten: key = item.python_name
  558. else: key = repr(str(item.clsid)) # really the iid.
  559. print('\t\t%s,' % (key,), file=stream)
  560. print('\t]', file=stream)
  561. if defItem:
  562. if defItem.bWritten: defName = defItem.python_name
  563. else: defName = repr(str(defItem.clsid)) # really the iid.
  564. print('\tdefault_interface = %s' % (defName,), file=stream)
  565. self.bWritten = 1
  566. print(file=stream)
  567. class GeneratorProgress:
  568. def __init__(self):
  569. pass
  570. def Starting(self, tlb_desc):
  571. """Called when the process starts.
  572. """
  573. self.tlb_desc = tlb_desc
  574. def Finished(self):
  575. """Called when the process is complete.
  576. """
  577. def SetDescription(self, desc, maxticks = None):
  578. """We are entering a major step. If maxticks, then this
  579. is how many ticks we expect to make until finished
  580. """
  581. def Tick(self, desc = None):
  582. """Minor progress step. Can provide new description if necessary
  583. """
  584. def VerboseProgress(self, desc):
  585. """Verbose/Debugging output.
  586. """
  587. def LogWarning(self, desc):
  588. """If a warning is generated
  589. """
  590. def LogBeginGenerate(self, filename):
  591. pass
  592. def Close(self):
  593. pass
  594. class Generator:
  595. def __init__(self, typelib, sourceFilename, progressObject, bBuildHidden=1, bUnicodeToString=None):
  596. assert bUnicodeToString is None, "this is deprecated and will go away"
  597. self.bHaveWrittenDispatchBaseClass = 0
  598. self.bHaveWrittenCoClassBaseClass = 0
  599. self.bHaveWrittenEventBaseClass = 0
  600. self.typelib = typelib
  601. self.sourceFilename = sourceFilename
  602. self.bBuildHidden = bBuildHidden
  603. self.progress = progressObject
  604. # These 2 are later additions and most of the code still 'print's...
  605. self.file = None
  606. def CollectOleItemInfosFromType(self):
  607. ret = []
  608. for i in range(self.typelib.GetTypeInfoCount()):
  609. info = self.typelib.GetTypeInfo(i)
  610. infotype = self.typelib.GetTypeInfoType(i)
  611. doc = self.typelib.GetDocumentation(i)
  612. attr = info.GetTypeAttr()
  613. ret.append((info, infotype, doc, attr))
  614. return ret
  615. def _Build_CoClass(self, type_info_tuple):
  616. info, infotype, doc, attr = type_info_tuple
  617. # find the source and dispinterfaces for the coclass
  618. child_infos = []
  619. for j in range(attr[8]):
  620. flags = info.GetImplTypeFlags(j)
  621. try:
  622. refType = info.GetRefTypeInfo(info.GetRefTypeOfImplType(j))
  623. except pythoncom.com_error:
  624. # Can't load a dependent typelib?
  625. continue
  626. refAttr = refType.GetTypeAttr()
  627. child_infos.append( (info, refAttr.typekind, refType, refType.GetDocumentation(-1), refAttr, flags) )
  628. # Done generating children - now the CoClass itself.
  629. newItem = CoClassItem(info, attr, doc)
  630. return newItem, child_infos
  631. def _Build_CoClassChildren(self, coclass, coclass_info, oleItems, vtableItems):
  632. sources = {}
  633. interfaces = {}
  634. for info, info_type, refType, doc, refAttr, flags in coclass_info:
  635. # sys.stderr.write("Attr typeflags for coclass referenced object %s=%d (%d), typekind=%d\n" % (name, refAttr.wTypeFlags, refAttr.wTypeFlags & pythoncom.TYPEFLAG_FDUAL,refAttr.typekind))
  636. if refAttr.typekind == pythoncom.TKIND_DISPATCH or \
  637. (refAttr.typekind == pythoncom.TKIND_INTERFACE and refAttr[11] & pythoncom.TYPEFLAG_FDISPATCHABLE):
  638. clsid = refAttr[0]
  639. if clsid in oleItems:
  640. dispItem = oleItems[clsid]
  641. else:
  642. dispItem = DispatchItem(refType, refAttr, doc)
  643. oleItems[dispItem.clsid] = dispItem
  644. dispItem.coclass_clsid = coclass.clsid
  645. if flags & pythoncom.IMPLTYPEFLAG_FSOURCE:
  646. dispItem.bIsSink = 1
  647. sources[dispItem.clsid] = (dispItem, flags)
  648. else:
  649. interfaces[dispItem.clsid] = (dispItem, flags)
  650. # If dual interface, make do that too.
  651. if clsid not in vtableItems and refAttr[11] & pythoncom.TYPEFLAG_FDUAL:
  652. refType = refType.GetRefTypeInfo(refType.GetRefTypeOfImplType(-1))
  653. refAttr = refType.GetTypeAttr()
  654. assert refAttr.typekind == pythoncom.TKIND_INTERFACE, "must be interface bynow!"
  655. vtableItem = VTableItem(refType, refAttr, doc)
  656. vtableItems[clsid] = vtableItem
  657. coclass.sources = list(sources.values())
  658. coclass.interfaces = list(interfaces.values())
  659. def _Build_Interface(self, type_info_tuple):
  660. info, infotype, doc, attr = type_info_tuple
  661. oleItem = vtableItem = None
  662. if infotype == pythoncom.TKIND_DISPATCH or \
  663. (infotype == pythoncom.TKIND_INTERFACE and attr[11] & pythoncom.TYPEFLAG_FDISPATCHABLE):
  664. oleItem = DispatchItem(info, attr, doc)
  665. # If this DISPATCH interface dual, then build that too.
  666. if (attr.wTypeFlags & pythoncom.TYPEFLAG_FDUAL):
  667. # Get the vtable interface
  668. refhtype = info.GetRefTypeOfImplType(-1)
  669. info = info.GetRefTypeInfo(refhtype)
  670. attr = info.GetTypeAttr()
  671. infotype = pythoncom.TKIND_INTERFACE
  672. else:
  673. infotype = None
  674. assert infotype in [None, pythoncom.TKIND_INTERFACE], "Must be a real interface at this point"
  675. if infotype == pythoncom.TKIND_INTERFACE:
  676. vtableItem = VTableItem(info, attr, doc)
  677. return oleItem, vtableItem
  678. def BuildOleItemsFromType(self):
  679. assert self.bBuildHidden, "This code doesnt look at the hidden flag - I thought everyone set it true!?!?!"
  680. oleItems = {}
  681. enumItems = {}
  682. recordItems = {}
  683. vtableItems = {}
  684. for type_info_tuple in self.CollectOleItemInfosFromType():
  685. info, infotype, doc, attr = type_info_tuple
  686. clsid = attr[0]
  687. if infotype == pythoncom.TKIND_ENUM or infotype == pythoncom.TKIND_MODULE:
  688. newItem = EnumerationItem(info, attr, doc)
  689. enumItems[newItem.doc[0]] = newItem
  690. # We never hide interfaces (MSAccess, for example, nominates interfaces as
  691. # hidden, assuming that you only ever use them via the CoClass)
  692. elif infotype in [pythoncom.TKIND_DISPATCH, pythoncom.TKIND_INTERFACE]:
  693. if clsid not in oleItems:
  694. oleItem, vtableItem = self._Build_Interface(type_info_tuple)
  695. oleItems[clsid] = oleItem # Even "None" goes in here.
  696. if vtableItem is not None:
  697. vtableItems[clsid] = vtableItem
  698. elif infotype == pythoncom.TKIND_RECORD or infotype == pythoncom.TKIND_UNION:
  699. newItem = RecordItem(info, attr, doc)
  700. recordItems[newItem.clsid] = newItem
  701. elif infotype == pythoncom.TKIND_ALIAS:
  702. # We dont care about alias' - handled intrinsicly.
  703. continue
  704. elif infotype == pythoncom.TKIND_COCLASS:
  705. newItem, child_infos = self._Build_CoClass(type_info_tuple)
  706. self._Build_CoClassChildren(newItem, child_infos, oleItems, vtableItems)
  707. oleItems[newItem.clsid] = newItem
  708. else:
  709. self.progress.LogWarning("Unknown TKIND found: %d" % infotype)
  710. return oleItems, enumItems, recordItems, vtableItems
  711. def open_writer(self, filename, encoding="mbcs"):
  712. # A place to put code to open a file with the appropriate encoding.
  713. # Does *not* set self.file - just opens and returns a file.
  714. # Actually returns a handle to a temp file - finish_writer then deletes
  715. # the filename asked for and puts everything back in place. This
  716. # is so errors don't leave a 1/2 generated file around causing bizarre
  717. # errors later, and so that multiple processes writing the same file
  718. # don't step on each others' toes.
  719. # Could be a classmethod one day...
  720. temp_filename = self.get_temp_filename(filename)
  721. return open(temp_filename, "wt", encoding=encoding)
  722. def finish_writer(self, filename, f, worked):
  723. f.close()
  724. try:
  725. os.unlink(filename)
  726. except os.error:
  727. pass
  728. temp_filename = self.get_temp_filename(filename)
  729. if worked:
  730. try:
  731. os.rename(temp_filename, filename)
  732. except os.error:
  733. # If we are really unlucky, another process may have written the
  734. # file in between our calls to os.unlink and os.rename. So try
  735. # again, but only once.
  736. # There are still some race conditions, but they seem difficult to
  737. # fix, and they probably occur much less frequently:
  738. # * The os.rename failure could occur more than once if more than
  739. # two processes are involved.
  740. # * In between os.unlink and os.rename, another process could try
  741. # to import the module, having seen that it already exists.
  742. # * If another process starts a COM server while we are still
  743. # generating __init__.py, that process sees that the folder
  744. # already exists and assumes that __init__.py is already there
  745. # as well.
  746. try:
  747. os.unlink(filename)
  748. except os.error:
  749. pass
  750. os.rename(temp_filename, filename)
  751. else:
  752. os.unlink(temp_filename)
  753. def get_temp_filename(self, filename):
  754. return '%s.%d.temp' % (filename, os.getpid())
  755. def generate(self, file, is_for_demand = 0):
  756. if is_for_demand:
  757. self.generate_type = GEN_DEMAND_BASE
  758. else:
  759. self.generate_type = GEN_FULL
  760. self.file = file
  761. self.do_generate()
  762. self.file = None
  763. self.progress.Finished()
  764. def do_gen_file_header(self):
  765. la = self.typelib.GetLibAttr()
  766. moduleDoc = self.typelib.GetDocumentation(-1)
  767. docDesc = ""
  768. if moduleDoc[1]:
  769. docDesc = moduleDoc[1]
  770. # Reset all the 'per file' state
  771. self.bHaveWrittenDispatchBaseClass = 0
  772. self.bHaveWrittenCoClassBaseClass = 0
  773. self.bHaveWrittenEventBaseClass = 0
  774. # You must provide a file correctly configured for writing unicode.
  775. # We assert this is it may indicate somewhere in pywin32 that needs
  776. # upgrading.
  777. assert self.file.encoding, self.file
  778. encoding = self.file.encoding # or "mbcs"
  779. print('# -*- coding: %s -*-' % (encoding,), file=self.file)
  780. print('# Created by makepy.py version %s' % (makepy_version,), file=self.file)
  781. print('# By python version %s' % \
  782. (sys.version.replace("\n", "-"),), file=self.file)
  783. if self.sourceFilename:
  784. print("# From type library '%s'" % (os.path.split(self.sourceFilename)[1],), file=self.file)
  785. print('# On %s' % time.ctime(time.time()), file=self.file)
  786. print(build._makeDocString(docDesc), file=self.file)
  787. print('makepy_version =', repr(makepy_version), file=self.file)
  788. print('python_version = 0x%x' % (sys.hexversion,), file=self.file)
  789. print(file=self.file)
  790. print('import win32com.client.CLSIDToClass, pythoncom, pywintypes', file=self.file)
  791. print('import win32com.client.util', file=self.file)
  792. print('from pywintypes import IID', file=self.file)
  793. print('from win32com.client import Dispatch', file=self.file)
  794. print(file=self.file)
  795. print('# The following 3 lines may need tweaking for the particular server', file=self.file)
  796. print('# Candidates are pythoncom.Missing, .Empty and .ArgNotFound', file=self.file)
  797. print('defaultNamedOptArg=pythoncom.Empty', file=self.file)
  798. print('defaultNamedNotOptArg=pythoncom.Empty', file=self.file)
  799. print('defaultUnnamedArg=pythoncom.Empty', file=self.file)
  800. print(file=self.file)
  801. print('CLSID = ' + repr(la[0]), file=self.file)
  802. print('MajorVersion = ' + str(la[3]), file=self.file)
  803. print('MinorVersion = ' + str(la[4]), file=self.file)
  804. print('LibraryFlags = ' + str(la[5]), file=self.file)
  805. print('LCID = ' + hex(la[1]), file=self.file)
  806. print(file=self.file)
  807. def do_generate(self):
  808. moduleDoc = self.typelib.GetDocumentation(-1)
  809. stream = self.file
  810. docDesc = ""
  811. if moduleDoc[1]:
  812. docDesc = moduleDoc[1]
  813. self.progress.Starting(docDesc)
  814. self.progress.SetDescription("Building definitions from type library...")
  815. self.do_gen_file_header()
  816. oleItems, enumItems, recordItems, vtableItems = self.BuildOleItemsFromType()
  817. self.progress.SetDescription("Generating...", len(oleItems)+len(enumItems)+len(vtableItems))
  818. # Generate the constants and their support.
  819. if enumItems:
  820. print("class constants:", file=stream)
  821. items = list(enumItems.values())
  822. items.sort()
  823. num_written = 0
  824. for oleitem in items:
  825. num_written += oleitem.WriteEnumerationItems(stream)
  826. self.progress.Tick()
  827. if not num_written:
  828. print("\tpass", file=stream)
  829. print(file=stream)
  830. if self.generate_type == GEN_FULL:
  831. items = [l for l in oleItems.values() if l is not None]
  832. items.sort()
  833. for oleitem in items:
  834. self.progress.Tick()
  835. oleitem.WriteClass(self)
  836. items = list(vtableItems.values())
  837. items.sort()
  838. for oleitem in items:
  839. self.progress.Tick()
  840. oleitem.WriteClass(self)
  841. else:
  842. self.progress.Tick(len(oleItems)+len(vtableItems))
  843. print('RecordMap = {', file=stream)
  844. for record in recordItems.values():
  845. if record.clsid == pythoncom.IID_NULL:
  846. print("\t###%s: %s, # Record disabled because it doesn't have a non-null GUID" % (repr(record.doc[0]), repr(str(record.clsid))), file=stream)
  847. else:
  848. print("\t%s: %s," % (repr(record.doc[0]), repr(str(record.clsid))), file=stream)
  849. print("}", file=stream)
  850. print(file=stream)
  851. # Write out _all_ my generated CLSID's in the map
  852. if self.generate_type == GEN_FULL:
  853. print('CLSIDToClassMap = {', file=stream)
  854. for item in oleItems.values():
  855. if item is not None and item.bWritten:
  856. print("\t'%s' : %s," % (str(item.clsid), item.python_name), file=stream)
  857. print('}', file=stream)
  858. print('CLSIDToPackageMap = {}', file=stream)
  859. print('win32com.client.CLSIDToClass.RegisterCLSIDsFromDict( CLSIDToClassMap )', file=stream)
  860. print("VTablesToPackageMap = {}", file=stream)
  861. print("VTablesToClassMap = {", file=stream)
  862. for item in vtableItems.values():
  863. print("\t'%s' : '%s'," % (item.clsid,item.python_name), file=stream)
  864. print('}', file=stream)
  865. print(file=stream)
  866. else:
  867. print('CLSIDToClassMap = {}', file=stream)
  868. print('CLSIDToPackageMap = {', file=stream)
  869. for item in oleItems.values():
  870. if item is not None:
  871. print("\t'%s' : %s," % (str(item.clsid), repr(item.python_name)), file=stream)
  872. print('}', file=stream)
  873. print("VTablesToClassMap = {}", file=stream)
  874. print("VTablesToPackageMap = {", file=stream)
  875. for item in vtableItems.values():
  876. print("\t'%s' : '%s'," % (item.clsid,item.python_name), file=stream)
  877. print('}', file=stream)
  878. print(file=stream)
  879. print(file=stream)
  880. # Bit of a hack - build a temp map of iteItems + vtableItems - coClasses
  881. map = {}
  882. for item in oleItems.values():
  883. if item is not None and not isinstance(item, CoClassItem):
  884. map[item.python_name] = item.clsid
  885. for item in vtableItems.values(): # No nones or CoClasses in this map
  886. map[item.python_name] = item.clsid
  887. print("NamesToIIDMap = {", file=stream)
  888. for name, iid in map.items():
  889. print("\t'%s' : '%s'," % (name, iid), file=stream)
  890. print('}', file=stream)
  891. print(file=stream)
  892. if enumItems:
  893. print('win32com.client.constants.__dicts__.append(constants.__dict__)', file=stream)
  894. print(file=stream)
  895. def generate_child(self, child, dir):
  896. "Generate a single child. May force a few children to be built as we generate deps"
  897. self.generate_type = GEN_DEMAND_CHILD
  898. la = self.typelib.GetLibAttr()
  899. lcid = la[1]
  900. clsid = la[0]
  901. major=la[3]
  902. minor=la[4]
  903. self.base_mod_name = "win32com.gen_py." + str(clsid)[1:-1] + "x%sx%sx%s" % (lcid, major, minor)
  904. try:
  905. # Process the type library's CoClass objects, looking for the
  906. # specified name, or where a child has the specified name.
  907. # This ensures that all interesting things (including event interfaces)
  908. # are generated correctly.
  909. oleItems = {}
  910. vtableItems = {}
  911. infos = self.CollectOleItemInfosFromType()
  912. found = 0
  913. for type_info_tuple in infos:
  914. info, infotype, doc, attr = type_info_tuple
  915. if infotype == pythoncom.TKIND_COCLASS:
  916. coClassItem, child_infos = self._Build_CoClass(type_info_tuple)
  917. found = build.MakePublicAttributeName(doc[0])==child
  918. if not found:
  919. # OK, check the child interfaces
  920. for info, info_type, refType, doc, refAttr, flags in child_infos:
  921. if build.MakePublicAttributeName(doc[0]) == child:
  922. found = 1
  923. break
  924. if found:
  925. oleItems[coClassItem.clsid] = coClassItem
  926. self._Build_CoClassChildren(coClassItem, child_infos, oleItems, vtableItems)
  927. break
  928. if not found:
  929. # Doesn't appear in a class defn - look in the interface objects for it
  930. for type_info_tuple in infos:
  931. info, infotype, doc, attr = type_info_tuple
  932. if infotype in [pythoncom.TKIND_INTERFACE, pythoncom.TKIND_DISPATCH]:
  933. if build.MakePublicAttributeName(doc[0]) == child:
  934. found = 1
  935. oleItem, vtableItem = self._Build_Interface(type_info_tuple)
  936. oleItems[clsid] = oleItem # Even "None" goes in here.
  937. if vtableItem is not None:
  938. vtableItems[clsid] = vtableItem
  939. assert found, "Cant find the '%s' interface in the CoClasses, or the interfaces" % (child,)
  940. # Make a map of iid: dispitem, vtableitem)
  941. items = {}
  942. for key, value in oleItems.items():
  943. items[key] = (value,None)
  944. for key, value in vtableItems.items():
  945. existing = items.get(key, None)
  946. if existing is not None:
  947. new_val = existing[0], value
  948. else:
  949. new_val = None, value
  950. items[key] = new_val
  951. self.progress.SetDescription("Generating...", len(items))
  952. for oleitem, vtableitem in items.values():
  953. an_item = oleitem or vtableitem
  954. assert not self.file, "already have a file?"
  955. # like makepy.py, we gen to a .temp file so failure doesn't
  956. # leave a 1/2 generated mess.
  957. out_name = os.path.join(dir, an_item.python_name) + ".py"
  958. worked = False
  959. self.file = self.open_writer(out_name)
  960. try:
  961. if oleitem is not None:
  962. self.do_gen_child_item(oleitem)
  963. if vtableitem is not None:
  964. self.do_gen_child_item(vtableitem)
  965. self.progress.Tick()
  966. worked = True
  967. finally:
  968. self.finish_writer(out_name, self.file, worked)
  969. self.file = None
  970. finally:
  971. self.progress.Finished()
  972. def do_gen_child_item(self, oleitem):
  973. moduleDoc = self.typelib.GetDocumentation(-1)
  974. docDesc = ""
  975. if moduleDoc[1]:
  976. docDesc = moduleDoc[1]
  977. self.progress.Starting(docDesc)
  978. self.progress.SetDescription("Building definitions from type library...")
  979. self.do_gen_file_header()
  980. oleitem.WriteClass(self)
  981. if oleitem.bWritten:
  982. print('win32com.client.CLSIDToClass.RegisterCLSID( "%s", %s )' % (oleitem.clsid, oleitem.python_name), file=self.file)
  983. def checkWriteDispatchBaseClass(self):
  984. if not self.bHaveWrittenDispatchBaseClass:
  985. print("from win32com.client import DispatchBaseClass", file=self.file)
  986. self.bHaveWrittenDispatchBaseClass = 1
  987. def checkWriteCoClassBaseClass(self):
  988. if not self.bHaveWrittenCoClassBaseClass:
  989. print("from win32com.client import CoClassBaseClass", file=self.file)
  990. self.bHaveWrittenCoClassBaseClass = 1
  991. def checkWriteEventBaseClass(self):
  992. # Not a base class as such...
  993. if not self.bHaveWrittenEventBaseClass:
  994. # Nothing to do any more!
  995. self.bHaveWrittenEventBaseClass = 1
  996. if __name__=='__main__':
  997. print("This is a worker module. Please use makepy to generate Python files.")