layout.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. from abc import ABC, abstractmethod
  2. from itertools import islice
  3. from operator import itemgetter
  4. from threading import RLock
  5. from typing import (
  6. TYPE_CHECKING,
  7. Dict,
  8. Iterable,
  9. List,
  10. NamedTuple,
  11. Optional,
  12. Sequence,
  13. Tuple,
  14. Union,
  15. )
  16. from ._ratio import ratio_resolve
  17. from .align import Align
  18. from .console import Console, ConsoleOptions, RenderableType, RenderResult
  19. from .highlighter import ReprHighlighter
  20. from .panel import Panel
  21. from .pretty import Pretty
  22. from .region import Region
  23. from .repr import Result, rich_repr
  24. from .segment import Segment
  25. from .style import StyleType
  26. if TYPE_CHECKING:
  27. from pip._vendor.rich.tree import Tree
  28. class LayoutRender(NamedTuple):
  29. """An individual layout render."""
  30. region: Region
  31. render: List[List[Segment]]
  32. RegionMap = Dict["Layout", Region]
  33. RenderMap = Dict["Layout", LayoutRender]
  34. class LayoutError(Exception):
  35. """Layout related error."""
  36. class NoSplitter(LayoutError):
  37. """Requested splitter does not exist."""
  38. class _Placeholder:
  39. """An internal renderable used as a Layout placeholder."""
  40. highlighter = ReprHighlighter()
  41. def __init__(self, layout: "Layout", style: StyleType = "") -> None:
  42. self.layout = layout
  43. self.style = style
  44. def __rich_console__(
  45. self, console: Console, options: ConsoleOptions
  46. ) -> RenderResult:
  47. width = options.max_width
  48. height = options.height or options.size.height
  49. layout = self.layout
  50. title = (
  51. f"{layout.name!r} ({width} x {height})"
  52. if layout.name
  53. else f"({width} x {height})"
  54. )
  55. yield Panel(
  56. Align.center(Pretty(layout), vertical="middle"),
  57. style=self.style,
  58. title=self.highlighter(title),
  59. border_style="blue",
  60. height=height,
  61. )
  62. class Splitter(ABC):
  63. """Base class for a splitter."""
  64. name: str = ""
  65. @abstractmethod
  66. def get_tree_icon(self) -> str:
  67. """Get the icon (emoji) used in layout.tree"""
  68. @abstractmethod
  69. def divide(
  70. self, children: Sequence["Layout"], region: Region
  71. ) -> Iterable[Tuple["Layout", Region]]:
  72. """Divide a region amongst several child layouts.
  73. Args:
  74. children (Sequence(Layout)): A number of child layouts.
  75. region (Region): A rectangular region to divide.
  76. """
  77. class RowSplitter(Splitter):
  78. """Split a layout region in to rows."""
  79. name = "row"
  80. def get_tree_icon(self) -> str:
  81. return "[layout.tree.row]⬌"
  82. def divide(
  83. self, children: Sequence["Layout"], region: Region
  84. ) -> Iterable[Tuple["Layout", Region]]:
  85. x, y, width, height = region
  86. render_widths = ratio_resolve(width, children)
  87. offset = 0
  88. _Region = Region
  89. for child, child_width in zip(children, render_widths):
  90. yield child, _Region(x + offset, y, child_width, height)
  91. offset += child_width
  92. class ColumnSplitter(Splitter):
  93. """Split a layout region in to columns."""
  94. name = "column"
  95. def get_tree_icon(self) -> str:
  96. return "[layout.tree.column]⬍"
  97. def divide(
  98. self, children: Sequence["Layout"], region: Region
  99. ) -> Iterable[Tuple["Layout", Region]]:
  100. x, y, width, height = region
  101. render_heights = ratio_resolve(height, children)
  102. offset = 0
  103. _Region = Region
  104. for child, child_height in zip(children, render_heights):
  105. yield child, _Region(x, y + offset, width, child_height)
  106. offset += child_height
  107. @rich_repr
  108. class Layout:
  109. """A renderable to divide a fixed height in to rows or columns.
  110. Args:
  111. renderable (RenderableType, optional): Renderable content, or None for placeholder. Defaults to None.
  112. name (str, optional): Optional identifier for Layout. Defaults to None.
  113. size (int, optional): Optional fixed size of layout. Defaults to None.
  114. minimum_size (int, optional): Minimum size of layout. Defaults to 1.
  115. ratio (int, optional): Optional ratio for flexible layout. Defaults to 1.
  116. visible (bool, optional): Visibility of layout. Defaults to True.
  117. """
  118. splitters = {"row": RowSplitter, "column": ColumnSplitter}
  119. def __init__(
  120. self,
  121. renderable: Optional[RenderableType] = None,
  122. *,
  123. name: Optional[str] = None,
  124. size: Optional[int] = None,
  125. minimum_size: int = 1,
  126. ratio: int = 1,
  127. visible: bool = True,
  128. ) -> None:
  129. self._renderable = renderable or _Placeholder(self)
  130. self.size = size
  131. self.minimum_size = minimum_size
  132. self.ratio = ratio
  133. self.name = name
  134. self.visible = visible
  135. self.splitter: Splitter = self.splitters["column"]()
  136. self._children: List[Layout] = []
  137. self._render_map: RenderMap = {}
  138. self._lock = RLock()
  139. def __rich_repr__(self) -> Result:
  140. yield "name", self.name, None
  141. yield "size", self.size, None
  142. yield "minimum_size", self.minimum_size, 1
  143. yield "ratio", self.ratio, 1
  144. @property
  145. def renderable(self) -> RenderableType:
  146. """Layout renderable."""
  147. return self if self._children else self._renderable
  148. @property
  149. def children(self) -> List["Layout"]:
  150. """Gets (visible) layout children."""
  151. return [child for child in self._children if child.visible]
  152. @property
  153. def map(self) -> RenderMap:
  154. """Get a map of the last render."""
  155. return self._render_map
  156. def get(self, name: str) -> Optional["Layout"]:
  157. """Get a named layout, or None if it doesn't exist.
  158. Args:
  159. name (str): Name of layout.
  160. Returns:
  161. Optional[Layout]: Layout instance or None if no layout was found.
  162. """
  163. if self.name == name:
  164. return self
  165. else:
  166. for child in self._children:
  167. named_layout = child.get(name)
  168. if named_layout is not None:
  169. return named_layout
  170. return None
  171. def __getitem__(self, name: str) -> "Layout":
  172. layout = self.get(name)
  173. if layout is None:
  174. raise KeyError(f"No layout with name {name!r}")
  175. return layout
  176. @property
  177. def tree(self) -> "Tree":
  178. """Get a tree renderable to show layout structure."""
  179. from pip._vendor.rich.styled import Styled
  180. from pip._vendor.rich.table import Table
  181. from pip._vendor.rich.tree import Tree
  182. def summary(layout: "Layout") -> Table:
  183. icon = layout.splitter.get_tree_icon()
  184. table = Table.grid(padding=(0, 1, 0, 0))
  185. text: RenderableType = (
  186. Pretty(layout) if layout.visible else Styled(Pretty(layout), "dim")
  187. )
  188. table.add_row(icon, text)
  189. _summary = table
  190. return _summary
  191. layout = self
  192. tree = Tree(
  193. summary(layout),
  194. guide_style=f"layout.tree.{layout.splitter.name}",
  195. highlight=True,
  196. )
  197. def recurse(tree: "Tree", layout: "Layout") -> None:
  198. for child in layout._children:
  199. recurse(
  200. tree.add(
  201. summary(child),
  202. guide_style=f"layout.tree.{child.splitter.name}",
  203. ),
  204. child,
  205. )
  206. recurse(tree, self)
  207. return tree
  208. def split(
  209. self,
  210. *layouts: Union["Layout", RenderableType],
  211. splitter: Union[Splitter, str] = "column",
  212. ) -> None:
  213. """Split the layout in to multiple sub-layouts.
  214. Args:
  215. *layouts (Layout): Positional arguments should be (sub) Layout instances.
  216. splitter (Union[Splitter, str]): Splitter instance or name of splitter.
  217. """
  218. _layouts = [
  219. layout if isinstance(layout, Layout) else Layout(layout)
  220. for layout in layouts
  221. ]
  222. try:
  223. self.splitter = (
  224. splitter
  225. if isinstance(splitter, Splitter)
  226. else self.splitters[splitter]()
  227. )
  228. except KeyError:
  229. raise NoSplitter(f"No splitter called {splitter!r}")
  230. self._children[:] = _layouts
  231. def add_split(self, *layouts: Union["Layout", RenderableType]) -> None:
  232. """Add a new layout(s) to existing split.
  233. Args:
  234. *layouts (Union[Layout, RenderableType]): Positional arguments should be renderables or (sub) Layout instances.
  235. """
  236. _layouts = (
  237. layout if isinstance(layout, Layout) else Layout(layout)
  238. for layout in layouts
  239. )
  240. self._children.extend(_layouts)
  241. def split_row(self, *layouts: Union["Layout", RenderableType]) -> None:
  242. """Split the layout in to a row (layouts side by side).
  243. Args:
  244. *layouts (Layout): Positional arguments should be (sub) Layout instances.
  245. """
  246. self.split(*layouts, splitter="row")
  247. def split_column(self, *layouts: Union["Layout", RenderableType]) -> None:
  248. """Split the layout in to a column (layouts stacked on top of each other).
  249. Args:
  250. *layouts (Layout): Positional arguments should be (sub) Layout instances.
  251. """
  252. self.split(*layouts, splitter="column")
  253. def unsplit(self) -> None:
  254. """Reset splits to initial state."""
  255. del self._children[:]
  256. def update(self, renderable: RenderableType) -> None:
  257. """Update renderable.
  258. Args:
  259. renderable (RenderableType): New renderable object.
  260. """
  261. with self._lock:
  262. self._renderable = renderable
  263. def refresh_screen(self, console: "Console", layout_name: str) -> None:
  264. """Refresh a sub-layout.
  265. Args:
  266. console (Console): Console instance where Layout is to be rendered.
  267. layout_name (str): Name of layout.
  268. """
  269. with self._lock:
  270. layout = self[layout_name]
  271. region, _lines = self._render_map[layout]
  272. (x, y, width, height) = region
  273. lines = console.render_lines(
  274. layout, console.options.update_dimensions(width, height)
  275. )
  276. self._render_map[layout] = LayoutRender(region, lines)
  277. console.update_screen_lines(lines, x, y)
  278. def _make_region_map(self, width: int, height: int) -> RegionMap:
  279. """Create a dict that maps layout on to Region."""
  280. stack: List[Tuple[Layout, Region]] = [(self, Region(0, 0, width, height))]
  281. push = stack.append
  282. pop = stack.pop
  283. layout_regions: List[Tuple[Layout, Region]] = []
  284. append_layout_region = layout_regions.append
  285. while stack:
  286. append_layout_region(pop())
  287. layout, region = layout_regions[-1]
  288. children = layout.children
  289. if children:
  290. for child_and_region in layout.splitter.divide(children, region):
  291. push(child_and_region)
  292. region_map = {
  293. layout: region
  294. for layout, region in sorted(layout_regions, key=itemgetter(1))
  295. }
  296. return region_map
  297. def render(self, console: Console, options: ConsoleOptions) -> RenderMap:
  298. """Render the sub_layouts.
  299. Args:
  300. console (Console): Console instance.
  301. options (ConsoleOptions): Console options.
  302. Returns:
  303. RenderMap: A dict that maps Layout on to a tuple of Region, lines
  304. """
  305. render_width = options.max_width
  306. render_height = options.height or console.height
  307. region_map = self._make_region_map(render_width, render_height)
  308. layout_regions = [
  309. (layout, region)
  310. for layout, region in region_map.items()
  311. if not layout.children
  312. ]
  313. render_map: Dict["Layout", "LayoutRender"] = {}
  314. render_lines = console.render_lines
  315. update_dimensions = options.update_dimensions
  316. for layout, region in layout_regions:
  317. lines = render_lines(
  318. layout.renderable, update_dimensions(region.width, region.height)
  319. )
  320. render_map[layout] = LayoutRender(region, lines)
  321. return render_map
  322. def __rich_console__(
  323. self, console: Console, options: ConsoleOptions
  324. ) -> RenderResult:
  325. with self._lock:
  326. width = options.max_width or console.width
  327. height = options.height or console.height
  328. render_map = self.render(console, options.update_dimensions(width, height))
  329. self._render_map = render_map
  330. layout_lines: List[List[Segment]] = [[] for _ in range(height)]
  331. _islice = islice
  332. for (region, lines) in render_map.values():
  333. _x, y, _layout_width, layout_height = region
  334. for row, line in zip(
  335. _islice(layout_lines, y, y + layout_height), lines
  336. ):
  337. row.extend(line)
  338. new_line = Segment.line()
  339. for layout_row in layout_lines:
  340. yield from layout_row
  341. yield new_line
  342. if __name__ == "__main__":
  343. from pip._vendor.rich.console import Console
  344. console = Console()
  345. layout = Layout()
  346. layout.split_column(
  347. Layout(name="header", size=3),
  348. Layout(ratio=1, name="main"),
  349. Layout(size=10, name="footer"),
  350. )
  351. layout["main"].split_row(Layout(name="side"), Layout(name="body", ratio=2))
  352. layout["body"].split_row(Layout(name="content", ratio=2), Layout(name="s2"))
  353. layout["s2"].split_column(
  354. Layout(name="top"), Layout(name="middle"), Layout(name="bottom")
  355. )
  356. layout["side"].split_column(Layout(layout.tree, name="left1"), Layout(name="left2"))
  357. layout["content"].update("foo")
  358. console.print(layout)