jpayne@68: # XXX TO DO: jpayne@68: # - popup menu jpayne@68: # - support partial or total redisplay jpayne@68: # - key bindings (instead of quick-n-dirty bindings on Canvas): jpayne@68: # - up/down arrow keys to move focus around jpayne@68: # - ditto for page up/down, home/end jpayne@68: # - left/right arrows to expand/collapse & move out/in jpayne@68: # - more doc strings jpayne@68: # - add icons for "file", "module", "class", "method"; better "python" icon jpayne@68: # - callback for selection??? jpayne@68: # - multiple-item selection jpayne@68: # - tooltips jpayne@68: # - redo geometry without magic numbers jpayne@68: # - keep track of object ids to allow more careful cleaning jpayne@68: # - optimize tree redraw after expand of subnode jpayne@68: jpayne@68: import os jpayne@68: jpayne@68: from tkinter import * jpayne@68: from tkinter.ttk import Frame, Scrollbar jpayne@68: jpayne@68: from idlelib.config import idleConf jpayne@68: from idlelib import zoomheight jpayne@68: jpayne@68: ICONDIR = "Icons" jpayne@68: jpayne@68: # Look for Icons subdirectory in the same directory as this module jpayne@68: try: jpayne@68: _icondir = os.path.join(os.path.dirname(__file__), ICONDIR) jpayne@68: except NameError: jpayne@68: _icondir = ICONDIR jpayne@68: if os.path.isdir(_icondir): jpayne@68: ICONDIR = _icondir jpayne@68: elif not os.path.isdir(ICONDIR): jpayne@68: raise RuntimeError("can't find icon directory (%r)" % (ICONDIR,)) jpayne@68: jpayne@68: def listicons(icondir=ICONDIR): jpayne@68: """Utility to display the available icons.""" jpayne@68: root = Tk() jpayne@68: import glob jpayne@68: list = glob.glob(os.path.join(icondir, "*.gif")) jpayne@68: list.sort() jpayne@68: images = [] jpayne@68: row = column = 0 jpayne@68: for file in list: jpayne@68: name = os.path.splitext(os.path.basename(file))[0] jpayne@68: image = PhotoImage(file=file, master=root) jpayne@68: images.append(image) jpayne@68: label = Label(root, image=image, bd=1, relief="raised") jpayne@68: label.grid(row=row, column=column) jpayne@68: label = Label(root, text=name) jpayne@68: label.grid(row=row+1, column=column) jpayne@68: column = column + 1 jpayne@68: if column >= 10: jpayne@68: row = row+2 jpayne@68: column = 0 jpayne@68: root.images = images jpayne@68: jpayne@68: def wheel_event(event, widget=None): jpayne@68: """Handle scrollwheel event. jpayne@68: jpayne@68: For wheel up, event.delta = 120*n on Windows, -1*n on darwin, jpayne@68: where n can be > 1 if one scrolls fast. Flicking the wheel jpayne@68: generates up to maybe 20 events with n up to 10 or more 1. jpayne@68: Macs use wheel down (delta = 1*n) to scroll up, so positive jpayne@68: delta means to scroll up on both systems. jpayne@68: jpayne@68: X-11 sends Control-Button-4,5 events instead. jpayne@68: jpayne@68: The widget parameter is needed so browser label bindings can pass jpayne@68: the underlying canvas. jpayne@68: jpayne@68: This function depends on widget.yview to not be overridden by jpayne@68: a subclass. jpayne@68: """ jpayne@68: up = {EventType.MouseWheel: event.delta > 0, jpayne@68: EventType.ButtonPress: event.num == 4} jpayne@68: lines = -5 if up[event.type] else 5 jpayne@68: widget = event.widget if widget is None else widget jpayne@68: widget.yview(SCROLL, lines, 'units') jpayne@68: return 'break' jpayne@68: jpayne@68: jpayne@68: class TreeNode: jpayne@68: jpayne@68: def __init__(self, canvas, parent, item): jpayne@68: self.canvas = canvas jpayne@68: self.parent = parent jpayne@68: self.item = item jpayne@68: self.state = 'collapsed' jpayne@68: self.selected = False jpayne@68: self.children = [] jpayne@68: self.x = self.y = None jpayne@68: self.iconimages = {} # cache of PhotoImage instances for icons jpayne@68: jpayne@68: def destroy(self): jpayne@68: for c in self.children[:]: jpayne@68: self.children.remove(c) jpayne@68: c.destroy() jpayne@68: self.parent = None jpayne@68: jpayne@68: def geticonimage(self, name): jpayne@68: try: jpayne@68: return self.iconimages[name] jpayne@68: except KeyError: jpayne@68: pass jpayne@68: file, ext = os.path.splitext(name) jpayne@68: ext = ext or ".gif" jpayne@68: fullname = os.path.join(ICONDIR, file + ext) jpayne@68: image = PhotoImage(master=self.canvas, file=fullname) jpayne@68: self.iconimages[name] = image jpayne@68: return image jpayne@68: jpayne@68: def select(self, event=None): jpayne@68: if self.selected: jpayne@68: return jpayne@68: self.deselectall() jpayne@68: self.selected = True jpayne@68: self.canvas.delete(self.image_id) jpayne@68: self.drawicon() jpayne@68: self.drawtext() jpayne@68: jpayne@68: def deselect(self, event=None): jpayne@68: if not self.selected: jpayne@68: return jpayne@68: self.selected = False jpayne@68: self.canvas.delete(self.image_id) jpayne@68: self.drawicon() jpayne@68: self.drawtext() jpayne@68: jpayne@68: def deselectall(self): jpayne@68: if self.parent: jpayne@68: self.parent.deselectall() jpayne@68: else: jpayne@68: self.deselecttree() jpayne@68: jpayne@68: def deselecttree(self): jpayne@68: if self.selected: jpayne@68: self.deselect() jpayne@68: for child in self.children: jpayne@68: child.deselecttree() jpayne@68: jpayne@68: def flip(self, event=None): jpayne@68: if self.state == 'expanded': jpayne@68: self.collapse() jpayne@68: else: jpayne@68: self.expand() jpayne@68: self.item.OnDoubleClick() jpayne@68: return "break" jpayne@68: jpayne@68: def expand(self, event=None): jpayne@68: if not self.item._IsExpandable(): jpayne@68: return jpayne@68: if self.state != 'expanded': jpayne@68: self.state = 'expanded' jpayne@68: self.update() jpayne@68: self.view() jpayne@68: jpayne@68: def collapse(self, event=None): jpayne@68: if self.state != 'collapsed': jpayne@68: self.state = 'collapsed' jpayne@68: self.update() jpayne@68: jpayne@68: def view(self): jpayne@68: top = self.y - 2 jpayne@68: bottom = self.lastvisiblechild().y + 17 jpayne@68: height = bottom - top jpayne@68: visible_top = self.canvas.canvasy(0) jpayne@68: visible_height = self.canvas.winfo_height() jpayne@68: visible_bottom = self.canvas.canvasy(visible_height) jpayne@68: if visible_top <= top and bottom <= visible_bottom: jpayne@68: return jpayne@68: x0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion']) jpayne@68: if top >= visible_top and height <= visible_height: jpayne@68: fraction = top + height - visible_height jpayne@68: else: jpayne@68: fraction = top jpayne@68: fraction = float(fraction) / y1 jpayne@68: self.canvas.yview_moveto(fraction) jpayne@68: jpayne@68: def lastvisiblechild(self): jpayne@68: if self.children and self.state == 'expanded': jpayne@68: return self.children[-1].lastvisiblechild() jpayne@68: else: jpayne@68: return self jpayne@68: jpayne@68: def update(self): jpayne@68: if self.parent: jpayne@68: self.parent.update() jpayne@68: else: jpayne@68: oldcursor = self.canvas['cursor'] jpayne@68: self.canvas['cursor'] = "watch" jpayne@68: self.canvas.update() jpayne@68: self.canvas.delete(ALL) # XXX could be more subtle jpayne@68: self.draw(7, 2) jpayne@68: x0, y0, x1, y1 = self.canvas.bbox(ALL) jpayne@68: self.canvas.configure(scrollregion=(0, 0, x1, y1)) jpayne@68: self.canvas['cursor'] = oldcursor jpayne@68: jpayne@68: def draw(self, x, y): jpayne@68: # XXX This hard-codes too many geometry constants! jpayne@68: dy = 20 jpayne@68: self.x, self.y = x, y jpayne@68: self.drawicon() jpayne@68: self.drawtext() jpayne@68: if self.state != 'expanded': jpayne@68: return y + dy jpayne@68: # draw children jpayne@68: if not self.children: jpayne@68: sublist = self.item._GetSubList() jpayne@68: if not sublist: jpayne@68: # _IsExpandable() was mistaken; that's allowed jpayne@68: return y+17 jpayne@68: for item in sublist: jpayne@68: child = self.__class__(self.canvas, self, item) jpayne@68: self.children.append(child) jpayne@68: cx = x+20 jpayne@68: cy = y + dy jpayne@68: cylast = 0 jpayne@68: for child in self.children: jpayne@68: cylast = cy jpayne@68: self.canvas.create_line(x+9, cy+7, cx, cy+7, fill="gray50") jpayne@68: cy = child.draw(cx, cy) jpayne@68: if child.item._IsExpandable(): jpayne@68: if child.state == 'expanded': jpayne@68: iconname = "minusnode" jpayne@68: callback = child.collapse jpayne@68: else: jpayne@68: iconname = "plusnode" jpayne@68: callback = child.expand jpayne@68: image = self.geticonimage(iconname) jpayne@68: id = self.canvas.create_image(x+9, cylast+7, image=image) jpayne@68: # XXX This leaks bindings until canvas is deleted: jpayne@68: self.canvas.tag_bind(id, "<1>", callback) jpayne@68: self.canvas.tag_bind(id, "", lambda x: None) jpayne@68: id = self.canvas.create_line(x+9, y+10, x+9, cylast+7, jpayne@68: ##stipple="gray50", # XXX Seems broken in Tk 8.0.x jpayne@68: fill="gray50") jpayne@68: self.canvas.tag_lower(id) # XXX .lower(id) before Python 1.5.2 jpayne@68: return cy jpayne@68: jpayne@68: def drawicon(self): jpayne@68: if self.selected: jpayne@68: imagename = (self.item.GetSelectedIconName() or jpayne@68: self.item.GetIconName() or jpayne@68: "openfolder") jpayne@68: else: jpayne@68: imagename = self.item.GetIconName() or "folder" jpayne@68: image = self.geticonimage(imagename) jpayne@68: id = self.canvas.create_image(self.x, self.y, anchor="nw", image=image) jpayne@68: self.image_id = id jpayne@68: self.canvas.tag_bind(id, "<1>", self.select) jpayne@68: self.canvas.tag_bind(id, "", self.flip) jpayne@68: jpayne@68: def drawtext(self): jpayne@68: textx = self.x+20-1 jpayne@68: texty = self.y-4 jpayne@68: labeltext = self.item.GetLabelText() jpayne@68: if labeltext: jpayne@68: id = self.canvas.create_text(textx, texty, anchor="nw", jpayne@68: text=labeltext) jpayne@68: self.canvas.tag_bind(id, "<1>", self.select) jpayne@68: self.canvas.tag_bind(id, "", self.flip) jpayne@68: x0, y0, x1, y1 = self.canvas.bbox(id) jpayne@68: textx = max(x1, 200) + 10 jpayne@68: text = self.item.GetText() or "" jpayne@68: try: jpayne@68: self.entry jpayne@68: except AttributeError: jpayne@68: pass jpayne@68: else: jpayne@68: self.edit_finish() jpayne@68: try: jpayne@68: self.label jpayne@68: except AttributeError: jpayne@68: # padding carefully selected (on Windows) to match Entry widget: jpayne@68: self.label = Label(self.canvas, text=text, bd=0, padx=2, pady=2) jpayne@68: theme = idleConf.CurrentTheme() jpayne@68: if self.selected: jpayne@68: self.label.configure(idleConf.GetHighlight(theme, 'hilite')) jpayne@68: else: jpayne@68: self.label.configure(idleConf.GetHighlight(theme, 'normal')) jpayne@68: id = self.canvas.create_window(textx, texty, jpayne@68: anchor="nw", window=self.label) jpayne@68: self.label.bind("<1>", self.select_or_edit) jpayne@68: self.label.bind("", self.flip) jpayne@68: self.label.bind("", lambda e: wheel_event(e, self.canvas)) jpayne@68: self.label.bind("", lambda e: wheel_event(e, self.canvas)) jpayne@68: self.label.bind("", lambda e: wheel_event(e, self.canvas)) jpayne@68: self.text_id = id jpayne@68: jpayne@68: def select_or_edit(self, event=None): jpayne@68: if self.selected and self.item.IsEditable(): jpayne@68: self.edit(event) jpayne@68: else: jpayne@68: self.select(event) jpayne@68: jpayne@68: def edit(self, event=None): jpayne@68: self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0) jpayne@68: self.entry.insert(0, self.label['text']) jpayne@68: self.entry.selection_range(0, END) jpayne@68: self.entry.pack(ipadx=5) jpayne@68: self.entry.focus_set() jpayne@68: self.entry.bind("", self.edit_finish) jpayne@68: self.entry.bind("", self.edit_cancel) jpayne@68: jpayne@68: def edit_finish(self, event=None): jpayne@68: try: jpayne@68: entry = self.entry jpayne@68: del self.entry jpayne@68: except AttributeError: jpayne@68: return jpayne@68: text = entry.get() jpayne@68: entry.destroy() jpayne@68: if text and text != self.item.GetText(): jpayne@68: self.item.SetText(text) jpayne@68: text = self.item.GetText() jpayne@68: self.label['text'] = text jpayne@68: self.drawtext() jpayne@68: self.canvas.focus_set() jpayne@68: jpayne@68: def edit_cancel(self, event=None): jpayne@68: try: jpayne@68: entry = self.entry jpayne@68: del self.entry jpayne@68: except AttributeError: jpayne@68: return jpayne@68: entry.destroy() jpayne@68: self.drawtext() jpayne@68: self.canvas.focus_set() jpayne@68: jpayne@68: jpayne@68: class TreeItem: jpayne@68: jpayne@68: """Abstract class representing tree items. jpayne@68: jpayne@68: Methods should typically be overridden, otherwise a default action jpayne@68: is used. jpayne@68: jpayne@68: """ jpayne@68: jpayne@68: def __init__(self): jpayne@68: """Constructor. Do whatever you need to do.""" jpayne@68: jpayne@68: def GetText(self): jpayne@68: """Return text string to display.""" jpayne@68: jpayne@68: def GetLabelText(self): jpayne@68: """Return label text string to display in front of text (if any).""" jpayne@68: jpayne@68: expandable = None jpayne@68: jpayne@68: def _IsExpandable(self): jpayne@68: """Do not override! Called by TreeNode.""" jpayne@68: if self.expandable is None: jpayne@68: self.expandable = self.IsExpandable() jpayne@68: return self.expandable jpayne@68: jpayne@68: def IsExpandable(self): jpayne@68: """Return whether there are subitems.""" jpayne@68: return 1 jpayne@68: jpayne@68: def _GetSubList(self): jpayne@68: """Do not override! Called by TreeNode.""" jpayne@68: if not self.IsExpandable(): jpayne@68: return [] jpayne@68: sublist = self.GetSubList() jpayne@68: if not sublist: jpayne@68: self.expandable = 0 jpayne@68: return sublist jpayne@68: jpayne@68: def IsEditable(self): jpayne@68: """Return whether the item's text may be edited.""" jpayne@68: jpayne@68: def SetText(self, text): jpayne@68: """Change the item's text (if it is editable).""" jpayne@68: jpayne@68: def GetIconName(self): jpayne@68: """Return name of icon to be displayed normally.""" jpayne@68: jpayne@68: def GetSelectedIconName(self): jpayne@68: """Return name of icon to be displayed when selected.""" jpayne@68: jpayne@68: def GetSubList(self): jpayne@68: """Return list of items forming sublist.""" jpayne@68: jpayne@68: def OnDoubleClick(self): jpayne@68: """Called on a double-click on the item.""" jpayne@68: jpayne@68: jpayne@68: # Example application jpayne@68: jpayne@68: class FileTreeItem(TreeItem): jpayne@68: jpayne@68: """Example TreeItem subclass -- browse the file system.""" jpayne@68: jpayne@68: def __init__(self, path): jpayne@68: self.path = path jpayne@68: jpayne@68: def GetText(self): jpayne@68: return os.path.basename(self.path) or self.path jpayne@68: jpayne@68: def IsEditable(self): jpayne@68: return os.path.basename(self.path) != "" jpayne@68: jpayne@68: def SetText(self, text): jpayne@68: newpath = os.path.dirname(self.path) jpayne@68: newpath = os.path.join(newpath, text) jpayne@68: if os.path.dirname(newpath) != os.path.dirname(self.path): jpayne@68: return jpayne@68: try: jpayne@68: os.rename(self.path, newpath) jpayne@68: self.path = newpath jpayne@68: except OSError: jpayne@68: pass jpayne@68: jpayne@68: def GetIconName(self): jpayne@68: if not self.IsExpandable(): jpayne@68: return "python" # XXX wish there was a "file" icon jpayne@68: jpayne@68: def IsExpandable(self): jpayne@68: return os.path.isdir(self.path) jpayne@68: jpayne@68: def GetSubList(self): jpayne@68: try: jpayne@68: names = os.listdir(self.path) jpayne@68: except OSError: jpayne@68: return [] jpayne@68: names.sort(key = os.path.normcase) jpayne@68: sublist = [] jpayne@68: for name in names: jpayne@68: item = FileTreeItem(os.path.join(self.path, name)) jpayne@68: sublist.append(item) jpayne@68: return sublist jpayne@68: jpayne@68: jpayne@68: # A canvas widget with scroll bars and some useful bindings jpayne@68: jpayne@68: class ScrolledCanvas: jpayne@68: jpayne@68: def __init__(self, master, **opts): jpayne@68: if 'yscrollincrement' not in opts: jpayne@68: opts['yscrollincrement'] = 17 jpayne@68: self.master = master jpayne@68: self.frame = Frame(master) jpayne@68: self.frame.rowconfigure(0, weight=1) jpayne@68: self.frame.columnconfigure(0, weight=1) jpayne@68: self.canvas = Canvas(self.frame, **opts) jpayne@68: self.canvas.grid(row=0, column=0, sticky="nsew") jpayne@68: self.vbar = Scrollbar(self.frame, name="vbar") jpayne@68: self.vbar.grid(row=0, column=1, sticky="nse") jpayne@68: self.hbar = Scrollbar(self.frame, name="hbar", orient="horizontal") jpayne@68: self.hbar.grid(row=1, column=0, sticky="ews") jpayne@68: self.canvas['yscrollcommand'] = self.vbar.set jpayne@68: self.vbar['command'] = self.canvas.yview jpayne@68: self.canvas['xscrollcommand'] = self.hbar.set jpayne@68: self.hbar['command'] = self.canvas.xview jpayne@68: self.canvas.bind("", self.page_up) jpayne@68: self.canvas.bind("", self.page_down) jpayne@68: self.canvas.bind("", self.unit_up) jpayne@68: self.canvas.bind("", self.unit_down) jpayne@68: self.canvas.bind("", wheel_event) jpayne@68: self.canvas.bind("", wheel_event) jpayne@68: self.canvas.bind("", wheel_event) jpayne@68: #if isinstance(master, Toplevel) or isinstance(master, Tk): jpayne@68: self.canvas.bind("", self.zoom_height) jpayne@68: self.canvas.focus_set() jpayne@68: def page_up(self, event): jpayne@68: self.canvas.yview_scroll(-1, "page") jpayne@68: return "break" jpayne@68: def page_down(self, event): jpayne@68: self.canvas.yview_scroll(1, "page") jpayne@68: return "break" jpayne@68: def unit_up(self, event): jpayne@68: self.canvas.yview_scroll(-1, "unit") jpayne@68: return "break" jpayne@68: def unit_down(self, event): jpayne@68: self.canvas.yview_scroll(1, "unit") jpayne@68: return "break" jpayne@68: def zoom_height(self, event): jpayne@68: zoomheight.zoom_height(self.master) jpayne@68: return "break" jpayne@68: jpayne@68: jpayne@68: def _tree_widget(parent): # htest # jpayne@68: top = Toplevel(parent) jpayne@68: x, y = map(int, parent.geometry().split('+')[1:]) jpayne@68: top.geometry("+%d+%d" % (x+50, y+175)) jpayne@68: sc = ScrolledCanvas(top, bg="white", highlightthickness=0, takefocus=1) jpayne@68: sc.frame.pack(expand=1, fill="both", side=LEFT) jpayne@68: item = FileTreeItem(ICONDIR) jpayne@68: node = TreeNode(sc.canvas, None, item) jpayne@68: node.expand() jpayne@68: jpayne@68: if __name__ == '__main__': jpayne@68: from unittest import main jpayne@68: main('idlelib.idle_test.test_tree', verbosity=2, exit=False) jpayne@68: jpayne@68: from idlelib.idle_test.htest import run jpayne@68: run(_tree_widget)