diff --git a/old examples/README.md b/old examples/README.md new file mode 100644 index 000000000..0a60ffba4 --- /dev/null +++ b/old examples/README.md @@ -0,0 +1,11 @@ +These examples probably don't rub. We will be back-porting them to the examples dir + +# Examples + +Run any of these examples to demonstrate a Textual features. + +The example code will generate a log file called "textual.log". Tail this file to gain insight in to what Textual is doing. + +``` +tail -f textual +``` diff --git a/old examples/animation.py b/old examples/animation.py new file mode 100644 index 000000000..0a6efaf19 --- /dev/null +++ b/old examples/animation.py @@ -0,0 +1,38 @@ +from textual.app import App +from textual.reactive import Reactive +from textual.widgets import Footer, Placeholder + + +class SmoothApp(App): + """Demonstrates smooth animation. Press 'b' to see it in action.""" + + async def on_load(self) -> None: + """Bind keys here.""" + await self.bind("b", "toggle_sidebar", "Toggle sidebar") + await self.bind("q", "quit", "Quit") + + show_bar = Reactive(False) + + def watch_show_bar(self, show_bar: bool) -> None: + """Called when show_bar changes.""" + self.bar.animate("layout_offset_x", 0 if show_bar else -40) + + def action_toggle_sidebar(self) -> None: + """Called when user hits 'b' key.""" + self.show_bar = not self.show_bar + + async def on_mount(self) -> None: + """Build layout here.""" + footer = Footer() + self.bar = Placeholder(name="left") + + await self.screen.dock(footer, edge="bottom") + await self.screen.dock(Placeholder(), Placeholder(), edge="top") + await self.screen.dock(self.bar, edge="left", size=40, z=1) + + self.bar.layout_offset_x = -40 + + # self.set_timer(10, lambda: self.action("quit")) + + +SmoothApp.run(log_path="textual.log", log_verbosity=2) diff --git a/old examples/big_table.py b/old examples/big_table.py new file mode 100644 index 000000000..7bfc428d7 --- /dev/null +++ b/old examples/big_table.py @@ -0,0 +1,33 @@ +from rich.table import Table + +from textual import events +from textual.app import App +from textual.widgets import ScrollView + + +class MyApp(App): + """An example of a very simple Textual App""" + + async def on_load(self, event: events.Load) -> None: + await self.bind("q", "quit", "Quit") + + async def on_mount(self, event: events.Mount) -> None: + + self.body = body = ScrollView(auto_width=True) + + await self.screen.dock(body) + + async def add_content(): + table = Table(title="Demo") + + for i in range(20): + table.add_column(f"Col {i + 1}", style="magenta") + for i in range(100): + table.add_row(*[f"cell {i},{j}" for j in range(20)]) + + await body.update(table) + + await self.call_later(add_content) + + +MyApp.run(title="Simple App", log_path="textual.log") diff --git a/old examples/borders.css b/old examples/borders.css new file mode 100644 index 000000000..f27374927 --- /dev/null +++ b/old examples/borders.css @@ -0,0 +1,59 @@ +Screen { + /* text-background: #212121; */ +} + +#borders { + layout: vertical; + background: #212121; + overflow-y: scroll; +} + +Lorem.border { + height: 12; + margin: 2 4; + background: #303f9f; +} + +Lorem.round { + border: round #8bc34a; +} + +Lorem.solid { + border: solid #8bc34a; +} + +Lorem.double { + border: double #8bc34a; +} + +Lorem.dashed { + border: dashed #8bc34a; +} + +Lorem.heavy { + border: heavy #8bc34a; +} + +Lorem.inner { + border: inner #8bc34a; +} + +Lorem.outer { + border: outer #8bc34a; +} + +Lorem.hkey { + border: hkey #8bc34a; +} + +Lorem.vkey { + border: vkey #8bc34a; +} + +Lorem.tall { + border: tall #8bc34a; +} + +Lorem.wide { + border: wide #8bc34a; +} diff --git a/old examples/borders.py b/old examples/borders.py new file mode 100644 index 000000000..62e4d296e --- /dev/null +++ b/old examples/borders.py @@ -0,0 +1,57 @@ +from rich.padding import Padding +from rich.style import Style +from rich.text import Text + +from textual.app import App +from textual.renderables.gradient import VerticalGradient +from textual.widget import Widget + +lorem = Text.from_markup( + """[#C5CAE9]Lorem ipsum dolor sit amet, consectetur adipiscing elit. In velit libero, volutpat nec hendrerit at, faucibus in odio. Aliquam hendrerit nibh sed quam volutpat maximus. Nullam suscipit convallis lorem quis sodales. In tristique lobortis ante et dictum. Ut at finibus ipsum. In urna dolor, placerat et mi facilisis, congue sollicitudin massa. Phasellus felis turpis, cursus eu lectus et, porttitor malesuada augue. Sed feugiat volutpat velit, sollicitudin fringilla velit bibendum faucibus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In velit libero, volutpat nec hendrerit at, faucibus in odio. Aliquam hendrerit nibh sed quam volutpat maximus. Nullam suscipit convallis lorem quis sodales. In tristique lobortis ante et dictum. Ut at finibus ipsum. In urna dolor, placerat et mi facilisis, congue sollicitudin massa. Phasellus felis turpis, cursus eu lectus et, porttitor malesuada augue. Sed feugiat volutpat velit, sollicitudin fringilla velit bibendum faucibus. """, + justify="full", +) + + +class Lorem(Widget): + def render(self) -> Text: + return Padding(lorem, 1) + + +class Background(Widget): + def render(self): + return VerticalGradient("#212121", "#212121") + + +class BordersApp(App): + """Sandbox application used for testing/development by Textual developers""" + + def on_load(self): + self.bind("q", "quit", "Quit") + + def on_mount(self): + """Build layout here.""" + + borders = [ + Lorem(classes={"border", border}) + for border in ( + "round", + "solid", + "double", + "dashed", + "heavy", + "inner", + "outer", + "hkey", + "vkey", + "tall", + "wide", + ) + ] + borders_view = Background(*borders) + borders_view.show_vertical_scrollbar = True + + self.mount(borders=borders_view) + + +app = BordersApp(css_path="borders.css", log_path="textual.log") +app.run() diff --git a/old examples/calculator.py b/old examples/calculator.py new file mode 100644 index 000000000..7f4bbe3cc --- /dev/null +++ b/old examples/calculator.py @@ -0,0 +1,216 @@ +""" + +A Textual app to create a fully working calculator, modelled after MacOS Calculator. + +""" + +from decimal import Decimal + +from rich.align import Align +from rich.console import Console, ConsoleOptions, RenderResult, RenderableType +from rich.padding import Padding +from rich.style import Style +from rich.text import Text + +from textual.app import App +from textual.reactive import Reactive +from textual.views import GridView +from textual.widget import Widget +from textual.widgets import Button + +try: + from pyfiglet import Figlet +except ImportError: + print("Please install pyfiglet to run this example") + raise + + +class FigletText: + """A renderable to generate figlet text that adapts to fit the container.""" + + def __init__(self, text: str) -> None: + self.text = text + + def __rich_console__( + self, console: Console, options: ConsoleOptions + ) -> RenderResult: + """Build a Rich renderable to render the Figlet text.""" + size = min(options.max_width / 2, options.max_height) + if size < 4: + yield Text(self.text, style="bold") + else: + if size < 7: + font_name = "mini" + elif size < 8: + font_name = "small" + elif size < 10: + font_name = "standard" + else: + font_name = "big" + font = Figlet(font=font_name, width=options.max_width) + yield Text(font.renderText(self.text).rstrip("\n"), style="bold") + + +class Numbers(Widget): + """The digital display of the calculator.""" + + value = Reactive("0") + + def render(self) -> RenderableType: + """Build a Rich renderable to render the calculator display.""" + return Padding( + Align.right(FigletText(self.value), vertical="middle"), + (0, 1), + style="white on rgb(51,51,51)", + ) + + +class Calculator(GridView): + """A working calculator app.""" + + DARK = "white on rgb(51,51,51)" + LIGHT = "black on rgb(165,165,165)" + YELLOW = "white on rgb(255,159,7)" + + BUTTON_STYLES = { + "AC": LIGHT, + "C": LIGHT, + "+/-": LIGHT, + "%": LIGHT, + "/": YELLOW, + "X": YELLOW, + "-": YELLOW, + "+": YELLOW, + "=": YELLOW, + } + + display = Reactive("0") + show_ac = Reactive(True) + + def watch_display(self, value: str) -> None: + """Called when self.display is modified.""" + # self.numbers is a widget that displays the calculator result + # Setting the attribute value changes the display + # This allows us to write self.display = "100" to update the display + self.numbers.value = value + + def compute_show_ac(self) -> bool: + """Compute show_ac reactive value.""" + # Condition to show AC button over C + return self.value in ("", "0") and self.display == "0" + + def watch_show_ac(self, show_ac: bool) -> None: + """When the show_ac attribute change we need to update the buttons.""" + # Show AC and hide C or vice versa + self.c.display = not show_ac + self.ac.display = show_ac + + def on_mount(self) -> None: + """Event when widget is first mounted (added to a parent view).""" + + # Attributes to store the current calculation + self.left = Decimal("0") + self.right = Decimal("0") + self.value = "" + self.operator = "+" + + # The calculator display + self.numbers = Numbers() + self.numbers.style_border = "bold" + + def make_button(text: str, style: str) -> Button: + """Create a button with the given Figlet label.""" + return Button(FigletText(text), style=style, name=text) + + # Make all the buttons + self.buttons = { + name: make_button(name, self.BUTTON_STYLES.get(name, self.DARK)) + for name in "+/-,%,/,7,8,9,X,4,5,6,-,1,2,3,+,.,=".split(",") + } + + # Buttons that have to be treated specially + self.zero = make_button("0", self.DARK) + self.ac = make_button("AC", self.LIGHT) + self.c = make_button("C", self.LIGHT) + self.c.display = False + + # Set basic grid settings + self.grid.set_gap(2, 1) + self.grid.set_gutter(1) + self.grid.set_align("center", "center") + + # Create rows / columns / areas + self.grid.add_column("col", max_size=30, repeat=4) + self.grid.add_row("numbers", max_size=15) + self.grid.add_row("row", max_size=15, repeat=5) + self.grid.add_areas( + clear="col1,row1", + numbers="col1-start|col4-end,numbers", + zero="col1-start|col2-end,row5", + ) + # Place out widgets in to the layout + self.grid.place(clear=self.c) + self.grid.place( + *self.buttons.values(), clear=self.ac, numbers=self.numbers, zero=self.zero + ) + + def handle_button_pressed(self, message: ButtonPressed) -> None: + """A message sent by the button widget""" + + assert isinstance(message.sender, Button) + button_name = message.sender.name + + def do_math() -> None: + """Does the math: LEFT OPERATOR RIGHT""" + self.log(self.left, self.operator, self.right) + try: + if self.operator == "+": + self.left += self.right + elif self.operator == "-": + self.left -= self.right + elif self.operator == "/": + self.left /= self.right + elif self.operator == "X": + self.left *= self.right + self.display = str(self.left) + self.value = "" + self.log("=", self.left) + except Exception: + self.display = "Error" + + if button_name.isdigit(): + self.display = self.value = self.value.lstrip("0") + button_name + elif button_name == "+/-": + self.display = self.value = str(Decimal(self.value or "0") * -1) + elif button_name == "%": + self.display = self.value = str(Decimal(self.value or "0") / Decimal(100)) + elif button_name == ".": + if "." not in self.value: + self.display = self.value = (self.value or "0") + "." + elif button_name == "AC": + self.value = "" + self.left = self.right = Decimal(0) + self.operator = "+" + self.display = "0" + elif button_name == "C": + self.value = "" + self.display = "0" + elif button_name in ("+", "-", "/", "X"): + self.right = Decimal(self.value or "0") + do_math() + self.operator = button_name + elif button_name == "=": + if self.value: + self.right = Decimal(self.value) + do_math() + + +class CalculatorApp(App): + """The Calculator Application""" + + async def on_mount(self) -> None: + """Mount the calculator widget.""" + await self.screen.dock(Calculator()) + + +CalculatorApp.run(title="Calculator Test", log_path="textual.log") diff --git a/old examples/code_viewer.py b/old examples/code_viewer.py new file mode 100644 index 000000000..6c9e4ce91 --- /dev/null +++ b/old examples/code_viewer.py @@ -0,0 +1,70 @@ +import os +import sys +from rich.console import RenderableType + +from rich.syntax import Syntax +from rich.traceback import Traceback + +from textual.app import App +from textual.widgets import Header, Footer, FileClick, ScrollView, DirectoryTree + + +class MyApp(App): + """An example of a very simple Textual App""" + + async def on_load(self) -> None: + """Sent before going in to application mode.""" + + # Bind our basic keys + await self.bind("b", "view.toggle('sidebar')", "Toggle sidebar") + await self.bind("q", "quit", "Quit") + + # Get path to show + try: + self.path = sys.argv[1] + except IndexError: + self.path = os.path.abspath( + os.path.join(os.path.basename(__file__), "../../") + ) + + async def on_mount(self) -> None: + """Call after terminal goes in to application mode""" + + # Create our widgets + # In this a scroll view for the code and a directory tree + self.body = ScrollView() + self.directory = DirectoryTree(self.path, "Code") + + # Dock our widgets + await self.screen.dock(Header(), edge="top") + await self.screen.dock(Footer(), edge="bottom") + + # Note the directory is also in a scroll view + await self.screen.dock( + ScrollView(self.directory), edge="left", size=48, name="sidebar" + ) + await self.screen.dock(self.body, edge="top") + + async def handle_file_click(self, message: FileClick) -> None: + """A message sent by the directory tree when a file is clicked.""" + + syntax: RenderableType + try: + # Construct a Syntax object for the path in the message + syntax = Syntax.from_path( + message.path, + line_numbers=True, + word_wrap=True, + indent_guides=True, + theme="monokai", + ) + except Exception: + # Possibly a binary file + # For demonstration purposes we will show the traceback + syntax = Traceback(theme="monokai", width=None, show_locals=True) + self.app.sub_title = os.path.basename(message.path) + await self.body.update(syntax) + + +# Run our app class +MyApp.run(title="Code Viewer", log_path="textual.log") diff --git a/old examples/colours.txt b/old examples/colours.txt new file mode 100644 index 000000000..c96d59ffd --- /dev/null +++ b/old examples/colours.txt @@ -0,0 +1,10 @@ +header blue white on #173f5f + +sidebar #09312e on #3caea3 +sidebar border #09312e + +content blue white #20639b +content border #0f2b41 + +footer border #0f2b41 +footer yellow #3a3009 on #f6d55c; diff --git a/old examples/easing.py b/old examples/easing.py new file mode 100644 index 000000000..447f69e5f --- /dev/null +++ b/old examples/easing.py @@ -0,0 +1,45 @@ +from textual._easing import EASING +from textual.app import App +from textual.reactive import Reactive + +from textual.views import DockView +from textual.widgets import Placeholder, TreeControl, ScrollView, TreeClick + + +class EasingApp(App): + """An app do demonstrate easing.""" + + side = Reactive(False) + easing = Reactive("linear") + + def watch_side(self, side: bool) -> None: + """Animate when the side changes (False for left, True for right).""" + width = self.easing_view.size.width + animate_x = (width - self.placeholder.size.width) if side else 0 + self.placeholder.animate( + "layout_offset_x", animate_x, easing=self.easing, duration=1 + ) + + async def on_mount(self) -> None: + """Called when application mode is ready.""" + + self.placeholder = Placeholder() + self.easing_view = DockView() + self.placeholder.style = "white on dark_blue" + + tree = TreeControl("Easing", {}) + for easing_key in sorted(EASING.keys()): + await tree.add(tree.root.id, easing_key, {"easing": easing_key}) + await tree.root.expand() + + await self.screen.dock(ScrollView(tree), edge="left", size=32) + await self.screen.dock(self.easing_view) + await self.easing_view.dock(self.placeholder, edge="left", size=32) + + async def handle_tree_click(self, message: TreeClick[dict]) -> None: + """Called in response to a tree click.""" + self.easing = message.node.data.get("easing", "linear") + self.side = not self.side + + +EasingApp().run(log_path="textual.log") diff --git a/old examples/example.css b/old examples/example.css new file mode 100644 index 000000000..2ccd53034 --- /dev/null +++ b/old examples/example.css @@ -0,0 +1,34 @@ +App > View { + layout: dock; + docks: side=left/1; +} + +#header { + text: on #173f5f; + height: 3; + border: hkey white; +} + +#content { + text: on #20639b; +} + +#footer { + height: 3; + border-top: hkey #0f2b41; + text: #3a3009 on #f6d55c; +} + +#sidebar { + text: #09312e on #3caea3; + dock: side; + width: 30; + border-right: outer #09312e; + offset-x: -100%; + transition: offset 400ms in_out_cubic; +} + +#sidebar.-active { + offset-x: 0; + transition: offset 400ms in_out_cubic; +} diff --git a/old examples/grid.py b/old examples/grid.py new file mode 100644 index 000000000..23873c406 --- /dev/null +++ b/old examples/grid.py @@ -0,0 +1,34 @@ +from textual.app import App +from textual.widgets import Placeholder + + +class GridTest(App): + async def on_mount(self) -> None: + """Make a simple grid arrangement.""" + + grid = await self.screen.dock_grid(edge="left", name="left") + + grid.add_column(fraction=1, name="left", min_size=20) + grid.add_column(size=30, name="center") + grid.add_column(fraction=1, name="right") + + grid.add_row(fraction=1, name="top", min_size=2) + grid.add_row(fraction=2, name="middle") + grid.add_row(fraction=1, name="bottom") + + grid.add_areas( + area1="left,top", + area2="center,middle", + area3="left-start|right-end,bottom", + area4="right,top-start|middle-end", + ) + + grid.place( + area1=Placeholder(name="area1"), + area2=Placeholder(name="area2"), + area3=Placeholder(name="area3"), + area4=Placeholder(name="area4"), + ) + + +GridTest.run(title="Grid Test", log_path="textual.log") diff --git a/old examples/grid_auto.py b/old examples/grid_auto.py new file mode 100644 index 000000000..7a738670a --- /dev/null +++ b/old examples/grid_auto.py @@ -0,0 +1,22 @@ +from textual.app import App +from textual import events +from textual.widgets import Placeholder + + +class GridTest(App): + async def on_mount(self, event: events.Mount) -> None: + """Create a grid with auto-arranging cells.""" + + grid = await self.screen.dock_grid() + + grid.add_column("col", fraction=1, max_size=20) + grid.add_row("row", fraction=1, max_size=10) + grid.set_repeat(True, True) + grid.add_areas(center="col-2-start|col-4-end,row-2-start|row-3-end") + grid.set_align("stretch", "center") + + placeholders = [Placeholder() for _ in range(20)] + grid.place(*placeholders, center=Placeholder()) + + +GridTest.run(title="Grid Test", log_path="textual.log") diff --git a/old examples/richreadme.md b/old examples/richreadme.md new file mode 100644 index 000000000..880d2544d --- /dev/null +++ b/old examples/richreadme.md @@ -0,0 +1,444 @@ +[![Downloads](https://pepy.tech/badge/rich/month)](https://pepy.tech/project/rich) +[![PyPI version](https://badge.fury.io/py/rich.svg)](https://badge.fury.io/py/rich) +[![codecov](https://codecov.io/gh/willmcgugan/rich/branch/master/graph/badge.svg)](https://codecov.io/gh/willmcgugan/rich) +[![Rich blog](https://img.shields.io/badge/blog-rich%20news-yellowgreen)](https://www.willmcgugan.com/tag/rich/) +[![Twitter Follow](https://img.shields.io/twitter/follow/willmcgugan.svg?style=social)](https://twitter.com/willmcgugan) + +![Logo](https://github.com/willmcgugan/rich/raw/master/imgs/logo.svg) + +[中文 readme](https://github.com/willmcgugan/rich/blob/master/README.cn.md) • [Lengua española readme](https://github.com/willmcgugan/rich/blob/master/README.es.md) • [Deutsche readme](https://github.com/willmcgugan/rich/blob/master/README.de.md) • [Läs på svenska](https://github.com/willmcgugan/rich/blob/master/README.sv.md) • [日本語 readme](https://github.com/willmcgugan/rich/blob/master/README.ja.md) • [한국어 readme](https://github.com/willmcgugan/rich/blob/master/README.kr.md) + +Rich is a Python library for _rich_ text and beautiful formatting in the terminal. + +The [Rich API](https://rich.readthedocs.io/en/latest/) makes it easy to add color and style to terminal output. Rich can also render pretty tables, progress bars, markdown, syntax highlighted source code, tracebacks, and more — out of the box. + +![Features](https://github.com/willmcgugan/rich/raw/master/imgs/features.png) + +For a video introduction to Rich see [calmcode.io](https://calmcode.io/rich/introduction.html) by [@fishnets88](https://twitter.com/fishnets88). + +See what [people are saying about Rich](https://www.willmcgugan.com/blog/pages/post/rich-tweets/). + +## Compatibility + +Rich works with Linux, OSX, and Windows. True color / emoji works with new Windows Terminal, classic terminal is limited to 16 colors. Rich requires Python 3.6.1 or later. + +Rich works with [Jupyter notebooks](https://jupyter.org/) with no additional configuration required. + +## Installing + +Install with `pip` or your favorite PyPi package manager. + +``` +pip install rich +``` + +Run the following to test Rich output on your terminal: + +``` +python -m rich +``` + +## Rich Print + +To effortlessly add rich output to your application, you can import the [rich print](https://rich.readthedocs.io/en/latest/introduction.html#quick-start) method, which has the same signature as the builtin Python function. Try this: + +```python +from rich import print + +print("Hello, [bold magenta]World[/bold magenta]!", ":vampire:", locals()) +``` + +![Hello World](https://github.com/willmcgugan/rich/raw/master/imgs/print.png) + +## Rich REPL + +Rich can be installed in the Python REPL, so that any data structures will be pretty printed and highlighted. + +```python +>>> from rich import pretty +>>> pretty.install() +``` + +![REPL](https://github.com/willmcgugan/rich/raw/master/imgs/repl.png) + +## Using the Console + +For more control over rich terminal content, import and construct a [Console](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console) object. + +```python +from rich.console import Console + +console = Console() +``` + +The Console object has a `print` method which has an intentionally similar interface to the builtin `print` function. Here's an example of use: + +```python +console.print("Hello", "World!") +``` + +As you might expect, this will print `"Hello World!"` to the terminal. Note that unlike the builtin `print` function, Rich will word-wrap your text to fit within the terminal width. + +There are a few ways of adding color and style to your output. You can set a style for the entire output by adding a `style` keyword argument. Here's an example: + +```python +console.print("Hello", "World!", style="bold red") +``` + +The output will be something like the following: + +![Hello World](https://github.com/willmcgugan/rich/raw/master/imgs/hello_world.png) + +That's fine for styling a line of text at a time. For more finely grained styling, Rich renders a special markup which is similar in syntax to [bbcode](https://en.wikipedia.org/wiki/BBCode). Here's an example: + +```python +console.print("Where there is a [bold cyan]Will[/bold cyan] there [u]is[/u] a [i]way[/i].") +``` + +![Console Markup](https://github.com/willmcgugan/rich/raw/master/imgs/where_there_is_a_will.png) + +You can use a Console object to generate sophisticated output with minimal effort. See the [Console API](https://rich.readthedocs.io/en/latest/console.html) docs for details. + +## Rich Inspect + +Rich has an [inspect](https://rich.readthedocs.io/en/latest/reference/init.html?highlight=inspect#rich.inspect) function which can produce a report on any Python object, such as class, instance, or builtin. + +```python +>>> my_list = ["foo", "bar"] +>>> from rich import inspect +>>> inspect(my_list, methods=True) +``` + +![Log](https://github.com/willmcgugan/rich/raw/master/imgs/inspect.png) + +See the [inspect docs](https://rich.readthedocs.io/en/latest/reference/init.html#rich.inspect) for details. + +# Rich Library + +Rich contains a number of builtin _renderables_ you can use to create elegant output in your CLI and help you debug your code. + +Click the following headings for details: + +
+Log + +The Console object has a `log()` method which has a similar interface to `print()`, but also renders a column for the current time and the file and line which made the call. By default Rich will do syntax highlighting for Python structures and for repr strings. If you log a collection (i.e. a dict or a list) Rich will pretty print it so that it fits in the available space. Here's an example of some of these features. + +```python +from rich.console import Console +console = Console() + +test_data = [ + {"jsonrpc": "2.0", "method": "sum", "params": [None, 1, 2, 4, False, True], "id": "1",}, + {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]}, + {"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": "2"}, +] + +def test_log(): + enabled = False + context = { + "foo": "bar", + } + movies = ["Deadpool", "Rise of the Skywalker"] + console.log("Hello from", console, "!") + console.log(test_data, log_locals=True) + + +test_log() +``` + +The above produces the following output: + +![Log](https://github.com/willmcgugan/rich/raw/master/imgs/log.png) + +Note the `log_locals` argument, which outputs a table containing the local variables where the log method was called. + +The log method could be used for logging to the terminal for long running applications such as servers, but is also a very nice debugging aid. + +
+
+Logging Handler + +You can also use the builtin [Handler class](https://rich.readthedocs.io/en/latest/logging.html) to format and colorize output from Python's logging module. Here's an example of the output: + +![Logging](https://github.com/willmcgugan/rich/raw/master/imgs/logging.png) + +
+ +
+Emoji + +To insert an emoji in to console output place the name between two colons. Here's an example: + +```python +>>> console.print(":smiley: :vampire: :pile_of_poo: :thumbs_up: :raccoon:") +😃 🧛 💩 👍 🦝 +``` + +Please use this feature wisely. + +
+ +
+Tables + +Rich can render flexible [tables](https://rich.readthedocs.io/en/latest/tables.html) with unicode box characters. There is a large variety of formatting options for borders, styles, cell alignment etc. + +![table movie](https://github.com/willmcgugan/rich/raw/master/imgs/table_movie.gif) + +The animation above was generated with [table_movie.py](https://github.com/willmcgugan/rich/blob/master/examples/table_movie.py) in the examples directory. + +Here's a simpler table example: + +```python +from rich.console import Console +from rich.table import Table + +console = Console() + +table = Table(show_header=True, header_style="bold magenta") +table.add_column("Date", style="dim", width=12) +table.add_column("Title") +table.add_column("Production Budget", justify="right") +table.add_column("Box Office", justify="right") +table.add_row( + "Dev 20, 2019", "Star Wars: The Rise of Skywalker", "$275,000,000", "$375,126,118" +) +table.add_row( + "May 25, 2018", + "[red]Solo[/red]: A Star Wars Story", + "$275,000,000", + "$393,151,347", +) +table.add_row( + "Dec 15, 2017", + "Star Wars Ep. VIII: The Last Jedi", + "$262,000,000", + "[bold]$1,332,539,889[/bold]", +) + +console.print(table) +``` + +This produces the following output: + +![table](https://github.com/willmcgugan/rich/raw/master/imgs/table.png) + +Note that console markup is rendered in the same way as `print()` and `log()`. In fact, anything that is renderable by Rich may be included in the headers / rows (even other tables). + +The `Table` class is smart enough to resize columns to fit the available width of the terminal, wrapping text as required. Here's the same example, with the terminal made smaller than the table above: + +![table2](https://github.com/willmcgugan/rich/raw/master/imgs/table2.png) + +
+ +
+Progress Bars + +Rich can render multiple flicker-free [progress](https://rich.readthedocs.io/en/latest/progress.html) bars to track long-running tasks. + +For basic usage, wrap any sequence in the `track` function and iterate over the result. Here's an example: + +```python +from rich.progress import track + +for step in track(range(100)): + do_step(step) +``` + +It's not much harder to add multiple progress bars. Here's an example taken from the docs: + +![progress](https://github.com/willmcgugan/rich/raw/master/imgs/progress.gif) + +The columns may be configured to show any details you want. Built-in columns include percentage complete, file size, file speed, and time remaining. Here's another example showing a download in progress: + +![progress](https://github.com/willmcgugan/rich/raw/master/imgs/downloader.gif) + +To try this out yourself, see [examples/downloader.py](https://github.com/willmcgugan/rich/blob/master/examples/downloader.py) which can download multiple URLs simultaneously while displaying progress. + +
+ +
+Status + +For situations where it is hard to calculate progress, you can use the [status](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console.status) method which will display a 'spinner' animation and message. The animation won't prevent you from using the console as normal. Here's an example: + +```python +from time import sleep +from rich.console import Console + +console = Console() +tasks = [f"task {n}" for n in range(1, 11)] + +with console.status("[bold green]Working on tasks...") as status: + while tasks: + task = tasks.pop(0) + sleep(1) + console.log(f"{task} complete") +``` + +This generates the following output in the terminal. + +![status](https://github.com/willmcgugan/rich/raw/master/imgs/status.gif) + +The spinner animations were borrowed from [cli-spinners](https://www.npmjs.com/package/cli-spinners). You can select a spinner by specifying the `spinner` parameter. Run the following command to see the available values: + +``` +python -m rich.spinner +``` + +The above command generate the following output in the terminal: + +![spinners](https://github.com/willmcgugan/rich/raw/master/imgs/spinners.gif) + +
+ +
+Tree + +Rich can render a [tree](https://rich.readthedocs.io/en/latest/tree.html) with guide lines. A tree is ideal for displaying a file structure, or any other hierarchical data. + +The labels of the tree can be simple text or anything else Rich can render. Run the following for a demonstration: + +``` +python -m rich.tree +``` + +This generates the following output: + +![markdown](https://github.com/willmcgugan/rich/raw/master/imgs/tree.png) + +See the [tree.py](https://github.com/willmcgugan/rich/blob/master/examples/tree.py) example for a script that displays a tree view of any directory, similar to the linux `tree` command. + +
+ +
+Columns + +Rich can render content in neat [columns](https://rich.readthedocs.io/en/latest/columns.html) with equal or optimal width. Here's a very basic clone of the (MacOS / Linux) `ls` command which displays a directory listing in columns: + +```python +import os +import sys + +from rich import print +from rich.columns import Columns + +directory = os.listdir(sys.argv[1]) +print(Columns(directory)) +``` + +The following screenshot is the output from the [columns example](https://github.com/willmcgugan/rich/blob/master/examples/columns.py) which displays data pulled from an API in columns: + +![columns](https://github.com/willmcgugan/rich/raw/master/imgs/columns.png) + +
+ +
+Markdown + +Rich can render [markdown](https://rich.readthedocs.io/en/latest/markdown.html) and does a reasonable job of translating the formatting to the terminal. + +To render markdown import the `Markdown` class and construct it with a string containing markdown code. Then print it to the console. Here's an example: + +```python +from rich.console import Console +from rich.markdown import Markdown + +console = Console() +with open("README.md") as readme: + markdown = Markdown(readme.read()) +console.print(markdown) +``` + +This will produce output something like the following: + +![markdown](https://github.com/willmcgugan/rich/raw/master/imgs/markdown.png) + +
+ +
+Syntax Highlighting + +Rich uses the [pygments](https://pygments.org/) library to implement [syntax highlighting](https://rich.readthedocs.io/en/latest/syntax.html). Usage is similar to rendering markdown; construct a `Syntax` object and print it to the console. Here's an example: + +```python +from rich.console import Console +from rich.syntax import Syntax + +my_code = ''' +def iter_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]: + """Iterate and generate a tuple with a flag for first and last value.""" + iter_values = iter(values) + try: + previous_value = next(iter_values) + except StopIteration: + return + first = True + for value in iter_values: + yield first, False, previous_value + first = False + previous_value = value + yield first, True, previous_value +''' +syntax = Syntax(my_code, "python", theme="monokai", line_numbers=True) +console = Console() +console.print(syntax) +``` + +This will produce the following output: + +![syntax](https://github.com/willmcgugan/rich/raw/master/imgs/syntax.png) + +
+ +
+Tracebacks + +Rich can render [beautiful tracebacks](https://rich.readthedocs.io/en/latest/traceback.html) which are easier to read and show more code than standard Python tracebacks. You can set Rich as the default traceback handler so all uncaught exceptions will be rendered by Rich. + +Here's what it looks like on OSX (similar on Linux): + +![traceback](https://github.com/willmcgugan/rich/raw/master/imgs/traceback.png) + +
+ +All Rich renderables make use of the [Console Protocol](https://rich.readthedocs.io/en/latest/protocol.html), which you can also use to implement your own Rich content. + +# Rich for enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of Rich and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source packages you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use. [Learn more.](https://tidelift.com/subscription/pkg/pypi-rich?utm_source=pypi-rich&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + +# Project using Rich + +Here are a few projects using Rich: + +- [BrancoLab/BrainRender](https://github.com/BrancoLab/BrainRender) + a python package for the visualization of three dimensional neuro-anatomical data +- [Ciphey/Ciphey](https://github.com/Ciphey/Ciphey) + Automated decryption tool +- [emeryberger/scalene](https://github.com/emeryberger/scalene) + a high-performance, high-precision CPU and memory profiler for Python +- [hedythedev/StarCli](https://github.com/hedythedev/starcli) + Browse GitHub trending projects from your command line +- [intel/cve-bin-tool](https://github.com/intel/cve-bin-tool) + This tool scans for a number of common, vulnerable components (openssl, libpng, libxml2, expat and a few others) to let you know if your system includes common libraries with known vulnerabilities. +- [nf-core/tools](https://github.com/nf-core/tools) + Python package with helper tools for the nf-core community. +- [cansarigol/pdbr](https://github.com/cansarigol/pdbr) + pdb + Rich library for enhanced debugging +- [plant99/felicette](https://github.com/plant99/felicette) + Satellite imagery for dummies. +- [seleniumbase/SeleniumBase](https://github.com/seleniumbase/SeleniumBase) + Automate & test 10x faster with Selenium & pytest. Batteries included. +- [smacke/ffsubsync](https://github.com/smacke/ffsubsync) + Automagically synchronize subtitles with video. +- [tryolabs/norfair](https://github.com/tryolabs/norfair) + Lightweight Python library for adding real-time 2D object tracking to any detector. +- [ansible/ansible-lint](https://github.com/ansible/ansible-lint) Ansible-lint checks playbooks for practices and behaviour that could potentially be improved +- [ansible-community/molecule](https://github.com/ansible-community/molecule) Ansible Molecule testing framework +- +[Many more](https://github.com/willmcgugan/rich/network/dependents)! + + diff --git a/old examples/simple.py b/old examples/simple.py new file mode 100644 index 000000000..0d75c5190 --- /dev/null +++ b/old examples/simple.py @@ -0,0 +1,51 @@ +from rich.markdown import Markdown + +from textual.app import App +from textual.widgets import Header, Footer, Placeholder, ScrollView + + +class MyApp(App): + """An example of a very simple Textual App""" + + stylesheet = """ + + App > View { + layout: dock + } + + #body { + padding: 1 + } + + #sidebar { + edge left + size: 40 + } + + """ + + async def on_load(self) -> None: + """Bind keys with the app loads (but before entering application mode)""" + await self.bind("b", "view.toggle('sidebar')", "Toggle sidebar") + await self.bind("q", "quit", "Quit") + + async def on_mount(self) -> None: + """Create and dock the widgets.""" + + body = ScrollView() + await self.screen.mount( + Header(), + Footer(), + body=body, + sidebar=Placeholder(), + ) + + async def get_markdown(filename: str) -> None: + with open(filename, "rt") as fh: + readme = Markdown(fh.read(), hyperlinks=True) + await body.update(readme) + + await self.call_later(get_markdown, "richreadme.md") + + +MyApp.run(title="Simple App", log_path="textual.log") diff --git a/old examples/theme.css b/old examples/theme.css new file mode 100644 index 000000000..3f852c16f --- /dev/null +++ b/old examples/theme.css @@ -0,0 +1,7 @@ +Header { + border: solid #122233; +} + +App > View > Widget { + display: none; +} diff --git a/sandbox/scroll_view.py b/sandbox/scroll_view.py new file mode 100644 index 000000000..0e831ed73 --- /dev/null +++ b/sandbox/scroll_view.py @@ -0,0 +1,11 @@ +from textual.app import App, ComposeResult +from textual.scroll_view import ScrollView + + +class ScrollApp(App): + def compose(self) -> ComposeResult: + yield ScrollView() + + +app = ScrollApp() +app.run() diff --git a/sandbox/table.py b/sandbox/table.py new file mode 100644 index 000000000..ed676efcd --- /dev/null +++ b/sandbox/table.py @@ -0,0 +1,31 @@ +from textual.app import App, ComposeResult +from textual.widgets import DataTable + + +class TableApp(App): + def compose(self) -> ComposeResult: + table = self.table = DataTable(id="data") + table.add_column("Foo", width=16) + table.add_column("Bar", width=16) + table.add_column("Baz", width=16) + table.add_column("Egg", width=16) + table.add_column("Foo", width=16) + table.add_column("Bar", width=16) + table.add_column("Baz", width=16) + table.add_column("Egg", width=16) + + for n in range(100): + row = [f"row [b]{n}[/b] col [i]{c}[/i]" for c in range(8)] + table.add_row(*row) + yield table + + def on_mount(self): + self.bind("d", "toggle_dark") + + def action_toggle_dark(self) -> None: + self.app.dark = not self.app.dark + + +app = TableApp() +if __name__ == "__main__": + app.run() diff --git a/src/textual/_compositor.py b/src/textual/_compositor.py index ecfc6f1e7..dcc8aa0f0 100644 --- a/src/textual/_compositor.py +++ b/src/textual/_compositor.py @@ -444,7 +444,7 @@ class Compositor: x -= region.x y -= region.y - lines = widget.render_lines(y, y + 1) + lines = widget.render_lines((y, y + 1), (0, region.width)) if not lines: return Style.null() end = 0 @@ -543,7 +543,10 @@ class Compositor: if not region: continue if region in clip: - yield region, clip, widget.render_lines(0, region.height) + yield region, clip, widget.render_lines( + (0, region.height), + (0, region.width), + ) elif overlaps(clip, region): clipped_region = intersection(region, clip) if not clipped_region: @@ -552,11 +555,10 @@ class Compositor: delta_x = new_x - region.x delta_y = new_y - region.y crop_x = delta_x + new_width - lines = widget.render_lines(delta_y, delta_y + new_height) - if (delta_x, crop_x) != (0, region.width): - lines = [ - line_crop(line, delta_x, crop_x, region.width) for line in lines - ] + lines = widget.render_lines( + (delta_y, delta_y + new_height), + (delta_x, crop_x), + ) yield region, clip, lines @classmethod diff --git a/src/textual/css/model.py b/src/textual/css/model.py index 74b7e8bea..89623ac95 100644 --- a/src/textual/css/model.py +++ b/src/textual/css/model.py @@ -80,6 +80,14 @@ class Selector: self.specificity = (specificity1, specificity2 + 1, specificity3) def check(self, node: DOMNode) -> bool: + """Check if a given node matches the selector. + + Args: + node (DOMNode): A DOM node. + + Returns: + bool: True if the selector matches, otherwise False. + """ return self._checks[self.type](node) def _check_universal(self, node: DOMNode) -> bool: diff --git a/src/textual/dom.py b/src/textual/dom.py index fbc232740..8fa0a9c2d 100644 --- a/src/textual/dom.py +++ b/src/textual/dom.py @@ -358,6 +358,13 @@ class DOMNode(MessagePump): return style + @property + def rich_style(self) -> Style: + (_, _), (background, color) = self.colors + style = Style.from_color(color.rich_color, background.rich_color) + style += self.text_style + return style + @property def colors(self) -> tuple[tuple[Color, Color], tuple[Color, Color]]: """Gets the Widgets foreground and background colors, and its parent's colors. diff --git a/src/textual/geometry.py b/src/textual/geometry.py index 32495cfaa..f9d5da54a 100644 --- a/src/textual/geometry.py +++ b/src/textual/geometry.py @@ -516,7 +516,7 @@ class Region(NamedTuple): @lru_cache(maxsize=4096) def union(self, region: Region) -> Region: - """Get a new region that contains both regions. + """Get the smallest region that contains both regions. Args: region (Region): Another region. diff --git a/src/textual/scroll_view.py b/src/textual/scroll_view.py index c8938e1d4..912c5afdd 100644 --- a/src/textual/scroll_view.py +++ b/src/textual/scroll_view.py @@ -15,7 +15,7 @@ class ScrollView(Widget): ScrollView { overflow-y: auto; overflow-x: auto; - } + } """ @@ -33,7 +33,6 @@ class ScrollView(Widget): return False def on_mount(self): - self.virtual_size = Size(200, 200) self._refresh_scrollbars() def get_content_width(self, container: Size, viewport: Size) -> int: @@ -65,17 +64,7 @@ class ScrollView(Widget): self.refresh(layout=False) self.call_later(self.scroll_to, self.scroll_x, self.scroll_y) - # def render_lines(self, start: int | None = None, end: int | None = None) -> Lines: - # style = Style.parse("white on green") - # width, height = self.size - # lines = [ - # [Segment(str(" " * width), style)] - # for line in range(start or 0, end or height) - # ] - # return lines - def render(self) -> RenderableType: - from rich.panel import Panel return Panel(f"{self.scroll_offset} {self.show_vertical_scrollbar}") diff --git a/src/textual/widget.py b/src/textual/widget.py index b52d8808d..324af485d 100644 --- a/src/textual/widget.py +++ b/src/textual/widget.py @@ -4,6 +4,7 @@ from fractions import Fraction from typing import ( Any, Awaitable, + ClassVar, TYPE_CHECKING, Callable, Iterable, @@ -36,6 +37,8 @@ from ._layout import Layout from .reactive import Reactive, watch from .renderables.opacity import Opacity from .renderables.tint import Tint +from ._segment_tools import line_crop +from .css.styles import Styles if TYPE_CHECKING: @@ -73,13 +76,15 @@ class Widget(DOMNode): scrollbar-background: $panel-darken-2; scrollbar-background-hover: $panel-darken-3; scrollbar-color: $system; - scrollbar-color-active: $accent-darken-1; + scrollbar-color-active: $secondary-darken-1; scrollbar-size-vertical: 2; scrollbar-size-horizontal: 1; } """ + COMPONENTS: ClassVar[set[str]] = set() + can_focus: bool = False can_focus_children: bool = True @@ -114,6 +119,8 @@ class Widget(DOMNode): self._arrangement: ArrangeResult | None = None self._arrangement_cache_key: tuple[int, Size] = (-1, Size()) + self.component_styles: dict[str, Styles] = {} + super().__init__(name=name, id=id, classes=classes) self.add_children(*children) @@ -871,19 +878,22 @@ class Widget(DOMNode): self._render_cache = RenderCache(self.size, lines) self._dirty_regions.clear() - def render_lines(self, start: int, end: int) -> Lines: - """Get segment lines to render the widget. + def _crop_lines(self, lines: Lines, x1, x2) -> Lines: + if (x1, x2) != (0, self.size.width): + lines = [line_crop(line, x1, x2, self.size.width) for line in lines] + return lines - Args: - start (int | None, optional): line start index, or None for first line. Defaults to None. - end (int | None, optional): line end index, or None for last line. Defaults to None. - - Returns: - Lines: A list of lists of segments. - """ + def render_lines( + self, line_range: tuple[int, int], column_range: tuple[int, int] + ) -> Lines: + """Get segment lines to render the widget.""" if self._dirty_regions: self._render_lines() - lines = self._render_cache.lines[start:end] + + y1, y2 = line_range + lines = self._render_cache.lines[y1:y2] + if column_range is not None: + lines = self._crop_lines(lines, *column_range) return lines def get_style_at(self, x: int, y: int) -> Style: diff --git a/src/textual/widgets/_datatable.py b/src/textual/widgets/_datatable.py index e4fc65649..08fff6fd3 100644 --- a/src/textual/widgets/_datatable.py +++ b/src/textual/widgets/_datatable.py @@ -2,29 +2,34 @@ from __future__ import annotations from rich.segment import Segment -from typing import cast, Generic, TypeVar +from typing import cast, Generic, Iterable, TypeVar from collections.abc import Container from dataclasses import dataclass from rich.console import RenderableType -from rich.text import TextType +from rich.padding import Padding +from rich.style import Style +from rich.text import Text, TextType +from ..widget import Widget +from ..geometry import Size from .._lru_cache import LRUCache +from ..reactive import Reactive from .._types import Lines from ..scroll_view import ScrollView +from .._segment_tools import line_crop -RowType = TypeVar("RowType") -IndexType = TypeVar("IndexType", int, str) +CellType = TypeVar("CellType") @dataclass -class Column(Generic[IndexType]): - index: IndexType - label: TextType +class Column: + label: Text width: int visible: bool = False + index: int = 0 @dataclass @@ -32,7 +37,21 @@ class Cell: value: object -class DataTable(ScrollView, Generic[RowType, IndexType]): +class Header(Widget): + pass + + +class DataTable(ScrollView, Generic[CellType]): + + CSS = """ + DataTable Header { + display: none; + text-style: bold; + background: $primary; + color: $text-primary; + } + """ + def __init__( self, name: str | None = None, @@ -40,51 +59,115 @@ class DataTable(ScrollView, Generic[RowType, IndexType]): classes: str | None = None, ) -> None: super().__init__(name=name, id=id, classes=classes) - self.columns: list[Column[IndexType]] = [] - self.rows: dict[int, RowType] = {} + self.columns: list[Column] = [] + self.data: dict[int, list[CellType]] = {} self.row_count = 0 + self._cells: dict[int, list[Cell]] = {} - self._cell_render_cache: dict[tuple[int, IndexType, int], Lines] = LRUCache( - 1000 - ) + self._cell_render_cache: dict[tuple[int, int], Lines] = LRUCache(10000) - def add_column(self, label: TextType, index: IndexType | None, width: int) -> None: - if index is None: - index = cast(IndexType, len(self.columns)) - self.columns.append(Column(index, label, width)) + show_header = Reactive(True) + fixed_rows = Reactive(1) + fixed_columns = Reactive(1) + + def compose(self): + yield Header() + + def _update_dimensions(self) -> None: + max_width = sum(column.width for column in self.columns) + + self.virtual_size = Size(max_width, len(self.data) + self.show_header) + + def add_column(self, label: TextType, *, width: int = 10) -> None: + text_label = Text.from_markup(label) if isinstance(label, str) else label + self.columns.append(Column(text_label, width, index=len(self.columns))) + self._update_dimensions() self.refresh() - def add_row(self, row: RowType) -> None: - self.rows[self.row_count] = row + def add_row(self, *cells: CellType) -> None: + self.data[self.row_count] = list(cells) self.row_count += 1 + self._update_dimensions() self.refresh() - def _get_row(self, row_index: int) -> RowType | None: - return self.rows.get(row_index) + def get_row(self, y: int) -> list[CellType | Text]: - def _get_cell(self, row_index: int, column: IndexType) -> object | None: - row = self.rows.get(row_index) - if row is None: - return None - try: - return row[column] - except LookupError: - return None + if y == 0 and self.show_header: + row = [column.label for column in self.columns] + return row - # def _render_cell(self, row_index: int, column: IndexType) -> Lines: + data_offset = y - 1 if self.show_header else 0 + data = self.data.get(data_offset) + if data is None: + return [Text() for column in self.columns] + else: + return data - # cell = self._get_cell(row_index, column) + def _render_cell(self, y: int, column: Column) -> Lines: - # def render_row( - # self, - # row: int, - # ): - # list[list[Segment]] + cell_key = (y, column.index) + if cell_key not in self._cell_render_cache: + cell = self.get_row(y)[column.index] + lines = self.app.console.render_lines( + Padding(cell, (0, 1)), + self.app.console.options.update_dimensions(column.width, 1), + ) + self._cell_render_cache[cell_key] = lines - # def _render_cell(self, row: int, column: int) -> Lines: + return self._cell_render_cache[cell_key] - # self.app.console.render_lines() + def _render_line(self, y: int, x1: int, x2: int) -> list[Segment]: - def render_lines(self, start: int, end: int) -> Lines: - pass + width = self.content_region.width + + cell_segments: list[list[Segment]] = [] + rendered_width = 0 + for column in self.columns: + lines = self._render_cell(y, column) + rendered_width += column.width + cell_segments.append(lines[0]) + + header_style = self.query("Header").first().rich_style + + fixed: list[Segment] = sum(cell_segments[: self.fixed_columns], start=[]) + fixed_width = sum(column.width for column in self.columns[: self.fixed_columns]) + + fixed = list(Segment.apply_style(fixed, header_style)) + + line: list[Segment] = [] + extend = line.extend + for segments in cell_segments: + extend(segments) + segments = fixed + line_crop(line, x1 + fixed_width, x2, width) + line = Segment.adjust_line_length(segments, width) + + if y == 0 and self.show_header: + line = list(Segment.apply_style(line, header_style)) + + return line + + def render_lines( + self, line_range: tuple[int, int], column_range: tuple[int, int] + ) -> Lines: + scroll_x, scroll_y = self.scroll_offset + y1, y2 = line_range + y1 += scroll_y + y2 += scroll_y + + x1, x2 = column_range + x1 += scroll_x + x2 += scroll_x + + fixed_lines = [ + list(self._render_line(y, x1, x2)) for y in range(0, self.fixed_rows) + ] + lines = [list(self._render_line(y, x1, x2)) for y in range(y1, y2)] + if fixed_lines: + lines = fixed_lines + lines[self.fixed_rows :] + + (base_background, base_color), (background, color) = self.colors + style = Style.from_color(color.rich_color, background.rich_color) + lines = [list(Segment.apply_style(line, style)) for line in lines] + + return lines