home *** CD-ROM | disk | FTP | other *** search
/ PC World 2005 June / PCWorld_2005-06_cd.bin / software / vyzkuste / firewally / firewally.exe / framework-2.3.exe / TreeWidget.py < prev    next >
Text File  |  2003-12-30  |  15KB  |  477 lines

  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.  
  17. import os
  18. import sys
  19. from Tkinter import *
  20. import imp
  21.  
  22. import ZoomHeight
  23.  
  24. ICONDIR = "Icons"
  25.  
  26. # Look for Icons subdirectory in the same directory as this module
  27. try:
  28.     _icondir = os.path.join(os.path.dirname(__file__), ICONDIR)
  29. except NameError:
  30.     _icondir = ICONDIR
  31. if os.path.isdir(_icondir):
  32.     ICONDIR = _icondir
  33. elif not os.path.isdir(ICONDIR):
  34.     raise RuntimeError, "can't find icon directory (%s)" % `ICONDIR`
  35.  
  36. def listicons(icondir=ICONDIR):
  37.     """Utility to display the available icons."""
  38.     root = Tk()
  39.     import glob
  40.     list = glob.glob(os.path.join(icondir, "*.gif"))
  41.     list.sort()
  42.     images = []
  43.     row = column = 0
  44.     for file in list:
  45.         name = os.path.splitext(os.path.basename(file))[0]
  46.         image = PhotoImage(file=file, master=root)
  47.         images.append(image)
  48.         label = Label(root, image=image, bd=1, relief="raised")
  49.         label.grid(row=row, column=column)
  50.         label = Label(root, text=name)
  51.         label.grid(row=row+1, column=column)
  52.         column = column + 1
  53.         if column >= 10:
  54.             row = row+2
  55.             column = 0
  56.     root.images = images
  57.  
  58.  
  59. class TreeNode:
  60.  
  61.     def __init__(self, canvas, parent, item):
  62.         self.canvas = canvas
  63.         self.parent = parent
  64.         self.item = item
  65.         self.state = 'collapsed'
  66.         self.selected = False
  67.         self.children = []
  68.         self.x = self.y = None
  69.         self.iconimages = {} # cache of PhotoImage instances for icons
  70.  
  71.     def destroy(self):
  72.         for c in self.children[:]:
  73.             self.children.remove(c)
  74.             c.destroy()
  75.         self.parent = None
  76.  
  77.     def geticonimage(self, name):
  78.         try:
  79.             return self.iconimages[name]
  80.         except KeyError:
  81.             pass
  82.         file, ext = os.path.splitext(name)
  83.         ext = ext or ".gif"
  84.         fullname = os.path.join(ICONDIR, file + ext)
  85.         image = PhotoImage(master=self.canvas, file=fullname)
  86.         self.iconimages[name] = image
  87.         return image
  88.  
  89.     def select(self, event=None):
  90.         if self.selected:
  91.             return
  92.         self.deselectall()
  93.         self.selected = True
  94.         self.canvas.delete(self.image_id)
  95.         self.drawicon()
  96.         self.drawtext()
  97.  
  98.     def deselect(self, event=None):
  99.         if not self.selected:
  100.             return
  101.         self.selected = False
  102.         self.canvas.delete(self.image_id)
  103.         self.drawicon()
  104.         self.drawtext()
  105.  
  106.     def deselectall(self):
  107.         if self.parent:
  108.             self.parent.deselectall()
  109.         else:
  110.             self.deselecttree()
  111.  
  112.     def deselecttree(self):
  113.         if self.selected:
  114.             self.deselect()
  115.         for child in self.children:
  116.             child.deselecttree()
  117.  
  118.     def flip(self, event=None):
  119.         if self.state == 'expanded':
  120.             self.collapse()
  121.         else:
  122.             self.expand()
  123.         self.item.OnDoubleClick()
  124.         return "break"
  125.  
  126.     def expand(self, event=None):
  127.         if not self.item._IsExpandable():
  128.             return
  129.         if self.state != 'expanded':
  130.             self.state = 'expanded'
  131.             self.update()
  132.             self.view()
  133.  
  134.     def collapse(self, event=None):
  135.         if self.state != 'collapsed':
  136.             self.state = 'collapsed'
  137.             self.update()
  138.  
  139.     def view(self):
  140.         top = self.y - 2
  141.         bottom = self.lastvisiblechild().y + 17
  142.         height = bottom - top
  143.         visible_top = self.canvas.canvasy(0)
  144.         visible_height = self.canvas.winfo_height()
  145.         visible_bottom = self.canvas.canvasy(visible_height)
  146.         if visible_top <= top and bottom <= visible_bottom:
  147.             return
  148.         x0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion'])
  149.         if top >= visible_top and height <= visible_height:
  150.             fraction = top + height - visible_height
  151.         else:
  152.             fraction = top
  153.         fraction = float(fraction) / y1
  154.         self.canvas.yview_moveto(fraction)
  155.  
  156.     def lastvisiblechild(self):
  157.         if self.children and self.state == 'expanded':
  158.             return self.children[-1].lastvisiblechild()
  159.         else:
  160.             return self
  161.  
  162.     def update(self):
  163.         if self.parent:
  164.             self.parent.update()
  165.         else:
  166.             oldcursor = self.canvas['cursor']
  167.             self.canvas['cursor'] = "watch"
  168.             self.canvas.update()
  169.             self.canvas.delete(ALL)     # XXX could be more subtle
  170.             self.draw(7, 2)
  171.             x0, y0, x1, y1 = self.canvas.bbox(ALL)
  172.             self.canvas.configure(scrollregion=(0, 0, x1, y1))
  173.             self.canvas['cursor'] = oldcursor
  174.  
  175.     def draw(self, x, y):
  176.         # XXX This hard-codes too many geometry constants!
  177.         self.x, self.y = x, y
  178.         self.drawicon()
  179.         self.drawtext()
  180.         if self.state != 'expanded':
  181.             return y+17
  182.         # draw children
  183.         if not self.children:
  184.             sublist = self.item._GetSubList()
  185.             if not sublist:
  186.                 # _IsExpandable() was mistaken; that's allowed
  187.                 return y+17
  188.             for item in sublist:
  189.                 child = self.__class__(self.canvas, self, item)
  190.                 self.children.append(child)
  191.         cx = x+20
  192.         cy = y+17
  193.         cylast = 0
  194.         for child in self.children:
  195.             cylast = cy
  196.             self.canvas.create_line(x+9, cy+7, cx, cy+7, fill="gray50")
  197.             cy = child.draw(cx, cy)
  198.             if child.item._IsExpandable():
  199.                 if child.state == 'expanded':
  200.                     iconname = "minusnode"
  201.                     callback = child.collapse
  202.                 else:
  203.                     iconname = "plusnode"
  204.                     callback = child.expand
  205.                 image = self.geticonimage(iconname)
  206.                 id = self.canvas.create_image(x+9, cylast+7, image=image)
  207.                 # XXX This leaks bindings until canvas is deleted:
  208.                 self.canvas.tag_bind(id, "<1>", callback)
  209.                 self.canvas.tag_bind(id, "<Double-1>", lambda x: None)
  210.         id = self.canvas.create_line(x+9, y+10, x+9, cylast+7,
  211.             ##stipple="gray50",     # XXX Seems broken in Tk 8.0.x
  212.             fill="gray50")
  213.         self.canvas.tag_lower(id) # XXX .lower(id) before Python 1.5.2
  214.         return cy
  215.  
  216.     def drawicon(self):
  217.         if self.selected:
  218.             imagename = (self.item.GetSelectedIconName() or
  219.                          self.item.GetIconName() or
  220.                          "openfolder")
  221.         else:
  222.             imagename = self.item.GetIconName() or "folder"
  223.         image = self.geticonimage(imagename)
  224.         id = self.canvas.create_image(self.x, self.y, anchor="nw", image=image)
  225.         self.image_id = id
  226.         self.canvas.tag_bind(id, "<1>", self.select)
  227.         self.canvas.tag_bind(id, "<Double-1>", self.flip)
  228.  
  229.     def drawtext(self):
  230.         textx = self.x+20-1
  231.         texty = self.y-1
  232.         labeltext = self.item.GetLabelText()
  233.         if labeltext:
  234.             id = self.canvas.create_text(textx, texty, anchor="nw",
  235.                                          text=labeltext)
  236.             self.canvas.tag_bind(id, "<1>", self.select)
  237.             self.canvas.tag_bind(id, "<Double-1>", self.flip)
  238.             x0, y0, x1, y1 = self.canvas.bbox(id)
  239.             textx = max(x1, 200) + 10
  240.         text = self.item.GetText() or "<no text>"
  241.         try:
  242.             self.entry
  243.         except AttributeError:
  244.             pass
  245.         else:
  246.             self.edit_finish()
  247.         try:
  248.             label = self.label
  249.         except AttributeError:
  250.             # padding carefully selected (on Windows) to match Entry widget:
  251.             self.label = Label(self.canvas, text=text, bd=0, padx=2, pady=2)
  252.         if self.selected:
  253.             self.label.configure(fg="white", bg="darkblue")
  254.         else:
  255.             self.label.configure(fg="black", bg="white")
  256.         id = self.canvas.create_window(textx, texty,
  257.                                        anchor="nw", window=self.label)
  258.         self.label.bind("<1>", self.select_or_edit)
  259.         self.label.bind("<Double-1>", self.flip)
  260.         self.text_id = id
  261.  
  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.  
  268.     def edit(self, event=None):
  269.         self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0)
  270.         self.entry.insert(0, self.label['text'])
  271.         self.entry.selection_range(0, END)
  272.         self.entry.pack(ipadx=5)
  273.         self.entry.focus_set()
  274.         self.entry.bind("<Return>", self.edit_finish)
  275.         self.entry.bind("<Escape>", self.edit_cancel)
  276.  
  277.     def edit_finish(self, event=None):
  278.         try:
  279.             entry = self.entry
  280.             del self.entry
  281.         except AttributeError:
  282.             return
  283.         text = entry.get()
  284.         entry.destroy()
  285.         if text and text != self.item.GetText():
  286.             self.item.SetText(text)
  287.         text = self.item.GetText()
  288.         self.label['text'] = text
  289.         self.drawtext()
  290.         self.canvas.focus_set()
  291.  
  292.     def edit_cancel(self, event=None):
  293.         try:
  294.             entry = self.entry
  295.             del self.entry
  296.         except AttributeError:
  297.             return
  298.         entry.destroy()
  299.         self.drawtext()
  300.         self.canvas.focus_set()
  301.  
  302.  
  303. class TreeItem:
  304.  
  305.     """Abstract class representing tree items.
  306.  
  307.     Methods should typically be overridden, otherwise a default action
  308.     is used.
  309.  
  310.     """
  311.  
  312.     def __init__(self):
  313.         """Constructor.  Do whatever you need to do."""
  314.  
  315.     def GetText(self):
  316.         """Return text string to display."""
  317.  
  318.     def GetLabelText(self):
  319.         """Return label text string to display in front of text (if any)."""
  320.  
  321.     expandable = None
  322.  
  323.     def _IsExpandable(self):
  324.         """Do not override!  Called by TreeNode."""
  325.         if self.expandable is None:
  326.             self.expandable = self.IsExpandable()
  327.         return self.expandable
  328.  
  329.     def IsExpandable(self):
  330.         """Return whether there are subitems."""
  331.         return 1
  332.  
  333.     def _GetSubList(self):
  334.         """Do not override!  Called by TreeNode."""
  335.         if not self.IsExpandable():
  336.             return []
  337.         sublist = self.GetSubList()
  338.         if not sublist:
  339.             self.expandable = 0
  340.         return sublist
  341.  
  342.     def IsEditable(self):
  343.         """Return whether the item's text may be edited."""
  344.  
  345.     def SetText(self, text):
  346.         """Change the item's text (if it is editable)."""
  347.  
  348.     def GetIconName(self):
  349.         """Return name of icon to be displayed normally."""
  350.  
  351.     def GetSelectedIconName(self):
  352.         """Return name of icon to be displayed when selected."""
  353.  
  354.     def GetSubList(self):
  355.         """Return list of items forming sublist."""
  356.  
  357.     def OnDoubleClick(self):
  358.         """Called on a double-click on the item."""
  359.  
  360.  
  361. # Example application
  362.  
  363. class FileTreeItem(TreeItem):
  364.  
  365.     """Example TreeItem subclass -- browse the file system."""
  366.  
  367.     def __init__(self, path):
  368.         self.path = path
  369.  
  370.     def GetText(self):
  371.         return os.path.basename(self.path) or self.path
  372.  
  373.     def IsEditable(self):
  374.         return os.path.basename(self.path) != ""
  375.  
  376.     def SetText(self, text):
  377.         newpath = os.path.dirname(self.path)
  378.         newpath = os.path.join(newpath, text)
  379.         if os.path.dirname(newpath) != os.path.dirname(self.path):
  380.             return
  381.         try:
  382.             os.rename(self.path, newpath)
  383.             self.path = newpath
  384.         except os.error:
  385.             pass
  386.  
  387.     def GetIconName(self):
  388.         if not self.IsExpandable():
  389.             return "python" # XXX wish there was a "file" icon
  390.  
  391.     def IsExpandable(self):
  392.         return os.path.isdir(self.path)
  393.  
  394.     def GetSubList(self):
  395.         try:
  396.             names = os.listdir(self.path)
  397.         except os.error:
  398.             return []
  399.         names.sort(lambda a, b: cmp(os.path.normcase(a), os.path.normcase(b)))
  400.         sublist = []
  401.         for name in names:
  402.             item = FileTreeItem(os.path.join(self.path, name))
  403.             sublist.append(item)
  404.         return sublist
  405.  
  406.  
  407. # A canvas widget with scroll bars and some useful bindings
  408.  
  409. class ScrolledCanvas:
  410.     def __init__(self, master, **opts):
  411.         if not opts.has_key('yscrollincrement'):
  412.             opts['yscrollincrement'] = 17
  413.         self.master = master
  414.         self.frame = Frame(master)
  415.         self.frame.rowconfigure(0, weight=1)
  416.         self.frame.columnconfigure(0, weight=1)
  417.         self.canvas = Canvas(self.frame, **opts)
  418.         self.canvas.grid(row=0, column=0, sticky="nsew")
  419.         self.vbar = Scrollbar(self.frame, name="vbar")
  420.         self.vbar.grid(row=0, column=1, sticky="nse")
  421.         self.hbar = Scrollbar(self.frame, name="hbar", orient="horizontal")
  422.         self.hbar.grid(row=1, column=0, sticky="ews")
  423.         self.canvas['yscrollcommand'] = self.vbar.set
  424.         self.vbar['command'] = self.canvas.yview
  425.         self.canvas['xscrollcommand'] = self.hbar.set
  426.         self.hbar['command'] = self.canvas.xview
  427.         self.canvas.bind("<Key-Prior>", self.page_up)
  428.         self.canvas.bind("<Key-Next>", self.page_down)
  429.         self.canvas.bind("<Key-Up>", self.unit_up)
  430.         self.canvas.bind("<Key-Down>", self.unit_down)
  431.         #if isinstance(master, Toplevel) or isinstance(master, Tk):
  432.         self.canvas.bind("<Alt-Key-2>", self.zoom_height)
  433.         self.canvas.focus_set()
  434.     def page_up(self, event):
  435.         self.canvas.yview_scroll(-1, "page")
  436.         return "break"
  437.     def page_down(self, event):
  438.         self.canvas.yview_scroll(1, "page")
  439.         return "break"
  440.     def unit_up(self, event):
  441.         self.canvas.yview_scroll(-1, "unit")
  442.         return "break"
  443.     def unit_down(self, event):
  444.         self.canvas.yview_scroll(1, "unit")
  445.         return "break"
  446.     def zoom_height(self, event):
  447.         ZoomHeight.zoom_height(self.master)
  448.         return "break"
  449.  
  450.  
  451. # Testing functions
  452.  
  453. def test():
  454.     import PyShell
  455.     root = Toplevel(PyShell.root)
  456.     root.configure(bd=0, bg="yellow")
  457.     root.focus_set()
  458.     sc = ScrolledCanvas(root, bg="white", highlightthickness=0, takefocus=1)
  459.     sc.frame.pack(expand=1, fill="both")
  460.     item = FileTreeItem("C:/windows/desktop")
  461.     node = TreeNode(sc.canvas, None, item)
  462.     node.expand()
  463.  
  464. def test2():
  465.     # test w/o scrolling canvas
  466.     root = Tk()
  467.     root.configure(bd=0)
  468.     canvas = Canvas(root, bg="white", highlightthickness=0)
  469.     canvas.pack(expand=1, fill="both")
  470.     item = FileTreeItem(os.curdir)
  471.     node = TreeNode(canvas, None, item)
  472.     node.update()
  473.     canvas.focus_set()
  474.  
  475. if __name__ == '__main__':
  476.     test()
  477.