xnano.canvas
xnano.canvas
¶
xnano.canvas
The canvas: a virtual terminal of cells with a clock, hooks, sound, a cursor and state.
Classes:
-
CanvasSettings–The keyword settings of
new: the terminal settings and the canvas's own look. -
Canvas–A terminal made of devices: a screen, a speaker, a microphone, a keyboard, a mouse and a
Functions:
-
new–Create a canvas: a virtual terminal with a clock, hooks, sound, a cursor and state.
-
active–Return the innermost canvas that is running in this thread or task.
-
write–Put content on the running canvas, and return the placement that holds it.
Attributes:
-
CanvasLayout(TypeAlias) –How a canvas places what is written on it.
CanvasLayout
module-attribute
¶
How a canvas places what is written on it.
'overlay' places every piece on its own, over the whole canvas. 'column' stacks the
pieces from top to bottom in the order they are written, and 'row' from left to right.
CanvasSettings
¶
Bases: TerminalSettings, CanvasAppearanceArguments
The keyword settings of new: the terminal settings and the canvas's own look.
Every key is described where it is declared, in
TerminalSettings and
CanvasAppearanceArguments.
Attributes:
-
mouse(bool | Literal['motion']) –See
TerminalSettings; the same forscroll,keyboard,paste,focus,interrupt,capture,clears_on_closeandalternate_screen. -
background(ColorValue | None) –See
CanvasAppearanceArguments; the same for the other appearance keys. -
layout(CanvasLayout) –How the canvas places what is written on it; see
CanvasLayout.'overlay'when left out. -
edges(EdgeBehavior) –What content written on the canvas does at the edges of its area, unless it is given its own; see
EdgeBehavior.'clip'when left out.
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.
Canvas
¶
Canvas(*, 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: _Hooked[DepsT, StateT], _LookState, Generic[DepsT, StateT]
A terminal made of devices: a screen, a speaker, a microphone, a keyboard, a mouse and a clock, with or without a real screen.
A canvas is a virtual terminal. Create one with new: its screen draws into
memory, its speaker records instead of playing, its keyboard and mouse are driven by your
program, and its clock moves only when you move it with
clock.step or iter, which makes
every run the same. new(realtime=True) runs it on the wall clock instead, on a thread
of its own. open puts the same object on your screen, where
it becomes a Terminal and its clock continues from where it was. It is
not the drawing widget xnano.widgets.Figure.
Each device has the members that belong to it: canvas.screen.write(...) puts content
on the Screen, canvas.speaker.play(...) plays on the
Speaker, canvas.clock.sleep(...) waits on the
Clock, and canvas.keyboard and canvas.mouse read and
press keys and buttons. The canvas itself holds what spans them: hooks, events, state,
dependencies, and running and closing. canvas.write, canvas.render and
canvas.fx are the same as the members of the screen with these names, and
item in canvas is the same as item in canvas.screen.region.
How a canvas ends depends on who moves its clock. On a canvas from new(),
stop only ends a running iter(): the canvas stays open
for writing and rendering. On a canvas that runs by itself (realtime=True, or opened
on the screen) its loop ends with stop(), Ctrl-C or a stop key of
run, and that closes the canvas. close
(or leaving the with block) always closes it. The three states are:
| State | Read it from | Meaning |
|---|---|---|
| running | is_running |
open, and its loop has not been asked to end |
| time paused | clock.is_paused |
frozen by clock.pause(); it still draws and hears input |
| closed | is_closed |
torn down; it cannot draw or listen |
Any thread may write, remove, draw and play. Hooks run on the canvas's loop, so keep them short.
Attributes:
-
screen(Screen[DepsT, StateT]) –The
Screen: what is written and drawn, and its look. -
speaker(Speaker) –The
Speaker: notes, melodies and sounds. -
microphone(Microphone) –The
Microphone: the level of the sound around. -
keyboard(Keyboard) –The
Keyboard: keys held, and the program's own key presses, pastes and prompts. -
mouse(Mouse) –The
Mouse: the pointer, the buttons, the wheel. -
clock(Clock) –The
Clockeverything on the canvas runs on. -
fx(WritableEffectProperties) –The visual effects of all of the canvas, the same as
screen.fx. -
is_closed(bool) –Whether the canvas has been torn down.
-
is_running(bool) –Whether the canvas is open and its loop has not been asked to end.
-
deps(DepsT) –The dependencies given to
new(deps=...), which hooks read. -
state–The dataclass given to
new(state=...).
Examples:
import xnano
with xnano.new(width=12, height=2, fps=10) as canvas:
greeting = canvas.screen.write('hello', x=1, y=1)
for frame in canvas.iter(frames=3):
greeting.text = f'frame {frame.index}'
assert canvas.screen.render().splitlines()[1] == ' frame 2'
assert round(canvas.clock.elapsed_seconds, 3) == 0.3
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.
-
API Reference
xnano
-
xnano -
xnano.ai
ai -
xnano.ai.capabilities
capabilities -
xnano.audio
audioMicrophone -
xnano.canvas
canvas -
xnano.devices
devices -
xnano.effects
effects-
AudioEffectParametersapply_to -
BitCrushAudioEffectParametersapply_to -
CoalesceEffectParametersapply_to -
DarkenEffectParametersapply_to -
DelayAudioEffectParametersapply_to -
DissolveEffectParametersapply_to -
DistortionAudioEffectParametersapply_to -
EffectParametersapply_to -
EvolveEffectParametersapply_to -
EvolveFromEffectParametersapply_to -
EvolveIntoEffectParametersapply_to -
ExpandEffectParametersapply_to -
ExplodeEffectParametersapply_to -
FadeFromEffectParametersapply_to -
FadeToEffectParametersapply_to -
GlitchEffectParametersapply_to -
HighPassAudioEffectParametersapply_to -
HslShiftEffectParametersapply_to -
LightenEffectParametersapply_to -
LowPassAudioEffectParametersapply_to -
PaintEffectParametersapply_to -
ReverbAudioEffectParametersapply_to -
SaturateEffectParametersapply_to -
SleepEffectParametersapply_to -
SlideInEffectParametersapply_to -
SlideOutEffectParametersapply_to -
StretchEffectParametersapply_to -
SweepInEffectParametersapply_to -
SweepOutEffectParametersapply_to -
TremoloAudioEffectParametersapply_to -
WritableEffectProperties
-
-
xnano.hooks
hooks -
xnano.layout
layout -
xnano.operations
operations -
xnano.sandbox
sandbox -
xnano.state
stateStateNamespace -
xnano.terminal
terminal
-
Methods:
-
__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.
-
__setattr__–Set an attribute, or raise
AttributeErrorfor an unknown public name. -
hook–Call a function when something happens on this canvas or placement.
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()
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.
__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)
__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
¶
new(content: Content | Canvas[WrittenDepsT, WrittenStateT] | None = None, /, *, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float | None = None, bpm: float | None = None, realtime: bool = False, title: str | None = None, effects: Sequence[WritableEffectSpecification] = (), **settings: Unpack[CanvasSettings]) -> Canvas[None, None]
new(content: Content | Canvas[WrittenDepsT, WrittenStateT] | None = None, /, *, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float | None = None, bpm: float | None = None, realtime: bool = False, title: str | None = None, effects: Sequence[WritableEffectSpecification] = (), state: StateT, **settings: Unpack[CanvasSettings]) -> Canvas[None, StateT]
new(content: Content | Canvas[WrittenDepsT, WrittenStateT] | None = None, /, *, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float | None = None, bpm: float | None = None, realtime: bool = False, title: str | None = None, effects: Sequence[WritableEffectSpecification] = (), deps: DepsT, **settings: Unpack[CanvasSettings]) -> Canvas[DepsT, None]
new(content: Content | Canvas[WrittenDepsT, WrittenStateT] | None = None, /, *, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float | None = None, bpm: float | None = None, realtime: bool = False, title: str | None = None, effects: Sequence[WritableEffectSpecification] = (), deps: DepsT, state: StateT, **settings: Unpack[CanvasSettings]) -> Canvas[DepsT, StateT]
new(content: Content | Canvas[WrittenDepsT, WrittenStateT] | None = None, /, *, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float | None = None, bpm: float | None = None, realtime: bool = False, title: str | None = None, effects: Sequence[WritableEffectSpecification] = (), deps: object = _UNSET, state: object = _UNSET, **settings: object) -> Canvas[DepsT, StateT]
Create a canvas: a virtual terminal with a clock, hooks, sound, a cursor and state.
It has no screen and draws into memory. Its clock moves only when you move it, with
step or iter, so every run is
the same; realtime=True runs it on the wall clock on a thread of its own instead.
Canvas.open (or open) puts it on the screen.
A with block closes it.
A canvas with a manual clock belongs to the thread that created it: use it, and close it,
on that thread, for example with a with block in the worker that made it. A canvas
that several threads use, or that is closed after its thread has ended, is created with
realtime=True.
content, when given, is written at the top-left corner, as canvas.screen.write(content)
would. The appearance keywords (colors, text modifiers, border, border_style)
style the canvas itself, not its content, so they are accepted only without content:
new(border='rounded') borders the canvas, and new().write('hello', border='rounded')
borders the text. A canvas's foreground and background color the cells no content
covers. padding and margin pad and space the canvas itself. title is the
window title.
Created inside the with block of another canvas, the new canvas belongs to that one
from the start but is hidden in it: its size is measured in that canvas ('50%' is
half of it, and no size fills it), it runs on that canvas's time and its hooks hear that
canvas's input. outer.screen.write(canvas, x=..., y=...) shows it, once, where it is
written. Leaving its own with block keeps it; it closes with the canvas it belongs
to. Inside its with block, outer.screen.write(...) places content within the new
canvas's area of outer. It takes that canvas's edges unless given its own.
Screen.new creates a canvas that is shown at once. A canvas
given state or deps stays on its own, because those belong to the outermost
canvas: it is measured in the canvas around it, takes its fps, bpm and edges
unless given its own, and closes with it.
The terminal settings (mouse, scroll, keyboard, paste, focus,
interrupt, capture, clears_on_close, alternate_screen) are stored and take effect
when the canvas is opened on the screen; see
TerminalSettings.
Parameters:
-
content(Content | Canvas[WrittenDepsT, WrittenStateT] | None, default:None) –Something to write into the canvas at once, such as text or a widget.
-
width(int | Percentage | str | None, default:None) –The width in cells, or a percentage of the window such as
'50%', read when the canvas is created; 80 whenNone.'fit'makes the canvas as wide as what is written on it, following it as it changes. On the screen it is the width of the region the canvas draws in, read again when it is opened. -
height(int | Percentage | str | None, default:None) –The height in cells, or a percentage of the window such as
'50%'; 24 whenNone.'fit'makes the canvas as tall as what is written on it. On the screen it is the height of the region the canvas draws in, and'100%'for both sizes fills the whole window. -
fps(float | None, default:None) –The most frames drawn per second, and the length of one step of
iter(); the enclosing canvas's, else 60, whenNone. -
bpm(float | None, default:None) –Beats per minute for beat timers, notes and melodies; the enclosing canvas's, else 120, when
None. -
realtime(bool, default:False) –Whether the canvas runs by itself on the wall clock, on a thread of its own.
-
title(str | None, default:None) –The window title, shown when the canvas is on the screen.
-
effects(Sequence[WritableEffectSpecification], default:()) –Effects to apply to the canvas, as dictionaries with a
kindkey. -
deps(object, default:_UNSET) –Dependencies that hooks read as
context.deps; the canvas never reads them. -
state(object, default:_UNSET) –A dataclass instance the canvas keeps and validates. Hooks read and write it.
-
settings(object, default:{}) –The terminal settings and the canvas's own look; see
CanvasSettings.
Returns:
-
Canvas[DepsT, StateT]–The
Canvas, which is also the one module-level functions such -
Canvas[DepsT, StateT]–as
activefind.
Raises:
-
TypeError–An appearance keyword was given with content, or a keyword is unknown.
-
ValueError–A size (1 to 65535 cells),
fps,bpm,realtime, terminal setting or border kind is out of range.
Examples:
import xnano
with xnano.new(width=16, height=3) as canvas:
assert (canvas.screen.width, canvas.screen.height) == (16, 3)
assert xnano.active() is canvas
assert not canvas.clock.is_realtime
with xnano.new('hello', width=8, height=1) as greeting:
assert greeting.screen.render() == 'hello'
with xnano.new(width=12, height=4) as outer:
with xnano.new(height='50%') as inner:
inner.screen.write('inside')
assert (inner.screen.width, inner.screen.height) == (12, 2)
assert outer.screen.render().strip() == ''
outer.screen.write(inner, y=2)
assert outer.screen.render().splitlines()[2] == 'inside'
assert xnano.active() is outer
Source code in xnano/canvas.py
def new(
content: Content | Canvas[WrittenDepsT, WrittenStateT] | None = None,
/,
*,
width: int | Percentage | str | None = None,
height: int | Percentage | str | None = None,
fps: float | None = None,
bpm: float | None = None,
realtime: bool = False,
title: str | None = None,
effects: Sequence[WritableEffectSpecification] = (),
deps: object = _UNSET,
state: object = _UNSET,
**settings: object,
) -> Canvas[DepsT, StateT]:
"""
Create a canvas: a virtual terminal with a clock, hooks, sound, a cursor and state.
It has no screen and draws into memory. Its clock moves only when you move it, with
[`step`][xnano.devices.Clock.step] or [`iter`][xnano.canvas.Canvas.iter], so every run is
the same; ``realtime=True`` runs it on the wall clock on a thread of its own instead.
[`Canvas.open`][xnano.canvas.Canvas.open] (or [`open`][xnano.open]) puts it on the screen.
A ``with`` block closes it.
A canvas with a manual clock belongs to the thread that created it: use it, and close it,
on that thread, for example with a ``with`` block in the worker that made it. A canvas
that several threads use, or that is closed after its thread has ended, is created with
``realtime=True``.
``content``, when given, is written at the top-left corner, as ``canvas.screen.write(content)``
would. The appearance keywords (colors, text modifiers, ``border``, ``border_style``)
style the canvas itself, not its content, so they are accepted only without content:
``new(border='rounded')`` borders the canvas, and ``new().write('hello', border='rounded')``
borders the text. A canvas's ``foreground`` and ``background`` color the cells no content
covers. ``padding`` and ``margin`` pad and space the canvas itself. ``title`` is the
window title.
Created inside the ``with`` block of another canvas, the new canvas belongs to that one
from the start but is hidden in it: its size is measured in that canvas (``'50%'`` is
half of it, and no size fills it), it runs on that canvas's time and its hooks hear that
canvas's input. ``outer.screen.write(canvas, x=..., y=...)`` shows it, once, where it is
written. Leaving its own ``with`` block keeps it; it closes with the canvas it belongs
to. Inside its ``with`` block, ``outer.screen.write(...)`` places content within the new
canvas's area of ``outer``. It takes that canvas's ``edges`` unless given its own.
[`Screen.new`][xnano.devices.Screen.new] creates a canvas that is shown at once. A canvas
given ``state`` or ``deps`` stays on its own, because those belong to the outermost
canvas: it is measured in the canvas around it, takes its ``fps``, ``bpm`` and ``edges``
unless given its own, and closes with it.
The terminal settings (``mouse``, ``scroll``, ``keyboard``, ``paste``, ``focus``,
``interrupt``, ``capture``, ``clears_on_close``, ``alternate_screen``) are stored and take effect
when the canvas is opened on the screen; see
[`TerminalSettings`][xnano.terminal.TerminalSettings].
Args:
content: Something to write into the canvas at once, such as text or a widget.
width: The width in cells, or a percentage of the window such as ``'50%'``, read
when the canvas is created; 80 when ``None``. ``'fit'`` makes the canvas as
wide as what is written on it, following it as it changes. On the screen it is
the width of the region the canvas draws in, read again when it is opened.
height: The height in cells, or a percentage of the window such as ``'50%'``; 24
when ``None``. ``'fit'`` makes the canvas as tall as what is written on it. On
the screen it is the height of the region the canvas draws in, and ``'100%'``
for both sizes fills the whole window.
fps: The most frames drawn per second, and the length of one step of ``iter()``;
the enclosing canvas's, else 60, when ``None``.
bpm: Beats per minute for beat timers, notes and melodies; the enclosing canvas's,
else 120, when ``None``.
realtime: Whether the canvas runs by itself on the wall clock, on a thread of its own.
title: The window title, shown when the canvas is on the screen.
effects: Effects to apply to the canvas, as dictionaries with a ``kind`` key.
deps: Dependencies that hooks read as ``context.deps``; the canvas never reads them.
state: A dataclass instance the canvas keeps and validates. Hooks read and write it.
settings: The terminal settings and the canvas's own look; see
[`CanvasSettings`][xnano.canvas.CanvasSettings].
Returns:
The [`Canvas`][xnano.canvas.Canvas], which is also the one module-level functions such
as [`active`][xnano.active] find.
Raises:
TypeError: An appearance keyword was given with content, or a keyword is unknown.
ValueError: A size (1 to 65535 cells), ``fps``, ``bpm``, ``realtime``, terminal
setting or border kind is out of range.
Examples:
```python
import xnano
with xnano.new(width=16, height=3) as canvas:
assert (canvas.screen.width, canvas.screen.height) == (16, 3)
assert xnano.active() is canvas
assert not canvas.clock.is_realtime
with xnano.new('hello', width=8, height=1) as greeting:
assert greeting.screen.render() == 'hello'
with xnano.new(width=12, height=4) as outer:
with xnano.new(height='50%') as inner:
inner.screen.write('inside')
assert (inner.screen.width, inner.screen.height) == (12, 2)
assert outer.screen.render().strip() == ''
outer.screen.write(inner, y=2)
assert outer.screen.render().splitlines()[2] == 'inside'
assert xnano.active() is outer
```
"""
enclosing = _enclosing_canvas()
canvas: Canvas[DepsT, StateT] = _create(
content,
width=width,
height=height,
fps=fps,
bpm=bpm,
realtime=realtime,
title=title,
effects=effects,
deps=deps,
state=state,
enclosing=enclosing,
**settings,
)
if enclosing is not None and deps is _UNSET and state is _UNSET:
try:
placement = enclosing._canvas._place_on(
enclosing._content,
cast('Canvas[object, object]', canvas),
parent_owner=enclosing,
is_in_flow=False,
)
placement.is_visible = False
except BaseException:
canvas.close(raise_failure=False)
raise
canvas._is_hidden_until_written = True
return canvas
active
¶
Return the innermost canvas that is running in this thread or task.
A canvas is active from the moment it is created until it ends: the most recently created
one wins, and a canvas that was asked to stop gives way to the
one created before it. A canvas created inside the with block of another one belongs
to that canvas, so the outer canvas stays active. Hooks run on a canvas's loop see that
canvas.
Parameters:
-
is_required(bool, default:True) –Whether to raise when no canvas is running.
Raises:
-
TerminalClosedError–No canvas is running and
is_requiredis true.
Examples:
import xnano
assert xnano.active(is_required=False) is None
with xnano.new(width=4, height=1) as outer:
assert xnano.active() is outer
with xnano.new(width=4, height=1):
assert xnano.active() is outer
assert xnano.active(is_required=False) is None
Source code in xnano/canvas.py
def active(*, is_required: bool = True) -> Canvas[object, object] | None:
"""
Return the innermost canvas that is running in this thread or task.
A canvas is active from the moment it is created until it ends: the most recently created
one wins, and a canvas that was asked to [`stop`][xnano.canvas.Canvas.stop] gives way to the
one created before it. A canvas created inside the ``with`` block of another one belongs
to that canvas, so the outer canvas stays active. Hooks run on a canvas's loop see that
canvas.
Args:
is_required: Whether to raise when no canvas is running.
Raises:
TerminalClosedError: No canvas is running and ``is_required`` is true.
Examples:
```python
import xnano
assert xnano.active(is_required=False) is None
with xnano.new(width=4, height=1) as outer:
assert xnano.active() is outer
with xnano.new(width=4, height=1):
assert xnano.active() is outer
assert xnano.active(is_required=False) is None
```
"""
canvas = next(
(
candidate
for candidate in _live_canvases()
if candidate.is_running and candidate._canvas is candidate
),
None,
)
if canvas is None and is_required:
raise TerminalClosedError(
'No canvas is running. Create one with "with xnano.new() as canvas:" or '
'"with xnano.open() as terminal:", and call this inside the block.'
)
return canvas
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[object, object]
Put content on the running canvas, and return the placement that holds it.
The running canvas is the canvas that active returns.
xnano.write(...) is the same as xnano.active().screen.write(...). It takes the
same arguments as Screen.write.
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[object, object]–The
Placementthat holds the content. Use it to move, -
Placement[object, object]–resize or remove the content.
Raises:
-
TerminalClosedError– -
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=2) as canvas:
label = xnano.write('hello', foreground='green')
assert label.text == 'hello'
assert canvas.render().splitlines()[0] == 'hello'
Source code in xnano/canvas.py
@refuse_unknown_keywords
def 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: _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[object, object]:
"""
Put content on the running canvas, and return the placement that holds it.
The running canvas is the canvas that [`active`][xnano.active] returns.
``xnano.write(...)`` is the same as ``xnano.active().screen.write(...)``. It takes the
same arguments as [`Screen.write`][xnano.devices.Screen.write].
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:
TerminalClosedError: No canvas is running. Start a canvas with
[`open`][xnano.open] or [`new`][xnano.new]. Then write inside its ``with`` block.
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=2) as canvas:
label = xnano.write('hello', foreground='green')
assert label.text == 'hello'
assert canvas.render().splitlines()[0] == 'hello'
```
"""
canvas = active(is_required=False)
if canvas is None:
raise TerminalClosedError(
'xnano.write() did not write, because no canvas is running. Start a canvas with '
'"with xnano.open() as terminal:" or "with xnano.new() as canvas:". Then call '
'xnano.write() inside the "with" block.'
)
return canvas.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,
)