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

squeezer.py (12834B)


  1. """An IDLE extension to avoid having very long texts printed in the shell.
  2. A common problem in IDLE's interactive shell is printing of large amounts of
  3. text into the shell. This makes looking at the previous history difficult.
  4. Worse, this can cause IDLE to become very slow, even to the point of being
  5. completely unusable.
  6. This extension will automatically replace long texts with a small button.
  7. Double-clicking this button will remove it and insert the original text instead.
  8. Middle-clicking will copy the text to the clipboard. Right-clicking will open
  9. the text in a separate viewing window.
  10. Additionally, any output can be manually "squeezed" by the user. This includes
  11. output written to the standard error stream ("stderr"), such as exception
  12. messages and their tracebacks.
  13. """
  14. import re
  15. import tkinter as tk
  16. from tkinter import messagebox
  17. from idlelib.config import idleConf
  18. from idlelib.textview import view_text
  19. from idlelib.tooltip import Hovertip
  20. from idlelib import macosx
  21. def count_lines_with_wrapping(s, linewidth=80):
  22. """Count the number of lines in a given string.
  23. Lines are counted as if the string was wrapped so that lines are never over
  24. linewidth characters long.
  25. Tabs are considered tabwidth characters long.
  26. """
  27. tabwidth = 8 # Currently always true in Shell.
  28. pos = 0
  29. linecount = 1
  30. current_column = 0
  31. for m in re.finditer(r"[\t\n]", s):
  32. # Process the normal chars up to tab or newline.
  33. numchars = m.start() - pos
  34. pos += numchars
  35. current_column += numchars
  36. # Deal with tab or newline.
  37. if s[pos] == '\n':
  38. # Avoid the `current_column == 0` edge-case, and while we're
  39. # at it, don't bother adding 0.
  40. if current_column > linewidth:
  41. # If the current column was exactly linewidth, divmod
  42. # would give (1,0), even though a new line hadn't yet
  43. # been started. The same is true if length is any exact
  44. # multiple of linewidth. Therefore, subtract 1 before
  45. # dividing a non-empty line.
  46. linecount += (current_column - 1) // linewidth
  47. linecount += 1
  48. current_column = 0
  49. else:
  50. assert s[pos] == '\t'
  51. current_column += tabwidth - (current_column % tabwidth)
  52. # If a tab passes the end of the line, consider the entire
  53. # tab as being on the next line.
  54. if current_column > linewidth:
  55. linecount += 1
  56. current_column = tabwidth
  57. pos += 1 # After the tab or newline.
  58. # Process remaining chars (no more tabs or newlines).
  59. current_column += len(s) - pos
  60. # Avoid divmod(-1, linewidth).
  61. if current_column > 0:
  62. linecount += (current_column - 1) // linewidth
  63. else:
  64. # Text ended with newline; don't count an extra line after it.
  65. linecount -= 1
  66. return linecount
  67. class ExpandingButton(tk.Button):
  68. """Class for the "squeezed" text buttons used by Squeezer
  69. These buttons are displayed inside a Tk Text widget in place of text. A
  70. user can then use the button to replace it with the original text, copy
  71. the original text to the clipboard or view the original text in a separate
  72. window.
  73. Each button is tied to a Squeezer instance, and it knows to update the
  74. Squeezer instance when it is expanded (and therefore removed).
  75. """
  76. def __init__(self, s, tags, numoflines, squeezer):
  77. self.s = s
  78. self.tags = tags
  79. self.numoflines = numoflines
  80. self.squeezer = squeezer
  81. self.editwin = editwin = squeezer.editwin
  82. self.text = text = editwin.text
  83. # The base Text widget is needed to change text before iomark.
  84. self.base_text = editwin.per.bottom
  85. line_plurality = "lines" if numoflines != 1 else "line"
  86. button_text = f"Squeezed text ({numoflines} {line_plurality})."
  87. tk.Button.__init__(self, text, text=button_text,
  88. background="#FFFFC0", activebackground="#FFFFE0")
  89. button_tooltip_text = (
  90. "Double-click to expand, right-click for more options."
  91. )
  92. Hovertip(self, button_tooltip_text, hover_delay=80)
  93. self.bind("<Double-Button-1>", self.expand)
  94. if macosx.isAquaTk():
  95. # AquaTk defines <2> as the right button, not <3>.
  96. self.bind("<Button-2>", self.context_menu_event)
  97. else:
  98. self.bind("<Button-3>", self.context_menu_event)
  99. self.selection_handle( # X windows only.
  100. lambda offset, length: s[int(offset):int(offset) + int(length)])
  101. self.is_dangerous = None
  102. self.after_idle(self.set_is_dangerous)
  103. def set_is_dangerous(self):
  104. dangerous_line_len = 50 * self.text.winfo_width()
  105. self.is_dangerous = (
  106. self.numoflines > 1000 or
  107. len(self.s) > 50000 or
  108. any(
  109. len(line_match.group(0)) >= dangerous_line_len
  110. for line_match in re.finditer(r'[^\n]+', self.s)
  111. )
  112. )
  113. def expand(self, event=None):
  114. """expand event handler
  115. This inserts the original text in place of the button in the Text
  116. widget, removes the button and updates the Squeezer instance.
  117. If the original text is dangerously long, i.e. expanding it could
  118. cause a performance degradation, ask the user for confirmation.
  119. """
  120. if self.is_dangerous is None:
  121. self.set_is_dangerous()
  122. if self.is_dangerous:
  123. confirm = messagebox.askokcancel(
  124. title="Expand huge output?",
  125. message="\n\n".join([
  126. "The squeezed output is very long: %d lines, %d chars.",
  127. "Expanding it could make IDLE slow or unresponsive.",
  128. "It is recommended to view or copy the output instead.",
  129. "Really expand?"
  130. ]) % (self.numoflines, len(self.s)),
  131. default=messagebox.CANCEL,
  132. parent=self.text)
  133. if not confirm:
  134. return "break"
  135. index = self.text.index(self)
  136. self.base_text.insert(index, self.s, self.tags)
  137. self.base_text.delete(self)
  138. self.editwin.on_squeezed_expand(index, self.s, self.tags)
  139. self.squeezer.expandingbuttons.remove(self)
  140. def copy(self, event=None):
  141. """copy event handler
  142. Copy the original text to the clipboard.
  143. """
  144. self.clipboard_clear()
  145. self.clipboard_append(self.s)
  146. def view(self, event=None):
  147. """view event handler
  148. View the original text in a separate text viewer window.
  149. """
  150. view_text(self.text, "Squeezed Output Viewer", self.s,
  151. modal=False, wrap='none')
  152. rmenu_specs = (
  153. # Item structure: (label, method_name).
  154. ('copy', 'copy'),
  155. ('view', 'view'),
  156. )
  157. def context_menu_event(self, event):
  158. self.text.mark_set("insert", "@%d,%d" % (event.x, event.y))
  159. rmenu = tk.Menu(self.text, tearoff=0)
  160. for label, method_name in self.rmenu_specs:
  161. rmenu.add_command(label=label, command=getattr(self, method_name))
  162. rmenu.tk_popup(event.x_root, event.y_root)
  163. return "break"
  164. class Squeezer:
  165. """Replace long outputs in the shell with a simple button.
  166. This avoids IDLE's shell slowing down considerably, and even becoming
  167. completely unresponsive, when very long outputs are written.
  168. """
  169. @classmethod
  170. def reload(cls):
  171. """Load class variables from config."""
  172. cls.auto_squeeze_min_lines = idleConf.GetOption(
  173. "main", "PyShell", "auto-squeeze-min-lines",
  174. type="int", default=50,
  175. )
  176. def __init__(self, editwin):
  177. """Initialize settings for Squeezer.
  178. editwin is the shell's Editor window.
  179. self.text is the editor window text widget.
  180. self.base_test is the actual editor window Tk text widget, rather than
  181. EditorWindow's wrapper.
  182. self.expandingbuttons is the list of all buttons representing
  183. "squeezed" output.
  184. """
  185. self.editwin = editwin
  186. self.text = text = editwin.text
  187. # Get the base Text widget of the PyShell object, used to change
  188. # text before the iomark. PyShell deliberately disables changing
  189. # text before the iomark via its 'text' attribute, which is
  190. # actually a wrapper for the actual Text widget. Squeezer,
  191. # however, needs to make such changes.
  192. self.base_text = editwin.per.bottom
  193. # Twice the text widget's border width and internal padding;
  194. # pre-calculated here for the get_line_width() method.
  195. self.window_width_delta = 2 * (
  196. int(text.cget('border')) +
  197. int(text.cget('padx'))
  198. )
  199. self.expandingbuttons = []
  200. # Replace the PyShell instance's write method with a wrapper,
  201. # which inserts an ExpandingButton instead of a long text.
  202. def mywrite(s, tags=(), write=editwin.write):
  203. # Only auto-squeeze text which has just the "stdout" tag.
  204. if tags != "stdout":
  205. return write(s, tags)
  206. # Only auto-squeeze text with at least the minimum
  207. # configured number of lines.
  208. auto_squeeze_min_lines = self.auto_squeeze_min_lines
  209. # First, a very quick check to skip very short texts.
  210. if len(s) < auto_squeeze_min_lines:
  211. return write(s, tags)
  212. # Now the full line-count check.
  213. numoflines = self.count_lines(s)
  214. if numoflines < auto_squeeze_min_lines:
  215. return write(s, tags)
  216. # Create an ExpandingButton instance.
  217. expandingbutton = ExpandingButton(s, tags, numoflines, self)
  218. # Insert the ExpandingButton into the Text widget.
  219. text.mark_gravity("iomark", tk.RIGHT)
  220. text.window_create("iomark", window=expandingbutton,
  221. padx=3, pady=5)
  222. text.see("iomark")
  223. text.update()
  224. text.mark_gravity("iomark", tk.LEFT)
  225. # Add the ExpandingButton to the Squeezer's list.
  226. self.expandingbuttons.append(expandingbutton)
  227. editwin.write = mywrite
  228. def count_lines(self, s):
  229. """Count the number of lines in a given text.
  230. Before calculation, the tab width and line length of the text are
  231. fetched, so that up-to-date values are used.
  232. Lines are counted as if the string was wrapped so that lines are never
  233. over linewidth characters long.
  234. Tabs are considered tabwidth characters long.
  235. """
  236. return count_lines_with_wrapping(s, self.editwin.width)
  237. def squeeze_current_text(self):
  238. """Squeeze the text block where the insertion cursor is.
  239. If the cursor is not in a squeezable block of text, give the
  240. user a small warning and do nothing.
  241. """
  242. # Set tag_name to the first valid tag found on the "insert" cursor.
  243. tag_names = self.text.tag_names(tk.INSERT)
  244. for tag_name in ("stdout", "stderr"):
  245. if tag_name in tag_names:
  246. break
  247. else:
  248. # The insert cursor doesn't have a "stdout" or "stderr" tag.
  249. self.text.bell()
  250. return "break"
  251. # Find the range to squeeze.
  252. start, end = self.text.tag_prevrange(tag_name, tk.INSERT + "+1c")
  253. s = self.text.get(start, end)
  254. # If the last char is a newline, remove it from the range.
  255. if len(s) > 0 and s[-1] == '\n':
  256. end = self.text.index("%s-1c" % end)
  257. s = s[:-1]
  258. # Delete the text.
  259. self.base_text.delete(start, end)
  260. # Prepare an ExpandingButton.
  261. numoflines = self.count_lines(s)
  262. expandingbutton = ExpandingButton(s, tag_name, numoflines, self)
  263. # insert the ExpandingButton to the Text
  264. self.text.window_create(start, window=expandingbutton,
  265. padx=3, pady=5)
  266. # Insert the ExpandingButton to the list of ExpandingButtons,
  267. # while keeping the list ordered according to the position of
  268. # the buttons in the Text widget.
  269. i = len(self.expandingbuttons)
  270. while i > 0 and self.text.compare(self.expandingbuttons[i-1],
  271. ">", expandingbutton):
  272. i -= 1
  273. self.expandingbuttons.insert(i, expandingbutton)
  274. return "break"
  275. Squeezer.reload()
  276. if __name__ == "__main__":
  277. from unittest import main
  278. main('idlelib.idle_test.test_squeezer', verbosity=2, exit=False)
  279. # Add htest.