xnano_core
xnano_core
¶
xnano_core
The terminal engine behind xnano: buffers, widgets, operations, effects, the expression
language, events, state and the runtime.
Everything public is importable from here, for example
from xnano_core import Buffer, Gauge, Effect, Width. Most programs use these through
xnano, which re-exports the everyday ones.
Classes:
-
AnimateDrawing–Play a
DrawingAnimationon a mounted buffer. -
ApplyStatePatch–Apply a JSON patch to a state branch in one validated commit.
-
ApplyStyle–Patch a
Styleonto every cell of the target. -
Background–Set the background color of every cell of the target.
-
Bar–One labelled value in a bar chart.
-
BarChart–Grouped bars with editable values and styles.
-
BarGroup–A labelled group of bars.
-
Block–Borders, titles and padding shared by retained widgets.
-
BlockTitle–A styled title positioned on the top or bottom border of a block.
-
Border–Draw a border around the edge of the target.
-
Buffer–A layer of cells with a position, a size and the hooks that animate it.
-
BufferExpressionScope–A buffer's own position and size, as expressions.
-
Calendar–A monthly calendar with editable dates and styles for events.
-
CancelEffect–Stop the running effect that was started with
key. -
Canvas–A coordinate plane that shapes, points and labels are drawn on.
-
CanvasCircle–A circle outline.
-
CanvasLabel–Text printed at a position, always on top of the shapes.
-
CanvasLayer–Saves what was drawn so far as a layer; the shapes after it draw on top.
-
CanvasLine–A straight line between two points, optionally filled down to a baseline.
-
CanvasMap–The world map, in longitude and latitude (use bounds
(-180, 180)and(-90, 90)). -
CanvasMarker–Switches the marker the shapes after it are drawn with.
-
CanvasPoints–A set of single points.
-
CanvasRectangle–An axis-aligned rectangle outline.
-
Cell–A detached grapheme with its style, copied out of or written into a surface.
-
CellAnimationInfo–The header of a packed cell animation.
-
CellFilter–A composable selection of cells affected by an animation.
-
CellGridError–Packed cell data is malformed, incompatible or over a resource limit.
-
CellGridInfo–The header of a packed cell grid.
-
Chart–Point series drawn against shared editable axes.
-
ChartAxis–An editable axis with bounds, labels and a title.
-
ChartDataset–An editable series of points displayed by a chart.
-
Clear–Blank cells that hide whatever is behind them.
-
Clock–The time source a runtime reads, either real or stepped by hand.
-
Color–A terminal color: a named palette color, a palette index or a true color.
-
Conditional–Apply one operation when a condition is true and optionally another when it is not.
-
Cursor–The one cursor a terminal has.
-
Customization–A named, typed set of parameters that is also an operation.
-
CustomWidget–A widget drawn by a Python function.
-
DecodeLimits–Upper bounds checked before packed cell data is accepted.
-
Device–The display and terminal a runtime draws on.
-
Dissolve–Dissolve the glyphs of the target away cell by cell.
-
Draw–Draw a
Drawinginto the target. -
Drawing–An immutable picture made of rows of text or palette pixels.
-
DrawingAnimation–A sequence of timed drawings.
-
DrawingFrame–One frame of a
DrawingAnimation. -
DynamicStyle–A style whose colors may follow expressions.
-
Editor–Draw a
TextEditorinto a buffer. -
Effect–A composable animation with editable and bindable settings.
-
EffectManager–Start, replace, inspect and cancel animations on a runtime.
-
ErrorDetail–One labelled problem of an
ErrorReport. -
ErrorReport–One or more labelled problems, formatted like a pydantic
ValidationError. -
Event–Something that happened: input, a resize, a timer or a frame.
-
EventStream–The events a runtime reports, as an iterator.
-
Expression–A value or action described now and evaluated later against a buffer or runtime.
-
ExpressionScope–A named group of expressions, such as the parent's size or the terminal's clock.
-
Fade–Fade the colors of the target toward a foreground and background color.
-
Fill–Fill every cell of the target with one cell.
-
FocusScope–A group of input targets, optionally modal.
-
Foreground–Set the foreground color of every cell of the target.
-
FrameMetrics–Timing of the frames a runtime has drawn.
-
FrameSnapshot–An immutable copy of a drawn frame.
-
Fuzz–Replace a percentage of the visible glyphs of the target with noise glyphs, once.
-
Gauge–A filled progress bar that repaints when its ratio changes.
-
Glitch–Randomly corrupt and displace glyphs of the target.
-
HitArea–A named rectangle that receives mouse hits without needing painted text.
-
Hook–A registered callback that can be paused, reprioritized or cancelled.
-
InputOptions–The input modes a live terminal asks for.
-
InputRouter–Routes input events to buffers: handlers, hit areas, focus and scopes.
-
InputState–The keys and pointer position a runtime currently sees.
-
InvalidRegionError–A region no longer fits inside its resized buffer.
-
ItemList–Selectable styled items with editable selection and scrolling.
-
KeyBinding–A key and modifiers to match against key events.
-
KeyboardCapabilities–What the terminal's keyboard protocol can report.
-
KeyboardExpressionScope–The latest key event, as expressions.
-
KeyEvent–A key press, repeat or release.
-
Layout–Arrange attached children within the parent's content area.
-
LineGauge–A progress indicator drawn with line symbols.
-
ListItem–Styled content displayed by an item list.
-
Live–Operations that are applied again whenever something they show changes.
-
Margin–Horizontal and vertical inset distances.
-
MouseEvent–A mouse press, release, drag, move or scroll.
-
MouseExpressionScope–The latest mouse button or motion report, as expressions.
-
Move–Move the target buffer relative to its current position in its parent.
-
NumericProperty–A reference to a numeric property that can be read, computed with and assigned.
-
NumericValue–A numeric expression that supports comparisons and arithmetic.
-
Offset–A displacement in terminal columns and rows.
-
Operation–An action that changes a buffer, applied with
Buffer.update. -
OperationChain–Operations applied one after another when they cannot become one native sequence.
-
Paragraph–Styled text that can wrap, align and scroll.
-
ParentExpressionScope–The geometry of the enclosing buffer, as expressions.
-
Paste–Copy the cells of another buffer or region into the target.
-
Pixels–Draw ordered RGB pixels into the target.
-
PixelView–A raster view that draws logical pixels into the cells of a surface.
-
Place–Move the target buffer to an absolute position in its parent.
-
Point–A cell position, counted in columns (
x) and rows (y) from the top-left. -
Predicate–A condition that evaluates to
TrueorFalse. -
Property–A reference to a concrete property of a buffer or runtime.
-
Raster–Draw a row-major RGBA8 image into the target as pixels.
-
Rectangle–A rectangle of cells with half-open bounds.
-
Region–A fixed rectangle of a buffer that shares the buffer's cells.
-
RenderError–A recoverable failure while drawing a frame; the failed frame is not committed.
-
ReportedError–An error raised with an
ErrorReportas its one argument. -
Resize–Resize the target buffer to
widthbyheightcells. -
RootExpressionScope–The geometry and clock of the root terminal, as expressions.
-
RunningEffect–Playback controls and progress for a started animation.
-
Runtime–A session that mounts buffers, runs hooks and schedules, and draws frames.
-
RuntimeRequiredError–An operation needs a buffer mounted on an active runtime.
-
ScheduledCall–A callback scheduled on a clock with
call_laterorcall_every. -
Scrollbar–A scrollbar showing position within content.
-
ScrollExpressionScope–The mouse wheel steps of the current step, as expressions.
-
SequenceOperation–Apply several operations in order as one operation.
-
SetState–Assign a state branch and publish one validated commit.
-
SetValue–Assign a value to a property.
-
SimulationClock–A clock derived from a parent clock, with its own rate and stopped state.
-
Size–A width and a height, counted in cells.
-
SizeRule–How much space one child takes along a layout's main axis.
-
Sparkline–A compact history of numeric samples.
-
SparklineBar–A sample with an optional individual style.
-
StateReference–A branch of a state store that can be read, written or bound.
-
StepResult–What one
Runtime.step()did. -
Style–A foreground color, a background color and text modifiers.
-
StyledText–Text made of differently styled spans.
-
Surface–A grid of cells that text, styles, pixels and operations can be applied to.
-
Table–A retained table with row, column and cell selection.
-
TableCell–Styled content displayed in a table cell.
-
TableRow–A row of cells with height and spacing.
-
Tabs–Selectable titles with editable padding, divider and styles.
-
TerminalCapabilities–What a terminal can display.
-
TerminalOptions–How a live runtime takes over the terminal.
-
TerminalStateAccessError–Raised when a change touches a path that an observation did not grant for writing.
-
TerminalStateChange–The result of one committed change: what changed and the state before and after.
-
TerminalStateConflictError–Raised when a change was prepared against a revision that is no longer current.
-
TerminalStateIssue–One problem found while validating a value against a schema.
-
TerminalStateObservation–A record of what was read from a store, and which paths may be written.
-
TerminalStatePatch–A list of edits to a state tree, in the JSON Patch format (RFC 6902).
-
TerminalStateSchema–A compiled schema that validates state values.
-
TerminalStateSelection–Values read from several paths at one consistent revision.
-
TerminalStateSnapshot–An immutable view of a state tree, or of one branch of it, at one revision.
-
TerminalStateStore–Thread-safe state storage with schema validation, revisions and notifications.
-
TerminalStateSubscription–A registration that delivers state changes until it is cancelled.
-
TerminalStateTransaction–Staged edits that publish together or not at all.
-
TerminalStateValidationError–Raised when a value or a change does not satisfy a state schema.
-
TextEditor–An editable text buffer with a cursor and undo history.
-
TextLayout–Text wrapped to a width, with conversions between cells and string offsets.
-
TextLine–One wrapped line of a
TextLayout. -
TextSpan–A run of text with one style.
-
Trigger–When something runs, and which events count.
-
UnsupportedOperationError–The registry of the target cannot apply the operation it was given.
-
Value–An expression that evaluates to a value.
-
Waker–A handle other threads use to wake a runtime and run code on its thread.
-
Widget–A buffer painted from editable settings or bound expressions.
-
Write–Write text into the target at a cell position.
-
WriteCellText–Write text addressed by
columnandrowinstead ofxandy. -
CoreContext–A hook's view of the runtime: device, clock, input and focus.
-
EvaluationContext–What an expression or operation handler can see.
-
EventContext–A routed input event's view.
-
Extension–Something that adds operations to a registry.
-
FrameContext–A frame callback's view: every layout and drawing uses this frame's destination.
-
HookSignal–Control flow recognized only while the runtime executes a hook.
-
Invalidate–End the current hook and request a display frame.
-
Propagate–End the current hook and continue with the parent event target.
-
Registry–Operation handlers and extension installs for a buffer or runtime.
-
Rendering–A lazy static or live render of a buffer.
-
Skip–End the current hook and continue dispatch.
-
Stop–End the hook and request that the runtime stop.
-
UpdateContext–A simulation update's view.
Functions:
-
animation_frame_at–Return the packed cell grid shown at a time in an animation.
-
cell_grid_size–Return the
(columns, rows)of a packed cell grid. -
cell_grid_to_ansi–Return a packed cell grid as text with styling escape sequences.
-
cell_grid_to_text–Return the plain text rows of a packed cell grid.
-
detect_terminal_capabilities–Inspect the environment and ask the terminal what it can display.
-
display_width–The number of terminal cells a string occupies.
-
inspect_cell_animation–Read the header of a packed cell animation without decoding its frames.
-
inspect_cell_grid–Read the header of a packed cell grid without decoding its cells.
-
layout_text–Wrap text to a width.
-
pack_cell_animation–Pack cell grids into a cell animation.
-
query_keyboard_capabilities–Ask the terminal which keyboard protocol features it supports.
-
validate_cell_animation–Check that packed bytes are a complete, valid cell animation.
-
validate_cell_grid–Check that packed bytes are a complete, valid cell grid.
-
default_registry–The registry used by buffers and runtimes that were not given one.
Attributes:
-
FPS(NumericValue[int | float]) –The runtime's estimated frames per second.
-
Bounds(Value[Rectangle]) –The full bounds of a buffer or region as a
Rectangle. -
BufferRegion(Value[Rectangle]) –The rectangle of a buffer on the screen, counting every parent offset.
-
BufferScope(BufferExpressionScope) –A buffer's own geometry:
BufferScope.x,BufferScope.width, ... -
BufferSize(Value[Size]) –The dimensions of a buffer as a
Size. -
DeviceHeight(NumericValue[int | float]) –The terminal height, in cells.
-
DeviceWidth(NumericValue[int | float]) –The terminal width, in cells.
-
Focused(Value[bool]) –Whether the runtime has focus.
-
Frame(NumericValue[int | float]) –The current runtime frame number.
-
Height(NumericValue[int | float]) –The height of a buffer or region, in terminal cells.
-
IsVisible(Property[bool]) –Whether a buffer is drawn. Assign it with
IsVisible(False). -
KeyboardBinding(Value[str | None]) –The latest key event with its modifiers, such as
'ctrl+s', orNone. -
KeyboardKey(Value[str | None]) –The key of the latest key event, or
Nonewhile the latest input was not a key. -
KeyboardKind(Value[Literal['press', 'repeat', 'release'] | None]) –Whether the latest key event was a press, repeat or release, or
None. -
KeyboardScope(KeyboardExpressionScope) –The latest key event:
KeyboardScope.key,KeyboardScope.kind,KeyboardScope.binding. -
Layer(NumericProperty[int]) –The paint order of a buffer among its siblings. Assign it with
Layer(2). -
MouseButtonValue(Value[MouseButton | None]) –The button of the latest button or motion report, or
None. -
MouseIsDown(Predicate) –Whether any mouse button is held.
-
MouseKind(Value[Literal['press', 'release', 'drag', 'move'] | None]) –The kind of the latest button or motion report, or
None(also for a wheel report). -
MousePosition(Value[Point | None]) –The cell of the latest button or motion report, or
None. -
MouseScope(MouseExpressionScope) –The latest mouse button or motion report:
MouseScope.position,MouseScope.is_down, ... -
ParentHeight(NumericValue[int]) –The height of the parent buffer, in cells.
-
ParentScope(ParentExpressionScope) –The parent's geometry:
ParentScope.width,ParentScope.height,ParentScope.size. -
ParentSize(Value[Size]) –The size of the parent buffer, or of the buffer a region belongs to.
-
ParentWidth(NumericValue[int]) –The width of the parent buffer, in cells.
-
PointerPosition(Value[Point | None]) –The cell under the pointer, or
Noneuntil the runtime has seen the pointer. -
Position(Value[Point]) –The position of a buffer or region as a
Point. -
RootScope(RootExpressionScope) –The terminal's geometry and clock:
RootScope.width,RootScope.time, ... -
Running(Value[bool]) –Whether the runtime is running.
-
ScreenBounds(Value[Rectangle]) –The rectangle of a buffer or region on the screen, counting every parent offset.
-
ScreenPosition(Value[Point]) –The top-left cell of a buffer or region on the screen, counting every parent offset.
-
ScrollScope(ScrollExpressionScope) –The latest wheel report of the current step:
ScrollScope.xandScrollScope.y. -
ScrollX(NumericValue[int]) –Horizontal steps of the latest wheel report of the current step (right is positive).
-
ScrollY(NumericValue[int]) –Vertical steps of the latest wheel report of the step (down is positive, up is
-1). -
TimeDelta(NumericValue[int | float]) –The elapsed time since the previous runtime frame, in seconds.
-
TimeDeltaMilliseconds(NumericValue[int | float]) –The elapsed time since the previous runtime frame, in milliseconds.
-
TimeElapsed(NumericValue[int | float]) –The elapsed runtime time, in seconds.
-
TimeElapsedMilliseconds(NumericValue[int | float]) –The elapsed runtime time, in milliseconds.
-
Width(NumericValue[int | float]) –The width of a buffer or region, in terminal cells.
-
X(NumericValue[int | float]) –The horizontal position of a buffer or region, in terminal cells.
-
Y(NumericValue[int | float]) –The vertical position of a buffer or region, in terminal cells.
-
is_optimized_build(bool) –Whether the extension was built with optimizations and without coverage instrumentation. Timing any other build says nothing.
-
BorderKind(TypeAlias) –The line style of a border.
-
CanvasShape(TypeAlias) –Anything a canvas can draw.
-
CapabilityStatus(TypeAlias) –Whether a terminal feature is available.
-
ColorName(TypeAlias) –A named ANSI terminal color.
-
ColorProfile(TypeAlias) –How many colors a terminal can display.
-
ColorValue(TypeAlias) –A color, an ANSI color name, a
'#rrggbb'string, or a(red, green, blue)tuple. -
Coordinate(TypeAlias) –A
(column, row)pair. -
CursorShape(TypeAlias) –What a terminal cursor looks like.
-
EventKind(TypeAlias) –What an event reports.
-
EvolveSymbolSet(TypeAlias) –The symbols an evolve effect steps through.
-
GeometryMode(TypeAlias) –Whether a buffer takes its geometry from its parent or keeps its own.
-
GraphicsProtocol(TypeAlias) –How images are drawn into a terminal.
-
HookCallback(TypeAlias) –A function a hook calls with its context.
-
HookDecorator(TypeAlias) –A decorator that registers a hook callback and returns it unchanged.
-
HookEventKind(TypeAlias) –What a hook can listen to.
-
Interpolation(TypeAlias) –How an effect eases between its start and end;
'ease_in'is'quad_in'. -
JSONSchema(TypeAlias) –A JSON Schema document.
-
JSONValue(TypeAlias) –A finite JSON-compatible value.
-
KeyBindingText(TypeAlias) –A key optionally preceded by
+-joined modifiers, such asq,ctrl+corshift+tab. -
KeyEventKind(TypeAlias) –Whether a key was pressed, held down or released.
-
KeyModifier(TypeAlias) –A modifier key held during a key event.
-
KeyName(TypeAlias) –A key name as events report it and bindings accept it, such as
q,enterorpage_up. -
Modifier(TypeAlias) –A text style modifier.
-
MouseButton(TypeAlias) –A mouse button.
-
MouseEventKind(TypeAlias) –What a mouse event reports.
-
Orientation(TypeAlias) –The direction something runs in.
-
PasteMode(TypeAlias) –How copied cells combine with the destination.
-
PixelAnchor(TypeAlias) –Which pixel of a cell a cell coordinate refers to.
-
PixelEntry(TypeAlias) –One pixel:
(column, row, (red, green, blue)). -
RasterMode(TypeAlias) –How RGBA pixels combine with what is already there.
-
RenderFormat(TypeAlias) –How a buffer serializes: plain text rows or text with ANSI styling.
-
ScalarExpression(TypeAlias) –An expression of a number, text or a condition.
-
Side(TypeAlias) –A side of a rectangle.
-
StatePath(TypeAlias) –A path into a state tree: object keys are
strand array indexes areint. -
TailwindColorBinding(TypeAlias) –A Tailwind palette and shade, such as
'slate-400'. -
TailwindColorName(TypeAlias) –A Tailwind palette that has shades.
-
TailwindColorShade(TypeAlias) –A Tailwind shade.
-
TextContent(TypeAlias) –Text accepted by writing operations and components.
-
TriggerKind(TypeAlias) –When something runs: a moment of the loop, an interval, or a kind of event.
-
WriteMode(TypeAlias) –How written text treats the background already in the cell.
FPS
module-attribute
¶
FPS: NumericValue[int | float]
The runtime's estimated frames per second.
Bounds
module-attribute
¶
The full bounds of a buffer or region as a Rectangle.
BufferRegion
module-attribute
¶
The rectangle of a buffer on the screen, counting every parent offset.
BufferScope
module-attribute
¶
BufferScope: BufferExpressionScope
A buffer's own geometry: BufferScope.x, BufferScope.width, ...
BufferSize
module-attribute
¶
The dimensions of a buffer as a Size.
DeviceHeight
module-attribute
¶
DeviceHeight: NumericValue[int | float]
The terminal height, in cells.
DeviceWidth
module-attribute
¶
DeviceWidth: NumericValue[int | float]
The terminal width, in cells.
Focused
module-attribute
¶
Whether the runtime has focus.
Height
module-attribute
¶
Height: NumericValue[int | float]
The height of a buffer or region, in terminal cells.
IsVisible
module-attribute
¶
Whether a buffer is drawn. Assign it with IsVisible(False).
KeyboardBinding
module-attribute
¶
The latest key event with its modifiers, such as 'ctrl+s', or None.
KeyboardKey
module-attribute
¶
The key of the latest key event, or None while the latest input was not a key.
KeyboardKind
module-attribute
¶
Whether the latest key event was a press, repeat or release, or None.
KeyboardScope
module-attribute
¶
KeyboardScope: KeyboardExpressionScope
The latest key event: KeyboardScope.key, KeyboardScope.kind, KeyboardScope.binding.
Layer
module-attribute
¶
Layer: NumericProperty[int]
The paint order of a buffer among its siblings. Assign it with Layer(2).
MouseButtonValue
module-attribute
¶
MouseButtonValue: Value[MouseButton | None]
The button of the latest button or motion report, or None.
MouseKind
module-attribute
¶
The kind of the latest button or motion report, or None (also for a wheel report).
MousePosition
module-attribute
¶
The cell of the latest button or motion report, or None.
PointerPosition is the last cell the pointer was seen at, whatever came since; this one
belongs to the event being handled.
MouseScope
module-attribute
¶
MouseScope: MouseExpressionScope
The latest mouse button or motion report: MouseScope.position, MouseScope.is_down, ...
ParentHeight
module-attribute
¶
ParentHeight: NumericValue[int]
The height of the parent buffer, in cells.
ParentScope
module-attribute
¶
ParentScope: ParentExpressionScope
The parent's geometry: ParentScope.width, ParentScope.height, ParentScope.size.
ParentSize
module-attribute
¶
The size of the parent buffer, or of the buffer a region belongs to.
Evaluating it raises TypeError for a buffer without a parent.
ParentWidth
module-attribute
¶
ParentWidth: NumericValue[int]
The width of the parent buffer, in cells.
PointerPosition
module-attribute
¶
The cell under the pointer, or None until the runtime has seen the pointer.
It is the last known cell, held between events. MousePosition is the cell of the event
being handled. Reading it needs a mounted runtime.
Position
module-attribute
¶
The position of a buffer or region as a Point.
RootScope
module-attribute
¶
RootScope: RootExpressionScope
The terminal's geometry and clock: RootScope.width, RootScope.time, ...
ScreenBounds
module-attribute
¶
The rectangle of a buffer or region on the screen, counting every parent offset.
ScreenPosition
module-attribute
¶
The top-left cell of a buffer or region on the screen, counting every parent offset.
ScrollScope
module-attribute
¶
ScrollScope: ScrollExpressionScope
The latest wheel report of the current step: ScrollScope.x and ScrollScope.y.
ScrollX
module-attribute
¶
ScrollX: NumericValue[int]
Horizontal steps of the latest wheel report of the current step (right is positive).
ScrollY
module-attribute
¶
ScrollY: NumericValue[int]
Vertical steps of the latest wheel report of the step (down is positive, up is -1).
TimeDelta
module-attribute
¶
TimeDelta: NumericValue[int | float]
The elapsed time since the previous runtime frame, in seconds.
TimeDeltaMilliseconds
module-attribute
¶
TimeDeltaMilliseconds: NumericValue[int | float]
The elapsed time since the previous runtime frame, in milliseconds.
TimeElapsed
module-attribute
¶
TimeElapsed: NumericValue[int | float]
The elapsed runtime time, in seconds.
TimeElapsedMilliseconds
module-attribute
¶
TimeElapsedMilliseconds: NumericValue[int | float]
The elapsed runtime time, in milliseconds.
Width
module-attribute
¶
Width: NumericValue[int | float]
The width of a buffer or region, in terminal cells.
X
module-attribute
¶
X: NumericValue[int | float]
The horizontal position of a buffer or region, in terminal cells.
Y
module-attribute
¶
Y: NumericValue[int | float]
The vertical position of a buffer or region, in terminal cells.
is_optimized_build
module-attribute
¶
is_optimized_build: bool
Whether the extension was built with optimizations and without coverage instrumentation. Timing any other build says nothing.
BorderKind
module-attribute
¶
The line style of a border.
CanvasShape
module-attribute
¶
CanvasShape: TypeAlias = 'CanvasLine | CanvasRectangle | CanvasCircle | CanvasPoints | CanvasMap | CanvasLabel | CanvasLayer | CanvasMarker'
Anything a canvas can draw.
CapabilityStatus
module-attribute
¶
Whether a terminal feature is available.
ColorName
module-attribute
¶
ColorName: TypeAlias = Literal['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'gray', 'grey', 'dark_gray', 'dark_grey', 'darkgray', 'darkgrey', 'light_black', 'light_red', 'bright_red', 'light_green', 'bright_green', 'light_yellow', 'bright_yellow', 'light_blue', 'bright_blue', 'light_magenta', 'bright_magenta', 'light_cyan', 'bright_cyan', 'white', 'reset']
A named ANSI terminal color.
gray and grey are the same color, and so are light_ and bright_.
dark_gray is the dim gray. reset restores the terminal default.
ColorProfile
module-attribute
¶
How many colors a terminal can display.
ColorValue
module-attribute
¶
A color, an ANSI color name, a '#rrggbb' string, or a (red, green, blue) tuple.
A Tailwind name such as 'slate-400' is a TailwindColorBinding.
It is not parsed by Color.
-
API Reference
-
xnano
xnano.styles
stylesColorValue -
xnano_core
-
xnano_core -
xnano_core._xnano_core
_xnano_core
-
-
xnano
xnano.styles
Coordinate
module-attribute
¶
A (column, row) pair.
-
API Reference
xnano_core
-
xnano_core-
BarChart__setitem__ -
Block__setitem__ -
Buffer__setitem__ -
Calendar__setitem__ -
Canvas__setitem__ -
Chart__setitem__ -
Clear__setitem__ -
CustomWidget__setitem__ -
Gauge__setitem__ -
ItemList__setitem__ -
LineGauge__setitem__ -
Live__setitem__ -
Paragraph__setitem__ -
Region__setitem__ -
Scrollbar__setitem__ -
Sparkline__setitem__ -
Surface__setitem__ -
Table__setitem__ -
Tabs__setitem__ -
Widget__setitem__
-
-
xnano_core._xnano_core
_xnano_core-
BarChart__setitem__ -
Block__setitem__ -
Buffer__setitem__ -
Calendar__setitem__ -
Canvas__setitem__ -
Chart__setitem__ -
Clear__setitem__ -
CustomWidget__setitem__ -
Gauge__setitem__ -
ItemList__setitem__ -
LineGauge__setitem__ -
Live__setitem__ -
Paragraph__setitem__ -
Region__setitem__ -
Scrollbar__setitem__ -
Sparkline__setitem__ -
Surface__setitem__ -
Table__setitem__ -
Tabs__setitem__ -
Widget__setitem__
-
-
CursorShape
module-attribute
¶
What a terminal cursor looks like.
EventKind
module-attribute
¶
EventKind: TypeAlias = Literal['key', 'mouse', 'paste', 'resize', 'focus_gained', 'focus_lost', 'tick', 'timer', 'frame', 'wake', 'exit_requested', 'custom']
What an event reports.
EvolveSymbolSet
module-attribute
¶
EvolveSymbolSet: TypeAlias = Literal['blocks_horizontal', 'blocks_vertical', 'circle_fill', 'circles', 'quadrants', 'shaded', 'squares']
The symbols an evolve effect steps through.
-
API Reference
xnano
xnano.effects
effects-
EvolveEffectParameterssymbols -
EvolveEffectParametersSchemasymbols -
EvolveEffectSpecificationsymbols -
EvolveFromEffectParameterssymbols -
EvolveFromEffectParametersSchemasymbols -
EvolveFromEffectSpecificationsymbols -
EvolveIntoEffectParameterssymbols -
EvolveIntoEffectParametersSchemasymbols -
EvolveIntoEffectSpecificationsymbols
-
GeometryMode
module-attribute
¶
Whether a buffer takes its geometry from its parent or keeps its own.
GraphicsProtocol
module-attribute
¶
How images are drawn into a terminal.
HookCallback
module-attribute
¶
HookCallback: TypeAlias = 'Callable[[CoreContext], None]'
A function a hook calls with its context.
-
API Reference
xnano_core
-
xnano_core-
BarChartadd_hook -
Blockadd_hook -
Bufferadd_hook -
Calendaradd_hook -
Canvasadd_hook -
Chartadd_hook -
Clearadd_hook -
CustomWidgetadd_hook -
Gaugeadd_hook -
ItemListadd_hook -
LineGaugeadd_hook -
Liveadd_hook -
Paragraphadd_hook -
Regionadd_hook -
Scrollbaradd_hook -
Sparklineadd_hook -
Surfaceadd_hook -
Tableadd_hook -
Tabsadd_hook -
Widgetadd_hook
-
-
xnano_core._xnano_core
_xnano_core-
BarChartadd_hook -
Blockadd_hook -
Bufferadd_hook -
Calendaradd_hook -
Canvasadd_hook -
Chartadd_hook -
Clearadd_hook -
CustomWidgetadd_hook -
Gaugeadd_hook -
ItemListadd_hook -
LineGaugeadd_hook -
Liveadd_hook -
Paragraphadd_hook -
Regionadd_hook -
Scrollbaradd_hook -
Sparklineadd_hook -
Surfaceadd_hook -
Tableadd_hook -
Tabsadd_hook -
Widgetadd_hook
-
-
HookDecorator
module-attribute
¶
HookDecorator: TypeAlias = 'Callable[[HookCallback], HookCallback]'
A decorator that registers a hook callback and returns it unchanged.
HookEventKind
module-attribute
¶
HookEventKind: TypeAlias = Literal['key', 'mouse', 'paste', 'resize', 'focus_gained', 'focus_lost', 'tick', 'timer', 'frame', 'wake', 'exit_requested', 'custom', 'mount', 'unmount', 'change', 'state_change', 'before_render', 'after_render']
What a hook can listen to.
-
API Reference
xnano_core
-
xnano_core-
BarChartadd_hook -
Blockadd_hook -
Bufferadd_hook -
Calendaradd_hook -
Canvasadd_hook -
Chartadd_hook -
Clearadd_hook -
CustomWidgetadd_hook -
Gaugeadd_hook -
ItemListadd_hook -
LineGaugeadd_hook -
Liveadd_hook -
Paragraphadd_hook -
Regionadd_hook -
Scrollbaradd_hook -
Sparklineadd_hook -
Surfaceadd_hook -
Tableadd_hook -
Tabsadd_hook -
Widgetadd_hook
-
-
xnano_core._xnano_core
_xnano_core-
BarChartadd_hook -
Blockadd_hook -
Bufferadd_hook -
Calendaradd_hook -
Canvasadd_hook -
Chartadd_hook -
Clearadd_hook -
CustomWidgetadd_hook -
Gaugeadd_hook -
ItemListadd_hook -
LineGaugeadd_hook -
Liveadd_hook -
Paragraphadd_hook -
Regionadd_hook -
Scrollbaradd_hook -
Sparklineadd_hook -
Surfaceadd_hook -
Tableadd_hook -
Tabsadd_hook -
Widgetadd_hook
-
-
Interpolation
module-attribute
¶
Interpolation: TypeAlias = Literal['linear', 'back_in', 'back_out', 'back_in_out', 'bounce_in', 'bounce_out', 'bounce_in_out', 'circ_in', 'circ_out', 'circ_in_out', 'cubic_in', 'cubic_out', 'cubic_in_out', 'elastic_in', 'elastic_out', 'elastic_in_out', 'expo_in', 'expo_out', 'expo_in_out', 'quad_in', 'quad_out', 'quad_in_out', 'quart_in', 'quart_out', 'quart_in_out', 'quint_in', 'quint_out', 'quint_in_out', 'sine_in', 'sine_out', 'sine_in_out', 'smooth_step', 'spring', 'reverse', 'ease_in']
How an effect eases between its start and end; 'ease_in' is 'quad_in'.
JSONSchema
module-attribute
¶
JSONSchema: TypeAlias = 'dict[str, JSONValue]'
A JSON Schema document.
JSONValue
module-attribute
¶
JSONValue: TypeAlias = 'None | bool | int | float | str | list[JSONValue] | dict[str, JSONValue]'
A finite JSON-compatible value.
KeyBindingText
module-attribute
¶
KeyBindingText: TypeAlias = 'KeyName | str'
A key optionally preceded by +-joined modifiers, such as q, ctrl+c or shift+tab.
KeyEventKind
module-attribute
¶
Whether a key was pressed, held down or released.
KeyModifier
module-attribute
¶
A modifier key held during a key event.
KeyName
module-attribute
¶
KeyName: TypeAlias = Literal['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'enter', 'escape', 'backspace', 'tab', 'space', 'delete', 'insert', 'up', 'down', 'left', 'right', 'home', 'end', 'page_up', 'page_down', 'caps_lock', 'scroll_lock', 'num_lock', 'print_screen', 'pause', 'menu', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12']
A key name as events report it and bindings accept it, such as q, enter or page_up.
Modifier
module-attribute
¶
Modifier: TypeAlias = Literal['bold', 'dim', 'italic', 'underline', 'blink', 'reverse', 'hidden', 'crossed_out']
A text style modifier.
MouseButton
module-attribute
¶
A mouse button.
MouseEventKind
module-attribute
¶
What a mouse event reports.
Orientation
module-attribute
¶
The direction something runs in.
PasteMode
module-attribute
¶
How copied cells combine with the destination.
-
API Reference
xnano_core
-
xnano_core -
xnano_core._xnano_core
_xnano_core
-
PixelAnchor
module-attribute
¶
Which pixel of a cell a cell coordinate refers to.
PixelEntry
module-attribute
¶
One pixel: (column, row, (red, green, blue)).
RasterMode
module-attribute
¶
How RGBA pixels combine with what is already there.
RenderFormat
module-attribute
¶
How a buffer serializes: plain text rows or text with ANSI styling.
ScalarExpression
module-attribute
¶
ScalarExpression: TypeAlias = 'Expression[bool] | Expression[int | float] | Expression[str]'
An expression of a number, text or a condition.
Side
module-attribute
¶
A side of a rectangle.
StatePath
module-attribute
¶
StatePath: TypeAlias = 'tuple[str | int, ...]'
A path into a state tree: object keys are str and array indexes are int.
TailwindColorBinding
module-attribute
¶
TailwindColorBinding: TypeAlias = Literal['slate-50', 'slate-100', 'slate-200', 'slate-300', 'slate-400', 'slate-500', 'slate-600', 'slate-700', 'slate-800', 'slate-900', 'slate-950', 'gray-50', 'gray-100', 'gray-200', 'gray-300', 'gray-400', 'gray-500', 'gray-600', 'gray-700', 'gray-800', 'gray-900', 'gray-950', 'zinc-50', 'zinc-100', 'zinc-200', 'zinc-300', 'zinc-400', 'zinc-500', 'zinc-600', 'zinc-700', 'zinc-800', 'zinc-900', 'zinc-950', 'neutral-50', 'neutral-100', 'neutral-200', 'neutral-300', 'neutral-400', 'neutral-500', 'neutral-600', 'neutral-700', 'neutral-800', 'neutral-900', 'neutral-950', 'stone-50', 'stone-100', 'stone-200', 'stone-300', 'stone-400', 'stone-500', 'stone-600', 'stone-700', 'stone-800', 'stone-900', 'stone-950', 'red-50', 'red-100', 'red-200', 'red-300', 'red-400', 'red-500', 'red-600', 'red-700', 'red-800', 'red-900', 'red-950', 'orange-50', 'orange-100', 'orange-200', 'orange-300', 'orange-400', 'orange-500', 'orange-600', 'orange-700', 'orange-800', 'orange-900', 'orange-950', 'amber-50', 'amber-100', 'amber-200', 'amber-300', 'amber-400', 'amber-500', 'amber-600', 'amber-700', 'amber-800', 'amber-900', 'amber-950', 'yellow-50', 'yellow-100', 'yellow-200', 'yellow-300', 'yellow-400', 'yellow-500', 'yellow-600', 'yellow-700', 'yellow-800', 'yellow-900', 'yellow-950', 'lime-50', 'lime-100', 'lime-200', 'lime-300', 'lime-400', 'lime-500', 'lime-600', 'lime-700', 'lime-800', 'lime-900', 'lime-950', 'green-50', 'green-100', 'green-200', 'green-300', 'green-400', 'green-500', 'green-600', 'green-700', 'green-800', 'green-900', 'green-950', 'emerald-50', 'emerald-100', 'emerald-200', 'emerald-300', 'emerald-400', 'emerald-500', 'emerald-600', 'emerald-700', 'emerald-800', 'emerald-900', 'emerald-950', 'teal-50', 'teal-100', 'teal-200', 'teal-300', 'teal-400', 'teal-500', 'teal-600', 'teal-700', 'teal-800', 'teal-900', 'teal-950', 'cyan-50', 'cyan-100', 'cyan-200', 'cyan-300', 'cyan-400', 'cyan-500', 'cyan-600', 'cyan-700', 'cyan-800', 'cyan-900', 'cyan-950', 'sky-50', 'sky-100', 'sky-200', 'sky-300', 'sky-400', 'sky-500', 'sky-600', 'sky-700', 'sky-800', 'sky-900', 'sky-950', 'blue-50', 'blue-100', 'blue-200', 'blue-300', 'blue-400', 'blue-500', 'blue-600', 'blue-700', 'blue-800', 'blue-900', 'blue-950', 'indigo-50', 'indigo-100', 'indigo-200', 'indigo-300', 'indigo-400', 'indigo-500', 'indigo-600', 'indigo-700', 'indigo-800', 'indigo-900', 'indigo-950', 'violet-50', 'violet-100', 'violet-200', 'violet-300', 'violet-400', 'violet-500', 'violet-600', 'violet-700', 'violet-800', 'violet-900', 'violet-950', 'purple-50', 'purple-100', 'purple-200', 'purple-300', 'purple-400', 'purple-500', 'purple-600', 'purple-700', 'purple-800', 'purple-900', 'purple-950', 'fuchsia-50', 'fuchsia-100', 'fuchsia-200', 'fuchsia-300', 'fuchsia-400', 'fuchsia-500', 'fuchsia-600', 'fuchsia-700', 'fuchsia-800', 'fuchsia-900', 'fuchsia-950', 'pink-50', 'pink-100', 'pink-200', 'pink-300', 'pink-400', 'pink-500', 'pink-600', 'pink-700', 'pink-800', 'pink-900', 'pink-950', 'rose-50', 'rose-100', 'rose-200', 'rose-300', 'rose-400', 'rose-500', 'rose-600', 'rose-700', 'rose-800', 'rose-900', 'rose-950']
A Tailwind palette and shade, such as 'slate-400'.
Color does not parse these. Pass the palette and shade
to Color.from_tailwind.
TailwindColorName
module-attribute
¶
TailwindColorName: TypeAlias = Literal['slate', 'gray', 'zinc', 'neutral', 'stone', 'red', 'orange', 'amber', 'yellow', 'lime', 'green', 'emerald', 'teal', 'cyan', 'sky', 'blue', 'indigo', 'violet', 'purple', 'fuchsia', 'pink', 'rose']
A Tailwind palette that has shades.
TailwindColorShade
module-attribute
¶
A Tailwind shade.
TextContent
module-attribute
¶
TextContent: TypeAlias = 'str | StyledText | Sequence[str | StyledText]'
Text accepted by writing operations and components.
- API Reference
-
API Reference
- xnano
-
xnano_core
-
xnano_core -
xnano_core._xnano_core
_xnano_core
-
TriggerKind
module-attribute
¶
TriggerKind: TypeAlias = Literal['immediate', 'frame', 'update', 'key', 'key_release', 'click', 'drag', 'mouse', 'paste', 'resize', 'state_change', 'every', 'after']
When something runs: a moment of the loop, an interval, or a kind of event.
WriteMode
module-attribute
¶
How written text treats the background already in the cell.
-
API Reference
-
xnano
xnano.operations
operationsDynamicWrite -
xnano_core
-
xnano_core-
BarChartwrite -
Blockwrite -
Bufferwrite -
Calendarwrite -
Canvaswrite -
Chartwrite -
Clearwrite -
CustomWidgetwrite -
Editor -
Gaugewrite -
ItemListwrite -
LineGaugewrite -
Livewrite -
Paragraphwrite -
Paste -
Regionwrite -
Scrollbarwrite -
Sparklinewrite -
Surfacewrite -
Tablewrite -
Tabswrite -
Widgetwrite -
Write -
WriteCellText
-
-
xnano_core._xnano_core
_xnano_core-
BarChartwrite -
Blockwrite -
Bufferwrite -
Calendarwrite -
Canvaswrite -
Chartwrite -
Clearwrite -
CustomWidgetwrite -
Editor -
Gaugewrite -
ItemListwrite -
LineGaugewrite -
Livewrite -
Paragraphwrite -
Paste -
Regionwrite -
Scrollbarwrite -
Sparklinewrite -
Surfacewrite -
Tablewrite -
Tabswrite -
Widgetwrite -
Write -
WriteCellText
-
-
-
xnano
xnano.operations
AnimateDrawing
¶
AnimateDrawing(animation: DrawingAnimation, *, x: int = 0, y: int = 0, encoding: PixelEncoding = 'half_blocks', start_milliseconds: int = 0)
Bases: Operation
Play a DrawingAnimation on a mounted buffer.
The animation runs on the runtime clock, so applying it needs a runtime.
Parameters:
-
animation(DrawingAnimation) –The animation to play.
-
x(int, default:0) –The column of the picture's top-left cell.
-
y(int, default:0) –The row of the picture's top-left cell.
-
encoding(PixelEncoding, default:'half_blocks') –How palette pixels pack into cells.
-
start_milliseconds(int, default:0) –Where in the animation to start.
Examples:
runtime = Runtime.offscreen(width=4, height=1)
buffer = Buffer(width=4, height=1)
runtime.mount(buffer, geometry='inherit')
animation = DrawingAnimation(
[
DrawingFrame(Drawing(['a']), duration_milliseconds=50),
DrawingFrame(Drawing(['b']), duration_milliseconds=50),
]
)
buffer.update(AnimateDrawing(animation))
runtime.step()
assert runtime.snapshot().lines()[0].strip() == 'a'
runtime.advance_clock(50)
runtime.step()
assert runtime.snapshot().lines()[0].strip() == 'b'
Create a AnimateDrawing.
Parameters:
-
animation(DrawingAnimation) –DrawingAnimation. -
x(int, default:0) –int. Defaults to0. -
y(int, default:0) –int. Defaults to0. -
encoding(PixelEncoding, default:'half_blocks') –PixelEncoding. Defaults to'half_blocks'. -
start_milliseconds(int, default:0) –int. Defaults to0.
Methods:
-
evaluate–Compute the expression's value.
-
then–An operation that applies this operation, then
other. -
when–An operation that applies only while
conditionis true. -
__or__–Combine this operation with
otherso both run in sequence.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
self,
animation: DrawingAnimation,
*,
x: int = 0,
y: int = 0,
encoding: PixelEncoding = 'half_blocks',
start_milliseconds: int = 0,
) -> None:
"""
Create a AnimateDrawing.
Args:
animation: ``DrawingAnimation``.
x: ``int``. Defaults to ``0``.
y: ``int``. Defaults to ``0``.
encoding: ``PixelEncoding``. Defaults to ``'half_blocks'``.
start_milliseconds: ``int``. Defaults to ``0``.
"""
evaluate
¶
evaluate(context: EvaluationContext) -> ValueType_co
Compute the expression's value.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def evaluate(self, context: EvaluationContext) -> ValueType_co:
"""
Compute the expression's value.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
```
"""
then
¶
when
¶
An operation that applies only while condition is true.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
buffer = Buffer(width=6, height=1)
buffer.update(Write('wide').when(width > 4))
assert buffer.text.startswith('wide')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def when(self, condition: Predicate) -> Operation:
"""
An operation that applies only while ``condition`` is true.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
buffer = Buffer(width=6, height=1)
buffer.update(Write('wide').when(width > 4))
assert buffer.text.startswith('wide')
```
"""
__or__
¶
ApplyStatePatch
¶
ApplyStatePatch(reference: StateReference[StateType], patch: TerminalStatePatch, *, expected_revision: int | None = None)
Bases: Operation
Apply a JSON patch to a state branch in one validated commit.
Patch paths are relative to the reference.
Parameters:
-
reference(StateReference[StateType]) –A state reference exposing
pathandnative_store. -
patch(TerminalStatePatch) –The patch to apply below the reference's path.
-
expected_revision(int | None, default:None) –Fail with a conflict error unless the store is at this revision.
Examples:
schema = TerminalStateSchema.compile(
{
'type': 'object',
'properties': {
'player': {'type': 'object', 'properties': {'x': {'type': 'integer'}}}
},
}
)
store = TerminalStateStore({'player': {'x': 0}}, schema=schema)
class Reference:
path = ('player',)
native_store = store
schema = None
patch = TerminalStatePatch.from_value(
[{'op': 'replace', 'path': '/x', 'value': 9}]
)
Buffer().update(ApplyStatePatch(Reference(), patch))
assert store.snapshot().to_value() == {'player': {'x': 9}}
Create a ApplyStatePatch.
Parameters:
-
reference(StateReference[StateType]) –StateReference[StateType]. -
patch(TerminalStatePatch) –TerminalStatePatch. -
expected_revision(int | None, default:None) –int | None. Defaults toNone.
Methods:
-
evaluate–Compute the expression's value.
-
then–An operation that applies this operation, then
other. -
when–An operation that applies only while
conditionis true. -
__or__–Combine this operation with
otherso both run in sequence.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
self,
reference: StateReference[StateType],
patch: TerminalStatePatch,
*,
expected_revision: int | None = None,
) -> None:
"""
Create a ApplyStatePatch.
Args:
reference: ``StateReference[StateType]``.
patch: ``TerminalStatePatch``.
expected_revision: ``int | None``. Defaults to ``None``.
"""
evaluate
¶
evaluate(context: EvaluationContext) -> ValueType_co
Compute the expression's value.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def evaluate(self, context: EvaluationContext) -> ValueType_co:
"""
Compute the expression's value.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
```
"""
then
¶
when
¶
An operation that applies only while condition is true.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
buffer = Buffer(width=6, height=1)
buffer.update(Write('wide').when(width > 4))
assert buffer.text.startswith('wide')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def when(self, condition: Predicate) -> Operation:
"""
An operation that applies only while ``condition`` is true.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
buffer = Buffer(width=6, height=1)
buffer.update(Write('wide').when(width > 4))
assert buffer.text.startswith('wide')
```
"""
__or__
¶
ApplyStyle
¶
ApplyStyle(style: Style)
Bases: Operation
Patch a Style onto every cell of the target.
Colors and modifiers the style leaves unset are kept.
Parameters:
-
style(Style) –The style to patch onto each cell.
Examples:
buffer = Buffer(width=3, height=1)
buffer.update(Write('abc'), ApplyStyle(Style('green', bold=True)))
assert 'bold' in buffer[0, 0].style.modifiers
Create a ApplyStyle.
Parameters:
-
style(Style) –Style.
Methods:
-
evaluate–Compute the expression's value.
-
then–An operation that applies this operation, then
other. -
when–An operation that applies only while
conditionis true. -
__or__–Combine this operation with
otherso both run in sequence.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
evaluate
¶
evaluate(context: EvaluationContext) -> ValueType_co
Compute the expression's value.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def evaluate(self, context: EvaluationContext) -> ValueType_co:
"""
Compute the expression's value.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
```
"""
then
¶
when
¶
An operation that applies only while condition is true.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
buffer = Buffer(width=6, height=1)
buffer.update(Write('wide').when(width > 4))
assert buffer.text.startswith('wide')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def when(self, condition: Predicate) -> Operation:
"""
An operation that applies only while ``condition`` is true.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
buffer = Buffer(width=6, height=1)
buffer.update(Write('wide').when(width > 4))
assert buffer.text.startswith('wide')
```
"""
__or__
¶
Background
¶
Background(color: ColorValue)
Bases: Operation
Set the background color of every cell of the target.
Parameters:
-
color(ColorValue) –A
Color, a color name, a hex string or an(red, green, blue)tuple.
Examples:
buffer = Buffer(width=3, height=1)
buffer.update(Background((0, 0, 255)))
assert buffer[0, 0].background.to_rgb() == (0, 0, 255)
Create a Background.
Parameters:
-
color(ColorValue) –ColorValue.
Methods:
-
evaluate–Compute the expression's value.
-
then–An operation that applies this operation, then
other. -
when–An operation that applies only while
conditionis true. -
__or__–Combine this operation with
otherso both run in sequence.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
evaluate
¶
evaluate(context: EvaluationContext) -> ValueType_co
Compute the expression's value.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def evaluate(self, context: EvaluationContext) -> ValueType_co:
"""
Compute the expression's value.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
```
"""
then
¶
when
¶
An operation that applies only while condition is true.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
buffer = Buffer(width=6, height=1)
buffer.update(Write('wide').when(width > 4))
assert buffer.text.startswith('wide')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def when(self, condition: Predicate) -> Operation:
"""
An operation that applies only while ``condition`` is true.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
buffer = Buffer(width=6, height=1)
buffer.update(Write('wide').when(width > 4))
assert buffer.text.startswith('wide')
```
"""
__or__
¶
Bar
¶
Bar(value: int | Expression[int | float], label: TextContent | Expression[str] | None = None, *, text_value: str | Expression[str] | None = None, style: Style | DynamicStyle | None = None, value_style: Style | DynamicStyle | None = None)
One labelled value in a bar chart.
Attributes:
-
label(TextContent | Expression[str] | None) –The text displayed as the label, or
Noneto omit it. -
style(Style | DynamicStyle) –The default colors and text modifiers applied to the cells.
-
value(int | Expression[int | float]) –The nonnegative numeric value represented by the bar.
-
text_value(str | Expression[str]) –The text drawn for the value, or
Noneto display the numeric value. -
value_style(Style | DynamicStyle) –The colors and text modifiers applied to the displayed value.
Examples:
Create a Bar.
Parameters:
-
value(int | Expression[int | float]) –int | Expression[int | float]. -
label(TextContent | Expression[str] | None, default:None) –TextContent | Expression[str] | None. Defaults toNone. -
text_value(str | Expression[str] | None, default:None) –str | Expression[str] | None. Defaults toNone. -
style(Style | DynamicStyle | None, default:None) –Style | DynamicStyle | None. Defaults toNone. -
value_style(Style | DynamicStyle | None, default:None) –Style | DynamicStyle | None. Defaults toNone.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
self,
/,
value: int | Expression[int | float],
label: TextContent | Expression[str] | None = None,
*,
text_value: str | Expression[str] | None = None,
style: Style | DynamicStyle | None = None,
value_style: Style | DynamicStyle | None = None,
) -> None:
"""
Create a Bar.
Args:
value: ``int | Expression[int | float]``.
label: ``TextContent | Expression[str] | None``. Defaults to ``None``.
text_value: ``str | Expression[str] | None``. Defaults to ``None``.
style: ``Style | DynamicStyle | None``. Defaults to ``None``.
value_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
"""
label
property
¶
label: TextContent | Expression[str] | None
The text displayed as the label, or None to omit it.
style
property
¶
style: Style | DynamicStyle
The default colors and text modifiers applied to the cells.
value
property
¶
value: int | Expression[int | float]
The nonnegative numeric value represented by the bar.
text_value
property
¶
text_value: str | Expression[str]
The text drawn for the value, or None to display the numeric value.
value_style
property
¶
value_style: Style | DynamicStyle
The colors and text modifiers applied to the displayed value.
BarChart
¶
BarChart(data: Sequence[Bar | BarGroup | int] | None = None, *, bar_width: int | Expression[int | float] | None = None, bar_gap: int | Expression[int | float] | None = None, group_gap: int | Expression[int | float] | None = None, maximum: int | Expression[int | float] | None = None, direction: str | Expression[str] | None = None, bar_style: Style | DynamicStyle | None = None, value_style: Style | DynamicStyle | None = None, label_style: Style | DynamicStyle | None = None, style: Style | DynamicStyle | None = None, bar_set: str | Expression[str] | None = None, block: Block | None = None, width: int | Expression[int | float] | None = None, height: int | Expression[int | float] | None = None, x: int | Expression[int | float] = 0, y: int | Expression[int | float] = 0)
Bases: Widget
Grouped bars with editable values and styles.
Attributes:
-
label_style(Style | DynamicStyle) –The colors and text modifiers applied to bar and group labels.
-
group_gap(int | Expression[int | float]) –The number of empty cells between groups of bars.
-
bar_gap(int | Expression[int | float]) –The number of empty cells between adjacent bars.
-
block(Block | None) –The optional border, titles and padding around the content.
-
style(Style | DynamicStyle) –The default colors and text modifiers applied to the cells.
-
bar_width(int | Expression[int | float]) –The thickness of each bar, in cells.
-
direction(str | Expression[str]) –The orientation of the bars:
verticalorhorizontal. -
maximum(int | Expression[int | float] | None) –The value represented by a full bar, or
Noneto use the largest value. -
groups(Sequence[BarGroup]) –The groups of bars displayed in sequence order.
-
bar_set(str | Expression[str]) –The named set of symbols used to draw partial and full bars.
-
bar_style(Style | DynamicStyle) –The default colors and text modifiers applied to the bars.
-
value_style(Style | DynamicStyle) –The colors and text modifiers applied to the displayed value.
Examples:
Create a BarChart.
Parameters:
-
data(Sequence[Bar | BarGroup | int] | None, default:None) –Sequence[Bar | BarGroup | int] | None. Defaults toNone. -
bar_width(int | Expression[int | float] | None, default:None) –int | Expression[int | float] | None. Defaults toNone. -
bar_gap(int | Expression[int | float] | None, default:None) –int | Expression[int | float] | None. Defaults toNone. -
group_gap(int | Expression[int | float] | None, default:None) –int | Expression[int | float] | None. Defaults toNone. -
maximum(int | Expression[int | float] | None, default:None) –int | Expression[int | float] | None. Defaults toNone. -
direction(str | Expression[str] | None, default:None) –str | Expression[str] | None. Defaults toNone. -
bar_style(Style | DynamicStyle | None, default:None) –Style | DynamicStyle | None. Defaults toNone. -
value_style(Style | DynamicStyle | None, default:None) –Style | DynamicStyle | None. Defaults toNone. -
label_style(Style | DynamicStyle | None, default:None) –Style | DynamicStyle | None. Defaults toNone. -
style(Style | DynamicStyle | None, default:None) –Style | DynamicStyle | None. Defaults toNone. -
bar_set(str | Expression[str] | None, default:None) –str | Expression[str] | None. Defaults toNone. -
block(Block | None, default:None) –Block | None. Defaults toNone. -
width(int | Expression[int | float] | None, default:None) –int | Expression[int | float] | None. Defaults toNone. -
height(int | Expression[int | float] | None, default:None) –int | Expression[int | float] | None. Defaults toNone. -
x(int | Expression[int | float], default:0) –int | Expression[int | float]. Defaults to0. -
y(int | Expression[int | float], default:0) –int | Expression[int | float]. Defaults to0.
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.
-
supports–Return whether the buffer's registry can apply an operation type.
-
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.
-
__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
def __init__(
self,
/,
data: Sequence[Bar | BarGroup | int] | None = None,
*,
bar_width: int | Expression[int | float] | None = None,
bar_gap: int | Expression[int | float] | None = None,
group_gap: int | Expression[int | float] | None = None,
maximum: int | Expression[int | float] | None = None,
direction: str | Expression[str] | None = None,
bar_style: Style | DynamicStyle | None = None,
value_style: Style | DynamicStyle | None = None,
label_style: Style | DynamicStyle | None = None,
style: Style | DynamicStyle | None = None,
bar_set: str | Expression[str] | None = None,
block: Block | None = None,
width: int | Expression[int | float] | None = None,
height: int | Expression[int | float] | None = None,
x: int | Expression[int | float] = 0,
y: int | Expression[int | float] = 0,
) -> None:
"""
Create a BarChart.
Args:
data: ``Sequence[Bar | BarGroup | int] | None``. Defaults to ``None``.
bar_width: ``int | Expression[int | float] | None``. Defaults to ``None``.
bar_gap: ``int | Expression[int | float] | None``. Defaults to ``None``.
group_gap: ``int | Expression[int | float] | None``. Defaults to ``None``.
maximum: ``int | Expression[int | float] | None``. Defaults to ``None``.
direction: ``str | Expression[str] | None``. Defaults to ``None``.
bar_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
value_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
label_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
style: ``Style | DynamicStyle | None``. Defaults to ``None``.
bar_set: ``str | Expression[str] | None``. Defaults to ``None``.
block: ``Block | None``. Defaults to ``None``.
width: ``int | Expression[int | float] | None``. Defaults to ``None``.
height: ``int | Expression[int | float] | None``. Defaults to ``None``.
x: ``int | Expression[int | float]``. Defaults to ``0``.
y: ``int | Expression[int | float]``. Defaults to ``0``.
"""
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.
should_fit_width
property
writable
¶
should_fit_width: bool
Whether the width follows the children: as wide as the farthest right edge.
Only visible children attached with explicit geometry count, and a child whose
parent_measured_axes include 'width' (or whose x is placed by this
buffer's size) is placed within the width the others give. The width is fitted
before every frame, and at once by
Runtime.fit_to_content. A buffer
that fits its children and is mounted on a runtime with geometry='inherit'
decides that runtime's width.
Examples:
should_fit_height
property
writable
¶
should_fit_height: bool
Whether the height follows the children: as tall as the lowest bottom edge.
The rules of should_fit_width apply along the other axis.
fit_padding
property
writable
¶
The columns after the farthest right edge and the rows below the lowest bottom edge that a buffer which fits its children adds, for a border or padding on those sides.
parent_measured_axes
property
writable
¶
The parts of the buffer's place that its parent's size decides.
Set it to the axes that are a percentage, a word such as 'center' or a formula of
the parent's size. A parent that fits its children places such a buffer within the
size the other children give it: one placed by the parent's size counts with its own
size, and one sized by it does not count along that axis.
Raises:
-
ValueError–A name is not
'x','y','width'or'height'.
Examples:
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.
label_style
property
writable
¶
label_style: Style | DynamicStyle
The colors and text modifiers applied to bar and group labels.
group_gap
property
writable
¶
group_gap: int | Expression[int | float]
The number of empty cells between groups of bars.
bar_gap
property
writable
¶
bar_gap: int | Expression[int | float]
The number of empty cells between adjacent bars.
block
property
writable
¶
block: Block | None
The optional border, titles and padding around the content.
style
property
writable
¶
style: Style | DynamicStyle
The default colors and text modifiers applied to the cells.
bar_width
property
writable
¶
bar_width: int | Expression[int | float]
The thickness of each bar, in cells.
direction
property
writable
¶
direction: str | Expression[str]
The orientation of the bars: vertical or horizontal.
maximum
property
writable
¶
maximum: int | Expression[int | float] | None
The value represented by a full bar, or None to use the largest value.
groups
property
writable
¶
The groups of bars displayed in sequence order.
bar_set
property
writable
¶
bar_set: str | Expression[str]
The named set of symbols used to draw partial and full bars.
bar_style
property
writable
¶
bar_style: Style | DynamicStyle
The default colors and text modifiers applied to the bars.
value_style
property
writable
¶
value_style: Style | DynamicStyle
The colors and text modifiers applied to the displayed value.
__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
def write(
self,
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.
Args:
text: A string or styled text.
x: The starting column.
y: The starting row.
style: A style applied to the written cells.
mode: ``'replace'`` overwrites the cell; ``'preserve_background'`` keeps
the background already there.
Examples:
```python
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'
```
"""
fill
¶
Set every cell of the surface.
Examples:
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
def set_background_colors(
self,
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).
Args:
colors: A flat, row-major sequence of colors (names, ``(r, g, b)`` tuples or
[`Color`][xnano_core._xnano_core.Color] values). ``None`` leaves a cell alone.
width: The number of colors in one row of ``colors``.
x: The column of the block's top-left cell in this surface.
y: The row of the block's top-left cell in this surface.
Raises:
ValueError: ``width`` is below 1, ``len(colors)`` is not a multiple of ``width``, or
the block does not fit inside the surface, or an entry is not a color.
TypeError: ``colors`` is a single string instead of a sequence of colors, or an
entry has no color meaning.
Examples:
```python
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'
```
"""
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
def set_foreground_colors(
self,
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).
Args:
colors: A flat, row-major sequence of colors (names, ``(r, g, b)`` tuples or
[`Color`][xnano_core._xnano_core.Color] values). ``None`` leaves a cell alone.
width: The number of colors in one row of ``colors``.
x: The column of the block's top-left cell in this surface.
y: The row of the block's top-left cell in this surface.
Raises:
ValueError: ``width`` is below 1, ``len(colors)`` is not a multiple of ``width``, or
the block does not fit inside the surface, or an entry is not a color.
TypeError: ``colors`` is a single string instead of a sequence of colors, or an
entry has no color meaning.
Examples:
```python
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'
```
"""
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
def pixels(self, *, encoding: PixelEncoding = 'half_blocks') -> PixelView:
"""
Return a pixel view that draws into this surface.
Args:
encoding: ``'half_blocks'`` for one column and two rows per cell or
``'braille'`` for two columns and four rows per cell.
Examples:
```python
buffer = Buffer(width=3, height=2)
assert (buffer.pixels().width, buffer.pixels().height) == (3, 4)
assert (buffer.pixels(encoding='braille').width) == 6
```
"""
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
def update(self, *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:
```python
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'
```
"""
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
def inspect(self, expression: Expression[ValueType]) -> ValueType:
"""
Evaluate an expression against this surface and return its value.
Examples:
```python
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
```
"""
supports
¶
Return whether the buffer's registry can apply an operation type.
Examples:
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
def add_hook(
self,
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.
Args:
callback: Called with a context for the event.
condition: An expression that must be true for the callback to run.
events: The event kinds to listen to.
priority: Hooks with higher priority run first.
once: Whether to remove the hook after its first run.
Returns:
The registered hook, which can be cancelled.
Examples:
```python
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']
```
"""
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
__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:
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
@classmethod
def from_cell_animation(cls, packed: bytes, *, start_milliseconds: int = 0) -> Buffer:
"""
Create a buffer showing one frame of a packed cell animation.
Args:
packed: The cell animation bytes.
start_milliseconds: The point in the animation to show.
Raises:
CellGridError: The bytes are not a valid cell animation.
Examples:
```python
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'
```
"""
region
¶
resize
¶
Change the size, keeping the cells that still fit.
Examples:
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
def paste(
self,
source: Buffer | Region,
*,
x: int = 0,
y: int = 0,
mode: PasteMode = 'replace',
) -> None:
"""
Copy the cells of another buffer or region into this one.
Args:
source: The cells to copy.
x: The destination column of the source's left edge.
y: The destination row of the source's top edge.
mode: ``'replace'`` copies every cell, ``'preserve_background'`` keeps
the destination background and ``'transparent'`` skips cells that
are marked transparent.
Examples:
```python
sprite = Buffer.with_text('ab')
canvas = Buffer(width=5, height=1)
canvas.paste(sprite, x=2)
assert canvas.text == ' ab'
```
"""
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
def attach(
self,
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:
```python
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'
```
"""
detach
¶
detach(child: Buffer) -> None
__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
def __call__(self, *, runtime: Runtime | None = None) -> Rendering:
"""
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:
```python
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
```
"""
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 the same rows with styling escape sequences. Both join the rows with newlines and add none after the last row, soprintshows exactly the buffer.
Examples:
buffer = Buffer.with_text('hi', style=Style(foreground='red'))
assert buffer.render(format='text') == 'hi'
assert '\x1b[' in buffer.render(format='ansi')
assert not buffer.render(format='ansi').endswith('\n')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def render(self, *, format: RenderFormat = 'ansi') -> str:
"""
Compose the visible children and serialize the buffer.
No terminal or device is opened.
Args:
format: ``'text'`` for plain rows or ``'ansi'`` for the same rows with
styling escape sequences. Both join the rows with newlines and add
none after the last row, so ``print`` shows exactly the buffer.
Examples:
```python
buffer = Buffer.with_text('hi', style=Style(foreground='red'))
assert buffer.render(format='text') == 'hi'
assert '\\x1b[' in buffer.render(format='ansi')
assert not buffer.render(format='ansi').endswith('\\n')
```
"""
BarGroup
¶
BarGroup(bars: Sequence[Bar], label: TextContent | Expression[str] | None = None)
A labelled group of bars.
Attributes:
-
label(TextContent | Expression[str] | None) –The text displayed as the label, or
Noneto omit it. -
bars(Sequence[Bar]) –The bars displayed in their sequence order.
Examples:
Create a BarGroup.
Parameters:
-
bars(Sequence[Bar]) –Sequence[Bar]. -
label(TextContent | Expression[str] | None, default:None) –TextContent | Expression[str] | None. Defaults toNone.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
label
property
¶
label: TextContent | Expression[str] | None
The text displayed as the label, or None to omit it.
Block
¶
Block(title: str | Expression[str] | None = None, *, borders: str | Sequence[str] | None = None, border_type: str | Expression[str] | None = None, border_style: Style | DynamicStyle | None = None, style: Style | DynamicStyle | None = None, title_style: Style | DynamicStyle | None = None, title_alignment: str = 'left', padding: int | Expression[int | float] | tuple[int | Expression[int | float], int | Expression[int | float], int | Expression[int | float], int | Expression[int | float]] | None = None, merge: str | Expression[str] | None = None, width: int | Expression[int | float] | None = None, height: int | Expression[int | float] | None = None, x: int | Expression[int | float] = 0, y: int | Expression[int | float] = 0)
Bases: Widget
Borders, titles and padding shared by retained widgets.
Attributes:
-
border_type(str | Expression[str]) –The named border-symbol style, such as
plain,roundedordouble. -
title_alignment(str | Expression[str]) –The default horizontal alignment of titles:
left,centerorright. -
border_style(Style | DynamicStyle) –The colors and text modifiers applied to the border.
-
title_style(Style | DynamicStyle) –The default colors and text modifiers applied to titles.
-
padding(int | Expression[int | float] | tuple[int | Expression[int | float], int | Expression[int | float], int | Expression[int | float], int | Expression[int | float]]) –The inner spacing in cells: one value for every edge or a tuple of left, right, top and bottom values.
-
merge(str | Expression[str]) –The border-merging policy used where this block meets another border.
-
style(Style | DynamicStyle) –The default colors and text modifiers applied to the cells.
-
titles(Sequence[BlockTitle | str]) –The titles placed on the block border, in sequence order.
-
borders(str | Sequence[str]) –The edges on which borders are drawn.
Examples:
block = Block('Status', width=12, height=3)
assert 'Status' in block.render(format='text')
block.border_type = 'double'
assert '╔' in block.render(format='text')
Create a Block.
Parameters:
-
title(str | Expression[str] | None, default:None) –str | Expression[str] | None. Defaults toNone. -
borders(str | Sequence[str] | None, default:None) –str | Sequence[str] | None. Defaults toNone. -
border_type(str | Expression[str] | None, default:None) –str | Expression[str] | None. Defaults toNone. -
border_style(Style | DynamicStyle | None, default:None) –Style | DynamicStyle | None. Defaults toNone. -
style(Style | DynamicStyle | None, default:None) –Style | DynamicStyle | None. Defaults toNone. -
title_style(Style | DynamicStyle | None, default:None) –Style | DynamicStyle | None. Defaults toNone. -
title_alignment(str, default:'left') –str. Defaults to'left'. -
padding(int | Expression[int | float] | tuple[int | Expression[int | float], int | Expression[int | float], int | Expression[int | float], int | Expression[int | float]] | None, default:None) –int | Expression[int | float] | tuple[int | Expression[int | float], int | Expression[int | float], int | Expression[int | float], int | Expression[int | float]] | None. Defaults toNone. -
merge(str | Expression[str] | None, default:None) –str | Expression[str] | None. Defaults toNone. -
width(int | Expression[int | float] | None, default:None) –int | Expression[int | float] | None. Defaults toNone. -
height(int | Expression[int | float] | None, default:None) –int | Expression[int | float] | None. Defaults toNone. -
x(int | Expression[int | float], default:0) –int | Expression[int | float]. Defaults to0. -
y(int | Expression[int | float], default:0) –int | Expression[int | float]. Defaults to0.
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.
-
supports–Return whether the buffer's registry can apply an operation type.
-
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.
-
__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
def __init__(
self,
/,
title: str | Expression[str] | None = None,
*,
borders: str | Sequence[str] | None = None,
border_type: str | Expression[str] | None = None,
border_style: Style | DynamicStyle | None = None,
style: Style | DynamicStyle | None = None,
title_style: Style | DynamicStyle | None = None,
title_alignment: str = 'left',
padding: int
| Expression[int | float]
| tuple[
int | Expression[int | float],
int | Expression[int | float],
int | Expression[int | float],
int | Expression[int | float],
]
| None = None,
merge: str | Expression[str] | None = None,
width: int | Expression[int | float] | None = None,
height: int | Expression[int | float] | None = None,
x: int | Expression[int | float] = 0,
y: int | Expression[int | float] = 0,
) -> None:
"""
Create a Block.
Args:
title: ``str | Expression[str] | None``. Defaults to ``None``.
borders: ``str | Sequence[str] | None``. Defaults to ``None``.
border_type: ``str | Expression[str] | None``. Defaults to ``None``.
border_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
style: ``Style | DynamicStyle | None``. Defaults to ``None``.
title_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
title_alignment: ``str``. Defaults to ``'left'``.
padding: ``int | Expression[int | float] | tuple[int | Expression[int | float], int |
Expression[int | float], int | Expression[int | float], int | Expression[int | float]] | None``.
Defaults to ``None``.
merge: ``str | Expression[str] | None``. Defaults to ``None``.
width: ``int | Expression[int | float] | None``. Defaults to ``None``.
height: ``int | Expression[int | float] | None``. Defaults to ``None``.
x: ``int | Expression[int | float]``. Defaults to ``0``.
y: ``int | Expression[int | float]``. Defaults to ``0``.
"""
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.
should_fit_width
property
writable
¶
should_fit_width: bool
Whether the width follows the children: as wide as the farthest right edge.
Only visible children attached with explicit geometry count, and a child whose
parent_measured_axes include 'width' (or whose x is placed by this
buffer's size) is placed within the width the others give. The width is fitted
before every frame, and at once by
Runtime.fit_to_content. A buffer
that fits its children and is mounted on a runtime with geometry='inherit'
decides that runtime's width.
Examples:
should_fit_height
property
writable
¶
should_fit_height: bool
Whether the height follows the children: as tall as the lowest bottom edge.
The rules of should_fit_width apply along the other axis.
fit_padding
property
writable
¶
The columns after the farthest right edge and the rows below the lowest bottom edge that a buffer which fits its children adds, for a border or padding on those sides.
parent_measured_axes
property
writable
¶
The parts of the buffer's place that its parent's size decides.
Set it to the axes that are a percentage, a word such as 'center' or a formula of
the parent's size. A parent that fits its children places such a buffer within the
size the other children give it: one placed by the parent's size counts with its own
size, and one sized by it does not count along that axis.
Raises:
-
ValueError–A name is not
'x','y','width'or'height'.
Examples:
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.
border_type
property
writable
¶
border_type: str | Expression[str]
The named border-symbol style, such as plain, rounded or double.
title_alignment
property
writable
¶
title_alignment: str | Expression[str]
The default horizontal alignment of titles: left, center or right.
border_style
property
writable
¶
border_style: Style | DynamicStyle
The colors and text modifiers applied to the border.
title_style
property
writable
¶
title_style: Style | DynamicStyle
The default colors and text modifiers applied to titles.
padding
property
writable
¶
padding: int | Expression[int | float] | tuple[int | Expression[int | float], int | Expression[int | float], int | Expression[int | float], int | Expression[int | float]]
The inner spacing in cells: one value for every edge or a tuple of left, right, top and bottom values.
merge
property
writable
¶
merge: str | Expression[str]
The border-merging policy used where this block meets another border.
style
property
writable
¶
style: Style | DynamicStyle
The default colors and text modifiers applied to the cells.
titles
property
writable
¶
titles: Sequence[BlockTitle | str]
The titles placed on the block border, in sequence order.
__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
def write(
self,
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.
Args:
text: A string or styled text.
x: The starting column.
y: The starting row.
style: A style applied to the written cells.
mode: ``'replace'`` overwrites the cell; ``'preserve_background'`` keeps
the background already there.
Examples:
```python
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'
```
"""
fill
¶
Set every cell of the surface.
Examples:
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
def set_background_colors(
self,
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).
Args:
colors: A flat, row-major sequence of colors (names, ``(r, g, b)`` tuples or
[`Color`][xnano_core._xnano_core.Color] values). ``None`` leaves a cell alone.
width: The number of colors in one row of ``colors``.
x: The column of the block's top-left cell in this surface.
y: The row of the block's top-left cell in this surface.
Raises:
ValueError: ``width`` is below 1, ``len(colors)`` is not a multiple of ``width``, or
the block does not fit inside the surface, or an entry is not a color.
TypeError: ``colors`` is a single string instead of a sequence of colors, or an
entry has no color meaning.
Examples:
```python
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'
```
"""
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
def set_foreground_colors(
self,
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).
Args:
colors: A flat, row-major sequence of colors (names, ``(r, g, b)`` tuples or
[`Color`][xnano_core._xnano_core.Color] values). ``None`` leaves a cell alone.
width: The number of colors in one row of ``colors``.
x: The column of the block's top-left cell in this surface.
y: The row of the block's top-left cell in this surface.
Raises:
ValueError: ``width`` is below 1, ``len(colors)`` is not a multiple of ``width``, or
the block does not fit inside the surface, or an entry is not a color.
TypeError: ``colors`` is a single string instead of a sequence of colors, or an
entry has no color meaning.
Examples:
```python
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'
```
"""
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
def pixels(self, *, encoding: PixelEncoding = 'half_blocks') -> PixelView:
"""
Return a pixel view that draws into this surface.
Args:
encoding: ``'half_blocks'`` for one column and two rows per cell or
``'braille'`` for two columns and four rows per cell.
Examples:
```python
buffer = Buffer(width=3, height=2)
assert (buffer.pixels().width, buffer.pixels().height) == (3, 4)
assert (buffer.pixels(encoding='braille').width) == 6
```
"""
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
def update(self, *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:
```python
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'
```
"""
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
def inspect(self, expression: Expression[ValueType]) -> ValueType:
"""
Evaluate an expression against this surface and return its value.
Examples:
```python
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
```
"""
supports
¶
Return whether the buffer's registry can apply an operation type.
Examples:
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
def add_hook(
self,
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.
Args:
callback: Called with a context for the event.
condition: An expression that must be true for the callback to run.
events: The event kinds to listen to.
priority: Hooks with higher priority run first.
once: Whether to remove the hook after its first run.
Returns:
The registered hook, which can be cancelled.
Examples:
```python
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']
```
"""
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
__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:
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
@classmethod
def from_cell_animation(cls, packed: bytes, *, start_milliseconds: int = 0) -> Buffer:
"""
Create a buffer showing one frame of a packed cell animation.
Args:
packed: The cell animation bytes.
start_milliseconds: The point in the animation to show.
Raises:
CellGridError: The bytes are not a valid cell animation.
Examples:
```python
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'
```
"""
region
¶
resize
¶
Change the size, keeping the cells that still fit.
Examples:
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
def paste(
self,
source: Buffer | Region,
*,
x: int = 0,
y: int = 0,
mode: PasteMode = 'replace',
) -> None:
"""
Copy the cells of another buffer or region into this one.
Args:
source: The cells to copy.
x: The destination column of the source's left edge.
y: The destination row of the source's top edge.
mode: ``'replace'`` copies every cell, ``'preserve_background'`` keeps
the destination background and ``'transparent'`` skips cells that
are marked transparent.
Examples:
```python
sprite = Buffer.with_text('ab')
canvas = Buffer(width=5, height=1)
canvas.paste(sprite, x=2)
assert canvas.text == ' ab'
```
"""
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
def attach(
self,
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:
```python
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'
```
"""
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
__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
def __call__(self, *, runtime: Runtime | None = None) -> Rendering:
"""
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:
```python
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
```
"""
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 the same rows with styling escape sequences. Both join the rows with newlines and add none after the last row, soprintshows exactly the buffer.
Examples:
buffer = Buffer.with_text('hi', style=Style(foreground='red'))
assert buffer.render(format='text') == 'hi'
assert '\x1b[' in buffer.render(format='ansi')
assert not buffer.render(format='ansi').endswith('\n')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def render(self, *, format: RenderFormat = 'ansi') -> str:
"""
Compose the visible children and serialize the buffer.
No terminal or device is opened.
Args:
format: ``'text'`` for plain rows or ``'ansi'`` for the same rows with
styling escape sequences. Both join the rows with newlines and add
none after the last row, so ``print`` shows exactly the buffer.
Examples:
```python
buffer = Buffer.with_text('hi', style=Style(foreground='red'))
assert buffer.render(format='text') == 'hi'
assert '\\x1b[' in buffer.render(format='ansi')
assert not buffer.render(format='ansi').endswith('\\n')
```
"""
BlockTitle
¶
BlockTitle(text: TextContent | Expression[str], *, position: str = 'top', alignment: str | Expression[str] | None = None, style: Style | DynamicStyle | None = None)
A styled title positioned on the top or bottom border of a block.
Attributes:
-
style(Style | DynamicStyle) –The default colors and text modifiers applied to the cells.
-
alignment(str | Expression[str]) –The horizontal title alignment, or
Noneto use the block setting. -
text(TextContent | Expression[str]) –The text displayed on the block border.
-
position(int | Expression[int | float]) –The border holding this title:
toporbottom.
Examples:
Create a BlockTitle.
Parameters:
-
text(TextContent | Expression[str]) –TextContent | Expression[str]. -
position(str, default:'top') –str. Defaults to'top'. -
alignment(str | Expression[str] | None, default:None) –str | Expression[str] | None. Defaults toNone. -
style(Style | DynamicStyle | None, default:None) –Style | DynamicStyle | None. Defaults toNone.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
self,
/,
text: TextContent | Expression[str],
*,
position: str = 'top',
alignment: str | Expression[str] | None = None,
style: Style | DynamicStyle | None = None,
) -> None:
"""
Create a BlockTitle.
Args:
text: ``TextContent | Expression[str]``.
position: ``str``. Defaults to ``'top'``.
alignment: ``str | Expression[str] | None``. Defaults to ``None``.
style: ``Style | DynamicStyle | None``. Defaults to ``None``.
"""
style
property
¶
style: Style | DynamicStyle
The default colors and text modifiers applied to the cells.
alignment
property
¶
alignment: str | Expression[str]
The horizontal title alignment, or None to use the block setting.
position
property
¶
position: int | Expression[int | float]
The border holding this title: top or bottom.
Border
¶
Border(kind: BorderKind = 'plain', *, style: Style | None = None)
Bases: Operation
Draw a border around the edge of the target.
Maps to ratatui::widgets::Block
with BorderType.
Parameters:
-
kind(BorderKind, default:'plain') –'plain','rounded','double'or'thick'. -
style(Style | None, default:None) –The style of the border cells.
Examples:
buffer = Buffer(width=6, height=3)
buffer.update(Border('rounded'))
assert buffer.render(format='text').split('\n')[0] == '╭────╮'
Create a Border.
Parameters:
-
kind(BorderKind, default:'plain') –BorderKind. Defaults to'plain'. -
style(Style | None, default:None) –Style | None. Defaults toNone.
Methods:
-
evaluate–Compute the expression's value.
-
then–An operation that applies this operation, then
other. -
when–An operation that applies only while
conditionis true. -
__or__–Combine this operation with
otherso both run in sequence.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
evaluate
¶
evaluate(context: EvaluationContext) -> ValueType_co
Compute the expression's value.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def evaluate(self, context: EvaluationContext) -> ValueType_co:
"""
Compute the expression's value.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
```
"""
then
¶
when
¶
An operation that applies only while condition is true.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
buffer = Buffer(width=6, height=1)
buffer.update(Write('wide').when(width > 4))
assert buffer.text.startswith('wide')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def when(self, condition: Predicate) -> Operation:
"""
An operation that applies only while ``condition`` is true.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
buffer = Buffer(width=6, height=1)
buffer.update(Write('wide').when(width > 4))
assert buffer.text.startswith('wide')
```
"""
__or__
¶
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.
-
should_fit_width(bool) –Whether the width follows the children it holds.
-
should_fit_height(bool) –Whether the height follows the children it holds.
-
fit_padding(tuple[int, int]) –The columns and rows a buffer that fits its children adds after them.
-
parent_measured_axes(tuple[Literal['x', 'y', 'width', 'height'], ...]) –The parts of the buffer's place that its parent's size decides.
-
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_core
-
xnano_core -
xnano_core._xnano_core
_xnano_core -
xnano_core._xnano_core._core_types
_core_types
-
-
API Reference
- xnano
-
xnano_core
-
xnano_core -
xnano_core._xnano_core
_xnano_core -
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
def __init__(
self,
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,
) -> None:
"""
Create a Buffer.
Args:
content: ``TextContent | None``. Defaults to ``None``.
width: ``int | None``. Defaults to ``None``.
height: ``int | None``. Defaults to ``None``.
x: ``int``. Defaults to ``0``.
y: ``int``. Defaults to ``0``.
style: ``Style | None``. Defaults to ``None``.
registry: ``Registry | None``. Defaults to ``None``.
"""
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.
should_fit_width
property
writable
¶
should_fit_width: bool
Whether the width follows the children: as wide as the farthest right edge.
Only visible children attached with explicit geometry count, and a child whose
parent_measured_axes include 'width' (or whose x is placed by this
buffer's size) is placed within the width the others give. The width is fitted
before every frame, and at once by
Runtime.fit_to_content. A buffer
that fits its children and is mounted on a runtime with geometry='inherit'
decides that runtime's width.
Examples:
should_fit_height
property
writable
¶
should_fit_height: bool
Whether the height follows the children: as tall as the lowest bottom edge.
The rules of should_fit_width apply along the other axis.
fit_padding
property
writable
¶
The columns after the farthest right edge and the rows below the lowest bottom edge that a buffer which fits its children adds, for a border or padding on those sides.
parent_measured_axes
property
writable
¶
The parts of the buffer's place that its parent's size decides.
Set it to the axes that are a percentage, a word such as 'center' or a formula of
the parent's size. A parent that fits its children places such a buffer within the
size the other children give it: one placed by the parent's size counts with its own
size, and one sized by it does not count along that axis.
Raises:
-
ValueError–A name is not
'x','y','width'or'height'.
Examples:
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
def write(
self,
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.
Args:
text: A string or styled text.
x: The starting column.
y: The starting row.
style: A style applied to the written cells.
mode: ``'replace'`` overwrites the cell; ``'preserve_background'`` keeps
the background already there.
Examples:
```python
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'
```
"""
fill
¶
Set every cell of the surface.
Examples:
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
def set_background_colors(
self,
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).
Args:
colors: A flat, row-major sequence of colors (names, ``(r, g, b)`` tuples or
[`Color`][xnano_core._xnano_core.Color] values). ``None`` leaves a cell alone.
width: The number of colors in one row of ``colors``.
x: The column of the block's top-left cell in this surface.
y: The row of the block's top-left cell in this surface.
Raises:
ValueError: ``width`` is below 1, ``len(colors)`` is not a multiple of ``width``, or
the block does not fit inside the surface, or an entry is not a color.
TypeError: ``colors`` is a single string instead of a sequence of colors, or an
entry has no color meaning.
Examples:
```python
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'
```
"""
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
def set_foreground_colors(
self,
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).
Args:
colors: A flat, row-major sequence of colors (names, ``(r, g, b)`` tuples or
[`Color`][xnano_core._xnano_core.Color] values). ``None`` leaves a cell alone.
width: The number of colors in one row of ``colors``.
x: The column of the block's top-left cell in this surface.
y: The row of the block's top-left cell in this surface.
Raises:
ValueError: ``width`` is below 1, ``len(colors)`` is not a multiple of ``width``, or
the block does not fit inside the surface, or an entry is not a color.
TypeError: ``colors`` is a single string instead of a sequence of colors, or an
entry has no color meaning.
Examples:
```python
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'
```
"""
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
def pixels(self, *, encoding: PixelEncoding = 'half_blocks') -> PixelView:
"""
Return a pixel view that draws into this surface.
Args:
encoding: ``'half_blocks'`` for one column and two rows per cell or
``'braille'`` for two columns and four rows per cell.
Examples:
```python
buffer = Buffer(width=3, height=2)
assert (buffer.pixels().width, buffer.pixels().height) == (3, 4)
assert (buffer.pixels(encoding='braille').width) == 6
```
"""
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
def update(self, *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:
```python
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'
```
"""
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
def inspect(self, expression: Expression[ValueType]) -> ValueType:
"""
Evaluate an expression against this surface and return its value.
Examples:
```python
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
```
"""
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
def add_hook(
self,
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.
Args:
callback: Called with a context for the event.
condition: An expression that must be true for the callback to run.
events: The event kinds to listen to.
priority: Hooks with higher priority run first.
once: Whether to remove the hook after its first run.
Returns:
The registered hook, which can be cancelled.
Examples:
```python
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']
```
"""
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
__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:
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
@classmethod
def from_cell_animation(cls, packed: bytes, *, start_milliseconds: int = 0) -> Buffer:
"""
Create a buffer showing one frame of a packed cell animation.
Args:
packed: The cell animation bytes.
start_milliseconds: The point in the animation to show.
Raises:
CellGridError: The bytes are not a valid cell animation.
Examples:
```python
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'
```
"""
region
¶
resize
¶
Change the size, keeping the cells that still fit.
Examples:
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
def paste(
self,
source: Buffer | Region,
*,
x: int = 0,
y: int = 0,
mode: PasteMode = 'replace',
) -> None:
"""
Copy the cells of another buffer or region into this one.
Args:
source: The cells to copy.
x: The destination column of the source's left edge.
y: The destination row of the source's top edge.
mode: ``'replace'`` copies every cell, ``'preserve_background'`` keeps
the destination background and ``'transparent'`` skips cells that
are marked transparent.
Examples:
```python
sprite = Buffer.with_text('ab')
canvas = Buffer(width=5, height=1)
canvas.paste(sprite, x=2)
assert canvas.text == ' ab'
```
"""
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
def attach(
self,
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:
```python
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'
```
"""
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:
__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
def __call__(self, *, runtime: Runtime | None = None) -> Rendering:
"""
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:
```python
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
```
"""
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 the same rows with styling escape sequences. Both join the rows with newlines and add none after the last row, soprintshows exactly the buffer.
Examples:
buffer = Buffer.with_text('hi', style=Style(foreground='red'))
assert buffer.render(format='text') == 'hi'
assert '\x1b[' in buffer.render(format='ansi')
assert not buffer.render(format='ansi').endswith('\n')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def render(self, *, format: RenderFormat = 'ansi') -> str:
"""
Compose the visible children and serialize the buffer.
No terminal or device is opened.
Args:
format: ``'text'`` for plain rows or ``'ansi'`` for the same rows with
styling escape sequences. Both join the rows with newlines and add
none after the last row, so ``print`` shows exactly the buffer.
Examples:
```python
buffer = Buffer.with_text('hi', style=Style(foreground='red'))
assert buffer.render(format='text') == 'hi'
assert '\\x1b[' in buffer.render(format='ansi')
assert not buffer.render(format='ansi').endswith('\\n')
```
"""
BufferExpressionScope
¶
Bases: ExpressionScope
A buffer's own position and size, as expressions.
Attributes:
-
x(NumericValue[int | float]) –The column in the parent.
-
y(NumericValue[int | float]) –The row in the parent.
-
position(Value[Point]) –The position in the parent.
-
width(NumericValue[int | float]) –The width in cells.
-
height(NumericValue[int | float]) –The height in cells.
-
size(Value[Size]) –The size in cells.
-
region(Value[Rectangle]) –The rectangle on the screen, counting every parent offset.
Examples:
Calendar
¶
Calendar(year: int | Expression[int | float], month: int | Expression[int | float], day: int | Expression[int | float] | None = None, *, events: Mapping[tuple[int, int, int], Style | DynamicStyle] | None = None, style: Style | DynamicStyle | None = None, surrounding_style: Style | DynamicStyle | None = None, weekdays_header_style: Style | DynamicStyle | None = None, month_header_style: Style | DynamicStyle | None = None, block: Block | None = None, width: int | Expression[int | float] | None = None, height: int | Expression[int | float] | None = None, x: int | Expression[int | float] = 0, y: int | Expression[int | float] = 0)
Bases: Widget
A monthly calendar with editable dates and styles for events.
Attributes:
-
weekdays_header_style(Style | DynamicStyle) –The colors and text modifiers applied to the weekday headings.
-
events(Mapping[tuple[int, int, int], Style | DynamicStyle]) –The styles applied to dates, keyed by year, month and day.
-
day(int | Expression[int | float]) –The day of the month selected by the calendar date.
-
year(int | Expression[int | float]) –The year of the displayed calendar month.
-
month_header_style(Style | DynamicStyle) –The colors and text modifiers applied to the month heading.
-
block(Block | None) –The optional border, titles and padding around the content.
-
style(Style | DynamicStyle) –The default colors and text modifiers applied to the cells.
-
surrounding_style(Style | DynamicStyle) –The colors and text modifiers applied to dates outside the displayed month.
-
month(int | Expression[int | float]) –The displayed month number, from
1for January to12for December.
Examples:
calendar = Calendar(2026, 10, month_header_style=Style(), width=22, height=8)
assert 'October' in calendar.render(format='text')
calendar.month = 11
assert 'November' in calendar.render(format='text')
Create a Calendar.
Parameters:
-
year(int | Expression[int | float]) –int | Expression[int | float]. -
month(int | Expression[int | float]) –int | Expression[int | float]. -
day(int | Expression[int | float] | None, default:None) –int | Expression[int | float] | None. Defaults toNone. -
events(Mapping[tuple[int, int, int], Style | DynamicStyle] | None, default:None) –Mapping[tuple[int, int, int], Style | DynamicStyle] | None. Defaults toNone. -
style(Style | DynamicStyle | None, default:None) –Style | DynamicStyle | None. Defaults toNone. -
surrounding_style(Style | DynamicStyle | None, default:None) –Style | DynamicStyle | None. Defaults toNone. -
weekdays_header_style(Style | DynamicStyle | None, default:None) –Style | DynamicStyle | None. Defaults toNone. -
month_header_style(Style | DynamicStyle | None, default:None) –Style | DynamicStyle | None. Defaults toNone. -
block(Block | None, default:None) –Block | None. Defaults toNone. -
width(int | Expression[int | float] | None, default:None) –int | Expression[int | float] | None. Defaults toNone. -
height(int | Expression[int | float] | None, default:None) –int | Expression[int | float] | None. Defaults toNone. -
x(int | Expression[int | float], default:0) –int | Expression[int | float]. Defaults to0. -
y(int | Expression[int | float], default:0) –int | Expression[int | float]. Defaults to0.
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.
-
supports–Return whether the buffer's registry can apply an operation type.
-
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.
-
__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
def __init__(
self,
/,
year: int | Expression[int | float],
month: int | Expression[int | float],
day: int | Expression[int | float] | None = None,
*,
events: Mapping[tuple[int, int, int], Style | DynamicStyle] | None = None,
style: Style | DynamicStyle | None = None,
surrounding_style: Style | DynamicStyle | None = None,
weekdays_header_style: Style | DynamicStyle | None = None,
month_header_style: Style | DynamicStyle | None = None,
block: Block | None = None,
width: int | Expression[int | float] | None = None,
height: int | Expression[int | float] | None = None,
x: int | Expression[int | float] = 0,
y: int | Expression[int | float] = 0,
) -> None:
"""
Create a Calendar.
Args:
year: ``int | Expression[int | float]``.
month: ``int | Expression[int | float]``.
day: ``int | Expression[int | float] | None``. Defaults to ``None``.
events: ``Mapping[tuple[int, int, int], Style | DynamicStyle] | None``. Defaults to
``None``.
style: ``Style | DynamicStyle | None``. Defaults to ``None``.
surrounding_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
weekdays_header_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
month_header_style: ``Style | DynamicStyle | None``. Defaults to ``None``.
block: ``Block | None``. Defaults to ``None``.
width: ``int | Expression[int | float] | None``. Defaults to ``None``.
height: ``int | Expression[int | float] | None``. Defaults to ``None``.
x: ``int | Expression[int | float]``. Defaults to ``0``.
y: ``int | Expression[int | float]``. Defaults to ``0``.
"""
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.
should_fit_width
property
writable
¶
should_fit_width: bool
Whether the width follows the children: as wide as the farthest right edge.
Only visible children attached with explicit geometry count, and a child whose
parent_measured_axes include 'width' (or whose x is placed by this
buffer's size) is placed within the width the others give. The width is fitted
before every frame, and at once by
Runtime.fit_to_content. A buffer
that fits its children and is mounted on a runtime with geometry='inherit'
decides that runtime's width.
Examples:
should_fit_height
property
writable
¶
should_fit_height: bool
Whether the height follows the children: as tall as the lowest bottom edge.
The rules of should_fit_width apply along the other axis.
fit_padding
property
writable
¶
The columns after the farthest right edge and the rows below the lowest bottom edge that a buffer which fits its children adds, for a border or padding on those sides.
parent_measured_axes
property
writable
¶
The parts of the buffer's place that its parent's size decides.
Set it to the axes that are a percentage, a word such as 'center' or a formula of
the parent's size. A parent that fits its children places such a buffer within the
size the other children give it: one placed by the parent's size counts with its own
size, and one sized by it does not count along that axis.
Raises:
-
ValueError–A name is not
'x','y','width'or'height'.
Examples:
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.
weekdays_header_style
property
writable
¶
weekdays_header_style: Style | DynamicStyle
The colors and text modifiers applied to the weekday headings.
events
property
writable
¶
The styles applied to dates, keyed by year, month and day.
day
property
writable
¶
day: int | Expression[int | float]
The day of the month selected by the calendar date.
year
property
writable
¶
year: int | Expression[int | float]
The year of the displayed calendar month.
month_header_style
property
writable
¶
month_header_style: Style | DynamicStyle
The colors and text modifiers applied to the month heading.
block
property
writable
¶
block: Block | None
The optional border, titles and padding around the content.
style
property
writable
¶
style: Style | DynamicStyle
The default colors and text modifiers applied to the cells.
surrounding_style
property
writable
¶
surrounding_style: Style | DynamicStyle
The colors and text modifiers applied to dates outside the displayed month.
month
property
writable
¶
month: int | Expression[int | float]
The displayed month number, from 1 for January to 12 for December.
__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
def write(
self,
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.
Args:
text: A string or styled text.
x: The starting column.
y: The starting row.
style: A style applied to the written cells.
mode: ``'replace'`` overwrites the cell; ``'preserve_background'`` keeps
the background already there.
Examples:
```python
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'
```
"""
fill
¶
Set every cell of the surface.
Examples:
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
def set_background_colors(
self,
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).
Args:
colors: A flat, row-major sequence of colors (names, ``(r, g, b)`` tuples or
[`Color`][xnano_core._xnano_core.Color] values). ``None`` leaves a cell alone.
width: The number of colors in one row of ``colors``.
x: The column of the block's top-left cell in this surface.
y: The row of the block's top-left cell in this surface.
Raises:
ValueError: ``width`` is below 1, ``len(colors)`` is not a multiple of ``width``, or
the block does not fit inside the surface, or an entry is not a color.
TypeError: ``colors`` is a single string instead of a sequence of colors, or an
entry has no color meaning.
Examples:
```python
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'
```
"""
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
def set_foreground_colors(
self,
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).
Args:
colors: A flat, row-major sequence of colors (names, ``(r, g, b)`` tuples or
[`Color`][xnano_core._xnano_core.Color] values). ``None`` leaves a cell alone.
width: The number of colors in one row of ``colors``.
x: The column of the block's top-left cell in this surface.
y: The row of the block's top-left cell in this surface.
Raises:
ValueError: ``width`` is below 1, ``len(colors)`` is not a multiple of ``width``, or
the block does not fit inside the surface, or an entry is not a color.
TypeError: ``colors`` is a single string instead of a sequence of colors, or an
entry has no color meaning.
Examples:
```python
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'
```
"""
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
def pixels(self, *, encoding: PixelEncoding = 'half_blocks') -> PixelView:
"""
Return a pixel view that draws into this surface.
Args:
encoding: ``'half_blocks'`` for one column and two rows per cell or
``'braille'`` for two columns and four rows per cell.
Examples:
```python
buffer = Buffer(width=3, height=2)
assert (buffer.pixels().width, buffer.pixels().height) == (3, 4)
assert (buffer.pixels(encoding='braille').width) == 6
```
"""
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
def update(self, *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:
```python
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'
```
"""
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
def inspect(self, expression: Expression[ValueType]) -> ValueType:
"""
Evaluate an expression against this surface and return its value.
Examples:
```python
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
```
"""
supports
¶
Return whether the buffer's registry can apply an operation type.
Examples:
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
def add_hook(
self,
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.
Args:
callback: Called with a context for the event.
condition: An expression that must be true for the callback to run.
events: The event kinds to listen to.
priority: Hooks with higher priority run first.
once: Whether to remove the hook after its first run.
Returns:
The registered hook, which can be cancelled.
Examples:
```python
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']
```
"""
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
__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:
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
@classmethod
def from_cell_animation(cls, packed: bytes, *, start_milliseconds: int = 0) -> Buffer:
"""
Create a buffer showing one frame of a packed cell animation.
Args:
packed: The cell animation bytes.
start_milliseconds: The point in the animation to show.
Raises:
CellGridError: The bytes are not a valid cell animation.
Examples:
```python
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'
```
"""
region
¶
resize
¶
Change the size, keeping the cells that still fit.
Examples:
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
def paste(
self,
source: Buffer | Region,
*,
x: int = 0,
y: int = 0,
mode: PasteMode = 'replace',
) -> None:
"""
Copy the cells of another buffer or region into this one.
Args:
source: The cells to copy.
x: The destination column of the source's left edge.
y: The destination row of the source's top edge.
mode: ``'replace'`` copies every cell, ``'preserve_background'`` keeps
the destination background and ``'transparent'`` skips cells that
are marked transparent.
Examples:
```python
sprite = Buffer.with_text('ab')
canvas = Buffer(width=5, height=1)
canvas.paste(sprite, x=2)
assert canvas.text == ' ab'
```
"""
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
def attach(
self,
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:
```python
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'
```
"""
detach
¶
detach(child: Buffer) -> None
__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
def __call__(self, *, runtime: Runtime | None = None) -> Rendering:
"""
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:
```python
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
```
"""
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 the same rows with styling escape sequences. Both join the rows with newlines and add none after the last row, soprintshows exactly the buffer.
Examples:
buffer = Buffer.with_text('hi', style=Style(foreground='red'))
assert buffer.render(format='text') == 'hi'
assert '\x1b[' in buffer.render(format='ansi')
assert not buffer.render(format='ansi').endswith('\n')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def render(self, *, format: RenderFormat = 'ansi') -> str:
"""
Compose the visible children and serialize the buffer.
No terminal or device is opened.
Args:
format: ``'text'`` for plain rows or ``'ansi'`` for the same rows with
styling escape sequences. Both join the rows with newlines and add
none after the last row, so ``print`` shows exactly the buffer.
Examples:
```python
buffer = Buffer.with_text('hi', style=Style(foreground='red'))
assert buffer.render(format='text') == 'hi'
assert '\\x1b[' in buffer.render(format='ansi')
assert not buffer.render(format='ansi').endswith('\\n')
```
"""
CancelEffect
¶
CancelEffect(key: str)
Bases: Operation
Stop the running effect that was started with key.
Parameters:
-
key(str) –The
keythe effect was created with.
Examples:
runtime = Runtime.offscreen(width=10, height=1)
buffer = Buffer(width=10, height=1)
buffer.update(Write('hello'))
runtime.mount(buffer, geometry='inherit')
runtime.step()
buffer.update(Dissolve(duration_milliseconds=100, key='fade-out'))
buffer.update(CancelEffect('fade-out'))
runtime.step()
runtime.advance_clock(100)
runtime.step()
assert runtime.snapshot().lines()[0] == 'hello'
Create a CancelEffect.
Parameters:
-
key(str) –str.
Methods:
-
evaluate–Compute the expression's value.
-
then–An operation that applies this operation, then
other. -
when–An operation that applies only while
conditionis true. -
__or__–Combine this operation with
otherso both run in sequence.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
evaluate
¶
evaluate(context: EvaluationContext) -> ValueType_co
Compute the expression's value.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def evaluate(self, context: EvaluationContext) -> ValueType_co:
"""
Compute the expression's value.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
context = EvaluationContext(buffer=Buffer(width=5, height=1))
assert (width * 2).evaluate(context) == 10
```
"""
then
¶
when
¶
An operation that applies only while condition is true.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
buffer = Buffer(width=6, height=1)
buffer.update(Write('wide').when(width > 4))
assert buffer.text.startswith('wide')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def when(self, condition: Predicate) -> Operation:
"""
An operation that applies only while ``condition`` is true.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
buffer = Buffer(width=6, height=1)
buffer.update(Write('wide').when(width > 4))
assert buffer.text.startswith('wide')
```
"""
__or__
¶
Canvas
¶
Canvas(x_bounds: Sequence[float | Value[float]] | None = None, y_bounds: Sequence[float | Value[float]] | None = None, *, marker: str | Value[str] | None = None, background_color: ColorValue | None = None, shapes: Iterable[CanvasLine | CanvasRectangle | CanvasCircle | CanvasPoints | CanvasMap | CanvasLabel | CanvasLayer | CanvasMarker] | None = None, block: Block | None = None, width: int | None = None, height: int | None = None, x: int = 0, y: int = 0)
Bases: Widget
A coordinate plane that shapes, points and labels are drawn on.
Maps to ratatui::widgets::canvas::Canvas.
Parameters:
-
x_bounds(Sequence[float | Value[float]] | None, default:None) –The lower and upper horizontal coordinates visible on the canvas.
-
y_bounds(Sequence[float | Value[float]] | None, default:None) –The lower and upper vertical coordinates visible on the canvas.
-
marker(str | Value[str] | None, default:None) –How points are drawn; see
CanvasMarker. Defaults to'braille'. -
background_color(ColorValue | None, default:None) –Color behind the shapes, or
None. -
shapes(Iterable[CanvasLine | CanvasRectangle | CanvasCircle | CanvasPoints | CanvasMap | CanvasLabel | CanvasLayer | CanvasMarker] | None, default:None) –Shapes drawn in order.
-
block(Block | None, default:None) –A
Blockframing the canvas. -
width(int | None, default:None) –Width in cells. Defaults to 20.
-
height(int | None, default:None) –Height in cells. Defaults to 10.
-
x(int, default:0) –Column in the parent.
-
y(int, default:0) –Row in the parent.
Raises:
-
ValueError–A bound pair does not have two numbers, or the marker is unknown.
-
TypeError–A shape is not one of the Canvas shape classes.
Attributes:
-
x_bounds(tuple[float | Value[float], float | Value[float]]) –The lower and upper horizontal coordinates visible on the canvas.
-
y_bounds(tuple[float | Value[float], float | Value[float]]) –The lower and upper vertical coordinates visible on the canvas.
-
marker(str | Value[str]) –The default cell marker used to draw shapes.
-
background_color(Color | Value[Color] | None) –The color filling the canvas behind its shapes.
-
shapes(list[CanvasShape]) –The shapes and labels drawn in sequence order.
-
block(Block | None) –The optional border, titles and padding around the content.
Examples:
canvas = Canvas((0, 10), (0, 10), marker='block', width=10, height=5)
canvas.add_shape(CanvasRectangle(0, 0, 10, 10, 'red'))
assert '█' in canvas.render(format='text')
canvas.clear_shapes()
assert '█' not in canvas.render(format='text')
Create a Canvas.
Parameters:
-
x_bounds(Sequence[float | Value[float]] | None, default:None) –Sequence[float | Value[float]] | None. Defaults toNone. -
y_bounds(Sequence[float | Value[float]] | None, default:None) –Sequence[float | Value[float]] | None. Defaults toNone. -
marker(str | Value[str] | None, default:None) –str | Value[str] | None. Defaults toNone. -
background_color(ColorValue | None, default:None) –ColorValue | None. Defaults toNone. -
shapes(Iterable[CanvasLine | CanvasRectangle | CanvasCircle | CanvasPoints | CanvasMap | CanvasLabel | CanvasLayer | CanvasMarker] | None, default:None) –Iterable[CanvasLine | CanvasRectangle | CanvasCircle | CanvasPoints | CanvasMap | CanvasLabel | CanvasLayer | CanvasMarker] | None. Defaults toNone. -
block(Block | None, default:None) –Block | 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.
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.
-
supports–Return whether the buffer's registry can apply an operation type.
-
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.
-
__call__–Return a lazy render of the buffer.
-
render–Compose the visible children and serialize the buffer.
-
add_shape–Draw
shapeafter the shapes already on the canvas. -
extend_shapes–Draw every shape of
shapesafter the shapes already on the canvas. -
clear_shapes–Remove every shape.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
self,
x_bounds: Sequence[float | Value[float]] | None = None,
y_bounds: Sequence[float | Value[float]] | None = None,
*,
marker: str | Value[str] | None = None,
background_color: ColorValue | None = None,
shapes: Iterable[
CanvasLine
| CanvasRectangle
| CanvasCircle
| CanvasPoints
| CanvasMap
| CanvasLabel
| CanvasLayer
| CanvasMarker
]
| None = None,
block: Block | None = None,
width: int | None = None,
height: int | None = None,
x: int = 0,
y: int = 0,
) -> None:
"""
Create a Canvas.
Args:
x_bounds: ``Sequence[float | Value[float]] | None``. Defaults to ``None``.
y_bounds: ``Sequence[float | Value[float]] | None``. Defaults to ``None``.
marker: ``str | Value[str] | None``. Defaults to ``None``.
background_color: ``ColorValue | None``. Defaults to ``None``.
shapes: ``Iterable[CanvasLine | CanvasRectangle | CanvasCircle | CanvasPoints |
CanvasMap | CanvasLabel | CanvasLayer | CanvasMarker] | None``. Defaults to
``None``.
block: ``Block | None``. Defaults to ``None``.
width: ``int | None``. Defaults to ``None``.
height: ``int | None``. Defaults to ``None``.
x: ``int``. Defaults to ``0``.
y: ``int``. Defaults to ``0``.
"""
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.
should_fit_width
property
writable
¶
should_fit_width: bool
Whether the width follows the children: as wide as the farthest right edge.
Only visible children attached with explicit geometry count, and a child whose
parent_measured_axes include 'width' (or whose x is placed by this
buffer's size) is placed within the width the others give. The width is fitted
before every frame, and at once by
Runtime.fit_to_content. A buffer
that fits its children and is mounted on a runtime with geometry='inherit'
decides that runtime's width.
Examples:
should_fit_height
property
writable
¶
should_fit_height: bool
Whether the height follows the children: as tall as the lowest bottom edge.
The rules of should_fit_width apply along the other axis.
fit_padding
property
writable
¶
The columns after the farthest right edge and the rows below the lowest bottom edge that a buffer which fits its children adds, for a border or padding on those sides.
parent_measured_axes
property
writable
¶
The parts of the buffer's place that its parent's size decides.
Set it to the axes that are a percentage, a word such as 'center' or a formula of
the parent's size. A parent that fits its children places such a buffer within the
size the other children give it: one placed by the parent's size counts with its own
size, and one sized by it does not count along that axis.
Raises:
-
ValueError–A name is not
'x','y','width'or'height'.
Examples:
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.
x_bounds
instance-attribute
¶
The lower and upper horizontal coordinates visible on the canvas.
y_bounds
instance-attribute
¶
The lower and upper vertical coordinates visible on the canvas.
background_color
instance-attribute
¶
The color filling the canvas behind its shapes.
shapes
instance-attribute
¶
shapes: list[CanvasShape]
The shapes and labels drawn in sequence order.
block
instance-attribute
¶
block: Block | None
The optional border, titles and padding around the content.
__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
def write(
self,
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.
Args:
text: A string or styled text.
x: The starting column.
y: The starting row.
style: A style applied to the written cells.
mode: ``'replace'`` overwrites the cell; ``'preserve_background'`` keeps
the background already there.
Examples:
```python
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'
```
"""
fill
¶
Set every cell of the surface.
Examples:
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
def set_background_colors(
self,
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).
Args:
colors: A flat, row-major sequence of colors (names, ``(r, g, b)`` tuples or
[`Color`][xnano_core._xnano_core.Color] values). ``None`` leaves a cell alone.
width: The number of colors in one row of ``colors``.
x: The column of the block's top-left cell in this surface.
y: The row of the block's top-left cell in this surface.
Raises:
ValueError: ``width`` is below 1, ``len(colors)`` is not a multiple of ``width``, or
the block does not fit inside the surface, or an entry is not a color.
TypeError: ``colors`` is a single string instead of a sequence of colors, or an
entry has no color meaning.
Examples:
```python
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'
```
"""
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
def set_foreground_colors(
self,
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).
Args:
colors: A flat, row-major sequence of colors (names, ``(r, g, b)`` tuples or
[`Color`][xnano_core._xnano_core.Color] values). ``None`` leaves a cell alone.
width: The number of colors in one row of ``colors``.
x: The column of the block's top-left cell in this surface.
y: The row of the block's top-left cell in this surface.
Raises:
ValueError: ``width`` is below 1, ``len(colors)`` is not a multiple of ``width``, or
the block does not fit inside the surface, or an entry is not a color.
TypeError: ``colors`` is a single string instead of a sequence of colors, or an
entry has no color meaning.
Examples:
```python
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'
```
"""
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
def pixels(self, *, encoding: PixelEncoding = 'half_blocks') -> PixelView:
"""
Return a pixel view that draws into this surface.
Args:
encoding: ``'half_blocks'`` for one column and two rows per cell or
``'braille'`` for two columns and four rows per cell.
Examples:
```python
buffer = Buffer(width=3, height=2)
assert (buffer.pixels().width, buffer.pixels().height) == (3, 4)
assert (buffer.pixels(encoding='braille').width) == 6
```
"""
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
def update(self, *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:
```python
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'
```
"""
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
def inspect(self, expression: Expression[ValueType]) -> ValueType:
"""
Evaluate an expression against this surface and return its value.
Examples:
```python
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
```
"""
supports
¶
Return whether the buffer's registry can apply an operation type.
Examples:
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
def add_hook(
self,
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.
Args:
callback: Called with a context for the event.
condition: An expression that must be true for the callback to run.
events: The event kinds to listen to.
priority: Hooks with higher priority run first.
once: Whether to remove the hook after its first run.
Returns:
The registered hook, which can be cancelled.
Examples:
```python
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']
```
"""
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
__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:
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
@classmethod
def from_cell_animation(cls, packed: bytes, *, start_milliseconds: int = 0) -> Buffer:
"""
Create a buffer showing one frame of a packed cell animation.
Args:
packed: The cell animation bytes.
start_milliseconds: The point in the animation to show.
Raises:
CellGridError: The bytes are not a valid cell animation.
Examples:
```python
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'
```
"""
region
¶
resize
¶
Change the size, keeping the cells that still fit.
Examples:
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
def paste(
self,
source: Buffer | Region,
*,
x: int = 0,
y: int = 0,
mode: PasteMode = 'replace',
) -> None:
"""
Copy the cells of another buffer or region into this one.
Args:
source: The cells to copy.
x: The destination column of the source's left edge.
y: The destination row of the source's top edge.
mode: ``'replace'`` copies every cell, ``'preserve_background'`` keeps
the destination background and ``'transparent'`` skips cells that
are marked transparent.
Examples:
```python
sprite = Buffer.with_text('ab')
canvas = Buffer(width=5, height=1)
canvas.paste(sprite, x=2)
assert canvas.text == ' ab'
```
"""
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
def attach(
self,
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:
```python
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'
```
"""
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
__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
def __call__(self, *, runtime: Runtime | None = None) -> Rendering:
"""
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:
```python
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
```
"""
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 the same rows with styling escape sequences. Both join the rows with newlines and add none after the last row, soprintshows exactly the buffer.
Examples:
buffer = Buffer.with_text('hi', style=Style(foreground='red'))
assert buffer.render(format='text') == 'hi'
assert '\x1b[' in buffer.render(format='ansi')
assert not buffer.render(format='ansi').endswith('\n')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def render(self, *, format: RenderFormat = 'ansi') -> str:
"""
Compose the visible children and serialize the buffer.
No terminal or device is opened.
Args:
format: ``'text'`` for plain rows or ``'ansi'`` for the same rows with
styling escape sequences. Both join the rows with newlines and add
none after the last row, so ``print`` shows exactly the buffer.
Examples:
```python
buffer = Buffer.with_text('hi', style=Style(foreground='red'))
assert buffer.render(format='text') == 'hi'
assert '\\x1b[' in buffer.render(format='ansi')
assert not buffer.render(format='ansi').endswith('\\n')
```
"""
add_shape
¶
add_shape(shape: CanvasShape) -> None
extend_shapes
¶
extend_shapes(shapes: Iterable[CanvasShape]) -> None
Draw every shape of shapes after the shapes already on the canvas.
Examples:
canvas = Canvas((0, 10), (0, 10), width=10, height=5)
canvas.extend_shapes([CanvasCircle(5, 5, 2), CanvasLabel(0, 0, 'x')])
assert len(canvas.shapes) == 2
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def extend_shapes(self, shapes: Iterable[CanvasShape]) -> None:
"""
Draw every shape of ``shapes`` after the shapes already on the canvas.
Examples:
```python
canvas = Canvas((0, 10), (0, 10), width=10, height=5)
canvas.extend_shapes([CanvasCircle(5, 5, 2), CanvasLabel(0, 0, 'x')])
assert len(canvas.shapes) == 2
```
"""
clear_shapes
¶
CanvasCircle
¶
CanvasCircle(x: float | Value[float], y: float | Value[float], radius: float | Value[float], color: ColorValue | None = None)
A circle outline.
Parameters:
-
x(float | Value[float]) –Horizontal position of the center.
-
y(float | Value[float]) –Vertical position of the center.
-
radius(float | Value[float]) –Radius in canvas units.
-
color(ColorValue | None, default:None) –A color name,
Coloror expression.
Attributes:
-
x(float | Value[float]) –The horizontal coordinate of the center.
-
y(float | Value[float]) –The vertical coordinate of the center.
-
radius(float | Value[float]) –The radius in canvas coordinates.
-
color(Color | Value[Color]) –The color of the circle outline.
Examples:
circle = CanvasCircle(5, 5, 3, 'blue')
canvas = Canvas((0, 10), (0, 10), marker='block', shapes=[circle], width=20, height=10)
assert '█' in canvas.render(format='text')
circle.radius = 1
Create a CanvasCircle.
Parameters:
-
x(float | Value[float]) –float | Value[float]. -
y(float | Value[float]) –float | Value[float]. -
radius(float | Value[float]) –float | Value[float]. -
color(ColorValue | None, default:None) –ColorValue | None. Defaults toNone.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
self,
x: float | Value[float],
y: float | Value[float],
radius: float | Value[float],
color: ColorValue | None = None,
) -> None:
"""
Create a CanvasCircle.
Args:
x: ``float | Value[float]``.
y: ``float | Value[float]``.
radius: ``float | Value[float]``.
color: ``ColorValue | None``. Defaults to ``None``.
"""
CanvasLabel
¶
CanvasLabel(x: float | Value[float], y: float | Value[float], text: str | Value[str], style: Style | DynamicStyle | None = None)
Text printed at a position, always on top of the shapes.
Parameters:
-
x(float | Value[float]) –Horizontal position of the text start.
-
y(float | Value[float]) –Vertical position of the text.
-
text(str | Value[str]) –The text, or an expression producing it.
-
style(Style | DynamicStyle | None, default:None) –A
StyleorDynamicStyle.
Attributes:
-
x(float | Value[float]) –The horizontal coordinate where the label starts.
-
y(float | Value[float]) –The vertical coordinate where the label starts.
-
text(str | Value[str]) –The styled text displayed at the given canvas position.
-
style(Style | DynamicStyle) –The default colors and text modifiers applied to the cells.
Examples:
label = CanvasLabel(1, 5, 'hello')
canvas = Canvas((0, 10), (0, 10), shapes=[label], width=10, height=5)
assert 'hello' in canvas.render(format='text')
label.text = 'bye'
assert 'bye' in canvas.render(format='text')
Create a CanvasLabel.
Parameters:
-
x(float | Value[float]) –float | Value[float]. -
y(float | Value[float]) –float | Value[float]. -
text(str | Value[str]) –str | Value[str]. -
style(Style | DynamicStyle | None, default:None) –Style | DynamicStyle | None. Defaults toNone.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
self,
x: float | Value[float],
y: float | Value[float],
text: str | Value[str],
style: Style | DynamicStyle | None = None,
) -> None:
"""
Create a CanvasLabel.
Args:
x: ``float | Value[float]``.
y: ``float | Value[float]``.
text: ``str | Value[str]``.
style: ``Style | DynamicStyle | None``. Defaults to ``None``.
"""
text
instance-attribute
¶
The styled text displayed at the given canvas position.
style
instance-attribute
¶
style: Style | DynamicStyle
The default colors and text modifiers applied to the cells.
CanvasLayer
¶
Saves what was drawn so far as a layer; the shapes after it draw on top.
Examples:
canvas = Canvas((0, 10), (0, 10), shapes=[CanvasPoints([(1, 1)]), CanvasLayer(), CanvasPoints([(9, 9)])])
assert CanvasLayer() == CanvasLayer()
Create a CanvasLayer.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
CanvasLine
¶
CanvasLine(x1: float | Value[float], y1: float | Value[float], x2: float | Value[float], y2: float | Value[float], color: ColorValue | None = None, *, fill_to_y: float | Value[float] | None = None)
A straight line between two points, optionally filled down to a baseline.
Every coordinate and the color accept a plain value or an expression, so a line can follow state. A shape can be edited after it is created; widgets that draw it repaint immediately.
Parameters:
-
x1(float | Value[float]) –Horizontal position of the start.
-
y1(float | Value[float]) –Vertical position of the start.
-
x2(float | Value[float]) –Horizontal position of the end.
-
y2(float | Value[float]) –Vertical position of the end.
-
color(ColorValue | None, default:None) –A color name,
Coloror expression. Defaults to the terminal default. -
fill_to_y(float | Value[float] | None, default:None) –When set, the area between the line and this vertical position is filled.
Attributes:
-
x1(float | Value[float]) –The horizontal coordinate of the starting point.
-
y1(float | Value[float]) –The vertical coordinate of the starting point.
-
x2(float | Value[float]) –The horizontal coordinate of the ending point.
-
y2(float | Value[float]) –The vertical coordinate of the ending point.
-
color(Color | Value[Color]) –The color of the line.
-
fill_to_y(float | Value[float] | None) –The vertical coordinate to fill toward, or
Noneto draw only the line.
Examples:
line = CanvasLine(0, 0, 10, 10, 'green')
canvas = Canvas((0, 10), (0, 10), marker='block', shapes=[line], width=10, height=5)
assert '█' in canvas.render(format='text')
line.x2 = 0
assert line.x2 == 0.0
Create a CanvasLine.
Parameters:
-
x1(float | Value[float]) –float | Value[float]. -
y1(float | Value[float]) –float | Value[float]. -
x2(float | Value[float]) –float | Value[float]. -
y2(float | Value[float]) –float | Value[float]. -
color(ColorValue | None, default:None) –ColorValue | None. Defaults toNone. -
fill_to_y(float | Value[float] | None, default:None) –float | Value[float] | None. Defaults toNone.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
self,
x1: float | Value[float],
y1: float | Value[float],
x2: float | Value[float],
y2: float | Value[float],
color: ColorValue | None = None,
*,
fill_to_y: float | Value[float] | None = None,
) -> None:
"""
Create a CanvasLine.
Args:
x1: ``float | Value[float]``.
y1: ``float | Value[float]``.
x2: ``float | Value[float]``.
y2: ``float | Value[float]``.
color: ``ColorValue | None``. Defaults to ``None``.
fill_to_y: ``float | Value[float] | None``. Defaults to ``None``.
"""
CanvasMap
¶
CanvasMap(resolution: Literal['low', 'high'] | str | Value[str] | None = None, color: ColorValue | None = None)
The world map, in longitude and latitude (use bounds (-180, 180) and (-90, 90)).
Parameters:
-
resolution(Literal['low', 'high'] | str | Value[str] | None, default:None) –The detail level of the world map:
loworhigh. -
color(ColorValue | None, default:None) –A color name,
Coloror expression.
Raises:
-
ValueError–The resolution is not
'low'or'high'.
Attributes:
-
resolution(str | Value[str]) –The detail level of the world map:
loworhigh. -
color(Color | Value[Color]) –The color of the map outline.
Examples:
world = CanvasMap('low', 'white')
canvas = Canvas((-180, 180), (-90, 90), shapes=[world], width=40, height=12)
assert canvas.render(format='text').strip()
Create a CanvasMap.
Parameters:
-
resolution(Literal['low', 'high'] | str | Value[str] | None, default:None) –Literal['low', 'high'] | str | Value[str] | None. Defaults toNone. -
color(ColorValue | None, default:None) –ColorValue | None. Defaults toNone.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
self,
resolution: Literal['low', 'high'] | str | Value[str] | None = None,
color: ColorValue | None = None,
) -> None:
"""
Create a CanvasMap.
Args:
resolution: ``Literal['low', 'high'] | str | Value[str] | None``. Defaults to
``None``.
color: ``ColorValue | None``. Defaults to ``None``.
"""
CanvasMarker
¶
Switches the marker the shapes after it are drawn with.
Parameters:
-
marker(str | Value[str]) –A marker name (
'dot','block','bar','braille','half_block','quadrant','sextant','octant') or any single character.
Raises:
-
ValueError–The marker is not a known name or a single character.
Attributes:
Examples:
canvas = Canvas((0, 10), (0, 10), shapes=[CanvasMarker('block'), CanvasRectangle(0, 0, 10, 10)], width=10, height=5)
assert '█' in canvas.render(format='text')
Create a CanvasMarker.
Parameters:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
CanvasPoints
¶
CanvasPoints(coordinates: Iterable[tuple[float, float]], color: ColorValue | None = None)
A set of single points.
Parameters:
-
coordinates(Iterable[tuple[float, float]]) –The horizontal and vertical coordinate pairs to draw.
-
color(ColorValue | None, default:None) –A color name,
Coloror expression.
Raises:
-
ValueError–A coordinate is not finite.
Attributes:
-
coordinates(list[tuple[float, float]]) –The horizontal and vertical coordinate pairs to draw.
-
color(Color | Value[Color]) –The color of the points.
Examples:
points = CanvasPoints([(1, 1), (5, 5)], 'yellow')
canvas = Canvas((0, 10), (0, 10), marker='block', shapes=[points], width=10, height=5)
points.coordinates = [(1, 1), (9, 9)]
assert len(points) == 2 and '█' in canvas.render(format='text')
Create a CanvasPoints.
Parameters:
-
coordinates(Iterable[tuple[float, float]]) –Iterable[tuple[float, float]]. -
color(ColorValue | None, default:None) –ColorValue | None. Defaults toNone.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
CanvasRectangle
¶
CanvasRectangle(x: float | Value[float], y: float | Value[float], width: float | Value[float], height: float | Value[float], color: ColorValue | None = None)
An axis-aligned rectangle outline.
Parameters:
-
x(float | Value[float]) –Horizontal position of the lower-left corner.
-
y(float | Value[float]) –Vertical position of the lower-left corner.
-
width(float | Value[float]) –Width in canvas units.
-
height(float | Value[float]) –Height in canvas units.
-
color(ColorValue | None, default:None) –A color name,
Coloror expression.
Attributes:
-
x(float | Value[float]) –The horizontal coordinate of the left edge.
-
y(float | Value[float]) –The vertical coordinate of the bottom edge.
-
width(float | Value[float]) –The width in canvas coordinates.
-
height(float | Value[float]) –The height in canvas coordinates.
-
color(Color | Value[Color]) –The color of the rectangle outline.
Examples:
shape = CanvasRectangle(0, 0, 10, 10, 'red')
canvas = Canvas((0, 10), (0, 10), marker='block', shapes=[shape], width=10, height=5)
assert '█' in canvas.render(format='text')
Create a CanvasRectangle.
Parameters:
-
x(float | Value[float]) –float | Value[float]. -
y(float | Value[float]) –float | Value[float]. -
width(float | Value[float]) –float | Value[float]. -
height(float | Value[float]) –float | Value[float]. -
color(ColorValue | None, default:None) –ColorValue | None. Defaults toNone.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
self,
x: float | Value[float],
y: float | Value[float],
width: float | Value[float],
height: float | Value[float],
color: ColorValue | None = None,
) -> None:
"""
Create a CanvasRectangle.
Args:
x: ``float | Value[float]``.
y: ``float | Value[float]``.
width: ``float | Value[float]``.
height: ``float | Value[float]``.
color: ``ColorValue | None``. Defaults to ``None``.
"""
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
def __init__(
self,
symbol: str = ' ',
*,
style: Style | None = None,
foreground: ColorValue | None = None,
background: ColorValue | None = None,
modifiers: Sequence[Modifier] = (),
is_transparent: bool = False,
) -> None:
"""
Create a Cell.
Args:
symbol: ``str``. Defaults to ``' '``.
style: ``Style | None``. Defaults to ``None``.
foreground: ``ColorValue | None``. Defaults to ``None``.
background: ``ColorValue | None``. Defaults to ``None``.
modifiers: ``Sequence[Modifier]``. Defaults to ``()``.
is_transparent: ``bool``. Defaults to ``False``.
"""
CellAnimationInfo
¶
The header of a packed cell animation.
Attributes:
-
format_version(int) –The version of the cell animation byte format.
-
columns(int) –The width of every frame in cells.
-
rows(int) –The height of every frame in cells.
-
frame_count(int) –The number of frames.
-
duration_milliseconds(int) –The total duration of one pass in milliseconds.
-
should_loop(bool) –Whether the animation repeats.
Examples:
frames = [Buffer.with_text('a').to_cell_grid(), Buffer.with_text('b').to_cell_grid()]
packed = pack_cell_animation(frames, frame_durations_milliseconds=[40, 60])
info = inspect_cell_animation(packed)
assert info.frame_count == 2
assert info.duration_milliseconds == 100
assert info.should_loop
CellFilter
¶
CellGridError
¶
Bases: ValueError
Packed cell data is malformed, incompatible or over a resource limit.
Examples:
try:
inspect_cell_grid(b'not a cell grid')
except CellGridError as error:
assert 'cell grid' in str(error)
-
API Reference
xnano_core
-
xnano_core -
xnano_core._xnano_core
_xnano_core
-
CellGridInfo
¶
The header of a packed cell grid.
Attributes:
-
format_version(int) –The version of the cell grid byte format.
-
columns(int) –The width in cells.
-
rows(int) –The height in cells.
-
has_graphics_protocol_cells(bool) –Whether the grid carries cells for a terminal graphics protocol.
-
required_protocol(GraphicsProtocol | None) –The graphics protocol the grid needs, or
Nonefor plain cells.
Examples:
info = inspect_cell_grid(Buffer.with_text('abc').to_cell_grid())
assert (info.columns, info.rows) == (3, 1)
assert info.required_protocol is None
has_graphics_protocol_cells
property
¶
has_graphics_protocol_cells: bool
Whether the grid carries cells for a terminal graphics protocol.
required_protocol
property
¶
required_protocol: GraphicsProtocol | None
The graphics protocol the grid needs, or None for plain cells.
Chart
¶
Chart(datasets: Sequence[ChartDataset] | None = None, *, x_axis: ChartAxis | None = None, y_axis: ChartAxis | None = None, style: Style | DynamicStyle | None = None, legend_position: str | Expression[str] | None = None, block: Block | None = None, width: int | Expression[int | float] | None = None, height: int | Expression[int | float] | None = None, x: int | Expression[int | float] = 0, y: int | Expression[int | float] = 0)
Bases: Widget
Point series drawn against shared editable axes.
Attributes:
-
datasets(Sequence[ChartDataset]) –The datasets plotted against the chart axes.
-
style(Style | DynamicStyle) –The default colors and text modifiers applied to the cells.
-
y_axis(ChartAxis) –The vertical axis and its bounds, labels and title.
-
block(Block | None) –The optional border, titles and padding around the content.
-
legend_position(str | Expression[str] | None) –The named position of the legend, or
Noneto omit it. -
x_axis(ChartAxis) –The horizontal axis and its bounds, labels and title.
Examples:
chart = Chart([ChartDataset(data=[(0, 0), (1, 1)])], width=20, height=8)
assert chart.render(format='text')
Create a Chart.
Parameters:
-
datasets(Sequence[ChartDataset] | None, default:None) –Sequence[ChartDataset] | None. Defaults toNone. -
x_axis(ChartAxis | None, default:None) –ChartAxis | None. Defaults toNone. -
y_axis(ChartAxis | None, default:None) –ChartAxis | None. Defaults toNone. -
style(Style | DynamicStyle | None, default:None) –Style | DynamicStyle | None. Defaults toNone. -
legend_position(str | Expression[str] | None, default:None) –str | Expression[str] | None. Defaults toNone. -
block(Block | None, default:None) –Block | None. Defaults toNone. -
width(int | Expression[int | float] | None, default:None) –int | Expression[int | float] | None. Defaults toNone. -
height(int | Expression[int | float] | None, default:None) –int | Expression[int | float] | None. Defaults toNone. -
x(int | Expression[int | float], default:0) –int | Expression[int | float]. Defaults to0. -
y(int | Expression[int | float], default:0) –int | Expression[int | float]. Defaults to0.
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.
-
supports–Return whether the buffer's registry can apply an operation type.
-
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.
-
__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
def __init__(
self,
/,
datasets: Sequence[ChartDataset] | None = None,
*,
x_axis: ChartAxis | None = None,
y_axis: ChartAxis | None = None,
style: Style | DynamicStyle | None = None,
legend_position: str | Expression[str] | None = None,
block: Block | None = None,
width: int | Expression[int | float] | None = None,
height: int | Expression[int | float] | None = None,
x: int | Expression[int | float] = 0,
y: int | Expression[int | float] = 0,
) -> None:
"""
Create a Chart.
Args:
datasets: ``Sequence[ChartDataset] | None``. Defaults to ``None``.
x_axis: ``ChartAxis | None``. Defaults to ``None``.
y_axis: ``ChartAxis | None``. Defaults to ``None``.
style: ``Style | DynamicStyle | None``. Defaults to ``None``.
legend_position: ``str | Expression[str] | None``. Defaults to ``None``.
block: ``Block | None``. Defaults to ``None``.
width: ``int | Expression[int | float] | None``. Defaults to ``None``.
height: ``int | Expression[int | float] | None``. Defaults to ``None``.
x: ``int | Expression[int | float]``. Defaults to ``0``.
y: ``int | Expression[int | float]``. Defaults to ``0``.
"""
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.
should_fit_width
property
writable
¶
should_fit_width: bool
Whether the width follows the children: as wide as the farthest right edge.
Only visible children attached with explicit geometry count, and a child whose
parent_measured_axes include 'width' (or whose x is placed by this
buffer's size) is placed within the width the others give. The width is fitted
before every frame, and at once by
Runtime.fit_to_content. A buffer
that fits its children and is mounted on a runtime with geometry='inherit'
decides that runtime's width.
Examples:
should_fit_height
property
writable
¶
should_fit_height: bool
Whether the height follows the children: as tall as the lowest bottom edge.
The rules of should_fit_width apply along the other axis.
fit_padding
property
writable
¶
The columns after the farthest right edge and the rows below the lowest bottom edge that a buffer which fits its children adds, for a border or padding on those sides.
parent_measured_axes
property
writable
¶
The parts of the buffer's place that its parent's size decides.
Set it to the axes that are a percentage, a word such as 'center' or a formula of
the parent's size. A parent that fits its children places such a buffer within the
size the other children give it: one placed by the parent's size counts with its own
size, and one sized by it does not count along that axis.
Raises:
-
ValueError–A name is not
'x','y','width'or'height'.
Examples:
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.
datasets
property
writable
¶
datasets: Sequence[ChartDataset]
The datasets plotted against the chart axes.
style
property
writable
¶
style: Style | DynamicStyle
The default colors and text modifiers applied to the cells.
block
property
writable
¶
block: Block | None
The optional border, titles and padding around the content.
legend_position
property
writable
¶
legend_position: str | Expression[str] | None
The named position of the legend, or None to omit it.
__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
def write(
self,
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.
Args:
text: A string or styled text.
x: The starting column.
y: The starting row.
style: A style applied to the written cells.
mode: ``'replace'`` overwrites the cell; ``'preserve_background'`` keeps
the background already there.
Examples:
```python
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'
```
"""
fill
¶
Set every cell of the surface.
Examples:
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
def set_background_colors(
self,
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).
Args:
colors: A flat, row-major sequence of colors (names, ``(r, g, b)`` tuples or
[`Color`][xnano_core._xnano_core.Color] values). ``None`` leaves a cell alone.
width: The number of colors in one row of ``colors``.
x: The column of the block's top-left cell in this surface.
y: The row of the block's top-left cell in this surface.
Raises:
ValueError: ``width`` is below 1, ``len(colors)`` is not a multiple of ``width``, or
the block does not fit inside the surface, or an entry is not a color.
TypeError: ``colors`` is a single string instead of a sequence of colors, or an
entry has no color meaning.
Examples:
```python
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'
```
"""
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
def set_foreground_colors(
self,
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).
Args:
colors: A flat, row-major sequence of colors (names, ``(r, g, b)`` tuples or
[`Color`][xnano_core._xnano_core.Color] values). ``None`` leaves a cell alone.
width: The number of colors in one row of ``colors``.
x: The column of the block's top-left cell in this surface.
y: The row of the block's top-left cell in this surface.
Raises:
ValueError: ``width`` is below 1, ``len(colors)`` is not a multiple of ``width``, or
the block does not fit inside the surface, or an entry is not a color.
TypeError: ``colors`` is a single string instead of a sequence of colors, or an
entry has no color meaning.
Examples:
```python
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'
```
"""
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
def pixels(self, *, encoding: PixelEncoding = 'half_blocks') -> PixelView:
"""
Return a pixel view that draws into this surface.
Args:
encoding: ``'half_blocks'`` for one column and two rows per cell or
``'braille'`` for two columns and four rows per cell.
Examples:
```python
buffer = Buffer(width=3, height=2)
assert (buffer.pixels().width, buffer.pixels().height) == (3, 4)
assert (buffer.pixels(encoding='braille').width) == 6
```
"""
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
def update(self, *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:
```python
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'
```
"""
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
def inspect(self, expression: Expression[ValueType]) -> ValueType:
"""
Evaluate an expression against this surface and return its value.
Examples:
```python
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
```
"""
supports
¶
Return whether the buffer's registry can apply an operation type.
Examples: