containers.py 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743
  1. """
  2. Container for the layout.
  3. (Containers can contain other containers or user interface controls.)
  4. """
  5. from __future__ import annotations
  6. from abc import ABCMeta, abstractmethod
  7. from enum import Enum
  8. from functools import partial
  9. from typing import TYPE_CHECKING, Callable, Sequence, Union, cast
  10. from prompt_toolkit.application.current import get_app
  11. from prompt_toolkit.cache import SimpleCache
  12. from prompt_toolkit.data_structures import Point
  13. from prompt_toolkit.filters import (
  14. FilterOrBool,
  15. emacs_insert_mode,
  16. to_filter,
  17. vi_insert_mode,
  18. )
  19. from prompt_toolkit.formatted_text import (
  20. AnyFormattedText,
  21. StyleAndTextTuples,
  22. to_formatted_text,
  23. )
  24. from prompt_toolkit.formatted_text.utils import (
  25. fragment_list_to_text,
  26. fragment_list_width,
  27. )
  28. from prompt_toolkit.key_binding import KeyBindingsBase
  29. from prompt_toolkit.mouse_events import MouseEvent, MouseEventType
  30. from prompt_toolkit.utils import get_cwidth, take_using_weights, to_int, to_str
  31. from .controls import (
  32. DummyControl,
  33. FormattedTextControl,
  34. GetLinePrefixCallable,
  35. UIContent,
  36. UIControl,
  37. )
  38. from .dimension import (
  39. AnyDimension,
  40. Dimension,
  41. max_layout_dimensions,
  42. sum_layout_dimensions,
  43. to_dimension,
  44. )
  45. from .margins import Margin
  46. from .mouse_handlers import MouseHandlers
  47. from .screen import _CHAR_CACHE, Screen, WritePosition
  48. from .utils import explode_text_fragments
  49. if TYPE_CHECKING:
  50. from typing_extensions import Protocol, TypeGuard
  51. from prompt_toolkit.key_binding.key_bindings import NotImplementedOrNone
  52. __all__ = [
  53. "AnyContainer",
  54. "Container",
  55. "HorizontalAlign",
  56. "VerticalAlign",
  57. "HSplit",
  58. "VSplit",
  59. "FloatContainer",
  60. "Float",
  61. "WindowAlign",
  62. "Window",
  63. "WindowRenderInfo",
  64. "ConditionalContainer",
  65. "ScrollOffsets",
  66. "ColorColumn",
  67. "to_container",
  68. "to_window",
  69. "is_container",
  70. "DynamicContainer",
  71. ]
  72. class Container(metaclass=ABCMeta):
  73. """
  74. Base class for user interface layout.
  75. """
  76. @abstractmethod
  77. def reset(self) -> None:
  78. """
  79. Reset the state of this container and all the children.
  80. (E.g. reset scroll offsets, etc...)
  81. """
  82. @abstractmethod
  83. def preferred_width(self, max_available_width: int) -> Dimension:
  84. """
  85. Return a :class:`~prompt_toolkit.layout.Dimension` that represents the
  86. desired width for this container.
  87. """
  88. @abstractmethod
  89. def preferred_height(self, width: int, max_available_height: int) -> Dimension:
  90. """
  91. Return a :class:`~prompt_toolkit.layout.Dimension` that represents the
  92. desired height for this container.
  93. """
  94. @abstractmethod
  95. def write_to_screen(
  96. self,
  97. screen: Screen,
  98. mouse_handlers: MouseHandlers,
  99. write_position: WritePosition,
  100. parent_style: str,
  101. erase_bg: bool,
  102. z_index: int | None,
  103. ) -> None:
  104. """
  105. Write the actual content to the screen.
  106. :param screen: :class:`~prompt_toolkit.layout.screen.Screen`
  107. :param mouse_handlers: :class:`~prompt_toolkit.layout.mouse_handlers.MouseHandlers`.
  108. :param parent_style: Style string to pass to the :class:`.Window`
  109. object. This will be applied to all content of the windows.
  110. :class:`.VSplit` and :class:`.HSplit` can use it to pass their
  111. style down to the windows that they contain.
  112. :param z_index: Used for propagating z_index from parent to child.
  113. """
  114. def is_modal(self) -> bool:
  115. """
  116. When this container is modal, key bindings from parent containers are
  117. not taken into account if a user control in this container is focused.
  118. """
  119. return False
  120. def get_key_bindings(self) -> KeyBindingsBase | None:
  121. """
  122. Returns a :class:`.KeyBindings` object. These bindings become active when any
  123. user control in this container has the focus, except if any containers
  124. between this container and the focused user control is modal.
  125. """
  126. return None
  127. @abstractmethod
  128. def get_children(self) -> list[Container]:
  129. """
  130. Return the list of child :class:`.Container` objects.
  131. """
  132. return []
  133. if TYPE_CHECKING:
  134. class MagicContainer(Protocol):
  135. """
  136. Any object that implements ``__pt_container__`` represents a container.
  137. """
  138. def __pt_container__(self) -> AnyContainer:
  139. ...
  140. AnyContainer = Union[Container, "MagicContainer"]
  141. def _window_too_small() -> Window:
  142. "Create a `Window` that displays the 'Window too small' text."
  143. return Window(
  144. FormattedTextControl(text=[("class:window-too-small", " Window too small... ")])
  145. )
  146. class VerticalAlign(Enum):
  147. "Alignment for `HSplit`."
  148. TOP = "TOP"
  149. CENTER = "CENTER"
  150. BOTTOM = "BOTTOM"
  151. JUSTIFY = "JUSTIFY"
  152. class HorizontalAlign(Enum):
  153. "Alignment for `VSplit`."
  154. LEFT = "LEFT"
  155. CENTER = "CENTER"
  156. RIGHT = "RIGHT"
  157. JUSTIFY = "JUSTIFY"
  158. class _Split(Container):
  159. """
  160. The common parts of `VSplit` and `HSplit`.
  161. """
  162. def __init__(
  163. self,
  164. children: Sequence[AnyContainer],
  165. window_too_small: Container | None = None,
  166. padding: AnyDimension = Dimension.exact(0),
  167. padding_char: str | None = None,
  168. padding_style: str = "",
  169. width: AnyDimension = None,
  170. height: AnyDimension = None,
  171. z_index: int | None = None,
  172. modal: bool = False,
  173. key_bindings: KeyBindingsBase | None = None,
  174. style: str | Callable[[], str] = "",
  175. ) -> None:
  176. self.children = [to_container(c) for c in children]
  177. self.window_too_small = window_too_small or _window_too_small()
  178. self.padding = padding
  179. self.padding_char = padding_char
  180. self.padding_style = padding_style
  181. self.width = width
  182. self.height = height
  183. self.z_index = z_index
  184. self.modal = modal
  185. self.key_bindings = key_bindings
  186. self.style = style
  187. def is_modal(self) -> bool:
  188. return self.modal
  189. def get_key_bindings(self) -> KeyBindingsBase | None:
  190. return self.key_bindings
  191. def get_children(self) -> list[Container]:
  192. return self.children
  193. class HSplit(_Split):
  194. """
  195. Several layouts, one stacked above/under the other. ::
  196. +--------------------+
  197. | |
  198. +--------------------+
  199. | |
  200. +--------------------+
  201. By default, this doesn't display a horizontal line between the children,
  202. but if this is something you need, then create a HSplit as follows::
  203. HSplit(children=[ ... ], padding_char='-',
  204. padding=1, padding_style='#ffff00')
  205. :param children: List of child :class:`.Container` objects.
  206. :param window_too_small: A :class:`.Container` object that is displayed if
  207. there is not enough space for all the children. By default, this is a
  208. "Window too small" message.
  209. :param align: `VerticalAlign` value.
  210. :param width: When given, use this width instead of looking at the children.
  211. :param height: When given, use this height instead of looking at the children.
  212. :param z_index: (int or None) When specified, this can be used to bring
  213. element in front of floating elements. `None` means: inherit from parent.
  214. :param style: A style string.
  215. :param modal: ``True`` or ``False``.
  216. :param key_bindings: ``None`` or a :class:`.KeyBindings` object.
  217. :param padding: (`Dimension` or int), size to be used for the padding.
  218. :param padding_char: Character to be used for filling in the padding.
  219. :param padding_style: Style to applied to the padding.
  220. """
  221. def __init__(
  222. self,
  223. children: Sequence[AnyContainer],
  224. window_too_small: Container | None = None,
  225. align: VerticalAlign = VerticalAlign.JUSTIFY,
  226. padding: AnyDimension = 0,
  227. padding_char: str | None = None,
  228. padding_style: str = "",
  229. width: AnyDimension = None,
  230. height: AnyDimension = None,
  231. z_index: int | None = None,
  232. modal: bool = False,
  233. key_bindings: KeyBindingsBase | None = None,
  234. style: str | Callable[[], str] = "",
  235. ) -> None:
  236. super().__init__(
  237. children=children,
  238. window_too_small=window_too_small,
  239. padding=padding,
  240. padding_char=padding_char,
  241. padding_style=padding_style,
  242. width=width,
  243. height=height,
  244. z_index=z_index,
  245. modal=modal,
  246. key_bindings=key_bindings,
  247. style=style,
  248. )
  249. self.align = align
  250. self._children_cache: SimpleCache[
  251. tuple[Container, ...], list[Container]
  252. ] = SimpleCache(maxsize=1)
  253. self._remaining_space_window = Window() # Dummy window.
  254. def preferred_width(self, max_available_width: int) -> Dimension:
  255. if self.width is not None:
  256. return to_dimension(self.width)
  257. if self.children:
  258. dimensions = [c.preferred_width(max_available_width) for c in self.children]
  259. return max_layout_dimensions(dimensions)
  260. else:
  261. return Dimension()
  262. def preferred_height(self, width: int, max_available_height: int) -> Dimension:
  263. if self.height is not None:
  264. return to_dimension(self.height)
  265. dimensions = [
  266. c.preferred_height(width, max_available_height) for c in self._all_children
  267. ]
  268. return sum_layout_dimensions(dimensions)
  269. def reset(self) -> None:
  270. for c in self.children:
  271. c.reset()
  272. @property
  273. def _all_children(self) -> list[Container]:
  274. """
  275. List of child objects, including padding.
  276. """
  277. def get() -> list[Container]:
  278. result: list[Container] = []
  279. # Padding Top.
  280. if self.align in (VerticalAlign.CENTER, VerticalAlign.BOTTOM):
  281. result.append(Window(width=Dimension(preferred=0)))
  282. # The children with padding.
  283. for child in self.children:
  284. result.append(child)
  285. result.append(
  286. Window(
  287. height=self.padding,
  288. char=self.padding_char,
  289. style=self.padding_style,
  290. )
  291. )
  292. if result:
  293. result.pop()
  294. # Padding right.
  295. if self.align in (VerticalAlign.CENTER, VerticalAlign.TOP):
  296. result.append(Window(width=Dimension(preferred=0)))
  297. return result
  298. return self._children_cache.get(tuple(self.children), get)
  299. def write_to_screen(
  300. self,
  301. screen: Screen,
  302. mouse_handlers: MouseHandlers,
  303. write_position: WritePosition,
  304. parent_style: str,
  305. erase_bg: bool,
  306. z_index: int | None,
  307. ) -> None:
  308. """
  309. Render the prompt to a `Screen` instance.
  310. :param screen: The :class:`~prompt_toolkit.layout.screen.Screen` class
  311. to which the output has to be written.
  312. """
  313. sizes = self._divide_heights(write_position)
  314. style = parent_style + " " + to_str(self.style)
  315. z_index = z_index if self.z_index is None else self.z_index
  316. if sizes is None:
  317. self.window_too_small.write_to_screen(
  318. screen, mouse_handlers, write_position, style, erase_bg, z_index
  319. )
  320. else:
  321. #
  322. ypos = write_position.ypos
  323. xpos = write_position.xpos
  324. width = write_position.width
  325. # Draw child panes.
  326. for s, c in zip(sizes, self._all_children):
  327. c.write_to_screen(
  328. screen,
  329. mouse_handlers,
  330. WritePosition(xpos, ypos, width, s),
  331. style,
  332. erase_bg,
  333. z_index,
  334. )
  335. ypos += s
  336. # Fill in the remaining space. This happens when a child control
  337. # refuses to take more space and we don't have any padding. Adding a
  338. # dummy child control for this (in `self._all_children`) is not
  339. # desired, because in some situations, it would take more space, even
  340. # when it's not required. This is required to apply the styling.
  341. remaining_height = write_position.ypos + write_position.height - ypos
  342. if remaining_height > 0:
  343. self._remaining_space_window.write_to_screen(
  344. screen,
  345. mouse_handlers,
  346. WritePosition(xpos, ypos, width, remaining_height),
  347. style,
  348. erase_bg,
  349. z_index,
  350. )
  351. def _divide_heights(self, write_position: WritePosition) -> list[int] | None:
  352. """
  353. Return the heights for all rows.
  354. Or None when there is not enough space.
  355. """
  356. if not self.children:
  357. return []
  358. width = write_position.width
  359. height = write_position.height
  360. # Calculate heights.
  361. dimensions = [c.preferred_height(width, height) for c in self._all_children]
  362. # Sum dimensions
  363. sum_dimensions = sum_layout_dimensions(dimensions)
  364. # If there is not enough space for both.
  365. # Don't do anything.
  366. if sum_dimensions.min > height:
  367. return None
  368. # Find optimal sizes. (Start with minimal size, increase until we cover
  369. # the whole height.)
  370. sizes = [d.min for d in dimensions]
  371. child_generator = take_using_weights(
  372. items=list(range(len(dimensions))), weights=[d.weight for d in dimensions]
  373. )
  374. i = next(child_generator)
  375. # Increase until we meet at least the 'preferred' size.
  376. preferred_stop = min(height, sum_dimensions.preferred)
  377. preferred_dimensions = [d.preferred for d in dimensions]
  378. while sum(sizes) < preferred_stop:
  379. if sizes[i] < preferred_dimensions[i]:
  380. sizes[i] += 1
  381. i = next(child_generator)
  382. # Increase until we use all the available space. (or until "max")
  383. if not get_app().is_done:
  384. max_stop = min(height, sum_dimensions.max)
  385. max_dimensions = [d.max for d in dimensions]
  386. while sum(sizes) < max_stop:
  387. if sizes[i] < max_dimensions[i]:
  388. sizes[i] += 1
  389. i = next(child_generator)
  390. return sizes
  391. class VSplit(_Split):
  392. """
  393. Several layouts, one stacked left/right of the other. ::
  394. +---------+----------+
  395. | | |
  396. | | |
  397. +---------+----------+
  398. By default, this doesn't display a vertical line between the children, but
  399. if this is something you need, then create a HSplit as follows::
  400. VSplit(children=[ ... ], padding_char='|',
  401. padding=1, padding_style='#ffff00')
  402. :param children: List of child :class:`.Container` objects.
  403. :param window_too_small: A :class:`.Container` object that is displayed if
  404. there is not enough space for all the children. By default, this is a
  405. "Window too small" message.
  406. :param align: `HorizontalAlign` value.
  407. :param width: When given, use this width instead of looking at the children.
  408. :param height: When given, use this height instead of looking at the children.
  409. :param z_index: (int or None) When specified, this can be used to bring
  410. element in front of floating elements. `None` means: inherit from parent.
  411. :param style: A style string.
  412. :param modal: ``True`` or ``False``.
  413. :param key_bindings: ``None`` or a :class:`.KeyBindings` object.
  414. :param padding: (`Dimension` or int), size to be used for the padding.
  415. :param padding_char: Character to be used for filling in the padding.
  416. :param padding_style: Style to applied to the padding.
  417. """
  418. def __init__(
  419. self,
  420. children: Sequence[AnyContainer],
  421. window_too_small: Container | None = None,
  422. align: HorizontalAlign = HorizontalAlign.JUSTIFY,
  423. padding: AnyDimension = 0,
  424. padding_char: str | None = None,
  425. padding_style: str = "",
  426. width: AnyDimension = None,
  427. height: AnyDimension = None,
  428. z_index: int | None = None,
  429. modal: bool = False,
  430. key_bindings: KeyBindingsBase | None = None,
  431. style: str | Callable[[], str] = "",
  432. ) -> None:
  433. super().__init__(
  434. children=children,
  435. window_too_small=window_too_small,
  436. padding=padding,
  437. padding_char=padding_char,
  438. padding_style=padding_style,
  439. width=width,
  440. height=height,
  441. z_index=z_index,
  442. modal=modal,
  443. key_bindings=key_bindings,
  444. style=style,
  445. )
  446. self.align = align
  447. self._children_cache: SimpleCache[
  448. tuple[Container, ...], list[Container]
  449. ] = SimpleCache(maxsize=1)
  450. self._remaining_space_window = Window() # Dummy window.
  451. def preferred_width(self, max_available_width: int) -> Dimension:
  452. if self.width is not None:
  453. return to_dimension(self.width)
  454. dimensions = [
  455. c.preferred_width(max_available_width) for c in self._all_children
  456. ]
  457. return sum_layout_dimensions(dimensions)
  458. def preferred_height(self, width: int, max_available_height: int) -> Dimension:
  459. if self.height is not None:
  460. return to_dimension(self.height)
  461. # At the point where we want to calculate the heights, the widths have
  462. # already been decided. So we can trust `width` to be the actual
  463. # `width` that's going to be used for the rendering. So,
  464. # `divide_widths` is supposed to use all of the available width.
  465. # Using only the `preferred` width caused a bug where the reported
  466. # height was more than required. (we had a `BufferControl` which did
  467. # wrap lines because of the smaller width returned by `_divide_widths`.
  468. sizes = self._divide_widths(width)
  469. children = self._all_children
  470. if sizes is None:
  471. return Dimension()
  472. else:
  473. dimensions = [
  474. c.preferred_height(s, max_available_height)
  475. for s, c in zip(sizes, children)
  476. ]
  477. return max_layout_dimensions(dimensions)
  478. def reset(self) -> None:
  479. for c in self.children:
  480. c.reset()
  481. @property
  482. def _all_children(self) -> list[Container]:
  483. """
  484. List of child objects, including padding.
  485. """
  486. def get() -> list[Container]:
  487. result: list[Container] = []
  488. # Padding left.
  489. if self.align in (HorizontalAlign.CENTER, HorizontalAlign.RIGHT):
  490. result.append(Window(width=Dimension(preferred=0)))
  491. # The children with padding.
  492. for child in self.children:
  493. result.append(child)
  494. result.append(
  495. Window(
  496. width=self.padding,
  497. char=self.padding_char,
  498. style=self.padding_style,
  499. )
  500. )
  501. if result:
  502. result.pop()
  503. # Padding right.
  504. if self.align in (HorizontalAlign.CENTER, HorizontalAlign.LEFT):
  505. result.append(Window(width=Dimension(preferred=0)))
  506. return result
  507. return self._children_cache.get(tuple(self.children), get)
  508. def _divide_widths(self, width: int) -> list[int] | None:
  509. """
  510. Return the widths for all columns.
  511. Or None when there is not enough space.
  512. """
  513. children = self._all_children
  514. if not children:
  515. return []
  516. # Calculate widths.
  517. dimensions = [c.preferred_width(width) for c in children]
  518. preferred_dimensions = [d.preferred for d in dimensions]
  519. # Sum dimensions
  520. sum_dimensions = sum_layout_dimensions(dimensions)
  521. # If there is not enough space for both.
  522. # Don't do anything.
  523. if sum_dimensions.min > width:
  524. return None
  525. # Find optimal sizes. (Start with minimal size, increase until we cover
  526. # the whole width.)
  527. sizes = [d.min for d in dimensions]
  528. child_generator = take_using_weights(
  529. items=list(range(len(dimensions))), weights=[d.weight for d in dimensions]
  530. )
  531. i = next(child_generator)
  532. # Increase until we meet at least the 'preferred' size.
  533. preferred_stop = min(width, sum_dimensions.preferred)
  534. while sum(sizes) < preferred_stop:
  535. if sizes[i] < preferred_dimensions[i]:
  536. sizes[i] += 1
  537. i = next(child_generator)
  538. # Increase until we use all the available space.
  539. max_dimensions = [d.max for d in dimensions]
  540. max_stop = min(width, sum_dimensions.max)
  541. while sum(sizes) < max_stop:
  542. if sizes[i] < max_dimensions[i]:
  543. sizes[i] += 1
  544. i = next(child_generator)
  545. return sizes
  546. def write_to_screen(
  547. self,
  548. screen: Screen,
  549. mouse_handlers: MouseHandlers,
  550. write_position: WritePosition,
  551. parent_style: str,
  552. erase_bg: bool,
  553. z_index: int | None,
  554. ) -> None:
  555. """
  556. Render the prompt to a `Screen` instance.
  557. :param screen: The :class:`~prompt_toolkit.layout.screen.Screen` class
  558. to which the output has to be written.
  559. """
  560. if not self.children:
  561. return
  562. children = self._all_children
  563. sizes = self._divide_widths(write_position.width)
  564. style = parent_style + " " + to_str(self.style)
  565. z_index = z_index if self.z_index is None else self.z_index
  566. # If there is not enough space.
  567. if sizes is None:
  568. self.window_too_small.write_to_screen(
  569. screen, mouse_handlers, write_position, style, erase_bg, z_index
  570. )
  571. return
  572. # Calculate heights, take the largest possible, but not larger than
  573. # write_position.height.
  574. heights = [
  575. child.preferred_height(width, write_position.height).preferred
  576. for width, child in zip(sizes, children)
  577. ]
  578. height = max(write_position.height, min(write_position.height, max(heights)))
  579. #
  580. ypos = write_position.ypos
  581. xpos = write_position.xpos
  582. # Draw all child panes.
  583. for s, c in zip(sizes, children):
  584. c.write_to_screen(
  585. screen,
  586. mouse_handlers,
  587. WritePosition(xpos, ypos, s, height),
  588. style,
  589. erase_bg,
  590. z_index,
  591. )
  592. xpos += s
  593. # Fill in the remaining space. This happens when a child control
  594. # refuses to take more space and we don't have any padding. Adding a
  595. # dummy child control for this (in `self._all_children`) is not
  596. # desired, because in some situations, it would take more space, even
  597. # when it's not required. This is required to apply the styling.
  598. remaining_width = write_position.xpos + write_position.width - xpos
  599. if remaining_width > 0:
  600. self._remaining_space_window.write_to_screen(
  601. screen,
  602. mouse_handlers,
  603. WritePosition(xpos, ypos, remaining_width, height),
  604. style,
  605. erase_bg,
  606. z_index,
  607. )
  608. class FloatContainer(Container):
  609. """
  610. Container which can contain another container for the background, as well
  611. as a list of floating containers on top of it.
  612. Example Usage::
  613. FloatContainer(content=Window(...),
  614. floats=[
  615. Float(xcursor=True,
  616. ycursor=True,
  617. content=CompletionsMenu(...))
  618. ])
  619. :param z_index: (int or None) When specified, this can be used to bring
  620. element in front of floating elements. `None` means: inherit from parent.
  621. This is the z_index for the whole `Float` container as a whole.
  622. """
  623. def __init__(
  624. self,
  625. content: AnyContainer,
  626. floats: list[Float],
  627. modal: bool = False,
  628. key_bindings: KeyBindingsBase | None = None,
  629. style: str | Callable[[], str] = "",
  630. z_index: int | None = None,
  631. ) -> None:
  632. self.content = to_container(content)
  633. self.floats = floats
  634. self.modal = modal
  635. self.key_bindings = key_bindings
  636. self.style = style
  637. self.z_index = z_index
  638. def reset(self) -> None:
  639. self.content.reset()
  640. for f in self.floats:
  641. f.content.reset()
  642. def preferred_width(self, max_available_width: int) -> Dimension:
  643. return self.content.preferred_width(max_available_width)
  644. def preferred_height(self, width: int, max_available_height: int) -> Dimension:
  645. """
  646. Return the preferred height of the float container.
  647. (We don't care about the height of the floats, they should always fit
  648. into the dimensions provided by the container.)
  649. """
  650. return self.content.preferred_height(width, max_available_height)
  651. def write_to_screen(
  652. self,
  653. screen: Screen,
  654. mouse_handlers: MouseHandlers,
  655. write_position: WritePosition,
  656. parent_style: str,
  657. erase_bg: bool,
  658. z_index: int | None,
  659. ) -> None:
  660. style = parent_style + " " + to_str(self.style)
  661. z_index = z_index if self.z_index is None else self.z_index
  662. self.content.write_to_screen(
  663. screen, mouse_handlers, write_position, style, erase_bg, z_index
  664. )
  665. for number, fl in enumerate(self.floats):
  666. # z_index of a Float is computed by summing the z_index of the
  667. # container and the `Float`.
  668. new_z_index = (z_index or 0) + fl.z_index
  669. style = parent_style + " " + to_str(self.style)
  670. # If the float that we have here, is positioned relative to the
  671. # cursor position, but the Window that specifies the cursor
  672. # position is not drawn yet, because it's a Float itself, we have
  673. # to postpone this calculation. (This is a work-around, but good
  674. # enough for now.)
  675. postpone = fl.xcursor is not None or fl.ycursor is not None
  676. if postpone:
  677. new_z_index = (
  678. number + 10**8
  679. ) # Draw as late as possible, but keep the order.
  680. screen.draw_with_z_index(
  681. z_index=new_z_index,
  682. draw_func=partial(
  683. self._draw_float,
  684. fl,
  685. screen,
  686. mouse_handlers,
  687. write_position,
  688. style,
  689. erase_bg,
  690. new_z_index,
  691. ),
  692. )
  693. else:
  694. self._draw_float(
  695. fl,
  696. screen,
  697. mouse_handlers,
  698. write_position,
  699. style,
  700. erase_bg,
  701. new_z_index,
  702. )
  703. def _draw_float(
  704. self,
  705. fl: Float,
  706. screen: Screen,
  707. mouse_handlers: MouseHandlers,
  708. write_position: WritePosition,
  709. style: str,
  710. erase_bg: bool,
  711. z_index: int | None,
  712. ) -> None:
  713. "Draw a single Float."
  714. # When a menu_position was given, use this instead of the cursor
  715. # position. (These cursor positions are absolute, translate again
  716. # relative to the write_position.)
  717. # Note: This should be inside the for-loop, because one float could
  718. # set the cursor position to be used for the next one.
  719. cpos = screen.get_menu_position(
  720. fl.attach_to_window or get_app().layout.current_window
  721. )
  722. cursor_position = Point(
  723. x=cpos.x - write_position.xpos, y=cpos.y - write_position.ypos
  724. )
  725. fl_width = fl.get_width()
  726. fl_height = fl.get_height()
  727. width: int
  728. height: int
  729. xpos: int
  730. ypos: int
  731. # Left & width given.
  732. if fl.left is not None and fl_width is not None:
  733. xpos = fl.left
  734. width = fl_width
  735. # Left & right given -> calculate width.
  736. elif fl.left is not None and fl.right is not None:
  737. xpos = fl.left
  738. width = write_position.width - fl.left - fl.right
  739. # Width & right given -> calculate left.
  740. elif fl_width is not None and fl.right is not None:
  741. xpos = write_position.width - fl.right - fl_width
  742. width = fl_width
  743. # Near x position of cursor.
  744. elif fl.xcursor:
  745. if fl_width is None:
  746. width = fl.content.preferred_width(write_position.width).preferred
  747. width = min(write_position.width, width)
  748. else:
  749. width = fl_width
  750. xpos = cursor_position.x
  751. if xpos + width > write_position.width:
  752. xpos = max(0, write_position.width - width)
  753. # Only width given -> center horizontally.
  754. elif fl_width:
  755. xpos = int((write_position.width - fl_width) / 2)
  756. width = fl_width
  757. # Otherwise, take preferred width from float content.
  758. else:
  759. width = fl.content.preferred_width(write_position.width).preferred
  760. if fl.left is not None:
  761. xpos = fl.left
  762. elif fl.right is not None:
  763. xpos = max(0, write_position.width - width - fl.right)
  764. else: # Center horizontally.
  765. xpos = max(0, int((write_position.width - width) / 2))
  766. # Trim.
  767. width = min(width, write_position.width - xpos)
  768. # Top & height given.
  769. if fl.top is not None and fl_height is not None:
  770. ypos = fl.top
  771. height = fl_height
  772. # Top & bottom given -> calculate height.
  773. elif fl.top is not None and fl.bottom is not None:
  774. ypos = fl.top
  775. height = write_position.height - fl.top - fl.bottom
  776. # Height & bottom given -> calculate top.
  777. elif fl_height is not None and fl.bottom is not None:
  778. ypos = write_position.height - fl_height - fl.bottom
  779. height = fl_height
  780. # Near cursor.
  781. elif fl.ycursor:
  782. ypos = cursor_position.y + (0 if fl.allow_cover_cursor else 1)
  783. if fl_height is None:
  784. height = fl.content.preferred_height(
  785. width, write_position.height
  786. ).preferred
  787. else:
  788. height = fl_height
  789. # Reduce height if not enough space. (We can use the height
  790. # when the content requires it.)
  791. if height > write_position.height - ypos:
  792. if write_position.height - ypos + 1 >= ypos:
  793. # When the space below the cursor is more than
  794. # the space above, just reduce the height.
  795. height = write_position.height - ypos
  796. else:
  797. # Otherwise, fit the float above the cursor.
  798. height = min(height, cursor_position.y)
  799. ypos = cursor_position.y - height
  800. # Only height given -> center vertically.
  801. elif fl_height:
  802. ypos = int((write_position.height - fl_height) / 2)
  803. height = fl_height
  804. # Otherwise, take preferred height from content.
  805. else:
  806. height = fl.content.preferred_height(width, write_position.height).preferred
  807. if fl.top is not None:
  808. ypos = fl.top
  809. elif fl.bottom is not None:
  810. ypos = max(0, write_position.height - height - fl.bottom)
  811. else: # Center vertically.
  812. ypos = max(0, int((write_position.height - height) / 2))
  813. # Trim.
  814. height = min(height, write_position.height - ypos)
  815. # Write float.
  816. # (xpos and ypos can be negative: a float can be partially visible.)
  817. if height > 0 and width > 0:
  818. wp = WritePosition(
  819. xpos=xpos + write_position.xpos,
  820. ypos=ypos + write_position.ypos,
  821. width=width,
  822. height=height,
  823. )
  824. if not fl.hide_when_covering_content or self._area_is_empty(screen, wp):
  825. fl.content.write_to_screen(
  826. screen,
  827. mouse_handlers,
  828. wp,
  829. style,
  830. erase_bg=not fl.transparent(),
  831. z_index=z_index,
  832. )
  833. def _area_is_empty(self, screen: Screen, write_position: WritePosition) -> bool:
  834. """
  835. Return True when the area below the write position is still empty.
  836. (For floats that should not hide content underneath.)
  837. """
  838. wp = write_position
  839. for y in range(wp.ypos, wp.ypos + wp.height):
  840. if y in screen.data_buffer:
  841. row = screen.data_buffer[y]
  842. for x in range(wp.xpos, wp.xpos + wp.width):
  843. c = row[x]
  844. if c.char != " ":
  845. return False
  846. return True
  847. def is_modal(self) -> bool:
  848. return self.modal
  849. def get_key_bindings(self) -> KeyBindingsBase | None:
  850. return self.key_bindings
  851. def get_children(self) -> list[Container]:
  852. children = [self.content]
  853. children.extend(f.content for f in self.floats)
  854. return children
  855. class Float:
  856. """
  857. Float for use in a :class:`.FloatContainer`.
  858. Except for the `content` parameter, all other options are optional.
  859. :param content: :class:`.Container` instance.
  860. :param width: :class:`.Dimension` or callable which returns a :class:`.Dimension`.
  861. :param height: :class:`.Dimension` or callable which returns a :class:`.Dimension`.
  862. :param left: Distance to the left edge of the :class:`.FloatContainer`.
  863. :param right: Distance to the right edge of the :class:`.FloatContainer`.
  864. :param top: Distance to the top of the :class:`.FloatContainer`.
  865. :param bottom: Distance to the bottom of the :class:`.FloatContainer`.
  866. :param attach_to_window: Attach to the cursor from this window, instead of
  867. the current window.
  868. :param hide_when_covering_content: Hide the float when it covers content underneath.
  869. :param allow_cover_cursor: When `False`, make sure to display the float
  870. below the cursor. Not on top of the indicated position.
  871. :param z_index: Z-index position. For a Float, this needs to be at least
  872. one. It is relative to the z_index of the parent container.
  873. :param transparent: :class:`.Filter` indicating whether this float needs to be
  874. drawn transparently.
  875. """
  876. def __init__(
  877. self,
  878. content: AnyContainer,
  879. top: int | None = None,
  880. right: int | None = None,
  881. bottom: int | None = None,
  882. left: int | None = None,
  883. width: int | Callable[[], int] | None = None,
  884. height: int | Callable[[], int] | None = None,
  885. xcursor: bool = False,
  886. ycursor: bool = False,
  887. attach_to_window: AnyContainer | None = None,
  888. hide_when_covering_content: bool = False,
  889. allow_cover_cursor: bool = False,
  890. z_index: int = 1,
  891. transparent: bool = False,
  892. ) -> None:
  893. assert z_index >= 1
  894. self.left = left
  895. self.right = right
  896. self.top = top
  897. self.bottom = bottom
  898. self.width = width
  899. self.height = height
  900. self.xcursor = xcursor
  901. self.ycursor = ycursor
  902. self.attach_to_window = (
  903. to_window(attach_to_window) if attach_to_window else None
  904. )
  905. self.content = to_container(content)
  906. self.hide_when_covering_content = hide_when_covering_content
  907. self.allow_cover_cursor = allow_cover_cursor
  908. self.z_index = z_index
  909. self.transparent = to_filter(transparent)
  910. def get_width(self) -> int | None:
  911. if callable(self.width):
  912. return self.width()
  913. return self.width
  914. def get_height(self) -> int | None:
  915. if callable(self.height):
  916. return self.height()
  917. return self.height
  918. def __repr__(self) -> str:
  919. return "Float(content=%r)" % self.content
  920. class WindowRenderInfo:
  921. """
  922. Render information for the last render time of this control.
  923. It stores mapping information between the input buffers (in case of a
  924. :class:`~prompt_toolkit.layout.controls.BufferControl`) and the actual
  925. render position on the output screen.
  926. (Could be used for implementation of the Vi 'H' and 'L' key bindings as
  927. well as implementing mouse support.)
  928. :param ui_content: The original :class:`.UIContent` instance that contains
  929. the whole input, without clipping. (ui_content)
  930. :param horizontal_scroll: The horizontal scroll of the :class:`.Window` instance.
  931. :param vertical_scroll: The vertical scroll of the :class:`.Window` instance.
  932. :param window_width: The width of the window that displays the content,
  933. without the margins.
  934. :param window_height: The height of the window that displays the content.
  935. :param configured_scroll_offsets: The scroll offsets as configured for the
  936. :class:`Window` instance.
  937. :param visible_line_to_row_col: Mapping that maps the row numbers on the
  938. displayed screen (starting from zero for the first visible line) to
  939. (row, col) tuples pointing to the row and column of the :class:`.UIContent`.
  940. :param rowcol_to_yx: Mapping that maps (row, column) tuples representing
  941. coordinates of the :class:`UIContent` to (y, x) absolute coordinates at
  942. the rendered screen.
  943. """
  944. def __init__(
  945. self,
  946. window: Window,
  947. ui_content: UIContent,
  948. horizontal_scroll: int,
  949. vertical_scroll: int,
  950. window_width: int,
  951. window_height: int,
  952. configured_scroll_offsets: ScrollOffsets,
  953. visible_line_to_row_col: dict[int, tuple[int, int]],
  954. rowcol_to_yx: dict[tuple[int, int], tuple[int, int]],
  955. x_offset: int,
  956. y_offset: int,
  957. wrap_lines: bool,
  958. ) -> None:
  959. self.window = window
  960. self.ui_content = ui_content
  961. self.vertical_scroll = vertical_scroll
  962. self.window_width = window_width # Width without margins.
  963. self.window_height = window_height
  964. self.configured_scroll_offsets = configured_scroll_offsets
  965. self.visible_line_to_row_col = visible_line_to_row_col
  966. self.wrap_lines = wrap_lines
  967. self._rowcol_to_yx = rowcol_to_yx # row/col from input to absolute y/x
  968. # screen coordinates.
  969. self._x_offset = x_offset
  970. self._y_offset = y_offset
  971. @property
  972. def visible_line_to_input_line(self) -> dict[int, int]:
  973. return {
  974. visible_line: rowcol[0]
  975. for visible_line, rowcol in self.visible_line_to_row_col.items()
  976. }
  977. @property
  978. def cursor_position(self) -> Point:
  979. """
  980. Return the cursor position coordinates, relative to the left/top corner
  981. of the rendered screen.
  982. """
  983. cpos = self.ui_content.cursor_position
  984. try:
  985. y, x = self._rowcol_to_yx[cpos.y, cpos.x]
  986. except KeyError:
  987. # For `DummyControl` for instance, the content can be empty, and so
  988. # will `_rowcol_to_yx` be. Return 0/0 by default.
  989. return Point(x=0, y=0)
  990. else:
  991. return Point(x=x - self._x_offset, y=y - self._y_offset)
  992. @property
  993. def applied_scroll_offsets(self) -> ScrollOffsets:
  994. """
  995. Return a :class:`.ScrollOffsets` instance that indicates the actual
  996. offset. This can be less than or equal to what's configured. E.g, when
  997. the cursor is completely at the top, the top offset will be zero rather
  998. than what's configured.
  999. """
  1000. if self.displayed_lines[0] == 0:
  1001. top = 0
  1002. else:
  1003. # Get row where the cursor is displayed.
  1004. y = self.input_line_to_visible_line[self.ui_content.cursor_position.y]
  1005. top = min(y, self.configured_scroll_offsets.top)
  1006. return ScrollOffsets(
  1007. top=top,
  1008. bottom=min(
  1009. self.ui_content.line_count - self.displayed_lines[-1] - 1,
  1010. self.configured_scroll_offsets.bottom,
  1011. ),
  1012. # For left/right, it probably doesn't make sense to return something.
  1013. # (We would have to calculate the widths of all the lines and keep
  1014. # double width characters in mind.)
  1015. left=0,
  1016. right=0,
  1017. )
  1018. @property
  1019. def displayed_lines(self) -> list[int]:
  1020. """
  1021. List of all the visible rows. (Line numbers of the input buffer.)
  1022. The last line may not be entirely visible.
  1023. """
  1024. return sorted(row for row, col in self.visible_line_to_row_col.values())
  1025. @property
  1026. def input_line_to_visible_line(self) -> dict[int, int]:
  1027. """
  1028. Return the dictionary mapping the line numbers of the input buffer to
  1029. the lines of the screen. When a line spans several rows at the screen,
  1030. the first row appears in the dictionary.
  1031. """
  1032. result: dict[int, int] = {}
  1033. for k, v in self.visible_line_to_input_line.items():
  1034. if v in result:
  1035. result[v] = min(result[v], k)
  1036. else:
  1037. result[v] = k
  1038. return result
  1039. def first_visible_line(self, after_scroll_offset: bool = False) -> int:
  1040. """
  1041. Return the line number (0 based) of the input document that corresponds
  1042. with the first visible line.
  1043. """
  1044. if after_scroll_offset:
  1045. return self.displayed_lines[self.applied_scroll_offsets.top]
  1046. else:
  1047. return self.displayed_lines[0]
  1048. def last_visible_line(self, before_scroll_offset: bool = False) -> int:
  1049. """
  1050. Like `first_visible_line`, but for the last visible line.
  1051. """
  1052. if before_scroll_offset:
  1053. return self.displayed_lines[-1 - self.applied_scroll_offsets.bottom]
  1054. else:
  1055. return self.displayed_lines[-1]
  1056. def center_visible_line(
  1057. self, before_scroll_offset: bool = False, after_scroll_offset: bool = False
  1058. ) -> int:
  1059. """
  1060. Like `first_visible_line`, but for the center visible line.
  1061. """
  1062. return (
  1063. self.first_visible_line(after_scroll_offset)
  1064. + (
  1065. self.last_visible_line(before_scroll_offset)
  1066. - self.first_visible_line(after_scroll_offset)
  1067. )
  1068. // 2
  1069. )
  1070. @property
  1071. def content_height(self) -> int:
  1072. """
  1073. The full height of the user control.
  1074. """
  1075. return self.ui_content.line_count
  1076. @property
  1077. def full_height_visible(self) -> bool:
  1078. """
  1079. True when the full height is visible (There is no vertical scroll.)
  1080. """
  1081. return (
  1082. self.vertical_scroll == 0
  1083. and self.last_visible_line() == self.content_height
  1084. )
  1085. @property
  1086. def top_visible(self) -> bool:
  1087. """
  1088. True when the top of the buffer is visible.
  1089. """
  1090. return self.vertical_scroll == 0
  1091. @property
  1092. def bottom_visible(self) -> bool:
  1093. """
  1094. True when the bottom of the buffer is visible.
  1095. """
  1096. return self.last_visible_line() == self.content_height - 1
  1097. @property
  1098. def vertical_scroll_percentage(self) -> int:
  1099. """
  1100. Vertical scroll as a percentage. (0 means: the top is visible,
  1101. 100 means: the bottom is visible.)
  1102. """
  1103. if self.bottom_visible:
  1104. return 100
  1105. else:
  1106. return 100 * self.vertical_scroll // self.content_height
  1107. def get_height_for_line(self, lineno: int) -> int:
  1108. """
  1109. Return the height of the given line.
  1110. (The height that it would take, if this line became visible.)
  1111. """
  1112. if self.wrap_lines:
  1113. return self.ui_content.get_height_for_line(
  1114. lineno, self.window_width, self.window.get_line_prefix
  1115. )
  1116. else:
  1117. return 1
  1118. class ScrollOffsets:
  1119. """
  1120. Scroll offsets for the :class:`.Window` class.
  1121. Note that left/right offsets only make sense if line wrapping is disabled.
  1122. """
  1123. def __init__(
  1124. self,
  1125. top: int | Callable[[], int] = 0,
  1126. bottom: int | Callable[[], int] = 0,
  1127. left: int | Callable[[], int] = 0,
  1128. right: int | Callable[[], int] = 0,
  1129. ) -> None:
  1130. self._top = top
  1131. self._bottom = bottom
  1132. self._left = left
  1133. self._right = right
  1134. @property
  1135. def top(self) -> int:
  1136. return to_int(self._top)
  1137. @property
  1138. def bottom(self) -> int:
  1139. return to_int(self._bottom)
  1140. @property
  1141. def left(self) -> int:
  1142. return to_int(self._left)
  1143. @property
  1144. def right(self) -> int:
  1145. return to_int(self._right)
  1146. def __repr__(self) -> str:
  1147. return "ScrollOffsets(top={!r}, bottom={!r}, left={!r}, right={!r})".format(
  1148. self._top,
  1149. self._bottom,
  1150. self._left,
  1151. self._right,
  1152. )
  1153. class ColorColumn:
  1154. """
  1155. Column for a :class:`.Window` to be colored.
  1156. """
  1157. def __init__(self, position: int, style: str = "class:color-column") -> None:
  1158. self.position = position
  1159. self.style = style
  1160. _in_insert_mode = vi_insert_mode | emacs_insert_mode
  1161. class WindowAlign(Enum):
  1162. """
  1163. Alignment of the Window content.
  1164. Note that this is different from `HorizontalAlign` and `VerticalAlign`,
  1165. which are used for the alignment of the child containers in respectively
  1166. `VSplit` and `HSplit`.
  1167. """
  1168. LEFT = "LEFT"
  1169. RIGHT = "RIGHT"
  1170. CENTER = "CENTER"
  1171. class Window(Container):
  1172. """
  1173. Container that holds a control.
  1174. :param content: :class:`.UIControl` instance.
  1175. :param width: :class:`.Dimension` instance or callable.
  1176. :param height: :class:`.Dimension` instance or callable.
  1177. :param z_index: When specified, this can be used to bring element in front
  1178. of floating elements.
  1179. :param dont_extend_width: When `True`, don't take up more width then the
  1180. preferred width reported by the control.
  1181. :param dont_extend_height: When `True`, don't take up more width then the
  1182. preferred height reported by the control.
  1183. :param ignore_content_width: A `bool` or :class:`.Filter` instance. Ignore
  1184. the :class:`.UIContent` width when calculating the dimensions.
  1185. :param ignore_content_height: A `bool` or :class:`.Filter` instance. Ignore
  1186. the :class:`.UIContent` height when calculating the dimensions.
  1187. :param left_margins: A list of :class:`.Margin` instance to be displayed on
  1188. the left. For instance: :class:`~prompt_toolkit.layout.NumberedMargin`
  1189. can be one of them in order to show line numbers.
  1190. :param right_margins: Like `left_margins`, but on the other side.
  1191. :param scroll_offsets: :class:`.ScrollOffsets` instance, representing the
  1192. preferred amount of lines/columns to be always visible before/after the
  1193. cursor. When both top and bottom are a very high number, the cursor
  1194. will be centered vertically most of the time.
  1195. :param allow_scroll_beyond_bottom: A `bool` or
  1196. :class:`.Filter` instance. When True, allow scrolling so far, that the
  1197. top part of the content is not visible anymore, while there is still
  1198. empty space available at the bottom of the window. In the Vi editor for
  1199. instance, this is possible. You will see tildes while the top part of
  1200. the body is hidden.
  1201. :param wrap_lines: A `bool` or :class:`.Filter` instance. When True, don't
  1202. scroll horizontally, but wrap lines instead.
  1203. :param get_vertical_scroll: Callable that takes this window
  1204. instance as input and returns a preferred vertical scroll.
  1205. (When this is `None`, the scroll is only determined by the last and
  1206. current cursor position.)
  1207. :param get_horizontal_scroll: Callable that takes this window
  1208. instance as input and returns a preferred vertical scroll.
  1209. :param always_hide_cursor: A `bool` or
  1210. :class:`.Filter` instance. When True, never display the cursor, even
  1211. when the user control specifies a cursor position.
  1212. :param cursorline: A `bool` or :class:`.Filter` instance. When True,
  1213. display a cursorline.
  1214. :param cursorcolumn: A `bool` or :class:`.Filter` instance. When True,
  1215. display a cursorcolumn.
  1216. :param colorcolumns: A list of :class:`.ColorColumn` instances that
  1217. describe the columns to be highlighted, or a callable that returns such
  1218. a list.
  1219. :param align: :class:`.WindowAlign` value or callable that returns an
  1220. :class:`.WindowAlign` value. alignment of content.
  1221. :param style: A style string. Style to be applied to all the cells in this
  1222. window. (This can be a callable that returns a string.)
  1223. :param char: (string) Character to be used for filling the background. This
  1224. can also be a callable that returns a character.
  1225. :param get_line_prefix: None or a callable that returns formatted text to
  1226. be inserted before a line. It takes a line number (int) and a
  1227. wrap_count and returns formatted text. This can be used for
  1228. implementation of line continuations, things like Vim "breakindent" and
  1229. so on.
  1230. """
  1231. def __init__(
  1232. self,
  1233. content: UIControl | None = None,
  1234. width: AnyDimension = None,
  1235. height: AnyDimension = None,
  1236. z_index: int | None = None,
  1237. dont_extend_width: FilterOrBool = False,
  1238. dont_extend_height: FilterOrBool = False,
  1239. ignore_content_width: FilterOrBool = False,
  1240. ignore_content_height: FilterOrBool = False,
  1241. left_margins: Sequence[Margin] | None = None,
  1242. right_margins: Sequence[Margin] | None = None,
  1243. scroll_offsets: ScrollOffsets | None = None,
  1244. allow_scroll_beyond_bottom: FilterOrBool = False,
  1245. wrap_lines: FilterOrBool = False,
  1246. get_vertical_scroll: Callable[[Window], int] | None = None,
  1247. get_horizontal_scroll: Callable[[Window], int] | None = None,
  1248. always_hide_cursor: FilterOrBool = False,
  1249. cursorline: FilterOrBool = False,
  1250. cursorcolumn: FilterOrBool = False,
  1251. colorcolumns: (
  1252. None | list[ColorColumn] | Callable[[], list[ColorColumn]]
  1253. ) = None,
  1254. align: WindowAlign | Callable[[], WindowAlign] = WindowAlign.LEFT,
  1255. style: str | Callable[[], str] = "",
  1256. char: None | str | Callable[[], str] = None,
  1257. get_line_prefix: GetLinePrefixCallable | None = None,
  1258. ) -> None:
  1259. self.allow_scroll_beyond_bottom = to_filter(allow_scroll_beyond_bottom)
  1260. self.always_hide_cursor = to_filter(always_hide_cursor)
  1261. self.wrap_lines = to_filter(wrap_lines)
  1262. self.cursorline = to_filter(cursorline)
  1263. self.cursorcolumn = to_filter(cursorcolumn)
  1264. self.content = content or DummyControl()
  1265. self.dont_extend_width = to_filter(dont_extend_width)
  1266. self.dont_extend_height = to_filter(dont_extend_height)
  1267. self.ignore_content_width = to_filter(ignore_content_width)
  1268. self.ignore_content_height = to_filter(ignore_content_height)
  1269. self.left_margins = left_margins or []
  1270. self.right_margins = right_margins or []
  1271. self.scroll_offsets = scroll_offsets or ScrollOffsets()
  1272. self.get_vertical_scroll = get_vertical_scroll
  1273. self.get_horizontal_scroll = get_horizontal_scroll
  1274. self.colorcolumns = colorcolumns or []
  1275. self.align = align
  1276. self.style = style
  1277. self.char = char
  1278. self.get_line_prefix = get_line_prefix
  1279. self.width = width
  1280. self.height = height
  1281. self.z_index = z_index
  1282. # Cache for the screens generated by the margin.
  1283. self._ui_content_cache: SimpleCache[
  1284. tuple[int, int, int], UIContent
  1285. ] = SimpleCache(maxsize=8)
  1286. self._margin_width_cache: SimpleCache[tuple[Margin, int], int] = SimpleCache(
  1287. maxsize=1
  1288. )
  1289. self.reset()
  1290. def __repr__(self) -> str:
  1291. return "Window(content=%r)" % self.content
  1292. def reset(self) -> None:
  1293. self.content.reset()
  1294. #: Scrolling position of the main content.
  1295. self.vertical_scroll = 0
  1296. self.horizontal_scroll = 0
  1297. # Vertical scroll 2: this is the vertical offset that a line is
  1298. # scrolled if a single line (the one that contains the cursor) consumes
  1299. # all of the vertical space.
  1300. self.vertical_scroll_2 = 0
  1301. #: Keep render information (mappings between buffer input and render
  1302. #: output.)
  1303. self.render_info: WindowRenderInfo | None = None
  1304. def _get_margin_width(self, margin: Margin) -> int:
  1305. """
  1306. Return the width for this margin.
  1307. (Calculate only once per render time.)
  1308. """
  1309. # Margin.get_width, needs to have a UIContent instance.
  1310. def get_ui_content() -> UIContent:
  1311. return self._get_ui_content(width=0, height=0)
  1312. def get_width() -> int:
  1313. return margin.get_width(get_ui_content)
  1314. key = (margin, get_app().render_counter)
  1315. return self._margin_width_cache.get(key, get_width)
  1316. def _get_total_margin_width(self) -> int:
  1317. """
  1318. Calculate and return the width of the margin (left + right).
  1319. """
  1320. return sum(self._get_margin_width(m) for m in self.left_margins) + sum(
  1321. self._get_margin_width(m) for m in self.right_margins
  1322. )
  1323. def preferred_width(self, max_available_width: int) -> Dimension:
  1324. """
  1325. Calculate the preferred width for this window.
  1326. """
  1327. def preferred_content_width() -> int | None:
  1328. """Content width: is only calculated if no exact width for the
  1329. window was given."""
  1330. if self.ignore_content_width():
  1331. return None
  1332. # Calculate the width of the margin.
  1333. total_margin_width = self._get_total_margin_width()
  1334. # Window of the content. (Can be `None`.)
  1335. preferred_width = self.content.preferred_width(
  1336. max_available_width - total_margin_width
  1337. )
  1338. if preferred_width is not None:
  1339. # Include width of the margins.
  1340. preferred_width += total_margin_width
  1341. return preferred_width
  1342. # Merge.
  1343. return self._merge_dimensions(
  1344. dimension=to_dimension(self.width),
  1345. get_preferred=preferred_content_width,
  1346. dont_extend=self.dont_extend_width(),
  1347. )
  1348. def preferred_height(self, width: int, max_available_height: int) -> Dimension:
  1349. """
  1350. Calculate the preferred height for this window.
  1351. """
  1352. def preferred_content_height() -> int | None:
  1353. """Content height: is only calculated if no exact height for the
  1354. window was given."""
  1355. if self.ignore_content_height():
  1356. return None
  1357. total_margin_width = self._get_total_margin_width()
  1358. wrap_lines = self.wrap_lines()
  1359. return self.content.preferred_height(
  1360. width - total_margin_width,
  1361. max_available_height,
  1362. wrap_lines,
  1363. self.get_line_prefix,
  1364. )
  1365. return self._merge_dimensions(
  1366. dimension=to_dimension(self.height),
  1367. get_preferred=preferred_content_height,
  1368. dont_extend=self.dont_extend_height(),
  1369. )
  1370. @staticmethod
  1371. def _merge_dimensions(
  1372. dimension: Dimension | None,
  1373. get_preferred: Callable[[], int | None],
  1374. dont_extend: bool = False,
  1375. ) -> Dimension:
  1376. """
  1377. Take the Dimension from this `Window` class and the received preferred
  1378. size from the `UIControl` and return a `Dimension` to report to the
  1379. parent container.
  1380. """
  1381. dimension = dimension or Dimension()
  1382. # When a preferred dimension was explicitly given to the Window,
  1383. # ignore the UIControl.
  1384. preferred: int | None
  1385. if dimension.preferred_specified:
  1386. preferred = dimension.preferred
  1387. else:
  1388. # Otherwise, calculate the preferred dimension from the UI control
  1389. # content.
  1390. preferred = get_preferred()
  1391. # When a 'preferred' dimension is given by the UIControl, make sure
  1392. # that it stays within the bounds of the Window.
  1393. if preferred is not None:
  1394. if dimension.max_specified:
  1395. preferred = min(preferred, dimension.max)
  1396. if dimension.min_specified:
  1397. preferred = max(preferred, dimension.min)
  1398. # When a `dont_extend` flag has been given, use the preferred dimension
  1399. # also as the max dimension.
  1400. max_: int | None
  1401. min_: int | None
  1402. if dont_extend and preferred is not None:
  1403. max_ = min(dimension.max, preferred)
  1404. else:
  1405. max_ = dimension.max if dimension.max_specified else None
  1406. min_ = dimension.min if dimension.min_specified else None
  1407. return Dimension(
  1408. min=min_, max=max_, preferred=preferred, weight=dimension.weight
  1409. )
  1410. def _get_ui_content(self, width: int, height: int) -> UIContent:
  1411. """
  1412. Create a `UIContent` instance.
  1413. """
  1414. def get_content() -> UIContent:
  1415. return self.content.create_content(width=width, height=height)
  1416. key = (get_app().render_counter, width, height)
  1417. return self._ui_content_cache.get(key, get_content)
  1418. def _get_digraph_char(self) -> str | None:
  1419. "Return `False`, or the Digraph symbol to be used."
  1420. app = get_app()
  1421. if app.quoted_insert:
  1422. return "^"
  1423. if app.vi_state.waiting_for_digraph:
  1424. if app.vi_state.digraph_symbol1:
  1425. return app.vi_state.digraph_symbol1
  1426. return "?"
  1427. return None
  1428. def write_to_screen(
  1429. self,
  1430. screen: Screen,
  1431. mouse_handlers: MouseHandlers,
  1432. write_position: WritePosition,
  1433. parent_style: str,
  1434. erase_bg: bool,
  1435. z_index: int | None,
  1436. ) -> None:
  1437. """
  1438. Write window to screen. This renders the user control, the margins and
  1439. copies everything over to the absolute position at the given screen.
  1440. """
  1441. # If dont_extend_width/height was given. Then reduce width/height in
  1442. # WritePosition if the parent wanted us to paint in a bigger area.
  1443. # (This happens if this window is bundled with another window in a
  1444. # HSplit/VSplit, but with different size requirements.)
  1445. write_position = WritePosition(
  1446. xpos=write_position.xpos,
  1447. ypos=write_position.ypos,
  1448. width=write_position.width,
  1449. height=write_position.height,
  1450. )
  1451. if self.dont_extend_width():
  1452. write_position.width = min(
  1453. write_position.width,
  1454. self.preferred_width(write_position.width).preferred,
  1455. )
  1456. if self.dont_extend_height():
  1457. write_position.height = min(
  1458. write_position.height,
  1459. self.preferred_height(
  1460. write_position.width, write_position.height
  1461. ).preferred,
  1462. )
  1463. # Draw
  1464. z_index = z_index if self.z_index is None else self.z_index
  1465. draw_func = partial(
  1466. self._write_to_screen_at_index,
  1467. screen,
  1468. mouse_handlers,
  1469. write_position,
  1470. parent_style,
  1471. erase_bg,
  1472. )
  1473. if z_index is None or z_index <= 0:
  1474. # When no z_index is given, draw right away.
  1475. draw_func()
  1476. else:
  1477. # Otherwise, postpone.
  1478. screen.draw_with_z_index(z_index=z_index, draw_func=draw_func)
  1479. def _write_to_screen_at_index(
  1480. self,
  1481. screen: Screen,
  1482. mouse_handlers: MouseHandlers,
  1483. write_position: WritePosition,
  1484. parent_style: str,
  1485. erase_bg: bool,
  1486. ) -> None:
  1487. # Don't bother writing invisible windows.
  1488. # (We save some time, but also avoid applying last-line styling.)
  1489. if write_position.height <= 0 or write_position.width <= 0:
  1490. return
  1491. # Calculate margin sizes.
  1492. left_margin_widths = [self._get_margin_width(m) for m in self.left_margins]
  1493. right_margin_widths = [self._get_margin_width(m) for m in self.right_margins]
  1494. total_margin_width = sum(left_margin_widths + right_margin_widths)
  1495. # Render UserControl.
  1496. ui_content = self.content.create_content(
  1497. write_position.width - total_margin_width, write_position.height
  1498. )
  1499. assert isinstance(ui_content, UIContent)
  1500. # Scroll content.
  1501. wrap_lines = self.wrap_lines()
  1502. self._scroll(
  1503. ui_content, write_position.width - total_margin_width, write_position.height
  1504. )
  1505. # Erase background and fill with `char`.
  1506. self._fill_bg(screen, write_position, erase_bg)
  1507. # Resolve `align` attribute.
  1508. align = self.align() if callable(self.align) else self.align
  1509. # Write body
  1510. visible_line_to_row_col, rowcol_to_yx = self._copy_body(
  1511. ui_content,
  1512. screen,
  1513. write_position,
  1514. sum(left_margin_widths),
  1515. write_position.width - total_margin_width,
  1516. self.vertical_scroll,
  1517. self.horizontal_scroll,
  1518. wrap_lines=wrap_lines,
  1519. highlight_lines=True,
  1520. vertical_scroll_2=self.vertical_scroll_2,
  1521. always_hide_cursor=self.always_hide_cursor(),
  1522. has_focus=get_app().layout.current_control == self.content,
  1523. align=align,
  1524. get_line_prefix=self.get_line_prefix,
  1525. )
  1526. # Remember render info. (Set before generating the margins. They need this.)
  1527. x_offset = write_position.xpos + sum(left_margin_widths)
  1528. y_offset = write_position.ypos
  1529. render_info = WindowRenderInfo(
  1530. window=self,
  1531. ui_content=ui_content,
  1532. horizontal_scroll=self.horizontal_scroll,
  1533. vertical_scroll=self.vertical_scroll,
  1534. window_width=write_position.width - total_margin_width,
  1535. window_height=write_position.height,
  1536. configured_scroll_offsets=self.scroll_offsets,
  1537. visible_line_to_row_col=visible_line_to_row_col,
  1538. rowcol_to_yx=rowcol_to_yx,
  1539. x_offset=x_offset,
  1540. y_offset=y_offset,
  1541. wrap_lines=wrap_lines,
  1542. )
  1543. self.render_info = render_info
  1544. # Set mouse handlers.
  1545. def mouse_handler(mouse_event: MouseEvent) -> NotImplementedOrNone:
  1546. """
  1547. Wrapper around the mouse_handler of the `UIControl` that turns
  1548. screen coordinates into line coordinates.
  1549. Returns `NotImplemented` if no UI invalidation should be done.
  1550. """
  1551. # Don't handle mouse events outside of the current modal part of
  1552. # the UI.
  1553. if self not in get_app().layout.walk_through_modal_area():
  1554. return NotImplemented
  1555. # Find row/col position first.
  1556. yx_to_rowcol = {v: k for k, v in rowcol_to_yx.items()}
  1557. y = mouse_event.position.y
  1558. x = mouse_event.position.x
  1559. # If clicked below the content area, look for a position in the
  1560. # last line instead.
  1561. max_y = write_position.ypos + len(visible_line_to_row_col) - 1
  1562. y = min(max_y, y)
  1563. result: NotImplementedOrNone
  1564. while x >= 0:
  1565. try:
  1566. row, col = yx_to_rowcol[y, x]
  1567. except KeyError:
  1568. # Try again. (When clicking on the right side of double
  1569. # width characters, or on the right side of the input.)
  1570. x -= 1
  1571. else:
  1572. # Found position, call handler of UIControl.
  1573. result = self.content.mouse_handler(
  1574. MouseEvent(
  1575. position=Point(x=col, y=row),
  1576. event_type=mouse_event.event_type,
  1577. button=mouse_event.button,
  1578. modifiers=mouse_event.modifiers,
  1579. )
  1580. )
  1581. break
  1582. else:
  1583. # nobreak.
  1584. # (No x/y coordinate found for the content. This happens in
  1585. # case of a DummyControl, that does not have any content.
  1586. # Report (0,0) instead.)
  1587. result = self.content.mouse_handler(
  1588. MouseEvent(
  1589. position=Point(x=0, y=0),
  1590. event_type=mouse_event.event_type,
  1591. button=mouse_event.button,
  1592. modifiers=mouse_event.modifiers,
  1593. )
  1594. )
  1595. # If it returns NotImplemented, handle it here.
  1596. if result == NotImplemented:
  1597. result = self._mouse_handler(mouse_event)
  1598. return result
  1599. mouse_handlers.set_mouse_handler_for_range(
  1600. x_min=write_position.xpos + sum(left_margin_widths),
  1601. x_max=write_position.xpos + write_position.width - total_margin_width,
  1602. y_min=write_position.ypos,
  1603. y_max=write_position.ypos + write_position.height,
  1604. handler=mouse_handler,
  1605. )
  1606. # Render and copy margins.
  1607. move_x = 0
  1608. def render_margin(m: Margin, width: int) -> UIContent:
  1609. "Render margin. Return `Screen`."
  1610. # Retrieve margin fragments.
  1611. fragments = m.create_margin(render_info, width, write_position.height)
  1612. # Turn it into a UIContent object.
  1613. # already rendered those fragments using this size.)
  1614. return FormattedTextControl(fragments).create_content(
  1615. width + 1, write_position.height
  1616. )
  1617. for m, width in zip(self.left_margins, left_margin_widths):
  1618. if width > 0: # (ConditionalMargin returns a zero width. -- Don't render.)
  1619. # Create screen for margin.
  1620. margin_content = render_margin(m, width)
  1621. # Copy and shift X.
  1622. self._copy_margin(margin_content, screen, write_position, move_x, width)
  1623. move_x += width
  1624. move_x = write_position.width - sum(right_margin_widths)
  1625. for m, width in zip(self.right_margins, right_margin_widths):
  1626. # Create screen for margin.
  1627. margin_content = render_margin(m, width)
  1628. # Copy and shift X.
  1629. self._copy_margin(margin_content, screen, write_position, move_x, width)
  1630. move_x += width
  1631. # Apply 'self.style'
  1632. self._apply_style(screen, write_position, parent_style)
  1633. # Tell the screen that this user control has been painted at this
  1634. # position.
  1635. screen.visible_windows_to_write_positions[self] = write_position
  1636. def _copy_body(
  1637. self,
  1638. ui_content: UIContent,
  1639. new_screen: Screen,
  1640. write_position: WritePosition,
  1641. move_x: int,
  1642. width: int,
  1643. vertical_scroll: int = 0,
  1644. horizontal_scroll: int = 0,
  1645. wrap_lines: bool = False,
  1646. highlight_lines: bool = False,
  1647. vertical_scroll_2: int = 0,
  1648. always_hide_cursor: bool = False,
  1649. has_focus: bool = False,
  1650. align: WindowAlign = WindowAlign.LEFT,
  1651. get_line_prefix: Callable[[int, int], AnyFormattedText] | None = None,
  1652. ) -> tuple[dict[int, tuple[int, int]], dict[tuple[int, int], tuple[int, int]]]:
  1653. """
  1654. Copy the UIContent into the output screen.
  1655. Return (visible_line_to_row_col, rowcol_to_yx) tuple.
  1656. :param get_line_prefix: None or a callable that takes a line number
  1657. (int) and a wrap_count (int) and returns formatted text.
  1658. """
  1659. xpos = write_position.xpos + move_x
  1660. ypos = write_position.ypos
  1661. line_count = ui_content.line_count
  1662. new_buffer = new_screen.data_buffer
  1663. empty_char = _CHAR_CACHE["", ""]
  1664. # Map visible line number to (row, col) of input.
  1665. # 'col' will always be zero if line wrapping is off.
  1666. visible_line_to_row_col: dict[int, tuple[int, int]] = {}
  1667. # Maps (row, col) from the input to (y, x) screen coordinates.
  1668. rowcol_to_yx: dict[tuple[int, int], tuple[int, int]] = {}
  1669. def copy_line(
  1670. line: StyleAndTextTuples,
  1671. lineno: int,
  1672. x: int,
  1673. y: int,
  1674. is_input: bool = False,
  1675. ) -> tuple[int, int]:
  1676. """
  1677. Copy over a single line to the output screen. This can wrap over
  1678. multiple lines in the output. It will call the prefix (prompt)
  1679. function before every line.
  1680. """
  1681. if is_input:
  1682. current_rowcol_to_yx = rowcol_to_yx
  1683. else:
  1684. current_rowcol_to_yx = {} # Throwaway dictionary.
  1685. # Draw line prefix.
  1686. if is_input and get_line_prefix:
  1687. prompt = to_formatted_text(get_line_prefix(lineno, 0))
  1688. x, y = copy_line(prompt, lineno, x, y, is_input=False)
  1689. # Scroll horizontally.
  1690. skipped = 0 # Characters skipped because of horizontal scrolling.
  1691. if horizontal_scroll and is_input:
  1692. h_scroll = horizontal_scroll
  1693. line = explode_text_fragments(line)
  1694. while h_scroll > 0 and line:
  1695. h_scroll -= get_cwidth(line[0][1])
  1696. skipped += 1
  1697. del line[:1] # Remove first character.
  1698. x -= h_scroll # When scrolling over double width character,
  1699. # this can end up being negative.
  1700. # Align this line. (Note that this doesn't work well when we use
  1701. # get_line_prefix and that function returns variable width prefixes.)
  1702. if align == WindowAlign.CENTER:
  1703. line_width = fragment_list_width(line)
  1704. if line_width < width:
  1705. x += (width - line_width) // 2
  1706. elif align == WindowAlign.RIGHT:
  1707. line_width = fragment_list_width(line)
  1708. if line_width < width:
  1709. x += width - line_width
  1710. col = 0
  1711. wrap_count = 0
  1712. for style, text, *_ in line:
  1713. new_buffer_row = new_buffer[y + ypos]
  1714. # Remember raw VT escape sequences. (E.g. FinalTerm's
  1715. # escape sequences.)
  1716. if "[ZeroWidthEscape]" in style:
  1717. new_screen.zero_width_escapes[y + ypos][x + xpos] += text
  1718. continue
  1719. for c in text:
  1720. char = _CHAR_CACHE[c, style]
  1721. char_width = char.width
  1722. # Wrap when the line width is exceeded.
  1723. if wrap_lines and x + char_width > width:
  1724. visible_line_to_row_col[y + 1] = (
  1725. lineno,
  1726. visible_line_to_row_col[y][1] + x,
  1727. )
  1728. y += 1
  1729. wrap_count += 1
  1730. x = 0
  1731. # Insert line prefix (continuation prompt).
  1732. if is_input and get_line_prefix:
  1733. prompt = to_formatted_text(
  1734. get_line_prefix(lineno, wrap_count)
  1735. )
  1736. x, y = copy_line(prompt, lineno, x, y, is_input=False)
  1737. new_buffer_row = new_buffer[y + ypos]
  1738. if y >= write_position.height:
  1739. return x, y # Break out of all for loops.
  1740. # Set character in screen and shift 'x'.
  1741. if x >= 0 and y >= 0 and x < width:
  1742. new_buffer_row[x + xpos] = char
  1743. # When we print a multi width character, make sure
  1744. # to erase the neighbors positions in the screen.
  1745. # (The empty string if different from everything,
  1746. # so next redraw this cell will repaint anyway.)
  1747. if char_width > 1:
  1748. for i in range(1, char_width):
  1749. new_buffer_row[x + xpos + i] = empty_char
  1750. # If this is a zero width characters, then it's
  1751. # probably part of a decomposed unicode character.
  1752. # See: https://en.wikipedia.org/wiki/Unicode_equivalence
  1753. # Merge it in the previous cell.
  1754. elif char_width == 0:
  1755. # Handle all character widths. If the previous
  1756. # character is a multiwidth character, then
  1757. # merge it two positions back.
  1758. for pw in [2, 1]: # Previous character width.
  1759. if (
  1760. x - pw >= 0
  1761. and new_buffer_row[x + xpos - pw].width == pw
  1762. ):
  1763. prev_char = new_buffer_row[x + xpos - pw]
  1764. char2 = _CHAR_CACHE[
  1765. prev_char.char + c, prev_char.style
  1766. ]
  1767. new_buffer_row[x + xpos - pw] = char2
  1768. # Keep track of write position for each character.
  1769. current_rowcol_to_yx[lineno, col + skipped] = (
  1770. y + ypos,
  1771. x + xpos,
  1772. )
  1773. col += 1
  1774. x += char_width
  1775. return x, y
  1776. # Copy content.
  1777. def copy() -> int:
  1778. y = -vertical_scroll_2
  1779. lineno = vertical_scroll
  1780. while y < write_position.height and lineno < line_count:
  1781. # Take the next line and copy it in the real screen.
  1782. line = ui_content.get_line(lineno)
  1783. visible_line_to_row_col[y] = (lineno, horizontal_scroll)
  1784. # Copy margin and actual line.
  1785. x = 0
  1786. x, y = copy_line(line, lineno, x, y, is_input=True)
  1787. lineno += 1
  1788. y += 1
  1789. return y
  1790. copy()
  1791. def cursor_pos_to_screen_pos(row: int, col: int) -> Point:
  1792. "Translate row/col from UIContent to real Screen coordinates."
  1793. try:
  1794. y, x = rowcol_to_yx[row, col]
  1795. except KeyError:
  1796. # Normally this should never happen. (It is a bug, if it happens.)
  1797. # But to be sure, return (0, 0)
  1798. return Point(x=0, y=0)
  1799. # raise ValueError(
  1800. # 'Invalid position. row=%r col=%r, vertical_scroll=%r, '
  1801. # 'horizontal_scroll=%r, height=%r' %
  1802. # (row, col, vertical_scroll, horizontal_scroll, write_position.height))
  1803. else:
  1804. return Point(x=x, y=y)
  1805. # Set cursor and menu positions.
  1806. if ui_content.cursor_position:
  1807. screen_cursor_position = cursor_pos_to_screen_pos(
  1808. ui_content.cursor_position.y, ui_content.cursor_position.x
  1809. )
  1810. if has_focus:
  1811. new_screen.set_cursor_position(self, screen_cursor_position)
  1812. if always_hide_cursor:
  1813. new_screen.show_cursor = False
  1814. else:
  1815. new_screen.show_cursor = ui_content.show_cursor
  1816. self._highlight_digraph(new_screen)
  1817. if highlight_lines:
  1818. self._highlight_cursorlines(
  1819. new_screen,
  1820. screen_cursor_position,
  1821. xpos,
  1822. ypos,
  1823. width,
  1824. write_position.height,
  1825. )
  1826. # Draw input characters from the input processor queue.
  1827. if has_focus and ui_content.cursor_position:
  1828. self._show_key_processor_key_buffer(new_screen)
  1829. # Set menu position.
  1830. if ui_content.menu_position:
  1831. new_screen.set_menu_position(
  1832. self,
  1833. cursor_pos_to_screen_pos(
  1834. ui_content.menu_position.y, ui_content.menu_position.x
  1835. ),
  1836. )
  1837. # Update output screen height.
  1838. new_screen.height = max(new_screen.height, ypos + write_position.height)
  1839. return visible_line_to_row_col, rowcol_to_yx
  1840. def _fill_bg(
  1841. self, screen: Screen, write_position: WritePosition, erase_bg: bool
  1842. ) -> None:
  1843. """
  1844. Erase/fill the background.
  1845. (Useful for floats and when a `char` has been given.)
  1846. """
  1847. char: str | None
  1848. if callable(self.char):
  1849. char = self.char()
  1850. else:
  1851. char = self.char
  1852. if erase_bg or char:
  1853. wp = write_position
  1854. char_obj = _CHAR_CACHE[char or " ", ""]
  1855. for y in range(wp.ypos, wp.ypos + wp.height):
  1856. row = screen.data_buffer[y]
  1857. for x in range(wp.xpos, wp.xpos + wp.width):
  1858. row[x] = char_obj
  1859. def _apply_style(
  1860. self, new_screen: Screen, write_position: WritePosition, parent_style: str
  1861. ) -> None:
  1862. # Apply `self.style`.
  1863. style = parent_style + " " + to_str(self.style)
  1864. new_screen.fill_area(write_position, style=style, after=False)
  1865. # Apply the 'last-line' class to the last line of each Window. This can
  1866. # be used to apply an 'underline' to the user control.
  1867. wp = WritePosition(
  1868. write_position.xpos,
  1869. write_position.ypos + write_position.height - 1,
  1870. write_position.width,
  1871. 1,
  1872. )
  1873. new_screen.fill_area(wp, "class:last-line", after=True)
  1874. def _highlight_digraph(self, new_screen: Screen) -> None:
  1875. """
  1876. When we are in Vi digraph mode, put a question mark underneath the
  1877. cursor.
  1878. """
  1879. digraph_char = self._get_digraph_char()
  1880. if digraph_char:
  1881. cpos = new_screen.get_cursor_position(self)
  1882. new_screen.data_buffer[cpos.y][cpos.x] = _CHAR_CACHE[
  1883. digraph_char, "class:digraph"
  1884. ]
  1885. def _show_key_processor_key_buffer(self, new_screen: Screen) -> None:
  1886. """
  1887. When the user is typing a key binding that consists of several keys,
  1888. display the last pressed key if the user is in insert mode and the key
  1889. is meaningful to be displayed.
  1890. E.g. Some people want to bind 'jj' to escape in Vi insert mode. But the
  1891. first 'j' needs to be displayed in order to get some feedback.
  1892. """
  1893. app = get_app()
  1894. key_buffer = app.key_processor.key_buffer
  1895. if key_buffer and _in_insert_mode() and not app.is_done:
  1896. # The textual data for the given key. (Can be a VT100 escape
  1897. # sequence.)
  1898. data = key_buffer[-1].data
  1899. # Display only if this is a 1 cell width character.
  1900. if get_cwidth(data) == 1:
  1901. cpos = new_screen.get_cursor_position(self)
  1902. new_screen.data_buffer[cpos.y][cpos.x] = _CHAR_CACHE[
  1903. data, "class:partial-key-binding"
  1904. ]
  1905. def _highlight_cursorlines(
  1906. self, new_screen: Screen, cpos: Point, x: int, y: int, width: int, height: int
  1907. ) -> None:
  1908. """
  1909. Highlight cursor row/column.
  1910. """
  1911. cursor_line_style = " class:cursor-line "
  1912. cursor_column_style = " class:cursor-column "
  1913. data_buffer = new_screen.data_buffer
  1914. # Highlight cursor line.
  1915. if self.cursorline():
  1916. row = data_buffer[cpos.y]
  1917. for x in range(x, x + width):
  1918. original_char = row[x]
  1919. row[x] = _CHAR_CACHE[
  1920. original_char.char, original_char.style + cursor_line_style
  1921. ]
  1922. # Highlight cursor column.
  1923. if self.cursorcolumn():
  1924. for y2 in range(y, y + height):
  1925. row = data_buffer[y2]
  1926. original_char = row[cpos.x]
  1927. row[cpos.x] = _CHAR_CACHE[
  1928. original_char.char, original_char.style + cursor_column_style
  1929. ]
  1930. # Highlight color columns
  1931. colorcolumns = self.colorcolumns
  1932. if callable(colorcolumns):
  1933. colorcolumns = colorcolumns()
  1934. for cc in colorcolumns:
  1935. assert isinstance(cc, ColorColumn)
  1936. column = cc.position
  1937. if column < x + width: # Only draw when visible.
  1938. color_column_style = " " + cc.style
  1939. for y2 in range(y, y + height):
  1940. row = data_buffer[y2]
  1941. original_char = row[column + x]
  1942. row[column + x] = _CHAR_CACHE[
  1943. original_char.char, original_char.style + color_column_style
  1944. ]
  1945. def _copy_margin(
  1946. self,
  1947. margin_content: UIContent,
  1948. new_screen: Screen,
  1949. write_position: WritePosition,
  1950. move_x: int,
  1951. width: int,
  1952. ) -> None:
  1953. """
  1954. Copy characters from the margin screen to the real screen.
  1955. """
  1956. xpos = write_position.xpos + move_x
  1957. ypos = write_position.ypos
  1958. margin_write_position = WritePosition(xpos, ypos, width, write_position.height)
  1959. self._copy_body(margin_content, new_screen, margin_write_position, 0, width)
  1960. def _scroll(self, ui_content: UIContent, width: int, height: int) -> None:
  1961. """
  1962. Scroll body. Ensure that the cursor is visible.
  1963. """
  1964. if self.wrap_lines():
  1965. func = self._scroll_when_linewrapping
  1966. else:
  1967. func = self._scroll_without_linewrapping
  1968. func(ui_content, width, height)
  1969. def _scroll_when_linewrapping(
  1970. self, ui_content: UIContent, width: int, height: int
  1971. ) -> None:
  1972. """
  1973. Scroll to make sure the cursor position is visible and that we maintain
  1974. the requested scroll offset.
  1975. Set `self.horizontal_scroll/vertical_scroll`.
  1976. """
  1977. scroll_offsets_bottom = self.scroll_offsets.bottom
  1978. scroll_offsets_top = self.scroll_offsets.top
  1979. # We don't have horizontal scrolling.
  1980. self.horizontal_scroll = 0
  1981. def get_line_height(lineno: int) -> int:
  1982. return ui_content.get_height_for_line(lineno, width, self.get_line_prefix)
  1983. # When there is no space, reset `vertical_scroll_2` to zero and abort.
  1984. # This can happen if the margin is bigger than the window width.
  1985. # Otherwise the text height will become "infinite" (a big number) and
  1986. # the copy_line will spend a huge amount of iterations trying to render
  1987. # nothing.
  1988. if width <= 0:
  1989. self.vertical_scroll = ui_content.cursor_position.y
  1990. self.vertical_scroll_2 = 0
  1991. return
  1992. # If the current line consumes more than the whole window height,
  1993. # then we have to scroll vertically inside this line. (We don't take
  1994. # the scroll offsets into account for this.)
  1995. # Also, ignore the scroll offsets in this case. Just set the vertical
  1996. # scroll to this line.
  1997. line_height = get_line_height(ui_content.cursor_position.y)
  1998. if line_height > height - scroll_offsets_top:
  1999. # Calculate the height of the text before the cursor (including
  2000. # line prefixes).
  2001. text_before_height = ui_content.get_height_for_line(
  2002. ui_content.cursor_position.y,
  2003. width,
  2004. self.get_line_prefix,
  2005. slice_stop=ui_content.cursor_position.x,
  2006. )
  2007. # Adjust scroll offset.
  2008. self.vertical_scroll = ui_content.cursor_position.y
  2009. self.vertical_scroll_2 = min(
  2010. text_before_height - 1, # Keep the cursor visible.
  2011. line_height
  2012. - height, # Avoid blank lines at the bottom when scrolling up again.
  2013. self.vertical_scroll_2,
  2014. )
  2015. self.vertical_scroll_2 = max(
  2016. 0, text_before_height - height, self.vertical_scroll_2
  2017. )
  2018. return
  2019. else:
  2020. self.vertical_scroll_2 = 0
  2021. # Current line doesn't consume the whole height. Take scroll offsets into account.
  2022. def get_min_vertical_scroll() -> int:
  2023. # Make sure that the cursor line is not below the bottom.
  2024. # (Calculate how many lines can be shown between the cursor and the .)
  2025. used_height = 0
  2026. prev_lineno = ui_content.cursor_position.y
  2027. for lineno in range(ui_content.cursor_position.y, -1, -1):
  2028. used_height += get_line_height(lineno)
  2029. if used_height > height - scroll_offsets_bottom:
  2030. return prev_lineno
  2031. else:
  2032. prev_lineno = lineno
  2033. return 0
  2034. def get_max_vertical_scroll() -> int:
  2035. # Make sure that the cursor line is not above the top.
  2036. prev_lineno = ui_content.cursor_position.y
  2037. used_height = 0
  2038. for lineno in range(ui_content.cursor_position.y - 1, -1, -1):
  2039. used_height += get_line_height(lineno)
  2040. if used_height > scroll_offsets_top:
  2041. return prev_lineno
  2042. else:
  2043. prev_lineno = lineno
  2044. return prev_lineno
  2045. def get_topmost_visible() -> int:
  2046. """
  2047. Calculate the upper most line that can be visible, while the bottom
  2048. is still visible. We should not allow scroll more than this if
  2049. `allow_scroll_beyond_bottom` is false.
  2050. """
  2051. prev_lineno = ui_content.line_count - 1
  2052. used_height = 0
  2053. for lineno in range(ui_content.line_count - 1, -1, -1):
  2054. used_height += get_line_height(lineno)
  2055. if used_height > height:
  2056. return prev_lineno
  2057. else:
  2058. prev_lineno = lineno
  2059. return prev_lineno
  2060. # Scroll vertically. (Make sure that the whole line which contains the
  2061. # cursor is visible.
  2062. topmost_visible = get_topmost_visible()
  2063. # Note: the `min(topmost_visible, ...)` is to make sure that we
  2064. # don't require scrolling up because of the bottom scroll offset,
  2065. # when we are at the end of the document.
  2066. self.vertical_scroll = max(
  2067. self.vertical_scroll, min(topmost_visible, get_min_vertical_scroll())
  2068. )
  2069. self.vertical_scroll = min(self.vertical_scroll, get_max_vertical_scroll())
  2070. # Disallow scrolling beyond bottom?
  2071. if not self.allow_scroll_beyond_bottom():
  2072. self.vertical_scroll = min(self.vertical_scroll, topmost_visible)
  2073. def _scroll_without_linewrapping(
  2074. self, ui_content: UIContent, width: int, height: int
  2075. ) -> None:
  2076. """
  2077. Scroll to make sure the cursor position is visible and that we maintain
  2078. the requested scroll offset.
  2079. Set `self.horizontal_scroll/vertical_scroll`.
  2080. """
  2081. cursor_position = ui_content.cursor_position or Point(x=0, y=0)
  2082. # Without line wrapping, we will never have to scroll vertically inside
  2083. # a single line.
  2084. self.vertical_scroll_2 = 0
  2085. if ui_content.line_count == 0:
  2086. self.vertical_scroll = 0
  2087. self.horizontal_scroll = 0
  2088. return
  2089. else:
  2090. current_line_text = fragment_list_to_text(
  2091. ui_content.get_line(cursor_position.y)
  2092. )
  2093. def do_scroll(
  2094. current_scroll: int,
  2095. scroll_offset_start: int,
  2096. scroll_offset_end: int,
  2097. cursor_pos: int,
  2098. window_size: int,
  2099. content_size: int,
  2100. ) -> int:
  2101. "Scrolling algorithm. Used for both horizontal and vertical scrolling."
  2102. # Calculate the scroll offset to apply.
  2103. # This can obviously never be more than have the screen size. Also, when the
  2104. # cursor appears at the top or bottom, we don't apply the offset.
  2105. scroll_offset_start = int(
  2106. min(scroll_offset_start, window_size / 2, cursor_pos)
  2107. )
  2108. scroll_offset_end = int(
  2109. min(scroll_offset_end, window_size / 2, content_size - 1 - cursor_pos)
  2110. )
  2111. # Prevent negative scroll offsets.
  2112. if current_scroll < 0:
  2113. current_scroll = 0
  2114. # Scroll back if we scrolled to much and there's still space to show more of the document.
  2115. if (
  2116. not self.allow_scroll_beyond_bottom()
  2117. and current_scroll > content_size - window_size
  2118. ):
  2119. current_scroll = max(0, content_size - window_size)
  2120. # Scroll up if cursor is before visible part.
  2121. if current_scroll > cursor_pos - scroll_offset_start:
  2122. current_scroll = max(0, cursor_pos - scroll_offset_start)
  2123. # Scroll down if cursor is after visible part.
  2124. if current_scroll < (cursor_pos + 1) - window_size + scroll_offset_end:
  2125. current_scroll = (cursor_pos + 1) - window_size + scroll_offset_end
  2126. return current_scroll
  2127. # When a preferred scroll is given, take that first into account.
  2128. if self.get_vertical_scroll:
  2129. self.vertical_scroll = self.get_vertical_scroll(self)
  2130. assert isinstance(self.vertical_scroll, int)
  2131. if self.get_horizontal_scroll:
  2132. self.horizontal_scroll = self.get_horizontal_scroll(self)
  2133. assert isinstance(self.horizontal_scroll, int)
  2134. # Update horizontal/vertical scroll to make sure that the cursor
  2135. # remains visible.
  2136. offsets = self.scroll_offsets
  2137. self.vertical_scroll = do_scroll(
  2138. current_scroll=self.vertical_scroll,
  2139. scroll_offset_start=offsets.top,
  2140. scroll_offset_end=offsets.bottom,
  2141. cursor_pos=ui_content.cursor_position.y,
  2142. window_size=height,
  2143. content_size=ui_content.line_count,
  2144. )
  2145. if self.get_line_prefix:
  2146. current_line_prefix_width = fragment_list_width(
  2147. to_formatted_text(self.get_line_prefix(ui_content.cursor_position.y, 0))
  2148. )
  2149. else:
  2150. current_line_prefix_width = 0
  2151. self.horizontal_scroll = do_scroll(
  2152. current_scroll=self.horizontal_scroll,
  2153. scroll_offset_start=offsets.left,
  2154. scroll_offset_end=offsets.right,
  2155. cursor_pos=get_cwidth(current_line_text[: ui_content.cursor_position.x]),
  2156. window_size=width - current_line_prefix_width,
  2157. # We can only analyze the current line. Calculating the width off
  2158. # all the lines is too expensive.
  2159. content_size=max(
  2160. get_cwidth(current_line_text), self.horizontal_scroll + width
  2161. ),
  2162. )
  2163. def _mouse_handler(self, mouse_event: MouseEvent) -> NotImplementedOrNone:
  2164. """
  2165. Mouse handler. Called when the UI control doesn't handle this
  2166. particular event.
  2167. Return `NotImplemented` if nothing was done as a consequence of this
  2168. key binding (no UI invalidate required in that case).
  2169. """
  2170. if mouse_event.event_type == MouseEventType.SCROLL_DOWN:
  2171. self._scroll_down()
  2172. return None
  2173. elif mouse_event.event_type == MouseEventType.SCROLL_UP:
  2174. self._scroll_up()
  2175. return None
  2176. return NotImplemented
  2177. def _scroll_down(self) -> None:
  2178. "Scroll window down."
  2179. info = self.render_info
  2180. if info is None:
  2181. return
  2182. if self.vertical_scroll < info.content_height - info.window_height:
  2183. if info.cursor_position.y <= info.configured_scroll_offsets.top:
  2184. self.content.move_cursor_down()
  2185. self.vertical_scroll += 1
  2186. def _scroll_up(self) -> None:
  2187. "Scroll window up."
  2188. info = self.render_info
  2189. if info is None:
  2190. return
  2191. if info.vertical_scroll > 0:
  2192. # TODO: not entirely correct yet in case of line wrapping and long lines.
  2193. if (
  2194. info.cursor_position.y
  2195. >= info.window_height - 1 - info.configured_scroll_offsets.bottom
  2196. ):
  2197. self.content.move_cursor_up()
  2198. self.vertical_scroll -= 1
  2199. def get_key_bindings(self) -> KeyBindingsBase | None:
  2200. return self.content.get_key_bindings()
  2201. def get_children(self) -> list[Container]:
  2202. return []
  2203. class ConditionalContainer(Container):
  2204. """
  2205. Wrapper around any other container that can change the visibility. The
  2206. received `filter` determines whether the given container should be
  2207. displayed or not.
  2208. :param content: :class:`.Container` instance.
  2209. :param filter: :class:`.Filter` instance.
  2210. """
  2211. def __init__(self, content: AnyContainer, filter: FilterOrBool) -> None:
  2212. self.content = to_container(content)
  2213. self.filter = to_filter(filter)
  2214. def __repr__(self) -> str:
  2215. return f"ConditionalContainer({self.content!r}, filter={self.filter!r})"
  2216. def reset(self) -> None:
  2217. self.content.reset()
  2218. def preferred_width(self, max_available_width: int) -> Dimension:
  2219. if self.filter():
  2220. return self.content.preferred_width(max_available_width)
  2221. else:
  2222. return Dimension.zero()
  2223. def preferred_height(self, width: int, max_available_height: int) -> Dimension:
  2224. if self.filter():
  2225. return self.content.preferred_height(width, max_available_height)
  2226. else:
  2227. return Dimension.zero()
  2228. def write_to_screen(
  2229. self,
  2230. screen: Screen,
  2231. mouse_handlers: MouseHandlers,
  2232. write_position: WritePosition,
  2233. parent_style: str,
  2234. erase_bg: bool,
  2235. z_index: int | None,
  2236. ) -> None:
  2237. if self.filter():
  2238. return self.content.write_to_screen(
  2239. screen, mouse_handlers, write_position, parent_style, erase_bg, z_index
  2240. )
  2241. def get_children(self) -> list[Container]:
  2242. return [self.content]
  2243. class DynamicContainer(Container):
  2244. """
  2245. Container class that dynamically returns any Container.
  2246. :param get_container: Callable that returns a :class:`.Container` instance
  2247. or any widget with a ``__pt_container__`` method.
  2248. """
  2249. def __init__(self, get_container: Callable[[], AnyContainer]) -> None:
  2250. self.get_container = get_container
  2251. def _get_container(self) -> Container:
  2252. """
  2253. Return the current container object.
  2254. We call `to_container`, because `get_container` can also return a
  2255. widget with a ``__pt_container__`` method.
  2256. """
  2257. obj = self.get_container()
  2258. return to_container(obj)
  2259. def reset(self) -> None:
  2260. self._get_container().reset()
  2261. def preferred_width(self, max_available_width: int) -> Dimension:
  2262. return self._get_container().preferred_width(max_available_width)
  2263. def preferred_height(self, width: int, max_available_height: int) -> Dimension:
  2264. return self._get_container().preferred_height(width, max_available_height)
  2265. def write_to_screen(
  2266. self,
  2267. screen: Screen,
  2268. mouse_handlers: MouseHandlers,
  2269. write_position: WritePosition,
  2270. parent_style: str,
  2271. erase_bg: bool,
  2272. z_index: int | None,
  2273. ) -> None:
  2274. self._get_container().write_to_screen(
  2275. screen, mouse_handlers, write_position, parent_style, erase_bg, z_index
  2276. )
  2277. def is_modal(self) -> bool:
  2278. return False
  2279. def get_key_bindings(self) -> KeyBindingsBase | None:
  2280. # Key bindings will be collected when `layout.walk()` finds the child
  2281. # container.
  2282. return None
  2283. def get_children(self) -> list[Container]:
  2284. # Here we have to return the current active container itself, not its
  2285. # children. Otherwise, we run into issues where `layout.walk()` will
  2286. # never see an object of type `Window` if this contains a window. We
  2287. # can't/shouldn't proxy the "isinstance" check.
  2288. return [self._get_container()]
  2289. def to_container(container: AnyContainer) -> Container:
  2290. """
  2291. Make sure that the given object is a :class:`.Container`.
  2292. """
  2293. if isinstance(container, Container):
  2294. return container
  2295. elif hasattr(container, "__pt_container__"):
  2296. return to_container(container.__pt_container__())
  2297. else:
  2298. raise ValueError(f"Not a container object: {container!r}")
  2299. def to_window(container: AnyContainer) -> Window:
  2300. """
  2301. Make sure that the given argument is a :class:`.Window`.
  2302. """
  2303. if isinstance(container, Window):
  2304. return container
  2305. elif hasattr(container, "__pt_container__"):
  2306. return to_window(cast("MagicContainer", container).__pt_container__())
  2307. else:
  2308. raise ValueError(f"Not a Window object: {container!r}.")
  2309. def is_container(value: object) -> TypeGuard[AnyContainer]:
  2310. """
  2311. Checks whether the given value is a container object
  2312. (for use in assert statements).
  2313. """
  2314. if isinstance(value, Container):
  2315. return True
  2316. if hasattr(value, "__pt_container__"):
  2317. return is_container(cast("MagicContainer", value).__pt_container__())
  2318. return False