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
9 # - add icons for "file", "module", "class", "method"; better "python" icon
10 # - callback for selection???
11 # - multiple-item selection
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
22 from configHandler
import idleConf
26 # Look for Icons subdirectory in the same directory as this module
28 _icondir
= os
.path
.join(os
.path
.dirname(__file__
), ICONDIR
)
31 if os
.path
.isdir(_icondir
):
33 elif not os
.path
.isdir(ICONDIR
):
34 raise RuntimeError, "can't find icon directory (%r)" % (ICONDIR
,)
36 def listicons(icondir
=ICONDIR
):
37 """Utility to display the available icons."""
40 list = glob
.glob(os
.path
.join(icondir
, "*.gif"))
45 name
= os
.path
.splitext(os
.path
.basename(file))[0]
46 image
= PhotoImage(file=file, master
=root
)
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
)
61 def __init__(self
, canvas
, parent
, item
):
65 self
.state
= 'collapsed'
68 self
.x
= self
.y
= None
69 self
.iconimages
= {} # cache of PhotoImage instances for icons
72 for c
in self
.children
[:]:
73 self
.children
.remove(c
)
77 def geticonimage(self
, name
):
79 return self
.iconimages
[name
]
82 file, ext
= os
.path
.splitext(name
)
84 fullname
= os
.path
.join(ICONDIR
, file + ext
)
85 image
= PhotoImage(master
=self
.canvas
, file=fullname
)
86 self
.iconimages
[name
] = image
89 def select(self
, event
=None):
94 self
.canvas
.delete(self
.image_id
)
98 def deselect(self
, event
=None):
101 self
.selected
= False
102 self
.canvas
.delete(self
.image_id
)
106 def deselectall(self
):
108 self
.parent
.deselectall()
112 def deselecttree(self
):
115 for child
in self
.children
:
118 def flip(self
, event
=None):
119 if self
.state
== 'expanded':
123 self
.item
.OnDoubleClick()
126 def expand(self
, event
=None):
127 if not self
.item
._IsExpandable
():
129 if self
.state
!= 'expanded':
130 self
.state
= 'expanded'
134 def collapse(self
, event
=None):
135 if self
.state
!= 'collapsed':
136 self
.state
= 'collapsed'
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
:
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
153 fraction
= float(fraction
) / y1
154 self
.canvas
.yview_moveto(fraction
)
156 def lastvisiblechild(self
):
157 if self
.children
and self
.state
== 'expanded':
158 return self
.children
[-1].lastvisiblechild()
166 oldcursor
= self
.canvas
['cursor']
167 self
.canvas
['cursor'] = "watch"
169 self
.canvas
.delete(ALL
) # XXX could be more subtle
171 x0
, y0
, x1
, y1
= self
.canvas
.bbox(ALL
)
172 self
.canvas
.configure(scrollregion
=(0, 0, x1
, y1
))
173 self
.canvas
['cursor'] = oldcursor
175 def draw(self
, x
, y
):
176 # XXX This hard-codes too many geometry constants!
177 self
.x
, self
.y
= x
, y
180 if self
.state
!= 'expanded':
183 if not self
.children
:
184 sublist
= self
.item
._GetSubList
()
186 # _IsExpandable() was mistaken; that's allowed
189 child
= self
.__class
__(self
.canvas
, self
, item
)
190 self
.children
.append(child
)
194 for child
in self
.children
:
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
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
213 self
.canvas
.tag_lower(id) # XXX .lower(id) before Python 1.5.2
218 imagename
= (self
.item
.GetSelectedIconName() or
219 self
.item
.GetIconName() or
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
)
226 self
.canvas
.tag_bind(id, "<1>", self
.select
)
227 self
.canvas
.tag_bind(id, "<Double-1>", self
.flip
)
232 labeltext
= self
.item
.GetLabelText()
234 id = self
.canvas
.create_text(textx
, texty
, anchor
="nw",
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>"
243 except AttributeError:
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 theme
= idleConf
.GetOption('main','Theme','name')
254 self
.label
.configure(idleConf
.GetHighlight(theme
, 'hilite'))
256 self
.label
.configure(idleConf
.GetHighlight(theme
, 'normal'))
257 id = self
.canvas
.create_window(textx
, texty
,
258 anchor
="nw", window
=self
.label
)
259 self
.label
.bind("<1>", self
.select_or_edit
)
260 self
.label
.bind("<Double-1>", self
.flip
)
263 def select_or_edit(self
, event
=None):
264 if self
.selected
and self
.item
.IsEditable():
269 def edit(self
, event
=None):
270 self
.entry
= Entry(self
.label
, bd
=0, highlightthickness
=1, width
=0)
271 self
.entry
.insert(0, self
.label
['text'])
272 self
.entry
.selection_range(0, END
)
273 self
.entry
.pack(ipadx
=5)
274 self
.entry
.focus_set()
275 self
.entry
.bind("<Return>", self
.edit_finish
)
276 self
.entry
.bind("<Escape>", self
.edit_cancel
)
278 def edit_finish(self
, event
=None):
282 except AttributeError:
286 if text
and text
!= self
.item
.GetText():
287 self
.item
.SetText(text
)
288 text
= self
.item
.GetText()
289 self
.label
['text'] = text
291 self
.canvas
.focus_set()
293 def edit_cancel(self
, event
=None):
297 except AttributeError:
301 self
.canvas
.focus_set()
306 """Abstract class representing tree items.
308 Methods should typically be overridden, otherwise a default action
314 """Constructor. Do whatever you need to do."""
317 """Return text string to display."""
319 def GetLabelText(self
):
320 """Return label text string to display in front of text (if any)."""
324 def _IsExpandable(self
):
325 """Do not override! Called by TreeNode."""
326 if self
.expandable
is None:
327 self
.expandable
= self
.IsExpandable()
328 return self
.expandable
330 def IsExpandable(self
):
331 """Return whether there are subitems."""
334 def _GetSubList(self
):
335 """Do not override! Called by TreeNode."""
336 if not self
.IsExpandable():
338 sublist
= self
.GetSubList()
343 def IsEditable(self
):
344 """Return whether the item's text may be edited."""
346 def SetText(self
, text
):
347 """Change the item's text (if it is editable)."""
349 def GetIconName(self
):
350 """Return name of icon to be displayed normally."""
352 def GetSelectedIconName(self
):
353 """Return name of icon to be displayed when selected."""
355 def GetSubList(self
):
356 """Return list of items forming sublist."""
358 def OnDoubleClick(self
):
359 """Called on a double-click on the item."""
362 # Example application
364 class FileTreeItem(TreeItem
):
366 """Example TreeItem subclass -- browse the file system."""
368 def __init__(self
, path
):
372 return os
.path
.basename(self
.path
) or self
.path
374 def IsEditable(self
):
375 return os
.path
.basename(self
.path
) != ""
377 def SetText(self
, text
):
378 newpath
= os
.path
.dirname(self
.path
)
379 newpath
= os
.path
.join(newpath
, text
)
380 if os
.path
.dirname(newpath
) != os
.path
.dirname(self
.path
):
383 os
.rename(self
.path
, newpath
)
388 def GetIconName(self
):
389 if not self
.IsExpandable():
390 return "python" # XXX wish there was a "file" icon
392 def IsExpandable(self
):
393 return os
.path
.isdir(self
.path
)
395 def GetSubList(self
):
397 names
= os
.listdir(self
.path
)
400 names
.sort(lambda a
, b
: cmp(os
.path
.normcase(a
), os
.path
.normcase(b
)))
403 item
= FileTreeItem(os
.path
.join(self
.path
, name
))
408 # A canvas widget with scroll bars and some useful bindings
410 class ScrolledCanvas
:
411 def __init__(self
, master
, **opts
):
412 if not opts
.has_key('yscrollincrement'):
413 opts
['yscrollincrement'] = 17
415 self
.frame
= Frame(master
)
416 self
.frame
.rowconfigure(0, weight
=1)
417 self
.frame
.columnconfigure(0, weight
=1)
418 self
.canvas
= Canvas(self
.frame
, **opts
)
419 self
.canvas
.grid(row
=0, column
=0, sticky
="nsew")
420 self
.vbar
= Scrollbar(self
.frame
, name
="vbar")
421 self
.vbar
.grid(row
=0, column
=1, sticky
="nse")
422 self
.hbar
= Scrollbar(self
.frame
, name
="hbar", orient
="horizontal")
423 self
.hbar
.grid(row
=1, column
=0, sticky
="ews")
424 self
.canvas
['yscrollcommand'] = self
.vbar
.set
425 self
.vbar
['command'] = self
.canvas
.yview
426 self
.canvas
['xscrollcommand'] = self
.hbar
.set
427 self
.hbar
['command'] = self
.canvas
.xview
428 self
.canvas
.bind("<Key-Prior>", self
.page_up
)
429 self
.canvas
.bind("<Key-Next>", self
.page_down
)
430 self
.canvas
.bind("<Key-Up>", self
.unit_up
)
431 self
.canvas
.bind("<Key-Down>", self
.unit_down
)
432 #if isinstance(master, Toplevel) or isinstance(master, Tk):
433 self
.canvas
.bind("<Alt-Key-2>", self
.zoom_height
)
434 self
.canvas
.focus_set()
435 def page_up(self
, event
):
436 self
.canvas
.yview_scroll(-1, "page")
438 def page_down(self
, event
):
439 self
.canvas
.yview_scroll(1, "page")
441 def unit_up(self
, event
):
442 self
.canvas
.yview_scroll(-1, "unit")
444 def unit_down(self
, event
):
445 self
.canvas
.yview_scroll(1, "unit")
447 def zoom_height(self
, event
):
448 ZoomHeight
.zoom_height(self
.master
)
456 root
= Toplevel(PyShell
.root
)
457 root
.configure(bd
=0, bg
="yellow")
459 sc
= ScrolledCanvas(root
, bg
="white", highlightthickness
=0, takefocus
=1)
460 sc
.frame
.pack(expand
=1, fill
="both")
461 item
= FileTreeItem("C:/windows/desktop")
462 node
= TreeNode(sc
.canvas
, None, item
)
466 # test w/o scrolling canvas
469 canvas
= Canvas(root
, bg
="white", highlightthickness
=0)
470 canvas
.pack(expand
=1, fill
="both")
471 item
= FileTreeItem(os
.curdir
)
472 node
= TreeNode(canvas
, None, item
)
476 if __name__
== '__main__':