From 9c3278b48c053eb75f959cd7f8bcb28ea0846134 Mon Sep 17 00:00:00 2001 From: Joscha Date: Tue, 14 May 2019 18:57:39 +0000 Subject: [PATCH] Allow updating the AttributedTextWidget's text --- cheuph/widgets/attributed_text_widget.py | 44 +++++++++++++++++++++--- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/cheuph/widgets/attributed_text_widget.py b/cheuph/widgets/attributed_text_widget.py index 50af55e..921a49f 100644 --- a/cheuph/widgets/attributed_text_widget.py +++ b/cheuph/widgets/attributed_text_widget.py @@ -1,4 +1,4 @@ -from typing import Any +from typing import Any, List, Tuple, Union import urwid @@ -26,10 +26,44 @@ class AttributedTextWidget(urwid.Text): work the same way. """ - chunk_info = [ - chunk.text if style is None else (style, chunk.text) - for chunk, style in text.split_by("style") + self._attributed_text = text + super().__init__(self._convert_to_markup(text), *args, **kwargs) + + @staticmethod + def _convert_to_markup(text: AttributedText + ) -> List[Union[str, Tuple[str, str]]]: + + # Wonder why it can't figure out the type signature of markup on its + # own... :P + markup: List[Union[str, Tuple[str, str]]] + markup = [ + segment.text if style is None else (style, segment.text) + for segment, style in text.split_by("style") ] - super().__init__(chunk_info, *args, **kwargs) + + return markup or [""] + + def set_attributed_text(self, text: AttributedText) -> None: + """ + Set the content of the AttributedTextWidget. + """ + + self._attributed_text = text + super().set_text(self._convert_to_markup(text)) + + def get_attributed_text(self) -> AttributedText: + """ + Returns the currently used AttributedText. + + urwid.Text's get_text() also returns a run length encoded list of + attributes. This is not necessary here because the AttributedText + already contains all its attributes. + """ + + return self._attributed_text + + @property + def attributed_text(self) -> AttributedText: + return self.get_attributed_text() ATWidget = AttributedTextWidget