combrowse.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. """A utility for browsing COM objects.
  2. Usage:
  3. Command Prompt
  4. Use the command *"python.exe catbrowse.py"*. This will display
  5. display a fairly small, modal dialog.
  6. Pythonwin
  7. Use the "Run Script" menu item, and this will create the browser in an
  8. MDI window. This window can be fully resized.
  9. Details
  10. This module allows browsing of registered Type Libraries, COM categories,
  11. and running COM objects. The display is similar to the Pythonwin object
  12. browser, and displays the objects in a hierarchical window.
  13. Note that this module requires the win32ui (ie, Pythonwin) distribution to
  14. work.
  15. """
  16. import win32con
  17. import win32api, win32ui
  18. import sys
  19. import pythoncom
  20. from win32com.client import util
  21. from pywin.tools import browser
  22. class HLIRoot(browser.HLIPythonObject):
  23. def __init__(self, title):
  24. self.name = title
  25. def GetSubList(self):
  26. return [HLIHeadingCategory(), HLI_IEnumMoniker(pythoncom.GetRunningObjectTable().EnumRunning(), "Running Objects"), HLIHeadingRegisterdTypeLibs()]
  27. def __cmp__(self, other):
  28. return cmp(self.name, other.name)
  29. class HLICOM(browser.HLIPythonObject):
  30. def GetText(self):
  31. return self.name
  32. def CalculateIsExpandable(self):
  33. return 1
  34. class HLICLSID(HLICOM):
  35. def __init__(self, myobject, name=None ):
  36. if type(myobject)==type(''):
  37. myobject = pythoncom.MakeIID(myobject)
  38. if name is None:
  39. try:
  40. name = pythoncom.ProgIDFromCLSID(myobject)
  41. except pythoncom.com_error:
  42. name = str(myobject)
  43. name = "IID: " + name
  44. HLICOM.__init__(self, myobject, name)
  45. def CalculateIsExpandable(self):
  46. return 0
  47. def GetSubList(self):
  48. return []
  49. class HLI_Interface(HLICOM):
  50. pass
  51. class HLI_Enum(HLI_Interface):
  52. def GetBitmapColumn(self):
  53. return 0 # Always a folder.
  54. def CalculateIsExpandable(self):
  55. if self.myobject is not None:
  56. rc = len(self.myobject.Next(1))>0
  57. self.myobject.Reset()
  58. else:
  59. rc = 0
  60. return rc
  61. pass
  62. class HLI_IEnumMoniker(HLI_Enum):
  63. def GetSubList(self):
  64. ctx = pythoncom.CreateBindCtx()
  65. ret = []
  66. for mon in util.Enumerator(self.myobject):
  67. ret.append(HLI_IMoniker(mon, mon.GetDisplayName(ctx, None)))
  68. return ret
  69. class HLI_IMoniker(HLI_Interface):
  70. def GetSubList(self):
  71. ret = []
  72. ret.append(browser.MakeHLI(self.myobject.Hash(), "Hash Value"))
  73. subenum = self.myobject.Enum(1)
  74. ret.append(HLI_IEnumMoniker(subenum, "Sub Monikers"))
  75. return ret
  76. class HLIHeadingCategory(HLICOM):
  77. "A tree heading for registered categories"
  78. def GetText(self):
  79. return "Registered Categories"
  80. def GetSubList(self):
  81. catinf=pythoncom.CoCreateInstance(pythoncom.CLSID_StdComponentCategoriesMgr,None,pythoncom.CLSCTX_INPROC,pythoncom.IID_ICatInformation)
  82. enum=util.Enumerator(catinf.EnumCategories())
  83. ret = []
  84. try:
  85. for catid, lcid, desc in enum:
  86. ret.append(HLICategory((catid, lcid, desc)))
  87. except pythoncom.com_error:
  88. # Registered categories occasionally seem to give spurious errors.
  89. pass # Use what we already have.
  90. return ret
  91. class HLICategory(HLICOM):
  92. "An actual Registered Category"
  93. def GetText(self):
  94. desc = self.myobject[2]
  95. if not desc: desc = "(unnamed category)"
  96. return desc
  97. def GetSubList(self):
  98. win32ui.DoWaitCursor(1)
  99. catid, lcid, desc = self.myobject
  100. catinf=pythoncom.CoCreateInstance(pythoncom.CLSID_StdComponentCategoriesMgr,None,pythoncom.CLSCTX_INPROC,pythoncom.IID_ICatInformation)
  101. ret = []
  102. for clsid in util.Enumerator(catinf.EnumClassesOfCategories((catid,),())):
  103. ret.append(HLICLSID(clsid))
  104. win32ui.DoWaitCursor(0)
  105. return ret
  106. class HLIHelpFile(HLICOM):
  107. def CalculateIsExpandable(self):
  108. return 0
  109. def GetText(self):
  110. import os
  111. fname, ctx = self.myobject
  112. base = os.path.split(fname)[1]
  113. return "Help reference in %s" %( base)
  114. def TakeDefaultAction(self):
  115. fname, ctx = self.myobject
  116. if ctx:
  117. cmd = win32con.HELP_CONTEXT
  118. else:
  119. cmd = win32con.HELP_FINDER
  120. win32api.WinHelp(win32ui.GetMainFrame().GetSafeHwnd(), fname, cmd, ctx)
  121. def GetBitmapColumn(self):
  122. return 6
  123. class HLIRegisteredTypeLibrary(HLICOM):
  124. def GetSubList(self):
  125. import os
  126. clsidstr, versionStr = self.myobject
  127. collected = []
  128. helpPath = ""
  129. key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "TypeLib\\%s\\%s" % (clsidstr, versionStr))
  130. win32ui.DoWaitCursor(1)
  131. try:
  132. num = 0
  133. while 1:
  134. try:
  135. subKey = win32api.RegEnumKey(key, num)
  136. except win32api.error:
  137. break
  138. hSubKey = win32api.RegOpenKey(key, subKey)
  139. try:
  140. value, typ = win32api.RegQueryValueEx(hSubKey, None)
  141. if typ == win32con.REG_EXPAND_SZ:
  142. value = win32api.ExpandEnvironmentStrings(value)
  143. except win32api.error:
  144. value = ""
  145. if subKey=="HELPDIR":
  146. helpPath = value
  147. elif subKey=="Flags":
  148. flags = value
  149. else:
  150. try:
  151. lcid = int(subKey)
  152. lcidkey = win32api.RegOpenKey(key, subKey)
  153. # Enumerate the platforms
  154. lcidnum = 0
  155. while 1:
  156. try:
  157. platform = win32api.RegEnumKey(lcidkey, lcidnum)
  158. except win32api.error:
  159. break
  160. try:
  161. hplatform = win32api.RegOpenKey(lcidkey, platform)
  162. fname, typ = win32api.RegQueryValueEx(hplatform, None)
  163. if typ == win32con.REG_EXPAND_SZ:
  164. fname = win32api.ExpandEnvironmentStrings(fname)
  165. except win32api.error:
  166. fname = ""
  167. collected.append((lcid, platform, fname))
  168. lcidnum = lcidnum + 1
  169. win32api.RegCloseKey(lcidkey)
  170. except ValueError:
  171. pass
  172. num = num + 1
  173. finally:
  174. win32ui.DoWaitCursor(0)
  175. win32api.RegCloseKey(key)
  176. # Now, loop over my collected objects, adding a TypeLib and a HelpFile
  177. ret = []
  178. # if helpPath: ret.append(browser.MakeHLI(helpPath, "Help Path"))
  179. ret.append(HLICLSID(clsidstr))
  180. for lcid, platform, fname in collected:
  181. extraDescs = []
  182. if platform!="win32":
  183. extraDescs.append(platform)
  184. if lcid:
  185. extraDescs.append("locale=%s"%lcid)
  186. extraDesc = ""
  187. if extraDescs: extraDesc = " (%s)" % ", ".join(extraDescs)
  188. ret.append(HLITypeLib(fname, "Type Library" + extraDesc))
  189. ret.sort()
  190. return ret
  191. class HLITypeLibEntry(HLICOM):
  192. def GetText(self):
  193. tlb, index = self.myobject
  194. name, doc, ctx, helpFile = tlb.GetDocumentation(index)
  195. try:
  196. typedesc = HLITypeKinds[tlb.GetTypeInfoType(index)][1]
  197. except KeyError:
  198. typedesc = "Unknown!"
  199. return name + " - " + typedesc
  200. def GetSubList(self):
  201. tlb, index = self.myobject
  202. name, doc, ctx, helpFile = tlb.GetDocumentation(index)
  203. ret = []
  204. if doc: ret.append(browser.HLIDocString(doc, "Doc"))
  205. if helpFile: ret.append(HLIHelpFile( (helpFile, ctx) ))
  206. return ret
  207. class HLICoClass(HLITypeLibEntry):
  208. def GetSubList(self):
  209. ret = HLITypeLibEntry.GetSubList(self)
  210. tlb, index = self.myobject
  211. typeinfo = tlb.GetTypeInfo(index)
  212. attr = typeinfo.GetTypeAttr()
  213. for j in range(attr[8]):
  214. flags = typeinfo.GetImplTypeFlags(j)
  215. refType = typeinfo.GetRefTypeInfo(typeinfo.GetRefTypeOfImplType(j))
  216. refAttr = refType.GetTypeAttr()
  217. ret.append(browser.MakeHLI(refAttr[0], "Name=%s, Flags = %d" % (refAttr[0], flags)))
  218. return ret
  219. class HLITypeLibMethod(HLITypeLibEntry):
  220. def __init__(self, ob, name = None):
  221. self.entry_type = "Method"
  222. HLITypeLibEntry.__init__(self, ob, name)
  223. def GetSubList(self):
  224. ret = HLITypeLibEntry.GetSubList(self)
  225. tlb, index = self.myobject
  226. typeinfo = tlb.GetTypeInfo(index)
  227. attr = typeinfo.GetTypeAttr()
  228. for i in range(attr[7]):
  229. ret.append(HLITypeLibProperty((typeinfo, i)))
  230. for i in range(attr[6]):
  231. ret.append(HLITypeLibFunction((typeinfo, i)))
  232. return ret
  233. class HLITypeLibEnum(HLITypeLibEntry):
  234. def __init__(self, myitem):
  235. typelib, index = myitem
  236. typeinfo = typelib.GetTypeInfo(index)
  237. self.id = typeinfo.GetVarDesc(index)[0]
  238. name = typeinfo.GetNames(self.id)[0]
  239. HLITypeLibEntry.__init__(self, myitem, name)
  240. def GetText(self):
  241. return self.name + " - Enum/Module"
  242. def GetSubList(self):
  243. ret = []
  244. typelib, index = self.myobject
  245. typeinfo = typelib.GetTypeInfo(index)
  246. attr = typeinfo.GetTypeAttr()
  247. for j in range(attr[7]):
  248. vdesc = typeinfo.GetVarDesc(j)
  249. name = typeinfo.GetNames(vdesc[0])[0]
  250. ret.append(browser.MakeHLI(vdesc[1], name))
  251. return ret
  252. class HLITypeLibProperty(HLICOM):
  253. def __init__(self, myitem):
  254. typeinfo, index = myitem
  255. self.id = typeinfo.GetVarDesc(index)[0]
  256. name = typeinfo.GetNames(self.id)[0]
  257. HLICOM.__init__(self, myitem, name)
  258. def GetText(self):
  259. return self.name + " - Property"
  260. def GetSubList(self):
  261. ret = []
  262. typeinfo, index = self.myobject
  263. names = typeinfo.GetNames(self.id)
  264. if len(names)>1:
  265. ret.append(browser.MakeHLI(names[1:], "Named Params"))
  266. vd = typeinfo.GetVarDesc(index)
  267. ret.append(browser.MakeHLI(self.id, "Dispatch ID"))
  268. ret.append(browser.MakeHLI(vd[1], "Value"))
  269. ret.append(browser.MakeHLI(vd[2], "Elem Desc"))
  270. ret.append(browser.MakeHLI(vd[3], "Var Flags"))
  271. ret.append(browser.MakeHLI(vd[4], "Var Kind"))
  272. return ret
  273. class HLITypeLibFunction(HLICOM):
  274. funckinds = {pythoncom.FUNC_VIRTUAL : "Virtual",
  275. pythoncom.FUNC_PUREVIRTUAL : "Pure Virtual",
  276. pythoncom.FUNC_STATIC : "Static",
  277. pythoncom.FUNC_DISPATCH : "Dispatch",
  278. }
  279. invokekinds = {pythoncom.INVOKE_FUNC: "Function",
  280. pythoncom.INVOKE_PROPERTYGET : "Property Get",
  281. pythoncom.INVOKE_PROPERTYPUT : "Property Put",
  282. pythoncom.INVOKE_PROPERTYPUTREF : "Property Put by reference",
  283. }
  284. funcflags = [(pythoncom.FUNCFLAG_FRESTRICTED, "Restricted"),
  285. (pythoncom.FUNCFLAG_FSOURCE, "Source"),
  286. (pythoncom.FUNCFLAG_FBINDABLE, "Bindable"),
  287. (pythoncom.FUNCFLAG_FREQUESTEDIT, "Request Edit"),
  288. (pythoncom.FUNCFLAG_FDISPLAYBIND, "Display Bind"),
  289. (pythoncom.FUNCFLAG_FDEFAULTBIND, "Default Bind"),
  290. (pythoncom.FUNCFLAG_FHIDDEN, "Hidden"),
  291. (pythoncom.FUNCFLAG_FUSESGETLASTERROR, "Uses GetLastError"),
  292. ]
  293. vartypes = {pythoncom.VT_EMPTY: "Empty",
  294. pythoncom.VT_NULL: "NULL",
  295. pythoncom.VT_I2: "Integer 2",
  296. pythoncom.VT_I4: "Integer 4",
  297. pythoncom.VT_R4: "Real 4",
  298. pythoncom.VT_R8: "Real 8",
  299. pythoncom.VT_CY: "CY",
  300. pythoncom.VT_DATE: "Date",
  301. pythoncom.VT_BSTR: "String",
  302. pythoncom.VT_DISPATCH: "IDispatch",
  303. pythoncom.VT_ERROR: "Error",
  304. pythoncom.VT_BOOL: "BOOL",
  305. pythoncom.VT_VARIANT: "Variant",
  306. pythoncom.VT_UNKNOWN: "IUnknown",
  307. pythoncom.VT_DECIMAL: "Decimal",
  308. pythoncom.VT_I1: "Integer 1",
  309. pythoncom.VT_UI1: "Unsigned integer 1",
  310. pythoncom.VT_UI2: "Unsigned integer 2",
  311. pythoncom.VT_UI4: "Unsigned integer 4",
  312. pythoncom.VT_I8: "Integer 8",
  313. pythoncom.VT_UI8: "Unsigned integer 8",
  314. pythoncom.VT_INT: "Integer",
  315. pythoncom.VT_UINT: "Unsigned integer",
  316. pythoncom.VT_VOID: "Void",
  317. pythoncom.VT_HRESULT: "HRESULT",
  318. pythoncom.VT_PTR: "Pointer",
  319. pythoncom.VT_SAFEARRAY: "SafeArray",
  320. pythoncom.VT_CARRAY: "C Array",
  321. pythoncom.VT_USERDEFINED: "User Defined",
  322. pythoncom.VT_LPSTR: "Pointer to string",
  323. pythoncom.VT_LPWSTR: "Pointer to Wide String",
  324. pythoncom.VT_FILETIME: "File time",
  325. pythoncom.VT_BLOB: "Blob",
  326. pythoncom.VT_STREAM: "IStream",
  327. pythoncom.VT_STORAGE: "IStorage",
  328. pythoncom.VT_STORED_OBJECT: "Stored object",
  329. pythoncom.VT_STREAMED_OBJECT: "Streamed object",
  330. pythoncom.VT_BLOB_OBJECT: "Blob object",
  331. pythoncom.VT_CF: "CF",
  332. pythoncom.VT_CLSID: "CLSID",
  333. }
  334. type_flags = [ (pythoncom.VT_VECTOR, "Vector"),
  335. (pythoncom.VT_ARRAY, "Array"),
  336. (pythoncom.VT_BYREF, "ByRef"),
  337. (pythoncom.VT_RESERVED, "Reserved"),
  338. ]
  339. def __init__(self, myitem):
  340. typeinfo, index = myitem
  341. self.id = typeinfo.GetFuncDesc(index)[0]
  342. name = typeinfo.GetNames(self.id)[0]
  343. HLICOM.__init__(self, myitem, name)
  344. def GetText(self):
  345. return self.name + " - Function"
  346. def MakeReturnTypeName(self, typ):
  347. justtyp = typ & pythoncom.VT_TYPEMASK
  348. try:
  349. typname = self.vartypes[justtyp]
  350. except KeyError:
  351. typname = "?Bad type?"
  352. for (flag, desc) in self.type_flags:
  353. if flag & typ:
  354. typname = "%s(%s)" % (desc, typname)
  355. return typname
  356. def MakeReturnType(self, returnTypeDesc):
  357. if type(returnTypeDesc)==type(()):
  358. first = returnTypeDesc[0]
  359. result = self.MakeReturnType(first)
  360. if first != pythoncom.VT_USERDEFINED:
  361. result = result + " " + self.MakeReturnType(returnTypeDesc[1])
  362. return result
  363. else:
  364. return self.MakeReturnTypeName(returnTypeDesc)
  365. def GetSubList(self):
  366. ret = []
  367. typeinfo, index = self.myobject
  368. names = typeinfo.GetNames(self.id)
  369. ret.append(browser.MakeHLI(self.id, "Dispatch ID"))
  370. if len(names)>1:
  371. ret.append(browser.MakeHLI(", ".join(names[1:]), "Named Params"))
  372. fd = typeinfo.GetFuncDesc(index)
  373. if fd[1]:
  374. ret.append(browser.MakeHLI(fd[1], "Possible result values"))
  375. if fd[8]:
  376. typ, flags, default = fd[8]
  377. val = self.MakeReturnType(typ)
  378. if flags:
  379. val = "%s (Flags=%d, default=%s)" % (val, flags, default)
  380. ret.append(browser.MakeHLI(val, "Return Type"))
  381. for argDesc in fd[2]:
  382. typ, flags, default = argDesc
  383. val = self.MakeReturnType(typ)
  384. if flags:
  385. val = "%s (Flags=%d)" % (val, flags)
  386. if default is not None:
  387. val = "%s (Default=%s)" % (val, default)
  388. ret.append(browser.MakeHLI(val, "Argument"))
  389. try:
  390. fkind = self.funckinds[fd[3]]
  391. except KeyError:
  392. fkind = "Unknown"
  393. ret.append(browser.MakeHLI(fkind, "Function Kind"))
  394. try:
  395. ikind = self.invokekinds[fd[4]]
  396. except KeyError:
  397. ikind = "Unknown"
  398. ret.append(browser.MakeHLI(ikind, "Invoke Kind"))
  399. # 5 = call conv
  400. # 5 = offset vtbl
  401. ret.append(browser.MakeHLI(fd[6], "Number Optional Params"))
  402. flagDescs = []
  403. for flag, desc in self.funcflags:
  404. if flag & fd[9]:
  405. flagDescs.append(desc)
  406. if flagDescs:
  407. ret.append(browser.MakeHLI(", ".join(flagDescs), "Function Flags"))
  408. return ret
  409. HLITypeKinds = {
  410. pythoncom.TKIND_ENUM : (HLITypeLibEnum, 'Enumeration'),
  411. pythoncom.TKIND_RECORD : (HLITypeLibEntry, 'Record'),
  412. pythoncom.TKIND_MODULE : (HLITypeLibEnum, 'Module'),
  413. pythoncom.TKIND_INTERFACE : (HLITypeLibMethod, 'Interface'),
  414. pythoncom.TKIND_DISPATCH : (HLITypeLibMethod, 'Dispatch'),
  415. pythoncom.TKIND_COCLASS : (HLICoClass, 'CoClass'),
  416. pythoncom.TKIND_ALIAS : (HLITypeLibEntry, 'Alias'),
  417. pythoncom.TKIND_UNION : (HLITypeLibEntry, 'Union')
  418. }
  419. class HLITypeLib(HLICOM):
  420. def GetSubList(self):
  421. ret = []
  422. ret.append(browser.MakeHLI(self.myobject, "Filename"))
  423. try:
  424. tlb = pythoncom.LoadTypeLib(self.myobject)
  425. except pythoncom.com_error:
  426. return [browser.MakeHLI("%s can not be loaded" % self.myobject)]
  427. for i in range(tlb.GetTypeInfoCount()):
  428. try:
  429. ret.append(HLITypeKinds[tlb.GetTypeInfoType(i)][0]( (tlb, i) ) )
  430. except pythoncom.com_error:
  431. ret.append(browser.MakeHLI("The type info can not be loaded!"))
  432. ret.sort()
  433. return ret
  434. class HLIHeadingRegisterdTypeLibs(HLICOM):
  435. "A tree heading for registered type libraries"
  436. def GetText(self):
  437. return "Registered Type Libraries"
  438. def GetSubList(self):
  439. # Explicit lookup in the registry.
  440. ret = []
  441. key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "TypeLib")
  442. win32ui.DoWaitCursor(1)
  443. try:
  444. num = 0
  445. while 1:
  446. try:
  447. keyName = win32api.RegEnumKey(key, num)
  448. except win32api.error:
  449. break
  450. # Enumerate all version info
  451. subKey = win32api.RegOpenKey(key, keyName)
  452. name = None
  453. try:
  454. subNum = 0
  455. bestVersion = 0.0
  456. while 1:
  457. try:
  458. versionStr = win32api.RegEnumKey(subKey, subNum)
  459. except win32api.error:
  460. break
  461. try:
  462. versionFlt = float(versionStr)
  463. except ValueError:
  464. versionFlt = 0 # ????
  465. if versionFlt > bestVersion:
  466. bestVersion = versionFlt
  467. name = win32api.RegQueryValue(subKey, versionStr)
  468. subNum = subNum + 1
  469. finally:
  470. win32api.RegCloseKey(subKey)
  471. if name is not None:
  472. ret.append(HLIRegisteredTypeLibrary((keyName, versionStr), name))
  473. num = num + 1
  474. finally:
  475. win32api.RegCloseKey(key)
  476. win32ui.DoWaitCursor(0)
  477. ret.sort()
  478. return ret
  479. def main(modal=False):
  480. from pywin.tools import hierlist
  481. root = HLIRoot("COM Browser")
  482. if "app" in sys.modules:
  483. # do it in a window
  484. browser.MakeTemplate()
  485. browser.template.OpenObject(root)
  486. else:
  487. # list=hierlist.HierListWithItems( root, win32ui.IDB_BROWSER_HIER )
  488. # dlg=hierlist.HierDialog("COM Browser",list)
  489. dlg = browser.dynamic_browser(root)
  490. if modal:
  491. dlg.DoModal()
  492. else:
  493. dlg.CreateWindow()
  494. dlg.ShowWindow()
  495. if __name__=='__main__':
  496. main()
  497. ni = pythoncom._GetInterfaceCount()
  498. ng = pythoncom._GetGatewayCount()
  499. if ni or ng:
  500. print("Warning - exiting with %d/%d objects alive" % (ni,ng))