utils.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. from __future__ import annotations
  2. import os
  3. import signal
  4. import sys
  5. import threading
  6. from collections import deque
  7. from typing import (
  8. Callable,
  9. ContextManager,
  10. Dict,
  11. Generator,
  12. Generic,
  13. TypeVar,
  14. Union,
  15. )
  16. from wcwidth import wcwidth
  17. __all__ = [
  18. "Event",
  19. "DummyContext",
  20. "get_cwidth",
  21. "suspend_to_background_supported",
  22. "is_conemu_ansi",
  23. "is_windows",
  24. "in_main_thread",
  25. "get_bell_environment_variable",
  26. "get_term_environment_variable",
  27. "take_using_weights",
  28. "to_str",
  29. "to_int",
  30. "AnyFloat",
  31. "to_float",
  32. "is_dumb_terminal",
  33. ]
  34. # Used to ensure sphinx autodoc does not try to import platform-specific
  35. # stuff when documenting win32.py modules.
  36. SPHINX_AUTODOC_RUNNING = "sphinx.ext.autodoc" in sys.modules
  37. _Sender = TypeVar("_Sender", covariant=True)
  38. class Event(Generic[_Sender]):
  39. """
  40. Simple event to which event handlers can be attached. For instance::
  41. class Cls:
  42. def __init__(self):
  43. # Define event. The first parameter is the sender.
  44. self.event = Event(self)
  45. obj = Cls()
  46. def handler(sender):
  47. pass
  48. # Add event handler by using the += operator.
  49. obj.event += handler
  50. # Fire event.
  51. obj.event()
  52. """
  53. def __init__(
  54. self, sender: _Sender, handler: Callable[[_Sender], None] | None = None
  55. ) -> None:
  56. self.sender = sender
  57. self._handlers: list[Callable[[_Sender], None]] = []
  58. if handler is not None:
  59. self += handler
  60. def __call__(self) -> None:
  61. "Fire event."
  62. for handler in self._handlers:
  63. handler(self.sender)
  64. def fire(self) -> None:
  65. "Alias for just calling the event."
  66. self()
  67. def add_handler(self, handler: Callable[[_Sender], None]) -> None:
  68. """
  69. Add another handler to this callback.
  70. (Handler should be a callable that takes exactly one parameter: the
  71. sender object.)
  72. """
  73. # Add to list of event handlers.
  74. self._handlers.append(handler)
  75. def remove_handler(self, handler: Callable[[_Sender], None]) -> None:
  76. """
  77. Remove a handler from this callback.
  78. """
  79. if handler in self._handlers:
  80. self._handlers.remove(handler)
  81. def __iadd__(self, handler: Callable[[_Sender], None]) -> Event[_Sender]:
  82. """
  83. `event += handler` notation for adding a handler.
  84. """
  85. self.add_handler(handler)
  86. return self
  87. def __isub__(self, handler: Callable[[_Sender], None]) -> Event[_Sender]:
  88. """
  89. `event -= handler` notation for removing a handler.
  90. """
  91. self.remove_handler(handler)
  92. return self
  93. class DummyContext(ContextManager[None]):
  94. """
  95. (contextlib.nested is not available on Py3)
  96. """
  97. def __enter__(self) -> None:
  98. pass
  99. def __exit__(self, *a: object) -> None:
  100. pass
  101. class _CharSizesCache(Dict[str, int]):
  102. """
  103. Cache for wcwidth sizes.
  104. """
  105. LONG_STRING_MIN_LEN = 64 # Minimum string length for considering it long.
  106. MAX_LONG_STRINGS = 16 # Maximum number of long strings to remember.
  107. def __init__(self) -> None:
  108. super().__init__()
  109. # Keep track of the "long" strings in this cache.
  110. self._long_strings: deque[str] = deque()
  111. def __missing__(self, string: str) -> int:
  112. # Note: We use the `max(0, ...` because some non printable control
  113. # characters, like e.g. Ctrl-underscore get a -1 wcwidth value.
  114. # It can be possible that these characters end up in the input
  115. # text.
  116. result: int
  117. if len(string) == 1:
  118. result = max(0, wcwidth(string))
  119. else:
  120. result = sum(self[c] for c in string)
  121. # Store in cache.
  122. self[string] = result
  123. # Rotate long strings.
  124. # (It's hard to tell what we can consider short...)
  125. if len(string) > self.LONG_STRING_MIN_LEN:
  126. long_strings = self._long_strings
  127. long_strings.append(string)
  128. if len(long_strings) > self.MAX_LONG_STRINGS:
  129. key_to_remove = long_strings.popleft()
  130. if key_to_remove in self:
  131. del self[key_to_remove]
  132. return result
  133. _CHAR_SIZES_CACHE = _CharSizesCache()
  134. def get_cwidth(string: str) -> int:
  135. """
  136. Return width of a string. Wrapper around ``wcwidth``.
  137. """
  138. return _CHAR_SIZES_CACHE[string]
  139. def suspend_to_background_supported() -> bool:
  140. """
  141. Returns `True` when the Python implementation supports
  142. suspend-to-background. This is typically `False' on Windows systems.
  143. """
  144. return hasattr(signal, "SIGTSTP")
  145. def is_windows() -> bool:
  146. """
  147. True when we are using Windows.
  148. """
  149. return sys.platform == "win32" # Not 'darwin' or 'linux2'
  150. def is_windows_vt100_supported() -> bool:
  151. """
  152. True when we are using Windows, but VT100 escape sequences are supported.
  153. """
  154. if sys.platform == "win32":
  155. # Import needs to be inline. Windows libraries are not always available.
  156. from prompt_toolkit.output.windows10 import is_win_vt100_enabled
  157. return is_win_vt100_enabled()
  158. return False
  159. def is_conemu_ansi() -> bool:
  160. """
  161. True when the ConEmu Windows console is used.
  162. """
  163. return sys.platform == "win32" and os.environ.get("ConEmuANSI", "OFF") == "ON"
  164. def in_main_thread() -> bool:
  165. """
  166. True when the current thread is the main thread.
  167. """
  168. return threading.current_thread().__class__.__name__ == "_MainThread"
  169. def get_bell_environment_variable() -> bool:
  170. """
  171. True if env variable is set to true (true, TRUE, True, 1).
  172. """
  173. value = os.environ.get("PROMPT_TOOLKIT_BELL", "true")
  174. return value.lower() in ("1", "true")
  175. def get_term_environment_variable() -> str:
  176. "Return the $TERM environment variable."
  177. return os.environ.get("TERM", "")
  178. _T = TypeVar("_T")
  179. def take_using_weights(
  180. items: list[_T], weights: list[int]
  181. ) -> Generator[_T, None, None]:
  182. """
  183. Generator that keeps yielding items from the items list, in proportion to
  184. their weight. For instance::
  185. # Getting the first 70 items from this generator should have yielded 10
  186. # times A, 20 times B and 40 times C, all distributed equally..
  187. take_using_weights(['A', 'B', 'C'], [5, 10, 20])
  188. :param items: List of items to take from.
  189. :param weights: Integers representing the weight. (Numbers have to be
  190. integers, not floats.)
  191. """
  192. assert len(items) == len(weights)
  193. assert len(items) > 0
  194. # Remove items with zero-weight.
  195. items2 = []
  196. weights2 = []
  197. for item, w in zip(items, weights):
  198. if w > 0:
  199. items2.append(item)
  200. weights2.append(w)
  201. items = items2
  202. weights = weights2
  203. # Make sure that we have some items left.
  204. if not items:
  205. raise ValueError("Did't got any items with a positive weight.")
  206. #
  207. already_taken = [0 for i in items]
  208. item_count = len(items)
  209. max_weight = max(weights)
  210. i = 0
  211. while True:
  212. # Each iteration of this loop, we fill up until by (total_weight/max_weight).
  213. adding = True
  214. while adding:
  215. adding = False
  216. for item_i, item, weight in zip(range(item_count), items, weights):
  217. if already_taken[item_i] < i * weight / float(max_weight):
  218. yield item
  219. already_taken[item_i] += 1
  220. adding = True
  221. i += 1
  222. def to_str(value: Callable[[], str] | str) -> str:
  223. "Turn callable or string into string."
  224. if callable(value):
  225. return to_str(value())
  226. else:
  227. return str(value)
  228. def to_int(value: Callable[[], int] | int) -> int:
  229. "Turn callable or int into int."
  230. if callable(value):
  231. return to_int(value())
  232. else:
  233. return int(value)
  234. AnyFloat = Union[Callable[[], float], float]
  235. def to_float(value: AnyFloat) -> float:
  236. "Turn callable or float into float."
  237. if callable(value):
  238. return to_float(value())
  239. else:
  240. return float(value)
  241. def is_dumb_terminal(term: str | None = None) -> bool:
  242. """
  243. True if this terminal type is considered "dumb".
  244. If so, we should fall back to the simplest possible form of line editing,
  245. without cursor positioning and color support.
  246. """
  247. if term is None:
  248. return is_dumb_terminal(os.environ.get("TERM", ""))
  249. return term.lower() in ["dumb", "unknown"]