xnano.layout
xnano.layout
¶
xnano.layout
Where things are written and how much room they take.
A Placement is something written on a screen, with its position
and size, which follow the lines written before it unless you say where it goes. A
Region is a rectangle of cells: of a screen, of a placement, or one
built with region or box. Positions and sizes take
a number of cells, a share such as '50%', a word such as 'center' or 'next', or a
expression of xnano.expressions; Point,
Size and Rectangle are plain values measured
in cells.
Classes:
-
Placement–A buffer placed on a canvas, with a position and size that are expressions.
-
Region–A rectangle in the grid of a medium: cells on the screen, or beats by semitones on the timeline.
Functions:
-
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).
Attributes:
-
Axis(TypeAlias) –One number of a position or size:
x,y,widthorheight. -
FlowPosition(TypeAlias) –The word that places something after what was written before it, where
writeputs content -
HorizontalPosition(TypeAlias) –A word that places something inside its parent along
x. -
Percentage(TypeAlias) –A share of the space a size or position is measured against, such as
'50%'. -
RangeBound(TypeAlias) –One end of a range as written: cells, a percentage string, an expression, or
None. -
VerticalPosition(TypeAlias) –A word that places something inside its parent along
y. -
Anchor(TypeAlias) –The
(x, y)pixel inside anArtthat sits at the art's(x, y). -
EdgeBehavior(TypeAlias) –What content does at the edges of its area.
-
Point–A cell position, counted in columns (
x) and rows (y) from the top-left. -
Rectangle–A rectangle of cells, measured from its top-left corner.
-
Size–A width and a height, counted in cells.
-
SizeRule–How much space one child takes along the main axis of a layout.
-
PixelAnchor(TypeAlias) –Which pixel of a cell
Region.pixel_for_cellreturns. -
Resolution(TypeAlias) –The grid a
Regionis measured in.
Axis
module-attribute
¶
Axis: TypeAlias = int | float | Percentage | HorizontalPosition | VerticalPosition | FlowPosition | str | tuple[RangeBound, RangeBound] | NumericExpression
One number of a position or size: x, y, width or height.
12: exactly that many cells.'50%': that share of the parent.- a word that places it inside its parent:
'left','center'or'right'forx, and'top','center'or'bottom'fory. 'next'forxandy: after what was written before it, on the next line by default; seeFlowPosition.- an expression such as
(ParentWidth - Width) // 2orParentWidth * (TimeElapsed % 4 / 4): evaluated again on every frame, withTimeElapsedand the other clock references moving with the canvas's clock. An expression such asPointerPosition.xreads input that the canvas can receive later. Until the input arrives, the placement is not drawn. - a range, a pair
(low, high): not a value but a limit on the values the axis may take. Forxandyit is how far the placement may travel, such as the track of a slider; forwidthandheightit is the smallest and largest size. Whatever is assigned afterwards is held inside the range, and the range stays until another one replaces it. Each bound is a number, a percentage string or an expression, andNoneleaves that side open.
FlowPosition
module-attribute
¶
The word that places something after what was written before it, where write puts content
that is given no position.
y='next' starts a line on the first row below the lines written before it, at column 0
when x is 'next' too; content given a y of its own, such as a status line at
y='bottom', is not one of the lines. x='next' with a y that was given continues on
that row, right after the content written just before, when that content is on the row and
there is room after it; otherwise it starts at column 0. The position is kept up to date:
when a line grows, shrinks or is removed, the lines after it follow.
HorizontalPosition
module-attribute
¶
A word that places something inside its parent along x.
Percentage
module-attribute
¶
Percentage: TypeAlias = Literal['5%', '10%', '15%', '20%', '25%', '30%', '35%', '40%', '45%', '50%', '55%', '60%', '65%', '70%', '75%', '80%', '85%', '90%', '95%', '100%']
A share of the space a size or position is measured against, such as '50%'.
Editors suggest the steps of 5% listed here, and every other percentage, such as '33%' or
'12.5%', works the same way; a parameter that takes a percentage also takes any str.
RangeBound
module-attribute
¶
RangeBound: TypeAlias = Number | Percentage | str | NumericExpression | None
One end of a range as written: cells, a percentage string, an expression, or None.
VerticalPosition
module-attribute
¶
A word that places something inside its parent along y.
Anchor
module-attribute
¶
EdgeBehavior
module-attribute
¶
What content does at the edges of its area.
'clip' lets it go past the edge, where it is not drawn. 'stop' holds it inside the
area when it moves. 'wrap' continues text on the next rows of the area.
Point
module-attribute
¶
Point = _CorePoint
A cell position, counted in columns (x) and rows (y) from the top-left.
Use it where a position is a value of its own, such as the cell of a click, or to add and subtract positions.
import xnano
from xnano.layout import Point
with xnano.new(width=20, height=4) as canvas:
start = Point(2, 1) + Point(1, 0)
canvas.screen.write('here', x=start.x, y=start.y)
assert canvas.screen.render().splitlines()[1] == ' here'
Rectangle
module-attribute
¶
Rectangle = _CoreRectangle
A rectangle of cells, measured from its top-left corner.
Its left and top edges are inclusive and its right and bottom edges are exclusive. Use
it to describe an area, such as the bounds of a placement, and to test whether a
Point falls inside.
import xnano
from xnano.layout import Point, Rectangle
area = Rectangle(2, 1, 10, 2)
with xnano.new(width=20, height=4) as canvas:
canvas.screen.write('box', x=area.x, y=area.y, width=area.width, height=area.height)
assert area.contains(Point(2, 1))
assert not area.contains(Point(12, 1))
assert area.area == 20
Size
module-attribute
¶
Size = _CoreSize
A width and a height, counted in cells.
Use it where a size is a value of its own, such as the size of a canvas.
import xnano
from xnano.layout import Size
with xnano.new(width=20, height=4) as canvas:
assert canvas.screen.size == Size(20, 4)
assert Size(2, 1) + Size(3, 3) == Size(5, 4)
SizeRule
module-attribute
¶
SizeRule = _CoreSizeRule
How much space one child takes along the main axis of a layout.
A rule is a fixed number of cells, a percentage, a share of what is left or a limit.
Pass it where a column of a Table takes a rule instead of a
number of cells.
import xnano
from xnano.layout import SizeRule
from xnano.widgets import Table, TableRow
rows = [TableRow(['name', 'value'])]
table = Table(rows, widths=[SizeRule.cells(6), SizeRule.fill()], width=16, height=1)
with xnano.new(width=16, height=1) as canvas:
canvas.screen.write(table)
assert canvas.screen.render() == 'name value'
PixelAnchor
module-attribute
¶
Which pixel of a cell Region.pixel_for_cell returns.
'top_left' is the top left pixel of the cell, 'center' the pixel in its middle and
'bottom_right' the bottom right pixel.
Resolution
module-attribute
¶
Resolution: TypeAlias = Literal['cells', 'half_blocks', 'braille', 'beats', 'sixteenths', 'milliseconds']
The grid a Region is measured in.
The first three are grids on the screen: 'cells' measures a region in terminal cells,
'half_blocks' in pixels, one by two per cell, and 'braille' in dots, two by four per
cell.
The last three are grids on the timeline: 'beats' measures it in beats, 'sixteenths' in
sixteenth notes (4 per beat) and 'milliseconds' in thousandths of a second, which follows
the tempo. In every timeline grid y is the lowest pitch of the region as a MIDI number and
height is how many semitones it spans.
Placement
¶
Placement(canvas: Canvas[DepsT, StateT], buffer: Buffer, parent_buffer: Buffer | None = None, parent_owner: Canvas[object, object] | Placement[object, object] | None = None)
Bases: _Hooked[DepsT, StateT], _TextModifiers
A buffer placed on a canvas, with a position and size that are expressions.
Assign any of x, y, width and height an Axis:
a number, a percentage of the parent, or an expression. Numbers apply at once;
everything else is evaluated again before every frame, so a placement can follow the
clock, the canvas's size or another buffer without a callback. A placement written with
no position follows the one written before it ('next', see
FlowPosition) until it is given a position of its own;
assigning 'next' makes it follow again.
Assigning a range instead ((0, 20)) limits the axis rather than setting it.
For x and y the range is how far the placement may travel, so a slider's thumb
is a placement whose x is limited to its track; whatever is assigned to it later,
by a drag hook, is held inside the track.
For width and height it is the smallest and largest size.
Percentages and ranges only change when something about the canvas does, so they cost nothing while it is still. An expression is assumed to change with time, so a canvas with one keeps drawing every frame; use a percentage for a layout that only follows the size of the canvas.
An expression can read input that the canvas did not receive yet, such as
PointerPosition before the pointer moves. Then
the placement is not drawn. When each of its axes has a value, it is drawn, and it
follows the input from then on. Until that time, such an axis reads the value that it
had before: 0 for the position of a new placement, and the size of the content for
its size. is_visible keeps the value that you set. A placement that follows the
pointer does not keep the canvas drawing: the canvas draws a frame when the pointer
moves.
Get one from Screen.write or nest a child placement inside
another with Placement.write.
Attributes:
-
core_buffer(Buffer) –The core buffer that is placed.
-
canvas(Canvas[DepsT, StateT]) –The canvas the buffer is placed on.
-
parent(Canvas[DepsT, StateT]) –Symbolic expressions for the parent container's
width,heightandsize. -
root(Canvas[DepsT, StateT]) –Symbolic expressions for the root canvas's
width,height,sizeandtime. -
time(Canvas[DepsT, StateT]) –Symbolic expression for elapsed seconds on the canvas clock.
-
x(int) –The column of the left edge, relative to the parent.
-
y(int) –The row of the top edge, relative to the parent.
-
width(int) –The width in cells.
-
height(int) –The height in cells.
-
right_edge(int) –The first column after the placement,
x + width, relative to the parent. -
bottom_edge(int) –The first row below the placement,
y + height, relative to the parent. -
layer(int) –Placements with a higher layer are drawn over those with a lower one.
-
is_visible(bool) –Whether the placement is shown, as you set it.
-
text(str) –The text shown, line by line.
Examples:
import xnano
from xnano.events import Event
from xnano.expressions import PointerPosition, parent
with xnano.new(width=20, height=3) as canvas:
label = canvas.screen.write('hi')
label.x = (parent.width - label.width) // 2
assert label.x == 9
thumb = canvas.screen.write('#', x=(2, 10))
thumb.x = 40
assert thumb.x == 10
thumb.x = 0
assert thumb.x == 2
with xnano.new(width=20, height=3) as canvas:
marker = canvas.screen.write('+', x=PointerPosition.x, y=PointerPosition.y)
assert canvas.screen.render().strip() == ''
canvas.push(Event.mouse_event(column=4, row=1, kind='move'))
canvas.deliver_events()
assert (marker.x, marker.y) == (4, 1)
Place a buffer on a canvas. Get one from canvas.screen.write instead of calling this.
Parameters:
-
canvas(Canvas[DepsT, StateT]) –The canvas the buffer is placed on.
-
buffer(Buffer) –The buffer that is placed.
-
parent_buffer(Buffer | None, default:None) –The parent buffer
bufferis attached to (defaults tocanvas.screen.core_buffer). -
parent_owner(Canvas[object, object] | Placement[object, object] | None, default:None) –The placement or canvas that owns
parent_buffer(defaults tocanvas).
- API Reference xnano
- API Reference xnano
-
API Reference
xnano
-
xnanoContext -
xnano.ai
ai -
xnano.ai.capabilities
capabilitiesCanvasCapability -
xnano.ai.models.text
text -
xnano.components
componentsComponentContext -
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
hooksContext -
xnano.layout
layout -
xnano.operations
operations
-
Methods:
-
__setattr__–Set an attribute, or raise
AttributeErrorfor an unknown public name. -
bold–Make the text bold, or undo it with
False; the same as settingis_bold. -
dim–Dim the text, or undo it with
False; the same as settingis_dim. -
italic–Make the text italic, or undo it with
False; the same as settingis_italic. -
underline–Underline the text, or undo it with
False; the same as settingis_underlined. -
blink–Make the text blink, or undo it with
False; the same as settingis_blinking. -
reverse–Swap the foreground and background, or undo it with
False; the same as settingis_reversed. -
hidden–Hide the text, or undo it with
False; the same as settingis_hidden. -
crossed_out–Strike the text through, or undo it with
False; the same as settingis_crossed_out. -
hook–Call a function when something happens on this canvas or placement.
-
local–Convert a cell of the screen into a cell of this placement.
-
move–Move the placement by a number of cells along each axis.
-
up–Move the placement up by
countrows; seemove. -
down–Move the placement down by
countrows; seemove. -
left–Move the placement left by
countcolumns; seemove. -
right–Move the placement right by
countcolumns; seemove. -
__contains__–Whether a screen cell or a whole area is inside the cells that the placement takes.
-
overlaps–Whether the cells that the placement takes and another area share at least one cell.
-
render–Draw the placement, with its border, padding and nested placements, to a string.
-
__rich_console__–Show the placement 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.
-
refresh–Draw a placement made from a component again, at the next frame.
-
write–Add a child placement inside this placement.
-
update–Change this placement's content with operations, styles or effects.
-
__or__–Apply
operationto this placement and returnself. -
__ior__–Apply
operationto this placement in place and returnself. -
remove–Take the buffer off the canvas. Removing twice is harmless.
Source code in xnano/layout/_placement.py
def __init__(
self,
canvas: Canvas[DepsT, StateT],
buffer: _core.Buffer,
parent_buffer: _core.Buffer | None = None,
parent_owner: Canvas[object, object] | Placement[object, object] | None = None,
) -> None:
"""
Place a buffer on a canvas. Get one from ``canvas.screen.write`` instead of calling this.
Args:
canvas: The canvas the buffer is placed on.
buffer: The buffer that is placed.
parent_buffer: The parent buffer ``buffer`` is attached to (defaults to
``canvas.screen.core_buffer``).
parent_owner: The placement or canvas that owns ``parent_buffer`` (defaults to
``canvas``).
"""
super().__init__()
self._canvas = canvas
self._buffer = buffer
self._parent_buffer: _core.Buffer = (
canvas._root if parent_buffer is None else parent_buffer
)
self._parent_owner: Canvas[object, object] | Placement[object, object] = cast(
'Canvas[object, object] | Placement[object, object]',
canvas if parent_owner is None else parent_owner,
)
self._bindings: dict[AxisName, tuple[NumericExpression, bool]] = {}
self._limits: dict[AxisName, tuple[Bound | None, Bound | None, bool]] = {}
self._seal()
color
property
¶
color: Colors
border
property
writable
¶
border: BorderAppearance
The border: its kind, a setting for each side, its color and its title.
Assign 'plain', 'rounded', 'double' or 'thick' to draw a border
on every side, True for 'plain' and False to remove it. It works on any
content, not only on text.
The border, padding and margin are drawn around the content, so the placement grows by the cells they take. A widget with no size of its own is shrunk to fit its parent, border included.
Examples:
padding
property
writable
¶
padding: PaddingAppearance
The space between the border and the content, edge by edge.
Assign a number of cells, a percentage such as '10%' or a dictionary such as
{'vertical': 1, 'horizontal': 2}, or set one edge with padding.left = 2.
margin
property
writable
¶
margin: MarginAppearance
The transparent space outside the border, edge by edge, set like padding.
core_buffer
property
¶
core_buffer: Buffer
The core buffer of the content, which core operations and widgets draw into.
A placement with a border, padding or margin around content that is not plain text draws that decoration in a buffer of its own; this is the buffer inside it.
state
property
¶
state: StateNamespace
State that belongs to this placement, read with get and written with set.
It is the state of one placement, separate from the canvas's own
(Canvas.state) and from that of other placements, and
it is deleted when the placement is removed. Asking a removed placement for its state
raises a TerminalClosedError, so finish with the
state before calling remove. See StateNamespace for the
path rules.
Examples:
x
property
writable
¶
x: int
The column of the left edge, relative to the parent.
If x reads input that the canvas did not receive yet, the placement is not
drawn, and x is the value that it had before: 0 for a new placement.
y
property
writable
¶
y: int
The row of the top edge, relative to the parent.
If y reads input that the canvas did not receive yet, the placement is not
drawn, and y is the value that it had before: 0 for a new placement.
width
property
writable
¶
width: int
The width in cells.
If width reads input that the canvas did not receive yet, the placement is not
drawn, and width is the value that it had before: the width of the content
for a new placement.
height
property
writable
¶
height: int
The height in cells.
If height reads input that the canvas did not receive yet, the placement is not
drawn, and height is the value that it had before: the height of the content
for a new placement.
right_edge
property
¶
right_edge: int
The first column after the placement: x + width, in cells, relative to the parent.
Like x and width, it is a number of cells at the moment you read it. If x
or width is an expression, it uses the value that the canvas calculated last.
Examples:
bottom_edge
property
¶
bottom_edge: int
The first row below the placement: y + height, in cells, relative to the parent.
Like y and height, it is a number of cells at the moment you read it. If y
or height is an expression, it uses the value that the canvas calculated last.
Examples:
layer
property
writable
¶
layer: int
Placements with a higher layer are drawn over those with a lower one.
is_visible
property
writable
¶
is_visible: bool
Whether the placement is shown. Set it to False to hide the placement.
A placement whose position or size reads input that the canvas did not receive yet
is not drawn. is_visible keeps the value that you set, and the placement is
drawn when the input arrives, if is_visible is True.
edges
property
writable
¶
edges: EdgeBehavior
What this content does at the edges of its area: 'clip', 'stop' or 'wrap'.
Its area is what it is written on: the canvas, the placement around it, or its slot
on a canvas with a 'column' or 'row' layout. Content written on the outer
canvas inside the with block of a canvas created in it lives in that canvas's
area, and follows that canvas's edges. 'clip' lets it move past an
edge, where it is not drawn. 'stop' holds it inside the area whenever it moves
or is assigned a position, so a moved piece stops at the edge; a range given for
x or y takes the place of the area's edges on that axis. 'wrap' continues
text on the next rows of the area, wrapped again whenever the area's width changes;
on content that is not text it is the same as 'clip'. Assign None to follow
what it is written on again: the setting of the placement around it, or the canvas's
edges.
Raises:
-
ValueError–The value is not
'clip','stop','wrap'orNone.
Examples:
import xnano
with xnano.new(width=10, height=3) as canvas:
ball = canvas.screen.write('o', edges='stop')
ball.right(50).down(50)
assert (ball.x, ball.y) == (9, 2)
note = canvas.screen.write('one two three', x=0, y=0, edges='wrap')
assert note.text == 'one two three'
assert canvas.screen.render().splitlines()[:2] == ['one two', 'three']
fx
property
¶
The visual effects of this placement, one method for each effect.
placement.fx.fade_to(foreground='red') starts a fade on the placement at once, from
a hook or from anywhere else, and placement.fx.clear() stops what was started here.
See WritableEffectProperties.
Examples:
import xnano
from xnano.events import Event
with xnano.new(width=20, height=1) as canvas:
content = canvas.screen.write('Press e')
@canvas.hook(on='key')
def flash(context: xnano.Context) -> None:
if context.keyboard.key == 'e':
content.fx.fade_to(foreground='red', duration_milliseconds=200)
canvas.push(Event.key_press('e'))
canvas.clock.step()
assert len(content.fx.active) == 1
region
property
¶
The cells of the content as a Region: read and write
placement.region[x, y].
Around text with a border, padding or margin, the region is the area inside them. The
same holds for a box from box whose look the placement draws: a box
with a relative size, a box written with a width or a height, and a box
written with a look. A box written as it is, with no size and no look, is a snapshot
whose border is part of its cells, so the region includes the border.
Examples:
text
property
writable
¶
text: str
The text shown, line by line, without styles.
Assign a string or a StyledText to change what a text
placement says. The placement grows or shrinks to fit the text, unless its size was
set. Styled text is drawn with the styles of its spans, and the colors and modifiers
of the placement go over them.
Raises:
-
TypeError–The value is not a string or a
StyledText.
Examples:
import xnano
from xnano.styles import StyledText
with xnano.new(width=20, height=1) as canvas:
log = canvas.screen.write('starting')
log.text = StyledText.from_ansi('\x1b[31merror\x1b[0m: disk full')
assert log.text == 'error: disk full'
assert log.width == 16
assert log.core_buffer[0, 0].foreground == xnano.Color('red')
style
property
writable
¶
style: Style | None
A ready-made style that the colors and modifiers are applied over.
__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)
bold
¶
bold(value: bool = True) -> Self
Make the text bold, or undo it with False; the same as setting is_bold.
Parameters:
-
value(bool, default:True) –Whether the text is bold.
Returns:
-
Self–This canvas or placement, so calls can chain.
Raises:
-
TypeError–valueis notTrueorFalse.
Examples:
import xnano
with xnano.new(width=12, height=1) as canvas:
title = canvas.screen.write('Ready').bold().underline()
assert title.is_bold and title.is_underlined
title.bold(False)
assert not title.is_bold
Source code in xnano/styles/_owners.py
def bold(self, value: bool = True) -> Self:
"""
Make the text bold, or undo it with ``False``; the same as setting ``is_bold``.
Args:
value: Whether the text is bold.
Returns:
This canvas or placement, so calls can chain.
Raises:
TypeError: ``value`` is not ``True`` or ``False``.
Examples:
```python
import xnano
with xnano.new(width=12, height=1) as canvas:
title = canvas.screen.write('Ready').bold().underline()
assert title.is_bold and title.is_underlined
title.bold(False)
assert not title.is_bold
```
"""
self.is_bold = value
return self
dim
¶
dim(value: bool = True) -> Self
Dim the text, or undo it with False; the same as setting is_dim.
Parameters:
-
value(bool, default:True) –Whether the text is dimmed.
Returns:
-
Self–This canvas or placement, so calls can chain.
Raises:
-
TypeError–valueis notTrueorFalse.
Source code in xnano/styles/_owners.py
def dim(self, value: bool = True) -> Self:
"""
Dim the text, or undo it with ``False``; the same as setting ``is_dim``.
Args:
value: Whether the text is dimmed.
Returns:
This canvas or placement, so calls can chain.
Raises:
TypeError: ``value`` is not ``True`` or ``False``.
"""
self.is_dim = value
return self
italic
¶
italic(value: bool = True) -> Self
Make the text italic, or undo it with False; the same as setting is_italic.
Parameters:
-
value(bool, default:True) –Whether the text is italic.
Returns:
-
Self–This canvas or placement, so calls can chain.
Raises:
-
TypeError–valueis notTrueorFalse.
Source code in xnano/styles/_owners.py
def italic(self, value: bool = True) -> Self:
"""
Make the text italic, or undo it with ``False``; the same as setting ``is_italic``.
Args:
value: Whether the text is italic.
Returns:
This canvas or placement, so calls can chain.
Raises:
TypeError: ``value`` is not ``True`` or ``False``.
"""
self.is_italic = value
return self
underline
¶
underline(value: bool = True) -> Self
Underline the text, or undo it with False; the same as setting is_underlined.
Parameters:
-
value(bool, default:True) –Whether the text is underlined.
Returns:
-
Self–This canvas or placement, so calls can chain.
Raises:
-
TypeError–valueis notTrueorFalse.
Source code in xnano/styles/_owners.py
def underline(self, value: bool = True) -> Self:
"""
Underline the text, or undo it with ``False``; the same as setting ``is_underlined``.
Args:
value: Whether the text is underlined.
Returns:
This canvas or placement, so calls can chain.
Raises:
TypeError: ``value`` is not ``True`` or ``False``.
"""
self.is_underlined = value
return self
blink
¶
blink(value: bool = True) -> Self
Make the text blink, or undo it with False; the same as setting is_blinking.
Parameters:
-
value(bool, default:True) –Whether the text blinks.
Returns:
-
Self–This canvas or placement, so calls can chain.
Raises:
-
TypeError–valueis notTrueorFalse.
Source code in xnano/styles/_owners.py
def blink(self, value: bool = True) -> Self:
"""
Make the text blink, or undo it with ``False``; the same as setting ``is_blinking``.
Args:
value: Whether the text blinks.
Returns:
This canvas or placement, so calls can chain.
Raises:
TypeError: ``value`` is not ``True`` or ``False``.
"""
self.is_blinking = value
return self
reverse
¶
reverse(value: bool = True) -> Self
Swap the foreground and background, or undo it with False; the same as setting is_reversed.
Parameters:
-
value(bool, default:True) –Whether foreground and background are swapped.
Returns:
-
Self–This canvas or placement, so calls can chain.
Raises:
-
TypeError–valueis notTrueorFalse.
Source code in xnano/styles/_owners.py
def reverse(self, value: bool = True) -> Self:
"""
Swap the foreground and background, or undo it with ``False``; the same as setting ``is_reversed``.
Args:
value: Whether foreground and background are swapped.
Returns:
This canvas or placement, so calls can chain.
Raises:
TypeError: ``value`` is not ``True`` or ``False``.
"""
self.is_reversed = value
return self
hidden
¶
hidden(value: bool = True) -> Self
Hide the text, or undo it with False; the same as setting is_hidden.
Parameters:
-
value(bool, default:True) –Whether the text is hidden.
Returns:
-
Self–This canvas or placement, so calls can chain.
Raises:
-
TypeError–valueis notTrueorFalse.
Source code in xnano/styles/_owners.py
def hidden(self, value: bool = True) -> Self:
"""
Hide the text, or undo it with ``False``; the same as setting ``is_hidden``.
Args:
value: Whether the text is hidden.
Returns:
This canvas or placement, so calls can chain.
Raises:
TypeError: ``value`` is not ``True`` or ``False``.
"""
self.is_hidden = value
return self
crossed_out
¶
crossed_out(value: bool = True) -> Self
Strike the text through, or undo it with False; the same as setting is_crossed_out.
Parameters:
-
value(bool, default:True) –Whether the text is struck through.
Returns:
-
Self–This canvas or placement, so calls can chain.
Raises:
-
TypeError–valueis notTrueorFalse.
Source code in xnano/styles/_owners.py
def crossed_out(self, value: bool = True) -> Self:
"""
Strike the text through, or undo it with ``False``; the same as setting ``is_crossed_out``.
Args:
value: Whether the text is struck through.
Returns:
This canvas or placement, so calls can chain.
Raises:
TypeError: ``value`` is not ``True`` or ``False``.
"""
self.is_crossed_out = value
return self
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)
local
¶
Convert a cell of the screen into a cell of this placement.
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)
assert placement.local(Point(11, 1)) == Point(1, 0)
Source code in xnano/layout/_placement.py
def local(self, point: _core.Point) -> _core.Point:
"""
Convert a cell of the screen into a cell of this placement.
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)
assert placement.local(Point(11, 1)) == Point(1, 0)
```
"""
point = check_point(point)
bounds = self._buffer._absolute_bounds
return _core.Point(point.x - bounds.x, point.y - bounds.y)
move
¶
Move the placement by a number of cells along each axis.
The move is held inside a range on the axis
(x=(0, 39)), so a slider's thumb stops at the ends of its track. A position that
is an expression keeps its expression and shifts it. Piping xnano.operations.Move onto
the placement is also held inside its ranges.
Parameters:
-
x(int, default:0) –Columns to move right; a negative number moves left.
-
y(int, default:0) –Rows to move down; a negative number moves up.
Returns:
-
Placement[DepsT, StateT]–The placement, so calls can chain.
Raises:
-
TypeError–An amount is not a whole number.
Examples:
import xnano
with xnano.new(width=20, height=3) as canvas:
thumb = canvas.screen.write('#', x=(0, 10), y=1)
thumb.move(x=4, y=-1)
assert (thumb.x, thumb.y) == (4, 0)
thumb.right(99)
assert thumb.x == 10
Source code in xnano/layout/_placement.py
def move(self, x: int = 0, y: int = 0) -> Placement[DepsT, StateT]:
"""
Move the placement by a number of cells along each axis.
The move is held inside a range on the axis
(``x=(0, 39)``), so a slider's thumb stops at the ends of its track. A position that
is an expression keeps its expression and shifts it. Piping ``xnano.operations.Move`` onto
the placement is also held inside its ranges.
Args:
x: Columns to move right; a negative number moves left.
y: Rows to move down; a negative number moves up.
Returns:
The placement, so calls can chain.
Raises:
TypeError: An amount is not a whole number.
Examples:
```python
import xnano
with xnano.new(width=20, height=3) as canvas:
thumb = canvas.screen.write('#', x=(0, 10), y=1)
thumb.move(x=4, y=-1)
assert (thumb.x, thumb.y) == (4, 0)
thumb.right(99)
assert thumb.x == 10
```
"""
horizontal = check_cells(x, 'x')
vertical = check_cells(y, 'y')
self._require_attached()
steps: tuple[tuple[AxisName, int], ...] = (('x', horizontal), ('y', vertical))
for axis, step in steps:
if step == 0:
continue
with self._canvas._lock:
binding = self._bindings.get(axis)
if binding is None:
self._set_axis(axis, getattr(self._buffer, axis) + step)
continue
# An expression moves only as far as its range or edges let it, so moves past an
# edge do not pile up and have to be undone before the opposite move shows.
current = getattr(self._buffer, axis)
try:
target = self._clamp(axis, current + step, self._resolve_offline)
except _core.RuntimeRequiredError:
target = current + step
self._set_axis(axis, binding[0] + _round_half_away(target - current))
return self
up
¶
Move the placement up by count rows; see move.
Parameters:
-
count(int, default:1) –How many rows to move.
Raises:
-
TypeError–countis not a whole number. -
ValueError–countis negative.
Source code in xnano/layout/_placement.py
def up(self, count: int = 1) -> Placement[DepsT, StateT]:
"""
Move the placement up by ``count`` rows; see [`move`][xnano.layout.Placement.move].
Args:
count: How many rows to move.
Raises:
TypeError: ``count`` is not a whole number.
ValueError: ``count`` is negative.
"""
return self.move(y=-check_count(count, verb='up', opposite='down'))
down
¶
Move the placement down by count rows; see move.
Parameters:
-
count(int, default:1) –How many rows to move.
Raises:
-
TypeError–countis not a whole number. -
ValueError–countis negative.
Source code in xnano/layout/_placement.py
def down(self, count: int = 1) -> Placement[DepsT, StateT]:
"""
Move the placement down by ``count`` rows; see [`move`][xnano.layout.Placement.move].
Args:
count: How many rows to move.
Raises:
TypeError: ``count`` is not a whole number.
ValueError: ``count`` is negative.
"""
return self.move(y=check_count(count, verb='down', opposite='up'))
left
¶
Move the placement left by count columns; see move.
Parameters:
-
count(int, default:1) –How many columns to move.
Raises:
-
TypeError–countis not a whole number. -
ValueError–countis negative.
Source code in xnano/layout/_placement.py
def left(self, count: int = 1) -> Placement[DepsT, StateT]:
"""
Move the placement left by ``count`` columns; see [`move`][xnano.layout.Placement.move].
Args:
count: How many columns to move.
Raises:
TypeError: ``count`` is not a whole number.
ValueError: ``count`` is negative.
"""
return self.move(x=-check_count(count, verb='left', opposite='right'))
right
¶
Move the placement right by count columns; see move.
Parameters:
-
count(int, default:1) –How many columns to move.
Raises:
-
TypeError–countis not a whole number. -
ValueError–countis negative.
Source code in xnano/layout/_placement.py
def right(self, count: int = 1) -> Placement[DepsT, StateT]:
"""
Move the placement right by ``count`` columns; see [`move`][xnano.layout.Placement.move].
Args:
count: How many columns to move.
Raises:
TypeError: ``count`` is not a whole number.
ValueError: ``count`` is negative.
"""
return self.move(x=check_count(count, verb='right', opposite='left'))
__contains__
¶
Whether a screen cell or a whole area is inside the cells that the placement takes.
These cells include the border, the padding and the margin of the placement. Its
mouse hooks hear the mouse in the same cells. The region of the placement is only the
area inside the border, padding and margin. For a placement with a border, padding or
margin, item in placement and item in placement.region can give different
answers. See Region for the comparison of areas.
Parameters:
-
item(object) –
Examples:
import xnano
with xnano.new(width=20, height=4) as canvas:
button = canvas.screen.write('ok', x=2, y=1, border='rounded')
assert (2, 1) in button and (6, 1) not in button
assert (2, 1) not in button.region
assert button.region in button
Source code in xnano/layout/_placement.py
def __contains__(self, item: object) -> bool:
"""
Whether a screen cell or a whole area is inside the cells that the placement takes.
These cells include the border, the padding and the margin of the placement. Its
mouse hooks hear the mouse in the same cells. The region of the placement is only the
area inside the border, padding and margin. For a placement with a border, padding or
margin, ``item in placement`` and ``item in placement.region`` can give different
answers. See [`Region`][xnano.layout.Region] for the comparison of areas.
Args:
item: A screen cell as a ``(x, y)`` pair of numbers or a
[`Point`][xnano_core.Point], such as ``context.mouse.position``. It can also be
an area: a [`Region`][xnano.layout.Region], a placement or a
[`Screen`][xnano.devices.Screen]. A placement counts as all the cells that it
takes. Other values are not inside.
Examples:
```python
import xnano
with xnano.new(width=20, height=4) as canvas:
button = canvas.screen.write('ok', x=2, y=1, border='rounded')
assert (2, 1) in button and (6, 1) not in button
assert (2, 1) not in button.region
assert button.region in button
```
"""
return item in self._screen_area()
overlaps
¶
overlaps(other: Point | tuple[float, float] | Region | Placement[Any, Any] | Screen[Any, Any]) -> bool
Whether the cells that the placement takes and another area share at least one cell.
These cells include the border, the padding and the margin of the placement, as with
in. For a placement with a border, padding or margin,
placement.overlaps(other) and placement.region.overlaps(other) can give
different answers. See Region.overlaps.
Parameters:
Returns:
-
bool–Truewhen the two share a cell, or when the cell is inside the placement.
Raises:
-
TypeError–otheris not an area or a screen cell.
Examples:
import xnano
with xnano.new(width=20, height=6) as canvas:
basket = canvas.screen.write('[___]', x=5, y=5)
apple = canvas.screen.write('o', x=7, y=4)
assert not basket.overlaps(apple)
apple.down()
assert basket.overlaps(apple) and apple.overlaps(basket)
card = canvas.screen.write('card', x=12, y=0, border='plain')
assert card.overlaps((12, 0)) and not card.region.overlaps((12, 0))
Source code in xnano/layout/_placement.py
def overlaps(
self,
other: _core.Point
| tuple[float, float]
| Region
| Placement[Any, Any]
| Screen[Any, Any],
) -> bool:
"""
Whether the cells that the placement takes and another area share at least one cell.
These cells include the border, the padding and the margin of the placement, as with
``in``. For a placement with a border, padding or margin,
``placement.overlaps(other)`` and ``placement.region.overlaps(other)`` can give
different answers. See [`Region.overlaps`][xnano.layout.Region.overlaps].
Args:
other: An area: a [`Region`][xnano.layout.Region], a placement or a
[`Screen`][xnano.devices.Screen]. A placement counts as all the cells that it
takes. A screen cell as a ``(x, y)`` pair of numbers or a
[`Point`][xnano_core.Point] overlaps when it is inside.
Returns:
``True`` when the two share a cell, or when the cell is inside the placement.
Raises:
TypeError: ``other`` is not an area or a screen cell.
Examples:
```python
import xnano
with xnano.new(width=20, height=6) as canvas:
basket = canvas.screen.write('[___]', x=5, y=5)
apple = canvas.screen.write('o', x=7, y=4)
assert not basket.overlaps(apple)
apple.down()
assert basket.overlaps(apple) and apple.overlaps(basket)
card = canvas.screen.write('card', x=12, y=0, border='plain')
assert card.overlaps((12, 0)) and not card.region.overlaps((12, 0))
```
"""
return self._screen_area().overlaps(other)
render
¶
Draw the placement, with its border, padding and nested placements, to a string.
Parameters:
-
format(Literal['text', 'ansi'], default:'text') –'text'for the characters only,'ansi'with colors and styles.
Examples:
import xnano
with xnano.new(width=10, height=3) as canvas:
card = canvas.screen.write('hi', border='rounded')
assert card.render().splitlines() == ['╭──╮', '│hi│', '╰──╯']
Source code in xnano/layout/_placement.py
def render(self, *, format: Literal['text', 'ansi'] = 'text') -> str:
"""
Draw the placement, with its border, padding and nested placements, to a string.
Args:
format: ``'text'`` for the characters only, ``'ansi'`` with colors and styles.
Examples:
```python
import xnano
with xnano.new(width=10, height=3) as canvas:
card = canvas.screen.write('hi', border='rounded')
assert card.render().splitlines() == ['╭──╮', '│hi│', '╰──╯']
```
"""
self._flush_look()
return self._buffer.render(format=format)
__rich_console__
¶
Show the placement in rich and Textual, with its colors and styles.
Rich shows what render draws: the placement
with its border, padding and nested placements. If a line is longer than the space
that rich gives it, rich cuts the line. Rich must be installed.
Source code in xnano/layout/_placement.py
def __rich_console__(
self, console: RichConsole, options: RichConsoleOptions
) -> RichRenderResult:
"""
Show the placement in rich and Textual, with its colors and styles.
Rich shows what [`render`][xnano.layout.Placement.render] draws: the placement
with its border, padding and nested placements. If a line is longer than the space
that rich gives it, rich cuts the line. Rich must be installed.
"""
from rich.text import Text as RichText
yield RichText.from_ansi(
self.render(format='ansi'), no_wrap=True, overflow='crop'
)
__rich_measure__
¶
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/layout/_placement.py
def __rich_measure__(
self, console: RichConsole, options: RichConsoleOptions
) -> RichMeasurement:
"""
Tell rich the width of what it shows, so that rich keeps it whole when it can.
A frame of cells cannot wrap, so its smallest and its largest width are the same.
Rich uses this width to lay out panels, columns and nested tables. In a rich
``Table``, add the column with ``no_wrap=True``, so that rich makes the other
columns narrower before it cuts this one.
"""
from rich.measure import Measurement as RichMeasurement
width = self.width
return RichMeasurement(width, width)
refresh
¶
Draw a placement made from a component again, at the next frame.
A component is evaluated once, and again only when it read something that changes. When
something it does not track changes, such as a field of a class-based component or a
value in context.deps, call this to evaluate it again. A placement that was not made
from a component has nothing to evaluate, so this does nothing.
Examples:
import xnano
@xnano.writable
def counter(context: xnano.Context) -> str:
return str(context.deps['count'])
dependencies = {'count': 0}
with xnano.new(width=4, height=1, deps=dependencies) as canvas:
placement = canvas.screen.write(counter)
dependencies['count'] = 7
placement.refresh()
canvas.clock.step()
assert canvas.screen.render().strip() == '7'
Source code in xnano/layout/_placement.py
def refresh(self) -> None:
"""
Draw a placement made from a component again, at the next frame.
A component is evaluated once, and again only when it read something that changes. When
something it does not track changes, such as a field of a class-based component or a
value in ``context.deps``, call this to evaluate it again. A placement that was not made
from a component has nothing to evaluate, so this does nothing.
Examples:
```python
import xnano
@xnano.writable
def counter(context: xnano.Context) -> str:
return str(context.deps['count'])
dependencies = {'count': 0}
with xnano.new(width=4, height=1, deps=dependencies) as canvas:
placement = canvas.screen.write(counter)
dependencies['count'] = 7
placement.refresh()
canvas.clock.step()
assert canvas.screen.render().strip() == '7'
```
"""
driver = self._driver
if driver is not None:
driver.refresh()
write
¶
write(content: Content | Canvas[WrittenDepsT, WrittenStateT] | None = None, /, *, x: Axis = 'next', y: Axis = 'next', width: Axis | None = None, height: Axis | None = None, layer: int = 0, lock: bool = False, edges: EdgeBehavior | None = None, effects: Sequence[WritableEffectSpecification] = (), style: Style | None = None, foreground: ColorValue | None = None, background: ColorValue | None = None, bold: bool = False, dim: bool = False, italic: bool = False, underline: bool = False, blink: bool = False, reverse: bool = False, hidden: bool = False, crossed_out: bool = False, title: str | None = None, border: BorderKind | bool | None = None, border_style: Style | None = None, padding: Spacing | None = None, margin: Spacing | None = None, theme: ThemeName | None = None) -> Placement[DepsT, StateT]
Add a child placement inside this placement.
A child placement's x, y, width and height are measured relative to
this placement's buffer, so track.write('█', x=(0, track.width - 1), y=0) moves
inside track. Children given no position go on the next line inside this
placement, as Screen.write puts them on a canvas. To change this placement with an operation, a style or an effect, use
update.
A box from box with a percentage, expression or state reference size is
measured against this placement and drawn again when it changes size; see
Screen.write for how the look given here applies over
the look of the box.
Parameters:
-
content(Content | Canvas[WrittenDepsT, WrittenStateT] | None, default:None) –Child content to place inside this buffer.
-
x(Axis, default:'next') –Column of the child's left edge, relative to this placement;
'next', the default, follows what was written inside it before. -
y(Axis, default:'next') –Row of the child's top edge, relative to this placement;
'next', the default, is the first row below what was written inside it before. -
width(Axis | None, default:None) –Width of the child in cells.
-
height(Axis | None, default:None) –Height of the child in cells.
-
layer(int, default:0) –Layer ordering among siblings.
-
lock(bool, default:False) –Lock dynamic axes to their initial values.
-
edges(EdgeBehavior | None, default:None) –What the content does at the edges of its area:
'clip','stop'or'wrap'; seePlacement.edges. Left out, it follows what it is written on. -
effects(Sequence[WritableEffectSpecification], default:()) –Effects to start on the child, as dictionaries with a
kindkey. -
style(Style | None, default:None) –Ready-made
Stylefor text. -
foreground(ColorValue | None, default:None) –Text foreground color.
-
background(ColorValue | None, default:None) –Text background color.
-
bold(bool, default:False) –Whether text is bold.
-
dim(bool, default:False) –Whether text is dimmed.
-
italic(bool, default:False) –Whether text is italic.
-
underline(bool, default:False) –Whether text is underlined.
-
blink(bool, default:False) –Whether text blinks.
-
reverse(bool, default:False) –Whether foreground and background are swapped.
-
hidden(bool, default:False) –Whether text is hidden.
-
crossed_out(bool, default:False) –Whether text is struck through.
-
title(str | None, default:None) –Title for a box around text.
-
border(BorderKind | bool | None, default:None) –The kind of border for a box around the content, a
BorderKindsuch as'plain','rounded','double'or'thick';Truefor'plain'andFalsefor none. -
border_style(Style | None, default:None) –Style for the box's border.
-
padding(Spacing | None, default:None) –Space between the border and the text; see
Screen.write. -
margin(Spacing | None, default:None) –Space outside the box, in the same forms.
-
theme(ThemeName | None, default:None) –The name of a theme for this content, in place of the theme of the canvas; see
ThemeName. A theme gives text, borders and widgets its colors, unless they are given their own.
Source code in xnano/layout/_placement.py
@refuse_unknown_keywords
def write(
self,
content: Content | Canvas[WrittenDepsT, WrittenStateT] | None = None,
/,
*,
x: Axis = 'next',
y: Axis = 'next',
width: Axis | None = None,
height: Axis | None = None,
layer: int = 0,
lock: bool = False,
edges: EdgeBehavior | None = None,
effects: Sequence[WritableEffectSpecification] = (),
style: _core.Style | None = None,
foreground: ColorValue | None = None,
background: ColorValue | None = None,
bold: bool = False,
dim: bool = False,
italic: bool = False,
underline: bool = False,
blink: bool = False,
reverse: bool = False,
hidden: bool = False,
crossed_out: bool = False,
title: str | None = None,
border: _core.BorderKind | bool | None = None,
border_style: _core.Style | None = None,
padding: Spacing | None = None,
margin: Spacing | None = None,
theme: ThemeName | None = None,
) -> Placement[DepsT, StateT]:
"""
Add a child placement inside this placement.
A child placement's ``x``, ``y``, ``width`` and ``height`` are measured relative to
this placement's buffer, so ``track.write('█', x=(0, track.width - 1), y=0)`` moves
inside ``track``. Children given no position go on the next line inside this
placement, as [`Screen.write`][xnano.devices.Screen.write] puts them on a canvas. To change this placement with an operation, a style or an effect, use
[`update`][xnano.layout.Placement.update].
A box from [`box`][xnano.box] with a percentage, expression or state reference size is
measured against this placement and drawn again when it changes size; see
[`Screen.write`][xnano.devices.Screen.write] for how the look given here applies over
the look of the box.
Args:
content: Child content to place inside this buffer.
x: Column of the child's left edge, relative to this placement; ``'next'``, the
default, follows what was written inside it before.
y: Row of the child's top edge, relative to this placement; ``'next'``, the
default, is the first row below what was written inside it before.
width: Width of the child in cells.
height: Height of the child in cells.
layer: Layer ordering among siblings.
lock: Lock dynamic axes to their initial values.
edges: What the content does at the edges of its area: ``'clip'``, ``'stop'`` or
``'wrap'``; see [`Placement.edges`][xnano.layout.Placement.edges]. Left
out, it follows what it is written on.
effects: Effects to start on the child, as dictionaries with a ``kind`` key.
style: Ready-made [`Style`][xnano.styles.Style] for text.
foreground: Text foreground color.
background: Text background color.
bold: Whether text is bold.
dim: Whether text is dimmed.
italic: Whether text is italic.
underline: Whether text is underlined.
blink: Whether text blinks.
reverse: Whether foreground and background are swapped.
hidden: Whether text is hidden.
crossed_out: Whether text is struck through.
title: Title for a box around text.
border: The kind of border for a box around the content, a
[`BorderKind`][xnano.styles.BorderKind] such as ``'plain'``, ``'rounded'``,
``'double'`` or ``'thick'``; ``True`` for ``'plain'`` and ``False`` for none.
border_style: Style for the box's border.
padding: Space between the border and the text; see
[`Screen.write`][xnano.devices.Screen.write].
margin: Space outside the box, in the same forms.
theme: The name of a theme for this content, in place of the theme of the canvas;
see [`ThemeName`][xnano.themes.ThemeName]. A theme gives text, borders and
widgets its colors, unless they are given their own.
"""
self._require_attached()
if isinstance(content, Region):
content._require_drawable('placement.write()')
width, height = content._written_size(width, height)
if edges is not None:
edges = check_edges(edges)
look = self._appearance
if look is not None and self._decorated is None and self._has_frame(look):
self._has_nested = True
self._look_changed()
self._flush_look()
placement = self._canvas._place_on(
self._content,
content,
parent_owner=cast('Placement[object, object]', self),
x=x,
y=y,
width=width,
height=height,
layer=layer,
lock=lock,
style=style,
foreground=foreground,
background=background,
bold=bold,
dim=dim,
italic=italic,
underline=underline,
blink=blink,
reverse=reverse,
hidden=hidden,
crossed_out=crossed_out,
title=title,
border=border,
border_style=border_style,
padding=padding,
margin=margin,
theme=theme,
)
if effects:
apply_effects(cast('Placement[object, object]', placement), effects)
placement._take_edges(edges, content)
return placement
update
¶
Change this placement's content with operations, styles or effects.
Parameters:
-
operations(Operation | Style, default:()) –What to apply, in order: an operation, a contextual operation, a style, or an effect such as
Effect.dissolve(duration_milliseconds=500).
Examples:
import xnano
from xnano.operations import Effect
with xnano.new(width=20, height=3) as canvas:
title = canvas.screen.write('Welcome')
title.update(Effect.dissolve(duration_milliseconds=500))
Source code in xnano/layout/_placement.py
def update(
self, *operations: _core.Operation | _core.Style
) -> Placement[DepsT, StateT]:
"""
Change this placement's content with operations, styles or effects.
Args:
operations: What to apply, in order: an operation, a contextual operation, a style,
or an effect such as ``Effect.dissolve(duration_milliseconds=500)``.
Examples:
```python
import xnano
from xnano.operations import Effect
with xnano.new(width=20, height=3) as canvas:
title = canvas.screen.write('Welcome')
title.update(Effect.dissolve(duration_milliseconds=500))
```
"""
self._require_attached()
for item in operations:
if isinstance(item, ContextualOperation):
cast('ContextualOperation[DepsT, StateT]', item).apply_to(self)
elif isinstance(item, DynamicOperation):
item.apply_to(cast('Placement[object, object]', self))
elif isinstance(item, _core.Style):
self._buffer.update(_core.ApplyStyle(item))
else:
self._buffer.update(item)
if isinstance(item, (_core.Move, _core.Place)):
for axis in ('x', 'y'):
if axis in self._limits:
self._enforce(axis)
return self
__or__
¶
__ior__
¶
remove
¶
Take the buffer off the canvas. Removing twice is harmless.
Source code in xnano/layout/_placement.py
def remove(self) -> None:
"""Take the buffer off the canvas. Removing twice is harmless."""
if self._removed:
return
self._removed = True
# A look that was waiting to be drawn is dropped with the placement.
self._look_is_dirty = False
canvas = self._canvas
if not canvas._is_closed:
canvas._look_was_drawn(self)
inner = canvas._canvas._flows.get(id(self._content))
if inner is not None:
# What was written in here goes with it, so its flow ends without moving any of it.
inner.dissolve()
with canvas._lock:
nested = [
other
for other in canvas._placements
if other._parent_owner is self
or getattr(other._parent_owner, '_parent_placement', None) is self
]
for other in nested:
other.remove()
follow = canvas._cursor_follow
if (
follow is not None
and not canvas._is_closed
and any(follow[0] is buffer for buffer in (self._buffer, self._content))
):
# A cursor that followed this placement has nowhere to be once it is gone.
canvas._cursor_source.position = None
canvas._cursor_follow = None
driver = self._driver
if driver is not None:
self._driver = None
driver.close()
self._cancel_hooks()
effects = self._writable_effects
if effects is not None:
effects.clear()
namespace = self._state_namespace
if namespace is not None:
self._state_namespace = None
namespace._remove()
with self._canvas._lock:
self._bindings.clear()
self._limits.clear()
try:
self._parent_buffer.detach(self._buffer)
except ValueError:
pass
flow = self._flow
if flow is not None:
flow.remove(cast('Placement[object, object]', self))
if self._is_fitted_canvas:
self._is_fitted_canvas = False
fitted = self._canvas._canvas._fitted_placements
if self in fitted:
fitted.remove(cast('Placement[object, object]', self))
self._canvas._release(self)
with canvas._lock:
children = [
child
for child in canvas._children
if child._parent_placement is self and not child._is_closed
]
for child in children:
# A canvas written into this placement is closed with it.
child.close()
Region
¶
Region(buffer: Buffer, *, owner: Canvas[object, object] | Placement[object, object] | None = None, inset: tuple[int, int, int, int] = (0, 0, 0, 0), resolution: Resolution = 'cells', is_standalone: bool = False, look: Appearance | None = None, is_text: bool = False, timeline: _TimelineSpan | None = None)
Bases: _Looked, Generic[NumberT_co]
A rectangle in the grid of a medium: cells on the screen, or beats by semitones on the timeline.
A region on the screen is a rectangle of cells that you can read and write, one cell
or dot at a time. It is either standalone, made by region or
box, which owns its cells and can be written into a canvas, or a live
view of the cells of a canvas or a placement, from canvas.screen.region and
placement.region. Coordinates are region coordinates, (0, 0) being the top-left
cell. (x, y) in region and region.local(point) use screen cells, the frame of
context.mouse.position. in and overlaps also take
a placement, a screen or another region, and compare them in screen cells.
The default resolution is one cell. region.half_blocks addresses two pixels per cell
(one above the other) and region.braille eight dots per cell (two by four, one color
for the whole cell); region.cells is the view in whole cells again. Reading gives a
Pixel; assigning accepts a pixel, a color (the background of a cell,
the color of a pixel or dot), a str (text) or, over a slice, anything write
accepts.
A standalone region owns color, border, padding and margin and draws
them in its own cells, so its coordinates include them: (0, 0) of a bordered region
is the corner of the border. On a live view they belong to the canvas or the placement,
and the coordinates address the area inside them. A region written into a canvas is a
snapshot: changing the region afterwards changes nothing on the canvas. The look of a
box with a relative size, or written with a width or a height, is the exception:
its placement draws it again at its own size, so it follows the canvas when the canvas
is resized. A region made by write draws its text again whenever its look changes,
so cells you edited are replaced; edit the cells of a box instead.
A region on the timeline is a piano roll: x is the beat it starts on and width
how many beats it lasts, y is its lowest pitch as a MIDI number and height how
many semitones it spans. It has no cells, so region.beats, region.sixteenths
(sixteenth notes, 4 per beat) and region.milliseconds (through the tempo) are the views that
measure it, and reading cells, half_blocks, braille, size or a cell raises
a TerminalError. The same holds the other way around: a
region on the screen refuses beats, sixteenths and milliseconds.
(beat, pitch) in region and region.local((beat, pitch)) use the grid of the region.
The type parameter says which medium a region is in. A region on the screen is a
Region[int]: its x and width are whole numbers, so range(region.width)
type-checks. A region on the timeline is a Region[float]: its x and width are
beats, sixteenths or milliseconds and can be fractions. canvas.screen.region, placement.region,
region and box give a Region[int]; the region of a
note, a melody or a sound gives a Region[float], and so does context.region, which
is on the screen or on the timeline depending on what the hook is attached to. Annotate
a parameter as Region to accept either.
Attributes:
-
width(NumberT_co) –The width in cells, or in pixels or dots at the other screen resolutions; on the timeline, how many beats, sixteenths or milliseconds it lasts.
-
height(int) –The height in cells, or in pixels or dots at the other screen resolutions; on the timeline, how many semitones it spans.
-
x(NumberT_co) –The screen column of the left edge; on the timeline, the beat, tick or millisecond it starts at.
-
y(int) –The screen row of the top edge; on the timeline, the lowest pitch as a MIDI number.
-
right_edge(NumberT_co) –The first screen column after the region, in cells. On the timeline, the end of the region.
-
bottom_edge(int) –The first screen row below the region, in cells. On the timeline, the first pitch above the region.
-
resolution(Resolution) –The grid the region is measured in:
'cells','half_blocks'or'braille'on the screen,'beats','sixteenths'or'milliseconds'on the timeline. -
size(Size) –The width and height of a region on the screen, at its resolution.
-
cells(Region[int]) –The same region as whole cells.
-
braille(Region[int]) –The same cells as braille dots.
-
half_blocks(Region[int]) –The same cells as half-block pixels.
-
beats(Region[float]) –The same region on the timeline, measured in beats.
-
sixteenths(Region[float]) –The same region on the timeline, measured in sixteenth notes.
-
milliseconds(Region[float]) –The same region on the timeline, measured in milliseconds.
-
color(Colors) –The colors of a standalone region.
-
border(BorderAppearance) –The border of a standalone region.
-
padding(PaddingAppearance) –The padding of a standalone region.
-
margin(MarginAppearance) –The margin of a standalone region.
Examples:
import xnano
card = xnano.region('hello', border='rounded')
assert card.render().splitlines()[0] == '╭─────╮'
with xnano.new(width=8, height=2) as canvas:
region = canvas.screen.region
region[0:4, 0:1] = 'abcd'
region[5, 0] = xnano.Pixel('diamond', foreground='red')
region[0, 1] = (0, 0, 255)
assert region[5, 0].character == '◆'
assert region[1, 0].character == 'b'
assert (1, 1) in region
assert (region.size.width, region.size.height) == (8, 2)
dots = region.braille
assert (dots.width, dots.height) == (16, 8)
assert dots.cells.resolution == 'cells'
A note, a melody or a sound has a region on the timeline:
import pytest
import xnano
from xnano.errors import TerminalError
region = xnano.Note(('C4', 'G4'), beats=2).region
assert (region.x, region.width, region.y, region.height) == (0.0, 2.0, 60, 8)
assert region.sixteenths.width == 8.0
with pytest.raises(TerminalError):
region.half_blocks
Wrap a buffer. Get a region from write, box or canvas.screen.region instead.
Parameters:
-
buffer(Buffer) –The core buffer whose cells the region addresses.
-
owner(Canvas[object, object] | Placement[object, object] | None, default:None) –The canvas or placement a live view belongs to.
-
inset(tuple[int, int, int, int], default:(0, 0, 0, 0)) –Cells left out on the left, top, right and bottom of the buffer.
-
resolution(Resolution, default:'cells') –The grid of the region:
'cells','half_blocks'or'braille'on the screen,'beats','sixteenths'or'milliseconds'on the timeline. -
is_standalone(bool, default:False) –Whether the region owns its buffer and its look.
-
look(Appearance | None, default:None) –The look of a standalone region.
-
is_text(bool, default:False) –Whether a standalone region shows the text of its look.
-
timeline(_TimelineSpan | None, default:None) –The beats and pitches of a region on the timeline. Get that region from the
regionof a note, a melody or a sound instead.
Raises:
-
TerminalError–timelineis given with a resolution on the screen, or a resolution on the timeline is given withouttimeline.
- API Reference xnano
- Learn Writing Content Ask what an area holds
- API Reference xnano
Methods:
-
__setattr__–Set an attribute, or raise
AttributeErrorfor an unknown public name. -
__contains__–Whether a screen cell, a whole area, or a beat and a pitch is inside the region.
-
overlaps–Whether this region and another area share at least one screen cell.
-
local–Convert a screen cell, or a beat and a pitch, into a position in this region.
-
resize–Change the size of the region, in cells.
-
__getitem__–Read a cell (a
Pixel) or take a part of the region. -
__setitem__–Write a pixel, a color, text or content into a cell or a part of the region.
-
shade–Color every cell, pixel or dot from a function of its position, in one write.
-
draw_color_bytes–Draw a row-major RGBA image with its top-left pixel at
(x, y). -
draw_image–Draw an image with its top-left pixel at
(x, y). -
cell_for_pixel–Return the cell that holds a pixel or dot.
-
pixel_for_cell–Return the pixel or dot at an anchor of a cell.
-
copy–Return a standalone region with a copy of these cells and, for one, its look.
-
render–Draw the region to a string.
-
__str__–Return the characters of a region on the screen, so
print(region)shows it. -
__rich_console__–Show the region 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.
-
__xnano_write__–Return the buffer that shows the region: its own, or a copy for a view.
Source code in xnano/layout/_region.py
def __init__(
self,
buffer: _core.Buffer,
*,
owner: Canvas[object, object] | Placement[object, object] | None = None,
inset: tuple[int, int, int, int] = (0, 0, 0, 0),
resolution: Resolution = 'cells',
is_standalone: bool = False,
look: Appearance | None = None,
is_text: bool = False,
timeline: _TimelineSpan | None = None,
) -> None:
"""
Wrap a buffer. Get a region from ``write``, ``box`` or ``canvas.screen.region`` instead.
Args:
buffer: The core buffer whose cells the region addresses.
owner: The canvas or placement a live view belongs to.
inset: Cells left out on the left, top, right and bottom of the buffer.
resolution: The grid of the region: ``'cells'``, ``'half_blocks'`` or
``'braille'`` on the screen, ``'beats'``, ``'sixteenths'`` or ``'milliseconds'``
on the timeline.
is_standalone: Whether the region owns its buffer and its look.
look: The look of a standalone region.
is_text: Whether a standalone region shows the text of its look.
timeline: The beats and pitches of a region on the timeline. Get that region
from the ``region`` of a note, a melody or a sound instead.
Raises:
TerminalError: ``timeline`` is given with a resolution on the screen, or a
resolution on the timeline is given without ``timeline``.
"""
if timeline is None and resolution in _TIMELINE_RESOLUTIONS:
raise TerminalError(
f'Region() got the timeline resolution {resolution!r} without a timeline, '
f'but a region on the timeline needs the beats and pitches it covers. Get '
f'it from the region of a note, a melody or a sound, or pass a screen '
f"resolution: 'cells', 'half_blocks' or 'braille'.",
code='validation.value',
location='resolution',
input_value=resolution,
)
if timeline is not None and resolution not in _TIMELINE_RESOLUTIONS:
raise TerminalError(
f'Region() got a timeline with the screen resolution {resolution!r}, but '
f'a region on the timeline is measured in beats. Pass resolution='
f"'beats', 'sixteenths' or 'milliseconds'.",
code='validation.value',
location='resolution',
input_value=resolution,
)
self._buffer = buffer
self._owner = owner
self._inset = inset
self._resolution: Resolution = resolution
self._is_standalone = is_standalone
self._is_text = is_text
self._appearance = look
self._timeline = timeline
self._canvas: Canvas[object, object] | None = None
self._insets_applied: tuple[int, int, int, int] | None = None
# The width and height a box was made with: whole cells, or the relative size it
# keeps until it is written.
self._box_size: (
tuple[
int
| str
| NumericExpression
| _core.StateReference[int]
| _core.StateReference[float],
int
| str
| NumericExpression
| _core.StateReference[int]
| _core.StateReference[float],
]
| None
) = None
self._seal()
border
property
writable
¶
border: BorderAppearance
The border of a standalone region; see BorderAppearance.
padding
property
writable
¶
padding: PaddingAppearance
The padding of a standalone region; see Edges.
width
property
¶
The width of the region.
On the screen it is counted in cells, or in pixels or dots at the other resolutions,
and is a whole number (int). On the timeline it is how long the region lasts, in
beats, sixteenths or milliseconds (float).
height
property
¶
height: int
The height of the region.
On the screen it is counted in cells, or in pixels or dots at the other resolutions. On the timeline it is how many semitones the region spans: 1 for a single note, and more for a chord or a melody, at every timeline resolution.
resolution
property
¶
resolution: Resolution
The grid the region is measured in.
On the screen it is 'cells', 'half_blocks' (1 by 2 per cell) or 'braille'
(2 by 4). On the timeline it is 'beats', 'sixteenths' (sixteenth notes, 4 per beat)
or 'milliseconds'.
x
property
¶
The position of the region's left edge.
On the screen it is the column, a whole number (int), and 0 for a region that is
not on screen. On the timeline it is the beat, tick or millisecond the region starts
at (float).
y
property
¶
y: int
The position of the region's top edge.
On the screen it is the row, and 0 for a region that is not on screen. On the timeline it is the lowest pitch of the region as a MIDI number, at every timeline resolution; 0 when nothing is played.
size
property
¶
size: Size
The width and height of a region on the screen, at its resolution.
Raises:
-
TerminalError–The region is on the timeline, which has no cells. Read its
widthandheightinstead.
right_edge
property
¶
The first column after the region: x plus the width in cells.
On the screen it is a screen column in cells. The braille and half_blocks
views give the same column as cells. On the timeline it is where the region ends:
x plus width, in the resolution of the region.
Examples:
bottom_edge
property
¶
bottom_edge: int
The first row below the region: y plus the height in cells.
On the screen it is a screen row in cells. The braille and half_blocks views
give the same row as cells. On the timeline it is the first pitch above the
region, as a MIDI number.
Examples:
cells
property
¶
The same region as whole cells, whatever resolution it was viewed at.
Raises:
-
TerminalError–The region is on the timeline, which has no cells. Read
beats,sixteenthsormillisecondsinstead.
braille
property
¶
The same cells as braille dots: two columns and four rows per cell.
A dot is drawn in the color of its cell, so the eight dots of a cell share one color.
Raises:
-
TerminalError–The region is on the timeline, which has no cells. Read
beats,sixteenthsormillisecondsinstead.
Examples:
import xnano
with xnano.new(width=4, height=2) as canvas:
dots = canvas.screen.region.braille
dots[0, 0] = (255, 255, 255)
assert dots[0, 0].character == '•'
assert dots[1, 0].character == ' '
half_blocks
property
¶
The same cells as pixels, two to a cell: one above the other.
Raises:
-
TerminalError–The region is on the timeline, which has no cells. Read
beats,sixteenthsormillisecondsinstead.
beats
property
¶
The same region on the timeline, measured in beats.
Raises:
-
TerminalError–The region is on the screen, which has no beats. Read
cells,half_blocksorbrailleinstead.
sixteenths
property
¶
The same region on the timeline, measured in sixteenth notes, 4 to a beat.
Raises:
-
TerminalError–The region is on the screen, which has no beats. Read
cells,half_blocksorbrailleinstead.
milliseconds
property
¶
The same region on the timeline, measured in milliseconds through the tempo.
A tempo that changes inside the region makes its beats different lengths in
milliseconds, so x and width follow the tempo at each beat.
Raises:
-
TerminalError–The region is on the screen, which has no beats. Read
cells,half_blocksorbrailleinstead.
__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)
__contains__
¶
Whether a screen cell, a whole area, or a beat and a pitch is inside the region.
On the screen, an area is inside when each of its cells is a cell of this region. The comparison uses screen cells at every resolution. An empty area has a width or a height of 0. It is inside when its top-left position is inside.
Parameters:
-
item(object) –On the screen, a
(x, y)pair of numbers or aPointin screen cells, such ascontext.mouse.position. It can also be an area: aRegion, aPlacementor aScreen. A placement counts as all the cells that it takes, with its border, padding and margin. A screen counts as itsregion. On the timeline, a(beat, pitch)pair of numbers in the grid of the region, where the pitch is a MIDI number. No area is inside a region on the timeline. Other values are not inside.
Examples:
import xnano
with xnano.new(width=10, height=4) as canvas:
card = canvas.screen.write('card', x=2, y=1, border='plain')
assert (3, 2) in card.region
assert card in canvas.screen.region
assert card not in card.region
assert canvas.screen not in card.region
Source code in xnano/layout/_region.py
def __contains__(self, item: object) -> bool:
"""
Whether a screen cell, a whole area, or a beat and a pitch is inside the region.
On the screen, an area is inside when each of its cells is a cell of this region. The
comparison uses screen cells at every resolution. An empty area has a width or a
height of 0. It is inside when its top-left position is inside.
Args:
item: On the screen, a ``(x, y)`` pair of numbers or a
[`Point`][xnano_core.Point] in screen cells, such as
``context.mouse.position``. It can also be an area: a
[`Region`][xnano.layout.Region], a [`Placement`][xnano.layout.Placement] or a
[`Screen`][xnano.devices.Screen]. A placement counts as all the cells that it
takes, with its border, padding and margin. A screen counts as its
``region``. On the timeline, a ``(beat, pitch)`` pair of numbers in the grid
of the region, where the pitch is a MIDI number. No area is inside a region on
the timeline. Other values are not inside.
Examples:
```python
import xnano
with xnano.new(width=10, height=4) as canvas:
card = canvas.screen.write('card', x=2, y=1, border='plain')
assert (3, 2) in card.region
assert card in canvas.screen.region
assert card not in card.region
assert canvas.screen not in card.region
```
"""
span = self._timeline
if span is not None:
if not _is_number_pair(item):
return False
beat, pitch = cast('tuple[float, float]', item)
origin_x, width = self._timeline_extent(span)
return (
origin_x <= beat < origin_x + width
and span.lowest_pitch <= pitch < span.lowest_pitch + span.pitch_count
)
if isinstance(item, _core.Point):
column, row = item.x, item.y
elif _is_number_pair(item):
column, row = cast('tuple[float, float]', item)
else:
area = _area_region(item)
if area is None or area._timeline is not None:
return False
column, row = area._screen_origin()
area_width, area_height = area._cell_size()
if area_width and area_height:
origin_x, origin_y = self._screen_origin()
width, height = self._cell_size()
return (
origin_x <= column
and column + area_width <= origin_x + width
and origin_y <= row
and row + area_height <= origin_y + height
)
width, height = self._cell_size()
origin_x, origin_y = self._screen_origin()
return (
origin_x <= column < origin_x + width and origin_y <= row < origin_y + height
)
overlaps
¶
overlaps(other: Point | tuple[float, float] | Region | Placement[Any, Any] | Screen[Any, Any]) -> bool
Whether this region and another area share at least one screen cell.
Use it to find a collision, such as an apple that falls into a basket. Areas that touch at an edge do not share a cell, so they do not overlap. An empty area, with a width or a height of 0, has no cells and overlaps no area. A region on the timeline has no screen cells, so it overlaps no area.
Parameters:
Returns:
-
bool–Truewhen the two share a cell, or when the cell is inside this region.
Raises:
-
TypeError–otheris not an area or a screen cell.
Examples:
import xnano
with xnano.new(width=20, height=6) as canvas:
basket = canvas.screen.write('[___]', x=5, y=5)
apple = canvas.screen.write('o', x=7, y=4)
assert not basket.region.overlaps(apple)
apple.down()
assert basket.region.overlaps(apple)
assert basket.region.overlaps((9, 5))
Source code in xnano/layout/_region.py
def overlaps(
self,
other: _core.Point
| tuple[float, float]
| Region
| Placement[Any, Any]
| Screen[Any, Any],
) -> bool:
"""
Whether this region and another area share at least one screen cell.
Use it to find a collision, such as an apple that falls into a basket. Areas that
touch at an edge do not share a cell, so they do not overlap. An empty area, with a
width or a height of 0, has no cells and overlaps no area. A region on the timeline
has no screen cells, so it overlaps no area.
Args:
other: An area: a [`Region`][xnano.layout.Region], a
[`Placement`][xnano.layout.Placement] or a [`Screen`][xnano.devices.Screen].
A placement counts as all the cells that it takes, with its border, padding
and margin. A screen counts as its ``region``. A screen cell as a ``(x, y)``
pair of numbers or a [`Point`][xnano_core.Point] overlaps when it is inside,
as with ``in``.
Returns:
``True`` when the two share a cell, or when the cell is inside this region.
Raises:
TypeError: ``other`` is not an area or a screen cell.
Examples:
```python
import xnano
with xnano.new(width=20, height=6) as canvas:
basket = canvas.screen.write('[___]', x=5, y=5)
apple = canvas.screen.write('o', x=7, y=4)
assert not basket.region.overlaps(apple)
apple.down()
assert basket.region.overlaps(apple)
assert basket.region.overlaps((9, 5))
```
"""
area = _area_region(other)
if area is None:
if isinstance(other, _core.Point) or _is_number_pair(other):
return other in self
raise TypeError(
f'overlaps() takes an area or a screen cell, but got {other!r}. An area is a '
f'Region, a Placement or a Screen, such as canvas.screen. A screen cell is an '
f'(x, y) pair of numbers or a Point, such as context.mouse.position. Pass one '
f'of these, such as basket.overlaps(apple).'
)
if self._timeline is not None or area._timeline is not None:
return False
origin_x, origin_y = self._screen_origin()
width, height = self._cell_size()
area_x, area_y = area._screen_origin()
area_width, area_height = area._cell_size()
has_shared_column = max(origin_x, area_x) < min(
origin_x + width, area_x + area_width
)
has_shared_row = max(origin_y, area_y) < min(
origin_y + height, area_y + area_height
)
return has_shared_column and has_shared_row
local
¶
Convert a screen cell, or a beat and a pitch, into a position in this region.
Parameters:
-
point(Point | tuple[float, float]) –On the screen, a cell in screen coordinates as a
Point, such ascontext.mouse.position. On the timeline, a(beat, pitch)pair of numbers in the grid of the region.
Returns:
-
Point | tuple[float, float]–On the screen, the cell relative to the region's top-left cell. On the timeline,
-
Point | tuple[float, float]–the
(beat, pitch)pair relative to the region's start and lowest pitch.
Raises:
-
TerminalError–The point is a tuple for a region on the screen, or a
Pointor anything but a pair of numbers for a region on the timeline.
Source code in xnano/layout/_region.py
def local(
self, point: _core.Point | tuple[float, float]
) -> _core.Point | tuple[float, float]:
"""
Convert a screen cell, or a beat and a pitch, into a position in this region.
Args:
point: On the screen, a cell in screen coordinates as a
[`Point`][xnano_core.Point], such as ``context.mouse.position``. On the
timeline, a ``(beat, pitch)`` pair of numbers in the grid of the region.
Returns:
On the screen, the cell relative to the region's top-left cell. On the timeline,
the ``(beat, pitch)`` pair relative to the region's start and lowest pitch.
Raises:
TerminalError: The point is a tuple for a region on the screen, or a ``Point`` or
anything but a pair of numbers for a region on the timeline.
"""
span = self._timeline
if span is not None:
if not (
isinstance(point, tuple)
and len(point) == 2
and _is_real_number(point[0])
and _is_real_number(point[1])
):
raise TerminalError(
f'local() takes a (beat, pitch) pair of numbers for a region on the '
f'timeline, but got {point!r}. Pass the beat in {self._resolution} and '
f'the pitch as a MIDI number, such as region.local((1.5, 62)).',
code='validation.type',
location='point',
input_value=point,
)
return (
point[0] - self._timeline_extent(span)[0],
point[1] - span.lowest_pitch,
)
point = check_point(point)
origin_x, origin_y = self._screen_origin()
return _core.Point(point.x - origin_x, point.y - origin_y)
resize
¶
Change the size of the region, in cells.
On a view of a placement this resizes the placement. A standalone region made by
box keeps its cells where they fit, and a box with a relative size
takes the whole-cell size given here and keeps it. A region made by
region is sized by its text, border, padding and margin, so it
cannot be resized.
Parameters:
Raises:
-
TerminalError–The region is the view of a canvas, whose size follows its screen, a slice of another region, or it was made by
write, whose size follows its text; or it is on the timeline, which has no cells. -
ValueError–A size is below 1 or above 65535.
Source code in xnano/layout/_region.py
def resize(self, width: int, height: int) -> None:
"""
Change the size of the region, in cells.
On a view of a placement this resizes the placement. A standalone region made by
[`box`][xnano.box] keeps its cells where they fit, and a box with a relative size
takes the whole-cell size given here and keeps it. A region made by
[`region`][xnano.region] is sized by its text, border, padding and margin, so it
cannot be resized.
Args:
width: The new width in cells.
height: The new height in cells.
Raises:
TerminalError: The region is the view of a canvas, whose size follows its screen,
a slice of another region, or it was made by ``write``, whose size follows
its text; or it is on the timeline, which has no cells.
ValueError: A size is below 1 or above 65535.
"""
self._require_screen('region.resize()')
_check_cell_counts('resize', width, height)
if width < 1 or height < 1:
raise ValueError(
f'A region is at least 1 by 1 cells, but resize got {width} by {height}. '
f'Pass whole numbers of cells, 1 or more.'
)
owner = self._owner
if self._is_standalone and self._is_text:
raise TerminalError(
'A region made by xnano.region() is sized by its text, border, padding and margin, '
'so resize() cannot change it. Make a region of a size you choose with '
'xnano.box(width, height), or change the text or the padding.'
)
if self._is_standalone:
self._resize_standalone(width, height)
if self._box_size is not None:
self._box_size = (width, height)
return
if owner is None or not hasattr(owner, '_set_axis'):
if owner is None or any(self._inset):
raise TerminalError(
'A slice of a region is a window onto it and cannot be resized. Resize the '
'region it was taken from with its resize(width, height), or take a new '
'slice.'
)
raise TerminalError(
'The size of a canvas follows its screen or its width and height; set '
'those instead of resizing its region.'
)
left, top, right, bottom = self._inset
placement = cast('Placement[object, object]', owner)
extra_width = left + right
extra_height = top + bottom
decorated = getattr(placement, '_decorated', None)
if decorated is not None:
extra_width += decorated.insets.horizontal
extra_height += decorated.insets.vertical
placement.width = width + extra_width
placement.height = height + extra_height
__getitem__
¶
Read a cell (a Pixel) or take a part of the region.
Parameters:
Raises:
-
IndexError–A coordinate is outside the region; the message names the valid ranges.
-
TypeError–The key is a screen
Pointor not a pair. -
ValueError–A slice has a step, or a slice is taken from a pixel resolution.
-
TerminalError–The region is on the timeline, which has no cells.
Source code in xnano/layout/_region.py
def __getitem__(self, key: tuple[int | slice, int | slice]) -> Pixel | Region[int]:
"""
Read a cell (a [`Pixel`][xnano.art.Pixel]) or take a part of the region.
Args:
key: ``(x, y)`` in region coordinates, or two slices without a step.
Raises:
IndexError: A coordinate is outside the region; the message names the valid ranges.
TypeError: The key is a screen [`Point`][xnano_core.Point] or not a pair.
ValueError: A slice has a step, or a slice is taken from a pixel resolution.
TerminalError: The region is on the timeline, which has no cells.
"""
if self._timeline is not None: # checked inline: indexing is the hot path
self._require_screen('region[x, y]')
if type(key) is tuple and len(key) == 2 and self._resolution == 'cells':
column, row = key
if type(column) is int and type(row) is int:
self._flush_look()
buffer = self._buffer
if (
not any(self._inset)
and 0 <= column < buffer.width
and 0 <= row < buffer.height
):
cell = buffer[column, row]
foreground = cell.foreground
background = cell.background
return Pixel._of(
cell.symbol,
None if foreground is None or foreground.is_reset else foreground,
None if background is None or background.is_reset else background,
)
self._check_point(key)
column, row = key
if isinstance(column, slice) or isinstance(row, slice):
if self._resolution != 'cells':
raise ValueError(
f'A slice of a {self._resolution} region would cut cells in two. '
f'Take the slice from the cell region (region[0:5, 0:2]) and then '
f'use .{self._resolution}.'
)
width, height = self._cell_size()
first_x, last_x = self._span(column, width, 'x')
first_y, last_y = self._span(row, height, 'y')
left, top, right, bottom = self._inset
view: Region[int] = Region(
self._buffer,
owner=self._owner,
inset=(
left + first_x,
top + first_y,
right + (width - last_x),
bottom + (height - last_y),
),
)
view._canvas = self._canvas
return view
column, row = self._check_bounds(column, row)
surface = self._surface()
if self._resolution == 'cells':
cell = surface[column, row]
return Pixel._of(
cell.symbol, _plain(cell.foreground), _plain(cell.background)
)
if self._resolution == 'half_blocks':
cell = surface[column, row // 2]
is_top = row % 2 == 0
symbol = cell.symbol
if symbol == '▀':
color = cell.foreground if is_top else cell.background
elif symbol == '▄':
color = cell.background if is_top else cell.foreground
elif symbol == '█':
color = cell.foreground
else:
color = cell.background
plain = _plain(color)
return Pixel._of('█', plain) if plain is not None else Pixel._of(' ')
cell = surface[column // 2, row // 4]
code = ord(cell.symbol[0]) - 0x2800 if cell.symbol else -1
is_set = 0 <= code <= 0xFF and bool(code & _BRAILLE_BITS[row % 4][column % 2])
return Pixel._of('•', _plain(cell.foreground)) if is_set else Pixel._of(' ')
__setitem__
¶
__setitem__(key: tuple[int | slice, int | slice], value: Pixel | Color | tuple[int, int, int] | str | object) -> None
Write a pixel, a color, text or content into a cell or a part of the region.
- A
Pixelwrites its character and colors; over a slice it fills it. - A
Coloror an(red, green, blue)tuple sets the background of a cell (the color of a pixel or dot at the other resolutions). Astris never a color: make one withColor('#336699'). - A
stris text, written from the cell and clipped at the slice. - Any other content that
writeaccepts covers a slice.
Parameters:
-
key(tuple[int | slice, int | slice]) –(x, y)in region coordinates, or two slices without a step. -
value(Pixel | Color | tuple[int, int, int] | str | object) –What to write.
Raises:
-
IndexError–A coordinate is outside the region.
-
TypeError–A single cell was given content that needs a slice, a screen
Pointwas used as the key, or text was written at a pixel resolution. -
ValueError–A slice has a step.
-
TerminalError–The region is on the timeline, which has no cells.
Source code in xnano/layout/_region.py
def __setitem__(
self,
key: tuple[int | slice, int | slice],
value: Pixel | _core.Color | tuple[int, int, int] | str | object,
) -> None:
"""
Write a pixel, a color, text or content into a cell or a part of the region.
* A [`Pixel`][xnano.art.Pixel] writes its character and colors; over a slice it fills it.
* A [`Color`][xnano_core.Color] or an ``(red, green, blue)`` tuple sets the background
of a cell (the color of a pixel or dot at the other resolutions). A ``str`` is never
a color: make one with ``Color('#336699')``.
* A ``str`` is text, written from the cell and clipped at the slice.
* Any other content that ``write`` accepts covers a slice.
Args:
key: ``(x, y)`` in region coordinates, or two slices without a step.
value: What to write.
Raises:
IndexError: A coordinate is outside the region.
TypeError: A single cell was given content that needs a slice, a screen
[`Point`][xnano_core.Point] was used as the key, or text was written at a
pixel resolution.
ValueError: A slice has a step.
TerminalError: The region is on the timeline, which has no cells.
"""
if self._timeline is not None: # checked inline: indexing is the hot path
self._require_screen('region[x, y]')
if type(key) is tuple and len(key) == 2 and self._resolution == 'cells':
column, row = key
if type(column) is int and type(row) is int and type(value) is Pixel:
self._flush_look()
buffer = self._buffer
if (
not any(self._inset)
and 0 <= column < buffer.width
and 0 <= row < buffer.height
):
buffer[column, row] = value.cell()
return
self._check_point(key)
column, row = key
if isinstance(column, int) and isinstance(row, int):
x, y = self._check_bounds(column, row)
self._set_cell(x, y, value)
return
width, height = self._grid_size()
first_x, last_x = self._span(column, width, 'x')
first_y, last_y = self._span(row, height, 'y')
if last_x <= first_x or last_y <= first_y:
return
self._set_block(first_x, last_x, first_y, last_y, value)
shade
¶
Color every cell, pixel or dot from a function of its position, in one write.
At the default resolution the function is called for each cell and the result is
the cell's background; region.half_blocks.shade and region.braille.shade call
it for each pixel or dot.
Parameters:
-
function(Callable[[int, int], ColorValue | None]) –Called with
(x, y)in region coordinates; return the color, orNoneto leave the cell alone.
Raises:
-
TerminalError–The region is on the timeline, which has no cells.
Examples:
import xnano
with xnano.new(width=4, height=2) as canvas:
canvas.screen.region.shade(lambda x, y: (x * 60, y * 60, 0) if x < 3 else None)
assert canvas.screen.region[2, 1].background.to_rgb() == (120, 60, 0)
canvas.screen.region.half_blocks.shade(lambda x, y: (0, y * 30, 0))
assert canvas.screen.region.half_blocks[0, 3].foreground is not None
Source code in xnano/layout/_region.py
def shade(self, function: Callable[[int, int], ColorValue | None]) -> None:
"""
Color every cell, pixel or dot from a function of its position, in one write.
At the default resolution the function is called for each cell and the result is
the cell's background; ``region.half_blocks.shade`` and ``region.braille.shade`` call
it for each pixel or dot.
Args:
function: Called with ``(x, y)`` in region coordinates; return the color, or
``None`` to leave the cell alone.
Raises:
TerminalError: The region is on the timeline, which has no cells.
Examples:
```python
import xnano
with xnano.new(width=4, height=2) as canvas:
canvas.screen.region.shade(lambda x, y: (x * 60, y * 60, 0) if x < 3 else None)
assert canvas.screen.region[2, 1].background.to_rgb() == (120, 60, 0)
canvas.screen.region.half_blocks.shade(lambda x, y: (0, y * 30, 0))
assert canvas.screen.region.half_blocks[0, 3].foreground is not None
```
"""
self._require_screen('region.shade()')
_check_shade_function(function)
if self._resolution == 'cells':
width, height = self._cell_size()
if width == 0 or height == 0:
return
colors = [
function(column, row) for row in range(height) for column in range(width)
]
self._surface().set_background_colors(colors, width=width)
return
view = self._pixel_view()
colored: list[tuple[int, int, RGB]] = []
for row in range(view.height):
for column in range(view.width):
color = function(column, row)
if color is not None:
colored.append((column, row, to_rgb(color)))
view.write(colored)
draw_color_bytes
¶
draw_color_bytes(data: bytes, *, width: int, height: int, x: int = 0, y: int = 0, mode: RasterMode = 'over') -> None
Draw a row-major RGBA image with its top-left pixel at (x, y).
At the default resolution the image is drawn with half-block pixels.
Parameters:
-
data(bytes) –width * height * 4bytes of red, green, blue and alpha. -
width(int) –The image width in pixels.
-
height(int) –The image height in pixels.
-
x(int, default:0) –The pixel column of the image's left edge.
-
y(int, default:0) –The pixel row of the image's top edge.
-
mode(RasterMode, default:'over') –'over'blends by alpha;'replace'overwrites.
Raises:
-
TerminalError–The region is on the timeline, which has no cells.
Source code in xnano/layout/_region.py
def draw_color_bytes(
self,
data: bytes,
*,
width: int,
height: int,
x: int = 0,
y: int = 0,
mode: _core.RasterMode = 'over',
) -> None:
"""
Draw a row-major RGBA image with its top-left pixel at ``(x, y)``.
At the default resolution the image is drawn with half-block pixels.
Args:
data: ``width * height * 4`` bytes of red, green, blue and alpha.
width: The image width in pixels.
height: The image height in pixels.
x: The pixel column of the image's left edge.
y: The pixel row of the image's top edge.
mode: ``'over'`` blends by alpha; ``'replace'`` overwrites.
Raises:
TerminalError: The region is on the timeline, which has no cells.
"""
self._require_screen('region.draw_color_bytes()')
self._pixel_view().draw_rgba(
data, width=width, height=height, x=x, y=y, mode=mode
)
draw_image
¶
draw_image(image: Image | TerminalImage, *, x: int = 0, y: int = 0, mode: RasterMode = 'over', frame_index: int = 0) -> None
Draw an image with its top-left pixel at (x, y).
Pixels outside the region are skipped, so drawing a large image at a negative x
and y scrolls it. At the default resolution the image is drawn with half-block
pixels.
Parameters:
-
image(Image | TerminalImage) –An
Imageor aTerminalImagefromxnano_image. It needs the optionalxnano-imagepackage. -
x(int, default:0) –The pixel column of the image's left edge. May be negative.
-
y(int, default:0) –The pixel row of the image's top edge. May be negative.
-
mode(RasterMode, default:'over') –'over'blends by alpha;'replace'overwrites. -
frame_index(int, default:0) –Which frame of an animated image to draw.
Raises:
-
TerminalError–The region is on the timeline, which has no cells.
Source code in xnano/layout/_region.py
def draw_image(
self,
image: Image | TerminalImage,
*,
x: int = 0,
y: int = 0,
mode: _core.RasterMode = 'over',
frame_index: int = 0,
) -> None:
"""
Draw an image with its top-left pixel at ``(x, y)``.
Pixels outside the region are skipped, so drawing a large image at a negative ``x``
and ``y`` scrolls it. At the default resolution the image is drawn with half-block
pixels.
Args:
image: An [`Image`][xnano.Image] or a ``TerminalImage`` from ``xnano_image``. It
needs the optional ``xnano-image`` package.
x: The pixel column of the image's left edge. May be negative.
y: The pixel row of the image's top edge. May be negative.
mode: ``'over'`` blends by alpha; ``'replace'`` overwrites.
frame_index: Which frame of an animated image to draw.
Raises:
TerminalError: The region is on the timeline, which has no cells.
"""
self._require_screen('region.draw_image()')
from xnano.art._images import Image
picture = image.decoded if isinstance(image, Image) else image
if not hasattr(picture, 'to_rgba'):
raise TypeError(
f'draw_image() takes an xnano.Image or a TerminalImage, but got '
f'{image!r}. Load one with xnano.load_image(path) first.'
)
self.draw_color_bytes(
picture.to_rgba(frame_index),
width=picture.width,
height=picture.height,
x=x,
y=y,
mode=mode,
)
cell_for_pixel
¶
Return the cell that holds a pixel or dot.
Parameters:
Raises:
-
TerminalError–The region is on the timeline, which has no cells.
Source code in xnano/layout/_region.py
def cell_for_pixel(self, x: int, y: int) -> tuple[int, int]:
"""
Return the cell that holds a pixel or dot.
Args:
x: The pixel or dot column.
y: The pixel or dot row.
Raises:
TerminalError: The region is on the timeline, which has no cells.
"""
self._require_screen('region.cell_for_pixel()')
if self._resolution == 'cells':
return (x, y)
return self._pixel_view().cell_at(x, y)
pixel_for_cell
¶
Return the pixel or dot at an anchor of a cell.
The mouse reports cells; this picks one pixel of the cell the pointer is over.
Parameters:
-
x(int) –The cell column.
-
y(int) –The cell row.
-
anchor(PixelAnchor, default:'center') –Which pixel of the cell to return.
Raises:
-
TerminalError–The region is on the timeline, which has no cells.
Source code in xnano/layout/_region.py
def pixel_for_cell(
self, x: int, y: int, *, anchor: PixelAnchor = 'center'
) -> tuple[int, int]:
"""
Return the pixel or dot at an anchor of a cell.
The mouse reports cells; this picks one pixel of the cell the pointer is over.
Args:
x: The cell column.
y: The cell row.
anchor: Which pixel of the cell to return.
Raises:
TerminalError: The region is on the timeline, which has no cells.
"""
self._require_screen('region.pixel_for_cell()')
if self._resolution == 'cells':
return (x, y)
return self._pixel_view().pixel_at(x, y, anchor=anchor)
copy
¶
Return a standalone region with a copy of these cells and, for one, its look.
Raises:
-
TerminalError–The region is on the timeline, which has no cells.
Source code in xnano/layout/_region.py
def copy(self) -> Region[int]:
"""
Return a standalone region with a copy of these cells and, for one, its look.
Raises:
TerminalError: The region is on the timeline, which has no cells.
"""
self._require_screen('region.copy()')
copy: Region[int] = Region(_snapshot(self._surface()), is_standalone=True)
if self._is_standalone and self._appearance is not None:
import dataclasses
copy._appearance = dataclasses.replace(
self._appearance, sides=dict(self._appearance.sides)
)
copy._is_text = self._is_text
copy._insets_applied = self._insets_applied
copy._box_size = self._box_size
return copy
render
¶
Draw the region to a string.
Parameters:
-
format(Literal['text', 'ansi'], default:'text') –'text'for the characters only,'ansi'with colors and styles.
Raises:
-
TerminalError–The region is on the timeline, which has no cells.
Examples:
Source code in xnano/layout/_region.py
def render(self, *, format: Literal['text', 'ansi'] = 'text') -> str:
"""
Draw the region to a string.
Args:
format: ``'text'`` for the characters only, ``'ansi'`` with colors and styles.
Raises:
TerminalError: The region is on the timeline, which has no cells.
Examples:
```python
import xnano
assert xnano.region('hi', padding=1).render().splitlines() == ['', ' hi']
```
"""
self._require_screen('region.render()')
return _snapshot(self._surface()).render(format=format)
__str__
¶
__str__() -> str
Return the characters of a region on the screen, so print(region) shows it.
A region on the timeline has no characters, so str of it is its repr.
Source code in xnano/layout/_region.py
__rich_console__
¶
Show the region in rich and Textual, with its colors and styles.
Rich shows what render draws. A region on the
timeline has no cells, so rich shows its repr. If a line is longer than the
space that rich gives it, rich cuts the line. Rich must be installed.
Source code in xnano/layout/_region.py
def __rich_console__(
self, console: RichConsole, options: RichConsoleOptions
) -> RichRenderResult:
"""
Show the region in rich and Textual, with its colors and styles.
Rich shows what [`render`][xnano.layout.Region.render] draws. A region on the
timeline has no cells, so rich shows its ``repr``. If a line is longer than the
space that rich gives it, rich cuts the line. Rich must be installed.
"""
from rich.text import Text as RichText
if self._timeline is not None:
yield RichText(repr(self), no_wrap=True, overflow='crop')
return
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.
The width is in cells, also for a braille or half_blocks view. 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/layout/_region.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.
The width is in cells, also for a ``braille`` or ``half_blocks`` view. 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 = len(repr(self)) if self._timeline is not None else int(self.cells.width)
return RichMeasurement(width, width)
__xnano_write__
¶
Return the buffer that shows the region: its own, or a copy for a view.
Source code in xnano/layout/_region.py
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)
__getattr__
¶
Import a name the first time it is read, then keep it.
Source code in xnano/layout/__init__.py
def __getattr__(name: str) -> object:
"""Import a name the first time it is read, then keep it."""
module = _MODULES.get(name)
if module is None:
raise AttributeError(
f'xnano.layout has no name {name!r}. Its names are {", ".join(__all__)}.'
)
value = getattr(importlib.import_module(module), name)
globals()[name] = value
return value