xnano
xnano
¶
xnano
An extremely nano python terminal experience; built on ratatui.
Modules:
-
ai–xnano.ai
-
art–xnano.art
-
audio–xnano.audio
-
buffers–xnano.buffers
-
canvas–xnano.canvas
-
components–xnano.components
-
demo–xnano.demo
-
devices–xnano.devices
-
effects–xnano.effects
-
errors–xnano.errors
-
events–xnano.events
-
expressions–xnano.expressions
-
hooks–xnano.hooks
-
layout–xnano.layout
-
operations–xnano.operations
-
sandbox–xnano.sandbox
-
state–xnano.state
-
styles–xnano.styles
-
symbols–xnano.symbols
-
terminal–xnano.terminal
-
widgets–xnano.widgets
Classes:
-
Image–An image and how it is shown: what
Screen.writetakes -
Pixel–One cell (or one dot, at half-block and braille resolution) of a region.
-
Audio–Audio to play: a recording loaded from a file, samples you made, or what a canvas played.
-
Note–A note, or a chord, to play: a pitch, how long it lasts and how it sounds.
-
Canvas–A terminal made of devices: a screen, a speaker, a microphone, a keyboard, a mouse and a
-
Context–What a hook is called with.
-
Terminal–A canvas that draws on your screen and reads your keyboard and mouse.
-
Color–A terminal color: a named palette color, a palette index or a true color.
Functions:
-
load_image–Load an image or an animation from a file path or from bytes.
-
pixel_art–Build pixel art from text, a picture, bytes or nothing (does not draw).
-
load_audio–Load audio from an audio file: its path, or its bytes.
-
play–Play a note, a sound, a symbol name, a melody or a sequence of those.
-
active–Return the innermost canvas that is running in this thread or task.
-
new–Create a canvas: a virtual terminal with a clock, hooks, sound, a cursor and state.
-
write–Put content on the running canvas, and return the placement that holds it.
-
playable–Turn a function into a component that plays itself.
-
renderable–Turn a function into a component with a screen of its own, which draws and plays.
-
writable–Turn a function into a component that draws itself.
-
effect–Create the parameters of a visual or sound effect.
-
hook–Describe a hook once, to attach to any canvas or placement later.
-
box–Build an empty standalone rectangle of cells (does not draw).
-
region–Build a standalone region from the content that
canvas.screen.writeaccepts (does not draw). -
from_rich–Draw anything the rich library draws: rich markup, a table, a panel, syntax and more.
-
iter–Open a terminal and run it one frame at a time: the program's main loop, as a
forloop. -
iter_async–Open a terminal and run it one frame at a time with
async for, likeiter. -
open–Put a canvas on your screen and return it as a
Terminal. -
open_async–Put a canvas on your screen like
open, from a coroutine.
Image
dataclass
¶
Image(source: TerminalImage | PathLike[str] | str | bytes, *, x: Axis | None = None, y: Axis | None = None, width: Axis | None = None, height: Axis | None = None, layer: int = 0, lock: bool = False, fit: ImageFit | None = None, resampling_filter: ResamplingFilter | None = None, background: ColorValue = (0, 0, 0), speed: float = 1.0, symbol: str | None = None)
An image and how it is shown: what Screen.write takes
to put a picture on the canvas.
Make one from the path of an image file, its bytes, or a
TerminalImage. A file is read once, here, where you can
see it; write never takes a path. The placement values are what write uses when it
is not given its own. An image sized by a percentage (or not sized at all) is converted
again whenever the canvas is resized, so it always fits; give it a number, or
lock=True, and it keeps its size.
A picture with transparent pixels (a PNG with an alpha channel, for example) lets what is
below it on the canvas show through them. Pixels that are only partly transparent blend
with background, and a cell with one transparent half and one drawn half shows the terminal's
default color in the transparent half.
Maps to xnano_image.TerminalImage.
Attributes:
-
decoded(TerminalImage) –The decoded picture, a
TerminalImage. -
x(Axis | None) –The column of the left edge, or
Nonefor the top-left corner. -
y(Axis | None) –The row of the top edge, or
None. -
width(Axis | None) –The width: cells, a percentage, an expression, or
Nonefor the picture's own. -
height(Axis | None) –The height, in the same forms.
-
layer(int) –Content with a higher layer is drawn over content with a lower one.
-
lock(bool) –Whether the image keeps the size it was shown at when the canvas is resized.
-
fit(ImageFit | None) –How the picture sits in a box of
widthbyheight:'contain'(the default),'cover','stretch','crop'or'smart'. -
resampling_filter(ResamplingFilter | None) –How pixels are blended when it is resized. By default a small picture that is enlarged keeps hard pixel edges (
'nearest') and any other is smoothed ('lanczos3'). -
background(tuple[int, int, int]) –The color of the margins around a picture with no transparent pixel, and the color its partly transparent pixels are blended with. Fully transparent pixels let the canvas show through.
-
symbol(str | None) –The name the image is registered under in
symbols, orNone.
Examples:
import xnano
from xnano_image import TerminalImage
picture = xnano.Image(TerminalImage.from_rgba(2, 2, bytes([255, 0, 0, 255]) * 4), width=8)
with xnano.new(width=20, height=6) as canvas:
canvas.screen.write(picture, x='center')
# xnano.Image('photo.png', width='100%') loads a file, and refits when the window resizes.
Load an image and set how it is shown.
Parameters:
-
source(TerminalImage | PathLike[str] | str | bytes) –The path of an image file (PNG, JPEG, GIF, WebP or XNI), the bytes of one, or an image. An animated file plays on the canvas's clock.
-
x(Axis | None, default:None) –The column of the left edge: cells, a percentage, a word such as
'center', an expression or a range. SeeAxis. -
y(Axis | None, default:None) –The row of the top edge, in the same forms.
-
width(Axis | None, default:None) –The width, in the same forms; the picture's own when
None. -
height(Axis | None, default:None) –The height, in the same forms.
-
layer(int, default:0) –Content with a higher layer is drawn over content with a lower one.
-
lock(bool, default:False) –Keep the size the image has when it is added, whatever the canvas does.
-
fit(ImageFit | None, default:None) –How the picture sits in a box of
widthbyheight. -
resampling_filter(ResamplingFilter | None, default:None) –How pixels are blended when it is resized.
-
background(ColorValue, default:(0, 0, 0)) –The color of the margins around a picture with no transparent pixel and the color partly transparent pixels are blended with, as a color name, a hex string, an
(r, g, b)tuple or aColor. Fully transparent pixels let the canvas show through. -
speed(float, default:1.0) –How fast an animated image plays:
2.0is twice as fast. -
symbol(str | None, default:None) –A name to register the image under in
symbols.
Raises:
-
ImportError–xnano-imageis not installed. Install it withpip install "xnano[image]". -
TypeError–sourceis not a path, bytes or an image. -
FileNotFoundError–sourceis a path with no file at it. -
ValueError–symbolcannot be a symbol name, or another kind of value already has it.
Source code in xnano/art/_images.py
def __init__(
self,
source: TerminalImage | os.PathLike[str] | str | bytes,
*,
x: Axis | None = None,
y: Axis | None = None,
width: Axis | None = None,
height: Axis | None = None,
layer: int = 0,
lock: bool = False,
fit: ImageFit | None = None,
resampling_filter: ResamplingFilter | None = None,
background: ColorValue = (0, 0, 0),
speed: float = 1.0,
symbol: str | None = None,
) -> None:
"""
Load an image and set how it is shown.
Args:
source: The path of an image file (PNG, JPEG, GIF, WebP or XNI), the bytes of one,
or an image. An animated file plays on the canvas's clock.
x: The column of the left edge: cells, a percentage, a word such as ``'center'``, an
expression or a range. See [`Axis`][xnano.layout.Axis].
y: The row of the top edge, in the same forms.
width: The width, in the same forms; the picture's own when ``None``.
height: The height, in the same forms.
layer: Content with a higher layer is drawn over content with a lower one.
lock: Keep the size the image has when it is added, whatever the canvas does.
fit: How the picture sits in a box of ``width`` by ``height``.
resampling_filter: How pixels are blended when it is resized.
background: The color of the margins around a picture with no transparent pixel
and the color partly transparent pixels are blended with, as a color name, a
hex string, an ``(r, g, b)`` tuple or a [`Color`][xnano_core.Color]. Fully
transparent pixels let the canvas show through.
speed: How fast an animated image plays: ``2.0`` is twice as fast.
symbol: A name to register the image under in [`symbols`][xnano.symbols].
Raises:
ImportError: ``xnano-image`` is not installed. Install it with
``pip install "xnano[image]"``.
TypeError: ``source`` is not a path, bytes or an image.
FileNotFoundError: ``source`` is a path with no file at it.
ValueError: ``symbol`` cannot be a symbol name, or another kind of value
already has it.
"""
if is_image(source):
image = cast('TerminalImage', source)
else:
module = require('image', needed_for='xnano.Image')
if isinstance(source, bytes):
image = module.TerminalImage.from_bytes(source)
elif isinstance(source, (str, os.PathLike)):
path = pathlib.Path(source)
if not path.is_file():
raise FileNotFoundError(
f'Image could not load {str(path)!r}, because no image file exists '
f'there. Check the path, or pass the bytes of the image.'
)
image = module.TerminalImage.open(path)
else:
raise TypeError(
f'Image needs the path of an image file, the bytes of an image or an '
f'image, but got {type(source).__name__}. Pass Image("picture.png").'
)
if speed != 1.0:
image = image.with_speed(speed)
for name, value in (
('decoded', image),
('x', x),
('y', y),
('width', width),
('height', height),
('layer', layer),
('lock', lock),
('fit', fit),
('resampling_filter', resampling_filter),
('background', to_rgb(background)),
('symbol', symbol),
):
object.__setattr__(self, name, value)
if symbol is not None:
symbols.register(symbol, self)
width
instance-attribute
¶
width: Axis | None
The width: cells, a percentage, an expression, or None for the picture's own.
layer
instance-attribute
¶
layer: int
Content with a higher layer is drawn over content with a lower one.
lock
instance-attribute
¶
lock: bool
Whether the image keeps the size it was shown at when the canvas is resized.
fit
instance-attribute
¶
fit: ImageFit | None
How the picture sits in a box of width by height, or None for the default.
resampling_filter
instance-attribute
¶
resampling_filter: ResamplingFilter | None
How pixels are blended when it is resized, or None to choose by scale.
background
instance-attribute
¶
The color of margins and partly transparent pixels, as (red, green, blue).
Pixel
dataclass
¶
Pixel(preset_or_character: PixelPreset | str = 'block', *, foreground: ColorValue | None = None, background: ColorValue | None = None, symbol: str | None = None)
One cell (or one dot, at half-block and braille resolution) of a region.
The first argument is a preset name such as 'diamond', the name of a registered
symbol, or a single character that is drawn as it is. A pixel is a value: it compares by
its fields, and region[x, y] returns one and accepts one.
Parameters:
-
preset_or_character(PixelPreset | str, default:'block') –A
PixelPreset, the name of a registered symbol, or one character. -
foreground(ColorValue | None, default:None) –The color of the character.
-
background(ColorValue | None, default:None) –The color behind the character.
-
symbol(str | None, default:None) –A name to register this pixel under, so that
Pixel('wall')finds it later. The name takes two characters or more; seeregister.
Attributes:
-
character(str) –The glyph drawn in the cell or dot.
-
foreground(ColorValue | None) –The color of the glyph, or
Nonefor the cell's own. -
background(ColorValue | None) –The color behind the glyph, or
Nonefor the cell's own. -
symbol(str | None) –The registered symbol name, or
None.
Raises:
-
ValueError–The name is not a preset or a registered symbol (the message lists both and the closest names first), or the character is empty.
Examples:
import xnano
from xnano import Pixel
diamond = Pixel('diamond', foreground='red')
assert diamond.character == '◆'
assert Pixel('x').character == 'x'
with xnano.new(width=4, height=1) as canvas:
canvas.screen.region[1, 0] = diamond
assert canvas.screen.region[1, 0].character == '◆'
Make a pixel from a preset, a symbol name or a character.
Parameters:
-
preset_or_character(PixelPreset | str, default:'block') –A preset name, a registered symbol name or one character.
-
foreground(ColorValue | None, default:None) –The color of the character.
-
background(ColorValue | None, default:None) –The color behind the character.
-
symbol(str | None, default:None) –A name to register this pixel under.
Methods:
-
cell–Return the core cell that draws this pixel.
-
__str__–Return the character of the pixel, so
print(pixel)shows what it draws. -
__xnano_write__–Return a buffer of one cell that shows the pixel.
Source code in xnano/art/_pixels.py
def __init__(
self,
preset_or_character: PixelPreset | str = 'block',
*,
foreground: ColorValue | None = None,
background: ColorValue | None = None,
symbol: str | None = None,
) -> None:
"""
Make a pixel from a preset, a symbol name or a character.
Args:
preset_or_character: A preset name, a registered symbol name or one character.
foreground: The color of the character.
background: The color behind the character.
symbol: A name to register this pixel under.
"""
if not isinstance(preset_or_character, str) or not preset_or_character:
raise ValueError(
f'A pixel is made from a preset name, a symbol name or one character, but '
f'got {preset_or_character!r}. Try Pixel("block") or Pixel("#").'
)
for color_name, color in (('foreground', foreground), ('background', background)):
if color is None:
continue
try:
if color_name == 'foreground':
_core.Cell(' ', foreground=color)
else:
_core.Cell(' ', background=color)
except (TypeError, ValueError) as error:
raise type(error)(
f'The {color_name} of a pixel must be a color, but was {color!r}. Use a '
f'name such as "red", a hex string such as "#ff8800", an (r, g, b) '
f'tuple or a Color.'
) from error
name = preset_or_character
known_symbol: str | None = None
if len(name) == 1:
if unicodedata.category(name) == 'Cc':
raise ValueError(
f'A pixel cannot be the control character {name!r}, because a cell '
f'cannot hold one. Pass a printable character such as Pixel("#"), or a '
f'preset such as Pixel("block").'
)
character = name
elif name in _PRESET_CHARACTERS:
character = _PRESET_CHARACTERS[name]
elif name in symbols.names(kind=Pixel):
registered = symbols.lookup(name, kind=Pixel)
character = registered.character
foreground = registered.foreground if foreground is None else foreground
background = registered.background if background is None else background
known_symbol = name
else:
raise _unknown_name_error(name)
object.__setattr__(self, 'character', character)
object.__setattr__(self, 'foreground', foreground)
object.__setattr__(self, 'background', background)
object.__setattr__(self, 'symbol', symbol if symbol is not None else known_symbol)
object.__setattr__(self, '_cell', None)
if symbol is not None:
symbols.register(symbol, self)
foreground
instance-attribute
¶
The color of the glyph, or None for the cell's own.
background
instance-attribute
¶
The color behind the glyph, or None for the cell's own.
cell
¶
cell() -> Cell
Return the core cell that draws this pixel.
The cell is built once and kept, so writing the same pixel many times is cheap.
Source code in xnano/art/_pixels.py
def cell(self) -> _core.Cell:
"""
Return the core cell that draws this pixel.
The cell is built once and kept, so writing the same pixel many times is cheap.
"""
built = self._cell
if built is None:
built = _core.Cell(
self.character,
foreground=self.foreground,
background=self.background,
)
object.__setattr__(self, '_cell', built)
return built
__xnano_write__
¶
Audio
dataclass
¶
Audio(terminal_sound: TerminalSound, /, *, symbol: str | None = None)
Audio to play: a recording loaded from a file, samples you made, or what a canvas played.
Load a WAV, MP3, FLAC, Ogg Vorbis or MP4/AAC file with load_audio,
make audio from samples with from_samples, or take what a
canvas from new() played with Speaker.render. Play it
with Speaker.play or play, or give it a
symbol and play it by name. Audio is mono, and all of it is kept in memory, so a long
song takes memory in proportion to its length.
Attributes:
-
terminal_sound(TerminalSound) –The audio as an
xnano-audiosound, for the functions of that package. Maps toxnano_audio.TerminalSound. -
symbol(str | None) –The name the audio is registered under in
symbols, orNone.play('kick')plays the audio registered as'kick'. -
sample_rate(int) –How many samples it has per second.
-
duration_milliseconds(float) –How long it lasts, in milliseconds.
-
peak(float) –The largest absolute sample:
0.0for silence, above1.0when it clips. -
region(Region[float]) –The audio on the timeline as a piano roll: a
Regionthat starts at beat 0, lasts as long as the audio at 120 beats per minute and covers the single row of middle C, because audio has no pitch of its own.
Examples:
import xnano
audio = xnano.Audio.from_samples([0.0, 0.5, -0.5, 0.0])
assert (audio.sample_rate, audio.peak) == (44100, 0.5)
assert (audio.region.y, audio.region.height) == (60, 1)
Make audio from a sound made with xnano-audio.
For a file use load_audio, and for samples
from_samples.
Parameters:
-
terminal_sound(TerminalSound) –A
TerminalSound, such as one that anxnano-audiofunction rendered. -
symbol(str | None, default:None) –A name to register the audio under in
symbols, soplay(name)plays it.
Raises:
-
ImportError–xnano-audiois not installed. Install it withpip install "xnano[audio]". -
TypeError–terminal_soundis not aTerminalSound. -
ValueError–symbolcannot be a symbol name, or another kind of value already has it.
Methods:
-
from_samples–Make audio from samples: numbers from
-1.0to1.0, one per instant. -
samples–A copy of the samples, in order.
Source code in xnano/audio/_audio.py
def __init__(
self, terminal_sound: TerminalSound, /, *, symbol: str | None = None
) -> None:
"""
Make audio from a sound made with ``xnano-audio``.
For a file use [`load_audio`][xnano.load_audio], and for samples
[`from_samples`][xnano.Audio.from_samples].
Args:
terminal_sound: A [`TerminalSound`][xnano_audio.TerminalSound], such as one
that an ``xnano-audio`` function rendered.
symbol: A name to register the audio under in [`symbols`][xnano.symbols], so
``play(name)`` plays it.
Raises:
ImportError: ``xnano-audio`` is not installed. Install it with
``pip install "xnano[audio]"``.
TypeError: ``terminal_sound`` is not a ``TerminalSound``.
ValueError: ``symbol`` cannot be a symbol name, or another kind of value
already has it.
"""
module = require('audio', needed_for='xnano.Audio')
if not isinstance(terminal_sound, module.TerminalSound):
raise TypeError(
f'Audio wraps an xnano_audio.TerminalSound, but got '
f'{type(terminal_sound).__name__}. Load a file with '
f'xnano.load_audio("song.mp3"), or make audio from samples with '
f'xnano.Audio.from_samples([0.0, 0.5, -0.5]).'
)
object.__setattr__(self, 'terminal_sound', terminal_sound)
object.__setattr__(self, 'symbol', symbol)
if symbol is not None:
symbols.register(symbol, self)
terminal_sound
instance-attribute
¶
terminal_sound: TerminalSound
The audio as an xnano-audio sound. Maps to xnano_audio.TerminalSound.
duration_milliseconds
property
¶
duration_milliseconds: float
How long the audio lasts, in milliseconds.
region
property
¶
The audio on the timeline as a piano roll.
The region starts at beat 0 and lasts as long as the audio does at 120 beats per
minute, the tempo of play when no canvas is running, so its
milliseconds view is the duration of the audio. Audio has no pitch of its own,
so the region covers the one row of middle C (60). context.region of a hook on
a playable measures at the tempo of the canvas instead.
Examples:
from_samples
classmethod
¶
from_samples(samples: Sequence[float], /, *, sample_rate: int = 44100, symbol: str | None = None) -> Audio
Make audio from samples: numbers from -1.0 to 1.0, one per instant.
Parameters:
-
samples(Sequence[float]) –The samples, in order.
-
sample_rate(int, default:44100) –How many samples there are per second.
-
symbol(str | None, default:None) –A name to register the audio under in
symbols, soplay(name)plays it.
Returns:
Raises:
-
ImportError–xnano-audiois not installed. Install it withpip install "xnano[audio]". -
ValueError–samplesis empty, orsample_rateis not above 0.
Examples:
import math
import xnano
tone = [math.sin(index / 10) for index in range(44100)]
audio = xnano.Audio.from_samples(tone, symbol='tone')
assert audio.duration_milliseconds == 1000.0
Source code in xnano/audio/_audio.py
@classmethod
def from_samples(
cls,
samples: Sequence[float],
/,
*,
sample_rate: int = 44100,
symbol: str | None = None,
) -> Audio:
"""
Make audio from samples: numbers from ``-1.0`` to ``1.0``, one per instant.
Args:
samples: The samples, in order.
sample_rate: How many samples there are per second.
symbol: A name to register the audio under in [`symbols`][xnano.symbols], so
``play(name)`` plays it.
Returns:
The [`Audio`][xnano.Audio].
Raises:
ImportError: ``xnano-audio`` is not installed. Install it with
``pip install "xnano[audio]"``.
ValueError: ``samples`` is empty, or ``sample_rate`` is not above 0.
Examples:
```python
import math
import xnano
tone = [math.sin(index / 10) for index in range(44100)]
audio = xnano.Audio.from_samples(tone, symbol='tone')
assert audio.duration_milliseconds == 1000.0
```
"""
module = require('audio', needed_for='xnano.Audio.from_samples')
values = samples if isinstance(samples, list) else list(samples)
return cls(
module.TerminalSound.from_samples(values, sample_rate=sample_rate),
symbol=symbol,
)
Note
dataclass
¶
Note(pitch: Pitch | tuple[Pitch, ...], *, beats: float = 1.0, instrument: InstrumentName = 'piano', velocity: float = 0.8, effects: tuple[PlayableEffectSpecification, ...] = (), symbol: str | None = None)
A note, or a chord, to play: a pitch, how long it lasts and how it sounds.
A note is a plain value. It needs no sound device, no canvas and not even the audio
extra to be created, so a song can be defined at the top of a module and played later
with play or Speaker.play. A sequence of
notes plays one after another. symbol registers the note under a name, so
play('kick') finds it.
Attributes:
-
pitch(Pitch | tuple[Pitch, ...]) –A note name such as
'C#4', a MIDI number from 0 to 127 (60 is middle C), or a tuple of them for a chord. -
beats(float) –How long the note is held, in beats at the canvas's tempo. A beat is half a second at 120 beats per minute.
-
instrument(InstrumentName) –A built-in instrument, from
instrument_names. -
velocity(float) –How hard the note is played, from 0.0 to 1.0.
-
effects(tuple[PlayableEffectSpecification, ...]) –Sound effects as dictionaries with a
kindkey, such as{'kind': 'audio.reverb', 'mix': 0.4}. -
symbol(str | None) –The name the note is registered under in
symbols, orNone. -
region(Region[float]) –The note on the timeline as a piano roll: a
Regionthat starts at beat 0, lastsbeatsand spans the semitones from the lowest to the highest pitch.
Raises:
-
TypeError–The pitch is not a note name or a number, or an effect is not a dictionary.
-
ValueError–The pitch is not valid,
beatsis not above 0,velocityis not from 0.0 to 1.0, or the instrument is unknown (checked when theaudioextra is installed, and otherwise when the note is played).
Examples:
import xnano
chord = xnano.Note(('C4', 'E4', 'G4'), beats=2.0, instrument='bell')
assert chord.beats == 2.0
assert chord.region.y == 60
assert chord.region.height == 8
assert chord.region.width == 2.0
assert chord.region.sixteenths.width == 8.0
assert chord.region.milliseconds.width == 1000.0
with xnano.new(width=8, height=1) as canvas:
canvas.speaker.play([chord, xnano.Note('C5')])
canvas.clock.step(delta_seconds=1.0)
assert canvas.speaker.render().duration_milliseconds == 1000.0
Methods:
-
__post_init__–Check the values and register the symbol.
-
__hash__–Hash the note by its values, so notes that are equal hash equal.
-
__xnano_play__–Return this note, so a note is playable like any other component.
pitch
instance-attribute
¶
A note name, a MIDI number, or a tuple of them for a chord.
instrument
class-attribute
instance-attribute
¶
instrument: InstrumentName = 'piano'
The built-in instrument.
velocity
class-attribute
instance-attribute
¶
velocity: float = 0.8
How hard the note is played, from 0.0 to 1.0.
effects
class-attribute
instance-attribute
¶
effects: tuple[PlayableEffectSpecification, ...] = ()
The sound effects, as dictionaries with a kind key.
symbol
class-attribute
instance-attribute
¶
symbol: str | None = None
The registered symbol name, or None.
region
property
¶
The note on the timeline as a piano roll, on its own.
The region starts at beat 0 and lasts beats. Its y is the lowest pitch as a
MIDI number and its height the semitones from the lowest to the highest pitch,
so a chord spans several rows and a single note one. Its milliseconds view
assumes 120 beats per minute, the tempo of play when no canvas is
running; context.region of a hook on a playable measures at the tempo of the
canvas instead.
Examples:
__post_init__
¶
Check the values and register the symbol.
Source code in xnano/audio/_notes.py
def __post_init__(self) -> None:
"""Check the values and register the symbol."""
pitch = self.pitch
if isinstance(pitch, (list, tuple)):
if not pitch:
raise ValueError(
'A chord needs at least one pitch, but got an empty one. Pass '
'Note(("C4", "E4", "G4")) for a chord or Note("C4") for one note.'
)
pitch = tuple(pitch)
for each in pitch:
_check_pitch(each)
object.__setattr__(self, 'pitch', pitch)
else:
_check_pitch(pitch)
if (
isinstance(self.beats, bool)
or not isinstance(self.beats, (int, float))
or not math.isfinite(self.beats)
or self.beats <= 0
):
raise ValueError(
f'beats must be a number above 0, but was {self.beats!r}. Use 1.0 for one '
f'beat or 0.5 for half a beat.'
)
if isinstance(self.velocity, bool) or not isinstance(self.velocity, (int, float)):
raise ValueError(
f'velocity must be a number from 0.0 to 1.0, but was {self.velocity!r}. Use '
f'0.8 for an ordinary note.'
)
if not isinstance(self.instrument, str):
raise ValueError(
f'instrument must be the name of a built-in instrument, such as "piano", '
f'but was {self.instrument!r}.'
)
if not 0.0 <= self.velocity <= 1.0:
raise ValueError(
f'velocity must be from 0.0 to 1.0, but was {self.velocity!r}. Use 0.8 for '
f'an ordinary note.'
)
audio = _installed_audio()
if audio is not None:
names = audio.instrument_names()
if self.instrument not in names:
raise ValueError(
f'{self.instrument!r} is not an instrument. Use one of: '
f'{", ".join(names)}.'
)
effects = effect_sequence(self.effects, 'playable')
for effect in effects:
normalize_effect(effect, 'playable')
object.__setattr__(self, 'effects', effects)
if self.symbol is not None:
symbols.register(self.symbol, self)
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:
-
__setattr__–Set an attribute, or raise
AttributeErrorfor an unknown public name. -
hook–Call a function when something happens on this canvas or placement.
-
__new__–Refuse a direct call: a canvas is created with
xnano.new. -
write–Put content on the screen of the canvas, and return the placement that holds it.
-
render–Draw the current frame and return it as text, with no screen.
-
__rich_console__–Show the current frame in rich and Textual, with its colors and styles.
-
__rich_measure__–Tell rich the width of what it shows, so that rich keeps it whole when it can.
-
__contains__–Whether an item is inside the screen of the canvas.
-
open–Put this canvas on your screen, and return it as a
Terminal. -
open_async–Put this canvas on your screen like
open, from a coroutine. -
close–Release everything the canvas holds, and give the screen back if it has one.
-
close_async–Close the canvas like
close, awaiting its loop's end. -
wait_for_tasks_async–Wait until every run of the canvas's
async defhooks has finished. -
__or__–Attach a hook operation, such as one from
xnano.hook(), withcanvas | operation. -
__ior__–Attach a hook operation in place with
canvas |= operation. -
evaluate–Evaluate an expression against the canvas and return its value.
-
iter–Run the canvas one frame at a time: iterate over its frames, drawing between them.
-
iter_async–Run the canvas one frame at a time with
async for, likeiter. -
deliver_events–Deliver pushed events to their hooks and draw a frame, without moving time.
-
stop–Ask the canvas's loop to end.
-
run–Wait until the canvas's loop ends.
-
run_async–Wait until the canvas's loop ends, like
run, withawait. -
push–Deliver an event to the canvas as if it had been typed, clicked or reported.
-
state_reference–A core reference for one field of the canvas's state.
Source code in xnano/canvas.py
def __init__(
self,
*,
width: int | str | None,
height: int | str | None,
fps: float,
bpm: float,
is_realtime: bool,
deps: object,
state: object,
title: str | None,
gates: Mapping[str, object],
appearance: Mapping[str, object],
effects: Sequence[WritableEffectSpecification],
enclosing: Canvas[object, object] | None = None,
layout: CanvasLayout = 'overlay',
edges: EdgeBehavior = 'clip',
) -> None:
"""
Create a canvas. Use [`new`][xnano.new] instead of calling this.
Args:
width: The width in cells, as a percentage of the window, ``'fit'`` for the
width of the content, or ``None`` for 80.
height: The height in cells, as a percentage of the window, ``'fit'`` for the
height of the content, or ``None`` for 24.
fps: The most frames drawn per second.
bpm: Beats per minute.
is_realtime: Whether the canvas runs on the wall clock, on a thread of its own.
deps: The dependencies, or the unset marker when none were given.
state: A dataclass instance the canvas keeps and validates, or the unset marker.
title: The window title, or ``None``.
gates: The terminal settings that were given, by name.
appearance: The appearance keywords of the canvas itself, by name.
effects: Effects to apply to the canvas, as dictionaries with a ``kind`` key.
enclosing: The canvas whose ``with`` block this one was created in, which its
sizes are measured in and which closes it, or ``None``.
layout: How the canvas places what is written on it.
edges: What content written on the canvas does at the edges of its area.
"""
super().__init__()
self._canvas = self
self._root_canvas = self
self._lock = threading.RLock()
self._root = _core.Buffer()
self._buffer = self._root
# 'fit' takes the size of the content; a stacking canvas shares its size among its
# slots, so it cannot fit them.
if layout != 'overlay' and 'fit' in (width, height):
raise ValueError(
f'A {layout} canvas shares its size among the pieces written on it, so it '
f'cannot take the size of them. Give it a size such as height=12, or use '
f"layout='overlay' with width='fit' and height='fit'."
)
self._fits_width = width == 'fit'
self._fits_height = height == 'fit'
# Canvases written into this one that fit their content, and whether a fit runs now.
# The placements of canvases written into this one that fit their content.
self._fitted_placements: list[Placement[object, object]] = []
self._root.should_fit_width = self._fits_width
self._root.should_fit_height = self._fits_height
self._fps = fps
self._bpm = bpm
self._is_realtime = is_realtime
self._requested_width = width
self._requested_height = height
self._deps_given = deps is not _UNSET
self._deps = cast('DepsT', None if deps is _UNSET else deps)
self._state_given = state is not _UNSET
self._title = title
self._gates: dict[str, object] = dict(gates)
self._resolved_gates: dict[str, object] = {}
self._appearance = (
Appearance(**cast('dict[str, object]', _plain_appearance(appearance))) # type: ignore[arg-type]
if appearance
else None
)
self._dirty_looks: dict[int, _LookState] = {}
self._placements: list[Placement[DepsT, StateT]] = []
self._ledger: list[_Registration] = []
self._effects: list[
tuple[EffectParameters, Canvas[object, object] | Placement[object, object]]
] = []
self._frame_listeners: dict[int, Callable[[FrameContext], None]] = {}
self._frame_listener_tokens = itertools.count()
self._children: list[Canvas[object, object]] = []
self._nested_canvases: list[weakref.ref[Canvas[object, object]]] = []
self._areas: dict[int, Placement[object, object]] = {}
self._layout: CanvasLayout = layout
self._edges: EdgeBehavior = edges
self._slots: list[
tuple[Placement[object, object] | None, _core.Buffer, _core.SizeRule]
] = []
self._pending_layouts: dict[int, Canvas[object, object]] = {}
# The flow of every container that something was written into, by its buffer.
self._flows: dict[int, Flow] = {}
if enclosing is not None:
self._enclosing = weakref.ref(enclosing)
self._enclosing_size = (enclosing.screen.width, enclosing.screen.height)
with enclosing._lock:
enclosing._nested_canvases.append(
weakref.ref(cast('Canvas[object, object]', self))
)
self._stop_requested = _AwaitableEvent()
# The event loop that async def hooks run on: the one this canvas was created in.
self._event_loop: asyncio.AbstractEventLoop | None = running_loop()
self._state_fields: dict[str, object] = {}
if state is not _UNSET and state is not None:
self._state_store = _prepare_state(cast('DataclassInstance', state))
self._state_fields = _state_field_types(cast('DataclassInstance', state))
self._state_marked: dict[_StateFollower, _core.TerminalStateChange] = {}
self._internal_revisions: deque[int] = deque(maxlen=16)
self._namespace_identifiers = itertools.count(1)
self._active_run_by_thread = threading.local()
self._images: dict[int, ImageSource] = {}
# Only placements with an expression or a range need looking at before each frame.
self._dynamic: dict[int, Placement[DepsT, StateT]] = {}
# Whether the engine asks for a frame when the pointer moves: only while a placement
# before each frame reads the pointer. Only the canvas's loop changes it.
self._follows_pointer = False
self._clock_view = Clock(cast('Canvas[object, object]', self))
self._output = Output(cast('Canvas[object, object]', self))
# The mouse buttons the program pressed and has not released.
self._program_held_buttons: set[_core.MouseButton] = set()
self._size = _core.Size(0, 0)
self._previous_chain = tuple(
reference for reference in _active_canvas.get() if reference() is not None
)
_active_canvas.set(
(weakref.ref(cast('Canvas[object, object]', self)), *self._previous_chain)
)
self._host: _Host
columns, rows = _canvas_size(
None if self._fits_width else width,
None if self._fits_height else height,
self._enclosing_size,
)
if self._fits_width:
columns = 1
if self._fits_height:
rows = 1
interval_milliseconds = max(1, round(1000.0 / fps))
def create_runtime() -> _core.Runtime:
runtime = _core.Runtime.offscreen(
width=columns,
height=rows,
frame_interval_milliseconds=interval_milliseconds,
clock=_core.Clock.monotonic() if is_realtime else None,
)
if title is not None:
runtime.title = title
return runtime
try:
if is_realtime:
_ThreadHost(cast('Canvas[object, object]', self), create_runtime)
else:
_InlineHost(cast('Canvas[object, object]', self), create_runtime)
except BaseException:
_active_canvas.set(self._previous_chain)
self._finalize()
raise
try:
if effects:
apply_effects(cast('Canvas[object, object]', self), effects)
except BaseException:
self.close(raise_failure=False)
raise
self._writable_effects = WritableEffectProperties(
cast('Canvas[object, object]', self)
)
self._seal()
screen
property
¶
screen: Screen[DepsT, StateT]
The Screen: what is written and drawn on the canvas, and how
it looks.
A canvas written into another one has a screen of its own, its area of the outer canvas.
speaker
property
¶
speaker: Speaker
The Speaker: notes, melodies, sounds and playable components.
It needs the optional xnano-audio package, which is imported the first time it plays.
microphone
property
¶
microphone: Microphone
The Microphone: the level of the sound around, and its
history.
Raises:
-
ImportError–xnano-audiois not installed. Install it withpip install "xnano[audio]".
keyboard
property
¶
keyboard: Keyboard
The Keyboard: the keys held down, and the program's own key
presses, pastes, waits and prompts.
mouse
property
¶
mouse: Mouse
The Mouse: the pointer, the buttons held, the wheel, and the
program's own clicks and drags.
clock
property
¶
clock: Clock
The Clock: how long the canvas has run, stopping, stepping,
sleeping, its frame rate, its tempo and its beats.
fx
property
¶
The visual effects of all of the canvas, one method for each effect.
canvas.fx is the same as canvas.screen.fx. An effect
that starts here changes every cell of the canvas, and canvas.fx.clear() stops
the effects that started here. See
WritableEffectProperties.
Examples:
is_closed
property
¶
is_closed: bool
Whether the canvas has been torn down: closed, or its loop has ended.
is_running
property
¶
is_running: bool
Whether the canvas is open and its loop has not been asked to end.
state
class-attribute
instance-attribute
¶
The canvas's state: values that hooks and your code share, read and written by path.
canvas.state.get('player.score') reads a value and canvas.state.set('player.score',
3) writes one; see StateNamespace for the path rules. A
canvas created with new(state=Settings()) also gives the fields of the dataclass as
attributes with their declared types, so canvas.state.volume is an int for a field
declared volume: int; a write is checked against the field's type. A type checker
sees get and set only on a canvas without a state dataclass, but both exist on
every canvas.
The state can be used from any thread. A write updates every expression that reads the field and draws a frame.
__setattr__
¶
Set an attribute, or raise AttributeError for an unknown public name.
Source code in xnano/_internal/_attributes.py
def __setattr__(self, name: str, value: object) -> None:
"""Set an attribute, or raise ``AttributeError`` for an unknown public name."""
if (
name[:1] != '_'
and self.__dict__.get('_is_sealed')
and not hasattr(type(self), name)
and name not in self.__dict__
):
kind = type(self).__name__
settable = sorted(
key
for key in dir(type(self))
if key[:1] != '_' and _is_settable(type(self), key)
)
close = difflib.get_close_matches(name, settable, n=1)
hint = f' Did you mean {close[0]!r}?' if close else ''
raise AttributeError(
f'{kind} has no attribute called {name!r}, so assigning to it would change '
f'nothing.{hint} The attributes you can assign are: {", ".join(settable)}.'
)
object.__setattr__(self, name, value)
hook
¶
hook(function: Hook[DepsT, StateT], /, *, on: HookTrigger[DepsT, StateT] | None = None, every: float | None = None, after: float | None = None, keys: KeyName | Sequence[KeyName] | None = None, requires_deps: bool = False, if_running: IfRunning = 'replace') -> HookHandle[DepsT, StateT]
hook(function: Hook[DepsT, StateT] | None = None, /, *, on: HookTrigger[DepsT, StateT] | None = None, every: float | None = None, after: float | None = None, keys: KeyName | Sequence[KeyName] | None = None, requires_deps: bool = False, if_running: IfRunning = 'replace') -> HookHandle[DepsT, StateT] | Callable[[Hook[DepsT, StateT]], HookHandle[DepsT, StateT]]
Call a function when something happens on this canvas or placement.
on says when the hook runs: a kind of event such as 'key' or 'tick', the
name of an event pushed with Event.custom(name), or a condition such as
"mouse.kind == 'press'" (see HookTrigger). A hook
without on hears every input event. A mouse,
scroll or drag hook on a placement hears only the pointer inside the placement, and a
press inside holds the pointer for the hook until the button is released. A pointer hook
that matches an event stops it from reaching the parent; a hook that does not match lets
it through. Keys are not consumed: while nothing has focus, every key hook hears a key.
A hook hears only the input the screen reports. A hook added to a canvas that is
already on the screen turns no terminal setting on, so one that needs input the screen
does not report, such as on='mouse' on a canvas opened without mouse=True, is
attached and never runs.
hook(function, ...) attaches one function, and @target.hook(...) decorates the
function that follows. A hook function may be a generator that receives a new context
at each bare yield: write context = yield. A drag is a loop that runs while
context.mouse.is_down.
A hook without on hears every input event. While a mouse button it heard is held,
it also runs on every frame once the button has been held for 0.15 seconds, so a
quick click runs it only for the press and the release. A release names its button
in context.mouse.button; test context.mouse.is_down to leave the release out.
A hook function may also be written with async def. Each time the hook runs, its
coroutine starts on the event loop the canvas was created or opened in, and on
xnano's own background loop when there is none, and the canvas goes on drawing while
it awaits. if_running says what happens when the hook runs again before the
previous run has finished. A canvas with a manual clock (from new()) needs an event
loop of its own for that: create it in a coroutine or use async with on it.
wait_for_tasks_async waits until every
run has finished. A run that raises ends the canvas like a plain hook that raises; a
cancelled run is not a failure.
every and after are seconds for on='tick' and beats for on='beat':
every=2 means 2 seconds for a tick hook and 2 beats for a beat hook. On a canvas
from new() a hook that is due several times in one step runs once for each
interval, up to 100,000 times in one step; the intervals that remain run in the steps
that follow. The function's return value is ignored, unless it is an operation, a
style or an effect, which is applied to this target.
Parameters:
-
function(Hook[DepsT, StateT] | None, default:None) –The function to call with a
Context, or a function with no parameters, which is called without it. -
on(HookTrigger[DepsT, StateT] | None, default:None) –When the hook runs. A kind:
'frame','tick','beat','key','mouse','scroll','drag','paste','focus','resize','state'or'custom'(every custom event); seeHookKind. The name of a custom event, such as'volume_changed'. Or a condition: a string, an expression or a function of the context; seeWhen. A string that reads one input hears only that input ("mouse.kind == 'press'"is a mouse hook, and hears the pointer inside a placement), a string that reads no input is checked on every tick, and a string tells xnano which terminal settings the hook needs, somouseandscrollturn on when the canvas opens. A string that reads key releases needskeyboard='release_events'given tonew()oropen(). An expression or a function hears every input event and does not tell xnano what it reads, so one that readsmouse,scrollor key releases needsmouse=True,scroll=Trueorkeyboard='release_events'given tonew()oropen()yourself. Withevery,afterorkeysa condition is checked on those ticks or keys. A comparison with an input the event does not carry, such askeyboard.keyon a paste, does not hold;!=is one of them, sokeyboard.key != 'q'hears only key events.notandnot innegate the whole comparison, sonot keyboard.key == 'q'andkeyboard.key not in ['q']also hold for events that have no key. -
every(float | None, default:None) –Repeat every this many seconds (
'tick') or beats ('beat'). -
after(float | None, default:None) –Run once after this many seconds (
'tick') or beats ('beat'). -
keys(KeyName | Sequence[KeyName] | None, default:None) –The key or keys an
on='key'hook reacts to, such as'q'or'ctrl+s'. A key hook with keys hears presses and repeats; omit them and testkeyboard.kindto hear releases. -
requires_deps(bool, default:False) –Whether the hook needs the dependencies given to
new(deps=...). -
if_running(IfRunning, default:'replace') –For an
async defhook, what happens when it runs again while its previous run has not finished:'replace'cancels that run (the latest wins),'ignore'drops the new one,'queue'runs them one after the other and'overlap'runs them together. SeeIfRunning.
Returns:
-
HookHandle[DepsT, StateT] | Callable[[Hook[DepsT, StateT]], HookHandle[DepsT, StateT]]–The hook, whose
removestops it; removing it cancels the unfinished runs of -
HookHandle[DepsT, StateT] | Callable[[Hook[DepsT, StateT]], HookHandle[DepsT, StateT]]–an
async defhook. Without a function, the decorator.
Raises:
-
ValueError–The combination of arguments does not make sense, a key name is unknown, a condition string is not a condition,
onis one letter away from a kind, orif_runningis given to a function that is notasync def. The message says what to write instead. -
TypeError–onis a plainboolor not a kind, a name or a condition, or the function is not callable with a context, or is an async generator. -
TerminalError–requires_depsis true and the canvas was created withoutdeps, or anasync defhook has no event loop to run on.
Examples:
import xnano
from xnano_core import Event
with xnano.new(width=8, height=1) as canvas:
heard = []
@canvas.hook(on='key', keys=['q', 'escape'])
def leave(context: xnano.Context) -> None:
heard.append(context.keyboard.key)
@canvas.hook(on='tick', every=0.5)
def blink(context: xnano.Context) -> None:
heard.append('tick')
canvas.push(Event.key_press('q'))
canvas.clock.step(delta_seconds=1.0)
assert heard == ['q', 'tick', 'tick']
Source code in xnano/hooks/_handles.py
def hook(
self,
function: Hook[DepsT, StateT] | None = None,
/,
*,
on: HookTrigger[DepsT, StateT] | None = None,
every: float | None = None,
after: float | None = None,
keys: KeyName | Sequence[KeyName] | None = None,
requires_deps: bool = False,
if_running: IfRunning = 'replace',
) -> (
HookHandle[DepsT, StateT]
| Callable[[Hook[DepsT, StateT]], HookHandle[DepsT, StateT]]
):
"""
Call a function when something happens on this canvas or placement.
``on`` says when the hook runs: a kind of event such as ``'key'`` or ``'tick'``, the
name of an event pushed with ``Event.custom(name)``, or a condition such as
``"mouse.kind == 'press'"`` (see [`HookTrigger`][xnano.hooks.HookTrigger]). A hook
without ``on`` hears every input event. A mouse,
scroll or drag hook on a placement hears only the pointer inside the placement, and a
press inside holds the pointer for the hook until the button is released. A pointer hook
that matches an event stops it from reaching the parent; a hook that does not match lets
it through. Keys are not consumed: while nothing has focus, every key hook hears a key.
A hook hears only the input the screen reports. A hook added to a canvas that is
already on the screen turns no terminal setting on, so one that needs input the screen
does not report, such as ``on='mouse'`` on a canvas opened without ``mouse=True``, is
attached and never runs.
``hook(function, ...)`` attaches one function, and ``@target.hook(...)`` decorates the
function that follows. A hook function may be a generator that receives a new context
at each bare ``yield``: write ``context = yield``. A drag is a loop that runs while
``context.mouse.is_down``.
A hook without ``on`` hears every input event. While a mouse button it heard is held,
it also runs on every frame once the button has been held for 0.15 seconds, so a
quick click runs it only for the press and the release. A release names its button
in ``context.mouse.button``; test ``context.mouse.is_down`` to leave the release out.
A hook function may also be written with ``async def``. Each time the hook runs, its
coroutine starts on the event loop the canvas was created or opened in, and on
xnano's own background loop when there is none, and the canvas goes on drawing while
it awaits. ``if_running`` says what happens when the hook runs again before the
previous run has finished. A canvas with a manual clock (from ``new()``) needs an event
loop of its own for that: create it in a coroutine or use ``async with`` on it.
[`wait_for_tasks_async`][xnano.canvas.Canvas.wait_for_tasks_async] waits until every
run has finished. A run that raises ends the canvas like a plain hook that raises; a
cancelled run is not a failure.
``every`` and ``after`` are seconds for ``on='tick'`` and beats for ``on='beat'``:
``every=2`` means 2 seconds for a tick hook and 2 beats for a beat hook. On a canvas
from ``new()`` a hook that is due several times in one ``step`` runs once for each
interval, up to 100,000 times in one step; the intervals that remain run in the steps
that follow. The function's return value is ignored, unless it is an operation, a
style or an effect, which is applied to this target.
Args:
function: The function to call with a [`Context`][xnano.hooks.Context], or a
function with no parameters, which is called without it.
on: When the hook runs. A kind: ``'frame'``, ``'tick'``, ``'beat'``, ``'key'``,
``'mouse'``, ``'scroll'``, ``'drag'``, ``'paste'``, ``'focus'``, ``'resize'``,
``'state'`` or ``'custom'`` (every custom event); see
[`HookKind`][xnano.hooks.HookKind]. The name of a custom event, such as
``'volume_changed'``. Or a condition: a string, an expression or a function of
the context; see [`When`][xnano.hooks.When]. A string that reads one input
hears only that input (``"mouse.kind == 'press'"`` is a mouse hook, and hears
the pointer inside a placement), a string that reads no input is checked on
every tick, and a string tells xnano which terminal settings the hook needs,
so ``mouse`` and ``scroll`` turn on when the canvas opens. A string that reads
key releases needs ``keyboard='release_events'`` given to ``new()`` or
``open()``. An expression or a function hears every input event and does not
tell xnano what it reads, so one that reads ``mouse``, ``scroll`` or key
releases needs ``mouse=True``, ``scroll=True`` or
``keyboard='release_events'`` given to ``new()`` or ``open()`` yourself. With
``every``, ``after`` or ``keys`` a condition is checked on those ticks or keys.
A comparison with an input the event does not carry, such as ``keyboard.key``
on a paste, does not hold; ``!=`` is one of them, so ``keyboard.key != 'q'``
hears only key events. ``not`` and ``not in`` negate the whole comparison, so
``not keyboard.key == 'q'`` and ``keyboard.key not in ['q']`` also hold for
events that have no key.
every: Repeat every this many seconds (``'tick'``) or beats (``'beat'``).
after: Run once after this many seconds (``'tick'``) or beats (``'beat'``).
keys: The key or keys an ``on='key'`` hook reacts to, such as ``'q'`` or
``'ctrl+s'``. A key hook with keys hears presses and repeats; omit them and
test ``keyboard.kind`` to hear releases.
requires_deps: Whether the hook needs the dependencies given to
``new(deps=...)``.
if_running: For an ``async def`` hook, what happens when it runs again while
its previous run has not finished: ``'replace'`` cancels that run (the
latest wins), ``'ignore'`` drops the new one, ``'queue'`` runs them one after
the other and ``'overlap'`` runs them together. See
[`IfRunning`][xnano.hooks.IfRunning].
Returns:
The hook, whose ``remove`` stops it; removing it cancels the unfinished runs of
an ``async def`` hook. Without a function, the decorator.
Raises:
ValueError: The combination of arguments does not make sense, a key name is
unknown, a condition string is not a condition, ``on`` is one letter away
from a kind, or ``if_running`` is given to a function that is not
``async def``. The message says what to write instead.
TypeError: ``on`` is a plain ``bool`` or not a kind, a name or a condition, or the
function is not callable with a context, or is an async generator.
TerminalError: ``requires_deps`` is true and the canvas was created without
``deps``, or an ``async def`` hook has no event loop to run on.
Examples:
```python
import xnano
from xnano_core import Event
with xnano.new(width=8, height=1) as canvas:
heard = []
@canvas.hook(on='key', keys=['q', 'escape'])
def leave(context: xnano.Context) -> None:
heard.append(context.keyboard.key)
@canvas.hook(on='tick', every=0.5)
def blink(context: xnano.Context) -> None:
heard.append('tick')
canvas.push(Event.key_press('q'))
canvas.clock.step(delta_seconds=1.0)
assert heard == ['q', 'tick', 'tick']
```
"""
canvas = self._canvas
self._require_attached()
owner = cast('_Hooked[object, object]', self)
kind, condition = resolve_trigger(on, every=every, after=after, keys=keys)
normalized_keys = _check_hook_arguments(owner, kind, every, after, keys)
compiled = compile_when(condition)
if requires_deps and not canvas._deps_given:
raise TerminalError(
'This hook needs dependencies (requires_deps=True), but the canvas has none '
'yet. Give them when you create the canvas: xnano.new(deps=your_dependencies) '
'or xnano.open(deps=your_dependencies), or open the canvas with '
'canvas.open(deps=your_dependencies) before you register this hook.'
)
_check_if_running(if_running)
def attach(
callback: Hook[DepsT, StateT],
) -> HookHandle[DepsT, StateT]:
checked = _check_hook_function(callback)
_check_coroutine_hook(owner, checked, kind, if_running)
return self._attach_hook(
cast('Callable[[Context[DepsT, StateT]], object]', checked),
on=kind,
when=compiled,
every=every,
after=after,
keys=normalized_keys,
if_running=if_running,
)
if function is None:
return attach
return attach(function)
__new__
¶
Refuse a direct call: a canvas is created with xnano.new.
Source code in xnano/canvas.py
def __new__(cls, *arguments: object, **keywords: object) -> Self:
"""Refuse a direct call: a canvas is created with ``xnano.new``."""
if arguments or 'is_realtime' not in keywords:
raise TypeError(
f'{cls.__name__} is not created by calling it. Create a canvas with '
f'xnano.new(...), or put one on the screen with xnano.open(...).'
)
return super().__new__(cls)
write
¶
write(content: Content | Canvas[WrittenDepsT, WrittenStateT] | None = None, /, *, x: Axis = 'next', y: Axis = 'next', width: Axis | None = None, height: Axis | None = None, layer: int = 0, lock: bool = False, edges: EdgeBehavior | None = None, effects: Sequence[WritableEffectSpecification] = (), style: Style | None = None, foreground: ColorValue | None = None, background: ColorValue | None = None, bold: bool = False, dim: bool = False, italic: bool = False, underline: bool = False, blink: bool = False, reverse: bool = False, hidden: bool = False, crossed_out: bool = False, title: str | None = None, border: BorderKind | bool | None = None, border_style: Style | None = None, padding: Spacing | None = None, margin: Spacing | None = None) -> Placement[DepsT, StateT]
Put content on the screen of the canvas, and return the placement that holds it.
canvas.write(...) is the same as canvas.screen.write(...). It takes the same
arguments, does the same work and gives the same result. See
Screen.write for how the screen places each kind of
content.
Parameters:
-
content(Content | Canvas[WrittenDepsT, WrittenStateT] | None, default:None) – -
x(Axis, default:'next') –The column of the left edge: a number of cells, a percentage string, a word (
'left','center','right'or'next'), an expression or a range. SeeAxis. -
y(Axis, default:'next') –The row of the top edge, in the same forms (
'top','center','bottom'or'next').'next', the default, is the first row below the content written before. -
width(Axis | None, default:None) –The width, in the same forms.
Noneuses the width of the content. -
height(Axis | None, default:None) –The height, in the same forms.
Noneuses the height of the content. -
layer(int, default:0) –The layer. Content on a higher layer shows over content on a lower layer.
-
lock(bool, default:False) –Whether to keep the position and the size that the content has now when the canvas changes size.
-
edges(EdgeBehavior | None, default:None) –What the content does at the edges of its area:
'clip','stop'or'wrap'.Noneuses theedgesof the screen. -
effects(Sequence[WritableEffectSpecification], default:()) –The effects to start on the placement, as dictionaries with a
kindkey. -
style(Style | None, default:None) –A
Stylefor the text. The arguments below apply over it. -
foreground(ColorValue | None, default:None) –The color of the text.
-
background(ColorValue | None, default:None) –The color behind the text.
-
bold(bool, default:False) –Whether the text is bold.
-
dim(bool, default:False) –Whether the text is dim.
-
italic(bool, default:False) –Whether the text is italic.
-
underline(bool, default:False) –Whether the text has a line below it.
-
blink(bool, default:False) –Whether the text blinks.
-
reverse(bool, default:False) –Whether the foreground color and the background color change places.
-
hidden(bool, default:False) –Whether the text is hidden.
-
crossed_out(bool, default:False) –Whether the text has a line through it.
-
title(str | None, default:None) –The title on the border of a box around the content.
-
border(BorderKind | bool | None, default:None) –The
BorderKindof a box around the content, such as'plain'or'rounded'.Trueis'plain', andFalseis no border. -
border_style(Style | None, default:None) –The style of the border.
-
padding(Spacing | None, default:None) –The space between the border and the content: a number of cells, a share of the size of the content, or a dictionary of sides.
-
margin(Spacing | None, default:None) –The space outside the box, in the same forms.
Returns:
-
Placement[DepsT, StateT]–The
Placementthat holds the content. Use it to move, -
Placement[DepsT, StateT]–resize or remove the content.
Raises:
-
TypeError–The content is a file path, raw bytes, an operation, a style or an effect. Apply those with
canvas.screen.update(...). -
TerminalError–The content is a canvas that you cannot write here.
Examples:
import xnano
with xnano.new(width=12, height=3) as canvas:
greeting = canvas.write('hello', x='center', y='center', bold=True)
assert (greeting.width, greeting.y) == (5, 1)
assert canvas.render().splitlines()[1].strip() == 'hello'
Source code in xnano/canvas.py
@refuse_unknown_keywords
def write(
self,
content: Content | Canvas[WrittenDepsT, WrittenStateT] | None = None,
/,
*,
x: Axis = 'next',
y: Axis = 'next',
width: Axis | None = None,
height: Axis | None = None,
layer: int = 0,
lock: bool = False,
edges: EdgeBehavior | None = None,
effects: Sequence[WritableEffectSpecification] = (),
style: _core.Style | None = None,
foreground: ColorValue | None = None,
background: ColorValue | None = None,
bold: bool = False,
dim: bool = False,
italic: bool = False,
underline: bool = False,
blink: bool = False,
reverse: bool = False,
hidden: bool = False,
crossed_out: bool = False,
title: str | None = None,
border: _core.BorderKind | bool | None = None,
border_style: _core.Style | None = None,
padding: Spacing | None = None,
margin: Spacing | None = None,
) -> Placement[DepsT, StateT]:
"""
Put content on the screen of the canvas, and return the placement that holds it.
``canvas.write(...)`` is the same as ``canvas.screen.write(...)``. It takes the same
arguments, does the same work and gives the same result. See
[`Screen.write`][xnano.devices.Screen.write] for how the screen places each kind of
content.
Args:
content: Text (or a list of lines), a [`Buffer`][xnano_core.Buffer] or widget, a
canvas from ``new()``, an image, or any
[`Writable`][xnano.components.Writable]. ``None`` makes an empty placement.
x: The column of the left edge: a number of cells, a percentage string, a word
(``'left'``, ``'center'``, ``'right'`` or ``'next'``), an expression or a
range. See [`Axis`][xnano.layout.Axis].
y: The row of the top edge, in the same forms (``'top'``, ``'center'``,
``'bottom'`` or ``'next'``). ``'next'``, the default, is the first row below
the content written before.
width: The width, in the same forms. ``None`` uses the width of the content.
height: The height, in the same forms. ``None`` uses the height of the content.
layer: The layer. Content on a higher layer shows over content on a lower layer.
lock: Whether to keep the position and the size that the content has now when
the canvas changes size.
edges: What the content does at the edges of its area: ``'clip'``, ``'stop'`` or
``'wrap'``. ``None`` uses the ``edges`` of the screen.
effects: The effects to start on the placement, as dictionaries with a ``kind``
key.
style: A [`Style`][xnano.styles.Style] for the text. The arguments below apply
over it.
foreground: The color of the text.
background: The color behind the text.
bold: Whether the text is bold.
dim: Whether the text is dim.
italic: Whether the text is italic.
underline: Whether the text has a line below it.
blink: Whether the text blinks.
reverse: Whether the foreground color and the background color change places.
hidden: Whether the text is hidden.
crossed_out: Whether the text has a line through it.
title: The title on the border of a box around the content.
border: The [`BorderKind`][xnano.styles.BorderKind] of a box around the content,
such as ``'plain'`` or ``'rounded'``. ``True`` is ``'plain'``, and ``False``
is no border.
border_style: The style of the border.
padding: The space between the border and the content: a number of cells, a
share of the size of the content, or a dictionary of sides.
margin: The space outside the box, in the same forms.
Returns:
The [`Placement`][xnano.layout.Placement] that holds the content. Use it to move,
resize or remove the content.
Raises:
TypeError: The content is a file path, raw bytes, an operation, a style or an
effect. Apply those with ``canvas.screen.update(...)``.
TerminalError: The content is a canvas that you cannot write here.
Examples:
```python
import xnano
with xnano.new(width=12, height=3) as canvas:
greeting = canvas.write('hello', x='center', y='center', bold=True)
assert (greeting.width, greeting.y) == (5, 1)
assert canvas.render().splitlines()[1].strip() == 'hello'
```
"""
return self.screen.write(
content,
x=x,
y=y,
width=width,
height=height,
layer=layer,
lock=lock,
edges=edges,
effects=effects,
style=style,
foreground=foreground,
background=background,
bold=bold,
dim=dim,
italic=italic,
underline=underline,
blink=blink,
reverse=reverse,
hidden=hidden,
crossed_out=crossed_out,
title=title,
border=border,
border_style=border_style,
padding=padding,
margin=margin,
)
render
¶
Draw the current frame and return it as text, with no screen.
canvas.render(...) is the same as
canvas.screen.render(...).
Parameters:
-
format(Literal['text', 'ansi'], default:'text') –'text'for the characters only.'ansi'for the characters with their colors and styles as escape codes.
Returns:
-
str–The frame, with one line for each row.
Raises:
-
ValueError–formatis not'text'or'ansi'.
Examples:
import xnano
with xnano.new(width=6, height=2) as canvas:
canvas.write('hello', y=1)
assert canvas.render().splitlines() == ['', 'hello']
assert canvas.render(format='ansi') == canvas.screen.render(format='ansi')
Source code in xnano/canvas.py
def render(self, *, format: Literal['text', 'ansi'] = 'text') -> str:
"""
Draw the current frame and return it as text, with no screen.
``canvas.render(...)`` is the same as
[`canvas.screen.render(...)`][xnano.devices.Screen.render].
Args:
format: ``'text'`` for the characters only. ``'ansi'`` for the characters with
their colors and styles as escape codes.
Returns:
The frame, with one line for each row.
Raises:
ValueError: ``format`` is not ``'text'`` or ``'ansi'``.
Examples:
```python
import xnano
with xnano.new(width=6, height=2) as canvas:
canvas.write('hello', y=1)
assert canvas.render().splitlines() == ['', 'hello']
assert canvas.render(format='ansi') == canvas.screen.render(format='ansi')
```
"""
return self.screen.render(format=format)
__rich_console__
¶
Show the current frame in rich and Textual, with its colors and styles.
rich.print(canvas) prints the frame. A canvas can also go into a rich Panel
or Table, or into a Textual Static. If a line is longer than the space that
rich gives it, rich cuts the line, as a terminal does. Rich must be installed.
A closed canvas cannot draw. Textual draws a Static after you make it, so give
Textual a canvas that stays open, such as one from xnano.new() outside a
with block.
Examples:
import io
import xnano
from rich.console import Console
with xnano.new(width=5, height=1) as canvas:
canvas.write('hello')
console = Console(file=io.StringIO(), width=20)
console.print(canvas)
assert console.file.getvalue() == 'hello\n'
Source code in xnano/canvas.py
def __rich_console__(
self, console: RichConsole, options: RichConsoleOptions
) -> RichRenderResult:
r"""
Show the current frame in rich and Textual, with its colors and styles.
``rich.print(canvas)`` prints the frame. A canvas can also go into a rich ``Panel``
or ``Table``, or into a Textual ``Static``. If a line is longer than the space that
rich gives it, rich cuts the line, as a terminal does. Rich must be installed.
A closed canvas cannot draw. Textual draws a ``Static`` after you make it, so give
Textual a canvas that stays open, such as one from ``xnano.new()`` outside a
``with`` block.
Examples:
```python
import io
import xnano
from rich.console import Console
with xnano.new(width=5, height=1) as canvas:
canvas.write('hello')
console = Console(file=io.StringIO(), width=20)
console.print(canvas)
assert console.file.getvalue() == 'hello\n'
```
"""
from rich.text import Text as RichText
yield RichText.from_ansi(
self.render(format='ansi'), no_wrap=True, overflow='crop'
)
__rich_measure__
¶
Tell rich the width of what it shows, so that rich keeps it whole when it can.
A frame of cells cannot wrap, so its smallest and its largest width are the same.
Rich uses this width to lay out panels, columns and nested tables. In a rich
Table, add the column with no_wrap=True, so that rich makes the other
columns narrower before it cuts this one.
Source code in xnano/canvas.py
def __rich_measure__(
self, console: RichConsole, options: RichConsoleOptions
) -> RichMeasurement:
"""
Tell rich the width of what it shows, so that rich keeps it whole when it can.
A frame of cells cannot wrap, so its smallest and its largest width are the same.
Rich uses this width to lay out panels, columns and nested tables. In a rich
``Table``, add the column with ``no_wrap=True``, so that rich makes the other
columns narrower before it cuts this one.
"""
from rich.measure import Measurement as RichMeasurement
width = self.screen.width
return RichMeasurement(width, width)
__contains__
¶
Whether an item is inside the screen of the canvas.
item in canvas is the same as item in canvas.screen.region. See
Region for the items that it accepts.
Parameters:
Examples:
import xnano
with xnano.new(width=4, height=2) as canvas:
assert (3, 1) in canvas
assert (4, 1) not in canvas
Source code in xnano/canvas.py
def __contains__(self, item: object) -> bool:
"""
Whether an item is inside the screen of the canvas.
``item in canvas`` is the same as ``item in canvas.screen.region``. See
[`Region`][xnano.layout.Region] for the items that it accepts.
Args:
item: What to find, such as an ``(x, y)`` pair or a
[`Point`][xnano_core.Point] in screen cells.
Examples:
```python
import xnano
with xnano.new(width=4, height=2) as canvas:
assert (3, 1) in canvas
assert (4, 1) not in canvas
```
"""
return item in self.screen.region
open
¶
open(*, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, **settings: Unpack[OpenSettings]) -> Terminal[DepsT, StateT]
Put this canvas on your screen, and return it as a Terminal.
The same object is returned: after this, isinstance(canvas, xnano.Terminal) is
true. From then on it runs by itself on a thread of its own and on the wall clock, which
continues from the time the canvas had: elapsed time, the frame count, every and
after timers and a stopped clock carry over, and so do the cursor, the title,
everything written and every hook. Effects that were running start again from their
beginning, and keyboard focus and a captured pointer are released.
width and height are the size of the canvas: the ones given here, else the
ones given to new(), draw in a region of that size below the cursor; a canvas
created without a size, or with '100%' for both, fills the whole window. A
percentage such as '50%' is a share of the window when the canvas is opened. Any
other keyword of new() except realtime may be given and applies before the
canvas is shown; a terminal setting given here wins over the one given to new().
title is the window title.
Parameters:
-
title(str | None, default:None) –The window title;
Nonekeeps the canvas's title. -
width(int | Percentage | str | None, default:None) –The width of the region to draw in: cells, or a percentage of the window.
-
height(int | Percentage | str | None, default:None) –The height of the region to draw in: cells, or a percentage of the window.
-
settings(Unpack[OpenSettings], default:{}) –Terminal settings, appearance keywords,
fps,bpm,effects, anddepsandstatefor a canvas that was created without them; seeOpenSettings.
Returns:
-
Terminal[DepsT, StateT]–This canvas, now attached to the screen.
Raises:
-
TerminalAlreadyOpenError–Another canvas is already on the screen.
-
TerminalError–This canvas is already on the screen, was written into another canvas, has a hook that needs a terminal setting given as
False, or there is no terminal to draw on; the canvas stays as it was. -
TypeError–realtimewas given,depsorstatethat the canvas already has, or an effect that is not a visual effect dictionary. -
ValueError–A
widthwas given without aheight, or a value is out of range.
Examples:
with xnano.new(width=40, height=5) as canvas:
canvas.screen.write('hello', border='rounded')
canvas.clock.step()
canvas.open(mouse=True) # now a xnano.Terminal, 40 by 5 below the prompt
canvas.run(stop_on='q')
Source code in xnano/canvas.py
def open(
self,
*,
title: str | None = None,
width: int | Percentage | str | None = None,
height: int | Percentage | str | None = None,
**settings: Unpack[OpenSettings],
) -> Terminal[DepsT, StateT]:
"""
Put this canvas on your screen, and return it as a [`Terminal`][xnano.Terminal].
The same object is returned: after this, ``isinstance(canvas, xnano.Terminal)`` is
true. From then on it runs by itself on a thread of its own and on the wall clock, which
continues from the time the canvas had: elapsed time, the frame count, ``every`` and
``after`` timers and a stopped clock carry over, and so do the cursor, the title,
everything written and every hook. Effects that were running start again from their
beginning, and keyboard focus and a captured pointer are released.
``width`` and ``height`` are the size of the canvas: the ones given here, else the
ones given to ``new()``, draw in a region of that size below the cursor; a canvas
created without a size, or with ``'100%'`` for both, fills the whole window. A
percentage such as ``'50%'`` is a share of the window when the canvas is opened. Any
other keyword of ``new()`` except ``realtime`` may be given and applies before the
canvas is shown; a terminal setting given here wins over the one given to ``new()``.
``title`` is the window title.
Args:
title: The window title; ``None`` keeps the canvas's title.
width: The width of the region to draw in: cells, or a percentage of the window.
height: The height of the region to draw in: cells, or a percentage of the window.
settings: Terminal settings, appearance keywords, ``fps``, ``bpm``, ``effects``,
and ``deps`` and ``state`` for a canvas that was created without them; see
[`OpenSettings`][xnano.terminal.OpenSettings].
Returns:
This canvas, now attached to the screen.
Raises:
TerminalAlreadyOpenError: Another canvas is already on the screen.
TerminalError: This canvas is already on the screen, was written into another
canvas, has a hook that needs a terminal setting given as ``False``, or
there is no terminal to draw on; the canvas stays as it was.
TypeError: ``realtime`` was given, ``deps`` or ``state`` that the canvas already
has, or an effect that is not a visual effect dictionary.
ValueError: A ``width`` was given without a ``height``, or a value is out of
range.
Examples:
```text
with xnano.new(width=40, height=5) as canvas:
canvas.screen.write('hello', border='rounded')
canvas.clock.step()
canvas.open(mouse=True) # now a xnano.Terminal, 40 by 5 below the prompt
canvas.run(stop_on='q')
```
"""
from xnano.terminal import Terminal
from xnano.terminal._screen import attach_screen
attach_screen(self, title=title, width=width, height=height, settings=settings)
assert isinstance(self, Terminal)
return self
open_async
¶
open_async(*, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, **settings: Unpack[OpenSettings]) -> OpeningTerminal[DepsT, StateT]
Put this canvas on your screen like open, from a coroutine.
The terminal is asked what it can do while your event loop goes on running other
tasks. Await the result for the Terminal, or enter it with
async with, which closes it when the block ends. The keywords are the ones
open() takes, and so are the errors, which are raised when it is awaited.
Parameters:
-
title(str | None, default:None) –The window title;
Nonekeeps the canvas's title. -
width(int | Percentage | str | None, default:None) –The width of the region to draw in: cells, or a percentage of the window.
-
height(int | Percentage | str | None, default:None) –The height of the region to draw in: cells, or a percentage of the window.
-
settings(Unpack[OpenSettings], default:{}) –Terminal settings, appearance keywords,
fps,bpm,effects, anddepsandstatefor a canvas that was created without them; seeOpenSettings.
Returns:
-
OpeningTerminal[DepsT, StateT]–The opening terminal: await it, or use it in
async with.
Examples:
async def main() -> None:
async with xnano.new(width=40, height=5) as canvas:
canvas.screen.write('hello', border='rounded')
terminal = await canvas.open_async(mouse=True)
await terminal.run_async(stop_on='q')
Source code in xnano/canvas.py
def open_async(
self,
*,
title: str | None = None,
width: int | Percentage | str | None = None,
height: int | Percentage | str | None = None,
**settings: Unpack[OpenSettings],
) -> OpeningTerminal[DepsT, StateT]:
"""
Put this canvas on your screen like [`open`][xnano.canvas.Canvas.open], from a coroutine.
The terminal is asked what it can do while your event loop goes on running other
tasks. Await the result for the [`Terminal`][xnano.Terminal], or enter it with
``async with``, which closes it when the block ends. The keywords are the ones
``open()`` takes, and so are the errors, which are raised when it is awaited.
Args:
title: The window title; ``None`` keeps the canvas's title.
width: The width of the region to draw in: cells, or a percentage of the window.
height: The height of the region to draw in: cells, or a percentage of the window.
settings: Terminal settings, appearance keywords, ``fps``, ``bpm``, ``effects``,
and ``deps`` and ``state`` for a canvas that was created without them; see
[`OpenSettings`][xnano.terminal.OpenSettings].
Returns:
The opening terminal: await it, or use it in ``async with``.
Examples:
```text
async def main() -> None:
async with xnano.new(width=40, height=5) as canvas:
canvas.screen.write('hello', border='rounded')
terminal = await canvas.open_async(mouse=True)
await terminal.run_async(stop_on='q')
```
"""
from xnano.terminal import Terminal
from xnano.terminal._opening import OpeningTerminal
from xnano.terminal._screen import attach_screen_async
async def open_terminal() -> Terminal[DepsT, StateT]:
await attach_screen_async(
self, title=title, width=width, height=height, settings=settings
)
assert isinstance(self, Terminal)
# async def hooks run on the loop the terminal was opened in.
self._event_loop = running_loop()
return self
return OpeningTerminal(open_terminal)
close
¶
close(*, raise_failure: bool = True) -> None
Release everything the canvas holds, and give the screen back if it has one.
Closing twice is harmless. Leaving a with block closes the canvas, unless it is
part of another canvas or was created inside another canvas's with block: then it
stays usable and closes with that canvas. Closing a canvas closes the canvases created
inside its block that were not written anywhere. Closing a canvas that was written into
another one takes it off and leaves that one running.
Parameters:
-
raise_failure(bool, default:True) –Whether to raise the error a callback raised on the loop, which stopped the canvas. A
withblock passesFalsewhile another error is already propagating.
Raises:
-
TerminalError–A callback raised on the canvas's loop, or the loop would not stop.
Source code in xnano/canvas.py
def close(self, *, raise_failure: bool = True) -> None:
"""
Release everything the canvas holds, and give the screen back if it has one.
Closing twice is harmless. Leaving a ``with`` block closes the canvas, unless it is
part of another canvas or was created inside another canvas's ``with`` block: then it
stays usable and closes with that canvas. Closing a canvas closes the canvases created
inside its block that were not written anywhere. Closing a canvas that was written into
another one takes it off and leaves that one running.
Args:
raise_failure: Whether to raise the error a callback raised on the loop, which
stopped the canvas. A ``with`` block passes ``False`` while another error is
already propagating.
Raises:
TerminalError: A callback raised on the canvas's loop, or the loop would not stop.
"""
self._close_nested_canvases()
if self._canvas is not self:
if not self._is_closed:
self._is_closed = True
root = self._canvas
closing: list[Canvas[object, object]] = [
cast('Canvas[object, object]', self)
]
with root._lock:
# A canvas written into this one is part of it, so it ends with it.
closing.extend(
inner
for inner in list(root._children)
if inner is not self
and inner._is_inside(cast('Canvas[object, object]', self))
)
for canvas in closing:
canvas._is_closed = True
if canvas in root._children:
root._children.remove(canvas)
placement = self._parent_placement
if placement is not None and not root.is_closed:
for canvas in closing:
root._host.post(canvas._cancel_hooks)
placement.remove()
if _current_canvas() is self:
_active_canvas.set(self._previous_chain)
return
if not self._stop_requested.is_set() or not self._is_finalized:
host = getattr(self, '_host', None)
if host is not None:
host.require_closable()
self._stop_requested.set()
try:
if host is not None:
host.shutdown()
finally:
self._finalize()
if _current_canvas() is self:
_active_canvas.set(self._previous_chain)
failure = self._failure
if failure is not None and raise_failure and not self._is_failure_reported:
self._failure = None
raise TerminalError(
self._failure_text(failure), code='canvas.callback'
) from failure
close_async
async
¶
close_async(*, raise_failure: bool = True) -> None
Close the canvas like close, awaiting its loop's end.
A canvas that runs by itself (on the screen, or realtime=True) stops its loop while
your event loop goes on running other tasks; a canvas with a manual clock closes at
once. Leaving an async with block calls this.
Parameters:
-
raise_failure(bool, default:True) –Whether to raise the error a callback raised on the loop, which stopped the canvas. An
async withblock passesFalsewhile another error is already propagating.
Raises:
-
TerminalError–A callback raised on the canvas's loop, or the loop would not stop.
Examples:
import asyncio
import xnano
async def main() -> None:
canvas = xnano.new(realtime=True, width=8, height=1)
canvas.screen.write('hello')
await canvas.close_async()
assert canvas.is_closed
asyncio.run(main())
Source code in xnano/canvas.py
async def close_async(self, *, raise_failure: bool = True) -> None:
"""
Close the canvas like [`close`][xnano.canvas.Canvas.close], awaiting its loop's end.
A canvas that runs by itself (on the screen, or ``realtime=True``) stops its loop while
your event loop goes on running other tasks; a canvas with a manual clock closes at
once. Leaving an ``async with`` block calls this.
Args:
raise_failure: Whether to raise the error a callback raised on the loop, which
stopped the canvas. An ``async with`` block passes ``False`` while another
error is already propagating.
Raises:
TerminalError: A callback raised on the canvas's loop, or the loop would not stop.
Examples:
```python
import asyncio
import xnano
async def main() -> None:
canvas = xnano.new(realtime=True, width=8, height=1)
canvas.screen.write('hello')
await canvas.close_async()
assert canvas.is_closed
asyncio.run(main())
```
"""
host = getattr(self, '_host', None)
if self._canvas is self and not self._is_closed and isinstance(host, _ThreadHost):
await host.stop_async()
self.close(raise_failure=raise_failure)
wait_for_tasks_async
async
¶
Wait until every run of the canvas's async def hooks has finished.
Runs that start while this waits are waited for too. Use it in an async program before reading what the hooks changed, and in tests instead of sleeping.
Raises:
-
TerminalError–A run raised, which ends the canvas the way a failing plain hook does.
Examples:
import asyncio
import xnano
from xnano.events import Event
async def main() -> None:
async with xnano.new(width=20, height=1) as canvas:
label = canvas.screen.write('...')
@canvas.hook(on='key', keys='enter')
async def answer(context: xnano.Context) -> None:
await asyncio.sleep(0.01)
label.text = 'done'
canvas.push(Event.key_press('enter'))
canvas.clock.step()
await canvas.wait_for_tasks_async()
assert canvas.screen.render() == 'done'
asyncio.run(main())
Source code in xnano/canvas.py
async def wait_for_tasks_async(self) -> None:
"""
Wait until every run of the canvas's ``async def`` hooks has finished.
Runs that start while this waits are waited for too. Use it in an async program
before reading what the hooks changed, and in tests instead of sleeping.
Raises:
TerminalError: A run raised, which ends the canvas the way a failing plain hook
does.
Examples:
```python
import asyncio
import xnano
from xnano.events import Event
async def main() -> None:
async with xnano.new(width=20, height=1) as canvas:
label = canvas.screen.write('...')
@canvas.hook(on='key', keys='enter')
async def answer(context: xnano.Context) -> None:
await asyncio.sleep(0.01)
label.text = 'done'
canvas.push(Event.key_press('enter'))
canvas.clock.step()
await canvas.wait_for_tasks_async()
assert canvas.screen.render() == 'done'
asyncio.run(main())
```
"""
canvas = self._canvas
tasks = canvas._tasks
if tasks is not None:
await tasks.idle.wait_async()
if canvas._host.is_autonomous:
canvas._raise_run_failure()
else:
canvas._raise_failure()
__or__
¶
__or__(other: ContextualOperation[DepsT, StateT]) -> Self
Attach a hook operation, such as one from xnano.hook(), with canvas | operation.
Raises:
-
TypeError–otherdraws instead of listening: draw it on the screen, withcanvas.screen | operation.
Source code in xnano/canvas.py
def __or__(self, other: ContextualOperation[DepsT, StateT]) -> Self:
"""
Attach a hook operation, such as one from ``xnano.hook()``, with ``canvas | operation``.
Raises:
TypeError: ``other`` draws instead of listening: draw it on the screen, with
``canvas.screen | operation``.
"""
if not isinstance(other, ContextualOperation):
raise TypeError(
f'canvas | ... attaches hooks, such as canvas | xnano.hook(...), but '
f'{type(other).__name__} draws on the cells. Draw it on the screen: '
f'canvas.screen | operation.'
)
cast('ContextualOperation[DepsT, StateT]', other).apply_to(self)
return self
__ior__
¶
__ior__(other: ContextualOperation[DepsT, StateT]) -> Self
evaluate
¶
evaluate(expression: Expression[ValueT]) -> ValueT
Evaluate an expression against the canvas and return its value.
Parameters:
-
expression(Expression[ValueT]) –Any expression, such as
Width,TimeElapsed % 1orcanvas.microphone.level.
Examples:
import xnano
from xnano_core import Width
with xnano.new(width=12, height=2) as canvas:
assert canvas.evaluate(Width) == 12
Source code in xnano/canvas.py
def evaluate(self, expression: _core.Expression[ValueT]) -> ValueT:
"""
Evaluate an expression against the canvas and return its value.
Args:
expression: Any expression, such as ``Width``, ``TimeElapsed % 1`` or
``canvas.microphone.level``.
Examples:
```python
import xnano
from xnano_core import Width
with xnano.new(width=12, height=2) as canvas:
assert canvas.evaluate(Width) == 12
```
"""
self._require_open()
return self._canvas._host.call(lambda: self._root.inspect(expression))
iter
¶
iter(*, frames: int | None = None, seconds: float | None = None, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c') -> Iterator[Frame]
Run the canvas one frame at a time: iterate over its frames, drawing between them.
Each iteration yields a Frame with the events that reached
the canvas since the previous one in frame.events, and whatever you change before
asking for the next frame is drawn. On a canvas from new() each iteration moves
the clock by one frame of its fps, so the same loop produces the same frames every
run, as fast as your code; a canvas that runs by itself (on the screen, or
realtime=True) draws as you declare, so there this paces your code at its fps:
if you are slow, frames are skipped rather than queued.
Without frames or seconds it runs the way run
does: until a key of stop_on is pressed, the canvas is asked to
stop or closes, or you break out of the loop. With
them, it also ends after that many frames, or when the canvas's time has run that
long, whichever comes first. pause freezes the time it
follows: the iterations go on drawing and hooks still run, but the clock stands still
until resume.
Parameters:
-
frames(int | None, default:None) –The most frames to yield.
-
seconds(float | None, default:None) –The most seconds of the canvas's time to run for.
-
stop_on(KeyName | Sequence[KeyName] | None, default:'ctrl+c') –The key, or keys, that end the loop and stop the canvas, such as
'q';Nonefor none.
Raises:
-
TerminalError–secondswithoutframeson a stopped canvas, which would never reach the end. -
TerminalClosedError–The canvas is closed.
Examples:
import xnano
from xnano.events import Event
with xnano.new(width=8, height=1, fps=10) as canvas:
pressed = []
for frame in canvas.iter(frames=3):
pressed.extend(event.key.key for event in frame.events)
if frame.index == 0:
canvas.push(Event.key_press('a'))
assert [frame.index for frame in canvas.iter(frames=2)] == [3, 4]
assert pressed == ['a']
Source code in xnano/canvas.py
def iter(
self,
*,
frames: int | None = None,
seconds: float | None = None,
stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c',
) -> Iterator[Frame]:
"""
Run the canvas one frame at a time: iterate over its frames, drawing between them.
Each iteration yields a [`Frame`][xnano.hooks.Frame] with the events that reached
the canvas since the previous one in ``frame.events``, and whatever you change before
asking for the next frame is drawn. On a canvas from ``new()`` each iteration moves
the clock by one frame of its ``fps``, so the same loop produces the same frames every
run, as fast as your code; a canvas that runs by itself (on the screen, or
``realtime=True``) draws as you declare, so there this paces your code at its ``fps``:
if you are slow, frames are skipped rather than queued.
Without ``frames`` or ``seconds`` it runs the way [`run`][xnano.canvas.Canvas.run]
does: until a key of ``stop_on`` is pressed, the canvas is asked to
[`stop`][xnano.canvas.Canvas.stop] or closes, or you break out of the loop. With
them, it also ends after that many frames, or when the canvas's time has run that
long, whichever comes first. [`pause`][xnano.devices.Clock.pause] freezes the time it
follows: the iterations go on drawing and hooks still run, but the clock stands still
until [`resume`][xnano.devices.Clock.resume].
Args:
frames: The most frames to yield.
seconds: The most seconds of the canvas's time to run for.
stop_on: The key, or keys, that end the loop and stop the canvas, such as
``'q'``; ``None`` for none.
Raises:
TerminalError: ``seconds`` without ``frames`` on a stopped canvas, which would
never reach the end.
TerminalClosedError: The canvas is closed.
Examples:
```python
import xnano
from xnano.events import Event
with xnano.new(width=8, height=1, fps=10) as canvas:
pressed = []
for frame in canvas.iter(frames=3):
pressed.extend(event.key.key for event in frame.events)
if frame.index == 0:
canvas.push(Event.key_press('a'))
assert [frame.index for frame in canvas.iter(frames=2)] == [3, 4]
assert pressed == ['a']
```
"""
canvas = self._check_iteration(frames, seconds)
return canvas._frames(frames, seconds, _parse_stop_keys(stop_on))
iter_async
¶
iter_async(*, frames: int | None = None, seconds: float | None = None, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c') -> AsyncIterator[Frame]
Run the canvas one frame at a time with async for, like iter.
The frames, the keywords and the ways the iteration ends are the ones iter()
has. Between frames, a canvas that runs by itself waits for the next one with
await, so the rest of your event loop runs meanwhile; a canvas from new()
moves its clock at once and lets other tasks run before the next frame.
Parameters:
-
frames(int | None, default:None) –The most frames to yield.
-
seconds(float | None, default:None) –The most seconds of the canvas's time to run for.
-
stop_on(KeyName | Sequence[KeyName] | None, default:'ctrl+c') –The key, or keys, that end the loop and stop the canvas;
Nonefor none.
Raises:
-
TerminalError–secondswithoutframeson a stopped canvas, which would never reach the end. -
TerminalClosedError–The canvas is closed.
Examples:
import asyncio
import xnano
async def main() -> None:
async with xnano.new(width=8, height=1, fps=10) as canvas:
frames = [frame async for frame in canvas.iter_async(frames=3)]
assert [frame.elapsed_seconds for frame in frames] == [0.0, 0.1, 0.2]
asyncio.run(main())
Source code in xnano/canvas.py
def iter_async(
self,
*,
frames: int | None = None,
seconds: float | None = None,
stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c',
) -> AsyncIterator[Frame]:
"""
Run the canvas one frame at a time with ``async for``, like [`iter`][xnano.canvas.Canvas.iter].
The frames, the keywords and the ways the iteration ends are the ones ``iter()``
has. Between frames, a canvas that runs by itself waits for the next one with
``await``, so the rest of your event loop runs meanwhile; a canvas from ``new()``
moves its clock at once and lets other tasks run before the next frame.
Args:
frames: The most frames to yield.
seconds: The most seconds of the canvas's time to run for.
stop_on: The key, or keys, that end the loop and stop the canvas; ``None`` for
none.
Raises:
TerminalError: ``seconds`` without ``frames`` on a stopped canvas, which would
never reach the end.
TerminalClosedError: The canvas is closed.
Examples:
```python
import asyncio
import xnano
async def main() -> None:
async with xnano.new(width=8, height=1, fps=10) as canvas:
frames = [frame async for frame in canvas.iter_async(frames=3)]
assert [frame.elapsed_seconds for frame in frames] == [0.0, 0.1, 0.2]
asyncio.run(main())
```
"""
canvas = self._check_iteration(frames, seconds)
return canvas._frames_async(frames, seconds, _parse_stop_keys(stop_on))
deliver_events
¶
Deliver pushed events to their hooks and draw a frame, without moving time.
Events pushed with push reach their hooks at the
canvas's next step; this is that step on a canvas whose clock you move. A canvas that
runs by itself delivers them on its own.
Examples:
import xnano
from xnano_core import Event
with xnano.new(width=8, height=1) as canvas:
heard = []
canvas.hook(lambda context: heard.append(context.event.kind))
canvas.push(Event.custom('ping'))
canvas.deliver_events()
assert heard == ['custom']
assert canvas.clock.elapsed_seconds == 0.0
Source code in xnano/canvas.py
def deliver_events(self) -> None:
"""
Deliver pushed events to their hooks and draw a frame, without moving time.
Events pushed with [`push`][xnano.canvas.Canvas.push] reach their hooks at the
canvas's next step; this is that step on a canvas whose clock you move. A canvas that
runs by itself delivers them on its own.
Examples:
```python
import xnano
from xnano_core import Event
with xnano.new(width=8, height=1) as canvas:
heard = []
canvas.hook(lambda context: heard.append(context.event.kind))
canvas.push(Event.custom('ping'))
canvas.deliver_events()
assert heard == ['custom']
assert canvas.clock.elapsed_seconds == 0.0
```
"""
self._require_own_presence()
canvas = self._canvas
canvas._require_open()
if canvas._host.is_autonomous:
canvas._host.call(lambda: canvas._runtime.request_frame())
return
canvas._raise_failure()
canvas._runtime.step()
canvas._pushed_pointer = None
canvas._raise_failure()
stop
¶
Ask the canvas's loop to end.
Safe from any thread, including from a hook. A running iter(), run(),
keyboard.wait() or keyboard.prompt() ends. On a canvas from new() the canvas stays
open for writing and rendering; on a canvas that runs by itself (realtime=True, or
on the screen) the loop ends and the canvas closes.
Source code in xnano/canvas.py
def stop(self) -> None:
"""
Ask the canvas's loop to end.
Safe from any thread, including from a hook. A running ``iter()``, ``run()``,
``keyboard.wait()`` or ``keyboard.prompt()`` ends. On a canvas from ``new()`` the canvas stays
open for writing and rendering; on a canvas that runs by itself (``realtime=True``, or
on the screen) the loop ends and the canvas closes.
"""
self._require_own_presence()
canvas = self._canvas
canvas._stop_requested.set()
if not canvas._is_closed and canvas._host.is_autonomous:
canvas._host.post(lambda: canvas._stop_runtime())
run
¶
Wait until the canvas's loop ends.
A canvas that runs by itself draws and listens on its own, so this only keeps your
program alive until a stop key is pressed, or something calls
stop (a hook, another thread). Declare what you want
before calling it.
Parameters:
-
stop_on(KeyName | Sequence[KeyName] | None, default:'ctrl+c') –The key, or keys, that end the loop, such as
'q'or('q', 'escape').'ctrl+c'by default; giveNoneto leave ending to your own code.
Raises:
-
TerminalError–A callback raised on the canvas's loop, or the canvas has a clock that only moves when you move it, so waiting would never end.
Source code in xnano/canvas.py
def run(self, *, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c') -> None:
"""
Wait until the canvas's loop ends.
A canvas that runs by itself draws and listens on its own, so this only keeps your
program alive until a stop key is pressed, or something calls
[`stop`][xnano.canvas.Canvas.stop] (a hook, another thread). Declare what you want
before calling it.
Args:
stop_on: The key, or keys, that end the loop, such as ``'q'`` or
``('q', 'escape')``. ``'ctrl+c'`` by default; give ``None`` to leave ending
to your own code.
Raises:
TerminalError: A callback raised on the canvas's loop, or the canvas has a clock
that only moves when you move it, so waiting would never end.
"""
canvas = self._canvas
host = canvas._prepare_run(stop_on, 'run()')
try:
while not host.wait(0.1):
pass
except KeyboardInterrupt:
canvas.stop()
raise
canvas._raise_run_failure()
run_async
async
¶
Wait until the canvas's loop ends, like run, with await.
Your event loop goes on running other tasks meanwhile. Cancelling the waiting task
asks the canvas to stop.
Parameters:
-
stop_on(KeyName | Sequence[KeyName] | None, default:'ctrl+c') –The key, or keys, that end the loop, such as
'q'or('q', 'escape').'ctrl+c'by default; giveNoneto leave ending to your own code.
Raises:
-
TerminalError–A callback raised on the canvas's loop, or the canvas has a clock that only moves when you move it, so waiting would never end.
Examples:
import asyncio
import xnano
async def main() -> None:
async with xnano.new(realtime=True, width=20, height=1) as canvas:
canvas.screen.write('working...')
@canvas.hook(on='tick', after=0.05)
def finish(context: xnano.Context) -> None:
context.canvas.stop()
await canvas.run_async()
asyncio.run(main())
Source code in xnano/canvas.py
async def run_async(
self, *, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c'
) -> None:
"""
Wait until the canvas's loop ends, like [`run`][xnano.canvas.Canvas.run], with ``await``.
Your event loop goes on running other tasks meanwhile. Cancelling the waiting task
asks the canvas to [`stop`][xnano.canvas.Canvas.stop].
Args:
stop_on: The key, or keys, that end the loop, such as ``'q'`` or
``('q', 'escape')``. ``'ctrl+c'`` by default; give ``None`` to leave ending
to your own code.
Raises:
TerminalError: A callback raised on the canvas's loop, or the canvas has a clock
that only moves when you move it, so waiting would never end.
Examples:
```python
import asyncio
import xnano
async def main() -> None:
async with xnano.new(realtime=True, width=20, height=1) as canvas:
canvas.screen.write('working...')
@canvas.hook(on='tick', after=0.05)
def finish(context: xnano.Context) -> None:
context.canvas.stop()
await canvas.run_async()
asyncio.run(main())
```
"""
import asyncio
canvas = self._canvas
host = canvas._prepare_run(stop_on, 'run_async()')
try:
await host.wait_async()
except asyncio.CancelledError:
canvas.stop()
raise
canvas._raise_run_failure()
push
¶
push(event: Event) -> None
Deliver an event to the canvas as if it had been typed, clicked or reported.
Hooks hear it the same way as input from the keyboard and mouse, at the canvas's
next step, whatever the terminal settings say. Build events with
Event; Event.custom(name, data=...) makes one of your own.
Parameters:
-
event(Event) –The event to deliver.
Raises:
Examples:
import xnano
from xnano_core import Event
with xnano.new(width=8, height=1) as canvas:
heard = []
canvas.hook(
lambda context: heard.append(context.event.custom_name),
on='volume_changed',
)
canvas.push(Event.custom('volume_changed'))
canvas.deliver_events()
assert heard == ['volume_changed']
Source code in xnano/canvas.py
def push(self, event: _core.Event) -> None:
"""
Deliver an event to the canvas as if it had been typed, clicked or reported.
Hooks hear it the same way as input from the keyboard and mouse, at the canvas's
next step, whatever the terminal settings say. Build events with
[`Event`][xnano_core.Event]; ``Event.custom(name, data=...)`` makes one of your own.
Args:
event: The event to deliver.
Raises:
TypeError: The value is not an [`Event`][xnano_core.Event].
Examples:
```python
import xnano
from xnano_core import Event
with xnano.new(width=8, height=1) as canvas:
heard = []
canvas.hook(
lambda context: heard.append(context.event.custom_name),
on='volume_changed',
)
canvas.push(Event.custom('volume_changed'))
canvas.deliver_events()
assert heard == ['volume_changed']
```
"""
if not isinstance(event, _core.Event):
raise TypeError(
f'push() takes an Event such as xnano_core.Event.custom("ping"), but got '
f'{event!r}. To press a key, push xnano_core.Event.key_press("q"), or call '
f'context.keyboard.press("q") inside a hook.'
)
self._require_own_presence()
canvas = self._canvas
canvas._require_open()
canvas._host.post(lambda: canvas._runtime.inject(event))
state_reference
¶
state_reference(reader: Callable[[StateT], ValueT]) -> StateReference[ValueT]
A core reference for one field of the canvas's state.
The reference can be used as an axis, a range bound or a widget parameter.
Parameters:
-
reader(Callable[[StateT], ValueT]) –A function or lambda that reads the field, such as
lambda state: state.volume.
Raises:
-
TypeError–readeris not a function. -
TerminalError–The canvas was created without
state.
Source code in xnano/canvas.py
def state_reference(
self, reader: Callable[[StateT], ValueT]
) -> _core.StateReference[ValueT]:
"""
A core reference for one field of the canvas's state.
The reference can be used as an axis, a range bound or a widget parameter.
Args:
reader: A function or lambda that reads the field, such as
``lambda state: state.volume``.
Raises:
TypeError: ``reader`` is not a function.
TerminalError: The canvas was created without ``state``.
"""
if not callable(reader):
raise TypeError(
f'state_reference() takes a function that reads one field, but got '
f'{reader!r}. Pass a function such as lambda state: state.volume.'
)
store = self._canvas._state_store
if store is None:
raise TerminalError(
'This canvas has no state, so state_reference() has nothing to read. Create it with '
'xnano.new(state=YourDataclass()).'
)
return _reference_for(store, reader)
Context
¶
Context(canvas: Canvas[DepsT_co, StateT_co], owner: Canvas[object, object] | Placement[object, object], hook: HookHandle[object, object], event: Event | TerminalStateChange | Frame | Tick | None, core: CoreContext | None, log: ReadLog | None = None, timeline: Callable[[], Region[float]] | None = None, screen: Screen[object, object] | None = None)
Bases: Generic[DepsT_co, StateT_co]
What a hook is called with.
The context carries the event and live views of where the hook is attached. Its members are
read when you use them, so a context costs almost nothing to receive. A generator hook
receives a new context each time it resumes, so context.mouse.position is always the
newest event's.
target, parent and root are live objects with concrete values. target is
what the hook is attached to, a placement or the canvas, with its hook, state and
fx. parent is where the target is drawn: the placement it is nested in, or the
canvas's screen. Either one has the same members, so context.parent.width is an int
and context.parent.local(context.mouse.position) turns a pointer into its cells at any
depth. The expressions of the same names, such as parent.width, are in
xnano.expressions.
The context has the canvas's devices: screen, speaker, microphone,
keyboard, mouse and clock. Its keyboard and mouse read the event being
handled: each reading is None (or 0 for the wheel) unless the event is of that
kind, and both can press keys and buttons for the program.
Attributes:
-
canvas(Canvas[DepsT_co, StateT_co]) –The root canvas the hook belongs to.
-
event(Event | TerminalStateChange | Frame | Tick | None) –The event, a
Frameforhook(on='frame'), anTickforhook(on='tick'), aTerminalStateChangeforhook(on='state'), orNonewhen no event caused the call. -
hook(HookHandle[object, object]) –The registration, so the hook can call
hook.remove(). -
screen(Screen[DepsT_co, StateT_co]) –The canvas's
Screen; for arenderable, its own screen. -
speaker(Speaker) –The canvas's
Speaker. -
microphone(Microphone) –The canvas's
Microphone. -
keyboard(Keyboard) –The
Keyboard, with the key of the event:key,kind,modifiers, andpastedfor a paste. -
mouse(Mouse) –The
Mouse, with the pointer event:position,buttonandkind, and the wheel steps inscroll. -
clock(Clock) –The canvas's
Clock. -
buffer(Clock) –The placement (or the canvas) the hook is attached to.
-
parent(Placement[object, object] | Screen[object, object]) –Where the buffer is drawn: the placement it is nested in, or the
Screenof the canvas. -
root(Canvas[DepsT_co, StateT_co]) –The root canvas.
-
plugin(Plugin) –The attachment of the hook that is running.
-
deps(DepsT_co) –The dependencies given to
new(deps=...). -
fx(EffectController) –Applies effects to the hook's target while the hook is active.
-
region(Region[float]) –The
Regionof the hook's target: its cells on the screen, or for a hook on a playable the beats and semitones of what it plays. -
size(Size) –The size in cells of
context.targeton the screen, the shortcut forcontext.region.size.
Examples:
import xnano
from xnano_core import Event
with xnano.new(width=20, height=3) as canvas:
label = canvas.screen.write('hi', x=2)
heard = []
@label.hook(on="mouse.kind == 'press'")
def pressed(context: xnano.Context) -> None:
heard.append((context.mouse.position.x, context.target.x))
canvas.push(Event.mouse_event(column=3, row=0, kind='press', button='left'))
canvas.deliver_events()
assert heard == [(3, 2)]
Create a context. The runtime does this for you; hooks receive one.
Parameters:
-
canvas(Canvas[DepsT_co, StateT_co]) –The root canvas.
-
owner(Canvas[object, object] | Placement[object, object]) –The canvas or placement the hook is attached to.
-
hook(HookHandle[object, object]) –The hook that is called.
-
event(Event | TerminalStateChange | Frame | Tick | None) –The event, or
None. -
core(CoreContext | None) –The runtime's context for the event, or
None. -
log(ReadLog | None, default:None) –Where to record what is read, for a component;
Nonefor a hook. -
timeline(Callable[[], Region[float]] | None, default:None) –Returns the region on the timeline of what a playable is playing, for a context of a playable;
Nonefor any other, whoseregionis on the screen. -
screen(Screen[object, object] | None, default:None) –The screen of a renderable, its own;
Nonefor the canvas's.
- API Reference xnano
- Learn Hooks & Input
-
API Reference
xnano
-
xnano -
xnano.ai
ai -
xnano.ai.models.art
artAnimation__xnano_write__ -
xnano.ai.models.components
componentsComponent__xnano_write__ -
xnano.art
art -
xnano.audio
audioNote__xnano_play__ -
xnano.components
components-
PlayableComponent__xnano_play__ -
PlayableFunction__xnano_play__ -
RenderableComponent__xnano_render__ -
RenderableFunction__xnano_render__ -
SupportsPlay__xnano_play__ -
SupportsRender__xnano_render__ -
SupportsWrite__xnano_write__ -
WritableComponent__xnano_write__ -
WritableFunction__xnano_write__ -
playable -
renderable -
writable
-
-
xnano.devices
devices -
xnano.effects
effectsEffectController -
xnano.hooks
hooksHookHandle -
xnano.layout
layoutRegion__xnano_write__ -
xnano.operations
operationsContextualOperation -
xnano.styles
stylesRichContent__xnano_write__
-
Methods:
-
local–Convert a cell of the screen into a cell of the hook's target.
Source code in xnano/hooks/_context.py
def __init__(
self,
canvas: Canvas[DepsT_co, StateT_co],
owner: Canvas[object, object] | Placement[object, object],
hook: HookHandle[object, object],
event: _core.Event | _core.TerminalStateChange | Frame | Tick | None,
core: _core.CoreContext | None,
log: ReadLog | None = None,
timeline: Callable[[], Region[float]] | None = None,
screen: Screen[object, object] | None = None,
) -> None:
"""
Create a context. The runtime does this for you; hooks receive one.
Args:
canvas: The root canvas.
owner: The canvas or placement the hook is attached to.
hook: The hook that is called.
event: The event, or ``None``.
core: The runtime's context for the event, or ``None``.
log: Where to record what is read, for a component; ``None`` for a hook.
timeline: Returns the region on the timeline of what a playable is playing, for a
context of a playable; ``None`` for any other, whose ``region`` is on the
screen.
screen: The screen of a renderable, its own; ``None`` for the canvas's.
"""
self.canvas = canvas
self._owner = owner
self.hook = hook
self._event = event
self._core = core
self._log = log
self._timeline = timeline
self._screen = screen
canvas
instance-attribute
¶
canvas: Canvas[DepsT_co, StateT_co] = canvas
The root canvas the hook belongs to.
hook
instance-attribute
¶
hook: HookHandle[object, object] = hook
The registration, so the hook can call hook.remove().
event
property
¶
keyboard
property
¶
keyboard: Keyboard
The Keyboard, reading the key being handled.
key is None unless the event is a key, and pasted unless it is a paste.
mouse
property
¶
mouse: Mouse
The Mouse, reading the pointer event being handled.
position is None for any other event; the wheel is mouse.scroll.
screen
property
¶
screen: Screen[DepsT_co, StateT_co]
The Screen of the canvas the hook belongs to; for a
renderable, its own screen.
target
property
¶
The placement the hook is attached to, or the canvas for a hook on the canvas.
parent
property
¶
Where the hook's target is drawn: the placement it is nested in, or the canvas's
Screen (for a hook on the canvas too).
region
property
¶
The region of the hook's target.
For a hook on a canvas or a placement it is the cells of context.target on the
screen, the same region as context.target.region: x and y are its
column and row, inside the border and padding, and width and height its
cells. A component that reads it runs again when the screen is resized.
For a hook on a playable, or the playable itself, it is on the timeline: a piano roll
of the sound the playable played most recently. x is the beat that sound started
on, counted on the canvas's clock at its bpm, width
the beats it lasts, y its lowest pitch as a MIDI number and height the
semitones it spans. Until the playable has played, the region is empty and starts at
the beat the canvas has reached. Reading the cells of a region on the timeline, or the
beats of a region on the screen, raises a
TerminalError.
The region is typed Region[float], because the same property serves a hook on a
playable. For whole-number x and width on the screen, read
context.target.region, a Region[int], or context.size.
Examples:
import xnano
from xnano_core import Event
with xnano.new(width=20, height=6) as canvas:
seen = []
@canvas.hook(on='key')
def pressed(context: xnano.Context) -> None:
seen.append(context.region)
canvas.push(Event.key_press('a'))
canvas.deliver_events()
assert (seen[0].resolution, seen[0].width, seen[0].height) == ('cells', 20, 6)
A hook on a playable sees the timeline of its sound:
import xnano
from xnano_core import Event
seen = []
@xnano.playable
def chord(context: xnano.Context) -> xnano.Note:
return xnano.Note(('C4', 'G4'), beats=2)
@chord.hook(on='key')
def pressed(
context: xnano.Context, component_context: xnano.components.ComponentContext
) -> None:
seen.append(context.region)
with xnano.new(width=8, height=1) as canvas:
canvas.speaker.play(chord)
canvas.push(Event.key_press('a'))
canvas.deliver_events()
assert (seen[0].width, seen[0].y, seen[0].height) == (2.0, 60, 8)
size
property
¶
The size in cells of context.target on the screen.
For a hook on a canvas or a placement this is context.region.size: inside the
border and padding of a placement. A playable has no region on the screen, so for it
this is the size of the canvas it plays on.
local
¶
Convert a cell of the screen into a cell of the hook's target.
Parameters:
-
point(Point) –A cell in screen coordinates, such as
context.mouse.position.
Examples:
import xnano
from xnano_core import Point
with xnano.new(width=20, height=4) as canvas:
placement = canvas.screen.write('hi', x=10, y=1)
@placement.hook(on='mouse')
def pressed(context: xnano.Context) -> None:
if context.mouse.position is not None:
context.local(context.mouse.position)
assert placement.local(Point(11, 1)) == Point(1, 0)
Source code in xnano/hooks/_context.py
def local(self, point: _core.Point) -> _core.Point:
"""
Convert a cell of the screen into a cell of the hook's target.
Args:
point: A cell in screen coordinates, such as ``context.mouse.position``.
Examples:
```python
import xnano
from xnano_core import Point
with xnano.new(width=20, height=4) as canvas:
placement = canvas.screen.write('hi', x=10, y=1)
@placement.hook(on='mouse')
def pressed(context: xnano.Context) -> None:
if context.mouse.position is not None:
context.local(context.mouse.position)
assert placement.local(Point(11, 1)) == Point(1, 0)
```
"""
point = check_point(point)
bounds = self._owner._buffer._absolute_bounds
return _core.Point(point.x - bounds.x, point.y - bounds.y)
Terminal
¶
Terminal(*, width: int | str | None, height: int | str | None, fps: float, bpm: float, is_realtime: bool, deps: object, state: object, title: str | None, gates: Mapping[str, object], appearance: Mapping[str, object], effects: Sequence[WritableEffectSpecification], enclosing: Canvas[object, object] | None = None, layout: CanvasLayout = 'overlay', edges: EdgeBehavior = 'clip')
Bases: Canvas[DepsT, StateT]
A canvas that draws on your screen and reads your keyboard and mouse.
A canvas becomes a terminal when it is opened, with open or
Canvas.open: it is the same object, and
isinstance(canvas, xnano.Terminal) is how to ask whether a canvas is on the screen.
It has every member of Canvas, and its devices are the real ones:
its screen is the terminal's, its speaker the computer's sound, and its keyboard and mouse
the person's. It runs by itself: opening it
starts a loop on a thread of its own, and everything you write, remove or draw appears the
moment it is declared, however slowly the rest of your program runs, because declaring
only changes buffers and the loop draws them. A program has one screen, so only one
terminal is open at a time.
Attributes:
-
is_closed(bool) –Whether the terminal has been closed, or its loop has ended.
-
is_running(bool) –Whether the loop is running and has not been asked to end.
-
capabilities(TerminalCapabilities) –What the terminal answered about itself when the canvas was opened.
-
settings(TerminalSettings) –Every setting the terminal was opened with, as it was resolved.
Examples:
with xnano.open(width=20, height=2) as terminal:
terminal.screen.write('hello')
assert isinstance(terminal, xnano.Terminal)
terminal.run(stop_on='q')
Create a canvas. Use new instead of calling this.
Parameters:
-
width(int | str | None) –The width in cells, as a percentage of the window,
'fit'for the width of the content, orNonefor 80. -
height(int | str | None) –The height in cells, as a percentage of the window,
'fit'for the height of the content, orNonefor 24. -
fps(float) –The most frames drawn per second.
-
bpm(float) –Beats per minute.
-
is_realtime(bool) –Whether the canvas runs on the wall clock, on a thread of its own.
-
deps(object) –The dependencies, or the unset marker when none were given.
-
state(object) –A dataclass instance the canvas keeps and validates, or the unset marker.
-
title(str | None) –The window title, or
None. -
gates(Mapping[str, object]) –The terminal settings that were given, by name.
-
appearance(Mapping[str, object]) –The appearance keywords of the canvas itself, by name.
-
effects(Sequence[WritableEffectSpecification]) –Effects to apply to the canvas, as dictionaries with a
kindkey. -
enclosing(Canvas[object, object] | None, default:None) –The canvas whose
withblock this one was created in, which its sizes are measured in and which closes it, orNone. -
layout(CanvasLayout, default:'overlay') –How the canvas places what is written on it.
-
edges(EdgeBehavior, default:'clip') –What content written on the canvas does at the edges of its area.
Methods:
-
__setattr__–Set an attribute, or raise
AttributeErrorfor an unknown public name. -
hook–Call a function when something happens on this canvas or placement.
-
__new__–Refuse a direct call: a canvas is created with
xnano.new. -
write–Put content on the screen of the canvas, and return the placement that holds it.
-
render–Draw the current frame and return it as text, with no screen.
-
__rich_console__–Show the current frame in rich and Textual, with its colors and styles.
-
__rich_measure__–Tell rich the width of what it shows, so that rich keeps it whole when it can.
-
__contains__–Whether an item is inside the screen of the canvas.
-
open–Put this canvas on your screen, and return it as a
Terminal. -
open_async–Put this canvas on your screen like
open, from a coroutine. -
close–Release everything the canvas holds, and give the screen back if it has one.
-
close_async–Close the canvas like
close, awaiting its loop's end. -
wait_for_tasks_async–Wait until every run of the canvas's
async defhooks has finished. -
__or__–Attach a hook operation, such as one from
xnano.hook(), withcanvas | operation. -
__ior__–Attach a hook operation in place with
canvas |= operation. -
evaluate–Evaluate an expression against the canvas and return its value.
-
iter–Run the canvas one frame at a time: iterate over its frames, drawing between them.
-
iter_async–Run the canvas one frame at a time with
async for, likeiter. -
deliver_events–Deliver pushed events to their hooks and draw a frame, without moving time.
-
stop–Ask the canvas's loop to end.
-
run–Wait until the canvas's loop ends.
-
run_async–Wait until the canvas's loop ends, like
run, withawait. -
push–Deliver an event to the canvas as if it had been typed, clicked or reported.
-
state_reference–A core reference for one field of the canvas's state.
Source code in xnano/canvas.py
def __init__(
self,
*,
width: int | str | None,
height: int | str | None,
fps: float,
bpm: float,
is_realtime: bool,
deps: object,
state: object,
title: str | None,
gates: Mapping[str, object],
appearance: Mapping[str, object],
effects: Sequence[WritableEffectSpecification],
enclosing: Canvas[object, object] | None = None,
layout: CanvasLayout = 'overlay',
edges: EdgeBehavior = 'clip',
) -> None:
"""
Create a canvas. Use [`new`][xnano.new] instead of calling this.
Args:
width: The width in cells, as a percentage of the window, ``'fit'`` for the
width of the content, or ``None`` for 80.
height: The height in cells, as a percentage of the window, ``'fit'`` for the
height of the content, or ``None`` for 24.
fps: The most frames drawn per second.
bpm: Beats per minute.
is_realtime: Whether the canvas runs on the wall clock, on a thread of its own.
deps: The dependencies, or the unset marker when none were given.
state: A dataclass instance the canvas keeps and validates, or the unset marker.
title: The window title, or ``None``.
gates: The terminal settings that were given, by name.
appearance: The appearance keywords of the canvas itself, by name.
effects: Effects to apply to the canvas, as dictionaries with a ``kind`` key.
enclosing: The canvas whose ``with`` block this one was created in, which its
sizes are measured in and which closes it, or ``None``.
layout: How the canvas places what is written on it.
edges: What content written on the canvas does at the edges of its area.
"""
super().__init__()
self._canvas = self
self._root_canvas = self
self._lock = threading.RLock()
self._root = _core.Buffer()
self._buffer = self._root
# 'fit' takes the size of the content; a stacking canvas shares its size among its
# slots, so it cannot fit them.
if layout != 'overlay' and 'fit' in (width, height):
raise ValueError(
f'A {layout} canvas shares its size among the pieces written on it, so it '
f'cannot take the size of them. Give it a size such as height=12, or use '
f"layout='overlay' with width='fit' and height='fit'."
)
self._fits_width = width == 'fit'
self._fits_height = height == 'fit'
# Canvases written into this one that fit their content, and whether a fit runs now.
# The placements of canvases written into this one that fit their content.
self._fitted_placements: list[Placement[object, object]] = []
self._root.should_fit_width = self._fits_width
self._root.should_fit_height = self._fits_height
self._fps = fps
self._bpm = bpm
self._is_realtime = is_realtime
self._requested_width = width
self._requested_height = height
self._deps_given = deps is not _UNSET
self._deps = cast('DepsT', None if deps is _UNSET else deps)
self._state_given = state is not _UNSET
self._title = title
self._gates: dict[str, object] = dict(gates)
self._resolved_gates: dict[str, object] = {}
self._appearance = (
Appearance(**cast('dict[str, object]', _plain_appearance(appearance))) # type: ignore[arg-type]
if appearance
else None
)
self._dirty_looks: dict[int, _LookState] = {}
self._placements: list[Placement[DepsT, StateT]] = []
self._ledger: list[_Registration] = []
self._effects: list[
tuple[EffectParameters, Canvas[object, object] | Placement[object, object]]
] = []
self._frame_listeners: dict[int, Callable[[FrameContext], None]] = {}
self._frame_listener_tokens = itertools.count()
self._children: list[Canvas[object, object]] = []
self._nested_canvases: list[weakref.ref[Canvas[object, object]]] = []
self._areas: dict[int, Placement[object, object]] = {}
self._layout: CanvasLayout = layout
self._edges: EdgeBehavior = edges
self._slots: list[
tuple[Placement[object, object] | None, _core.Buffer, _core.SizeRule]
] = []
self._pending_layouts: dict[int, Canvas[object, object]] = {}
# The flow of every container that something was written into, by its buffer.
self._flows: dict[int, Flow] = {}
if enclosing is not None:
self._enclosing = weakref.ref(enclosing)
self._enclosing_size = (enclosing.screen.width, enclosing.screen.height)
with enclosing._lock:
enclosing._nested_canvases.append(
weakref.ref(cast('Canvas[object, object]', self))
)
self._stop_requested = _AwaitableEvent()
# The event loop that async def hooks run on: the one this canvas was created in.
self._event_loop: asyncio.AbstractEventLoop | None = running_loop()
self._state_fields: dict[str, object] = {}
if state is not _UNSET and state is not None:
self._state_store = _prepare_state(cast('DataclassInstance', state))
self._state_fields = _state_field_types(cast('DataclassInstance', state))
self._state_marked: dict[_StateFollower, _core.TerminalStateChange] = {}
self._internal_revisions: deque[int] = deque(maxlen=16)
self._namespace_identifiers = itertools.count(1)
self._active_run_by_thread = threading.local()
self._images: dict[int, ImageSource] = {}
# Only placements with an expression or a range need looking at before each frame.
self._dynamic: dict[int, Placement[DepsT, StateT]] = {}
# Whether the engine asks for a frame when the pointer moves: only while a placement
# before each frame reads the pointer. Only the canvas's loop changes it.
self._follows_pointer = False
self._clock_view = Clock(cast('Canvas[object, object]', self))
self._output = Output(cast('Canvas[object, object]', self))
# The mouse buttons the program pressed and has not released.
self._program_held_buttons: set[_core.MouseButton] = set()
self._size = _core.Size(0, 0)
self._previous_chain = tuple(
reference for reference in _active_canvas.get() if reference() is not None
)
_active_canvas.set(
(weakref.ref(cast('Canvas[object, object]', self)), *self._previous_chain)
)
self._host: _Host
columns, rows = _canvas_size(
None if self._fits_width else width,
None if self._fits_height else height,
self._enclosing_size,
)
if self._fits_width:
columns = 1
if self._fits_height:
rows = 1
interval_milliseconds = max(1, round(1000.0 / fps))
def create_runtime() -> _core.Runtime:
runtime = _core.Runtime.offscreen(
width=columns,
height=rows,
frame_interval_milliseconds=interval_milliseconds,
clock=_core.Clock.monotonic() if is_realtime else None,
)
if title is not None:
runtime.title = title
return runtime
try:
if is_realtime:
_ThreadHost(cast('Canvas[object, object]', self), create_runtime)
else:
_InlineHost(cast('Canvas[object, object]', self), create_runtime)
except BaseException:
_active_canvas.set(self._previous_chain)
self._finalize()
raise
try:
if effects:
apply_effects(cast('Canvas[object, object]', self), effects)
except BaseException:
self.close(raise_failure=False)
raise
self._writable_effects = WritableEffectProperties(
cast('Canvas[object, object]', self)
)
self._seal()
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.
capabilities
property
¶
capabilities: TerminalCapabilities
What the terminal answered about itself when the canvas was opened.
settings
property
¶
settings: TerminalSettings
A copy of every setting of the terminal, including the ones that hooks turned on.
__setattr__
¶
Set an attribute, or raise AttributeError for an unknown public name.
Source code in xnano/_internal/_attributes.py
def __setattr__(self, name: str, value: object) -> None:
"""Set an attribute, or raise ``AttributeError`` for an unknown public name."""
if (
name[:1] != '_'
and self.__dict__.get('_is_sealed')
and not hasattr(type(self), name)
and name not in self.__dict__
):
kind = type(self).__name__
settable = sorted(
key
for key in dir(type(self))
if key[:1] != '_' and _is_settable(type(self), key)
)
close = difflib.get_close_matches(name, settable, n=1)
hint = f' Did you mean {close[0]!r}?' if close else ''
raise AttributeError(
f'{kind} has no attribute called {name!r}, so assigning to it would change '
f'nothing.{hint} The attributes you can assign are: {", ".join(settable)}.'
)
object.__setattr__(self, name, value)
hook
¶
hook(function: Hook[DepsT, StateT], /, *, on: HookTrigger[DepsT, StateT] | None = None, every: float | None = None, after: float | None = None, keys: KeyName | Sequence[KeyName] | None = None, requires_deps: bool = False, if_running: IfRunning = 'replace') -> HookHandle[DepsT, StateT]
hook(function: Hook[DepsT, StateT] | None = None, /, *, on: HookTrigger[DepsT, StateT] | None = None, every: float | None = None, after: float | None = None, keys: KeyName | Sequence[KeyName] | None = None, requires_deps: bool = False, if_running: IfRunning = 'replace') -> HookHandle[DepsT, StateT] | Callable[[Hook[DepsT, StateT]], HookHandle[DepsT, StateT]]
Call a function when something happens on this canvas or placement.
on says when the hook runs: a kind of event such as 'key' or 'tick', the
name of an event pushed with Event.custom(name), or a condition such as
"mouse.kind == 'press'" (see HookTrigger). A hook
without on hears every input event. A mouse,
scroll or drag hook on a placement hears only the pointer inside the placement, and a
press inside holds the pointer for the hook until the button is released. A pointer hook
that matches an event stops it from reaching the parent; a hook that does not match lets
it through. Keys are not consumed: while nothing has focus, every key hook hears a key.
A hook hears only the input the screen reports. A hook added to a canvas that is
already on the screen turns no terminal setting on, so one that needs input the screen
does not report, such as on='mouse' on a canvas opened without mouse=True, is
attached and never runs.
hook(function, ...) attaches one function, and @target.hook(...) decorates the
function that follows. A hook function may be a generator that receives a new context
at each bare yield: write context = yield. A drag is a loop that runs while
context.mouse.is_down.
A hook without on hears every input event. While a mouse button it heard is held,
it also runs on every frame once the button has been held for 0.15 seconds, so a
quick click runs it only for the press and the release. A release names its button
in context.mouse.button; test context.mouse.is_down to leave the release out.
A hook function may also be written with async def. Each time the hook runs, its
coroutine starts on the event loop the canvas was created or opened in, and on
xnano's own background loop when there is none, and the canvas goes on drawing while
it awaits. if_running says what happens when the hook runs again before the
previous run has finished. A canvas with a manual clock (from new()) needs an event
loop of its own for that: create it in a coroutine or use async with on it.
wait_for_tasks_async waits until every
run has finished. A run that raises ends the canvas like a plain hook that raises; a
cancelled run is not a failure.
every and after are seconds for on='tick' and beats for on='beat':
every=2 means 2 seconds for a tick hook and 2 beats for a beat hook. On a canvas
from new() a hook that is due several times in one step runs once for each
interval, up to 100,000 times in one step; the intervals that remain run in the steps
that follow. The function's return value is ignored, unless it is an operation, a
style or an effect, which is applied to this target.
Parameters:
-
function(Hook[DepsT, StateT] | None, default:None) –The function to call with a
Context, or a function with no parameters, which is called without it. -
on(HookTrigger[DepsT, StateT] | None, default:None) –When the hook runs. A kind:
'frame','tick','beat','key','mouse','scroll','drag','paste','focus','resize','state'or'custom'(every custom event); seeHookKind. The name of a custom event, such as'volume_changed'. Or a condition: a string, an expression or a function of the context; seeWhen. A string that reads one input hears only that input ("mouse.kind == 'press'"is a mouse hook, and hears the pointer inside a placement), a string that reads no input is checked on every tick, and a string tells xnano which terminal settings the hook needs, somouseandscrollturn on when the canvas opens. A string that reads key releases needskeyboard='release_events'given tonew()oropen(). An expression or a function hears every input event and does not tell xnano what it reads, so one that readsmouse,scrollor key releases needsmouse=True,scroll=Trueorkeyboard='release_events'given tonew()oropen()yourself. Withevery,afterorkeysa condition is checked on those ticks or keys. A comparison with an input the event does not carry, such askeyboard.keyon a paste, does not hold;!=is one of them, sokeyboard.key != 'q'hears only key events.notandnot innegate the whole comparison, sonot keyboard.key == 'q'andkeyboard.key not in ['q']also hold for events that have no key. -
every(float | None, default:None) –Repeat every this many seconds (
'tick') or beats ('beat'). -
after(float | None, default:None) –Run once after this many seconds (
'tick') or beats ('beat'). -
keys(KeyName | Sequence[KeyName] | None, default:None) –The key or keys an
on='key'hook reacts to, such as'q'or'ctrl+s'. A key hook with keys hears presses and repeats; omit them and testkeyboard.kindto hear releases. -
requires_deps(bool, default:False) –Whether the hook needs the dependencies given to
new(deps=...). -
if_running(IfRunning, default:'replace') –For an
async defhook, what happens when it runs again while its previous run has not finished:'replace'cancels that run (the latest wins),'ignore'drops the new one,'queue'runs them one after the other and'overlap'runs them together. SeeIfRunning.
Returns:
-
HookHandle[DepsT, StateT] | Callable[[Hook[DepsT, StateT]], HookHandle[DepsT, StateT]]–The hook, whose
removestops it; removing it cancels the unfinished runs of -
HookHandle[DepsT, StateT] | Callable[[Hook[DepsT, StateT]], HookHandle[DepsT, StateT]]–an
async defhook. Without a function, the decorator.
Raises:
-
ValueError–The combination of arguments does not make sense, a key name is unknown, a condition string is not a condition,
onis one letter away from a kind, orif_runningis given to a function that is notasync def. The message says what to write instead. -
TypeError–onis a plainboolor not a kind, a name or a condition, or the function is not callable with a context, or is an async generator. -
TerminalError–requires_depsis true and the canvas was created withoutdeps, or anasync defhook has no event loop to run on.
Examples:
import xnano
from xnano_core import Event
with xnano.new(width=8, height=1) as canvas:
heard = []
@canvas.hook(on='key', keys=['q', 'escape'])
def leave(context: xnano.Context) -> None:
heard.append(context.keyboard.key)
@canvas.hook(on='tick', every=0.5)
def blink(context: xnano.Context) -> None:
heard.append('tick')
canvas.push(Event.key_press('q'))
canvas.clock.step(delta_seconds=1.0)
assert heard == ['q', 'tick', 'tick']
Source code in xnano/hooks/_handles.py
def hook(
self,
function: Hook[DepsT, StateT] | None = None,
/,
*,
on: HookTrigger[DepsT, StateT] | None = None,
every: float | None = None,
after: float | None = None,
keys: KeyName | Sequence[KeyName] | None = None,
requires_deps: bool = False,
if_running: IfRunning = 'replace',
) -> (
HookHandle[DepsT, StateT]
| Callable[[Hook[DepsT, StateT]], HookHandle[DepsT, StateT]]
):
"""
Call a function when something happens on this canvas or placement.
``on`` says when the hook runs: a kind of event such as ``'key'`` or ``'tick'``, the
name of an event pushed with ``Event.custom(name)``, or a condition such as
``"mouse.kind == 'press'"`` (see [`HookTrigger`][xnano.hooks.HookTrigger]). A hook
without ``on`` hears every input event. A mouse,
scroll or drag hook on a placement hears only the pointer inside the placement, and a
press inside holds the pointer for the hook until the button is released. A pointer hook
that matches an event stops it from reaching the parent; a hook that does not match lets
it through. Keys are not consumed: while nothing has focus, every key hook hears a key.
A hook hears only the input the screen reports. A hook added to a canvas that is
already on the screen turns no terminal setting on, so one that needs input the screen
does not report, such as ``on='mouse'`` on a canvas opened without ``mouse=True``, is
attached and never runs.
``hook(function, ...)`` attaches one function, and ``@target.hook(...)`` decorates the
function that follows. A hook function may be a generator that receives a new context
at each bare ``yield``: write ``context = yield``. A drag is a loop that runs while
``context.mouse.is_down``.
A hook without ``on`` hears every input event. While a mouse button it heard is held,
it also runs on every frame once the button has been held for 0.15 seconds, so a
quick click runs it only for the press and the release. A release names its button
in ``context.mouse.button``; test ``context.mouse.is_down`` to leave the release out.
A hook function may also be written with ``async def``. Each time the hook runs, its
coroutine starts on the event loop the canvas was created or opened in, and on
xnano's own background loop when there is none, and the canvas goes on drawing while
it awaits. ``if_running`` says what happens when the hook runs again before the
previous run has finished. A canvas with a manual clock (from ``new()``) needs an event
loop of its own for that: create it in a coroutine or use ``async with`` on it.
[`wait_for_tasks_async`][xnano.canvas.Canvas.wait_for_tasks_async] waits until every
run has finished. A run that raises ends the canvas like a plain hook that raises; a
cancelled run is not a failure.
``every`` and ``after`` are seconds for ``on='tick'`` and beats for ``on='beat'``:
``every=2`` means 2 seconds for a tick hook and 2 beats for a beat hook. On a canvas
from ``new()`` a hook that is due several times in one ``step`` runs once for each
interval, up to 100,000 times in one step; the intervals that remain run in the steps
that follow. The function's return value is ignored, unless it is an operation, a
style or an effect, which is applied to this target.
Args:
function: The function to call with a [`Context`][xnano.hooks.Context], or a
function with no parameters, which is called without it.
on: When the hook runs. A kind: ``'frame'``, ``'tick'``, ``'beat'``, ``'key'``,
``'mouse'``, ``'scroll'``, ``'drag'``, ``'paste'``, ``'focus'``, ``'resize'``,
``'state'`` or ``'custom'`` (every custom event); see
[`HookKind`][xnano.hooks.HookKind]. The name of a custom event, such as
``'volume_changed'``. Or a condition: a string, an expression or a function of
the context; see [`When`][xnano.hooks.When]. A string that reads one input
hears only that input (``"mouse.kind == 'press'"`` is a mouse hook, and hears
the pointer inside a placement), a string that reads no input is checked on
every tick, and a string tells xnano which terminal settings the hook needs,
so ``mouse`` and ``scroll`` turn on when the canvas opens. A string that reads
key releases needs ``keyboard='release_events'`` given to ``new()`` or
``open()``. An expression or a function hears every input event and does not
tell xnano what it reads, so one that reads ``mouse``, ``scroll`` or key
releases needs ``mouse=True``, ``scroll=True`` or
``keyboard='release_events'`` given to ``new()`` or ``open()`` yourself. With
``every``, ``after`` or ``keys`` a condition is checked on those ticks or keys.
A comparison with an input the event does not carry, such as ``keyboard.key``
on a paste, does not hold; ``!=`` is one of them, so ``keyboard.key != 'q'``
hears only key events. ``not`` and ``not in`` negate the whole comparison, so
``not keyboard.key == 'q'`` and ``keyboard.key not in ['q']`` also hold for
events that have no key.
every: Repeat every this many seconds (``'tick'``) or beats (``'beat'``).
after: Run once after this many seconds (``'tick'``) or beats (``'beat'``).
keys: The key or keys an ``on='key'`` hook reacts to, such as ``'q'`` or
``'ctrl+s'``. A key hook with keys hears presses and repeats; omit them and
test ``keyboard.kind`` to hear releases.
requires_deps: Whether the hook needs the dependencies given to
``new(deps=...)``.
if_running: For an ``async def`` hook, what happens when it runs again while
its previous run has not finished: ``'replace'`` cancels that run (the
latest wins), ``'ignore'`` drops the new one, ``'queue'`` runs them one after
the other and ``'overlap'`` runs them together. See
[`IfRunning`][xnano.hooks.IfRunning].
Returns:
The hook, whose ``remove`` stops it; removing it cancels the unfinished runs of
an ``async def`` hook. Without a function, the decorator.
Raises:
ValueError: The combination of arguments does not make sense, a key name is
unknown, a condition string is not a condition, ``on`` is one letter away
from a kind, or ``if_running`` is given to a function that is not
``async def``. The message says what to write instead.
TypeError: ``on`` is a plain ``bool`` or not a kind, a name or a condition, or the
function is not callable with a context, or is an async generator.
TerminalError: ``requires_deps`` is true and the canvas was created without
``deps``, or an ``async def`` hook has no event loop to run on.
Examples:
```python
import xnano
from xnano_core import Event
with xnano.new(width=8, height=1) as canvas:
heard = []
@canvas.hook(on='key', keys=['q', 'escape'])
def leave(context: xnano.Context) -> None:
heard.append(context.keyboard.key)
@canvas.hook(on='tick', every=0.5)
def blink(context: xnano.Context) -> None:
heard.append('tick')
canvas.push(Event.key_press('q'))
canvas.clock.step(delta_seconds=1.0)
assert heard == ['q', 'tick', 'tick']
```
"""
canvas = self._canvas
self._require_attached()
owner = cast('_Hooked[object, object]', self)
kind, condition = resolve_trigger(on, every=every, after=after, keys=keys)
normalized_keys = _check_hook_arguments(owner, kind, every, after, keys)
compiled = compile_when(condition)
if requires_deps and not canvas._deps_given:
raise TerminalError(
'This hook needs dependencies (requires_deps=True), but the canvas has none '
'yet. Give them when you create the canvas: xnano.new(deps=your_dependencies) '
'or xnano.open(deps=your_dependencies), or open the canvas with '
'canvas.open(deps=your_dependencies) before you register this hook.'
)
_check_if_running(if_running)
def attach(
callback: Hook[DepsT, StateT],
) -> HookHandle[DepsT, StateT]:
checked = _check_hook_function(callback)
_check_coroutine_hook(owner, checked, kind, if_running)
return self._attach_hook(
cast('Callable[[Context[DepsT, StateT]], object]', checked),
on=kind,
when=compiled,
every=every,
after=after,
keys=normalized_keys,
if_running=if_running,
)
if function is None:
return attach
return attach(function)
__new__
¶
Refuse a direct call: a canvas is created with xnano.new.
Source code in xnano/canvas.py
def __new__(cls, *arguments: object, **keywords: object) -> Self:
"""Refuse a direct call: a canvas is created with ``xnano.new``."""
if arguments or 'is_realtime' not in keywords:
raise TypeError(
f'{cls.__name__} is not created by calling it. Create a canvas with '
f'xnano.new(...), or put one on the screen with xnano.open(...).'
)
return super().__new__(cls)
write
¶
write(content: Content | Canvas[WrittenDepsT, WrittenStateT] | None = None, /, *, x: Axis = 'next', y: Axis = 'next', width: Axis | None = None, height: Axis | None = None, layer: int = 0, lock: bool = False, edges: EdgeBehavior | None = None, effects: Sequence[WritableEffectSpecification] = (), style: Style | None = None, foreground: ColorValue | None = None, background: ColorValue | None = None, bold: bool = False, dim: bool = False, italic: bool = False, underline: bool = False, blink: bool = False, reverse: bool = False, hidden: bool = False, crossed_out: bool = False, title: str | None = None, border: BorderKind | bool | None = None, border_style: Style | None = None, padding: Spacing | None = None, margin: Spacing | None = None) -> Placement[DepsT, StateT]
Put content on the screen of the canvas, and return the placement that holds it.
canvas.write(...) is the same as canvas.screen.write(...). It takes the same
arguments, does the same work and gives the same result. See
Screen.write for how the screen places each kind of
content.
Parameters:
-
content(Content | Canvas[WrittenDepsT, WrittenStateT] | None, default:None) – -
x(Axis, default:'next') –The column of the left edge: a number of cells, a percentage string, a word (
'left','center','right'or'next'), an expression or a range. SeeAxis. -
y(Axis, default:'next') –The row of the top edge, in the same forms (
'top','center','bottom'or'next').'next', the default, is the first row below the content written before. -
width(Axis | None, default:None) –The width, in the same forms.
Noneuses the width of the content. -
height(Axis | None, default:None) –The height, in the same forms.
Noneuses the height of the content. -
layer(int, default:0) –The layer. Content on a higher layer shows over content on a lower layer.
-
lock(bool, default:False) –Whether to keep the position and the size that the content has now when the canvas changes size.
-
edges(EdgeBehavior | None, default:None) –What the content does at the edges of its area:
'clip','stop'or'wrap'.Noneuses theedgesof the screen. -
effects(Sequence[WritableEffectSpecification], default:()) –The effects to start on the placement, as dictionaries with a
kindkey. -
style(Style | None, default:None) –A
Stylefor the text. The arguments below apply over it. -
foreground(ColorValue | None, default:None) –The color of the text.
-
background(ColorValue | None, default:None) –The color behind the text.
-
bold(bool, default:False) –Whether the text is bold.
-
dim(bool, default:False) –Whether the text is dim.
-
italic(bool, default:False) –Whether the text is italic.
-
underline(bool, default:False) –Whether the text has a line below it.
-
blink(bool, default:False) –Whether the text blinks.
-
reverse(bool, default:False) –Whether the foreground color and the background color change places.
-
hidden(bool, default:False) –Whether the text is hidden.
-
crossed_out(bool, default:False) –Whether the text has a line through it.
-
title(str | None, default:None) –The title on the border of a box around the content.
-
border(BorderKind | bool | None, default:None) –The
BorderKindof a box around the content, such as'plain'or'rounded'.Trueis'plain', andFalseis no border. -
border_style(Style | None, default:None) –The style of the border.
-
padding(Spacing | None, default:None) –The space between the border and the content: a number of cells, a share of the size of the content, or a dictionary of sides.
-
margin(Spacing | None, default:None) –The space outside the box, in the same forms.
Returns:
-
Placement[DepsT, StateT]–The
Placementthat holds the content. Use it to move, -
Placement[DepsT, StateT]–resize or remove the content.
Raises:
-
TypeError–The content is a file path, raw bytes, an operation, a style or an effect. Apply those with
canvas.screen.update(...). -
TerminalError–The content is a canvas that you cannot write here.
Examples:
import xnano
with xnano.new(width=12, height=3) as canvas:
greeting = canvas.write('hello', x='center', y='center', bold=True)
assert (greeting.width, greeting.y) == (5, 1)
assert canvas.render().splitlines()[1].strip() == 'hello'
Source code in xnano/canvas.py
@refuse_unknown_keywords
def write(
self,
content: Content | Canvas[WrittenDepsT, WrittenStateT] | None = None,
/,
*,
x: Axis = 'next',
y: Axis = 'next',
width: Axis | None = None,
height: Axis | None = None,
layer: int = 0,
lock: bool = False,
edges: EdgeBehavior | None = None,
effects: Sequence[WritableEffectSpecification] = (),
style: _core.Style | None = None,
foreground: ColorValue | None = None,
background: ColorValue | None = None,
bold: bool = False,
dim: bool = False,
italic: bool = False,
underline: bool = False,
blink: bool = False,
reverse: bool = False,
hidden: bool = False,
crossed_out: bool = False,
title: str | None = None,
border: _core.BorderKind | bool | None = None,
border_style: _core.Style | None = None,
padding: Spacing | None = None,
margin: Spacing | None = None,
) -> Placement[DepsT, StateT]:
"""
Put content on the screen of the canvas, and return the placement that holds it.
``canvas.write(...)`` is the same as ``canvas.screen.write(...)``. It takes the same
arguments, does the same work and gives the same result. See
[`Screen.write`][xnano.devices.Screen.write] for how the screen places each kind of
content.
Args:
content: Text (or a list of lines), a [`Buffer`][xnano_core.Buffer] or widget, a
canvas from ``new()``, an image, or any
[`Writable`][xnano.components.Writable]. ``None`` makes an empty placement.
x: The column of the left edge: a number of cells, a percentage string, a word
(``'left'``, ``'center'``, ``'right'`` or ``'next'``), an expression or a
range. See [`Axis`][xnano.layout.Axis].
y: The row of the top edge, in the same forms (``'top'``, ``'center'``,
``'bottom'`` or ``'next'``). ``'next'``, the default, is the first row below
the content written before.
width: The width, in the same forms. ``None`` uses the width of the content.
height: The height, in the same forms. ``None`` uses the height of the content.
layer: The layer. Content on a higher layer shows over content on a lower layer.
lock: Whether to keep the position and the size that the content has now when
the canvas changes size.
edges: What the content does at the edges of its area: ``'clip'``, ``'stop'`` or
``'wrap'``. ``None`` uses the ``edges`` of the screen.
effects: The effects to start on the placement, as dictionaries with a ``kind``
key.
style: A [`Style`][xnano.styles.Style] for the text. The arguments below apply
over it.
foreground: The color of the text.
background: The color behind the text.
bold: Whether the text is bold.
dim: Whether the text is dim.
italic: Whether the text is italic.
underline: Whether the text has a line below it.
blink: Whether the text blinks.
reverse: Whether the foreground color and the background color change places.
hidden: Whether the text is hidden.
crossed_out: Whether the text has a line through it.
title: The title on the border of a box around the content.
border: The [`BorderKind`][xnano.styles.BorderKind] of a box around the content,
such as ``'plain'`` or ``'rounded'``. ``True`` is ``'plain'``, and ``False``
is no border.
border_style: The style of the border.
padding: The space between the border and the content: a number of cells, a
share of the size of the content, or a dictionary of sides.
margin: The space outside the box, in the same forms.
Returns:
The [`Placement`][xnano.layout.Placement] that holds the content. Use it to move,
resize or remove the content.
Raises:
TypeError: The content is a file path, raw bytes, an operation, a style or an
effect. Apply those with ``canvas.screen.update(...)``.
TerminalError: The content is a canvas that you cannot write here.
Examples:
```python
import xnano
with xnano.new(width=12, height=3) as canvas:
greeting = canvas.write('hello', x='center', y='center', bold=True)
assert (greeting.width, greeting.y) == (5, 1)
assert canvas.render().splitlines()[1].strip() == 'hello'
```
"""
return self.screen.write(
content,
x=x,
y=y,
width=width,
height=height,
layer=layer,
lock=lock,
edges=edges,
effects=effects,
style=style,
foreground=foreground,
background=background,
bold=bold,
dim=dim,
italic=italic,
underline=underline,
blink=blink,
reverse=reverse,
hidden=hidden,
crossed_out=crossed_out,
title=title,
border=border,
border_style=border_style,
padding=padding,
margin=margin,
)
render
¶
Draw the current frame and return it as text, with no screen.
canvas.render(...) is the same as
canvas.screen.render(...).
Parameters:
-
format(Literal['text', 'ansi'], default:'text') –'text'for the characters only.'ansi'for the characters with their colors and styles as escape codes.
Returns:
-
str–The frame, with one line for each row.
Raises:
-
ValueError–formatis not'text'or'ansi'.
Examples:
import xnano
with xnano.new(width=6, height=2) as canvas:
canvas.write('hello', y=1)
assert canvas.render().splitlines() == ['', 'hello']
assert canvas.render(format='ansi') == canvas.screen.render(format='ansi')
Source code in xnano/canvas.py
def render(self, *, format: Literal['text', 'ansi'] = 'text') -> str:
"""
Draw the current frame and return it as text, with no screen.
``canvas.render(...)`` is the same as
[`canvas.screen.render(...)`][xnano.devices.Screen.render].
Args:
format: ``'text'`` for the characters only. ``'ansi'`` for the characters with
their colors and styles as escape codes.
Returns:
The frame, with one line for each row.
Raises:
ValueError: ``format`` is not ``'text'`` or ``'ansi'``.
Examples:
```python
import xnano
with xnano.new(width=6, height=2) as canvas:
canvas.write('hello', y=1)
assert canvas.render().splitlines() == ['', 'hello']
assert canvas.render(format='ansi') == canvas.screen.render(format='ansi')
```
"""
return self.screen.render(format=format)
__rich_console__
¶
Show the current frame in rich and Textual, with its colors and styles.
rich.print(canvas) prints the frame. A canvas can also go into a rich Panel
or Table, or into a Textual Static. If a line is longer than the space that
rich gives it, rich cuts the line, as a terminal does. Rich must be installed.
A closed canvas cannot draw. Textual draws a Static after you make it, so give
Textual a canvas that stays open, such as one from xnano.new() outside a
with block.
Examples:
import io
import xnano
from rich.console import Console
with xnano.new(width=5, height=1) as canvas:
canvas.write('hello')
console = Console(file=io.StringIO(), width=20)
console.print(canvas)
assert console.file.getvalue() == 'hello\n'
Source code in xnano/canvas.py
def __rich_console__(
self, console: RichConsole, options: RichConsoleOptions
) -> RichRenderResult:
r"""
Show the current frame in rich and Textual, with its colors and styles.
``rich.print(canvas)`` prints the frame. A canvas can also go into a rich ``Panel``
or ``Table``, or into a Textual ``Static``. If a line is longer than the space that
rich gives it, rich cuts the line, as a terminal does. Rich must be installed.
A closed canvas cannot draw. Textual draws a ``Static`` after you make it, so give
Textual a canvas that stays open, such as one from ``xnano.new()`` outside a
``with`` block.
Examples:
```python
import io
import xnano
from rich.console import Console
with xnano.new(width=5, height=1) as canvas:
canvas.write('hello')
console = Console(file=io.StringIO(), width=20)
console.print(canvas)
assert console.file.getvalue() == 'hello\n'
```
"""
from rich.text import Text as RichText
yield RichText.from_ansi(
self.render(format='ansi'), no_wrap=True, overflow='crop'
)
__rich_measure__
¶
Tell rich the width of what it shows, so that rich keeps it whole when it can.
A frame of cells cannot wrap, so its smallest and its largest width are the same.
Rich uses this width to lay out panels, columns and nested tables. In a rich
Table, add the column with no_wrap=True, so that rich makes the other
columns narrower before it cuts this one.
Source code in xnano/canvas.py
def __rich_measure__(
self, console: RichConsole, options: RichConsoleOptions
) -> RichMeasurement:
"""
Tell rich the width of what it shows, so that rich keeps it whole when it can.
A frame of cells cannot wrap, so its smallest and its largest width are the same.
Rich uses this width to lay out panels, columns and nested tables. In a rich
``Table``, add the column with ``no_wrap=True``, so that rich makes the other
columns narrower before it cuts this one.
"""
from rich.measure import Measurement as RichMeasurement
width = self.screen.width
return RichMeasurement(width, width)
__contains__
¶
Whether an item is inside the screen of the canvas.
item in canvas is the same as item in canvas.screen.region. See
Region for the items that it accepts.
Parameters:
Examples:
import xnano
with xnano.new(width=4, height=2) as canvas:
assert (3, 1) in canvas
assert (4, 1) not in canvas
Source code in xnano/canvas.py
def __contains__(self, item: object) -> bool:
"""
Whether an item is inside the screen of the canvas.
``item in canvas`` is the same as ``item in canvas.screen.region``. See
[`Region`][xnano.layout.Region] for the items that it accepts.
Args:
item: What to find, such as an ``(x, y)`` pair or a
[`Point`][xnano_core.Point] in screen cells.
Examples:
```python
import xnano
with xnano.new(width=4, height=2) as canvas:
assert (3, 1) in canvas
assert (4, 1) not in canvas
```
"""
return item in self.screen.region
open
¶
open(*, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, **settings: Unpack[OpenSettings]) -> Terminal[DepsT, StateT]
Put this canvas on your screen, and return it as a Terminal.
The same object is returned: after this, isinstance(canvas, xnano.Terminal) is
true. From then on it runs by itself on a thread of its own and on the wall clock, which
continues from the time the canvas had: elapsed time, the frame count, every and
after timers and a stopped clock carry over, and so do the cursor, the title,
everything written and every hook. Effects that were running start again from their
beginning, and keyboard focus and a captured pointer are released.
width and height are the size of the canvas: the ones given here, else the
ones given to new(), draw in a region of that size below the cursor; a canvas
created without a size, or with '100%' for both, fills the whole window. A
percentage such as '50%' is a share of the window when the canvas is opened. Any
other keyword of new() except realtime may be given and applies before the
canvas is shown; a terminal setting given here wins over the one given to new().
title is the window title.
Parameters:
-
title(str | None, default:None) –The window title;
Nonekeeps the canvas's title. -
width(int | Percentage | str | None, default:None) –The width of the region to draw in: cells, or a percentage of the window.
-
height(int | Percentage | str | None, default:None) –The height of the region to draw in: cells, or a percentage of the window.
-
settings(Unpack[OpenSettings], default:{}) –Terminal settings, appearance keywords,
fps,bpm,effects, anddepsandstatefor a canvas that was created without them; seeOpenSettings.
Returns:
-
Terminal[DepsT, StateT]–This canvas, now attached to the screen.
Raises:
-
TerminalAlreadyOpenError–Another canvas is already on the screen.
-
TerminalError–This canvas is already on the screen, was written into another canvas, has a hook that needs a terminal setting given as
False, or there is no terminal to draw on; the canvas stays as it was. -
TypeError–realtimewas given,depsorstatethat the canvas already has, or an effect that is not a visual effect dictionary. -
ValueError–A
widthwas given without aheight, or a value is out of range.
Examples:
with xnano.new(width=40, height=5) as canvas:
canvas.screen.write('hello', border='rounded')
canvas.clock.step()
canvas.open(mouse=True) # now a xnano.Terminal, 40 by 5 below the prompt
canvas.run(stop_on='q')
Source code in xnano/canvas.py
def open(
self,
*,
title: str | None = None,
width: int | Percentage | str | None = None,
height: int | Percentage | str | None = None,
**settings: Unpack[OpenSettings],
) -> Terminal[DepsT, StateT]:
"""
Put this canvas on your screen, and return it as a [`Terminal`][xnano.Terminal].
The same object is returned: after this, ``isinstance(canvas, xnano.Terminal)`` is
true. From then on it runs by itself on a thread of its own and on the wall clock, which
continues from the time the canvas had: elapsed time, the frame count, ``every`` and
``after`` timers and a stopped clock carry over, and so do the cursor, the title,
everything written and every hook. Effects that were running start again from their
beginning, and keyboard focus and a captured pointer are released.
``width`` and ``height`` are the size of the canvas: the ones given here, else the
ones given to ``new()``, draw in a region of that size below the cursor; a canvas
created without a size, or with ``'100%'`` for both, fills the whole window. A
percentage such as ``'50%'`` is a share of the window when the canvas is opened. Any
other keyword of ``new()`` except ``realtime`` may be given and applies before the
canvas is shown; a terminal setting given here wins over the one given to ``new()``.
``title`` is the window title.
Args:
title: The window title; ``None`` keeps the canvas's title.
width: The width of the region to draw in: cells, or a percentage of the window.
height: The height of the region to draw in: cells, or a percentage of the window.
settings: Terminal settings, appearance keywords, ``fps``, ``bpm``, ``effects``,
and ``deps`` and ``state`` for a canvas that was created without them; see
[`OpenSettings`][xnano.terminal.OpenSettings].
Returns:
This canvas, now attached to the screen.
Raises:
TerminalAlreadyOpenError: Another canvas is already on the screen.
TerminalError: This canvas is already on the screen, was written into another
canvas, has a hook that needs a terminal setting given as ``False``, or
there is no terminal to draw on; the canvas stays as it was.
TypeError: ``realtime`` was given, ``deps`` or ``state`` that the canvas already
has, or an effect that is not a visual effect dictionary.
ValueError: A ``width`` was given without a ``height``, or a value is out of
range.
Examples:
```text
with xnano.new(width=40, height=5) as canvas:
canvas.screen.write('hello', border='rounded')
canvas.clock.step()
canvas.open(mouse=True) # now a xnano.Terminal, 40 by 5 below the prompt
canvas.run(stop_on='q')
```
"""
from xnano.terminal import Terminal
from xnano.terminal._screen import attach_screen
attach_screen(self, title=title, width=width, height=height, settings=settings)
assert isinstance(self, Terminal)
return self
open_async
¶
open_async(*, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, **settings: Unpack[OpenSettings]) -> OpeningTerminal[DepsT, StateT]
Put this canvas on your screen like open, from a coroutine.
The terminal is asked what it can do while your event loop goes on running other
tasks. Await the result for the Terminal, or enter it with
async with, which closes it when the block ends. The keywords are the ones
open() takes, and so are the errors, which are raised when it is awaited.
Parameters:
-
title(str | None, default:None) –The window title;
Nonekeeps the canvas's title. -
width(int | Percentage | str | None, default:None) –The width of the region to draw in: cells, or a percentage of the window.
-
height(int | Percentage | str | None, default:None) –The height of the region to draw in: cells, or a percentage of the window.
-
settings(Unpack[OpenSettings], default:{}) –Terminal settings, appearance keywords,
fps,bpm,effects, anddepsandstatefor a canvas that was created without them; seeOpenSettings.
Returns:
-
OpeningTerminal[DepsT, StateT]–The opening terminal: await it, or use it in
async with.
Examples:
async def main() -> None:
async with xnano.new(width=40, height=5) as canvas:
canvas.screen.write('hello', border='rounded')
terminal = await canvas.open_async(mouse=True)
await terminal.run_async(stop_on='q')
Source code in xnano/canvas.py
def open_async(
self,
*,
title: str | None = None,
width: int | Percentage | str | None = None,
height: int | Percentage | str | None = None,
**settings: Unpack[OpenSettings],
) -> OpeningTerminal[DepsT, StateT]:
"""
Put this canvas on your screen like [`open`][xnano.canvas.Canvas.open], from a coroutine.
The terminal is asked what it can do while your event loop goes on running other
tasks. Await the result for the [`Terminal`][xnano.Terminal], or enter it with
``async with``, which closes it when the block ends. The keywords are the ones
``open()`` takes, and so are the errors, which are raised when it is awaited.
Args:
title: The window title; ``None`` keeps the canvas's title.
width: The width of the region to draw in: cells, or a percentage of the window.
height: The height of the region to draw in: cells, or a percentage of the window.
settings: Terminal settings, appearance keywords, ``fps``, ``bpm``, ``effects``,
and ``deps`` and ``state`` for a canvas that was created without them; see
[`OpenSettings`][xnano.terminal.OpenSettings].
Returns:
The opening terminal: await it, or use it in ``async with``.
Examples:
```text
async def main() -> None:
async with xnano.new(width=40, height=5) as canvas:
canvas.screen.write('hello', border='rounded')
terminal = await canvas.open_async(mouse=True)
await terminal.run_async(stop_on='q')
```
"""
from xnano.terminal import Terminal
from xnano.terminal._opening import OpeningTerminal
from xnano.terminal._screen import attach_screen_async
async def open_terminal() -> Terminal[DepsT, StateT]:
await attach_screen_async(
self, title=title, width=width, height=height, settings=settings
)
assert isinstance(self, Terminal)
# async def hooks run on the loop the terminal was opened in.
self._event_loop = running_loop()
return self
return OpeningTerminal(open_terminal)
close
¶
close(*, raise_failure: bool = True) -> None
Release everything the canvas holds, and give the screen back if it has one.
Closing twice is harmless. Leaving a with block closes the canvas, unless it is
part of another canvas or was created inside another canvas's with block: then it
stays usable and closes with that canvas. Closing a canvas closes the canvases created
inside its block that were not written anywhere. Closing a canvas that was written into
another one takes it off and leaves that one running.
Parameters:
-
raise_failure(bool, default:True) –Whether to raise the error a callback raised on the loop, which stopped the canvas. A
withblock passesFalsewhile another error is already propagating.
Raises:
-
TerminalError–A callback raised on the canvas's loop, or the loop would not stop.
Source code in xnano/canvas.py
def close(self, *, raise_failure: bool = True) -> None:
"""
Release everything the canvas holds, and give the screen back if it has one.
Closing twice is harmless. Leaving a ``with`` block closes the canvas, unless it is
part of another canvas or was created inside another canvas's ``with`` block: then it
stays usable and closes with that canvas. Closing a canvas closes the canvases created
inside its block that were not written anywhere. Closing a canvas that was written into
another one takes it off and leaves that one running.
Args:
raise_failure: Whether to raise the error a callback raised on the loop, which
stopped the canvas. A ``with`` block passes ``False`` while another error is
already propagating.
Raises:
TerminalError: A callback raised on the canvas's loop, or the loop would not stop.
"""
self._close_nested_canvases()
if self._canvas is not self:
if not self._is_closed:
self._is_closed = True
root = self._canvas
closing: list[Canvas[object, object]] = [
cast('Canvas[object, object]', self)
]
with root._lock:
# A canvas written into this one is part of it, so it ends with it.
closing.extend(
inner
for inner in list(root._children)
if inner is not self
and inner._is_inside(cast('Canvas[object, object]', self))
)
for canvas in closing:
canvas._is_closed = True
if canvas in root._children:
root._children.remove(canvas)
placement = self._parent_placement
if placement is not None and not root.is_closed:
for canvas in closing:
root._host.post(canvas._cancel_hooks)
placement.remove()
if _current_canvas() is self:
_active_canvas.set(self._previous_chain)
return
if not self._stop_requested.is_set() or not self._is_finalized:
host = getattr(self, '_host', None)
if host is not None:
host.require_closable()
self._stop_requested.set()
try:
if host is not None:
host.shutdown()
finally:
self._finalize()
if _current_canvas() is self:
_active_canvas.set(self._previous_chain)
failure = self._failure
if failure is not None and raise_failure and not self._is_failure_reported:
self._failure = None
raise TerminalError(
self._failure_text(failure), code='canvas.callback'
) from failure
close_async
async
¶
close_async(*, raise_failure: bool = True) -> None
Close the canvas like close, awaiting its loop's end.
A canvas that runs by itself (on the screen, or realtime=True) stops its loop while
your event loop goes on running other tasks; a canvas with a manual clock closes at
once. Leaving an async with block calls this.
Parameters:
-
raise_failure(bool, default:True) –Whether to raise the error a callback raised on the loop, which stopped the canvas. An
async withblock passesFalsewhile another error is already propagating.
Raises:
-
TerminalError–A callback raised on the canvas's loop, or the loop would not stop.
Examples:
import asyncio
import xnano
async def main() -> None:
canvas = xnano.new(realtime=True, width=8, height=1)
canvas.screen.write('hello')
await canvas.close_async()
assert canvas.is_closed
asyncio.run(main())
Source code in xnano/canvas.py
async def close_async(self, *, raise_failure: bool = True) -> None:
"""
Close the canvas like [`close`][xnano.canvas.Canvas.close], awaiting its loop's end.
A canvas that runs by itself (on the screen, or ``realtime=True``) stops its loop while
your event loop goes on running other tasks; a canvas with a manual clock closes at
once. Leaving an ``async with`` block calls this.
Args:
raise_failure: Whether to raise the error a callback raised on the loop, which
stopped the canvas. An ``async with`` block passes ``False`` while another
error is already propagating.
Raises:
TerminalError: A callback raised on the canvas's loop, or the loop would not stop.
Examples:
```python
import asyncio
import xnano
async def main() -> None:
canvas = xnano.new(realtime=True, width=8, height=1)
canvas.screen.write('hello')
await canvas.close_async()
assert canvas.is_closed
asyncio.run(main())
```
"""
host = getattr(self, '_host', None)
if self._canvas is self and not self._is_closed and isinstance(host, _ThreadHost):
await host.stop_async()
self.close(raise_failure=raise_failure)
wait_for_tasks_async
async
¶
Wait until every run of the canvas's async def hooks has finished.
Runs that start while this waits are waited for too. Use it in an async program before reading what the hooks changed, and in tests instead of sleeping.
Raises:
-
TerminalError–A run raised, which ends the canvas the way a failing plain hook does.
Examples:
import asyncio
import xnano
from xnano.events import Event
async def main() -> None:
async with xnano.new(width=20, height=1) as canvas:
label = canvas.screen.write('...')
@canvas.hook(on='key', keys='enter')
async def answer(context: xnano.Context) -> None:
await asyncio.sleep(0.01)
label.text = 'done'
canvas.push(Event.key_press('enter'))
canvas.clock.step()
await canvas.wait_for_tasks_async()
assert canvas.screen.render() == 'done'
asyncio.run(main())
Source code in xnano/canvas.py
async def wait_for_tasks_async(self) -> None:
"""
Wait until every run of the canvas's ``async def`` hooks has finished.
Runs that start while this waits are waited for too. Use it in an async program
before reading what the hooks changed, and in tests instead of sleeping.
Raises:
TerminalError: A run raised, which ends the canvas the way a failing plain hook
does.
Examples:
```python
import asyncio
import xnano
from xnano.events import Event
async def main() -> None:
async with xnano.new(width=20, height=1) as canvas:
label = canvas.screen.write('...')
@canvas.hook(on='key', keys='enter')
async def answer(context: xnano.Context) -> None:
await asyncio.sleep(0.01)
label.text = 'done'
canvas.push(Event.key_press('enter'))
canvas.clock.step()
await canvas.wait_for_tasks_async()
assert canvas.screen.render() == 'done'
asyncio.run(main())
```
"""
canvas = self._canvas
tasks = canvas._tasks
if tasks is not None:
await tasks.idle.wait_async()
if canvas._host.is_autonomous:
canvas._raise_run_failure()
else:
canvas._raise_failure()
__or__
¶
__or__(other: ContextualOperation[DepsT, StateT]) -> Self
Attach a hook operation, such as one from xnano.hook(), with canvas | operation.
Raises:
-
TypeError–otherdraws instead of listening: draw it on the screen, withcanvas.screen | operation.
Source code in xnano/canvas.py
def __or__(self, other: ContextualOperation[DepsT, StateT]) -> Self:
"""
Attach a hook operation, such as one from ``xnano.hook()``, with ``canvas | operation``.
Raises:
TypeError: ``other`` draws instead of listening: draw it on the screen, with
``canvas.screen | operation``.
"""
if not isinstance(other, ContextualOperation):
raise TypeError(
f'canvas | ... attaches hooks, such as canvas | xnano.hook(...), but '
f'{type(other).__name__} draws on the cells. Draw it on the screen: '
f'canvas.screen | operation.'
)
cast('ContextualOperation[DepsT, StateT]', other).apply_to(self)
return self
__ior__
¶
__ior__(other: ContextualOperation[DepsT, StateT]) -> Self
evaluate
¶
evaluate(expression: Expression[ValueT]) -> ValueT
Evaluate an expression against the canvas and return its value.
Parameters:
-
expression(Expression[ValueT]) –Any expression, such as
Width,TimeElapsed % 1orcanvas.microphone.level.
Examples:
import xnano
from xnano_core import Width
with xnano.new(width=12, height=2) as canvas:
assert canvas.evaluate(Width) == 12
Source code in xnano/canvas.py
def evaluate(self, expression: _core.Expression[ValueT]) -> ValueT:
"""
Evaluate an expression against the canvas and return its value.
Args:
expression: Any expression, such as ``Width``, ``TimeElapsed % 1`` or
``canvas.microphone.level``.
Examples:
```python
import xnano
from xnano_core import Width
with xnano.new(width=12, height=2) as canvas:
assert canvas.evaluate(Width) == 12
```
"""
self._require_open()
return self._canvas._host.call(lambda: self._root.inspect(expression))
iter
¶
iter(*, frames: int | None = None, seconds: float | None = None, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c') -> Iterator[Frame]
Run the canvas one frame at a time: iterate over its frames, drawing between them.
Each iteration yields a Frame with the events that reached
the canvas since the previous one in frame.events, and whatever you change before
asking for the next frame is drawn. On a canvas from new() each iteration moves
the clock by one frame of its fps, so the same loop produces the same frames every
run, as fast as your code; a canvas that runs by itself (on the screen, or
realtime=True) draws as you declare, so there this paces your code at its fps:
if you are slow, frames are skipped rather than queued.
Without frames or seconds it runs the way run
does: until a key of stop_on is pressed, the canvas is asked to
stop or closes, or you break out of the loop. With
them, it also ends after that many frames, or when the canvas's time has run that
long, whichever comes first. pause freezes the time it
follows: the iterations go on drawing and hooks still run, but the clock stands still
until resume.
Parameters:
-
frames(int | None, default:None) –The most frames to yield.
-
seconds(float | None, default:None) –The most seconds of the canvas's time to run for.
-
stop_on(KeyName | Sequence[KeyName] | None, default:'ctrl+c') –The key, or keys, that end the loop and stop the canvas, such as
'q';Nonefor none.
Raises:
-
TerminalError–secondswithoutframeson a stopped canvas, which would never reach the end. -
TerminalClosedError–The canvas is closed.
Examples:
import xnano
from xnano.events import Event
with xnano.new(width=8, height=1, fps=10) as canvas:
pressed = []
for frame in canvas.iter(frames=3):
pressed.extend(event.key.key for event in frame.events)
if frame.index == 0:
canvas.push(Event.key_press('a'))
assert [frame.index for frame in canvas.iter(frames=2)] == [3, 4]
assert pressed == ['a']
Source code in xnano/canvas.py
def iter(
self,
*,
frames: int | None = None,
seconds: float | None = None,
stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c',
) -> Iterator[Frame]:
"""
Run the canvas one frame at a time: iterate over its frames, drawing between them.
Each iteration yields a [`Frame`][xnano.hooks.Frame] with the events that reached
the canvas since the previous one in ``frame.events``, and whatever you change before
asking for the next frame is drawn. On a canvas from ``new()`` each iteration moves
the clock by one frame of its ``fps``, so the same loop produces the same frames every
run, as fast as your code; a canvas that runs by itself (on the screen, or
``realtime=True``) draws as you declare, so there this paces your code at its ``fps``:
if you are slow, frames are skipped rather than queued.
Without ``frames`` or ``seconds`` it runs the way [`run`][xnano.canvas.Canvas.run]
does: until a key of ``stop_on`` is pressed, the canvas is asked to
[`stop`][xnano.canvas.Canvas.stop] or closes, or you break out of the loop. With
them, it also ends after that many frames, or when the canvas's time has run that
long, whichever comes first. [`pause`][xnano.devices.Clock.pause] freezes the time it
follows: the iterations go on drawing and hooks still run, but the clock stands still
until [`resume`][xnano.devices.Clock.resume].
Args:
frames: The most frames to yield.
seconds: The most seconds of the canvas's time to run for.
stop_on: The key, or keys, that end the loop and stop the canvas, such as
``'q'``; ``None`` for none.
Raises:
TerminalError: ``seconds`` without ``frames`` on a stopped canvas, which would
never reach the end.
TerminalClosedError: The canvas is closed.
Examples:
```python
import xnano
from xnano.events import Event
with xnano.new(width=8, height=1, fps=10) as canvas:
pressed = []
for frame in canvas.iter(frames=3):
pressed.extend(event.key.key for event in frame.events)
if frame.index == 0:
canvas.push(Event.key_press('a'))
assert [frame.index for frame in canvas.iter(frames=2)] == [3, 4]
assert pressed == ['a']
```
"""
canvas = self._check_iteration(frames, seconds)
return canvas._frames(frames, seconds, _parse_stop_keys(stop_on))
iter_async
¶
iter_async(*, frames: int | None = None, seconds: float | None = None, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c') -> AsyncIterator[Frame]
Run the canvas one frame at a time with async for, like iter.
The frames, the keywords and the ways the iteration ends are the ones iter()
has. Between frames, a canvas that runs by itself waits for the next one with
await, so the rest of your event loop runs meanwhile; a canvas from new()
moves its clock at once and lets other tasks run before the next frame.
Parameters:
-
frames(int | None, default:None) –The most frames to yield.
-
seconds(float | None, default:None) –The most seconds of the canvas's time to run for.
-
stop_on(KeyName | Sequence[KeyName] | None, default:'ctrl+c') –The key, or keys, that end the loop and stop the canvas;
Nonefor none.
Raises:
-
TerminalError–secondswithoutframeson a stopped canvas, which would never reach the end. -
TerminalClosedError–The canvas is closed.
Examples:
import asyncio
import xnano
async def main() -> None:
async with xnano.new(width=8, height=1, fps=10) as canvas:
frames = [frame async for frame in canvas.iter_async(frames=3)]
assert [frame.elapsed_seconds for frame in frames] == [0.0, 0.1, 0.2]
asyncio.run(main())
Source code in xnano/canvas.py
def iter_async(
self,
*,
frames: int | None = None,
seconds: float | None = None,
stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c',
) -> AsyncIterator[Frame]:
"""
Run the canvas one frame at a time with ``async for``, like [`iter`][xnano.canvas.Canvas.iter].
The frames, the keywords and the ways the iteration ends are the ones ``iter()``
has. Between frames, a canvas that runs by itself waits for the next one with
``await``, so the rest of your event loop runs meanwhile; a canvas from ``new()``
moves its clock at once and lets other tasks run before the next frame.
Args:
frames: The most frames to yield.
seconds: The most seconds of the canvas's time to run for.
stop_on: The key, or keys, that end the loop and stop the canvas; ``None`` for
none.
Raises:
TerminalError: ``seconds`` without ``frames`` on a stopped canvas, which would
never reach the end.
TerminalClosedError: The canvas is closed.
Examples:
```python
import asyncio
import xnano
async def main() -> None:
async with xnano.new(width=8, height=1, fps=10) as canvas:
frames = [frame async for frame in canvas.iter_async(frames=3)]
assert [frame.elapsed_seconds for frame in frames] == [0.0, 0.1, 0.2]
asyncio.run(main())
```
"""
canvas = self._check_iteration(frames, seconds)
return canvas._frames_async(frames, seconds, _parse_stop_keys(stop_on))
deliver_events
¶
Deliver pushed events to their hooks and draw a frame, without moving time.
Events pushed with push reach their hooks at the
canvas's next step; this is that step on a canvas whose clock you move. A canvas that
runs by itself delivers them on its own.
Examples:
import xnano
from xnano_core import Event
with xnano.new(width=8, height=1) as canvas:
heard = []
canvas.hook(lambda context: heard.append(context.event.kind))
canvas.push(Event.custom('ping'))
canvas.deliver_events()
assert heard == ['custom']
assert canvas.clock.elapsed_seconds == 0.0
Source code in xnano/canvas.py
def deliver_events(self) -> None:
"""
Deliver pushed events to their hooks and draw a frame, without moving time.
Events pushed with [`push`][xnano.canvas.Canvas.push] reach their hooks at the
canvas's next step; this is that step on a canvas whose clock you move. A canvas that
runs by itself delivers them on its own.
Examples:
```python
import xnano
from xnano_core import Event
with xnano.new(width=8, height=1) as canvas:
heard = []
canvas.hook(lambda context: heard.append(context.event.kind))
canvas.push(Event.custom('ping'))
canvas.deliver_events()
assert heard == ['custom']
assert canvas.clock.elapsed_seconds == 0.0
```
"""
self._require_own_presence()
canvas = self._canvas
canvas._require_open()
if canvas._host.is_autonomous:
canvas._host.call(lambda: canvas._runtime.request_frame())
return
canvas._raise_failure()
canvas._runtime.step()
canvas._pushed_pointer = None
canvas._raise_failure()
stop
¶
Ask the canvas's loop to end.
Safe from any thread, including from a hook. A running iter(), run(),
keyboard.wait() or keyboard.prompt() ends. On a canvas from new() the canvas stays
open for writing and rendering; on a canvas that runs by itself (realtime=True, or
on the screen) the loop ends and the canvas closes.
Source code in xnano/canvas.py
def stop(self) -> None:
"""
Ask the canvas's loop to end.
Safe from any thread, including from a hook. A running ``iter()``, ``run()``,
``keyboard.wait()`` or ``keyboard.prompt()`` ends. On a canvas from ``new()`` the canvas stays
open for writing and rendering; on a canvas that runs by itself (``realtime=True``, or
on the screen) the loop ends and the canvas closes.
"""
self._require_own_presence()
canvas = self._canvas
canvas._stop_requested.set()
if not canvas._is_closed and canvas._host.is_autonomous:
canvas._host.post(lambda: canvas._stop_runtime())
run
¶
Wait until the canvas's loop ends.
A canvas that runs by itself draws and listens on its own, so this only keeps your
program alive until a stop key is pressed, or something calls
stop (a hook, another thread). Declare what you want
before calling it.
Parameters:
-
stop_on(KeyName | Sequence[KeyName] | None, default:'ctrl+c') –The key, or keys, that end the loop, such as
'q'or('q', 'escape').'ctrl+c'by default; giveNoneto leave ending to your own code.
Raises:
-
TerminalError–A callback raised on the canvas's loop, or the canvas has a clock that only moves when you move it, so waiting would never end.
Source code in xnano/canvas.py
def run(self, *, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c') -> None:
"""
Wait until the canvas's loop ends.
A canvas that runs by itself draws and listens on its own, so this only keeps your
program alive until a stop key is pressed, or something calls
[`stop`][xnano.canvas.Canvas.stop] (a hook, another thread). Declare what you want
before calling it.
Args:
stop_on: The key, or keys, that end the loop, such as ``'q'`` or
``('q', 'escape')``. ``'ctrl+c'`` by default; give ``None`` to leave ending
to your own code.
Raises:
TerminalError: A callback raised on the canvas's loop, or the canvas has a clock
that only moves when you move it, so waiting would never end.
"""
canvas = self._canvas
host = canvas._prepare_run(stop_on, 'run()')
try:
while not host.wait(0.1):
pass
except KeyboardInterrupt:
canvas.stop()
raise
canvas._raise_run_failure()
run_async
async
¶
Wait until the canvas's loop ends, like run, with await.
Your event loop goes on running other tasks meanwhile. Cancelling the waiting task
asks the canvas to stop.
Parameters:
-
stop_on(KeyName | Sequence[KeyName] | None, default:'ctrl+c') –The key, or keys, that end the loop, such as
'q'or('q', 'escape').'ctrl+c'by default; giveNoneto leave ending to your own code.
Raises:
-
TerminalError–A callback raised on the canvas's loop, or the canvas has a clock that only moves when you move it, so waiting would never end.
Examples:
import asyncio
import xnano
async def main() -> None:
async with xnano.new(realtime=True, width=20, height=1) as canvas:
canvas.screen.write('working...')
@canvas.hook(on='tick', after=0.05)
def finish(context: xnano.Context) -> None:
context.canvas.stop()
await canvas.run_async()
asyncio.run(main())
Source code in xnano/canvas.py
async def run_async(
self, *, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c'
) -> None:
"""
Wait until the canvas's loop ends, like [`run`][xnano.canvas.Canvas.run], with ``await``.
Your event loop goes on running other tasks meanwhile. Cancelling the waiting task
asks the canvas to [`stop`][xnano.canvas.Canvas.stop].
Args:
stop_on: The key, or keys, that end the loop, such as ``'q'`` or
``('q', 'escape')``. ``'ctrl+c'`` by default; give ``None`` to leave ending
to your own code.
Raises:
TerminalError: A callback raised on the canvas's loop, or the canvas has a clock
that only moves when you move it, so waiting would never end.
Examples:
```python
import asyncio
import xnano
async def main() -> None:
async with xnano.new(realtime=True, width=20, height=1) as canvas:
canvas.screen.write('working...')
@canvas.hook(on='tick', after=0.05)
def finish(context: xnano.Context) -> None:
context.canvas.stop()
await canvas.run_async()
asyncio.run(main())
```
"""
import asyncio
canvas = self._canvas
host = canvas._prepare_run(stop_on, 'run_async()')
try:
await host.wait_async()
except asyncio.CancelledError:
canvas.stop()
raise
canvas._raise_run_failure()
push
¶
push(event: Event) -> None
Deliver an event to the canvas as if it had been typed, clicked or reported.
Hooks hear it the same way as input from the keyboard and mouse, at the canvas's
next step, whatever the terminal settings say. Build events with
Event; Event.custom(name, data=...) makes one of your own.
Parameters:
-
event(Event) –The event to deliver.
Raises:
Examples:
import xnano
from xnano_core import Event
with xnano.new(width=8, height=1) as canvas:
heard = []
canvas.hook(
lambda context: heard.append(context.event.custom_name),
on='volume_changed',
)
canvas.push(Event.custom('volume_changed'))
canvas.deliver_events()
assert heard == ['volume_changed']
Source code in xnano/canvas.py
def push(self, event: _core.Event) -> None:
"""
Deliver an event to the canvas as if it had been typed, clicked or reported.
Hooks hear it the same way as input from the keyboard and mouse, at the canvas's
next step, whatever the terminal settings say. Build events with
[`Event`][xnano_core.Event]; ``Event.custom(name, data=...)`` makes one of your own.
Args:
event: The event to deliver.
Raises:
TypeError: The value is not an [`Event`][xnano_core.Event].
Examples:
```python
import xnano
from xnano_core import Event
with xnano.new(width=8, height=1) as canvas:
heard = []
canvas.hook(
lambda context: heard.append(context.event.custom_name),
on='volume_changed',
)
canvas.push(Event.custom('volume_changed'))
canvas.deliver_events()
assert heard == ['volume_changed']
```
"""
if not isinstance(event, _core.Event):
raise TypeError(
f'push() takes an Event such as xnano_core.Event.custom("ping"), but got '
f'{event!r}. To press a key, push xnano_core.Event.key_press("q"), or call '
f'context.keyboard.press("q") inside a hook.'
)
self._require_own_presence()
canvas = self._canvas
canvas._require_open()
canvas._host.post(lambda: canvas._runtime.inject(event))
state_reference
¶
state_reference(reader: Callable[[StateT], ValueT]) -> StateReference[ValueT]
A core reference for one field of the canvas's state.
The reference can be used as an axis, a range bound or a widget parameter.
Parameters:
-
reader(Callable[[StateT], ValueT]) –A function or lambda that reads the field, such as
lambda state: state.volume.
Raises:
-
TypeError–readeris not a function. -
TerminalError–The canvas was created without
state.
Source code in xnano/canvas.py
def state_reference(
self, reader: Callable[[StateT], ValueT]
) -> _core.StateReference[ValueT]:
"""
A core reference for one field of the canvas's state.
The reference can be used as an axis, a range bound or a widget parameter.
Args:
reader: A function or lambda that reads the field, such as
``lambda state: state.volume``.
Raises:
TypeError: ``reader`` is not a function.
TerminalError: The canvas was created without ``state``.
"""
if not callable(reader):
raise TypeError(
f'state_reference() takes a function that reads one field, but got '
f'{reader!r}. Pass a function such as lambda state: state.volume.'
)
store = self._canvas._state_store
if store is None:
raise TerminalError(
'This canvas has no state, so state_reference() has nothing to read. Create it with '
'xnano.new(state=YourDataclass()).'
)
return _reference_for(store, reader)
Color
¶
A terminal color: a named palette color, a palette index or a true color.
Maps to ratatui::style::Color.
Parameters:
-
value(ColorName | str | tuple[int, int, int]) –A color name such as
'red'or'light_blue', a hex string such as'#ff8800', a palette index string such as'4', or a(red, green, blue)tuple.
Attributes:
-
black(Color) –The black terminal color.
-
red(Color) –The red terminal color.
-
green(Color) –The green terminal color.
-
yellow(Color) –The yellow terminal color.
-
blue(Color) –The blue terminal color.
-
magenta(Color) –The magenta terminal color.
-
cyan(Color) –The cyan terminal color.
-
gray(Color) –The gray terminal color.
-
dark_gray(Color) –The dark gray terminal color.
-
light_red(Color) –The light red terminal color.
-
light_green(Color) –The light green terminal color.
-
light_yellow(Color) –The light yellow terminal color.
-
light_blue(Color) –The light blue terminal color.
-
light_magenta(Color) –The light magenta terminal color.
-
light_cyan(Color) –The light cyan terminal color.
-
white(Color) –The white terminal color.
-
reset(Color) –The reset terminal color, which follows the terminal theme.
-
is_reset(bool) –Whether this is the
resetcolor.
Raises:
-
ValueError–valueis not a recognized color.
Examples:
assert Color('#ff8800').to_rgb() == (255, 136, 0)
assert Color((1, 2, 3)) == Color.from_rgb(1, 2, 3)
assert Color('red').to_rgb() is None
Create a Color.
Parameters:
-
API Reference
- xnano
-
xnano_core
-
xnano_core -
xnano_core._xnano_core
_xnano_core -
xnano_core._xnano_core._core_types
_core_types
-
-
API Reference
- xnano
-
xnano_core
-
xnano_core -
xnano_core._xnano_core
_xnano_core
-
Methods:
-
parse–Parse a color name, hex string or palette index string.
-
from_tailwind–A true color from a Tailwind palette and shade.
-
indexed–A color from the 256-color palette.
-
from_rgb–A true color from red, green and blue values between 0 and 255.
-
to_rgb–The
(red, green, blue)values of a true color, orNonefor named and indexed colors. -
to_hex–The color as a
'#rrggbb'string. -
from_hsl–A true color from hue, saturation and lightness.
-
from_hsv–A true color from hue, saturation and value.
-
random–A random true color, or a random shade of
base. -
to_hsl–The hue (degrees), saturation and lightness (percentages) of the color.
-
to_hsv–The hue (degrees), saturation and value (percentages) of the color.
-
lerp–The color between this one and
other. -
lighten–A lighter color for a positive
amount, a darker one for a negativeamount. -
darken–A darker color.
-
inverse–The color that has each red, green and blue channel inverted.
-
saturate–The color with its saturation scaled.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
is_reset
property
¶
is_reset: bool
Whether this is the reset color, which follows the terminal's theme.
parse
classmethod
¶
Parse a color name, hex string or palette index string.
Examples:
from_tailwind
classmethod
¶
from_tailwind(palette: TailwindColorName, shade: TailwindColorShade) -> Color
A true color from a Tailwind palette and shade.
Color does not read a name such as 'slate-400'. Pass the palette and the
shade here.
Parameters:
-
palette(TailwindColorName) –A palette such as
'slate'or'red'. -
shade(TailwindColorShade) –50,100through900, or950.
Raises:
-
ValueError–paletteis not a palette, orshadeis not a shade.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def from_tailwind(
cls, palette: TailwindColorName, shade: TailwindColorShade
) -> Color:
"""
A true color from a Tailwind palette and shade.
``Color`` does not read a name such as ``'slate-400'``. Pass the palette and the
shade here.
Args:
palette: A palette such as ``'slate'`` or ``'red'``.
shade: ``50``, ``100`` through ``900``, or ``950``.
Raises:
ValueError: ``palette`` is not a palette, or ``shade`` is not a shade.
Examples:
```python
assert Color.from_tailwind('red', 500).to_rgb() == (239, 68, 68)
```
"""
indexed
classmethod
¶
A color from the 256-color palette.
Examples:
from_rgb
classmethod
¶
A true color from red, green and blue values between 0 and 255.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
to_rgb
¶
The (red, green, blue) values of a true color, or None for named and indexed colors.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
to_hex
¶
to_hex() -> str
The color as a '#rrggbb' string.
Only a true color has one, as with to_rgb.
Raises:
-
ValueError–The color is named, indexed or
reset, which the terminal's theme chooses.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def to_hex(self) -> str:
"""
The color as a ``'#rrggbb'`` string.
Only a true color has one, as with [`to_rgb`][xnano_core._xnano_core.Color.to_rgb].
Raises:
ValueError: The color is named, indexed or ``reset``, which the terminal's theme
chooses.
Examples:
```python
assert Color((255, 136, 0)).to_hex() == '#ff8800'
assert Color('#FF8800').to_hex() == '#ff8800'
```
"""
from_hsl
classmethod
¶
A true color from hue, saturation and lightness.
Parameters:
-
hue(float) –Degrees from 0 to 360.
-
saturation(float) –A percentage from 0 to 100.
-
lightness(float) –A percentage from 0 to 100.
Raises:
-
ValueError–A value is out of range.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def from_hsl(cls, hue: float, saturation: float, lightness: float) -> Color:
"""
A true color from hue, saturation and lightness.
Args:
hue: Degrees from 0 to 360.
saturation: A percentage from 0 to 100.
lightness: A percentage from 0 to 100.
Raises:
ValueError: A value is out of range.
Examples:
```python
assert Color.from_hsl(0, 100, 50).to_hex() == '#ff0000'
```
"""
from_hsv
classmethod
¶
A true color from hue, saturation and value.
Parameters:
-
hue(float) –Degrees from 0 to 360.
-
saturation(float) –A percentage from 0 to 100.
-
value(float) –A percentage from 0 to 100.
Raises:
-
ValueError–A value is out of range.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def from_hsv(cls, hue: float, saturation: float, value: float) -> Color:
"""
A true color from hue, saturation and value.
Args:
hue: Degrees from 0 to 360.
saturation: A percentage from 0 to 100.
value: A percentage from 0 to 100.
Raises:
ValueError: A value is out of range.
Examples:
```python
assert Color.from_hsv(120, 100, 100).to_hex() == '#00ff00'
```
"""
random
classmethod
¶
A random true color, or a random shade of base.
Without base every red, green and blue channel is picked at random. With base
the color keeps its hue and saturation and takes a random lightness from 15 to 85
percent, so every color it returns is a lighter or darker shade of base. The
colors come from Python's random
module, so random.seed(...) repeats them.
Parameters:
-
base(Color | ColorName | str | tuple[int, int, int] | None, default:None) –The color to pick shades of, or
Nonefor any color.
Raises:
-
ValueError–baseisColor.reset, or not a color.
Examples:
import random
random.seed(7)
first = Color.random()
random.seed(7)
assert Color.random() == first
hue, saturation, _ = Color.random('#3366cc').to_hsl()
assert round(hue) == 220 and round(saturation) == 60
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def random(
cls, base: Color | ColorName | str | tuple[int, int, int] | None = None
) -> Color:
"""
A random true color, or a random shade of ``base``.
Without ``base`` every red, green and blue channel is picked at random. With ``base``
the color keeps its hue and saturation and takes a random lightness from 15 to 85
percent, so every color it returns is a lighter or darker shade of ``base``. The
colors come from Python's [`random`](https://docs.python.org/3/library/random.html)
module, so ``random.seed(...)`` repeats them.
Args:
base: The color to pick shades of, or ``None`` for any color.
Raises:
ValueError: ``base`` is ``Color.reset``, or not a color.
Examples:
```python
import random
random.seed(7)
first = Color.random()
random.seed(7)
assert Color.random() == first
hue, saturation, _ = Color.random('#3366cc').to_hsl()
assert round(hue) == 220 and round(saturation) == 60
```
"""
to_hsl
¶
The hue (degrees), saturation and lightness (percentages) of the color.
Named and indexed colors use their standard values.
Raises:
-
ValueError–The color is
reset.
Examples:
hue, saturation, lightness = Color('#ff0000').to_hsl()
assert round(hue) == 0
assert round(saturation) == 100
assert round(lightness) == 50
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def to_hsl(self) -> tuple[float, float, float]:
"""
The hue (degrees), saturation and lightness (percentages) of the color.
Named and indexed colors use their standard values.
Raises:
ValueError: The color is ``reset``.
Examples:
```python
hue, saturation, lightness = Color('#ff0000').to_hsl()
assert round(hue) == 0
assert round(saturation) == 100
assert round(lightness) == 50
```
"""
to_hsv
¶
The hue (degrees), saturation and value (percentages) of the color.
Named and indexed colors use their standard values.
Raises:
-
ValueError–The color is
reset.
Examples:
hue, saturation, value = Color('#00ff00').to_hsv()
assert round(hue) == 120
assert round(saturation) == 100
assert round(value) == 100
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def to_hsv(self) -> tuple[float, float, float]:
"""
The hue (degrees), saturation and value (percentages) of the color.
Named and indexed colors use their standard values.
Raises:
ValueError: The color is ``reset``.
Examples:
```python
hue, saturation, value = Color('#00ff00').to_hsv()
assert round(hue) == 120
assert round(saturation) == 100
assert round(value) == 100
```
"""
lerp
¶
lerp(other: Color | ColorName | str | tuple[int, int, int], ratio: float, *, color_space: Literal['rgb', 'hsl', 'hsv'] = 'hsl') -> Color
The color between this one and other.
Parameters:
-
other(Color | ColorName | str | tuple[int, int, int]) –The color to blend toward.
-
ratio(float) –0.0is this color and1.0isother. -
color_space(Literal['rgb', 'hsl', 'hsv'], default:'hsl') –The space the blend runs through.
'hsl'and'hsv'keep colors vivid in the middle;'rgb'is the straight average.
Raises:
-
ValueError–A color is
reset, orcolor_spaceis not a color space.
Examples:
middle = Color('#000000').lerp('#ffffff', 0.5, color_space='rgb')
red, green, blue = middle.to_rgb()
assert red == green == blue
assert 126 <= red <= 129
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def lerp(
self,
other: Color | ColorName | str | tuple[int, int, int],
ratio: float,
*,
color_space: Literal['rgb', 'hsl', 'hsv'] = 'hsl',
) -> Color:
"""
The color between this one and ``other``.
Args:
other: The color to blend toward.
ratio: ``0.0`` is this color and ``1.0`` is ``other``.
color_space: The space the blend runs through. ``'hsl'`` and ``'hsv'`` keep colors
vivid in the middle; ``'rgb'`` is the straight average.
Raises:
ValueError: A color is ``reset``, or ``color_space`` is not a color space.
Examples:
```python
middle = Color('#000000').lerp('#ffffff', 0.5, color_space='rgb')
red, green, blue = middle.to_rgb()
assert red == green == blue
assert 126 <= red <= 129
```
"""
lighten
¶
A lighter color for a positive amount, a darker one for a negative amount.
Parameters:
-
amount(float) –A fraction from -1.0 (black) to 1.0 (white).
-
color_space(Literal['rgb', 'hsl', 'hsv'], default:'hsl') –The space the change runs through.
Raises:
-
ValueError–The color is
reset, orcolor_spaceis not a color space.
Examples:
base = Color('#336699')
assert base.lighten(0.2).to_hsl()[2] > base.to_hsl()[2]
assert base.lighten(-0.2).to_hsl()[2] < base.to_hsl()[2]
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def lighten(
self, amount: float, *, color_space: Literal['rgb', 'hsl', 'hsv'] = 'hsl'
) -> Color:
"""
A lighter color for a positive ``amount``, a darker one for a negative ``amount``.
Args:
amount: A fraction from -1.0 (black) to 1.0 (white).
color_space: The space the change runs through.
Raises:
ValueError: The color is ``reset``, or ``color_space`` is not a color space.
Examples:
```python
base = Color('#336699')
assert base.lighten(0.2).to_hsl()[2] > base.to_hsl()[2]
assert base.lighten(-0.2).to_hsl()[2] < base.to_hsl()[2]
```
"""
darken
¶
A darker color.
Parameters:
-
amount(float) –A fraction from 0.0 (unchanged) to 1.0 (black). Use
lightento make a color lighter. -
color_space(Literal['rgb', 'hsl', 'hsv'], default:'hsl') –The space the change runs through.
Returns:
-
Color–The darkened color; the original is unchanged.
Raises:
-
ValueError–amountis outside 0.0 to 1.0, the color isreset, orcolor_spaceis not a color space.
Examples:
assert Color('#808080').darken(1.0).to_rgb() == (0, 0, 0)
base = Color('#336699')
assert base.darken(0.2).to_hsl()[2] < base.to_hsl()[2]
assert base.darken(0.0) == base
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def darken(
self, amount: float, *, color_space: Literal['rgb', 'hsl', 'hsv'] = 'hsl'
) -> Color:
"""
A darker color.
Args:
amount: A fraction from 0.0 (unchanged) to 1.0 (black). Use
[`lighten`][xnano_core._xnano_core.Color.lighten] to make a color lighter.
color_space: The space the change runs through.
Returns:
The darkened color; the original is unchanged.
Raises:
ValueError: ``amount`` is outside 0.0 to 1.0, the color is ``reset``, or
``color_space`` is not a color space.
Examples:
```python
assert Color('#808080').darken(1.0).to_rgb() == (0, 0, 0)
base = Color('#336699')
assert base.darken(0.2).to_hsl()[2] < base.to_hsl()[2]
assert base.darken(0.0) == base
```
"""
inverse
¶
inverse() -> Color
The color that has each red, green and blue channel inverted.
Named and indexed colors are inverted through their standard values, so the result is always a true color.
Returns:
-
Color–The inverted true color; the original is unchanged.
Raises:
-
ValueError–The color is
reset, which has no fixed value.
Examples:
assert Color('#ff8000').inverse().to_hex() == '#007fff'
assert Color('#ff8000').inverse().inverse() == Color('#ff8000')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def inverse(self) -> Color:
"""
The color that has each red, green and blue channel inverted.
Named and indexed colors are inverted through their standard values, so the result
is always a true color.
Returns:
The inverted true color; the original is unchanged.
Raises:
ValueError: The color is ``reset``, which has no fixed value.
Examples:
```python
assert Color('#ff8000').inverse().to_hex() == '#007fff'
assert Color('#ff8000').inverse().inverse() == Color('#ff8000')
```
"""
saturate
¶
The color with its saturation scaled.
Parameters:
-
factor(float) –0.0removes the saturation,1.0keeps it and more than1.0boosts it. -
color_space(Literal['rgb', 'hsl', 'hsv'], default:'hsl') –The space the change runs through.
Raises:
-
ValueError–The color is
reset, orcolor_spaceis not a color space.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def saturate(
self, factor: float, *, color_space: Literal['rgb', 'hsl', 'hsv'] = 'hsl'
) -> Color:
"""
The color with its saturation scaled.
Args:
factor: ``0.0`` removes the saturation, ``1.0`` keeps it and more than ``1.0``
boosts it.
color_space: The space the change runs through.
Raises:
ValueError: The color is ``reset``, or ``color_space`` is not a color space.
Examples:
```python
gray = Color('#336699').saturate(0.0)
assert round(gray.to_hsl()[1]) == 0
```
"""
load_image
¶
load_image(source: TerminalImage | PathLike[str] | str | bytes, /, *, x: Axis | None = None, y: Axis | None = None, width: Axis | None = None, height: Axis | None = None, layer: int = 0, lock: bool = False, fit: ImageFit | None = None, resampling_filter: ResamplingFilter | None = None, background: ColorValue = (0, 0, 0), speed: float = 1.0, symbol: str | None = None) -> Image
Load an image or an animation from a file path or from bytes.
This is Image with the same arguments: PNG, JPEG, GIF, WebP and XNI files
are read, and an animated one plays on the canvas's clock. Write the result with
canvas.screen.write(picture).
Parameters:
-
source(TerminalImage | PathLike[str] | str | bytes) –The path of an image file, the bytes of one, or a
TerminalImage. -
x(Axis | None, default:None) –The column of the left edge; see
Image. -
y(Axis | None, default:None) –The row of the top edge.
-
width(Axis | None, default:None) –The width: cells, a percentage, an expression, or
Nonefor the picture's own. -
height(Axis | None, default:None) –The height, in the same forms.
-
layer(int, default:0) –Content with a higher layer is drawn over content with a lower one.
-
lock(bool, default:False) –Keep the size the image has when it is added, whatever the canvas does.
-
fit(ImageFit | None, default:None) –How the picture sits in a box of
widthbyheight. -
resampling_filter(ResamplingFilter | None, default:None) –How pixels are blended when it is resized.
-
background(ColorValue, default:(0, 0, 0)) –The color of the margins around a picture with no transparent pixel, and the color partly transparent pixels are blended with.
-
speed(float, default:1.0) –How fast an animated image plays:
2.0is twice as fast. -
symbol(str | None, default:None) –A name to register the image under in
symbols.
Returns:
Raises:
-
ImportError–xnano-imageis not installed. Install it withpip install "xnano[image]". -
TypeError–sourceis not a path, bytes or an image. -
FileNotFoundError–The path does not exist.
Examples:
import xnano
from xnano_image import TerminalImage
picture = xnano.load_image(
TerminalImage.from_rgba(1, 1, bytes([255, 0, 0, 255])), width=4, symbol='red_dot'
)
assert isinstance(picture, xnano.Image)
assert xnano.symbols.lookup('red_dot') is picture
Source code in xnano/art/_images.py
def load_image(
source: TerminalImage | os.PathLike[str] | str | bytes,
/,
*,
x: Axis | None = None,
y: Axis | None = None,
width: Axis | None = None,
height: Axis | None = None,
layer: int = 0,
lock: bool = False,
fit: ImageFit | None = None,
resampling_filter: ResamplingFilter | None = None,
background: ColorValue = (0, 0, 0),
speed: float = 1.0,
symbol: str | None = None,
) -> Image:
"""
Load an image or an animation from a file path or from bytes.
This is [`Image`][xnano.Image] with the same arguments: PNG, JPEG, GIF, WebP and XNI files
are read, and an animated one plays on the canvas's clock. Write the result with
``canvas.screen.write(picture)``.
Args:
source: The path of an image file, the bytes of one, or a
[`TerminalImage`][xnano_image.TerminalImage].
x: The column of the left edge; see [`Image`][xnano.Image].
y: The row of the top edge.
width: The width: cells, a percentage, an expression, or ``None`` for the picture's own.
height: The height, in the same forms.
layer: Content with a higher layer is drawn over content with a lower one.
lock: Keep the size the image has when it is added, whatever the canvas does.
fit: How the picture sits in a box of ``width`` by ``height``.
resampling_filter: How pixels are blended when it is resized.
background: The color of the margins around a picture with no transparent pixel, and
the color partly transparent pixels are blended with.
speed: How fast an animated image plays: ``2.0`` is twice as fast.
symbol: A name to register the image under in [`symbols`][xnano.symbols].
Returns:
The [`Image`][xnano.Image].
Raises:
ImportError: ``xnano-image`` is not installed. Install it with
``pip install "xnano[image]"``.
TypeError: ``source`` is not a path, bytes or an image.
FileNotFoundError: The path does not exist.
Examples:
```python
import xnano
from xnano_image import TerminalImage
picture = xnano.load_image(
TerminalImage.from_rgba(1, 1, bytes([255, 0, 0, 255])), width=4, symbol='red_dot'
)
assert isinstance(picture, xnano.Image)
assert xnano.symbols.lookup('red_dot') is picture
```
"""
require('image', needed_for='xnano.load_image')
return Image(
source,
x=x,
y=y,
width=width,
height=height,
layer=layer,
lock=lock,
fit=fit,
resampling_filter=resampling_filter,
background=background,
speed=speed,
symbol=symbol,
)
pixel_art
¶
pixel_art(source: str | Sequence[str] | Image | TerminalImage | bytes | bytearray | None = None, palette: Mapping[str, ColorValue] | str | None = None, *, width: int | None = None, height: int | None = None, background: ColorValue | None = None, symbol: str | None = None, effects: Sequence[WritableEffectSpecification] = (), encoding: PixelEncoding = 'half_blocks', borders: bool = False) -> Art
Build pixel art from text, a picture, bytes or nothing (does not draw).
This is how pixel-art sprites are written in code, one character per pixel. Nothing is
drawn: the art is a value that you write into a canvas. Text rows (a multi-line string, which
may be indented, or a list of rows) are painted with a palette that says what each
character means; any character the palette does not name, such as '.', is a
transparent pixel. The palette is a mapping, or one string of character=color pairs.
What source is decides what is made:
- Text with a newline, or a list of rows: pixel art painted with
palette. - Text without a newline: the name of a registered art or image (see
symbols); you get a copy of the art, or the pixels of the image. A one-row picture is a list,pixel_art(['GG'], palette), so that a call never changes meaning because a symbol was registered later. - An
Imageor aTerminalImagefromxnano_image: its pixels are copied (the first frame of an animation). bytesof red, green, blue and alpha, withwidthandheight.None: a blank world ofwidthbyheightpixels filled withbackground.
Parameters:
-
source(str | Sequence[str] | Image | TerminalImage | bytes | bytearray | None, default:None) –What to draw.
-
palette(Mapping[str, ColorValue] | str | None, default:None) –The color of each character of text rows, as a mapping to names,
'#rrggbb'strings or(red, green, blue)tuples, or as a string such as'R=#e03040 G=green'. -
width(int | None, default:None) –The width in pixels of
bytesor of a blank world. -
height(int | None, default:None) –The height in pixels.
-
background(ColorValue | None, default:None) –The color behind the art. Transparent pixels show it.
-
symbol(str | None, default:None) –A name to register the art under, so
pixel_art('name')returns a copy of it. -
effects(Sequence[WritableEffectSpecification], default:()) –Effects to start on the placement when the art is written, as dictionaries with a
kindkey. -
encoding(PixelEncoding, default:'half_blocks') –How the pixels are packed into cells:
'half_blocks'(one column and two rows of pixels per cell) or'braille'(two by four, one colour per cell, for a finer, drawing-like look). -
borders(bool, default:False) –Whether to show one pixel per cell, with the edges between colours and against the background traced in box-drawing characters and the inside of each colour filled with it.
Raises:
-
ValueError–The rows are empty or differ in length, the palette or a color in it is not valid, a text without a newline is not a known symbol, the sizes do not match the bytes, or
encodingis not one of the two. -
TypeError–sourceis not one of the kinds above.
Examples:
import xnano
heart = xnano.pixel_art(
'''
.RR.RR.
RRRRRRR
.RRRRR.
..RRR..
...R...
''',
'R=#e03040',
)
assert (heart.width, heart.height) == (7, 5)
print(heart.render())
xnano.pixel_art(['G'], {'G': 'green'}, symbol='grass')
assert xnano.pixel_art('grass').width == 1
Source code in xnano/art/_worlds.py
def pixel_art(
source: str | Sequence[str] | Image | TerminalImage | bytes | bytearray | None = None,
palette: Mapping[str, ColorValue] | str | None = None,
*,
width: int | None = None,
height: int | None = None,
background: ColorValue | None = None,
symbol: str | None = None,
effects: Sequence[WritableEffectSpecification] = (),
encoding: PixelEncoding = 'half_blocks',
borders: bool = False,
) -> Art:
"""
Build pixel art from text, a picture, bytes or nothing (does not draw).
This is how pixel-art sprites are written in code, one character per pixel. Nothing is
drawn: the art is a value that you write into a canvas. Text rows (a multi-line string, which
may be indented, or a list of rows) are painted with a palette that says what each
character means; any character the palette does not name, such as ``'.'``, is a
transparent pixel. The palette is a mapping, or one string of ``character=color`` pairs.
What ``source`` is decides what is made:
* Text with a newline, or a list of rows: pixel art painted with ``palette``.
* Text without a newline: the name of a registered art or image (see
[`symbols`][xnano.symbols]); you get a copy of the art, or the pixels of the image.
A one-row picture is a list, ``pixel_art(['GG'], palette)``, so that a call never changes
meaning because a symbol was registered later.
* An [`Image`][xnano.Image] or a ``TerminalImage`` from ``xnano_image``: its pixels are copied
(the first frame of an animation).
* ``bytes`` of red, green, blue and alpha, with ``width`` and ``height``.
* ``None``: a blank world of ``width`` by ``height`` pixels filled with ``background``.
Args:
source: What to draw.
palette: The color of each character of text rows, as a mapping to names,
``'#rrggbb'`` strings or ``(red, green, blue)`` tuples, or as a string such as
``'R=#e03040 G=green'``.
width: The width in pixels of ``bytes`` or of a blank world.
height: The height in pixels.
background: The color behind the art. Transparent pixels show it.
symbol: A name to register the art under, so ``pixel_art('name')`` returns a copy of it.
effects: Effects to start on the placement when the art is written, as dictionaries
with a ``kind`` key.
encoding: How the pixels are packed into cells: ``'half_blocks'`` (one column and two
rows of pixels per cell) or ``'braille'`` (two by four, one colour per cell, for a
finer, drawing-like look).
borders: Whether to show one pixel per cell, with the edges between colours and
against the background traced in box-drawing characters and the inside of each
colour filled with it.
Raises:
ValueError: The rows are empty or differ in length, the palette or a color in it is
not valid, a text without a newline is not a known symbol, the sizes do not match
the bytes, or ``encoding`` is not one of the two.
TypeError: ``source`` is not one of the kinds above.
Examples:
```python
import xnano
heart = xnano.pixel_art(
'''
.RR.RR.
RRRRRRR
.RRRRR.
..RRR..
...R...
''',
'R=#e03040',
)
assert (heart.width, heart.height) == (7, 5)
print(heart.render())
xnano.pixel_art(['G'], {'G': 'green'}, symbol='grass')
assert xnano.pixel_art('grass').width == 1
```
"""
if isinstance(source, str) and '\n' not in source:
if source in symbols.names(kind=Image):
# The name of a registered image draws that image.
source = symbols.lookup(source, kind=Image)
if isinstance(source, str) and '\n' not in source:
try:
registered = symbols.lookup(source, kind=Art)
except ValueError as error:
raise ValueError(
f'{error} To draw a one-row picture, pass a list: pixel_art([{source!r}], '
f'palette).'
) from None
art = registered._copy()
if background is not None:
art.background = background
effects = cast(
'tuple[WritableEffectSpecification, ...]',
effect_sequence(effects, 'writable'),
)
if effects:
for effect in effects:
normalize_effect(effect, 'writable')
art._effects = effects
if symbol is not None:
symbols.register(symbol, art)
art._symbol = symbol
return art
rgba, pixel_width, pixel_height = _pixels_of(source, palette, width, height)
return Art(
rgba,
pixel_width,
pixel_height,
background=background,
symbol=symbol,
effects=effects,
encoding=encoding,
borders=borders,
)
load_audio
¶
Load audio from an audio file: its path, or its bytes.
WAV, MP3, FLAC, Ogg Vorbis and MP4/AAC files are read, and the format is recognised from
the content of the file, whatever its name. The whole file is decoded into mono audio.
Play the result with canvas.speaker.play(audio), or give it a symbol and play it
by name.
Parameters:
-
file(PathLike[str] | str | bytes) –The path of an audio file, or the bytes of one.
-
symbol(str | None, default:None) –A name to register the audio under in
symbols, soplay(name)plays it.
Returns:
Raises:
-
ImportError–xnano-audiois not installed. Install it withpip install "xnano[audio]". -
TypeError–fileis neither a path nor bytes. -
FileNotFoundError–No file exists at the path.
-
ValueError–The file is not a WAV, MP3, FLAC, Ogg Vorbis or MP4/AAC file that xnano can read, or
symbolcannot be a symbol name, or another kind of value already has it.
Examples:
import io
import wave
import xnano
data = io.BytesIO()
with wave.open(data, 'wb') as writer:
writer.setnchannels(1)
writer.setsampwidth(2)
writer.setframerate(8000)
writer.writeframes(bytes([0, 64]) * 800)
beep = xnano.load_audio(data.getvalue(), symbol='beep')
assert beep.duration_milliseconds == 100.0
with xnano.new(width=8, height=1) as canvas:
canvas.speaker.play('beep')
canvas.clock.step(delta_seconds=0.1)
assert canvas.speaker.render().peak > 0.0
Source code in xnano/audio/_audio.py
def load_audio(
file: os.PathLike[str] | str | bytes,
/,
*,
symbol: str | None = None,
) -> Audio:
"""
Load audio from an audio file: its path, or its bytes.
WAV, MP3, FLAC, Ogg Vorbis and MP4/AAC files are read, and the format is recognised from
the content of the file, whatever its name. The whole file is decoded into mono audio.
Play the result with ``canvas.speaker.play(audio)``, or give it a ``symbol`` and play it
by name.
Args:
file: The path of an audio file, or the bytes of one.
symbol: A name to register the audio under in [`symbols`][xnano.symbols], so
``play(name)`` plays it.
Returns:
The [`Audio`][xnano.Audio].
Raises:
ImportError: ``xnano-audio`` is not installed. Install it with
``pip install "xnano[audio]"``.
TypeError: ``file`` is neither a path nor bytes.
FileNotFoundError: No file exists at the path.
ValueError: The file is not a WAV, MP3, FLAC, Ogg Vorbis or MP4/AAC file that xnano
can read, or ``symbol`` cannot be a symbol name, or another kind of value
already has it.
Examples:
```python
import io
import wave
import xnano
data = io.BytesIO()
with wave.open(data, 'wb') as writer:
writer.setnchannels(1)
writer.setsampwidth(2)
writer.setframerate(8000)
writer.writeframes(bytes([0, 64]) * 800)
beep = xnano.load_audio(data.getvalue(), symbol='beep')
assert beep.duration_milliseconds == 100.0
with xnano.new(width=8, height=1) as canvas:
canvas.speaker.play('beep')
canvas.clock.step(delta_seconds=0.1)
assert canvas.speaker.render().peak > 0.0
```
"""
module = require('audio', needed_for='xnano.load_audio')
if isinstance(file, bytes):
terminal_sound = _decode_audio_bytes(module, file)
elif isinstance(file, (str, os.PathLike)):
path = pathlib.Path(file)
if not path.is_file():
raise FileNotFoundError(
f'load_audio could not load {str(path)!r}, because no audio file exists '
f'there. Check the path, or pass the bytes of the file.'
)
terminal_sound = _decode_audio_path(module, path)
else:
raise TypeError(
f'load_audio needs the path of an audio file or the bytes of one, but got '
f'{type(file).__name__}. Pass xnano.load_audio("song.mp3"); for samples use '
f'xnano.Audio.from_samples(), and for an xnano_audio.TerminalSound use '
f'xnano.Audio(terminal_sound).'
)
return Audio(terminal_sound, symbol=symbol)
play
¶
play(playable: PlaySource, /, **options: Unpack[PlayOptions]) -> PlayHandle
Play a note, a sound, a symbol name, a melody or a sequence of those.
The sound goes to the running canvas (see active); with no canvas
running it goes to this computer's sound output. On a canvas from new,
which has a clock you move, the sound is recorded and makes no noise: read it with
canvas.speaker.render().
A str is a symbol name first, so play('kick') plays the note or sound registered
with symbol='kick'. Any other str is a note name such as 'C#4', a frequency such
as '440hz' or melody text: notes separated by spaces, :2 holds a note for two
beats, rest is a silence, + joins a chord and | marks a bar, as in
'C4 E4 G4:2 rest C5+E5+G5'. A sequence plays one after another. An option replaces
the same value on a Note, so play(Note('C4'), instrument='violin')
plays the violin.
Parameters:
-
playable(PlaySource) –What to play.
-
**options(Unpack[PlayOptions], default:{}) –See
PlayOptions:instrument,velocity,effects,volume,pan,at_beatandbeats, the length in beats of a note name, a number or aNote.
Returns:
-
PlayHandle–A
PlayHandle.
Raises:
-
ImportError–xnano-audiois not installed. Install it withpip install "xnano[audio]". -
TerminalAudioUnavailableError–No canvas is running and this computer has no sound output device.
-
ValueError–An option is out of range, or a
stris neither a symbol, a note name nor melody text. The message lists the known sound symbols.
Examples:
import xnano
with xnano.new(width=8, height=1) as canvas:
xnano.play([xnano.Note('C4'), xnano.Note('E4'), xnano.Note('G4')])
canvas.clock.step(delta_seconds=1.5)
assert canvas.speaker.render().peak > 0.0
Source code in xnano/audio/_notes.py
def play(playable: PlaySource, /, **options: Unpack[PlayOptions]) -> PlayHandle:
"""
Play a note, a sound, a symbol name, a melody or a sequence of those.
The sound goes to the running canvas (see [`active`][xnano.active]); with no canvas
running it goes to this computer's sound output. On a canvas from [`new`][xnano.new],
which has a clock you move, the sound is recorded and makes no noise: read it with
``canvas.speaker.render()``.
A ``str`` is a symbol name first, so ``play('kick')`` plays the note or sound registered
with ``symbol='kick'``. Any other ``str`` is a note name such as ``'C#4'``, a frequency such
as ``'440hz'`` or melody text: notes separated by spaces, ``:2`` holds a note for two
beats, ``rest`` is a silence, ``+`` joins a chord and ``|`` marks a bar, as in
``'C4 E4 G4:2 rest C5+E5+G5'``. A sequence plays one after another. An option replaces
the same value on a [`Note`][xnano.Note], so ``play(Note('C4'), instrument='violin')``
plays the violin.
Args:
playable: What to play.
**options: See [`PlayOptions`][xnano.devices.PlayOptions]: ``instrument``, ``velocity``,
``effects``, ``volume``, ``pan``, ``at_beat`` and ``beats``, the length in beats
of a note name, a number or a ``Note``.
Returns:
A [`PlayHandle`][xnano.audio.PlayHandle].
Raises:
ImportError: ``xnano-audio`` is not installed. Install it with
``pip install "xnano[audio]"``.
TerminalAudioUnavailableError: No canvas is running and this computer has no sound
output device.
ValueError: An option is out of range, or a ``str`` is neither a symbol, a note name
nor melody text. The message lists the known sound symbols.
Examples:
```python
import xnano
with xnano.new(width=8, height=1) as canvas:
xnano.play([xnano.Note('C4'), xnano.Note('E4'), xnano.Note('G4')])
canvas.clock.step(delta_seconds=1.5)
assert canvas.speaker.render().peak > 0.0
```
"""
from xnano.canvas import active
canvas = active(is_required=False)
if canvas is not None:
return canvas.speaker.play(playable, **options)
return _default_player().play(playable, **options)
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
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
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,
)
playable
¶
playable(function: Callable[[], Playable]) -> PlayableFunction[[], None, None]
playable(function: Callable[Concatenate[Context[DepsT, StateT], ParametersT], Playable]) -> PlayableFunction[ParametersT, DepsT, StateT]
playable(function: Callable[Concatenate[Context[DepsT, StateT], ParametersT], Playable] | Callable[[], Playable]) -> PlayableFunction[ParametersT, DepsT, StateT] | PlayableFunction[[], None, None]
Turn a function into a component that plays itself.
The function takes the Context first, then its own parameters,
and returns anything canvas.play accepts; a function with no parameters at all is
called without the context. It is evaluated once when played, and again
on a beat only when it read something that changes (the time or the beat, a state path or
an input), playing the new result each time. canvas.play returns a
PlayHandle whose remove() stops it.
Parameters:
-
function(Callable[Concatenate[Context[DepsT, StateT], ParametersT], Playable] | Callable[[], Playable]) –The function
(context, **own_parameters) -> playable.
Raises:
-
TypeError–The decorated object is a class or is not callable, or the function's first parameter is keyword-only or variadic, so it cannot take the context.
Examples:
import xnano
@xnano.playable
def chord(context: xnano.Context, root: str = 'C4') -> xnano.Note:
return xnano.Note(root, beats=0.5)
with xnano.new(width=8, height=1) as canvas:
canvas.speaker.play(chord(root='E4'))
canvas.clock.step(delta_seconds=0.5)
assert canvas.speaker.render().peak > 0.0
Source code in xnano/components.py
def playable( # pyright: ignore[reportGeneralTypeIssues]
function: Callable[Concatenate[Context[DepsT, StateT], ParametersT], Playable]
| Callable[[], Playable],
/,
) -> PlayableFunction[ParametersT, DepsT, StateT] | PlayableFunction[[], None, None]:
"""
Turn a function into a component that plays itself.
The function takes the [`Context`][xnano.hooks.Context] first, then its own parameters,
and returns anything ``canvas.play`` accepts; a function with no parameters at all is
called without the context. It is evaluated once when played, and again
on a beat only when it read something that changes (the time or the beat, a state path or
an input), playing the new result each time. ``canvas.play`` returns a
[`PlayHandle`][xnano.audio.PlayHandle] whose ``remove()`` stops it.
Args:
function: The function ``(context, **own_parameters) -> playable``.
Raises:
TypeError: The decorated object is a class or is not callable, or the function's
first parameter is keyword-only or variadic, so it cannot take the context.
Examples:
```python
import xnano
@xnano.playable
def chord(context: xnano.Context, root: str = 'C4') -> xnano.Note:
return xnano.Note(root, beats=0.5)
with xnano.new(width=8, height=1) as canvas:
canvas.speaker.play(chord(root='E4'))
canvas.clock.step(delta_seconds=0.5)
assert canvas.speaker.render().peak > 0.0
```
"""
return PlayableFunction(
cast(
'Callable[Concatenate[Context[DepsT, StateT], ParametersT], Playable]',
function,
)
)
renderable
¶
renderable(function: Callable[Concatenate[Context[DepsT, StateT], ParametersT], None]) -> RenderableFunction[ParametersT, DepsT, StateT]
Turn a function into a component with a screen of its own, which draws and plays.
The function takes the Context first, then its own parameters,
and returns nothing. Its context.screen is its own: a screen where the component is
written, as large as what the function writes on it unless the component was written
with a width or a height. Its context.speaker, context.clock,
context.keyboard and context.mouse are the canvas's. Write it with
canvas.screen.write(meter), or canvas.screen.write(meter(limit=0.9)) to give it
parameters; meter.hook(...) adds behavior to where it is written.
The function runs once, and again only when it read something that changes, as a
writable does. Each run starts from an empty screen: what the run
before wrote is removed first, so the screen shows what the latest run wrote. What a run
plays starts when that run plays it.
Parameters:
-
function(Callable[Concatenate[Context[DepsT, StateT], ParametersT], None]) –The function
(context, **own_parameters) -> None.
Raises:
-
TypeError–The decorated object is a class or is not callable, or the function takes no parameters or its first parameter is keyword-only or variadic, so it cannot take the context.
Examples:
import xnano
@xnano.renderable
def meter(context: xnano.Context, level: float = 0.5) -> None:
context.screen.write('level')
context.screen.write('#' * round(level * 10))
with xnano.new(width=12, height=3) as canvas:
placement = canvas.screen.write(meter(level=0.3), y=1)
assert canvas.screen.render().splitlines()[1:] == ['level', '###']
assert (placement.width, placement.height) == (5, 2)
Source code in xnano/components.py
def renderable( # pyright: ignore[reportGeneralTypeIssues]
function: Callable[Concatenate[Context[DepsT, StateT], ParametersT], None], /
) -> RenderableFunction[ParametersT, DepsT, StateT]:
"""
Turn a function into a component with a screen of its own, which draws and plays.
The function takes the [`Context`][xnano.hooks.Context] first, then its own parameters,
and returns nothing. Its ``context.screen`` is its own: a screen where the component is
written, as large as what the function writes on it unless the component was written
with a ``width`` or a ``height``. Its ``context.speaker``, ``context.clock``,
``context.keyboard`` and ``context.mouse`` are the canvas's. Write it with
``canvas.screen.write(meter)``, or ``canvas.screen.write(meter(limit=0.9))`` to give it
parameters; ``meter.hook(...)`` adds behavior to where it is written.
The function runs once, and again only when it read something that changes, as a
[`writable`][xnano.writable] does. Each run starts from an empty screen: what the run
before wrote is removed first, so the screen shows what the latest run wrote. What a run
plays starts when that run plays it.
Args:
function: The function ``(context, **own_parameters) -> None``.
Raises:
TypeError: The decorated object is a class or is not callable, or the function takes
no parameters or its first parameter is keyword-only or variadic, so it cannot
take the context.
Examples:
```python
import xnano
@xnano.renderable
def meter(context: xnano.Context, level: float = 0.5) -> None:
context.screen.write('level')
context.screen.write('#' * round(level * 10))
with xnano.new(width=12, height=3) as canvas:
placement = canvas.screen.write(meter(level=0.3), y=1)
assert canvas.screen.render().splitlines()[1:] == ['level', '###']
assert (placement.width, placement.height) == (5, 2)
```
"""
return RenderableFunction(function)
writable
¶
writable(function: Callable[[], Writable]) -> WritableFunction[[], None, None]
writable(function: Callable[Concatenate[Context[DepsT, StateT], ParametersT], Writable]) -> WritableFunction[ParametersT, DepsT, StateT]
writable(function: Callable[Concatenate[Context[DepsT, StateT], ParametersT], Writable] | Callable[[], Writable]) -> WritableFunction[ParametersT, DepsT, StateT] | WritableFunction[[], None, None]
Turn a function into a component that draws itself.
The function takes the Context first, then its own parameters,
and returns anything canvas.screen.write accepts; a function with no parameters at all is
called without the context. The decorated object is the component:
canvas.screen.write(gauge) draws it with its defaults, canvas.screen.write(gauge(ratio=0.7)) gives
it parameters, and gauge.hook(...) adds behavior to its placements.
A component is evaluated once, and again only when it read something that changes: the
time or the event (every frame), the size of its buffer, the parent or the canvas (when
the screen is resized), a state path (when it changes), or an input such as
context.keyboard (when it arrives). What it reads is recorded as it runs. Reads of
context.deps and of mutable fields on self are not tracked: when they change, call
placement.refresh().
Parameters:
-
function(Callable[Concatenate[Context[DepsT, StateT], ParametersT], Writable] | Callable[[], Writable]) –The function
(context, **own_parameters) -> content.
Raises:
-
TypeError–The decorated object is a class or is not callable, or the function's first parameter is keyword-only or variadic, so it cannot take the context.
Examples:
import xnano
@xnano.writable
def gauge(context: xnano.Context, ratio: float = 0.5) -> str:
return '#' * round(ratio * 10)
with xnano.new(width=12, height=1) as canvas:
canvas.screen.write(gauge(ratio=0.3))
assert canvas.screen.render().strip() == '###'
Source code in xnano/components.py
def writable( # pyright: ignore[reportGeneralTypeIssues]
function: Callable[Concatenate[Context[DepsT, StateT], ParametersT], Writable]
| Callable[[], Writable],
/,
) -> WritableFunction[ParametersT, DepsT, StateT] | WritableFunction[[], None, None]:
"""
Turn a function into a component that draws itself.
The function takes the [`Context`][xnano.hooks.Context] first, then its own parameters,
and returns anything ``canvas.screen.write`` accepts; a function with no parameters at all is
called without the context. The decorated object is the component:
``canvas.screen.write(gauge)`` draws it with its defaults, ``canvas.screen.write(gauge(ratio=0.7))`` gives
it parameters, and ``gauge.hook(...)`` adds behavior to its placements.
A component is evaluated once, and again only when it read something that changes: the
time or the event (every frame), the size of its buffer, the parent or the canvas (when
the screen is resized), a state path (when it changes), or an input such as
``context.keyboard`` (when it arrives). What it reads is recorded as it runs. Reads of
``context.deps`` and of mutable fields on ``self`` are not tracked: when they change, call
[`placement.refresh()`][xnano.layout.Placement.refresh].
Args:
function: The function ``(context, **own_parameters) -> content``.
Raises:
TypeError: The decorated object is a class or is not callable, or the function's
first parameter is keyword-only or variadic, so it cannot take the context.
Examples:
```python
import xnano
@xnano.writable
def gauge(context: xnano.Context, ratio: float = 0.5) -> str:
return '#' * round(ratio * 10)
with xnano.new(width=12, height=1) as canvas:
canvas.screen.write(gauge(ratio=0.3))
assert canvas.screen.render().strip() == '###'
```
"""
return WritableFunction(
cast(
'Callable[Concatenate[Context[DepsT, StateT], ParametersT], Writable]',
function,
)
)
effect
¶
effect(kind: Literal['effect.fade_to'], /, **parameters: Unpack[FadeToEffectParametersSchema]) -> FadeToEffectParameters
effect(kind: Literal['effect.fade_from'], /, **parameters: Unpack[FadeFromEffectParametersSchema]) -> FadeFromEffectParameters
effect(kind: Literal['effect.paint'], /, **parameters: Unpack[PaintEffectParametersSchema]) -> PaintEffectParameters
effect(kind: Literal['effect.saturate'], /, **parameters: Unpack[SaturateEffectParametersSchema]) -> SaturateEffectParameters
effect(kind: Literal['effect.lighten'], /, **parameters: Unpack[LightenEffectParametersSchema]) -> LightenEffectParameters
effect(kind: Literal['effect.darken'], /, **parameters: Unpack[DarkenEffectParametersSchema]) -> DarkenEffectParameters
effect(kind: Literal['effect.sweep_in'], /, **parameters: Unpack[SweepInEffectParametersSchema]) -> SweepInEffectParameters
effect(kind: Literal['effect.sweep_out'], /, **parameters: Unpack[SweepOutEffectParametersSchema]) -> SweepOutEffectParameters
effect(kind: Literal['effect.slide_in'], /, **parameters: Unpack[SlideInEffectParametersSchema]) -> SlideInEffectParameters
effect(kind: Literal['effect.slide_out'], /, **parameters: Unpack[SlideOutEffectParametersSchema]) -> SlideOutEffectParameters
effect(kind: Literal['effect.hsl_shift'], /, **parameters: Unpack[HslShiftEffectParametersSchema]) -> HslShiftEffectParameters
effect(kind: Literal['effect.dissolve'], /, **parameters: Unpack[DissolveEffectParametersSchema]) -> DissolveEffectParameters
effect(kind: Literal['effect.coalesce'], /, **parameters: Unpack[CoalesceEffectParametersSchema]) -> CoalesceEffectParameters
effect(kind: Literal['effect.glitch'], /, **parameters: Unpack[GlitchEffectParametersSchema]) -> GlitchEffectParameters
effect(kind: Literal['effect.sleep'], /, **parameters: Unpack[SleepEffectParametersSchema]) -> SleepEffectParameters
effect(kind: Literal['effect.evolve'], /, **parameters: Unpack[EvolveEffectParametersSchema]) -> EvolveEffectParameters
effect(kind: Literal['effect.evolve_into'], /, **parameters: Unpack[EvolveIntoEffectParametersSchema]) -> EvolveIntoEffectParameters
effect(kind: Literal['effect.evolve_from'], /, **parameters: Unpack[EvolveFromEffectParametersSchema]) -> EvolveFromEffectParameters
effect(kind: Literal['effect.expand'], /, **parameters: Unpack[ExpandEffectParametersSchema]) -> ExpandEffectParameters
effect(kind: Literal['effect.stretch'], /, **parameters: Unpack[StretchEffectParametersSchema]) -> StretchEffectParameters
effect(kind: Literal['effect.explode'], /, **parameters: Unpack[ExplodeEffectParametersSchema]) -> ExplodeEffectParameters
effect(kind: Literal['audio.bit_crush'], /, **parameters: Unpack[BitCrushAudioEffectParametersSchema]) -> BitCrushAudioEffectParameters
effect(kind: Literal['audio.distortion'], /, **parameters: Unpack[DistortionAudioEffectParametersSchema]) -> DistortionAudioEffectParameters
effect(kind: Literal['audio.low_pass'], /, **parameters: Unpack[LowPassAudioEffectParametersSchema]) -> LowPassAudioEffectParameters
effect(kind: Literal['audio.high_pass'], /, **parameters: Unpack[HighPassAudioEffectParametersSchema]) -> HighPassAudioEffectParameters
effect(kind: Literal['audio.delay'], /, **parameters: Unpack[DelayAudioEffectParametersSchema]) -> DelayAudioEffectParameters
effect(kind: Literal['audio.reverb'], /, **parameters: Unpack[ReverbAudioEffectParametersSchema]) -> ReverbAudioEffectParameters
effect(kind: Literal['audio.tremolo'], /, **parameters: Unpack[TremoloAudioEffectParametersSchema]) -> TremoloAudioEffectParameters
effect(kind: EffectKind, /, **parameters: object) -> EffectParameters
Create the parameters of a visual or sound effect.
Each kind is an overload whose keyword arguments are typed by the settings of that
effect and which returns that effect's parameters:
effect('effect.fade_to', ...) returns a
FadeToEffectParameters. The result can be
inspected and edited, piped with |, passed to add and update, returned from a
hook or listed in effects=.
Parameters:
-
kind(EffectKind) –The effect to create: a visual kind such as
'effect.fade_to'or a sound kind such as'audio.reverb'. -
parameters(object, default:{}) –The keyword arguments of that kind.
Returns:
-
EffectParameters–The parameters of the effect, not yet applied to anything.
Raises:
-
ValueError–kindis not a known effect kind, or is the kind of an operation that is not an effect, such as'fill'. -
TypeError–A keyword is not a setting of that kind. The message lists its settings.
Examples:
import xnano
fade = xnano.effect('effect.fade_to', foreground='red', duration_milliseconds=200)
assert fade.duration_milliseconds == 200
with xnano.new('hi', width=4, height=1) as canvas:
canvas.screen | fade
Source code in xnano/effects/__init__.py
def effect(kind: EffectKind, /, **parameters: object) -> EffectParameters:
"""
Create the parameters of a visual or sound effect.
Each ``kind`` is an overload whose keyword arguments are typed by the settings of that
effect and which returns that effect's parameters:
``effect('effect.fade_to', ...)`` returns a
[`FadeToEffectParameters`][xnano.effects.FadeToEffectParameters]. The result can be
inspected and edited, piped with ``|``, passed to ``add`` and ``update``, returned from a
[`hook`][xnano.hooks.hook] or listed in ``effects=``.
Args:
kind: The effect to create: a visual kind such as ``'effect.fade_to'`` or a sound kind
such as ``'audio.reverb'``.
parameters: The keyword arguments of that kind.
Returns:
The parameters of the effect, not yet applied to anything.
Raises:
ValueError: ``kind`` is not a known effect kind, or is the kind of an operation that
is not an effect, such as ``'fill'``.
TypeError: A keyword is not a setting of that kind. The message lists its settings.
Examples:
```python
import xnano
fade = xnano.effect('effect.fade_to', foreground='red', duration_milliseconds=200)
assert fade.duration_milliseconds == 200
with xnano.new('hi', width=4, height=1) as canvas:
canvas.screen | fade
```
"""
return build_effect(kind, parameters)
hook
¶
hook(function: Hook[DepsT, StateT]) -> ContextualOperation[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') -> ContextualOperation[DepsT, StateT] | Callable[[Hook[DepsT, StateT]], ContextualOperation[DepsT, StateT]]
Describe a hook once, to attach to any canvas or placement later.
It takes the same arguments as target.hook(...) and returns an operation: pipe it onto
a target with target | operation, or pass it to update. Each target gets its own
hook. The function may return an operation, a style or an effect, which is applied to the
target it runs on.
Parameters:
-
function(Hook[DepsT, StateT] | None, default:None) –The function to wrap when
@xnano.hookis used without parentheses: a function of theContext, or one with no parameters. -
on(HookTrigger[DepsT, StateT] | None, default:None) –When the hook runs: a kind of event, the name of a custom event, or a condition; see
HookTrigger. -
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. -
requires_deps(bool, default:False) –Whether the hook needs the dependencies given to
new(deps=...). -
if_running(IfRunning, default:'replace') –For an
async deffunction, what happens when the hook runs again before its previous run has finished; seeIfRunning.
Raises:
-
TypeError–functioncannot be called with a context,keysis not a key name or a list of them, oronis not a kind, a name or a condition. -
ValueError–on,every,after,keysorif_runningis not valid, or they do not fit together.
Examples:
import xnano
readings = []
@xnano.hook(on='frame')
def clock_readout(context: xnano.Context) -> None:
readings.append(round(context.clock.elapsed_seconds, 1))
with xnano.new(width=12, height=1) as canvas:
canvas.screen | clock_readout
canvas.clock.step(delta_seconds=0.5)
assert readings == [0.5]
Source code in xnano/hooks/__init__.py
def 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',
) -> (
ContextualOperation[DepsT, StateT]
| Callable[
[Hook[DepsT, StateT]],
ContextualOperation[DepsT, StateT],
]
):
"""
Describe a hook once, to attach to any canvas or placement later.
It takes the same arguments as ``target.hook(...)`` and returns an operation: pipe it onto
a target with ``target | operation``, or pass it to ``update``. Each target gets its own
hook. The function may return an operation, a style or an effect, which is applied to the
target it runs on.
Args:
function: The function to wrap when ``@xnano.hook`` is used without parentheses: a
function of the [`Context`][xnano.hooks.Context], or one with no parameters.
on: When the hook runs: a kind of event, the name of a custom event, or a condition;
see [`HookTrigger`][xnano.hooks.HookTrigger].
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.
requires_deps: Whether the hook needs the dependencies given to ``new(deps=...)``.
if_running: For an ``async def`` function, what happens when the hook runs again
before its previous run has finished; see [`IfRunning`][xnano.hooks.IfRunning].
Raises:
TypeError: ``function`` cannot be called with a context, ``keys`` is not a key name
or a list of them, or ``on`` is not a kind, a name or a condition.
ValueError: ``on``, ``every``, ``after``, ``keys`` or ``if_running`` is not valid, or
they do not fit together.
Examples:
```python
import xnano
readings = []
@xnano.hook(on='frame')
def clock_readout(context: xnano.Context) -> None:
readings.append(round(context.clock.elapsed_seconds, 1))
with xnano.new(width=12, height=1) as canvas:
canvas.screen | clock_readout
canvas.clock.step(delta_seconds=0.5)
assert readings == [0.5]
```
"""
kind, condition = resolve_trigger(on, every=every, after=after, keys=keys)
_check_hook_arguments(
cast('_Hooked[object, object]', object()), kind, every, after, keys
)
compile_when(condition)
_check_if_running(if_running)
normalized_keys: tuple[str, ...] = (
() if keys is None else (keys,) if isinstance(keys, str) else tuple(keys)
)
def wrap(
callback: Hook[DepsT, StateT],
) -> ContextualOperation[DepsT, StateT]:
checked = _check_hook_function(callback)
_check_if_running_fits(checked, if_running)
return ContextualOperation(
cast('Callable[[Context[DepsT, StateT]], object]', checked),
on=on,
every=every,
after=after,
keys=normalized_keys,
requires_deps=requires_deps,
if_running=if_running,
)
if function is not None:
return wrap(function)
return wrap
box
¶
box(width: int | Percentage | str | NumericExpression | StateReference[int] | StateReference[float], height: int | Percentage | str | NumericExpression | StateReference[int] | StateReference[float], /, **appearance: Unpack[AppearanceArguments]) -> Region[int]
Build an empty standalone rectangle of cells (does not draw).
The region is a value that you write into a canvas. It has no border unless you pass
border: 'plain' or another kind, or True for 'plain'. A background
colors every cell of the box. A box with a relative size is drawn at the size of its
placement when it is written, and again whenever the canvas is resized.
The look given to canvas.screen.write(box, ...) is laid over the look of the box: a color,
border, title or padding that the write names wins, and the rest stays as the box has
it. border=False leaves out the border of the box, with its title, border style and
sides. A box written with a look keeps its size, border included, so the look of the
write replaces the look of the box instead of surrounding it, and a margin given to
the write is space around that size.
Parameters:
-
width(int | Percentage | str | NumericExpression | StateReference[int] | StateReference[float]) –The width in cells, border included: a whole number, a percentage such as
'50%', an expression such asParentWidth - 4or a reference to the canvas state fromcanvas.state_reference(). A relative size (every form but a whole number) is measured where the box is written, likecanvas.screen.write(..., width='50%'), and until then against the active canvas or, with none, the terminal window. Until the box is written, a relative size that measures outside 1 to 65535 cells is held to that range. -
height(int | Percentage | str | NumericExpression | StateReference[int] | StateReference[float]) –The height in cells, border included, in the same forms as
width. -
appearance(Unpack[AppearanceArguments], default:{}) –The look of the box: colors, text modifiers,
border,title,paddingandmargin; seeAppearanceArguments. When the placement of a box draws its look, its border is on the placement andplacement.regionaddresses the cells inside the border and padding. That is the case for a relative box, a box written with a width or height, and a box written with a look. A whole-number box written as it is is a snapshot whose border is part of its cells, soplacement.regionincludes the border.
Raises:
-
TerminalError–A size is not a whole number of cells, a percentage, an expression or a state reference; a whole number is outside 1 to 65535; a share is 0% or less; or a expression reads the clock or input that has not arrived. A relative size that measures outside 1 to 65535 cells is held to that range, not refused.
Examples:
import xnano
assert xnano.box(5, 3).render().strip() == ''
frame = xnano.box(5, 3, border='plain')
assert frame.render().splitlines() == ['┌───┐', '│ │', '└───┘']
with xnano.new(width=80, height=4) as canvas:
half = xnano.box('50%', 3)
assert half.width == 40
placement = canvas.screen.write(xnano.box('50%', 3, border='plain'))
assert placement.width == 40
card = canvas.screen.write(xnano.box(6, 3, border='plain'), border=False)
assert (card.width, card.height) == (6, 3)
Source code in xnano/layout/_region.py
def box(
width: int
| Percentage
| str
| NumericExpression
| _core.StateReference[int]
| _core.StateReference[float],
height: int
| Percentage
| str
| NumericExpression
| _core.StateReference[int]
| _core.StateReference[float],
/,
**appearance: Unpack[AppearanceArguments],
) -> Region[int]:
"""
Build an empty standalone rectangle of cells (does not draw).
The region is a value that you write into a canvas. It has no border unless you pass
``border``: ``'plain'`` or another kind, or ``True`` for ``'plain'``. A ``background``
colors every cell of the box. A box with a relative size is drawn at the size of its
placement when it is written, and again whenever the canvas is resized.
The look given to ``canvas.screen.write(box, ...)`` is laid over the look of the box: a color,
border, title or padding that the write names wins, and the rest stays as the box has
it. ``border=False`` leaves out the border of the box, with its title, border style and
sides. A box written with a look keeps its size, border included, so the look of the
write replaces the look of the box instead of surrounding it, and a ``margin`` given to
the write is space around that size.
Args:
width: The width in cells, border included: a whole number, a percentage such as
``'50%'``, an expression such as ``ParentWidth - 4`` or a reference to the canvas
state from ``canvas.state_reference()``. A relative size (every form but a whole
number) is measured where the box is written, like
``canvas.screen.write(..., width='50%')``, and until then against the active canvas or,
with none, the terminal window. Until the box is written, a relative size that
measures outside 1 to 65535 cells is held to that range.
height: The height in cells, border included, in the same forms as ``width``.
appearance: The look of the box: colors, text modifiers, ``border``, ``title``,
``padding`` and ``margin``; see [`AppearanceArguments`][xnano.styles.AppearanceArguments].
When the placement of a box draws its look, its border is on the placement and
``placement.region`` addresses the cells inside the border and padding. That is
the case for a relative box, a box written with a width or height, and a box
written with a look. A whole-number box written as it is is a snapshot whose
border is part of its cells, so ``placement.region`` includes the border.
Raises:
TerminalError: A size is not a whole number of cells, a percentage, an expression or a
state reference; a whole number is outside 1 to 65535; a share is 0% or less; or a
expression reads the clock or input that has not arrived. A relative size that
measures outside 1 to 65535 cells is held to that range, not refused.
Examples:
```python
import xnano
assert xnano.box(5, 3).render().strip() == ''
frame = xnano.box(5, 3, border='plain')
assert frame.render().splitlines() == ['┌───┐', '│ │', '└───┘']
with xnano.new(width=80, height=4) as canvas:
half = xnano.box('50%', 3)
assert half.width == 40
placement = canvas.screen.write(xnano.box('50%', 3, border='plain'))
assert placement.width == 40
card = canvas.screen.write(xnano.box(6, 3, border='plain'), border=False)
assert (card.width, card.height) == (6, 3)
```
"""
space = (0, 0)
if _is_relative_size(width) or _is_relative_size(height):
space = _measuring_space()
cells_wide = _box_cells(width, 'width', space)
cells_high = _box_cells(height, 'height', space)
look = _standalone_look('box', '', cast('dict[str, object]', appearance))
region: Region[int] = Region(
_core.Buffer(width=cells_wide, height=cells_high),
is_standalone=True,
look=look,
is_text=False,
)
region._box_size = (
width.strip() if isinstance(width, str) else width,
height.strip() if isinstance(height, str) else height,
)
region._redraw_look()
return region
region
¶
region(content: Writable | None = None, /, *, width: int | Percentage | str | NumericExpression | StateReference[int] | StateReference[float] | None = None, height: int | Percentage | str | NumericExpression | StateReference[int] | StateReference[float] | None = None, **appearance: Unpack[AppearanceArguments]) -> Region[int]
Build a standalone region from the content that canvas.screen.write accepts (does not draw).
The region is a value that owns its cells. Write it into a canvas with
canvas.screen.write(region, x=...), print it with render, or
change its look afterwards with region.border and its siblings. Where the region goes
(x, y, layer, lock and edges) and which effects run on it are given to
canvas.screen.write when you write it.
Text, or a list of lines, makes a region the size of the text, bordered, padded and colored as asked. Everything else is drawn the way a canvas would show it and kept as cells:
- A widget or
Buffer, anArt, aPixel, anImageand a writable component are drawn at the sizewidthandheightgive, or at their own size. - A
Regionis copied. It takes no size or look, because it has its own: change those on the copy. Nonemakes an empty box ofwidthbyheightcells (1 by 1 when left out), likebox.
A relative width or height (a percentage such as '50%', an expression such as
ParentWidth - 4 or a state reference) is measured against the active canvas, or the
terminal window when no canvas is active. Content that depends on its surroundings, such
as a widget with expressions, an image fitted to a size or a component that reads the time,
the state or the size, is drawn as the active canvas sees it at that moment and kept as
cells. Only an empty box (None) keeps its relative size and is drawn again at
the size of its placement when it is written, and whenever the canvas is resized.
Parameters:
-
content(Writable | None, default:None) –Text (or a list of lines), a widget or core buffer, a region, an image, art, a pixel or any
Writable;Nonefor an empty box. -
width(int | Percentage | str | NumericExpression | StateReference[int] | StateReference[float] | None, default:None) –The width in cells, border included: a whole number, a percentage, an expression or a state reference. The content's own width when left out.
-
height(int | Percentage | str | NumericExpression | StateReference[int] | StateReference[float] | None, default:None) –The height in cells, in the same forms as
width. -
appearance(Unpack[AppearanceArguments], default:{}) –The look: colors, text modifiers,
border,title,paddingandmargin; seeAppearanceArguments.
Returns:
Raises:
-
TypeError–The content is not something a canvas can show, or a keyword is not a size or a look.
-
TerminalError–The content is a canvas, or a region given a size or a look, or a size cannot be measured.
Examples:
import xnano
from xnano.widgets import Gauge
card = xnano.region('hello', border='rounded', padding={'horizontal': 1})
assert card.render().splitlines()[1] == '│ hello │'
card.border = False
assert card.render().strip() == 'hello'
with xnano.new(width=40, height=4) as canvas:
gauge = xnano.region(Gauge(0.6, label='60%'), width='50%')
assert gauge.width == 20
canvas.screen.write(gauge, x=10)
assert '60%' in canvas.screen.render()
Source code in xnano/layout/_region.py
def region(
content: Writable | None = None,
/,
*,
width: int
| Percentage
| str
| NumericExpression
| _core.StateReference[int]
| _core.StateReference[float]
| None = None,
height: int
| Percentage
| str
| NumericExpression
| _core.StateReference[int]
| _core.StateReference[float]
| None = None,
**appearance: Unpack[AppearanceArguments],
) -> Region[int]:
"""
Build a standalone region from the content that ``canvas.screen.write`` accepts (does not draw).
The region is a value that owns its cells. Write it into a canvas with
``canvas.screen.write(region, x=...)``, print it with [`render`][xnano.layout.Region.render], or
change its look afterwards with ``region.border`` and its siblings. Where the region goes
(``x``, ``y``, ``layer``, ``lock`` and ``edges``) and which effects run on it are given to
``canvas.screen.write`` when you write it.
Text, or a list of lines, makes a region the size of the text, bordered, padded and
colored as asked. Everything else is drawn the way a canvas would show it and kept as
cells:
- A widget or [`Buffer`][xnano_core.Buffer], an [`Art`][xnano.art.Art], a
[`Pixel`][xnano.Pixel], an [`Image`][xnano.Image] and a writable component are
drawn at the size ``width`` and ``height`` give, or at their own size.
- A [`Region`][xnano.layout.Region] is copied. It takes no size or look, because it has
its own: change those on the copy.
- ``None`` makes an empty box of ``width`` by ``height`` cells (1 by 1 when left out), like
[`box`][xnano.box].
A relative ``width`` or ``height`` (a percentage such as ``'50%'``, an expression such as
``ParentWidth - 4`` or a state reference) is measured against the active canvas, or the
terminal window when no canvas is active. Content that depends on its surroundings, such
as a widget with expressions, an image fitted to a size or a component that reads the time,
the state or the size, is drawn as the active canvas sees it at that moment and kept as
cells. Only an empty box (``None``) keeps its relative size and is drawn again at
the size of its placement when it is written, and whenever the canvas is resized.
Args:
content: Text (or a list of lines), a widget or core buffer, a region, an image, art,
a pixel or any [`Writable`][xnano.components.Writable]; ``None`` for an empty
box.
width: The width in cells, border included: a whole number, a percentage, an expression
or a state reference. The content's own width when left out.
height: The height in cells, in the same forms as ``width``.
appearance: The look: colors, text modifiers, ``border``, ``title``, ``padding`` and
``margin``; see [`AppearanceArguments`][xnano.styles.AppearanceArguments].
Returns:
A standalone [`Region`][xnano.layout.Region] on the screen.
Raises:
TypeError: The content is not something a canvas can show, or a keyword is not a
size or a look.
TerminalError: The content is a canvas, or a region given a size or a look, or a
size cannot be measured.
Examples:
```python
import xnano
from xnano.widgets import Gauge
card = xnano.region('hello', border='rounded', padding={'horizontal': 1})
assert card.render().splitlines()[1] == '│ hello │'
card.border = False
assert card.render().strip() == 'hello'
with xnano.new(width=40, height=4) as canvas:
gauge = xnano.region(Gauge(0.6, label='60%'), width='50%')
assert gauge.width == 20
canvas.screen.write(gauge, x=10)
assert '60%' in canvas.screen.render()
```
"""
_check_content(content)
if (width is not None or height is not None) and not isinstance(content, Region):
space = (0, 0)
if _is_relative_size(width) or _is_relative_size(height):
space = _measuring_space()
if width is not None:
_box_cells(width, 'width', space, 'xnano.region()')
if height is not None:
_box_cells(height, 'height', space, 'xnano.region()')
if isinstance(width, str):
width = width.strip()
if isinstance(height, str):
height = height.strip()
if isinstance(content, str) or (
isinstance(content, (list, tuple))
and all(isinstance(line, str) for line in content)
):
if width is None and height is None:
text = (
content
if isinstance(content, str)
else '\n'.join(cast('list[str]', content))
)
look = _standalone_look('region', text, cast('dict[str, object]', appearance))
region: Region[int] = Region(
_core.Buffer(width=1, height=1),
is_standalone=True,
look=look,
is_text=True,
)
region._redraw_look()
return region
if content is None:
return box(
1 if width is None else width,
1 if height is None else height,
**appearance,
)
if isinstance(content, Region):
content._require_drawable('xnano.region()')
if width is not None or height is not None or appearance:
raise TerminalError(
'xnano.region() copies a region as it is, but it was also given a size or a '
'look. A region has its own: change the copy with region.border, '
'region.padding or region.color, or give the size and the look to '
'canvas.screen.write(region, width=..., border=...) where you write it.',
code='validation.value',
location='content',
input_value=content,
)
return cast('Region[int]', content.copy())
_standalone_look('region', '', cast('dict[str, object]', appearance))
return _drawn_region(content, width, height, appearance)
from_rich
¶
from_rich(renderable: RenderableType) -> RichContent
Draw anything the rich library draws: rich markup, a table, a panel, syntax and more.
Write the result like any other content. Rich draws it at the size of its placement. If
the write gives no width, rich uses the natural width of the renderable. xnano draws it
again when that size changes. xnano draws text as rich.print draws it, with markup,
emoji codes and highlighting. For the size, the time and the styles, see
RichContent. Rich is not a dependency of xnano. To use
this function, install rich.
Parameters:
-
renderable(RenderableType) –Rich markup text such as
'[bold red]error[/]', or any rich renderable: an object with__rich_console__or__rich__, such as arich.table.Table, arich.panel.Panelor arich.syntax.Syntax.
Returns:
-
RichContent–The content, ready for
Screen.write.
Raises:
-
ImportError–The rich library is not installed.
-
TypeError–renderableis not something rich can draw.
Examples:
import xnano
from rich.panel import Panel
with xnano.new(width=24, height=3) as canvas:
canvas.screen.write(xnano.from_rich(Panel('[bold]ready[/bold]')), width='100%')
assert 'ready' in canvas.screen.render()
Source code in xnano/styles/_rich.py
def from_rich(renderable: RenderableType) -> RichContent:
"""
Draw anything the rich library draws: rich markup, a table, a panel, syntax and more.
Write the result like any other content. Rich draws it at the size of its placement. If
the write gives no width, rich uses the natural width of the renderable. xnano draws it
again when that size changes. xnano draws text as ``rich.print`` draws it, with markup,
emoji codes and highlighting. For the size, the time and the styles, see
[`RichContent`][xnano.styles.RichContent]. Rich is not a dependency of xnano. To use
this function, install rich.
Args:
renderable: Rich markup text such as ``'[bold red]error[/]'``, or any rich renderable:
an object with ``__rich_console__`` or ``__rich__``, such as a
``rich.table.Table``, a ``rich.panel.Panel`` or a ``rich.syntax.Syntax``.
Returns:
The content, ready for [`Screen.write`][xnano.devices.Screen.write].
Raises:
ImportError: The rich library is not installed.
TypeError: ``renderable`` is not something rich can draw.
Examples:
```python
import xnano
from rich.panel import Panel
with xnano.new(width=24, height=3) as canvas:
canvas.screen.write(xnano.from_rich(Panel('[bold]ready[/bold]')), width='100%')
assert 'ready' in canvas.screen.render()
```
"""
try:
from rich.protocol import is_renderable
except ImportError:
raise ImportError(_INSTALL_RICH) from None
if not is_renderable(renderable):
raise TypeError(
f'from_rich() draws what rich can render, but got the '
f'{type(renderable).__name__} {reprlib.repr(renderable)}. Pass rich markup text '
'or a rich renderable, such as a rich.table.Table, or write the value with '
'screen.write() directly.'
)
return RichContent(renderable)
iter
¶
iter(canvas: Canvas[DepsT, StateT], /, *, frames: int | None = None, seconds: float | None = None, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c', title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, **settings: Unpack[OpenSettings]) -> Iterator[Frame]
iter(content: Content | None = None, /, *, frames: int | None = None, seconds: float | None = None, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c', title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float = 60.0, bpm: float = 120.0, effects: Sequence[WritableEffectSpecification] = (), deps: object = ..., state: object = ..., **settings: Unpack[CanvasSettings]) -> Iterator[Frame]
iter(canvas_or_content: Canvas[object, object] | Content | None = None, /, *, frames: int | None = None, seconds: float | None = None, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c', title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, **settings: object) -> Iterator[Frame]
Open a terminal and run it one frame at a time: the program's main loop, as a for loop.
It takes the keywords of open (so xnano.iter(fps=30, mouse=True) opens
the terminal at 30 frames a second with the mouse on), opens the terminal when the loop
starts, and closes it when the loop ends. Each Frame has the
terminal in frame.canvas and the events that arrived since the previous frame in
frame.events; anything you change before the next frame is drawn.
Without frames or seconds it runs the way run does:
until a key of stop_on is pressed, the terminal is asked to
stop, or you break out of the loop. With them, it also ends
after that many frames, or when the terminal has run that long. To run a canvas you have
one frame at a time, use Canvas.iter.
Parameters:
-
canvas_or_content(Canvas[object, object] | Content | None, default:None) –A canvas from
new()to open, or content to write into a new one. -
frames(int | None, default:None) –The most frames to yield.
-
seconds(float | None, default:None) –The most seconds to run for.
-
stop_on(KeyName | Sequence[KeyName] | None, default:'ctrl+c') –The key, or keys, that end the loop and close the terminal;
Nonefor none. -
title(str | None, default:None) –The window title.
-
width(int | Percentage | str | None, default:None) –The width of the region to draw in, as for
open(). -
height(int | Percentage | str | None, default:None) –The height of the region to draw in, as for
open(). -
settings(object, default:{}) –The other keywords of
open(): the terminal settings, the look,fps,bpm,effects,depsandstate.
Yields:
-
Frame–Each frame, until the loop ends.
Raises:
-
TerminalAlreadyOpenError–Another canvas is already on the screen.
-
TerminalError–There is no terminal to draw on.
Examples:
ball = None
for frame in xnano.iter(height=3, fps=30, stop_on='q'):
if ball is None:
ball = frame.canvas.screen.write('o')
for event in frame.events:
if event.key is not None and event.key.key == 'space':
ball.x = 0
ball.x = (ball.x + 1) % frame.canvas.screen.width
Source code in xnano/terminal/__init__.py
def iter(
canvas_or_content: Canvas[object, object] | Content | None = None,
/,
*,
frames: int | None = None,
seconds: float | None = None,
stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c',
title: str | None = None,
width: int | Percentage | str | None = None,
height: int | Percentage | str | None = None,
**settings: object,
) -> Iterator[Frame]:
"""
Open a terminal and run it one frame at a time: the program's main loop, as a ``for`` loop.
It takes the keywords of [`open`][xnano.open] (so ``xnano.iter(fps=30, mouse=True)`` opens
the terminal at 30 frames a second with the mouse on), opens the terminal when the loop
starts, and closes it when the loop ends. Each [`Frame`][xnano.hooks.Frame] has the
terminal in ``frame.canvas`` and the events that arrived since the previous frame in
``frame.events``; anything you change before the next frame is drawn.
Without ``frames`` or ``seconds`` it runs the way [`run`][xnano.canvas.Canvas.run] does:
until a key of ``stop_on`` is pressed, the terminal is asked to
[`stop`][xnano.canvas.Canvas.stop], or you break out of the loop. With them, it also ends
after that many frames, or when the terminal has run that long. To run a canvas you have
one frame at a time, use [`Canvas.iter`][xnano.canvas.Canvas.iter].
Args:
canvas_or_content: A canvas from ``new()`` to open, or content to write into a new
one.
frames: The most frames to yield.
seconds: The most seconds to run for.
stop_on: The key, or keys, that end the loop and close the terminal; ``None`` for
none.
title: The window title.
width: The width of the region to draw in, as for ``open()``.
height: The height of the region to draw in, as for ``open()``.
settings: The other keywords of ``open()``: the terminal settings, the look,
``fps``, ``bpm``, ``effects``, ``deps`` and ``state``.
Yields:
Each frame, until the loop ends.
Raises:
TerminalAlreadyOpenError: Another canvas is already on the screen.
TerminalError: There is no terminal to draw on.
Examples:
```text
ball = None
for frame in xnano.iter(height=3, fps=30, stop_on='q'):
if ball is None:
ball = frame.canvas.screen.write('o')
for event in frame.events:
if event.key is not None and event.key.key == 'space':
ball.x = 0
ball.x = (ball.x + 1) % frame.canvas.screen.width
```
"""
# The keywords were checked by the overloads of this function, which are those of open().
opening = cast('Callable[..., Terminal[object, object]]', open)
with opening(
canvas_or_content, title=title, width=width, height=height, **settings
) as terminal:
yield from terminal.iter(frames=frames, seconds=seconds, stop_on=stop_on)
iter_async
async
¶
iter_async(canvas: Canvas[DepsT, StateT], /, *, frames: int | None = None, seconds: float | None = None, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c', title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, **settings: Unpack[OpenSettings]) -> AsyncIterator[Frame]
iter_async(content: Content | None = None, /, *, frames: int | None = None, seconds: float | None = None, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c', title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float = 60.0, bpm: float = 120.0, effects: Sequence[WritableEffectSpecification] = (), deps: object = ..., state: object = ..., **settings: Unpack[CanvasSettings]) -> AsyncIterator[Frame]
iter_async(canvas_or_content: Canvas[object, object] | Content | None = None, /, *, frames: int | None = None, seconds: float | None = None, stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c', title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, **settings: object) -> AsyncIterator[Frame]
Open a terminal and run it one frame at a time with async for, like iter.
The keywords, the frames and the ways the loop ends are the ones iter() has. Between
frames the rest of your event loop runs, and the terminal's async def hooks run on it.
Yields:
-
AsyncIterator[Frame]–Each frame, until the loop ends.
Examples:
Source code in xnano/terminal/__init__.py
async def iter_async(
canvas_or_content: Canvas[object, object] | Content | None = None,
/,
*,
frames: int | None = None,
seconds: float | None = None,
stop_on: KeyName | Sequence[KeyName] | None = 'ctrl+c',
title: str | None = None,
width: int | Percentage | str | None = None,
height: int | Percentage | str | None = None,
**settings: object,
) -> AsyncIterator[Frame]:
"""
Open a terminal and run it one frame at a time with ``async for``, like [`iter`][xnano.iter].
The keywords, the frames and the ways the loop ends are the ones ``iter()`` has. Between
frames the rest of your event loop runs, and the terminal's ``async def`` hooks run on it.
Yields:
Each frame, until the loop ends.
Examples:
```text
async def main() -> None:
async for frame in xnano.iter_async(height=3, seconds=2):
...
```
"""
opening = cast('Callable[..., OpeningTerminal[object, object]]', open_async)
async with opening(
canvas_or_content, title=title, width=width, height=height, **settings
) as terminal:
async for frame in terminal.iter_async(
frames=frames, seconds=seconds, stop_on=stop_on
):
yield frame
open
¶
open(canvas: Canvas[DepsT, StateT], /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, **settings: Unpack[OpenSettings]) -> Terminal[DepsT, StateT]
open(content: Content | None = None, /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float = 60.0, bpm: float = 120.0, effects: Sequence[WritableEffectSpecification] = (), **settings: Unpack[CanvasSettings]) -> Terminal[None, None]
open(content: Content | None = None, /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float = 60.0, bpm: float = 120.0, effects: Sequence[WritableEffectSpecification] = (), state: StateT, **settings: Unpack[CanvasSettings]) -> Terminal[None, StateT]
open(content: Content | None = None, /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float = 60.0, bpm: float = 120.0, effects: Sequence[WritableEffectSpecification] = (), deps: DepsT, **settings: Unpack[CanvasSettings]) -> Terminal[DepsT, None]
open(content: Content | None = None, /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float = 60.0, bpm: float = 120.0, effects: Sequence[WritableEffectSpecification] = (), deps: DepsT, state: StateT, **settings: Unpack[CanvasSettings]) -> Terminal[DepsT, StateT]
open(canvas_or_content: Canvas[object, object] | Content | None = None, /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, **settings: object) -> Terminal[DepsT, StateT]
Put a canvas on your screen and return it as a Terminal.
Given a canvas from new, this is Canvas.open:
the same object is attached to the screen and its time continues. Given content or
nothing, it creates the canvas with new() (the same keywords, except realtime)
and attaches that. From here on, anything you write, remove or draw appears at once, on a
loop of the canvas's own that your code never waits for. A with block closes it and
gives the screen back.
By default the canvas takes over the whole window, on the alternate screen so that your
shell's history comes back untouched; width='100%', height='100%' asks for the same.
Give height (and optionally width) to draw in a region of that size below the cursor
instead, in cells or as a percentage of the window such as '50%'; that region is erased
when the canvas closes, unless you pass clears_on_close=False. title is the window title.
The terminal settings say what the screen reports: mouse for buttons and drags,
scroll for the wheel, keyboard, paste, focus and interrupt
(Ctrl-C), and capture holds back what the program prints while the canvas is on
the screen. See TerminalSettings. mouse, scroll
and paste are turned on by themselves when a hook registered before opening needs
them. A hook added after opening turns nothing on: one that needs input the screen does
not report is attached and never runs.
Parameters:
-
canvas_or_content(Canvas[object, object] | Content | None, default:None) –A canvas from
new(), or content to write into a new canvas. -
title(str | None, default:None) –The window title;
Nonekeeps the canvas's title. -
width(int | Percentage | str | None, default:None) –The width of the region to draw in, in cells or as a percentage of the window; the whole window when neither
widthnorheightis given. -
height(int | Percentage | str | None, default:None) –The height of the region to draw in, in cells or as a percentage of the window.
-
settings(object, default:{}) –The other keywords of
new()exceptrealtime: the terminal settings, the canvas's look,fps,bpm,effects,depsandstate.
Returns:
-
Terminal[DepsT, StateT]–The open
Terminal, which is also the one module-level functions -
Terminal[DepsT, StateT]–such as
activefind.
Raises:
-
TerminalAlreadyOpenError–Another canvas is already on the screen.
-
TerminalError–There is no terminal to draw on.
-
TypeError–realtimewas given, an appearance keyword was given with content, or a keyword is unknown. -
ValueError–A
widthwas given without aheight, or a value is out of range.
Examples:
with xnano.open(height=3, mouse=True) as terminal:
terminal.screen.write('hello')
terminal.run(stop_on='q')
Source code in xnano/terminal/__init__.py
def open(
canvas_or_content: Canvas[object, object] | Content | None = None,
/,
*,
title: str | None = None,
width: int | Percentage | str | None = None,
height: int | Percentage | str | None = None,
**settings: object,
) -> Terminal[DepsT, StateT]:
"""
Put a canvas on your screen and return it as a [`Terminal`][xnano.Terminal].
Given a canvas from [`new`][xnano.new], this is [`Canvas.open`][xnano.canvas.Canvas.open]:
the same object is attached to the screen and its time continues. Given content or
nothing, it creates the canvas with ``new()`` (the same keywords, except ``realtime``)
and attaches that. From here on, anything you write, remove or draw appears at once, on a
loop of the canvas's own that your code never waits for. A ``with`` block closes it and
gives the screen back.
By default the canvas takes over the whole window, on the alternate screen so that your
shell's history comes back untouched; ``width='100%', height='100%'`` asks for the same.
Give ``height`` (and optionally ``width``) to draw in a region of that size below the cursor
instead, in cells or as a percentage of the window such as ``'50%'``; that region is erased
when the canvas closes, unless you pass ``clears_on_close=False``. ``title`` is the window title.
The terminal settings say what the screen reports: ``mouse`` for buttons and drags,
``scroll`` for the wheel, ``keyboard``, ``paste``, ``focus`` and ``interrupt``
(``Ctrl-C``), and ``capture`` holds back what the program prints while the canvas is on
the screen. See [`TerminalSettings`][xnano.terminal.TerminalSettings]. ``mouse``, ``scroll``
and ``paste`` are turned on by themselves when a hook registered before opening needs
them. A hook added after opening turns nothing on: one that needs input the screen does
not report is attached and never runs.
Args:
canvas_or_content: A canvas from ``new()``, or content to write into a new canvas.
title: The window title; ``None`` keeps the canvas's title.
width: The width of the region to draw in, in cells or as a percentage of the
window; the whole window when neither ``width`` nor ``height`` is given.
height: The height of the region to draw in, in cells or as a percentage of the
window.
settings: The other keywords of ``new()`` except ``realtime``: the terminal
settings, the canvas's look, ``fps``, ``bpm``, ``effects``, ``deps`` and ``state``.
Returns:
The open [`Terminal`][xnano.Terminal], which is also the one module-level functions
such as [`active`][xnano.active] find.
Raises:
TerminalAlreadyOpenError: Another canvas is already on the screen.
TerminalError: There is no terminal to draw on.
TypeError: ``realtime`` was given, an appearance keyword was given with content, or a
keyword is unknown.
ValueError: A ``width`` was given without a ``height``, or a value is out of range.
Examples:
```text
with xnano.open(height=3, mouse=True) as terminal:
terminal.screen.write('hello')
terminal.run(stop_on='q')
```
"""
if isinstance(canvas_or_content, Canvas):
return cast('Canvas[DepsT, StateT]', canvas_or_content).open(
title=title,
width=width,
height=height,
**settings, # type: ignore[arg-type]
)
canvas: Canvas[DepsT, StateT] = _canvas_to_open(
'open',
canvas_or_content,
title=title,
width=width,
height=height,
settings=settings,
)
try:
return canvas.open()
except BaseException:
canvas.close(raise_failure=False)
raise
open_async
¶
open_async(canvas: Canvas[DepsT, StateT], /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, **settings: Unpack[OpenSettings]) -> OpeningTerminal[DepsT, StateT]
open_async(content: Content | None = None, /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float = 60.0, bpm: float = 120.0, effects: Sequence[WritableEffectSpecification] = (), **settings: Unpack[CanvasSettings]) -> OpeningTerminal[None, None]
open_async(content: Content | None = None, /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float = 60.0, bpm: float = 120.0, effects: Sequence[WritableEffectSpecification] = (), state: StateT, **settings: Unpack[CanvasSettings]) -> OpeningTerminal[None, StateT]
open_async(content: Content | None = None, /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float = 60.0, bpm: float = 120.0, effects: Sequence[WritableEffectSpecification] = (), deps: DepsT, **settings: Unpack[CanvasSettings]) -> OpeningTerminal[DepsT, None]
open_async(content: Content | None = None, /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, fps: float = 60.0, bpm: float = 120.0, effects: Sequence[WritableEffectSpecification] = (), deps: DepsT, state: StateT, **settings: Unpack[CanvasSettings]) -> OpeningTerminal[DepsT, StateT]
open_async(canvas_or_content: Canvas[object, object] | Content | None = None, /, *, title: str | None = None, width: int | Percentage | str | None = None, height: int | Percentage | str | None = None, **settings: object) -> OpeningTerminal[DepsT, StateT]
Put a canvas on your screen like open, from a coroutine.
The keywords, the canvas and the errors are the ones open() has; the terminal is
asked what it can do while your event loop goes on running other tasks. Await the result
for the Terminal, or enter it with async with, which closes it and
gives the screen back when the block ends. Errors are raised when it is awaited or
entered.
Then wait with the _async spellings, which let the rest of your program run:
run_async,
iter_async,
keyboard.wait_async and
keyboard.prompt_async.
Parameters:
-
canvas_or_content(Canvas[object, object] | Content | None, default:None) –A canvas from
new(), or content to write into a new canvas. -
title(str | None, default:None) –The window title;
Nonekeeps the canvas's title. -
width(int | Percentage | str | None, default:None) –The width of the region to draw in, in cells or as a percentage of the window; the whole window when neither
widthnorheightis given. -
height(int | Percentage | str | None, default:None) –The height of the region to draw in, in cells or as a percentage of the window.
-
settings(object, default:{}) –The other keywords of
new()exceptrealtime: the terminal settings, the canvas's look,fps,bpm,effects,depsandstate.
Returns:
-
OpeningTerminal[DepsT, StateT]–The opening terminal: await it, or use it in
async with.
Examples:
async def main() -> None:
async with xnano.open_async(height=3, mouse=True) as terminal:
terminal.screen.write('hello')
await terminal.run_async(stop_on='q')
asyncio.run(main())
Source code in xnano/terminal/__init__.py
def open_async(
canvas_or_content: Canvas[object, object] | Content | None = None,
/,
*,
title: str | None = None,
width: int | Percentage | str | None = None,
height: int | Percentage | str | None = None,
**settings: object,
) -> OpeningTerminal[DepsT, StateT]:
"""
Put a canvas on your screen like [`open`][xnano.open], from a coroutine.
The keywords, the canvas and the errors are the ones ``open()`` has; the terminal is
asked what it can do while your event loop goes on running other tasks. Await the result
for the [`Terminal`][xnano.Terminal], or enter it with ``async with``, which closes it and
gives the screen back when the block ends. Errors are raised when it is awaited or
entered.
Then wait with the ``_async`` spellings, which let the rest of your program run:
[`run_async`][xnano.canvas.Canvas.run_async],
[`iter_async`][xnano.canvas.Canvas.iter_async],
[`keyboard.wait_async`][xnano.devices.Keyboard.wait_async] and
[`keyboard.prompt_async`][xnano.devices.Keyboard.prompt_async].
Args:
canvas_or_content: A canvas from ``new()``, or content to write into a new canvas.
title: The window title; ``None`` keeps the canvas's title.
width: The width of the region to draw in, in cells or as a percentage of the
window; the whole window when neither ``width`` nor ``height`` is given.
height: The height of the region to draw in, in cells or as a percentage of the
window.
settings: The other keywords of ``new()`` except ``realtime``: the terminal
settings, the canvas's look, ``fps``, ``bpm``, ``effects``, ``deps`` and ``state``.
Returns:
The opening terminal: await it, or use it in ``async with``.
Examples:
```text
async def main() -> None:
async with xnano.open_async(height=3, mouse=True) as terminal:
terminal.screen.write('hello')
await terminal.run_async(stop_on='q')
asyncio.run(main())
```
"""
if isinstance(canvas_or_content, Canvas):
return cast('Canvas[DepsT, StateT]', canvas_or_content).open_async(
title=title,
width=width,
height=height,
**settings, # type: ignore[arg-type]
)
async def open_new() -> Terminal[DepsT, StateT]:
canvas: Canvas[DepsT, StateT] = _canvas_to_open(
'open_async',
canvas_or_content,
title=title,
width=width,
height=height,
settings=settings,
)
try:
return await canvas.open_async()
except BaseException:
canvas.close(raise_failure=False)
raise
return OpeningTerminal(open_new)