logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

autocomplete_w.py (21097B)


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