sidebar.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. """Line numbering implementation for IDLE as an extension.
  2. Includes BaseSideBar which can be extended for other sidebar based extensions
  3. """
  4. import contextlib
  5. import functools
  6. import itertools
  7. import tkinter as tk
  8. from tkinter.font import Font
  9. from idlelib.config import idleConf
  10. from idlelib.delegator import Delegator
  11. from idlelib import macosx
  12. def get_lineno(text, index):
  13. """Return the line number of an index in a Tk text widget."""
  14. text_index = text.index(index)
  15. return int(float(text_index)) if text_index else None
  16. def get_end_linenumber(text):
  17. """Return the number of the last line in a Tk text widget."""
  18. return get_lineno(text, 'end-1c')
  19. def get_displaylines(text, index):
  20. """Display height, in lines, of a logical line in a Tk text widget."""
  21. res = text.count(f"{index} linestart",
  22. f"{index} lineend",
  23. "displaylines")
  24. return res[0] if res else 0
  25. def get_widget_padding(widget):
  26. """Get the total padding of a Tk widget, including its border."""
  27. # TODO: use also in codecontext.py
  28. manager = widget.winfo_manager()
  29. if manager == 'pack':
  30. info = widget.pack_info()
  31. elif manager == 'grid':
  32. info = widget.grid_info()
  33. else:
  34. raise ValueError(f"Unsupported geometry manager: {manager}")
  35. # All values are passed through getint(), since some
  36. # values may be pixel objects, which can't simply be added to ints.
  37. padx = sum(map(widget.tk.getint, [
  38. info['padx'],
  39. widget.cget('padx'),
  40. widget.cget('border'),
  41. ]))
  42. pady = sum(map(widget.tk.getint, [
  43. info['pady'],
  44. widget.cget('pady'),
  45. widget.cget('border'),
  46. ]))
  47. return padx, pady
  48. @contextlib.contextmanager
  49. def temp_enable_text_widget(text):
  50. text.configure(state=tk.NORMAL)
  51. try:
  52. yield
  53. finally:
  54. text.configure(state=tk.DISABLED)
  55. class BaseSideBar:
  56. """A base class for sidebars using Text."""
  57. def __init__(self, editwin):
  58. self.editwin = editwin
  59. self.parent = editwin.text_frame
  60. self.text = editwin.text
  61. self.is_shown = False
  62. self.main_widget = self.init_widgets()
  63. self.bind_events()
  64. self.update_font()
  65. self.update_colors()
  66. def init_widgets(self):
  67. """Initialize the sidebar's widgets, returning the main widget."""
  68. raise NotImplementedError
  69. def update_font(self):
  70. """Update the sidebar text font, usually after config changes."""
  71. raise NotImplementedError
  72. def update_colors(self):
  73. """Update the sidebar text colors, usually after config changes."""
  74. raise NotImplementedError
  75. def grid(self):
  76. """Layout the widget, always using grid layout."""
  77. raise NotImplementedError
  78. def show_sidebar(self):
  79. if not self.is_shown:
  80. self.grid()
  81. self.is_shown = True
  82. def hide_sidebar(self):
  83. if self.is_shown:
  84. self.main_widget.grid_forget()
  85. self.is_shown = False
  86. def yscroll_event(self, *args, **kwargs):
  87. """Hook for vertical scrolling for sub-classes to override."""
  88. raise NotImplementedError
  89. def redirect_yscroll_event(self, *args, **kwargs):
  90. """Redirect vertical scrolling to the main editor text widget.
  91. The scroll bar is also updated.
  92. """
  93. self.editwin.vbar.set(*args)
  94. return self.yscroll_event(*args, **kwargs)
  95. def redirect_focusin_event(self, event):
  96. """Redirect focus-in events to the main editor text widget."""
  97. self.text.focus_set()
  98. return 'break'
  99. def redirect_mousebutton_event(self, event, event_name):
  100. """Redirect mouse button events to the main editor text widget."""
  101. self.text.focus_set()
  102. self.text.event_generate(event_name, x=0, y=event.y)
  103. return 'break'
  104. def redirect_mousewheel_event(self, event):
  105. """Redirect mouse wheel events to the editwin text widget."""
  106. self.text.event_generate('<MouseWheel>',
  107. x=0, y=event.y, delta=event.delta)
  108. return 'break'
  109. def bind_events(self):
  110. self.text['yscrollcommand'] = self.redirect_yscroll_event
  111. # Ensure focus is always redirected to the main editor text widget.
  112. self.main_widget.bind('<FocusIn>', self.redirect_focusin_event)
  113. # Redirect mouse scrolling to the main editor text widget.
  114. #
  115. # Note that without this, scrolling with the mouse only scrolls
  116. # the line numbers.
  117. self.main_widget.bind('<MouseWheel>', self.redirect_mousewheel_event)
  118. # Redirect mouse button events to the main editor text widget,
  119. # except for the left mouse button (1).
  120. #
  121. # Note: X-11 sends Button-4 and Button-5 events for the scroll wheel.
  122. def bind_mouse_event(event_name, target_event_name):
  123. handler = functools.partial(self.redirect_mousebutton_event,
  124. event_name=target_event_name)
  125. self.main_widget.bind(event_name, handler)
  126. for button in [2, 3, 4, 5]:
  127. for event_name in (f'<Button-{button}>',
  128. f'<ButtonRelease-{button}>',
  129. f'<B{button}-Motion>',
  130. ):
  131. bind_mouse_event(event_name, target_event_name=event_name)
  132. # Convert double- and triple-click events to normal click events,
  133. # since event_generate() doesn't allow generating such events.
  134. for event_name in (f'<Double-Button-{button}>',
  135. f'<Triple-Button-{button}>',
  136. ):
  137. bind_mouse_event(event_name,
  138. target_event_name=f'<Button-{button}>')
  139. # start_line is set upon <Button-1> to allow selecting a range of rows
  140. # by dragging. It is cleared upon <ButtonRelease-1>.
  141. start_line = None
  142. # last_y is initially set upon <B1-Leave> and is continuously updated
  143. # upon <B1-Motion>, until <B1-Enter> or the mouse button is released.
  144. # It is used in text_auto_scroll(), which is called repeatedly and
  145. # does have a mouse event available.
  146. last_y = None
  147. # auto_scrolling_after_id is set whenever text_auto_scroll is
  148. # scheduled via .after(). It is used to stop the auto-scrolling
  149. # upon <B1-Enter>, as well as to avoid scheduling the function several
  150. # times in parallel.
  151. auto_scrolling_after_id = None
  152. def drag_update_selection_and_insert_mark(y_coord):
  153. """Helper function for drag and selection event handlers."""
  154. lineno = get_lineno(self.text, f"@0,{y_coord}")
  155. a, b = sorted([start_line, lineno])
  156. self.text.tag_remove("sel", "1.0", "end")
  157. self.text.tag_add("sel", f"{a}.0", f"{b+1}.0")
  158. self.text.mark_set("insert",
  159. f"{lineno if lineno == a else lineno + 1}.0")
  160. def b1_mousedown_handler(event):
  161. nonlocal start_line
  162. nonlocal last_y
  163. start_line = int(float(self.text.index(f"@0,{event.y}")))
  164. last_y = event.y
  165. drag_update_selection_and_insert_mark(event.y)
  166. self.main_widget.bind('<Button-1>', b1_mousedown_handler)
  167. def b1_mouseup_handler(event):
  168. # On mouse up, we're no longer dragging. Set the shared persistent
  169. # variables to None to represent this.
  170. nonlocal start_line
  171. nonlocal last_y
  172. start_line = None
  173. last_y = None
  174. self.text.event_generate('<ButtonRelease-1>', x=0, y=event.y)
  175. self.main_widget.bind('<ButtonRelease-1>', b1_mouseup_handler)
  176. def b1_drag_handler(event):
  177. nonlocal last_y
  178. if last_y is None: # i.e. if not currently dragging
  179. return
  180. last_y = event.y
  181. drag_update_selection_and_insert_mark(event.y)
  182. self.main_widget.bind('<B1-Motion>', b1_drag_handler)
  183. def text_auto_scroll():
  184. """Mimic Text auto-scrolling when dragging outside of it."""
  185. # See: https://github.com/tcltk/tk/blob/064ff9941b4b80b85916a8afe86a6c21fd388b54/library/text.tcl#L670
  186. nonlocal auto_scrolling_after_id
  187. y = last_y
  188. if y is None:
  189. self.main_widget.after_cancel(auto_scrolling_after_id)
  190. auto_scrolling_after_id = None
  191. return
  192. elif y < 0:
  193. self.text.yview_scroll(-1 + y, 'pixels')
  194. drag_update_selection_and_insert_mark(y)
  195. elif y > self.main_widget.winfo_height():
  196. self.text.yview_scroll(1 + y - self.main_widget.winfo_height(),
  197. 'pixels')
  198. drag_update_selection_and_insert_mark(y)
  199. auto_scrolling_after_id = \
  200. self.main_widget.after(50, text_auto_scroll)
  201. def b1_leave_handler(event):
  202. # Schedule the initial call to text_auto_scroll(), if not already
  203. # scheduled.
  204. nonlocal auto_scrolling_after_id
  205. if auto_scrolling_after_id is None:
  206. nonlocal last_y
  207. last_y = event.y
  208. auto_scrolling_after_id = \
  209. self.main_widget.after(0, text_auto_scroll)
  210. self.main_widget.bind('<B1-Leave>', b1_leave_handler)
  211. def b1_enter_handler(event):
  212. # Cancel the scheduling of text_auto_scroll(), if it exists.
  213. nonlocal auto_scrolling_after_id
  214. if auto_scrolling_after_id is not None:
  215. self.main_widget.after_cancel(auto_scrolling_after_id)
  216. auto_scrolling_after_id = None
  217. self.main_widget.bind('<B1-Enter>', b1_enter_handler)
  218. class EndLineDelegator(Delegator):
  219. """Generate callbacks with the current end line number.
  220. The provided callback is called after every insert and delete.
  221. """
  222. def __init__(self, changed_callback):
  223. Delegator.__init__(self)
  224. self.changed_callback = changed_callback
  225. def insert(self, index, chars, tags=None):
  226. self.delegate.insert(index, chars, tags)
  227. self.changed_callback(get_end_linenumber(self.delegate))
  228. def delete(self, index1, index2=None):
  229. self.delegate.delete(index1, index2)
  230. self.changed_callback(get_end_linenumber(self.delegate))
  231. class LineNumbers(BaseSideBar):
  232. """Line numbers support for editor windows."""
  233. def __init__(self, editwin):
  234. super().__init__(editwin)
  235. end_line_delegator = EndLineDelegator(self.update_sidebar_text)
  236. # Insert the delegator after the undo delegator, so that line numbers
  237. # are properly updated after undo and redo actions.
  238. self.editwin.per.insertfilterafter(end_line_delegator,
  239. after=self.editwin.undo)
  240. def init_widgets(self):
  241. _padx, pady = get_widget_padding(self.text)
  242. self.sidebar_text = tk.Text(self.parent, width=1, wrap=tk.NONE,
  243. padx=2, pady=pady,
  244. borderwidth=0, highlightthickness=0)
  245. self.sidebar_text.config(state=tk.DISABLED)
  246. self.prev_end = 1
  247. self._sidebar_width_type = type(self.sidebar_text['width'])
  248. with temp_enable_text_widget(self.sidebar_text):
  249. self.sidebar_text.insert('insert', '1', 'linenumber')
  250. self.sidebar_text.config(takefocus=False, exportselection=False)
  251. self.sidebar_text.tag_config('linenumber', justify=tk.RIGHT)
  252. end = get_end_linenumber(self.text)
  253. self.update_sidebar_text(end)
  254. return self.sidebar_text
  255. def grid(self):
  256. self.sidebar_text.grid(row=1, column=0, sticky=tk.NSEW)
  257. def update_font(self):
  258. font = idleConf.GetFont(self.text, 'main', 'EditorWindow')
  259. self.sidebar_text['font'] = font
  260. def update_colors(self):
  261. """Update the sidebar text colors, usually after config changes."""
  262. colors = idleConf.GetHighlight(idleConf.CurrentTheme(), 'linenumber')
  263. foreground = colors['foreground']
  264. background = colors['background']
  265. self.sidebar_text.config(
  266. fg=foreground, bg=background,
  267. selectforeground=foreground, selectbackground=background,
  268. inactiveselectbackground=background,
  269. )
  270. def update_sidebar_text(self, end):
  271. """
  272. Perform the following action:
  273. Each line sidebar_text contains the linenumber for that line
  274. Synchronize with editwin.text so that both sidebar_text and
  275. editwin.text contain the same number of lines"""
  276. if end == self.prev_end:
  277. return
  278. width_difference = len(str(end)) - len(str(self.prev_end))
  279. if width_difference:
  280. cur_width = int(float(self.sidebar_text['width']))
  281. new_width = cur_width + width_difference
  282. self.sidebar_text['width'] = self._sidebar_width_type(new_width)
  283. with temp_enable_text_widget(self.sidebar_text):
  284. if end > self.prev_end:
  285. new_text = '\n'.join(itertools.chain(
  286. [''],
  287. map(str, range(self.prev_end + 1, end + 1)),
  288. ))
  289. self.sidebar_text.insert(f'end -1c', new_text, 'linenumber')
  290. else:
  291. self.sidebar_text.delete(f'{end+1}.0 -1c', 'end -1c')
  292. self.prev_end = end
  293. def yscroll_event(self, *args, **kwargs):
  294. self.sidebar_text.yview_moveto(args[0])
  295. return 'break'
  296. class WrappedLineHeightChangeDelegator(Delegator):
  297. def __init__(self, callback):
  298. """
  299. callback - Callable, will be called when an insert, delete or replace
  300. action on the text widget may require updating the shell
  301. sidebar.
  302. """
  303. Delegator.__init__(self)
  304. self.callback = callback
  305. def insert(self, index, chars, tags=None):
  306. is_single_line = '\n' not in chars
  307. if is_single_line:
  308. before_displaylines = get_displaylines(self, index)
  309. self.delegate.insert(index, chars, tags)
  310. if is_single_line:
  311. after_displaylines = get_displaylines(self, index)
  312. if after_displaylines == before_displaylines:
  313. return # no need to update the sidebar
  314. self.callback()
  315. def delete(self, index1, index2=None):
  316. if index2 is None:
  317. index2 = index1 + "+1c"
  318. is_single_line = get_lineno(self, index1) == get_lineno(self, index2)
  319. if is_single_line:
  320. before_displaylines = get_displaylines(self, index1)
  321. self.delegate.delete(index1, index2)
  322. if is_single_line:
  323. after_displaylines = get_displaylines(self, index1)
  324. if after_displaylines == before_displaylines:
  325. return # no need to update the sidebar
  326. self.callback()
  327. class ShellSidebar(BaseSideBar):
  328. """Sidebar for the PyShell window, for prompts etc."""
  329. def __init__(self, editwin):
  330. self.canvas = None
  331. self.line_prompts = {}
  332. super().__init__(editwin)
  333. change_delegator = \
  334. WrappedLineHeightChangeDelegator(self.change_callback)
  335. # Insert the TextChangeDelegator after the last delegator, so that
  336. # the sidebar reflects final changes to the text widget contents.
  337. d = self.editwin.per.top
  338. if d.delegate is not self.text:
  339. while d.delegate is not self.editwin.per.bottom:
  340. d = d.delegate
  341. self.editwin.per.insertfilterafter(change_delegator, after=d)
  342. self.is_shown = True
  343. def init_widgets(self):
  344. self.canvas = tk.Canvas(self.parent, width=30,
  345. borderwidth=0, highlightthickness=0,
  346. takefocus=False)
  347. self.update_sidebar()
  348. self.grid()
  349. return self.canvas
  350. def bind_events(self):
  351. super().bind_events()
  352. self.main_widget.bind(
  353. # AquaTk defines <2> as the right button, not <3>.
  354. "<Button-2>" if macosx.isAquaTk() else "<Button-3>",
  355. self.context_menu_event,
  356. )
  357. def context_menu_event(self, event):
  358. rmenu = tk.Menu(self.main_widget, tearoff=0)
  359. has_selection = bool(self.text.tag_nextrange('sel', '1.0'))
  360. def mkcmd(eventname):
  361. return lambda: self.text.event_generate(eventname)
  362. rmenu.add_command(label='Copy',
  363. command=mkcmd('<<copy>>'),
  364. state='normal' if has_selection else 'disabled')
  365. rmenu.add_command(label='Copy with prompts',
  366. command=mkcmd('<<copy-with-prompts>>'),
  367. state='normal' if has_selection else 'disabled')
  368. rmenu.tk_popup(event.x_root, event.y_root)
  369. return "break"
  370. def grid(self):
  371. self.canvas.grid(row=1, column=0, sticky=tk.NSEW, padx=2, pady=0)
  372. def change_callback(self):
  373. if self.is_shown:
  374. self.update_sidebar()
  375. def update_sidebar(self):
  376. text = self.text
  377. text_tagnames = text.tag_names
  378. canvas = self.canvas
  379. line_prompts = self.line_prompts = {}
  380. canvas.delete(tk.ALL)
  381. index = text.index("@0,0")
  382. if index.split('.', 1)[1] != '0':
  383. index = text.index(f'{index}+1line linestart')
  384. while (lineinfo := text.dlineinfo(index)) is not None:
  385. y = lineinfo[1]
  386. prev_newline_tagnames = text_tagnames(f"{index} linestart -1c")
  387. prompt = (
  388. '>>>' if "console" in prev_newline_tagnames else
  389. '...' if "stdin" in prev_newline_tagnames else
  390. None
  391. )
  392. if prompt:
  393. canvas.create_text(2, y, anchor=tk.NW, text=prompt,
  394. font=self.font, fill=self.colors[0])
  395. lineno = get_lineno(text, index)
  396. line_prompts[lineno] = prompt
  397. index = text.index(f'{index}+1line')
  398. def yscroll_event(self, *args, **kwargs):
  399. """Redirect vertical scrolling to the main editor text widget.
  400. The scroll bar is also updated.
  401. """
  402. self.change_callback()
  403. return 'break'
  404. def update_font(self):
  405. """Update the sidebar text font, usually after config changes."""
  406. font = idleConf.GetFont(self.text, 'main', 'EditorWindow')
  407. tk_font = Font(self.text, font=font)
  408. char_width = max(tk_font.measure(char) for char in ['>', '.'])
  409. self.canvas.configure(width=char_width * 3 + 4)
  410. self.font = font
  411. self.change_callback()
  412. def update_colors(self):
  413. """Update the sidebar text colors, usually after config changes."""
  414. linenumbers_colors = idleConf.GetHighlight(idleConf.CurrentTheme(), 'linenumber')
  415. prompt_colors = idleConf.GetHighlight(idleConf.CurrentTheme(), 'console')
  416. foreground = prompt_colors['foreground']
  417. background = linenumbers_colors['background']
  418. self.colors = (foreground, background)
  419. self.canvas.configure(background=background)
  420. self.change_callback()
  421. def _linenumbers_drag_scrolling(parent): # htest #
  422. from idlelib.idle_test.test_sidebar import Dummy_editwin
  423. toplevel = tk.Toplevel(parent)
  424. text_frame = tk.Frame(toplevel)
  425. text_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
  426. text_frame.rowconfigure(1, weight=1)
  427. text_frame.columnconfigure(1, weight=1)
  428. font = idleConf.GetFont(toplevel, 'main', 'EditorWindow')
  429. text = tk.Text(text_frame, width=80, height=24, wrap=tk.NONE, font=font)
  430. text.grid(row=1, column=1, sticky=tk.NSEW)
  431. editwin = Dummy_editwin(text)
  432. editwin.vbar = tk.Scrollbar(text_frame)
  433. linenumbers = LineNumbers(editwin)
  434. linenumbers.show_sidebar()
  435. text.insert('1.0', '\n'.join('a'*i for i in range(1, 101)))
  436. if __name__ == '__main__':
  437. from unittest import main
  438. main('idlelib.idle_test.test_sidebar', verbosity=2, exit=False)
  439. from idlelib.idle_test.htest import run
  440. run(_linenumbers_drag_scrolling)