containers.py 97 KB

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