Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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