base.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  1. """
  2. Collection of reusable components for building full screen applications.
  3. All of these widgets implement the ``__pt_container__`` method, which makes
  4. them usable in any situation where we are expecting a `prompt_toolkit`
  5. container object.
  6. .. warning::
  7. At this point, the API for these widgets is considered unstable, and can
  8. potentially change between minor releases (we try not too, but no
  9. guarantees are made yet). The public API in
  10. `prompt_toolkit.shortcuts.dialogs` on the other hand is considered stable.
  11. """
  12. from __future__ import annotations
  13. from functools import partial
  14. from typing import Callable, Generic, Sequence, TypeVar
  15. from prompt_toolkit.application.current import get_app
  16. from prompt_toolkit.auto_suggest import AutoSuggest, DynamicAutoSuggest
  17. from prompt_toolkit.buffer import Buffer, BufferAcceptHandler
  18. from prompt_toolkit.completion import Completer, DynamicCompleter
  19. from prompt_toolkit.document import Document
  20. from prompt_toolkit.filters import (
  21. Condition,
  22. FilterOrBool,
  23. has_focus,
  24. is_done,
  25. is_true,
  26. to_filter,
  27. )
  28. from prompt_toolkit.formatted_text import (
  29. AnyFormattedText,
  30. StyleAndTextTuples,
  31. Template,
  32. to_formatted_text,
  33. )
  34. from prompt_toolkit.formatted_text.utils import fragment_list_to_text
  35. from prompt_toolkit.history import History
  36. from prompt_toolkit.key_binding.key_bindings import KeyBindings
  37. from prompt_toolkit.key_binding.key_processor import KeyPressEvent
  38. from prompt_toolkit.keys import Keys
  39. from prompt_toolkit.layout.containers import (
  40. AnyContainer,
  41. ConditionalContainer,
  42. Container,
  43. DynamicContainer,
  44. Float,
  45. FloatContainer,
  46. HSplit,
  47. VSplit,
  48. Window,
  49. WindowAlign,
  50. )
  51. from prompt_toolkit.layout.controls import (
  52. BufferControl,
  53. FormattedTextControl,
  54. GetLinePrefixCallable,
  55. )
  56. from prompt_toolkit.layout.dimension import AnyDimension
  57. from prompt_toolkit.layout.dimension import Dimension as D
  58. from prompt_toolkit.layout.margins import (
  59. ConditionalMargin,
  60. NumberedMargin,
  61. ScrollbarMargin,
  62. )
  63. from prompt_toolkit.layout.processors import (
  64. AppendAutoSuggestion,
  65. BeforeInput,
  66. ConditionalProcessor,
  67. PasswordProcessor,
  68. Processor,
  69. )
  70. from prompt_toolkit.lexers import DynamicLexer, Lexer
  71. from prompt_toolkit.mouse_events import MouseEvent, MouseEventType
  72. from prompt_toolkit.utils import get_cwidth
  73. from prompt_toolkit.validation import DynamicValidator, Validator
  74. from .toolbars import SearchToolbar
  75. __all__ = [
  76. "TextArea",
  77. "Label",
  78. "Button",
  79. "Frame",
  80. "Shadow",
  81. "Box",
  82. "VerticalLine",
  83. "HorizontalLine",
  84. "RadioList",
  85. "CheckboxList",
  86. "Checkbox", # backward compatibility
  87. "ProgressBar",
  88. ]
  89. E = KeyPressEvent
  90. class Border:
  91. "Box drawing characters. (Thin)"
  92. HORIZONTAL = "\u2500"
  93. VERTICAL = "\u2502"
  94. TOP_LEFT = "\u250c"
  95. TOP_RIGHT = "\u2510"
  96. BOTTOM_LEFT = "\u2514"
  97. BOTTOM_RIGHT = "\u2518"
  98. class TextArea:
  99. """
  100. A simple input field.
  101. This is a higher level abstraction on top of several other classes with
  102. sane defaults.
  103. This widget does have the most common options, but it does not intend to
  104. cover every single use case. For more configurations options, you can
  105. always build a text area manually, using a
  106. :class:`~prompt_toolkit.buffer.Buffer`,
  107. :class:`~prompt_toolkit.layout.BufferControl` and
  108. :class:`~prompt_toolkit.layout.Window`.
  109. Buffer attributes:
  110. :param text: The initial text.
  111. :param multiline: If True, allow multiline input.
  112. :param completer: :class:`~prompt_toolkit.completion.Completer` instance
  113. for auto completion.
  114. :param complete_while_typing: Boolean.
  115. :param accept_handler: Called when `Enter` is pressed (This should be a
  116. callable that takes a buffer as input).
  117. :param history: :class:`~prompt_toolkit.history.History` instance.
  118. :param auto_suggest: :class:`~prompt_toolkit.auto_suggest.AutoSuggest`
  119. instance for input suggestions.
  120. BufferControl attributes:
  121. :param password: When `True`, display using asterisks.
  122. :param focusable: When `True`, allow this widget to receive the focus.
  123. :param focus_on_click: When `True`, focus after mouse click.
  124. :param input_processors: `None` or a list of
  125. :class:`~prompt_toolkit.layout.Processor` objects.
  126. :param validator: `None` or a :class:`~prompt_toolkit.validation.Validator`
  127. object.
  128. Window attributes:
  129. :param lexer: :class:`~prompt_toolkit.lexers.Lexer` instance for syntax
  130. highlighting.
  131. :param wrap_lines: When `True`, don't scroll horizontally, but wrap lines.
  132. :param width: Window width. (:class:`~prompt_toolkit.layout.Dimension` object.)
  133. :param height: Window height. (:class:`~prompt_toolkit.layout.Dimension` object.)
  134. :param scrollbar: When `True`, display a scroll bar.
  135. :param style: A style string.
  136. :param dont_extend_width: When `True`, don't take up more width then the
  137. preferred width reported by the control.
  138. :param dont_extend_height: When `True`, don't take up more width then the
  139. preferred height reported by the control.
  140. :param get_line_prefix: None or a callable that returns formatted text to
  141. be inserted before a line. It takes a line number (int) and a
  142. wrap_count and returns formatted text. This can be used for
  143. implementation of line continuations, things like Vim "breakindent" and
  144. so on.
  145. Other attributes:
  146. :param search_field: An optional `SearchToolbar` object.
  147. """
  148. def __init__(
  149. self,
  150. text: str = "",
  151. multiline: FilterOrBool = True,
  152. password: FilterOrBool = False,
  153. lexer: Lexer | None = None,
  154. auto_suggest: AutoSuggest | None = None,
  155. completer: Completer | None = None,
  156. complete_while_typing: FilterOrBool = True,
  157. validator: Validator | None = None,
  158. accept_handler: BufferAcceptHandler | None = None,
  159. history: History | None = None,
  160. focusable: FilterOrBool = True,
  161. focus_on_click: FilterOrBool = False,
  162. wrap_lines: FilterOrBool = True,
  163. read_only: FilterOrBool = False,
  164. width: AnyDimension = None,
  165. height: AnyDimension = None,
  166. dont_extend_height: FilterOrBool = False,
  167. dont_extend_width: FilterOrBool = False,
  168. line_numbers: bool = False,
  169. get_line_prefix: GetLinePrefixCallable | None = None,
  170. scrollbar: bool = False,
  171. style: str = "",
  172. search_field: SearchToolbar | None = None,
  173. preview_search: FilterOrBool = True,
  174. prompt: AnyFormattedText = "",
  175. input_processors: list[Processor] | None = None,
  176. name: str = "",
  177. ) -> None:
  178. if search_field is None:
  179. search_control = None
  180. elif isinstance(search_field, SearchToolbar):
  181. search_control = search_field.control
  182. if input_processors is None:
  183. input_processors = []
  184. # Writeable attributes.
  185. self.completer = completer
  186. self.complete_while_typing = complete_while_typing
  187. self.lexer = lexer
  188. self.auto_suggest = auto_suggest
  189. self.read_only = read_only
  190. self.wrap_lines = wrap_lines
  191. self.validator = validator
  192. self.buffer = Buffer(
  193. document=Document(text, 0),
  194. multiline=multiline,
  195. read_only=Condition(lambda: is_true(self.read_only)),
  196. completer=DynamicCompleter(lambda: self.completer),
  197. complete_while_typing=Condition(
  198. lambda: is_true(self.complete_while_typing)
  199. ),
  200. validator=DynamicValidator(lambda: self.validator),
  201. auto_suggest=DynamicAutoSuggest(lambda: self.auto_suggest),
  202. accept_handler=accept_handler,
  203. history=history,
  204. name=name,
  205. )
  206. self.control = BufferControl(
  207. buffer=self.buffer,
  208. lexer=DynamicLexer(lambda: self.lexer),
  209. input_processors=[
  210. ConditionalProcessor(
  211. AppendAutoSuggestion(), has_focus(self.buffer) & ~is_done
  212. ),
  213. ConditionalProcessor(
  214. processor=PasswordProcessor(), filter=to_filter(password)
  215. ),
  216. BeforeInput(prompt, style="class:text-area.prompt"),
  217. ]
  218. + input_processors,
  219. search_buffer_control=search_control,
  220. preview_search=preview_search,
  221. focusable=focusable,
  222. focus_on_click=focus_on_click,
  223. )
  224. if multiline:
  225. if scrollbar:
  226. right_margins = [ScrollbarMargin(display_arrows=True)]
  227. else:
  228. right_margins = []
  229. if line_numbers:
  230. left_margins = [NumberedMargin()]
  231. else:
  232. left_margins = []
  233. else:
  234. height = D.exact(1)
  235. left_margins = []
  236. right_margins = []
  237. style = "class:text-area " + style
  238. # If no height was given, guarantee height of at least 1.
  239. if height is None:
  240. height = D(min=1)
  241. self.window = Window(
  242. height=height,
  243. width=width,
  244. dont_extend_height=dont_extend_height,
  245. dont_extend_width=dont_extend_width,
  246. content=self.control,
  247. style=style,
  248. wrap_lines=Condition(lambda: is_true(self.wrap_lines)),
  249. left_margins=left_margins,
  250. right_margins=right_margins,
  251. get_line_prefix=get_line_prefix,
  252. )
  253. @property
  254. def text(self) -> str:
  255. """
  256. The `Buffer` text.
  257. """
  258. return self.buffer.text
  259. @text.setter
  260. def text(self, value: str) -> None:
  261. self.document = Document(value, 0)
  262. @property
  263. def document(self) -> Document:
  264. """
  265. The `Buffer` document (text + cursor position).
  266. """
  267. return self.buffer.document
  268. @document.setter
  269. def document(self, value: Document) -> None:
  270. self.buffer.set_document(value, bypass_readonly=True)
  271. @property
  272. def accept_handler(self) -> BufferAcceptHandler | None:
  273. """
  274. The accept handler. Called when the user accepts the input.
  275. """
  276. return self.buffer.accept_handler
  277. @accept_handler.setter
  278. def accept_handler(self, value: BufferAcceptHandler) -> None:
  279. self.buffer.accept_handler = value
  280. def __pt_container__(self) -> Container:
  281. return self.window
  282. class Label:
  283. """
  284. Widget that displays the given text. It is not editable or focusable.
  285. :param text: Text to display. Can be multiline. All value types accepted by
  286. :class:`prompt_toolkit.layout.FormattedTextControl` are allowed,
  287. including a callable.
  288. :param style: A style string.
  289. :param width: When given, use this width, rather than calculating it from
  290. the text size.
  291. :param dont_extend_width: When `True`, don't take up more width than
  292. preferred, i.e. the length of the longest line of
  293. the text, or value of `width` parameter, if
  294. given. `True` by default
  295. :param dont_extend_height: When `True`, don't take up more width than the
  296. preferred height, i.e. the number of lines of
  297. the text. `False` by default.
  298. """
  299. def __init__(
  300. self,
  301. text: AnyFormattedText,
  302. style: str = "",
  303. width: AnyDimension = None,
  304. dont_extend_height: bool = True,
  305. dont_extend_width: bool = False,
  306. align: WindowAlign | Callable[[], WindowAlign] = WindowAlign.LEFT,
  307. # There is no cursor navigation in a label, so it makes sense to always
  308. # wrap lines by default.
  309. wrap_lines: FilterOrBool = True,
  310. ) -> None:
  311. self.text = text
  312. def get_width() -> AnyDimension:
  313. if width is None:
  314. text_fragments = to_formatted_text(self.text)
  315. text = fragment_list_to_text(text_fragments)
  316. if text:
  317. longest_line = max(get_cwidth(line) for line in text.splitlines())
  318. else:
  319. return D(preferred=0)
  320. return D(preferred=longest_line)
  321. else:
  322. return width
  323. self.formatted_text_control = FormattedTextControl(text=lambda: self.text)
  324. self.window = Window(
  325. content=self.formatted_text_control,
  326. width=get_width,
  327. height=D(min=1),
  328. style="class:label " + style,
  329. dont_extend_height=dont_extend_height,
  330. dont_extend_width=dont_extend_width,
  331. align=align,
  332. wrap_lines=wrap_lines,
  333. )
  334. def __pt_container__(self) -> Container:
  335. return self.window
  336. class Button:
  337. """
  338. Clickable button.
  339. :param text: The caption for the button.
  340. :param handler: `None` or callable. Called when the button is clicked. No
  341. parameters are passed to this callable. Use for instance Python's
  342. `functools.partial` to pass parameters to this callable if needed.
  343. :param width: Width of the button.
  344. """
  345. def __init__(
  346. self,
  347. text: str,
  348. handler: Callable[[], None] | None = None,
  349. width: int = 12,
  350. left_symbol: str = "<",
  351. right_symbol: str = ">",
  352. ) -> None:
  353. self.text = text
  354. self.left_symbol = left_symbol
  355. self.right_symbol = right_symbol
  356. self.handler = handler
  357. self.width = width
  358. self.control = FormattedTextControl(
  359. self._get_text_fragments,
  360. key_bindings=self._get_key_bindings(),
  361. focusable=True,
  362. )
  363. def get_style() -> str:
  364. if get_app().layout.has_focus(self):
  365. return "class:button.focused"
  366. else:
  367. return "class:button"
  368. # Note: `dont_extend_width` is False, because we want to allow buttons
  369. # to take more space if the parent container provides more space.
  370. # Otherwise, we will also truncate the text.
  371. # Probably we need a better way here to adjust to width of the
  372. # button to the text.
  373. self.window = Window(
  374. self.control,
  375. align=WindowAlign.CENTER,
  376. height=1,
  377. width=width,
  378. style=get_style,
  379. dont_extend_width=False,
  380. dont_extend_height=True,
  381. )
  382. def _get_text_fragments(self) -> StyleAndTextTuples:
  383. width = (
  384. self.width
  385. - (get_cwidth(self.left_symbol) + get_cwidth(self.right_symbol))
  386. + (len(self.text) - get_cwidth(self.text))
  387. )
  388. text = (f"{{:^{max(0, width)}}}").format(self.text)
  389. def handler(mouse_event: MouseEvent) -> None:
  390. if (
  391. self.handler is not None
  392. and mouse_event.event_type == MouseEventType.MOUSE_UP
  393. ):
  394. self.handler()
  395. return [
  396. ("class:button.arrow", self.left_symbol, handler),
  397. ("[SetCursorPosition]", ""),
  398. ("class:button.text", text, handler),
  399. ("class:button.arrow", self.right_symbol, handler),
  400. ]
  401. def _get_key_bindings(self) -> KeyBindings:
  402. "Key bindings for the Button."
  403. kb = KeyBindings()
  404. @kb.add(" ")
  405. @kb.add("enter")
  406. def _(event: E) -> None:
  407. if self.handler is not None:
  408. self.handler()
  409. return kb
  410. def __pt_container__(self) -> Container:
  411. return self.window
  412. class Frame:
  413. """
  414. Draw a border around any container, optionally with a title text.
  415. Changing the title and body of the frame is possible at runtime by
  416. assigning to the `body` and `title` attributes of this class.
  417. :param body: Another container object.
  418. :param title: Text to be displayed in the top of the frame (can be formatted text).
  419. :param style: Style string to be applied to this widget.
  420. """
  421. def __init__(
  422. self,
  423. body: AnyContainer,
  424. title: AnyFormattedText = "",
  425. style: str = "",
  426. width: AnyDimension = None,
  427. height: AnyDimension = None,
  428. key_bindings: KeyBindings | None = None,
  429. modal: bool = False,
  430. ) -> None:
  431. self.title = title
  432. self.body = body
  433. fill = partial(Window, style="class:frame.border")
  434. style = "class:frame " + style
  435. top_row_with_title = VSplit(
  436. [
  437. fill(width=1, height=1, char=Border.TOP_LEFT),
  438. fill(char=Border.HORIZONTAL),
  439. fill(width=1, height=1, char="|"),
  440. # Notice: we use `Template` here, because `self.title` can be an
  441. # `HTML` object for instance.
  442. Label(
  443. lambda: Template(" {} ").format(self.title),
  444. style="class:frame.label",
  445. dont_extend_width=True,
  446. ),
  447. fill(width=1, height=1, char="|"),
  448. fill(char=Border.HORIZONTAL),
  449. fill(width=1, height=1, char=Border.TOP_RIGHT),
  450. ],
  451. height=1,
  452. )
  453. top_row_without_title = VSplit(
  454. [
  455. fill(width=1, height=1, char=Border.TOP_LEFT),
  456. fill(char=Border.HORIZONTAL),
  457. fill(width=1, height=1, char=Border.TOP_RIGHT),
  458. ],
  459. height=1,
  460. )
  461. @Condition
  462. def has_title() -> bool:
  463. return bool(self.title)
  464. self.container = HSplit(
  465. [
  466. ConditionalContainer(
  467. content=top_row_with_title,
  468. filter=has_title,
  469. alternative_content=top_row_without_title,
  470. ),
  471. VSplit(
  472. [
  473. fill(width=1, char=Border.VERTICAL),
  474. DynamicContainer(lambda: self.body),
  475. fill(width=1, char=Border.VERTICAL),
  476. # Padding is required to make sure that if the content is
  477. # too small, the right frame border is still aligned.
  478. ],
  479. padding=0,
  480. ),
  481. VSplit(
  482. [
  483. fill(width=1, height=1, char=Border.BOTTOM_LEFT),
  484. fill(char=Border.HORIZONTAL),
  485. fill(width=1, height=1, char=Border.BOTTOM_RIGHT),
  486. ],
  487. # specifying height here will increase the rendering speed.
  488. height=1,
  489. ),
  490. ],
  491. width=width,
  492. height=height,
  493. style=style,
  494. key_bindings=key_bindings,
  495. modal=modal,
  496. )
  497. def __pt_container__(self) -> Container:
  498. return self.container
  499. class Shadow:
  500. """
  501. Draw a shadow underneath/behind this container.
  502. (This applies `class:shadow` the the cells under the shadow. The Style
  503. should define the colors for the shadow.)
  504. :param body: Another container object.
  505. """
  506. def __init__(self, body: AnyContainer) -> None:
  507. self.container = FloatContainer(
  508. content=body,
  509. floats=[
  510. Float(
  511. bottom=-1,
  512. height=1,
  513. left=1,
  514. right=-1,
  515. transparent=True,
  516. content=Window(style="class:shadow"),
  517. ),
  518. Float(
  519. bottom=-1,
  520. top=1,
  521. width=1,
  522. right=-1,
  523. transparent=True,
  524. content=Window(style="class:shadow"),
  525. ),
  526. ],
  527. )
  528. def __pt_container__(self) -> Container:
  529. return self.container
  530. class Box:
  531. """
  532. Add padding around a container.
  533. This also makes sure that the parent can provide more space than required by
  534. the child. This is very useful when wrapping a small element with a fixed
  535. size into a ``VSplit`` or ``HSplit`` object. The ``HSplit`` and ``VSplit``
  536. try to make sure to adapt respectively the width and height, possibly
  537. shrinking other elements. Wrapping something in a ``Box`` makes it flexible.
  538. :param body: Another container object.
  539. :param padding: The margin to be used around the body. This can be
  540. overridden by `padding_left`, padding_right`, `padding_top` and
  541. `padding_bottom`.
  542. :param style: A style string.
  543. :param char: Character to be used for filling the space around the body.
  544. (This is supposed to be a character with a terminal width of 1.)
  545. """
  546. def __init__(
  547. self,
  548. body: AnyContainer,
  549. padding: AnyDimension = None,
  550. padding_left: AnyDimension = None,
  551. padding_right: AnyDimension = None,
  552. padding_top: AnyDimension = None,
  553. padding_bottom: AnyDimension = None,
  554. width: AnyDimension = None,
  555. height: AnyDimension = None,
  556. style: str = "",
  557. char: None | str | Callable[[], str] = None,
  558. modal: bool = False,
  559. key_bindings: KeyBindings | None = None,
  560. ) -> None:
  561. self.padding = padding
  562. self.padding_left = padding_left
  563. self.padding_right = padding_right
  564. self.padding_top = padding_top
  565. self.padding_bottom = padding_bottom
  566. self.body = body
  567. def left() -> AnyDimension:
  568. if self.padding_left is None:
  569. return self.padding
  570. return self.padding_left
  571. def right() -> AnyDimension:
  572. if self.padding_right is None:
  573. return self.padding
  574. return self.padding_right
  575. def top() -> AnyDimension:
  576. if self.padding_top is None:
  577. return self.padding
  578. return self.padding_top
  579. def bottom() -> AnyDimension:
  580. if self.padding_bottom is None:
  581. return self.padding
  582. return self.padding_bottom
  583. self.container = HSplit(
  584. [
  585. Window(height=top, char=char),
  586. VSplit(
  587. [
  588. Window(width=left, char=char),
  589. body,
  590. Window(width=right, char=char),
  591. ]
  592. ),
  593. Window(height=bottom, char=char),
  594. ],
  595. width=width,
  596. height=height,
  597. style=style,
  598. modal=modal,
  599. key_bindings=None,
  600. )
  601. def __pt_container__(self) -> Container:
  602. return self.container
  603. _T = TypeVar("_T")
  604. class _DialogList(Generic[_T]):
  605. """
  606. Common code for `RadioList` and `CheckboxList`.
  607. """
  608. def __init__(
  609. self,
  610. values: Sequence[tuple[_T, AnyFormattedText]],
  611. default_values: Sequence[_T] | None = None,
  612. select_on_focus: bool = False,
  613. open_character: str = "",
  614. select_character: str = "*",
  615. close_character: str = "",
  616. container_style: str = "",
  617. default_style: str = "",
  618. number_style: str = "",
  619. selected_style: str = "",
  620. checked_style: str = "",
  621. multiple_selection: bool = False,
  622. show_scrollbar: bool = True,
  623. show_cursor: bool = True,
  624. show_numbers: bool = False,
  625. ) -> None:
  626. assert len(values) > 0
  627. default_values = default_values or []
  628. self.values = values
  629. self.show_numbers = show_numbers
  630. self.open_character = open_character
  631. self.select_character = select_character
  632. self.close_character = close_character
  633. self.container_style = container_style
  634. self.default_style = default_style
  635. self.number_style = number_style
  636. self.selected_style = selected_style
  637. self.checked_style = checked_style
  638. self.multiple_selection = multiple_selection
  639. self.show_scrollbar = show_scrollbar
  640. # current_values will be used in multiple_selection,
  641. # current_value will be used otherwise.
  642. keys: list[_T] = [value for (value, _) in values]
  643. self.current_values: list[_T] = [
  644. value for value in default_values if value in keys
  645. ]
  646. self.current_value: _T = (
  647. default_values[0]
  648. if len(default_values) and default_values[0] in keys
  649. else values[0][0]
  650. )
  651. # Cursor index: take first selected item or first item otherwise.
  652. if len(self.current_values) > 0:
  653. self._selected_index = keys.index(self.current_values[0])
  654. else:
  655. self._selected_index = 0
  656. # Key bindings.
  657. kb = KeyBindings()
  658. @kb.add("up")
  659. @kb.add("k") # Vi-like.
  660. def _up(event: E) -> None:
  661. self._selected_index = max(0, self._selected_index - 1)
  662. if select_on_focus:
  663. self._handle_enter()
  664. @kb.add("down")
  665. @kb.add("j") # Vi-like.
  666. def _down(event: E) -> None:
  667. self._selected_index = min(len(self.values) - 1, self._selected_index + 1)
  668. if select_on_focus:
  669. self._handle_enter()
  670. @kb.add("pageup")
  671. def _pageup(event: E) -> None:
  672. w = event.app.layout.current_window
  673. if w.render_info:
  674. self._selected_index = max(
  675. 0, self._selected_index - len(w.render_info.displayed_lines)
  676. )
  677. @kb.add("pagedown")
  678. def _pagedown(event: E) -> None:
  679. w = event.app.layout.current_window
  680. if w.render_info:
  681. self._selected_index = min(
  682. len(self.values) - 1,
  683. self._selected_index + len(w.render_info.displayed_lines),
  684. )
  685. @kb.add("enter")
  686. @kb.add(" ")
  687. def _click(event: E) -> None:
  688. self._handle_enter()
  689. @kb.add(Keys.Any)
  690. def _find(event: E) -> None:
  691. # We first check values after the selected value, then all values.
  692. values = list(self.values)
  693. for value in values[self._selected_index + 1 :] + values:
  694. text = fragment_list_to_text(to_formatted_text(value[1])).lower()
  695. if text.startswith(event.data.lower()):
  696. self._selected_index = self.values.index(value)
  697. return
  698. numbers_visible = Condition(lambda: self.show_numbers)
  699. for i in range(1, 10):
  700. @kb.add(str(i), filter=numbers_visible)
  701. def _select_i(event: E, index: int = i) -> None:
  702. self._selected_index = min(len(self.values) - 1, index - 1)
  703. if select_on_focus:
  704. self._handle_enter()
  705. # Control and window.
  706. self.control = FormattedTextControl(
  707. self._get_text_fragments,
  708. key_bindings=kb,
  709. focusable=True,
  710. show_cursor=show_cursor,
  711. )
  712. self.window = Window(
  713. content=self.control,
  714. style=self.container_style,
  715. right_margins=[
  716. ConditionalMargin(
  717. margin=ScrollbarMargin(display_arrows=True),
  718. filter=Condition(lambda: self.show_scrollbar),
  719. ),
  720. ],
  721. dont_extend_height=True,
  722. )
  723. def _handle_enter(self) -> None:
  724. if self.multiple_selection:
  725. val = self.values[self._selected_index][0]
  726. if val in self.current_values:
  727. self.current_values.remove(val)
  728. else:
  729. self.current_values.append(val)
  730. else:
  731. self.current_value = self.values[self._selected_index][0]
  732. def _get_text_fragments(self) -> StyleAndTextTuples:
  733. def mouse_handler(mouse_event: MouseEvent) -> None:
  734. """
  735. Set `_selected_index` and `current_value` according to the y
  736. position of the mouse click event.
  737. """
  738. if mouse_event.event_type == MouseEventType.MOUSE_UP:
  739. self._selected_index = mouse_event.position.y
  740. self._handle_enter()
  741. result: StyleAndTextTuples = []
  742. for i, value in enumerate(self.values):
  743. if self.multiple_selection:
  744. checked = value[0] in self.current_values
  745. else:
  746. checked = value[0] == self.current_value
  747. selected = i == self._selected_index
  748. style = ""
  749. if checked:
  750. style += " " + self.checked_style
  751. if selected:
  752. style += " " + self.selected_style
  753. result.append((style, self.open_character))
  754. if selected:
  755. result.append(("[SetCursorPosition]", ""))
  756. if checked:
  757. result.append((style, self.select_character))
  758. else:
  759. result.append((style, " "))
  760. result.append((style, self.close_character))
  761. result.append((f"{style} {self.default_style}", " "))
  762. if self.show_numbers:
  763. result.append((f"{style} {self.number_style}", f"{i + 1:2d}. "))
  764. result.extend(
  765. to_formatted_text(value[1], style=f"{style} {self.default_style}")
  766. )
  767. result.append(("", "\n"))
  768. # Add mouse handler to all fragments.
  769. for i in range(len(result)):
  770. result[i] = (result[i][0], result[i][1], mouse_handler)
  771. result.pop() # Remove last newline.
  772. return result
  773. def __pt_container__(self) -> Container:
  774. return self.window
  775. class RadioList(_DialogList[_T]):
  776. """
  777. List of radio buttons. Only one can be checked at the same time.
  778. :param values: List of (value, label) tuples.
  779. """
  780. def __init__(
  781. self,
  782. values: Sequence[tuple[_T, AnyFormattedText]],
  783. default: _T | None = None,
  784. show_numbers: bool = False,
  785. select_on_focus: bool = False,
  786. open_character: str = "(",
  787. select_character: str = "*",
  788. close_character: str = ")",
  789. container_style: str = "class:radio-list",
  790. default_style: str = "class:radio",
  791. selected_style: str = "class:radio-selected",
  792. checked_style: str = "class:radio-checked",
  793. number_style: str = "class:radio-number",
  794. multiple_selection: bool = False,
  795. show_cursor: bool = True,
  796. show_scrollbar: bool = True,
  797. ) -> None:
  798. if default is None:
  799. default_values = None
  800. else:
  801. default_values = [default]
  802. super().__init__(
  803. values,
  804. default_values=default_values,
  805. select_on_focus=select_on_focus,
  806. show_numbers=show_numbers,
  807. open_character=open_character,
  808. select_character=select_character,
  809. close_character=close_character,
  810. container_style=container_style,
  811. default_style=default_style,
  812. selected_style=selected_style,
  813. checked_style=checked_style,
  814. number_style=number_style,
  815. multiple_selection=False,
  816. show_cursor=show_cursor,
  817. show_scrollbar=show_scrollbar,
  818. )
  819. class CheckboxList(_DialogList[_T]):
  820. """
  821. List of checkbox buttons. Several can be checked at the same time.
  822. :param values: List of (value, label) tuples.
  823. """
  824. def __init__(
  825. self,
  826. values: Sequence[tuple[_T, AnyFormattedText]],
  827. default_values: Sequence[_T] | None = None,
  828. open_character: str = "[",
  829. select_character: str = "*",
  830. close_character: str = "]",
  831. container_style: str = "class:checkbox-list",
  832. default_style: str = "class:checkbox",
  833. selected_style: str = "class:checkbox-selected",
  834. checked_style: str = "class:checkbox-checked",
  835. ) -> None:
  836. super().__init__(
  837. values,
  838. default_values=default_values,
  839. open_character=open_character,
  840. select_character=select_character,
  841. close_character=close_character,
  842. container_style=container_style,
  843. default_style=default_style,
  844. selected_style=selected_style,
  845. checked_style=checked_style,
  846. multiple_selection=True,
  847. )
  848. class Checkbox(CheckboxList[str]):
  849. """Backward compatibility util: creates a 1-sized CheckboxList
  850. :param text: the text
  851. """
  852. show_scrollbar = False
  853. def __init__(self, text: AnyFormattedText = "", checked: bool = False) -> None:
  854. values = [("value", text)]
  855. super().__init__(values=values)
  856. self.checked = checked
  857. @property
  858. def checked(self) -> bool:
  859. return "value" in self.current_values
  860. @checked.setter
  861. def checked(self, value: bool) -> None:
  862. if value:
  863. self.current_values = ["value"]
  864. else:
  865. self.current_values = []
  866. class VerticalLine:
  867. """
  868. A simple vertical line with a width of 1.
  869. """
  870. def __init__(self) -> None:
  871. self.window = Window(
  872. char=Border.VERTICAL, style="class:line,vertical-line", width=1
  873. )
  874. def __pt_container__(self) -> Container:
  875. return self.window
  876. class HorizontalLine:
  877. """
  878. A simple horizontal line with a height of 1.
  879. """
  880. def __init__(self) -> None:
  881. self.window = Window(
  882. char=Border.HORIZONTAL, style="class:line,horizontal-line", height=1
  883. )
  884. def __pt_container__(self) -> Container:
  885. return self.window
  886. class ProgressBar:
  887. def __init__(self) -> None:
  888. self._percentage = 60
  889. self.label = Label("60%")
  890. self.container = FloatContainer(
  891. content=Window(height=1),
  892. floats=[
  893. # We first draw the label, then the actual progress bar. Right
  894. # now, this is the only way to have the colors of the progress
  895. # bar appear on top of the label. The problem is that our label
  896. # can't be part of any `Window` below.
  897. Float(content=self.label, top=0, bottom=0),
  898. Float(
  899. left=0,
  900. top=0,
  901. right=0,
  902. bottom=0,
  903. content=VSplit(
  904. [
  905. Window(
  906. style="class:progress-bar.used",
  907. width=lambda: D(weight=int(self._percentage)),
  908. ),
  909. Window(
  910. style="class:progress-bar",
  911. width=lambda: D(weight=int(100 - self._percentage)),
  912. ),
  913. ]
  914. ),
  915. ),
  916. ],
  917. )
  918. @property
  919. def percentage(self) -> int:
  920. return self._percentage
  921. @percentage.setter
  922. def percentage(self, value: int) -> None:
  923. self._percentage = value
  924. self.label.text = f"{value}%"
  925. def __pt_container__(self) -> Container:
  926. return self.container