tree.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. # XXX TO DO:
  2. # - popup menu
  3. # - support partial or total redisplay
  4. # - key bindings (instead of quick-n-dirty bindings on Canvas):
  5. # - up/down arrow keys to move focus around
  6. # - ditto for page up/down, home/end
  7. # - left/right arrows to expand/collapse & move out/in
  8. # - more doc strings
  9. # - add icons for "file", "module", "class", "method"; better "python" icon
  10. # - callback for selection???
  11. # - multiple-item selection
  12. # - tooltips
  13. # - redo geometry without magic numbers
  14. # - keep track of object ids to allow more careful cleaning
  15. # - optimize tree redraw after expand of subnode
  16. import os
  17. from tkinter import *
  18. from tkinter.ttk import Frame, Scrollbar
  19. from idlelib.config import idleConf
  20. from idlelib import zoomheight
  21. ICONDIR = "Icons"
  22. # Look for Icons subdirectory in the same directory as this module
  23. try:
  24. _icondir = os.path.join(os.path.dirname(__file__), ICONDIR)
  25. except NameError:
  26. _icondir = ICONDIR
  27. if os.path.isdir(_icondir):
  28. ICONDIR = _icondir
  29. elif not os.path.isdir(ICONDIR):
  30. raise RuntimeError(f"can't find icon directory ({ICONDIR!r})")
  31. def listicons(icondir=ICONDIR):
  32. """Utility to display the available icons."""
  33. root = Tk()
  34. import glob
  35. list = glob.glob(os.path.join(glob.escape(icondir), "*.gif"))
  36. list.sort()
  37. images = []
  38. row = column = 0
  39. for file in list:
  40. name = os.path.splitext(os.path.basename(file))[0]
  41. image = PhotoImage(file=file, master=root)
  42. images.append(image)
  43. label = Label(root, image=image, bd=1, relief="raised")
  44. label.grid(row=row, column=column)
  45. label = Label(root, text=name)
  46. label.grid(row=row+1, column=column)
  47. column = column + 1
  48. if column >= 10:
  49. row = row+2
  50. column = 0
  51. root.images = images
  52. def wheel_event(event, widget=None):
  53. """Handle scrollwheel event.
  54. For wheel up, event.delta = 120*n on Windows, -1*n on darwin,
  55. where n can be > 1 if one scrolls fast. Flicking the wheel
  56. generates up to maybe 20 events with n up to 10 or more 1.
  57. Macs use wheel down (delta = 1*n) to scroll up, so positive
  58. delta means to scroll up on both systems.
  59. X-11 sends Control-Button-4,5 events instead.
  60. The widget parameter is needed so browser label bindings can pass
  61. the underlying canvas.
  62. This function depends on widget.yview to not be overridden by
  63. a subclass.
  64. """
  65. up = {EventType.MouseWheel: event.delta > 0,
  66. EventType.ButtonPress: event.num == 4}
  67. lines = -5 if up[event.type] else 5
  68. widget = event.widget if widget is None else widget
  69. widget.yview(SCROLL, lines, 'units')
  70. return 'break'
  71. class TreeNode:
  72. def __init__(self, canvas, parent, item):
  73. self.canvas = canvas
  74. self.parent = parent
  75. self.item = item
  76. self.state = 'collapsed'
  77. self.selected = False
  78. self.children = []
  79. self.x = self.y = None
  80. self.iconimages = {} # cache of PhotoImage instances for icons
  81. def destroy(self):
  82. for c in self.children[:]:
  83. self.children.remove(c)
  84. c.destroy()
  85. self.parent = None
  86. def geticonimage(self, name):
  87. try:
  88. return self.iconimages[name]
  89. except KeyError:
  90. pass
  91. file, ext = os.path.splitext(name)
  92. ext = ext or ".gif"
  93. fullname = os.path.join(ICONDIR, file + ext)
  94. image = PhotoImage(master=self.canvas, file=fullname)
  95. self.iconimages[name] = image
  96. return image
  97. def select(self, event=None):
  98. if self.selected:
  99. return
  100. self.deselectall()
  101. self.selected = True
  102. self.canvas.delete(self.image_id)
  103. self.drawicon()
  104. self.drawtext()
  105. def deselect(self, event=None):
  106. if not self.selected:
  107. return
  108. self.selected = False
  109. self.canvas.delete(self.image_id)
  110. self.drawicon()
  111. self.drawtext()
  112. def deselectall(self):
  113. if self.parent:
  114. self.parent.deselectall()
  115. else:
  116. self.deselecttree()
  117. def deselecttree(self):
  118. if self.selected:
  119. self.deselect()
  120. for child in self.children:
  121. child.deselecttree()
  122. def flip(self, event=None):
  123. if self.state == 'expanded':
  124. self.collapse()
  125. else:
  126. self.expand()
  127. self.item.OnDoubleClick()
  128. return "break"
  129. def expand(self, event=None):
  130. if not self.item._IsExpandable():
  131. return
  132. if self.state != 'expanded':
  133. self.state = 'expanded'
  134. self.update()
  135. self.view()
  136. def collapse(self, event=None):
  137. if self.state != 'collapsed':
  138. self.state = 'collapsed'
  139. self.update()
  140. def view(self):
  141. top = self.y - 2
  142. bottom = self.lastvisiblechild().y + 17
  143. height = bottom - top
  144. visible_top = self.canvas.canvasy(0)
  145. visible_height = self.canvas.winfo_height()
  146. visible_bottom = self.canvas.canvasy(visible_height)
  147. if visible_top <= top and bottom <= visible_bottom:
  148. return
  149. x0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion'])
  150. if top >= visible_top and height <= visible_height:
  151. fraction = top + height - visible_height
  152. else:
  153. fraction = top
  154. fraction = float(fraction) / y1
  155. self.canvas.yview_moveto(fraction)
  156. def lastvisiblechild(self):
  157. if self.children and self.state == 'expanded':
  158. return self.children[-1].lastvisiblechild()
  159. else:
  160. return self
  161. def update(self):
  162. if self.parent:
  163. self.parent.update()
  164. else:
  165. oldcursor = self.canvas['cursor']
  166. self.canvas['cursor'] = "watch"
  167. self.canvas.update()
  168. self.canvas.delete(ALL) # XXX could be more subtle
  169. self.draw(7, 2)
  170. x0, y0, x1, y1 = self.canvas.bbox(ALL)
  171. self.canvas.configure(scrollregion=(0, 0, x1, y1))
  172. self.canvas['cursor'] = oldcursor
  173. def draw(self, x, y):
  174. # XXX This hard-codes too many geometry constants!
  175. dy = 20
  176. self.x, self.y = x, y
  177. self.drawicon()
  178. self.drawtext()
  179. if self.state != 'expanded':
  180. return y + dy
  181. # draw children
  182. if not self.children:
  183. sublist = self.item._GetSubList()
  184. if not sublist:
  185. # _IsExpandable() was mistaken; that's allowed
  186. return y+17
  187. for item in sublist:
  188. child = self.__class__(self.canvas, self, item)
  189. self.children.append(child)
  190. cx = x+20
  191. cy = y + dy
  192. cylast = 0
  193. for child in self.children:
  194. cylast = cy
  195. self.canvas.create_line(x+9, cy+7, cx, cy+7, fill="gray50")
  196. cy = child.draw(cx, cy)
  197. if child.item._IsExpandable():
  198. if child.state == 'expanded':
  199. iconname = "minusnode"
  200. callback = child.collapse
  201. else:
  202. iconname = "plusnode"
  203. callback = child.expand
  204. image = self.geticonimage(iconname)
  205. id = self.canvas.create_image(x+9, cylast+7, image=image)
  206. # XXX This leaks bindings until canvas is deleted:
  207. self.canvas.tag_bind(id, "<1>", callback)
  208. self.canvas.tag_bind(id, "<Double-1>", lambda x: None)
  209. id = self.canvas.create_line(x+9, y+10, x+9, cylast+7,
  210. ##stipple="gray50", # XXX Seems broken in Tk 8.0.x
  211. fill="gray50")
  212. self.canvas.tag_lower(id) # XXX .lower(id) before Python 1.5.2
  213. return cy
  214. def drawicon(self):
  215. if self.selected:
  216. imagename = (self.item.GetSelectedIconName() or
  217. self.item.GetIconName() or
  218. "openfolder")
  219. else:
  220. imagename = self.item.GetIconName() or "folder"
  221. image = self.geticonimage(imagename)
  222. id = self.canvas.create_image(self.x, self.y, anchor="nw", image=image)
  223. self.image_id = id
  224. self.canvas.tag_bind(id, "<1>", self.select)
  225. self.canvas.tag_bind(id, "<Double-1>", self.flip)
  226. def drawtext(self):
  227. textx = self.x+20-1
  228. texty = self.y-4
  229. labeltext = self.item.GetLabelText()
  230. if labeltext:
  231. id = self.canvas.create_text(textx, texty, anchor="nw",
  232. text=labeltext)
  233. self.canvas.tag_bind(id, "<1>", self.select)
  234. self.canvas.tag_bind(id, "<Double-1>", self.flip)
  235. x0, y0, x1, y1 = self.canvas.bbox(id)
  236. textx = max(x1, 200) + 10
  237. text = self.item.GetText() or "<no text>"
  238. try:
  239. self.entry
  240. except AttributeError:
  241. pass
  242. else:
  243. self.edit_finish()
  244. try:
  245. self.label
  246. except AttributeError:
  247. # padding carefully selected (on Windows) to match Entry widget:
  248. self.label = Label(self.canvas, text=text, bd=0, padx=2, pady=2)
  249. theme = idleConf.CurrentTheme()
  250. if self.selected:
  251. self.label.configure(idleConf.GetHighlight(theme, 'hilite'))
  252. else:
  253. self.label.configure(idleConf.GetHighlight(theme, 'normal'))
  254. id = self.canvas.create_window(textx, texty,
  255. anchor="nw", window=self.label)
  256. self.label.bind("<1>", self.select_or_edit)
  257. self.label.bind("<Double-1>", self.flip)
  258. self.label.bind("<MouseWheel>", lambda e: wheel_event(e, self.canvas))
  259. self.label.bind("<Button-4>", lambda e: wheel_event(e, self.canvas))
  260. self.label.bind("<Button-5>", lambda e: wheel_event(e, self.canvas))
  261. self.text_id = id
  262. def select_or_edit(self, event=None):
  263. if self.selected and self.item.IsEditable():
  264. self.edit(event)
  265. else:
  266. self.select(event)
  267. def edit(self, event=None):
  268. self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0)
  269. self.entry.insert(0, self.label['text'])
  270. self.entry.selection_range(0, END)
  271. self.entry.pack(ipadx=5)
  272. self.entry.focus_set()
  273. self.entry.bind("<Return>", self.edit_finish)
  274. self.entry.bind("<Escape>", self.edit_cancel)
  275. def edit_finish(self, event=None):
  276. try:
  277. entry = self.entry
  278. del self.entry
  279. except AttributeError:
  280. return
  281. text = entry.get()
  282. entry.destroy()
  283. if text and text != self.item.GetText():
  284. self.item.SetText(text)
  285. text = self.item.GetText()
  286. self.label['text'] = text
  287. self.drawtext()
  288. self.canvas.focus_set()
  289. def edit_cancel(self, event=None):
  290. try:
  291. entry = self.entry
  292. del self.entry
  293. except AttributeError:
  294. return
  295. entry.destroy()
  296. self.drawtext()
  297. self.canvas.focus_set()
  298. class TreeItem:
  299. """Abstract class representing tree items.
  300. Methods should typically be overridden, otherwise a default action
  301. is used.
  302. """
  303. def __init__(self):
  304. """Constructor. Do whatever you need to do."""
  305. def GetText(self):
  306. """Return text string to display."""
  307. def GetLabelText(self):
  308. """Return label text string to display in front of text (if any)."""
  309. expandable = None
  310. def _IsExpandable(self):
  311. """Do not override! Called by TreeNode."""
  312. if self.expandable is None:
  313. self.expandable = self.IsExpandable()
  314. return self.expandable
  315. def IsExpandable(self):
  316. """Return whether there are subitems."""
  317. return 1
  318. def _GetSubList(self):
  319. """Do not override! Called by TreeNode."""
  320. if not self.IsExpandable():
  321. return []
  322. sublist = self.GetSubList()
  323. if not sublist:
  324. self.expandable = 0
  325. return sublist
  326. def IsEditable(self):
  327. """Return whether the item's text may be edited."""
  328. def SetText(self, text):
  329. """Change the item's text (if it is editable)."""
  330. def GetIconName(self):
  331. """Return name of icon to be displayed normally."""
  332. def GetSelectedIconName(self):
  333. """Return name of icon to be displayed when selected."""
  334. def GetSubList(self):
  335. """Return list of items forming sublist."""
  336. def OnDoubleClick(self):
  337. """Called on a double-click on the item."""
  338. # Example application
  339. class FileTreeItem(TreeItem):
  340. """Example TreeItem subclass -- browse the file system."""
  341. def __init__(self, path):
  342. self.path = path
  343. def GetText(self):
  344. return os.path.basename(self.path) or self.path
  345. def IsEditable(self):
  346. return os.path.basename(self.path) != ""
  347. def SetText(self, text):
  348. newpath = os.path.dirname(self.path)
  349. newpath = os.path.join(newpath, text)
  350. if os.path.dirname(newpath) != os.path.dirname(self.path):
  351. return
  352. try:
  353. os.rename(self.path, newpath)
  354. self.path = newpath
  355. except OSError:
  356. pass
  357. def GetIconName(self):
  358. if not self.IsExpandable():
  359. return "python" # XXX wish there was a "file" icon
  360. def IsExpandable(self):
  361. return os.path.isdir(self.path)
  362. def GetSubList(self):
  363. try:
  364. names = os.listdir(self.path)
  365. except OSError:
  366. return []
  367. names.sort(key = os.path.normcase)
  368. sublist = []
  369. for name in names:
  370. item = FileTreeItem(os.path.join(self.path, name))
  371. sublist.append(item)
  372. return sublist
  373. # A canvas widget with scroll bars and some useful bindings
  374. class ScrolledCanvas:
  375. def __init__(self, master, **opts):
  376. if 'yscrollincrement' not in opts:
  377. opts['yscrollincrement'] = 17
  378. self.master = master
  379. self.frame = Frame(master)
  380. self.frame.rowconfigure(0, weight=1)
  381. self.frame.columnconfigure(0, weight=1)
  382. self.canvas = Canvas(self.frame, **opts)
  383. self.canvas.grid(row=0, column=0, sticky="nsew")
  384. self.vbar = Scrollbar(self.frame, name="vbar")
  385. self.vbar.grid(row=0, column=1, sticky="nse")
  386. self.hbar = Scrollbar(self.frame, name="hbar", orient="horizontal")
  387. self.hbar.grid(row=1, column=0, sticky="ews")
  388. self.canvas['yscrollcommand'] = self.vbar.set
  389. self.vbar['command'] = self.canvas.yview
  390. self.canvas['xscrollcommand'] = self.hbar.set
  391. self.hbar['command'] = self.canvas.xview
  392. self.canvas.bind("<Key-Prior>", self.page_up)
  393. self.canvas.bind("<Key-Next>", self.page_down)
  394. self.canvas.bind("<Key-Up>", self.unit_up)
  395. self.canvas.bind("<Key-Down>", self.unit_down)
  396. self.canvas.bind("<MouseWheel>", wheel_event)
  397. self.canvas.bind("<Button-4>", wheel_event)
  398. self.canvas.bind("<Button-5>", wheel_event)
  399. #if isinstance(master, Toplevel) or isinstance(master, Tk):
  400. self.canvas.bind("<Alt-Key-2>", self.zoom_height)
  401. self.canvas.focus_set()
  402. def page_up(self, event):
  403. self.canvas.yview_scroll(-1, "page")
  404. return "break"
  405. def page_down(self, event):
  406. self.canvas.yview_scroll(1, "page")
  407. return "break"
  408. def unit_up(self, event):
  409. self.canvas.yview_scroll(-1, "unit")
  410. return "break"
  411. def unit_down(self, event):
  412. self.canvas.yview_scroll(1, "unit")
  413. return "break"
  414. def zoom_height(self, event):
  415. zoomheight.zoom_height(self.master)
  416. return "break"
  417. def _tree_widget(parent): # htest #
  418. top = Toplevel(parent)
  419. x, y = map(int, parent.geometry().split('+')[1:])
  420. top.geometry("+%d+%d" % (x+50, y+175))
  421. sc = ScrolledCanvas(top, bg="white", highlightthickness=0, takefocus=1)
  422. sc.frame.pack(expand=1, fill="both", side=LEFT)
  423. item = FileTreeItem(ICONDIR)
  424. node = TreeNode(sc.canvas, None, item)
  425. node.expand()
  426. if __name__ == '__main__':
  427. from unittest import main
  428. main('idlelib.idle_test.test_tree', verbosity=2, exit=False)
  429. from idlelib.idle_test.htest import run
  430. run(_tree_widget)