Allow updating the AttributedTextWidget's text

This commit is contained in:
Joscha 2019-05-14 18:57:39 +00:00
parent 55cea8ea7f
commit 9c3278b48c

View file

@ -1,4 +1,4 @@
from typing import Any from typing import Any, List, Tuple, Union
import urwid import urwid
@ -26,10 +26,44 @@ class AttributedTextWidget(urwid.Text):
work the same way. work the same way.
""" """
chunk_info = [ self._attributed_text = text
chunk.text if style is None else (style, chunk.text) super().__init__(self._convert_to_markup(text), *args, **kwargs)
for chunk, style in text.split_by("style")
@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 ATWidget = AttributedTextWidget