blob: 2e3f9c14a1981419190165f8e952bb38e2801e17 [file] [log] [blame]
Kurt B. Kaiserb1754452005-11-18 22:05:48 +00001"""
Terry Jan Reedy6fa5bdc2016-05-28 13:22:31 -04002An auto-completion window for IDLE, used by the autocomplete extension
Kurt B. Kaiserb1754452005-11-18 22:05:48 +00003"""
mlouielu778b4842017-06-14 23:13:19 +08004import platform
5
Georg Brandl14fc4272008-05-17 18:39:55 +00006from tkinter import *
Victor Stinner6900f162020-04-30 03:28:51 +02007from tkinter.ttk import Scrollbar
Terry Jan Reedybfbaa6b2016-08-31 00:50:55 -04008
Terry Jan Reedy12131232019-08-04 19:48:52 -04009from idlelib.autocomplete import FILES, ATTRS
Terry Jan Reedybfbaa6b2016-08-31 00:50:55 -040010from idlelib.multicall import MC_SHIFT
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000011
12HIDE_VIRTUAL_EVENT_NAME = "<<autocompletewindow-hide>>"
mlouielu778b4842017-06-14 23:13:19 +080013HIDE_FOCUS_OUT_SEQUENCE = "<FocusOut>"
14HIDE_SEQUENCES = (HIDE_FOCUS_OUT_SEQUENCE, "<ButtonPress>")
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000015KEYPRESS_VIRTUAL_EVENT_NAME = "<<autocompletewindow-keypress>>"
16# We need to bind event beyond <Key> so that the function will be called
17# before the default specific IDLE function
Thomas Wouterscf297e42007-02-23 15:07:44 +000018KEYPRESS_SEQUENCES = ("<Key>", "<Key-BackSpace>", "<Key-Return>", "<Key-Tab>",
19 "<Key-Up>", "<Key-Down>", "<Key-Home>", "<Key-End>",
JohnnyNajera232689b2019-12-10 01:22:16 +020020 "<Key-Prior>", "<Key-Next>", "<Key-Escape>")
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000021KEYRELEASE_VIRTUAL_EVENT_NAME = "<<autocompletewindow-keyrelease>>"
22KEYRELEASE_SEQUENCE = "<KeyRelease>"
Thomas Wouterscf297e42007-02-23 15:07:44 +000023LISTUPDATE_SEQUENCE = "<B1-ButtonRelease>"
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000024WINCONFIG_SEQUENCE = "<Configure>"
Thomas Wouterscf297e42007-02-23 15:07:44 +000025DOUBLECLICK_SEQUENCE = "<B1-Double-ButtonRelease>"
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000026
27class AutoCompleteWindow:
28
Tal Einatb43cc312021-05-03 05:27:38 +030029 def __init__(self, widget, tags):
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000030 # The widget (Text) on which we place the AutoCompleteWindow
31 self.widget = widget
Tal Einatb43cc312021-05-03 05:27:38 +030032 # Tags to mark inserted text with
33 self.tags = tags
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000034 # The widgets we create
35 self.autocompletewindow = self.listbox = self.scrollbar = None
36 # The default foreground and background of a selection. Saved because
37 # they are changed to the regular colors of list items when the
38 # completion start is not a prefix of the selected completion
39 self.origselforeground = self.origselbackground = None
40 # The list of completions
41 self.completions = None
42 # A list with more completions, or None
43 self.morecompletions = None
Terry Jan Reedy12131232019-08-04 19:48:52 -040044 # The completion mode, either autocomplete.ATTRS or .FILES.
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000045 self.mode = None
46 # The current completion start, on the text box (a string)
47 self.start = None
48 # The index of the start of the completion
49 self.startindex = None
50 # The last typed start, used so that when the selection changes,
51 # the new start will be as close as possible to the last typed one.
52 self.lasttypedstart = None
53 # Do we have an indication that the user wants the completion window
54 # (for example, he clicked the list)
55 self.userwantswindow = None
56 # event ids
Tal Einat71662dc2019-08-14 20:06:06 +030057 self.hideid = self.keypressid = self.listupdateid = \
58 self.winconfigid = self.keyreleaseid = self.doubleclickid = None
Thomas Wouterscf297e42007-02-23 15:07:44 +000059 # Flag set if last keypress was a tab
60 self.lastkey_was_tab = False
Tal Einat71662dc2019-08-14 20:06:06 +030061 # Flag set to avoid recursive <Configure> callback invocations.
62 self.is_configuring = False
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000063
64 def _change_start(self, newstart):
Christian Heimes81ee3ef2008-05-04 22:42:01 +000065 min_len = min(len(self.start), len(newstart))
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000066 i = 0
Christian Heimes81ee3ef2008-05-04 22:42:01 +000067 while i < min_len and self.start[i] == newstart[i]:
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000068 i += 1
69 if i < len(self.start):
70 self.widget.delete("%s+%dc" % (self.startindex, i),
71 "%s+%dc" % (self.startindex, len(self.start)))
72 if i < len(newstart):
73 self.widget.insert("%s+%dc" % (self.startindex, i),
Tal Einatb43cc312021-05-03 05:27:38 +030074 newstart[i:],
75 self.tags)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000076 self.start = newstart
77
78 def _binary_search(self, s):
79 """Find the first index in self.completions where completions[i] is
Terry Jan Reedy12131232019-08-04 19:48:52 -040080 greater or equal to s, or the last index if there is no such.
81 """
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000082 i = 0; j = len(self.completions)
83 while j > i:
84 m = (i + j) // 2
85 if self.completions[m] >= s:
86 j = m
87 else:
88 i = m + 1
89 return min(i, len(self.completions)-1)
90
91 def _complete_string(self, s):
92 """Assuming that s is the prefix of a string in self.completions,
93 return the longest string which is a prefix of all the strings which
Terry Jan Reedy12131232019-08-04 19:48:52 -040094 s is a prefix of them. If s is not a prefix of a string, return s.
95 """
Kurt B. Kaiserb1754452005-11-18 22:05:48 +000096 first = self._binary_search(s)
97 if self.completions[first][:len(s)] != s:
98 # There is not even one completion which s is a prefix of.
99 return s
100 # Find the end of the range of completions where s is a prefix of.
101 i = first + 1
102 j = len(self.completions)
103 while j > i:
104 m = (i + j) // 2
105 if self.completions[m][:len(s)] != s:
106 j = m
107 else:
108 i = m + 1
109 last = i-1
110
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000111 if first == last: # only one possible completion
112 return self.completions[first]
113
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000114 # We should return the maximum prefix of first and last
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000115 first_comp = self.completions[first]
116 last_comp = self.completions[last]
117 min_len = min(len(first_comp), len(last_comp))
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000118 i = len(s)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000119 while i < min_len and first_comp[i] == last_comp[i]:
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000120 i += 1
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000121 return first_comp[:i]
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000122
123 def _selection_changed(self):
Terry Jan Reedy12131232019-08-04 19:48:52 -0400124 """Call when the selection of the Listbox has changed.
125
126 Updates the Listbox display and calls _change_start.
127 """
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000128 cursel = int(self.listbox.curselection()[0])
129
130 self.listbox.see(cursel)
131
132 lts = self.lasttypedstart
133 selstart = self.completions[cursel]
134 if self._binary_search(lts) == cursel:
135 newstart = lts
136 else:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000137 min_len = min(len(lts), len(selstart))
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000138 i = 0
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000139 while i < min_len and lts[i] == selstart[i]:
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000140 i += 1
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000141 newstart = selstart[:i]
142 self._change_start(newstart)
143
144 if self.completions[cursel][:len(self.start)] == self.start:
145 # start is a prefix of the selected completion
146 self.listbox.configure(selectbackground=self.origselbackground,
147 selectforeground=self.origselforeground)
148 else:
149 self.listbox.configure(selectbackground=self.listbox.cget("bg"),
150 selectforeground=self.listbox.cget("fg"))
151 # If there are more completions, show them, and call me again.
152 if self.morecompletions:
153 self.completions = self.morecompletions
154 self.morecompletions = None
155 self.listbox.delete(0, END)
156 for item in self.completions:
157 self.listbox.insert(END, item)
158 self.listbox.select_set(self._binary_search(self.start))
159 self._selection_changed()
160
161 def show_window(self, comp_lists, index, complete, mode, userWantsWin):
162 """Show the autocomplete list, bind events.
Terry Jan Reedy12131232019-08-04 19:48:52 -0400163
164 If complete is True, complete the text, and if there is exactly
165 one matching completion, don't open a list.
166 """
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000167 # Handle the start we already have
168 self.completions, self.morecompletions = comp_lists
169 self.mode = mode
170 self.startindex = self.widget.index(index)
171 self.start = self.widget.get(self.startindex, "insert")
172 if complete:
173 completed = self._complete_string(self.start)
Serhiy Storchakadd4754e2013-09-11 22:46:27 +0300174 start = self.start
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000175 self._change_start(completed)
176 i = self._binary_search(completed)
177 if self.completions[i] == completed and \
178 (i == len(self.completions)-1 or
179 self.completions[i+1][:len(completed)] != completed):
180 # There is exactly one matching completion
Serhiy Storchakadd4754e2013-09-11 22:46:27 +0300181 return completed == start
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000182 self.userwantswindow = userWantsWin
183 self.lasttypedstart = self.start
184
185 # Put widgets in place
186 self.autocompletewindow = acw = Toplevel(self.widget)
187 # Put it in a position so that it is not seen.
188 acw.wm_geometry("+10000+10000")
189 # Make it float
190 acw.wm_overrideredirect(1)
191 try:
192 # This command is only needed and available on Tk >= 8.4.0 for OSX
193 # Without it, call tips intrude on the typing process by grabbing
194 # the focus.
195 acw.tk.call("::tk::unsupported::MacWindowStyle", "style", acw._w,
196 "help", "noActivates")
197 except TclError:
198 pass
199 self.scrollbar = scrollbar = Scrollbar(acw, orient=VERTICAL)
200 self.listbox = listbox = Listbox(acw, yscrollcommand=scrollbar.set,
Terry Jan Reedy491ef532019-03-10 20:18:40 -0400201 exportselection=False)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000202 for item in self.completions:
203 listbox.insert(END, item)
204 self.origselforeground = listbox.cget("selectforeground")
205 self.origselbackground = listbox.cget("selectbackground")
206 scrollbar.config(command=listbox.yview)
207 scrollbar.pack(side=RIGHT, fill=Y)
208 listbox.pack(side=LEFT, fill=BOTH, expand=True)
Terry Jan Reedyd2134c72015-09-26 20:03:57 -0400209 acw.lift() # work around bug in Tk 8.5.18+ (issue #24570)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000210
211 # Initialize the listbox selection
212 self.listbox.select_set(self._binary_search(self.start))
213 self._selection_changed()
214
215 # bind events
mlouielu778b4842017-06-14 23:13:19 +0800216 self.hideaid = acw.bind(HIDE_VIRTUAL_EVENT_NAME, self.hide_event)
217 self.hidewid = self.widget.bind(HIDE_VIRTUAL_EVENT_NAME, self.hide_event)
218 acw.event_add(HIDE_VIRTUAL_EVENT_NAME, HIDE_FOCUS_OUT_SEQUENCE)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000219 for seq in HIDE_SEQUENCES:
220 self.widget.event_add(HIDE_VIRTUAL_EVENT_NAME, seq)
mlouielu778b4842017-06-14 23:13:19 +0800221
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000222 self.keypressid = self.widget.bind(KEYPRESS_VIRTUAL_EVENT_NAME,
223 self.keypress_event)
224 for seq in KEYPRESS_SEQUENCES:
225 self.widget.event_add(KEYPRESS_VIRTUAL_EVENT_NAME, seq)
226 self.keyreleaseid = self.widget.bind(KEYRELEASE_VIRTUAL_EVENT_NAME,
227 self.keyrelease_event)
228 self.widget.event_add(KEYRELEASE_VIRTUAL_EVENT_NAME,KEYRELEASE_SEQUENCE)
229 self.listupdateid = listbox.bind(LISTUPDATE_SEQUENCE,
Thomas Wouterscf297e42007-02-23 15:07:44 +0000230 self.listselect_event)
Tal Einat71662dc2019-08-14 20:06:06 +0300231 self.is_configuring = False
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000232 self.winconfigid = acw.bind(WINCONFIG_SEQUENCE, self.winconfig_event)
233 self.doubleclickid = listbox.bind(DOUBLECLICK_SEQUENCE,
234 self.doubleclick_event)
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400235 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000236
237 def winconfig_event(self, event):
Tal Einat71662dc2019-08-14 20:06:06 +0300238 if self.is_configuring:
239 # Avoid running on recursive <Configure> callback invocations.
240 return
241
242 self.is_configuring = True
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000243 if not self.is_active():
244 return
Miss Islington (bot)448abe82021-05-27 23:39:36 -0700245
246 # Since the <Configure> event may occur after the completion window is gone,
247 # catch potential TclError exceptions when accessing acw. See: bpo-41611.
248 try:
249 # Position the completion list window
250 text = self.widget
251 text.see(self.startindex)
252 x, y, cx, cy = text.bbox(self.startindex)
253 acw = self.autocompletewindow
254 if platform.system().startswith('Windows'):
255 # On Windows an update() call is needed for the completion
256 # list window to be created, so that we can fetch its width
257 # and height. However, this is not needed on other platforms
258 # (tested on Ubuntu and macOS) but at one point began
259 # causing freezes on macOS. See issues 37849 and 41611.
260 acw.update()
261 acw_width, acw_height = acw.winfo_width(), acw.winfo_height()
262 text_width, text_height = text.winfo_width(), text.winfo_height()
263 new_x = text.winfo_rootx() + min(x, max(0, text_width - acw_width))
264 new_y = text.winfo_rooty() + y
265 if (text_height - (y + cy) >= acw_height # enough height below
266 or y < acw_height): # not enough height above
267 # place acw below current line
268 new_y += cy
269 else:
270 # place acw above current line
271 new_y -= acw_height
272 acw.wm_geometry("+%d+%d" % (new_x, new_y))
273 acw.update_idletasks()
274 except TclError:
275 pass
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000276
mlouielu778b4842017-06-14 23:13:19 +0800277 if platform.system().startswith('Windows'):
Miss Islington (bot)448abe82021-05-27 23:39:36 -0700278 # See issue 15786. When on Windows platform, Tk will misbehave
mlouielu778b4842017-06-14 23:13:19 +0800279 # to call winconfig_event multiple times, we need to prevent this,
280 # otherwise mouse button double click will not be able to used.
Miss Islington (bot)448abe82021-05-27 23:39:36 -0700281 try:
282 acw.unbind(WINCONFIG_SEQUENCE, self.winconfigid)
283 except TclError:
284 pass
mlouielu778b4842017-06-14 23:13:19 +0800285 self.winconfigid = None
286
Tal Einat71662dc2019-08-14 20:06:06 +0300287 self.is_configuring = False
288
mlouielu778b4842017-06-14 23:13:19 +0800289 def _hide_event_check(self):
290 if not self.autocompletewindow:
291 return
292
293 try:
294 if not self.autocompletewindow.focus_get():
295 self.hide_window()
296 except KeyError:
297 # See issue 734176, when user click on menu, acw.focus_get()
298 # will get KeyError.
Terry Jan Reedyc665dfd2016-07-24 23:01:28 -0400299 self.hide_window()
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000300
mlouielu778b4842017-06-14 23:13:19 +0800301 def hide_event(self, event):
302 # Hide autocomplete list if it exists and does not have focus or
303 # mouse click on widget / text area.
304 if self.is_active():
305 if event.type == EventType.FocusOut:
Terry Jan Reedy33c74202018-06-20 22:49:55 -0400306 # On Windows platform, it will need to delay the check for
mlouielu778b4842017-06-14 23:13:19 +0800307 # acw.focus_get() when click on acw, otherwise it will return
308 # None and close the window
309 self.widget.after(1, self._hide_event_check)
310 elif event.type == EventType.ButtonPress:
311 # ButtonPress event only bind to self.widget
312 self.hide_window()
313
Thomas Wouterscf297e42007-02-23 15:07:44 +0000314 def listselect_event(self, event):
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400315 if self.is_active():
316 self.userwantswindow = True
317 cursel = int(self.listbox.curselection()[0])
318 self._change_start(self.completions[cursel])
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000319
320 def doubleclick_event(self, event):
321 # Put the selected completion in the text, and close the list
322 cursel = int(self.listbox.curselection()[0])
323 self._change_start(self.completions[cursel])
324 self.hide_window()
325
326 def keypress_event(self, event):
327 if not self.is_active():
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400328 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000329 keysym = event.keysym
330 if hasattr(event, "mc_state"):
331 state = event.mc_state
332 else:
333 state = 0
Thomas Wouterscf297e42007-02-23 15:07:44 +0000334 if keysym != "Tab":
335 self.lastkey_was_tab = False
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000336 if (len(keysym) == 1 or keysym in ("underscore", "BackSpace")
Terry Jan Reedy12131232019-08-04 19:48:52 -0400337 or (self.mode == FILES and keysym in
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000338 ("period", "minus"))) \
339 and not (state & ~MC_SHIFT):
340 # Normal editing of text
341 if len(keysym) == 1:
342 self._change_start(self.start + keysym)
343 elif keysym == "underscore":
344 self._change_start(self.start + '_')
345 elif keysym == "period":
346 self._change_start(self.start + '.')
347 elif keysym == "minus":
348 self._change_start(self.start + '-')
349 else:
350 # keysym == "BackSpace"
351 if len(self.start) == 0:
352 self.hide_window()
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400353 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000354 self._change_start(self.start[:-1])
355 self.lasttypedstart = self.start
356 self.listbox.select_clear(0, int(self.listbox.curselection()[0]))
357 self.listbox.select_set(self._binary_search(self.start))
358 self._selection_changed()
359 return "break"
360
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000361 elif keysym == "Return":
terryjreedy32fd8742017-06-14 15:43:15 -0400362 self.complete()
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000363 self.hide_window()
terryjreedy32fd8742017-06-14 15:43:15 -0400364 return 'break'
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000365
Terry Jan Reedy12131232019-08-04 19:48:52 -0400366 elif (self.mode == ATTRS and keysym in
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000367 ("period", "space", "parenleft", "parenright", "bracketleft",
368 "bracketright")) or \
Terry Jan Reedy12131232019-08-04 19:48:52 -0400369 (self.mode == FILES and keysym in
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000370 ("slash", "backslash", "quotedbl", "apostrophe")) \
371 and not (state & ~MC_SHIFT):
372 # If start is a prefix of the selection, but is not '' when
373 # completing file names, put the whole
374 # selected completion. Anyway, close the list.
375 cursel = int(self.listbox.curselection()[0])
376 if self.completions[cursel][:len(self.start)] == self.start \
Terry Jan Reedy12131232019-08-04 19:48:52 -0400377 and (self.mode == ATTRS or self.start):
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000378 self._change_start(self.completions[cursel])
379 self.hide_window()
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400380 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000381
382 elif keysym in ("Home", "End", "Prior", "Next", "Up", "Down") and \
383 not state:
384 # Move the selection in the listbox
385 self.userwantswindow = True
386 cursel = int(self.listbox.curselection()[0])
387 if keysym == "Home":
388 newsel = 0
389 elif keysym == "End":
390 newsel = len(self.completions)-1
391 elif keysym in ("Prior", "Next"):
392 jump = self.listbox.nearest(self.listbox.winfo_height()) - \
393 self.listbox.nearest(0)
394 if keysym == "Prior":
395 newsel = max(0, cursel-jump)
396 else:
397 assert keysym == "Next"
398 newsel = min(len(self.completions)-1, cursel+jump)
399 elif keysym == "Up":
400 newsel = max(0, cursel-1)
401 else:
402 assert keysym == "Down"
403 newsel = min(len(self.completions)-1, cursel+1)
404 self.listbox.select_clear(cursel)
405 self.listbox.select_set(newsel)
406 self._selection_changed()
Thomas Wouterscf297e42007-02-23 15:07:44 +0000407 self._change_start(self.completions[newsel])
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000408 return "break"
409
410 elif (keysym == "Tab" and not state):
Thomas Wouterscf297e42007-02-23 15:07:44 +0000411 if self.lastkey_was_tab:
412 # two tabs in a row; insert current selection and close acw
413 cursel = int(self.listbox.curselection()[0])
414 self._change_start(self.completions[cursel])
415 self.hide_window()
416 return "break"
417 else:
418 # first tab; let AutoComplete handle the completion
419 self.userwantswindow = True
420 self.lastkey_was_tab = True
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400421 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000422
Guido van Rossum89da5d72006-08-22 00:21:25 +0000423 elif any(s in keysym for s in ("Shift", "Control", "Alt",
424 "Meta", "Command", "Option")):
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000425 # A modifier key, so ignore
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400426 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000427
Martin v. Löwis97aa21b2012-06-03 12:26:09 +0200428 elif event.char and event.char >= ' ':
Martin v. Löwis862d13a2012-06-03 11:55:32 +0200429 # Regular character with a non-length-1 keycode
430 self._change_start(self.start + event.char)
431 self.lasttypedstart = self.start
432 self.listbox.select_clear(0, int(self.listbox.curselection()[0]))
433 self.listbox.select_set(self._binary_search(self.start))
434 self._selection_changed()
435 return "break"
436
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000437 else:
438 # Unknown event, close the window and let it through.
439 self.hide_window()
Terry Jan Reedyc74fb9c2016-07-24 20:35:43 -0400440 return None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000441
442 def keyrelease_event(self, event):
443 if not self.is_active():
444 return
445 if self.widget.index("insert") != \
446 self.widget.index("%s+%dc" % (self.startindex, len(self.start))):
447 # If we didn't catch an event which moved the insert, close window
448 self.hide_window()
449
450 def is_active(self):
451 return self.autocompletewindow is not None
452
453 def complete(self):
454 self._change_start(self._complete_string(self.start))
455 # The selection doesn't change.
456
457 def hide_window(self):
458 if not self.is_active():
459 return
460
461 # unbind events
mlouielu778b4842017-06-14 23:13:19 +0800462 self.autocompletewindow.event_delete(HIDE_VIRTUAL_EVENT_NAME,
463 HIDE_FOCUS_OUT_SEQUENCE)
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000464 for seq in HIDE_SEQUENCES:
465 self.widget.event_delete(HIDE_VIRTUAL_EVENT_NAME, seq)
mlouielu778b4842017-06-14 23:13:19 +0800466
467 self.autocompletewindow.unbind(HIDE_VIRTUAL_EVENT_NAME, self.hideaid)
468 self.widget.unbind(HIDE_VIRTUAL_EVENT_NAME, self.hidewid)
469 self.hideaid = None
470 self.hidewid = None
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000471 for seq in KEYPRESS_SEQUENCES:
472 self.widget.event_delete(KEYPRESS_VIRTUAL_EVENT_NAME, seq)
473 self.widget.unbind(KEYPRESS_VIRTUAL_EVENT_NAME, self.keypressid)
474 self.keypressid = None
475 self.widget.event_delete(KEYRELEASE_VIRTUAL_EVENT_NAME,
476 KEYRELEASE_SEQUENCE)
477 self.widget.unbind(KEYRELEASE_VIRTUAL_EVENT_NAME, self.keyreleaseid)
478 self.keyreleaseid = None
479 self.listbox.unbind(LISTUPDATE_SEQUENCE, self.listupdateid)
480 self.listupdateid = None
mlouielu778b4842017-06-14 23:13:19 +0800481 if self.winconfigid:
482 self.autocompletewindow.unbind(WINCONFIG_SEQUENCE, self.winconfigid)
483 self.winconfigid = None
484
485 # Re-focusOn frame.text (See issue #15786)
486 self.widget.focus_set()
Kurt B. Kaiserb1754452005-11-18 22:05:48 +0000487
488 # destroy widgets
489 self.scrollbar.destroy()
490 self.scrollbar = None
491 self.listbox.destroy()
492 self.listbox = None
493 self.autocompletewindow.destroy()
494 self.autocompletewindow = None
Terry Jan Reedyee5ef302018-06-15 18:20:55 -0400495
496
497if __name__ == '__main__':
498 from unittest import main
499 main('idlelib.idle_test.test_autocomplete_w', verbosity=2, exit=False)
500
501# TODO: autocomplete/w htest here