From bf90f7032d2f9a471ab2626be4bf53fa434d034c Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Fri, 16 Sep 2022 16:14:28 +0100 Subject: [PATCH] text log widget --- docs/examples/events/bubble01.py | 27 +++++ docs/guide/events.md | 31 ++++- src/textual/reactive.py | 5 +- src/textual/scroll_view.py | 4 + src/textual/widget.py | 177 +++++++++++++++++++++++------ src/textual/widgets/__init__.py | 1 + src/textual/widgets/__init__.pyi | 1 + src/textual/widgets/_data_table.py | 15 +-- src/textual/widgets/_text_log.py | 98 ++++++++++++++++ 9 files changed, 304 insertions(+), 55 deletions(-) create mode 100644 docs/examples/events/bubble01.py create mode 100644 src/textual/widgets/_text_log.py diff --git a/docs/examples/events/bubble01.py b/docs/examples/events/bubble01.py new file mode 100644 index 000000000..5084273ef --- /dev/null +++ b/docs/examples/events/bubble01.py @@ -0,0 +1,27 @@ +from textual.app import App, ComposeResult + +from textual.widgets import Static, TextLog + + +class BubbleApp(App): + + CSS = """ + + + + + """ + + def compose(self) -> ComposeResult: + Static("Foo", id="static") + yield TextLog() + + def on_key(self) -> None: + log = self.query_one(TextLog) + self.query_one(TextLog).write(self.tree) + log.write(repr((log.size, log.virtual_size))) + + +app = BubbleApp() +if __name__ == "__main__": + app.run() diff --git a/docs/guide/events.md b/docs/guide/events.md index 53603112c..9c4b54b49 100644 --- a/docs/guide/events.md +++ b/docs/guide/events.md @@ -4,11 +4,9 @@ We've used event handler methods in many of the examples in this guide. This cha ## Messages -Events are a particular kind of *message* which is sent by Textual in response to input and other state changes. Events are reserved for use by Textual but you can create messages for the purpose of coordinating between widgets in your app. +Events are a particular kind of *message* which is sent by Textual in response to input and other state changes. Events are reserved for use by Textual but you can also create custom messages for the purpose of coordinating between widgets in your app. -More on that later, but for now keep in mind that events are also messages, and anything that is true of messages is also true of events. - -Event classes (as used in event handlers) extend the [Event][textual.events.Event] class, which itself extends the [Message][textual.message.Message] class. +More on that later, but for now keep in mind that events are also messages, and anything that is true of messages is true of events. ## Message Queue @@ -20,7 +18,7 @@ This processing of messages is done within an asyncio Task which is started when If you aren't yet familiar with asyncio, you can consider this part to be black box and trust that Textual will get events to your handler methods. -By way of an example, let's consider what happens if the user types "Text" in to a text input widget. When the user hits the ++t++ key it is translated in to a [key][textual.events.Key] event and sent to the widget's message queue. Ditto for ++e++, ++x++, and ++t++. +By way of an example, let's consider what happens if you were to type "Text" in to a text input widget. When you hit the ++t++ key it is translated in to a [key][textual.events.Key] event and sent to the widget's message queue. Ditto for ++e++, ++x++, and ++t++. The widget's task will pick the first key event from the queue (for the ++t++ key) and call the `on_key` handler to update the display. @@ -38,9 +36,32 @@ When the `on_key` method returns, Textual will get the next event off the the qu --8<-- "docs/images/events/queue2.excalidraw.svg" +## Creating Messages + ## Handlers +### Naming + +Let's explore how Textual decides what method to call for a given event. + +- Start with `"on_"`. +- Add the messages namespace (if any) converted from CamelCase to snake_case plus an underscore `"_"` +- Add the name of the class converted from CamelCase to snake_case. + +### Default behaviors + +You may be familiar with using Python's [super](https://docs.python.org/3/library/functions.html#super) function to call a function defined in a base class. You will not have to do this for Textual event handlers as Textual will automatically call any handler methods defined in the base class *after* the current handler has run. This allows textual to run any default behavior for the given event. + +For instance if a widget defines an `on_key` handler it will run when the user hits a key. Textual will also run `Widget.on_key`, which allows Textual to respond to any key bindings. This is generally desirable, but you can prevent Textual from running the base class handler by calling [prevent_default()][textual.message.Message.prevent_default] on the event object. + +For the case of key events, you may want to prevent the default behavior for keys that you handle by calling `event.prevent_default()`, but allow the base class to handle all other keys. + +### Bubbling + + + +
TODO: events docs diff --git a/src/textual/reactive.py b/src/textual/reactive.py index 7859ec784..53694076a 100644 --- a/src/textual/reactive.py +++ b/src/textual/reactive.py @@ -94,8 +94,9 @@ class Reactive(Generic[ReactiveType]): for key in obj.__class__.__dict__.keys(): if startswith(key, "_init_"): name = key[6:] - default = getattr(obj, key) - setattr(obj, name, default() if callable(default) else default) + if not hasattr(obj, name): + default = getattr(obj, key) + setattr(obj, name, default() if callable(default) else default) def __set_name__(self, owner: Type[MessageTarget], name: str) -> None: diff --git a/src/textual/scroll_view.py b/src/textual/scroll_view.py index 34eb72987..5d15b360c 100644 --- a/src/textual/scroll_view.py +++ b/src/textual/scroll_view.py @@ -68,6 +68,9 @@ class ScrollView(Widget): """ return self.virtual_size.height + def watch_virtual_size(self, virtual_size: Size) -> None: + self._scroll_update(virtual_size) + def _size_updated( self, size: Size, virtual_size: Size, container_size: Size ) -> None: @@ -78,6 +81,7 @@ class ScrollView(Widget): virtual_size (Size): New virtual size. container_size (Size): New container size. """ + virtual_size = self.virtual_size if self._size != size: self._size = size diff --git a/src/textual/widget.py b/src/textual/widget.py index ea5edc37f..994ba4bd8 100644 --- a/src/textual/widget.py +++ b/src/textual/widget.py @@ -922,135 +922,241 @@ class Widget(DOMNode): duration=duration, ) - def scroll_home(self, *, animate: bool = True) -> bool: + def scroll_home( + self, + *, + animate: bool = True, + speed: float | None = None, + duration: float | None = None, + ) -> bool: """Scroll to home position. Args: animate (bool, optional): Animate scroll. Defaults to True. + speed (float | None, optional): Speed of scroll if animate is True. Or None to use duration. + duration (float | None, optional): Duration of animation, if animate is True and speed is False. Returns: bool: True if any scrolling was done. """ - return self.scroll_to(0, 0, animate=animate, duration=1) + if speed is None and duration is None: + duration = 1.0 + return self.scroll_to(0, 0, animate=animate, speed=speed, duration=duration) - def scroll_end(self, *, animate: bool = True) -> bool: + def scroll_end( + self, + *, + animate: bool = True, + speed: float | None = None, + duration: float | None = None, + ) -> bool: """Scroll to the end of the container. Args: animate (bool, optional): Animate scroll. Defaults to True. + speed (float | None, optional): Speed of scroll if animate is True. Or None to use duration. + duration (float | None, optional): Duration of animation, if animate is True and speed is False. Returns: bool: True if any scrolling was done. """ - return self.scroll_to(0, self.max_scroll_y, animate=animate, duration=1) + if speed is None and duration is None: + duration = 1.0 + return self.scroll_to( + 0, self.max_scroll_y, animate=animate, speed=speed, duration=duration + ) - def scroll_left(self, *, animate: bool = True) -> bool: + def scroll_left( + self, + *, + animate: bool = True, + speed: float | None = None, + duration: float | None = None, + ) -> bool: """Scroll one cell left. Args: animate (bool, optional): Animate scroll. Defaults to True. + speed (float | None, optional): Speed of scroll if animate is True. Or None to use duration. + duration (float | None, optional): Duration of animation, if animate is True and speed is False. Returns: bool: True if any scrolling was done. """ - return self.scroll_to(x=self.scroll_target_x - 1, animate=animate) + return self.scroll_to( + x=self.scroll_target_x - 1, animate=animate, speed=speed, duration=duration + ) - def scroll_right(self, *, animate: bool = True) -> bool: + def scroll_right( + self, + *, + animate: bool = True, + speed: float | None = None, + duration: float | None = None, + ) -> bool: """Scroll on cell right. Args: animate (bool, optional): Animate scroll. Defaults to True. + speed (float | None, optional): Speed of scroll if animate is True. Or None to use duration. + duration (float | None, optional): Duration of animation, if animate is True and speed is False. Returns: bool: True if any scrolling was done. """ - return self.scroll_to(x=self.scroll_target_x + 1, animate=animate) + return self.scroll_to( + x=self.scroll_target_x + 1, animate=animate, speed=speed, duration=duration + ) - def scroll_down(self, *, animate: bool = True) -> bool: + def scroll_down( + self, + *, + animate: bool = True, + speed: float | None = None, + duration: float | None = None, + ) -> bool: """Scroll one line down. Args: animate (bool, optional): Animate scroll. Defaults to True. + speed (float | None, optional): Speed of scroll if animate is True. Or None to use duration. + duration (float | None, optional): Duration of animation, if animate is True and speed is False. Returns: bool: True if any scrolling was done. """ - return self.scroll_to(y=self.scroll_target_y + 1, animate=animate) + return self.scroll_to( + y=self.scroll_target_y + 1, animate=animate, speed=speed, duration=duration + ) - def scroll_up(self, *, animate: bool = True) -> bool: + def scroll_up( + self, + *, + animate: bool = True, + speed: float | None = None, + duration: float | None = None, + ) -> bool: """Scroll one line up. Args: animate (bool, optional): Animate scroll. Defaults to True. + speed (float | None, optional): Speed of scroll if animate is True. Or None to use duration. + duration (float | None, optional): Duration of animation, if animate is True and speed is False. Returns: bool: True if any scrolling was done. """ - return self.scroll_to(y=self.scroll_target_y - 1, animate=animate) + return self.scroll_to( + y=self.scroll_target_y - 1, animate=animate, speed=speed, duration=duration + ) - def scroll_page_up(self, *, animate: bool = True) -> bool: + def scroll_page_up( + self, + *, + animate: bool = True, + speed: float | None = None, + duration: float | None = None, + ) -> bool: """Scroll one page up. Args: animate (bool, optional): Animate scroll. Defaults to True. + speed (float | None, optional): Speed of scroll if animate is True. Or None to use duration. + duration (float | None, optional): Duration of animation, if animate is True and speed is False. Returns: bool: True if any scrolling was done. """ return self.scroll_to( - y=self.scroll_target_y - self.container_size.height, animate=animate + y=self.scroll_target_y - self.container_size.height, + animate=animate, + speed=speed, + duration=duration, ) - def scroll_page_down(self, *, animate: bool = True) -> bool: + def scroll_page_down( + self, + *, + animate: bool = True, + speed: float | None = None, + duration: float | None = None, + ) -> bool: """Scroll one page down. Args: animate (bool, optional): Animate scroll. Defaults to True. + speed (float | None, optional): Speed of scroll if animate is True. Or None to use duration. + duration (float | None, optional): Duration of animation, if animate is True and speed is False. Returns: bool: True if any scrolling was done. """ return self.scroll_to( - y=self.scroll_target_y + self.container_size.height, animate=animate + y=self.scroll_target_y + self.container_size.height, + animate=animate, + speed=speed, + duration=duration, ) - def scroll_page_left(self, *, animate: bool = True) -> bool: + def scroll_page_left( + self, + *, + animate: bool = True, + speed: float | None = None, + duration: float | None = None, + ) -> bool: """Scroll one page left. Args: animate (bool, optional): Animate scroll. Defaults to True. + speed (float | None, optional): Speed of scroll if animate is True. Or None to use duration. + duration (float | None, optional): Duration of animation, if animate is True and speed is False. Returns: bool: True if any scrolling was done. """ + if speed is None and duration is None: + duration = 0.3 return self.scroll_to( x=self.scroll_target_x - self.container_size.width, animate=animate, - duration=0.3, + speed=speed, + duration=duration, ) - def scroll_page_right(self, *, animate: bool = True) -> bool: + def scroll_page_right( + self, + *, + animate: bool = True, + speed: float | None = None, + duration: float | None = None, + ) -> bool: """Scroll one page right. Args: animate (bool, optional): Animate scroll. Defaults to True. + speed (float | None, optional): Speed of scroll if animate is True. Or None to use duration. + duration (float | None, optional): Duration of animation, if animate is True and speed is False. Returns: bool: True if any scrolling was done. """ + if speed is None and duration is None: + duration = 0.3 return self.scroll_to( x=self.scroll_target_x + self.container_size.width, animate=animate, - duration=0.3, + speed=speed, + duration=duration, ) def scroll_to_widget(self, widget: Widget, *, animate: bool = True) -> bool: @@ -1294,26 +1400,27 @@ class Widget(DOMNode): self.virtual_size = virtual_size self._container_size = container_size if self.is_scrollable: - self._refresh_scrollbars() - width, height = self.container_size - if self.show_vertical_scrollbar: - self.vertical_scrollbar.window_virtual_size = virtual_size.height - self.vertical_scrollbar.window_size = ( - height - self.scrollbar_size_horizontal - ) - if self.show_horizontal_scrollbar: - self.horizontal_scrollbar.window_virtual_size = virtual_size.width - self.horizontal_scrollbar.window_size = ( - width - self.scrollbar_size_vertical - ) - - self.scroll_x = self.validate_scroll_x(self.scroll_x) - self.scroll_y = self.validate_scroll_y(self.scroll_y) + self._scroll_update(virtual_size) self.refresh(layout=True) self.scroll_to(self.scroll_x, self.scroll_y) else: self.refresh() + def _scroll_update(self, virtual_size): + self._refresh_scrollbars() + width, height = self.container_size + if self.show_vertical_scrollbar: + self.vertical_scrollbar.window_virtual_size = virtual_size.height + self.vertical_scrollbar.window_size = ( + height - self.scrollbar_size_horizontal + ) + if self.show_horizontal_scrollbar: + self.horizontal_scrollbar.window_virtual_size = virtual_size.width + self.horizontal_scrollbar.window_size = width - self.scrollbar_size_vertical + + self.scroll_x = self.validate_scroll_x(self.scroll_x) + self.scroll_y = self.validate_scroll_y(self.scroll_y) + def _render_content(self) -> None: """Render all lines.""" width, height = self.size diff --git a/src/textual/widgets/__init__.py b/src/textual/widgets/__init__.py index 447110325..df9fc54e6 100644 --- a/src/textual/widgets/__init__.py +++ b/src/textual/widgets/__init__.py @@ -20,6 +20,7 @@ __all__ = [ "Pretty", "Static", "TextInput", + "TextLog", "TreeControl", "Welcome", ] diff --git a/src/textual/widgets/__init__.pyi b/src/textual/widgets/__init__.pyi index 49537d599..530227341 100644 --- a/src/textual/widgets/__init__.pyi +++ b/src/textual/widgets/__init__.pyi @@ -8,5 +8,6 @@ from ._placeholder import Placeholder as Placeholder from ._pretty import Pretty as Pretty from ._static import Static as Static from ._text_input import TextInput as TextInput +from ._text_log import TextLog as TextLog from ._tree_control import TreeControl as TreeControl from ._welcome import Welcome as Welcome diff --git a/src/textual/widgets/_data_table.py b/src/textual/widgets/_data_table.py index 5bf59fd54..57bbaa5b2 100644 --- a/src/textual/widgets/_data_table.py +++ b/src/textual/widgets/_data_table.py @@ -20,7 +20,7 @@ from ..geometry import clamp, Region, Size, Spacing from ..reactive import Reactive from .._profile import timer from ..scroll_view import ScrollView -from ..widget import Widget + from .. import messages @@ -155,6 +155,7 @@ class DataTable(ScrollView, Generic[CellType], can_focus=True): def __init__( self, + *, name: str | None = None, id: str | None = None, classes: str | None = None, @@ -522,18 +523,6 @@ class DataTable(ScrollView, Generic[CellType], can_focus=True): return self._render_line(y, scroll_x, scroll_x + width, style) - def render_lines(self, crop: Region) -> Lines: - """Render the widget in to lines. - - Args: - crop (Region): Region within visible area to. - - Returns: - Lines: A list of list of segments - """ - lines = self._styles_cache.render_widget(self, crop) - return lines - def on_mouse_move(self, event: events.MouseMove): meta = event.style.meta if meta: diff --git a/src/textual/widgets/_text_log.py b/src/textual/widgets/_text_log.py new file mode 100644 index 000000000..cb3a82f44 --- /dev/null +++ b/src/textual/widgets/_text_log.py @@ -0,0 +1,98 @@ +from __future__ import annotations + +from rich.console import RenderableType +from rich.segment import Segment + +from ..reactive import var +from ..geometry import Size, Region +from ..scroll_view import ScrollView +from .._cache import LRUCache +from .._segment_tools import line_crop +from .._types import Lines + + +class TextLog(ScrollView, can_focus=True): + DEFAULT_CSS = """ + TextLog{ + background: $surface; + color: $text; + } + """ + + max_lines: var[int | None] = var(None) + + def __init__( + self, + *, + max_lines: int | None = None, + name: str | None = None, + id: str | None = None, + classes: str | None = None, + ) -> None: + self.max_lines = max_lines + self.lines: list[list[Segment]] = [] + self._line_cache: LRUCache[tuple[int, int, int, int], list[Segment]] + self._line_cache = LRUCache(1024) + self.max_width: int = 0 + super().__init__(name=name, id=id, classes=classes) + + def write(self, content: RenderableType) -> None: + """Write text or a rich renderable. + + Args: + content (RenderableType): Rich renderable (or text). + """ + console = self.app.console + width = self.size.width or 80 + lines = self.app.console.render_lines( + content, console.options.update_width(width) + ) + self.max_width = max( + self.max_width, + max(sum(segment.cell_length for segment in _line) for _line in lines), + ) + self.lines.extend(lines) + + if self.max_lines is not None: + self.lines = self.lines[-self.max_lines :] + self.virtual_size = Size(self.max_width, len(self.lines)) + self.scroll_end(animate=True, speed=100) + + def clear(self) -> None: + """Clear the text log.""" + del self.lines[:] + self.max_width = 0 + self.virtual_size = Size(self.max_width, len(self.lines)) + + def render_line(self, y: int) -> list[Segment]: + scroll_x, scroll_y = self.scroll_offset + return self._render_line(scroll_y + y, scroll_x, self.size.width) + + def render_lines(self, crop: Region) -> Lines: + """Render the widget in to lines. + + Args: + crop (Region): Region within visible area to. + + Returns: + Lines: A list of list of segments + """ + lines = self._styles_cache.render_widget(self, crop) + return lines + + def _render_line(self, y: int, scroll_x: int, width: int) -> list[Segment]: + + if y >= len(self.lines): + return [Segment(" " * width, self.rich_style)] + + key = (y, scroll_x, width, self.max_width) + if key in self._line_cache: + return self._line_cache[key] + + line = self.lines[y] + line = Segment.adjust_line_length( + line, max(self.max_width, width), self.rich_style + ) + line = line_crop(line, scroll_x, scroll_x + width, self.max_width) + self._line_cache[key] = line + return line