base.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  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 = self.width - (
  384. get_cwidth(self.left_symbol) + get_cwidth(self.right_symbol)
  385. )
  386. text = (f"{{:^{width}}}").format(self.text)
  387. def handler(mouse_event: MouseEvent) -> None:
  388. if (
  389. self.handler is not None
  390. and mouse_event.event_type == MouseEventType.MOUSE_UP
  391. ):
  392. self.handler()
  393. return [
  394. ("class:button.arrow", self.left_symbol, handler),
  395. ("[SetCursorPosition]", ""),
  396. ("class:button.text", text, handler),
  397. ("class:button.arrow", self.right_symbol, handler),
  398. ]
  399. def _get_key_bindings(self) -> KeyBindings:
  400. "Key bindings for the Button."
  401. kb = KeyBindings()
  402. @kb.add(" ")
  403. @kb.add("enter")
  404. def _(event: E) -> None:
  405. if self.handler is not None:
  406. self.handler()
  407. return kb
  408. def __pt_container__(self) -> Container:
  409. return self.window
  410. class Frame:
  411. """
  412. Draw a border around any container, optionally with a title text.
  413. Changing the title and body of the frame is possible at runtime by
  414. assigning to the `body` and `title` attributes of this class.
  415. :param body: Another container object.
  416. :param title: Text to be displayed in the top of the frame (can be formatted text).
  417. :param style: Style string to be applied to this widget.
  418. """
  419. def __init__(
  420. self,
  421. body: AnyContainer,
  422. title: AnyFormattedText = "",
  423. style: str = "",
  424. width: AnyDimension = None,
  425. height: AnyDimension = None,
  426. key_bindings: KeyBindings | None = None,
  427. modal: bool = False,
  428. ) -> None:
  429. self.title = title
  430. self.body = body
  431. fill = partial(Window, style="class:frame.border")
  432. style = "class:frame " + style
  433. top_row_with_title = VSplit(
  434. [
  435. fill(width=1, height=1, char=Border.TOP_LEFT),
  436. fill(char=Border.HORIZONTAL),
  437. fill(width=1, height=1, char="|"),
  438. # Notice: we use `Template` here, because `self.title` can be an
  439. # `HTML` object for instance.
  440. Label(
  441. lambda: Template(" {} ").format(self.title),
  442. style="class:frame.label",
  443. dont_extend_width=True,
  444. ),
  445. fill(width=1, height=1, char="|"),
  446. fill(char=Border.HORIZONTAL),
  447. fill(width=1, height=1, char=Border.TOP_RIGHT),
  448. ],
  449. height=1,
  450. )
  451. top_row_without_title = VSplit(
  452. [
  453. fill(width=1, height=1, char=Border.TOP_LEFT),
  454. fill(char=Border.HORIZONTAL),
  455. fill(width=1, height=1, char=Border.TOP_RIGHT),
  456. ],
  457. height=1,
  458. )
  459. @Condition
  460. def has_title() -> bool:
  461. return bool(self.title)
  462. self.container = HSplit(
  463. [
  464. ConditionalContainer(content=top_row_with_title, filter=has_title),
  465. ConditionalContainer(content=top_row_without_title, filter=~has_title),
  466. VSplit(
  467. [
  468. fill(width=1, char=Border.VERTICAL),
  469. DynamicContainer(lambda: self.body),
  470. fill(width=1, char=Border.VERTICAL),
  471. # Padding is required to make sure that if the content is
  472. # too small, the right frame border is still aligned.
  473. ],
  474. padding=0,
  475. ),
  476. VSplit(
  477. [
  478. fill(width=1, height=1, char=Border.BOTTOM_LEFT),
  479. fill(char=Border.HORIZONTAL),
  480. fill(width=1, height=1, char=Border.BOTTOM_RIGHT),
  481. ],
  482. # specifying height here will increase the rendering speed.
  483. height=1,
  484. ),
  485. ],
  486. width=width,
  487. height=height,
  488. style=style,
  489. key_bindings=key_bindings,
  490. modal=modal,
  491. )
  492. def __pt_container__(self) -> Container:
  493. return self.container
  494. class Shadow:
  495. """
  496. Draw a shadow underneath/behind this container.
  497. (This applies `class:shadow` the the cells under the shadow. The Style
  498. should define the colors for the shadow.)
  499. :param body: Another container object.
  500. """
  501. def __init__(self, body: AnyContainer) -> None:
  502. self.container = FloatContainer(
  503. content=body,
  504. floats=[
  505. Float(
  506. bottom=-1,
  507. height=1,
  508. left=1,
  509. right=-1,
  510. transparent=True,
  511. content=Window(style="class:shadow"),
  512. ),
  513. Float(
  514. bottom=-1,
  515. top=1,
  516. width=1,
  517. right=-1,
  518. transparent=True,
  519. content=Window(style="class:shadow"),
  520. ),
  521. ],
  522. )
  523. def __pt_container__(self) -> Container:
  524. return self.container
  525. class Box:
  526. """
  527. Add padding around a container.
  528. This also makes sure that the parent can provide more space than required by
  529. the child. This is very useful when wrapping a small element with a fixed
  530. size into a ``VSplit`` or ``HSplit`` object. The ``HSplit`` and ``VSplit``
  531. try to make sure to adapt respectively the width and height, possibly
  532. shrinking other elements. Wrapping something in a ``Box`` makes it flexible.
  533. :param body: Another container object.
  534. :param padding: The margin to be used around the body. This can be
  535. overridden by `padding_left`, padding_right`, `padding_top` and
  536. `padding_bottom`.
  537. :param style: A style string.
  538. :param char: Character to be used for filling the space around the body.
  539. (This is supposed to be a character with a terminal width of 1.)
  540. """
  541. def __init__(
  542. self,
  543. body: AnyContainer,
  544. padding: AnyDimension = None,
  545. padding_left: AnyDimension = None,
  546. padding_right: AnyDimension = None,
  547. padding_top: AnyDimension = None,
  548. padding_bottom: AnyDimension = None,
  549. width: AnyDimension = None,
  550. height: AnyDimension = None,
  551. style: str = "",
  552. char: None | str | Callable[[], str] = None,
  553. modal: bool = False,
  554. key_bindings: KeyBindings | None = None,
  555. ) -> None:
  556. self.padding = padding
  557. self.padding_left = padding_left
  558. self.padding_right = padding_right
  559. self.padding_top = padding_top
  560. self.padding_bottom = padding_bottom
  561. self.body = body
  562. def left() -> AnyDimension:
  563. if self.padding_left is None:
  564. return self.padding
  565. return self.padding_left
  566. def right() -> AnyDimension:
  567. if self.padding_right is None:
  568. return self.padding
  569. return self.padding_right
  570. def top() -> AnyDimension:
  571. if self.padding_top is None:
  572. return self.padding
  573. return self.padding_top
  574. def bottom() -> AnyDimension:
  575. if self.padding_bottom is None:
  576. return self.padding
  577. return self.padding_bottom
  578. self.container = HSplit(
  579. [
  580. Window(height=top, char=char),
  581. VSplit(
  582. [
  583. Window(width=left, char=char),
  584. body,
  585. Window(width=right, char=char),
  586. ]
  587. ),
  588. Window(height=bottom, char=char),
  589. ],
  590. width=width,
  591. height=height,
  592. style=style,
  593. modal=modal,
  594. key_bindings=None,
  595. )
  596. def __pt_container__(self) -> Container:
  597. return self.container
  598. _T = TypeVar("_T")
  599. class _DialogList(Generic[_T]):
  600. """
  601. Common code for `RadioList` and `CheckboxList`.
  602. """
  603. open_character: str = ""
  604. close_character: str = ""
  605. container_style: str = ""
  606. default_style: str = ""
  607. selected_style: str = ""
  608. checked_style: str = ""
  609. multiple_selection: bool = False
  610. show_scrollbar: bool = True
  611. def __init__(
  612. self,
  613. values: Sequence[tuple[_T, AnyFormattedText]],
  614. default_values: Sequence[_T] | None = None,
  615. ) -> None:
  616. assert len(values) > 0
  617. default_values = default_values or []
  618. self.values = values
  619. # current_values will be used in multiple_selection,
  620. # current_value will be used otherwise.
  621. keys: list[_T] = [value for (value, _) in values]
  622. self.current_values: list[_T] = [
  623. value for value in default_values if value in keys
  624. ]
  625. self.current_value: _T = (
  626. default_values[0]
  627. if len(default_values) and default_values[0] in keys
  628. else values[0][0]
  629. )
  630. # Cursor index: take first selected item or first item otherwise.
  631. if len(self.current_values) > 0:
  632. self._selected_index = keys.index(self.current_values[0])
  633. else:
  634. self._selected_index = 0
  635. # Key bindings.
  636. kb = KeyBindings()
  637. @kb.add("up")
  638. def _up(event: E) -> None:
  639. self._selected_index = max(0, self._selected_index - 1)
  640. @kb.add("down")
  641. def _down(event: E) -> None:
  642. self._selected_index = min(len(self.values) - 1, self._selected_index + 1)
  643. @kb.add("pageup")
  644. def _pageup(event: E) -> None:
  645. w = event.app.layout.current_window
  646. if w.render_info:
  647. self._selected_index = max(
  648. 0, self._selected_index - len(w.render_info.displayed_lines)
  649. )
  650. @kb.add("pagedown")
  651. def _pagedown(event: E) -> None:
  652. w = event.app.layout.current_window
  653. if w.render_info:
  654. self._selected_index = min(
  655. len(self.values) - 1,
  656. self._selected_index + len(w.render_info.displayed_lines),
  657. )
  658. @kb.add("enter")
  659. @kb.add(" ")
  660. def _click(event: E) -> None:
  661. self._handle_enter()
  662. @kb.add(Keys.Any)
  663. def _find(event: E) -> None:
  664. # We first check values after the selected value, then all values.
  665. values = list(self.values)
  666. for value in values[self._selected_index + 1 :] + values:
  667. text = fragment_list_to_text(to_formatted_text(value[1])).lower()
  668. if text.startswith(event.data.lower()):
  669. self._selected_index = self.values.index(value)
  670. return
  671. # Control and window.
  672. self.control = FormattedTextControl(
  673. self._get_text_fragments, key_bindings=kb, focusable=True
  674. )
  675. self.window = Window(
  676. content=self.control,
  677. style=self.container_style,
  678. right_margins=[
  679. ConditionalMargin(
  680. margin=ScrollbarMargin(display_arrows=True),
  681. filter=Condition(lambda: self.show_scrollbar),
  682. ),
  683. ],
  684. dont_extend_height=True,
  685. )
  686. def _handle_enter(self) -> None:
  687. if self.multiple_selection:
  688. val = self.values[self._selected_index][0]
  689. if val in self.current_values:
  690. self.current_values.remove(val)
  691. else:
  692. self.current_values.append(val)
  693. else:
  694. self.current_value = self.values[self._selected_index][0]
  695. def _get_text_fragments(self) -> StyleAndTextTuples:
  696. def mouse_handler(mouse_event: MouseEvent) -> None:
  697. """
  698. Set `_selected_index` and `current_value` according to the y
  699. position of the mouse click event.
  700. """
  701. if mouse_event.event_type == MouseEventType.MOUSE_UP:
  702. self._selected_index = mouse_event.position.y
  703. self._handle_enter()
  704. result: StyleAndTextTuples = []
  705. for i, value in enumerate(self.values):
  706. if self.multiple_selection:
  707. checked = value[0] in self.current_values
  708. else:
  709. checked = value[0] == self.current_value
  710. selected = i == self._selected_index
  711. style = ""
  712. if checked:
  713. style += " " + self.checked_style
  714. if selected:
  715. style += " " + self.selected_style
  716. result.append((style, self.open_character))
  717. if selected:
  718. result.append(("[SetCursorPosition]", ""))
  719. if checked:
  720. result.append((style, "*"))
  721. else:
  722. result.append((style, " "))
  723. result.append((style, self.close_character))
  724. result.append((self.default_style, " "))
  725. result.extend(to_formatted_text(value[1], style=self.default_style))
  726. result.append(("", "\n"))
  727. # Add mouse handler to all fragments.
  728. for i in range(len(result)):
  729. result[i] = (result[i][0], result[i][1], mouse_handler)
  730. result.pop() # Remove last newline.
  731. return result
  732. def __pt_container__(self) -> Container:
  733. return self.window
  734. class RadioList(_DialogList[_T]):
  735. """
  736. List of radio buttons. Only one can be checked at the same time.
  737. :param values: List of (value, label) tuples.
  738. """
  739. open_character = "("
  740. close_character = ")"
  741. container_style = "class:radio-list"
  742. default_style = "class:radio"
  743. selected_style = "class:radio-selected"
  744. checked_style = "class:radio-checked"
  745. multiple_selection = False
  746. def __init__(
  747. self,
  748. values: Sequence[tuple[_T, AnyFormattedText]],
  749. default: _T | None = None,
  750. ) -> None:
  751. if default is None:
  752. default_values = None
  753. else:
  754. default_values = [default]
  755. super().__init__(values, default_values=default_values)
  756. class CheckboxList(_DialogList[_T]):
  757. """
  758. List of checkbox buttons. Several can be checked at the same time.
  759. :param values: List of (value, label) tuples.
  760. """
  761. open_character = "["
  762. close_character = "]"
  763. container_style = "class:checkbox-list"
  764. default_style = "class:checkbox"
  765. selected_style = "class:checkbox-selected"
  766. checked_style = "class:checkbox-checked"
  767. multiple_selection = True
  768. class Checkbox(CheckboxList[str]):
  769. """Backward compatibility util: creates a 1-sized CheckboxList
  770. :param text: the text
  771. """
  772. show_scrollbar = False
  773. def __init__(self, text: AnyFormattedText = "", checked: bool = False) -> None:
  774. values = [("value", text)]
  775. super().__init__(values=values)
  776. self.checked = checked
  777. @property
  778. def checked(self) -> bool:
  779. return "value" in self.current_values
  780. @checked.setter
  781. def checked(self, value: bool) -> None:
  782. if value:
  783. self.current_values = ["value"]
  784. else:
  785. self.current_values = []
  786. class VerticalLine:
  787. """
  788. A simple vertical line with a width of 1.
  789. """
  790. def __init__(self) -> None:
  791. self.window = Window(
  792. char=Border.VERTICAL, style="class:line,vertical-line", width=1
  793. )
  794. def __pt_container__(self) -> Container:
  795. return self.window
  796. class HorizontalLine:
  797. """
  798. A simple horizontal line with a height of 1.
  799. """
  800. def __init__(self) -> None:
  801. self.window = Window(
  802. char=Border.HORIZONTAL, style="class:line,horizontal-line", height=1
  803. )
  804. def __pt_container__(self) -> Container:
  805. return self.window
  806. class ProgressBar:
  807. def __init__(self) -> None:
  808. self._percentage = 60
  809. self.label = Label("60%")
  810. self.container = FloatContainer(
  811. content=Window(height=1),
  812. floats=[
  813. # We first draw the label, then the actual progress bar. Right
  814. # now, this is the only way to have the colors of the progress
  815. # bar appear on top of the label. The problem is that our label
  816. # can't be part of any `Window` below.
  817. Float(content=self.label, top=0, bottom=0),
  818. Float(
  819. left=0,
  820. top=0,
  821. right=0,
  822. bottom=0,
  823. content=VSplit(
  824. [
  825. Window(
  826. style="class:progress-bar.used",
  827. width=lambda: D(weight=int(self._percentage)),
  828. ),
  829. Window(
  830. style="class:progress-bar",
  831. width=lambda: D(weight=int(100 - self._percentage)),
  832. ),
  833. ]
  834. ),
  835. ),
  836. ],
  837. )
  838. @property
  839. def percentage(self) -> int:
  840. return self._percentage
  841. @percentage.setter
  842. def percentage(self, value: int) -> None:
  843. self._percentage = value
  844. self.label.text = f"{value}%"
  845. def __pt_container__(self) -> Container:
  846. return self.container