From a80f4c3788d07b1e8a19b986686ff7ac11234a70 Mon Sep 17 00:00:00 2001 From: Joscha Date: Tue, 14 May 2019 16:15:39 +0000 Subject: [PATCH] Add AttributedTextWidget --- cheuph/__init__.py | 2 ++ cheuph/widgets/__init__.py | 6 ++++ cheuph/widgets/attributed_text_widget.py | 35 ++++++++++++++++++++++++ 3 files changed, 43 insertions(+) create mode 100644 cheuph/widgets/__init__.py create mode 100644 cheuph/widgets/attributed_text_widget.py diff --git a/cheuph/__init__.py b/cheuph/__init__.py index a93c15e..3d3cbfc 100644 --- a/cheuph/__init__.py +++ b/cheuph/__init__.py @@ -6,6 +6,7 @@ from .exceptions import * from .markup import * from .tree_display import * from .tree_list import * +from .widgets import * __all__: List[str] = [] __all__ += element.__all__ @@ -14,3 +15,4 @@ __all__ += exceptions.__all__ __all__ += markup.__all__ __all__ += tree_display.__all__ __all__ += tree_list.__all__ +__all__ += widgets.__all__ diff --git a/cheuph/widgets/__init__.py b/cheuph/widgets/__init__.py new file mode 100644 index 0000000..47dec9c --- /dev/null +++ b/cheuph/widgets/__init__.py @@ -0,0 +1,6 @@ +from typing import List + +from .attributed_text_widget import * + +__all__: List[str] = [] +__all__ += attributed_text_widget.__all__ diff --git a/cheuph/widgets/attributed_text_widget.py b/cheuph/widgets/attributed_text_widget.py new file mode 100644 index 0000000..50af55e --- /dev/null +++ b/cheuph/widgets/attributed_text_widget.py @@ -0,0 +1,35 @@ +from typing import Any + +import urwid + +from ..markup import AttributedText + +__all__ = ["AttributedTextWidget", "ATWidget"] + +class AttributedTextWidget(urwid.Text): + """ + A widget that works like urwid.Text, but displays AttributedText. + + The AttributedText's "style" attribute is used as the style for urwid.Text, + where present. + """ + + def __init__(self, + text: AttributedText, + *args: Any, + **kwargs: Any + ) -> None: + """ + text - an AttributedText object + + All other arguments are passed onto a urwid.Text constructor and thus + work the same way. + """ + + chunk_info = [ + chunk.text if style is None else (style, chunk.text) + for chunk, style in text.split_by("style") + ] + super().__init__(chunk_info, *args, **kwargs) + +ATWidget = AttributedTextWidget