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), or None if 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), or None if no cursor is set.

get_pop_up() → tuple[int, int, tuple[AbstractWidget, PopUpSize, PopUpSize]] | None

Return the pop-up info set on this canvas, or None if none was set.

get_pop_up_align() → tuple[str | None, str | None]

Return the horizontal and vertical alignments set with the pop-up on this canvas.

Returns:

the left and top alignments given to CompositeCanvas.set_pop_up(), as strings; None for an axis given as an offset, and (None, None) when no pop-up was set.

get_pop_up_anchor_height() → int | None

Return the anchor height set with the pop-up on this canvas, or None if none was set.

get_pop_up_anchor_width() → tuple[int, Literal['left', 'right']] | None

Return the horizontal anchor set with the pop-up on this canvas.

Returns:

(anchor_width, anchor_side) as given to CompositeCanvas.set_pop_up(), or None when the pop-up was set without anchor_width or no pop-up 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 None when none was set.

get_pop_up_margin() → tuple[int, int] | None

Return the margin set with the pop-up on this canvas.

Returns:

the (columns, rows) margin given to CompositeCanvas.set_pop_up(), or None when the pop-up was set without a margin or no pop-up was set.

get_pop_up_on_anchor_side() → Callable[[Literal['left', 'right']], None] | None

Return the callback set with the pop-up on this canvas to learn which side of it the anchor ended up on.

Returns:

the on_anchor_side callback given to CompositeCanvas.set_pop_up(), or None when none was set or no pop-up was set.

get_pop_up_pass_key_below() → PopUpPassKey | None

Return the callback for keys passed below the pop-up set on this canvas, or None if 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 None if 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 is None.

Raises:

CanvasError – this canvas has already been finalized and can no longer be modified.

set_pop_up(w: AbstractWidget, left: PopUpLeft, top: PopUpTop, overlay_width: PopUpSize, overlay_height: PopUpSize, *, anchor_height: int | None = None, anchor_width: int | None = None, anchor_side: Literal['left', 'right'] = 'left', on_anchor_side: Callable[[Literal['left', 'right']], None] | None = None, on_unhandled_key: Callable[[str], str | None] | None = None, pass_key_below: PopUpPassKey | None = None, on_click_outside: Callable[[], None] | None = None, margin: tuple[int, int] | 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 PopUpTarget is moved, and shrunk when it is larger, to fit inside it.

An alignment instead of a number places the pop-up inside the whole PopUpTarget, wherever this canvas is: left="center", top="middle" centres a dialog on the screen. It is applied after the size is known, so it also centres a "pack" sized pop-up.

Parameters:
  • w – widget to use for the pop-up

  • left – x position for left edge of pop-up, may be negative, or "left", "center" or "right" to align the pop-up inside the target

  • top – y position for top edge of pop-up, may be negative, or "top", "middle" or "bottom" to align the pop-up inside the target

  • overlay_width – width of overlay in screen columns > 0, ("relative", percentage) of the columns from the pop-up’s left edge to the right edge of the PopUpTarget (of all its columns when left is an alignment), with a percentage > 0, or "pack" for the width of w as a fixed widget

  • overlay_height – height of overlay in screen rows > 0, ("relative", percentage) of the rows from the pop-up’s top edge to the bottom edge of the PopUpTarget (of all its rows when top is an alignment), with a percentage > 0, or "pack" for the rows of w as a flow widget at the pop-up width

  • anchor_height – rows of the launcher directly above the pop-up, >= 0, or None to place the pop-up exactly as given. With an anchor, PopUpTarget keeps 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. It needs top as a number of rows.

  • anchor_width – columns of the anchor beside the pop-up, >= 0, such as a launcher or the menu that opened the pop-up, or None to place the pop-up exactly as given. With an anchor, PopUpTarget keeps the pop-up off those columns, by the same rule as for anchor_height, with the side anchor_side gives preferred. It needs left as a number of columns: the column of the anchor edge that the pop-up touches on its preferred side. A relative overlay_width is then a percentage of the columns on the preferred side.

  • anchor_side – the side of the pop-up the anchor is on. "left": the anchor is the anchor_width columns before left, and the pop-up prefers to start at left, to the right of the anchor. "right": the anchor is the anchor_width columns from left on, and the pop-up prefers to end just before left, to the left of the anchor. It needs anchor_width.

  • on_anchor_side – called by PopUpTarget each time it places the pop-up, with the side of the pop-up the anchor ended up on, in the terms of anchor_side. It differs from anchor_side when the pop-up moved to the other side of the anchor. A widget that opens a chain of pop-ups, such as submenus, uses it to know which way leads back. It needs anchor_width.

  • on_unhandled_key – called by PopUpTarget with a key that w returned unhandled while it is the topmost open pop-up; it returns None when it handled the key, or the key to pass on. None passes every unhandled key on.

  • pass_key_below – called by PopUpTarget with a key that w and on_unhandled_key left unhandled while w is the topmost open pop-up, and with a function that sends a key to the widgets w is drawn over. That function returns the key when those widgets leave it unhandled, and None when they handled it. The callback returns the key to pass on, or None when the key was handled. It belongs to the pop-up that was topmost when the key arrived, so it can run after that pop-up closed during the same keypress. None passes every such key on without offering it to the widgets under the pop-up.

  • on_click_outside – called by PopUpTarget instead of passing on a press of mouse button 1, 2 or 3 outside w while it is the topmost open pop-up. None leaves such a press unhandled.

  • margin – (columns, rows) of the PopUpTarget kept clear at each of its edges, each >= 0, or None for no margin. The pop-up is at most as large as the target without the margins, whatever its size was given as. An alignment places it inside the margins, and a relative size on an aligned axis is a percentage of the cells inside them. A pop-up placed by a number is not moved; it is shifted only to fit inside the target. A margin that would leave no cell inside is reduced until at least one cell is left.

Raises:

CanvasError – the canvas is already finalised, the anchor height or width is negative, an anchor height is given with an aligned top, an anchor width with an aligned left, anchor_side is neither "left" nor "right", anchor_side="right" or on_anchor_side is given without an anchor width, a position is neither a number nor an alignment of its axis, an overlay dimension is not a positive integer, a positive finite percentage or "pack", or margin is not a pair of integers >= 0

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, or None if 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, get None: the default attribute, or the default character set.

For example, attr=[[("bold", 3), ("red", 2)], [("blue", 4)]] with text=[b"foobar", b"test string"] shows foo as bold, ba as red, r with the default attribute, test as blue, 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, AttrSpec or LayeredAttr values, or None for the default attribute

  • cs –

    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 (see LayeredAttr). An attribute mapping sends to None shows mapping[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.

Terminal Canvas

The canvas of the Terminal and TerminalOutput widgets, available on every platform.

class urwid.TermCanvas(width: int, height: int, widget: _TermCanvasOwner, *, scroll_on_output: bool = True, term_type: TermType = 'linux')

Canvas holding a terminal’s screen and scrollback content, for the widget that owns it.

Initialize an empty width by height canvas backing widget.

Parameters:
  • scroll_on_output – move a view scrolled back from the bottom to the bottom when output arrives. When off, the view stays on the lines it shows while new lines scroll into the scrollback below them.

  • term_type – the terminal type the output is written for: "linux" follows the Linux console where it differs from xterm, "xterm-256color" follows xterm.

addbyte(byte: int) → None

Parse main charset and add the processed byte(s) to the terminal state machine.

Parameters:

byte – an integer ordinal

addstr(data: Iterable[int]) → None

Feed a sequence of input bytes through the terminal parser, one byte at a time.

property escbuf: bytes

Return the buffered bytes of the escape sequence being parsed.

get_utf8_len(bytenum: int) → int

Process startbyte and return the number of bytes following it to get a valid UTF-8 multibyte sequence.

Parameters:

bytenum – an integer ordinal

leave_escape() → None

Reset the escape-sequence parser state, discarding any sequence being read.

parse_csi(char: bytes) → None

Parse ECMA-48 CSI (Control Sequence Introducer) sequences.

parse_dcs(body: bytes) → None

Apply the DCS string body, given without its ESC P and ST framing.

DECRQSS and XTGETTCAP are answered and DECRSPS is applied. As in xterm, DECRSPS is applied from the VT300 level (63) on, and at the VT100 level (61) DECRQSS does not answer the conformance level. Any other DCS string is ignored.

parse_escape(char: bytes) → None

Feed char, read inside an escape sequence, to that sequence.

It is a parameter or final byte of an ESC or CSI sequence, or a character of a string. process_char() handles control characters outside strings itself.

parse_noncsi(char: bytes, mod: bytes = b'') → None

Parse escape sequences which are not CSI.

parse_osc(buf: bytes) → None

Parse operating system command: a window title, or an OSC 8 hyperlink for the text written after it.

The OSC bodies are recognised by urwid.ansi_parser.resolve_osc_title() and urwid.ansi_parser.resolve_osc_hyperlink(), shared with ANSIText. An invalid OSC 8 command ends the current link, so the text after it does not point at the previous target; An over-long one, which never reaches this method, ends it as well. The body is in the encoding addbyte() passes characters on in, and as in tmux, a title that is not valid in it is not set. A string that had a sequence that is not valid UTF-8, in UTF-8 mode, sets no title and ends the current link.

Parameters:

buf – the OSC command body, excluding the ESC ] framing and terminator.

property parsestate: ParseState

Return the state of the escape-sequence parser.

Setting it to a number that names no ParseState raises ValueError.

process_char(char: int | bytes) → None

Process a single character (single- and multi-byte).

Display control mode, the 8-bit CSI and the controls inside the Linux palette sequence are handled here, and REP is tracked; everything else is the escape-sequence state machine’s, see urwid.ansi_parser._vt_parser._VTParser.

Parameters:

char – a byte string

property reads_utf8: bool

Whether input bytes are decoded as UTF-8.

They are when the data selected UTF-8 (ESC % G) or urwid’s encoding is UTF-8. Otherwise each byte is one character in urwid’s encoding.

set_g01(char: bytes, mod: bytes) → None

Designate the character set of final byte char to the slot of intermediate byte mod.

The slots are G0 for (, G2 for *, G3 for + and G1 for any other byte.

property within_escape: bool

Return whether an escape sequence is being read.

class urwid.TermCharset(*, g1_graphics: bool = True)

Tracks the terminal’s G0 to G3 character set slots and which one is currently active.

Initialize with G0, G2 and G3 at the default charset, G0 active.

Parameters:

g1_graphics – G1 starts as DEC special graphics, as on the Linux console; otherwise it starts at the default charset, as in xterm.

activate(g: int) → None

Activate the given charset slot.

A pending single shift still applies to the next character.

apply_mapping(char: bytes) → bytes

Map char through the active IBM PC/DEC special character set, tracking which slot the result came from.

A display writes a charset “U” cell to the host terminal unchanged. With the UTF-8 encoding a control character there would be executed by the host terminal, so it is stored as ?.

define(g: int, charset: str, *, final: bytes | None = None, size96: bool = False) → None

Redefine G’g’ with new mapping.

Parameters:
  • g – the slot, 0 to 3 for G0 to G3.

  • charset – the name of the character set, a key of MAPPING.

  • final – the final byte of the designation, reported by DECCIR; the one charset is known by by default. A final that is not one byte from 0 to ~, or is ;, cannot be reported and is replaced so too.

  • size96 – the designation is of a 96-character set.

property designations: tuple[bytes, int]

Return the final bytes G0 to G3 were designated with, and a bit per slot holding a 96-character set.

end_single_shift() → None

End a single shift after the character it applied to.

gr

the slot invoked into GR by LS1R, LS2R or LS3R; GR is not drawn from, only reported

property ibmpc_mapped: bool

Return whether the characters written are mapped as the IBM PC character set, by SGR 11 or a designation.

reset_sgr_ibmpc() → None

Reset graphics rendition mapping to IBM PC CP437.

set_sgr_ibmpc() → None

Set graphics rendition mapping to IBM PC CP437.

single_shift(g: int) → None

Draw the next character only from slot g, as SS2 and SS3 do.

property single_shifted: int | None

Return the slot a pending single shift draws the next character from, or None without one.

class urwid.TermModes(display_ctrl: bool = False, insert: bool = False, lfnl: bool = False, keys_decckm: bool = False, reverse_video: bool = False, constrain_scrolling: bool = False, autowrap: bool = True, visible_cursor: bool = True, bracketed_paste: bool = False, synchronized_output: bool = False, in_band_resize: bool = False, mouse_tracking: PrivateMode | None = None, mouse_encoding: PrivateMode | None = None, alternate_screen: bool = False, keyboard_flags: list[int] = <factory>, main_charset: Literal[1, 2]=1, keypad_application: bool = False, backarrow_sends_backspace: bool = False, cursor_style: int | None = None, iso_protection: bool = False, focus_reporting: bool = False, alternate_scroll: bool = False, left_right_margins: bool = False)

Terminal mode flags (ECMA-48 and DEC private modes) tracked for a TermCanvas.

reset() → None

Reset every mode flag to its terminal-startup default.

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: weakref.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.