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

Python code coverage for Lib/idlelib/AutoCompleteWindow.py

#countcontent
1n/a"""
2n/aAn auto-completion window for IDLE, used by the AutoComplete extension
3n/a"""
4n/afrom tkinter import *
5n/afrom idlelib.MultiCall import MC_SHIFT
6n/afrom idlelib.AutoComplete import COMPLETE_FILES, COMPLETE_ATTRIBUTES
7n/a
8n/aHIDE_VIRTUAL_EVENT_NAME = "<<autocompletewindow-hide>>"
9n/aHIDE_SEQUENCES = ("<FocusOut>", "<ButtonPress>")
10n/aKEYPRESS_VIRTUAL_EVENT_NAME = "<<autocompletewindow-keypress>>"
11n/a# We need to bind event beyond <Key> so that the function will be called
12n/a# before the default specific IDLE function
13n/aKEYPRESS_SEQUENCES = ("<Key>", "<Key-BackSpace>", "<Key-Return>", "<Key-Tab>",
14n/a "<Key-Up>", "<Key-Down>", "<Key-Home>", "<Key-End>",
15n/a "<Key-Prior>", "<Key-Next>")
16n/aKEYRELEASE_VIRTUAL_EVENT_NAME = "<<autocompletewindow-keyrelease>>"
17n/aKEYRELEASE_SEQUENCE = "<KeyRelease>"
18n/aLISTUPDATE_SEQUENCE = "<B1-ButtonRelease>"
19n/aWINCONFIG_SEQUENCE = "<Configure>"
20n/aDOUBLECLICK_SEQUENCE = "<B1-Double-ButtonRelease>"
21n/a
22n/aclass AutoCompleteWindow:
23n/a
24n/a def __init__(self, widget):
25n/a # The widget (Text) on which we place the AutoCompleteWindow
26n/a self.widget = widget
27n/a # The widgets we create
28n/a self.autocompletewindow = self.listbox = self.scrollbar = None
29n/a # The default foreground and background of a selection. Saved because
30n/a # they are changed to the regular colors of list items when the
31n/a # completion start is not a prefix of the selected completion
32n/a self.origselforeground = self.origselbackground = None
33n/a # The list of completions
34n/a self.completions = None
35n/a # A list with more completions, or None
36n/a self.morecompletions = None
37n/a # The completion mode. Either AutoComplete.COMPLETE_ATTRIBUTES or
38n/a # AutoComplete.COMPLETE_FILES
39n/a self.mode = None
40n/a # The current completion start, on the text box (a string)
41n/a self.start = None
42n/a # The index of the start of the completion
43n/a self.startindex = None
44n/a # The last typed start, used so that when the selection changes,
45n/a # the new start will be as close as possible to the last typed one.
46n/a self.lasttypedstart = None
47n/a # Do we have an indication that the user wants the completion window
48n/a # (for example, he clicked the list)
49n/a self.userwantswindow = None
50n/a # event ids
51n/a self.hideid = self.keypressid = self.listupdateid = self.winconfigid \
52n/a = self.keyreleaseid = self.doubleclickid = None
53n/a # Flag set if last keypress was a tab
54n/a self.lastkey_was_tab = False
55n/a
56n/a def _change_start(self, newstart):
57n/a min_len = min(len(self.start), len(newstart))
58n/a i = 0
59n/a while i < min_len and self.start[i] == newstart[i]:
60n/a i += 1
61n/a if i < len(self.start):
62n/a self.widget.delete("%s+%dc" % (self.startindex, i),
63n/a "%s+%dc" % (self.startindex, len(self.start)))
64n/a if i < len(newstart):
65n/a self.widget.insert("%s+%dc" % (self.startindex, i),
66n/a newstart[i:])
67n/a self.start = newstart
68n/a
69n/a def _binary_search(self, s):
70n/a """Find the first index in self.completions where completions[i] is
71n/a greater or equal to s, or the last index if there is no such
72n/a one."""
73n/a i = 0; j = len(self.completions)
74n/a while j > i:
75n/a m = (i + j) // 2
76n/a if self.completions[m] >= s:
77n/a j = m
78n/a else:
79n/a i = m + 1
80n/a return min(i, len(self.completions)-1)
81n/a
82n/a def _complete_string(self, s):
83n/a """Assuming that s is the prefix of a string in self.completions,
84n/a return the longest string which is a prefix of all the strings which
85n/a s is a prefix of them. If s is not a prefix of a string, return s."""
86n/a first = self._binary_search(s)
87n/a if self.completions[first][:len(s)] != s:
88n/a # There is not even one completion which s is a prefix of.
89n/a return s
90n/a # Find the end of the range of completions where s is a prefix of.
91n/a i = first + 1
92n/a j = len(self.completions)
93n/a while j > i:
94n/a m = (i + j) // 2
95n/a if self.completions[m][:len(s)] != s:
96n/a j = m
97n/a else:
98n/a i = m + 1
99n/a last = i-1
100n/a
101n/a if first == last: # only one possible completion
102n/a return self.completions[first]
103n/a
104n/a # We should return the maximum prefix of first and last
105n/a first_comp = self.completions[first]
106n/a last_comp = self.completions[last]
107n/a min_len = min(len(first_comp), len(last_comp))
108n/a i = len(s)
109n/a while i < min_len and first_comp[i] == last_comp[i]:
110n/a i += 1
111n/a return first_comp[:i]
112n/a
113n/a def _selection_changed(self):
114n/a """Should be called when the selection of the Listbox has changed.
115n/a Updates the Listbox display and calls _change_start."""
116n/a cursel = int(self.listbox.curselection()[0])
117n/a
118n/a self.listbox.see(cursel)
119n/a
120n/a lts = self.lasttypedstart
121n/a selstart = self.completions[cursel]
122n/a if self._binary_search(lts) == cursel:
123n/a newstart = lts
124n/a else:
125n/a min_len = min(len(lts), len(selstart))
126n/a i = 0
127n/a while i < min_len and lts[i] == selstart[i]:
128n/a i += 1
129n/a newstart = selstart[:i]
130n/a self._change_start(newstart)
131n/a
132n/a if self.completions[cursel][:len(self.start)] == self.start:
133n/a # start is a prefix of the selected completion
134n/a self.listbox.configure(selectbackground=self.origselbackground,
135n/a selectforeground=self.origselforeground)
136n/a else:
137n/a self.listbox.configure(selectbackground=self.listbox.cget("bg"),
138n/a selectforeground=self.listbox.cget("fg"))
139n/a # If there are more completions, show them, and call me again.
140n/a if self.morecompletions:
141n/a self.completions = self.morecompletions
142n/a self.morecompletions = None
143n/a self.listbox.delete(0, END)
144n/a for item in self.completions:
145n/a self.listbox.insert(END, item)
146n/a self.listbox.select_set(self._binary_search(self.start))
147n/a self._selection_changed()
148n/a
149n/a def show_window(self, comp_lists, index, complete, mode, userWantsWin):
150n/a """Show the autocomplete list, bind events.
151n/a If complete is True, complete the text, and if there is exactly one
152n/a matching completion, don't open a list."""
153n/a # Handle the start we already have
154n/a self.completions, self.morecompletions = comp_lists
155n/a self.mode = mode
156n/a self.startindex = self.widget.index(index)
157n/a self.start = self.widget.get(self.startindex, "insert")
158n/a if complete:
159n/a completed = self._complete_string(self.start)
160n/a self._change_start(completed)
161n/a i = self._binary_search(completed)
162n/a if self.completions[i] == completed and \
163n/a (i == len(self.completions)-1 or
164n/a self.completions[i+1][:len(completed)] != completed):
165n/a # There is exactly one matching completion
166n/a return
167n/a self.userwantswindow = userWantsWin
168n/a self.lasttypedstart = self.start
169n/a
170n/a # Put widgets in place
171n/a self.autocompletewindow = acw = Toplevel(self.widget)
172n/a # Put it in a position so that it is not seen.
173n/a acw.wm_geometry("+10000+10000")
174n/a # Make it float
175n/a acw.wm_overrideredirect(1)
176n/a try:
177n/a # This command is only needed and available on Tk >= 8.4.0 for OSX
178n/a # Without it, call tips intrude on the typing process by grabbing
179n/a # the focus.
180n/a acw.tk.call("::tk::unsupported::MacWindowStyle", "style", acw._w,
181n/a "help", "noActivates")
182n/a except TclError:
183n/a pass
184n/a self.scrollbar = scrollbar = Scrollbar(acw, orient=VERTICAL)
185n/a self.listbox = listbox = Listbox(acw, yscrollcommand=scrollbar.set,
186n/a exportselection=False, bg="white")
187n/a for item in self.completions:
188n/a listbox.insert(END, item)
189n/a self.origselforeground = listbox.cget("selectforeground")
190n/a self.origselbackground = listbox.cget("selectbackground")
191n/a scrollbar.config(command=listbox.yview)
192n/a scrollbar.pack(side=RIGHT, fill=Y)
193n/a listbox.pack(side=LEFT, fill=BOTH, expand=True)
194n/a
195n/a # Initialize the listbox selection
196n/a self.listbox.select_set(self._binary_search(self.start))
197n/a self._selection_changed()
198n/a
199n/a # bind events
200n/a self.hideid = self.widget.bind(HIDE_VIRTUAL_EVENT_NAME,
201n/a self.hide_event)
202n/a for seq in HIDE_SEQUENCES:
203n/a self.widget.event_add(HIDE_VIRTUAL_EVENT_NAME, seq)
204n/a self.keypressid = self.widget.bind(KEYPRESS_VIRTUAL_EVENT_NAME,
205n/a self.keypress_event)
206n/a for seq in KEYPRESS_SEQUENCES:
207n/a self.widget.event_add(KEYPRESS_VIRTUAL_EVENT_NAME, seq)
208n/a self.keyreleaseid = self.widget.bind(KEYRELEASE_VIRTUAL_EVENT_NAME,
209n/a self.keyrelease_event)
210n/a self.widget.event_add(KEYRELEASE_VIRTUAL_EVENT_NAME,KEYRELEASE_SEQUENCE)
211n/a self.listupdateid = listbox.bind(LISTUPDATE_SEQUENCE,
212n/a self.listselect_event)
213n/a self.winconfigid = acw.bind(WINCONFIG_SEQUENCE, self.winconfig_event)
214n/a self.doubleclickid = listbox.bind(DOUBLECLICK_SEQUENCE,
215n/a self.doubleclick_event)
216n/a
217n/a def winconfig_event(self, event):
218n/a if not self.is_active():
219n/a return
220n/a # Position the completion list window
221n/a text = self.widget
222n/a text.see(self.startindex)
223n/a x, y, cx, cy = text.bbox(self.startindex)
224n/a acw = self.autocompletewindow
225n/a acw_width, acw_height = acw.winfo_width(), acw.winfo_height()
226n/a text_width, text_height = text.winfo_width(), text.winfo_height()
227n/a new_x = text.winfo_rootx() + min(x, max(0, text_width - acw_width))
228n/a new_y = text.winfo_rooty() + y
229n/a if (text_height - (y + cy) >= acw_height # enough height below
230n/a or y < acw_height): # not enough height above
231n/a # place acw below current line
232n/a new_y += cy
233n/a else:
234n/a # place acw above current line
235n/a new_y -= acw_height
236n/a acw.wm_geometry("+%d+%d" % (new_x, new_y))
237n/a
238n/a def hide_event(self, event):
239n/a if not self.is_active():
240n/a return
241n/a self.hide_window()
242n/a
243n/a def listselect_event(self, event):
244n/a if not self.is_active():
245n/a return
246n/a self.userwantswindow = True
247n/a cursel = int(self.listbox.curselection()[0])
248n/a self._change_start(self.completions[cursel])
249n/a
250n/a def doubleclick_event(self, event):
251n/a # Put the selected completion in the text, and close the list
252n/a cursel = int(self.listbox.curselection()[0])
253n/a self._change_start(self.completions[cursel])
254n/a self.hide_window()
255n/a
256n/a def keypress_event(self, event):
257n/a if not self.is_active():
258n/a return
259n/a keysym = event.keysym
260n/a if hasattr(event, "mc_state"):
261n/a state = event.mc_state
262n/a else:
263n/a state = 0
264n/a if keysym != "Tab":
265n/a self.lastkey_was_tab = False
266n/a if (len(keysym) == 1 or keysym in ("underscore", "BackSpace")
267n/a or (self.mode == COMPLETE_FILES and keysym in
268n/a ("period", "minus"))) \
269n/a and not (state & ~MC_SHIFT):
270n/a # Normal editing of text
271n/a if len(keysym) == 1:
272n/a self._change_start(self.start + keysym)
273n/a elif keysym == "underscore":
274n/a self._change_start(self.start + '_')
275n/a elif keysym == "period":
276n/a self._change_start(self.start + '.')
277n/a elif keysym == "minus":
278n/a self._change_start(self.start + '-')
279n/a else:
280n/a # keysym == "BackSpace"
281n/a if len(self.start) == 0:
282n/a self.hide_window()
283n/a return
284n/a self._change_start(self.start[:-1])
285n/a self.lasttypedstart = self.start
286n/a self.listbox.select_clear(0, int(self.listbox.curselection()[0]))
287n/a self.listbox.select_set(self._binary_search(self.start))
288n/a self._selection_changed()
289n/a return "break"
290n/a
291n/a elif keysym == "Return":
292n/a self.hide_window()
293n/a return
294n/a
295n/a elif (self.mode == COMPLETE_ATTRIBUTES and keysym in
296n/a ("period", "space", "parenleft", "parenright", "bracketleft",
297n/a "bracketright")) or \
298n/a (self.mode == COMPLETE_FILES and keysym in
299n/a ("slash", "backslash", "quotedbl", "apostrophe")) \
300n/a and not (state & ~MC_SHIFT):
301n/a # If start is a prefix of the selection, but is not '' when
302n/a # completing file names, put the whole
303n/a # selected completion. Anyway, close the list.
304n/a cursel = int(self.listbox.curselection()[0])
305n/a if self.completions[cursel][:len(self.start)] == self.start \
306n/a and (self.mode == COMPLETE_ATTRIBUTES or self.start):
307n/a self._change_start(self.completions[cursel])
308n/a self.hide_window()
309n/a return
310n/a
311n/a elif keysym in ("Home", "End", "Prior", "Next", "Up", "Down") and \
312n/a not state:
313n/a # Move the selection in the listbox
314n/a self.userwantswindow = True
315n/a cursel = int(self.listbox.curselection()[0])
316n/a if keysym == "Home":
317n/a newsel = 0
318n/a elif keysym == "End":
319n/a newsel = len(self.completions)-1
320n/a elif keysym in ("Prior", "Next"):
321n/a jump = self.listbox.nearest(self.listbox.winfo_height()) - \
322n/a self.listbox.nearest(0)
323n/a if keysym == "Prior":
324n/a newsel = max(0, cursel-jump)
325n/a else:
326n/a assert keysym == "Next"
327n/a newsel = min(len(self.completions)-1, cursel+jump)
328n/a elif keysym == "Up":
329n/a newsel = max(0, cursel-1)
330n/a else:
331n/a assert keysym == "Down"
332n/a newsel = min(len(self.completions)-1, cursel+1)
333n/a self.listbox.select_clear(cursel)
334n/a self.listbox.select_set(newsel)
335n/a self._selection_changed()
336n/a self._change_start(self.completions[newsel])
337n/a return "break"
338n/a
339n/a elif (keysym == "Tab" and not state):
340n/a if self.lastkey_was_tab:
341n/a # two tabs in a row; insert current selection and close acw
342n/a cursel = int(self.listbox.curselection()[0])
343n/a self._change_start(self.completions[cursel])
344n/a self.hide_window()
345n/a return "break"
346n/a else:
347n/a # first tab; let AutoComplete handle the completion
348n/a self.userwantswindow = True
349n/a self.lastkey_was_tab = True
350n/a return
351n/a
352n/a elif any(s in keysym for s in ("Shift", "Control", "Alt",
353n/a "Meta", "Command", "Option")):
354n/a # A modifier key, so ignore
355n/a return
356n/a
357n/a elif event.char and event.char >= ' ':
358n/a # Regular character with a non-length-1 keycode
359n/a self._change_start(self.start + event.char)
360n/a self.lasttypedstart = self.start
361n/a self.listbox.select_clear(0, int(self.listbox.curselection()[0]))
362n/a self.listbox.select_set(self._binary_search(self.start))
363n/a self._selection_changed()
364n/a return "break"
365n/a
366n/a else:
367n/a # Unknown event, close the window and let it through.
368n/a self.hide_window()
369n/a return
370n/a
371n/a def keyrelease_event(self, event):
372n/a if not self.is_active():
373n/a return
374n/a if self.widget.index("insert") != \
375n/a self.widget.index("%s+%dc" % (self.startindex, len(self.start))):
376n/a # If we didn't catch an event which moved the insert, close window
377n/a self.hide_window()
378n/a
379n/a def is_active(self):
380n/a return self.autocompletewindow is not None
381n/a
382n/a def complete(self):
383n/a self._change_start(self._complete_string(self.start))
384n/a # The selection doesn't change.
385n/a
386n/a def hide_window(self):
387n/a if not self.is_active():
388n/a return
389n/a
390n/a # unbind events
391n/a for seq in HIDE_SEQUENCES:
392n/a self.widget.event_delete(HIDE_VIRTUAL_EVENT_NAME, seq)
393n/a self.widget.unbind(HIDE_VIRTUAL_EVENT_NAME, self.hideid)
394n/a self.hideid = None
395n/a for seq in KEYPRESS_SEQUENCES:
396n/a self.widget.event_delete(KEYPRESS_VIRTUAL_EVENT_NAME, seq)
397n/a self.widget.unbind(KEYPRESS_VIRTUAL_EVENT_NAME, self.keypressid)
398n/a self.keypressid = None
399n/a self.widget.event_delete(KEYRELEASE_VIRTUAL_EVENT_NAME,
400n/a KEYRELEASE_SEQUENCE)
401n/a self.widget.unbind(KEYRELEASE_VIRTUAL_EVENT_NAME, self.keyreleaseid)
402n/a self.keyreleaseid = None
403n/a self.listbox.unbind(LISTUPDATE_SEQUENCE, self.listupdateid)
404n/a self.listupdateid = None
405n/a self.autocompletewindow.unbind(WINCONFIG_SEQUENCE, self.winconfigid)
406n/a self.winconfigid = None
407n/a
408n/a # destroy widgets
409n/a self.scrollbar.destroy()
410n/a self.scrollbar = None
411n/a self.listbox.destroy()
412n/a self.listbox = None
413n/a self.autocompletewindow.destroy()
414n/a self.autocompletewindow = None