Skip to content

xnano.devices

xnano.devices

xnano.devices

The devices a terminal is made of: its Screen, its Speaker, its Microphone, its Keyboard, its Mouse and its Clock.

A canvas has every device, on the screen or off it: canvas.screen, canvas.speaker, canvas.microphone, canvas.keyboard, canvas.mouse and canvas.clock. Inside a hook the context has the same devices, and its keyboard and mouse also read the event being handled. You do not create these classes; they are what those attributes are.

Classes:

  • PlayOptions –

    The keyword options of play. An option replaces the same value on a

  • Beats –

    The musical clock of a terminal: where the music is, in beats.

  • Clock –

    The clock of a terminal: the time everything that moves follows.

  • Cursor –

    The one cursor a canvas has.

  • Keyboard –

    The keyboard of a terminal: what is typed, what is held down, and the program's own keys.

  • HeldButton –

    A mouse button the program holds down: move it to drag, and let go with release.

  • Mouse –

    The mouse of a terminal: the pointer event being handled, the buttons held, and the wheel.

  • Scroll –

    The mouse wheel: the steps of the wheel report being handled, and the program's own turns.

  • Output –

    The last frame a canvas drew, and the text printed while it was on the screen.

  • Screen –

    The screen of a terminal: what is written and drawn on it, and how it looks.

  • Speaker –

    The speaker of a terminal: notes, melodies, sounds and playable components.

  • Microphone –

    The canvas's microphone: how loud the sound at the default input device is.

Attributes:

  • KeyName (TypeAlias) –

    The name of a key such as 'q', 'enter' or 'page_up'.

  • KeyNames (TypeAlias) –

    One key name, or several that count the same, such as ('a', 'left').

KeyName module-attribute

KeyName: TypeAlias = Literal['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'space', 'enter', 'escape', 'tab', 'backspace', 'delete', 'insert', 'home', 'end', 'page_up', 'page_down', 'up', 'down', 'left', 'right', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12', 'f13', 'f14', 'f15', 'f16', 'f17', 'f18', 'f19', 'f20', 'f21', 'f22', 'f23', 'f24', 'caps_lock', 'scroll_lock', 'num_lock', 'print_screen', 'pause', 'menu'] | str

KeyNames module-attribute

One key name, or several that count the same, such as ('a', 'left').

PlayOptions

Bases: TypedDict

The keyword options of play. An option replaces the same value on a Note.

Attributes:

instrument instance-attribute

instrument: InstrumentName

A built-in instrument name.

velocity instance-attribute

velocity: float

How hard a note is played.

effects instance-attribute

Sound effects as dictionaries with a kind key.

volume instance-attribute

volume: float

Playback gain.

pan instance-attribute

pan: float

Stereo position.

at_beat instance-attribute

at_beat: int

The beat of the musical clock to start on.

beats instance-attribute

beats: float

The length in beats.

Beats

Beats(canvas: Canvas[object, object])

The musical clock of a terminal: where the music is, in beats.

Get it from clock.beats. It counts beats at the clock's bpm from when it is started, and stands still while it is paused or the whole clock is paused. Notes and melodies played with at_beat wait for it.

Attributes:

Examples:

import xnano

with xnano.new(width=20, height=2) as canvas:
    ball = canvas.screen.write('o')
    ball.x = (canvas.clock.beats.position % 1) * 19
    canvas.clock.beats.start()
    canvas.clock.step(delta_seconds=0.25)
    assert canvas.evaluate(canvas.clock.beats.position) == 0.5

Create a view of the musical clock. Use clock.beats instead of calling this.

Methods:

  • start –

    Start the musical clock.

  • pause –

    Pause the musical clock, keeping its position.

  • resume –

    Let the musical clock run on from where pause left it.

  • stop –

    Stop the musical clock and return it to the first beat.

Source code in xnano/devices/_clock.py
def __init__(self, canvas: Canvas[object, object]) -> None:
    """Create a view of the musical clock. Use ``clock.beats`` instead of calling this."""
    self._canvas = canvas

position property

position: NumericValue

The musical clock's position in beats, as an expression.

It stays at 0 until the clock is started with start or a sound is played with at_beat.

start

start() -> None

Start the musical clock.

Source code in xnano/devices/_clock.py
def start(self) -> None:
    """Start the musical clock."""
    self._canvas._audio_device().start()

pause

pause() -> None

Pause the musical clock, keeping its position.

Source code in xnano/devices/_clock.py
def pause(self) -> None:
    """Pause the musical clock, keeping its position."""
    self._canvas._audio_device().pause()

resume

resume() -> None

Let the musical clock run on from where pause left it.

Source code in xnano/devices/_clock.py
def resume(self) -> None:
    """Let the musical clock run on from where [`pause`][xnano.devices.Beats.pause] left it."""
    self._canvas._audio_device().resume()

stop

stop() -> None

Stop the musical clock and return it to the first beat.

This rewinds only the musical clock. To freeze the whole canvas, this clock included, use Clock.pause.

Source code in xnano/devices/_clock.py
def stop(self) -> None:
    """
    Stop the musical clock and return it to the first beat.

    This rewinds only the musical clock. To freeze the whole canvas, this clock included,
    use [`Clock.pause`][xnano.devices.Clock.pause].
    """
    self._canvas._audio_device().stop()

Clock

Clock(canvas: Canvas[object, object])

The clock of a terminal: the time everything that moves follows.

Get it from Canvas.clock, or from context.clock inside a hook. Animations, effects, expressions, hook timers (every and after), fixed-step updates, the frame rate and the musical beat all follow it. Any thread may read it. Used in arithmetic it is the expression TimeElapsed, so canvas.clock / 2 is a value that follows the clock. pause freezes all of them while input keeps arriving, step moves a clock one frame at a time, and sleep waits until some of its time has passed.

elapsed_seconds, delta_seconds and measured_fps are numbers you read now; the expressions a placement keeps following, such as TimeElapsed, are in xnano.expressions. A Frame carries the same numbers. fps is the most frames the canvas draws per second, and measured_fps the rate at which it drew its recent frames.

Attributes:

  • elapsed_seconds (float) –

    Seconds since the canvas started, not counting time spent paused.

  • elapsed_milliseconds (float) –

    The same, in milliseconds.

  • delta_seconds (float) –

    Seconds between the two most recent frames.

  • frame (int) –

    The number of steps the clock has counted.

  • fps (float) –

    The most frames drawn per second, and the rate iter aims for.

  • measured_fps (float) –

    The rate at which the canvas drew its recent frames, in frames per second.

  • bpm (float) –

    Beats per minute: the length of a beat for beat timers, notes and melodies.

  • beats (Beats) –

    The musical clock: its position in beats, started and stopped on its own.

  • is_paused (bool) –

    Whether time is frozen.

  • is_realtime (bool) –

    Whether time follows the wall clock. A canvas from xnano.new() without realtime=True moves only when you move it.

Examples:

import xnano

with xnano.new(width=20, height=1) as canvas:
    ball = canvas.screen.write('o')
    ball.x = (canvas.screen.width - 1) * ((canvas.clock / 2) % 1.0)
    canvas.clock.step(delta_seconds=1.0)
    assert canvas.clock.elapsed_seconds == 1.0
    canvas.clock.pause()
    assert canvas.clock.is_paused
    canvas.clock.step(delta_seconds=0.5)
    assert canvas.clock.elapsed_seconds == 1.5

Create the canvas's clock. Use canvas.clock instead of calling this.

Parameters:

Methods:

  • pause –

    Freeze time.

  • resume –

    Let time run on from where pause froze it.

  • step –

    Move time by delta_seconds, one frame by default, and draw exactly one frame.

  • sleep –

    Wait until seconds of the canvas's time have passed, while it goes on drawing.

  • sleep_async –

    Wait until seconds of the canvas's time have passed, with await.

Source code in xnano/devices/_clock.py
def __init__(self, canvas: Canvas[object, object]) -> None:
    """
    Create the canvas's clock. Use ``canvas.clock`` instead of calling this.

    Args:
        canvas: The root canvas the clock belongs to.
    """
    self._canvas = canvas

elapsed_seconds property

elapsed_seconds: float

Seconds since the canvas started, not counting time spent paused.

elapsed_milliseconds property

elapsed_milliseconds: float

Milliseconds since the canvas started, not counting time spent paused.

delta_seconds property

delta_seconds: float

Seconds between the two most recent frames.

frame property

frame: int

The number of steps the clock has counted, including steps that drew nothing.

measured_fps property

measured_fps: float

The rate at which the canvas drew its recent frames, in frames per second.

A canvas draws a frame when something on it changes, at most fps times a second, so a screen that changes less often reads below fps. A canvas that runs by itself (on the screen, or realtime=True) measures the rate on the wall clock, time spent paused included. A canvas from new() measures it on its own clock, so steps of one frame that each change something read fps. It is 0.0 until the canvas has drawn a few frames.

Examples:

import xnano

with xnano.new(width=8, height=1, fps=20) as canvas:
    label = canvas.screen.write('')
    for index in range(10):
        label.text = str(index)
        canvas.clock.step()
    assert round(canvas.clock.measured_fps) == 20

fps property writable

fps: float

The most frames drawn per second, and the rate iter aims for.

Assign a new rate at any time, from a hook as well: the next frame follows it, and a canvas from new() steps by the new length from its next step on.

Raises:

Examples:

import xnano

with xnano.new(width=8, height=1, fps=10) as canvas:
    canvas.clock.step()
    canvas.clock.fps = 20
    frame = canvas.clock.step()
    assert round(frame.delta_seconds, 3) == 0.05

bpm property writable

bpm: float

Beats per minute: the length of a beat for beat timers, notes and melodies.

It is 120 unless new(bpm=...) said otherwise, and it can change while things are playing; the change applies from the next beat.

Raises:

  • ValueError –

    The tempo is not above 0 and at most 600000.

beats property

beats: Beats

The musical clock: its position in beats, started, paused and stopped on its own.

is_paused property

is_paused: bool

Whether time is frozen by pause.

is_realtime property

is_realtime: bool

Whether time follows the wall clock instead of moving only when you move it.

pause

pause() -> None

Freeze time.

Animations, effects, expressions, timers, fixed-step updates and the musical beat stand still. The canvas still draws and input still arrives, so a key can resume it, and step moves it one frame at a time. Pausing a paused canvas does nothing.

Raises:

  • TerminalClosedError –

    The canvas is closed.

Source code in xnano/devices/_clock.py
def pause(self) -> None:
    """
    Freeze time.

    Animations, effects, expressions, timers, fixed-step updates and the musical beat stand
    still. The canvas still draws and input still arrives, so a key can
    [`resume`][xnano.devices.Clock.resume] it, and [`step`][xnano.devices.Clock.step] moves it one
    frame at a time. Pausing a paused canvas does nothing.

    Raises:
        TerminalClosedError: The canvas is closed.
    """
    canvas = self._canvas
    canvas._require_open()
    canvas._time_source.stop()
    audio = canvas._audio
    if audio is not None:
        canvas._host.post(audio._hold)
    # A frozen canvas still draws what changes, so it draws once more now.
    canvas._request_frame()

resume

resume() -> None

Let time run on from where pause froze it.

Resuming a canvas that is not paused does nothing.

Raises:

  • TerminalClosedError –

    The canvas is closed.

Source code in xnano/devices/_clock.py
def resume(self) -> None:
    """
    Let time run on from where [`pause`][xnano.devices.Clock.pause] froze it.

    Resuming a canvas that is not paused does nothing.

    Raises:
        TerminalClosedError: The canvas is closed.
    """
    canvas = self._canvas
    canvas._require_open()
    canvas._time_source.resume()
    audio = canvas._audio
    if audio is not None:
        canvas._host.post(audio._release)

step

step(*, delta_seconds: float | None = None) -> Frame

Move time by delta_seconds, one frame by default, and draw exactly one frame.

This is step; see it for every case.

Parameters:

  • delta_seconds (float | None, default: None ) –

    How far to move, above zero; one frame of the canvas's fps when None.

Returns:

Source code in xnano/devices/_clock.py
def step(self, *, delta_seconds: float | None = None) -> Frame:
    """
    Move time by ``delta_seconds``, one frame by default, and draw exactly one frame.

    This is [`step`][xnano.devices.Clock.step]; see it for every case.

    Args:
        delta_seconds: How far to move, above zero; one frame of the canvas's ``fps``
            when ``None``.

    Returns:
        The [`Frame`][xnano.hooks.Frame] that was drawn.
    """
    return self._canvas._step(delta_seconds)

sleep

sleep(seconds: float) -> None

Wait until seconds of the canvas's time have passed, while it goes on drawing.

On a canvas that runs by itself (on the screen, or realtime=True) your program waits here, like time.sleep, while animations, hooks and input go on. Time spent paused does not count, so on a paused canvas the wait goes on until it is resumed. On a canvas from new() the clock moves seconds at once, one frame of its fps at a time, so the hooks, timers and animations due in that time run as they would have.

The wait ends early when the canvas quits or closes.

Parameters:

  • seconds (float) –

    How long to wait, in seconds of the canvas's time; 0 or more.

Raises:

  • ValueError –

    seconds is negative or not a finite number.

  • TerminalError –

    It was called from a hook of a canvas that runs by itself, where waiting would freeze the screen; or the canvas has a manual clock that is paused, so the time would never pass.

  • TerminalClosedError –

    The canvas is closed.

Examples:

import xnano

with xnano.new(width=8, height=1, fps=10) as canvas:
    ticks = []
    canvas.hook(lambda: ticks.append(1), on='tick', every=0.5)
    canvas.clock.sleep(2)
    assert round(canvas.clock.elapsed_seconds, 6) == 2.0 and len(ticks) == 4
Source code in xnano/devices/_clock.py
def sleep(self, seconds: float) -> None:
    """
    Wait until ``seconds`` of the canvas's time have passed, while it goes on drawing.

    On a canvas that runs by itself (on the screen, or ``realtime=True``) your program waits
    here, like ``time.sleep``, while animations, hooks and input go on. Time spent paused
    does not count, so on a paused canvas the wait goes on until it is resumed. On a canvas
    from ``new()`` the clock moves ``seconds`` at once, one frame of its ``fps`` at a time,
    so the hooks, timers and animations due in that time run as they would have.

    The wait ends early when the canvas quits or closes.

    Args:
        seconds: How long to wait, in seconds of the canvas's time; ``0`` or more.

    Raises:
        ValueError: ``seconds`` is negative or not a finite number.
        TerminalError: It was called from a hook of a canvas that runs by itself, where
            waiting would freeze the screen; or the canvas has a manual clock that is
            paused, so the time would never pass.
        TerminalClosedError: The canvas is closed.

    Examples:
        ```python
        import xnano

        with xnano.new(width=8, height=1, fps=10) as canvas:
            ticks = []
            canvas.hook(lambda: ticks.append(1), on='tick', every=0.5)
            canvas.clock.sleep(2)
            assert round(canvas.clock.elapsed_seconds, 6) == 2.0 and len(ticks) == 4
        ```
    """
    canvas = self._check_sleep(seconds)
    if canvas._host.is_autonomous:
        clock = canvas._time_source
        target = clock.elapsed_seconds + seconds
        while canvas.is_running:
            remaining = target - clock.elapsed_seconds
            if remaining <= 0:
                return
            canvas._stop_requested.wait(
                _PAUSED_POLL if clock.is_stopped else remaining
            )
        return
    for delta in self._manual_steps(canvas, seconds):
        canvas._step(delta)

sleep_async async

sleep_async(seconds: float) -> None

Wait until seconds of the canvas's time have passed, with await.

The same as sleep, while your event loop goes on running other tasks; on a canvas from new() other tasks run between the frames it moves.

Examples:

import asyncio

import xnano


async def main() -> float:
    async with xnano.new(realtime=True, width=8, height=1) as canvas:
        start = canvas.clock.elapsed_seconds
        await canvas.clock.sleep_async(0.05)
        return canvas.clock.elapsed_seconds - start


assert asyncio.run(main()) >= 0.05
Source code in xnano/devices/_clock.py
async def sleep_async(self, seconds: float) -> None:
    """
    Wait until ``seconds`` of the canvas's time have passed, with ``await``.

    The same as [`sleep`][xnano.devices.Clock.sleep], while your event loop goes on running
    other tasks; on a canvas from ``new()`` other tasks run between the frames it moves.

    Examples:
        ```python
        import asyncio

        import xnano


        async def main() -> float:
            async with xnano.new(realtime=True, width=8, height=1) as canvas:
                start = canvas.clock.elapsed_seconds
                await canvas.clock.sleep_async(0.05)
                return canvas.clock.elapsed_seconds - start


        assert asyncio.run(main()) >= 0.05
        ```
    """
    import asyncio

    canvas = self._check_sleep(seconds)
    if canvas._host.is_autonomous:
        clock = canvas._time_source
        target = clock.elapsed_seconds + seconds
        while canvas.is_running:
            remaining = target - clock.elapsed_seconds
            if remaining <= 0:
                return
            await canvas._stop_requested.wait_async(
                _PAUSED_POLL if clock.is_stopped else remaining
            )
        return
    for delta in self._manual_steps(canvas, seconds):
        canvas._step(delta)
        await asyncio.sleep(0)

Cursor

Cursor(canvas: Canvas[object, object])

Bases: _SealedAttributes

The one cursor a canvas has.

Get it from Screen.cursor or from context.screen.cursor inside a hook. A canvas draws no cursor until it is given a position, which a text field does to show where typing goes. Any thread may change it, a change is drawn on the next frame even when no cell changed, and a canvas on the screen gives the user's own cursor back when it closes. Opening a canvas on the screen keeps its cursor as it was.

Moving is relative to where the cursor is: up, down, left and right move it by a count of cells, and move moves it along both axes at once. The cursor stays inside the canvas, so moving past an edge stops at the edge. A cursor with no position moves from the top-left cell. Each of these returns the cursor, so they chain.

Attributes:

  • position (Point | None) –

    The cell the cursor is at as a Point, or None when it has none. Assign a Point, an (x, y) pair or None.

  • shape (CursorShape | None) –

    'block', 'bar' or 'underline'; None keeps the user's own shape.

  • is_blinking (bool) –

    Whether the cursor blinks. Setting it without a shape uses a block.

  • is_visible (bool) –

    Whether the cursor is shown when it has a position.

Raises:

  • TypeError –

    is_blinking or is_visible is assigned a value that is not True or False.

Examples:

import xnano
from xnano_core import Point

with xnano.new(width=10, height=3) as canvas:
    canvas.screen.cursor.shape = 'bar'
    canvas.screen.cursor.home().right(4).down()
    assert canvas.screen.cursor.position == Point(4, 1)

Create the canvas's cursor. Use canvas.screen.cursor instead of calling this.

Parameters:

Methods:

  • __setattr__ –

    Set an attribute, or raise AttributeError for an unknown public name.

  • move –

    Move the cursor by a number of cells along each axis.

  • up –

    Move the cursor up by count rows, stopping at the top.

  • down –

    Move the cursor down by count rows, stopping at the bottom.

  • left –

    Move the cursor left by count columns, stopping at the left edge.

  • right –

    Move the cursor right by count columns, stopping at the right edge.

  • home –

    Put the cursor in the top-left cell.

  • show –

    Make the cursor visible, in the top-left cell when it has no position yet.

  • hide –

    Hide the cursor. Its position is kept, so show brings it back.

  • follow –

    Keep the cursor at a place inside a placement, region or buffer, wherever it goes.

  • stop_following –

    Stop following a placement or buffer, leaving the cursor where it is.

Source code in xnano/devices/_cursor.py
def __init__(self, canvas: Canvas[object, object]) -> None:
    """
    Create the canvas's cursor. Use ``canvas.screen.cursor`` instead of calling this.

    Args:
        canvas: The canvas the cursor belongs to.
    """
    self._canvas = canvas
    self._seal()

position property writable

position: Point | None

The cell the cursor is at, or None when it has none.

shape property writable

shape: CursorShape | None

'block', 'bar' or 'underline'; None keeps the user's own shape.

is_blinking property writable

is_blinking: bool

Whether the cursor blinks. Setting it without a shape uses a block.

is_visible property writable

is_visible: bool

Whether the cursor is shown when it has a position.

__setattr__

__setattr__(name: str, value: object) -> None

Set an attribute, or raise AttributeError for an unknown public name.

Source code in xnano/_internal/_attributes.py
def __setattr__(self, name: str, value: object) -> None:
    """Set an attribute, or raise ``AttributeError`` for an unknown public name."""
    if (
        name[:1] != '_'
        and self.__dict__.get('_is_sealed')
        and not hasattr(type(self), name)
        and name not in self.__dict__
    ):
        kind = type(self).__name__
        settable = sorted(
            key
            for key in dir(type(self))
            if key[:1] != '_' and _is_settable(type(self), key)
        )
        close = difflib.get_close_matches(name, settable, n=1)
        hint = f' Did you mean {close[0]!r}?' if close else ''
        raise AttributeError(
            f'{kind} has no attribute called {name!r}, so assigning to it would change '
            f'nothing.{hint} The attributes you can assign are: {", ".join(settable)}.'
        )
    object.__setattr__(self, name, value)

move

move(x: int = 0, y: int = 0) -> Cursor

Move the cursor by a number of cells along each axis.

Parameters:

  • x (int, default: 0 ) –

    Columns to move right; a negative number moves left.

  • y (int, default: 0 ) –

    Rows to move down; a negative number moves up.

Returns:

  • Cursor –

    The cursor, so calls can chain.

Raises:

  • TypeError –

    An amount is not a whole number.

  • ValueError –

    An amount is outside the range of a cell number.

Examples:

import xnano
from xnano_core import Point

with xnano.new(width=10, height=3) as canvas:
    canvas.screen.cursor.position = (2, 1)
    canvas.screen.cursor.move(x=3, y=-1)
    assert canvas.screen.cursor.position == Point(5, 0)
    canvas.screen.cursor.move(x=-99)
    assert canvas.screen.cursor.position == Point(0, 0)
Source code in xnano/devices/_cursor.py
def move(self, x: int = 0, y: int = 0) -> Cursor:
    """
    Move the cursor by a number of cells along each axis.

    Args:
        x: Columns to move right; a negative number moves left.
        y: Rows to move down; a negative number moves up.

    Returns:
        The cursor, so calls can chain.

    Raises:
        TypeError: An amount is not a whole number.
        ValueError: An amount is outside the range of a cell number.

    Examples:
        ```python
        import xnano
        from xnano_core import Point

        with xnano.new(width=10, height=3) as canvas:
            canvas.screen.cursor.position = (2, 1)
            canvas.screen.cursor.move(x=3, y=-1)
            assert canvas.screen.cursor.position == Point(5, 0)
            canvas.screen.cursor.move(x=-99)
            assert canvas.screen.cursor.position == Point(0, 0)
        ```
    """
    horizontal = check_cells(x, 'x')
    vertical = check_cells(y, 'y')
    source = self._source
    current = source.position
    column, row = (0, 0) if current is None else (current.x, current.y)
    size = self._canvas.screen.size
    column = min(max(column + horizontal, 0), max(size.width - 1, 0))
    row = min(max(row + vertical, 0), max(size.height - 1, 0))
    source.position = (column, row)
    self._canvas._cursor_follow = None
    return self

up

up(count: int = 1) -> Cursor

Move the cursor up by count rows, stopping at the top.

Parameters:

  • count (int, default: 1 ) –

    How many rows to move.

Raises:

Source code in xnano/devices/_cursor.py
def up(self, count: int = 1) -> Cursor:
    """
    Move the cursor up by ``count`` rows, stopping at the top.

    Args:
        count: How many rows to move.

    Raises:
        TypeError: ``count`` is not a whole number.
        ValueError: ``count`` is negative.
    """
    return self.move(y=-check_count(count, verb='up', opposite='down'))

down

down(count: int = 1) -> Cursor

Move the cursor down by count rows, stopping at the bottom.

Parameters:

  • count (int, default: 1 ) –

    How many rows to move.

Raises:

Source code in xnano/devices/_cursor.py
def down(self, count: int = 1) -> Cursor:
    """
    Move the cursor down by ``count`` rows, stopping at the bottom.

    Args:
        count: How many rows to move.

    Raises:
        TypeError: ``count`` is not a whole number.
        ValueError: ``count`` is negative.
    """
    return self.move(y=check_count(count, verb='down', opposite='up'))

left

left(count: int = 1) -> Cursor

Move the cursor left by count columns, stopping at the left edge.

Parameters:

  • count (int, default: 1 ) –

    How many columns to move.

Raises:

Source code in xnano/devices/_cursor.py
def left(self, count: int = 1) -> Cursor:
    """
    Move the cursor left by ``count`` columns, stopping at the left edge.

    Args:
        count: How many columns to move.

    Raises:
        TypeError: ``count`` is not a whole number.
        ValueError: ``count`` is negative.
    """
    return self.move(x=-check_count(count, verb='left', opposite='right'))

right

right(count: int = 1) -> Cursor

Move the cursor right by count columns, stopping at the right edge.

Parameters:

  • count (int, default: 1 ) –

    How many columns to move.

Raises:

Source code in xnano/devices/_cursor.py
def right(self, count: int = 1) -> Cursor:
    """
    Move the cursor right by ``count`` columns, stopping at the right edge.

    Args:
        count: How many columns to move.

    Raises:
        TypeError: ``count`` is not a whole number.
        ValueError: ``count`` is negative.
    """
    return self.move(x=check_count(count, verb='right', opposite='left'))

home

home() -> Cursor

Put the cursor in the top-left cell.

Source code in xnano/devices/_cursor.py
def home(self) -> Cursor:
    """Put the cursor in the top-left cell."""
    self._source.position = (0, 0)
    self._canvas._cursor_follow = None
    return self

show

show() -> Cursor

Make the cursor visible, in the top-left cell when it has no position yet.

Examples:

import xnano
from xnano_core import Point

with xnano.new(width=10, height=3) as canvas:
    canvas.screen.cursor.show()
    assert canvas.screen.cursor.is_visible
    assert canvas.screen.cursor.position == Point(0, 0)
Source code in xnano/devices/_cursor.py
def show(self) -> Cursor:
    """
    Make the cursor visible, in the top-left cell when it has no position yet.

    Examples:
        ```python
        import xnano
        from xnano_core import Point

        with xnano.new(width=10, height=3) as canvas:
            canvas.screen.cursor.show()
            assert canvas.screen.cursor.is_visible
            assert canvas.screen.cursor.position == Point(0, 0)
        ```
    """
    source = self._source
    if source.position is None:
        source.position = (0, 0)
    source.is_visible = True
    return self

hide

hide() -> Cursor

Hide the cursor. Its position is kept, so show brings it back.

Source code in xnano/devices/_cursor.py
def hide(self) -> Cursor:
    """Hide the cursor. Its position is kept, so [`show`][xnano.devices.Cursor.show] brings it back."""
    self._source.is_visible = False
    return self

follow

follow(target: Placement[object, object] | Region | Buffer, *, x: int = 0, y: int = 0) -> Cursor

Keep the cursor at a place inside a placement, region or buffer, wherever it goes.

The cursor hides while the target, or anything above it, is hidden, and it loses its position when the target is removed. Assigning position or calling move stops the following.

Parameters:

Raises:

  • TerminalClosedError –

    The target is a placement, or a region of one, that was already removed, or its canvas is closed.

  • TypeError –

    The target is not a placement, a region or a buffer, or x or y is not a whole number.

  • ValueError –

    x or y is outside the range of a cell number.

Examples:

import xnano
from xnano_core import Point

with xnano.new(width=20, height=3) as canvas:
    field = canvas.screen.write('name', x=5, y=1)
    canvas.screen.cursor.follow(field, x=4)
    field.x = 8
    assert canvas.screen.cursor.position == Point(12, 1)
Source code in xnano/devices/_cursor.py
def follow(
    self,
    target: Placement[object, object] | Region | _core.Buffer,
    *,
    x: int = 0,
    y: int = 0,
) -> Cursor:
    """
    Keep the cursor at a place inside a placement, region or buffer, wherever it goes.

    The cursor hides while the target, or anything above it, is hidden, and it loses its
    position when the target is removed. Assigning ``position`` or calling
    [`move`][xnano.devices.Cursor.move] stops the following.

    Args:
        target: The [`Placement`][xnano.layout.Placement],
            [`Region`][xnano.layout.Region] or buffer to follow.
        x: The column inside the target.
        y: The row inside the target.

    Raises:
        TerminalClosedError: The target is a placement, or a region of one, that was
            already removed, or its canvas is closed.
        TypeError: The target is not a placement, a region or a buffer, or ``x`` or ``y``
            is not a whole number.
        ValueError: ``x`` or ``y`` is outside the range of a cell number.

    Examples:
        ```python
        import xnano
        from xnano_core import Point

        with xnano.new(width=20, height=3) as canvas:
            field = canvas.screen.write('name', x=5, y=1)
            canvas.screen.cursor.follow(field, x=4)
            field.x = 8
            assert canvas.screen.cursor.position == Point(12, 1)
        ```
    """
    x = check_cells(x, 'x')
    y = check_cells(y, 'y')
    if isinstance(target, _core.Buffer):
        buffer = target
    elif hasattr(target, 'core_buffer'):
        require_attached = getattr(target, '_require_attached', None)
        if require_attached is not None:
            require_attached()
        buffer = target.core_buffer  # type: ignore[union-attr]
    else:
        if not hasattr(target, '_inset'):
            raise TypeError(
                f'follow() takes a placement, a region or a buffer, but got {target!r}. '
                f'Pass what canvas.screen.write(...) returned, for example '
                f'canvas.screen.cursor.follow(canvas.screen.write("name")).'
            )
        region = cast('Region', target)
        require_owner_attached = getattr(region._owner, '_require_attached', None)
        if require_owner_attached is not None:
            require_owner_attached()
        buffer = region._buffer
        left, top, _, _ = region._inset
        x = check_cells(x + left, 'x')
        y = check_cells(y + top, 'y')
    self._source.follow(buffer, x=x, y=y)
    self._canvas._cursor_follow = (buffer, x, y)
    return self

stop_following

stop_following() -> Cursor

Stop following a placement or buffer, leaving the cursor where it is.

Source code in xnano/devices/_cursor.py
def stop_following(self) -> Cursor:
    """Stop following a placement or buffer, leaving the cursor where it is."""
    source = self._source
    current = source.position
    source.follow(None)
    self._canvas._cursor_follow = None
    if current is not None:
        source.position = current
    return self

Keyboard

Keyboard(canvas: Canvas[object, object], event: Event | None = None, owner: Placement[object, object] | Canvas[object, object] | None = None, context: Context[object, object] | None = None)

The keyboard of a terminal: what is typed, what is held down, and the program's own keys.

Get it from Canvas.keyboard, or from context.keyboard inside a hook. In a hook, key, binding and the rest describe the key being handled, and are None (or empty) for any other event; outside a hook there is no key being handled. held_keys and is_down answer for right now, from any thread, for a program that polls instead of listening. press, paste and random are the program's own hands: the canvas hears them like keys a person typed.

A terminal that reports key releases (kitty, ghostty and wezterm, when the canvas is opened with keyboard='release_events') tells exactly when a key is let go. Any other terminal only repeats the newest key held, so that key counts as held for a short time after its last press or repeat, and pressing a different key takes its place.

Attributes:

Examples:

import xnano

with xnano.new(width=8, height=1) as canvas:
    heard = []

    @canvas.hook(on='key')
    def listen(context: xnano.Context) -> None:
        heard.append(context.keyboard.binding)

    canvas.keyboard.press('ctrl+s')
    canvas.deliver_events()
    assert heard == ['ctrl+s']

Create a view of the keyboard. Use canvas.keyboard or context.keyboard instead.

Parameters:

  • canvas (Canvas[object, object]) –

    The root canvas the keyboard belongs to.

  • event (Event | None, default: None ) –

    The event being handled, or None outside a hook.

  • owner (Placement[object, object] | Canvas[object, object] | None, default: None ) –

    The placement or canvas a hook is attached to; None for the canvas.

  • context (Context[object, object] | None, default: None ) –

    The hook's context, which notes what a component reads; None outside a hook.

Methods:

  • is_down –

    Whether any of the keys is held down right now.

  • axis –

    -1, 0 or 1 from a pair of keys: the negative one, neither or both, the

  • direction –

    The way the arrow keys or wasd point, as (step_x, step_y).

  • press –

    Press a key on the canvas, as if it had been typed.

  • random –

    Press a random key on the canvas and return its name.

  • paste –

    Paste text on the canvas, as if the person had.

  • wait –

    Wait until a key is pressed, and return its name.

  • wait_async –

    Wait until a key is pressed, like wait, with await.

  • prompt –

    Prompt for a line of text on the screen, and return what was typed.

  • prompt_async –

    Prompt for a line of text, like prompt, with

Source code in xnano/devices/_keyboard.py
def __init__(
    self,
    canvas: Canvas[object, object],
    event: _core.Event | None = None,
    owner: Placement[object, object] | Canvas[object, object] | None = None,
    context: Context[object, object] | None = None,
) -> None:
    """
    Create a view of the keyboard. Use ``canvas.keyboard`` or ``context.keyboard`` instead.

    Args:
        canvas: The root canvas the keyboard belongs to.
        event: The event being handled, or ``None`` outside a hook.
        owner: The placement or canvas a hook is attached to; ``None`` for the canvas.
        context: The hook's context, which notes what a component reads; ``None`` outside
            a hook.
    """
    self._canvas = canvas
    self._event = event
    self._owner = owner
    self._context = context

event property

event: KeyEvent | None

The key event being handled, or None when the event is not a key.

key property

key: KeyName | None

The name of the key, such as 'q' or 'enter', or None.

kind property

kind: KeyEventKind | None

'press', 'repeat' or 'release', or None for any other event.

modifiers property

modifiers: frozenset[KeyModifier]

The modifier keys held with the key; empty for any other event.

text property

text: str | None

The text the key types, or None for control keys, key bindings and other events.

binding property

binding: KeyBindingText | None

The key with its modifiers as one text such as 'ctrl+s', or None.

pasted property

pasted: str | None

The text of the paste being handled, or None when the event is not a paste.

held_keys property

held_keys: frozenset[KeyName]

The keys held down right now.

is_down

is_down(keys: KeyNames) -> bool

Whether any of the keys is held down right now.

Parameters:

  • keys (KeyNames) –

    One key name such as 'space', or several such as ('a', 'left'), spelled as in KeyName. A key binding such as 'ctrl+s' or a modifier alone is not held input.

Raises:

  • TypeError –

    A name is not text.

  • ValueError –

    A name is not a key, or is a key binding or a modifier.

Examples:

import xnano

with xnano.new(width=20, height=3) as canvas:
    hero = canvas.screen.write('@')

    @canvas.hook(on='tick', every=1 / 30)
    def walk(context: xnano.Context) -> None:
        step_x, step_y = context.keyboard.direction()
        hero.x += step_x
        hero.y += step_y

    canvas.clock.step()
    assert not canvas.keyboard.is_down('space')
Source code in xnano/devices/_keyboard.py
def is_down(self, keys: KeyNames) -> bool:
    """
    Whether any of the keys is held down right now.

    Args:
        keys: One key name such as ``'space'``, or several such as ``('a', 'left')``,
            spelled as in [`KeyName`][xnano.devices.KeyName]. A key binding such as
            ``'ctrl+s'`` or a modifier alone is not held input.

    Raises:
        TypeError: A name is not text.
        ValueError: A name is not a key, or is a key binding or a modifier.

    Examples:
        ```python
        import xnano

        with xnano.new(width=20, height=3) as canvas:
            hero = canvas.screen.write('@')

            @canvas.hook(on='tick', every=1 / 30)
            def walk(context: xnano.Context) -> None:
                step_x, step_y = context.keyboard.direction()
                hero.x += step_x
                hero.y += step_y

            canvas.clock.step()
            assert not canvas.keyboard.is_down('space')
        ```
    """
    names = _names(keys)
    held = self.held_keys
    return any(name in held for name in names)

axis

axis(negative: KeyNames, positive: KeyNames) -> int

-1, 0 or 1 from a pair of keys: the negative one, neither or both, the positive one.

Parameters:

  • negative (KeyNames) –

    The key or keys that push toward -1.

  • positive (KeyNames) –

    The key or keys that push toward 1.

Raises:

  • TypeError –

    A name is not text.

  • ValueError –

    A name is not a key, or is a key binding or a modifier.

Source code in xnano/devices/_keyboard.py
def axis(self, negative: KeyNames, positive: KeyNames) -> int:
    """
    ``-1``, ``0`` or ``1`` from a pair of keys: the negative one, neither or both, the
    positive one.

    Args:
        negative: The key or keys that push toward ``-1``.
        positive: The key or keys that push toward ``1``.

    Raises:
        TypeError: A name is not text.
        ValueError: A name is not a key, or is a key binding or a modifier.
    """
    return int(self.is_down(positive)) - int(self.is_down(negative))

direction

direction(*, left: KeyNames = ('a', 'left'), right: KeyNames = ('d', 'right'), up: KeyNames = ('w', 'up'), down: KeyNames = ('s', 'down')) -> tuple[int, int]

The way the arrow keys or wasd point, as (step_x, step_y).

Each step is -1, 0 or 1; y grows downward, like the screen.

Parameters:

  • left (KeyNames, default: ('a', 'left') ) –

    The key or keys that mean left.

  • right (KeyNames, default: ('d', 'right') ) –

    The key or keys that mean right.

  • up (KeyNames, default: ('w', 'up') ) –

    The key or keys that mean up.

  • down (KeyNames, default: ('s', 'down') ) –

    The key or keys that mean down.

Raises:

  • TypeError –

    A name is not text.

  • ValueError –

    A name is not a key, or is a key binding or a modifier.

Source code in xnano/devices/_keyboard.py
def direction(
    self,
    *,
    left: KeyNames = ('a', 'left'),
    right: KeyNames = ('d', 'right'),
    up: KeyNames = ('w', 'up'),
    down: KeyNames = ('s', 'down'),
) -> tuple[int, int]:
    """
    The way the arrow keys or ``wasd`` point, as ``(step_x, step_y)``.

    Each step is ``-1``, ``0`` or ``1``; ``y`` grows downward, like the screen.

    Args:
        left: The key or keys that mean left.
        right: The key or keys that mean right.
        up: The key or keys that mean up.
        down: The key or keys that mean down.

    Raises:
        TypeError: A name is not text.
        ValueError: A name is not a key, or is a key binding or a modifier.
    """
    return self.axis(left, right), self.axis(up, down)

press

press(key: KeyBindingText | KeyEvent) -> None

Press a key on the canvas, as if it had been typed.

The canvas's hooks hear it at its next step, whatever the terminal settings say.

Parameters:

Raises:

  • TypeError –

    key is neither text nor a key event.

  • ValueError –

    key is text that does not name a key. The message suggests the closest key names.

Examples:

import xnano

with xnano.new(width=8, height=1) as canvas:
    heard = []

    @canvas.hook(on='key')
    def listen(context: xnano.Context) -> None:
        heard.append(context.keyboard.key)

    @canvas.hook(on='tick', after=0.1)
    def press_for_the_program(context: xnano.Context) -> None:
        context.keyboard.press('q')

    canvas.clock.step(delta_seconds=0.2)
    canvas.deliver_events()
    assert heard == ['q']
Source code in xnano/devices/_keyboard.py
def press(self, key: _core.KeyBindingText | _core.KeyEvent) -> None:
    """
    Press a key on the canvas, as if it had been typed.

    The canvas's hooks hear it at its next step, whatever the terminal settings say.

    Args:
        key: A key name or key binding such as ``'q'`` or ``'ctrl+s'``, or a
            [`KeyEvent`][xnano_core.KeyEvent].

    Raises:
        TypeError: ``key`` is neither text nor a key event.
        ValueError: ``key`` is text that does not name a key. The message suggests the
            closest key names.

    Examples:
        ```python
        import xnano

        with xnano.new(width=8, height=1) as canvas:
            heard = []

            @canvas.hook(on='key')
            def listen(context: xnano.Context) -> None:
                heard.append(context.keyboard.key)

            @canvas.hook(on='tick', after=0.1)
            def press_for_the_program(context: xnano.Context) -> None:
                context.keyboard.press('q')

            canvas.clock.step(delta_seconds=0.2)
            canvas.deliver_events()
            assert heard == ['q']
        ```
    """
    if isinstance(key, _core.KeyEvent):
        self._canvas.push(_core.Event.key_press(_modifier_text(key), kind=key.kind))
        return
    if not isinstance(key, str):
        raise TypeError(
            f"keyboard.press takes a key name such as 'q' or 'ctrl+s', or a KeyEvent, but "
            f'got {key!r}. Pass the key as text: keyboard.press("q").'
        )
    from xnano.hooks._triggers import normalize_binding

    normalize_binding(key)
    self._canvas.push(_core.Event.key_press(key))

random

random() -> KeyName

Press a random key on the canvas and return its name.

The key is a letter, a digit, 'space', 'enter', 'escape', 'tab', 'backspace', 'delete', 'insert', 'home', 'end', 'page_up', 'page_down', an arrow or 'f1' to 'f12', pressed with no modifiers. It is delivered like press(name). random.seed(...) repeats the keys.

Returns:

Examples:

import random

import xnano

with xnano.new(width=8, height=1) as canvas:
    heard = []

    @canvas.hook(on='key')
    def listen(context: xnano.Context) -> None:
        heard.append(context.keyboard.key)

    random.seed(7)
    pressed = canvas.keyboard.random()
    canvas.deliver_events()
    assert heard == [pressed]
Source code in xnano/devices/_keyboard.py
def random(self) -> KeyName:
    """
    Press a random key on the canvas and return its name.

    The key is a letter, a digit, ``'space'``, ``'enter'``, ``'escape'``, ``'tab'``,
    ``'backspace'``, ``'delete'``, ``'insert'``, ``'home'``, ``'end'``, ``'page_up'``,
    ``'page_down'``, an arrow or ``'f1'`` to ``'f12'``, pressed with no modifiers. It is
    delivered like ``press(name)``. ``random.seed(...)`` repeats the keys.

    Returns:
        The [`KeyName`][xnano.devices.KeyName] that was pressed.

    Examples:
        ```python
        import random

        import xnano

        with xnano.new(width=8, height=1) as canvas:
            heard = []

            @canvas.hook(on='key')
            def listen(context: xnano.Context) -> None:
                heard.append(context.keyboard.key)

            random.seed(7)
            pressed = canvas.keyboard.random()
            canvas.deliver_events()
            assert heard == [pressed]
        ```
    """
    from xnano.hooks._triggers import _KEY_NAMES

    name = cast('KeyName', random.choice(_KEY_NAMES))
    self.press(name)
    return name

paste

paste(text: str) -> None

Paste text on the canvas, as if the person had.

Parameters:

  • text (str) –

    The text to paste.

Raises:

Examples:

import xnano

with xnano.new(width=8, height=1) as canvas:
    pasted = []
    canvas.hook(lambda context: pasted.append(context.keyboard.pasted), on='paste')
    canvas.keyboard.paste('hello')
    canvas.deliver_events()
    assert pasted == ['hello']
Source code in xnano/devices/_keyboard.py
def paste(self, text: str) -> None:
    """
    Paste text on the canvas, as if the person had.

    Args:
        text: The text to paste.

    Raises:
        TypeError: ``text`` is not text.

    Examples:
        ```python
        import xnano

        with xnano.new(width=8, height=1) as canvas:
            pasted = []
            canvas.hook(lambda context: pasted.append(context.keyboard.pasted), on='paste')
            canvas.keyboard.paste('hello')
            canvas.deliver_events()
            assert pasted == ['hello']
        ```
    """
    if not isinstance(text, str):
        raise TypeError(
            f'keyboard.paste takes the text to paste, but received {text!r}. Pass a str, '
            f"such as canvas.keyboard.paste('hello')."
        )
    self._canvas.push(_core.Event.paste(text))

wait

wait(*keys: KeyName) -> KeyName

Wait until a key is pressed, and return its name.

Your program waits here while the canvas goes on drawing and animating. It reads like input(): nothing else runs on your thread until the key arrives.

Parameters:

  • keys (KeyName, default: () ) –

    The keys to wait for, such as 'enter' or 'q'. Give none to take any key.

Returns:

  • KeyName –

    The name of the key that was pressed.

Raises:

  • TerminalError –

    The canvas ended, or has a manual clock, so no key could arrive.

Examples:

In a program: terminal.keyboard.wait() after writing "Press any key to start". Here a timer plays the part of the person pressing the key:

import xnano

with xnano.new(realtime=True, width=30, height=2) as canvas:
    canvas.screen.write('Press enter to start')

    @canvas.hook(on='tick', after=0.05)
    def press(context: xnano.Context) -> None:
        context.keyboard.press('enter')

    assert canvas.keyboard.wait('enter') == 'enter'
Source code in xnano/devices/_keyboard.py
def wait(self, *keys: KeyName) -> KeyName:
    """
    Wait until a key is pressed, and return its name.

    Your program waits here while the canvas goes on drawing and animating. It reads
    like ``input()``: nothing else runs on your thread until the key arrives.

    Args:
        keys: The keys to wait for, such as ``'enter'`` or ``'q'``. Give none to take any key.

    Returns:
        The name of the key that was pressed.

    Raises:
        TerminalError: The canvas ended, or has a manual clock, so no key could arrive.

    Examples:
        In a program: ``terminal.keyboard.wait()`` after writing "Press any key to start".
        Here a timer plays the part of the person pressing the key:

        ```python
        import xnano

        with xnano.new(realtime=True, width=30, height=2) as canvas:
            canvas.screen.write('Press enter to start')

            @canvas.hook(on='tick', after=0.05)
            def press(context: xnano.Context) -> None:
                context.keyboard.press('enter')

            assert canvas.keyboard.wait('enter') == 'enter'
        ```
    """
    return self._canvas._wait_for_key(keys)

wait_async

wait_async(*keys: KeyName) -> Coroutine[Any, Any, KeyName]

Wait until a key is pressed, like wait, with await.

Your event loop goes on running other tasks while the canvas waits for the key.

Parameters:

  • keys (KeyName, default: () ) –

    The keys to wait for, such as 'enter' or 'q'. Give none to take any key.

Returns:

Raises:

  • TerminalError –

    The canvas ended, or has a manual clock, so no key could arrive.

Examples:

import asyncio

import xnano


async def main() -> None:
    async with xnano.new(realtime=True, width=30, height=2) as canvas:
        canvas.screen.write('Press enter to start')

        @canvas.hook(on='tick', after=0.05)
        def press(context: xnano.Context) -> None:
            context.keyboard.press('enter')

        assert await canvas.keyboard.wait_async('enter') == 'enter'


asyncio.run(main())
Source code in xnano/devices/_keyboard.py
def wait_async(self, *keys: KeyName) -> Coroutine[Any, Any, KeyName]:
    """
    Wait until a key is pressed, like [`wait`][xnano.devices.Keyboard.wait], with ``await``.

    Your event loop goes on running other tasks while the canvas waits for the key.

    Args:
        keys: The keys to wait for, such as ``'enter'`` or ``'q'``. Give none to take any key.

    Returns:
        A coroutine that gives the name of the key that was pressed.

    Raises:
        TerminalError: The canvas ended, or has a manual clock, so no key could arrive.

    Examples:
        ```python
        import asyncio

        import xnano


        async def main() -> None:
            async with xnano.new(realtime=True, width=30, height=2) as canvas:
                canvas.screen.write('Press enter to start')

                @canvas.hook(on='tick', after=0.05)
                def press(context: xnano.Context) -> None:
                    context.keyboard.press('enter')

                assert await canvas.keyboard.wait_async('enter') == 'enter'


        asyncio.run(main())
        ```
    """
    return self._canvas._wait_for_key_async(keys)

prompt

prompt(text: str, *, x: Axis = 'next', y: Axis = 'next', default: str = '') -> str

Prompt for a line of text on the screen, and return what was typed.

The prompt and the answer appear on the canvas while your program waits, like input(). Enter submits and Backspace deletes.

Parameters:

  • text (str) –

    What to ask, such as 'Your name: '.

  • x (Axis, default: 'next' ) –

    The column of the prompt, in the forms screen.write takes.

  • y (Axis, default: 'next' ) –

    The row of the prompt; on the next line by default, like screen.write.

  • default (str, default: '' ) –

    Text already in the answer, which the user can edit.

Returns:

  • str –

    What was typed, without the prompt.

Raises:

  • TerminalError –

    The canvas ended, or has a manual clock, so no answer could arrive.

Examples:

In a program: name = terminal.keyboard.prompt('Your name: '). Here a timer plays the part of the person typing:

import xnano

with xnano.new(realtime=True, width=30, height=2) as canvas:

    @canvas.hook(on='tick', after=0.05)
    def type_answer(context: xnano.Context) -> None:
        for letter in 'Ada':
            context.keyboard.press(letter)
        context.keyboard.press('enter')

    assert canvas.keyboard.prompt('Your name: ') == 'Ada'
Source code in xnano/devices/_keyboard.py
def prompt(
    self, text: str, *, x: Axis = 'next', y: Axis = 'next', default: str = ''
) -> str:
    """
    Prompt for a line of text on the screen, and return what was typed.

    The prompt and the answer appear on the canvas while your program waits, like
    ``input()``. ``Enter`` submits and ``Backspace`` deletes.

    Args:
        text: What to ask, such as ``'Your name: '``.
        x: The column of the prompt, in the forms ``screen.write`` takes.
        y: The row of the prompt; on the next line by default, like ``screen.write``.
        default: Text already in the answer, which the user can edit.

    Returns:
        What was typed, without the prompt.

    Raises:
        TerminalError: The canvas ended, or has a manual clock, so no answer could arrive.

    Examples:
        In a program: ``name = terminal.keyboard.prompt('Your name: ')``. Here a timer
        plays the part of the person typing:

        ```python
        import xnano

        with xnano.new(realtime=True, width=30, height=2) as canvas:

            @canvas.hook(on='tick', after=0.05)
            def type_answer(context: xnano.Context) -> None:
                for letter in 'Ada':
                    context.keyboard.press(letter)
                context.keyboard.press('enter')

            assert canvas.keyboard.prompt('Your name: ') == 'Ada'
        ```
    """
    return self._canvas._prompt(text, x=x, y=y, default=default)

prompt_async

prompt_async(text: str, *, x: Axis = 'next', y: Axis = 'next', default: str = '') -> Coroutine[Any, Any, str]

Prompt for a line of text, like prompt, with await.

Your event loop goes on running other tasks while the person types.

Parameters:

  • text (str) –

    What to ask, such as 'Your name: '.

  • x (Axis, default: 'next' ) –

    The column of the prompt, in the forms screen.write takes.

  • y (Axis, default: 'next' ) –

    The row of the prompt; on the next line by default.

  • default (str, default: '' ) –

    Text already in the answer, which the user can edit.

Returns:

Raises:

  • TerminalError –

    The canvas ended, or has a manual clock, so no answer could arrive.

Source code in xnano/devices/_keyboard.py
def prompt_async(
    self, text: str, *, x: Axis = 'next', y: Axis = 'next', default: str = ''
) -> Coroutine[Any, Any, str]:
    """
    Prompt for a line of text, like [`prompt`][xnano.devices.Keyboard.prompt], with
    ``await``.

    Your event loop goes on running other tasks while the person types.

    Args:
        text: What to ask, such as ``'Your name: '``.
        x: The column of the prompt, in the forms ``screen.write`` takes.
        y: The row of the prompt; on the next line by default.
        default: Text already in the answer, which the user can edit.

    Returns:
        A coroutine that gives what was typed, without the prompt.

    Raises:
        TerminalError: The canvas ended, or has a manual clock, so no answer could arrive.
    """
    return self._canvas._prompt_async(text, x=x, y=y, default=default)

HeldButton

HeldButton(mouse: Mouse, button: MouseButton)

A mouse button the program holds down: move it to drag, and let go with release.

Mouse.press returns one. In a with block the button is released when the block ends, so the block is a drag. It moves like a placement and the cursor do: move by cells along each axis, or up, down, left and right.

Attributes:

  • button (MouseButton) –

    'left', 'right' or 'middle'.

  • is_released –

    Whether the button was let go.

Examples:

import xnano

with xnano.new(width=20, height=4) as canvas:
    seen = []
    canvas.hook(lambda context: seen.append(context.mouse.kind), on='mouse')
    with canvas.mouse.press('left', x=2, y=1) as button:
        button.right(3)
    canvas.deliver_events()
    assert seen == ['press', 'drag', 'release']
    assert canvas.mouse.pointer == (5, 1)

Hold a button. Use mouse.press instead of calling this.

Methods:

  • move –

    Drag the held button by a number of cells along each axis.

  • up –

    Drag the held button up by count rows.

  • down –

    Drag the held button down by count rows.

  • left –

    Drag the held button left by count columns.

  • right –

    Drag the held button right by count columns.

  • release –

    Let go of the button where the pointer is. Releasing twice does nothing.

Source code in xnano/devices/_mouse.py
def __init__(self, mouse: Mouse, button: _core.MouseButton) -> None:
    """Hold a button. Use ``mouse.press`` instead of calling this."""
    self._mouse = mouse
    self.button: _core.MouseButton = button
    self.is_released = False

move

move(x: int = 0, y: int = 0) -> Self

Drag the held button by a number of cells along each axis.

Parameters:

  • x (int, default: 0 ) –

    Cells to the right; negative moves left.

  • y (int, default: 0 ) –

    Cells down; negative moves up.

Returns:

  • Self –

    The held button, so moves can be chained.

Source code in xnano/devices/_mouse.py
def move(self, x: int = 0, y: int = 0) -> Self:
    """
    Drag the held button by a number of cells along each axis.

    Args:
        x: Cells to the right; negative moves left.
        y: Cells down; negative moves up.

    Returns:
        The held button, so moves can be chained.
    """
    self._mouse.move(x, y)
    return self

up

up(count: int = 1) -> Self

Drag the held button up by count rows.

Source code in xnano/devices/_mouse.py
def up(self, count: int = 1) -> Self:
    """Drag the held button up by ``count`` rows."""
    return self.move(0, -count)

down

down(count: int = 1) -> Self

Drag the held button down by count rows.

Source code in xnano/devices/_mouse.py
def down(self, count: int = 1) -> Self:
    """Drag the held button down by ``count`` rows."""
    return self.move(0, count)

left

left(count: int = 1) -> Self

Drag the held button left by count columns.

Source code in xnano/devices/_mouse.py
def left(self, count: int = 1) -> Self:
    """Drag the held button left by ``count`` columns."""
    return self.move(-count, 0)

right

right(count: int = 1) -> Self

Drag the held button right by count columns.

Source code in xnano/devices/_mouse.py
def right(self, count: int = 1) -> Self:
    """Drag the held button right by ``count`` columns."""
    return self.move(count, 0)

release

release() -> None

Let go of the button where the pointer is. Releasing twice does nothing.

Source code in xnano/devices/_mouse.py
def release(self) -> None:
    """Let go of the button where the pointer is. Releasing twice does nothing."""
    if self.is_released:
        return
    self.is_released = True
    self._mouse.release(self.button)

Mouse

Mouse(canvas: Canvas[object, object], event: Event | None = None, owner: Placement[object, object] | Canvas[object, object] | None = None, context: Context[object, object] | None = None)

The mouse of a terminal: the pointer event being handled, the buttons held, and the wheel.

Get it from Canvas.mouse, or from context.mouse inside a hook. In a hook, position and kind describe the pointer event being handled, and are None for any other event (a wheel report is scroll's). button is the button of that event, and otherwise the button held right now, so it stays 'left' from the press of the left button until its release. pointer and held_buttons answer for right now, from any thread. press, click, move and scroll.turn are the program's own hands, at screen cells: the canvas hears them like a person's mouse.

The pointer moves like the cursor and a placement: assign pointer to put it at a cell, or move it by cells; with a button held, a move is a drag.

Attributes:

Examples:

import xnano

with xnano.new(width=20, height=6) as canvas:
    button = canvas.screen.write('Go', x=5, y=2, border='plain')
    clicked = []

    @button.hook(on='mouse')
    def listen(context: xnano.Context) -> None:
        if context.mouse.kind == 'press':
            clicked.append(tuple(context.mouse.position))

    canvas.mouse.click(x=6, y=3)
    canvas.deliver_events()
    assert clicked == [(6, 3)]

Create a view of the mouse. Use canvas.mouse or context.mouse instead.

Parameters:

  • canvas (Canvas[object, object]) –

    The root canvas the mouse belongs to.

  • event (Event | None, default: None ) –

    The event being handled, or None outside a hook.

  • owner (Placement[object, object] | Canvas[object, object] | None, default: None ) –

    The placement or canvas a hook is attached to, whose cells random stays inside; None for the whole canvas.

  • context (Context[object, object] | None, default: None ) –

    The hook's context, which notes what a component reads; None outside a hook.

Methods:

  • press –

    Press a mouse button and hold it, as if the person had.

  • release –

    Let go of a mouse button, as if the person had.

  • click –

    Press and release a mouse button at one cell, as if the person had clicked.

  • move –

    Move the pointer by a number of cells along each axis; with a button held, a drag.

  • random –

    Click, drag or move at a random cell of this hook's canvas or placement.

Source code in xnano/devices/_mouse.py
def __init__(
    self,
    canvas: Canvas[object, object],
    event: _core.Event | None = None,
    owner: Placement[object, object] | Canvas[object, object] | None = None,
    context: Context[object, object] | None = None,
) -> None:
    """
    Create a view of the mouse. Use ``canvas.mouse`` or ``context.mouse`` instead.

    Args:
        canvas: The root canvas the mouse belongs to.
        event: The event being handled, or ``None`` outside a hook.
        owner: The placement or canvas a hook is attached to, whose cells ``random`` stays
            inside; ``None`` for the whole canvas.
        context: The hook's context, which notes what a component reads; ``None`` outside
            a hook.
    """
    self._canvas = canvas
    self._event = event
    self._owner = owner
    self._context = context

event property

event: MouseEvent | None

The mouse event being handled, or None for any other event and for the wheel.

position property

position: Point | None

The cell of the event, or None.

button property

button: MouseButton | None

The button of the pointer event being handled, else the button held right now.

A press, a release and a drag name their own button. For any other event, and outside a hook, it is the button held down: 'left', 'right' or 'middle', the first of them in that order when several are held, or None when none is.

kind property

kind: Literal['press', 'release', 'drag', 'move'] | None

'press', 'release', 'drag' or 'move', or None.

scroll property

scroll: Scroll

The mouse wheel: the steps of the wheel report being handled, and turning it.

is_down property

is_down: bool

Whether any mouse button is held right now.

held_buttons property

held_buttons: frozenset[MouseButton]

The buttons held right now: 'left', 'right' and 'middle'.

pointer property writable

pointer: tuple[int, int] | None

The (x, y) cell the pointer was last seen at, or None before it moved.

x grows to the right and y down. Assign a cell to move the pointer there, as if the person had; with a button held it drags there.

press

press(button: MouseButton = 'left', *, x: int | None = None, y: int | None = None) -> HeldButton

Press a mouse button and hold it, as if the person had.

The button stays down until it is released: call release on what this returns, or press in a with block, which releases it when the block ends. Moving the pointer meanwhile drags the button. For a press and a release at once, use click.

Parameters:

  • button (MouseButton, default: 'left' ) –

    'left', 'right' or 'middle'.

  • x (int | None, default: None ) –

    The column to press at; where the pointer is when left out.

  • y (int | None, default: None ) –

    The row to press at; where the pointer is when left out.

Returns:

Raises:

  • ValueError –

    button is not a mouse button, or a cell number is out of range.

  • TypeError –

    A cell number is not a whole number.

Source code in xnano/devices/_mouse.py
def press(
    self,
    button: _core.MouseButton = 'left',
    *,
    x: int | None = None,
    y: int | None = None,
) -> HeldButton:
    """
    Press a mouse button and hold it, as if the person had.

    The button stays down until it is released: call ``release`` on what this returns, or
    press in a ``with`` block, which releases it when the block ends. Moving the pointer
    meanwhile drags the button. For a press and a release at once, use
    [`click`][xnano.devices.Mouse.click].

    Args:
        button: ``'left'``, ``'right'`` or ``'middle'``.
        x: The column to press at; where the pointer is when left out.
        y: The row to press at; where the pointer is when left out.

    Returns:
        The [`HeldButton`][xnano.devices.HeldButton].

    Raises:
        ValueError: ``button`` is not a mouse button, or a cell number is out of range.
        TypeError: A cell number is not a whole number.
    """
    name = _check_button(button)
    column, row = self._here(x, y, 'mouse.press')
    self._send('press', column, row, name)
    return HeldButton(self, name)

release

release(button: MouseButton = 'left', *, x: int | None = None, y: int | None = None) -> None

Let go of a mouse button, as if the person had.

Parameters:

  • button (MouseButton, default: 'left' ) –

    'left', 'right' or 'middle'.

  • x (int | None, default: None ) –

    The column to release at; where the pointer is when left out.

  • y (int | None, default: None ) –

    The row to release at; where the pointer is when left out.

Raises:

  • ValueError –

    button is not a mouse button, or a cell number is out of range.

Source code in xnano/devices/_mouse.py
def release(
    self,
    button: _core.MouseButton = 'left',
    *,
    x: int | None = None,
    y: int | None = None,
) -> None:
    """
    Let go of a mouse button, as if the person had.

    Args:
        button: ``'left'``, ``'right'`` or ``'middle'``.
        x: The column to release at; where the pointer is when left out.
        y: The row to release at; where the pointer is when left out.

    Raises:
        ValueError: ``button`` is not a mouse button, or a cell number is out of range.
    """
    name = _check_button(button)
    column, row = self._here(x, y, 'mouse.release')
    self._send('release', column, row, name)

click

click(button: MouseButton = 'left', *, x: int | None = None, y: int | None = None) -> None

Press and release a mouse button at one cell, as if the person had clicked.

Parameters:

  • button (MouseButton, default: 'left' ) –

    'left', 'right' or 'middle'.

  • x (int | None, default: None ) –

    The column to click; where the pointer is when left out.

  • y (int | None, default: None ) –

    The row to click; where the pointer is when left out.

Raises:

  • ValueError –

    button is not a mouse button, or a cell number is out of range.

Source code in xnano/devices/_mouse.py
def click(
    self,
    button: _core.MouseButton = 'left',
    *,
    x: int | None = None,
    y: int | None = None,
) -> None:
    """
    Press and release a mouse button at one cell, as if the person had clicked.

    Args:
        button: ``'left'``, ``'right'`` or ``'middle'``.
        x: The column to click; where the pointer is when left out.
        y: The row to click; where the pointer is when left out.

    Raises:
        ValueError: ``button`` is not a mouse button, or a cell number is out of range.
    """
    self.press(button, x=x, y=y).release()

move

move(x: int = 0, y: int = 0) -> None

Move the pointer by a number of cells along each axis; with a button held, a drag.

Parameters:

  • x (int, default: 0 ) –

    Cells to the right; negative moves left.

  • y (int, default: 0 ) –

    Cells down; negative moves up.

Source code in xnano/devices/_mouse.py
def move(self, x: int = 0, y: int = 0) -> None:
    """
    Move the pointer by a number of cells along each axis; with a button held, a drag.

    Args:
        x: Cells to the right; negative moves left.
        y: Cells down; negative moves up.
    """
    column, row = self._here(None, None, 'mouse.move')
    target = _cell_pair((column + x, row + y), 'mouse.move')
    self._send('move', *target)

random

random(kind: Literal['click', 'drag', 'move'] = 'click') -> tuple[int, int]

Click, drag or move at a random cell of this hook's canvas or placement.

Cells are screen cells inside the cells the hook's target covers on the screen (the whole canvas outside a hook). The left button is used. random.seed(...) repeats the cells.

Parameters:

  • kind (Literal['click', 'drag', 'move'], default: 'click' ) –

    'click' presses and releases at one cell, 'drag' presses at one cell, drags to another and releases there, and 'move' moves the pointer to one.

Returns:

  • int –

    The (x, y) cell where it ended: the clicked cell, the cell a drag was released

  • int –

    at, or the cell the pointer moved to.

Raises:

  • ValueError –

    kind is not 'click', 'drag' or 'move'.

  • TerminalError –

    The canvas or placement covers no cell on the screen.

Examples:

import random

import xnano

with xnano.new(width=20, height=6) as canvas:
    button = canvas.screen.write('Go', x=5, y=2, border='plain')
    clicked = []
    chosen = []

    @button.hook(on='mouse')
    def listen(context: xnano.Context) -> None:
        if context.mouse.kind == 'press':
            clicked.append(tuple(context.mouse.position))

    @button.hook(on='tick', after=0.1)
    def click_somewhere(context: xnano.Context) -> None:
        chosen.append(context.mouse.random())

    random.seed(3)
    canvas.clock.step(delta_seconds=0.2)
    canvas.deliver_events()
    assert clicked == chosen
    assert 5 <= chosen[0][0] < 5 + button.width
Source code in xnano/devices/_mouse.py
def random(self, kind: Literal['click', 'drag', 'move'] = 'click') -> tuple[int, int]:
    """
    Click, drag or move at a random cell of this hook's canvas or placement.

    Cells are screen cells inside the cells the hook's target covers on the screen (the
    whole canvas outside a hook). The left button is used. ``random.seed(...)`` repeats the
    cells.

    Args:
        kind: ``'click'`` presses and releases at one cell, ``'drag'`` presses at one cell,
            drags to another and releases there, and ``'move'`` moves the pointer to one.

    Returns:
        The ``(x, y)`` cell where it ended: the clicked cell, the cell a drag was released
        at, or the cell the pointer moved to.

    Raises:
        ValueError: ``kind`` is not ``'click'``, ``'drag'`` or ``'move'``.
        TerminalError: The canvas or placement covers no cell on the screen.

    Examples:
        ```python
        import random

        import xnano

        with xnano.new(width=20, height=6) as canvas:
            button = canvas.screen.write('Go', x=5, y=2, border='plain')
            clicked = []
            chosen = []

            @button.hook(on='mouse')
            def listen(context: xnano.Context) -> None:
                if context.mouse.kind == 'press':
                    clicked.append(tuple(context.mouse.position))

            @button.hook(on='tick', after=0.1)
            def click_somewhere(context: xnano.Context) -> None:
                chosen.append(context.mouse.random())

            random.seed(3)
            canvas.clock.step(delta_seconds=0.2)
            canvas.deliver_events()
            assert clicked == chosen
            assert 5 <= chosen[0][0] < 5 + button.width
        ```
    """
    if kind not in ('click', 'drag', 'move'):
        raise ValueError(
            f"mouse.random takes the kind 'click', 'drag' or 'move', but got {kind!r}. "
            f"Use mouse.random() for a click, or mouse.random('drag')."
        )
    column, row = _random_cell(self._canvas, self._owner)
    if kind == 'move':
        self._send('move', column, row)
        return column, row
    start_column, start_row = column, row
    if kind == 'drag':
        column, row = _random_cell(self._canvas, self._owner)
    steps: list[tuple[_core.MouseEventKind, int, int]] = [
        ('press', start_column, start_row)
    ]
    if kind == 'drag':
        steps.append(('drag', column, row))
    steps.append(('release', column, row))
    for event_kind, event_column, event_row in steps:
        self._canvas.push(
            _core.Event.mouse_event(
                column=event_column, row=event_row, kind=event_kind, button='left'
            )
        )
    return column, row

Scroll

Scroll(canvas: Canvas[object, object], event: Event | None, owner: Placement[object, object] | Canvas[object, object] | None)

The mouse wheel: the steps of the wheel report being handled, and the program's own turns.

Get it from mouse.scroll. x and y are signed steps that grow right and down, so scrolling up is y == -1; both are 0 unless the event being handled is a wheel report.

Attributes:

  • x (int) –

    Horizontal steps, positive to the right.

  • y (int) –

    Vertical steps, positive downward.

  • event (MouseEvent | None) –

    The wheel MouseEvent being handled, or None.

Create a view of the wheel. Use mouse.scroll instead of calling this.

Methods:

  • turn –

    Turn the mouse wheel on the canvas, as if the person had.

  • random –

    Turn the mouse wheel a random way at a random cell of this hook's canvas or placement.

Source code in xnano/devices/_mouse.py
def __init__(
    self,
    canvas: Canvas[object, object],
    event: _core.Event | None,
    owner: Placement[object, object] | Canvas[object, object] | None,
) -> None:
    """Create a view of the wheel. Use ``mouse.scroll`` instead of calling this."""
    self._canvas = canvas
    self._event = event
    self._owner = owner

event property

event: MouseEvent | None

The wheel event being handled, or None for any other event.

x property

x: int

Horizontal steps, positive to the right; 0 unless the event is a wheel report.

y property

y: int

Vertical steps, positive downward; 0 unless the event is a wheel report.

turn

turn(*, x: int = 0, y: int = 0) -> None

Turn the mouse wheel on the canvas, as if the person had.

The wheel turns at the cell the pointer was last seen at; a pointer the program moved counts as seen there at once.

Parameters:

  • x (int, default: 0 ) –

    Horizontal steps, positive to the right.

  • y (int, default: 0 ) –

    Vertical steps, positive downward: y=-1 scrolls up one step.

Raises:

  • TypeError –

    A number of steps is not a whole number.

  • ValueError –

    A number of steps is outside the range a wheel report carries.

Examples:

import xnano

with xnano.new(width=8, height=4) as canvas:
    turned = []

    @canvas.hook(on='scroll')
    def listen(context: xnano.Context) -> None:
        turned.append(context.mouse.scroll.y)

    canvas.mouse.scroll.turn(y=-2)
    canvas.deliver_events()
    assert turned == [-2]
Source code in xnano/devices/_mouse.py
def turn(self, *, x: int = 0, y: int = 0) -> None:
    """
    Turn the mouse wheel on the canvas, as if the person had.

    The wheel turns at the cell the pointer was last seen at; a pointer the program moved
    counts as seen there at once.

    Args:
        x: Horizontal steps, positive to the right.
        y: Vertical steps, positive downward: ``y=-1`` scrolls up one step.

    Raises:
        TypeError: A number of steps is not a whole number.
        ValueError: A number of steps is outside the range a wheel report carries.

    Examples:
        ```python
        import xnano

        with xnano.new(width=8, height=4) as canvas:
            turned = []

            @canvas.hook(on='scroll')
            def listen(context: xnano.Context) -> None:
                turned.append(context.mouse.scroll.y)

            canvas.mouse.scroll.turn(y=-2)
            canvas.deliver_events()
            assert turned == [-2]
        ```
    """
    steps_x, steps_y = _cell_pair(
        (x, y), 'scroll.turn', description='steps of the wheel, such as y=1'
    )
    canvas = self._canvas
    state = canvas._input_state
    cell = None if state is None else state.pointer_cell
    pushed = canvas._pushed_pointer
    if (
        pushed is not None
        and pushed[1] == cell
        and pushed[2] == canvas._time_source.frame
    ):
        cell = pushed[0]
    column, row = cell if cell is not None else (0, 0)
    canvas.push(
        _core.Event.mouse_event(
            column=column, row=row, kind='scroll', scroll_x=steps_x, scroll_y=steps_y
        )
    )

random

random() -> tuple[int, int]

Turn the mouse wheel a random way at a random cell of this hook's canvas or placement.

The wheel turns one to three steps up, down, left or right, at a screen cell inside the cells the hook's target covers on the screen (the whole canvas outside a hook). random.seed(...) repeats the turns.

Returns:

  • tuple[int, int] –

    The (x, y) steps that were turned, such as (0, -2) for two steps up.

Raises:

  • TerminalError –

    The canvas or placement covers no cell on the screen.

Source code in xnano/devices/_mouse.py
def random(self) -> tuple[int, int]:
    """
    Turn the mouse wheel a random way at a random cell of this hook's canvas or placement.

    The wheel turns one to three steps up, down, left or right, at a screen cell inside the
    cells the hook's target covers on the screen (the whole canvas outside a hook).
    ``random.seed(...)`` repeats the turns.

    Returns:
        The ``(x, y)`` steps that were turned, such as ``(0, -2)`` for two steps up.

    Raises:
        TerminalError: The canvas or placement covers no cell on the screen.
    """
    column, row = _random_cell(self._canvas, self._owner)
    amount = random.randint(1, 3)
    steps_x, steps_y = random.choice(
        ((0, -amount), (0, amount), (-amount, 0), (amount, 0))
    )
    self._canvas.push(
        _core.Event.mouse_event(
            column=column, row=row, kind='scroll', scroll_x=steps_x, scroll_y=steps_y
        )
    )
    return steps_x, steps_y

Output

Output(canvas: Canvas[object, object])

The last frame a canvas drew, and the text printed while it was on the screen.

Get it from canvas.screen.output. text, ansi, size, revision, cursor_position, is_cursor_visible, lines() and to_cell_grid() read the last frame that was drawn without drawing a new one. To see a change, draw a frame first with canvas.clock.step(), canvas.screen.output.render() or Screen.render.

Each of these shorthands reads its own snapshot of the last drawn frame at the moment it is called. Code that needs several values from one frame should call snapshot once and read them from the returned frame.

Every member raises TerminalClosedError once the canvas is closed.

Attributes:

  • is_captured (bool) –

    Whether a canvas on the screen is holding back what is printed, so it cannot corrupt the screen.

  • text (str) –

    The last drawn frame's plain text rows joined by newlines.

  • ansi (str) –

    The last drawn frame as text with styling escape sequences.

  • size (Size) –

    The size of the last drawn frame in cells.

  • revision (int) –

    A number that increases with every drawn frame; 0 before the first one.

  • cursor_position (Point | None) –

    Where the cursor is in the last drawn frame, or None when no cursor is placed.

  • is_cursor_visible (bool) –

    Whether the cursor is shown in the last drawn frame.

Examples:

import xnano

with xnano.new(width=12, height=2) as canvas:
    canvas.screen.write('hello', x=1, y=1)
    assert canvas.screen.output.revision == 0
    canvas.clock.step()
    assert canvas.screen.output.text == '\n hello'
    assert canvas.screen.output.lines() == ['', ' hello']
    assert canvas.screen.output.size.width == 12
    assert canvas.screen.output.revision == 1

Create the output's view of a canvas. Use canvas.screen.output instead of calling this.

Parameters:

  • canvas (Canvas[object, object]) –

    The canvas whose frames and held-back text this reads.

Methods:

  • render –

    Draw a frame now and return it.

  • snapshot –

    Return the last frame that was drawn, without drawing.

  • lines –

    Return the plain text rows of the last drawn frame, without drawing.

  • to_cell_grid –

    Pack the last drawn frame into the cell grid byte format, without drawing.

  • take_captured –

    Return the text printed or logged since the last call, from a canvas on the screen.

Source code in xnano/devices/_output.py
def __init__(self, canvas: Canvas[object, object]) -> None:
    """
    Create the output's view of a canvas. Use ``canvas.screen.output`` instead of calling this.

    Args:
        canvas: The canvas whose frames and held-back text this reads.
    """
    self._canvas = canvas

is_captured property

is_captured: bool

Whether a canvas on the screen is holding back what is printed, so it cannot corrupt the screen.

text property

text: str

The last drawn frame's plain text rows joined by newlines.

ansi property

ansi: str

The last drawn frame as text with styling escape sequences.

size property

size: Size

The size of the last drawn frame in cells.

revision property

revision: int

A number that increases with every drawn frame; 0 before the first one.

cursor_position property

cursor_position: Point | None

Where the cursor is in the last drawn frame, or None when no cursor is placed.

is_cursor_visible property

is_cursor_visible: bool

Whether the cursor is shown in the last drawn frame.

render

render() -> FrameSnapshot

Draw a frame now and return it.

Raises:

  • TerminalClosedError –

    The canvas is closed.

Source code in xnano/devices/_output.py
def render(self) -> _core.FrameSnapshot:
    """
    Draw a frame now and return it.

    Raises:
        TerminalClosedError: The canvas is closed.
    """
    canvas = self._canvas
    canvas._require_open()
    return canvas._host.call(lambda: canvas._runtime.render())

snapshot

snapshot() -> FrameSnapshot

Return the last frame that was drawn, without drawing.

Raises:

  • TerminalClosedError –

    The canvas is closed.

Source code in xnano/devices/_output.py
def snapshot(self) -> _core.FrameSnapshot:
    """
    Return the last frame that was drawn, without drawing.

    Raises:
        TerminalClosedError: The canvas is closed.
    """
    canvas = self._canvas
    canvas._require_open()
    return canvas._host.call(lambda: canvas._runtime.snapshot())

lines

lines() -> list[str]

Return the plain text rows of the last drawn frame, without drawing.

Raises:

  • TerminalClosedError –

    The canvas is closed.

Source code in xnano/devices/_output.py
def lines(self) -> list[str]:
    """
    Return the plain text rows of the last drawn frame, without drawing.

    Raises:
        TerminalClosedError: The canvas is closed.
    """
    return self.snapshot().lines()

to_cell_grid

to_cell_grid() -> bytes

Pack the last drawn frame into the cell grid byte format, without drawing.

Raises:

  • TerminalClosedError –

    The canvas is closed.

Source code in xnano/devices/_output.py
def to_cell_grid(self) -> bytes:
    """
    Pack the last drawn frame into the cell grid byte format, without drawing.

    Raises:
        TerminalClosedError: The canvas is closed.
    """
    return self.snapshot().to_cell_grid()

take_captured

take_captured() -> str

Return the text printed or logged since the last call, from a canvas on the screen.

A canvas on the screen holds back anything written to standard output or standard error so it cannot corrupt the screen. Text you do not take is printed when the canvas closes.

Source code in xnano/devices/_output.py
def take_captured(self) -> str:
    """
    Return the text printed or logged since the last call, from a canvas on the screen.

    A canvas on the screen holds back anything written to standard output or standard
    error so it cannot corrupt the screen. Text you do not take is printed when the
    canvas closes.
    """
    canvas = self._canvas
    canvas._require_open()
    return canvas._host.call(lambda: canvas._runtime.take_captured_output())

Screen

Screen(canvas: Canvas[DepsT, StateT])

Bases: _TextModifiers, Generic[DepsT, StateT]

The screen of a terminal: what is written and drawn on it, and how it looks.

Get it from Canvas.screen, or from context.screen inside a hook. write puts content on it and returns the Placement that holds it; region reads and writes its cells; render gives the frame as text. Its look (color, border, padding, margin and the text modifiers) is the look of the whole canvas. A canvas from new() has a screen in memory: everything works the same, and render shows what it would draw.

A canvas written into another one has a screen of its own, its area of the outer canvas; x and y say where that area is, and move moves it.

Attributes:

  • size (Size) –

    The size of the screen in cells.

  • width (int) –

    The width of the screen in cells.

  • height (int) –

    The height of the screen in cells.

  • x (int) –

    The column of the screen: 0, unless its canvas was written into another one.

  • y (int) –

    The row of the screen: 0, unless its canvas was written into another one.

  • right_edge (int) –

    The first column after the screen, x + width.

  • bottom_edge (int) –

    The first row below the screen, y + height.

  • region (Region[int]) –

    The cells of the screen as a Region.

  • cursor (Cursor) –

    The terminal's Cursor.

  • title (str | None) –

    The window title last set on this screen.

  • window (Size) –

    The size of the whole terminal window in cells, for a canvas on the screen; the size of the screen otherwise.

  • output (Output) –

    The last frame drawn, and the text printed while the canvas was on the screen.

  • core_buffer (Buffer) –

    The core buffer the screen draws, as large as the screen.

  • fx (WritableEffectProperties) –

    The visual effects of the whole screen, one method for each effect.

  • layout (CanvasLayout) –

    How the screen places what is written on it.

  • edges (EdgeBehavior) –

    What content written on the screen does at the edges of its area.

  • parent (EdgeBehavior) –

    Symbolic expressions for the parent container's width, height and size.

  • root (EdgeBehavior) –

    Symbolic expressions for the root canvas's width, height, size and time.

Examples:

import xnano

with xnano.new(width=12, height=3) as canvas:
    canvas.screen.write('hello', x='center', y='center', bold=True)
    canvas.screen.border = 'rounded'
    assert canvas.screen.render().splitlines()[1] == '│  hello   │'

Create the screen of a canvas. Use canvas.screen instead of calling this.

Parameters:

  • canvas (Canvas[DepsT, StateT]) –

    The canvas whose screen this is.

Methods:

  • __setattr__ –

    Set an attribute, or raise AttributeError for an unknown public name.

  • bold –

    Make the text bold, or undo it with False; the same as setting is_bold.

  • dim –

    Dim the text, or undo it with False; the same as setting is_dim.

  • italic –

    Make the text italic, or undo it with False; the same as setting is_italic.

  • underline –

    Underline the text, or undo it with False; the same as setting is_underlined.

  • blink –

    Make the text blink, or undo it with False; the same as setting is_blinking.

  • reverse –

    Swap the foreground and background, or undo it with False; the same as setting is_reversed.

  • hidden –

    Hide the text, or undo it with False; the same as setting is_hidden.

  • crossed_out –

    Strike the text through, or undo it with False; the same as setting is_crossed_out.

  • write –

    Put something on the canvas: text, a widget, a buffer, another canvas or an image.

  • new –

    Create a canvas inside this one and draw it here at once, at the top-left corner.

  • clear –

    Erase everything written or drawn directly on the canvas's cells.

  • update –

    Change the canvas's own cells with operations, styles or effects.

  • render –

    Draw the current frame and return it, without a screen.

  • __rich_console__ –

    Show the current frame in rich and Textual, with its colors and styles.

  • __rich_measure__ –

    Tell rich the width of what it shows, so that rich keeps it whole when it can.

  • local –

    Convert a cell of the screen into a cell of this canvas.

  • move –

    Move a canvas that is written into another one by a number of cells along each axis.

  • up –

    Move a written canvas up by count rows; see move.

  • down –

    Move a written canvas down by count rows; see move.

  • left –

    Move a written canvas left by count columns; see move.

  • right –

    Move a written canvas right by count columns; see move.

  • __contains__ –

    Whether a screen cell or a whole area is inside the cells of the canvas.

  • overlaps –

    Whether the cells of the canvas and another area share at least one screen cell.

  • __or__ –

    Apply an operation, effect or style to the screen with screen | operation.

Source code in xnano/devices/_screen.py
def __init__(self, canvas: Canvas[DepsT, StateT]) -> None:
    """
    Create the screen of a canvas. Use ``canvas.screen`` instead of calling this.

    Args:
        canvas: The canvas whose screen this is.
    """
    object.__setattr__(self, '_canvas', canvas)
    self._seal()

color property

color: Colors

The colors: color.fg for the text and color.bg for what is behind it.

Each is a ColorSlot. Assign a color name, an (red, green, blue) tuple, a Color or another slot; 'reset' clears the color.

Examples:

import xnano

with xnano.new(width=10, height=3) as canvas:
    label = canvas.screen.write('hi')
    label.color.fg = 'red'
    label.color.bg = (0, 0, 80)
    label.color.bg.lighten(0.1)
    assert label.color.fg.value == xnano.Color('red')

border property writable

The border: its kind, a setting for each side, its color and its title.

Assign 'plain', 'rounded', 'double' or 'thick' to draw a border on every side, True for 'plain' and False to remove it. It works on any content, not only on text.

The border, padding and margin are drawn around the content, so the placement grows by the cells they take. A widget with no size of its own is shrunk to fit its parent, border included.

Examples:

import xnano

with xnano.new(width=12, height=5) as canvas:
    card = canvas.screen.write('hi', border='rounded')
    card.border.top = 'double'
    card.border.left = False
    card.border.color = 'cyan'
    card.border = False
    assert not card.border

padding property writable

The space between the border and the content, edge by edge.

Assign a number of cells, a percentage such as '10%' or a dictionary such as {'vertical': 1, 'horizontal': 2}, or set one edge with padding.left = 2.

margin property writable

The transparent space outside the border, edge by edge, set like padding.

is_bold property writable

is_bold: bool

Whether the text is bold.

is_dim property writable

is_dim: bool

Whether the text is dimmed.

is_italic property writable

is_italic: bool

Whether the text is italic.

is_underlined property writable

is_underlined: bool

Whether the text is underlined.

is_blinking property writable

is_blinking: bool

Whether the text blinks.

is_reversed property writable

is_reversed: bool

Whether foreground and background are swapped.

is_hidden property writable

is_hidden: bool

Whether the text is hidden.

is_crossed_out property writable

is_crossed_out: bool

Whether the text is struck through.

size property

size: Size

The size of the canvas in cells.

An axis given no size when the canvas was created follows the content: the canvas is as wide as the farthest right edge of what is written on it and as tall as its lowest bottom edge.

width property

width: int

The width of the canvas in cells.

height property

height: int

The height of the canvas in cells.

x property

x: int

The column of the canvas: 0, unless it was written into another canvas.

y property

y: int

The row of the canvas: 0, unless it was written into another canvas.

right_edge property

right_edge: int

The first column after the canvas: x + width, in cells.

For a canvas written into another one, it is relative to the area that holds it, like x. For any other canvas, it is the width.

Examples:

import xnano

with xnano.new(width=20, height=3) as outer:
    panel = outer.screen.new('panel', width=6, height=1)
    panel.screen.move(x=2)
    assert (outer.screen.right_edge, panel.screen.right_edge) == (20, 8)

bottom_edge property

bottom_edge: int

The first row below the canvas: y + height, in cells.

For a canvas written into another one, it is relative to the area that holds it, like y. For any other canvas, it is the height.

Examples:

import xnano

with xnano.new(width=20, height=5) as outer:
    panel = outer.screen.new('panel', width=6, height=2)
    panel.screen.move(y=1)
    assert (outer.screen.bottom_edge, panel.screen.bottom_edge) == (5, 3)

region property

region: Region[int]

The cells of the canvas as a Region: read and write canvas.screen.region[x, y].

The default resolution is one cell. canvas.screen.region.half_blocks addresses two pixels per cell and canvas.screen.region.braille eight dots.

Examples:

import xnano

with xnano.new(width=4, height=2) as canvas:
    canvas.screen.region[0, 0] = xnano.Pixel('diamond')
    canvas.screen.region.half_blocks[1, 0] = (255, 0, 0)
    assert canvas.screen.region[0, 0].character == '◆'
    assert canvas.screen.region.half_blocks.height == 4

cursor property

cursor: Cursor

The canvas's Cursor.

A canvas has exactly one cursor. Set its position (a cell, or None to hide it), shape, is_blinking and is_visible, move it with up, down, left, right and move, or follow a placement. It can be changed from any thread, and on the screen the cursor you had before is restored when the canvas closes.

Examples:

import xnano

with xnano.new(width=10, height=2) as canvas:
    canvas.screen.cursor.position = (3, 0)
    canvas.screen.cursor.shape = 'bar'
    assert canvas.screen.cursor.position.x == 3

title property writable

title: str | None

The window title last set on this canvas.

Assign a single line of printable text to set the title of the window a canvas on the screen draws in, or None to clear it. A canvas without a screen keeps the value and shows it when it is opened.

core_buffer property

core_buffer: Buffer

The core buffer the canvas draws, as large as the canvas.

Everything you write is a child of this buffer, and everything drawn directly on the canvas is stored in it. A canvas with a border, padding or margin draws them around a buffer of its own; this is the buffer inside them.

fx property

The visual effects of the canvas itself, one method for each effect.

canvas.screen.fx.fade_to(background='navy') starts a fade over the whole canvas at once, and canvas.screen.fx.clear() stops what was started here. A placement has its own fx, and the sound effects of what the canvas plays are canvas.speaker.fx. See WritableEffectProperties.

Examples:

import xnano

with xnano.new('hello', width=8, height=1) as canvas:
    canvas.screen.fx.dissolve(duration_milliseconds=300)
    assert len(canvas.screen.fx.active) == 1

layout property

layout: CanvasLayout

How the canvas places what is written on it, chosen when the canvas is created.

'overlay' places every piece on its own over the whole canvas. 'column' stacks the pieces from top to bottom in the order they are written, and 'row' from left to right. Each piece then takes a slot: one with a size on the stacking axis (height in a column, width in a row, in cells or as a percentage) gets exactly that, and the others share what is left equally. Inside its slot a piece is positioned as on any canvas, so y='center' and y='50%' are measured in the slot. Removing a piece gives its slot back. A canvas created inside the with block of a stacking canvas takes a slot only once it is written.

Examples:

import xnano

with xnano.new(width=20, height=10, layout='column') as terminal:
    terminal.screen.write('top half', y='center')
    panel = terminal.screen.new(height='50%')
    panel.screen.write('bottom half')
    rows = terminal.screen.render().splitlines()
    assert (rows[2], rows[5]) == ('top half', 'bottom half')

edges property writable

edges: EdgeBehavior

What content written on the canvas does at the edges of its area, unless given its own.

'clip' lets it move past the edge, where it is not drawn; 'stop' holds it inside its area when it moves; 'wrap' continues text on the next rows of its area. A piece written with edges=... keeps its own; see Placement.edges.

Raises:

  • ValueError –

    The value is not 'clip', 'stop' or 'wrap'.

output property

output: Output

The last frame drawn, and the text printed while the canvas was on the screen.

window property

window: Size

The size of the whole terminal window in cells, for a canvas on the screen.

For a terminal opened with a height it is larger than size, which is the region the canvas draws in; for one that takes the whole window the two are equal. A canvas from new() has no window, and this is its size.

__setattr__

__setattr__(name: str, value: object) -> None

Set an attribute, or raise AttributeError for an unknown public name.

Source code in xnano/_internal/_attributes.py
def __setattr__(self, name: str, value: object) -> None:
    """Set an attribute, or raise ``AttributeError`` for an unknown public name."""
    if (
        name[:1] != '_'
        and self.__dict__.get('_is_sealed')
        and not hasattr(type(self), name)
        and name not in self.__dict__
    ):
        kind = type(self).__name__
        settable = sorted(
            key
            for key in dir(type(self))
            if key[:1] != '_' and _is_settable(type(self), key)
        )
        close = difflib.get_close_matches(name, settable, n=1)
        hint = f' Did you mean {close[0]!r}?' if close else ''
        raise AttributeError(
            f'{kind} has no attribute called {name!r}, so assigning to it would change '
            f'nothing.{hint} The attributes you can assign are: {", ".join(settable)}.'
        )
    object.__setattr__(self, name, value)

bold

bold(value: bool = True) -> Self

Make the text bold, or undo it with False; the same as setting is_bold.

Parameters:

  • value (bool, default: True ) –

    Whether the text is bold.

Returns:

  • Self –

    This canvas or placement, so calls can chain.

Raises:

Examples:

import xnano

with xnano.new(width=12, height=1) as canvas:
    title = canvas.screen.write('Ready').bold().underline()
    assert title.is_bold and title.is_underlined
    title.bold(False)
    assert not title.is_bold
Source code in xnano/styles/_owners.py
def bold(self, value: bool = True) -> Self:
    """
    Make the text bold, or undo it with ``False``; the same as setting ``is_bold``.

    Args:
        value: Whether the text is bold.

    Returns:
        This canvas or placement, so calls can chain.

    Raises:
        TypeError: ``value`` is not ``True`` or ``False``.

    Examples:
        ```python
        import xnano

        with xnano.new(width=12, height=1) as canvas:
            title = canvas.screen.write('Ready').bold().underline()
            assert title.is_bold and title.is_underlined
            title.bold(False)
            assert not title.is_bold
        ```
    """
    self.is_bold = value
    return self

dim

dim(value: bool = True) -> Self

Dim the text, or undo it with False; the same as setting is_dim.

Parameters:

  • value (bool, default: True ) –

    Whether the text is dimmed.

Returns:

  • Self –

    This canvas or placement, so calls can chain.

Raises:

Source code in xnano/styles/_owners.py
def dim(self, value: bool = True) -> Self:
    """
    Dim the text, or undo it with ``False``; the same as setting ``is_dim``.

    Args:
        value: Whether the text is dimmed.

    Returns:
        This canvas or placement, so calls can chain.

    Raises:
        TypeError: ``value`` is not ``True`` or ``False``.
    """
    self.is_dim = value
    return self

italic

italic(value: bool = True) -> Self

Make the text italic, or undo it with False; the same as setting is_italic.

Parameters:

  • value (bool, default: True ) –

    Whether the text is italic.

Returns:

  • Self –

    This canvas or placement, so calls can chain.

Raises:

Source code in xnano/styles/_owners.py
def italic(self, value: bool = True) -> Self:
    """
    Make the text italic, or undo it with ``False``; the same as setting ``is_italic``.

    Args:
        value: Whether the text is italic.

    Returns:
        This canvas or placement, so calls can chain.

    Raises:
        TypeError: ``value`` is not ``True`` or ``False``.
    """
    self.is_italic = value
    return self

underline

underline(value: bool = True) -> Self

Underline the text, or undo it with False; the same as setting is_underlined.

Parameters:

  • value (bool, default: True ) –

    Whether the text is underlined.

Returns:

  • Self –

    This canvas or placement, so calls can chain.

Raises:

Source code in xnano/styles/_owners.py
def underline(self, value: bool = True) -> Self:
    """
    Underline the text, or undo it with ``False``; the same as setting ``is_underlined``.

    Args:
        value: Whether the text is underlined.

    Returns:
        This canvas or placement, so calls can chain.

    Raises:
        TypeError: ``value`` is not ``True`` or ``False``.
    """
    self.is_underlined = value
    return self
blink(value: bool = True) -> Self

Make the text blink, or undo it with False; the same as setting is_blinking.

Parameters:

  • value (bool, default: True ) –

    Whether the text blinks.

Returns:

  • Self –

    This canvas or placement, so calls can chain.

Raises:

Source code in xnano/styles/_owners.py
def blink(self, value: bool = True) -> Self:
    """
    Make the text blink, or undo it with ``False``; the same as setting ``is_blinking``.

    Args:
        value: Whether the text blinks.

    Returns:
        This canvas or placement, so calls can chain.

    Raises:
        TypeError: ``value`` is not ``True`` or ``False``.
    """
    self.is_blinking = value
    return self

reverse

reverse(value: bool = True) -> Self

Swap the foreground and background, or undo it with False; the same as setting is_reversed.

Parameters:

  • value (bool, default: True ) –

    Whether foreground and background are swapped.

Returns:

  • Self –

    This canvas or placement, so calls can chain.

Raises:

Source code in xnano/styles/_owners.py
def reverse(self, value: bool = True) -> Self:
    """
    Swap the foreground and background, or undo it with ``False``; the same as setting ``is_reversed``.

    Args:
        value: Whether foreground and background are swapped.

    Returns:
        This canvas or placement, so calls can chain.

    Raises:
        TypeError: ``value`` is not ``True`` or ``False``.
    """
    self.is_reversed = value
    return self

hidden

hidden(value: bool = True) -> Self

Hide the text, or undo it with False; the same as setting is_hidden.

Parameters:

  • value (bool, default: True ) –

    Whether the text is hidden.

Returns:

  • Self –

    This canvas or placement, so calls can chain.

Raises:

Source code in xnano/styles/_owners.py
def hidden(self, value: bool = True) -> Self:
    """
    Hide the text, or undo it with ``False``; the same as setting ``is_hidden``.

    Args:
        value: Whether the text is hidden.

    Returns:
        This canvas or placement, so calls can chain.

    Raises:
        TypeError: ``value`` is not ``True`` or ``False``.
    """
    self.is_hidden = value
    return self

crossed_out

crossed_out(value: bool = True) -> Self

Strike the text through, or undo it with False; the same as setting is_crossed_out.

Parameters:

  • value (bool, default: True ) –

    Whether the text is struck through.

Returns:

  • Self –

    This canvas or placement, so calls can chain.

Raises:

Source code in xnano/styles/_owners.py
def crossed_out(self, value: bool = True) -> Self:
    """
    Strike the text through, or undo it with ``False``; the same as setting ``is_crossed_out``.

    Args:
        value: Whether the text is struck through.

    Returns:
        This canvas or placement, so calls can chain.

    Raises:
        TypeError: ``value`` is not ``True`` or ``False``.
    """
    self.is_crossed_out = value
    return self

write

write(content: Content | Canvas[WrittenDepsT, WrittenStateT] | None = None, /, *, x: Axis = 'next', y: Axis = 'next', width: Axis | None = None, height: Axis | None = None, layer: int = 0, lock: bool = False, edges: EdgeBehavior | None = None, effects: Sequence[WritableEffectSpecification] = (), style: Style | None = None, foreground: ColorValue | None = None, background: ColorValue | None = None, bold: bool = False, dim: bool = False, italic: bool = False, underline: bool = False, blink: bool = False, reverse: bool = False, hidden: bool = False, crossed_out: bool = False, title: str | None = None, border: BorderKind | bool | None = None, border_style: Style | None = None, padding: Spacing | None = None, margin: Spacing | None = None, theme: ThemeName | None = None) -> Placement[DepsT, StateT]

Put something on the canvas: text, a widget, a buffer, another canvas or an image.

On a canvas that runs by itself it appears at once: this only declares it, and the canvas's own loop draws it. width and height you leave out are taken from the content, so canvas.screen.write('hello') shows five cells of text.

Content given no position goes on the next line, the way a terminal prints: the first write starts at the top-left corner and each one after it starts a new line below the lines written before it (x and y default to 'next'). The lines keep up with each other, so when a line grows, shrinks or is removed, the lines after it follow. A y you give places the content there instead, outside the lines, so a status line at y='bottom' never moves them; x='next' (the default) then continues right after the content written just before it when that content is on the same row and there is room. Change the text later by assigning the placement's text.

Inside the with block of a canvas created in this one's block, what is written here is placed and clipped within that canvas's area of this one: where it is written, or the top-left corner while it is not. Positions such as y='center' are measured in that area, and that canvas's edges applies there.

A canvas from new that is written here becomes part of this one: it draws inside the placement, its own clock is set aside and it runs on this canvas's time. It may not have been given state or deps, which belong to the outermost canvas. Its audio is not carried over: a musical clock it started and a note it was playing stop, and an expression that reads its audio.beat follows the outer canvas's musical clock, which starts at the first beat.

An image is added as an Image (never a file path or a bare TerminalImage; load one with load_image). With neither width nor height it keeps its own proportions at its own size, shrunk to fit the canvas. With one of them the other follows the image's proportions, and with both the image fits inside that box. An image sized by a percentage, or by the canvas because you gave no size, is converted again when the canvas is resized, unless it is locked. An animated image plays on the canvas's clock.

A box from box with a relative size (a percentage, an expression or a state reference), written with a width or a height, or written with a look, is drawn at the size of its placement, and its look becomes the placement's look, so it is drawn again when the canvas is resized. The size given to write wins over the box's own. The look keywords given to write win over the box's look and the rest of the box's look stays, and border=False leaves out the box's own border, title, border style and sides. A box written with a look and no size keeps its own size, border included, so the look of the write replaces the look of the box instead of surrounding it, and a margin given to write surrounds it outside that size, a percentage margin being a share of the box. The border of such a box is part of its placement, so placement.region starts inside it. A box written as it is, with no size and no look, and any other region, is written as a snapshot of its cells. The look given to write surrounds a region that is not a box, and placement.region of a snapshot includes the cells of its border.

Parameters:

  • content (Content | Canvas[WrittenDepsT, WrittenStateT] | None, default: None ) –

    Text (or a list of lines), a Buffer or widget, a canvas from new(), an image, or any Writable; None for an empty placement.

  • x (Axis, default: 'next' ) –

    The column of the left edge: a number of cells, a percentage string, a word ('left', 'center', 'right' or 'next'), an expression, or a range ((0, 20)) that limits how far it may travel. See Axis.

  • y (Axis, default: 'next' ) –

    The row of the top edge, in the same forms ('top', 'center', 'bottom', 'next'). 'next', the default, is the first row below what was written before; see FlowPosition.

  • width (Axis | None, default: None ) –

    The width, in the same forms; the content's own width when None.

  • height (Axis | None, default: None ) –

    The height, in the same forms; the content's own height when None.

  • layer (int, default: 0 ) –

    Content with a higher layer is drawn over content with a lower one.

  • lock (bool, default: False ) –

    Keep the position and size the content has now, whatever the canvas's size does afterwards: percentages, words and expressions are read once.

  • edges (EdgeBehavior | None, default: None ) –

    What the content does at the edges of its area: 'clip', 'stop' or 'wrap'; see Placement.edges. Left out, it follows what it is written on.

  • effects (Sequence[WritableEffectSpecification], default: () ) –

    Effects to start on the placement, as dictionaries with a kind key, such as [{'kind': 'effect.fade_to', 'foreground': 'red'}].

  • style (Style | None, default: None ) –

    A ready-made Style for text. The parameters below are applied over it.

  • foreground (ColorValue | None, default: None ) –

    The text color.

  • background (ColorValue | None, default: None ) –

    The color behind the text.

  • bold (bool, default: False ) –

    Whether the text is bold.

  • dim (bool, default: False ) –

    Whether the text is dimmed.

  • italic (bool, default: False ) –

    Whether the text is italic.

  • underline (bool, default: False ) –

    Whether the text is underlined.

  • blink (bool, default: False ) –

    Whether the text blinks.

  • reverse (bool, default: False ) –

    Whether foreground and background are swapped.

  • hidden (bool, default: False ) –

    Whether the text is hidden.

  • crossed_out (bool, default: False ) –

    Whether the text is struck through.

  • title (str | None, default: None ) –

    A title on the border of a box around the text.

  • border (BorderKind | bool | None, default: None ) –

    The kind of border for a box around the content, a BorderKind such as 'plain', 'rounded', 'double' or 'thick'; True for 'plain' and False for none. Giving a title alone draws a plain one.

  • border_style (Style | None, default: None ) –

    The style of the box's border.

  • padding (Spacing | None, default: None ) –

    Space between the border and the text: a number of cells, a float or a percentage of the text's size, or a dictionary with top, right, bottom, left, vertical and horizontal. Giving it draws the text in a box without a border unless border or title is also given.

  • margin (Spacing | None, default: None ) –

    Space outside the box, in the same forms.

  • theme (ThemeName | None, default: None ) –

    The name of a theme for this content, in place of the theme of the canvas; see ThemeName. A theme gives text, borders and widgets its colors, unless they are given their own.

Returns:

Raises:

  • TypeError –

    The content is a file path, raw bytes, or an operation, style or effect (apply those with canvas.screen.update(...) instead).

  • TerminalError –

    The content is a canvas that cannot be written here.

Examples:

import xnano

with xnano.new(width=20, height=4) as canvas:
    box = canvas.screen.write('hello', x='50%', y=1)
    assert box.x == 10
    assert (box.width, box.height) == (5, 1)
    canvas.screen.write(
        'Ready',
        x='center',
        y='bottom',
        foreground='green',
        bold=True,
        border='rounded',
        title='Status',
    )

with xnano.new(width=20, height=4) as canvas:
    title = canvas.screen.write('Build 142')
    status = canvas.screen.write('passed', x='center')
    assert (title.y, status.y) == (0, 1)
    title.height = 2
    assert status.y == 2
Source code in xnano/devices/_screen.py
@refuse_unknown_keywords
def write(
    self,
    content: Content | Canvas[WrittenDepsT, WrittenStateT] | None = None,
    /,
    *,
    x: Axis = 'next',
    y: Axis = 'next',
    width: Axis | None = None,
    height: Axis | None = None,
    layer: int = 0,
    lock: bool = False,
    edges: EdgeBehavior | None = None,
    effects: Sequence[WritableEffectSpecification] = (),
    style: _core.Style | None = None,
    foreground: ColorValue | None = None,
    background: ColorValue | None = None,
    bold: bool = False,
    dim: bool = False,
    italic: bool = False,
    underline: bool = False,
    blink: bool = False,
    reverse: bool = False,
    hidden: bool = False,
    crossed_out: bool = False,
    title: str | None = None,
    border: _core.BorderKind | bool | None = None,
    border_style: _core.Style | None = None,
    padding: Spacing | None = None,
    margin: Spacing | None = None,
    theme: ThemeName | None = None,
) -> Placement[DepsT, StateT]:
    """
    Put something on the canvas: text, a widget, a buffer, another canvas or an image.

    On a canvas that runs by itself it appears at once: this only declares it, and the
    canvas's own loop draws it. ``width`` and ``height`` you leave out are taken from the
    content, so ``canvas.screen.write('hello')`` shows five cells of text.

    Content given no position goes on the next line, the way a terminal prints: the first
    write starts at the top-left corner and each one after it starts a new line below the
    lines written before it (``x`` and ``y`` default to ``'next'``). The lines keep up with
    each other, so when a line grows, shrinks or is removed, the lines after it follow. A
    ``y`` you give places the content there instead, outside the lines, so a status line
    at ``y='bottom'`` never moves them; ``x='next'`` (the default) then continues right
    after the content written just before it when that content is on the same row and
    there is room. Change the text later by assigning the placement's
    [`text`][xnano.layout.Placement.text].

    Inside the ``with`` block of a canvas created in this one's block, what is written here
    is placed and clipped within that canvas's area of this one: where it is written, or
    the top-left corner while it is not. Positions such as ``y='center'`` are measured in
    that area, and that canvas's ``edges`` applies there.

    A canvas from [`new`][xnano.new] that is written here becomes part of this one: it
    draws inside the placement, its own clock is set aside and it runs on this canvas's
    time. It may not have been given ``state`` or ``deps``, which belong to the outermost
    canvas. Its audio is not carried over: a musical clock it started and a note it was
    playing stop, and an expression that reads its ``audio.beat`` follows the outer canvas's
    musical clock, which starts at the first beat.

    An image is added as an [`Image`][xnano.Image] (never a file path or a bare
    [`TerminalImage`][xnano_image.TerminalImage]; load one with
    [`load_image`][xnano.load_image]). With neither ``width`` nor ``height`` it keeps
    its own proportions at its own size, shrunk to fit the canvas. With one of them the
    other follows the image's proportions, and with both the image fits inside that box. An
    image sized by a percentage, or by the canvas because you gave no size, is converted
    again when the canvas is resized, unless it is locked. An animated image plays on the
    canvas's clock.

    A box from [`box`][xnano.box] with a relative size (a percentage, an expression or a state
    reference), written with a ``width`` or a ``height``, or written with a look, is drawn
    at the size of its placement, and its look becomes the placement's look, so it is
    drawn again when the canvas is resized. The size given to ``write`` wins over the
    box's own. The look keywords given to ``write`` win over the box's look and the rest
    of the box's look stays, and ``border=False`` leaves out the box's own border, title,
    border style and sides. A box written with a look and no size keeps its own size,
    border included, so the look of the write replaces the look of the box instead of
    surrounding it, and a ``margin`` given to ``write`` surrounds it outside that size,
    a percentage margin being a share of the box. The border of such a box is part of its
    placement, so ``placement.region`` starts inside it. A box written as it is, with no
    size and no look, and any other region, is written as a snapshot of its cells. The
    look given to ``write`` surrounds a region that is not a box, and ``placement.region``
    of a snapshot includes the cells of its border.

    Args:
        content: Text (or a list of lines), a [`Buffer`][xnano_core.Buffer] or widget, a
            canvas from ``new()``, an image, or any
            [`Writable`][xnano.components.Writable]; ``None`` for an empty placement.
        x: The column of the left edge: a number of cells, a percentage string, a word
            (``'left'``, ``'center'``, ``'right'`` or ``'next'``), an expression, or a
            range (``(0, 20)``) that limits how far it may travel. See
            [`Axis`][xnano.layout.Axis].
        y: The row of the top edge, in the same forms (``'top'``, ``'center'``,
            ``'bottom'``, ``'next'``). ``'next'``, the default, is the first row below
            what was written before; see [`FlowPosition`][xnano.layout.FlowPosition].
        width: The width, in the same forms; the content's own width when ``None``.
        height: The height, in the same forms; the content's own height when ``None``.
        layer: Content with a higher layer is drawn over content with a lower one.
        lock: Keep the position and size the content has now, whatever the canvas's
            size does afterwards: percentages, words and expressions are read once.
        edges: What the content does at the edges of its area: ``'clip'``, ``'stop'`` or
            ``'wrap'``; see [`Placement.edges`][xnano.layout.Placement.edges]. Left
            out, it follows what it is written on.
        effects: Effects to start on the placement, as dictionaries with a ``kind``
            key, such as ``[{'kind': 'effect.fade_to', 'foreground': 'red'}]``.
        style: A ready-made [`Style`][xnano.styles.Style] for text. The parameters below
            are applied over it.
        foreground: The text color.
        background: The color behind the text.
        bold: Whether the text is bold.
        dim: Whether the text is dimmed.
        italic: Whether the text is italic.
        underline: Whether the text is underlined.
        blink: Whether the text blinks.
        reverse: Whether foreground and background are swapped.
        hidden: Whether the text is hidden.
        crossed_out: Whether the text is struck through.
        title: A title on the border of a box around the text.
        border: The kind of border for a box around the content, a
            [`BorderKind`][xnano.styles.BorderKind] such as ``'plain'``, ``'rounded'``,
            ``'double'`` or ``'thick'``; ``True`` for ``'plain'`` and ``False`` for none.
            Giving a ``title`` alone draws a plain one.
        border_style: The style of the box's border.
        padding: Space between the border and the text: a number of cells, a float or a
            percentage of the text's size, or a dictionary with ``top``, ``right``,
            ``bottom``, ``left``, ``vertical`` and ``horizontal``. Giving it draws the
            text in a box without a border unless ``border`` or ``title`` is also given.
        margin: Space outside the box, in the same forms.
        theme: The name of a theme for this content, in place of the theme of the canvas;
            see [`ThemeName`][xnano.themes.ThemeName]. A theme gives text, borders and
            widgets its colors, unless they are given their own.

    Returns:
        A [`Placement`][xnano.layout.Placement] to move, resize, listen on or remove.

    Raises:
        TypeError: The content is a file path, raw bytes, or an operation, style or effect
            (apply those with ``canvas.screen.update(...)`` instead).
        TerminalError: The content is a canvas that cannot be written here.

    Examples:
        ```python
        import xnano

        with xnano.new(width=20, height=4) as canvas:
            box = canvas.screen.write('hello', x='50%', y=1)
            assert box.x == 10
            assert (box.width, box.height) == (5, 1)
            canvas.screen.write(
                'Ready',
                x='center',
                y='bottom',
                foreground='green',
                bold=True,
                border='rounded',
                title='Status',
            )

        with xnano.new(width=20, height=4) as canvas:
            title = canvas.screen.write('Build 142')
            status = canvas.screen.write('passed', x='center')
            assert (title.y, status.y) == (0, 1)
            title.height = 2
            assert status.y == 2
        ```
    """
    canvas = self._canvas
    canvas._require_open()
    if isinstance(content, Region):
        content._require_drawable('canvas.screen.write()')
        width, height = content._written_size(width, height)
    if edges is not None:
        edges = check_edges(edges)
    area = canvas._area_for_write(content)
    if area is not None:
        placement = area.write(
            content,
            x=x,
            y=y,
            width=width,
            height=height,
            layer=layer,
            lock=lock,
            edges=edges,
            effects=effects,
            style=style,
            foreground=foreground,
            background=background,
            bold=bold,
            dim=dim,
            italic=italic,
            underline=underline,
            blink=blink,
            reverse=reverse,
            hidden=hidden,
            crossed_out=crossed_out,
            title=title,
            border=border,
            border_style=border_style,
            padding=padding,
            margin=margin,
            theme=theme,
        )
        written = canvas._rendering_writes
        if written is not None:
            written.append(placement)
        return placement  # type: ignore[return-value]
    parent_buffer = canvas._content
    slot: _core.Buffer | None = None
    if canvas._layout != 'overlay':
        slot, width, height = open_slot(
            cast('Canvas[object, object]', canvas),
            content if isinstance(content, _canvas_module.Canvas) else None,
            width,
            height,
        )
        parent_buffer = slot
    try:
        placement = canvas._canvas._place_on(
            parent_buffer,
            content,
            parent_owner=cast('Canvas[object, object]', canvas),
            x=x,
            y=y,
            width=width,
            height=height,
            layer=layer,
            lock=lock,
            style=style,
            foreground=foreground,
            background=background,
            bold=bold,
            dim=dim,
            italic=italic,
            underline=underline,
            blink=blink,
            reverse=reverse,
            hidden=hidden,
            crossed_out=crossed_out,
            title=title,
            border=border,
            border_style=border_style,
            padding=padding,
            margin=margin,
            theme=theme,
        )
    except BaseException:
        if slot is not None:
            close_slot(cast('Canvas[object, object]', canvas), slot)
        raise
    if slot is not None:
        canvas._slots[-1] = (
            cast('Placement[object, object]', placement),
            *canvas._slots[-1][1:],
        )
    if effects:
        apply_effects(cast('Placement[object, object]', placement), effects)
    placement._take_edges(edges, content)
    written = canvas._rendering_writes
    if written is not None:
        written.append(cast('Placement[object, object]', placement))
    return placement

new

new(content: Content | None = None, /, *, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, effects: Sequence[WritableEffectSpecification] = (), **settings: Unpack[CanvasSettings]) -> Canvas[DepsT, StateT]

Create a canvas inside this one and draw it here at once, at the top-left corner.

This is new followed by canvas.screen.write(child): the child's size is measured in this canvas ('50%' is half of it, and no size fills it), it runs on this canvas's time and hears its input, and it closes with this canvas. Move it with move and its relatives, or create it with new and write it with x and y to place it elsewhere.

Parameters:

  • content (Content | None, default: None ) –

    Something to write into the new canvas at once, such as text.

  • width (int | Percentage | str | None, default: None ) –

    The width in cells, or a percentage of this canvas such as '50%'.

  • height (int | Percentage | str | None, default: None ) –

    The height in cells, or a percentage of this canvas.

  • effects (Sequence[WritableEffectSpecification], default: () ) –

    Effects to apply to the new canvas, as dictionaries with a kind key.

  • settings (Unpack[CanvasSettings], default: {} ) –

    The terminal settings and the new canvas's own look; see CanvasSettings.

Returns:

  • Canvas[DepsT, StateT] –

    The new Canvas, already drawn in this one.

Raises:

  • TypeError –

    An appearance keyword was given with content, or a keyword is unknown.

  • ValueError –

    A size, terminal setting or border kind is out of range.

  • TerminalError –

    This canvas is closed.

Examples:

import xnano

with xnano.new(width=12, height=6) as outer:
    panel = outer.screen.new(height='50%', border='plain')
    panel.screen.write('inside')
    assert (panel.screen.width, panel.screen.height) == (10, 1)
    assert outer.screen.render().splitlines()[:3] == [
        '┌──────────┐',
        '│inside    │',
        '└──────────┘',
    ]
Source code in xnano/devices/_screen.py
def new(
    self,
    content: Content | None = None,
    /,
    *,
    width: int | Percentage | str | None = None,
    height: int | Percentage | str | None = None,
    effects: Sequence[WritableEffectSpecification] = (),
    **settings: Unpack[CanvasSettings],
) -> Canvas[DepsT, StateT]:
    """
    Create a canvas inside this one and draw it here at once, at the top-left corner.

    This is [`new`][xnano.new] followed by ``canvas.screen.write(child)``: the child's size is
    measured in this canvas (``'50%'`` is half of it, and no size fills it), it runs on
    this canvas's time and hears its input, and it closes with this canvas. Move it with
    [`move`][xnano.devices.Screen.move] and its relatives, or create it with
    [`new`][xnano.new] and write it with ``x`` and ``y`` to place it elsewhere.

    Args:
        content: Something to write into the new canvas at once, such as text.
        width: The width in cells, or a percentage of this canvas such as ``'50%'``.
        height: The height in cells, or a percentage of this canvas.
        effects: Effects to apply to the new canvas, as dictionaries with a ``kind`` key.
        settings: The terminal settings and the new canvas's own look; see
            [`CanvasSettings`][xnano.canvas.CanvasSettings].

    Returns:
        The new [`Canvas`][xnano.canvas.Canvas], already drawn in this one.

    Raises:
        TypeError: An appearance keyword was given with content, or a keyword is unknown.
        ValueError: A size, terminal setting or border kind is out of range.
        TerminalError: This canvas is closed.

    Examples:
        ```python
        import xnano

        with xnano.new(width=12, height=6) as outer:
            panel = outer.screen.new(height='50%', border='plain')
            panel.screen.write('inside')
            assert (panel.screen.width, panel.screen.height) == (10, 1)
            assert outer.screen.render().splitlines()[:3] == [
                '┌──────────┐',
                '│inside    │',
                '└──────────┘',
            ]
        ```
    """
    return self._canvas._new(
        content, width=width, height=height, effects=effects, **settings
    )

clear

clear() -> None

Erase everything written or drawn directly on the canvas's cells.

Source code in xnano/devices/_screen.py
def clear(self) -> None:
    """Erase everything written or drawn directly on the canvas's cells."""
    return self._canvas._clear()

update

update(*operations: Operation | Style) -> Self

Change the canvas's own cells with operations, styles or effects.

canvas.screen | operation does the same. To put content on the canvas, use write instead.

Parameters:

  • operations (Operation | Style, default: () ) –

    What to apply, in order: a core operation such as Fill or Write, a style, or an xnano effect or dynamic operation.

Returns:

  • Self –

    The canvas, so calls chain.

Examples:

import xnano
from xnano_core import Fill

with xnano.new(width=4, height=1) as canvas:
    canvas.screen.update(Fill('.'))
    assert canvas.screen.render() == '....'
    canvas.screen | Fill('#')
    assert canvas.screen.render() == '####'
Source code in xnano/devices/_screen.py
def update(self, *operations: _core.Operation | _core.Style) -> Self:
    """
    Change the canvas's own cells with operations, styles or effects.

    ``canvas.screen | operation`` does the same. To put content on the canvas, use
    [`write`][xnano.devices.Screen.write] instead.

    Args:
        operations: What to apply, in order: a core operation such as ``Fill`` or
            ``Write``, a style, or an xnano effect or dynamic operation.

    Returns:
        The canvas, so calls chain.

    Examples:
        ```python
        import xnano
        from xnano_core import Fill

        with xnano.new(width=4, height=1) as canvas:
            canvas.screen.update(Fill('.'))
            assert canvas.screen.render() == '....'
            canvas.screen | Fill('#')
            assert canvas.screen.render() == '####'
        ```
    """
    self._canvas._update(*operations)
    return self

render

render(*, format: Literal['text', 'ansi'] = 'text') -> str

Draw the current frame and return it, without a screen.

A canvas that was written into another one returns its own cells alone, at its own size, as they stand in the outer canvas's current frame.

Parameters:

  • format (Literal['text', 'ansi'], default: 'text' ) –

    'text' for the characters alone, 'ansi' for the characters with their colors and styles as escape codes.

Raises:

  • ValueError –

    format is neither 'text' nor 'ansi'.

Examples:

import xnano

with xnano.new(width=6, height=2) as canvas:
    canvas.screen.write('hello', y=1)
    assert canvas.screen.render().splitlines() == ['', 'hello']
    assert 'hello' in canvas.screen.render(format='ansi')
Source code in xnano/devices/_screen.py
def render(self, *, format: Literal['text', 'ansi'] = 'text') -> str:
    """
    Draw the current frame and return it, without a screen.

    A canvas that was written into another one returns its own cells alone, at its own
    size, as they stand in the outer canvas's current frame.

    Args:
        format: ``'text'`` for the characters alone, ``'ansi'`` for the characters with
            their colors and styles as escape codes.

    Raises:
        ValueError: ``format`` is neither ``'text'`` nor ``'ansi'``.

    Examples:
        ```python
        import xnano

        with xnano.new(width=6, height=2) as canvas:
            canvas.screen.write('hello', y=1)
            assert canvas.screen.render().splitlines() == ['', 'hello']
            assert 'hello' in canvas.screen.render(format='ansi')
        ```
    """
    return self._canvas._render(format=format)

__rich_console__

__rich_console__(console: Console, options: ConsoleOptions) -> RenderResult

Show the current frame in rich and Textual, with its colors and styles.

rich.print(screen) prints the frame, as Canvas.__rich_console__ does. If a line is longer than the space that rich gives it, rich cuts the line. Rich must be installed.

Source code in xnano/devices/_screen.py
def __rich_console__(
    self, console: RichConsole, options: RichConsoleOptions
) -> RichRenderResult:
    """
    Show the current frame in rich and Textual, with its colors and styles.

    ``rich.print(screen)`` prints the frame, as
    [`Canvas.__rich_console__`][xnano.canvas.Canvas.__rich_console__] does. If a line
    is longer than the space that rich gives it, rich cuts the line. Rich must be
    installed.
    """
    from rich.text import Text as RichText

    yield RichText.from_ansi(
        self.render(format='ansi'), no_wrap=True, overflow='crop'
    )

__rich_measure__

__rich_measure__(console: Console, options: ConsoleOptions) -> Measurement

Tell rich the width of what it shows, so that rich keeps it whole when it can.

A frame of cells cannot wrap, so its smallest and its largest width are the same. Rich uses this width to lay out panels, columns and nested tables. In a rich Table, add the column with no_wrap=True, so that rich makes the other columns narrower before it cuts this one.

Source code in xnano/devices/_screen.py
def __rich_measure__(
    self, console: RichConsole, options: RichConsoleOptions
) -> RichMeasurement:
    """
    Tell rich the width of what it shows, so that rich keeps it whole when it can.

    A frame of cells cannot wrap, so its smallest and its largest width are the same.
    Rich uses this width to lay out panels, columns and nested tables. In a rich
    ``Table``, add the column with ``no_wrap=True``, so that rich makes the other
    columns narrower before it cuts this one.
    """
    from rich.measure import Measurement as RichMeasurement

    width = self.width
    return RichMeasurement(width, width)

local

local(point: Point) -> Point

Convert a cell of the screen into a cell of this canvas.

Parameters:

  • point (Point) –

    A cell in screen coordinates, such as context.mouse.position.

Examples:

import xnano
from xnano_core import Point

with xnano.new(width=10, height=3) as canvas:
    assert canvas.screen.local(Point(4, 1)) == Point(4, 1)
Source code in xnano/devices/_screen.py
def local(self, point: _core.Point) -> _core.Point:
    """
    Convert a cell of the screen into a cell of this canvas.

    Args:
        point: A cell in screen coordinates, such as ``context.mouse.position``.

    Examples:
        ```python
        import xnano
        from xnano_core import Point

        with xnano.new(width=10, height=3) as canvas:
            assert canvas.screen.local(Point(4, 1)) == Point(4, 1)
        ```
    """
    return self._canvas._local(point)

move

move(x: int = 0, y: int = 0) -> Self

Move a canvas that is written into another one by a number of cells along each axis.

This moves the placement the canvas is drawn in; see Placement.move.

Parameters:

  • x (int, default: 0 ) –

    Columns to move right; a negative number moves left.

  • y (int, default: 0 ) –

    Rows to move down; a negative number moves up.

Returns:

  • Self –

    The canvas, so calls can chain.

Raises:

  • TerminalError –

    The canvas is not written into another canvas, so it sits at the origin and cannot move.

  • TypeError –

    An amount is not a whole number.

Examples:

import xnano

with xnano.new(width=20, height=3) as outer:
    inner = outer.screen.new('box', width=4, height=1)
    inner.screen.move(x=2, y=1)
    assert (inner.screen.x, inner.screen.y) == (2, 1)
    assert outer.screen.render().splitlines()[1] == '  box'
Source code in xnano/devices/_screen.py
def move(self, x: int = 0, y: int = 0) -> Self:
    """
    Move a canvas that is written into another one by a number of cells along each axis.

    This moves the placement the canvas is drawn in; see
    [`Placement.move`][xnano.layout.Placement.move].

    Args:
        x: Columns to move right; a negative number moves left.
        y: Rows to move down; a negative number moves up.

    Returns:
        The canvas, so calls can chain.

    Raises:
        TerminalError: The canvas is not written into another canvas, so it sits at the
            origin and cannot move.
        TypeError: An amount is not a whole number.

    Examples:
        ```python
        import xnano

        with xnano.new(width=20, height=3) as outer:
            inner = outer.screen.new('box', width=4, height=1)
            inner.screen.move(x=2, y=1)
            assert (inner.screen.x, inner.screen.y) == (2, 1)
            assert outer.screen.render().splitlines()[1] == '  box'
        ```
    """
    self._canvas._move(x, y)
    return self

up

up(count: int = 1) -> Self

Move a written canvas up by count rows; see move.

Parameters:

  • count (int, default: 1 ) –

    How many rows to move.

Raises:

  • TerminalError –

    The canvas is not written into another canvas.

  • TypeError –

    count is not a whole number.

  • ValueError –

    count is negative.

Source code in xnano/devices/_screen.py
def up(self, count: int = 1) -> Self:
    """
    Move a written canvas up by ``count`` rows; see [`move`][xnano.devices.Screen.move].

    Args:
        count: How many rows to move.

    Raises:
        TerminalError: The canvas is not written into another canvas.
        TypeError: ``count`` is not a whole number.
        ValueError: ``count`` is negative.
    """
    self._canvas._up(count)
    return self

down

down(count: int = 1) -> Self

Move a written canvas down by count rows; see move.

Parameters:

  • count (int, default: 1 ) –

    How many rows to move.

Raises:

  • TerminalError –

    The canvas is not written into another canvas.

  • TypeError –

    count is not a whole number.

  • ValueError –

    count is negative.

Source code in xnano/devices/_screen.py
def down(self, count: int = 1) -> Self:
    """
    Move a written canvas down by ``count`` rows; see [`move`][xnano.devices.Screen.move].

    Args:
        count: How many rows to move.

    Raises:
        TerminalError: The canvas is not written into another canvas.
        TypeError: ``count`` is not a whole number.
        ValueError: ``count`` is negative.
    """
    self._canvas._down(count)
    return self

left

left(count: int = 1) -> Self

Move a written canvas left by count columns; see move.

Parameters:

  • count (int, default: 1 ) –

    How many columns to move.

Raises:

  • TerminalError –

    The canvas is not written into another canvas.

  • TypeError –

    count is not a whole number.

  • ValueError –

    count is negative.

Source code in xnano/devices/_screen.py
def left(self, count: int = 1) -> Self:
    """
    Move a written canvas left by ``count`` columns; see [`move`][xnano.devices.Screen.move].

    Args:
        count: How many columns to move.

    Raises:
        TerminalError: The canvas is not written into another canvas.
        TypeError: ``count`` is not a whole number.
        ValueError: ``count`` is negative.
    """
    self._canvas._left(count)
    return self

right

right(count: int = 1) -> Self

Move a written canvas right by count columns; see move.

Parameters:

  • count (int, default: 1 ) –

    How many columns to move.

Raises:

  • TerminalError –

    The canvas is not written into another canvas.

  • TypeError –

    count is not a whole number.

  • ValueError –

    count is negative.

Source code in xnano/devices/_screen.py
def right(self, count: int = 1) -> Self:
    """
    Move a written canvas right by ``count`` columns; see [`move`][xnano.devices.Screen.move].

    Args:
        count: How many columns to move.

    Raises:
        TerminalError: The canvas is not written into another canvas.
        TypeError: ``count`` is not a whole number.
        ValueError: ``count`` is negative.
    """
    self._canvas._right(count)
    return self

__contains__

__contains__(item: object) -> bool

Whether a screen cell or a whole area is inside the cells of the canvas.

The answer is the same as item in canvas.screen.region. See Region for the comparison of areas.

Parameters:

  • item (object) –

    A screen cell as a (x, y) pair of numbers or a Point, such as context.mouse.position. It can also be an area: a Region, a Placement or a screen. A placement counts as all the cells that it takes, with its border, padding and margin. Other values are not inside.

Examples:

import xnano

with xnano.new(width=10, height=3) as canvas:
    label = canvas.screen.write('hi', x=8, y=2)
    assert (9, 2) in canvas.screen and (10, 2) not in canvas.screen
    assert label in canvas.screen
    label.x = 9
    assert label not in canvas.screen
Source code in xnano/devices/_screen.py
def __contains__(self, item: object) -> bool:
    """
    Whether a screen cell or a whole area is inside the cells of the canvas.

    The answer is the same as ``item in canvas.screen.region``. See
    [`Region`][xnano.layout.Region] for the comparison of areas.

    Args:
        item: A screen cell as a ``(x, y)`` pair of numbers or a
            [`Point`][xnano_core.Point], such as ``context.mouse.position``. It can also be
            an area: a [`Region`][xnano.layout.Region], a
            [`Placement`][xnano.layout.Placement] or a screen. A placement counts as all
            the cells that it takes, with its border, padding and margin. Other values are
            not inside.

    Examples:
        ```python
        import xnano

        with xnano.new(width=10, height=3) as canvas:
            label = canvas.screen.write('hi', x=8, y=2)
            assert (9, 2) in canvas.screen and (10, 2) not in canvas.screen
            assert label in canvas.screen
            label.x = 9
            assert label not in canvas.screen
        ```
    """
    return item in self.region

overlaps

overlaps(other: Point | tuple[float, float] | Region | Placement[Any, Any] | Screen[Any, Any]) -> bool

Whether the cells of the canvas and another area share at least one screen cell.

The answer is the same as canvas.screen.region.overlaps(other). See Region.overlaps.

Parameters:

Returns:

  • bool –

    True when the two share a cell, or when the cell is inside the canvas.

Raises:

  • TypeError –

    other is not an area or a screen cell.

Examples:

import xnano

with xnano.new(width=10, height=3) as canvas:
    ball = canvas.screen.write('o', x=9, y=1)
    assert canvas.screen.overlaps(ball)
    ball.right(1)
    assert not canvas.screen.overlaps(ball)
Source code in xnano/devices/_screen.py
def overlaps(
    self,
    other: _core.Point
    | tuple[float, float]
    | Region
    | Placement[Any, Any]
    | Screen[Any, Any],
) -> bool:
    """
    Whether the cells of the canvas and another area share at least one screen cell.

    The answer is the same as ``canvas.screen.region.overlaps(other)``. See
    [`Region.overlaps`][xnano.layout.Region.overlaps].

    Args:
        other: An area: a [`Region`][xnano.layout.Region], a
            [`Placement`][xnano.layout.Placement] or a screen. A placement counts as all
            the cells that it takes, with its border, padding and margin. A screen cell as
            a ``(x, y)`` pair of numbers or a [`Point`][xnano_core.Point] overlaps when it
            is inside.

    Returns:
        ``True`` when the two share a cell, or when the cell is inside the canvas.

    Raises:
        TypeError: ``other`` is not an area or a screen cell.

    Examples:
        ```python
        import xnano

        with xnano.new(width=10, height=3) as canvas:
            ball = canvas.screen.write('o', x=9, y=1)
            assert canvas.screen.overlaps(ball)
            ball.right(1)
            assert not canvas.screen.overlaps(ball)
        ```
    """
    return self.region.overlaps(other)

__or__

__or__(other: Operation | Style | Sequence[Operation]) -> Self

Apply an operation, effect or style to the screen with screen | operation.

Source code in xnano/devices/_screen.py
def __or__(
    self, other: _core.Operation | _core.Style | Sequence[_core.Operation]
) -> Self:
    """Apply an operation, effect or style to the screen with ``screen | operation``."""
    if isinstance(other, (_core.Operation, _core.Style)):
        self.update(other)
    else:
        self.update(*other)
    return self

Speaker

Speaker(canvas: Canvas[object, object], context: Context[object, object] | None = None)

The speaker of a terminal: notes, melodies, sounds and playable components.

Get it from Canvas.speaker, or from context.speaker inside a hook. On the screen it plays through the computer's sound device. A canvas from new() has no device: what it plays is recorded at the canvas's time, and render turns it into Audio, the way screen.render() turns the screen into text.

Attributes:

  • fx (PlayableEffectProperties) –

    The sound effects of everything this speaker plays, one method for each effect.

  • is_available (bool) –

    Whether sound can be played: always without a device, otherwise when one exists.

  • is_offline (bool) –

    Whether this speaker records sound instead of playing it on a device.

Examples:

import xnano

with xnano.new(width=8, height=1, bpm=100) as canvas:
    canvas.speaker.play('C4 E4 G4:2 rest C5+E5+G5', instrument='bell')
    canvas.clock.step(delta_seconds=1.0)
    assert canvas.speaker.render().duration_milliseconds == 1000.0

Create a view of the speaker. Use canvas.speaker or context.speaker instead.

Parameters:

  • canvas (Canvas[object, object]) –

    The root canvas the speaker belongs to.

  • context (Context[object, object] | None, default: None ) –

    The hook's context, which notes what a component reads; None outside a hook.

Methods:

  • play –

    Play a note, audio, a symbol name, a melody or a sequence of those, and return at once.

  • render –

    Turn what was played since the previous call into audio, and forget it.

Source code in xnano/devices/_speaker.py
def __init__(
    self,
    canvas: Canvas[object, object],
    context: Context[object, object] | None = None,
) -> None:
    """
    Create a view of the speaker. Use ``canvas.speaker`` or ``context.speaker`` instead.

    Args:
        canvas: The root canvas the speaker belongs to.
        context: The hook's context, which notes what a component reads; ``None`` outside
            a hook.
    """
    self._canvas = canvas
    self._context = context

fx property

The sound effects of everything this speaker plays, one method for each effect.

Examples:

import xnano

with xnano.new(width=8, height=1) as canvas:
    canvas.speaker.fx.reverb(mix=0.3)
    canvas.speaker.play('C4')
    canvas.clock.step(delta_seconds=0.5)
    assert canvas.speaker.render().duration_milliseconds >= 500.0

is_available property

is_available: bool

Whether sound can be played: always without a device, otherwise when one exists.

is_offline property

is_offline: bool

Whether this speaker records sound instead of playing it on a device.

play

play(playable: PlaySource, /, **options: Unpack[PlayOptions]) -> PlayHandle

Play a note, audio, a symbol name, a melody or a sequence of those, and return at once.

playable is a Note, a Melody, a Audio, a playable component, the name of a registered symbol, a note name such as 'C#4', a MIDI number such as 60, a frequency in hertz, melody text, or a sequence of those that plays one after another. A str is a symbol name first; if no symbol has that name it is a note name, a frequency such as '440hz' or melody text. Melody text has spaces, :2 holds a note for two beats, rest is a silence, + joins a chord and | marks a bar: 'C4 E4 G4:2 rest C5+E5+G5'. An option you pass here replaces the same value on a Note, so play(Note('C4'), instrument='violin') plays the violin.

Parameters:

  • playable (PlaySource) –

    What to play.

  • options (Unpack[PlayOptions], default: {} ) –

    The settings of PlayOptions: instrument, beats, velocity, effects, volume, pan and at_beat.

Returns:

Raises:

  • ValueError –

    A name is not a known sound, note or melody, or an option is out of range. The message suggests the closest names.

  • TypeError –

    playable cannot be played.

Source code in xnano/devices/_speaker.py
def play(self, playable: PlaySource, /, **options: Unpack[PlayOptions]) -> PlayHandle:
    """
    Play a note, audio, a symbol name, a melody or a sequence of those, and return at once.

    ``playable`` is a [`Note`][xnano.Note], a [`Melody`][xnano.audio.Melody], a
    [`Audio`][xnano.Audio], a playable component, the name of a registered symbol, a note
    name such as ``'C#4'``, a MIDI number such as ``60``, a frequency in hertz, melody text,
    or a sequence of those that plays one after another. A ``str`` is a symbol name first;
    if no symbol has that name it is a note name, a frequency such as ``'440hz'`` or melody
    text. Melody text has spaces, ``:2`` holds a note for two beats, ``rest`` is a silence,
    ``+`` joins a chord and ``|`` marks a bar: ``'C4 E4 G4:2 rest C5+E5+G5'``. An option you
    pass here replaces the same value on a ``Note``, so
    ``play(Note('C4'), instrument='violin')`` plays the violin.

    Args:
        playable: What to play.
        options: The settings of [`PlayOptions`][xnano.devices.PlayOptions]: ``instrument``,
            ``beats``, ``velocity``, ``effects``, ``volume``, ``pan`` and ``at_beat``.

    Returns:
        A [`PlayHandle`][xnano.audio.PlayHandle] that tells when the sound is over.

    Raises:
        ValueError: A name is not a known sound, note or melody, or an option is out of
            range. The message suggests the closest names.
        TypeError: ``playable`` cannot be played.
    """
    return self._canvas._play(playable, options)

render

render() -> Audio

Turn what was played since the previous call into audio, and forget it.

On a canvas without a sound device everything played is recorded at the canvas's time; this mixes it into mono audio that starts at the previous call, so a program or a test can listen to it, save it or compare it. A note that rings on past now continues in the next call.

Returns:

  • Audio –

    The Audio, as long as the time that passed since the previous

  • Audio –

    call.

Raises:

  • TerminalError –

    The speaker plays on a device, so nothing was recorded.

Examples:

import xnano

with xnano.new(width=8, height=1, fps=10) as canvas:
    canvas.speaker.play('C4', instrument='bell')
    canvas.clock.step()
    audio = canvas.speaker.render()
    assert audio.duration_milliseconds == 100.0
    assert audio.peak > 0.0
Source code in xnano/devices/_speaker.py
def render(self) -> Audio:
    """
    Turn what was played since the previous call into audio, and forget it.

    On a canvas without a sound device everything played is recorded at the canvas's time;
    this mixes it into mono audio that starts at the previous call, so a program or a test
    can listen to it, save it or compare it. A note that rings on past now continues in
    the next call.

    Returns:
        The [`Audio`][xnano.Audio], as long as the time that passed since the previous
        call.

    Raises:
        TerminalError: The speaker plays on a device, so nothing was recorded.

    Examples:
        ```python
        import xnano

        with xnano.new(width=8, height=1, fps=10) as canvas:
            canvas.speaker.play('C4', instrument='bell')
            canvas.clock.step()
            audio = canvas.speaker.render()
            assert audio.duration_milliseconds == 100.0
            assert audio.peak > 0.0
        ```
    """
    return Audio(self._canvas._audio_device().render_sound())

Microphone

Microphone(canvas: Canvas[object, object])

The canvas's microphone: how loud the sound at the default input device is.

Get it from AudioDevice.microphone, which is canvas.microphone. The input device is opened the first time something reads the level, the level history, the sample rate or the channel count. On a computer without an input device, without permission to record, or on a canvas from new(), which has no device, the level is 0 and the history is empty.

The level is an expression, so it drives anything an expression can: a position, a size, a color, an effect.

Maps to xnano_audio.TerminalMicrophone.

Attributes:

  • level (NumericExpression) –

    The current level from 0.0 to 1.0, as an expression.

  • is_open (bool) –

    Whether the input device is open. Reading it never opens the device.

  • sample_rate (int | None) –

    The input device's sample rate in hertz, or None when there is no input device.

  • channels (int | None) –

    The input device's channel count, or None when there is no input device.

Examples:

import xnano

with xnano.new(width=20, height=1) as canvas:
    microphone = canvas.microphone
    assert canvas.evaluate(microphone.level) == 0.0
    assert not microphone.is_open
    assert microphone.sample_rate is None

Create the microphone of a canvas. Use canvas.microphone instead of calling this.

Parameters:

Methods:

  • level_history –

    Return the last count microphone levels, oldest first.

Source code in xnano/audio/_microphone.py
def __init__(self, canvas: Canvas[object, object]) -> None:
    """
    Create the microphone of a canvas. Use ``canvas.microphone`` instead of calling this.

    Args:
        canvas: The canvas the microphone belongs to.
    """
    self._canvas = canvas
    self._device: TerminalMicrophone | None = None
    self._is_unavailable = False
    self._level = _external(_LEVEL_NAME, True)

level property

level: NumericExpression

The microphone's current level from 0.0 to 1.0, as an expression.

Reading it opens the default input device the first time a frame evaluates it. Without an input device, without permission, or on a canvas without a device, the level is 0.

Examples:

import xnano

with xnano.new(width=20, height=2) as canvas:
    meter = canvas.screen.write('#')
    meter.x = canvas.microphone.level * 19
    assert canvas.evaluate(canvas.microphone.level) == 0.0

is_open property

is_open: bool

Whether the input device is open and listening.

This only reports; it never opens the device, so it is False until the level, the level history, the sample rate or the channel count has been read.

sample_rate property

sample_rate: int | None

The input device's sample rate in hertz.

Opens the default input device if it is not open yet. It is None without an input device, without permission, or on a canvas without a device.

channels property

channels: int | None

The input device's channel count.

Opens the default input device if it is not open yet. It is None without an input device, without permission, or on a canvas without a device.

level_history

level_history(count: int) -> list[float]

Return the last count microphone levels, oldest first.

Opens the default input device if it is not open yet. The list is empty without an input device, without permission, or on a canvas without a device.

Parameters:

  • count (int) –

    How many levels to return.

Returns:

  • list[float] –

    The levels, each from 0.0 to 1.0, one for each buffer of sound the device has

  • list[float] –

    delivered.

Source code in xnano/audio/_microphone.py
def level_history(self, count: int) -> list[float]:
    """
    Return the last ``count`` microphone levels, oldest first.

    Opens the default input device if it is not open yet. The list is empty without an
    input device, without permission, or on a canvas without a device.

    Args:
        count: How many levels to return.

    Returns:
        The levels, each from 0.0 to 1.0, one for each buffer of sound the device has
        delivered.
    """
    canvas = self._canvas
    canvas._require_open()

    def read() -> list[float]:
        device = self._open()
        return [] if device is None else device.level_history(count)

    return canvas._host.call(read)

__getattr__

__getattr__(name: str) -> object

Import Microphone, which needs the audio extra, the first time it is read.

Source code in xnano/devices/__init__.py
def __getattr__(name: str) -> object:
    """Import ``Microphone``, which needs the ``audio`` extra, the first time it is read."""
    if name != 'Microphone':
        raise AttributeError(
            f'xnano.devices has no name {name!r}. Its names are {", ".join(__all__)}.'
        )
    # Imported here so that `import xnano` works without the `audio` extra.
    from xnano.audio import Microphone

    globals()[name] = Microphone
    return Microphone

__dir__

__dir__() -> list[str]

The public names of the module, including Microphone.

Source code in xnano/devices/__init__.py
def __dir__() -> list[str]:
    """The public names of the module, including ``Microphone``."""
    return sorted(__all__)