xnano_core._xnano_core
xnano_core._xnano_core
¶
xnano_core._xnano_core
Type stubs for the compiled module behind the xnano_core package.
Every class and function here is implemented in Rust. The compiled module is the package
initializer, so xnano_core._xnano_core._core_types sits next to it.
Classes:
-
Point–A cell position, counted in columns (
x) and rows (y) from the top-left. -
Size–A width and a height, counted in cells.
-
Rectangle–A rectangle of cells with half-open bounds.
-
Color–A terminal color: a named palette color, a palette index or a true color.
-
Style–A foreground color, a background color and text modifiers.
-
Clock–The time source a runtime reads, either real or stepped by hand.
-
SimulationClock–A clock derived from a parent clock, with its own rate and stopped state.
-
TextSpan–A run of text with one style.
-
StyledText–Text made of differently styled spans.
-
TextLine–One wrapped line of a
TextLayout. -
TextLayout–Text wrapped to a width, with conversions between cells and string offsets.
-
TextEditor–An editable text buffer with a cursor and undo history.
-
Editor–Draw a
TextEditorinto a buffer. -
KeyEvent–A key press, repeat or release.
-
MouseEvent–A mouse press, release, drag, move or scroll.
-
Event–Something that happened: input, a resize, a timer or a frame.
-
KeyBinding–A key and modifiers to match against key events.
-
EventStream–The events a runtime reports, as an iterator.
-
Waker–A handle other threads use to wake a runtime and run code on its thread.
-
Hook–A registered callback that can be paused, reprioritized or cancelled.
-
ScheduledCall–A callback scheduled on a clock with
call_laterorcall_every. -
KeyboardCapabilities–What the terminal's keyboard protocol can report.
-
InputOptions–The input modes a live terminal asks for.
-
TerminalOptions–How a live runtime takes over the terminal.
-
Cursor–The one cursor a terminal has.
-
InputState–The keys and pointer position a runtime currently sees.
-
Device–The display and terminal a runtime draws on.
-
HitArea–A named rectangle that receives mouse hits without needing painted text.
-
FocusScope–A group of input targets, optionally modal.
-
InputRouter–Routes input events to buffers: handlers, hit areas, focus and scopes.
-
TerminalCapabilities–What a terminal can display.
-
Expression–A value or action described now and evaluated later against a buffer or runtime.
-
Predicate–A condition that evaluates to
TrueorFalse. -
Value–An expression that evaluates to a value.
-
NumericValue–A numeric expression that supports comparisons and arithmetic.
-
Operation–An action that changes a buffer, applied with
Buffer.update. -
Property–A reference to a concrete property of a buffer or runtime.
-
NumericProperty–A reference to a numeric property that can be read, computed with and assigned.
-
SetValue–Assign a value to a property.
-
SequenceOperation–Apply several operations in order as one operation.
-
Conditional–Apply one operation when a condition is true and optionally another when it is not.
-
Resize–Resize the target buffer to
widthbyheightcells. -
Move–Move the target buffer relative to its current position in its parent.
-
Place–Move the target buffer to an absolute position in its parent.
-
Write–Write text into the target at a cell position.
-
WriteCellText–Write text addressed by
columnandrowinstead ofxandy. -
Fill–Fill every cell of the target with one cell.
-
Clear–Blank cells that hide whatever is behind them.
-
Foreground–Set the foreground color of every cell of the target.
-
Background–Set the background color of every cell of the target.
-
ApplyStyle–Patch a
Styleonto every cell of the target. -
Border–Draw a border around the edge of the target.
-
Paste–Copy the cells of another buffer or region into the target.
-
Pixels–Draw ordered RGB pixels into the target.
-
Raster–Draw a row-major RGBA8 image into the target as pixels.
-
SetState–Assign a state branch and publish one validated commit.
-
ApplyStatePatch–Apply a JSON patch to a state branch in one validated commit.
-
Effect–A composable animation with editable and bindable settings.
-
Fade–Fade the colors of the target toward a foreground and background color.
-
Dissolve–Dissolve the glyphs of the target away cell by cell.
-
Glitch–Randomly corrupt and displace glyphs of the target.
-
Fuzz–Replace a percentage of the visible glyphs of the target with noise glyphs, once.
-
CancelEffect–Stop the running effect that was started with
key. -
SizeRule–How much space one child takes along a layout's main axis.
-
Layout–Arrange attached children within the parent's content area.
-
ItemList–Selectable styled items with editable selection and scrolling.
-
Gauge–A filled progress bar that repaints when its ratio changes.
-
LineGauge–A progress indicator drawn with line symbols.
-
Sparkline–A compact history of numeric samples.
-
Bar–One labelled value in a bar chart.
-
BarGroup–A labelled group of bars.
-
BarChart–Grouped bars with editable values and styles.
-
TableCell–Styled content displayed in a table cell.
-
TableRow–A row of cells with height and spacing.
-
Table–A retained table with row, column and cell selection.
-
Scrollbar–A scrollbar showing position within content.
-
Tabs–Selectable titles with editable padding, divider and styles.
-
Drawing–An immutable picture made of rows of text or palette pixels.
-
DrawingFrame–One frame of a
DrawingAnimation. -
DrawingAnimation–A sequence of timed drawings.
-
Draw–Draw a
Drawinginto the target. -
AnimateDrawing–Play a
DrawingAnimationon a mounted buffer. -
Cell–A detached grapheme with its style, copied out of or written into a surface.
-
PixelView–A raster view that draws logical pixels into the cells of a surface.
-
Surface–A grid of cells that text, styles, pixels and operations can be applied to.
-
Region–A fixed rectangle of a buffer that shares the buffer's cells.
-
Buffer–A layer of cells with a position, a size and the hooks that animate it.
-
StepResult–What one
Runtime.step()did. -
Runtime–A session that mounts buffers, runs hooks and schedules, and draws frames.
-
FrameMetrics–Timing of the frames a runtime has drawn.
-
FrameSnapshot–An immutable copy of a drawn frame.
-
ErrorDetail–One labelled problem of an
ErrorReport. -
ErrorReport–One or more labelled problems, formatted like a pydantic
ValidationError. -
ReportedError–An error raised with an
ErrorReportas its one argument. -
RenderError–A recoverable failure while drawing a frame; the failed frame is not committed.
-
UnsupportedOperationError–The registry of the target cannot apply the operation it was given.
-
RuntimeRequiredError–An operation needs a buffer mounted on an active runtime.
-
InvalidRegionError–A region no longer fits inside its resized buffer.
-
CellGridError–Packed cell data is malformed, incompatible or over a resource limit.
-
CellGridInfo–The header of a packed cell grid.
-
CellAnimationInfo–The header of a packed cell animation.
-
DecodeLimits–Upper bounds checked before packed cell data is accepted.
-
TerminalStateValidationError–Raised when a value or a change does not satisfy a state schema.
-
TerminalStateConflictError–Raised when a change was prepared against a revision that is no longer current.
-
TerminalStateAccessError–Raised when a change touches a path that an observation did not grant for writing.
-
TerminalStateIssue–One problem found while validating a value against a schema.
-
TerminalStateSchema–A compiled schema that validates state values.
-
TerminalStateSnapshot–An immutable view of a state tree, or of one branch of it, at one revision.
-
TerminalStateSelection–Values read from several paths at one consistent revision.
-
TerminalStatePatch–A list of edits to a state tree, in the JSON Patch format (RFC 6902).
-
TerminalStateChange–The result of one committed change: what changed and the state before and after.
-
TerminalStateSubscription–A registration that delivers state changes until it is cancelled.
-
TerminalStateTransaction–Staged edits that publish together or not at all.
-
TerminalStateStore–Thread-safe state storage with schema validation, revisions and notifications.
-
TerminalStateObservation–A record of what was read from a store, and which paths may be written.
-
Paragraph–Styled text that can wrap, align and scroll.
-
CustomWidget–A widget drawn by a Python function.
-
Live–Operations that are applied again whenever something they show changes.
-
CanvasLine–A straight line between two points, optionally filled down to a baseline.
-
CanvasRectangle–An axis-aligned rectangle outline.
-
CanvasCircle–A circle outline.
-
CanvasPoints–A set of single points.
-
CanvasMap–The world map, in longitude and latitude (use bounds
(-180, 180)and(-90, 90)). -
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.
-
CanvasMarker–Switches the marker the shapes after it are drawn with.
-
Canvas–A coordinate plane that shapes, points and labels are drawn on.
-
Widget–A buffer painted from editable settings or bound expressions.
-
BlockTitle–A styled title positioned on the top or bottom border of a block.
-
Block–Borders, titles and padding shared by retained widgets.
-
DynamicStyle–A style whose colors may follow expressions.
-
ListItem–Styled content displayed by an item list.
-
SparklineBar–A sample with an optional individual style.
-
ChartAxis–An editable axis with bounds, labels and a title.
-
ChartDataset–An editable series of points displayed by a chart.
-
Chart–Point series drawn against shared editable axes.
-
Calendar–A monthly calendar with editable dates and styles for events.
-
StateReference–A branch of a state store that can be read, written or bound.
-
CellFilter–A composable selection of cells affected by an animation.
-
RunningEffect–Playback controls and progress for a started animation.
-
EffectManager–Start, replace, inspect and cancel animations on a runtime.
-
Offset–A displacement in terminal columns and rows.
-
Margin–Horizontal and vertical inset distances.
-
Customization–A named, typed set of parameters that is also an operation.
-
OperationChain–Operations applied one after another when they cannot become one native sequence.
-
Trigger–When something runs, and which events count.
-
ExpressionScope–A named group of expressions, such as the parent's size or the terminal's clock.
-
ParentExpressionScope–The geometry of the enclosing buffer, as expressions.
-
RootExpressionScope–The geometry and clock of the root terminal, as expressions.
-
BufferExpressionScope–A buffer's own position and size, as expressions.
-
KeyboardExpressionScope–The latest key event, as expressions.
-
MouseExpressionScope–The latest mouse button or motion report, as expressions.
-
ScrollExpressionScope–The mouse wheel steps of the current step, as expressions.
Functions:
-
layout_text–Wrap text to a width.
-
display_width–The number of terminal cells a string occupies.
-
query_keyboard_capabilities–Ask the terminal which keyboard protocol features it supports.
-
detect_terminal_capabilities–Inspect the environment and ask the terminal what it can display.
-
inspect_cell_grid–Read the header of a packed cell grid without decoding its cells.
-
inspect_cell_animation–Read the header of a packed cell animation without decoding its frames.
-
validate_cell_grid–Check that packed bytes are a complete, valid cell grid.
-
validate_cell_animation–Check that packed bytes are a complete, valid cell animation.
-
cell_grid_size–Return the
(columns, rows)of a packed cell grid. -
cell_grid_to_text–Return the plain text rows of a packed cell grid.
-
cell_grid_to_ansi–Return a packed cell grid as text with styling escape sequences.
-
pack_cell_animation–Pack cell grids into a cell animation.
-
animation_frame_at–Return the packed cell grid shown at a time in an animation.
Attributes:
-
is_optimized_build(bool) –Whether the extension was built with optimizations and without coverage instrumentation. Timing any other build says nothing.
-
ParentScope(ParentExpressionScope) –The parent's geometry:
ParentScope.width,ParentScope.height,ParentScope.size. -
RootScope(RootExpressionScope) –The terminal's geometry and clock:
RootScope.width,RootScope.time, ... -
BufferScope(BufferExpressionScope) –A buffer's own geometry:
BufferScope.x,BufferScope.width, ... -
KeyboardScope(KeyboardExpressionScope) –The latest key event:
KeyboardScope.key,KeyboardScope.kind,KeyboardScope.binding. -
MouseScope(MouseExpressionScope) –The latest mouse button or motion report:
MouseScope.position,MouseScope.is_down, ... -
ScrollScope(ScrollExpressionScope) –The latest wheel report of the current step:
ScrollScope.xandScrollScope.y. -
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.
-
Width(NumericValue[int | float]) –The width of a buffer or region, in terminal cells.
-
Height(NumericValue[int | float]) –The height of a buffer or region, in terminal cells.
-
TimeElapsed(NumericValue[int | float]) –The elapsed runtime time, in seconds.
-
TimeDelta(NumericValue[int | float]) –The elapsed time since the previous runtime frame, in seconds.
-
TimeElapsedMilliseconds(NumericValue[int | float]) –The elapsed runtime time, in milliseconds.
-
TimeDeltaMilliseconds(NumericValue[int | float]) –The elapsed time since the previous runtime frame, in milliseconds.
-
Frame(NumericValue[int | float]) –The current runtime frame number.
-
FPS(NumericValue[int | float]) –The runtime's estimated frames per second.
-
DeviceWidth(NumericValue[int | float]) –The terminal width, in cells.
-
DeviceHeight(NumericValue[int | float]) –The terminal height, in cells.
-
Position(Value[Point]) –The position of a buffer or region as a
Point. -
Bounds(Value[Rectangle]) –The full bounds of a buffer or region as a
Rectangle. -
BufferSize(Value[Size]) –The dimensions of a buffer as a
Size. -
Focused(Value[bool]) –Whether the runtime has focus.
-
Running(Value[bool]) –Whether the runtime is running.
-
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.
-
ParentHeight(NumericValue[int]) –The height of the parent buffer, in cells.
-
ScreenPosition(Value[Point]) –The top-left cell of a buffer or region on the screen, counting every parent offset.
-
ScreenBounds(Value[Rectangle]) –The rectangle of a buffer or region on the screen, counting every parent offset.
-
PointerPosition(Value[Point | None]) –The cell under the pointer, or
Noneuntil the runtime has seen the pointer. -
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. -
KeyboardBinding(Value[str | None]) –The latest key event with its modifiers, such as
'ctrl+s', orNone. -
MouseButtonValue(Value[MouseButton | None]) –The button of the latest button or motion report, or
None. -
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. -
MouseIsDown(Predicate) –Whether any mouse button is held.
-
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). -
BufferRegion(Value[Rectangle]) –The rectangle of a buffer on the screen, counting every parent offset.
-
Layer(NumericProperty[int]) –The paint order of a buffer among its siblings. Assign it with
Layer(2). -
IsVisible(Property[bool]) –Whether a buffer is drawn. Assign it with
IsVisible(False).
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.
ParentScope
module-attribute
¶
ParentScope: ParentExpressionScope
The parent's geometry: ParentScope.width, ParentScope.height, ParentScope.size.
RootScope
module-attribute
¶
RootScope: RootExpressionScope
The terminal's geometry and clock: RootScope.width, RootScope.time, ...
BufferScope
module-attribute
¶
BufferScope: BufferExpressionScope
A buffer's own geometry: BufferScope.x, BufferScope.width, ...
KeyboardScope
module-attribute
¶
KeyboardScope: KeyboardExpressionScope
The latest key event: KeyboardScope.key, KeyboardScope.kind, KeyboardScope.binding.
MouseScope
module-attribute
¶
MouseScope: MouseExpressionScope
The latest mouse button or motion report: MouseScope.position, MouseScope.is_down, ...
ScrollScope
module-attribute
¶
ScrollScope: ScrollExpressionScope
The latest wheel report of the current step: ScrollScope.x and ScrollScope.y.
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.
Width
module-attribute
¶
Width: NumericValue[int | float]
The width of a buffer or region, in terminal cells.
Height
module-attribute
¶
Height: NumericValue[int | float]
The height of a buffer or region, in terminal cells.
TimeElapsed
module-attribute
¶
TimeElapsed: NumericValue[int | float]
The elapsed runtime time, in seconds.
TimeDelta
module-attribute
¶
TimeDelta: NumericValue[int | float]
The elapsed time since the previous runtime frame, in seconds.
TimeElapsedMilliseconds
module-attribute
¶
TimeElapsedMilliseconds: NumericValue[int | float]
The elapsed runtime time, in milliseconds.
TimeDeltaMilliseconds
module-attribute
¶
TimeDeltaMilliseconds: NumericValue[int | float]
The elapsed time since the previous runtime frame, in milliseconds.
FPS
module-attribute
¶
FPS: NumericValue[int | float]
The runtime's estimated frames per second.
DeviceWidth
module-attribute
¶
DeviceWidth: NumericValue[int | float]
The terminal width, in cells.
DeviceHeight
module-attribute
¶
DeviceHeight: NumericValue[int | float]
The terminal height, in cells.
Position
module-attribute
¶
The position of a buffer or region as a Point.
Bounds
module-attribute
¶
The full bounds of a buffer or region as a Rectangle.
BufferSize
module-attribute
¶
The dimensions of a buffer as a Size.
Focused
module-attribute
¶
Whether the runtime has focus.
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.
ParentHeight
module-attribute
¶
ParentHeight: NumericValue[int]
The height of the parent buffer, in cells.
ScreenPosition
module-attribute
¶
The top-left cell of a buffer or region on the screen, counting every parent offset.
ScreenBounds
module-attribute
¶
The rectangle of a buffer or region on the screen, counting every parent offset.
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.
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.
KeyboardBinding
module-attribute
¶
The latest key event with its modifiers, such as 'ctrl+s', or None.
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.
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).
BufferRegion
module-attribute
¶
The rectangle of a buffer on the screen, counting every parent offset.
Layer
module-attribute
¶
Layer: NumericProperty[int]
The paint order of a buffer among its siblings. Assign it with Layer(2).
IsVisible
module-attribute
¶
Whether a buffer is drawn. Assign it with IsVisible(False).
Point
¶
A cell position, counted in columns (x) and rows (y) from the top-left.
Maps to ratatui::layout::Position.
Parameters:
Attributes:
Examples:
point = Point(2, 3) + Point(1, 1)
assert (point.x, point.y) == (3, 4)
assert point - Point(3, 4) == Point(0, 0)
Create a Point.
Parameters:
- API Reference xnano
-
API Reference
- xnano
-
xnano_core
-
xnano_core-
MousePosition -
PointerPosition -
Position -
ScreenPosition -
BarChartposition -
Blockposition -
Bufferposition -
BufferExpressionScopeposition -
Calendarposition -
Canvasposition -
Chartposition -
Clearposition -
Cursorposition -
CustomWidgetposition -
FrameSnapshotcursor_position -
Gaugeposition -
ItemListposition -
LineGaugeposition -
Liveposition -
MouseEventposition -
MouseExpressionScopeposition -
Paragraphposition -
Point -
Rectangleposition -
Scrollbarposition -
Sparklineposition -
Tableposition -
Tabsposition -
Widgetposition
-
-
xnano_core._xnano_core
_xnano_core-
MousePosition -
PointerPosition -
Position -
ScreenPosition -
BarChartposition -
Blockposition -
Bufferposition -
BufferExpressionScopeposition -
Calendarposition -
Canvasposition -
Chartposition -
Clearposition -
Cursorposition -
CustomWidgetposition -
FrameSnapshotcursor_position -
Gaugeposition -
ItemListposition -
LineGaugeposition -
Liveposition -
MouseEventposition -
MouseExpressionScopeposition -
Paragraphposition -
Point -
Rectangleposition -
Scrollbarposition -
Sparklineposition -
Tableposition -
Tabsposition -
Widgetposition
-
-
Methods:
-
__add__–Add two positions component by component.
-
__sub__–Subtract two positions component by component.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
Size
¶
A width and a height, counted in cells.
Maps to ratatui::layout::Size.
Parameters:
Attributes:
Examples:
Create a Size.
Parameters:
-
API Reference
- xnano
-
xnano_core
-
xnano_core-
BufferSize -
ParentSize -
BarChartsize -
Blocksize -
Buffersize -
BufferExpressionScopesize -
Calendarsize -
Canvassize -
Chartsize -
Clearsize -
CustomWidgetsize -
Device -
Eventsize -
FrameSnapshotsize -
Gaugesize -
ItemListsize -
LineGaugesize -
Livesize -
Paragraphsize -
ParentExpressionScopesize -
Rectanglesize -
Runtimefit_to_content -
Scrollbarsize -
Sparklinesize -
Tablesize -
Tabssize -
Widgetsize
-
-
xnano_core._xnano_core
_xnano_core-
BufferSize -
ParentSize -
BarChartsize -
Blocksize -
Buffersize -
BufferExpressionScopesize -
Calendarsize -
Canvassize -
Chartsize -
Clearsize -
CustomWidgetsize -
Device -
Eventsize -
FrameSnapshotsize -
Gaugesize -
ItemListsize -
LineGaugesize -
Livesize -
Paragraphsize -
ParentExpressionScopesize -
Rectanglesize -
Runtimefit_to_content -
Scrollbarsize -
Sparklinesize -
Tablesize -
Tabssize -
Widgetsize
-
-
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
Rectangle
¶
A rectangle of cells with half-open bounds.
The left and top edges are inclusive, and the right and bottom edges are exclusive.
Maps to ratatui::layout::Rect.
Parameters:
-
x(int, default:0) –The left column.
-
y(int, default:0) –The top row.
-
width(int, default:0) –The number of columns.
-
height(int, default:0) –The number of rows.
Attributes:
-
x(int) –The left column.
-
y(int) –The top row.
-
width(int) –The number of columns.
-
height(int) –The number of rows.
-
position(Point) –The top-left corner.
-
size(Size) –The width and height.
-
area(int) –The number of cells,
width * height. -
is_empty(bool) –Whether the rectangle holds no cells.
Examples:
area = Rectangle(2, 1, 10, 4)
assert area.area == 40
assert area.contains(Point(2, 1))
assert not area.contains(Point(12, 1))
Create a Rectangle.
Parameters:
-
x(int, default:0) –int. Defaults to0. -
y(int, default:0) –int. Defaults to0. -
width(int, default:0) –int. Defaults to0. -
height(int, default:0) –int. Defaults to0.
-
API Reference
-
xnano
xnano.hooks
hooksFramearea -
xnano_core
-
xnano_core-
Bounds -
BufferRegion -
ScreenBounds -
BarChartbounds -
Blockbounds -
Bufferbounds -
BufferExpressionScoperegion -
Calendarbounds -
Canvasbounds -
Chartbounds -
Clearbounds -
CoreContextbounds -
CustomWidgetbounds -
EventContextbounds -
FrameContext -
Gaugebounds -
HitAreabounds -
ItemListbounds -
LineGaugebounds -
Livebounds -
Paragraphbounds -
Rectangle -
Regionbounds -
Scrollbarbounds -
Sparklinebounds -
Tablebounds -
Tabsbounds -
UpdateContextbounds -
Widgetbounds
-
-
xnano_core._xnano_core
_xnano_core-
Bounds -
BufferRegion -
ScreenBounds -
BarChartbounds -
Blockbounds -
Bufferbounds -
BufferExpressionScoperegion -
Calendarbounds -
Canvasbounds -
Chartbounds -
Clearbounds -
CustomWidgetbounds -
Gaugebounds -
HitAreabounds -
ItemListbounds -
LineGaugebounds -
Livebounds -
Paragraphbounds -
Rectangle -
Regionbounds -
Scrollbarbounds -
Sparklinebounds -
Tablebounds -
Tabsbounds -
Widgetbounds
-
-
xnano_core._xnano_core._core_types
_core_types
-
-
xnano
xnano.hooks
-
API Reference
- xnano
-
xnano_core
-
xnano_core-
BarChart -
Block -
Buffer -
Calendar -
Canvas -
Chart -
Clear -
CoreContextinvalidate -
CustomWidget -
Dissolvewith_area -
Editor -
Effectwith_area -
EventContextinvalidate -
Fadewith_area -
FrameContextinvalidate -
Gauge -
Glitchwith_area -
InputRouterhit_area -
ItemList -
LineGauge -
Liveregion -
Paragraph -
Rectangle -
Regioninvalidate -
Scrollbar -
Sparkline -
Surfaceinvalidate -
Table -
Tabs -
UpdateContextinvalidate -
Widget
-
-
xnano_core._xnano_core
_xnano_core -
xnano_core._xnano_core._core_types
_core_types
-
Methods:
-
contains–Whether
pointlies inside the rectangle. -
intersects–Whether the two rectangles share at least one cell.
-
intersection–The cells both rectangles share. The result is empty when they do not overlap.
-
union–The smallest rectangle that holds both rectangles.
-
translate–Move the rectangle by a number of columns and rows.
-
inset–Shrink the rectangle by a margin on every side.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
contains
¶
intersects
¶
intersection
¶
union
¶
translate
¶
Move the rectangle by a number of columns and rows.
Parameters:
-
x(int, default:0) –Columns to move right; negative values move left.
-
y(int, default:0) –Rows to move down; negative values move up.
Examples:
assert Rectangle(0, 0, 4, 2).translate(2, 1) == Rectangle(2, 1, 4, 2)
assert Rectangle(5, 5, 4, 2).translate(x=-1, y=-2) == Rectangle(4, 3, 4, 2)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def translate(self, x: int = 0, y: int = 0) -> Rectangle:
"""
Move the rectangle by a number of columns and rows.
Args:
x: Columns to move right; negative values move left.
y: Rows to move down; negative values move up.
Examples:
```python
assert Rectangle(0, 0, 4, 2).translate(2, 1) == Rectangle(2, 1, 4, 2)
assert Rectangle(5, 5, 4, 2).translate(x=-1, y=-2) == Rectangle(4, 3, 4, 2)
```
"""
inset
¶
Shrink the rectangle by a margin on every side.
Examples:
Color
¶
A terminal color: a named palette color, a palette index or a true color.
Maps to ratatui::style::Color.
Parameters:
-
value(ColorName | str | tuple[int, int, int]) –A color name such as
'red'or'light_blue', a hex string such as'#ff8800', a palette index string such as'4', or a(red, green, blue)tuple.
Attributes:
-
black(Color) –The black terminal color.
-
red(Color) –The red terminal color.
-
green(Color) –The green terminal color.
-
yellow(Color) –The yellow terminal color.
-
blue(Color) –The blue terminal color.
-
magenta(Color) –The magenta terminal color.
-
cyan(Color) –The cyan terminal color.
-
gray(Color) –The gray terminal color.
-
dark_gray(Color) –The dark gray terminal color.
-
light_red(Color) –The light red terminal color.
-
light_green(Color) –The light green terminal color.
-
light_yellow(Color) –The light yellow terminal color.
-
light_blue(Color) –The light blue terminal color.
-
light_magenta(Color) –The light magenta terminal color.
-
light_cyan(Color) –The light cyan terminal color.
-
white(Color) –The white terminal color.
-
reset(Color) –The reset terminal color, which follows the terminal theme.
-
is_reset(bool) –Whether this is the
resetcolor.
Raises:
-
ValueError–valueis not a recognized color.
Examples:
assert Color('#ff8800').to_rgb() == (255, 136, 0)
assert Color((1, 2, 3)) == Color.from_rgb(1, 2, 3)
assert Color('red').to_rgb() is None
Create a Color.
Parameters:
-
API Reference
- xnano
-
xnano_core
-
xnano_core -
xnano_core._xnano_core
_xnano_core -
xnano_core._xnano_core._core_types
_core_types
-
-
API Reference
- xnano
-
xnano_core
-
xnano_core -
xnano_core._xnano_core
_xnano_core
-
Methods:
-
parse–Parse a color name, hex string or palette index string.
-
from_tailwind–A true color from a Tailwind palette and shade.
-
indexed–A color from the 256-color palette.
-
from_rgb–A true color from red, green and blue values between 0 and 255.
-
to_rgb–The
(red, green, blue)values of a true color, orNonefor named and indexed colors. -
to_hex–The color as a
'#rrggbb'string. -
from_hsl–A true color from hue, saturation and lightness.
-
from_hsv–A true color from hue, saturation and value.
-
random–A random true color, or a random shade of
base. -
to_hsl–The hue (degrees), saturation and lightness (percentages) of the color.
-
to_hsv–The hue (degrees), saturation and value (percentages) of the color.
-
lerp–The color between this one and
other. -
lighten–A lighter color for a positive
amount, a darker one for a negativeamount. -
darken–A darker color.
-
inverse–The color that has each red, green and blue channel inverted.
-
saturate–The color with its saturation scaled.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
is_reset
property
¶
is_reset: bool
Whether this is the reset color, which follows the terminal's theme.
parse
classmethod
¶
Parse a color name, hex string or palette index string.
Examples:
from_tailwind
classmethod
¶
from_tailwind(palette: TailwindColorName, shade: TailwindColorShade) -> Color
A true color from a Tailwind palette and shade.
Color does not read a name such as 'slate-400'. Pass the palette and the
shade here.
Parameters:
-
palette(TailwindColorName) –A palette such as
'slate'or'red'. -
shade(TailwindColorShade) –50,100through900, or950.
Raises:
-
ValueError–paletteis not a palette, orshadeis not a shade.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def from_tailwind(
cls, palette: TailwindColorName, shade: TailwindColorShade
) -> Color:
"""
A true color from a Tailwind palette and shade.
``Color`` does not read a name such as ``'slate-400'``. Pass the palette and the
shade here.
Args:
palette: A palette such as ``'slate'`` or ``'red'``.
shade: ``50``, ``100`` through ``900``, or ``950``.
Raises:
ValueError: ``palette`` is not a palette, or ``shade`` is not a shade.
Examples:
```python
assert Color.from_tailwind('red', 500).to_rgb() == (239, 68, 68)
```
"""
indexed
classmethod
¶
A color from the 256-color palette.
Examples:
from_rgb
classmethod
¶
A true color from red, green and blue values between 0 and 255.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
to_rgb
¶
The (red, green, blue) values of a true color, or None for named and indexed colors.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
to_hex
¶
to_hex() -> str
The color as a '#rrggbb' string.
Only a true color has one, as with to_rgb.
Raises:
-
ValueError–The color is named, indexed or
reset, which the terminal's theme chooses.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def to_hex(self) -> str:
"""
The color as a ``'#rrggbb'`` string.
Only a true color has one, as with [`to_rgb`][xnano_core._xnano_core.Color.to_rgb].
Raises:
ValueError: The color is named, indexed or ``reset``, which the terminal's theme
chooses.
Examples:
```python
assert Color((255, 136, 0)).to_hex() == '#ff8800'
assert Color('#FF8800').to_hex() == '#ff8800'
```
"""
from_hsl
classmethod
¶
A true color from hue, saturation and lightness.
Parameters:
-
hue(float) –Degrees from 0 to 360.
-
saturation(float) –A percentage from 0 to 100.
-
lightness(float) –A percentage from 0 to 100.
Raises:
-
ValueError–A value is out of range.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def from_hsl(cls, hue: float, saturation: float, lightness: float) -> Color:
"""
A true color from hue, saturation and lightness.
Args:
hue: Degrees from 0 to 360.
saturation: A percentage from 0 to 100.
lightness: A percentage from 0 to 100.
Raises:
ValueError: A value is out of range.
Examples:
```python
assert Color.from_hsl(0, 100, 50).to_hex() == '#ff0000'
```
"""
from_hsv
classmethod
¶
A true color from hue, saturation and value.
Parameters:
-
hue(float) –Degrees from 0 to 360.
-
saturation(float) –A percentage from 0 to 100.
-
value(float) –A percentage from 0 to 100.
Raises:
-
ValueError–A value is out of range.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def from_hsv(cls, hue: float, saturation: float, value: float) -> Color:
"""
A true color from hue, saturation and value.
Args:
hue: Degrees from 0 to 360.
saturation: A percentage from 0 to 100.
value: A percentage from 0 to 100.
Raises:
ValueError: A value is out of range.
Examples:
```python
assert Color.from_hsv(120, 100, 100).to_hex() == '#00ff00'
```
"""
random
classmethod
¶
A random true color, or a random shade of base.
Without base every red, green and blue channel is picked at random. With base
the color keeps its hue and saturation and takes a random lightness from 15 to 85
percent, so every color it returns is a lighter or darker shade of base. The
colors come from Python's random
module, so random.seed(...) repeats them.
Parameters:
-
base(Color | ColorName | str | tuple[int, int, int] | None, default:None) –The color to pick shades of, or
Nonefor any color.
Raises:
-
ValueError–baseisColor.reset, or not a color.
Examples:
import random
random.seed(7)
first = Color.random()
random.seed(7)
assert Color.random() == first
hue, saturation, _ = Color.random('#3366cc').to_hsl()
assert round(hue) == 220 and round(saturation) == 60
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def random(
cls, base: Color | ColorName | str | tuple[int, int, int] | None = None
) -> Color:
"""
A random true color, or a random shade of ``base``.
Without ``base`` every red, green and blue channel is picked at random. With ``base``
the color keeps its hue and saturation and takes a random lightness from 15 to 85
percent, so every color it returns is a lighter or darker shade of ``base``. The
colors come from Python's [`random`](https://docs.python.org/3/library/random.html)
module, so ``random.seed(...)`` repeats them.
Args:
base: The color to pick shades of, or ``None`` for any color.
Raises:
ValueError: ``base`` is ``Color.reset``, or not a color.
Examples:
```python
import random
random.seed(7)
first = Color.random()
random.seed(7)
assert Color.random() == first
hue, saturation, _ = Color.random('#3366cc').to_hsl()
assert round(hue) == 220 and round(saturation) == 60
```
"""
to_hsl
¶
The hue (degrees), saturation and lightness (percentages) of the color.
Named and indexed colors use their standard values.
Raises:
-
ValueError–The color is
reset.
Examples:
hue, saturation, lightness = Color('#ff0000').to_hsl()
assert round(hue) == 0
assert round(saturation) == 100
assert round(lightness) == 50
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def to_hsl(self) -> tuple[float, float, float]:
"""
The hue (degrees), saturation and lightness (percentages) of the color.
Named and indexed colors use their standard values.
Raises:
ValueError: The color is ``reset``.
Examples:
```python
hue, saturation, lightness = Color('#ff0000').to_hsl()
assert round(hue) == 0
assert round(saturation) == 100
assert round(lightness) == 50
```
"""
to_hsv
¶
The hue (degrees), saturation and value (percentages) of the color.
Named and indexed colors use their standard values.
Raises:
-
ValueError–The color is
reset.
Examples:
hue, saturation, value = Color('#00ff00').to_hsv()
assert round(hue) == 120
assert round(saturation) == 100
assert round(value) == 100
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def to_hsv(self) -> tuple[float, float, float]:
"""
The hue (degrees), saturation and value (percentages) of the color.
Named and indexed colors use their standard values.
Raises:
ValueError: The color is ``reset``.
Examples:
```python
hue, saturation, value = Color('#00ff00').to_hsv()
assert round(hue) == 120
assert round(saturation) == 100
assert round(value) == 100
```
"""
lerp
¶
lerp(other: Color | ColorName | str | tuple[int, int, int], ratio: float, *, color_space: Literal['rgb', 'hsl', 'hsv'] = 'hsl') -> Color
The color between this one and other.
Parameters:
-
other(Color | ColorName | str | tuple[int, int, int]) –The color to blend toward.
-
ratio(float) –0.0is this color and1.0isother. -
color_space(Literal['rgb', 'hsl', 'hsv'], default:'hsl') –The space the blend runs through.
'hsl'and'hsv'keep colors vivid in the middle;'rgb'is the straight average.
Raises:
-
ValueError–A color is
reset, orcolor_spaceis not a color space.
Examples:
middle = Color('#000000').lerp('#ffffff', 0.5, color_space='rgb')
red, green, blue = middle.to_rgb()
assert red == green == blue
assert 126 <= red <= 129
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def lerp(
self,
other: Color | ColorName | str | tuple[int, int, int],
ratio: float,
*,
color_space: Literal['rgb', 'hsl', 'hsv'] = 'hsl',
) -> Color:
"""
The color between this one and ``other``.
Args:
other: The color to blend toward.
ratio: ``0.0`` is this color and ``1.0`` is ``other``.
color_space: The space the blend runs through. ``'hsl'`` and ``'hsv'`` keep colors
vivid in the middle; ``'rgb'`` is the straight average.
Raises:
ValueError: A color is ``reset``, or ``color_space`` is not a color space.
Examples:
```python
middle = Color('#000000').lerp('#ffffff', 0.5, color_space='rgb')
red, green, blue = middle.to_rgb()
assert red == green == blue
assert 126 <= red <= 129
```
"""
lighten
¶
A lighter color for a positive amount, a darker one for a negative amount.
Parameters:
-
amount(float) –A fraction from -1.0 (black) to 1.0 (white).
-
color_space(Literal['rgb', 'hsl', 'hsv'], default:'hsl') –The space the change runs through.
Raises:
-
ValueError–The color is
reset, orcolor_spaceis not a color space.
Examples:
base = Color('#336699')
assert base.lighten(0.2).to_hsl()[2] > base.to_hsl()[2]
assert base.lighten(-0.2).to_hsl()[2] < base.to_hsl()[2]
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def lighten(
self, amount: float, *, color_space: Literal['rgb', 'hsl', 'hsv'] = 'hsl'
) -> Color:
"""
A lighter color for a positive ``amount``, a darker one for a negative ``amount``.
Args:
amount: A fraction from -1.0 (black) to 1.0 (white).
color_space: The space the change runs through.
Raises:
ValueError: The color is ``reset``, or ``color_space`` is not a color space.
Examples:
```python
base = Color('#336699')
assert base.lighten(0.2).to_hsl()[2] > base.to_hsl()[2]
assert base.lighten(-0.2).to_hsl()[2] < base.to_hsl()[2]
```
"""
darken
¶
A darker color.
Parameters:
-
amount(float) –A fraction from 0.0 (unchanged) to 1.0 (black). Use
lightento make a color lighter. -
color_space(Literal['rgb', 'hsl', 'hsv'], default:'hsl') –The space the change runs through.
Returns:
-
Color–The darkened color; the original is unchanged.
Raises:
-
ValueError–amountis outside 0.0 to 1.0, the color isreset, orcolor_spaceis not a color space.
Examples:
assert Color('#808080').darken(1.0).to_rgb() == (0, 0, 0)
base = Color('#336699')
assert base.darken(0.2).to_hsl()[2] < base.to_hsl()[2]
assert base.darken(0.0) == base
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def darken(
self, amount: float, *, color_space: Literal['rgb', 'hsl', 'hsv'] = 'hsl'
) -> Color:
"""
A darker color.
Args:
amount: A fraction from 0.0 (unchanged) to 1.0 (black). Use
[`lighten`][xnano_core._xnano_core.Color.lighten] to make a color lighter.
color_space: The space the change runs through.
Returns:
The darkened color; the original is unchanged.
Raises:
ValueError: ``amount`` is outside 0.0 to 1.0, the color is ``reset``, or
``color_space`` is not a color space.
Examples:
```python
assert Color('#808080').darken(1.0).to_rgb() == (0, 0, 0)
base = Color('#336699')
assert base.darken(0.2).to_hsl()[2] < base.to_hsl()[2]
assert base.darken(0.0) == base
```
"""
inverse
¶
inverse() -> Color
The color that has each red, green and blue channel inverted.
Named and indexed colors are inverted through their standard values, so the result is always a true color.
Returns:
-
Color–The inverted true color; the original is unchanged.
Raises:
-
ValueError–The color is
reset, which has no fixed value.
Examples:
assert Color('#ff8000').inverse().to_hex() == '#007fff'
assert Color('#ff8000').inverse().inverse() == Color('#ff8000')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def inverse(self) -> Color:
"""
The color that has each red, green and blue channel inverted.
Named and indexed colors are inverted through their standard values, so the result
is always a true color.
Returns:
The inverted true color; the original is unchanged.
Raises:
ValueError: The color is ``reset``, which has no fixed value.
Examples:
```python
assert Color('#ff8000').inverse().to_hex() == '#007fff'
assert Color('#ff8000').inverse().inverse() == Color('#ff8000')
```
"""
saturate
¶
The color with its saturation scaled.
Parameters:
-
factor(float) –0.0removes the saturation,1.0keeps it and more than1.0boosts it. -
color_space(Literal['rgb', 'hsl', 'hsv'], default:'hsl') –The space the change runs through.
Raises:
-
ValueError–The color is
reset, orcolor_spaceis not a color space.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def saturate(
self, factor: float, *, color_space: Literal['rgb', 'hsl', 'hsv'] = 'hsl'
) -> Color:
"""
The color with its saturation scaled.
Args:
factor: ``0.0`` removes the saturation, ``1.0`` keeps it and more than ``1.0``
boosts it.
color_space: The space the change runs through.
Raises:
ValueError: The color is ``reset``, or ``color_space`` is not a color space.
Examples:
```python
gray = Color('#336699').saturate(0.0)
assert round(gray.to_hsl()[1]) == 0
```
"""
Style
¶
Style(foreground: ColorValue | None = None, background: ColorValue | None = None, *, bold: bool = False, dim: bool = False, italic: bool = False, underline: bool = False, blink: bool = False, reverse: bool = False, hidden: bool = False, crossed_out: bool = False, rapid_blink: bool = False, underline_color: ColorValue | None = None)
A foreground color, a background color and text modifiers.
Maps to ratatui::style::Style.
Parameters:
-
foreground(ColorValue | None, default:None) –The text color.
-
background(ColorValue | None, default:None) –The cell background color.
-
bold(bool, default:False) –Whether text is bold.
-
dim(bool, default:False) –Whether text is dimmed.
-
italic(bool, default:False) –Whether text is italic.
-
underline(bool, default:False) –Whether text is underlined.
-
blink(bool, default:False) –Whether text blinks.
-
reverse(bool, default:False) –Whether foreground and background swap.
-
hidden(bool, default:False) –Whether text is hidden.
-
crossed_out(bool, default:False) –Whether text is struck through.
Attributes:
-
foreground(Color | None) –The text color, or
Nonewhen unset. -
background(Color | None) –The background color, or
Nonewhen unset. -
modifiers(frozenset[Modifier]) –The enabled text modifiers.
Examples:
style = Style('red', 'black', bold=True)
assert style.foreground == Color('red')
assert 'bold' in style.modifiers
Create a Style.
Parameters:
-
foreground(ColorValue | None, default:None) –ColorValue | None. Defaults toNone. -
background(ColorValue | None, default:None) –ColorValue | None. Defaults toNone. -
bold(bool, default:False) –bool. Defaults toFalse. -
dim(bool, default:False) –bool. Defaults toFalse. -
italic(bool, default:False) –bool. Defaults toFalse. -
underline(bool, default:False) –bool. Defaults toFalse. -
blink(bool, default:False) –bool. Defaults toFalse. -
reverse(bool, default:False) –bool. Defaults toFalse. -
hidden(bool, default:False) –bool. Defaults toFalse. -
crossed_out(bool, default:False) –bool. Defaults toFalse. -
rapid_blink(bool, default:False) –bool. Defaults toFalse. -
underline_color(ColorValue | None, default:None) –ColorValue | None. Defaults toNone.
-
API Reference
-
xnano
-
xnano.canvas
canvasCanvasSettings -
xnano.effects
effects-
CoalesceEffectParametersstyle -
CoalesceEffectParametersSchemastyle -
CoalesceEffectSpecificationstyle -
DissolveEffectParametersstyle -
DissolveEffectParametersSchemastyle -
DissolveEffectSpecificationstyle -
EvolveEffectParametersstyle -
EvolveEffectParametersSchemastyle -
EvolveEffectSpecificationstyle -
EvolveFromEffectParametersstyle -
EvolveFromEffectParametersSchemastyle -
EvolveFromEffectSpecificationstyle -
EvolveIntoEffectParametersstyle -
EvolveIntoEffectParametersSchemastyle -
EvolveIntoEffectSpecificationstyle -
ExpandEffectParametersstyle -
ExpandEffectParametersSchemastyle -
ExpandEffectSpecificationstyle -
StretchEffectParametersstyle -
StretchEffectParametersSchemastyle -
StretchEffectSpecificationstyle
-
-
xnano.layout
layoutPlacementstyle -
xnano.operations
operations -
xnano.styles
styles -
xnano.terminal
terminalOpenSettings
-
xnano.canvas
-
xnano_core
-
xnano_core -
xnano_core._xnano_core
_xnano_core
-
-
xnano
-
API Reference
- xnano
-
xnano_core
-
xnano_core-
ApplyStyle -
Bar -
BarChart -
Block -
BlockTitle -
Border -
Buffer -
Calendar -
Canvas -
CanvasLabel -
Cell -
Chart -
ChartAxis -
ChartDataset -
Clear -
CustomWidget -
Dissolve -
Editor -
Effect -
Fade -
Gauge -
Glitch -
ItemList -
LineGauge -
ListItem -
Live -
Paragraph -
Region -
Scrollbar -
Sparkline -
SparklineBar -
Stylepatch -
Surface -
Table -
TableCell -
TableRow -
Tabs -
TextSpan -
Widget -
Write -
WriteCellText
-
-
xnano_core._xnano_core
_xnano_core-
ApplyStyle -
Bar -
BarChart -
Block -
BlockTitle -
Border -
Buffer -
Calendar -
Canvas -
CanvasLabel -
Cell -
Chart -
ChartAxis -
ChartDataset -
Clear -
CustomWidget -
Dissolve -
Editor -
Effect -
Fade -
Gauge -
Glitch -
ItemList -
LineGauge -
ListItem -
Live -
Paragraph -
Region -
Scrollbar -
Sparkline -
SparklineBar -
Stylepatch -
Surface -
Table -
TableCell -
TableRow -
Tabs -
TextSpan -
Widget -
Write -
WriteCellText
-
-
Methods:
-
patch–A style where every value
othersets replaces this style's value.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
self,
foreground: ColorValue | None = None,
background: ColorValue | None = None,
*,
bold: bool = False,
dim: bool = False,
italic: bool = False,
underline: bool = False,
blink: bool = False,
reverse: bool = False,
hidden: bool = False,
crossed_out: bool = False,
rapid_blink: bool = False,
underline_color: ColorValue | None = None,
) -> None:
"""
Create a Style.
Args:
foreground: ``ColorValue | None``. Defaults to ``None``.
background: ``ColorValue | None``. Defaults to ``None``.
bold: ``bool``. Defaults to ``False``.
dim: ``bool``. Defaults to ``False``.
italic: ``bool``. Defaults to ``False``.
underline: ``bool``. Defaults to ``False``.
blink: ``bool``. Defaults to ``False``.
reverse: ``bool``. Defaults to ``False``.
hidden: ``bool``. Defaults to ``False``.
crossed_out: ``bool``. Defaults to ``False``.
rapid_blink: ``bool``. Defaults to ``False``.
underline_color: ``ColorValue | None``. Defaults to ``None``.
"""
patch
¶
A style where every value other sets replaces this style's value.
Examples:
base = Style('red', bold=True)
patched = base.patch(Style(italic=True))
assert patched.foreground == Color('red')
assert patched.modifiers == {'bold', 'italic'}
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def patch(self, other: Style) -> Style:
"""
A style where every value ``other`` sets replaces this style's value.
Examples:
```python
base = Style('red', bold=True)
patched = base.patch(Style(italic=True))
assert patched.foreground == Color('red')
assert patched.modifiers == {'bold', 'italic'}
```
"""
Clock
¶
The time source a runtime reads, either real or stepped by hand.
A monotonic clock follows real time, so wall-clock adjustments never affect it. A manual clock moves only when you step it, which makes tests and replays exact. Either kind can be stopped; a stopped clock does not move until it is resumed or stepped by hand.
Attributes:
-
source(Literal['monotonic', 'manual']) –Whether the clock follows real time or is stepped by hand.
-
elapsed_seconds(float) –Seconds since the clock started.
-
elapsed_milliseconds(float) –Milliseconds since the clock started.
-
delta_seconds(float) –Seconds between the two most recent frames.
-
delta_milliseconds(float) –Milliseconds between the two most recent frames.
-
frame(int) –The number of frames the clock has counted.
-
frames_per_second(float) –The rate at which the runtime drew its recent frames.
-
is_stopped(bool) –Whether the clock is stopped.
Examples:
clock = Clock.manual()
clock.step(1500)
assert clock.elapsed_seconds == 1.5
assert clock.source == 'manual'
Methods:
-
monotonic–A clock that follows real elapsed time.
-
manual–A clock that moves only through
step. -
stop–Stop time from advancing.
-
resume–Let time advance again after it was stopped.
-
step–Move time forward by exactly
milliseconds. -
derive–Create a clock that follows this one at a different speed.
source
property
¶
source: Literal['monotonic', 'manual']
Whether the clock follows real time or is stepped by hand.
delta_milliseconds
property
¶
delta_milliseconds: float
Milliseconds between the two most recent frames.
frames_per_second
property
¶
frames_per_second: float
The rate at which the runtime drew its recent frames, in frames per second.
Only frames the runtime draws count, and it draws when something changed, at most once
per frame interval. A monotonic clock measures the rate in real time, time spent
stopped included; a manual clock measures it in its own time, so it is the rate its
steps imply. It is 0.0 until a few frames have been drawn.
monotonic
classmethod
¶
A clock that follows real elapsed time.
Parameters:
-
elapsed_seconds(float, default:0.0) –The time the clock starts at, zero or more.
-
frame(int, default:0) –The number of frames the clock has already counted, zero or more.
Returns:
-
Clock–A running clock that follows real time.
Raises:
-
ValueError–elapsed_secondsis negative or not finite, orframeis negative.
Examples:
clock = Clock.monotonic()
assert clock.source == 'monotonic'
continued = Clock.monotonic(elapsed_seconds=2.0, frame=120)
assert continued.elapsed_seconds >= 2.0
assert continued.frame == 120
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def monotonic(cls, *, elapsed_seconds: float = 0.0, frame: int = 0) -> Clock:
"""
A clock that follows real elapsed time.
Args:
elapsed_seconds: The time the clock starts at, zero or more.
frame: The number of frames the clock has already counted, zero or more.
Returns:
A running clock that follows real time.
Raises:
ValueError: ``elapsed_seconds`` is negative or not finite, or ``frame`` is
negative.
Examples:
```python
clock = Clock.monotonic()
assert clock.source == 'monotonic'
continued = Clock.monotonic(elapsed_seconds=2.0, frame=120)
assert continued.elapsed_seconds >= 2.0
assert continued.frame == 120
```
"""
manual
classmethod
¶
A clock that moves only through step.
Parameters:
-
elapsed_seconds(float, default:0.0) –The time the clock starts at, zero or more.
Raises:
-
ValueError–elapsed_secondsis negative or not finite.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def manual(cls, *, elapsed_seconds: float = 0.0) -> Clock:
"""
A clock that moves only through [`step`][xnano_core._xnano_core.Clock.step].
Args:
elapsed_seconds: The time the clock starts at, zero or more.
Raises:
ValueError: ``elapsed_seconds`` is negative or not finite.
Examples:
```python
clock = Clock.manual(elapsed_seconds=2.0)
assert clock.elapsed_milliseconds == 2000.0
```
"""
stop
¶
Stop time from advancing.
The time spent stopped is not counted in elapsed_seconds.
Examples:
resume
¶
Let time advance again after it was stopped.
Examples:
step
¶
step(milliseconds: int) -> None
Move time forward by exactly milliseconds.
A manual clock can always be stepped. A monotonic clock can be stepped only while it is stopped, which lets a stopped clock advance one frame at a time.
Parameters:
-
milliseconds(int) –How far to move, zero or more.
Raises:
-
ValueError–millisecondsis negative, or the clock is a monotonic clock that is running.
Examples:
clock = Clock.monotonic()
clock.stop()
before = clock.elapsed_milliseconds
clock.step(250)
assert abs(clock.elapsed_milliseconds - (before + 250.0)) < 1e-6
manual = Clock.manual()
manual.step(100)
assert manual.elapsed_milliseconds == 100.0
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def step(self, milliseconds: int) -> None:
"""
Move time forward by exactly ``milliseconds``.
A manual clock can always be stepped. A monotonic clock can be stepped only while it
is stopped, which lets a stopped clock advance one frame at a time.
Args:
milliseconds: How far to move, zero or more.
Raises:
ValueError: ``milliseconds`` is negative, or the clock is a monotonic clock
that is running.
Examples:
```python
clock = Clock.monotonic()
clock.stop()
before = clock.elapsed_milliseconds
clock.step(250)
assert abs(clock.elapsed_milliseconds - (before + 250.0)) < 1e-6
manual = Clock.manual()
manual.step(100)
assert manual.elapsed_milliseconds == 100.0
```
"""
derive
¶
derive(*, rate: float = 1.0, is_stopped: bool = False) -> SimulationClock
Create a clock that follows this one at a different speed.
Parameters:
-
rate(float, default:1.0) –How fast the new clock runs compared to this one. Zero or more.
-
is_stopped(bool, default:False) –Whether the new clock starts stopped.
Examples:
clock = Clock.manual()
slow_motion = clock.derive(rate=0.5)
assert slow_motion.rate == 0.5
assert slow_motion.parent.source == 'manual'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def derive(self, *, rate: float = 1.0, is_stopped: bool = False) -> SimulationClock:
"""
Create a clock that follows this one at a different speed.
Args:
rate: How fast the new clock runs compared to this one. Zero or more.
is_stopped: Whether the new clock starts stopped.
Examples:
```python
clock = Clock.manual()
slow_motion = clock.derive(rate=0.5)
assert slow_motion.rate == 0.5
assert slow_motion.parent.source == 'manual'
```
"""
SimulationClock
¶
A clock derived from a parent clock, with its own rate and stopped state.
Changing the rate keeps elapsed time continuous. Rates are finite and nonnegative.
Attributes:
-
parent(Clock) –The clock this clock follows.
-
rate(float) –How fast this clock runs compared to its parent. Assign to change it.
-
is_stopped(bool) –Whether this clock is stopped. Assign to stop or resume it.
-
elapsed_seconds(float) –Seconds of simulation time.
-
delta_seconds(float) –Seconds of simulation time between the two most recent calls to
sample.
Examples:
simulation = Clock.manual().derive(rate=1.0)
simulation.rate = 2.0
simulation.is_stopped = True
assert simulation.rate == 2.0
assert simulation.is_stopped
Methods:
-
sample–Record the current elapsed time so
delta_secondsreports time since this sample. -
stop–Stop this clock without affecting its parent.
-
resume–Resume this clock after it was stopped.
rate
property
writable
¶
rate: float
How fast this clock runs compared to its parent. Assign to change it.
is_stopped
property
writable
¶
is_stopped: bool
Whether this clock is stopped. Assign to stop or resume it.
delta_seconds
property
¶
delta_seconds: float
Seconds of simulation time between the two most recent calls to sample.
sample
¶
Record the current elapsed time so delta_seconds reports time since this sample.
Call once for each simulation frame whose elapsed time you want to measure.
Examples:
parent = Clock.manual()
simulation = parent.derive(rate=2.0)
simulation.sample()
parent.step(100)
simulation.sample()
assert simulation.delta_seconds == 0.2
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def sample(self) -> None:
"""
Record the current elapsed time so ``delta_seconds`` reports time since this sample.
Call once for each simulation frame whose elapsed time you want to measure.
Examples:
```python
parent = Clock.manual()
simulation = parent.derive(rate=2.0)
simulation.sample()
parent.step(100)
simulation.sample()
assert simulation.delta_seconds == 0.2
```
"""
stop
¶
Stop this clock without affecting its parent.
Examples:
resume
¶
TextSpan
¶
A run of text with one style.
Maps to ratatui::text::Span.
Parameters:
Attributes:
Examples:
span = TextSpan('warning', style=Style('yellow', bold=True))
assert span.text == 'warning'
assert 'bold' in span.style.modifiers
Create a TextSpan.
Parameters:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
StyledText
¶
Text made of differently styled spans.
Parameters:
Attributes:
Examples:
text = StyledText([TextSpan('error: ', style=Style('red')), TextSpan('disk full')])
assert str(text) == 'error: disk full'
assert len(text.spans) == 2
Create a StyledText.
Parameters:
Methods:
-
from_ansi–Read the text that a program prints for a terminal, with its ANSI colors and styles.
-
__str__–The text without styles.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
from_ansi
classmethod
¶
from_ansi(text: str) -> StyledText
Read the text that a program prints for a terminal, with its ANSI colors and styles.
Use it for the output of a command, a log file or a library that prints in color. The SGR sequences set the colors (the 16 named colors, the 256 palette colors and true colors) and the text modifiers. A newline starts a new line, a tab moves to the next column that is a multiple of eight, and a carriage return moves back to the start of the line, so the text after it writes over the line, as on a terminal. Every other control character and escape sequence (cursor movement, erasing, titles and modes) is removed. A final newline does not start an empty line.
Parameters:
-
text(str) –The text, with its escape sequences.
Returns:
-
StyledText–The styled text, with a newline between two lines.
Examples:
text = StyledText.from_ansi('\x1b[1;31merror:\x1b[0m disk full')
assert str(text) == 'error: disk full'
assert text.spans[0].style == Style('red', bold=True)
progress = StyledText.from_ansi('downloading 10%\rdownloading 100%\n')
assert str(progress) == 'downloading 100%'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def from_ansi(cls, text: str) -> StyledText:
"""
Read the text that a program prints for a terminal, with its ANSI colors and styles.
Use it for the output of a command, a log file or a library that prints in color.
The SGR sequences set the colors (the 16 named colors, the 256 palette colors and
true colors) and the text modifiers. A newline starts a new line, a tab moves to the
next column that is a multiple of eight, and a carriage return moves back to the
start of the line, so the text after it writes over the line, as on a terminal.
Every other control character and escape sequence (cursor movement, erasing,
titles and modes) is removed. A final newline does not start an empty line.
Args:
text: The text, with its escape sequences.
Returns:
The styled text, with a newline between two lines.
Examples:
```python
text = StyledText.from_ansi('\\x1b[1;31merror:\\x1b[0m disk full')
assert str(text) == 'error: disk full'
assert text.spans[0].style == Style('red', bold=True)
progress = StyledText.from_ansi('downloading 10%\\rdownloading 100%\\n')
assert str(progress) == 'downloading 100%'
```
"""
TextLine
¶
One wrapped line of a TextLayout.
Attributes:
-
text(str) –The text of the line.
-
start_offset(int) –Where the line starts in the original text, counted in Python string offsets.
-
end_offset(int) –Where the line ends in the original text, counted in Python string offsets.
-
width(int) –The number of cells the line occupies.
Examples:
layout = layout_text('hello world', width=6)
line = layout.lines[0]
assert line.text == 'hello '
assert (line.start_offset, line.end_offset, line.width) == (0, 6, 6)
TextLayout
¶
Text wrapped to a width, with conversions between cells and string offsets.
Cell positions and Python string offsets agree at grapheme boundaries.
Attributes:
-
lines(tuple[TextLine, ...]) –The wrapped lines.
-
cursor_cell(tuple[int, int] | None) –The
(column, row)of the cursor, orNonewhen no cursor was given.
Examples:
layout = layout_text('hello world foo', width=8, cursor_offset=3)
assert [line.text for line in layout.lines] == ['hello ', 'world ', 'foo']
assert layout.cursor_cell == (3, 0)
Methods:
-
text_offset_at–The string offset under a cell.
-
cell_at_text_offset–The
(column, row)of a string offset.
TextEditor
¶
An editable text buffer with a cursor and undo history.
Draw it with Editor.
Parameters:
-
text(str, default:'') –The starting text.
-
is_single_line(bool, default:False) –Whether line breaks are refused.
Attributes:
-
text(str) –The current text.
-
is_single_line(bool) –Whether line breaks are refused.
-
cursor_offset(int) –The cursor position, counted in Python string offsets.
-
placeholder_text(str) –The text shown while the editor is empty. Assign to change it.
Examples:
editor = TextEditor('abc')
editor.move_cursor(3)
editor.insert_text('d')
assert editor.text == 'abcd'
assert editor.undo()
assert editor.text == 'abc'
Create a TextEditor.
Parameters:
-
text(str, default:'') –str. Defaults to''. -
is_single_line(bool, default:False) –bool. Defaults toFalse.
Methods:
-
set_text–Replace all text.
-
insert_text–Insert text at the cursor.
-
handle_key–Apply a key press to the text and cursor.
-
move_cursor–Move the cursor to a string offset.
-
undo–Undo the most recent edit.
-
redo–Redo the most recently undone edit.
-
layout–Wrap the text to a width and locate the cursor.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
placeholder_text
property
writable
¶
placeholder_text: str
The text shown while the editor is empty. Assign to change it.
handle_key
¶
undo
¶
undo() -> bool
Undo the most recent edit.
Returns:
-
bool–Whether there was an edit to undo.
Examples:
editor = TextEditor('a')
editor.insert_text('b')
assert editor.undo()
assert not TextEditor().undo()
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
redo
¶
redo() -> bool
Redo the most recently undone edit.
Returns:
-
bool–Whether there was an edit to redo.
Examples:
editor = TextEditor('a')
editor.insert_text('b')
editor.undo()
assert editor.redo()
assert editor.text == 'ab'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
layout
¶
layout(*, width: int, should_wrap: bool = True) -> TextLayout
Wrap the text to a width and locate the cursor.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
Editor
¶
Editor(editor: TextEditor, *, area: Rectangle | None = None, style: Style | None = None, first_row: int = 0, should_wrap: bool = True, should_show_cursor: bool = True, mode: WriteMode = 'preserve_background')
Bases: Operation
Draw a TextEditor into a buffer.
Parameters:
-
editor(TextEditor) –The editor to draw.
-
area(Rectangle | None, default:None) –The region to draw into. Defaults to the whole target.
-
style(Style | None, default:None) –The style of the text.
-
first_row(int, default:0) –The first wrapped row to show, for scrolling.
-
should_wrap(bool, default:True) –Whether long lines wrap.
-
should_show_cursor(bool, default:True) –Whether the cursor cell is highlighted.
-
mode(WriteMode, default:'preserve_background') –How text treats the background already in the cells.
Examples:
editor = TextEditor('hi')
buffer = Buffer(width=5, height=1)
buffer.update(Editor(editor, area=Rectangle(0, 0, 5, 1)))
assert buffer.text.startswith('hi')
Create a Editor.
Parameters:
-
editor(TextEditor) –TextEditor. -
area(Rectangle | None, default:None) –Rectangle | None. Defaults toNone. -
style(Style | None, default:None) –Style | None. Defaults toNone. -
first_row(int, default:0) –int. Defaults to0. -
should_wrap(bool, default:True) –bool. Defaults toTrue. -
should_show_cursor(bool, default:True) –bool. Defaults toTrue. -
mode(WriteMode, default:'preserve_background') –WriteMode. Defaults to'preserve_background'.
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,
editor: TextEditor,
*,
area: Rectangle | None = None,
style: Style | None = None,
first_row: int = 0,
should_wrap: bool = True,
should_show_cursor: bool = True,
mode: WriteMode = 'preserve_background',
) -> None:
"""
Create a Editor.
Args:
editor: ``TextEditor``.
area: ``Rectangle | None``. Defaults to ``None``.
style: ``Style | None``. Defaults to ``None``.
first_row: ``int``. Defaults to ``0``.
should_wrap: ``bool``. Defaults to ``True``.
should_show_cursor: ``bool``. Defaults to ``True``.
mode: ``WriteMode``. Defaults to ``'preserve_background'``.
"""
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__
¶
KeyEvent
¶
A key press, repeat or release.
Get one from Event.key or build an event with
Event.key_press.
Attributes:
-
key(str) –The key name, such as
'a','enter'or'page_up'. -
text(str | None) –The text the key types, or
Nonefor control keys and chords. -
modifiers(frozenset[KeyModifier]) –The modifier keys held.
-
kind(KeyEventKind) –Whether the key was pressed, repeated or released.
Examples:
key = Event.key_press('ctrl+c').key
assert key.key == 'c'
assert key.modifiers == {'control'}
assert key.matches('ctrl+c')
Methods:
-
matches–Whether this event is the key and modifiers of
binding.
matches
¶
matches(binding: str | KeyBinding) -> bool
MouseEvent
¶
A mouse press, release, drag, move or scroll.
Attributes:
-
position(Point) –The cell under the pointer.
-
column(int) –The column under the pointer.
-
row(int) –The row under the pointer.
-
kind(MouseEventKind) –What the mouse did.
-
button(MouseButton | None) –The button involved, or
Nonefor moves and scrolls. -
scroll_x(int) –Horizontal scroll steps, negative for left and positive for right.
-
scroll_y(int) –Vertical scroll steps, negative for up and positive for down.
Examples:
mouse = Event.mouse_event(column=4, row=2, kind='press', button='left').mouse
assert (mouse.column, mouse.row) == (4, 2)
assert mouse.button == 'left'
Event
¶
Something that happened: input, a resize, a timer or a frame.
Hooks and the runtime report everything as an event. Build events with the class methods to test code without a terminal.
Attributes:
-
kind(EventKind) –What the event reports.
-
timestamp_seconds(float) –Seconds on the runtime clock when the event happened.
-
key(KeyEvent | None) –The key details of a key event, otherwise
None. -
mouse(MouseEvent | None) –The mouse details of a mouse event, otherwise
None. -
pasted_text(str | None) –The pasted text of a paste event, otherwise
None. -
size(Size | None) –The new size of a resize event, otherwise
None. -
timer_key(str | None) –The key of a timer event, otherwise
None. -
custom_name(str | None) –The name of a custom event, otherwise
None. -
custom_data(str | None) –The data of a custom event, otherwise
None.
Examples:
event = Event.key_press('q')
assert event.kind == 'key'
assert event.key.key == 'q'
assert Event.resize(width=80, height=24).size == Size(80, 24)
- API Reference
Methods:
-
key_press–A key event for a key name with optional
+-joined modifiers. -
paste–A paste event.
-
resize–A resize event.
-
mouse_event–A mouse event.
-
tick–Create a tick event, as a runtime with a tick interval reports.
-
timer–Create a timer event for the timer called
key. -
wake–Create a wake event, which only makes a runtime run an iteration.
-
exit_requested–Create the event a runtime reports when the application is asked to exit.
-
custom–Create an event your application defines.
-
focus_gained–An event reporting that the terminal window gained focus.
-
focus_lost–An event reporting that the terminal window lost focus.
timestamp_seconds
property
¶
timestamp_seconds: float
Seconds on the runtime clock when the event happened.
key_press
classmethod
¶
key_press(binding: str, *, kind: KeyEventKind = 'press') -> Event
A key event for a key name with optional +-joined modifiers.
Parameters:
-
binding(str) –The key, such as
'q','enter'or'ctrl+c'. -
kind(KeyEventKind, default:'press') –Whether the key is pressed, repeated or released.
Raises:
-
ValueError–bindingis not a valid key orkindis unknown.
Examples:
event = Event.key_press('alt+enter')
assert event.key.key == 'enter'
assert event.key.modifiers == {'alt'}
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def key_press(cls, binding: str, *, kind: KeyEventKind = 'press') -> Event:
"""
A key event for a key name with optional ``+``-joined modifiers.
Args:
binding: The key, such as ``'q'``, ``'enter'`` or ``'ctrl+c'``.
kind: Whether the key is pressed, repeated or released.
Raises:
ValueError: ``binding`` is not a valid key or ``kind`` is unknown.
Examples:
```python
event = Event.key_press('alt+enter')
assert event.key.key == 'enter'
assert event.key.modifiers == {'alt'}
```
"""
paste
classmethod
¶
resize
classmethod
¶
A resize event.
Examples:
mouse_event
classmethod
¶
mouse_event(*, column: int, row: int, kind: MouseEventKind, button: MouseButton | None = None, scroll_x: int = 0, scroll_y: int = 0) -> Event
A mouse event.
Parameters:
-
column(int) –The column under the pointer.
-
row(int) –The row under the pointer.
-
kind(MouseEventKind) –What the mouse did.
-
button(MouseButton | None, default:None) –The button involved in a press, release or drag.
-
scroll_x(int, default:0) –Horizontal scroll steps, negative for left and positive for right.
-
scroll_y(int, default:0) –Vertical scroll steps, negative for up and positive for down.
Examples:
event = Event.mouse_event(column=0, row=0, kind='scroll', scroll_y=-1)
assert event.mouse.scroll_y == -1
sideways = Event.mouse_event(column=0, row=0, kind='scroll', scroll_x=2)
assert (sideways.mouse.scroll_x, sideways.mouse.scroll_y) == (2, 0)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def mouse_event(
cls,
*,
column: int,
row: int,
kind: MouseEventKind,
button: MouseButton | None = None,
scroll_x: int = 0,
scroll_y: int = 0,
) -> Event:
"""
A mouse event.
Args:
column: The column under the pointer.
row: The row under the pointer.
kind: What the mouse did.
button: The button involved in a press, release or drag.
scroll_x: Horizontal scroll steps, negative for left and positive for right.
scroll_y: Vertical scroll steps, negative for up and positive for down.
Examples:
```python
event = Event.mouse_event(column=0, row=0, kind='scroll', scroll_y=-1)
assert event.mouse.scroll_y == -1
sideways = Event.mouse_event(column=0, row=0, kind='scroll', scroll_x=2)
assert (sideways.mouse.scroll_x, sideways.mouse.scroll_y) == (2, 0)
```
"""
tick
classmethod
¶
tick() -> Event
Create a tick event, as a runtime with a tick interval reports.
Examples:
timer
classmethod
¶
Create a timer event for the timer called key.
Examples:
wake
classmethod
¶
wake() -> Event
Create a wake event, which only makes a runtime run an iteration.
Examples:
exit_requested
classmethod
¶
exit_requested() -> Event
Create the event a runtime reports when the application is asked to exit.
Examples:
custom
classmethod
¶
Create an event your application defines.
Inject it with Runtime.inject and listen
for it with a hook on 'custom' events. Text such as JSON can travel in data.
Parameters:
-
name(str) –What the event is, such as
'volume_changed'. -
data(str | None, default:None) –Optional text that travels with the event.
Raises:
-
ValueError–The name is empty.
Examples:
event = Event.custom('volume_changed', data='40')
assert event.kind == 'custom'
assert (event.custom_name, event.custom_data) == ('volume_changed', '40')
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def custom(cls, name: str, *, data: str | None = None) -> Event:
"""
Create an event your application defines.
Inject it with [`Runtime.inject`][xnano_core._xnano_core.Runtime.inject] and listen
for it with a hook on ``'custom'`` events. Text such as JSON can travel in ``data``.
Args:
name: What the event is, such as ``'volume_changed'``.
data: Optional text that travels with the event.
Raises:
ValueError: The name is empty.
Examples:
```python
event = Event.custom('volume_changed', data='40')
assert event.kind == 'custom'
assert (event.custom_name, event.custom_data) == ('volume_changed', '40')
```
"""
focus_gained
classmethod
¶
focus_gained() -> Event
An event reporting that the terminal window gained focus.
Examples:
KeyBinding
¶
A key and modifiers to match against key events.
Examples:
binding = KeyBinding.parse('ctrl+q')
assert binding.matches(Event.key_press('ctrl+q'))
assert not binding.matches(Event.key_press('q'))
Methods:
-
parse–Parse text such as
'q','ctrl+c','shift+tab'or'alt+enter'. -
matches–Whether
eventis this key with exactly these modifiers.
parse
classmethod
¶
parse(binding: str) -> KeyBinding
Parse text such as 'q', 'ctrl+c', 'shift+tab' or 'alt+enter'.
Raises:
-
ValueError–bindingis empty or names an unknown key or modifier.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
@classmethod
def parse(cls, binding: str) -> KeyBinding:
"""
Parse text such as ``'q'``, ``'ctrl+c'``, ``'shift+tab'`` or ``'alt+enter'``.
Raises:
ValueError: ``binding`` is empty or names an unknown key or modifier.
Examples:
```python
assert KeyBinding.parse('ctrl+shift+z').matches(Event.key_press('ctrl+shift+z'))
```
"""
matches
¶
Whether event is this key with exactly these modifiers.
Examples:
EventStream
¶
The events a runtime reports, as an iterator.
Get one from Runtime.events. Iterate it
synchronously with for or asynchronously with async for.
Examples:
with Runtime.offscreen(width=10, height=3) as runtime:
runtime.mount(Buffer(), geometry='inherit')
stream = runtime.events()
runtime.inject(Event.key_press('q'))
runtime.step()
assert next(stream).key.key == 'q'
Waker
¶
A handle other threads use to wake a runtime and run code on its thread.
Get one from Runtime.waker. It is the only
object besides call_soon_threadsafe that is safe to use from another thread.
Examples:
calls = []
with Runtime.offscreen(width=10, height=3) as runtime:
waker = runtime.waker()
waker.call_soon(calls.append, 'woken')
runtime.step()
assert calls == ['woken']
Methods:
-
call_soon–Run
callbackwithargumentson the runtime's thread at its next step. -
wake–Wake the runtime so its next step does not wait.
call_soon
¶
Run callback with arguments on the runtime's thread at its next step.
Examples:
results = []
with Runtime.offscreen(width=10, height=3) as runtime:
runtime.waker().call_soon(results.append, 1)
runtime.step()
assert results == [1]
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def call_soon(self, callback: Callable[..., object], *arguments: object) -> None:
"""
Run ``callback`` with ``arguments`` on the runtime's thread at its next step.
Examples:
```python
results = []
with Runtime.offscreen(width=10, height=3) as runtime:
runtime.waker().call_soon(results.append, 1)
runtime.step()
assert results == [1]
```
"""
wake
¶
Wake the runtime so its next step does not wait.
Examples:
Hook
¶
A registered callback that can be paused, reprioritized or cancelled.
Higher priorities run first, and ties keep registration order. Register hooks with
Surface.add_hook.
Attributes:
-
enabled(bool) –Whether the hook runs. Assign
Falseto pause it andTrueto resume. -
priority(int) –The hook's priority.
-
is_cancelled(bool) –Whether the hook was cancelled.
Examples:
seen = []
with Runtime.offscreen(width=10, height=3) as runtime:
buffer = Buffer()
runtime.mount(buffer, geometry='inherit')
hook = buffer.add_hook(lambda context: seen.append('key'), events=('key',))
runtime.inject(Event.key_press('a'))
runtime.step()
hook.enabled = False
runtime.inject(Event.key_press('b'))
runtime.step()
hook.cancel()
assert seen == ['key']
assert hook.is_cancelled
-
API Reference
xnano_core
-
xnano_core-
BarChartadd_hook -
Blockadd_hook -
Bufferadd_hook -
Calendaradd_hook -
Canvasadd_hook -
Chartadd_hook -
Clearadd_hook -
CustomWidgetadd_hook -
Gaugeadd_hook -
InputRouteron -
ItemListadd_hook -
LineGaugeadd_hook -
Liveadd_hook -
Paragraphadd_hook -
Regionadd_hook -
Runtime -
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 -
InputRouteron -
ItemListadd_hook -
LineGaugeadd_hook -
Liveadd_hook -
Paragraphadd_hook -
Regionadd_hook -
Runtime -
Scrollbaradd_hook -
Sparklineadd_hook -
Surfaceadd_hook -
Tableadd_hook -
Tabsadd_hook -
Widgetadd_hook
-
-
Methods:
-
cancel–Remove the hook permanently.
ScheduledCall
¶
A callback scheduled on a clock with call_later or call_every.
Attributes:
-
is_cancelled(bool) –Whether the call was cancelled.
Examples:
calls = []
with Runtime.offscreen(width=10, height=3) as runtime:
scheduled = runtime.call_later(1.0, lambda: calls.append('done'))
runtime.advance_clock(1000)
runtime.step()
assert calls == ['done']
assert not scheduled.is_cancelled
Methods:
-
cancel–Stop the call from running.
cancel
¶
KeyboardCapabilities
¶
What the terminal's keyboard protocol can report.
Attributes:
-
enhancement(CapabilityStatus) –Whether the enhanced keyboard protocol is available.
-
disambiguates_keys(bool) –Whether keys such as
escapeandalt+keyare told apart. -
reports_event_types(bool) –Whether key repeats and releases are reported.
-
reports_all_keys(bool) –Whether modifier keys on their own are reported.
-
unavailable_reason(str | None) –Why the enhanced protocol is unavailable, or
None. -
enabled_features(frozenset[Literal['disambiguate', 'event_types', 'all_keys']]) –The protocol features that are switched on.
Examples:
with Runtime.offscreen(width=10, height=3) as runtime:
capabilities = runtime.device.keyboard
assert capabilities.enhancement in ('supported', 'unsupported', 'unknown')
enhancement
property
¶
enhancement: CapabilityStatus
Whether the enhanced keyboard protocol is available.
disambiguates_keys
property
¶
disambiguates_keys: bool
Whether keys such as escape and alt+key are told apart.
reports_event_types
property
¶
reports_event_types: bool
Whether key repeats and releases are reported.
InputOptions
¶
InputOptions(*, mouse: Literal['off', 'buttons', 'motion'] = 'off', scroll: bool = False, bracketed_paste: bool = True, focus_reporting: bool = True, keyboard: Literal['off', 'basic', 'disambiguated', 'release_events'] = 'basic', capability_timeout_milliseconds: int = 200, interrupt: Literal['event', 'stop'] = 'event')
The input modes a live terminal asks for.
Requested modes are negotiated with the terminal and restored when the runtime closes.
Parameters:
-
mouse(Literal['off', 'buttons', 'motion'], default:'off') –The requested mouse mode. Button and motion reports reach the runtime only when this is not
'off'. -
scroll(bool, default:False) –Whether mouse wheel reports reach the runtime. It is independent of
mouse:InputOptions(scroll=True)delivers the wheel and no button or motion reports. -
bracketed_paste(bool, default:True) –Whether pasted text arrives as one paste event.
-
focus_reporting(bool, default:True) –Whether the terminal reports focus changes.
-
keyboard(Literal['off', 'basic', 'disambiguated', 'release_events'], default:'basic') –The requested keyboard mode.
'off'drops key events that come from the terminal, except Ctrl+C wheninterruptis'stop', so a runtime without a keyboard can still be stopped. -
capability_timeout_milliseconds(int, default:200) –How long to wait for capability answers.
-
interrupt(Literal['event', 'stop'], default:'event') –Whether Ctrl+C becomes an
'event'or'stop'the runtime.
Raises:
-
ValueError–A mode is not one of the listed values.
Attributes:
-
mouse(Literal['off', 'buttons', 'motion']) –The requested mouse mode.
-
scroll(bool) –Whether mouse wheel reports are requested.
-
bracketed_paste(bool) –Whether bracketed paste is requested.
-
focus_reporting(bool) –Whether focus reporting is requested.
-
keyboard(Literal['off', 'basic', 'disambiguated', 'release_events']) –The requested keyboard mode.
-
capability_timeout_milliseconds(int) –How long capability queries wait.
-
interrupt(Literal['event', 'stop']) –How Ctrl+C is handled.
Examples:
options = InputOptions(mouse='buttons', keyboard='release_events')
assert options.mouse == 'buttons'
terminal = TerminalOptions(input=options)
wheel_only = InputOptions(scroll=True, keyboard='off', interrupt='stop')
assert wheel_only.scroll and wheel_only.mouse == 'off'
assert wheel_only.keyboard == 'off'
Create a InputOptions.
Parameters:
-
mouse(Literal['off', 'buttons', 'motion'], default:'off') –Literal['off', 'buttons', 'motion']. Defaults to'off'. -
scroll(bool, default:False) –bool. Defaults toFalse. -
bracketed_paste(bool, default:True) –bool. Defaults toTrue. -
focus_reporting(bool, default:True) –bool. Defaults toTrue. -
keyboard(Literal['off', 'basic', 'disambiguated', 'release_events'], default:'basic') –Literal['off', 'basic', 'disambiguated', 'release_events']. Defaults to'basic'. -
capability_timeout_milliseconds(int, default:200) –int. Defaults to200. -
interrupt(Literal['event', 'stop'], default:'event') –Literal['event', 'stop']. Defaults to'event'.
Methods:
-
__repr__–Every option in keyword form.
-
__eq__–Whether
otheris anInputOptionswith the same options.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
self,
*,
mouse: Literal['off', 'buttons', 'motion'] = 'off',
scroll: bool = False,
bracketed_paste: bool = True,
focus_reporting: bool = True,
keyboard: Literal['off', 'basic', 'disambiguated', 'release_events'] = 'basic',
capability_timeout_milliseconds: int = 200,
interrupt: Literal['event', 'stop'] = 'event',
) -> None:
"""
Create a InputOptions.
Args:
mouse: ``Literal['off', 'buttons', 'motion']``. Defaults to ``'off'``.
scroll: ``bool``. Defaults to ``False``.
bracketed_paste: ``bool``. Defaults to ``True``.
focus_reporting: ``bool``. Defaults to ``True``.
keyboard: ``Literal['off', 'basic', 'disambiguated', 'release_events']``. Defaults
to ``'basic'``.
capability_timeout_milliseconds: ``int``. Defaults to ``200``.
interrupt: ``Literal['event', 'stop']``. Defaults to ``'event'``.
"""
keyboard
property
¶
keyboard: Literal['off', 'basic', 'disambiguated', 'release_events']
The requested keyboard mode.
capability_timeout_milliseconds
property
¶
capability_timeout_milliseconds: int
How long capability queries wait.
__eq__
¶
TerminalOptions
¶
TerminalOptions(*, input: InputOptions | None = None, alternate_screen: bool = True, raw_mode: bool = True, drain_reports_on_exit: bool = True, drain_timeout_milliseconds: int = 250, should_capture_output: bool = True, should_clear_on_close: bool = False)
How a live runtime takes over the terminal.
Parameters:
-
input(InputOptions | None, default:None) –The input modes to request.
-
alternate_screen(bool, default:True) –Whether to draw on the alternate screen.
-
raw_mode(bool, default:True) –Whether to put the terminal in raw mode.
-
drain_reports_on_exit(bool, default:True) –Whether to discard pending terminal replies on exit.
-
drain_timeout_milliseconds(int, default:250) –How long to wait while discarding replies.
-
should_clear_on_close(bool, default:False) –Whether the area the runtime drew in is erased when it closes, instead of staying on the screen. Applies when the alternate screen is not used, such as an inline runtime.
-
should_capture_output(bool, default:True) –Whether text written to standard output and standard error while the session is open is held back instead of reaching the screen. It is printed to the stream it was written to when the runtime closes, or read earlier with
Runtime.take_captured_output. Captured on Unix only.
Attributes:
-
input(InputOptions) –The requested input modes.
-
alternate_screen(bool) –Whether the alternate screen is used.
-
raw_mode(bool) –Whether raw mode is used.
-
drain_reports_on_exit(bool) –Whether pending terminal replies are discarded on exit.
-
drain_timeout_milliseconds(int) –How long discarding replies may take.
-
should_capture_output(bool) –Whether text printed during the session is held back from the screen.
-
should_clear_on_close(bool) –Whether the runtime's area is erased when it closes.
Examples:
options = TerminalOptions(alternate_screen=False)
assert options.raw_mode
assert not options.alternate_screen
assert options.should_capture_output
assert not options.should_clear_on_close
Create a TerminalOptions.
Parameters:
-
input(InputOptions | None, default:None) –InputOptions | None. Defaults toNone. -
alternate_screen(bool, default:True) –bool. Defaults toTrue. -
raw_mode(bool, default:True) –bool. Defaults toTrue. -
drain_reports_on_exit(bool, default:True) –bool. Defaults toTrue. -
drain_timeout_milliseconds(int, default:250) –int. Defaults to250. -
should_capture_output(bool, default:True) –bool. Defaults toTrue. -
should_clear_on_close(bool, default:False) –bool. Defaults toFalse.
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __init__(
self,
*,
input: InputOptions | None = None,
alternate_screen: bool = True,
raw_mode: bool = True,
drain_reports_on_exit: bool = True,
drain_timeout_milliseconds: int = 250,
should_capture_output: bool = True,
should_clear_on_close: bool = False,
) -> None:
"""
Create a TerminalOptions.
Args:
input: ``InputOptions | None``. Defaults to ``None``.
alternate_screen: ``bool``. Defaults to ``True``.
raw_mode: ``bool``. Defaults to ``True``.
drain_reports_on_exit: ``bool``. Defaults to ``True``.
drain_timeout_milliseconds: ``int``. Defaults to ``250``.
should_capture_output: ``bool``. Defaults to ``True``.
should_clear_on_close: ``bool``. Defaults to ``False``.
"""
drain_reports_on_exit
property
¶
drain_reports_on_exit: bool
Whether pending terminal replies are discarded on exit.
drain_timeout_milliseconds
property
¶
drain_timeout_milliseconds: int
How long discarding replies may take.
Cursor
¶
The one cursor a terminal has.
A runtime has exactly one cursor, so it belongs to the runtime rather than to any buffer. It is hidden until it is given a position. Every property may be changed from any thread, and a change is drawn on the next frame even when no cell changed. A live runtime gives the user's own cursor back when it closes.
Get it from Runtime.cursor.
Attributes:
-
position(Point | None) –The cell the cursor is at, counted from the top-left of the runtime's area.
-
shape(CursorShape | None) –'block','bar'or'underline';Nonekeeps the user's own shape. -
is_blinking(bool) –Whether the cursor blinks. Setting it without a shape uses a block.
-
is_visible(bool) –Whether the cursor is shown when it has a position.
Trueby default.
Examples:
with Runtime.offscreen(width=10, height=3) as runtime:
runtime.mount(Buffer(), geometry='inherit')
runtime.cursor.position = (3, 1)
runtime.cursor.shape = 'bar'
frame = runtime.render()
assert frame.cursor_position == Point(3, 1)
runtime.cursor.is_visible = False
assert not runtime.render().is_cursor_visible
Methods:
-
follow–Keep the cursor at a place inside a buffer, wherever the buffer is.
position
property
writable
¶
position: Point | None
The cell the cursor is at, counted from the top-left of the runtime's area.
Assign a Point, an (x, y) pair or None to hide the cursor.
Assigning a position stops the cursor following a buffer. A cursor outside the
area is not shown.
shape
property
writable
¶
shape: CursorShape | None
'block', 'bar' or 'underline'; None keeps the user's own shape.
Raises:
-
ValueError–When assigned another name.
is_blinking
property
writable
¶
is_blinking: bool
Whether the cursor blinks. Setting it without a shape uses a block.
is_visible
property
writable
¶
is_visible: bool
Whether the cursor is shown when it has a position. True by default.
follow
¶
Keep the cursor at a place inside a buffer, wherever the buffer is.
The cursor is hidden while the buffer or any buffer above it is hidden.
Parameters:
-
buffer(Buffer | None) –The buffer to follow, or
Noneto stop following. -
x(int, default:0) –The column inside the buffer.
-
y(int, default:0) –The row inside the buffer.
Examples:
with Runtime.offscreen(width=10, height=3) as runtime:
field = Buffer(width=6, height=1, x=2, y=1)
runtime.mount(field)
runtime.cursor.follow(field, x=4)
assert runtime.render().cursor_position == Point(6, 1)
field.x = 3
assert runtime.render().cursor_position == Point(7, 1)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def follow(self, buffer: Buffer | None, *, x: int = 0, y: int = 0) -> None:
"""
Keep the cursor at a place inside a buffer, wherever the buffer is.
The cursor is hidden while the buffer or any buffer above it is hidden.
Args:
buffer: The buffer to follow, or ``None`` to stop following.
x: The column inside the buffer.
y: The row inside the buffer.
Examples:
```python
with Runtime.offscreen(width=10, height=3) as runtime:
field = Buffer(width=6, height=1, x=2, y=1)
runtime.mount(field)
runtime.cursor.follow(field, x=4)
assert runtime.render().cursor_position == Point(6, 1)
field.x = 3
assert runtime.render().cursor_position == Point(7, 1)
```
"""
InputState
¶
The keys and pointer position a runtime currently sees.
Reliable pressed keys require negotiated release reporting. In reliable mode keys are
cleared on focus loss, unmount and shutdown. When release reporting is unavailable,
pressed_keys is empty and the opt-in timeout estimates appear in
estimated_pressed_keys instead, so an estimate never passes as a real held key.
Attributes:
-
held_keys_available(bool) –Whether the terminal reports key releases.
-
pressed_keys(frozenset[str]) –The keys currently held, when releases are reported, and the held mouse buttons as
'mouse_left','mouse_right'and'mouse_middle'. -
estimated_pressed_keys(frozenset[str]) –The keys guessed to be held from a timeout, when estimates are enabled.
-
pointer_cell(tuple[int, int] | None) –The
(column, row)under the pointer, orNone. -
last_key(str | None) –The key of the latest key event, or
Nonewhile the latest input was not a key. -
last_key_kind(Literal['press', 'repeat', 'release'] | None) –'press','repeat'or'release'for the latest key event, orNone. -
last_binding(str | None) –The latest key event with its modifiers as text such as
'ctrl+s', orNone. Modifiers come in the orderctrl,alt,shift,super,meta,hyper. -
last_mouse_button(MouseButton | None) –'left','right'or'middle'for the latest button or motion report, orNone. -
last_mouse_kind(Literal['press', 'release', 'drag', 'move'] | None) –'press','release','drag'or'move'for the latest button or motion report.Nonefor a wheel report and while the latest input was not a mouse event. -
last_mouse_position(tuple[int, int] | None) –The
(column, row)of the latest button or motion report, orNone. Unlikepointer_cellit is cleared by any other kind of input. -
scroll_x(int) –The horizontal steps of the latest wheel report of the current step (right is positive),
0when no wheel report arrived or any other input followed it. -
scroll_y(int) –The vertical steps of the latest wheel report of the current step (down is positive, so scrolling up is
-1),0when no wheel report arrived or any other input followed it. -
is_mouse_down(bool) –Whether any mouse button is held.
-
last_pasted_text(str | None) –The text of the latest paste, or
Nonewhile the latest input was not a paste.
Each kind of input clears the "latest" values of the other kinds, so a value is None
unless the latest input was of its kind. Held mouse buttons are named 'mouse_left',
'mouse_right' and 'mouse_middle' in pressed_keys.
Examples:
with Runtime.offscreen(width=10, height=3) as runtime:
state = runtime.input
assert state.pressed_keys == frozenset()
assert state.pointer_cell is None
runtime.inject(Event.key_press('ctrl+s'))
runtime.step()
assert state.last_key == 's' and state.last_binding == 'ctrl+s'
runtime.inject(Event.mouse_event(column=4, row=1, kind='press', button='left'))
runtime.step()
assert state.is_mouse_down and 'mouse_left' in state.pressed_keys
assert state.last_mouse_position == (4, 1) and state.last_key is None
runtime.inject(Event.mouse_event(column=4, row=1, kind='release', button='left'))
runtime.inject(Event.mouse_event(column=4, row=1, kind='scroll', scroll_y=-1))
runtime.step()
assert not state.is_mouse_down
assert state.scroll_y == -1 and state.last_mouse_kind is None
runtime.step()
assert state.scroll_y == 0
Methods:
-
estimate_holds–Guess held keys from key repeats when releases are not reported.
pressed_keys
property
¶
The keys currently held, when releases are reported.
estimated_pressed_keys
property
¶
The keys guessed to be held from a timeout, when estimates are enabled.
pointer_cell
property
¶
The (column, row) under the pointer, or None.
last_key_kind
property
¶
last_key_kind: Literal['press', 'repeat', 'release'] | None
Whether the latest key event was a press, repeat or release.
last_binding
property
¶
last_binding: str | None
The latest key event with its modifiers, such as 'ctrl+s'.
last_mouse_button
property
¶
last_mouse_button: MouseButton | None
The button of the latest button or motion report.
last_mouse_kind
property
¶
last_mouse_kind: Literal['press', 'release', 'drag', 'move'] | None
The kind of the latest button or motion report; None for a wheel report.
last_mouse_position
property
¶
The (column, row) of the latest button or motion report.
scroll_x
property
¶
scroll_x: int
The horizontal steps of the latest wheel report of the current step.
scroll_y
property
¶
scroll_y: int
The vertical steps of the latest wheel report of the current step.
estimate_holds
¶
estimate_holds(*, timeout_seconds: float | None = None) -> None
Guess held keys from key repeats when releases are not reported.
A terminal repeats only the newest key held, so a press of a different key ends the estimate of the key before it, and at most one key is estimated at a time.
Parameters:
-
timeout_seconds(float | None, default:None) –How long after the last repeat a key counts as held. Positive.
Noneturns estimates off. The timeout cannot account for the operating system's initial repeat delay.
Examples:
with Runtime.offscreen(width=10, height=3) as runtime:
runtime.mount(Buffer())
runtime.input.estimate_holds(timeout_seconds=0.5)
runtime.inject(Event.key_press('left'))
runtime.inject(Event.key_press('right'))
runtime.step()
assert runtime.input.estimated_pressed_keys == {'right'}
runtime.input.estimate_holds(timeout_seconds=None)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def estimate_holds(self, *, timeout_seconds: float | None = None) -> None:
"""
Guess held keys from key repeats when releases are not reported.
A terminal repeats only the newest key held, so a press of a different key ends the
estimate of the key before it, and at most one key is estimated at a time.
Args:
timeout_seconds: How long after the last repeat a key counts as held. Positive.
``None`` turns estimates off. The timeout cannot account for the operating
system's initial repeat delay.
Examples:
```python
with Runtime.offscreen(width=10, height=3) as runtime:
runtime.mount(Buffer())
runtime.input.estimate_holds(timeout_seconds=0.5)
runtime.inject(Event.key_press('left'))
runtime.inject(Event.key_press('right'))
runtime.step()
assert runtime.input.estimated_pressed_keys == {'right'}
runtime.input.estimate_holds(timeout_seconds=None)
```
"""
Device
¶
The display and terminal a runtime draws on.
Attributes:
-
backend(Literal['terminal', 'offscreen']) –Whether output goes to a real terminal or an in-memory screen.
-
size(Size) –The size of the display in cells.
-
window_size_in_pixels(Size | None) –The size of the window in pixels, or
Nonewhen unknown. -
capabilities(TerminalCapabilities) –What the terminal can display.
-
keyboard(KeyboardCapabilities) –What the keyboard protocol can report.
-
is_focused(bool) –Whether the terminal window has focus.
-
is_inline(bool) –Whether the runtime draws inline instead of taking the whole screen.
-
is_raw_mode_enabled(bool) –Whether raw mode is on.
-
is_mouse_capture_enabled(bool) –Whether mouse capture is on.
-
is_bracketed_paste_enabled(bool) –Whether bracketed paste is on.
-
is_focus_reporting_enabled(bool) –Whether focus reporting is on.
-
is_alternate_screen_enabled(bool) –Whether the alternate screen is on.
Examples:
with Runtime.offscreen(width=40, height=10) as runtime:
device = runtime.device
assert device.backend == 'offscreen'
assert device.size == Size(40, 10)
backend
property
¶
backend: Literal['terminal', 'offscreen']
Whether output goes to a real terminal or an in-memory screen.
window_size_in_pixels
property
¶
window_size_in_pixels: Size | None
The size of the window in pixels, or None when unknown.
is_inline
property
¶
is_inline: bool
Whether the runtime draws inline instead of taking the whole screen.
is_bracketed_paste_enabled
property
¶
is_bracketed_paste_enabled: bool
Whether bracketed paste is on.
HitArea
¶
A named rectangle that receives mouse hits without needing painted text.
Create one with InputRouter.hit_area.
Attributes:
-
key(str) –The name the hit area was registered with.
-
bounds(Rectangle) –The rectangle, relative to the target. Assign to move or resize it.
Examples:
with Runtime.offscreen(width=20, height=5) as runtime:
buffer = Buffer()
runtime.mount(buffer, geometry='inherit')
area = runtime.router.hit_area('button', target=buffer, bounds=Rectangle(2, 1, 4, 2))
assert area.key == 'button'
area.bounds = Rectangle(0, 0, 2, 2)
area.remove()
Methods:
-
remove–Unregister the hit area.
bounds
property
writable
¶
bounds: Rectangle
The rectangle, relative to the target. Assign to move or resize it.
remove
¶
Unregister the hit area.
Examples:
with Runtime.offscreen(width=20, height=5) as runtime:
buffer = Buffer()
runtime.mount(buffer, geometry='inherit')
area = runtime.router.hit_area('x', target=buffer, bounds=Rectangle(0, 0, 2, 2))
area.remove()
assert runtime.router.hit_test(0, 0) == ()
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def remove(self) -> None:
"""
Unregister the hit area.
Examples:
```python
with Runtime.offscreen(width=20, height=5) as runtime:
buffer = Buffer()
runtime.mount(buffer, geometry='inherit')
area = runtime.router.hit_area('x', target=buffer, bounds=Rectangle(0, 0, 2, 2))
area.remove()
assert runtime.router.hit_test(0, 0) == ()
```
"""
FocusScope
¶
A group of input targets, optionally modal.
Modal scopes receive input first. Scopes change routing only, never application state. Use it as a context manager to close it automatically.
Attributes:
Examples:
with Runtime.offscreen(width=20, height=5) as runtime:
dialog = Buffer(width=10, height=3)
runtime.mount(dialog)
with runtime.router.scope(dialog, modal=True) as scope:
assert scope.is_active
assert not scope.is_active
Methods:
-
close–Close the scope.
close
¶
InputRouter
¶
Routes input events to buffers: handlers, hit areas, focus and scopes.
Get it from Runtime.router.
Examples:
seen = []
with Runtime.offscreen(width=20, height=5) as runtime:
buffer = Buffer()
runtime.mount(buffer, geometry='inherit')
runtime.router.on(lambda context: seen.append(context.event.key.key), target=buffer, events=('key',))
runtime.inject(Event.key_press('z'))
runtime.step()
assert seen == ['z']
Methods:
-
on–Call
callbackwhen an event reachestarget. -
hit_area–Register target-local geometry without requiring painted glyphs.
-
hit_test–The hit areas under a cell, topmost first.
-
scope–Open a focus scope around
target. -
focus–Give
targetinput focus. -
clear_focus–Remove input focus from every buffer.
on
¶
on(callback: Callable[[EventContext], None], *, target: Buffer | Region, events: Sequence[EventKind] = ('key', 'mouse', 'paste'), binding: KeyBinding | str | None = None, priority: int = 0) -> Hook
Call callback when an event reaches target.
Parameters:
-
callback(Callable[[EventContext], None]) –Called with an
EventContext. -
target(Buffer | Region) –The buffer or region that receives the events.
-
events(Sequence[EventKind], default:('key', 'mouse', 'paste')) –Which kinds of events to handle.
-
binding(KeyBinding | str | None, default:None) –Only handle key events matching this binding.
-
priority(int, default:0) –Higher priorities run first.
Returns:
-
Hook–A hook to pause or cancel the handler.
Examples:
with Runtime.offscreen(width=20, height=5) as runtime:
buffer = Buffer()
runtime.mount(buffer, geometry='inherit')
hook = runtime.router.on(lambda context: context.consume(), target=buffer, binding='ctrl+q')
hook.cancel()
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def on(
self,
callback: Callable[[EventContext], None],
*,
target: Buffer | Region,
events: Sequence[EventKind] = ('key', 'mouse', 'paste'),
binding: KeyBinding | str | None = None,
priority: int = 0,
) -> Hook:
"""
Call ``callback`` when an event reaches ``target``.
Args:
callback: Called with an ``EventContext``.
target: The buffer or region that receives the events.
events: Which kinds of events to handle.
binding: Only handle key events matching this binding.
priority: Higher priorities run first.
Returns:
A hook to pause or cancel the handler.
Examples:
```python
with Runtime.offscreen(width=20, height=5) as runtime:
buffer = Buffer()
runtime.mount(buffer, geometry='inherit')
hook = runtime.router.on(lambda context: context.consume(), target=buffer, binding='ctrl+q')
hook.cancel()
```
"""
hit_area
¶
Register target-local geometry without requiring painted glyphs.
Parameters:
-
key(str) –A name for the hit area.
-
target(Buffer | Region) –The buffer or region the bounds are relative to.
-
bounds(Rectangle) –The hit rectangle.
-
layer(int, default:0) –Higher layers are hit first.
Examples:
with Runtime.offscreen(width=20, height=5) as runtime:
buffer = Buffer()
runtime.mount(buffer, geometry='inherit')
runtime.router.hit_area('button', target=buffer, bounds=Rectangle(2, 1, 4, 2))
assert runtime.router.hit_test(3, 1)[0].key == 'button'
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def hit_area(
self, key: str, *, target: Buffer | Region, bounds: Rectangle, layer: int = 0
) -> HitArea:
"""
Register target-local geometry without requiring painted glyphs.
Args:
key: A name for the hit area.
target: The buffer or region the bounds are relative to.
bounds: The hit rectangle.
layer: Higher layers are hit first.
Examples:
```python
with Runtime.offscreen(width=20, height=5) as runtime:
buffer = Buffer()
runtime.mount(buffer, geometry='inherit')
runtime.router.hit_area('button', target=buffer, bounds=Rectangle(2, 1, 4, 2))
assert runtime.router.hit_test(3, 1)[0].key == 'button'
```
"""
hit_test
¶
The hit areas under a cell, topmost first.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
scope
¶
scope(target: Buffer, *, modal: bool = False) -> FocusScope
Open a focus scope around target.
Parameters:
-
target(Buffer) –The buffer whose subtree forms the scope.
-
modal(bool, default:False) –Whether the scope receives input before everything else.
Examples:
with Runtime.offscreen(width=20, height=5) as runtime:
dialog = Buffer(width=10, height=3)
runtime.mount(dialog)
with runtime.router.scope(dialog, modal=True) as scope:
assert scope.is_active
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def scope(self, target: Buffer, *, modal: bool = False) -> FocusScope:
"""
Open a focus scope around ``target``.
Args:
target: The buffer whose subtree forms the scope.
modal: Whether the scope receives input before everything else.
Examples:
```python
with Runtime.offscreen(width=20, height=5) as runtime:
dialog = Buffer(width=10, height=3)
runtime.mount(dialog)
with runtime.router.scope(dialog, modal=True) as scope:
assert scope.is_active
```
"""
focus
¶
Give target input focus.
Returns:
-
bool–Whether the buffer could take focus.
Examples:
with Runtime.offscreen(width=20, height=5) as runtime:
buffer = Buffer()
runtime.mount(buffer, geometry='inherit')
assert runtime.router.focus(buffer) in (True, False)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def focus(self, target: Buffer) -> bool:
"""
Give ``target`` input focus.
Returns:
Whether the buffer could take focus.
Examples:
```python
with Runtime.offscreen(width=20, height=5) as runtime:
buffer = Buffer()
runtime.mount(buffer, geometry='inherit')
assert runtime.router.focus(buffer) in (True, False)
```
"""
clear_focus
¶
Remove input focus from every buffer.
Examples:
TerminalCapabilities
¶
What a terminal can display.
Attributes:
-
is_terminal(bool) –Whether standard output is a terminal.
-
is_live_terminal_available(bool) –Whether a live terminal runtime can run here.
-
color_profile(ColorProfile) –How many colors the terminal displays.
-
graphics_protocol(Literal['half_blocks', 'kitty', 'sixel', 'iterm2']) –The best image protocol the terminal supports.
-
cell_size_in_pixels(tuple[int, int] | None) –The
(width, height)of one cell in pixels, orNonewhen unknown. -
synchronized_output(CapabilityStatus) –Whether the terminal supports synchronized output.
Examples:
capabilities = detect_terminal_capabilities(timeout_milliseconds=10)
assert capabilities.graphics_protocol in ('half_blocks', 'kitty', 'sixel', 'iterm2')
is_live_terminal_available
property
¶
is_live_terminal_available: bool
Whether a live terminal runtime can run here.
graphics_protocol
property
¶
graphics_protocol: Literal['half_blocks', 'kitty', 'sixel', 'iterm2']
The best image protocol the terminal supports.
cell_size_in_pixels
property
¶
The (width, height) of one cell in pixels, or None when unknown.
synchronized_output
property
¶
synchronized_output: CapabilityStatus
Whether the terminal supports synchronized output.
Expression
¶
Bases: Generic[ValueType_co]
A value or action described now and evaluated later against a buffer or runtime.
Evaluation is explicit. Using an expression where Python wants a truth value raises
TypeError; combine conditions with &, | and ~ instead.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
buffer = Buffer(width=8, height=1)
assert buffer.inspect(width + 2) == 10
assert (width + 2).evaluate(EvaluationContext(buffer=buffer)) == 10
-
API Reference
-
xnano
xnano.effects
effects-
CoalesceEffectParameters -
CoalesceEffectParametersSchema -
CoalesceEffectSpecification -
DarkenEffectParameters -
DarkenEffectParametersSchema -
DarkenEffectSpecification -
DissolveEffectParameters -
DissolveEffectParametersSchema -
DissolveEffectSpecification -
EvolveEffectParameters -
EvolveEffectParametersSchema -
EvolveEffectSpecification -
EvolveFromEffectParameters -
EvolveFromEffectParametersSchema -
EvolveFromEffectSpecification -
EvolveIntoEffectParameters -
EvolveIntoEffectParametersSchema -
EvolveIntoEffectSpecification -
ExpandEffectParameters -
ExpandEffectParametersSchema -
ExpandEffectSpecification -
ExplodeEffectParameters -
ExplodeEffectParametersSchema -
ExplodeEffectSpecification -
FadeFromEffectParameters -
FadeFromEffectParametersSchema -
FadeFromEffectSpecification -
FadeToEffectParameters -
FadeToEffectParametersSchema -
FadeToEffectSpecification -
GlitchEffectParameters -
GlitchEffectParametersSchema -
GlitchEffectSpecification -
HslShiftEffectParameters -
HslShiftEffectParametersSchema -
HslShiftEffectSpecification -
LightenEffectParameters -
LightenEffectParametersSchema -
LightenEffectSpecification -
PaintEffectParameters -
PaintEffectParametersSchema -
PaintEffectSpecification -
SaturateEffectParameters -
SaturateEffectParametersSchema -
SaturateEffectSpecification -
SleepEffectParameters -
SleepEffectParametersSchema -
SleepEffectSpecification -
SlideInEffectParameters -
SlideInEffectParametersSchema -
SlideInEffectSpecification -
SlideOutEffectParameters -
SlideOutEffectParametersSchema -
SlideOutEffectSpecification -
StretchEffectParameters -
StretchEffectParametersSchema -
StretchEffectSpecification -
SweepInEffectParameters -
SweepInEffectParametersSchema -
SweepInEffectSpecification -
SweepOutEffectParameters -
SweepOutEffectParametersSchema -
SweepOutEffectSpecification
-
-
xnano_core
-
xnano_core -
xnano_core._xnano_core
_xnano_core
-
-
xnano
xnano.effects
-
API Reference
-
xnano
-
xnano -
xnano.canvas
canvasCanvasevaluate -
xnano.effects
effects-
CoalesceEffectParameters -
DarkenEffectParameters -
DissolveEffectParameters -
EvolveEffectParameters -
EvolveFromEffectParameters -
EvolveIntoEffectParameters -
ExpandEffectParameters -
ExplodeEffectParameters -
FadeFromEffectParameters -
FadeToEffectParameters -
GlitchEffectParameters -
HslShiftEffectParameters -
LightenEffectParameters -
PaintEffectParameters -
SaturateEffectParameters -
SleepEffectParameters -
SlideInEffectParameters -
SlideOutEffectParameters -
StretchEffectParameters -
SweepInEffectParameters -
SweepOutEffectParameters
-
-
xnano.expressions
expressionsExpression -
xnano.hooks
hooksWhen -
xnano.terminal
terminalTerminalevaluate
-
-
xnano_core
-
xnano_core-
Bar -
BarChartinspect -
BarGroup -
Blockinspect -
BlockTitle -
Bufferinspect -
Calendarinspect -
Canvasinspect -
Chartinspect -
ChartAxis -
ChartDataset -
Clearinspect -
CustomWidgetinspect -
Dissolve -
DynamicStyle -
Effect -
Fade -
Gaugeinspect -
Glitch -
ItemListinspect -
LineGaugeinspect -
ListItem -
Liveinspect -
Margin -
Offset -
Paragraphinspect -
Regioninspect -
Scrollbarinspect -
Sparklineinspect -
SparklineBar -
Surfaceinspect -
Tableinspect -
TableCell -
TableRow -
Tabsinspect -
Widgetinspect
-
-
xnano_core._xnano_core
_xnano_core-
Bar -
BarChartinspect -
BarGroup -
Blockinspect -
BlockTitle -
Bufferinspect -
Calendarinspect -
Canvasinspect -
Chartinspect -
ChartAxis -
ChartDataset -
Clearinspect -
CustomWidgetinspect -
Dissolve -
DynamicStyle -
Effect -
Fade -
Gaugeinspect -
Glitch -
ItemListinspect -
LineGaugeinspect -
ListItem -
Liveinspect -
Margin -
Offset -
Paragraphinspect -
Regioninspect -
Scrollbarinspect -
Sparklineinspect -
SparklineBar -
Surfaceinspect -
Tableinspect -
TableCell -
TableRow -
Tabsinspect -
Widgetinspect
-
-
-
xnano
Methods:
-
evaluate–Compute the expression's value.
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
```
"""
Predicate
¶
Bases: Expression[bool]
A condition that evaluates to True or False.
Build predicates by comparing values, then combine them with &, | and ~.
== and != also build predicates, so (Width > 4) == False is a condition and not
a bool.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
height = _reference('Height', 'numeric_property')
buffer = Buffer(width=8, height=2)
assert buffer.inspect((width > 4) & (height < 3))
assert not buffer.inspect(~(width > 4))
- API Reference xnano_core
-
API Reference
-
xnano
-
xnano.effects
effects-
AudioEffectParameterswhen -
BitCrushAudioEffectParameterswhen -
CoalesceEffectParameterswhen -
DarkenEffectParameterswhen -
DelayAudioEffectParameterswhen -
DissolveEffectParameterswhen -
DistortionAudioEffectParameterswhen -
EffectParameterswhen -
EvolveEffectParameterswhen -
EvolveFromEffectParameterswhen -
EvolveIntoEffectParameterswhen -
ExpandEffectParameterswhen -
ExplodeEffectParameterswhen -
FadeFromEffectParameterswhen -
FadeToEffectParameterswhen -
GlitchEffectParameterswhen -
HighPassAudioEffectParameterswhen -
HslShiftEffectParameterswhen -
LightenEffectParameterswhen -
LowPassAudioEffectParameterswhen -
PaintEffectParameterswhen -
ReverbAudioEffectParameterswhen -
SaturateEffectParameterswhen -
SleepEffectParameterswhen -
SlideInEffectParameterswhen -
SlideOutEffectParameterswhen -
StretchEffectParameterswhen -
SweepInEffectParameterswhen -
SweepOutEffectParameterswhen -
TremoloAudioEffectParameterswhen
-
-
xnano.operations
operations
-
xnano.effects
-
xnano_core
-
xnano_core-
AnimateDrawingwhen -
ApplyStatePatchwhen -
ApplyStylewhen -
Backgroundwhen -
BarChartadd_hook -
Blockadd_hook -
Borderwhen -
Bufferadd_hook -
Calendaradd_hook -
CancelEffectwhen -
Canvasadd_hook -
Chartadd_hook -
Clearadd_hook -
Conditionalwhen -
CustomWidgetadd_hook -
Customizationwhen -
Dissolvewhen -
Drawwhen -
Editorwhen -
Effectwhen -
Fadewhen -
Fillwhen -
Foregroundwhen -
Fuzzwhen -
Gaugeadd_hook -
Glitchwhen -
ItemListadd_hook -
Layoutwhen -
LineGaugeadd_hook -
Liveadd_hook -
Movewhen -
Operationwhen -
OperationChainwhen -
Paragraphadd_hook -
Pastewhen -
Pixelswhen -
Placewhen -
Predicate -
Rasterwhen -
Regionadd_hook -
Resizewhen -
Scrollbaradd_hook -
SequenceOperationwhen -
SetStatewhen -
SetValuewhen -
Sparklineadd_hook -
Surfaceadd_hook -
Tableadd_hook -
Tabsadd_hook -
Widgetadd_hook -
Writewhen -
WriteCellTextwhen
-
-
xnano_core._xnano_core
_xnano_core-
AnimateDrawingwhen -
ApplyStatePatchwhen -
ApplyStylewhen -
Backgroundwhen -
BarChartadd_hook -
Blockadd_hook -
Borderwhen -
Bufferadd_hook -
Calendaradd_hook -
CancelEffectwhen -
Canvasadd_hook -
Chartadd_hook -
Clearadd_hook -
Conditionalwhen -
CustomWidgetadd_hook -
Customizationwhen -
Dissolvewhen -
Drawwhen -
Editorwhen -
Effectwhen -
Fadewhen -
Fillwhen -
Foregroundwhen -
Fuzzwhen -
Gaugeadd_hook -
Glitchwhen -
ItemListadd_hook -
Layoutwhen -
LineGaugeadd_hook -
Liveadd_hook -
Movewhen -
Operationwhen -
OperationChainwhen -
Paragraphadd_hook -
Pastewhen -
Pixelswhen -
Placewhen -
Predicate -
Rasterwhen -
Regionadd_hook -
Resizewhen -
Scrollbaradd_hook -
SequenceOperationwhen -
SetStatewhen -
SetValuewhen -
Sparklineadd_hook -
Surfaceadd_hook -
Tableadd_hook -
Tabsadd_hook -
Widgetadd_hook -
Writewhen -
WriteCellTextwhen
-
-
-
xnano
Methods:
-
__and__–True when both predicates are true.
-
__or__–True when either predicate is true.
-
__invert__–True when the predicate is false.
-
__eq__–A predicate that is true when this condition has the same truth value as
other. -
__ne__–A predicate that is true when this condition has a different truth value than
other. -
__hash__–The identity hash, which keeps predicates usable in sets and dictionaries.
-
choose–A value that is
when_truewhile the condition holds andwhen_falseotherwise. -
evaluate–Compute the expression's value.
__and__
¶
__or__
¶
__invert__
¶
__invert__() -> Predicate
__eq__
¶
A predicate that is true when this condition has the same truth value as other.
Examples:
from xnano_core._xnano_core import Width
wide = Width > 4
assert Buffer(width=2, height=1).inspect(wide == False) # noqa: E712
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __eq__(self, other: object) -> Predicate: # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
"""
A predicate that is true when this condition has the same truth value as ``other``.
Examples:
```python
from xnano_core._xnano_core import Width
wide = Width > 4
assert Buffer(width=2, height=1).inspect(wide == False) # noqa: E712
```
"""
__ne__
¶
A predicate that is true when this condition has a different truth value than other.
Examples:
from xnano_core._xnano_core import Width
wide = Width > 4
assert Buffer(width=2, height=1).inspect(wide != True) # noqa: E712
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __ne__(self, other: object) -> Predicate: # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
"""
A predicate that is true when this condition has a different truth value than ``other``.
Examples:
```python
from xnano_core._xnano_core import Width
wide = Width > 4
assert Buffer(width=2, height=1).inspect(wide != True) # noqa: E712
```
"""
choose
¶
choose(when_true: NumberType, when_false: NumberType) -> NumericValue[NumberType]
choose(when_true: NumericValue[NumberType], when_false: NumericValue[NumberType] | NumberType) -> NumericValue[NumberType]
A value that is when_true while the condition holds and when_false otherwise.
Numbers give a NumericValue, so the result
supports arithmetic and ordering. Raises TypeError when evaluated if the predicate
is not a condition.
Examples:
from xnano_core._xnano_core import Width
wide = Width > 10
assert Buffer(width=20, height=1).inspect(wide.choose(1, 2)) == 1
assert Buffer(width=4, height=1).inspect(wide.choose(1, 2)) == 2
assert Buffer(width=4, height=1).inspect(wide.choose(Width, 0) + 1) == 1
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def choose(self, when_true: object, when_false: object) -> Value[object]:
"""
A value that is ``when_true`` while the condition holds and ``when_false`` otherwise.
Numbers give a [`NumericValue`][xnano_core._xnano_core.NumericValue], so the result
supports arithmetic and ordering. Raises ``TypeError`` when evaluated if the predicate
is not a condition.
Examples:
```python
from xnano_core._xnano_core import Width
wide = Width > 10
assert Buffer(width=20, height=1).inspect(wide.choose(1, 2)) == 1
assert Buffer(width=4, height=1).inspect(wide.choose(1, 2)) == 2
assert Buffer(width=4, height=1).inspect(wide.choose(Width, 0) + 1) == 1
```
"""
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
```
"""
Value
¶
Bases: Expression[ValueType]
An expression that evaluates to a value.
== and != build conditions, as equals and not_equals do. A comparison with a
value that has not been seen yet, such as the key before any key was pressed, is false
(!= included) and never an error. Comparing with the literal None raises TypeError
because that condition could never hold; to test that a key arrived, compare with the key
itself or register the hook for the 'key' event. A value is hashed by identity, so expressions stay usable
in sets and dictionaries. Because == builds a condition, in and .index() on a list
or tuple of expressions raise TypeError as soon as they compare an expression with a
different item; look an expression up by identity (any(item is value for item in items))
or keep expressions in a set or dictionary. Comparing an expression with an object that cannot
be an expression, such as object(), gives False for == and True for !=.
Attributes:
-
x(NumericValue[int]) –The column of a
Pointor the left edge of aRectangle. -
y(NumericValue[int]) –The row of a
Pointor the top edge of aRectangle. -
width(NumericValue[int]) –The width of a
Sizeor aRectangle. -
height(NumericValue[int]) –The height of a
Sizeor aRectangle. -
right(NumericValue[int]) –The first column after a
Rectangle. -
bottom(NumericValue[int]) –The first row after a
Rectangle.
Examples:
from xnano_core._xnano_core import _reference
bounds = _reference('Bounds', 'value')
assert isinstance(bounds, Value)
buffer = Buffer(width=4, height=1)
assert buffer.inspect(bounds.equals(Rectangle(0, 0, 4, 1)))
assert buffer.inspect(bounds == Rectangle(0, 0, 4, 1))
-
API Reference
xnano_core
-
xnano_core-
Bounds -
BufferRegion -
BufferSize -
Focused -
KeyboardBinding -
KeyboardKey -
KeyboardKind -
MouseButtonValue -
MouseKind -
MousePosition -
ParentSize -
PointerPosition -
Position -
Running -
ScreenBounds -
ScreenPosition -
BufferExpressionScope -
Canvas -
CanvasCircle -
CanvasLabel -
CanvasLine -
CanvasMap -
CanvasMarkermarker -
CanvasPointscolor -
CanvasRectangle -
KeyboardExpressionScope -
MouseExpressionScope -
ParentExpressionScopesize -
Predicatechoose -
StateReferencevalue
-
-
xnano_core._xnano_core
_xnano_core-
Bounds -
BufferRegion -
BufferSize -
Focused -
KeyboardBinding -
KeyboardKey -
KeyboardKind -
MouseButtonValue -
MouseKind -
MousePosition -
ParentSize -
PointerPosition -
Position -
Running -
ScreenBounds -
ScreenPosition -
BufferExpressionScope -
Canvas -
CanvasCircle -
CanvasLabel -
CanvasLine -
CanvasMap -
CanvasMarkermarker -
CanvasPointscolor -
CanvasRectangle -
KeyboardExpressionScope -
MouseExpressionScope -
ParentExpressionScopesize -
Predicatechoose -
StateReferencevalue
-
-
Methods:
-
equals–A predicate that is true when the value equals
other. -
not_equals–A predicate that is true when the value differs from
other. -
contains–A condition that is true while this rectangle contains the point
other. -
__eq__–A predicate that is true when the value equals
other; the same asequals. -
__ne__–A predicate that is true when the value differs from
other; the same asnot_equals. -
__hash__–The identity hash, which keeps expressions usable in sets and dictionaries.
-
evaluate–Compute the expression's value.
x
property
¶
x: NumericValue[int]
y
property
¶
y: NumericValue[int]
width
property
¶
width: NumericValue[int]
height
property
¶
height: NumericValue[int]
right
property
¶
right: NumericValue[int]
bottom
property
¶
bottom: NumericValue[int]
equals
¶
A predicate that is true when the value equals other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.equals(20))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def equals(self, other: ValueType | Value[ValueType]) -> Predicate:
"""
A predicate that is true when the value equals ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.equals(20))
```
"""
not_equals
¶
A predicate that is true when the value differs from other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.not_equals(5))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def not_equals(self, other: ValueType | Value[ValueType]) -> Predicate:
"""
A predicate that is true when the value differs from ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.not_equals(5))
```
"""
contains
¶
A condition that is true while this rectangle contains the point other.
It is false, never an error, while either side has no value yet, such as a mouse position before any mouse event.
Parameters:
-
other(Point | Value[Point] | Value[Point | None]) –The
Point(or an expression that produces one) to look for.
Examples:
from xnano_core._xnano_core import Bounds, Point
buffer = Buffer(width=4, height=2)
assert buffer.inspect(Bounds.contains(Point(3, 1)))
assert not buffer.inspect(Bounds.contains(Point(4, 1)))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def contains(
self: Value[Rectangle],
other: Point | Value[Point] | Value[Point | None],
) -> Predicate:
"""
A condition that is true while this rectangle contains the point ``other``.
It is false, never an error, while either side has no value yet, such as a mouse
position before any mouse event.
Args:
other: The ``Point`` (or an expression that produces one) to look for.
Examples:
```python
from xnano_core._xnano_core import Bounds, Point
buffer = Buffer(width=4, height=2)
assert buffer.inspect(Bounds.contains(Point(3, 1)))
assert not buffer.inspect(Bounds.contains(Point(4, 1)))
```
"""
__eq__
¶
A predicate that is true when the value equals other; the same as equals.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width == 20)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __eq__(self, other: object) -> Predicate: # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
"""
A predicate that is true when the value equals ``other``; the same as ``equals``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width == 20)
```
"""
__ne__
¶
A predicate that is true when the value differs from other; the same as not_equals.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width != 5)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __ne__(self, other: object) -> Predicate: # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
"""
A predicate that is true when the value differs from ``other``; the same as ``not_equals``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width != 5)
```
"""
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
```
"""
NumericValue
¶
Bases: Value[NumberType]
A numeric expression that supports comparisons and arithmetic.
Arithmetic and comparisons build new expressions instead of computing right away.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
buffer = Buffer(width=8, height=3)
assert buffer.inspect(width + 2) == 10
assert buffer.inspect(10 - width) == 2
assert buffer.inspect(width > 4)
assert buffer.inspect(-width) == -8
-
API Reference
-
xnano
xnano.devices
devicesBeatsposition -
xnano_core
-
xnano_core-
DeviceHeight -
DeviceWidth -
FPS -
Frame -
Height -
ParentHeight -
ParentWidth -
ScrollX -
ScrollY -
TimeDelta -
TimeDeltaMilliseconds -
TimeElapsed -
TimeElapsedMilliseconds -
Width -
X -
Y -
BufferExpressionScope -
NumericProperty -
NumericValue -
ParentExpressionScope -
Predicatechoose -
Property -
RootExpressionScope -
ScrollExpressionScope -
StateReferencenumber -
Value
-
-
xnano_core._xnano_core
_xnano_core-
DeviceHeight -
DeviceWidth -
FPS -
Frame -
Height -
ParentHeight -
ParentWidth -
ScrollX -
ScrollY -
TimeDelta -
TimeDeltaMilliseconds -
TimeElapsed -
TimeElapsedMilliseconds -
Width -
X -
Y -
BufferExpressionScope -
NumericProperty -
NumericValue -
ParentExpressionScope -
Predicatechoose -
Property -
RootExpressionScope -
ScrollExpressionScope -
StateReferencenumber -
Value
-
-
-
xnano
xnano.devices
Methods:
-
__lt__–A predicate that is true when the value is less than
other. -
__le__–A predicate that is true when the value is at most
other. -
__gt__–A predicate that is true when the value is greater than
other. -
__ge__–A predicate that is true when the value is at least
other. -
__add__–The sum of the value and
other. -
__sub__–The value minus
other. -
__mul__–The product of the value and
other. -
__truediv__–The value divided by
other. -
__mod__–The remainder of dividing the value by
other. -
__neg__–The value with its sign flipped.
-
__rtruediv__–otherdivided by the value. -
__rmod__–The remainder of dividing
otherby the value. -
__floordiv__–The value divided by
other, rounded toward negative infinity like Python's//. -
__rfloordiv__–otherdivided by the value, rounded toward negative infinity. -
__pow__–The value raised to the power
other. -
__rpow__–otherraised to the power of the value. -
__abs__–The absolute value.
-
__floor__–The value rounded down to a whole number, used by
math.floor. -
__ceil__–The value rounded up to a whole number, used by
math.ceil. -
__round__–The value rounded to the nearest whole number, halves away from zero.
-
minimum–The smaller of the value and
other. -
maximum–The larger of the value and
other. -
clamp–The value limited to the range from
lowesttohighest. -
evaluate–Compute the expression's value.
-
equals–A predicate that is true when the value equals
other. -
not_equals–A predicate that is true when the value differs from
other. -
contains–A condition that is true while this rectangle contains the point
other. -
__eq__–A predicate that is true when the value equals
other; the same asequals. -
__ne__–A predicate that is true when the value differs from
other; the same asnot_equals. -
__hash__–The identity hash, which keeps expressions usable in sets and dictionaries.
Attributes:
-
x(NumericValue[int]) –The column of a
Pointor the left edge of aRectangle. -
y(NumericValue[int]) –The row of a
Pointor the top edge of aRectangle. -
width(NumericValue[int]) –The width of a
Sizeor aRectangle. -
height(NumericValue[int]) –The height of a
Sizeor aRectangle. -
right(NumericValue[int]) –The first column after a
Rectangle. -
bottom(NumericValue[int]) –The first row after a
Rectangle.
x
property
¶
x: NumericValue[int]
y
property
¶
y: NumericValue[int]
width
property
¶
width: NumericValue[int]
height
property
¶
height: NumericValue[int]
right
property
¶
right: NumericValue[int]
bottom
property
¶
bottom: NumericValue[int]
__lt__
¶
__lt__(other: float | NumericValue[int] | NumericValue[float]) -> Predicate
A predicate that is true when the value is less than other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=3, height=1).inspect(width < 4)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __lt__(self, other: float | NumericValue[int] | NumericValue[float]) -> Predicate:
"""
A predicate that is true when the value is less than ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=3, height=1).inspect(width < 4)
```
"""
__le__
¶
__le__(other: float | NumericValue[int] | NumericValue[float]) -> Predicate
A predicate that is true when the value is at most other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width <= 4)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __le__(self, other: float | NumericValue[int] | NumericValue[float]) -> Predicate:
"""
A predicate that is true when the value is at most ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width <= 4)
```
"""
__gt__
¶
__gt__(other: float | NumericValue[int] | NumericValue[float]) -> Predicate
A predicate that is true when the value is greater than other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=5, height=1).inspect(width > 4)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __gt__(self, other: float | NumericValue[int] | NumericValue[float]) -> Predicate:
"""
A predicate that is true when the value is greater than ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=5, height=1).inspect(width > 4)
```
"""
__ge__
¶
__ge__(other: float | NumericValue[int] | NumericValue[float]) -> Predicate
A predicate that is true when the value is at least other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width >= 4)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __ge__(self, other: float | NumericValue[int] | NumericValue[float]) -> Predicate:
"""
A predicate that is true when the value is at least ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width >= 4)
```
"""
__add__
¶
__add__(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[float]
The sum of the value and other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width + 1) == 5
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __add__(
self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[float]:
"""
The sum of the value and ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width + 1) == 5
```
"""
__sub__
¶
__sub__(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[float]
The value minus other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width - 1) == 3
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __sub__(
self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[float]:
"""
The value minus ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width - 1) == 3
```
"""
__mul__
¶
__mul__(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[float]
The product of the value and other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
height = _reference('Height', 'numeric_property')
assert Buffer(width=4, height=3).inspect(width * height) == 12
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __mul__(
self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[float]:
"""
The product of the value and ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
height = _reference('Height', 'numeric_property')
assert Buffer(width=4, height=3).inspect(width * height) == 12
```
"""
__truediv__
¶
__truediv__(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[float]
The value divided by other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=8, height=1).inspect(width / 2) == 4.0
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __truediv__(
self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[float]:
"""
The value divided by ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=8, height=1).inspect(width / 2) == 4.0
```
"""
__mod__
¶
__mod__(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[float]
The remainder of dividing the value by other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=8, height=1).inspect(width % 3) == 2
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __mod__(
self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[float]:
"""
The remainder of dividing the value by ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=8, height=1).inspect(width % 3) == 2
```
"""
__neg__
¶
__neg__() -> NumericValue[NumberType]
__rtruediv__
¶
__rtruediv__(other: float) -> NumericValue[float]
__rmod__
¶
__rmod__(other: float) -> NumericValue[float]
The remainder of dividing other by the value.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
__floordiv__
¶
__floordiv__(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[int | float]
The value divided by other, rounded toward negative infinity like Python's //.
Dividing by zero raises ZeroDivisionError when the expression is evaluated.
Examples:
from xnano_core._xnano_core import Width
assert Buffer(width=7, height=1).inspect(Width // 2) == 3
assert Buffer(width=7, height=1).inspect(-Width // 2) == -4
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __floordiv__(
self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[int | float]:
"""
The value divided by ``other``, rounded toward negative infinity like Python's ``//``.
Dividing by zero raises ``ZeroDivisionError`` when the expression is evaluated.
Examples:
```python
from xnano_core._xnano_core import Width
assert Buffer(width=7, height=1).inspect(Width // 2) == 3
assert Buffer(width=7, height=1).inspect(-Width // 2) == -4
```
"""
__rfloordiv__
¶
__rfloordiv__(other: float) -> NumericValue[int | float]
other divided by the value, rounded toward negative infinity.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
__pow__
¶
__pow__(other: float | NumericValue[int] | NumericValue[float], modulo: None = None) -> NumericValue[int | float]
The value raised to the power other.
Whole-number results stay integers; a negative or fractional exponent gives a float.
Examples:
from xnano_core._xnano_core import Width
assert Buffer(width=3, height=1).inspect(Width**2) == 9
assert Buffer(width=4, height=1).inspect(Width**0.5) == 2.0
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __pow__(
self, other: float | NumericValue[int] | NumericValue[float], modulo: None = None
) -> NumericValue[int | float]:
"""
The value raised to the power ``other``.
Whole-number results stay integers; a negative or fractional exponent gives a float.
Examples:
```python
from xnano_core._xnano_core import Width
assert Buffer(width=3, height=1).inspect(Width**2) == 9
assert Buffer(width=4, height=1).inspect(Width**0.5) == 2.0
```
"""
__rpow__
¶
__rpow__(other: float, modulo: None = None) -> NumericValue[int | float]
other raised to the power of the value.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
__floor__
¶
__floor__() -> NumericValue[int]
__ceil__
¶
__ceil__() -> NumericValue[int]
__round__
¶
__round__(digits: None = None) -> NumericValue[int]
The value rounded to the nearest whole number, halves away from zero.
Unlike Python's round, a half rounds away from zero, so 2.5 becomes 3.
Passing a number of digits raises TypeError.
Examples:
from xnano_core._xnano_core import Width
assert Buffer(width=5, height=1).inspect(round(Width / 2)) == 3
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __round__(self, digits: None = None) -> NumericValue[int]:
"""
The value rounded to the nearest whole number, halves away from zero.
Unlike Python's ``round``, a half rounds away from zero, so ``2.5`` becomes ``3``.
Passing a number of digits raises ``TypeError``.
Examples:
```python
from xnano_core._xnano_core import Width
assert Buffer(width=5, height=1).inspect(round(Width / 2)) == 3
```
"""
minimum
¶
minimum(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[NumberType]
maximum
¶
maximum(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[NumberType]
clamp
¶
clamp(lowest: float | NumericValue[int] | NumericValue[float], highest: float | NumericValue[int] | NumericValue[float]) -> NumericValue[NumberType]
The value limited to the range from lowest to highest.
Raises TypeError when evaluated if lowest is greater than highest.
Examples:
from xnano_core._xnano_core import Width
assert Buffer(width=50, height=1).inspect(Width.clamp(0, 10)) == 10
assert Buffer(width=5, height=1).inspect(Width.clamp(8, 10)) == 8
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def clamp(
self,
lowest: float | NumericValue[int] | NumericValue[float],
highest: float | NumericValue[int] | NumericValue[float],
) -> NumericValue[NumberType]:
"""
The value limited to the range from ``lowest`` to ``highest``.
Raises ``TypeError`` when evaluated if ``lowest`` is greater than ``highest``.
Examples:
```python
from xnano_core._xnano_core import Width
assert Buffer(width=50, height=1).inspect(Width.clamp(0, 10)) == 10
assert Buffer(width=5, height=1).inspect(Width.clamp(8, 10)) == 8
```
"""
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
```
"""
equals
¶
A predicate that is true when the value equals other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.equals(20))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def equals(self, other: ValueType | Value[ValueType]) -> Predicate:
"""
A predicate that is true when the value equals ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.equals(20))
```
"""
not_equals
¶
A predicate that is true when the value differs from other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.not_equals(5))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def not_equals(self, other: ValueType | Value[ValueType]) -> Predicate:
"""
A predicate that is true when the value differs from ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.not_equals(5))
```
"""
contains
¶
A condition that is true while this rectangle contains the point other.
It is false, never an error, while either side has no value yet, such as a mouse position before any mouse event.
Parameters:
-
other(Point | Value[Point] | Value[Point | None]) –The
Point(or an expression that produces one) to look for.
Examples:
from xnano_core._xnano_core import Bounds, Point
buffer = Buffer(width=4, height=2)
assert buffer.inspect(Bounds.contains(Point(3, 1)))
assert not buffer.inspect(Bounds.contains(Point(4, 1)))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def contains(
self: Value[Rectangle],
other: Point | Value[Point] | Value[Point | None],
) -> Predicate:
"""
A condition that is true while this rectangle contains the point ``other``.
It is false, never an error, while either side has no value yet, such as a mouse
position before any mouse event.
Args:
other: The ``Point`` (or an expression that produces one) to look for.
Examples:
```python
from xnano_core._xnano_core import Bounds, Point
buffer = Buffer(width=4, height=2)
assert buffer.inspect(Bounds.contains(Point(3, 1)))
assert not buffer.inspect(Bounds.contains(Point(4, 1)))
```
"""
__eq__
¶
A predicate that is true when the value equals other; the same as equals.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width == 20)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __eq__(self, other: object) -> Predicate: # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
"""
A predicate that is true when the value equals ``other``; the same as ``equals``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width == 20)
```
"""
__ne__
¶
A predicate that is true when the value differs from other; the same as not_equals.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width != 5)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __ne__(self, other: object) -> Predicate: # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
"""
A predicate that is true when the value differs from ``other``; the same as ``not_equals``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width != 5)
```
"""
Operation
¶
Bases: Expression[None]
An action that changes a buffer, applied with Buffer.update.
Operations apply in argument order. update accepts operations only, not query
expressions. Combine operations with then and when.
Examples:
buffer = Buffer(width=8, height=1)
buffer.update(Write('hi'), Foreground('red'))
assert buffer.text.startswith('hi')
-
API Reference
-
xnano
-
xnano.effects
effects-
AudioEffectParameters -
BitCrushAudioEffectParameters -
CoalesceEffectParameters -
DarkenEffectParameters -
DelayAudioEffectParameters -
DissolveEffectParameters -
DistortionAudioEffectParameters -
EffectParameters -
EvolveEffectParameters -
EvolveFromEffectParameters -
EvolveIntoEffectParameters -
ExpandEffectParameters -
ExplodeEffectParameters -
FadeFromEffectParameters -
FadeToEffectParameters -
GlitchEffectParameters -
HighPassAudioEffectParameters -
HslShiftEffectParameters -
LightenEffectParameters -
LowPassAudioEffectParameters -
PaintEffectParameters -
ReverbAudioEffectParameters -
SaturateEffectParameters -
SleepEffectParameters -
SlideInEffectParameters -
SlideOutEffectParameters -
StretchEffectParameters -
SweepInEffectParameters -
SweepOutEffectParameters -
TremoloAudioEffectParameters
-
-
xnano.operations
operations
-
xnano.effects
-
xnano_core
-
xnano_core-
AnimateDrawing -
ApplyStatePatch -
ApplyStyle -
Background -
Border -
CancelEffect -
Conditional -
Customization -
Dissolve -
Draw -
Editor -
Effect -
Fade -
Fill -
Foreground -
Fuzz -
Glitch -
Layout -
Liveoperations -
Move -
Operation -
OperationChain -
Paste -
Pixels -
Place -
Raster -
Resize -
SequenceOperation -
SetState -
SetValue -
Write -
WriteCellText
-
-
xnano_core._xnano_core
_xnano_core-
AnimateDrawing -
ApplyStatePatch -
ApplyStyle -
Background -
Border -
CancelEffect -
Conditional -
Customization -
Dissolve -
Draw -
Editor -
Effect -
Fade -
Fill -
Foreground -
Fuzz -
Glitch -
Layout -
Liveoperations -
Move -
Operation -
OperationChain -
Paste -
Pixels -
Place -
Raster -
Resize -
SequenceOperation -
SetState -
SetValue -
Write -
WriteCellText
-
-
-
xnano
- API Reference
-
API Reference
-
xnano
-
xnano.ai
aiwatch -
xnano.devices
devicesScreen -
xnano.effects
effects-
AudioEffectParametersthen -
BitCrushAudioEffectParametersthen -
CoalesceEffectParametersthen -
DarkenEffectParametersthen -
DelayAudioEffectParametersthen -
DissolveEffectParametersthen -
DistortionAudioEffectParametersthen -
EffectParametersthen -
EvolveEffectParametersthen -
EvolveFromEffectParametersthen -
EvolveIntoEffectParametersthen -
ExpandEffectParametersthen -
ExplodeEffectParametersthen -
FadeFromEffectParametersthen -
FadeToEffectParametersthen -
GlitchEffectParametersthen -
HighPassAudioEffectParametersthen -
HslShiftEffectParametersthen -
LightenEffectParametersthen -
LowPassAudioEffectParametersthen -
PaintEffectParametersthen -
ReverbAudioEffectParametersthen -
SaturateEffectParametersthen -
SleepEffectParametersthen -
SlideInEffectParametersthen -
SlideOutEffectParametersthen -
StretchEffectParametersthen -
SweepInEffectParametersthen -
SweepOutEffectParametersthen -
TremoloAudioEffectParametersthen
-
-
xnano.layout
layoutPlacement -
xnano.operations
operations
-
xnano.ai
-
xnano_core
-
xnano_core-
AnimateDrawing -
ApplyStatePatch -
ApplyStyle -
Background -
BarChart -
Block -
Border -
Buffer -
Calendar -
CancelEffect -
Canvas -
Chart -
Clear -
Conditional -
CoreContextupdate -
CustomWidget -
Customizationthen -
Dissolve -
Draw -
Editor -
Effect -
EvaluationContextupdate -
EventContextupdate -
Fade -
Fill -
Foreground -
FrameContextupdate -
Fuzz -
Gauge -
Glitch -
ItemList -
Layout -
LineGauge -
Live -
Move -
Operation -
OperationChain -
Paragraph -
Paste -
Pixels -
Place -
Raster -
Region -
Resize -
Scrollbar -
SequenceOperation -
SetState -
SetValue -
Sparkline -
Surface -
Table -
Tabs -
UpdateContextupdate -
Widget -
Write -
WriteCellText
-
-
xnano_core._xnano_core
_xnano_core-
AnimateDrawing -
ApplyStatePatch -
ApplyStyle -
Background -
BarChart -
Block -
Border -
Buffer -
Calendar -
CancelEffect -
Canvas -
Chart -
Clear -
Conditional -
CustomWidget -
Customizationthen -
Dissolve -
Draw -
Editor -
Effect -
Fade -
Fill -
Foreground -
Fuzz -
Gauge -
Glitch -
ItemList -
Layout -
LineGauge -
Live -
Move -
Operation -
OperationChain -
Paragraph -
Paste -
Pixels -
Place -
Raster -
Region -
Resize -
Scrollbar -
SequenceOperation -
SetState -
SetValue -
Sparkline -
Surface -
Table -
Tabs -
Widget -
Write -
WriteCellText
-
-
xnano_core._xnano_core._core_types
_core_types
-
-
xnano
Methods:
-
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. -
evaluate–Compute the expression's value.
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__
¶
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
```
"""
Property
¶
Bases: Value[ValueType]
A reference to a concrete property of a buffer or runtime.
Reading it gives the current value. Calling it creates an assignment operation.
Attributes:
Examples:
from xnano_core._xnano_core import _reference
position = _reference('Position', 'property')
buffer = Buffer(width=4, height=1)
buffer.update(position(Point(3, 2)))
assert buffer.inspect(position) == Point(3, 2)
assert position.name == 'Position'
Methods:
-
__call__–An operation that assigns
valueto the property. -
evaluate–Compute the expression's value.
-
equals–A predicate that is true when the value equals
other. -
not_equals–A predicate that is true when the value differs from
other. -
contains–A condition that is true while this rectangle contains the point
other. -
__eq__–A predicate that is true when the value equals
other; the same asequals. -
__ne__–A predicate that is true when the value differs from
other; the same asnot_equals. -
__hash__–The identity hash, which keeps expressions usable in sets and dictionaries.
x
property
¶
x: NumericValue[int]
y
property
¶
y: NumericValue[int]
width
property
¶
width: NumericValue[int]
height
property
¶
height: NumericValue[int]
right
property
¶
right: NumericValue[int]
bottom
property
¶
bottom: NumericValue[int]
__call__
¶
An operation that assigns value to the property.
Examples:
from xnano_core._xnano_core import _reference
size = _reference('Size', 'property')
buffer = Buffer(width=4, height=1)
buffer.update(size(Size(6, 2)))
assert buffer.width == 6
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __call__(self, value: ValueType | Value[ValueType]) -> SetValue[ValueType]:
"""
An operation that assigns ``value`` to the property.
Examples:
```python
from xnano_core._xnano_core import _reference
size = _reference('Size', 'property')
buffer = Buffer(width=4, height=1)
buffer.update(size(Size(6, 2)))
assert buffer.width == 6
```
"""
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
```
"""
equals
¶
A predicate that is true when the value equals other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.equals(20))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def equals(self, other: ValueType | Value[ValueType]) -> Predicate:
"""
A predicate that is true when the value equals ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.equals(20))
```
"""
not_equals
¶
A predicate that is true when the value differs from other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.not_equals(5))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def not_equals(self, other: ValueType | Value[ValueType]) -> Predicate:
"""
A predicate that is true when the value differs from ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.not_equals(5))
```
"""
contains
¶
A condition that is true while this rectangle contains the point other.
It is false, never an error, while either side has no value yet, such as a mouse position before any mouse event.
Parameters:
-
other(Point | Value[Point] | Value[Point | None]) –The
Point(or an expression that produces one) to look for.
Examples:
from xnano_core._xnano_core import Bounds, Point
buffer = Buffer(width=4, height=2)
assert buffer.inspect(Bounds.contains(Point(3, 1)))
assert not buffer.inspect(Bounds.contains(Point(4, 1)))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def contains(
self: Value[Rectangle],
other: Point | Value[Point] | Value[Point | None],
) -> Predicate:
"""
A condition that is true while this rectangle contains the point ``other``.
It is false, never an error, while either side has no value yet, such as a mouse
position before any mouse event.
Args:
other: The ``Point`` (or an expression that produces one) to look for.
Examples:
```python
from xnano_core._xnano_core import Bounds, Point
buffer = Buffer(width=4, height=2)
assert buffer.inspect(Bounds.contains(Point(3, 1)))
assert not buffer.inspect(Bounds.contains(Point(4, 1)))
```
"""
__eq__
¶
A predicate that is true when the value equals other; the same as equals.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width == 20)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __eq__(self, other: object) -> Predicate: # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
"""
A predicate that is true when the value equals ``other``; the same as ``equals``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width == 20)
```
"""
__ne__
¶
A predicate that is true when the value differs from other; the same as not_equals.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width != 5)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __ne__(self, other: object) -> Predicate: # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
"""
A predicate that is true when the value differs from ``other``; the same as ``not_equals``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width != 5)
```
"""
NumericProperty
¶
Bases: NumericValue[NumberType]
A reference to a numeric property that can be read, computed with and assigned.
Attributes:
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
buffer = Buffer(width=4, height=1)
buffer.update(width(10))
assert buffer.width == 10
buffer.update(width(width * 2))
assert buffer.width == 20
Methods:
-
__call__–An operation that assigns
valueto the property. -
evaluate–Compute the expression's value.
-
equals–A predicate that is true when the value equals
other. -
not_equals–A predicate that is true when the value differs from
other. -
contains–A condition that is true while this rectangle contains the point
other. -
__eq__–A predicate that is true when the value equals
other; the same asequals. -
__ne__–A predicate that is true when the value differs from
other; the same asnot_equals. -
__hash__–The identity hash, which keeps expressions usable in sets and dictionaries.
-
__lt__–A predicate that is true when the value is less than
other. -
__le__–A predicate that is true when the value is at most
other. -
__gt__–A predicate that is true when the value is greater than
other. -
__ge__–A predicate that is true when the value is at least
other. -
__add__–The sum of the value and
other. -
__sub__–The value minus
other. -
__mul__–The product of the value and
other. -
__truediv__–The value divided by
other. -
__mod__–The remainder of dividing the value by
other. -
__neg__–The value with its sign flipped.
-
__rtruediv__–otherdivided by the value. -
__rmod__–The remainder of dividing
otherby the value. -
__floordiv__–The value divided by
other, rounded toward negative infinity like Python's//. -
__rfloordiv__–otherdivided by the value, rounded toward negative infinity. -
__pow__–The value raised to the power
other. -
__rpow__–otherraised to the power of the value. -
__abs__–The absolute value.
-
__floor__–The value rounded down to a whole number, used by
math.floor. -
__ceil__–The value rounded up to a whole number, used by
math.ceil. -
__round__–The value rounded to the nearest whole number, halves away from zero.
-
minimum–The smaller of the value and
other. -
maximum–The larger of the value and
other. -
clamp–The value limited to the range from
lowesttohighest.
x
property
¶
x: NumericValue[int]
y
property
¶
y: NumericValue[int]
width
property
¶
width: NumericValue[int]
height
property
¶
height: NumericValue[int]
right
property
¶
right: NumericValue[int]
bottom
property
¶
bottom: NumericValue[int]
__call__
¶
An operation that assigns value to the property.
Examples:
from xnano_core._xnano_core import _reference
height = _reference('Height', 'numeric_property')
buffer = Buffer(width=4, height=1)
buffer.update(height(3))
assert buffer.height == 3
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __call__(self, value: NumberType | Value[NumberType]) -> SetValue[NumberType]:
"""
An operation that assigns ``value`` to the property.
Examples:
```python
from xnano_core._xnano_core import _reference
height = _reference('Height', 'numeric_property')
buffer = Buffer(width=4, height=1)
buffer.update(height(3))
assert buffer.height == 3
```
"""
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
```
"""
equals
¶
A predicate that is true when the value equals other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.equals(20))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def equals(self, other: ValueType | Value[ValueType]) -> Predicate:
"""
A predicate that is true when the value equals ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.equals(20))
```
"""
not_equals
¶
A predicate that is true when the value differs from other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.not_equals(5))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def not_equals(self, other: ValueType | Value[ValueType]) -> Predicate:
"""
A predicate that is true when the value differs from ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width.not_equals(5))
```
"""
contains
¶
A condition that is true while this rectangle contains the point other.
It is false, never an error, while either side has no value yet, such as a mouse position before any mouse event.
Parameters:
-
other(Point | Value[Point] | Value[Point | None]) –The
Point(or an expression that produces one) to look for.
Examples:
from xnano_core._xnano_core import Bounds, Point
buffer = Buffer(width=4, height=2)
assert buffer.inspect(Bounds.contains(Point(3, 1)))
assert not buffer.inspect(Bounds.contains(Point(4, 1)))
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def contains(
self: Value[Rectangle],
other: Point | Value[Point] | Value[Point | None],
) -> Predicate:
"""
A condition that is true while this rectangle contains the point ``other``.
It is false, never an error, while either side has no value yet, such as a mouse
position before any mouse event.
Args:
other: The ``Point`` (or an expression that produces one) to look for.
Examples:
```python
from xnano_core._xnano_core import Bounds, Point
buffer = Buffer(width=4, height=2)
assert buffer.inspect(Bounds.contains(Point(3, 1)))
assert not buffer.inspect(Bounds.contains(Point(4, 1)))
```
"""
__eq__
¶
A predicate that is true when the value equals other; the same as equals.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width == 20)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __eq__(self, other: object) -> Predicate: # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
"""
A predicate that is true when the value equals ``other``; the same as ``equals``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width == 20)
```
"""
__ne__
¶
A predicate that is true when the value differs from other; the same as not_equals.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width != 5)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __ne__(self, other: object) -> Predicate: # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
"""
A predicate that is true when the value differs from ``other``; the same as ``not_equals``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=20, height=1).inspect(width != 5)
```
"""
__lt__
¶
__lt__(other: float | NumericValue[int] | NumericValue[float]) -> Predicate
A predicate that is true when the value is less than other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=3, height=1).inspect(width < 4)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __lt__(self, other: float | NumericValue[int] | NumericValue[float]) -> Predicate:
"""
A predicate that is true when the value is less than ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=3, height=1).inspect(width < 4)
```
"""
__le__
¶
__le__(other: float | NumericValue[int] | NumericValue[float]) -> Predicate
A predicate that is true when the value is at most other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width <= 4)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __le__(self, other: float | NumericValue[int] | NumericValue[float]) -> Predicate:
"""
A predicate that is true when the value is at most ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width <= 4)
```
"""
__gt__
¶
__gt__(other: float | NumericValue[int] | NumericValue[float]) -> Predicate
A predicate that is true when the value is greater than other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=5, height=1).inspect(width > 4)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __gt__(self, other: float | NumericValue[int] | NumericValue[float]) -> Predicate:
"""
A predicate that is true when the value is greater than ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=5, height=1).inspect(width > 4)
```
"""
__ge__
¶
__ge__(other: float | NumericValue[int] | NumericValue[float]) -> Predicate
A predicate that is true when the value is at least other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width >= 4)
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __ge__(self, other: float | NumericValue[int] | NumericValue[float]) -> Predicate:
"""
A predicate that is true when the value is at least ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width >= 4)
```
"""
__add__
¶
__add__(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[float]
The sum of the value and other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width + 1) == 5
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __add__(
self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[float]:
"""
The sum of the value and ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width + 1) == 5
```
"""
__sub__
¶
__sub__(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[float]
The value minus other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width - 1) == 3
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __sub__(
self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[float]:
"""
The value minus ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=4, height=1).inspect(width - 1) == 3
```
"""
__mul__
¶
__mul__(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[float]
The product of the value and other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
height = _reference('Height', 'numeric_property')
assert Buffer(width=4, height=3).inspect(width * height) == 12
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __mul__(
self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[float]:
"""
The product of the value and ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
height = _reference('Height', 'numeric_property')
assert Buffer(width=4, height=3).inspect(width * height) == 12
```
"""
__truediv__
¶
__truediv__(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[float]
The value divided by other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=8, height=1).inspect(width / 2) == 4.0
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __truediv__(
self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[float]:
"""
The value divided by ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=8, height=1).inspect(width / 2) == 4.0
```
"""
__mod__
¶
__mod__(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[float]
The remainder of dividing the value by other.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=8, height=1).inspect(width % 3) == 2
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __mod__(
self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[float]:
"""
The remainder of dividing the value by ``other``.
Examples:
```python
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
assert Buffer(width=8, height=1).inspect(width % 3) == 2
```
"""
__neg__
¶
__neg__() -> NumericValue[NumberType]
__rtruediv__
¶
__rtruediv__(other: float) -> NumericValue[float]
__rmod__
¶
__rmod__(other: float) -> NumericValue[float]
The remainder of dividing other by the value.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
__floordiv__
¶
__floordiv__(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[int | float]
The value divided by other, rounded toward negative infinity like Python's //.
Dividing by zero raises ZeroDivisionError when the expression is evaluated.
Examples:
from xnano_core._xnano_core import Width
assert Buffer(width=7, height=1).inspect(Width // 2) == 3
assert Buffer(width=7, height=1).inspect(-Width // 2) == -4
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __floordiv__(
self, other: float | NumericValue[int] | NumericValue[float]
) -> NumericValue[int | float]:
"""
The value divided by ``other``, rounded toward negative infinity like Python's ``//``.
Dividing by zero raises ``ZeroDivisionError`` when the expression is evaluated.
Examples:
```python
from xnano_core._xnano_core import Width
assert Buffer(width=7, height=1).inspect(Width // 2) == 3
assert Buffer(width=7, height=1).inspect(-Width // 2) == -4
```
"""
__rfloordiv__
¶
__rfloordiv__(other: float) -> NumericValue[int | float]
other divided by the value, rounded toward negative infinity.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
__pow__
¶
__pow__(other: float | NumericValue[int] | NumericValue[float], modulo: None = None) -> NumericValue[int | float]
The value raised to the power other.
Whole-number results stay integers; a negative or fractional exponent gives a float.
Examples:
from xnano_core._xnano_core import Width
assert Buffer(width=3, height=1).inspect(Width**2) == 9
assert Buffer(width=4, height=1).inspect(Width**0.5) == 2.0
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __pow__(
self, other: float | NumericValue[int] | NumericValue[float], modulo: None = None
) -> NumericValue[int | float]:
"""
The value raised to the power ``other``.
Whole-number results stay integers; a negative or fractional exponent gives a float.
Examples:
```python
from xnano_core._xnano_core import Width
assert Buffer(width=3, height=1).inspect(Width**2) == 9
assert Buffer(width=4, height=1).inspect(Width**0.5) == 2.0
```
"""
__rpow__
¶
__rpow__(other: float, modulo: None = None) -> NumericValue[int | float]
other raised to the power of the value.
Examples:
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
__floor__
¶
__floor__() -> NumericValue[int]
__ceil__
¶
__ceil__() -> NumericValue[int]
__round__
¶
__round__(digits: None = None) -> NumericValue[int]
The value rounded to the nearest whole number, halves away from zero.
Unlike Python's round, a half rounds away from zero, so 2.5 becomes 3.
Passing a number of digits raises TypeError.
Examples:
from xnano_core._xnano_core import Width
assert Buffer(width=5, height=1).inspect(round(Width / 2)) == 3
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def __round__(self, digits: None = None) -> NumericValue[int]:
"""
The value rounded to the nearest whole number, halves away from zero.
Unlike Python's ``round``, a half rounds away from zero, so ``2.5`` becomes ``3``.
Passing a number of digits raises ``TypeError``.
Examples:
```python
from xnano_core._xnano_core import Width
assert Buffer(width=5, height=1).inspect(round(Width / 2)) == 3
```
"""
minimum
¶
minimum(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[NumberType]
maximum
¶
maximum(other: float | NumericValue[int] | NumericValue[float]) -> NumericValue[NumberType]
clamp
¶
clamp(lowest: float | NumericValue[int] | NumericValue[float], highest: float | NumericValue[int] | NumericValue[float]) -> NumericValue[NumberType]
The value limited to the range from lowest to highest.
Raises TypeError when evaluated if lowest is greater than highest.
Examples:
from xnano_core._xnano_core import Width
assert Buffer(width=50, height=1).inspect(Width.clamp(0, 10)) == 10
assert Buffer(width=5, height=1).inspect(Width.clamp(8, 10)) == 8
Source code in packages/xnano-core/src/xnano_core/_xnano_core/__init__.pyi
def clamp(
self,
lowest: float | NumericValue[int] | NumericValue[float],
highest: float | NumericValue[int] | NumericValue[float],
) -> NumericValue[NumberType]:
"""
The value limited to the range from ``lowest`` to ``highest``.
Raises ``TypeError`` when evaluated if ``lowest`` is greater than ``highest``.
Examples:
```python
from xnano_core._xnano_core import Width
assert Buffer(width=50, height=1).inspect(Width.clamp(0, 10)) == 10
assert Buffer(width=5, height=1).inspect(Width.clamp(8, 10)) == 8
```
"""
SetValue
¶
SetValue(property: Property[ValueType] | NumericProperty[int] | NumericProperty[float], value: ValueType | Value[ValueType])
Bases: Operation, Generic[ValueType]
Assign a value to a property.
Calling a property creates the same operation, so width(10) and
SetValue(width, 10) are equivalent.
Parameters:
-
property(Property[ValueType] | NumericProperty[int] | NumericProperty[float]) –The property to assign.
-
value(ValueType | Value[ValueType]) –The new value, or an expression that computes it.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
buffer = Buffer(width=4, height=1)
buffer.update(SetValue(width, 9))
assert buffer.width == 9
Create a SetValue.
Parameters:
-
property(Property[ValueType] | NumericProperty[int] | NumericProperty[float]) –Property[ValueType] | NumericProperty[int] | NumericProperty[float]. -
value(ValueType | Value[ValueType]) –ValueType | Value[ValueType].
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,
property: Property[ValueType] | NumericProperty[int] | NumericProperty[float],
value: ValueType | Value[ValueType],
) -> None:
"""
Create a SetValue.
Args:
property: ``Property[ValueType] | NumericProperty[int] | NumericProperty[float]``.
value: ``ValueType | Value[ValueType]``.
"""
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__
¶
SequenceOperation
¶
SequenceOperation(*operations: Operation)
Bases: Operation
Apply several operations in order as one operation.
Parameters:
-
*operations(Operation, default:()) –The operations to apply.
Examples:
buffer = Buffer(width=6, height=1)
buffer.update(SequenceOperation(Clear(), Write('seq')))
assert buffer.text.startswith('seq')
Create a SequenceOperation.
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__
¶
Conditional
¶
Bases: Operation
Apply one operation when a condition is true and optionally another when it is not.
Parameters:
-
condition(Predicate) –The predicate to test each time the operation applies.
-
operation(Operation) –Applied when the condition is true.
-
otherwise(Operation | None, default:None) –Applied when the condition is false.
Examples:
from xnano_core._xnano_core import _reference
width = _reference('Width', 'numeric_property')
buffer = Buffer(width=6, height=1)
buffer.update(Conditional(width > 100, Write('big'), otherwise=Write('small')))
assert buffer.text.startswith('small')
Create a Conditional.
Parameters:
-
condition(Predicate) –Predicate. -
operation(Operation) –Operation. -
otherwise(Operation | None, default:None) –Operation | 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__
¶
Resize
¶
Bases: Operation
Resize the target buffer to width by height cells.
Existing content is kept where it still fits and cleared where the buffer grows.
Parameters:
Examples:
buffer = Buffer(width=10, height=3)
buffer.update(Resize(6, 2))
assert (buffer.width, buffer.height) == (6, 2)
Create a Resize.
Parameters:
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__
¶
Move
¶
Bases: Operation
Move the target buffer relative to its current position in its parent.
Parameters:
-
x(int, default:0) –Columns to move right; negative values move left.
-
y(int, default:0) –Rows to move down; negative values move up.
Examples:
buffer = Buffer(width=4, height=1, x=2, y=1)
buffer.update(Move(1, 1))
assert (buffer.x, buffer.y) == (3, 2)
buffer.update(Move(x=-2, y=-1))
assert (buffer.x, buffer.y) == (1, 1)
Create a Move.
Parameters:
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__
¶
Place
¶
Bases: Operation
Move the target buffer to an absolute position in its parent.
Parameters:
Examples:
Create a Place.
Parameters:
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__
¶
Write
¶
Write(text: TextContent, *, x: int = 0, y: int = 0, style: Style | None = None, mode: WriteMode = 'replace')
Bases: Operation
Write text into the target at a cell position.
Text is clipped by display columns, whole graphemes are preserved and wide characters repair their continuation cells.
Parameters:
-
text(TextContent) –A string, a
StyledTextor a sequence of both. -
x(int, default:0) –The first column to write to.
-
y(int, default:0) –The row to write to.
-
style(Style | None, default:None) –The style applied to the written cells.
-
mode(WriteMode, default:'replace') –'replace'overwrites the cell style;'preserve_background'keeps the background that is already in the cell.
Examples:
buffer = Buffer(width=8, height=2)
buffer.update(Write('hi', x=1, y=1, style=Style('red')))
assert buffer.render(format='text').split('\n')[1].strip() == 'hi'
assert buffer[1, 1].foreground.to_rgb() is None
assert str(buffer[1, 1].foreground) == "Color('red')"
painted = Buffer(width=3, height=1)
painted.update(Write('a', style=Style('red', 'blue')))
painted.update(Write('b', mode='preserve_background', style=Style('green')))
assert str(painted[0, 0].background) == "Color('blue')"
Create a Write.
Parameters:
-
text(TextContent) –TextContent. -
x(int, default:0) –int. Defaults to0. -
y(int, default:0) –int. Defaults to0. -
style(Style | None, default:None) –Style | None. Defaults toNone. -
mode(WriteMode, default:'replace') –WriteMode. Defaults to'replace'.
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,
text: TextContent,
*,
x: int = 0,
y: int = 0,
style: Style | None = None,
mode: WriteMode = 'replace',
) -> None:
"""
Create a Write.
Args:
text: ``TextContent``.
x: ``int``. Defaults to ``0``.
y: ``int``. Defaults to ``0``.
style: ``Style | None``. Defaults to ``None``.
mode: ``WriteMode``. Defaults to ``'replace'``.
"""
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__
¶
WriteCellText
¶
WriteCellText(text: TextContent, *, column: int = 0, row: int = 0, style: Style | None = None, mode: WriteMode = 'replace')
Bases: Write
Write text addressed by column and row instead of x and y.
It behaves exactly like Write; use it when the position
is a cell index rather than a coordinate.
Parameters:
-
text(TextContent) –A string, a
StyledTextor a sequence of both. -
column(int, default:0) –The first column to write to.
-
row(int, default:0) –The row to write to.
-
style(Style | None, default:None) –The style applied to the written cells.
-
mode(WriteMode, default:'replace') –'replace'or'preserve_background'.
Examples:
buffer = Buffer(width=6, height=1)
buffer.update(WriteCellText('ab', column=2))
assert buffer.text.strip() == 'ab'
assert buffer[2, 0].symbol == 'a'
Create a WriteCellText.
Parameters:
-
text(TextContent) –TextContent. -
column(int, default:0) –int. Defaults to0. -
row(int, default:0) –int. Defaults to0. -
style(Style | None, default:None) –Style | None. Defaults toNone. -
mode(WriteMode, default:'replace') –WriteMode. Defaults to'replace'.
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,
text: TextContent,
*,
column: int = 0,
row: int = 0,
style: Style | None = None,
mode: WriteMode = 'replace',
) -> None:
"""
Create a WriteCellText.
Args:
text: ``TextContent``.
column: ``int``. Defaults to ``0``.
row: ``int``. Defaults to ``0``.
style: ``Style | None``. Defaults to ``None``.
mode: ``WriteMode``. Defaults to ``'replace'``.
"""