xnano.terminal
xnano.terminal
¶
xnano.terminal
The real screen: the canvas that is on it, the function that opens one, the settings it is asked
for and what the terminal can do, which capabilities reports.
Classes:
-
OpenSettings–The keyword settings of
Canvas.openand of -
TerminalSettings–What a canvas asks the terminal for: the input it reports and how the screen is used.
-
GraphicsCapabilities–How the terminal can draw images.
-
KeyboardCapabilities–What the keys of the terminal can report.
-
TerminalCapabilities–What the terminal can show and report.
-
OpeningTerminal–A terminal that is being opened: await it, or enter it with
async with. -
Terminal–A canvas that draws on your screen and reads your keyboard and mouse.
Functions:
-
capabilities–Ask the terminal this program runs in what it can show and report.
-
open–Put a canvas on your screen and return it as a
Terminal. -
open_async–Put a canvas on your screen like
open, from a coroutine. -
iter–Open a terminal and run it one frame at a time: the program's main loop, as a
forloop. -
iter_async–Open a terminal and run it one frame at a time with
async for, likeiter.
Attributes:
-
CapabilityStatus(TypeAlias) –Whether a terminal feature is available.
-
ColorProfile(TypeAlias) –How many colors a terminal displays.
-
GraphicsProtocol(TypeAlias) –How images are drawn into a terminal.
CapabilityStatus
module-attribute
¶
CapabilityStatus: TypeAlias = _core.CapabilityStatus
Whether a terminal feature is available.
'unknown' means the terminal did not answer, so the feature may or may not work.
Maps to xnano_core.CapabilityStatus.
ColorProfile
module-attribute
¶
ColorProfile: TypeAlias = _core.ColorProfile
How many colors a terminal displays.
'no_terminal' means standard output is not a terminal at all, such as a pipe or a file.
'no_color' is a terminal that displays no colors. 'ansi16' displays the 16 basic colors,
'ansi256' displays 256 and 'truecolor' displays any RGB color.
Maps to xnano_core.ColorProfile.
GraphicsProtocol
module-attribute
¶
GraphicsProtocol: TypeAlias = _core.GraphicsProtocol
How images are drawn into a terminal.
'half_blocks' draws an image with colored half-block characters, which every terminal that
shows colors can display. 'sixel', 'kitty' and 'iterm2' are the image protocols of
terminals that can draw real pixels.
Maps to xnano_core.GraphicsProtocol.
OpenSettings
¶
Bases: CanvasSettings
The keyword settings of Canvas.open and of
open given a canvas.
Everything new() takes except realtime (a screen always runs in real time) and the
content. deps and state are accepted only by a canvas created without them.
Attributes:
-
fps(float) –The most frames drawn per second.
-
bpm(float) –Beats per minute for beat hooks, notes and melodies.
-
effects(Sequence[WritableEffectSpecification]) –Effects to apply to the canvas, as dictionaries with a
kindkey. -
deps(object) –The dependencies hooks and components read as
context.deps. -
state(object) –A dataclass instance the canvas keeps and validates.
style
instance-attribute
¶
style: Style | None
A ready-made style that the colors and modifiers are applied over.
border
instance-attribute
¶
border: BorderKind | bool | None
The kind of border; True is 'plain' and False is none.
mouse
instance-attribute
¶
True for presses, releases and drags; 'motion' for every movement too.
keyboard
instance-attribute
¶
Which key events are reported, or False for none.
capture
instance-attribute
¶
capture: bool
Whether printed text is held back while the screen is in use.
clears_on_close
instance-attribute
¶
clears_on_close: bool
Whether what was drawn is erased when the canvas closes.
alternate_screen
instance-attribute
¶
alternate_screen: bool
Whether a full-window canvas draws on the alternate screen.
effects
instance-attribute
¶
effects: Sequence[WritableEffectSpecification]
Effects to apply, as dictionaries with a kind key.
TerminalSettings
¶
Bases: TypedDict
What a canvas asks the terminal for: the input it reports and how the screen is used.
A canvas stores the terminal settings it is given and applies them when it is opened on a
screen; a canvas without a screen has no device to report anything, and events pushed with
Canvas.push reach hooks whatever the settings say. A setting
that is left out takes its default. mouse, scroll and paste are turned on when
the canvas is opened if a hook registered before that needs them; a setting given as
False stays off, and a hook that needs it raises a
TerminalError that says which setting to turn on.
Attributes:
-
mouse(bool | Literal['motion']) –Truereports button presses, releases and drags;'motion'reports every movement as well. Unset by default: turned on when a hook registered before the canvas is opened needs it. The wheel is thescrollsetting. -
scroll(bool) –Whether the mouse wheel is reported. Unset by default: turned on when a hook registered before the canvas is opened needs it.
-
keyboard(bool | Literal['disambiguated', 'release_events']) –Truefor ordinary key presses,'disambiguated'to tell keys such asescapeandalt+keyapart,'release_events'to also report repeats and releases, andFalseto ignore keys.Trueby default. -
paste(bool) –Whether pasted text arrives as one paste event instead of as key presses. Unset by default, which means on.
-
focus(bool) –Whether the window gaining and losing focus is reported. On by default.
-
interrupt(bool) –Whether
Ctrl-Cends the loop.Falsedelivers it as a key press. On by default. -
capture(bool) –Whether text printed while the screen is in use is held back and printed when the canvas closes. On by default.
-
clears_on_close(bool) –Whether what was drawn is erased when the canvas closes. On by default.
-
alternate_screen(bool) –Whether a full-window canvas draws on the alternate screen, so the shell's history comes back untouched. On by default.
mouse
instance-attribute
¶
True for presses, releases and drags; 'motion' for every movement too.
keyboard
instance-attribute
¶
Which key events are reported, or False for none.
capture
instance-attribute
¶
capture: bool
Whether printed text is held back while the screen is in use.
GraphicsCapabilities
dataclass
¶
GraphicsCapabilities(protocol: GraphicsProtocol, cell_size_in_pixels: tuple[int, int] | None)
How the terminal can draw images.
Maps to xnano_image.TerminalGraphics, read from the
graphics_protocol and cell_size_in_pixels of
xnano_core.TerminalCapabilities, so it needs no
extra installed.
Attributes:
-
protocol(GraphicsProtocol) –The best image protocol the terminal supports.
-
cell_size_in_pixels(tuple[int, int] | None) –The
(width, height)of one cell in pixels, orNone.
KeyboardCapabilities
dataclass
¶
KeyboardCapabilities(enhancement: CapabilityStatus, can_disambiguate_keys: bool, can_report_release_events: bool, can_report_modifier_keys: bool, unavailable_reason: str | None)
What the keys of the terminal can report.
A terminal reports every key press. Whether it can also tell escape from the start of
alt+key, report a key being held or released, or report a modifier key on its own
depends on the enhanced keyboard protocol, which a terminal may or may not offer.
Maps to xnano_core.KeyboardCapabilities.
Attributes:
-
enhancement(CapabilityStatus) –Whether the terminal offers the enhanced keyboard protocol.
-
can_disambiguate_keys(bool) –Whether keys such as
escapeandalt+keyare told apart. -
can_report_release_events(bool) –Whether key repeats and releases are reported.
-
can_report_modifier_keys(bool) –Whether modifier keys on their own are reported.
-
unavailable_reason(str | None) –Why the enhanced protocol is unavailable, or
None.
enhancement
instance-attribute
¶
enhancement: CapabilityStatus
Whether the terminal offers the enhanced keyboard protocol, or 'unknown'.
can_disambiguate_keys
instance-attribute
¶
can_disambiguate_keys: bool
Whether keys such as escape and alt+key are told apart.
This is what keyboard='disambiguated' asks for.
can_report_release_events
instance-attribute
¶
can_report_release_events: bool
Whether key repeats and releases are reported.
This is what keyboard='release_events' asks for.
TerminalCapabilities
dataclass
¶
TerminalCapabilities(is_available: bool, colors: ColorProfile, keyboard: KeyboardCapabilities, graphics: GraphicsCapabilities)
What the terminal can show and report.
Read it with capabilities before a canvas is opened, or
with Terminal.capabilities on an open terminal.
Maps to xnano_core.TerminalCapabilities.
Attributes:
-
is_available(bool) –Whether a canvas can be put on the screen here.
-
colors(ColorProfile) –How many colors the terminal displays.
-
keyboard(KeyboardCapabilities) –What the keys of the terminal can report.
-
graphics(GraphicsCapabilities) –How the terminal can draw images.
is_available
instance-attribute
¶
is_available: bool
Whether a canvas can be put on the screen here.
keyboard
instance-attribute
¶
keyboard: KeyboardCapabilities
What the keys of the terminal can report.
OpeningTerminal
¶
Bases: Generic[DepsT, StateT]
A terminal that is being opened: await it, or enter it with async with.
open_async and
Canvas.open_async return one. await gives the open
Terminal. async with opens it, gives it to the block and closes it
when the block ends, the way with xnano.open() does. The terminal is opened once:
awaiting again gives the same terminal.
Attributes:
-
terminal(Terminal[DepsT, StateT] | None) –The open terminal, or
Noneuntil it is awaited or entered.
Examples:
async with xnano.open_async(height=3) as terminal:
terminal.screen.write('hello')
await terminal.run_async(stop_on='q')
terminal = await xnano.open_async(height=3)
Keep the coroutine function that opens the terminal; nothing opens until it is awaited.
Parameters:
-
open_terminal(Callable[[], Coroutine[object, object, Terminal[DepsT, StateT]]]) –Opens the terminal and returns it.
Source code in xnano/terminal/_opening.py
def __init__(
self,
open_terminal: Callable[[], Coroutine[object, object, Terminal[DepsT, StateT]]],
) -> None:
"""
Keep the coroutine function that opens the terminal; nothing opens until it is awaited.
Args:
open_terminal: Opens the terminal and returns it.
"""
self._open_terminal = open_terminal
self._terminal: Terminal[DepsT, StateT] | None = None
Terminal
¶
Terminal(*, width: int | str | None, height: int | str | None, fps: float, bpm: float, is_realtime: bool, deps: object, state: object, title: str | None, gates: Mapping[str, object], appearance: Mapping[str, object], effects: Sequence[WritableEffectSpecification], enclosing: Canvas[object, object] | None = None, layout: CanvasLayout = 'overlay', edges: EdgeBehavior = 'clip')
Bases: Canvas[DepsT, StateT]
A canvas that draws on your screen and reads your keyboard and mouse.
A canvas becomes a terminal when it is opened, with open or
Canvas.open: it is the same object, and
isinstance(canvas, xnano.Terminal) is how to ask whether a canvas is on the screen.
It has every member of Canvas, and its devices are the real ones:
its screen is the terminal's, its speaker the computer's sound, and its keyboard and mouse
the person's. It runs by itself: opening it
starts a loop on a thread of its own, and everything you write, remove or draw appears the
moment it is declared, however slowly the rest of your program runs, because declaring
only changes buffers and the loop draws them. A program has one screen, so only one
terminal is open at a time.
Attributes:
-
is_closed(bool) –Whether the terminal has been closed, or its loop has ended.
-
is_running(bool) –Whether the loop is running and has not been asked to end.
-
capabilities(TerminalCapabilities) –What the terminal answered about itself when the canvas was opened.
-
settings(TerminalSettings) –Every setting the terminal was opened with, as it was resolved.
Examples:
with xnano.open(width=20, height=2) as terminal:
terminal.screen.write('hello')
assert isinstance(terminal, xnano.Terminal)
terminal.run(stop_on='q')
Create a canvas. Use new instead of calling this.
Parameters:
-
width(int | str | None) –The width in cells, as a percentage of the window,
'fit'for the width of the content, orNonefor 80. -
height(int | str | None) –The height in cells, as a percentage of the window,
'fit'for the height of the content, orNonefor 24. -
fps(float) –The most frames drawn per second.
-
bpm(float) –Beats per minute.
-
is_realtime(bool) –Whether the canvas runs on the wall clock, on a thread of its own.
-
deps(object) –The dependencies, or the unset marker when none were given.
-
state(object) –A dataclass instance the canvas keeps and validates, or the unset marker.
-
title(str | None) –The window title, or
None. -
gates(Mapping[str, object]) –The terminal settings that were given, by name.
-
appearance(Mapping[str, object]) –The appearance keywords of the canvas itself, by name.
-
effects(Sequence[WritableEffectSpecification]) –Effects to apply to the canvas, as dictionaries with a
kindkey. -
enclosing(Canvas[object, object] | None, default:None) –The canvas whose
withblock this one was created in, which its sizes are measured in and which closes it, orNone. -
layout(CanvasLayout, default:'overlay') –How the canvas places what is written on it.
-
edges(EdgeBehavior, default:'clip') –What content written on the canvas does at the edges of its area.
Methods:
-
__setattr__–Set an attribute, or raise
AttributeErrorfor an unknown public name. -
hook–Call a function when something happens on this canvas or placement.
-
__new__–Refuse a direct call: a canvas is created with
xnano.new. -
write–Put content on the screen of the canvas, and return the placement that holds it.
-
render–Draw the current frame and return it as text, with no 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.
-
__contains__–Whether an item is inside the screen of the canvas.
-
open–Put this canvas on your screen, and return it as a
Terminal. -
open_async–Put this canvas on your screen like
open, from a coroutine. -
close–Release everything the canvas holds, and give the screen back if it has one.
-
close_async–Close the canvas like
close, awaiting its loop's end. -
wait_for_tasks_async–Wait until every run of the canvas's
async defhooks has finished. -
__or__–Attach a hook operation, such as one from
xnano.hook(), withcanvas | operation. -
__ior__–Attach a hook operation in place with
canvas |= operation. -
evaluate–Evaluate an expression against the canvas and return its value.
-
iter–Run the canvas one frame at a time: iterate over its frames, drawing between them.
-
iter_async–Run the canvas one frame at a time with
async for, likeiter. -
deliver_events–Deliver pushed events to their hooks and draw a frame, without moving time.
-
stop–Ask the canvas's loop to end.
-
run–Wait until the canvas's loop ends.
-
run_async–Wait until the canvas's loop ends, like
run, withawait. -
push–Deliver an event to the canvas as if it had been typed, clicked or reported.
-
state_reference–A core reference for one field of the canvas's state.
Source code in xnano/canvas.py
def __init__(
self,
*,
width: int | str | None,
height: int | str | None,
fps: float,
bpm: float,
is_realtime: bool,
deps: object,
state: object,
title: str | None,
gates: Mapping[str, object],
appearance: Mapping[str, object],
effects: Sequence[WritableEffectSpecification],
enclosing: Canvas[object, object] | None = None,
layout: CanvasLayout = 'overlay',
edges: EdgeBehavior = 'clip',
) -> None:
"""
Create a canvas. Use [`new`][xnano.new] instead of calling this.
Args:
width: The width in cells, as a percentage of the window, ``'fit'`` for the
width of the content, or ``None`` for 80.
height: The height in cells, as a percentage of the window, ``'fit'`` for the
height of the content, or ``None`` for 24.
fps: The most frames drawn per second.
bpm: Beats per minute.
is_realtime: Whether the canvas runs on the wall clock, on a thread of its own.
deps: The dependencies, or the unset marker when none were given.
state: A dataclass instance the canvas keeps and validates, or the unset marker.
title: The window title, or ``None``.
gates: The terminal settings that were given, by name.
appearance: The appearance keywords of the canvas itself, by name.
effects: Effects to apply to the canvas, as dictionaries with a ``kind`` key.
enclosing: The canvas whose ``with`` block this one was created in, which its
sizes are measured in and which closes it, or ``None``.
layout: How the canvas places what is written on it.
edges: What content written on the canvas does at the edges of its area.
"""
super().__init__()
self._canvas = self
self._root_canvas = self
self._lock = threading.RLock()
self._root = _core.Buffer()
self._buffer = self._root
# 'fit' takes the size of the content; a stacking canvas shares its size among its
# slots, so it cannot fit them.
if layout != 'overlay' and 'fit' in (width, height):
raise ValueError(
f'A {layout} canvas shares its size among the pieces written on it, so it '
f'cannot take the size of them. Give it a size such as height=12, or use '
f"layout='overlay' with width='fit' and height='fit'."
)
self._fits_width = width == 'fit'
self._fits_height = height == 'fit'
# Canvases written into this one that fit their content, and whether a fit runs now.
# The placements of canvases written into this one that fit their content.
self._fitted_placements: list[Placement[object, object]] = []
self._root.should_fit_width = self._fits_width
self._root.should_fit_height = self._fits_height
self._fps = fps
self._bpm = bpm
self._is_realtime = is_realtime
self._requested_width = width
self._requested_height = height
self._deps_given = deps is not _UNSET
self._deps = cast('DepsT', None if deps is _UNSET else deps)
self._state_given = state is not _UNSET
self._title = title
self._gates: dict[str, object] = dict(gates)
self._resolved_gates: dict[str, object] = {}
self._appearance = (
Appearance(**cast('dict[str, object]', _plain_appearance(appearance))) # type: ignore[arg-type]
if appearance
else None
)
self._dirty_looks: dict[int, _LookState] = {}
self._placements: list[Placement[DepsT, StateT]] = []
self._ledger: list[_Registration] = []
self._effects: list[
tuple[EffectParameters, Canvas[object, object] | Placement[object, object]]
] = []
self._frame_listeners: dict[int, Callable[[FrameContext], None]] = {}
self._frame_listener_tokens = itertools.count()
self._children: list[Canvas[object, object]] = []
self._nested_canvases: list[weakref.ref[Canvas[object, object]]] = []
self._areas: dict[int, Placement[object, object]] = {}
self._layout: CanvasLayout = layout
self._edges: EdgeBehavior = edges
self._slots: list[
tuple[Placement[object, object] | None, _core.Buffer, _core.SizeRule]
] = []
self._pending_layouts: dict[int, Canvas[object, object]] = {}
# The flow of every container that something was written into, by its buffer.
self._flows: dict[int, Flow] = {}
if enclosing is not None:
self._enclosing = weakref.ref(enclosing)
self._enclosing_size = (enclosing.screen.width, enclosing.screen.height)
with enclosing._lock:
enclosing._nested_canvases.append(
weakref.ref(cast('Canvas[object, object]', self))
)
self._stop_requested = _AwaitableEvent()
# The event loop that async def hooks run on: the one this canvas was created in.
self._event_loop: asyncio.AbstractEventLoop | None = running_loop()
self._state_fields: dict[str, object] = {}
if state is not _UNSET and state is not None:
self._state_store = _prepare_state(cast('DataclassInstance', state))
self._state_fields = _state_field_types(cast('DataclassInstance', state))
self._state_marked: dict[_StateFollower, _core.TerminalStateChange] = {}
self._internal_revisions: deque[int] = deque(maxlen=16)
self._namespace_identifiers = itertools.count(1)
self._active_run_by_thread = threading.local()
self._images: dict[int, ImageSource] = {}
# Only placements with an expression or a range need looking at before each frame.
self._dynamic: dict[int, Placement[DepsT, StateT]] = {}
# Whether the engine asks for a frame when the pointer moves: only while a placement
# before each frame reads the pointer. Only the canvas's loop changes it.
self._follows_pointer = False
self._clock_view = Clock(cast('Canvas[object, object]', self))
self._output = Output(cast('Canvas[object, object]', self))
# The mouse buttons the program pressed and has not released.
self._program_held_buttons: set[_core.MouseButton] = set()
self._size = _core.Size(0, 0)
self._previous_chain = tuple(
reference for reference in _active_canvas.get() if reference() is not None
)
_active_canvas.set(
(weakref.ref(cast('Canvas[object, object]', self)), *self._previous_chain)
)
self._host: _Host
columns, rows = _canvas_size(
None if self._fits_width else width,
None if self._fits_height else height,
self._enclosing_size,
)
if self._fits_width:
columns = 1
if self._fits_height:
rows = 1
interval_milliseconds = max(1, round(1000.0 / fps))
def create_runtime() -> _core.Runtime:
runtime = _core.Runtime.offscreen(
width=columns,
height=rows,
frame_interval_milliseconds=interval_milliseconds,
clock=_core.Clock.monotonic() if is_realtime else None,
)
if title is not None:
runtime.title = title
return runtime
try:
if is_realtime:
_ThreadHost(cast('Canvas[object, object]', self), create_runtime)
else:
_InlineHost(cast('Canvas[object, object]', self), create_runtime)
except BaseException:
_active_canvas.set(self._previous_chain)
self._finalize()
raise
try:
if effects:
apply_effects(cast('Canvas[object, object]', self), effects)
except BaseException:
self.close(raise_failure=False)
raise
self._writable_effects = WritableEffectProperties(
cast('Canvas[object, object]', self)
)
self._seal()
capabilities
property
¶
capabilities: TerminalCapabilities
What the terminal answered about itself when the canvas was opened.
settings
property
¶
settings: TerminalSettings
A copy of every setting of the terminal, including the ones that hooks turned on.
screen
property
¶
screen: Screen[DepsT, StateT]
The Screen: what is written and drawn on the canvas, and how
it looks.
A canvas written into another one has a screen of its own, its area of the outer canvas.
speaker
property
¶
speaker: Speaker
The Speaker: notes, melodies, sounds and playable components.
It needs the optional xnano-audio package, which is imported the first time it plays.
microphone
property
¶
microphone: Microphone
The Microphone: the level of the sound around, and its
history.
Raises:
-
ImportError–xnano-audiois not installed. Install it withpip install "xnano[audio]".
keyboard
property
¶
keyboard: Keyboard
The Keyboard: the keys held down, and the program's own key
presses, pastes, waits and prompts.
mouse
property
¶
mouse: Mouse
The Mouse: the pointer, the buttons held, the wheel, and the
program's own clicks and drags.
clock
property
¶
clock: Clock
The Clock: how long the canvas has run, stopping, stepping,
sleeping, its frame rate, its tempo and its beats.
fx
property
¶
The visual effects of all of the canvas, one method for each effect.
canvas.fx is the same as canvas.screen.fx. An effect
that starts here changes every cell of the canvas, and canvas.fx.clear() stops
the effects that started here. See
WritableEffectProperties.
Examples:
is_closed
property
¶
is_closed: bool
Whether the canvas has been torn down: closed, or its loop has ended.
is_running
property
¶
is_running: bool
Whether the canvas is open and its loop has not been asked to end.
state
class-attribute
instance-attribute
¶
The canvas's state: values that hooks and your code share, read and written by path.
canvas.state.get('player.score') reads a value and canvas.state.set('player.score',
3) writes one; see StateNamespace for the path rules. A
canvas created with new(state=Settings()) also gives the fields of the dataclass as
attributes with their declared types, so canvas.state.volume is an int for a field
declared volume: int; a write is checked against the field's type. A type checker
sees get and set only on a canvas without a state dataclass, but both exist on
every canvas.
The state can be used from any thread. A write updates every expression that reads the field and draws a frame.
__setattr__
¶
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)
hook
¶
hook(function: Hook[DepsT, StateT], /, *, on: HookTrigger[DepsT, StateT] | None = None, every: float | None = None, after: float | None = None, keys: KeyName | Sequence[KeyName] | None = None, requires_deps: bool = False, if_running: IfRunning = 'replace') -> HookHandle[DepsT, StateT]
hook(function: Hook[DepsT, StateT] | None = None, /, *, on: HookTrigger[DepsT, StateT] | None = None, every: float | None = None, after: float | None = None, keys: KeyName | Sequence[KeyName] | None = None, requires_deps: bool = False, if_running: IfRunning = 'replace') -> HookHandle[DepsT, StateT] | Callable[[Hook[DepsT, StateT]], HookHandle[DepsT, StateT]]
Call a function when something happens on this canvas or placement.
on says when the hook runs: a kind of event such as 'key' or 'tick', the
name of an event pushed with Event.custom(name), or a condition such as
"mouse.kind == 'press'" (see HookTrigger). A hook
without on hears every input event. A mouse,
scroll or drag hook on a placement hears only the pointer inside the placement, and a
press inside holds the pointer for the hook until the button is released. A pointer hook
that matches an event stops it from reaching the parent; a hook that does not match lets
it through. Keys are not consumed: while nothing has focus, every key hook hears a key.
A hook hears only the input the screen reports. A hook added to a canvas that is
already on the screen turns no terminal setting on, so one that needs input the screen
does not report, such as on='mouse' on a canvas opened without mouse=True, is
attached and never runs.
hook(function, ...) attaches one function, and @target.hook(...) decorates the
function that follows. A hook function may be a generator that receives a new context
at each bare yield: write context = yield. A drag is a loop that runs while
context.mouse.is_down.
A hook without on hears every input event. While a mouse button it heard is held,
it also runs on every frame once the button has been held for 0.15 seconds, so a
quick click runs it only for the press and the release. A release names its button
in context.mouse.button; test context.mouse.is_down to leave the release out.
A hook function may also be written with async def. Each time the hook runs, its
coroutine starts on the event loop the canvas was created or opened in, and on
xnano's own background loop when there is none, and the canvas goes on drawing while
it awaits. if_running says what happens when the hook runs again before the
previous run has finished. A canvas with a manual clock (from new()) needs an event
loop of its own for that: create it in a coroutine or use async with on it.
wait_for_tasks_async waits until every
run has finished. A run that raises ends the canvas like a plain hook that raises; a
cancelled run is not a failure.
every and after are seconds for on='tick' and beats for on='beat':
every=2 means 2 seconds for a tick hook and 2 beats for a beat hook. On a canvas
from new() a hook that is due several times in one step runs once for each
interval, up to 100,000 times in one step; the intervals that remain run in the steps
that follow. The function's return value is ignored, unless it is an operation, a
style or an effect, which is applied to this target.
Parameters:
-
function(Hook[DepsT, StateT] | None, default:None) –The function to call with a
Context, or a function with no parameters, which is called without it. -
on(HookTrigger[DepsT, StateT] | None, default:None) –When the hook runs. A kind:
'frame','tick','beat','key','mouse','scroll','drag','paste','focus','resize','state'or'custom'(every custom event); seeHookKind. The name of a custom event, such as'volume_changed'. Or a condition: a string, an expression or a function of the context; seeWhen. A string that reads one input hears only that input ("mouse.kind == 'press'"is a mouse hook, and hears the pointer inside a placement), a string that reads no input is checked on every tick, and a string tells xnano which terminal settings the hook needs, somouseandscrollturn on when the canvas opens. A string that reads key releases needskeyboard='release_events'given tonew()oropen(). An expression or a function hears every input event and does not tell xnano what it reads, so one that readsmouse,scrollor key releases needsmouse=True,scroll=Trueorkeyboard='release_events'given tonew()oropen()yourself. Withevery,afterorkeysa condition is checked on those ticks or keys. A comparison with an input the event does not carry, such askeyboard.keyon a paste, does not hold;!=is one of them, sokeyboard.key != 'q'hears only key events.notandnot innegate the whole comparison, sonot keyboard.key == 'q'andkeyboard.key not in ['q']also hold for events that have no key. -
every(float | None, default:None) –Repeat every this many seconds (
'tick') or beats ('beat'). -
after(float | None, default:None) –Run once after this many seconds (
'tick') or beats ('beat'). -
keys(KeyName | Sequence[KeyName] | None, default:None) –The key or keys an
on='key'hook reacts to, such as'q'or'ctrl+s'. A key hook with keys hears presses and repeats; omit them and testkeyboard.kindto hear releases. -
requires_deps(bool, default:False) –Whether the hook needs the dependencies given to
new(deps=...). -
if_running(IfRunning, default:'replace') –For an
async defhook, what happens when it runs again while its previous run has not finished:'replace'cancels that run (the latest wins),'ignore'drops the new one,'queue'runs them one after the other and'overlap'runs them together. SeeIfRunning.
Returns:
-
HookHandle[DepsT, StateT] | Callable[[Hook[DepsT, StateT]], HookHandle[DepsT, StateT]]–The hook, whose
removestops it; removing it cancels the unfinished runs of -
HookHandle[DepsT, StateT] | Callable[[Hook[DepsT, StateT]], HookHandle[DepsT, StateT]]–an
async defhook. Without a function, the decorator.
Raises:
-
ValueError–The combination of arguments does not make sense, a key name is unknown, a condition string is not a condition,
onis one letter away from a kind, orif_runningis given to a function that is notasync def. The message says what to write instead. -
TypeError–onis a plainboolor not a kind, a name or a condition, or the function is not callable with a context, or is an async generator. -
TerminalError–requires_depsis true and the canvas was created withoutdeps, or anasync defhook has no event loop to run on.
Examples:
import xnano
from xnano_core import Event
with xnano.new(width=8, height=1) as canvas:
heard = []
@canvas.hook(on='key', keys=['q', 'escape'])
def leave(context: xnano.Context) -> None:
heard.append(context.keyboard.key)
@canvas.hook(on='tick', every=0.5)
def blink(context: xnano.Context) -> None:
heard.append('tick')
canvas.push(Event.key_press('q'))
canvas.clock.step(delta_seconds=1.0)
assert heard == ['q', 'tick', 'tick']
Source code in xnano/hooks/_handles.py
def hook(
self,
function: Hook[DepsT, StateT] | None = None,
/,
*,
on: HookTrigger[DepsT, StateT] | None = None,
every: float | None = None,
after: float | None = None,
keys: KeyName | Sequence[KeyName] | None = None,
requires_deps: bool = False,
if_running: IfRunning = 'replace',
) -> (
HookHandle[DepsT, StateT]
| Callable[[Hook[DepsT, StateT]], HookHandle[DepsT, StateT]]
):
"""
Call a function when something happens on this canvas or placement.
``on`` says when the hook runs: a kind of event such as ``'key'`` or ``'tick'``, the
name of an event pushed with ``Event.custom(name)``, or a condition such as
``"mouse.kind == 'press'"`` (see [`HookTrigger`][xnano.hooks.HookTrigger]). A hook
without ``on`` hears every input event. A mouse,
scroll or drag hook on a placement hears only the pointer inside the placement, and a
press inside holds the pointer for the hook until the button is released. A pointer hook
that matches an event stops it from reaching the parent; a hook that does not match lets
it through. Keys are not consumed: while nothing has focus, every key hook hears a key.
A hook hears only the input the screen reports. A hook added to a canvas that is
already on the screen turns no terminal setting on, so one that needs input the screen
does not report, such as ``on='mouse'`` on a canvas opened without ``mouse=True``, is
attached and never runs.
``hook(function, ...)`` attaches one function, and ``@target.hook(...)`` decorates the
function that follows. A hook function may be a generator that receives a new context
at each bare ``yield``: write ``context = yield``. A drag is a loop that runs while
``context.mouse.is_down``.
A hook without ``on`` hears every input event. While a mouse button it heard is held,
it also runs on every frame once the button has been held for 0.15 seconds, so a
quick click runs it only for the press and the release. A release names its button
in ``context.mouse.button``; test ``context.mouse.is_down`` to leave the release out.
A hook function may also be written with ``async def``. Each time the hook runs, its
coroutine starts on the event loop the canvas was created or opened in, and on
xnano's own background loop when there is none, and the canvas goes on drawing while
it awaits. ``if_running`` says what happens when the hook runs again before the
previous run has finished. A canvas with a manual clock (from ``new()``) needs an event
loop of its own for that: create it in a coroutine or use ``async with`` on it.
[`wait_for_tasks_async`][xnano.canvas.Canvas.wait_for_tasks_async] waits until every
run has finished. A run that raises ends the canvas like a plain hook that raises; a
cancelled run is not a failure.
``every`` and ``after`` are seconds for ``on='tick'`` and beats for ``on='beat'``:
``every=2`` means 2 seconds for a tick hook and 2 beats for a beat hook. On a canvas
from ``new()`` a hook that is due several times in one ``step`` runs once for each
interval, up to 100,000 times in one step; the intervals that remain run in the steps
that follow. The function's return value is ignored, unless it is an operation, a
style or an effect, which is applied to this target.
Args:
function: The function to call with a [`Context`][xnano.hooks.Context], or a
function with no parameters, which is called without it.
on: When the hook runs. A kind: ``'frame'``, ``'tick'``, ``'beat'``, ``'key'``,
``'mouse'``, ``'scroll'``, ``'drag'``, ``'paste'``, ``'focus'``, ``'resize'``,
``'state'`` or ``'custom'`` (every custom event); see
[`HookKind`][xnano.hooks.HookKind]. The name of a custom event, such as
``'volume_changed'``. Or a condition: a string, an expression or a function of
the context; see [`When`][xnano.hooks.When]. A string that reads one input
hears only that input (``"mouse.kind == 'press'"`` is a mouse hook, and hears
the pointer inside a placement), a string that reads no input is checked on
every tick, and a string tells xnano which terminal settings the hook needs,
so ``mouse`` and ``scroll`` turn on when the canvas opens. A string that reads
key releases needs ``keyboard='release_events'`` given to ``new()`` or
``open()``. An expression or a function hears every input event and does not
tell xnano what it reads, so one that reads ``mouse``, ``scroll`` or key
releases needs ``mouse=True``, ``scroll=True`` or
``keyboard='release_events'`` given to ``new()`` or ``open()`` yourself. With
``every``, ``after`` or ``keys`` a condition is checked on those ticks or keys.
A comparison with an input the event does not carry, such as ``keyboard.key``
on a paste, does not hold; ``!=`` is one of them, so ``keyboard.key != 'q'``
hears only key events. ``not`` and ``not in`` negate the whole comparison, so
``not keyboard.key == 'q'`` and ``keyboard.key not in ['q']`` also hold for
events that have no key.
every: Repeat every this many seconds (``'tick'``) or beats (``'beat'``).
after: Run once after this many seconds (``'tick'``) or beats (``'beat'``).
keys: The key or keys an ``on='key'`` hook reacts to, such as ``'q'`` or
``'ctrl+s'``. A key hook with keys hears presses and repeats; omit them and
test ``keyboard.kind`` to hear releases.
requires_deps: Whether the hook needs the dependencies given to
``new(deps=...)``.
if_running: For an ``async def`` hook, what happens when it runs again while
its previous run has not finished: ``'replace'`` cancels that run (the
latest wins), ``'ignore'`` drops the new one, ``'queue'`` runs them one after
the other and ``'overlap'`` runs them together. See
[`IfRunning`][xnano.hooks.IfRunning].
Returns:
The hook, whose ``remove`` stops it; removing it cancels the unfinished runs of
an ``async def`` hook. Without a function, the decorator.
Raises:
ValueError: The combination of arguments does not make sense, a key name is
unknown, a condition string is not a condition, ``on`` is one letter away
from a kind, or ``if_running`` is given to a function that is not
``async def``. The message says what to write instead.
TypeError: ``on`` is a plain ``bool`` or not a kind, a name or a condition, or the
function is not callable with a context, or is an async generator.
TerminalError: ``requires_deps`` is true and the canvas was created without
``deps``, or an ``async def`` hook has no event loop to run on.
Examples:
```python
import xnano
from xnano_core import Event
with xnano.new(width=8, height=1) as canvas:
heard = []
@canvas.hook(on='key', keys=['q', 'escape'])
def leave(context: xnano.Context) -> None:
heard.append(context.keyboard.key)
@canvas.hook(on='tick', every=0.5)
def blink(context: xnano.Context) -> None:
heard.append('tick')
canvas.push(Event.key_press('q'))
canvas.clock.step(delta_seconds=1.0)
assert heard == ['q', 'tick', 'tick']
```
"""
canvas = self._canvas
self._require_attached()
owner = cast('_Hooked[object, object]', self)
kind, condition = resolve_trigger(on, every=every, after=after, keys=keys)
normalized_keys = _check_hook_arguments(owner, kind, every, after, keys)
compiled = compile_when(condition)
if requires_deps and not canvas._deps_given:
raise TerminalError(
'This hook needs dependencies (requires_deps=True), but the canvas has none '
'yet. Give them when you create the canvas: xnano.new(deps=your_dependencies) '
'or xnano.open(deps=your_dependencies), or open the canvas with '
'canvas.open(deps=your_dependencies) before you register this hook.'
)
_check_if_running(if_running)
def attach(
callback: Hook[DepsT, StateT],
) -> HookHandle[DepsT, StateT]:
checked = _check_hook_function(callback)
_check_coroutine_hook(owner, checked, kind, if_running)
return self._attach_hook(
cast('Callable[[Context[DepsT, StateT]], object]', checked),
on=kind,
when=compiled,
every=every,
after=after,
keys=normalized_keys,
if_running=if_running,
)
if function is None:
return attach
return attach(function)
__new__
¶
Refuse a direct call: a canvas is created with xnano.new.
Source code in xnano/canvas.py
def __new__(cls, *arguments: object, **keywords: object) -> Self:
"""Refuse a direct call: a canvas is created with ``xnano.new``."""
if arguments or 'is_realtime' not in keywords:
raise TypeError(
f'{cls.__name__} is not created by calling it. Create a canvas with '
f'xnano.new(...), or put one on the screen with xnano.open(...).'
)
return super().__new__(cls)
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) -> Placement[DepsT, StateT]
Put content on the screen of the canvas, and return the placement that holds it.
canvas.write(...) is the same as canvas.screen.write(...). It takes the same
arguments, does the same work and gives the same result. See
Screen.write for how the screen places each kind of
content.
Parameters:
-
content(Content | Canvas[WrittenDepsT, WrittenStateT] | None, default:None) – -
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. SeeAxis. -
y(Axis, default:'next') –The row of the top edge, in the same forms (
'top','center','bottom'or'next').'next', the default, is the first row below the content written before. -
width(Axis | None, default:None) –The width, in the same forms.
Noneuses the width of the content. -
height(Axis | None, default:None) –The height, in the same forms.
Noneuses the height of the content. -
layer(int, default:0) –The layer. Content on a higher layer shows over content on a lower layer.
-
lock(bool, default:False) –Whether to keep the position and the size that the content has now when the canvas changes size.
-
edges(EdgeBehavior | None, default:None) –What the content does at the edges of its area:
'clip','stop'or'wrap'.Noneuses theedgesof the screen. -
effects(Sequence[WritableEffectSpecification], default:()) –The effects to start on the placement, as dictionaries with a
kindkey. -
style(Style | None, default:None) –A
Stylefor the text. The arguments below apply over it. -
foreground(ColorValue | None, default:None) –The color of the text.
-
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 dim.
-
italic(bool, default:False) –Whether the text is italic.
-
underline(bool, default:False) –Whether the text has a line below it.
-
blink(bool, default:False) –Whether the text blinks.
-
reverse(bool, default:False) –Whether the foreground color and the background color change places.
-
hidden(bool, default:False) –Whether the text is hidden.
-
crossed_out(bool, default:False) –Whether the text has a line through it.
-
title(str | None, default:None) –The title on the border of a box around the content.
-
border(BorderKind | bool | None, default:None) –The
BorderKindof a box around the content, such as'plain'or'rounded'.Trueis'plain', andFalseis no border. -
border_style(Style | None, default:None) –The style of the border.
-
padding(Spacing | None, default:None) –The space between the border and the content: a number of cells, a share of the size of the content, or a dictionary of sides.
-
margin(Spacing | None, default:None) –The space outside the box, in the same forms.
Returns:
-
Placement[DepsT, StateT]–The
Placementthat holds the content. Use it to move, -
Placement[DepsT, StateT]–resize or remove the content.
Raises:
-
TypeError–The content is a file path, raw bytes, an operation, a style or an effect. Apply those with
canvas.screen.update(...). -
TerminalError–The content is a canvas that you cannot write here.
Examples:
import xnano
with xnano.new(width=12, height=3) as canvas:
greeting = canvas.write('hello', x='center', y='center', bold=True)
assert (greeting.width, greeting.y) == (5, 1)
assert canvas.render().splitlines()[1].strip() == 'hello'
Source code in xnano/canvas.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,
) -> Placement[DepsT, StateT]:
"""
Put content on the screen of the canvas, and return the placement that holds it.
``canvas.write(...)`` is the same as ``canvas.screen.write(...)``. It takes the same
arguments, does the same work and gives the same result. See
[`Screen.write`][xnano.devices.Screen.write] for how the screen places each kind of
content.
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`` makes 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. See [`Axis`][xnano.layout.Axis].
y: The row of the top edge, in the same forms (``'top'``, ``'center'``,
``'bottom'`` or ``'next'``). ``'next'``, the default, is the first row below
the content written before.
width: The width, in the same forms. ``None`` uses the width of the content.
height: The height, in the same forms. ``None`` uses the height of the content.
layer: The layer. Content on a higher layer shows over content on a lower layer.
lock: Whether to keep the position and the size that the content has now when
the canvas changes size.
edges: What the content does at the edges of its area: ``'clip'``, ``'stop'`` or
``'wrap'``. ``None`` uses the ``edges`` of the screen.
effects: The effects to start on the placement, as dictionaries with a ``kind``
key.
style: A [`Style`][xnano.styles.Style] for the text. The arguments below apply
over it.
foreground: The color of the text.
background: The color behind the text.
bold: Whether the text is bold.
dim: Whether the text is dim.
italic: Whether the text is italic.
underline: Whether the text has a line below it.
blink: Whether the text blinks.
reverse: Whether the foreground color and the background color change places.
hidden: Whether the text is hidden.
crossed_out: Whether the text has a line through it.
title: The title on the border of a box around the content.
border: The [`BorderKind`][xnano.styles.BorderKind] of a box around the content,
such as ``'plain'`` or ``'rounded'``. ``True`` is ``'plain'``, and ``False``
is no border.
border_style: The style of the border.
padding: The space between the border and the content: a number of cells, a
share of the size of the content, or a dictionary of sides.
margin: The space outside the box, in the same forms.
Returns:
The [`Placement`][xnano.layout.Placement] that holds the content. Use it to move,
resize or remove the content.
Raises:
TypeError: The content is a file path, raw bytes, an operation, a style or an
effect. Apply those with ``canvas.screen.update(...)``.
TerminalError: The content is a canvas that you cannot write here.
Examples:
```python
import xnano
with xnano.new(width=12, height=3) as canvas:
greeting = canvas.write('hello', x='center', y='center', bold=True)
assert (greeting.width, greeting.y) == (5, 1)
assert canvas.render().splitlines()[1].strip() == 'hello'
```
"""
return self.screen.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,
)
render
¶
Draw the current frame and return it as text, with no screen.
canvas.render(...) is the same as
canvas.screen.render(...).
Parameters:
-
format(Literal['text', 'ansi'], default:'text') –'text'for the characters only.'ansi'for the characters with their colors and styles as escape codes.
Returns:
-
str–The frame, with one line for each row.
Raises:
-
ValueError–formatis not'text'or'ansi'.
Examples:
import xnano
with xnano.new(width=6, height=2) as canvas:
canvas.write('hello', y=1)
assert canvas.render().splitlines() == ['', 'hello']
assert canvas.render(format='ansi') == canvas.screen.render(format='ansi')
Source code in xnano/canvas.py
def render(self, *, format: Literal['text', 'ansi'] = 'text') -> str:
"""
Draw the current frame and return it as text, with no screen.
``canvas.render(...)`` is the same as
[`canvas.screen.render(...)`][xnano.devices.Screen.render].
Args:
format: ``'text'`` for the characters only. ``'ansi'`` for the characters with
their colors and styles as escape codes.
Returns:
The frame, with one line for each row.
Raises:
ValueError: ``format`` is not ``'text'`` or ``'ansi'``.
Examples:
```python
import xnano
with xnano.new(width=6, height=2) as canvas:
canvas.write('hello', y=1)
assert canvas.render().splitlines() == ['', 'hello']
assert canvas.render(format='ansi') == canvas.screen.render(format='ansi')
```
"""
return self.screen.render(format=format)
__rich_console__
¶
Show the current frame in rich and Textual, with its colors and styles.
rich.print(canvas) prints the frame. A canvas can also go into a rich Panel
or Table, or into a Textual Static. If a line is longer than the space that
rich gives it, rich cuts the line, as a terminal does. Rich must be installed.
A closed canvas cannot draw. Textual draws a Static after you make it, so give
Textual a canvas that stays open, such as one from xnano.new() outside a
with block.
Examples:
import io
import xnano
from rich.console import Console
with xnano.new(width=5, height=1) as canvas:
canvas.write('hello')
console = Console(file=io.StringIO(), width=20)
console.print(canvas)
assert console.file.getvalue() == 'hello\n'
Source code in xnano/canvas.py
def __rich_console__(
self, console: RichConsole, options: RichConsoleOptions
) -> RichRenderResult:
r"""
Show the current frame in rich and Textual, with its colors and styles.
``rich.print(canvas)`` prints the frame. A canvas can also go into a rich ``Panel``
or ``Table``, or into a Textual ``Static``. If a line is longer than the space that
rich gives it, rich cuts the line, as a terminal does. Rich must be installed.
A closed canvas cannot draw. Textual draws a ``Static`` after you make it, so give
Textual a canvas that stays open, such as one from ``xnano.new()`` outside a
``with`` block.
Examples:
```python
import io
import xnano
from rich.console import Console
with xnano.new(width=5, height=1) as canvas:
canvas.write('hello')
console = Console(file=io.StringIO(), width=20)
console.print(canvas)
assert console.file.getvalue() == 'hello\n'
```
"""
from rich.text import Text as RichText
yield RichText.from_ansi(
self.render(format='ansi'), no_wrap=True, overflow='crop'
)
__rich_measure__
¶
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/canvas.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.screen.width
return RichMeasurement(width, width)
__contains__
¶
Whether an item is inside the screen of the canvas.
item in canvas is the same as item in canvas.screen.region. See
Region for the items that it accepts.
Parameters:
Examples:
import xnano
with xnano.new(width=4, height=2) as canvas:
assert (3, 1) in canvas
assert (4, 1) not in canvas
Source code in xnano/canvas.py
def __contains__(self, item: object) -> bool:
"""
Whether an item is inside the screen of the canvas.
``item in canvas`` is the same as ``item in canvas.screen.region``. See
[`Region`][xnano.layout.Region] for the items that it accepts.
Args:
item: What to find, such as an ``(x, y)`` pair or a
[`Point`][xnano_core.Point] in screen cells.
Examples:
```python
import xnano
with xnano.new(width=4, height=2) as canvas:
assert (3, 1) in canvas
assert (4, 1) not in canvas
```
"""
return item in self.screen.region
open
¶
open(*, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, **settings: Unpack[OpenSettings]) -> Terminal[DepsT, StateT]
Put this canvas on your screen, and return it as a Terminal.
The same object is returned: after this, isinstance(canvas, xnano.Terminal) is
true. From then on it runs by itself on a thread of its own and on the wall clock, which
continues from the time the canvas had: elapsed time, the frame count, every and
after timers and a stopped clock carry over, and so do the cursor, the title,
everything written and every hook. Effects that were running start again from their
beginning, and keyboard focus and a captured pointer are released.
width and height are the size of the canvas: the ones given here, else the
ones given to new(), draw in a region of that size below the cursor; a canvas
created without a size, or with '100%' for both, fills the whole window. A
percentage such as '50%' is a share of the window when the canvas is opened. Any
other keyword of new() except realtime may be given and applies before the
canvas is shown; a terminal setting given here wins over the one given to new().
title is the window title.
Parameters:
-
title(str | None, default:None) –The window title;
Nonekeeps the canvas's title. -
width(int | Percentage | str | None, default:None) –The width of the region to draw in: cells, or a percentage of the window.
-
height(int | Percentage | str | None, default:None) –The height of the region to draw in: cells, or a percentage of the window.
-
settings(Unpack[OpenSettings], default:{}) –Terminal settings, appearance keywords,
fps,bpm,effects, anddepsandstatefor a canvas that was created without them; seeOpenSettings.
Returns:
-
Terminal[DepsT, StateT]–This canvas, now attached to the screen.
Raises:
-
TerminalAlreadyOpenError–Another canvas is already on the screen.
-
TerminalError–This canvas is already on the screen, was written into another canvas, has a hook that needs a terminal setting given as
False, or there is no terminal to draw on; the canvas stays as it was. -
TypeError–realtimewas given,depsorstatethat the canvas already has, or an effect that is not a visual effect dictionary. -
ValueError–A
widthwas given without aheight, or a value is out of range.
Examples:
with xnano.new(width=40, height=5) as canvas:
canvas.screen.write('hello', border='rounded')
canvas.clock.step()
canvas.open(mouse=True) # now a xnano.Terminal, 40 by 5 below the prompt
canvas.run(stop_on='q')
Source code in xnano/canvas.py
def open(
self,
*,
title: str | None = None,
width: int | Percentage | str | None = None,
height: int | Percentage | str | None = None,
**settings: Unpack[OpenSettings],
) -> Terminal[DepsT, StateT]:
"""
Put this canvas on your screen, and return it as a [`Terminal`][xnano.Terminal].
The same object is returned: after this, ``isinstance(canvas, xnano.Terminal)`` is
true. From then on it runs by itself on a thread of its own and on the wall clock, which
continues from the time the canvas had: elapsed time, the frame count, ``every`` and
``after`` timers and a stopped clock carry over, and so do the cursor, the title,
everything written and every hook. Effects that were running start again from their
beginning, and keyboard focus and a captured pointer are released.
``width`` and ``height`` are the size of the canvas: the ones given here, else the
ones given to ``new()``, draw in a region of that size below the cursor; a canvas
created without a size, or with ``'100%'`` for both, fills the whole window. A
percentage such as ``'50%'`` is a share of the window when the canvas is opened. Any
other keyword of ``new()`` except ``realtime`` may be given and applies before the
canvas is shown; a terminal setting given here wins over the one given to ``new()``.
``title`` is the window title.
Args:
title: The window title; ``None`` keeps the canvas's title.
width: The width of the region to draw in: cells, or a percentage of the window.
height: The height of the region to draw in: cells, or a percentage of the window.
settings: Terminal settings, appearance keywords, ``fps``, ``bpm``, ``effects``,
and ``deps`` and ``state`` for a canvas that was created without them; see
[`OpenSettings`][xnano.terminal.OpenSettings].
Returns:
This canvas, now attached to the screen.
Raises:
TerminalAlreadyOpenError: Another canvas is already on the screen.
TerminalError: This canvas is already on the screen, was written into another
canvas, has a hook that needs a terminal setting given as ``False``, or
there is no terminal to draw on; the canvas stays as it was.
TypeError: ``realtime`` was given, ``deps`` or ``state`` that the canvas already
has, or an effect that is not a visual effect dictionary.
ValueError: A ``width`` was given without a ``height``, or a value is out of
range.
Examples:
```text
with xnano.new(width=40, height=5) as canvas:
canvas.screen.write('hello', border='rounded')
canvas.clock.step()
canvas.open(mouse=True) # now a xnano.Terminal, 40 by 5 below the prompt
canvas.run(stop_on='q')
```
"""
from xnano.terminal import Terminal
from xnano.terminal._screen import attach_screen
attach_screen(self, title=title, width=width, height=height, settings=settings)
assert isinstance(self, Terminal)
return self
open_async
¶
open_async(*, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, **settings: Unpack[OpenSettings]) -> OpeningTerminal[DepsT, StateT]
Put this canvas on your screen like open, from a coroutine.
The terminal is asked what it can do while your event loop goes on running other
tasks. Await the result for the Terminal, or enter it with
async with, which closes it when the block ends. The keywords are the ones
open() takes, and so are the errors, which are raised when it is awaited.
Parameters:
-
title(str | None, default:None) –The window title;
Nonekeeps the canvas's title. -
width(int | Percentage | str | None, default:None) –The width of the region to draw in: cells, or a percentage of the window.
-
height(int | Percentage | str | None, default:None) –The height of the region to draw in: cells, or a percentage of the window.
-
settings(Unpack[OpenSettings], default:{}) –Terminal settings, appearance keywords,
fps,bpm,effects, anddepsandstatefor a canvas that was created without them; seeOpenSettings.
Returns:
-
OpeningTerminal[DepsT, StateT]–The opening terminal: await it, or use it in
async with.
Examples:
async def main() -> None:
async with xnano.new(width=40, height=5) as canvas:
canvas.screen.write('hello', border='rounded')
terminal = await canvas.open_async(mouse=True)
await terminal.run_async(stop_on='q')
Source code in xnano/canvas.py
def open_async(
self,
*,
title: str | None = None,
width: int | Percentage | str | None = None,
height: int | Percentage | str | None = None,
**settings: Unpack[OpenSettings],
) -> OpeningTerminal[DepsT, StateT]:
"""
Put this canvas on your screen like [`open`][xnano.canvas.Canvas.open], from a coroutine.
The terminal is asked what it can do while your event loop goes on running other
tasks. Await the result for the [`Terminal`][xnano.Terminal], or enter it with
``async with``, which closes it when the block ends. The keywords are the ones
``open()`` takes, and so are the errors, which are raised when it is awaited.
Args:
title: The window title; ``None`` keeps the canvas's title.
width: The width of the region to draw in: cells, or a percentage of the window.
height: The height of the region to draw in: cells, or a percentage of the window.
settings: Terminal settings, appearance keywords, ``fps``, ``bpm``, ``effects``,
and ``deps`` and ``state`` for a canvas that was created without them; see
[`OpenSettings`][xnano.terminal.OpenSettings].
Returns:
The opening terminal: await it, or use it in ``async with``.
Examples:
```text
async def main() -> None:
async with xnano.new(width=40, height=5) as canvas:
canvas.screen.write('hello', border='rounded')
terminal = await canvas.open_async(mouse=True)
await terminal.run_async(stop_on='q')
```
"""
from xnano.terminal import Terminal
from xnano.terminal._opening import OpeningTerminal
from xnano.terminal._screen import attach_screen_async
async def open_terminal() -> Terminal[DepsT, StateT]:
await attach_screen_async(
self, title=title, width=width, height=height, settings=settings
)
assert isinstance(self, Terminal)
# async def hooks run on the loop the terminal was opened in.
self._event_loop = running_loop()
return self
return OpeningTerminal(open_terminal)
close
¶
close(*, raise_failure: bool = True) -> None
Release everything the canvas holds, and give the screen back if it has one.
Closing twice is harmless. Leaving a with block closes the canvas, unless it is
part of another canvas or was created inside another canvas's with block: then it
stays usable and closes with that canvas. Closing a canvas closes the canvases created
inside its block that were not written anywhere. Closing a canvas that was written into
another one takes it off and leaves that one running.
Parameters:
-
raise_failure(bool, default:True) –Whether to raise the error a callback raised on the loop, which stopped the canvas. A
withblock passesFalsewhile another error is already propagating.
Raises:
-
TerminalError–A callback raised on the canvas's loop, or the loop would not stop.
Source code in xnano/canvas.py
def close(self, *, raise_failure: bool = True) -> None:
"""
Release everything the canvas holds, and give the screen back if it has one.
Closing twice is harmless. Leaving a ``with`` block closes the canvas, unless it is
part of another canvas or was created inside another canvas's ``with`` block: then it
stays usable and closes with that canvas. Closing a canvas closes the canvases created
inside its block that were not written anywhere. Closing a canvas that was written into
another one takes it off and leaves that one running.
Args:
raise_failure: Whether to raise the error a callback raised on the loop, which
stopped the canvas. A ``with`` block passes ``False`` while another error is
already propagating.
Raises:
TerminalError: A callback raised on the canvas's loop, or the loop would not stop.
"""
self._close_nested_canvases()
if self._canvas is not self:
if not self._is_closed:
self._is_closed = True
root = self._canvas
closing: list[Canvas[object, object]] = [
cast('Canvas[object, object]', self)
]
with root._lock:
# A canvas written into this one is part of it, so it ends with it.
closing.extend(
inner
for inner in list(root._children)
if inner is not self
and inner._is_inside(cast('Canvas[object, object]', self))
)
for canvas in closing:
canvas._is_closed = True
if canvas in root._children:
root._children.remove(canvas)
placement = self._parent_placement
if placement is not None and not root.is_closed:
for canvas in closing:
root._host.post(canvas._cancel_hooks)
placement.remove()
if _current_canvas() is self:
_active_canvas.set(self._previous_chain)
return
if not self._stop_requested.is_set() or not self._is_finalized:
host = getattr(self, '_host', None)
if host is not None:
host.require_closable()
self._stop_requested.set()
try:
if host is not None:
host.shutdown()
finally:
self._finalize()
if _current_canvas() is self:
_active_canvas.set(self._previous_chain)
failure = self._failure
if failure is not None and raise_failure and not self._is_failure_reported:
self._failure = None
raise TerminalError(
self._failure_text(failure), code='canvas.callback'
) from failure
close_async
async
¶
close_async(*, raise_failure: bool = True) -> None
Close the canvas like close, awaiting its loop's end.
A canvas that runs by itself (on the screen, or realtime=True) stops its loop while
your event loop goes on running other tasks; a canvas with a manual clock closes at
once. Leaving an async with block calls this.
Parameters:
-
raise_failure(bool, default:True) –Whether to raise the error a callback raised on the loop, which stopped the canvas. An
async withblock passesFalsewhile another error is already propagating.
Raises:
-
TerminalError–A callback raised on the canvas's loop, or the loop would not stop.
Examples:
import asyncio
import xnano
async def main() -> None:
canvas = xnano.new(realtime=True, width=8, height=1)
canvas.screen.write('hello')
await canvas.close_async()
assert canvas.is_closed
asyncio.run(main())
Source code in xnano/canvas.py
async def close_async(self, *, raise_failure: bool = True) -> None:
"""
Close the canvas like [`close`][xnano.canvas.Canvas.close], awaiting its loop's end.
A canvas that runs by itself (on the screen, or ``realtime=True``) stops its loop while
your event loop goes on running other tasks; a canvas with a manual clock closes at
once. Leaving an ``async with`` block calls this.
Args:
raise_failure: Whether to raise the error a callback raised on the loop, which
stopped the canvas. An ``async with`` block passes ``False`` while another
error is already propagating.
Raises:
TerminalError: A callback raised on the canvas's loop, or the loop would not stop.
Examples:
```python
import asyncio
import xnano
async def main() -> None:
canvas = xnano.new(realtime=True, width=8, height=1)
canvas.screen.write('hello')
await canvas.close_async()
assert canvas.is_closed
asyncio.run(main())
```
"""
host = getattr(self, '_host', None)
if self._canvas is self and not self._is_closed and isinstance(host, _ThreadHost):
await host.stop_async()
self.close(raise_failure=raise_failure)
wait_for_tasks_async
async
¶
Wait until every run of the canvas's async def hooks has finished.
Runs that start while this waits are waited for too. Use it in an async program before reading what the hooks changed, and in tests instead of sleeping.
Raises:
-
TerminalError–A run raised, which ends the canvas the way a failing plain hook does.
Examples:
import asyncio
import xnano
from xnano.events import Event
async def main() -> None:
async with xnano.new(width=20, height=1) as canvas:
label = canvas.screen.write('...')
@canvas.hook(on='key', keys='enter')
async def answer(context: xnano.Context) -> None:
await asyncio.sleep(0.01)
label.text = 'done'
canvas.push(Event.key_press('enter'))
canvas.clock.step()
await canvas.wait_for_tasks_async()
assert canvas.screen.render() == 'done'
asyncio.run(main())
Source code in xnano/canvas.py
async def wait_for_tasks_async(self) -> None:
"""
Wait until every run of the canvas's ``async def`` hooks has finished.
Runs that start while this waits are waited for too. Use it in an async program
before reading what the hooks changed, and in tests instead of sleeping.
Raises:
TerminalError: A run raised, which ends the canvas the way a failing plain hook
does.
Examples:
```python
import asyncio
import xnano
from xnano.events import Event
async def main() -> None:
async with xnano.new(width=20, height=1) as canvas:
label = canvas.screen.write('...')
@canvas.hook(on='key', keys='enter')
async def answer(context: xnano.Context) -> None:
await asyncio.sleep(0.01)
label.text = 'done'
canvas.push(Event.key_press('enter'))
canvas.clock.step()
await canvas.wait_for_tasks_async()
assert canvas.screen.render() == 'done'
asyncio.run(main())
```
"""
canvas = self._canvas
tasks = canvas._tasks
if tasks is not None:
await tasks.idle.wait_async()
if canvas._host.is_autonomous:
canvas._raise_run_failure()
else:
canvas._raise_failure()
__or__
¶
__or__(other: ContextualOperation[DepsT, StateT]) -> Self
Attach a hook operation, such as one from xnano.hook(), with canvas | operation.
Raises:
-
TypeError–otherdraws instead of listening: draw it on the screen, withcanvas.screen | operation.
Source code in xnano/canvas.py
def __or__(self, other: ContextualOperation[DepsT, StateT]) -> Self:
"""
Attach a hook operation, such as one from ``xnano.hook()``, with ``canvas | operation``.
Raises:
TypeError: ``other`` draws instead of listening: draw it on the screen, with
``canvas.screen | operation``.
"""
if not isinstance(other, ContextualOperation):
raise TypeError(
f'canvas | ... attaches hooks, such as canvas | xnano.hook(...), but '
f'{type(other).__name__} draws on the cells. Draw it on the screen: '
f'canvas.screen | operation.'
)
cast('ContextualOperation[DepsT, StateT]', other).apply_to(self)
return self
__ior__
¶
__ior__(other: ContextualOperation[DepsT, StateT]) -> Self
evaluate
¶
evaluate(expression: Expression[ValueT]) -> ValueT
Evaluate an expression against the canvas and return its value.
Parameters:
-
expression(Expression[ValueT]) –Any expression, such as
Width,TimeElapsed % 1orcanvas.microphone.level.
Examples:
import xnano
from xnano_core import Width
with xnano.new(width=12, height=2) as canvas:
assert canvas.evaluate(Width) == 12
Source code in xnano/canvas.py
def evaluate(self, expression: _core.Expression[ValueT]) -> ValueT:
"""
Evaluate an expression against the canvas and return its value.
Args:
expression: Any expression, such as ``Width``, ``TimeElapsed % 1`` or
``canvas.microphone.level``.
Examples:
```python
import xnano
from xnano_core import Width
with xnano.new(width=12, height=2) as canvas:
assert canvas.evaluate(Width) == 12
```
"""
self._require_open()
return self._canvas._host.call(lambda: self._root.inspect(expression))
iter
¶
iter(*, frames: int | None = None, seconds: float | None = None, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c') -> Iterator[Frame]
Run the canvas one frame at a time: iterate over its frames, drawing between them.
Each iteration yields a Frame with the events that reached
the canvas since the previous one in frame.events, and whatever you change before
asking for the next frame is drawn. On a canvas from new() each iteration moves
the clock by one frame of its fps, so the same loop produces the same frames every
run, as fast as your code; a canvas that runs by itself (on the screen, or
realtime=True) draws as you declare, so there this paces your code at its fps:
if you are slow, frames are skipped rather than queued.
Without frames or seconds it runs the way run
does: until a key of stop_on is pressed, the canvas is asked to
stop or closes, or you break out of the loop. With
them, it also ends after that many frames, or when the canvas's time has run that
long, whichever comes first. pause freezes the time it
follows: the iterations go on drawing and hooks still run, but the clock stands still
until resume.
Parameters:
-
frames(int | None, default:None) –The most frames to yield.
-
seconds(float | None, default:None) –The most seconds of the canvas's time to run for.
-
stop_on(KeyName | Sequence[KeyName] | None, default:'ctrl+c') –The key, or keys, that end the loop and stop the canvas, such as
'q';Nonefor none.
Raises:
-
TerminalError–secondswithoutframeson a stopped canvas, which would never reach the end. -
TerminalClosedError–The canvas is closed.
Examples:
import xnano
from xnano.events import Event
with xnano.new(width=8, height=1, fps=10) as canvas:
pressed = []
for frame in canvas.iter(frames=3):
pressed.extend(event.key.key for event in frame.events)
if frame.index == 0:
canvas.push(Event.key_press('a'))
assert [frame.index for frame in canvas.iter(frames=2)] == [3, 4]
assert pressed == ['a']
Source code in xnano/canvas.py
def iter(
self,
*,
frames: int | None = None,
seconds: float | None = None,
stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c',
) -> Iterator[Frame]:
"""
Run the canvas one frame at a time: iterate over its frames, drawing between them.
Each iteration yields a [`Frame`][xnano.hooks.Frame] with the events that reached
the canvas since the previous one in ``frame.events``, and whatever you change before
asking for the next frame is drawn. On a canvas from ``new()`` each iteration moves
the clock by one frame of its ``fps``, so the same loop produces the same frames every
run, as fast as your code; a canvas that runs by itself (on the screen, or
``realtime=True``) draws as you declare, so there this paces your code at its ``fps``:
if you are slow, frames are skipped rather than queued.
Without ``frames`` or ``seconds`` it runs the way [`run`][xnano.canvas.Canvas.run]
does: until a key of ``stop_on`` is pressed, the canvas is asked to
[`stop`][xnano.canvas.Canvas.stop] or closes, or you break out of the loop. With
them, it also ends after that many frames, or when the canvas's time has run that
long, whichever comes first. [`pause`][xnano.devices.Clock.pause] freezes the time it
follows: the iterations go on drawing and hooks still run, but the clock stands still
until [`resume`][xnano.devices.Clock.resume].
Args:
frames: The most frames to yield.
seconds: The most seconds of the canvas's time to run for.
stop_on: The key, or keys, that end the loop and stop the canvas, such as
``'q'``; ``None`` for none.
Raises:
TerminalError: ``seconds`` without ``frames`` on a stopped canvas, which would
never reach the end.
TerminalClosedError: The canvas is closed.
Examples:
```python
import xnano
from xnano.events import Event
with xnano.new(width=8, height=1, fps=10) as canvas:
pressed = []
for frame in canvas.iter(frames=3):
pressed.extend(event.key.key for event in frame.events)
if frame.index == 0:
canvas.push(Event.key_press('a'))
assert [frame.index for frame in canvas.iter(frames=2)] == [3, 4]
assert pressed == ['a']
```
"""
canvas = self._check_iteration(frames, seconds)
return canvas._frames(frames, seconds, _parse_stop_keys(stop_on))
iter_async
¶
iter_async(*, frames: int | None = None, seconds: float | None = None, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c') -> AsyncIterator[Frame]
Run the canvas one frame at a time with async for, like iter.
The frames, the keywords and the ways the iteration ends are the ones iter()
has. Between frames, a canvas that runs by itself waits for the next one with
await, so the rest of your event loop runs meanwhile; a canvas from new()
moves its clock at once and lets other tasks run before the next frame.
Parameters:
-
frames(int | None, default:None) –The most frames to yield.
-
seconds(float | None, default:None) –The most seconds of the canvas's time to run for.
-
stop_on(KeyName | Sequence[KeyName] | None, default:'ctrl+c') –The key, or keys, that end the loop and stop the canvas;
Nonefor none.
Raises:
-
TerminalError–secondswithoutframeson a stopped canvas, which would never reach the end. -
TerminalClosedError–The canvas is closed.
Examples:
import asyncio
import xnano
async def main() -> None:
async with xnano.new(width=8, height=1, fps=10) as canvas:
frames = [frame async for frame in canvas.iter_async(frames=3)]
assert [frame.elapsed_seconds for frame in frames] == [0.0, 0.1, 0.2]
asyncio.run(main())
Source code in xnano/canvas.py
def iter_async(
self,
*,
frames: int | None = None,
seconds: float | None = None,
stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c',
) -> AsyncIterator[Frame]:
"""
Run the canvas one frame at a time with ``async for``, like [`iter`][xnano.canvas.Canvas.iter].
The frames, the keywords and the ways the iteration ends are the ones ``iter()``
has. Between frames, a canvas that runs by itself waits for the next one with
``await``, so the rest of your event loop runs meanwhile; a canvas from ``new()``
moves its clock at once and lets other tasks run before the next frame.
Args:
frames: The most frames to yield.
seconds: The most seconds of the canvas's time to run for.
stop_on: The key, or keys, that end the loop and stop the canvas; ``None`` for
none.
Raises:
TerminalError: ``seconds`` without ``frames`` on a stopped canvas, which would
never reach the end.
TerminalClosedError: The canvas is closed.
Examples:
```python
import asyncio
import xnano
async def main() -> None:
async with xnano.new(width=8, height=1, fps=10) as canvas:
frames = [frame async for frame in canvas.iter_async(frames=3)]
assert [frame.elapsed_seconds for frame in frames] == [0.0, 0.1, 0.2]
asyncio.run(main())
```
"""
canvas = self._check_iteration(frames, seconds)
return canvas._frames_async(frames, seconds, _parse_stop_keys(stop_on))
deliver_events
¶
Deliver pushed events to their hooks and draw a frame, without moving time.
Events pushed with push reach their hooks at the
canvas's next step; this is that step on a canvas whose clock you move. A canvas that
runs by itself delivers them on its own.
Examples:
import xnano
from xnano_core import Event
with xnano.new(width=8, height=1) as canvas:
heard = []
canvas.hook(lambda context: heard.append(context.event.kind))
canvas.push(Event.custom('ping'))
canvas.deliver_events()
assert heard == ['custom']
assert canvas.clock.elapsed_seconds == 0.0
Source code in xnano/canvas.py
def deliver_events(self) -> None:
"""
Deliver pushed events to their hooks and draw a frame, without moving time.
Events pushed with [`push`][xnano.canvas.Canvas.push] reach their hooks at the
canvas's next step; this is that step on a canvas whose clock you move. A canvas that
runs by itself delivers them on its own.
Examples:
```python
import xnano
from xnano_core import Event
with xnano.new(width=8, height=1) as canvas:
heard = []
canvas.hook(lambda context: heard.append(context.event.kind))
canvas.push(Event.custom('ping'))
canvas.deliver_events()
assert heard == ['custom']
assert canvas.clock.elapsed_seconds == 0.0
```
"""
self._require_own_presence()
canvas = self._canvas
canvas._require_open()
if canvas._host.is_autonomous:
canvas._host.call(lambda: canvas._runtime.request_frame())
return
canvas._raise_failure()
canvas._runtime.step()
canvas._pushed_pointer = None
canvas._raise_failure()
stop
¶
Ask the canvas's loop to end.
Safe from any thread, including from a hook. A running iter(), run(),
keyboard.wait() or keyboard.prompt() ends. On a canvas from new() the canvas stays
open for writing and rendering; on a canvas that runs by itself (realtime=True, or
on the screen) the loop ends and the canvas closes.
Source code in xnano/canvas.py
def stop(self) -> None:
"""
Ask the canvas's loop to end.
Safe from any thread, including from a hook. A running ``iter()``, ``run()``,
``keyboard.wait()`` or ``keyboard.prompt()`` ends. On a canvas from ``new()`` the canvas stays
open for writing and rendering; on a canvas that runs by itself (``realtime=True``, or
on the screen) the loop ends and the canvas closes.
"""
self._require_own_presence()
canvas = self._canvas
canvas._stop_requested.set()
if not canvas._is_closed and canvas._host.is_autonomous:
canvas._host.post(lambda: canvas._stop_runtime())
run
¶
Wait until the canvas's loop ends.
A canvas that runs by itself draws and listens on its own, so this only keeps your
program alive until a stop key is pressed, or something calls
stop (a hook, another thread). Declare what you want
before calling it.
Parameters:
-
stop_on(KeyName | Sequence[KeyName] | None, default:'ctrl+c') –The key, or keys, that end the loop, such as
'q'or('q', 'escape').'ctrl+c'by default; giveNoneto leave ending to your own code.
Raises:
-
TerminalError–A callback raised on the canvas's loop, or the canvas has a clock that only moves when you move it, so waiting would never end.
Source code in xnano/canvas.py
def run(self, *, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c') -> None:
"""
Wait until the canvas's loop ends.
A canvas that runs by itself draws and listens on its own, so this only keeps your
program alive until a stop key is pressed, or something calls
[`stop`][xnano.canvas.Canvas.stop] (a hook, another thread). Declare what you want
before calling it.
Args:
stop_on: The key, or keys, that end the loop, such as ``'q'`` or
``('q', 'escape')``. ``'ctrl+c'`` by default; give ``None`` to leave ending
to your own code.
Raises:
TerminalError: A callback raised on the canvas's loop, or the canvas has a clock
that only moves when you move it, so waiting would never end.
"""
canvas = self._canvas
host = canvas._prepare_run(stop_on, 'run()')
try:
while not host.wait(0.1):
pass
except KeyboardInterrupt:
canvas.stop()
raise
canvas._raise_run_failure()
run_async
async
¶
Wait until the canvas's loop ends, like run, with await.
Your event loop goes on running other tasks meanwhile. Cancelling the waiting task
asks the canvas to stop.
Parameters:
-
stop_on(KeyName | Sequence[KeyName] | None, default:'ctrl+c') –The key, or keys, that end the loop, such as
'q'or('q', 'escape').'ctrl+c'by default; giveNoneto leave ending to your own code.
Raises:
-
TerminalError–A callback raised on the canvas's loop, or the canvas has a clock that only moves when you move it, so waiting would never end.
Examples:
import asyncio
import xnano
async def main() -> None:
async with xnano.new(realtime=True, width=20, height=1) as canvas:
canvas.screen.write('working...')
@canvas.hook(on='tick', after=0.05)
def finish(context: xnano.Context) -> None:
context.canvas.stop()
await canvas.run_async()
asyncio.run(main())
Source code in xnano/canvas.py
async def run_async(
self, *, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c'
) -> None:
"""
Wait until the canvas's loop ends, like [`run`][xnano.canvas.Canvas.run], with ``await``.
Your event loop goes on running other tasks meanwhile. Cancelling the waiting task
asks the canvas to [`stop`][xnano.canvas.Canvas.stop].
Args:
stop_on: The key, or keys, that end the loop, such as ``'q'`` or
``('q', 'escape')``. ``'ctrl+c'`` by default; give ``None`` to leave ending
to your own code.
Raises:
TerminalError: A callback raised on the canvas's loop, or the canvas has a clock
that only moves when you move it, so waiting would never end.
Examples:
```python
import asyncio
import xnano
async def main() -> None:
async with xnano.new(realtime=True, width=20, height=1) as canvas:
canvas.screen.write('working...')
@canvas.hook(on='tick', after=0.05)
def finish(context: xnano.Context) -> None:
context.canvas.stop()
await canvas.run_async()
asyncio.run(main())
```
"""
import asyncio
canvas = self._canvas
host = canvas._prepare_run(stop_on, 'run_async()')
try:
await host.wait_async()
except asyncio.CancelledError:
canvas.stop()
raise
canvas._raise_run_failure()
push
¶
push(event: Event) -> None
Deliver an event to the canvas as if it had been typed, clicked or reported.
Hooks hear it the same way as input from the keyboard and mouse, at the canvas's
next step, whatever the terminal settings say. Build events with
Event; Event.custom(name, data=...) makes one of your own.
Parameters:
-
event(Event) –The event to deliver.
Raises:
Examples:
import xnano
from xnano_core import Event
with xnano.new(width=8, height=1) as canvas:
heard = []
canvas.hook(
lambda context: heard.append(context.event.custom_name),
on='volume_changed',
)
canvas.push(Event.custom('volume_changed'))
canvas.deliver_events()
assert heard == ['volume_changed']
Source code in xnano/canvas.py
def push(self, event: _core.Event) -> None:
"""
Deliver an event to the canvas as if it had been typed, clicked or reported.
Hooks hear it the same way as input from the keyboard and mouse, at the canvas's
next step, whatever the terminal settings say. Build events with
[`Event`][xnano_core.Event]; ``Event.custom(name, data=...)`` makes one of your own.
Args:
event: The event to deliver.
Raises:
TypeError: The value is not an [`Event`][xnano_core.Event].
Examples:
```python
import xnano
from xnano_core import Event
with xnano.new(width=8, height=1) as canvas:
heard = []
canvas.hook(
lambda context: heard.append(context.event.custom_name),
on='volume_changed',
)
canvas.push(Event.custom('volume_changed'))
canvas.deliver_events()
assert heard == ['volume_changed']
```
"""
if not isinstance(event, _core.Event):
raise TypeError(
f'push() takes an Event such as xnano_core.Event.custom("ping"), but got '
f'{event!r}. To press a key, push xnano_core.Event.key_press("q"), or call '
f'context.keyboard.press("q") inside a hook.'
)
self._require_own_presence()
canvas = self._canvas
canvas._require_open()
canvas._host.post(lambda: canvas._runtime.inject(event))
state_reference
¶
state_reference(reader: Callable[[StateT], ValueT]) -> StateReference[ValueT]
A core reference for one field of the canvas's state.
The reference can be used as an axis, a range bound or a widget parameter.
Parameters:
-
reader(Callable[[StateT], ValueT]) –A function or lambda that reads the field, such as
lambda state: state.volume.
Raises:
-
TypeError–readeris not a function. -
TerminalError–The canvas was created without
state.
Source code in xnano/canvas.py
def state_reference(
self, reader: Callable[[StateT], ValueT]
) -> _core.StateReference[ValueT]:
"""
A core reference for one field of the canvas's state.
The reference can be used as an axis, a range bound or a widget parameter.
Args:
reader: A function or lambda that reads the field, such as
``lambda state: state.volume``.
Raises:
TypeError: ``reader`` is not a function.
TerminalError: The canvas was created without ``state``.
"""
if not callable(reader):
raise TypeError(
f'state_reference() takes a function that reads one field, but got '
f'{reader!r}. Pass a function such as lambda state: state.volume.'
)
store = self._canvas._state_store
if store is None:
raise TerminalError(
'This canvas has no state, so state_reference() has nothing to read. Create it with '
'xnano.new(state=YourDataclass()).'
)
return _reference_for(store, reader)
capabilities
¶
capabilities() -> TerminalCapabilities
Ask the terminal this program runs in what it can show and report.
The answer says how many colors the terminal displays, which image protocol it can draw
with, whether its keyboard reports key releases, and whether a canvas can be put on its
screen at all. Call it before opening a canvas, to choose colors or a graphics protocol
that suit the terminal. It waits a fraction of a second for the terminal to answer, and a
status the terminal did not answer is 'unknown'.
While a canvas is on the screen it reads the terminal's input, so the terminal cannot be
asked again. Read Terminal.capabilities on the
open terminal instead.
Returns:
-
TerminalCapabilities–What the terminal can show and report.
is_availableisFalsewhen the program -
TerminalCapabilities–does not run in a terminal.
Raises:
-
TerminalAlreadyOpenError–A canvas is on the screen.
Examples:
import xnano
terminal_capabilities = xnano.terminal.capabilities()
assert terminal_capabilities.colors in (
'no_terminal',
'no_color',
'ansi16',
'ansi256',
'truecolor',
)
assert terminal_capabilities.graphics.protocol in (
'half_blocks',
'sixel',
'kitty',
'iterm2',
)
Source code in xnano/terminal/_capabilities.py
def capabilities() -> TerminalCapabilities:
"""
Ask the terminal this program runs in what it can show and report.
The answer says how many colors the terminal displays, which image protocol it can draw
with, whether its keyboard reports key releases, and whether a canvas can be put on its
screen at all. Call it before opening a canvas, to choose colors or a graphics protocol
that suit the terminal. It waits a fraction of a second for the terminal to answer, and a
status the terminal did not answer is ``'unknown'``.
While a canvas is on the screen it reads the terminal's input, so the terminal cannot be
asked again. Read [`Terminal.capabilities`][xnano.terminal.Terminal.capabilities] on the
open terminal instead.
Returns:
What the terminal can show and report. ``is_available`` is ``False`` when the program
does not run in a terminal.
Raises:
TerminalAlreadyOpenError: A canvas is on the screen.
Examples:
```python
import xnano
terminal_capabilities = xnano.terminal.capabilities()
assert terminal_capabilities.colors in (
'no_terminal',
'no_color',
'ansi16',
'ansi256',
'truecolor',
)
assert terminal_capabilities.graphics.protocol in (
'half_blocks',
'sixel',
'kitty',
'iterm2',
)
```
"""
if _screen.is_screen_claimed:
raise TerminalAlreadyOpenError(
'xnano.terminal.capabilities() asks the terminal directly, and it cannot while a '
'canvas is on the screen reading its input, because the canvas would take the '
'answer. Read terminal.capabilities on the open terminal instead, which holds what '
'the terminal answered when the canvas was opened, or call '
'xnano.terminal.capabilities() before opening a canvas.'
)
return capabilities_from_core(
_core.detect_terminal_capabilities(), _core.query_keyboard_capabilities()
)
open
¶
open(canvas: Canvas[DepsT, StateT], /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, **settings: Unpack[OpenSettings]) -> Terminal[DepsT, StateT]
open(content: Content | None = None, /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float = 60.0, bpm: float = 120.0, effects: Sequence[WritableEffectSpecification] = (), **settings: Unpack[CanvasSettings]) -> Terminal[None, None]
open(content: Content | None = None, /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float = 60.0, bpm: float = 120.0, effects: Sequence[WritableEffectSpecification] = (), state: StateT, **settings: Unpack[CanvasSettings]) -> Terminal[None, StateT]
open(content: Content | None = None, /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float = 60.0, bpm: float = 120.0, effects: Sequence[WritableEffectSpecification] = (), deps: DepsT, **settings: Unpack[CanvasSettings]) -> Terminal[DepsT, None]
open(content: Content | None = None, /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float = 60.0, bpm: float = 120.0, effects: Sequence[WritableEffectSpecification] = (), deps: DepsT, state: StateT, **settings: Unpack[CanvasSettings]) -> Terminal[DepsT, StateT]
open(canvas_or_content: Canvas[object, object] | Content | None = None, /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, **settings: object) -> Terminal[DepsT, StateT]
Put a canvas on your screen and return it as a Terminal.
Given a canvas from new, this is Canvas.open:
the same object is attached to the screen and its time continues. Given content or
nothing, it creates the canvas with new() (the same keywords, except realtime)
and attaches that. From here on, anything you write, remove or draw appears at once, on a
loop of the canvas's own that your code never waits for. A with block closes it and
gives the screen back.
By default the canvas takes over the whole window, on the alternate screen so that your
shell's history comes back untouched; width='100%', height='100%' asks for the same.
Give height (and optionally width) to draw in a region of that size below the cursor
instead, in cells or as a percentage of the window such as '50%'; that region is erased
when the canvas closes, unless you pass clears_on_close=False. title is the window title.
The terminal settings say what the screen reports: mouse for buttons and drags,
scroll for the wheel, keyboard, paste, focus and interrupt
(Ctrl-C), and capture holds back what the program prints while the canvas is on
the screen. See TerminalSettings. mouse, scroll
and paste are turned on by themselves when a hook registered before opening needs
them. A hook added after opening turns nothing on: one that needs input the screen does
not report is attached and never runs.
Parameters:
-
canvas_or_content(Canvas[object, object] | Content | None, default:None) –A canvas from
new(), or content to write into a new canvas. -
title(str | None, default:None) –The window title;
Nonekeeps the canvas's title. -
width(int | Percentage | str | None, default:None) –The width of the region to draw in, in cells or as a percentage of the window; the whole window when neither
widthnorheightis given. -
height(int | Percentage | str | None, default:None) –The height of the region to draw in, in cells or as a percentage of the window.
-
settings(object, default:{}) –The other keywords of
new()exceptrealtime: the terminal settings, the canvas's look,fps,bpm,effects,depsandstate.
Returns:
-
Terminal[DepsT, StateT]–The open
Terminal, which is also the one module-level functions -
Terminal[DepsT, StateT]–such as
activefind.
Raises:
-
TerminalAlreadyOpenError–Another canvas is already on the screen.
-
TerminalError–There is no terminal to draw on.
-
TypeError–realtimewas given, an appearance keyword was given with content, or a keyword is unknown. -
ValueError–A
widthwas given without aheight, or a value is out of range.
Examples:
with xnano.open(height=3, mouse=True) as terminal:
terminal.screen.write('hello')
terminal.run(stop_on='q')
Source code in xnano/terminal/__init__.py
def open(
canvas_or_content: Canvas[object, object] | Content | None = None,
/,
*,
title: str | None = None,
width: int | Percentage | str | None = None,
height: int | Percentage | str | None = None,
**settings: object,
) -> Terminal[DepsT, StateT]:
"""
Put a canvas on your screen and return it as a [`Terminal`][xnano.Terminal].
Given a canvas from [`new`][xnano.new], this is [`Canvas.open`][xnano.canvas.Canvas.open]:
the same object is attached to the screen and its time continues. Given content or
nothing, it creates the canvas with ``new()`` (the same keywords, except ``realtime``)
and attaches that. From here on, anything you write, remove or draw appears at once, on a
loop of the canvas's own that your code never waits for. A ``with`` block closes it and
gives the screen back.
By default the canvas takes over the whole window, on the alternate screen so that your
shell's history comes back untouched; ``width='100%', height='100%'`` asks for the same.
Give ``height`` (and optionally ``width``) to draw in a region of that size below the cursor
instead, in cells or as a percentage of the window such as ``'50%'``; that region is erased
when the canvas closes, unless you pass ``clears_on_close=False``. ``title`` is the window title.
The terminal settings say what the screen reports: ``mouse`` for buttons and drags,
``scroll`` for the wheel, ``keyboard``, ``paste``, ``focus`` and ``interrupt``
(``Ctrl-C``), and ``capture`` holds back what the program prints while the canvas is on
the screen. See [`TerminalSettings`][xnano.terminal.TerminalSettings]. ``mouse``, ``scroll``
and ``paste`` are turned on by themselves when a hook registered before opening needs
them. A hook added after opening turns nothing on: one that needs input the screen does
not report is attached and never runs.
Args:
canvas_or_content: A canvas from ``new()``, or content to write into a new canvas.
title: The window title; ``None`` keeps the canvas's title.
width: The width of the region to draw in, in cells or as a percentage of the
window; the whole window when neither ``width`` nor ``height`` is given.
height: The height of the region to draw in, in cells or as a percentage of the
window.
settings: The other keywords of ``new()`` except ``realtime``: the terminal
settings, the canvas's look, ``fps``, ``bpm``, ``effects``, ``deps`` and ``state``.
Returns:
The open [`Terminal`][xnano.Terminal], which is also the one module-level functions
such as [`active`][xnano.active] find.
Raises:
TerminalAlreadyOpenError: Another canvas is already on the screen.
TerminalError: There is no terminal to draw on.
TypeError: ``realtime`` was given, an appearance keyword was given with content, or a
keyword is unknown.
ValueError: A ``width`` was given without a ``height``, or a value is out of range.
Examples:
```text
with xnano.open(height=3, mouse=True) as terminal:
terminal.screen.write('hello')
terminal.run(stop_on='q')
```
"""
if isinstance(canvas_or_content, Canvas):
return cast('Canvas[DepsT, StateT]', canvas_or_content).open(
title=title,
width=width,
height=height,
**settings, # type: ignore[arg-type]
)
canvas: Canvas[DepsT, StateT] = _canvas_to_open(
'open',
canvas_or_content,
title=title,
width=width,
height=height,
settings=settings,
)
try:
return canvas.open()
except BaseException:
canvas.close(raise_failure=False)
raise
open_async
¶
open_async(canvas: Canvas[DepsT, StateT], /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, **settings: Unpack[OpenSettings]) -> OpeningTerminal[DepsT, StateT]
open_async(content: Content | None = None, /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float = 60.0, bpm: float = 120.0, effects: Sequence[WritableEffectSpecification] = (), **settings: Unpack[CanvasSettings]) -> OpeningTerminal[None, None]
open_async(content: Content | None = None, /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float = 60.0, bpm: float = 120.0, effects: Sequence[WritableEffectSpecification] = (), state: StateT, **settings: Unpack[CanvasSettings]) -> OpeningTerminal[None, StateT]
open_async(content: Content | None = None, /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float = 60.0, bpm: float = 120.0, effects: Sequence[WritableEffectSpecification] = (), deps: DepsT, **settings: Unpack[CanvasSettings]) -> OpeningTerminal[DepsT, None]
open_async(content: Content | None = None, /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float = 60.0, bpm: float = 120.0, effects: Sequence[WritableEffectSpecification] = (), deps: DepsT, state: StateT, **settings: Unpack[CanvasSettings]) -> OpeningTerminal[DepsT, StateT]
open_async(canvas_or_content: Canvas[object, object] | Content | None = None, /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, **settings: object) -> OpeningTerminal[DepsT, StateT]
Put a canvas on your screen like open, from a coroutine.
The keywords, the canvas and the errors are the ones open() has; the terminal is
asked what it can do while your event loop goes on running other tasks. Await the result
for the Terminal, or enter it with async with, which closes it and
gives the screen back when the block ends. Errors are raised when it is awaited or
entered.
Then wait with the _async spellings, which let the rest of your program run:
run_async,
iter_async,
keyboard.wait_async and
keyboard.prompt_async.
Parameters:
-
canvas_or_content(Canvas[object, object] | Content | None, default:None) –A canvas from
new(), or content to write into a new canvas. -
title(str | None, default:None) –The window title;
Nonekeeps the canvas's title. -
width(int | Percentage | str | None, default:None) –The width of the region to draw in, in cells or as a percentage of the window; the whole window when neither
widthnorheightis given. -
height(int | Percentage | str | None, default:None) –The height of the region to draw in, in cells or as a percentage of the window.
-
settings(object, default:{}) –The other keywords of
new()exceptrealtime: the terminal settings, the canvas's look,fps,bpm,effects,depsandstate.
Returns:
-
OpeningTerminal[DepsT, StateT]–The opening terminal: await it, or use it in
async with.
Examples:
async def main() -> None:
async with xnano.open_async(height=3, mouse=True) as terminal:
terminal.screen.write('hello')
await terminal.run_async(stop_on='q')
asyncio.run(main())
Source code in xnano/terminal/__init__.py
def open_async(
canvas_or_content: Canvas[object, object] | Content | None = None,
/,
*,
title: str | None = None,
width: int | Percentage | str | None = None,
height: int | Percentage | str | None = None,
**settings: object,
) -> OpeningTerminal[DepsT, StateT]:
"""
Put a canvas on your screen like [`open`][xnano.open], from a coroutine.
The keywords, the canvas and the errors are the ones ``open()`` has; the terminal is
asked what it can do while your event loop goes on running other tasks. Await the result
for the [`Terminal`][xnano.Terminal], or enter it with ``async with``, which closes it and
gives the screen back when the block ends. Errors are raised when it is awaited or
entered.
Then wait with the ``_async`` spellings, which let the rest of your program run:
[`run_async`][xnano.canvas.Canvas.run_async],
[`iter_async`][xnano.canvas.Canvas.iter_async],
[`keyboard.wait_async`][xnano.devices.Keyboard.wait_async] and
[`keyboard.prompt_async`][xnano.devices.Keyboard.prompt_async].
Args:
canvas_or_content: A canvas from ``new()``, or content to write into a new canvas.
title: The window title; ``None`` keeps the canvas's title.
width: The width of the region to draw in, in cells or as a percentage of the
window; the whole window when neither ``width`` nor ``height`` is given.
height: The height of the region to draw in, in cells or as a percentage of the
window.
settings: The other keywords of ``new()`` except ``realtime``: the terminal
settings, the canvas's look, ``fps``, ``bpm``, ``effects``, ``deps`` and ``state``.
Returns:
The opening terminal: await it, or use it in ``async with``.
Examples:
```text
async def main() -> None:
async with xnano.open_async(height=3, mouse=True) as terminal:
terminal.screen.write('hello')
await terminal.run_async(stop_on='q')
asyncio.run(main())
```
"""
if isinstance(canvas_or_content, Canvas):
return cast('Canvas[DepsT, StateT]', canvas_or_content).open_async(
title=title,
width=width,
height=height,
**settings, # type: ignore[arg-type]
)
async def open_new() -> Terminal[DepsT, StateT]:
canvas: Canvas[DepsT, StateT] = _canvas_to_open(
'open_async',
canvas_or_content,
title=title,
width=width,
height=height,
settings=settings,
)
try:
return await canvas.open_async()
except BaseException:
canvas.close(raise_failure=False)
raise
return OpeningTerminal(open_new)
iter
¶
iter(canvas: Canvas[DepsT, StateT], /, *, frames: int | None = None, seconds: float | None = None, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c', title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, **settings: Unpack[OpenSettings]) -> Iterator[Frame]
iter(content: Content | None = None, /, *, frames: int | None = None, seconds: float | None = None, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c', title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float = 60.0, bpm: float = 120.0, effects: Sequence[WritableEffectSpecification] = (), deps: object = ..., state: object = ..., **settings: Unpack[CanvasSettings]) -> Iterator[Frame]
iter(canvas_or_content: Canvas[object, object] | Content | None = None, /, *, frames: int | None = None, seconds: float | None = None, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c', title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, **settings: object) -> Iterator[Frame]
Open a terminal and run it one frame at a time: the program's main loop, as a for loop.
It takes the keywords of open (so xnano.iter(fps=30, mouse=True) opens
the terminal at 30 frames a second with the mouse on), opens the terminal when the loop
starts, and closes it when the loop ends. Each Frame has the
terminal in frame.canvas and the events that arrived since the previous frame in
frame.events; anything you change before the next frame is drawn.
Without frames or seconds it runs the way run does:
until a key of stop_on is pressed, the terminal is asked to
stop, or you break out of the loop. With them, it also ends
after that many frames, or when the terminal has run that long. To run a canvas you have
one frame at a time, use Canvas.iter.
Parameters:
-
canvas_or_content(Canvas[object, object] | Content | None, default:None) –A canvas from
new()to open, or content to write into a new one. -
frames(int | None, default:None) –The most frames to yield.
-
seconds(float | None, default:None) –The most seconds to run for.
-
stop_on(KeyName | Sequence[KeyName] | None, default:'ctrl+c') –The key, or keys, that end the loop and close the terminal;
Nonefor none. -
title(str | None, default:None) –The window title.
-
width(int | Percentage | str | None, default:None) –The width of the region to draw in, as for
open(). -
height(int | Percentage | str | None, default:None) –The height of the region to draw in, as for
open(). -
settings(object, default:{}) –The other keywords of
open(): the terminal settings, the look,fps,bpm,effects,depsandstate.
Yields:
-
Frame–Each frame, until the loop ends.
Raises:
-
TerminalAlreadyOpenError–Another canvas is already on the screen.
-
TerminalError–There is no terminal to draw on.
Examples:
ball = None
for frame in xnano.iter(height=3, fps=30, stop_on='q'):
if ball is None:
ball = frame.canvas.screen.write('o')
for event in frame.events:
if event.key is not None and event.key.key == 'space':
ball.x = 0
ball.x = (ball.x + 1) % frame.canvas.screen.width
Source code in xnano/terminal/__init__.py
def iter(
canvas_or_content: Canvas[object, object] | Content | None = None,
/,
*,
frames: int | None = None,
seconds: float | None = None,
stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c',
title: str | None = None,
width: int | Percentage | str | None = None,
height: int | Percentage | str | None = None,
**settings: object,
) -> Iterator[Frame]:
"""
Open a terminal and run it one frame at a time: the program's main loop, as a ``for`` loop.
It takes the keywords of [`open`][xnano.open] (so ``xnano.iter(fps=30, mouse=True)`` opens
the terminal at 30 frames a second with the mouse on), opens the terminal when the loop
starts, and closes it when the loop ends. Each [`Frame`][xnano.hooks.Frame] has the
terminal in ``frame.canvas`` and the events that arrived since the previous frame in
``frame.events``; anything you change before the next frame is drawn.
Without ``frames`` or ``seconds`` it runs the way [`run`][xnano.canvas.Canvas.run] does:
until a key of ``stop_on`` is pressed, the terminal is asked to
[`stop`][xnano.canvas.Canvas.stop], or you break out of the loop. With them, it also ends
after that many frames, or when the terminal has run that long. To run a canvas you have
one frame at a time, use [`Canvas.iter`][xnano.canvas.Canvas.iter].
Args:
canvas_or_content: A canvas from ``new()`` to open, or content to write into a new
one.
frames: The most frames to yield.
seconds: The most seconds to run for.
stop_on: The key, or keys, that end the loop and close the terminal; ``None`` for
none.
title: The window title.
width: The width of the region to draw in, as for ``open()``.
height: The height of the region to draw in, as for ``open()``.
settings: The other keywords of ``open()``: the terminal settings, the look,
``fps``, ``bpm``, ``effects``, ``deps`` and ``state``.
Yields:
Each frame, until the loop ends.
Raises:
TerminalAlreadyOpenError: Another canvas is already on the screen.
TerminalError: There is no terminal to draw on.
Examples:
```text
ball = None
for frame in xnano.iter(height=3, fps=30, stop_on='q'):
if ball is None:
ball = frame.canvas.screen.write('o')
for event in frame.events:
if event.key is not None and event.key.key == 'space':
ball.x = 0
ball.x = (ball.x + 1) % frame.canvas.screen.width
```
"""
# The keywords were checked by the overloads of this function, which are those of open().
opening = cast('Callable[..., Terminal[object, object]]', open)
with opening(
canvas_or_content, title=title, width=width, height=height, **settings
) as terminal:
yield from terminal.iter(frames=frames, seconds=seconds, stop_on=stop_on)
iter_async
async
¶
iter_async(canvas: Canvas[DepsT, StateT], /, *, frames: int | None = None, seconds: float | None = None, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c', title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, **settings: Unpack[OpenSettings]) -> AsyncIterator[Frame]
iter_async(content: Content | None = None, /, *, frames: int | None = None, seconds: float | None = None, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c', title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float = 60.0, bpm: float = 120.0, effects: Sequence[WritableEffectSpecification] = (), deps: object = ..., state: object = ..., **settings: Unpack[CanvasSettings]) -> AsyncIterator[Frame]
iter_async(canvas_or_content: Canvas[object, object] | Content | None = None, /, *, frames: int | None = None, seconds: float | None = None, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c', title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, **settings: object) -> AsyncIterator[Frame]
Open a terminal and run it one frame at a time with async for, like iter.
The keywords, the frames and the ways the loop ends are the ones iter() has. Between
frames the rest of your event loop runs, and the terminal's async def hooks run on it.
Yields:
-
AsyncIterator[Frame]–Each frame, until the loop ends.
Examples:
Source code in xnano/terminal/__init__.py
async def iter_async(
canvas_or_content: Canvas[object, object] | Content | None = None,
/,
*,
frames: int | None = None,
seconds: float | None = None,
stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c',
title: str | None = None,
width: int | Percentage | str | None = None,
height: int | Percentage | str | None = None,
**settings: object,
) -> AsyncIterator[Frame]:
"""
Open a terminal and run it one frame at a time with ``async for``, like [`iter`][xnano.iter].
The keywords, the frames and the ways the loop ends are the ones ``iter()`` has. Between
frames the rest of your event loop runs, and the terminal's ``async def`` hooks run on it.
Yields:
Each frame, until the loop ends.
Examples:
```text
async def main() -> None:
async for frame in xnano.iter_async(height=3, seconds=2):
...
```
"""
opening = cast('Callable[..., OpeningTerminal[object, object]]', open_async)
async with opening(
canvas_or_content, title=title, width=width, height=height, **settings
) as terminal:
async for frame in terminal.iter_async(
frames=frames, seconds=seconds, stop_on=stop_on
):
yield frame