xnano.buffers
xnano.buffers
¶
xnano.buffers
Buffers: grids of cells that hold text and styles.
A Buffer is what a canvas draws; each Cell holds
one symbol with its colors.
Classes:
-
Image–An image and how it is shown: what
Canvas.writetakes -
Buffer–A layer of cells with a position, a size and the hooks that animate it.
-
Cell–A detached grapheme with its style, copied out of or written into a surface.
Attributes:
-
BufferSize(Value[Size]) –The dimensions of a buffer as a
Size.
Image
dataclass
¶
Image(source: TerminalImage | PathLike[str] | str | bytes, *, x: Axis | None = None, y: Axis | None = None, width: Axis | None = None, height: Axis | None = None, layer: int = 0, lock: bool = False, fit: ImageFit | None = None, resampling_filter: ResamplingFilter | None = None, background: ColorValue = (0, 0, 0), speed: float = 1.0, symbol: str | None = None)
An image and how it is shown: what Canvas.write takes
to put a picture on the canvas.
Make one from the path of an image file, its bytes, or a
TerminalImage. A file is read once, here, where you can
see it; write never takes a path. The placement values are what write uses when it
is not given its own. An image sized by a percentage (or not sized at all) is converted
again whenever the canvas is resized, so it always fits; give it a number, or
lock=True, and it keeps its size.
Attributes:
-
image(TerminalImage) –The picture.
-
x(Axis | None) –The column of the left edge, or
Nonefor the top-left corner. -
y(Axis | None) –The row of the top edge, or
None. -
width(Axis | None) –The width: cells, a percentage, an expression, or
Nonefor the picture's own. -
height(Axis | None) –The height, in the same forms.
-
layer(int) –Content with a higher layer is drawn over content with a lower one.
-
lock(bool) –Whether the image keeps the size it was shown at when the canvas is resized.
-
fit(ImageFit | None) –How the picture sits in a box of
widthbyheight:'contain'(the default),'cover','stretch','crop'or'smart'. -
resampling_filter(ResamplingFilter | None) –How pixels are blended when it is resized. By default a small picture that is enlarged keeps hard pixel edges (
'nearest') and any other is smoothed ('lanczos3'). -
background(tuple[int, int, int]) –The color behind transparent pixels and padding.
-
symbol(str | None) –The name the image is registered under in
symbols, orNone.
Examples:
import xnano
from xnano.image import TerminalImage
picture = xnano.Image(TerminalImage.from_rgba(2, 2, bytes([255, 0, 0, 255]) * 4), width=8)
with xnano.new(width=20, height=6) as canvas:
canvas.write(picture, x='center')
# xnano.Image('photo.png', width='100%') loads a file, and refits when the window resizes.
Load an image and set how it is shown.
Parameters:
-
source(TerminalImage | PathLike[str] | str | bytes) –The path of an image file (PNG, JPEG, GIF, WebP or XNI), the bytes of one, or an image. An animated file plays on the canvas's clock.
-
x(Axis | None, default:None) –The column of the left edge: cells, a percentage, a word such as
'center', an expression or a range. SeeAxis. -
y(Axis | None, default:None) –The row of the top edge, in the same forms.
-
width(Axis | None, default:None) –The width, in the same forms; the picture's own when
None. -
height(Axis | None, default:None) –The height, in the same forms.
-
layer(int, default:0) –Content with a higher layer is drawn over content with a lower one.
-
lock(bool, default:False) –Keep the size the image has when it is added, whatever the canvas does.
-
fit(ImageFit | None, default:None) –How the picture sits in a box of
widthbyheight. -
resampling_filter(ResamplingFilter | None, default:None) –How pixels are blended when it is resized.
-
background(ColorValue, default:(0, 0, 0)) –The color behind transparent pixels and padding, as a color name, a hex string, an
(r, g, b)tuple or aColor. -
speed(float, default:1.0) –How fast an animated image plays:
2.0is twice as fast. -
symbol(str | None, default:None) –A name to register the image under in
symbols.
Raises:
-
ImportError–xnano-imageis not installed. Install it withpip install "xnano[image]". -
TypeError–sourceis not a path, bytes or an image. -
FileNotFoundError–sourceis a path with no file at it. -
ValueError–symbolcannot be a symbol name, or another kind of value already has it.
Source code in xnano/_media.py
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 | |
Buffer
¶
Buffer(content: TextContent | None = None, *, width: int | None = None, height: int | None = None, x: int = 0, y: int = 0, style: Style | None = None, registry: Registry | None = None)
Bases: Surface
A layer of cells with a position, a size and the hooks that animate it.
A buffer owns its cells, its geometry, its hook registrations and its place in a
tree: it has at most one parent and is mounted on at most one runtime. Direct
writes and operations share validation and revision tracking. Changing
width or height keeps the cells that still fit and blanks new ones.
Moving a mounted buffer redraws both its old and new area.
Parameters:
-
content(TextContent | None, default:None) –Text to start with. Without
widthandheightthe buffer is sized to fit it. -
width(int | None, default:None) –The width in cells.
-
height(int | None, default:None) –The height in cells.
-
x(int, default:0) –The column of the buffer in its parent.
-
y(int, default:0) –The row of the buffer in its parent.
-
style(Style | None, default:None) –A style applied to the initial content.
-
registry(Registry | None, default:None) –The operation registry; defaults to the shared default registry.
Attributes:
-
x(int) –The column of the buffer in its parent. Assigning moves the buffer.
-
y(int) –The row of the buffer in its parent. Assigning moves the buffer.
-
width(int) –The width in cells. Assigning resizes the buffer.
-
height(int) –The height in cells. Assigning resizes the buffer.
-
position(Point) –The
Pointof the buffer in its parent. Assigning moves the buffer. -
size(Size) –The
Sizeof the buffer. Assigning resizes the buffer. -
bounds(Rectangle) –The buffer's rectangle in its parent.
-
layer(int) –The stacking order among siblings; higher layers are drawn on top.
-
is_visible(bool) –Whether the buffer is drawn. Hidden buffers still keep their content.
-
is_focusable(bool) –Whether the buffer can receive input focus.
-
content(Region) –The whole buffer as a region. Assigning text replaces the content.
-
cells(Region) –The same view as
content; there is only one store of cells. -
text(str) –The plain text of the buffer's own cells, without mounted children.
-
revision(int) –A number that increases every time the buffer's cells or geometry change.
-
children(tuple[Buffer, ...]) –The attached child buffers in attachment order.
-
registry(Registry) –The registry that decides which operations this buffer can apply.
Examples:
card = Buffer(width=12, height=3, x=2, y=1)
card.update(Border('rounded'))
card.write('hello', x=1, y=1)
print(card.render(format='text'))
sized = Buffer('two\nlines')
assert (sized.width, sized.height) == (5, 2)
Create a Buffer.
Parameters:
-
content(TextContent | None, default:None) –TextContent | None. Defaults toNone. -
width(int | None, default:None) –int | None. Defaults toNone. -
height(int | None, default:None) –int | None. Defaults toNone. -
x(int, default:0) –int. Defaults to0. -
y(int, default:0) –int. Defaults to0. -
style(Style | None, default:None) –Style | None. Defaults toNone. -
registry(Registry | None, default:None) –Registry | None. Defaults toNone.
-
API Reference
-
xnano
-
xnano -
xnano.art
artArt__xnano_render__ -
xnano.buffers
buffersBuffer -
xnano.canvas
canvasCanvascore_buffer -
xnano.demo
demowordmark -
xnano.operations
operationsClear -
xnano.pixel
pixelPixel__xnano_render__ -
xnano.placement
placementPlacementcore_buffer -
xnano.region
regionRegion__xnano_render__ -
xnano.terminal
terminalTerminalcore_buffer -
xnano.widgets
widgets
-
-
xnano_core
-
xnano_core -
xnano_core._xnano_core
_xnano_core -
xnano_core._xnano_core._core_types
_core_types
-
-
xnano
-
API Reference
- xnano
-
xnano_core
-
xnano_core -
xnano_core._xnano_core
_xnano_core -
xnano_core._xnano_core._core_types
_core_types
-
Methods:
-
__setitem__–Replace one cell with a
Cellor a single grapheme. -
write–Write text starting at a cell.
-
fill–Set every cell of the surface.
-
set_background_colors–Set the background color of a block of cells in one pass.
-
set_foreground_colors–Set the foreground color of a block of cells in one pass.
-
pixels–Return a pixel view that draws into this surface.
-
update–Apply operations in argument order.
-
inspect–Evaluate an expression against this surface and return its value.
-
add_hook–Run a callback when the runtime reports matching events for this surface.
-
invalidate–Ask the runtime to redraw an area, or the whole surface.
-
to_cell_grid–Pack the surface into the cell grid byte format.
-
__or__–Apply
operationto this surface and return the surface. -
with_text–Create a buffer sized to fit some text.
-
with_size–Create a blank buffer of a given size.
-
with_cells–Create a buffer from cells in row-major order.
-
from_cell_grid–Create a buffer from the cell grid byte format.
-
from_cell_animation–Create a buffer showing one frame of a packed cell animation.
-
region–Return a region covering a rectangle of the buffer.
-
resize–Change the size, keeping the cells that still fit.
-
paste–Copy the cells of another buffer or region into this one.
-
attach–Attach a child buffer as a retained layer of this one.
-
detach–Remove an attached child.
-
copy–Copy the cells, geometry and children into a new, independent buffer.
-
supports–Return whether the buffer's registry can apply an operation type.
-
__call__–Return a lazy render of the buffer.
-
render–Compose the visible children and serialize the buffer.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
position
property
writable
¶
position: Point
The Point of the buffer in its parent. Assigning moves the buffer.
is_visible
property
writable
¶
is_visible: bool
Whether the buffer is drawn. Hidden buffers still keep their content.
content
property
writable
¶
content: Region
The whole buffer as a region. Assigning text replaces the content.
revision
property
¶
revision: int
A number that increases every time the buffer's cells or geometry change.
registry
property
¶
registry: Registry
The registry that decides which operations this buffer can apply.
__setitem__
¶
__setitem__(key: Coordinate, value: Cell | str) -> None
write
¶
write(text: TextContent, *, x: int = 0, y: int = 0, style: Style | None = None, mode: WriteMode = 'replace') -> None
Write text starting at a cell.
Text is clipped by display columns, whole graphemes are kept together and the continuation cells of wide characters are repaired.
Parameters:
-
text(TextContent) –A string or styled text.
-
x(int, default:0) –The starting column.
-
y(int, default:0) –The starting row.
-
style(Style | None, default:None) –A style applied to the written cells.
-
mode(WriteMode, default:'replace') –'replace'overwrites the cell;'preserve_background'keeps the background already there.
Examples:
buffer = Buffer(width=6, height=2)
buffer.write('hi', x=1, y=0, style=Style(foreground='red'))
assert buffer[1, 0].foreground == Color('red')
assert buffer.text.split('\n')[0] == ' hi'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
fill
¶
Set every cell of the surface.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
set_background_colors
¶
set_background_colors(colors: Sequence[ColorValue | None], *, width: int, x: int = 0, y: int = 0) -> None
Set the background color of a block of cells in one pass.
Symbols and foreground colors are kept, and the whole block counts as one change (the revision grows by one).
Parameters:
-
colors(Sequence[ColorValue | None]) –A flat, row-major sequence of colors (names,
(r, g, b)tuples orColorvalues).Noneleaves a cell alone. -
width(int) –The number of colors in one row of
colors. -
x(int, default:0) –The column of the block's top-left cell in this surface.
-
y(int, default:0) –The row of the block's top-left cell in this surface.
Raises:
-
ValueError–widthis below 1,len(colors)is not a multiple ofwidth, or the block does not fit inside the surface, or an entry is not a color. -
TypeError–colorsis a single string instead of a sequence of colors, or an entry has no color meaning.
Examples:
buffer = Buffer(width=3, height=2)
buffer.write('abc')
buffer.set_background_colors(['red', None, (0, 0, 255), 'green'], width=2, x=1)
assert buffer[1, 0].background == Color('red')
assert buffer[2, 0].background == Color.reset
assert buffer[1, 1].background == Color('#0000ff')
assert buffer[2, 1].background == Color('green')
assert buffer[1, 0].symbol == 'b'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
set_foreground_colors
¶
set_foreground_colors(colors: Sequence[ColorValue | None], *, width: int, x: int = 0, y: int = 0) -> None
Set the foreground color of a block of cells in one pass.
Symbols and background colors are kept, and the whole block counts as one change (the revision grows by one).
Parameters:
-
colors(Sequence[ColorValue | None]) –A flat, row-major sequence of colors (names,
(r, g, b)tuples orColorvalues).Noneleaves a cell alone. -
width(int) –The number of colors in one row of
colors. -
x(int, default:0) –The column of the block's top-left cell in this surface.
-
y(int, default:0) –The row of the block's top-left cell in this surface.
Raises:
-
ValueError–widthis below 1,len(colors)is not a multiple ofwidth, or the block does not fit inside the surface, or an entry is not a color. -
TypeError–colorsis a single string instead of a sequence of colors, or an entry has no color meaning.
Examples:
buffer = Buffer(width=3, height=2)
buffer.write('abc')
buffer.set_foreground_colors(['red', None, (0, 0, 255), 'green'], width=2, x=1)
assert buffer[1, 0].foreground == Color('red')
assert buffer[2, 0].foreground == Color.reset
assert buffer[1, 1].foreground == Color('#0000ff')
assert buffer[2, 1].foreground == Color('green')
assert buffer[1, 0].symbol == 'b'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
pixels
¶
pixels(*, encoding: PixelEncoding = 'half_blocks') -> PixelView
Return a pixel view that draws into this surface.
Parameters:
-
encoding(PixelEncoding, default:'half_blocks') –'half_blocks'for one column and two rows per cell or'braille'for two columns and four rows per cell.
Examples:
buffer = Buffer(width=3, height=2)
assert (buffer.pixels().width, buffer.pixels().height) == (3, 4)
assert (buffer.pixels(encoding='braille').width) == 6
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
update
¶
update(*operations: Operation) -> None
Apply operations in argument order.
Raises:
-
UnsupportedOperationError–The surface's registry cannot apply an operation.
-
RuntimeRequiredError–An operation needs a mounted buffer on a runtime.
Examples:
buffer = Buffer(width=8, height=3)
buffer.update(Border('rounded'), Write('hi', x=1, y=1))
assert buffer[0, 0].symbol == '╭'
assert buffer[1, 1].symbol == 'h'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
inspect
¶
inspect(expression: Expression[ValueType]) -> ValueType
Evaluate an expression against this surface and return its value.
Examples:
width = _reference('Width', 'numeric_property')
height = _reference('Height', 'numeric_property')
buffer = Buffer(width=8, height=3)
assert buffer.inspect(width) == 8
assert buffer.inspect(width * height) == 24
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
add_hook
¶
add_hook(callback: HookCallback, *, condition: Predicate | None = None, events: Sequence[HookEventKind] = ('tick',), priority: int = 0, once: bool = False) -> Hook
Run a callback when the runtime reports matching events for this surface.
Parameters:
-
callback(HookCallback) –Called with a context for the event.
-
condition(Predicate | None, default:None) –An expression that must be true for the callback to run.
-
events(Sequence[HookEventKind], default:('tick',)) –The event kinds to listen to.
-
priority(int, default:0) –Hooks with higher priority run first.
-
once(bool, default:False) –Whether to remove the hook after its first run.
Returns:
-
Hook–The registered hook, which can be cancelled.
Examples:
keys = []
with Runtime.offscreen(width=10, height=2) as runtime:
buffer = Buffer()
runtime.mount(buffer, geometry='inherit')
buffer.add_hook(lambda context: keys.append(context.event.key.key), events=['key'])
runtime.dispatch(Event.key_press('a'))
runtime.step()
assert keys == ['a']
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
invalidate
¶
invalidate(area: Rectangle | None = None) -> None
Ask the runtime to redraw an area, or the whole surface.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
to_cell_grid
¶
to_cell_grid() -> bytes
Pack the surface into the cell grid byte format.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
__or__
¶
Apply operation to this surface and return the surface.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
with_text
classmethod
¶
with_text(text: TextContent, *, style: Style | None = None) -> Buffer
Create a buffer sized to fit some text.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
with_size
classmethod
¶
Create a blank buffer of a given size.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
with_cells
classmethod
¶
Create a buffer from cells in row-major order.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
from_cell_grid
classmethod
¶
Create a buffer from the cell grid byte format.
Raises:
-
CellGridError–The bytes are not a valid cell grid.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
from_cell_animation
classmethod
¶
Create a buffer showing one frame of a packed cell animation.
Parameters:
-
packed(bytes) –The cell animation bytes.
-
start_milliseconds(int, default:0) –The point in the animation to show.
Raises:
-
CellGridError–The bytes are not a valid cell animation.
Examples:
frames = [Buffer.with_text('a').to_cell_grid(), Buffer.with_text('b').to_cell_grid()]
packed = pack_cell_animation(frames, frame_durations_milliseconds=[50, 50])
assert Buffer.from_cell_animation(packed, start_milliseconds=60).text == 'b'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
region
¶
resize
¶
Change the size, keeping the cells that still fit.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
paste
¶
Copy the cells of another buffer or region into this one.
Parameters:
-
source(Buffer | Region) –The cells to copy.
-
x(int, default:0) –The destination column of the source's left edge.
-
y(int, default:0) –The destination row of the source's top edge.
-
mode(PasteMode, default:'replace') –'replace'copies every cell,'preserve_background'keeps the destination background and'transparent'skips cells that are marked transparent.
Examples:
sprite = Buffer.with_text('ab')
canvas = Buffer(width=5, height=1)
canvas.paste(sprite, x=2)
assert canvas.text == ' ab'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
attach
¶
attach(child: Buffer, *, geometry: GeometryMode = 'explicit', mode: PasteMode = 'replace') -> None
Attach a child buffer as a retained layer of this one.
The child keeps its own cells and is composited when this buffer is drawn,
ordered by layer and then by attachment order. A child with
geometry='inherit' always fills the parent's content rectangle. The
'transparent' mode skips cells explicitly marked transparent, not spaces.
Raises:
-
ValueError–The child already has a parent.
Examples:
parent = Buffer(width=8, height=3)
child = Buffer('hi', x=2, y=1)
parent.attach(child)
assert parent.children == (child,)
assert parent.render(format='text').split('\n')[1] == ' hi'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
detach
¶
detach(child: Buffer) -> None
copy
¶
copy() -> Buffer
Copy the cells, geometry and children into a new, independent buffer.
Hooks and runtime state are not copied.
Examples:
original = Buffer.with_text('a')
duplicate = original.copy()
duplicate.write('b')
assert original.text == 'a'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
supports
¶
Return whether the buffer's registry can apply an operation type.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
__call__
¶
Return a lazy render of the buffer.
str(rendering) serializes the buffer without touching a terminal. Using
the result as a context manager mounts the buffer on runtime (or opens a
live runtime) and unmounts it on exit.
Examples:
buffer = Buffer.with_text('hi')
assert 'hi' in str(buffer())
with Runtime.offscreen(width=8, height=2) as runtime:
with buffer(runtime=runtime) as context:
assert context.runtime is runtime
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
render
¶
render(*, format: RenderFormat = 'ansi') -> str
Compose the visible children and serialize the buffer.
No terminal or device is opened.
Parameters:
-
format(RenderFormat, default:'ansi') –'text'for plain rows or'ansi'for text with styling escape sequences.
Examples:
buffer = Buffer.with_text('hi', style=Style(foreground='red'))
assert buffer.render(format='text') == 'hi'
assert '\x1b[' in buffer.render(format='ansi')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
Cell
¶
Cell(symbol: str = ' ', *, style: Style | None = None, foreground: ColorValue | None = None, background: ColorValue | None = None, modifiers: Sequence[Modifier] = (), is_transparent: bool = False)
A detached grapheme with its style, copied out of or written into a surface.
Reading buffer[column, row] returns a Cell snapshot; changing it does not
change the buffer until it is written back with buffer[column, row] = cell.
A transparent cell lets the content below it show through when buffers are
composited with the 'transparent' paste mode.
Maps to ratatui::buffer::Cell.
Parameters:
-
symbol(str, default:' ') –A single grapheme cluster. Defaults to one space.
-
style(Style | None, default:None) –A complete style for the cell. Combined with the color and modifier arguments below, which take precedence.
-
foreground(ColorValue | None, default:None) –The foreground color.
-
background(ColorValue | None, default:None) –The background color.
-
modifiers(Sequence[Modifier], default:()) –Text modifiers such as
'bold'or'underline'. -
is_transparent(bool, default:False) –Whether the cell lets lower layers show through.
Attributes:
-
symbol(str) –The grapheme drawn in the cell.
-
style(Style) –The cell's style.
-
foreground(Color) –The text color of this cell.
-
background(Color) –The background color of this cell.
-
is_transparent(bool) –Whether the cell lets lower layers show through.
Raises:
-
ValueError–symbolis not exactly one grapheme.
Examples:
cell = Cell('x', foreground='red', modifiers=['bold'])
assert cell.symbol == 'x'
assert cell.foreground == Color('red')
buffer = Buffer(width=3, height=1)
buffer[1, 0] = cell
assert buffer[1, 0].symbol == 'x'
Create a Cell.
Parameters:
-
symbol(str, default:' ') –str. Defaults to' '. -
style(Style | None, default:None) –Style | None. Defaults toNone. -
foreground(ColorValue | None, default:None) –ColorValue | None. Defaults toNone. -
background(ColorValue | None, default:None) –ColorValue | None. Defaults toNone. -
modifiers(Sequence[Modifier], default:()) –Sequence[Modifier]. Defaults to(). -
is_transparent(bool, default:False) –bool. Defaults toFalse.
-
API Reference
- xnano
-
xnano_core
-
xnano_core -
xnano_core._xnano_core
_xnano_core
-
Methods:
-
copy–Return an independent copy of the cell.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
is_transparent
instance-attribute
¶
is_transparent: bool
Whether the cell lets lower layers show through.