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