ยปCore Development>Code coverage>Lib/idlelib/tree.py

Python code coverage for Lib/idlelib/tree.py

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