sidebar.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. """Line numbering implementation for IDLE as an extension.
  2. Includes BaseSideBar which can be extended for other sidebar based extensions
  3. """
  4. import functools
  5. import itertools
  6. import tkinter as tk
  7. from idlelib.config import idleConf
  8. from idlelib.delegator import Delegator
  9. def get_end_linenumber(text):
  10. """Utility to get the last line's number in a Tk text widget."""
  11. return int(float(text.index('end-1c')))
  12. def get_widget_padding(widget):
  13. """Get the total padding of a Tk widget, including its border."""
  14. # TODO: use also in codecontext.py
  15. manager = widget.winfo_manager()
  16. if manager == 'pack':
  17. info = widget.pack_info()
  18. elif manager == 'grid':
  19. info = widget.grid_info()
  20. else:
  21. raise ValueError(f"Unsupported geometry manager: {manager}")
  22. # All values are passed through getint(), since some
  23. # values may be pixel objects, which can't simply be added to ints.
  24. padx = sum(map(widget.tk.getint, [
  25. info['padx'],
  26. widget.cget('padx'),
  27. widget.cget('border'),
  28. ]))
  29. pady = sum(map(widget.tk.getint, [
  30. info['pady'],
  31. widget.cget('pady'),
  32. widget.cget('border'),
  33. ]))
  34. return padx, pady
  35. class BaseSideBar:
  36. """
  37. The base class for extensions which require a sidebar.
  38. """
  39. def __init__(self, editwin):
  40. self.editwin = editwin
  41. self.parent = editwin.text_frame
  42. self.text = editwin.text
  43. _padx, pady = get_widget_padding(self.text)
  44. self.sidebar_text = tk.Text(self.parent, width=1, wrap=tk.NONE,
  45. padx=2, pady=pady,
  46. borderwidth=0, highlightthickness=0)
  47. self.sidebar_text.config(state=tk.DISABLED)
  48. self.text['yscrollcommand'] = self.redirect_yscroll_event
  49. self.update_font()
  50. self.update_colors()
  51. self.is_shown = False
  52. def update_font(self):
  53. """Update the sidebar text font, usually after config changes."""
  54. font = idleConf.GetFont(self.text, 'main', 'EditorWindow')
  55. self._update_font(font)
  56. def _update_font(self, font):
  57. self.sidebar_text['font'] = font
  58. def update_colors(self):
  59. """Update the sidebar text colors, usually after config changes."""
  60. colors = idleConf.GetHighlight(idleConf.CurrentTheme(), 'normal')
  61. self._update_colors(foreground=colors['foreground'],
  62. background=colors['background'])
  63. def _update_colors(self, foreground, background):
  64. self.sidebar_text.config(
  65. fg=foreground, bg=background,
  66. selectforeground=foreground, selectbackground=background,
  67. inactiveselectbackground=background,
  68. )
  69. def show_sidebar(self):
  70. if not self.is_shown:
  71. self.sidebar_text.grid(row=1, column=0, sticky=tk.NSEW)
  72. self.is_shown = True
  73. def hide_sidebar(self):
  74. if self.is_shown:
  75. self.sidebar_text.grid_forget()
  76. self.is_shown = False
  77. def redirect_yscroll_event(self, *args, **kwargs):
  78. """Redirect vertical scrolling to the main editor text widget.
  79. The scroll bar is also updated.
  80. """
  81. self.editwin.vbar.set(*args)
  82. self.sidebar_text.yview_moveto(args[0])
  83. return 'break'
  84. def redirect_focusin_event(self, event):
  85. """Redirect focus-in events to the main editor text widget."""
  86. self.text.focus_set()
  87. return 'break'
  88. def redirect_mousebutton_event(self, event, event_name):
  89. """Redirect mouse button events to the main editor text widget."""
  90. self.text.focus_set()
  91. self.text.event_generate(event_name, x=0, y=event.y)
  92. return 'break'
  93. def redirect_mousewheel_event(self, event):
  94. """Redirect mouse wheel events to the editwin text widget."""
  95. self.text.event_generate('<MouseWheel>',
  96. x=0, y=event.y, delta=event.delta)
  97. return 'break'
  98. class EndLineDelegator(Delegator):
  99. """Generate callbacks with the current end line number after
  100. insert or delete operations"""
  101. def __init__(self, changed_callback):
  102. """
  103. changed_callback - Callable, will be called after insert
  104. or delete operations with the current
  105. end line number.
  106. """
  107. Delegator.__init__(self)
  108. self.changed_callback = changed_callback
  109. def insert(self, index, chars, tags=None):
  110. self.delegate.insert(index, chars, tags)
  111. self.changed_callback(get_end_linenumber(self.delegate))
  112. def delete(self, index1, index2=None):
  113. self.delegate.delete(index1, index2)
  114. self.changed_callback(get_end_linenumber(self.delegate))
  115. class LineNumbers(BaseSideBar):
  116. """Line numbers support for editor windows."""
  117. def __init__(self, editwin):
  118. BaseSideBar.__init__(self, editwin)
  119. self.prev_end = 1
  120. self._sidebar_width_type = type(self.sidebar_text['width'])
  121. self.sidebar_text.config(state=tk.NORMAL)
  122. self.sidebar_text.insert('insert', '1', 'linenumber')
  123. self.sidebar_text.config(state=tk.DISABLED)
  124. self.sidebar_text.config(takefocus=False, exportselection=False)
  125. self.sidebar_text.tag_config('linenumber', justify=tk.RIGHT)
  126. self.bind_events()
  127. end = get_end_linenumber(self.text)
  128. self.update_sidebar_text(end)
  129. end_line_delegator = EndLineDelegator(self.update_sidebar_text)
  130. # Insert the delegator after the undo delegator, so that line numbers
  131. # are properly updated after undo and redo actions.
  132. end_line_delegator.setdelegate(self.editwin.undo.delegate)
  133. self.editwin.undo.setdelegate(end_line_delegator)
  134. # Reset the delegator caches of the delegators "above" the
  135. # end line delegator we just inserted.
  136. delegator = self.editwin.per.top
  137. while delegator is not end_line_delegator:
  138. delegator.resetcache()
  139. delegator = delegator.delegate
  140. self.is_shown = False
  141. def bind_events(self):
  142. # Ensure focus is always redirected to the main editor text widget.
  143. self.sidebar_text.bind('<FocusIn>', self.redirect_focusin_event)
  144. # Redirect mouse scrolling to the main editor text widget.
  145. #
  146. # Note that without this, scrolling with the mouse only scrolls
  147. # the line numbers.
  148. self.sidebar_text.bind('<MouseWheel>', self.redirect_mousewheel_event)
  149. # Redirect mouse button events to the main editor text widget,
  150. # except for the left mouse button (1).
  151. #
  152. # Note: X-11 sends Button-4 and Button-5 events for the scroll wheel.
  153. def bind_mouse_event(event_name, target_event_name):
  154. handler = functools.partial(self.redirect_mousebutton_event,
  155. event_name=target_event_name)
  156. self.sidebar_text.bind(event_name, handler)
  157. for button in [2, 3, 4, 5]:
  158. for event_name in (f'<Button-{button}>',
  159. f'<ButtonRelease-{button}>',
  160. f'<B{button}-Motion>',
  161. ):
  162. bind_mouse_event(event_name, target_event_name=event_name)
  163. # Convert double- and triple-click events to normal click events,
  164. # since event_generate() doesn't allow generating such events.
  165. for event_name in (f'<Double-Button-{button}>',
  166. f'<Triple-Button-{button}>',
  167. ):
  168. bind_mouse_event(event_name,
  169. target_event_name=f'<Button-{button}>')
  170. # This is set by b1_mousedown_handler() and read by
  171. # drag_update_selection_and_insert_mark(), to know where dragging
  172. # began.
  173. start_line = None
  174. # These are set by b1_motion_handler() and read by selection_handler().
  175. # last_y is passed this way since the mouse Y-coordinate is not
  176. # available on selection event objects. last_yview is passed this way
  177. # to recognize scrolling while the mouse isn't moving.
  178. last_y = last_yview = None
  179. def b1_mousedown_handler(event):
  180. # select the entire line
  181. lineno = int(float(self.sidebar_text.index(f"@0,{event.y}")))
  182. self.text.tag_remove("sel", "1.0", "end")
  183. self.text.tag_add("sel", f"{lineno}.0", f"{lineno+1}.0")
  184. self.text.mark_set("insert", f"{lineno+1}.0")
  185. # remember this line in case this is the beginning of dragging
  186. nonlocal start_line
  187. start_line = lineno
  188. self.sidebar_text.bind('<Button-1>', b1_mousedown_handler)
  189. def b1_mouseup_handler(event):
  190. # On mouse up, we're no longer dragging. Set the shared persistent
  191. # variables to None to represent this.
  192. nonlocal start_line
  193. nonlocal last_y
  194. nonlocal last_yview
  195. start_line = None
  196. last_y = None
  197. last_yview = None
  198. self.sidebar_text.bind('<ButtonRelease-1>', b1_mouseup_handler)
  199. def drag_update_selection_and_insert_mark(y_coord):
  200. """Helper function for drag and selection event handlers."""
  201. lineno = int(float(self.sidebar_text.index(f"@0,{y_coord}")))
  202. a, b = sorted([start_line, lineno])
  203. self.text.tag_remove("sel", "1.0", "end")
  204. self.text.tag_add("sel", f"{a}.0", f"{b+1}.0")
  205. self.text.mark_set("insert",
  206. f"{lineno if lineno == a else lineno + 1}.0")
  207. # Special handling of dragging with mouse button 1. In "normal" text
  208. # widgets this selects text, but the line numbers text widget has
  209. # selection disabled. Still, dragging triggers some selection-related
  210. # functionality under the hood. Specifically, dragging to above or
  211. # below the text widget triggers scrolling, in a way that bypasses the
  212. # other scrolling synchronization mechanisms.i
  213. def b1_drag_handler(event, *args):
  214. nonlocal last_y
  215. nonlocal last_yview
  216. last_y = event.y
  217. last_yview = self.sidebar_text.yview()
  218. if not 0 <= last_y <= self.sidebar_text.winfo_height():
  219. self.text.yview_moveto(last_yview[0])
  220. drag_update_selection_and_insert_mark(event.y)
  221. self.sidebar_text.bind('<B1-Motion>', b1_drag_handler)
  222. # With mouse-drag scrolling fixed by the above, there is still an edge-
  223. # case we need to handle: When drag-scrolling, scrolling can continue
  224. # while the mouse isn't moving, leading to the above fix not scrolling
  225. # properly.
  226. def selection_handler(event):
  227. if last_yview is None:
  228. # This logic is only needed while dragging.
  229. return
  230. yview = self.sidebar_text.yview()
  231. if yview != last_yview:
  232. self.text.yview_moveto(yview[0])
  233. drag_update_selection_and_insert_mark(last_y)
  234. self.sidebar_text.bind('<<Selection>>', selection_handler)
  235. def update_colors(self):
  236. """Update the sidebar text colors, usually after config changes."""
  237. colors = idleConf.GetHighlight(idleConf.CurrentTheme(), 'linenumber')
  238. self._update_colors(foreground=colors['foreground'],
  239. background=colors['background'])
  240. def update_sidebar_text(self, end):
  241. """
  242. Perform the following action:
  243. Each line sidebar_text contains the linenumber for that line
  244. Synchronize with editwin.text so that both sidebar_text and
  245. editwin.text contain the same number of lines"""
  246. if end == self.prev_end:
  247. return
  248. width_difference = len(str(end)) - len(str(self.prev_end))
  249. if width_difference:
  250. cur_width = int(float(self.sidebar_text['width']))
  251. new_width = cur_width + width_difference
  252. self.sidebar_text['width'] = self._sidebar_width_type(new_width)
  253. self.sidebar_text.config(state=tk.NORMAL)
  254. if end > self.prev_end:
  255. new_text = '\n'.join(itertools.chain(
  256. [''],
  257. map(str, range(self.prev_end + 1, end + 1)),
  258. ))
  259. self.sidebar_text.insert(f'end -1c', new_text, 'linenumber')
  260. else:
  261. self.sidebar_text.delete(f'{end+1}.0 -1c', 'end -1c')
  262. self.sidebar_text.config(state=tk.DISABLED)
  263. self.prev_end = end
  264. def _linenumbers_drag_scrolling(parent): # htest #
  265. from idlelib.idle_test.test_sidebar import Dummy_editwin
  266. toplevel = tk.Toplevel(parent)
  267. text_frame = tk.Frame(toplevel)
  268. text_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
  269. text_frame.rowconfigure(1, weight=1)
  270. text_frame.columnconfigure(1, weight=1)
  271. font = idleConf.GetFont(toplevel, 'main', 'EditorWindow')
  272. text = tk.Text(text_frame, width=80, height=24, wrap=tk.NONE, font=font)
  273. text.grid(row=1, column=1, sticky=tk.NSEW)
  274. editwin = Dummy_editwin(text)
  275. editwin.vbar = tk.Scrollbar(text_frame)
  276. linenumbers = LineNumbers(editwin)
  277. linenumbers.show_sidebar()
  278. text.insert('1.0', '\n'.join('a'*i for i in range(1, 101)))
  279. if __name__ == '__main__':
  280. from unittest import main
  281. main('idlelib.idle_test.test_sidebar', verbosity=2, exit=False)
  282. from idlelib.idle_test.htest import run
  283. run(_linenumbers_drag_scrolling)