browser.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. """Module browser.
  2. XXX TO DO:
  3. - reparse when source changed (maybe just a button would be OK?)
  4. (or recheck on window popup)
  5. - add popup menu with more options (e.g. doc strings, base classes, imports)
  6. - add base classes to class browser tree
  7. - finish removing limitation to x.py files (ModuleBrowserTreeItem)
  8. """
  9. import os
  10. import pyclbr
  11. import sys
  12. from idlelib.config import idleConf
  13. from idlelib import pyshell
  14. from idlelib.tree import TreeNode, TreeItem, ScrolledCanvas
  15. from idlelib.window import ListedToplevel
  16. file_open = None # Method...Item and Class...Item use this.
  17. # Normally pyshell.flist.open, but there is no pyshell.flist for htest.
  18. def transform_children(child_dict, modname=None):
  19. """Transform a child dictionary to an ordered sequence of objects.
  20. The dictionary maps names to pyclbr information objects.
  21. Filter out imported objects.
  22. Augment class names with bases.
  23. The insertion order of the dictionary is assumed to have been in line
  24. number order, so sorting is not necessary.
  25. The current tree only calls this once per child_dict as it saves
  26. TreeItems once created. A future tree and tests might violate this,
  27. so a check prevents multiple in-place augmentations.
  28. """
  29. obs = [] # Use list since values should already be sorted.
  30. for key, obj in child_dict.items():
  31. if modname is None or obj.module == modname:
  32. if hasattr(obj, 'super') and obj.super and obj.name == key:
  33. # If obj.name != key, it has already been suffixed.
  34. supers = []
  35. for sup in obj.super:
  36. if type(sup) is type(''):
  37. sname = sup
  38. else:
  39. sname = sup.name
  40. if sup.module != obj.module:
  41. sname = f'{sup.module}.{sname}'
  42. supers.append(sname)
  43. obj.name += '({})'.format(', '.join(supers))
  44. obs.append(obj)
  45. return obs
  46. class ModuleBrowser:
  47. """Browse module classes and functions in IDLE.
  48. """
  49. # This class is also the base class for pathbrowser.PathBrowser.
  50. # Init and close are inherited, other methods are overridden.
  51. # PathBrowser.__init__ does not call __init__ below.
  52. def __init__(self, master, path, *, _htest=False, _utest=False):
  53. """Create a window for browsing a module's structure.
  54. Args:
  55. master: parent for widgets.
  56. path: full path of file to browse.
  57. _htest - bool; change box location when running htest.
  58. -utest - bool; suppress contents when running unittest.
  59. Global variables:
  60. file_open: Function used for opening a file.
  61. Instance variables:
  62. name: Module name.
  63. file: Full path and module with .py extension. Used in
  64. creating ModuleBrowserTreeItem as the rootnode for
  65. the tree and subsequently in the children.
  66. """
  67. self.master = master
  68. self.path = path
  69. self._htest = _htest
  70. self._utest = _utest
  71. self.init()
  72. def close(self, event=None):
  73. "Dismiss the window and the tree nodes."
  74. self.top.destroy()
  75. self.node.destroy()
  76. def init(self):
  77. "Create browser tkinter widgets, including the tree."
  78. global file_open
  79. root = self.master
  80. flist = (pyshell.flist if not (self._htest or self._utest)
  81. else pyshell.PyShellFileList(root))
  82. file_open = flist.open
  83. pyclbr._modules.clear()
  84. # create top
  85. self.top = top = ListedToplevel(root)
  86. top.protocol("WM_DELETE_WINDOW", self.close)
  87. top.bind("<Escape>", self.close)
  88. if self._htest: # place dialog below parent if running htest
  89. top.geometry("+%d+%d" %
  90. (root.winfo_rootx(), root.winfo_rooty() + 200))
  91. self.settitle()
  92. top.focus_set()
  93. # create scrolled canvas
  94. theme = idleConf.CurrentTheme()
  95. background = idleConf.GetHighlight(theme, 'normal')['background']
  96. sc = ScrolledCanvas(top, bg=background, highlightthickness=0,
  97. takefocus=1)
  98. sc.frame.pack(expand=1, fill="both")
  99. item = self.rootnode()
  100. self.node = node = TreeNode(sc.canvas, None, item)
  101. if not self._utest:
  102. node.update()
  103. node.expand()
  104. def settitle(self):
  105. "Set the window title."
  106. self.top.wm_title("Module Browser - " + os.path.basename(self.path))
  107. self.top.wm_iconname("Module Browser")
  108. def rootnode(self):
  109. "Return a ModuleBrowserTreeItem as the root of the tree."
  110. return ModuleBrowserTreeItem(self.path)
  111. class ModuleBrowserTreeItem(TreeItem):
  112. """Browser tree for Python module.
  113. Uses TreeItem as the basis for the structure of the tree.
  114. Used by both browsers.
  115. """
  116. def __init__(self, file):
  117. """Create a TreeItem for the file.
  118. Args:
  119. file: Full path and module name.
  120. """
  121. self.file = file
  122. def GetText(self):
  123. "Return the module name as the text string to display."
  124. return os.path.basename(self.file)
  125. def GetIconName(self):
  126. "Return the name of the icon to display."
  127. return "python"
  128. def GetSubList(self):
  129. "Return ChildBrowserTreeItems for children."
  130. return [ChildBrowserTreeItem(obj) for obj in self.listchildren()]
  131. def OnDoubleClick(self):
  132. "Open a module in an editor window when double clicked."
  133. if os.path.normcase(self.file[-3:]) != ".py":
  134. return
  135. if not os.path.exists(self.file):
  136. return
  137. file_open(self.file)
  138. def IsExpandable(self):
  139. "Return True if Python (.py) file."
  140. return os.path.normcase(self.file[-3:]) == ".py"
  141. def listchildren(self):
  142. "Return sequenced classes and functions in the module."
  143. dir, base = os.path.split(self.file)
  144. name, ext = os.path.splitext(base)
  145. if os.path.normcase(ext) != ".py":
  146. return []
  147. try:
  148. tree = pyclbr.readmodule_ex(name, [dir] + sys.path)
  149. except ImportError:
  150. return []
  151. return transform_children(tree, name)
  152. class ChildBrowserTreeItem(TreeItem):
  153. """Browser tree for child nodes within the module.
  154. Uses TreeItem as the basis for the structure of the tree.
  155. """
  156. def __init__(self, obj):
  157. "Create a TreeItem for a pyclbr class/function object."
  158. self.obj = obj
  159. self.name = obj.name
  160. self.isfunction = isinstance(obj, pyclbr.Function)
  161. def GetText(self):
  162. "Return the name of the function/class to display."
  163. name = self.name
  164. if self.isfunction:
  165. return "def " + name + "(...)"
  166. else:
  167. return "class " + name
  168. def GetIconName(self):
  169. "Return the name of the icon to display."
  170. if self.isfunction:
  171. return "python"
  172. else:
  173. return "folder"
  174. def IsExpandable(self):
  175. "Return True if self.obj has nested objects."
  176. return self.obj.children != {}
  177. def GetSubList(self):
  178. "Return ChildBrowserTreeItems for children."
  179. return [ChildBrowserTreeItem(obj)
  180. for obj in transform_children(self.obj.children)]
  181. def OnDoubleClick(self):
  182. "Open module with file_open and position to lineno."
  183. try:
  184. edit = file_open(self.obj.file)
  185. edit.gotoline(self.obj.lineno)
  186. except (OSError, AttributeError):
  187. pass
  188. def _module_browser(parent): # htest #
  189. if len(sys.argv) > 1: # If pass file on command line.
  190. file = sys.argv[1]
  191. else:
  192. file = __file__
  193. # Add nested objects for htest.
  194. class Nested_in_func(TreeNode):
  195. def nested_in_class(): pass
  196. def closure():
  197. class Nested_in_closure: pass
  198. ModuleBrowser(parent, file, _htest=True)
  199. if __name__ == "__main__":
  200. if len(sys.argv) == 1: # If pass file on command line, unittest fails.
  201. from unittest import main
  202. main('idlelib.idle_test.test_browser', verbosity=2, exit=False)
  203. from idlelib.idle_test.htest import run
  204. run(_module_browser)