Canvas Classes and Functions¶
Canvas Classes¶
- class urwid.Canvas¶
base class for canvases.
Initialize the base canvas state shared by all canvas subclasses.
- cols() int¶
Return the screen column width of this canvas.
- Raises:
NotImplementedError – the subclass does not report its own width.
- content(trim_left: int = 0, trim_top: int = 0, cols: int = 0, rows: int = 0, attr: Mapping[Hashable, Hashable] | None = None) Iterator[_ContentLine]¶
Return the canvas content as a list of rows of
(attr, cs, text)tuples.- Raises:
NotImplementedError – the subclass does not implement the canvas content protocol.
- property cursor: tuple[int, int] | None¶
Return the cursor position as
(x, y), orNoneif no cursor is set.
- property decoded_text: Sequence[str]¶
Decoded text content of the canvas as a sequence of strings, one for each row.
- finalize(widget: AbstractWidget, size: tuple[()] | tuple[int] | tuple[int, int], focus: bool) None¶
Mark this canvas as finalized (should not be any future changes to its content).
This is required before caching the canvas. This happens automatically after a widget’s ‘render call returns the canvas thanks to some metaclass magic.
- Parameters:
widget – widget that rendered this canvas
size – size parameter passed to widget’s render method
focus – focus parameter passed to widget’s render method
- Raises:
CanvasError – this canvas has already been finalized and can no longer be modified.
- get_cursor() tuple[int, int] | None¶
Return the cursor position as
(x, y), orNoneif no cursor is set.
- get_pop_up() tuple[int, int, tuple[AbstractWidget, int, int]] | None¶
Return the pop-up info set on this canvas, or
Noneif none was set.
- get_pop_up_anchor_height() int | None¶
Return the anchor height set with the pop-up on this canvas, or
Noneif none was set.
- get_pop_up_click_outside() Callable[[], None] | None¶
Return the outside click callback set with the pop-up on this canvas.
- Returns:
the callback, or
Nonewhen none was set.
- get_pop_up_unhandled_key() Callable[[str], str | None] | None¶
Return the unhandled key callback set with the pop-up on this canvas, or
Noneif none was set.
- rows() int¶
Return the screen row height of this canvas.
- Raises:
NotImplementedError – the subclass does not report its own height.
- set_cursor(c: tuple[int, int] | None) None¶
Set the cursor position to
(x, y), or remove it when c isNone.- Raises:
CanvasError – this canvas has already been finalized and can no longer be modified.
- set_pop_up(w: AbstractWidget, left: int, top: int, overlay_width: int, overlay_height: int, *, anchor_height: int | None = None, on_unhandled_key: Callable[[str], str | None] | None = None, on_click_outside: Callable[[], None] | None = None) None¶
Add pop-up information to the canvas.
This information is intercepted by a PopUpTarget widget higher in the chain to display a pop-up at the given (left, top) position relative to the current canvas.
A negative position opens the pop-up to the left of or above this canvas, for example over a launcher with the current item on the launcher’s row. A pop-up that would extend past an edge of the
PopUpTargetis moved, and shrunk when it is larger, to fit inside it.- Parameters:
w – widget to use for the pop-up
left – x position for left edge of pop-up, may be negative
top – y position for top edge of pop-up, may be negative
overlay_width – width of overlay in screen columns > 0
overlay_height – height of overlay in screen rows > 0
anchor_height – rows of the launcher directly above the pop-up, >= 0, or
Noneto place the pop-up exactly as given. With an anchor,PopUpTargetkeeps the pop-up off those rows: it goes below them when it fits there, above them when it fits there, and otherwise on the side with more rows, with its height clipped to that side.on_unhandled_key – called by
PopUpTargetwith a key that w returned unhandled while it is the topmost open pop-up; it returnsNonewhen it handled the key, or the key to pass on.Nonepasses every unhandled key on.on_click_outside – called by
PopUpTargetinstead of passing on a press of mouse button 1, 2 or 3 outside w while it is the topmost open pop-up.Noneleaves such a press unhandled.
- Raises:
CanvasError – the canvas is already finalised, the anchor height is negative or the overlay size is not positive
- property text: list[bytes]¶
Return the text content of the canvas as a list of byte strings in the screen encoding, one for each row.
- translate_coords(dx: int, dy: int) _CanvasCoords¶
Return coords shifted by (dx, dy).
- property widget_info: tuple[AbstractWidget, tuple[()] | tuple[int] | tuple[int, int], bool] | None¶
Return the
(widget, size, focus)this canvas was finalized with, orNoneif not yet finalized.
- class urwid.TextCanvas(text: list[bytes] | None = None, attr: list[list[tuple[Hashable, int]]] | None = None, cs: list[list[tuple[Literal['0', 'U'] | None, int]]] | None = None, cursor: tuple[int, int] | None = None, maxcol: int | None = None, check_width: bool = True)¶
class for storing rendered text and attributes.
Build a text canvas from the given lines and attributes.
Each line of text is padded with spaces to maxcol columns. attr and cs hold one list of runs per line. A run is a
(value, length)tuple that applies value to the next length bytes of the line. The runs of a line cover it from its first byte, and their lengths add up to at most the padded line’s length. The bytes after the last run, and every line with no list of runs, getNone: the default attribute, or the default character set.For example,
attr=[[("bold", 3), ("red", 2)], [("blue", 4)]]withtext=[b"foobar", b"test string"]showsfooasbold,baasred,rwith the default attribute,testasblue, and the rest of the second line with the default attribute:>>> canvas = TextCanvas([b"foobar", b"test string"], [[("bold", 3), ("red", 2)], [("blue", 4)]]) >>> [[(a, text) for a, _cs, text in row] for row in canvas.content()] [[('bold', b'foo'), ('red', b'ba'), (None, b'r ')], [('blue', b'test'), (None, b' string')]]
- Parameters:
text – lines of text, encoded in the screen’s encoding (see
urwid.set_encoding())attr – runs of display attributes for each line: palette entry names,
AttrSpecorLayeredAttrvalues, orNonefor the default attributecs –
runs of character sets for each line:
"0": the DEC special graphics set, in a non-UTF-8 encoding."U": bytes written unchanged, without filtering control characters; in a non-UTF-8 encoding, also the IBM PC character set.None: the default set.
cursor – (x,y) of cursor or None
maxcol – screen columns taken by this canvas
check_width – check and fix width of all lines in text
- Raises:
CanvasError – a line of text is not a plain string in the screen encoding, is wider than maxcol, or has an attribute or character set run extending beyond its padded text.
TypeError – maxcol is not an integer.
- cols() int¶
Return the screen column width of this canvas.
- content(trim_left: int = 0, trim_top: int = 0, cols: int = 0, rows: int = 0, attr: Mapping[Hashable, Hashable] | None = None) Iterator[_ContentLine]¶
Return the canvas content as a list of rows where each row is a list of (attr, cs, text) tuples.
trim_left, trim_top, cols, rows may be set by CompositeCanvas when rendering a partially obscured canvas.
- Raises:
ValueError – trim_left or trim_top, together with cols or rows, selects a region outside this canvas.
- rows() int¶
Return the number of rows in this canvas.
- translated_coords(dx: int, dy: int) tuple[int, int] | None¶
Return cursor coords shifted by (dx, dy), or None if there is no cursor.
- class urwid.BlankCanvas¶
A canvas with nothing on it.
Only works as part of a composite canvas since it doesn’t know its own size.
Initialize the base canvas state shared by all canvas subclasses.
- cols() NoReturn¶
Raise
NotImplementedError: a BlankCanvas does not know its own size.- Raises:
NotImplementedError – a BlankCanvas does not know its own size.
- content(trim_left: int = 0, trim_top: int = 0, cols: int = 0, rows: int = 0, attr: Mapping[Hashable, Hashable] | None = None) Iterator[_ContentLine]¶
Return (cols, rows) of spaces with default attributes.
- rows() NoReturn¶
Raise
NotImplementedError: a BlankCanvas does not know its own size.- Raises:
NotImplementedError – a BlankCanvas does not know its own size.
- class urwid.SolidCanvas(fill_char: str | bytes, cols: int, rows: int)¶
A canvas filled completely with a single character.
Build a canvas of cols by rows screen cells, every one holding fill_char.
- Raises:
ValueError – fill_char is not exactly one screen column wide.
- cols() int¶
Return the screen column width of this canvas.
- content(trim_left: int = 0, trim_top: int = 0, cols: int | None = None, rows: int | None = None, attr: Mapping[Hashable, Hashable] | None = None) Iterator[_ContentLine]¶
Return the canvas content as rows of
(attr, cs, text)tuples, each row filled with fill_char.
- rows() int¶
Return the screen row height of this canvas.
- class urwid.CompositeCanvas(canv: Canvas | None = None)¶
class for storing a combination of canvases.
- Parameters:
canv – a Canvas object to wrap this CompositeCanvas around.
if canv is a CompositeCanvas, make a copy of its contents
- cols() int¶
Return the screen column width of this canvas.
- Raises:
TypeError – the shards add up to a non-integer column count.
- content(trim_left: int = 0, trim_top: int = 0, cols: int = 0, rows: int = 0, attr: Mapping[Hashable, Hashable] | None = None) Iterator[_ContentLine]¶
Return the canvas content as a list of rows where each row is a list of (attr, cs, text) tuples.
All parameters are ignored.
- fill_attr(a: Hashable) None¶
Apply attribute a to all areas of this canvas with default attribute currently set to None.
Other attributes are left intact.
- fill_attr_apply(mapping: Mapping[Hashable, Hashable]) None¶
Apply an attribute-mapping dictionary to the canvas.
Attributes not in mapping are kept, placed over
mapping[None]when it is set, so their ‘inherit’ colors show it (seeLayeredAttr). An attribute mapping sends toNoneshowsmapping[None].- Parameters:
mapping – dictionary of original-attribute:new-attribute items
- Raises:
CanvasError – this canvas has already been finalized and can no longer be modified.
- overlay(other: CompositeCanvas, left: int, top: int) None¶
Overlay other onto this canvas.
- Raises:
CanvasError – this canvas has already been finalized and can no longer be modified.
ValueError – other does not fit within this canvas at the given left and top offsets.
- pad_trim_left_right(left: int, right: int) None¶
Pad or trim this canvas on the left and right.
values > 0 indicate screen columns to pad values < 0 indicate screen columns to trim
- Raises:
CanvasError – this canvas has already been finalized and can no longer be modified.
- pad_trim_top_bottom(top: int, bottom: int) None¶
Pad or trim this canvas on the top and bottom.
- Raises:
CanvasError – this canvas has already been finalized and can no longer be modified.
- rows() int¶
Return the screen row height of this canvas.
- Raises:
TypeError – a shard carries a non-integer row count.
- set_depends(widget_list: Sequence[AbstractWidget]) None¶
Explicitly specify the list of widgets that this canvas depends on.
If any of these widgets change this canvas will have to be updated.
- Raises:
CanvasError – this canvas has already been finalized and can no longer be modified.
- trim(top: int, count: int | None = None) None¶
Trim lines from the top and/or bottom of canvas.
- Parameters:
top – number of lines to remove from top
count – number of lines to keep, or None for all the rest
- Raises:
ValueError – top is negative, or is at least the number of rows in this canvas.
CanvasError – this canvas has already been finalized and can no longer be modified.
- trim_end(end: int) None¶
Trim lines from the bottom of the canvas.
- Parameters:
end – number of lines to remove from the end
- Raises:
ValueError – end is not positive, or is greater than the number of rows in this canvas.
CanvasError – this canvas has already been finalized and can no longer be modified.
CompositeCanvas Builders¶
- urwid.CanvasCombine(canvas_info: Iterable[tuple[Canvas, Any, bool]]) CompositeCanvas¶
Stack canvases in l vertically and return resulting canvas.
- Parameters:
canvas_info –
list of (canvas, position, focus) tuples:
- position
a value that widget.set_focus will accept or None if not allowed
- focus
True if this canvas is the one that would be in focus if the whole widget is in focus
- urwid.CanvasJoin(canvas_info: Iterable[tuple[Canvas, Any, bool, int]]) CompositeCanvas¶
Join canvases in l horizontally. Return result.
- Parameters:
canvas_info –
list of (canvas, position, focus, cols) tuples:
- position
value that widget.set_focus will accept or None if not allowed
- focus
True if this canvas is the one that would be in focus if the whole widget is in focus
- cols
is the number of screen columns that this widget will require, if larger than the actual canvas.cols() value then this widget will be padded on the right.
- urwid.CanvasOverlay(top_c: Canvas, bottom_c: Canvas, left: int, top: int) CompositeCanvas¶
Overlay canvas top_c onto bottom_c at position (left, top).
CanvasCache¶
- class urwid.CanvasCache¶
Cache for rendered canvases.
Automatically populated and accessed by Widget render() MetaClass magic, cleared by Widget._invalidate().
Stores weakrefs to the canvas objects, so an external class must maintain a reference for this cache to be effective. At present the Screen classes store the last topmost canvas after redrawing the screen, keeping the canvases from being garbage collected.
_widgets[widget] = {(wcls, size, focus): weakref.ref(canvas), …} _refs[weakref.ref(canvas)] = (widget, wcls, size, focus) _deps[widget] = {dependent_widget, …} _children[dependent_widget] = {widget, …}
_children is the reverse of _deps. It removes a dependent widget from _deps once that widget has no cached canvas left. Widgets are not guaranteed to be weak-referenceable, so neither index can use weak references.
- classmethod cleanup(ref: ReferenceType[Canvas]) None¶
Drop the cache entry for a canvas weakref once the canvas it points to has been garbage collected.
- classmethod clear() None¶
Empty the cache.
- classmethod fetch(widget: AbstractWidget, wcls: type[AbstractWidget], size: tuple[int, int] | tuple[int] | tuple[()], focus: bool) Canvas | None¶
Return the cached canvas or None.
- Parameters:
widget – widget object requested
wcls – widget class that contains render() function
size – size parameter passed to the widget’s render method
focus – focus parameter passed to the widget’s render method
- classmethod invalidate(widget: AbstractWidget) None¶
Remove all canvases cached for widget.
- classmethod store(wcls: type[AbstractWidget], canvas: Canvas) None¶
Store a weakref to canvas in the cache.
- Parameters:
wcls – widget class that contains render() function
canvas – rendered canvas with widget_info (widget, size, focus)
- Raises:
TypeError – canvas has not been finalized, so it carries no widget_info.