application.py 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626
  1. from __future__ import annotations
  2. import asyncio
  3. import contextvars
  4. import os
  5. import re
  6. import signal
  7. import sys
  8. import threading
  9. import time
  10. from asyncio import (
  11. AbstractEventLoop,
  12. Future,
  13. Task,
  14. ensure_future,
  15. get_running_loop,
  16. sleep,
  17. )
  18. from contextlib import ExitStack, contextmanager
  19. from subprocess import Popen
  20. from traceback import format_tb
  21. from typing import (
  22. Any,
  23. Callable,
  24. Coroutine,
  25. Generator,
  26. Generic,
  27. Hashable,
  28. Iterable,
  29. Iterator,
  30. TypeVar,
  31. cast,
  32. overload,
  33. )
  34. from prompt_toolkit.buffer import Buffer
  35. from prompt_toolkit.cache import SimpleCache
  36. from prompt_toolkit.clipboard import Clipboard, InMemoryClipboard
  37. from prompt_toolkit.cursor_shapes import AnyCursorShapeConfig, to_cursor_shape_config
  38. from prompt_toolkit.data_structures import Size
  39. from prompt_toolkit.enums import EditingMode
  40. from prompt_toolkit.eventloop import (
  41. InputHook,
  42. get_traceback_from_context,
  43. new_eventloop_with_inputhook,
  44. run_in_executor_with_context,
  45. )
  46. from prompt_toolkit.eventloop.utils import call_soon_threadsafe
  47. from prompt_toolkit.filters import Condition, Filter, FilterOrBool, to_filter
  48. from prompt_toolkit.formatted_text import AnyFormattedText
  49. from prompt_toolkit.input.base import Input
  50. from prompt_toolkit.input.typeahead import get_typeahead, store_typeahead
  51. from prompt_toolkit.key_binding.bindings.page_navigation import (
  52. load_page_navigation_bindings,
  53. )
  54. from prompt_toolkit.key_binding.defaults import load_key_bindings
  55. from prompt_toolkit.key_binding.emacs_state import EmacsState
  56. from prompt_toolkit.key_binding.key_bindings import (
  57. Binding,
  58. ConditionalKeyBindings,
  59. GlobalOnlyKeyBindings,
  60. KeyBindings,
  61. KeyBindingsBase,
  62. KeysTuple,
  63. merge_key_bindings,
  64. )
  65. from prompt_toolkit.key_binding.key_processor import KeyPressEvent, KeyProcessor
  66. from prompt_toolkit.key_binding.vi_state import ViState
  67. from prompt_toolkit.keys import Keys
  68. from prompt_toolkit.layout.containers import Container, Window
  69. from prompt_toolkit.layout.controls import BufferControl, UIControl
  70. from prompt_toolkit.layout.dummy import create_dummy_layout
  71. from prompt_toolkit.layout.layout import Layout, walk
  72. from prompt_toolkit.output import ColorDepth, Output
  73. from prompt_toolkit.renderer import Renderer, print_formatted_text
  74. from prompt_toolkit.search import SearchState
  75. from prompt_toolkit.styles import (
  76. BaseStyle,
  77. DummyStyle,
  78. DummyStyleTransformation,
  79. DynamicStyle,
  80. StyleTransformation,
  81. default_pygments_style,
  82. default_ui_style,
  83. merge_styles,
  84. )
  85. from prompt_toolkit.utils import Event, in_main_thread
  86. from .current import get_app_session, set_app
  87. from .run_in_terminal import in_terminal, run_in_terminal
  88. __all__ = [
  89. "Application",
  90. ]
  91. E = KeyPressEvent
  92. _AppResult = TypeVar("_AppResult")
  93. ApplicationEventHandler = Callable[["Application[_AppResult]"], None]
  94. _SIGWINCH = getattr(signal, "SIGWINCH", None)
  95. _SIGTSTP = getattr(signal, "SIGTSTP", None)
  96. class Application(Generic[_AppResult]):
  97. """
  98. The main Application class!
  99. This glues everything together.
  100. :param layout: A :class:`~prompt_toolkit.layout.Layout` instance.
  101. :param key_bindings:
  102. :class:`~prompt_toolkit.key_binding.KeyBindingsBase` instance for
  103. the key bindings.
  104. :param clipboard: :class:`~prompt_toolkit.clipboard.Clipboard` to use.
  105. :param full_screen: When True, run the application on the alternate screen buffer.
  106. :param color_depth: Any :class:`~.ColorDepth` value, a callable that
  107. returns a :class:`~.ColorDepth` or `None` for default.
  108. :param erase_when_done: (bool) Clear the application output when it finishes.
  109. :param reverse_vi_search_direction: Normally, in Vi mode, a '/' searches
  110. forward and a '?' searches backward. In Readline mode, this is usually
  111. reversed.
  112. :param min_redraw_interval: Number of seconds to wait between redraws. Use
  113. this for applications where `invalidate` is called a lot. This could cause
  114. a lot of terminal output, which some terminals are not able to process.
  115. `None` means that every `invalidate` will be scheduled right away
  116. (which is usually fine).
  117. When one `invalidate` is called, but a scheduled redraw of a previous
  118. `invalidate` call has not been executed yet, nothing will happen in any
  119. case.
  120. :param max_render_postpone_time: When there is high CPU (a lot of other
  121. scheduled calls), postpone the rendering max x seconds. '0' means:
  122. don't postpone. '.5' means: try to draw at least twice a second.
  123. :param refresh_interval: Automatically invalidate the UI every so many
  124. seconds. When `None` (the default), only invalidate when `invalidate`
  125. has been called.
  126. :param terminal_size_polling_interval: Poll the terminal size every so many
  127. seconds. Useful if the applications runs in a thread other then then
  128. main thread where SIGWINCH can't be handled, or on Windows.
  129. Filters:
  130. :param mouse_support: (:class:`~prompt_toolkit.filters.Filter` or
  131. boolean). When True, enable mouse support.
  132. :param paste_mode: :class:`~prompt_toolkit.filters.Filter` or boolean.
  133. :param editing_mode: :class:`~prompt_toolkit.enums.EditingMode`.
  134. :param enable_page_navigation_bindings: When `True`, enable the page
  135. navigation key bindings. These include both Emacs and Vi bindings like
  136. page-up, page-down and so on to scroll through pages. Mostly useful for
  137. creating an editor or other full screen applications. Probably, you
  138. don't want this for the implementation of a REPL. By default, this is
  139. enabled if `full_screen` is set.
  140. Callbacks (all of these should accept an
  141. :class:`~prompt_toolkit.application.Application` object as input.)
  142. :param on_reset: Called during reset.
  143. :param on_invalidate: Called when the UI has been invalidated.
  144. :param before_render: Called right before rendering.
  145. :param after_render: Called right after rendering.
  146. I/O:
  147. (Note that the preferred way to change the input/output is by creating an
  148. `AppSession` with the required input/output objects. If you need multiple
  149. applications running at the same time, you have to create a separate
  150. `AppSession` using a `with create_app_session():` block.
  151. :param input: :class:`~prompt_toolkit.input.Input` instance.
  152. :param output: :class:`~prompt_toolkit.output.Output` instance. (Probably
  153. Vt100_Output or Win32Output.)
  154. Usage:
  155. app = Application(...)
  156. app.run()
  157. # Or
  158. await app.run_async()
  159. """
  160. def __init__(
  161. self,
  162. layout: Layout | None = None,
  163. style: BaseStyle | None = None,
  164. include_default_pygments_style: FilterOrBool = True,
  165. style_transformation: StyleTransformation | None = None,
  166. key_bindings: KeyBindingsBase | None = None,
  167. clipboard: Clipboard | None = None,
  168. full_screen: bool = False,
  169. color_depth: (ColorDepth | Callable[[], ColorDepth | None] | None) = None,
  170. mouse_support: FilterOrBool = False,
  171. enable_page_navigation_bindings: None
  172. | (FilterOrBool) = None, # Can be None, True or False.
  173. paste_mode: FilterOrBool = False,
  174. editing_mode: EditingMode = EditingMode.EMACS,
  175. erase_when_done: bool = False,
  176. reverse_vi_search_direction: FilterOrBool = False,
  177. min_redraw_interval: float | int | None = None,
  178. max_render_postpone_time: float | int | None = 0.01,
  179. refresh_interval: float | None = None,
  180. terminal_size_polling_interval: float | None = 0.5,
  181. cursor: AnyCursorShapeConfig = None,
  182. on_reset: ApplicationEventHandler[_AppResult] | None = None,
  183. on_invalidate: ApplicationEventHandler[_AppResult] | None = None,
  184. before_render: ApplicationEventHandler[_AppResult] | None = None,
  185. after_render: ApplicationEventHandler[_AppResult] | None = None,
  186. # I/O.
  187. input: Input | None = None,
  188. output: Output | None = None,
  189. ) -> None:
  190. # If `enable_page_navigation_bindings` is not specified, enable it in
  191. # case of full screen applications only. This can be overridden by the user.
  192. if enable_page_navigation_bindings is None:
  193. enable_page_navigation_bindings = Condition(lambda: self.full_screen)
  194. paste_mode = to_filter(paste_mode)
  195. mouse_support = to_filter(mouse_support)
  196. reverse_vi_search_direction = to_filter(reverse_vi_search_direction)
  197. enable_page_navigation_bindings = to_filter(enable_page_navigation_bindings)
  198. include_default_pygments_style = to_filter(include_default_pygments_style)
  199. if layout is None:
  200. layout = create_dummy_layout()
  201. if style_transformation is None:
  202. style_transformation = DummyStyleTransformation()
  203. self.style = style
  204. self.style_transformation = style_transformation
  205. # Key bindings.
  206. self.key_bindings = key_bindings
  207. self._default_bindings = load_key_bindings()
  208. self._page_navigation_bindings = load_page_navigation_bindings()
  209. self.layout = layout
  210. self.clipboard = clipboard or InMemoryClipboard()
  211. self.full_screen: bool = full_screen
  212. self._color_depth = color_depth
  213. self.mouse_support = mouse_support
  214. self.paste_mode = paste_mode
  215. self.editing_mode = editing_mode
  216. self.erase_when_done = erase_when_done
  217. self.reverse_vi_search_direction = reverse_vi_search_direction
  218. self.enable_page_navigation_bindings = enable_page_navigation_bindings
  219. self.min_redraw_interval = min_redraw_interval
  220. self.max_render_postpone_time = max_render_postpone_time
  221. self.refresh_interval = refresh_interval
  222. self.terminal_size_polling_interval = terminal_size_polling_interval
  223. self.cursor = to_cursor_shape_config(cursor)
  224. # Events.
  225. self.on_invalidate = Event(self, on_invalidate)
  226. self.on_reset = Event(self, on_reset)
  227. self.before_render = Event(self, before_render)
  228. self.after_render = Event(self, after_render)
  229. # I/O.
  230. session = get_app_session()
  231. self.output = output or session.output
  232. self.input = input or session.input
  233. # List of 'extra' functions to execute before a Application.run.
  234. self.pre_run_callables: list[Callable[[], None]] = []
  235. self._is_running = False
  236. self.future: Future[_AppResult] | None = None
  237. self.loop: AbstractEventLoop | None = None
  238. self._loop_thread: threading.Thread | None = None
  239. self.context: contextvars.Context | None = None
  240. #: Quoted insert. This flag is set if we go into quoted insert mode.
  241. self.quoted_insert = False
  242. #: Vi state. (For Vi key bindings.)
  243. self.vi_state = ViState()
  244. self.emacs_state = EmacsState()
  245. #: When to flush the input (For flushing escape keys.) This is important
  246. #: on terminals that use vt100 input. We can't distinguish the escape
  247. #: key from for instance the left-arrow key, if we don't know what follows
  248. #: after "\x1b". This little timer will consider "\x1b" to be escape if
  249. #: nothing did follow in this time span.
  250. #: This seems to work like the `ttimeoutlen` option in Vim.
  251. self.ttimeoutlen = 0.5 # Seconds.
  252. #: Like Vim's `timeoutlen` option. This can be `None` or a float. For
  253. #: instance, suppose that we have a key binding AB and a second key
  254. #: binding A. If the uses presses A and then waits, we don't handle
  255. #: this binding yet (unless it was marked 'eager'), because we don't
  256. #: know what will follow. This timeout is the maximum amount of time
  257. #: that we wait until we call the handlers anyway. Pass `None` to
  258. #: disable this timeout.
  259. self.timeoutlen = 1.0
  260. #: The `Renderer` instance.
  261. # Make sure that the same stdout is used, when a custom renderer has been passed.
  262. self._merged_style = self._create_merged_style(include_default_pygments_style)
  263. self.renderer = Renderer(
  264. self._merged_style,
  265. self.output,
  266. full_screen=full_screen,
  267. mouse_support=mouse_support,
  268. cpr_not_supported_callback=self.cpr_not_supported_callback,
  269. )
  270. #: Render counter. This one is increased every time the UI is rendered.
  271. #: It can be used as a key for caching certain information during one
  272. #: rendering.
  273. self.render_counter = 0
  274. # Invalidate flag. When 'True', a repaint has been scheduled.
  275. self._invalidated = False
  276. self._invalidate_events: list[
  277. Event[object]
  278. ] = [] # Collection of 'invalidate' Event objects.
  279. self._last_redraw_time = 0.0 # Unix timestamp of last redraw. Used when
  280. # `min_redraw_interval` is given.
  281. #: The `InputProcessor` instance.
  282. self.key_processor = KeyProcessor(_CombinedRegistry(self))
  283. # If `run_in_terminal` was called. This will point to a `Future` what will be
  284. # set at the point when the previous run finishes.
  285. self._running_in_terminal = False
  286. self._running_in_terminal_f: Future[None] | None = None
  287. # Trigger initialize callback.
  288. self.reset()
  289. def _create_merged_style(self, include_default_pygments_style: Filter) -> BaseStyle:
  290. """
  291. Create a `Style` object that merges the default UI style, the default
  292. pygments style, and the custom user style.
  293. """
  294. dummy_style = DummyStyle()
  295. pygments_style = default_pygments_style()
  296. @DynamicStyle
  297. def conditional_pygments_style() -> BaseStyle:
  298. if include_default_pygments_style():
  299. return pygments_style
  300. else:
  301. return dummy_style
  302. return merge_styles(
  303. [
  304. default_ui_style(),
  305. conditional_pygments_style,
  306. DynamicStyle(lambda: self.style),
  307. ]
  308. )
  309. @property
  310. def color_depth(self) -> ColorDepth:
  311. """
  312. The active :class:`.ColorDepth`.
  313. The current value is determined as follows:
  314. - If a color depth was given explicitly to this application, use that
  315. value.
  316. - Otherwise, fall back to the color depth that is reported by the
  317. :class:`.Output` implementation. If the :class:`.Output` class was
  318. created using `output.defaults.create_output`, then this value is
  319. coming from the $PROMPT_TOOLKIT_COLOR_DEPTH environment variable.
  320. """
  321. depth = self._color_depth
  322. if callable(depth):
  323. depth = depth()
  324. if depth is None:
  325. depth = self.output.get_default_color_depth()
  326. return depth
  327. @property
  328. def current_buffer(self) -> Buffer:
  329. """
  330. The currently focused :class:`~.Buffer`.
  331. (This returns a dummy :class:`.Buffer` when none of the actual buffers
  332. has the focus. In this case, it's really not practical to check for
  333. `None` values or catch exceptions every time.)
  334. """
  335. return self.layout.current_buffer or Buffer(
  336. name="dummy-buffer"
  337. ) # Dummy buffer.
  338. @property
  339. def current_search_state(self) -> SearchState:
  340. """
  341. Return the current :class:`.SearchState`. (The one for the focused
  342. :class:`.BufferControl`.)
  343. """
  344. ui_control = self.layout.current_control
  345. if isinstance(ui_control, BufferControl):
  346. return ui_control.search_state
  347. else:
  348. return SearchState() # Dummy search state. (Don't return None!)
  349. def reset(self) -> None:
  350. """
  351. Reset everything, for reading the next input.
  352. """
  353. # Notice that we don't reset the buffers. (This happens just before
  354. # returning, and when we have multiple buffers, we clearly want the
  355. # content in the other buffers to remain unchanged between several
  356. # calls of `run`. (And the same is true for the focus stack.)
  357. self.exit_style = ""
  358. self._background_tasks: set[Task[None]] = set()
  359. self.renderer.reset()
  360. self.key_processor.reset()
  361. self.layout.reset()
  362. self.vi_state.reset()
  363. self.emacs_state.reset()
  364. # Trigger reset event.
  365. self.on_reset.fire()
  366. # Make sure that we have a 'focusable' widget focused.
  367. # (The `Layout` class can't determine this.)
  368. layout = self.layout
  369. if not layout.current_control.is_focusable():
  370. for w in layout.find_all_windows():
  371. if w.content.is_focusable():
  372. layout.current_window = w
  373. break
  374. def invalidate(self) -> None:
  375. """
  376. Thread safe way of sending a repaint trigger to the input event loop.
  377. """
  378. if not self._is_running:
  379. # Don't schedule a redraw if we're not running.
  380. # Otherwise, `get_running_loop()` in `call_soon_threadsafe` can fail.
  381. # See: https://github.com/dbcli/mycli/issues/797
  382. return
  383. # `invalidate()` called if we don't have a loop yet (not running?), or
  384. # after the event loop was closed.
  385. if self.loop is None or self.loop.is_closed():
  386. return
  387. # Never schedule a second redraw, when a previous one has not yet been
  388. # executed. (This should protect against other threads calling
  389. # 'invalidate' many times, resulting in 100% CPU.)
  390. if self._invalidated:
  391. return
  392. else:
  393. self._invalidated = True
  394. # Trigger event.
  395. self.loop.call_soon_threadsafe(self.on_invalidate.fire)
  396. def redraw() -> None:
  397. self._invalidated = False
  398. self._redraw()
  399. def schedule_redraw() -> None:
  400. call_soon_threadsafe(
  401. redraw, max_postpone_time=self.max_render_postpone_time, loop=self.loop
  402. )
  403. if self.min_redraw_interval:
  404. # When a minimum redraw interval is set, wait minimum this amount
  405. # of time between redraws.
  406. diff = time.time() - self._last_redraw_time
  407. if diff < self.min_redraw_interval:
  408. async def redraw_in_future() -> None:
  409. await sleep(cast(float, self.min_redraw_interval) - diff)
  410. schedule_redraw()
  411. self.loop.call_soon_threadsafe(
  412. lambda: self.create_background_task(redraw_in_future())
  413. )
  414. else:
  415. schedule_redraw()
  416. else:
  417. schedule_redraw()
  418. @property
  419. def invalidated(self) -> bool:
  420. "True when a redraw operation has been scheduled."
  421. return self._invalidated
  422. def _redraw(self, render_as_done: bool = False) -> None:
  423. """
  424. Render the command line again. (Not thread safe!) (From other threads,
  425. or if unsure, use :meth:`.Application.invalidate`.)
  426. :param render_as_done: make sure to put the cursor after the UI.
  427. """
  428. def run_in_context() -> None:
  429. # Only draw when no sub application was started.
  430. if self._is_running and not self._running_in_terminal:
  431. if self.min_redraw_interval:
  432. self._last_redraw_time = time.time()
  433. # Render
  434. self.render_counter += 1
  435. self.before_render.fire()
  436. if render_as_done:
  437. if self.erase_when_done:
  438. self.renderer.erase()
  439. else:
  440. # Draw in 'done' state and reset renderer.
  441. self.renderer.render(self, self.layout, is_done=render_as_done)
  442. else:
  443. self.renderer.render(self, self.layout)
  444. self.layout.update_parents_relations()
  445. # Fire render event.
  446. self.after_render.fire()
  447. self._update_invalidate_events()
  448. # NOTE: We want to make sure this Application is the active one. The
  449. # invalidate function is often called from a context where this
  450. # application is not the active one. (Like the
  451. # `PromptSession._auto_refresh_context`).
  452. # We copy the context in case the context was already active, to
  453. # prevent RuntimeErrors. (The rendering is not supposed to change
  454. # any context variables.)
  455. if self.context is not None:
  456. self.context.copy().run(run_in_context)
  457. def _start_auto_refresh_task(self) -> None:
  458. """
  459. Start a while/true loop in the background for automatic invalidation of
  460. the UI.
  461. """
  462. if self.refresh_interval is not None and self.refresh_interval != 0:
  463. async def auto_refresh(refresh_interval: float) -> None:
  464. while True:
  465. await sleep(refresh_interval)
  466. self.invalidate()
  467. self.create_background_task(auto_refresh(self.refresh_interval))
  468. def _update_invalidate_events(self) -> None:
  469. """
  470. Make sure to attach 'invalidate' handlers to all invalidate events in
  471. the UI.
  472. """
  473. # Remove all the original event handlers. (Components can be removed
  474. # from the UI.)
  475. for ev in self._invalidate_events:
  476. ev -= self._invalidate_handler
  477. # Gather all new events.
  478. # (All controls are able to invalidate themselves.)
  479. def gather_events() -> Iterable[Event[object]]:
  480. for c in self.layout.find_all_controls():
  481. yield from c.get_invalidate_events()
  482. self._invalidate_events = list(gather_events())
  483. for ev in self._invalidate_events:
  484. ev += self._invalidate_handler
  485. def _invalidate_handler(self, sender: object) -> None:
  486. """
  487. Handler for invalidate events coming from UIControls.
  488. (This handles the difference in signature between event handler and
  489. `self.invalidate`. It also needs to be a method -not a nested
  490. function-, so that we can remove it again .)
  491. """
  492. self.invalidate()
  493. def _on_resize(self) -> None:
  494. """
  495. When the window size changes, we erase the current output and request
  496. again the cursor position. When the CPR answer arrives, the output is
  497. drawn again.
  498. """
  499. # Erase, request position (when cursor is at the start position)
  500. # and redraw again. -- The order is important.
  501. self.renderer.erase(leave_alternate_screen=False)
  502. self._request_absolute_cursor_position()
  503. self._redraw()
  504. def _pre_run(self, pre_run: Callable[[], None] | None = None) -> None:
  505. """
  506. Called during `run`.
  507. `self.future` should be set to the new future at the point where this
  508. is called in order to avoid data races. `pre_run` can be used to set a
  509. `threading.Event` to synchronize with UI termination code, running in
  510. another thread that would call `Application.exit`. (See the progress
  511. bar code for an example.)
  512. """
  513. if pre_run:
  514. pre_run()
  515. # Process registered "pre_run_callables" and clear list.
  516. for c in self.pre_run_callables:
  517. c()
  518. del self.pre_run_callables[:]
  519. async def run_async(
  520. self,
  521. pre_run: Callable[[], None] | None = None,
  522. set_exception_handler: bool = True,
  523. handle_sigint: bool = True,
  524. slow_callback_duration: float = 0.5,
  525. ) -> _AppResult:
  526. """
  527. Run the prompt_toolkit :class:`~prompt_toolkit.application.Application`
  528. until :meth:`~prompt_toolkit.application.Application.exit` has been
  529. called. Return the value that was passed to
  530. :meth:`~prompt_toolkit.application.Application.exit`.
  531. This is the main entry point for a prompt_toolkit
  532. :class:`~prompt_toolkit.application.Application` and usually the only
  533. place where the event loop is actually running.
  534. :param pre_run: Optional callable, which is called right after the
  535. "reset" of the application.
  536. :param set_exception_handler: When set, in case of an exception, go out
  537. of the alternate screen and hide the application, display the
  538. exception, and wait for the user to press ENTER.
  539. :param handle_sigint: Handle SIGINT signal if possible. This will call
  540. the `<sigint>` key binding when a SIGINT is received. (This only
  541. works in the main thread.)
  542. :param slow_callback_duration: Display warnings if code scheduled in
  543. the asyncio event loop takes more time than this. The asyncio
  544. default of `0.1` is sometimes not sufficient on a slow system,
  545. because exceptionally, the drawing of the app, which happens in the
  546. event loop, can take a bit longer from time to time.
  547. """
  548. assert not self._is_running, "Application is already running."
  549. if not in_main_thread() or sys.platform == "win32":
  550. # Handling signals in other threads is not supported.
  551. # Also on Windows, `add_signal_handler(signal.SIGINT, ...)` raises
  552. # `NotImplementedError`.
  553. # See: https://github.com/prompt-toolkit/python-prompt-toolkit/issues/1553
  554. handle_sigint = False
  555. async def _run_async(f: asyncio.Future[_AppResult]) -> _AppResult:
  556. context = contextvars.copy_context()
  557. self.context = context
  558. # Counter for cancelling 'flush' timeouts. Every time when a key is
  559. # pressed, we start a 'flush' timer for flushing our escape key. But
  560. # when any subsequent input is received, a new timer is started and
  561. # the current timer will be ignored.
  562. flush_task: asyncio.Task[None] | None = None
  563. # Reset.
  564. # (`self.future` needs to be set when `pre_run` is called.)
  565. self.reset()
  566. self._pre_run(pre_run)
  567. # Feed type ahead input first.
  568. self.key_processor.feed_multiple(get_typeahead(self.input))
  569. self.key_processor.process_keys()
  570. def read_from_input() -> None:
  571. nonlocal flush_task
  572. # Ignore when we aren't running anymore. This callback will
  573. # removed from the loop next time. (It could be that it was
  574. # still in the 'tasks' list of the loop.)
  575. # Except: if we need to process incoming CPRs.
  576. if not self._is_running and not self.renderer.waiting_for_cpr:
  577. return
  578. # Get keys from the input object.
  579. keys = self.input.read_keys()
  580. # Feed to key processor.
  581. self.key_processor.feed_multiple(keys)
  582. self.key_processor.process_keys()
  583. # Quit when the input stream was closed.
  584. if self.input.closed:
  585. if not f.done():
  586. f.set_exception(EOFError)
  587. else:
  588. # Automatically flush keys.
  589. if flush_task:
  590. flush_task.cancel()
  591. flush_task = self.create_background_task(auto_flush_input())
  592. def read_from_input_in_context() -> None:
  593. # Ensure that key bindings callbacks are always executed in the
  594. # current context. This is important when key bindings are
  595. # accessing contextvars. (These callbacks are currently being
  596. # called from a different context. Underneath,
  597. # `loop.add_reader` is used to register the stdin FD.)
  598. # (We copy the context to avoid a `RuntimeError` in case the
  599. # context is already active.)
  600. context.copy().run(read_from_input)
  601. async def auto_flush_input() -> None:
  602. # Flush input after timeout.
  603. # (Used for flushing the enter key.)
  604. # This sleep can be cancelled, in that case we won't flush yet.
  605. await sleep(self.ttimeoutlen)
  606. flush_input()
  607. def flush_input() -> None:
  608. if not self.is_done:
  609. # Get keys, and feed to key processor.
  610. keys = self.input.flush_keys()
  611. self.key_processor.feed_multiple(keys)
  612. self.key_processor.process_keys()
  613. if self.input.closed:
  614. f.set_exception(EOFError)
  615. # Enter raw mode, attach input and attach WINCH event handler.
  616. with self.input.raw_mode(), self.input.attach(
  617. read_from_input_in_context
  618. ), attach_winch_signal_handler(self._on_resize):
  619. # Draw UI.
  620. self._request_absolute_cursor_position()
  621. self._redraw()
  622. self._start_auto_refresh_task()
  623. self.create_background_task(self._poll_output_size())
  624. # Wait for UI to finish.
  625. try:
  626. result = await f
  627. finally:
  628. # In any case, when the application finishes.
  629. # (Successful, or because of an error.)
  630. try:
  631. self._redraw(render_as_done=True)
  632. finally:
  633. # _redraw has a good chance to fail if it calls widgets
  634. # with bad code. Make sure to reset the renderer
  635. # anyway.
  636. self.renderer.reset()
  637. # Unset `is_running`, this ensures that possibly
  638. # scheduled draws won't paint during the following
  639. # yield.
  640. self._is_running = False
  641. # Detach event handlers for invalidate events.
  642. # (Important when a UIControl is embedded in multiple
  643. # applications, like ptterm in pymux. An invalidate
  644. # should not trigger a repaint in terminated
  645. # applications.)
  646. for ev in self._invalidate_events:
  647. ev -= self._invalidate_handler
  648. self._invalidate_events = []
  649. # Wait for CPR responses.
  650. if self.output.responds_to_cpr:
  651. await self.renderer.wait_for_cpr_responses()
  652. # Wait for the run-in-terminals to terminate.
  653. previous_run_in_terminal_f = self._running_in_terminal_f
  654. if previous_run_in_terminal_f:
  655. await previous_run_in_terminal_f
  656. # Store unprocessed input as typeahead for next time.
  657. store_typeahead(self.input, self.key_processor.empty_queue())
  658. return result
  659. @contextmanager
  660. def set_loop() -> Iterator[AbstractEventLoop]:
  661. loop = get_running_loop()
  662. self.loop = loop
  663. self._loop_thread = threading.current_thread()
  664. try:
  665. yield loop
  666. finally:
  667. self.loop = None
  668. self._loop_thread = None
  669. @contextmanager
  670. def set_is_running() -> Iterator[None]:
  671. self._is_running = True
  672. try:
  673. yield
  674. finally:
  675. self._is_running = False
  676. @contextmanager
  677. def set_handle_sigint(loop: AbstractEventLoop) -> Iterator[None]:
  678. if handle_sigint:
  679. with _restore_sigint_from_ctypes():
  680. # save sigint handlers (python and os level)
  681. # See: https://github.com/prompt-toolkit/python-prompt-toolkit/issues/1576
  682. loop.add_signal_handler(
  683. signal.SIGINT,
  684. lambda *_: loop.call_soon_threadsafe(
  685. self.key_processor.send_sigint
  686. ),
  687. )
  688. try:
  689. yield
  690. finally:
  691. loop.remove_signal_handler(signal.SIGINT)
  692. else:
  693. yield
  694. @contextmanager
  695. def set_exception_handler_ctx(loop: AbstractEventLoop) -> Iterator[None]:
  696. if set_exception_handler:
  697. previous_exc_handler = loop.get_exception_handler()
  698. loop.set_exception_handler(self._handle_exception)
  699. try:
  700. yield
  701. finally:
  702. loop.set_exception_handler(previous_exc_handler)
  703. else:
  704. yield
  705. @contextmanager
  706. def set_callback_duration(loop: AbstractEventLoop) -> Iterator[None]:
  707. # Set slow_callback_duration.
  708. original_slow_callback_duration = loop.slow_callback_duration
  709. loop.slow_callback_duration = slow_callback_duration
  710. try:
  711. yield
  712. finally:
  713. # Reset slow_callback_duration.
  714. loop.slow_callback_duration = original_slow_callback_duration
  715. @contextmanager
  716. def create_future(
  717. loop: AbstractEventLoop,
  718. ) -> Iterator[asyncio.Future[_AppResult]]:
  719. f = loop.create_future()
  720. self.future = f # XXX: make sure to set this before calling '_redraw'.
  721. try:
  722. yield f
  723. finally:
  724. # Also remove the Future again. (This brings the
  725. # application back to its initial state, where it also
  726. # doesn't have a Future.)
  727. self.future = None
  728. with ExitStack() as stack:
  729. stack.enter_context(set_is_running())
  730. # Make sure to set `_invalidated` to `False` to begin with,
  731. # otherwise we're not going to paint anything. This can happen if
  732. # this application had run before on a different event loop, and a
  733. # paint was scheduled using `call_soon_threadsafe` with
  734. # `max_postpone_time`.
  735. self._invalidated = False
  736. loop = stack.enter_context(set_loop())
  737. stack.enter_context(set_handle_sigint(loop))
  738. stack.enter_context(set_exception_handler_ctx(loop))
  739. stack.enter_context(set_callback_duration(loop))
  740. stack.enter_context(set_app(self))
  741. stack.enter_context(self._enable_breakpointhook())
  742. f = stack.enter_context(create_future(loop))
  743. try:
  744. return await _run_async(f)
  745. finally:
  746. # Wait for the background tasks to be done. This needs to
  747. # go in the finally! If `_run_async` raises
  748. # `KeyboardInterrupt`, we still want to wait for the
  749. # background tasks.
  750. await self.cancel_and_wait_for_background_tasks()
  751. # The `ExitStack` above is defined in typeshed in a way that it can
  752. # swallow exceptions. Without next line, mypy would think that there's
  753. # a possibility we don't return here. See:
  754. # https://github.com/python/mypy/issues/7726
  755. assert False, "unreachable"
  756. def run(
  757. self,
  758. pre_run: Callable[[], None] | None = None,
  759. set_exception_handler: bool = True,
  760. handle_sigint: bool = True,
  761. in_thread: bool = False,
  762. inputhook: InputHook | None = None,
  763. ) -> _AppResult:
  764. """
  765. A blocking 'run' call that waits until the UI is finished.
  766. This will run the application in a fresh asyncio event loop.
  767. :param pre_run: Optional callable, which is called right after the
  768. "reset" of the application.
  769. :param set_exception_handler: When set, in case of an exception, go out
  770. of the alternate screen and hide the application, display the
  771. exception, and wait for the user to press ENTER.
  772. :param in_thread: When true, run the application in a background
  773. thread, and block the current thread until the application
  774. terminates. This is useful if we need to be sure the application
  775. won't use the current event loop (asyncio does not support nested
  776. event loops). A new event loop will be created in this background
  777. thread, and that loop will also be closed when the background
  778. thread terminates. When this is used, it's especially important to
  779. make sure that all asyncio background tasks are managed through
  780. `get_appp().create_background_task()`, so that unfinished tasks are
  781. properly cancelled before the event loop is closed. This is used
  782. for instance in ptpython.
  783. :param handle_sigint: Handle SIGINT signal. Call the key binding for
  784. `Keys.SIGINT`. (This only works in the main thread.)
  785. """
  786. if in_thread:
  787. result: _AppResult
  788. exception: BaseException | None = None
  789. def run_in_thread() -> None:
  790. nonlocal result, exception
  791. try:
  792. result = self.run(
  793. pre_run=pre_run,
  794. set_exception_handler=set_exception_handler,
  795. # Signal handling only works in the main thread.
  796. handle_sigint=False,
  797. inputhook=inputhook,
  798. )
  799. except BaseException as e:
  800. exception = e
  801. thread = threading.Thread(target=run_in_thread)
  802. thread.start()
  803. thread.join()
  804. if exception is not None:
  805. raise exception
  806. return result
  807. coro = self.run_async(
  808. pre_run=pre_run,
  809. set_exception_handler=set_exception_handler,
  810. handle_sigint=handle_sigint,
  811. )
  812. def _called_from_ipython() -> bool:
  813. try:
  814. return (
  815. sys.modules["IPython"].version_info < (8, 18, 0, "")
  816. and "IPython/terminal/interactiveshell.py"
  817. in sys._getframe(3).f_code.co_filename
  818. )
  819. except BaseException:
  820. return False
  821. if inputhook is not None:
  822. # Create new event loop with given input hook and run the app.
  823. # In Python 3.12, we can use asyncio.run(loop_factory=...)
  824. # For now, use `run_until_complete()`.
  825. loop = new_eventloop_with_inputhook(inputhook)
  826. result = loop.run_until_complete(coro)
  827. loop.run_until_complete(loop.shutdown_asyncgens())
  828. loop.close()
  829. return result
  830. elif _called_from_ipython():
  831. # workaround to make input hooks work for IPython until
  832. # https://github.com/ipython/ipython/pull/14241 is merged.
  833. # IPython was setting the input hook by installing an event loop
  834. # previously.
  835. try:
  836. # See whether a loop was installed already. If so, use that.
  837. # That's required for the input hooks to work, they are
  838. # installed using `set_event_loop`.
  839. loop = asyncio.get_event_loop()
  840. except RuntimeError:
  841. # No loop installed. Run like usual.
  842. return asyncio.run(coro)
  843. else:
  844. # Use existing loop.
  845. return loop.run_until_complete(coro)
  846. else:
  847. # No loop installed. Run like usual.
  848. return asyncio.run(coro)
  849. def _handle_exception(
  850. self, loop: AbstractEventLoop, context: dict[str, Any]
  851. ) -> None:
  852. """
  853. Handler for event loop exceptions.
  854. This will print the exception, using run_in_terminal.
  855. """
  856. # For Python 2: we have to get traceback at this point, because
  857. # we're still in the 'except:' block of the event loop where the
  858. # traceback is still available. Moving this code in the
  859. # 'print_exception' coroutine will loose the exception.
  860. tb = get_traceback_from_context(context)
  861. formatted_tb = "".join(format_tb(tb))
  862. async def in_term() -> None:
  863. async with in_terminal():
  864. # Print output. Similar to 'loop.default_exception_handler',
  865. # but don't use logger. (This works better on Python 2.)
  866. print("\nUnhandled exception in event loop:")
  867. print(formatted_tb)
  868. print("Exception {}".format(context.get("exception")))
  869. await _do_wait_for_enter("Press ENTER to continue...")
  870. ensure_future(in_term())
  871. @contextmanager
  872. def _enable_breakpointhook(self) -> Generator[None, None, None]:
  873. """
  874. Install our custom breakpointhook for the duration of this context
  875. manager. (We will only install the hook if no other custom hook was
  876. set.)
  877. """
  878. if sys.breakpointhook == sys.__breakpointhook__:
  879. sys.breakpointhook = self._breakpointhook
  880. try:
  881. yield
  882. finally:
  883. sys.breakpointhook = sys.__breakpointhook__
  884. else:
  885. yield
  886. def _breakpointhook(self, *a: object, **kw: object) -> None:
  887. """
  888. Breakpointhook which uses PDB, but ensures that the application is
  889. hidden and input echoing is restored during each debugger dispatch.
  890. This can be called from any thread. In any case, the application's
  891. event loop will be blocked while the PDB input is displayed. The event
  892. will continue after leaving the debugger.
  893. """
  894. app = self
  895. # Inline import on purpose. We don't want to import pdb, if not needed.
  896. import pdb
  897. from types import FrameType
  898. TraceDispatch = Callable[[FrameType, str, Any], Any]
  899. @contextmanager
  900. def hide_app_from_eventloop_thread() -> Generator[None, None, None]:
  901. """Stop application if `__breakpointhook__` is called from within
  902. the App's event loop."""
  903. # Hide application.
  904. app.renderer.erase()
  905. # Detach input and dispatch to debugger.
  906. with app.input.detach():
  907. with app.input.cooked_mode():
  908. yield
  909. # Note: we don't render the application again here, because
  910. # there's a good chance that there's a breakpoint on the next
  911. # line. This paint/erase cycle would move the PDB prompt back
  912. # to the middle of the screen.
  913. @contextmanager
  914. def hide_app_from_other_thread() -> Generator[None, None, None]:
  915. """Stop application if `__breakpointhook__` is called from a
  916. thread other than the App's event loop."""
  917. ready = threading.Event()
  918. done = threading.Event()
  919. async def in_loop() -> None:
  920. # from .run_in_terminal import in_terminal
  921. # async with in_terminal():
  922. # ready.set()
  923. # await asyncio.get_running_loop().run_in_executor(None, done.wait)
  924. # return
  925. # Hide application.
  926. app.renderer.erase()
  927. # Detach input and dispatch to debugger.
  928. with app.input.detach():
  929. with app.input.cooked_mode():
  930. ready.set()
  931. # Here we block the App's event loop thread until the
  932. # debugger resumes. We could have used `with
  933. # run_in_terminal.in_terminal():` like the commented
  934. # code above, but it seems to work better if we
  935. # completely stop the main event loop while debugging.
  936. done.wait()
  937. self.create_background_task(in_loop())
  938. ready.wait()
  939. try:
  940. yield
  941. finally:
  942. done.set()
  943. class CustomPdb(pdb.Pdb):
  944. def trace_dispatch(
  945. self, frame: FrameType, event: str, arg: Any
  946. ) -> TraceDispatch:
  947. if app._loop_thread is None:
  948. return super().trace_dispatch(frame, event, arg)
  949. if app._loop_thread == threading.current_thread():
  950. with hide_app_from_eventloop_thread():
  951. return super().trace_dispatch(frame, event, arg)
  952. with hide_app_from_other_thread():
  953. return super().trace_dispatch(frame, event, arg)
  954. frame = sys._getframe().f_back
  955. CustomPdb(stdout=sys.__stdout__).set_trace(frame)
  956. def create_background_task(
  957. self, coroutine: Coroutine[Any, Any, None]
  958. ) -> asyncio.Task[None]:
  959. """
  960. Start a background task (coroutine) for the running application. When
  961. the `Application` terminates, unfinished background tasks will be
  962. cancelled.
  963. Given that we still support Python versions before 3.11, we can't use
  964. task groups (and exception groups), because of that, these background
  965. tasks are not allowed to raise exceptions. If they do, we'll call the
  966. default exception handler from the event loop.
  967. If at some point, we have Python 3.11 as the minimum supported Python
  968. version, then we can use a `TaskGroup` (with the lifetime of
  969. `Application.run_async()`, and run run the background tasks in there.
  970. This is not threadsafe.
  971. """
  972. loop = self.loop or get_running_loop()
  973. task: asyncio.Task[None] = loop.create_task(coroutine)
  974. self._background_tasks.add(task)
  975. task.add_done_callback(self._on_background_task_done)
  976. return task
  977. def _on_background_task_done(self, task: asyncio.Task[None]) -> None:
  978. """
  979. Called when a background task completes. Remove it from
  980. `_background_tasks`, and handle exceptions if any.
  981. """
  982. self._background_tasks.discard(task)
  983. if task.cancelled():
  984. return
  985. exc = task.exception()
  986. if exc is not None:
  987. get_running_loop().call_exception_handler(
  988. {
  989. "message": f"prompt_toolkit.Application background task {task!r} "
  990. "raised an unexpected exception.",
  991. "exception": exc,
  992. "task": task,
  993. }
  994. )
  995. async def cancel_and_wait_for_background_tasks(self) -> None:
  996. """
  997. Cancel all background tasks, and wait for the cancellation to complete.
  998. If any of the background tasks raised an exception, this will also
  999. propagate the exception.
  1000. (If we had nurseries like Trio, this would be the `__aexit__` of a
  1001. nursery.)
  1002. """
  1003. for task in self._background_tasks:
  1004. task.cancel()
  1005. # Wait until the cancellation of the background tasks completes.
  1006. # `asyncio.wait()` does not propagate exceptions raised within any of
  1007. # these tasks, which is what we want. Otherwise, we can't distinguish
  1008. # between a `CancelledError` raised in this task because it got
  1009. # cancelled, and a `CancelledError` raised on this `await` checkpoint,
  1010. # because *we* got cancelled during the teardown of the application.
  1011. # (If we get cancelled here, then it's important to not suppress the
  1012. # `CancelledError`, and have it propagate.)
  1013. # NOTE: Currently, if we get cancelled at this point then we can't wait
  1014. # for the cancellation to complete (in the future, we should be
  1015. # using anyio or Python's 3.11 TaskGroup.)
  1016. # Also, if we had exception groups, we could propagate an
  1017. # `ExceptionGroup` if something went wrong here. Right now, we
  1018. # don't propagate exceptions, but have them printed in
  1019. # `_on_background_task_done`.
  1020. if len(self._background_tasks) > 0:
  1021. await asyncio.wait(
  1022. self._background_tasks, timeout=None, return_when=asyncio.ALL_COMPLETED
  1023. )
  1024. async def _poll_output_size(self) -> None:
  1025. """
  1026. Coroutine for polling the terminal dimensions.
  1027. Useful for situations where `attach_winch_signal_handler` is not sufficient:
  1028. - If we are not running in the main thread.
  1029. - On Windows.
  1030. """
  1031. size: Size | None = None
  1032. interval = self.terminal_size_polling_interval
  1033. if interval is None:
  1034. return
  1035. while True:
  1036. await asyncio.sleep(interval)
  1037. new_size = self.output.get_size()
  1038. if size is not None and new_size != size:
  1039. self._on_resize()
  1040. size = new_size
  1041. def cpr_not_supported_callback(self) -> None:
  1042. """
  1043. Called when we don't receive the cursor position response in time.
  1044. """
  1045. if not self.output.responds_to_cpr:
  1046. return # We know about this already.
  1047. def in_terminal() -> None:
  1048. self.output.write(
  1049. "WARNING: your terminal doesn't support cursor position requests (CPR).\r\n"
  1050. )
  1051. self.output.flush()
  1052. run_in_terminal(in_terminal)
  1053. @overload
  1054. def exit(self) -> None:
  1055. "Exit without arguments."
  1056. @overload
  1057. def exit(self, *, result: _AppResult, style: str = "") -> None:
  1058. "Exit with `_AppResult`."
  1059. @overload
  1060. def exit(
  1061. self, *, exception: BaseException | type[BaseException], style: str = ""
  1062. ) -> None:
  1063. "Exit with exception."
  1064. def exit(
  1065. self,
  1066. result: _AppResult | None = None,
  1067. exception: BaseException | type[BaseException] | None = None,
  1068. style: str = "",
  1069. ) -> None:
  1070. """
  1071. Exit application.
  1072. .. note::
  1073. If `Application.exit` is called before `Application.run()` is
  1074. called, then the `Application` won't exit (because the
  1075. `Application.future` doesn't correspond to the current run). Use a
  1076. `pre_run` hook and an event to synchronize the closing if there's a
  1077. chance this can happen.
  1078. :param result: Set this result for the application.
  1079. :param exception: Set this exception as the result for an application. For
  1080. a prompt, this is often `EOFError` or `KeyboardInterrupt`.
  1081. :param style: Apply this style on the whole content when quitting,
  1082. often this is 'class:exiting' for a prompt. (Used when
  1083. `erase_when_done` is not set.)
  1084. """
  1085. assert result is None or exception is None
  1086. if self.future is None:
  1087. raise Exception("Application is not running. Application.exit() failed.")
  1088. if self.future.done():
  1089. raise Exception("Return value already set. Application.exit() failed.")
  1090. self.exit_style = style
  1091. if exception is not None:
  1092. self.future.set_exception(exception)
  1093. else:
  1094. self.future.set_result(cast(_AppResult, result))
  1095. def _request_absolute_cursor_position(self) -> None:
  1096. """
  1097. Send CPR request.
  1098. """
  1099. # Note: only do this if the input queue is not empty, and a return
  1100. # value has not been set. Otherwise, we won't be able to read the
  1101. # response anyway.
  1102. if not self.key_processor.input_queue and not self.is_done:
  1103. self.renderer.request_absolute_cursor_position()
  1104. async def run_system_command(
  1105. self,
  1106. command: str,
  1107. wait_for_enter: bool = True,
  1108. display_before_text: AnyFormattedText = "",
  1109. wait_text: str = "Press ENTER to continue...",
  1110. ) -> None:
  1111. """
  1112. Run system command (While hiding the prompt. When finished, all the
  1113. output will scroll above the prompt.)
  1114. :param command: Shell command to be executed.
  1115. :param wait_for_enter: FWait for the user to press enter, when the
  1116. command is finished.
  1117. :param display_before_text: If given, text to be displayed before the
  1118. command executes.
  1119. :return: A `Future` object.
  1120. """
  1121. async with in_terminal():
  1122. # Try to use the same input/output file descriptors as the one,
  1123. # used to run this application.
  1124. try:
  1125. input_fd = self.input.fileno()
  1126. except AttributeError:
  1127. input_fd = sys.stdin.fileno()
  1128. try:
  1129. output_fd = self.output.fileno()
  1130. except AttributeError:
  1131. output_fd = sys.stdout.fileno()
  1132. # Run sub process.
  1133. def run_command() -> None:
  1134. self.print_text(display_before_text)
  1135. p = Popen(command, shell=True, stdin=input_fd, stdout=output_fd)
  1136. p.wait()
  1137. await run_in_executor_with_context(run_command)
  1138. # Wait for the user to press enter.
  1139. if wait_for_enter:
  1140. await _do_wait_for_enter(wait_text)
  1141. def suspend_to_background(self, suspend_group: bool = True) -> None:
  1142. """
  1143. (Not thread safe -- to be called from inside the key bindings.)
  1144. Suspend process.
  1145. :param suspend_group: When true, suspend the whole process group.
  1146. (This is the default, and probably what you want.)
  1147. """
  1148. # Only suspend when the operating system supports it.
  1149. # (Not on Windows.)
  1150. if _SIGTSTP is not None:
  1151. def run() -> None:
  1152. signal = cast(int, _SIGTSTP)
  1153. # Send `SIGTSTP` to own process.
  1154. # This will cause it to suspend.
  1155. # Usually we want the whole process group to be suspended. This
  1156. # handles the case when input is piped from another process.
  1157. if suspend_group:
  1158. os.kill(0, signal)
  1159. else:
  1160. os.kill(os.getpid(), signal)
  1161. run_in_terminal(run)
  1162. def print_text(
  1163. self, text: AnyFormattedText, style: BaseStyle | None = None
  1164. ) -> None:
  1165. """
  1166. Print a list of (style_str, text) tuples to the output.
  1167. (When the UI is running, this method has to be called through
  1168. `run_in_terminal`, otherwise it will destroy the UI.)
  1169. :param text: List of ``(style_str, text)`` tuples.
  1170. :param style: Style class to use. Defaults to the active style in the CLI.
  1171. """
  1172. print_formatted_text(
  1173. output=self.output,
  1174. formatted_text=text,
  1175. style=style or self._merged_style,
  1176. color_depth=self.color_depth,
  1177. style_transformation=self.style_transformation,
  1178. )
  1179. @property
  1180. def is_running(self) -> bool:
  1181. "`True` when the application is currently active/running."
  1182. return self._is_running
  1183. @property
  1184. def is_done(self) -> bool:
  1185. if self.future:
  1186. return self.future.done()
  1187. return False
  1188. def get_used_style_strings(self) -> list[str]:
  1189. """
  1190. Return a list of used style strings. This is helpful for debugging, and
  1191. for writing a new `Style`.
  1192. """
  1193. attrs_for_style = self.renderer._attrs_for_style
  1194. if attrs_for_style:
  1195. return sorted(
  1196. re.sub(r"\s+", " ", style_str).strip()
  1197. for style_str in attrs_for_style.keys()
  1198. )
  1199. return []
  1200. class _CombinedRegistry(KeyBindingsBase):
  1201. """
  1202. The `KeyBindings` of key bindings for a `Application`.
  1203. This merges the global key bindings with the one of the current user
  1204. control.
  1205. """
  1206. def __init__(self, app: Application[_AppResult]) -> None:
  1207. self.app = app
  1208. self._cache: SimpleCache[
  1209. tuple[Window, frozenset[UIControl]], KeyBindingsBase
  1210. ] = SimpleCache()
  1211. @property
  1212. def _version(self) -> Hashable:
  1213. """Not needed - this object is not going to be wrapped in another
  1214. KeyBindings object."""
  1215. raise NotImplementedError
  1216. @property
  1217. def bindings(self) -> list[Binding]:
  1218. """Not needed - this object is not going to be wrapped in another
  1219. KeyBindings object."""
  1220. raise NotImplementedError
  1221. def _create_key_bindings(
  1222. self, current_window: Window, other_controls: list[UIControl]
  1223. ) -> KeyBindingsBase:
  1224. """
  1225. Create a `KeyBindings` object that merges the `KeyBindings` from the
  1226. `UIControl` with all the parent controls and the global key bindings.
  1227. """
  1228. key_bindings = []
  1229. collected_containers = set()
  1230. # Collect key bindings from currently focused control and all parent
  1231. # controls. Don't include key bindings of container parent controls.
  1232. container: Container = current_window
  1233. while True:
  1234. collected_containers.add(container)
  1235. kb = container.get_key_bindings()
  1236. if kb is not None:
  1237. key_bindings.append(kb)
  1238. if container.is_modal():
  1239. break
  1240. parent = self.app.layout.get_parent(container)
  1241. if parent is None:
  1242. break
  1243. else:
  1244. container = parent
  1245. # Include global bindings (starting at the top-model container).
  1246. for c in walk(container):
  1247. if c not in collected_containers:
  1248. kb = c.get_key_bindings()
  1249. if kb is not None:
  1250. key_bindings.append(GlobalOnlyKeyBindings(kb))
  1251. # Add App key bindings
  1252. if self.app.key_bindings:
  1253. key_bindings.append(self.app.key_bindings)
  1254. # Add mouse bindings.
  1255. key_bindings.append(
  1256. ConditionalKeyBindings(
  1257. self.app._page_navigation_bindings,
  1258. self.app.enable_page_navigation_bindings,
  1259. )
  1260. )
  1261. key_bindings.append(self.app._default_bindings)
  1262. # Reverse this list. The current control's key bindings should come
  1263. # last. They need priority.
  1264. key_bindings = key_bindings[::-1]
  1265. return merge_key_bindings(key_bindings)
  1266. @property
  1267. def _key_bindings(self) -> KeyBindingsBase:
  1268. current_window = self.app.layout.current_window
  1269. other_controls = list(self.app.layout.find_all_controls())
  1270. key = current_window, frozenset(other_controls)
  1271. return self._cache.get(
  1272. key, lambda: self._create_key_bindings(current_window, other_controls)
  1273. )
  1274. def get_bindings_for_keys(self, keys: KeysTuple) -> list[Binding]:
  1275. return self._key_bindings.get_bindings_for_keys(keys)
  1276. def get_bindings_starting_with_keys(self, keys: KeysTuple) -> list[Binding]:
  1277. return self._key_bindings.get_bindings_starting_with_keys(keys)
  1278. async def _do_wait_for_enter(wait_text: AnyFormattedText) -> None:
  1279. """
  1280. Create a sub application to wait for the enter key press.
  1281. This has two advantages over using 'input'/'raw_input':
  1282. - This will share the same input/output I/O.
  1283. - This doesn't block the event loop.
  1284. """
  1285. from prompt_toolkit.shortcuts import PromptSession
  1286. key_bindings = KeyBindings()
  1287. @key_bindings.add("enter")
  1288. def _ok(event: E) -> None:
  1289. event.app.exit()
  1290. @key_bindings.add(Keys.Any)
  1291. def _ignore(event: E) -> None:
  1292. "Disallow typing."
  1293. pass
  1294. session: PromptSession[None] = PromptSession(
  1295. message=wait_text, key_bindings=key_bindings
  1296. )
  1297. try:
  1298. await session.app.run_async()
  1299. except KeyboardInterrupt:
  1300. pass # Control-c pressed. Don't propagate this error.
  1301. @contextmanager
  1302. def attach_winch_signal_handler(
  1303. handler: Callable[[], None],
  1304. ) -> Generator[None, None, None]:
  1305. """
  1306. Attach the given callback as a WINCH signal handler within the context
  1307. manager. Restore the original signal handler when done.
  1308. The `Application.run` method will register SIGWINCH, so that it will
  1309. properly repaint when the terminal window resizes. However, using
  1310. `run_in_terminal`, we can temporarily send an application to the
  1311. background, and run an other app in between, which will then overwrite the
  1312. SIGWINCH. This is why it's important to restore the handler when the app
  1313. terminates.
  1314. """
  1315. # The tricky part here is that signals are registered in the Unix event
  1316. # loop with a wakeup fd, but another application could have registered
  1317. # signals using signal.signal directly. For now, the implementation is
  1318. # hard-coded for the `asyncio.unix_events._UnixSelectorEventLoop`.
  1319. # No WINCH? Then don't do anything.
  1320. sigwinch = getattr(signal, "SIGWINCH", None)
  1321. if sigwinch is None or not in_main_thread():
  1322. yield
  1323. return
  1324. # Keep track of the previous handler.
  1325. # (Only UnixSelectorEventloop has `_signal_handlers`.)
  1326. loop = get_running_loop()
  1327. previous_winch_handler = getattr(loop, "_signal_handlers", {}).get(sigwinch)
  1328. try:
  1329. loop.add_signal_handler(sigwinch, handler)
  1330. yield
  1331. finally:
  1332. # Restore the previous signal handler.
  1333. loop.remove_signal_handler(sigwinch)
  1334. if previous_winch_handler is not None:
  1335. loop.add_signal_handler(
  1336. sigwinch,
  1337. previous_winch_handler._callback,
  1338. *previous_winch_handler._args,
  1339. )
  1340. @contextmanager
  1341. def _restore_sigint_from_ctypes() -> Generator[None, None, None]:
  1342. # The following functions are part of the stable ABI since python 3.2
  1343. # See: https://docs.python.org/3/c-api/sys.html#c.PyOS_getsig
  1344. # Inline import: these are not available on Pypy.
  1345. try:
  1346. from ctypes import c_int, c_void_p, pythonapi
  1347. except ImportError:
  1348. # Any of the above imports don't exist? Don't do anything here.
  1349. yield
  1350. return
  1351. # PyOS_sighandler_t PyOS_getsig(int i)
  1352. pythonapi.PyOS_getsig.restype = c_void_p
  1353. pythonapi.PyOS_getsig.argtypes = (c_int,)
  1354. # PyOS_sighandler_t PyOS_setsig(int i, PyOS_sighandler_t h)
  1355. pythonapi.PyOS_setsig.restype = c_void_p
  1356. pythonapi.PyOS_setsig.argtypes = (
  1357. c_int,
  1358. c_void_p,
  1359. )
  1360. sigint = signal.getsignal(signal.SIGINT)
  1361. sigint_os = pythonapi.PyOS_getsig(signal.SIGINT)
  1362. try:
  1363. yield
  1364. finally:
  1365. if sigint is not None:
  1366. signal.signal(signal.SIGINT, sigint)
  1367. pythonapi.PyOS_setsig(signal.SIGINT, sigint_os)