Terminal Interface
Interface
-
class Backend : public std::enable_shared_from_this<Backend>
The interface to the underlying platform.
This library expects that the platform implementation correctly handles UTF-8 encoding and VT100 ANSI control codes.
Subclassed by erbsland::cterm::impl::PosixBackend, erbsland::cterm::impl::WindowsBackend
Public Functions
-
virtual void initializePlatform() = 0
Initialize the platform.
This method is called from
Terminal::initializeScreen().
-
virtual void restorePlatform() = 0
Restore the platform.
This method is called from
Termina::restoreScreen().
-
virtual bool supportsColorCodes() const noexcept = 0
Test if the platform supports color output.
This just tests for color support, not cursor movement. If you return
false, no ANSI color codes are emitted and the line buffer is disabled. Instead, theemitColor()method is called on the backend.Note
Before each call to
emitColor(), the text from the line buffer is emitted.
-
virtual bool supportsCursorCodes() const noexcept = 0
Test if the platform supports cursor movement.
This includes cursor position, clearing the terminal and other cursor-related operations. If you return
false, no cursor movement commands are emitted and the line buffer is disabled. Instead, themoveCursor()etc. methods are called on the backend.Note
Before each call of the cursor methods, the text from the line buffer is emitted.
-
inline virtual bool supportsCursorVisibilityCodes() const noexcept
Test if the backend supports cursor visible/invisible ANSI sequences.
If this method returns
true, the ANSI codesESC[?25landESC[?25hto control the cursor visibility. If it returnsfalse,TerminalcallssetCursorVisible()instead.
-
inline virtual bool supportsAlternateScreenBufferCodes() const noexcept
Test if the backend supports alternate screen buffer codes.
If this method returns
true, the ANSI codesESC[?1049handESC[?1049lare sent to the backend to switch to the alternate screen buffer. AdditionallysetAlternateScreenBuffer()is called to notify the backend about the change. If this method returnsfalse,Terminalonly callssetAlternateScreenBuffer()instead.
-
virtual bool isInteractive() const noexcept = 0
Check if an interactive terminal is attached to the process.
This state is typically established during
Terminal::initializeScreen().- Returns:
trueif interactive terminal features such as resize and cursor control are available.
-
virtual std::optional<block::Size> detectScreenSize() = 0
Detect the current terminal screen size.
This method is invoked by
Terminal::initializeScreen()andTerminal::testScreenSize()when size detection is enabled. Interactive applications may calltestScreenSize()before every screen update, so implementations should be efficient or perform updates asynchronously in the background.The returned size should represent the visible terminal area available for output. A safety margin of one column and one row is applied by
Terminalautomatically.- Returns:
The detected screen size, or
std::nulloptif detection failed.
-
inline virtual void emitColor(Color color)
Change the current color.
Only called if
supportsColorCodes()returnsfalse.- Parameters:
color – The new color to set.
-
inline virtual BlockAttributes supportedBlockAttributes() const noexcept
Get the character attributes supported by this backend.
The returned value is a fully specified bit mask.
- Returns:
The supported character attributes.
-
inline virtual BlockAttributes supportedBlockAttributeCodes() const noexcept
Get the character attributes that can be emitted directly via ANSI codes.
The returned value is a fully specified bit mask.
- Returns:
The character attributes supported through ANSI codes.
-
inline virtual void emitBlockAttributes(BlockAttributes attributes)
Change the current character attributes.
Only called if one or more supported attributes cannot be emitted through ANSI codes. The backend receives the current supported attribute state and can diff it against its own local state.
- Parameters:
attributes – The current supported attribute state.
-
inline virtual void moveCursor(block::Position posOrDelta, MoveMode mode)
Move the cursor.
Only called if
supportsCursorCodes()returnsfalse.- Parameters:
posOrDelta – The absolute or relative movement for the cursor. (0,0) = top-left corner.
mode – The move mode, either absolute or relative.
-
inline virtual void clearScreen()
Clear the screen and move the cursor to (0,0).
Only called if
supportsCursorCodes()returnsfalse.
-
inline virtual void setCursorVisible(bool visible)
Control if the cursor is visible on the terminal.
If
supportsCursorVisibilityCodes()returnsfalse, this method is called to control the cursor visibility.
-
inline virtual void setAlternateScreenBuffer(bool enabled)
Enables/disables the alternate screen buffer or notifies the backend about the change.
-
virtual void emitText(const text::String &text) = 0
Emit the given UTF-8 encoded text.
If the backend does not support UTF-8, you are responsible to convert the text to the expected encoding. Line breaks are usually just NL and not CRLF. UTF-8 sequences, and ANSI sequences are always complete in one call of this method.
- Parameters:
text – The UTF-8 encoded text to emit.
-
virtual void emitFlush() = 0
Flush the output buffer.
After a call of this method, the backend must flush all previously emitted text and control sequences to the terminal.
-
virtual void setInputMode(Input::Mode mode) = 0
Set the current input mode.
- Parameters:
mode – The new input mode.
-
virtual Key readKey(std::chrono::milliseconds timeout) = 0
Read one key event without blocking longer than the given timeout.
In
Input::Mode::Key, negative timeouts must be normalized to zero and any timeout less than or equal to zero must perform a non-blocking poll. InInput::Mode::ReadLine, the timeout is ignored and this call may block until a line was entered.- Parameters:
timeout – Maximum wait time in
Mode::Key.- Returns:
The parsed key event, or an invalid key if no supported input was read before the timeout expired.
-
virtual Key waitForKey() = 0
Wait until one key event is available.
In
Input::Mode::ReadLine, this call blocks until a line was entered and returns the converted key.- Returns:
The parsed key event.
-
virtual text::String readLine() = 0
Read text input in the terminal.
Can be ignored in
Input::Mode::Keymode.- Returns:
The read text, without line breaks.
-
inline virtual void purgePendingInput() noexcept
Securely discard pending key input and partial native decoder state.
Public Static Functions
-
static BackendPtr createPlatformDefault(TerminalFlags terminalFlags)
Create the default backend for this platform.
-
virtual void initializePlatform() = 0
-
class Bitmap
A mutable bitmap storing boolean pixels in row-major order.
Subclassed by erbsland::cterm::FontGlyph
Public Functions
-
Bitmap() = default
Create an empty bitmap with the size
(0,0).
-
inline explicit Bitmap(const block::Size size)
Create a bitmap with the given size and all pixels cleared.
- Parameters:
size – The bitmap dimensions. The size is limited to 4096x4096 (cMaximumBitmapSize).
-
inline const std::vector<bool> &data() const noexcept
Access the raw pixel storage.
-
inline std::vector<bool> &data() noexcept
Access the raw pixel storage for modification.
-
bool pixel(block::Position pos) const noexcept
Read one pixel.
- Parameters:
pos – The pixel position.
- Returns:
The pixel state, or
falseifposis outside the bitmap.
-
uint8_t pixelQuad(block::Position pos) const noexcept
Read a 2x2 pixel block encoded as four bits.
- Parameters:
pos – The quad position in half-resolution coordinates.
- Returns:
Bit mask with top-left/top-right/bottom-left/bottom-right pixels in bits
0..3.
-
uint8_t pixelCardinal(block::Position pos) const noexcept
Read the four cardinal pixels as a bit-mask.
Clockwise bit-order: right, down, left, up
- Parameters:
pos – The center pixel position.
- Returns:
The bit mask, where bits
0..3represent the pixels in clockwise order starting from the right.
-
uint8_t pixelRing(block::Position pos) const noexcept
Read the ring of eight pixels surrounding the given position as a bitmask.
Clockwise bit-order: 0:E, 1:SE, 2:S, 3:SW, 4:W, 5:NW, 6:N, 7:NE
- Parameters:
pos – The center pixel position.
- Returns:
The bit mask, where bits
0..7represent the pixels in clockwise order starting from the right.
-
block::Rectangle boundingRect(bool value = true) const noexcept
Get a rectangle around all set/cleared pixels.
- Parameters:
value – If true, return the bounding box of set pixels, otherwise cleared pixels.
- Returns:
The bounding rectangle of the specified pixels or an empty rectangle if none are set/cleared.
-
std::size_t pixelCount(bool value = true) const noexcept
Get the number of set/cleared pixels in this bitmap.
- Parameters:
value – The pixel type to count.
-
void setPixel(block::Position pos, bool value) noexcept
Set one pixel in the bitmap.
Note
Positions outside the bitmap are ignored.
- Parameters:
pos – The pixel position.
value – The new pixel state.
-
void flipHorizontal() noexcept
Mirror the bitmap horizontally in-place.
-
void invert() noexcept
Invert the bitmap in-place.
-
Bitmap inverted() const noexcept
Get an inverted version of this bitmap.
- Returns:
The inverted bitmap.
-
Bitmap outlined() const noexcept
Convert this bitmap to an outlined version.
The bitmap needs to have a margin large enough for the outline. Algorithm: If at a cleared source pixel is surrounded by at least one set pixel, the target pixel is set.
-
Bitmap expanded(block::Margins margins, bool value) const noexcept
Create a new bitmap expanded with a given margin.
Negative margins cut sections from the bitmap.
- Parameters:
margins – The margins for the expansion.
value – The value to fill the expanded area with.
- Returns:
The expanded/shrunk bitmap. If the new width or height is zero, an empty bitmap is returned.
-
template<typename T>
void draw(block::Position position, const std::vector<T> &data) noexcept Draw pixels from a numeric bit mask.
Draw bit-mask rows at the given position.
- Template Parameters:
T – The unsigned integer type.
T – The unsigned integer type storing each row.
- Parameters:
position – The top left corner where to draw the bit mask.
data – The array with the data.
position – The top-left corner where to draw.
data – The rows to draw.
-
inline void draw(const block::Position position, const Bitmap &bitmap) noexcept
Draw another bitmap to the given position.
- Parameters:
position – The top left corner of the bitmap to draw.
bitmap – The bitmap to draw.
-
void fillRect(block::Rectangle rect, bool value) noexcept
Fill a rectangle with a given pixel state.
Positions outside this bitmap are ignored.
- Parameters:
rect – The rectangle to fill.
value – The new pixel state.
-
void floodFill(block::Position pos, bool value) noexcept
Perform a flood fill from the given position.
If the pixel at the given position is already set to the given value, nothing happens. If the start position is outside the bitmap, nothing happens.
- Parameters:
pos – The start position.
value – The new pixel state.
Public Static Functions
-
template<typename Fn>
static inline Bitmap fromFunction(const block::Size size, Fn fn) noexcept Build a new bitmap using a function.
- Parameters:
size – The size of the new bitmap.
fn – The function to use for building the bitmap. Takes a position and returns a boolean.
- Returns:
The new bitmap.
-
static Bitmap fromPattern(std::initializer_list<text::String> rows)
Create a bitmap from an ASCII pattern.
Each input string becomes one row. Dots (
.) and spaces create cleared pixels, every other character sets a pixel. Shorter rows are padded with cleared pixels to the maximum row width.- Parameters:
rows – The pattern rows to parse.
- Returns:
The created bitmap.
-
Bitmap() = default
-
enum class erbsland::cterm::BitmapColorMode : uint8_t
The mode how color is applied to the bitmap.
Values:
-
enumerator OneColor
Uses one color from the sequence for the whole bitmap.
The selected sequence entry is
animationCycle + colorAnimationOffset.
-
enumerator VerticalStripes
Uses the color sequence in vertical stripes.
The selected sequence entry is
x + animationCycle + colorAnimationOffset.
-
enumerator HorizontalStripes
Uses the color sequence in horizontal stripes.
The selected sequence entry is
y + animationCycle + colorAnimationOffset.
-
enumerator ForwardDiagonalStripes
Uses the color sequence in forward diagonal stripes.
The selected sequence entry is
x + y + animationCycle + colorAnimationOffset.
-
enumerator BackwardDiagonalStripes
Uses the color sequence in backward diagonal stripes.
The selected sequence entry is
-x + y + animationCycle + colorAnimationOffset.
-
enumerator OneColor
-
class BitmapDrawOptions
The options to draw a bitmap.
These options define how
Buffer::drawBitmap()converts bitmap pixels into terminal cells. For color animation and stripe modes, the color position is calculated in the rendered bitmap grid:FullBlock,DoubleBlock, andBlock16Styleuse one logical position per bitmap pixel, whileHalfBlockuses one logical position per 2x2 pixel cell. The rectangle overload ofdrawBitmap()aligns this rendered grid inside the target rectangle and crops it if needed.Note
Creating custom option instances is expensive. For that reason, create them once and keep the instances for multiple
drawBitmapcalls.Public Functions
-
BitmapDrawOptions() = default
Create default bitmap draw options.
-
template<typename tColor>
inline explicit BitmapDrawOptions(tColor color) Create options for one fixed color.
- Parameters:
color – The base color for the bitmap.
-
BitmapDrawOptions(ColorSequence colorSequence, BitmapColorMode colorMode = BitmapColorMode::OneColor)
Create options from a color sequence.
- Parameters:
colorSequence – The base colors for the bitmap.
colorMode – The mode used to pick colors from the sequence.
-
const ColorSequence &color() const noexcept
The color to use for drawing the bitmap.
The color can be either a single color or a sequence of colors. If this is an empty sequence, the color is inherited from the buffer. Colors are applied using the
colorMode(). If the characters infullBlock(),doubleBlocks()orhalfBlocks()have colors set, these colors are overlaid after calculating this base color.Note
For full-block and double-block mode, the background color is only applied to set pixels. Fill the bitmap area if you need a custom background color for unset pixels.
-
void setColor(Color color) noexcept
Set a single color.
Replaces the current color sequence with one entry.
-
void setColor(Foreground foreground, Background background) noexcept
Set explicit foreground and background colors.
-
void setColorSequence(ColorSequence colorSequence, BitmapColorMode colorMode = BitmapColorMode::OneColor) noexcept
Set a color sequence.
Pass an empty
ColorSequence{}to inherit the complete color from the buffer below.
-
BitmapColorMode colorMode() const noexcept
The color mode.
This mode controls how colors are applied to the bitmap. See
BitmapColorModefor more information.
-
void setColorMode(BitmapColorMode colorMode) noexcept
Set the color mode.
-
std::size_t colorAnimationOffset() const noexcept
The offset for color animations.
This offset is added to the
animationCyclepassed todrawBitmap. AnimateanimationCycleand keep this offset static.
-
void setColorAnimationOffset(std::size_t offset) noexcept
Set the offset for color animations.
-
const Block16StylePtr &block16Style() const noexcept
The Block16Style instance.
If a Block16Style instance is set, it overrides the scale mode and renders one terminal cell for each set bitmap pixel. The selected block depends on the four direct neighbors of the set pixel: east=bit 0, south=bit 1, west=bit 2, north=bit 3.
-
void setBlock16Style(Block16StylePtr block16Style) noexcept
Set a Block16Style instance.
-
const BlockCombinationStylePtr &combinationStyle() const noexcept
The combination style.
If a combination style is set, every block that is set in the buffer is first passed to this combination style. This happens for every mode used to draw the bitmap.
-
void setCombinationStyle(BlockCombinationStylePtr combinationStyle) noexcept
Set the combination style.
-
const Block &fullBlock() const noexcept
The full block.
The full block is only used when the scale mode
FullBlockis used and noBlock16Styleis set. Character colors are overlaid on the color from the color mode.
-
void setFullBlock(Block fullBlock)
Set the full block.
The full block must have a display width of 1.
-
const BlockString &doubleBlocks() const noexcept
The double blocks.
The double blocks are only used when the scale mode
DoubleBlockis used and noBlock16Styleis set. Character index 0 is used for the left half and index 1 for the right half of each set bitmap pixel. Character colors are overlaid on the color from the color mode.
-
void setDoubleBlocks(BlockString doubleBlocks)
Set the double block BlockString.
The string must have exactly two characters.
-
const BlockString &halfBlocks() const noexcept
The string with the half-blocks.
The half-blocks are only used when the scale mode
HalfBlockis used and noBlock16Styleis set. Entry0is used for an empty 2x2 block and entry15for a full 2x2 block. Character colors are overlaid on the color from the color mode.
-
void setHalfBlocks(BlockString halfBlocks)
Set the half-blocks string.
The half-blocks string must have exactly 16 characters.
-
BitmapScaleMode scaleMode() const noexcept
The scale mode.
See
BitmapScaleModefor more details.
-
void setScaleMode(BitmapScaleMode scaleMode) noexcept
Set the scale mode.
Public Static Functions
-
static const BitmapDrawOptions &defaultOptions() noexcept
Access the shared object with the default options.
Default options use default terminal colors, half-block rendering, and the standard Unicode half-block characters.
-
BitmapDrawOptions() = default
-
enum class erbsland::cterm::BitmapScaleMode : uint8_t
The mode how the bitmap is scaled.
Values:
-
enumerator HalfBlock
Draw the bitmap with half-blocks.
This mode uses the 16 characters from
halfBlocks(). Each 2x2 pixel block creates a 4-bit index in this order: bit 0 = top-left, bit 1 = top-right, bit 2 = bottom-left, bit 3 = bottom-right. This renders the bitmap at half width and half height, rounded up. Character colors are overlaid on the color from the color mode.
-
enumerator FullBlock
Draw the bitmap with full-blocks.
This mode uses
fullBlock()to draw each set pixel of the bitmap. Character colors are overlaid on the color from the color mode. To color the unset pixels, you must fill the bitmap area first.
-
enumerator DoubleBlock
Draw the bitmap with double-blocks.
This mode uses
doubleBlocks()to draw each set pixel of the bitmap. The bitmap is twice as large in the X axis, to compensate for the rectangular shape of terminal characters. Character colors are overlaid on the color from the color mode. To color the unset pixels, you must fill the bitmap area first.
-
enumerator HalfBlock
-
class Block
Represents a character string with combined terminal style information.
Used by the UI code to render colored text blocks on the console.
Public Functions
-
constexpr Block() noexcept = default
Construct an empty block character using inherited colors.
-
inline explicit constexpr Block(const text::Char character) noexcept
Construct a block character from a single Unicode code point using inherited colors.
- Parameters:
character – The base Unicode code point.
-
inline explicit Block(const text::String &charStr) noexcept
Construct a block character with inherited colors.
- Parameters:
charStr – The UTF-8 encoded text to display. Invalid or unsupported text normalizes deterministically to a single renderable character. Empty input, control codes, and leading zero-width code points normalize to
U+FFFD. Later visible code points also collapse the result toU+FFFD, while a third combining mark is ignored.
-
inline explicit Block(const text::U32String &charStr) noexcept
Construct a block character with inherited colors.
- Parameters:
charStr – The UTF-32 encoded text to display. Invalid or unsupported text normalizes deterministically to a single renderable character. Empty input, control codes, invalid Unicode scalar values, and leading zero-width code points normalize to
U+FFFD. Later visible code points also collapse the result toU+FFFD, while a third combining mark is ignored.
-
inline constexpr Block(const text::Char character, const BlockStyle style) noexcept
Construct a block character from a single Unicode code point with explicit style.
- Parameters:
character – The base Unicode code point.
style – The style for the character.
-
inline constexpr Block(const text::Char character, const Color color, const BlockAttributes attributes) noexcept
Construct a block character from a single Unicode code point with explicit color and attributes.
- Parameters:
character – The base Unicode code point.
color – The color for the character.
attributes – The character attributes.
-
inline explicit Block(const text::String &charStr, BlockStyle style) noexcept
Construct a block character with explicit text and style.
- Parameters:
charStr – The UTF-8 encoded text to display.
style – The style for the character. Invalid or unsupported text normalizes deterministically to a single renderable character. Empty input, control codes, and leading zero-width code points normalize to
U+FFFD. Later visible code points also collapse the result toU+FFFD, while a third combining mark is ignored.
-
inline explicit Block(const text::String &charStr, const Color color, const BlockAttributes attributes) noexcept
Construct a block character with explicit text, color, and attributes.
- Parameters:
charStr – The UTF-8 encoded text to display.
color – The color for the character.
attributes – The character attributes. Invalid or unsupported text normalizes deterministically to a single renderable character. Empty input, control codes, and leading zero-width code points normalize to
U+FFFD. Later visible code points also collapse the result toU+FFFD, while a third combining mark is ignored.
-
inline explicit Block(const text::U32String &charStr, const BlockStyle style) noexcept
Construct a block character with explicit text and style.
- Parameters:
charStr – The UTF-32 encoded text to display.
style – The style for the character. Invalid or unsupported text normalizes deterministically to a single renderable character. Empty input, control codes, invalid Unicode scalar values, and leading zero-width code points normalize to
U+FFFD. Later visible code points also collapse the result toU+FFFD, while a third combining mark is ignored.
-
inline explicit Block(const text::U32String &charStr, const Color color, const BlockAttributes attributes) noexcept
Construct a block character with explicit text, color, and attributes.
- Parameters:
charStr – The UTF-32 encoded text to display.
color – The color for the character.
attributes – The character attributes. Invalid or unsupported text normalizes deterministically to a single renderable character. Empty input, control codes, invalid Unicode scalar values, and leading zero-width code points normalize to
U+FFFD. Later visible code points also collapse the result toU+FFFD, while a third combining mark is ignored.
-
template<typename ...tColorArgs>
inline constexpr Block(const text::Char character, tColorArgs... color) noexcept Construct a block character from a single Unicode code point and a color.
- Parameters:
character – The base Unicode code point.
color – The color for the character.
-
template<typename ...tColorArgs>
inline explicit Block(const text::String &charStr, tColorArgs... color) noexcept Construct a block character with explicit text and colors.
- Parameters:
charStr – The UTF-8 encoded text to display.
color – The color for the character. Invalid or unsupported text normalizes deterministically to a single renderable character. Empty input, control codes, and leading zero-width code points normalize to
U+FFFD. Later visible code points also collapse the result toU+FFFD, while a third combining mark is ignored.
-
template<typename ...tColorArgs>
inline explicit Block(const text::U32String &charStr, tColorArgs... color) noexcept Construct a block character with explicit text and colors.
- Parameters:
charStr – The UTF-32 encoded text to display.
color – The color for the character. Invalid or unsupported text normalizes deterministically to a single renderable character. Empty input, control codes, invalid Unicode scalar values, and leading zero-width code points normalize to
U+FFFD. Later visible code points also collapse the result toU+FFFD, while a third combining mark is ignored.
-
inline bool operator==(const Block &other) const noexcept
Compare two terminal characters for equality.
-
inline bool operator!=(const Block &other) const noexcept
Compare two terminal characters for inequality.
-
inline bool operator==(const text::Char other) const noexcept
Compare just a single-code point character, without the color.
-
inline bool operator!=(const text::Char other) const noexcept
Compare just a single-code point character, without the color.
-
inline text::String toString() const
Convert the stored character sequence to UTF-8 text.
- Returns:
A UTF-8 encoded copy of the stored character sequence.
-
inline text::U32String toU32String() const
Convert the stored character sequence to UTF-32 text.
- Returns:
A UTF-32 encoded copy of the stored character sequence.
-
inline constexpr text::Char first() const noexcept
Get the leading Unicode code point.
- Returns:
The base code point, or
0if this character is empty.
-
inline constexpr text::Char singleOrNull() const noexcept
Get a single Unicode code point or zero for combined or empty characters.
This is a fast-path method for comparing a single-code point character, without the color.
- Returns:
The single code point, or
0if this character is combined or empty.
-
inline constexpr const text::CombinedChar::Storage &characters() const noexcept
Get the stored Unicode code points.
Unused entries are set to
0.
-
inline constexpr unit::CpLength characterCount() const noexcept
Get the number of stored Unicode code points.
-
inline BlockAttributes attributes() const noexcept
Get the character attributes.
-
inline const BlockStyle &style() const noexcept
Get the combined character style.
-
inline int displayWidth() const noexcept
Get the display width on a terminal in cells.
-
inline unit::ByteLength byteCount() const noexcept
Get the number of UTF-8 bytes needed to encode this character.
-
inline void setStyle(const BlockStyle style) noexcept
Replace the full style of this character.
- Parameters:
style – The new style.
-
Block withCombining(text::Char codePoint) const noexcept
Create a character with an additional combining code point appended.
- Parameters:
codePoint – The combining code point to append.
- Returns:
A copy of this character with the combining code point appended. Invalid combining code points and additions beyond the fixed storage are ignored.
-
Block withOverlay(BlockStyle style) const noexcept
Create a character with style applied on top of the stored style.
Inheritedcolor components keep the current color component, and unspecified attributes keep the current attribute state.- Parameters:
style – The style override to apply.
- Returns:
A copy of this character with the overlaid style.
-
Block withColorReplaced(Color color) const noexcept
Create a character with the given color replacing the stored color.
- Parameters:
color – The replacement color.
- Returns:
A copy of this character with exactly
color.
-
Block withStyleReplaced(BlockStyle style) const noexcept
Create a character with the given character style replaced.
- Parameters:
style – The replacement style.
- Returns:
A copy of this character with exactly
style.
-
Block withAttributes(BlockAttributes attributes) const noexcept
Create a character with the given attributes replacing the stored attributes.
- Parameters:
attributes – The replacement attributes.
- Returns:
A copy of this character with exactly
attributes.
-
Block withBase(BlockStyle style) const noexcept
Create a character with style used as the base underneath the stored style.
The stored color and stored attributes overwrite the base style.
- Parameters:
style – The base style.
- Returns:
A copy of this character resolved against the base style.
-
Block withBase(const Block &base) const noexcept
Create a character with another character used as the style base.
Only the style is used from
base; the stored Unicode character is preserved.- Parameters:
base – The character providing the base color and attributes.
- Returns:
A copy of this character resolved against
base.
-
inline constexpr bool isEmpty() const noexcept
Test if this character is empty (has no code-point).
-
bool isSpacing() const noexcept
Test if this character is spacing.
Tests for space, tab, newline, and CR.
-
bool isControl() const noexcept
Test if this character is a control character.
-
auto renderedEquals(const Block &other, bool colorEnabled = true, bool attributeEnabled = true) const noexcept -> bool
Compare how two characters would appear on screen.
Code points must match exactly. When
colorEnabledistrue, inherited color components are treated as the terminal default color before comparing. WhenattributeEnabledistrue, inherited attributes are treated as disabled before comparing.- Parameters:
other – The character to compare with.
colorEnabled –
trueto include colors in the comparison.attributeEnabled –
trueto include character attributes in the comparison.
- Returns:
trueif both characters render identically.
-
inline constexpr std::size_t hash() const noexcept
Get a hash for this character and its color.
Public Static Functions
-
static Block emptyBlock(BlockStyle style) noexcept
Create an empty render cell that carries only the given style.
This is mainly used for wide-character continuation cells, which must stay logically empty while preserving the visible style of the leading cell.
- Parameters:
style – The style to store on the empty block.
- Returns:
An empty block with
style.
-
constexpr Block() noexcept = default
-
class Block16Style
Defines a style for drawing tiles.
Public Functions
-
inline explicit Block16Style(std::array<Block, 16> tiles) noexcept
Create a new tile 16 style.
Connection points/bits: E:0, S:1, W:2, N:3
-
explicit Block16Style(const text::String &tiles)
Create a new tile 16 style from 16 terminal characters.
Connection points/bits: E:0, S:1, W:2, N:3
- Parameters:
tiles – A sequence of exactly 16 terminal characters.
- Throws:
err::ParameterError – If
tilesdoes not contain exactly 16 terminal characters.
-
explicit Block16Style(const text::U32String &tiles)
Create a new tile 16 style from 16 terminal characters.
Connection points/bits: E:0, S:1, W:2, N:3
- Parameters:
tiles – A sequence of exactly 16 terminal characters.
- Throws:
err::ParameterError – If
tilesdoes not contain exactly 16 terminal characters.
Public Static Functions
-
static Block16StylePtr create(const text::String &tiles)
Create a new shared style from 16 terminal characters.
- Parameters:
tiles – A sequence of exactly 16 terminal characters.
- Throws:
err::ParameterError – If
tilesdoes not contain exactly 16 terminal characters.- Returns:
A shared style instance.
-
static Block16StylePtr create(const text::U32String &tiles)
Create a new shared style from 16 terminal characters.
- Parameters:
tiles – A sequence of exactly 16 terminal characters.
- Throws:
err::ParameterError – If
tilesdoes not contain exactly 16 terminal characters.- Returns:
A shared style instance.
-
static Block16StylePtr lightFrame()
For drawing light frames.
-
static Block16StylePtr lightDoubleDashFrame()
For drawing light frames with double-dashed lines.
-
static Block16StylePtr lightTripleDashFrame()
For drawing light frames with triple-dashed lines.
-
static Block16StylePtr lightQuadrupleDashFrame()
For drawing light frames with quadruple-dashed lines.
-
static Block16StylePtr lightRoundedFrame()
For drawing light frames with rounded corners.
-
static Block16StylePtr heavyFrame()
For drawing heavy frames.
-
static Block16StylePtr heavyDoubleDashFrame()
For drawing heavy frames with double-dashed lines.
-
static Block16StylePtr heavyTripleDashFrame()
For drawing heavy frames with triple-dashed lines.
-
static Block16StylePtr heavyQuadrupleDashFrame()
For drawing heavy frames with quadruple-dashed lines.
-
static Block16StylePtr doubleFrame()
For drawing double frames.
-
static Block16StylePtr fullBlockFrame()
For drawing solid block frames.
-
static Block16StylePtr fullBlockWithChamferFrame()
For drawing solid block frames with chamfered corners.
-
static Block16StylePtr noneFrame()
For drawing empty frames with colored spaces.
-
static Block16StylePtr forStyle(FrameStyle frameStyle)
Get the style for the given frame style.
- Parameters:
frameStyle – The frame style to resolve.
- Returns:
The shared style instance, or
nullptrifframeStylerequiresTile9Style.
-
inline explicit Block16Style(std::array<Block, 16> tiles) noexcept
-
using erbsland::cterm::Block16StylePtr = std::shared_ptr<Block16Style>
Shared pointer for Block16Style.
-
class BlockAttributes
A set of optional ANSI character attributes.
Each attribute stores two states: whether it is explicitly specified and whether it is enabled. Unspecified attributes inherit the state from the surrounding writer or character below.
Public Functions
-
constexpr BlockAttributes() noexcept = default
Create attributes with no explicitly specified flags.
-
inline constexpr BlockAttributes(const Flag flag) noexcept
Create attributes with one enabled flag.
- Parameters:
flag – The flag to enable and specify.
-
bool operator==(const BlockAttributes&) const noexcept = default
Compare two attribute sets for equality.
-
bool operator!=(const BlockAttributes&) const noexcept = default
Compare two attribute sets for inequality.
-
inline constexpr uint8_t enabledMask() const noexcept
Get the enabled bit mask.
Only specified bits are relevant.
-
inline constexpr uint8_t specifiedMask() const noexcept
Get the specified bit mask.
-
inline constexpr uint8_t mask() const noexcept
Get the mask of attributes that are both specified and enabled.
-
text::String toString() const
Convert these attributes to their canonical textual representation.
- Returns:
The canonical attribute list.
-
inline constexpr bool isSpecified(const Flag flag) const noexcept
Test whether a flag is explicitly specified.
- Parameters:
flag – The flag to test.
- Returns:
trueif the flag is explicitly specified.
-
inline constexpr bool isEnabled(const Flag flag) const noexcept
Test whether a flag is specified and enabled.
- Parameters:
flag – The flag to test.
- Returns:
trueif the flag is specified and enabled.
-
inline constexpr BlockAttributes withBase(const BlockAttributes base) const noexcept
Apply these attributes on top of a base attribute set.
Only explicitly specified attributes overwrite the base state.
- Parameters:
base – The base attributes.
- Returns:
The resolved attribute set.
-
inline constexpr BlockAttributes withFlag(const Flag flag, const bool enabled) const noexcept
Create a copy with one flag explicitly enabled or disabled.
- Parameters:
flag – The flag to change.
enabled –
trueto enable the flag,falseto disable it.
- Returns:
The updated attribute set.
-
inline constexpr std::size_t hash() const noexcept
Get a stable hash for the attribute set.
-
inline constexpr bool isBoldSpecified() const noexcept
Test if the bold attribute is specified.
-
inline constexpr bool isBold() const noexcept
Test if the bold attribute is enabled.
-
inline constexpr bool isDimSpecified() const noexcept
Test if the dim attribute is specified.
-
inline constexpr bool isDim() const noexcept
Test if the dim attribute is enabled.
-
inline constexpr bool isItalicSpecified() const noexcept
Test if the italic attribute is specified.
-
inline constexpr bool isItalic() const noexcept
Test if the italic attribute is enabled.
-
inline constexpr bool isUnderlineSpecified() const noexcept
Test if the underline attribute is specified.
-
inline constexpr bool isUnderline() const noexcept
Test if the underline attribute is enabled.
-
inline constexpr bool isBlinkSpecified() const noexcept
Test if the blink attribute is specified.
-
inline constexpr bool isBlink() const noexcept
Test if the blink attribute is enabled.
-
inline constexpr bool isReverseSpecified() const noexcept
Test if the reverse attribute is specified.
-
inline constexpr bool isReverse() const noexcept
Test if the reverse attribute is enabled.
-
inline constexpr bool isHiddenSpecified() const noexcept
Test if the hidden attribute is specified.
-
inline constexpr bool isHidden() const noexcept
Test if the hidden attribute is enabled.
-
inline constexpr bool isStrikethroughSpecified() const noexcept
Test if the strikethrough attribute is specified.
-
inline constexpr bool isStrikethrough() const noexcept
Test if the strikethrough attribute is enabled.
-
inline constexpr void setBold(const bool enabled) noexcept
Set or clear the bold attribute explicitly.
- Parameters:
enabled –
trueto enable the attribute,falseto disable it.
-
inline constexpr void setBoldInherited() noexcept
Make the bold attribute inherit from the base state.
-
inline constexpr void setDim(const bool enabled) noexcept
Set or clear the dim attribute explicitly.
- Parameters:
enabled –
trueto enable the attribute,falseto disable it.
-
inline constexpr void setDimInherited() noexcept
Make the dim attribute inherit from the base state.
-
inline constexpr void setItalic(const bool enabled) noexcept
Set or clear the italic attribute explicitly.
- Parameters:
enabled –
trueto enable the attribute,falseto disable it.
-
inline constexpr void setItalicInherited() noexcept
Make the italic attribute inherit from the base state.
-
inline constexpr void setUnderline(const bool enabled) noexcept
Set or clear the underline attribute explicitly.
- Parameters:
enabled –
trueto enable the attribute,falseto disable it.
-
inline constexpr void setUnderlineInherited() noexcept
Make the underline attribute inherit from the base state.
-
inline constexpr void setBlink(const bool enabled) noexcept
Set or clear the blink attribute explicitly.
- Parameters:
enabled –
trueto enable the attribute,falseto disable it.
-
inline constexpr void setBlinkInherited() noexcept
Make the blink attribute inherit from the base state.
-
inline constexpr void setReverse(const bool enabled) noexcept
Set or clear the reverse attribute explicitly.
- Parameters:
enabled –
trueto enable the attribute,falseto disable it.
-
inline constexpr void setReverseInherited() noexcept
Make the reverse attribute inherit from the base state.
-
inline constexpr void setHidden(const bool enabled) noexcept
Set or clear the hidden attribute explicitly.
- Parameters:
enabled –
trueto enable the attribute,falseto disable it.
-
inline constexpr void setHiddenInherited() noexcept
Make the hidden attribute inherit from the base state.
-
inline constexpr void setStrikethrough(const bool enabled) noexcept
Set or clear the strikethrough attribute explicitly.
- Parameters:
enabled –
trueto enable the attribute,falseto disable it.
-
inline constexpr void setStrikethroughInherited() noexcept
Make the strikethrough attribute inherit from the base state.
-
inline constexpr BlockAttributes resolvedWith(const BlockAttributes base) const noexcept
Return these attributes resolved against a base state.
- Deprecated:
Use
withBase()instead.
- Parameters:
base – The base attributes.
- Returns:
The resolved attributes.
Public Static Functions
-
static BlockAttributes fromString(const text::String &str, BlockAttributes defaultValue)
Parse attributes, or return a fallback for invalid text.
- Parameters:
str – The attribute specification.
defaultValue – The value returned for invalid text.
- Returns:
The parsed attributes or
defaultValue.
-
static BlockAttributes fromStringOrThrow(const text::String &str)
Parse attributes.
- Parameters:
str – The attribute specification.
- Throws:
err::ParseError – if the text is invalid.
- Returns:
The parsed attributes.
-
static inline constexpr BlockAttributes fromMasks(uint8_t enabledMask, uint8_t specifiedMask) noexcept
Create attributes from an enabled/specified mask pair.
- Parameters:
enabledMask – The enabled bits.
specifiedMask – The specified bits.
- Returns:
The new attribute set.
-
static inline constexpr BlockAttributes fromMask(const uint8_t mask) noexcept
Create a fully specified attribute mask from enabled bits.
- Parameters:
mask – The enabled bits.
- Returns:
The fully specified attribute set.
-
static inline constexpr BlockAttributes reset() noexcept
Create a fully specified attribute set with all flags disabled.
- Returns:
The reset attribute set.
-
static inline constexpr BlockAttributes all() noexcept
Create a fully specified attribute set with all flags enabled.
- Returns:
The fully enabled attribute set.
Public Static Attributes
-
constexpr BlockAttributes() noexcept = default
-
class BlockCombinationStyle
A style how two characters are visually combined to a new one.
Subclassed by erbsland::cterm::MatrixBlockCombinationStyle, erbsland::cterm::SimpleBlockCombinationStyle, erbsland::cterm::impl::CommonBoxFrameBlockCombinationStyle
Public Functions
-
inline virtual bool isSurroundingAware() const noexcept
Does this style take the surrounding character into account? If this method returns false,
combinewith current as a single character is called.If this method returns true,
combinewith current and overlay is called.
-
virtual Block combine(const Block ¤t, const Block &overlay) const noexcept
Combines the current char with a new that is placed on top of the current one.
The default implementation just returns the overlay character.
- Parameters:
current – The current (lower) character.
overlay – The new (upper) character that overlays the current one.
- Returns:
The combined character.
-
virtual Block combine(const std::array<const Block*, 9> ¤t, const Block &overlay) const noexcept
Combines the current character situation with a new overlay character that is placed on top of the current one.
The default implementation just returns the overlay character. The matrix starts at (-1, -1) and ends at (1, 1) (left to right, top to bottom).
- Parameters:
current – A 3x3 matrix with nullptr for locations outside the buffer.
overlay – The new (upper) character that overlays the current one.
- Returns:
The combined character.
Public Static Functions
-
static const BlockCombinationStylePtr &overwrite() noexcept
Overwrite the character and color.
-
static const BlockCombinationStylePtr &colorOverlay() noexcept
Overwrite the character but overlay the color.
-
static const BlockCombinationStylePtr &commonBoxFrame() noexcept
Combine light, double, and heavy frames.
In that order: double overwrites light, and heavy overwrites double and light. Colors are overlay.
-
inline virtual bool isSurroundingAware() const noexcept
-
using erbsland::cterm::BlockCombinationStylePtr = std::shared_ptr<BlockCombinationStyle>
Shared pointer for BlockCombinationStyle.
-
using erbsland::cterm::BlockCount = unit::IntegerUnitAmount<BlockUnit>
A block-string count or length.
-
using erbsland::cterm::BlockIndex = unit::IntegerUnitIndex<BlockUnit>
A block-string index.
-
class BlockPrintContext
The print context interface for terminal block print commands.
You only need this interface if you implement a custom cursor writer subclass that uses an unusual backend storage. For regular writers, rely on the default implementation and implement the
writemethods.Subclassed by erbsland::cterm::impl::BlockPrintContextToString, erbsland::cterm::impl::BlockPrintContextToTerminal
Public Functions
-
virtual void commit() noexcept = 0
Commit the printed content and final active style.
-
virtual void print(Foreground color) noexcept = 0
Change the active foreground color.
-
virtual void print(Background color) noexcept = 0
Change the active background color.
-
virtual void print(BlockStyle style) noexcept = 0
Overlay the active style.
-
virtual void print(BlockAttributes attributes) noexcept = 0
Overlay the active attributes.
-
virtual void print(const BlockStringEditor &text) noexcept = 0
Print terminal text.
-
virtual void print(const BlockString &text) noexcept = 0
Print terminal text.
-
inline void print(const Foreground::Hue color) noexcept
Change the active foreground color.
-
inline void print(const Background::Hue color) noexcept
Change the active background color.
-
virtual void commit() noexcept = 0
-
using erbsland::cterm::BlockRange = unit::IntegerUnitRange<BlockUnit>
A block-string range.
-
using erbsland::cterm::BlockStringLines = std::vector<BlockString>
A sequence of completed terminal text lines.
-
class BlockString
An owning read-only terminal string value backed by shared storage.
Public Types
Public Functions
-
BlockString() noexcept
Create an empty read-only string.
-
explicit BlockString(const text::String &string, BlockStyle style)
Create a terminal string from UTF-8 text with a uniform style.
-
explicit BlockString(const text::U32String &string, BlockStyle style)
Create a terminal string from UTF-32 text with a uniform style.
-
explicit BlockString(BlockCount count, Block character) noexcept
Create a terminal string repeating the same block.
-
BlockString(const BlockStringEditor &string) noexcept
Create a read-only string from a string.
This conversion is implicit so APIs can migrate from
BlockStringEditortoBlockString.- Parameters:
string – The source string.
-
BlockString &operator=(BlockString &&other) noexcept
Move another terminal string into this string.
-
Block operator[](BlockIndex index) const noexcept
Access one character without bounds checking.
- Parameters:
index – The character index.
- Returns:
A copy of the character at
index, orBlock{}ifindexis out of bounds.
-
inline BlockCount length() const noexcept
Get the number of stored characters.
-
int displayWidth() const noexcept
Get the width of the string in terminal cells.
- Returns:
The sum of all character display widths.
-
inline bool isEmpty() const noexcept
Test if this read-only string is empty.
-
Block at(BlockIndex index) const
Access one character with bounds checking.
- Parameters:
index – The character index.
- Returns:
A copy of the character at
index.
-
const_iterator begin() const noexcept
Get an iterator to the first character.
-
const_iterator end() const noexcept
Get an iterator past the last character.
-
const_iterator cbegin() const noexcept
Get a const iterator to the first character.
-
const_iterator cend() const noexcept
Get a const iterator past the last character.
-
const_reverse_iterator rbegin() const noexcept
Get a const reverse iterator to the last character.
-
const_reverse_iterator rend() const noexcept
Get a const reverse iterator past the first character.
-
const_reverse_iterator crbegin() const noexcept
Get a const reverse iterator to the last character.
-
const_reverse_iterator crend() const noexcept
Get a const reverse iterator past the first character.
-
BlockCount count(const Block &character) const noexcept
Count the number of characters matching a fully styled character.
- Parameters:
character – The character to count.
- Returns:
The number of matching characters in this string.
-
BlockCount count(text::Char character) const noexcept
Count the number of characters matching one code point regardless of style.
- Parameters:
character – The character to count.
- Returns:
The number of matching characters in this string.
-
BlockIndex indexOf(const Block &character, BlockIndex startIndex = {}) const noexcept
Get the index of the next character with a given full style.
- Parameters:
character – The character to search for.
startIndex – The first local index to inspect.
- Returns:
The local index of the next match, or
BlockIndex::noIndex().
-
BlockIndex indexOf(text::Char character, BlockIndex startIndex = {}) const noexcept
Get the index of the next character matching one code point regardless of style.
- Parameters:
character – The character to search for.
startIndex – The first local index to inspect.
- Returns:
The local index of the next match, or
BlockIndex::noIndex().
-
BlockIndex indexOf(const text::CharSet &characterSet, BlockIndex startIndex = {}) const noexcept
Get the index of the next matching character.
Ignores the character style. If startIndex is out of bounds, returns
BlockIndex::noIndex(). If no character is found, returnsBlockIndex::noIndex(). This function matches any character in the character set.- Parameters:
characterSet – The character-set to search for. Only compares single-code-point characters.
startIndex – The start index to search from. Defaults to 0.
- Returns:
The index of the next character or
BlockIndex::noIndex()if not found.
-
BlockIndex indexNotOf(const text::CharSet &characterSet, BlockIndex startIndex = {}) const noexcept
Get the index of the next not matching character.
Ignores the character style. If startIndex is out of bounds, returns
BlockIndex::noIndex(). If no character is found, returnsBlockIndex::noIndex(). This function matches if no character in the character set matches the text.- Parameters:
characterSet – The character-set to search for. Only compares single-code-point characters.
startIndex – The start index to search from. Defaults to 0.
- Returns:
The index of the next character or
BlockIndex::noIndex()if not found.
-
BlockString slice(BlockRange range = BlockRange::all()) const noexcept
Get an owning read-only slice.
- Parameters:
range – The block range to slice.
- Returns:
The substring or an empty string if the range is out of bounds.
-
BlockString slice(text::StringSide side, BlockCount count) const noexcept
Get the initial or trailing block-based portion of this string.
-
auto croppedToDisplayWidth(block::Coordinate displayWidth, geometry::Alignment alignment) const noexcept -> BlockString
Get a substring that fits into the given display width.
If a double-sized character is at the edge, it isn’t included in the result. Therefore, the resulting string may be shorter than the display width.
- Parameters:
displayWidth – The maximum width of the substring in display units.
alignment – The alignment of the cropped text. Only
geometry::Alignment::Leftandgeometry::Alignment::Rightare supported.
- Returns:
The cropped substring or an empty string if displayWidth is <=0.
-
BlockString trimmed(const text::CharSet &characters = defaultTrimCharacters()) const noexcept
Trim the given characters from the beginning and end of the string.
Only single-code-point characters are matched.
- Parameters:
characters – The characters to remove from both ends. If empty, removes space, tab, and newline characters.
- Returns:
A trimmed read-only string.
-
bool containsControlCharacters() const noexcept
Test if this read-only string contains control characters.
As most control codes are filtered on construction, this mainly tests for NL and TAB.
-
std::vector<BlockString> splitWords() const noexcept
Split the string into words at space, tab, carriage return, or newline characters.
- Returns:
A sequence of owning read-only word slices.
-
auto wrapIntoLines(int width, ParagraphSpacing paragraphSpacing = ParagraphSpacing::SingleLine) const noexcept -> BlockStringLines
Wrap this string into lines that have a maximum display width.
Paragraph breaks from newline characters are preserved using the selected paragraph spacing.
- Parameters:
width – The maximum terminal width in cells. Must be greater than zero.
paragraphSpacing – The spacing to use between newline-separated paragraphs.
- Returns:
A sequence of materialized lines.
-
int terminalLines(int width) const noexcept
Count how many terminal lines this string occupies for a given terminal width.
- Parameters:
width – The available terminal width in cells. Must be greater than zero.
- Returns:
The number of occupied terminal lines.
-
block::Size naturalBlockTextSize() const noexcept
Get the natural rectangular size for this text without wrapping.
The returned size is at least 1x1, preserves explicit non-trailing newline characters as separate lines, and uses terminal cell width for wide and combining characters.
- Returns:
The natural text size in terminal cells.
-
block::Coordinate wrappedBlockTextHeight(block::Coordinate width, const BlockTextOptions &options) const noexcept
Calculate the height required to render this text with
WritableBuffer::drawBlockText().The given width is the full target rectangle width, including margins configured in
options.- Parameters:
width – The available rectangle width in terminal cells.
options – The text options used for paragraph layout.
- Returns:
The required rectangle height in terminal cells.
-
std::vector<BlockString> splitLines() const noexcept
Split this string into individual lines.
The string is split at the NL character that is not included in the result. Empty lines are preserved. A NL at the end of the string does not generate an additional empty line.
- Returns:
A sequence of owning read-only line slices.
-
BlockString withBase(BlockStyle style) const noexcept
Create a new string with the given style applied as a base.
- Parameters:
style – The style used as base for the resulting string.
- Returns:
A new string with the base style applied.
Public Static Functions
-
static auto fromLines(std::initializer_list<text::String> lines, Color color = {}, BlockAttributes attributes = {}) noexcept -> BlockString
Create completed terminal text from UTF-8 lines joined with newlines.
-
static BlockString fromLines(std::initializer_list<text::String> lines, BlockStyle style) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
static auto fromLines(std::initializer_list<text::U32String> lines, Color color = {}, BlockAttributes attributes = {}) noexcept -> BlockString
Create completed terminal text from UTF-32 lines joined with newlines.
-
static BlockString fromLines(std::initializer_list<text::U32String> lines, BlockStyle style) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
BlockString() noexcept
-
class BlockStringEditor
A terminal string represented as a sequence of
Blockvalues.BlockStringEditoris implicitly shared. Copying a string shares its backing data, and a deep copy is only made when one instance is modified through a mutating API.Public Types
Public Functions
-
BlockStringEditor() noexcept
Create an empty terminal string.
-
explicit BlockStringEditor(const text::String &str)
Create a terminal string from UTF-8 text.
- Parameters:
str – The UTF-8 text to split into terminal characters. Control codes are ignored except for tab and newline. Malformed UTF-8 is replaced with Unicode replacement characters.
-
explicit BlockStringEditor(const text::String &str, BlockStyle style)
Create a terminal string from UTF-8 text with a uniform style.
- Parameters:
str – The UTF-8 text to split into terminal characters.
style – The style to use for the characters. Control codes are ignored except for tab and newline. Malformed UTF-8 is replaced with Unicode replacement characters.
-
explicit BlockStringEditor(const text::U32String &str)
Create a terminal string from UTF-32 text.
- Parameters:
str – The UTF-32 text to split into terminal characters. Control codes are ignored except for tab and newline.
-
explicit BlockStringEditor(const text::U32String &str, BlockStyle style)
Create a terminal string from UTF-32 text with a uniform style.
- Parameters:
str – The UTF-32 text to split into terminal characters.
style – The style to use for the characters. Control codes are ignored except for tab and newline.
-
explicit BlockStringEditor(BlockCount count, Block character) noexcept
Create a terminal string repeating the same
Block.- Parameters:
count – The repetition count. Limited to 10’000’000.
character – The character to repeat.
-
explicit BlockStringEditor(const BlockString &view)
Create an editable terminal string from a read-only string.
- Parameters:
view – The read-only string to copy into an owned string.
-
BlockStringEditor &operator=(BlockStringEditor &&other) noexcept
Move another terminal string into this string.
-
bool operator==(const BlockStringEditor &other) const noexcept
Compare two strings.
Two strings are only equal, if all characters and styles are equal.
-
inline bool operator!=(const BlockStringEditor &other) const noexcept
Compare two strings for inequality.
- Parameters:
other – The string to compare.
- Returns:
trueif the strings differ in characters or styles.
-
Block operator[](BlockIndex index) const noexcept
Access one character without bounds checking.
- Parameters:
index – The character index.
- Returns:
A copy of the character at
index, orBlock{}ifindexis out of bounds.
-
Block &operator[](BlockIndex index) noexcept
Access one character without bounds checking.
- Parameters:
index – The character index.
- Returns:
A mutable reference to the character at
index, or a discardedBlock{}ifindexis out of bounds.
-
inline BlockStringEditor &operator+=(const Block &character) noexcept
Append one character to this string.
- Parameters:
character – The character to append.
- Returns:
Reference to this string.
-
BlockStringEditor &operator+=(const BlockStringEditor &other) noexcept
Append another terminal string to this string.
- Parameters:
other – The string to append.
- Returns:
Reference to this string.
-
BlockStringEditor &operator+=(const BlockString &other) noexcept
Append a read-only string to this editor.
- Parameters:
other – The read-only string to append.
- Returns:
Reference to this string.
-
inline BlockStringEditor operator+(const Block &character) const noexcept
Create a new string with one appended character.
- Parameters:
character – The character to append.
- Returns:
The concatenated string.
-
BlockStringEditor operator+(const BlockStringEditor &other) const noexcept
Create a new string with another appended string.
- Parameters:
other – The string to append.
- Returns:
The concatenated string.
-
BlockStringEditor operator+(const BlockString &other) const noexcept
Create a new editor with an appended read-only string.
- Parameters:
other – The read-only string to append.
- Returns:
The concatenated string.
-
inline BlockCount length() const noexcept
Get the number of stored characters.
-
int displayWidth() const noexcept
Get the width of the string in terminal cells.
- Returns:
The sum of all character display widths.
-
BlockStringEditor withTabsExpanded(int targetColumn) const
Return a copy with tab characters expanded to styled spaces up to the given column.
-
inline bool isEmpty() const noexcept
Test if this string is empty.
-
Block at(BlockIndex index) const
Access one character with bounds checking.
- Parameters:
index – The character index.
- Returns:
A copy of the character at
index.
-
const_iterator begin() const noexcept
Get a const iterator to the first character.
-
const_iterator end() const noexcept
Get a const iterator past the last character.
-
const_iterator cbegin() const noexcept
Get a const iterator to the first character.
-
const_iterator cend() const noexcept
Get a const iterator past the last character.
-
reverse_iterator rbegin() noexcept
Get a reverse iterator to the last character.
-
reverse_iterator rend() noexcept
Get a reverse iterator past the first character.
-
const_reverse_iterator rbegin() const noexcept
Get a const reverse iterator to the last character.
-
const_reverse_iterator rend() const noexcept
Get a const reverse iterator past the first character.
-
const_reverse_iterator crbegin() const noexcept
Get a const reverse iterator to the last character.
-
const_reverse_iterator crend() const noexcept
Get a const reverse iterator past the first character.
-
BlockCount count(const Block &character) const noexcept
Count the number of characters with a given color.
- Parameters:
character – The character to count.
- Returns:
The number of characters in this string.
-
BlockCount count(text::Char character) const noexcept
Count the number of characters matching any color.
- Parameters:
character – The character to count (1 code-point).
- Returns:
The number of characters in this string.
-
BlockIndex indexOf(const Block &character, BlockIndex startIndex = {}) const noexcept
Get the index of the next character with a given color.
If startIndex is out of bounds, returns
BlockIndex::noIndex(). If no character is found, returnsBlockIndex::noIndex().- Parameters:
character – The character to search for. Compares both, character and color!
startIndex – The start index to search from. Defaults to 0.
- Returns:
The index of the next character or
BlockIndex::noIndex()if not found.
-
BlockIndex indexOf(text::Char character, BlockIndex startIndex = {}) const noexcept
Get the index of the next matching character.
Ignores the character style. If startIndex is out of bounds, returns
BlockIndex::noIndex(). If no character is found, returnsBlockIndex::noIndex().- Parameters:
character – The character to search for. Only compares single-code-point characters.
startIndex – The start index to search from. Defaults to 0.
- Returns:
The index of the next character or
BlockIndex::noIndex()if not found.
-
BlockIndex indexOf(const text::CharSet &characterSet, BlockIndex startIndex = {}) const noexcept
Get the index of the next matching character.
Ignores the character style. If startIndex is out of bounds, returns
BlockIndex::noIndex(). If no character is found, returnsBlockIndex::noIndex(). This function matches any character in the character set.- Parameters:
characterSet – The character-set to search for. Only compares single-code-point characters.
startIndex – The start index to search from. Defaults to 0.
- Returns:
The index of the next character or
BlockIndex::noIndex()if not found.
-
BlockIndex indexNotOf(const text::CharSet &characterSet, BlockIndex startIndex = {}) const noexcept
Get the index of the next not matching character.
Ignores the character style. If startIndex is out of bounds, returns
BlockIndex::noIndex(). If no character is found, returnsBlockIndex::noIndex(). This function matches if no character in the character set matches the text.- Parameters:
characterSet – The character-set to search for. Only compares single-code-point characters.
startIndex – The start index to search from. Defaults to 0.
- Returns:
The index of the next character or
BlockIndex::noIndex()if not found.
-
BlockStringEditor slice(BlockRange range = BlockRange::all()) const noexcept
Get a substring.
- Parameters:
range – The block range to slice.
- Returns:
The substring or an empty string if the range is out of bounds.
-
BlockStringEditor slice(text::StringSide side, BlockCount count) const noexcept
Get the initial or trailing block-based portion of this string.
-
auto croppedToDisplayWidth(block::Coordinate displayWidth, geometry::Alignment alignment) const noexcept -> BlockStringEditor
Get a substring that fits into the given display width.
If a double-sized character is at the edge, it isn’t included in the result. Therefore, the resulting string may be shorter than the display width.
- Parameters:
displayWidth – The maximum width of the substring in display units.
alignment – The alignment of the cropped text. Only
geometry::Alignment::Leftandgeometry::Alignment::Rightare supported.
- Returns:
The cropped substring or an empty string if displayWidth is <=0.
-
BlockStringEditor trimmed(const text::CharSet &characters = defaultTrimCharacters()) const noexcept
Return a string with the given characters trimmed from the beginning and end.
Only single-code-point characters are matched.
- Parameters:
characters – The characters to remove from both ends. If empty, removes space, tab, and newline characters.
- Returns:
A copy without matching leading and trailing characters.
-
auto normalized(const text::CharSet &characters = defaultTrimCharacters(), Block separator = Block::space()) const noexcept -> BlockStringEditor
Return a normalized string.
Trim the given characters from start/end, and eplace any number of the given characters inside the string with a single separator. Only single-code-point characters are matched. The style of replaced characters is determined by using the first matches character style as a base for
separator.- Parameters:
characters – The characters to match. If empty: space, tab, and newline characters.
separator – The separator to use.
-
bool containsControlCharacters() const noexcept
Test if this string contains control characters.
Most control codes are filtered on construction, therefore, this test searched for NL and TAB.
-
void reserve(BlockCount size) noexcept
Reserve storage for at least the given number of characters.
- Parameters:
size – The requested capacity.
-
void clear() noexcept
Remove all characters from this string.
-
void trim(const text::CharSet &characters = defaultTrimCharacters()) noexcept
Trim the given characters from the beginning and end of the string.
Only single-code-point characters are matched.
- Parameters:
characters – The characters to remove from both ends. If empty, removes space, tab, and newline characters.
-
void normalize(const text::CharSet &characters = defaultTrimCharacters(), Block separator = Block::space()) noexcept
Normalize this string.
Trim the given characters from start/end, and eplace any number of the given characters inside the string with a single separator. Only single-code-point characters are matched. The style of replaced characters is determined by using the first matches character style as a base for
separator.- Parameters:
characters – The characters to match. If empty: space, tab, and newline characters.
separator – The separator to use.
-
void replace(BlockRange range, Block replacement) noexcept
Replace characters in this string.
If the range is out of bounds, it is clamped to the string’s length. If the range is outside the string or empty, no replacement is performed. If the operation does not change the string, no replacement is performed.
- Parameters:
range – The range of characters to replace.
replacement – The replacement for this range.
-
void replace(BlockRange range, const BlockString &replacement) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
void remove(BlockRange range) noexcept
Remove a part of the string.
If the range is out of bounds, it is clamped to the string’s length. If the range is outside the string or empty, no replacement is performed.
-
void set(BlockIndex index, Block character) noexcept
Set a character in this string.
This call is more efficient than using the index operator.
-
void insertWithBaseStyle(BlockIndex pos, const BlockString &other, BlockStyle style) noexcept
Append another terminal string with a base style.
If
posis out of range, appends the string at the end.- Parameters:
pos – The position to insert the string at.
other – The source text view.
style – The style used as base for inherited components in the appended range.
-
void appendStyled(const text::String &text, BlockStyle style)
Append text using one uniform style.
- Parameters:
text – The text to append.
style – The style applied to the appended characters.
-
void appendStyled(const text::U32String &text, BlockStyle style) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
void appendStyled(const BlockString &other, BlockStyle style) noexcept
Append another terminal string with a base style.
- Parameters:
other – The source text view.
style – The style used as base for inherited components in the appended range.
-
void append(BlockCount count, Block character) noexcept
Append a repeated character.
- Parameters:
count – The repetition count. Limited to 10’000’000.
character – The character to repeat.
-
void append(BlockCount count, text::Char character, BlockStyle style) noexcept
Append a repeated Unicode code point with a uniform style.
- Parameters:
count – The repetition count. Limited to 10’000’000.
character – The character to repeat.
style – The style for every appended character.
-
template<PrintableArg... Args>
inline void append(Args... args) noexcept Append elements to this string.
This works similar to
Terminal::print(). If you add a color, this color is “active” for all following characters in the same call. If you add character attributes, these attributes are active for all following characters in the same call. AppendedBlock,BlockStringEditor, andBlockStringvalues with inherited color components or inherited attributes resolve against the currently active state. Just adding a color does not change the string.- Parameters:
args – The arguments to append.
-
std::vector<BlockStringEditor> splitWords() const noexcept
Split the string into words at space, tab, carriage return, or newline characters.
- Returns:
A sequence of words.
-
auto wrapIntoLines(int width, ParagraphSpacing paragraphSpacing = ParagraphSpacing::SingleLine) const noexcept -> std::vector<BlockStringEditor>
Wrap this string into lines that have a maximum display width.
Paragraph breaks from newline characters are preserved using the selected paragraph spacing.
- Parameters:
width – The maximum terminal width in cells. Must be greater than zero.
paragraphSpacing – The spacing to use between newline-separated paragraphs.
- Returns:
A sequence of lines.
-
int terminalLines(int width) const noexcept
Count how many terminal lines this string occupies for a given terminal width.
Newline characters start a new terminal line and printable characters wrap at the given width. The result is undefined for abstract terminal widths smaller than 10 cells.
- Parameters:
width – The available terminal width in cells. Must be greater than zero.
- Returns:
The number of occupied terminal lines.
-
block::Size naturalBlockTextSize() const noexcept
Get the natural rectangular size for this text without wrapping.
The returned size is at least 1x1, preserves explicit non-trailing newline characters as separate lines, and uses terminal cell width for wide and combining characters.
- Returns:
The natural text size in terminal cells.
-
block::Coordinate wrappedBlockTextHeight(block::Coordinate width, const BlockTextOptions &options) const noexcept
Calculate the height required to render this text with
WritableBuffer::drawBlockText().The given width is the full target rectangle width, including margins configured in
options.- Parameters:
width – The available rectangle width in terminal cells.
options – The text options used for paragraph layout.
- Returns:
The required rectangle height in terminal cells.
-
std::vector<BlockStringEditor> splitLines() const noexcept
Splits this string into individual lines.
The string is split at the NL character that is not included in the result. Empty lines are preserved. A NL at the end of the string does not generate an additional empty line.
- Returns:
A sequence of lines.
-
BlockStringEditor withBase(BlockStyle style) const noexcept
Create a new string with the given style applied as a base.
- Parameters:
style – The style used as base for the resulting string.
- Returns:
A new string with the base style applied.
Public Static Functions
-
static auto fromLines(std::initializer_list<text::String> lines, Color color = {}, BlockAttributes attributes = {}) noexcept -> BlockStringEditor
Create a new string from a list of lines.
All lines are joined using a new-line character.
- Parameters:
lines – The lines for the string.
color – The base color to use for each character.
attributes – The base attributes to use for each character. Invalid UTF-8 bytes are replaced with the Unicode replacement character.
- Returns:
The new string.
-
static BlockStringEditor fromLines(std::initializer_list<text::String> lines, BlockStyle style) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
static auto fromLines(std::initializer_list<text::U32String> lines, Color color = {}, BlockAttributes attributes = {}) noexcept -> BlockStringEditor
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
static BlockStringEditor fromLines(std::initializer_list<text::U32String> lines, BlockStyle style) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
BlockStringEditor() noexcept
-
using erbsland::cterm::BlockStringEditorLines = std::vector<BlockStringEditor>
A sequence of wrapped terminal text lines.
-
class BlockStyle
A combined terminal text style with color and character attributes.
Public Functions
-
constexpr BlockStyle() noexcept = default
Create a style with inherited color and attributes.
-
template<typename tColor>
inline constexpr BlockStyle(const tColor color, const BlockAttributes attributes = {}) noexcept Create a style from color and attributes.
- Parameters:
color – The color for the style.
attributes – The character attributes for the style.
-
inline constexpr BlockStyle(const BlockAttributes attributes) noexcept
Create a style from character attributes and inherited color.
- Parameters:
attributes – The character attributes for the style.
-
inline constexpr BlockStyle(const Foreground fg) noexcept
Create a style with the given foreground color.
- Parameters:
fg – The foreground color for the style.
-
inline constexpr BlockStyle(const Background bg) noexcept
Create a style with the given background color.
- Parameters:
bg – The background color for the style.
-
inline constexpr BlockStyle(const Foreground fg, const Background bg) noexcept
Create a style with the given foreground and background color.
- Parameters:
fg – The foreground color for the style.
bg – The background color for the style.
-
bool operator==(const BlockStyle&) const noexcept = default
Compare two character styles for equality.
-
bool operator!=(const BlockStyle&) const noexcept = default
Compare two character styles for inequality.
-
inline void setColor(const Color color) noexcept
Set the color part of the style.
- Parameters:
color – The new color.
-
inline Foreground fg() const noexcept
Get the foreground color.
-
inline void setFg(const Foreground foreground) noexcept
Set the foreground color.
- Parameters:
foreground – The new foreground color.
-
inline Background bg() const noexcept
Get the background color.
-
inline void setBg(const Background background) noexcept
Set the background color.
- Parameters:
background – The new background color.
-
inline BlockAttributes attributes() const noexcept
Get the character attributes.
-
inline void setAttributes(const BlockAttributes attributes) noexcept
Set the character attributes.
- Parameters:
attributes – The new character attributes.
-
text::String toString() const
Convert this style to its canonical textual representation.
- Returns:
The canonical style specification.
-
BlockStyle withOverlay(BlockStyle overlay) const noexcept
Create a new style by overlaying another style onto this one.
Inherited color components keep the existing color, and unspecified attributes keep the existing attributes.
- Parameters:
overlay – The overlay style.
- Returns:
The combined style.
-
BlockStyle withBase(BlockStyle base) const noexcept
Create a new style by placing a base style underneath this one.
The current style overwrites inherited or unspecified parts from the base style.
- Parameters:
base – The base style.
- Returns:
The resolved style.
-
inline constexpr std::size_t hash() const noexcept
Get a stable hash for the character style.
Public Static Functions
-
static BlockStyle fromString(const text::String &str, BlockStyle defaultValue)
Parse a style, or return a fallback for invalid text.
- Parameters:
str – The style specification.
defaultValue – The value returned for invalid text.
- Returns:
The parsed style or
defaultValue.
-
static BlockStyle fromStringOrThrow(const text::String &str)
Parse a style.
- Parameters:
str – The style specification.
- Throws:
err::ParseError – if the text is invalid.
- Returns:
The parsed style.
-
static inline constexpr BlockStyle reset() noexcept
Get a character style with default colors and default attributes set.
-
constexpr BlockStyle() noexcept = default
-
class BlockText
Describes a text block to render into a
Buffer.Note
Creating and copying text instances is expensive. Please keep and reuse created instances.
Public Functions
-
BlockText() = default
Create an empty text description.
-
inline BlockText(BlockString text, block::Rectangle rect, const geometry::Alignment alignment = geometry::Alignment::TopLeft) noexcept
Create a text description for the given content and target rectangle.
- Parameters:
text – The text content to render.
rect – The target rectangle.
alignment – The text alignment inside the rectangle.
-
inline const BlockString &blockString() const noexcept
Get the text content.
-
inline void setBlockString(BlockString text) noexcept
Set the text content.
-
inline const BlockTextOptions &blockTextOptions() const noexcept
Get the text options.
-
inline void setBlockTextOptions(const BlockTextOptions &options) noexcept
Set the text options.
-
inline const ColorSequence &colorSequence() const noexcept
Get the optional text color sequence.
-
inline void setColorSequence(ColorSequence colorSequence) noexcept
Set the text color sequence.
- Parameters:
colorSequence – The sequence of colors to apply while rendering the text.
-
inline Color color() const noexcept
Get the first text color from the configured sequence.
- Returns:
The first sequence color, or the inherited color if no sequence is configured.
-
inline void setColor(const Color color) noexcept
Set a single text color.
- Parameters:
color – The single base color to use for the rendered text.
-
inline const FontPtr &font() const noexcept
Get the optional font. If this is empty, regular text rendering is used.
-
inline void setFont(const FontPtr &font) noexcept
Set the font.
- Parameters:
font – The font to use, or an empty pointer for regular terminal text rendering.
-
inline BlockTextAnimation animation() const noexcept
Get the animation mode.
-
inline void setAnimation(const BlockTextAnimation animation) noexcept
Set the animation mode.
- Parameters:
animation – The animation mode to apply while rendering the text.
-
inline geometry::Alignment alignment() const noexcept
The alignment of the paragraph.
For the
Terminal::printParagraphcalls, vertical alignment is ignored. For thedrawBlockText(BlockText)calls, the vertical alignment is used to align the text in the given rectangle.
-
inline void setAlignment(const geometry::Alignment alignment) noexcept
Set the alignment of the paragraph.
-
inline int lineIndent() const noexcept
The line indent for all lines.
Only valid if the alignment is set to
geometry::Alignment::Left. This indent can be overridden byfirstLineIndentandwrappedLineIndent.
-
inline void setLineIndent(const int indent) noexcept
Set the line indent for all lines.
- Parameters:
indent – The new indent value.
>=0
-
inline int firstLineIndent() const noexcept
Get the first line indent.
This is the indent for the first line of the paragraph. Only valid if the alignment is set to
geometry::Alignment::Left.1:| <first indent> A long text that is broken | 2:| into multiple lines. |
-
inline void setFirstLineIndent(const int indent) noexcept
Set the first line indent.
- Parameters:
indent – The new indent value.
>=0orcUseLineIndentto uselineIndent
-
inline int wrappedLineIndent() const noexcept
Get the indent for wrapped lines.
This is the indent for all lines that are wrapped at the terminal width. Only valid if the alignment is set to
geometry::Alignment::Left.1:| <first indent> A long text that is broken | 2:| into multiple lines. |
-
inline void setWrappedLineIndent(const int indent) noexcept
Set the indent for wrapped lines.
- Parameters:
indent – The new indent value.
>=0orcUseLineIndentto uselineIndent
-
inline void setMargins(const block::Margins margins) noexcept
Set the margins around the paragraph.
- Parameters:
margins – The margins around the paragraph area.
-
inline ParagraphBackgroundMode backgroundMode() const noexcept
Get the background mode.
The background mode determines how the background of the paragraph is handled when lines are wrapped. It also controls how the background is extended for the last line in the paragraph.
With
BlockText/drawBlockText(...), cells outside the wrapped text keep the existing buffer background unless the selected mode fills them from the wrapped text. WithCursorWriter::printParagraph(), indentation and padding are written as spaces, so cells not covered by wrapped-text background use the writer’s current background.
-
inline void setBackgroundMode(const ParagraphBackgroundMode backgroundMode) noexcept
Set the background mode.
When using
CursorWriter::printParagraph(), configure the writer background before printing if indentation or trailing padding should visually match a surrounding panel.
-
inline const BlockString &lineBreakEndMark() const noexcept
Get the line break end mark.
The line break end mark is appended to wrapped physical lines. The mark is aligned to the right edge of the available paragraph area. If the mark contains color information, it will override the background color.
1:| A long text that is broken <end mark> | 2:| into multiple lines. |
- Returns:
The current line break end mark. Empty for no line break end mark.
-
inline void setLineBreakEndMark(BlockString mark)
Set the line break end mark.
- Parameters:
mark – The new line break end mark. Must not exceed two characters.
-
inline const BlockString &lineBreakStartMark() const noexcept
Get the line break start mark.
The line break start mark prepends wrapped continuation lines in left-aligned paragraphs. The mark is inserted after the continuation indentation. If the mark contains color information, it will override the background color.
1:| A long text that is broken | 2:| <start mark> into multiple lines. |
- Returns:
The current line break start mark. Empty for no line break start mark.
-
inline void setLineBreakStartMark(BlockString mark)
Set the line break start mark.
Unlike the end mark, this decoration may contain an arbitrary number of characters so nested line prefixes and continuation indentation can be represented.
- Parameters:
mark – The new line break start mark.
-
inline ParagraphSpacing paragraphSpacing() const noexcept
The spacing between paragraphs.
The behavior of the paragraph spacing depends on the used interface. For
Terminal::printParagraph()andCursorBuffer::printParagraph(), embedded newlines are hard line breaks inside one printed paragraph, and the configured spacing is appended once after the whole call. FordrawBlockText(BlockText)calls, each newline starts a new paragraph and spacing is inserted between paragraphs.
-
inline void setParagraphSpacing(const ParagraphSpacing spacing) noexcept
Set the paragraph spacing.
-
inline text::U32String wordSeparators() const
Get the configured word separators as a canonicalized character string.
Word separators split a source line into words. Consecutive separators are rendered as a single space between words. Tabs use special tab-stop handling in left-aligned paragraphs before separator handling is applied. The returned string is duplicate-free and normalized for comparison and display.
-
inline void setWordSeparators(const text::U32String &separators)
Set the word separators.
Tabs remain special tab stops in left-aligned paragraphs and act as regular word separators in other alignments when included here. The provided string is canonicalized automatically and mapped to shared defaults for common patterns.
- Parameters:
separators – A string of Unicode characters that are used to split words.
-
inline const Block &wordBreakMark() const noexcept
Get the word break mark.
The word break mark is used when a long word had to be split in a paragraph.
-
inline int maximumLineWraps() const noexcept
Get the maximum line wraps.
A value >0 limits the automatic wraps for one source line. Once the limit is reached, the current source line is truncated and
paragraphEllipsisMark()is appended if configured. Embedded line breaks start a new source line and therefore reset the wrap counter.- Returns:
The maximum number of line wraps, or zero for unlimited line wraps.
-
inline void setMaximumLineWraps(const int lines) noexcept
Set the maximum number of line wraps.
- Parameters:
lines – The maximum number of line wraps, or zero for unlimited line wraps.
-
inline const BlockString ¶graphEllipsisMark() const noexcept
Get the paragraph ellipsis mark.
This string is used to indicate that a paragraph would have to be wrapped over even more lines to be displayed completely. A single character can be used, but a short text like
(more…)works as well. Please note that the width of this mark further reduces the available space for the paragraph text.- Returns:
The paragraph ellipsis mark or an empty string if no ellipsis mark shall be used.
-
inline void setParagraphEllipsisMark(BlockString mark) noexcept
Set the paragraph ellipsis mark.
We recommend using a single character or a very short text. Longer texts quickly make paragraph rendering impossible.
- Parameters:
mark – The paragraph ellipsis mark. If empty, no ellipsis mark will be used.
-
inline const std::vector<int> &tabStops() const noexcept
Get the tab stops for the paragraph.
Only valid if the alignment is set to
geometry::Alignment::Left. If a line (text up to a newline character) contains TAB characters, each tab character will pick the next tab-stop columns value from this array. If the column is larger than the current column, spacing is inserted until the cursor reaches the tab-stop column. If the tab column is smaller, or there is no further tab stop in the sequence,tabOverflowBehavior()is used to decide whether the tab becomes a single space or starts a wrapped continuation line. In centered or right-aligned paragraphs, tabs usewordSeparatorsinstead of these tab stops. The special valuecTabWrappedLineIndentcan be used to use the same indent as for wrapped lines.
-
inline void setTabStops(std::vector<int> tabStops) noexcept
Set the tab stops.
-
inline TabOverflowBehavior tabOverflowBehavior() const noexcept
Get the overflow handling for non-advancing tab stops.
This mode is used if a TAB resolves to a tab-stop column that is not larger than the current column, or if there is no further configured tab stop.
-
inline void setTabOverflowBehavior(const TabOverflowBehavior behavior) noexcept
Set the overflow handling for non-advancing tab stops.
- Parameters:
behavior – The behavior to use for tabs that do not advance the current line.
-
inline ParagraphOnError onError() const noexcept
Get the error resolution if a paragraph cannot be rendered with the given settings.
If the screen layout and the given parameters do not allow the paragraph to be rendered properly, this error resolution is used.
- Returns:
The error resolution to use when a paragraph cannot be rendered.
-
inline void setOnError(const ParagraphOnError onError) noexcept
Set the error resolution.
- Parameters:
onError – The error resolution to use when a paragraph cannot be rendered.
-
BlockText() = default
-
enum class erbsland::cterm::BlockTextAnimation : uint8_t
Supported text animation styles used by
Buffer::renderText().Values:
-
enumerator None
No animation.
-
enumerator ColorDiagonal
Diagonal color animation. Requires a color sequence.
-
enumerator None
-
class BlockTextOptions
Options for text rendering.
This class combines text color, font, animation, and paragraph layout settings into one reusable configuration object that can be attached to a
BlockTextinstance.Note
Creating and copying text instances is expensive. Please keep and reuse created instances.
Public Functions
-
inline explicit BlockTextOptions(const geometry::Alignment alignment) noexcept
Create a text options instance with the given alignment.
- Parameters:
alignment – The text alignment inside the rectangle.
-
inline const ColorSequence &colorSequence() const noexcept
Get the optional text color sequence.
-
inline void setColorSequence(ColorSequence colorSequence) noexcept
Set the text color sequence.
- Parameters:
colorSequence – The sequence of colors to apply while rendering the text.
-
inline Color color() const noexcept
Get the first text color from the configured sequence.
- Returns:
The first sequence color, or the inherited color if no sequence is configured.
-
inline void setColor(const Color color) noexcept
Set a single text color.
- Parameters:
color – The single base color to use for the rendered text.
-
inline BlockAttributes blockAttributes() const noexcept
Get the character attributes.
-
inline void setBlockAttributes(const BlockAttributes attributes) noexcept
Set the char attributes.
-
inline const FontPtr &font() const noexcept
Get the optional font. If this is empty, regular text rendering is used.
-
inline void setFont(const FontPtr &font) noexcept
Set the font.
- Parameters:
font – The font to use, or an empty pointer for regular terminal text rendering.
-
inline BlockTextAnimation animation() const noexcept
Get the animation mode.
-
inline void setAnimation(const BlockTextAnimation animation) noexcept
Set the animation mode.
- Parameters:
animation – The animation mode to apply while rendering the text.
-
inline const ParagraphOptions ¶graphOptions() const noexcept
Get the paragraph options.
- Returns:
The paragraph layout settings used for this text.
-
inline void setParagraphOptions(const ParagraphOptions &options) noexcept
Set the paragraph options.
- Parameters:
options – The paragraph layout settings to copy into this text configuration.
-
inline geometry::Alignment alignment() const noexcept
The alignment of the paragraph.
For the
Terminal::printParagraphcalls, vertical alignment is ignored. For thedrawBlockText(BlockText)calls, the vertical alignment is used to align the text in the given rectangle.
-
inline void setAlignment(const geometry::Alignment alignment) noexcept
Set the alignment of the paragraph.
-
inline int lineIndent() const noexcept
The line indent for all lines.
Only valid if the alignment is set to
geometry::Alignment::Left. This indent can be overridden byfirstLineIndentandwrappedLineIndent.
-
inline void setLineIndent(const int indent) noexcept
Set the line indent for all lines.
- Parameters:
indent – The new indent value.
>=0
-
inline int firstLineIndent() const noexcept
Get the first line indent.
This is the indent for the first line of the paragraph. Only valid if the alignment is set to
geometry::Alignment::Left.1:| <first indent> A long text that is broken | 2:| into multiple lines. |
-
inline void setFirstLineIndent(const int indent) noexcept
Set the first line indent.
- Parameters:
indent – The new indent value.
>=0orcUseLineIndentto uselineIndent
-
inline int wrappedLineIndent() const noexcept
Get the indent for wrapped lines.
This is the indent for all lines that are wrapped at the terminal width. Only valid if the alignment is set to
geometry::Alignment::Left.1:| <first indent> A long text that is broken | 2:| into multiple lines. |
-
inline void setWrappedLineIndent(const int indent) noexcept
Set the indent for wrapped lines.
- Parameters:
indent – The new indent value.
>=0orcUseLineIndentto uselineIndent
-
inline void setMargins(const block::Margins margins) noexcept
Set the margins around the paragraph.
- Parameters:
margins – The margins around the paragraph area.
-
inline ParagraphBackgroundMode backgroundMode() const noexcept
Get the background mode.
The background mode determines how the background of the paragraph is handled when lines are wrapped. It also controls how the background is extended for the last line in the paragraph.
With
BlockText/drawBlockText(...), cells outside the wrapped text keep the existing buffer background unless the selected mode fills them from the wrapped text. WithCursorWriter::printParagraph(), indentation and padding are written as spaces, so cells not covered by wrapped-text background use the writer’s current background.
-
inline void setBackgroundMode(const ParagraphBackgroundMode backgroundMode) noexcept
Set the background mode.
When using
CursorWriter::printParagraph(), configure the writer background before printing if indentation or trailing padding should visually match a surrounding panel.
-
inline const BlockString &lineBreakEndMark() const noexcept
Get the line break end mark.
The line break end mark is appended to wrapped physical lines. The mark is aligned to the right edge of the available paragraph area. If the mark contains color information, it will override the background color.
1:| A long text that is broken <end mark> | 2:| into multiple lines. |
- Returns:
The current line break end mark. Empty for no line break end mark.
-
inline void setLineBreakEndMark(BlockString mark)
Set the line break end mark.
- Parameters:
mark – The new line break end mark. Must not exceed two characters.
-
inline const BlockString &lineBreakStartMark() const noexcept
Get the line break start mark.
The line break start mark prepends wrapped continuation lines in left-aligned paragraphs. The mark is inserted after the continuation indentation. If the mark contains color information, it will override the background color.
1:| A long text that is broken | 2:| <start mark> into multiple lines. |
- Returns:
The current line break start mark. Empty for no line break start mark.
-
inline void setLineBreakStartMark(BlockString mark)
Set the line break start mark.
Unlike the end mark, this decoration may contain an arbitrary number of characters so nested line prefixes and continuation indentation can be represented.
- Parameters:
mark – The new line break start mark.
-
inline ParagraphSpacing paragraphSpacing() const noexcept
The spacing between paragraphs.
The behavior of the paragraph spacing depends on the used interface. For
Terminal::printParagraph()andCursorBuffer::printParagraph(), embedded newlines are hard line breaks inside one printed paragraph, and the configured spacing is appended once after the whole call. FordrawBlockText(BlockText)calls, each newline starts a new paragraph and spacing is inserted between paragraphs.
-
inline void setParagraphSpacing(const ParagraphSpacing spacing) noexcept
Set the paragraph spacing.
-
inline text::U32String wordSeparators() const
Get the configured word separators as a canonicalized character string.
Word separators split a source line into words. Consecutive separators are rendered as a single space between words. Tabs use special tab-stop handling in left-aligned paragraphs before separator handling is applied. The returned string is duplicate-free and normalized for comparison and display.
-
inline void setWordSeparators(const text::U32String &separators)
Set the word separators.
Tabs remain special tab stops in left-aligned paragraphs and act as regular word separators in other alignments when included here. The provided string is canonicalized automatically and mapped to shared defaults for common patterns.
- Parameters:
separators – A string of Unicode characters that are used to split words.
-
inline const Block &wordBreakMark() const noexcept
Get the word break mark.
The word break mark is used when a long word had to be split in a paragraph.
-
inline int maximumLineWraps() const noexcept
Get the maximum line wraps.
A value >0 limits the automatic wraps for one source line. Once the limit is reached, the current source line is truncated and
paragraphEllipsisMark()is appended if configured. Embedded line breaks start a new source line and therefore reset the wrap counter.- Returns:
The maximum number of line wraps, or zero for unlimited line wraps.
-
inline void setMaximumLineWraps(const int lines) noexcept
Set the maximum number of line wraps.
- Parameters:
lines – The maximum number of line wraps, or zero for unlimited line wraps.
-
inline const BlockString ¶graphEllipsisMark() const noexcept
Get the paragraph ellipsis mark.
This string is used to indicate that a paragraph would have to be wrapped over even more lines to be displayed completely. A single character can be used, but a short text like
(more…)works as well. Please note that the width of this mark further reduces the available space for the paragraph text.- Returns:
The paragraph ellipsis mark or an empty string if no ellipsis mark shall be used.
-
inline void setParagraphEllipsisMark(BlockString mark) noexcept
Set the paragraph ellipsis mark.
We recommend using a single character or a very short text. Longer texts quickly make paragraph rendering impossible.
- Parameters:
mark – The paragraph ellipsis mark. If empty, no ellipsis mark will be used.
-
inline const std::vector<int> &tabStops() const noexcept
Get the tab stops for the paragraph.
Only valid if the alignment is set to
geometry::Alignment::Left. If a line (text up to a newline character) contains TAB characters, each tab character will pick the next tab-stop columns value from this array. If the column is larger than the current column, spacing is inserted until the cursor reaches the tab-stop column. If the tab column is smaller, or there is no further tab stop in the sequence,tabOverflowBehavior()is used to decide whether the tab becomes a single space or starts a wrapped continuation line. In centered or right-aligned paragraphs, tabs usewordSeparatorsinstead of these tab stops. The special valuecTabWrappedLineIndentcan be used to use the same indent as for wrapped lines.
-
inline void setTabStops(std::vector<int> tabStops) noexcept
Set the tab stops.
-
inline TabOverflowBehavior tabOverflowBehavior() const noexcept
Get the overflow handling for non-advancing tab stops.
This mode is used if a TAB resolves to a tab-stop column that is not larger than the current column, or if there is no further configured tab stop.
-
inline void setTabOverflowBehavior(const TabOverflowBehavior behavior) noexcept
Set the overflow handling for non-advancing tab stops.
- Parameters:
behavior – The behavior to use for tabs that do not advance the current line.
-
inline ParagraphOnError onError() const noexcept
Get the error resolution if a paragraph cannot be rendered with the given settings.
If the screen layout and the given parameters do not allow the paragraph to be rendered properly, this error resolution is used.
- Returns:
The error resolution to use when a paragraph cannot be rendered.
-
inline void setOnError(const ParagraphOnError onError) noexcept
Set the error resolution.
- Parameters:
onError – The error resolution to use when a paragraph cannot be rendered.
-
inline explicit BlockTextOptions(const geometry::Alignment alignment) noexcept
-
struct BlockUnit : public erbsland::unit::IntegerUnit
The integer unit for terminal-block string positions and counts.
-
class Buffer : public erbsland::cterm::WritableBuffer
A mutable 2D buffer storing characters and colors for rendering.
Handling of non-1-width blocks:
Blocks with zero display width are ignored.
Blocks with a display width of 2 will overwrite two adjacent cells.
The first cell will contain the set character, the next cell a zero-width (empty) character.
Both cells will have the same color.
A 2-width block at the right edge is ignored.
Blocks with a display width > 2 are ignored.
Public Functions
-
Buffer()
Creates a 1x1 buffer filled with a space.
Usually only used as a placeholder until resized.
-
explicit Buffer(block::Size size, Block fillChar = Block::space())
Construct a buffer with the given size and fill it with an initial block.
- Parameters:
size – The dimensions of the buffer. block::Size must be at least 1x1.
fillChar – The optional fill character for the buffer.
- Throws:
err::ParameterError – if size is invalid.
-
virtual block::Size size() const noexcept override
Get the configured size of the buffer.
- Returns:
The width and height of the buffer.
-
virtual block::Rectangle rect() const noexcept override
Get a rectangle representing this buffer.
- Returns:
The rectangle for this buffer.
-
virtual const Block &get(block::Position pos) const noexcept override
Read the block stored at the given position.
- Parameters:
pos – The coordinates within the buffer.
- Returns:
A reference to the stored block.
-
virtual WritableBufferPtr clone() const override
Create a writeable copy of this buffer.
This will copy every block from this buffer into a new independent instance.
-
virtual void resize(block::Size newSize) override
Resize this buffer in a memory-efficient way.
The content of the resized buffer is undefined and must be filled with new content.
- Parameters:
newSize – The new size for the buffer.
-
virtual void resize(block::Size size, BufferResizeMode mode, Block fillChar) override
Resize this buffer and optionally preserve visible content.
The default implementation calls
resize(block::Size)forBufferResizeMode::Fast. ForBufferResizeMode::PreserveContent, it clones the current buffer, resizes it usingresize(block::Size), and restores the visible content withsetFrom(). Implementations can override this when they provide a faster preserve-content path.- Parameters:
size – The new size for the buffer.
mode – How existing content should be handled during resizing.
fillChar – The character to fill newly visible cells with in preserve-content mode.
-
virtual void set(block::Position pos, const Block &block) noexcept override
Write a block at the given position.
Note
Writes outside the buffer are ignored.
- Parameters:
pos – The coordinates within the buffer.
block – The block value to store.
-
virtual void setAndResizeFrom(const ReadableBuffer &other) override
Copy the content from another buffer and match its size.
This buffer is completely overwritten and resized to the size of
other.- Parameters:
other – The buffer to copy from.
-
virtual void fill(const Block &fillBlock) noexcept override
Fill/clear the buffer with the given character.
- Parameters:
fillBlock – The block to use to fill the buffer.
-
void drawBlockText(const text::String &text, geometry::Alignment alignment, block::Rectangle rect, Color color = {}, std::size_t animationCycle = 0)
Draw text into a rectangle using the legacy parameter order.
- Parameters:
text – The text to render.
alignment – The alignment inside the rectangle.
rect – The target rectangle.
color – The text color.
animationCycle – Animation cycle for animated text. Invalid UTF-8 bytes are replaced with the Unicode replacement character.
-
void drawBitmap(const Bitmap &bitmap, block::Position pos, const BitmapDrawOptions &options = BitmapDrawOptions::defaultOptions(), std::size_t animationCycle = 0) noexcept
Draw a bitmap at a given position.
The bitmap is rendered according to
options.scaleMode(). Ifoptions.block16Style()is set, it overrides the scale mode and renders one terminal cell per bitmap pixel. Pixels or rendered cells outside the buffer are ignored.- Parameters:
bitmap – The bitmap to draw.
pos – The position of the top left corner.
options – Bitmap drawing options.
animationCycle – Animation cycle for color animations.
-
void drawBitmap(const Bitmap &bitmap, block::Rectangle rect, geometry::Alignment alignment = geometry::Alignment::TopLeft, const BitmapDrawOptions &options = BitmapDrawOptions::defaultOptions(), std::size_t animationCycle = 0) noexcept
Draw a bitmap into the given rectangle.
The rendered bitmap is aligned inside
rect. If it is larger thanrect, it is cropped according to the alignment.Note
For half-block drawing mode, alignment and cropping happen at rendered cell boundaries, not per pixel.
- Parameters:
bitmap – The bitmap to draw.
rect – The rectangle to draw the bitmap into.
alignment – geometry::Alignment of the bitmap within the rectangle.
options – Bitmap drawing options.
animationCycle – Animation cycle for color animations.
-
virtual void drawBlockText(block::Position pos, const BlockString &str)
Draw a text without warping from the given position.
A newline breaks to the next line, starting at
pos.x. Characters outside this buffer are cut off.- Parameters:
pos – The start position (top-left corner).
str – The text to draw on this buffer.
-
void drawBlockText(const BlockText &text, std::size_t animationCycle = 0)
If fg or bg is set to
Inherited, the current color from the buffer is used.Draw simple text into a rectangle. If fg or bg is set to
Inherited, the current color from the buffer is used.- Parameters:
text – The text description.
animationCycle – Animation cycle for animated text.
-
void drawBlockText(const text::String &text, block::Rectangle rect, geometry::Alignment alignment = geometry::Alignment::TopLeft, BlockStyle style = {}, std::size_t animationCycle = 0)
Draw simple text into a rectangle.
If fg or bg is set to
Inherited, the current color from the buffer is used.- Parameters:
text – The text to render.
rect – The target rectangle.
alignment – The alignment inside the rectangle.
style – The base text style.
animationCycle – Animation cycle for animated text. Invalid UTF-8 bytes are replaced with the Unicode replacement character.
-
void drawBlockText(const text::U32String &text, block::Rectangle rect, geometry::Alignment alignment = geometry::Alignment::TopLeft, BlockStyle style = {}, std::size_t animationCycle = 0)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
void drawBlockText(const BlockString &text, block::Rectangle rect, geometry::Alignment alignment = geometry::Alignment::TopLeft, BlockStyle style = {}, std::size_t animationCycle = 0)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
void drawBlockText(const BlockString &text, block::Rectangle rect, const BlockTextOptions &options, std::size_t animationCycle = 0)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
virtual void fill(const Block &fillBlock) noexcept
Fill/clear the buffer with the given character.
- Parameters:
fillBlock – The block to use to fill the buffer.
-
void fill(block::Rectangle rect, const Block &fillBlock, const BlockCombinationStylePtr &combinationStyle = {}) noexcept
Fill the given rectangle.
Positions outside the buffer are ignored.
- Parameters:
rect – The rectangle to be filled.
fillBlock – The block for filling.
combinationStyle – The combination style for overwriting existing characters.
-
void fill(block::Rectangle rect, const Tile9StylePtr &style, Color baseColor = {}, const BlockCombinationStylePtr &combinationStyle = {}) noexcept
Fill the given rectangle using a repeating 9-tile style.
Positions outside the buffer are ignored.
- Parameters:
rect – The rectangle to be filled.
style – The tile style to repeat across the rectangle.
baseColor – The base color underneath the tile style.
combinationStyle – The combination style for overwriting existing characters.
-
void fill(block::Rectangle rect, const Tile9StylePtr &style, BlockStyle baseStyle, const BlockCombinationStylePtr &combinationStyle = {}) noexcept
Fill the given rectangle using a repeating 9-tile style.
Positions outside the buffer are ignored.
- Parameters:
rect – The rectangle to be filled.
style – The tile style to repeat across the rectangle.
baseStyle – The base style underneath the tile style.
combinationStyle – The combination style for overwriting existing characters.
-
virtual void resize(block::Size newSize) = 0
Resize this buffer in a memory-efficient way.
The content of the resized buffer is undefined and must be filled with new content.
- Parameters:
newSize – The new size for the buffer.
-
virtual void resize(block::Size size, BufferResizeMode mode, Block fillChar)
Resize this buffer and optionally preserve visible content.
The default implementation calls
resize(block::Size)forBufferResizeMode::Fast. ForBufferResizeMode::PreserveContent, it clones the current buffer, resizes it usingresize(block::Size), and restores the visible content withsetFrom(). Implementations can override this when they provide a faster preserve-content path.- Parameters:
size – The new size for the buffer.
mode – How existing content should be handled during resizing.
fillChar – The character to fill newly visible cells with in preserve-content mode.
-
virtual void set(block::Position pos, const Block &block) noexcept = 0
Write a block at the given position.
Note
Writes outside the buffer are ignored.
- Parameters:
pos – The coordinates within the buffer.
block – The block value to store.
-
virtual void set(block::Position pos, const Block &block, const BlockCombinationStylePtr &combinationStyle) noexcept
Write a block at the given position using a combination style.
Note
Writes outside the buffer are ignored.
- Parameters:
pos – The coordinates within the buffer.
block – The block value to store.
combinationStyle – The combination style for overwriting existing characters.
-
virtual void set(block::Position pos, const BlockString &str) noexcept
Write a string at the given position.
NL jumps to the next row. Other control and zero-width characters are ignored. Color (even inherited) overwrites the existing characters. Use
drawBlockText(pos, text)for a color overlay.- Parameters:
pos – The coordinates within the buffer.
str – The string to write.
Public Static Functions
-
static Buffer fromLinesInString(const BlockString &text)
Creates a buffer from the lines in a string.
This function splits the given string into lines and creates a buffer with a matching size.
- Parameters:
text – The string to split into lines and create a buffer from. Must not be empty.
- Returns:
A buffer containing the lines from the input string.
-
static Buffer fromLines(const BlockStringLines &lines)
Creates a buffer from the lines in a string.
- Parameters:
lines – The lines to create the buffer from. Must not be empty.
- Returns:
A buffer containing the lines from the input string.
-
class BufferConstRefView : public erbsland::cterm::BufferViewBase
A view that uses a reference to the content.
This view is to use as a thin temporary wrapper on the stack.
Public Functions
-
inline BufferConstRefView(const ReadableBuffer &content, const block::Size viewSize) noexcept
Create a view of the given content, with a given size.
The view shares the top-left corner with the buffer.
- Parameters:
content – A reference to the content buffer.
viewSize – The size of the view.
-
inline BufferConstRefView(const ReadableBuffer &content, const block::Rectangle viewRect) noexcept
Create a view of the given content.
- Parameters:
content – A reference to the content buffer.
viewRect – The rectangle of the view.
-
inline BufferConstRefView(const ReadableBuffer &content, const block::Size viewSize) noexcept
-
class BufferDrawOptions
Options for drawing a buffer onto another buffer.
Public Functions
-
inline explicit BufferDrawOptions(const block::Position targetPos) noexcept
Create default draw options with a target position.
- Parameters:
targetPos – The target position.
-
inline BufferDrawOptions(const block::Rectangle targetRect, const block::Rectangle sourceRect) noexcept
Create default draw options with a target rectangle and alignment.
- Parameters:
targetRect – The target rectangle.
sourceRect – The source rectangle.
-
inline const block::Rectangle &targetRect() const noexcept
Get the target rectangle.
- Returns:
The target rectangle.
-
inline bool isTargetPosition() const noexcept
Test if the target is just a position.
-
inline void setTargetRect(const block::Rectangle &rect) noexcept
Set the target rectangle.
- Parameters:
rect – The target rectangle.
-
inline const block::Rectangle &sourceRect() const noexcept
Get the source rectangle.
- Returns:
The source rectangle.
-
inline bool useFullSource() const noexcept
Test if the whole source shall be used.
-
inline void setSourceRect(const block::Rectangle &rect) noexcept
Set the source rectangle.
- Parameters:
rect – The source rectangle.
-
inline const BlockCombinationStylePtr &combinationStyle() const noexcept
Get the combination style.
If a combination style is set, the characters from the source buffer are combined with the target buffer. A combination style overrides the
overrideColorssetting.- Returns:
The combination style.
-
inline void setCombinationStyle(const BlockCombinationStylePtr &style) noexcept
Set the combination style.
- Parameters:
style – The combination style.
-
inline bool overwriteColors() const noexcept
Test if colors should be overwritten 1:1 in the target buffer.
If this is set to
true, evenInheritcolors are written as they are in the target buffer. If this is set tofalse,Inheritcolors are combined withuseBaseColor(<from target buffer>).
-
inline void setOverwriteColors(const bool overwrite) noexcept
Set if colors should be overwritten 1:1 in the target buffer.
- Parameters:
overwrite –
trueto overwrite colors in the target buffer.
-
inline explicit BufferDrawOptions(const block::Position targetPos) noexcept
-
enum class erbsland::cterm::BufferResizeMode : uint8_t
Describes how a buffer resize should handle existing content.
Values:
-
enumerator Fast
Resize using the fastest available path. Existing content order becomes undefined.
-
enumerator PreserveContent
Preserve the visible content and fill newly created cells with the fill character.
-
enumerator Fast
-
class BufferView : public erbsland::cterm::BufferViewBase
A view that uses a shared pointer to the content.
Public Functions
-
BufferView() = default
Create an empty view.
This creates a 1x1 view that returns the ‘block::Direction::None’ character.
-
inline explicit BufferView(const block::Size viewSize) noexcept
Create an empty view of a given size.
This creates a view that returns the ‘block::Direction::None’ character.
- Parameters:
viewSize – The size of the view.
-
inline BufferView(ReadableBufferPtr content, const block::Size viewSize) noexcept
Create a view of the given content, with a given size.
The view shares the top-left corner with the buffer.
- Parameters:
content – The buffer to create the view from.
viewSize – The size of the view.
-
inline BufferView(ReadableBufferPtr content, const block::Rectangle viewRect) noexcept
Create a view of the given content.
- Parameters:
content – The buffer to create the view from.
viewRect – The rectangle of the view.
-
inline virtual const Block &get(const block::Position pos) const noexcept override
Read the block stored at the given position.
- Parameters:
pos – The coordinates within the buffer.
- Returns:
A reference to the stored block.
-
const ReadableBufferPtr &content() const noexcept
Access the content.
-
void setContent(ReadableBufferPtr buffer) noexcept
Replace the content.
-
BufferView() = default
-
class BufferViewBase : public erbsland::cterm::ReadableBuffer
The base class for all buffer views.
Subclassed by erbsland::cterm::BufferConstRefView, erbsland::cterm::BufferView
Public Functions
-
inline explicit BufferViewBase(const block::Rectangle viewRectangle) noexcept
Create a buffer view with the given visible rectangle in the source buffer.
- Parameters:
viewRectangle – The rectangle of the underlying content that shall be exposed through the view.
-
virtual block::Size size() const noexcept override
Get the configured size of the buffer.
- Returns:
The width and height of the buffer.
-
virtual block::Rectangle rect() const noexcept override
Get a rectangle representing this buffer.
- Returns:
The rectangle for this buffer.
-
virtual WritableBufferPtr clone() const override
Create a writeable copy of this buffer.
This will copy every block from this buffer into a new independent instance.
-
const block::Rectangle &viewRect() const noexcept
Get the rectangle in the underlying content that is currently visible through this view.
-
void setViewRect(block::Rectangle rect) noexcept
Set the rectangle in the underlying content that shall be visible through this view.
- Parameters:
rect – The new source rectangle for the view.
-
bool showCropCharacters() const noexcept
Test whether crop indicator characters are shown when the view is clipped by the source buffer.
-
void setShowCropCharacters(bool show) noexcept
Enable or disable crop indicator characters.
- Parameters:
show –
trueto render crop indicators inside the view.
-
inline explicit BufferViewBase(const block::Rectangle viewRectangle) noexcept
-
class Color
A foreground/background color pair for terminal rendering.
Public Functions
-
Color() = default
Create a color that inherits both components from the layer below.
If no lower layer exists, terminal output resolves inherited colors to the terminal defaults.
-
inline constexpr Color(const Foreground foreground, const Background background) noexcept
Create a color from explicit foreground and background parts.
- Parameters:
foreground – The foreground color.
background – The background color.
-
inline constexpr Color(const Foreground foreground) noexcept
Create a color with an explicit foreground and inherited background color.
- Parameters:
foreground – The background color.
-
inline constexpr Color(const Foreground::Hue foreground) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
inline constexpr Color(const Background background) noexcept
Create a color with an explicit background and inherited foreground color.
- Parameters:
background – The background color.
-
inline constexpr Color(const Background::Hue background) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
inline Foreground fg() const noexcept
Get the foreground color.
-
inline void setFg(const Foreground foreground) noexcept
Set the foreground color.
- Parameters:
foreground – The new foreground color.
-
inline Background bg() const noexcept
Get the background color.
-
inline void setBg(const Background background) noexcept
Set the background color.
- Parameters:
background – The new background color.
-
text::String toString() const
Convert this color to its canonical textual representation.
- Returns:
The canonical color specification.
-
Color overlayWith(const Color &overlay) const
Combine this color with a new overlay color.
Foreground or background components set to
Inheritedkeep the value from this color. Components set toDefaultexplicitly reset to the terminal default color.Examples:
[this.fg = red] + [new.fg = inherited] => [result.fg = red]
[this.fg = red] + [new.fg = default] => [result.fg = default]
[this.fg = red] + [new.fg = green] => [result.fg = green]
- Parameters:
overlay – The overlay color.
- Returns:
The new color with the overlay applied.
-
inline constexpr std::size_t hash() const noexcept
Get a hash for this color pair.
Public Members
-
Foreground _foreground
Foreground component of the color.
-
Background _background
Background component of the color.
Public Static Functions
-
static Color fromString(const text::String &str, Color defaultValue)
Convert a color or color-pair into a block color, or return a fallback.
- Parameters:
str – The textual color specification.
defaultValue – The value returned for invalid text.
- Returns:
The parsed color or
defaultValue.
-
static Color fromStringOrThrow(const text::String &str)
Convert a color or color-pair into a block color.
- Parameters:
str – The textual color specification.
- Throws:
err::ParseError – if the specification is invalid.
- Returns:
The parsed color.
-
static inline Color fromIndex16(const int fgIndex, const int bgIndex)
Converts two indexes into a color-pair.
See also
ColorPart::fromIndex16 for details.
-
Color() = default
-
class ColorBase
Shared implementation for foreground and background color values.
Subclassed by erbsland::cterm::ColorPart< ColorRole::Foreground >, erbsland::cterm::ColorPart< ColorRole::Background >, erbsland::cterm::ColorPart< tColorType >
Public Types
-
enum class Value : uint8_t
Internal color identifiers used for ANSI conversion and parsing.
Values:
-
enumerator Black
Black.
-
enumerator Red
Dark red.
-
enumerator Green
Dark green.
-
enumerator Yellow
Dark yellow.
-
enumerator Blue
Blue.
-
enumerator Magenta
Magenta.
-
enumerator Cyan
Cyan.
-
enumerator White
Light gray.
-
enumerator BrightBlack
Gray.
-
enumerator BrightRed
Bright red.
-
enumerator BrightGreen
Bright green.
-
enumerator BrightYellow
Bright yellow.
-
enumerator BrightBlue
Blue.
-
enumerator BrightMagenta
Magenta.
-
enumerator BrightCyan
Cyan.
-
enumerator BrightWhite
White.
-
enumerator Default
The default color of the terminal.
-
enumerator Inherited
Inherited color from the layer below, or use the default color.
-
enumerator _Count
Number of values.
-
enumerator Black
-
enum class Value : uint8_t
-
template<ColorRole tColorType>
class ColorPart : public erbsland::cterm::ColorBase A foreground or background color.
Public Functions
-
ColorPart() = default
Create the inherited color for this role.
-
inline constexpr ColorPart(const Hue color)
Create a color from one of the predefined hue constants.
- Parameters:
color – The named hue.
-
inline int ansiCode() const noexcept
Convert this color part to its ANSI SGR numeric code.
-
inline constexpr std::size_t hash() const noexcept
Get a hash for this color part.
Public Static Functions
-
static inline ColorPart fromString(const text::String &str, const ColorPart defaultValue)
Create a color from the given string, or return a fallback.
Public Static Attributes
-
static constexpr auto cCodeBase = (tColorType == ColorRole::Foreground ? 30 : 40)
Base ANSI escape code for this color role.
-
ColorPart() = default
-
using erbsland::cterm::Background = ColorPart<ColorRole::Background>
The background color.
-
using erbsland::cterm::bg = Background
Short alias for
Background.
-
using erbsland::cterm::Foreground = ColorPart<ColorRole::Foreground>
The foreground color.
-
using erbsland::cterm::fg = Foreground
Short alias for
Foreground.
-
enum class erbsland::cterm::ColorRole : uint8_t
The type color.
Values:
-
enumerator Foreground
-
enumerator Background
-
enumerator Foreground
-
class ColorSequence
A configurable sequence of complete
Colorvalues with run-length style counts.Each effective position in the sequence yields one full foreground/background color pair. The sequence can be accessed by cyclic index or by a normalized value in the range
0.0..1.0. Consumers may perform multiple lookups, for example to combine the foreground of one entry with the background of a neighboring entry.Public Functions
-
ColorSequence() = default
Create an empty color sequence.
-
explicit ColorSequence(Color color, std::size_t count = 1) noexcept
Create a sequence with one repeated full-color entry.
- Parameters:
color – The color to add.
count – How often the color should repeat.
-
ColorSequence(std::initializer_list<Color> colors) noexcept
Create a sequence from individual full-color entries with count
1.- Parameters:
colors – The colors to add in order.
-
ColorSequence(std::initializer_list<Entry> entries) noexcept
Create a sequence from explicit run-length encoded entries.
- Parameters:
entries – The entries to add in order.
-
void add(Color color, std::size_t count = 1) noexcept
Add one full-color entry to this sequence.
- Parameters:
color – The color for this entry.
count – How often this color should repeat in the effective sequence.
-
Color color(std::size_t index) const noexcept
Get one complete color entry by effective sequence index.
Indexes wrap around to support cyclic access.
- Parameters:
index – The effective sequence index.
- Returns:
The full color at the wrapped index, or the inherited color if the sequence is empty.
-
Color colorNormalized(double normalized) const noexcept
Get a color by normalized position in the range
0.0..1.0.Values outside this range are clamped.
- Parameters:
normalized – The normalized sequence position.
- Returns:
The color at the requested normalized position.
-
inline std::size_t sequenceLength() const noexcept
Effective sequence length (sum of all counts).
-
inline std::size_t entryCount() const noexcept
Number of configured entries.
-
inline bool empty() const noexcept
Test if this sequence has no effective entries.
-
ColorSequence() = default
-
class CropEdges
Flags for crop edges and corners.
Public Types
-
using Flags = std::bitset<8>
Bitset type storing the eight crop-edge directions.
Public Functions
-
CropEdges() = default
No crop edges.
-
inline void reset() noexcept
Reset all crop edges.
-
inline block::Direction edgeForView(const block::Position pos, const block::Rectangle viewRect) const noexcept
Test if a frame position in a view rectangle matches a given crop direction.
This function automatically handles the corners of the view rectangle correctly. Corner directions, like
block::Direction::NorthEastare only returned ifblock::Direction::Northandblock::Direction::Eastare set. Otherwise, the corner direction matches the main direction.
-
using Flags = std::bitset<8>
-
class CursorBuffer : public erbsland::cterm::RemappedBuffer, public erbsland::cterm::CursorWriter
A buffer that can be used to write text using a cursor.
Cursor movement emulates VT100 terminals:
Cursor movements are bound to the buffer (they do not wrap around).
Printing characters do wrap around if wrap mode is enabled (it’s enabled by default.)
Printing a character in the last column is special:
A 1-width character is printed in the last column, but the cursor isn’t moved yet. A
wrapOnNextCharis set instead of the cursor movement.As soon as the next character is printed, the cursor is moved to the next line first; then the character is printed.
When a 2-width character is printed in the last column, the cursor is moved to the next line first; then the character is printed (not VT100, it didn’t have 2-width characters).
If the
wrapOnNextCharis set, and the cursor is moved, the flag is cleared.If the
wrapOnNextCharis set, and a line-break is printed, the flag is cleared first before moving the cursor to the next line.
Public Types
-
enum class OverflowMode : uint8_t
The overflow mode determines what happens when the cursor gets a line-break in the last line.
Values:
-
enumerator Shift
Shift the buffer content one line up, exposing a new blank line at the bottom.
-
enumerator Wrap
The cursor wraps back to the first line of the buffer.
-
enumerator ExpandThenShift
Expand the buffer by one line, keeping the content. Up to maximumSize(), then scroll.
-
enumerator ExpandThenWrap
Expand the buffer by one line, keeping the content. Up to maximumSize(), then wrap.
-
enumerator Shift
Public Functions
-
inline explicit CursorBuffer(const block::Size startSize, const OverflowMode overflowMode = OverflowMode::Shift, const block::Size maximumSize = cMaximumSize, const Block fillChar = Block::space())
Create a new cursor buffer with the given startSize.
- Parameters:
startSize – The start size of the buffer.
overflowMode – The overflow mode of the buffer.
maximumSize – The maximum size of the buffer. Only
heightis used.fillChar – The character used to initialize and refill empty cells.
- Throws:
err::ParameterError – if startSize exceeds the maximum or fillChar is not a single-width character.
-
inline CursorBuffer()
Create a new cursor buffer with a default size of 80x25 and overflow mode
Shift.
-
void setMaximumSize(block::Size maximumSize) noexcept
Change the maximum size.
Changing the maximum size will not affect the current content.
- Parameters:
maximumSize – The new maximum size.
-
OverflowMode overflowMode() const noexcept
Get the overflow mode for this buffer.
-
void setOverflowMode(OverflowMode mode) noexcept
Set the overflow mode for this buffer.
- Parameters:
mode – The new overflow mode.
-
const Block &fillChar() const noexcept
Get the character used for newly exposed or empty cells.
- Returns:
The current fill character.
-
void setFillChar(Block fillChar)
Set the character used for newly exposed or empty cells.
The character should have a display width of one cell.
- Parameters:
fillChar – The new fill character.
- Throws:
err::ParameterError – if fillChar is not a single-width character.
-
inline virtual block::Size size() const noexcept override
Get the configured size of the buffer.
- Returns:
The width and height of the buffer.
-
virtual Color color() const noexcept override
Get the current color.
- Returns:
The currently tracked terminal color state.
-
virtual BlockAttributes blockAttributes() const noexcept override
Get the current character attributes.
- Returns:
The currently tracked character attribute state.
-
virtual void setColor(Color color) noexcept override
Set foreground and background color.
Note
Inheritedcolors are converted toDefaultcolors.- Parameters:
color – The new combined color.
-
virtual void setBlockAttributes(BlockAttributes attributes) noexcept override
Set all character attributes.
Unspecified attributes are treated as disabled.
- Parameters:
attributes – The new character attributes.
-
virtual void setForeground(Foreground color) noexcept override
Set the foreground color.
Note
Inheritedcolors are converted toDefaultcolors.- Parameters:
color – The new foreground color.
-
virtual void setBackground(Background color) noexcept override
Set the background color.
Note
Inheritedcolors are converted toDefaultcolors.- Parameters:
color – The new background color.
-
virtual BlockAttributes supportedBlockAttributes() const noexcept override
Get the character attributes supported by this writer.
- Returns:
The supported character attributes.
-
virtual void moveCursor(block::Position posOrDelta, MoveMode mode) noexcept override
Move the cursor absolute or relative.
If the resulting position is out of bounds, the result is undefined.
- Parameters:
posOrDelta – The absolute position or delta for the move.
mode – The move mode, either absolute or relative.
-
virtual void setAutoWrap(bool enabled) noexcept override
Enabled/disable auto-wrap.
Auto wrap controls if the cursor automatically wraps to the next line when reaching the right margin. This is a feature that can be enabled or disabled. Do not confuse this with line wrapping, which is a different feature.
- Parameters:
enabled – Whether to enable or disable auto-wrap.
-
virtual void clearScreen() noexcept override
Clears the screen/writing area.
-
virtual void write(const Block &character) noexcept override
Write a character at the current cursor position.
Inherited color components resolve against the currently active color. Overwrites the character under the cursor.
- Parameters:
character – The character to write.
-
virtual void write(const BlockString &str) noexcept override
Write a string at the current cursor position.
Inherited color components in each character resolve against the currently active color. Overwrites the characters under the cursor.
- Parameters:
str – The string to write.
-
virtual void writeResolved(const Block &character) noexcept override
Write a character that is already fully resolved against the writer state.
This bypasses any additional inherited-style resolution in implementations that can optimize for it.
- Parameters:
character – The already resolved character to write.
-
virtual void writeResolved(const BlockString &str) noexcept override
Write a string whose characters are already fully resolved against the writer state.
This bypasses any additional inherited-style resolution in implementations that can optimize for it.
- Parameters:
str – The already resolved string to write.
-
virtual void write(const ReadableBuffer &buffer) noexcept override
Write a buffer at the current cursor position.
This will not perform any additional formatting, clipping, or processing. Each line of the buffer will be written, and a line-break added after each line.
- Parameters:
buffer – The buffer to write.
-
virtual void writeLineBreak() noexcept override
Write a line-break.
This will move the cursor to the beginning of the next line.
-
virtual void setColor(Color color) noexcept = 0
Set foreground and background color.
Note
Inheritedcolors are converted toDefaultcolors.- Parameters:
color – The new combined color.
-
inline void setColor(const Foreground foregroundColor, const Background backgroundColor) noexcept
Set foreground and background color.
Note
Inheritedcolors are converted toDefaultcolors.- Parameters:
foregroundColor – The new foreground color.
backgroundColor – The new background color.
-
virtual void write(const Block &character) noexcept = 0
Write a character at the current cursor position.
Inherited color components resolve against the currently active color. Overwrites the character under the cursor.
- Parameters:
character – The character to write.
-
virtual void write(const BlockString &str) noexcept = 0
Write a string at the current cursor position.
Inherited color components in each character resolve against the currently active color. Overwrites the characters under the cursor.
- Parameters:
str – The string to write.
-
inline void write(const text::String &text) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Invalid UTF-8 bytes are replaced with the Unicode replacement character.
-
inline void write(const text::U32String &text) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
virtual void write(const ReadableBuffer &buffer) noexcept = 0
Write a buffer at the current cursor position.
This will not perform any additional formatting, clipping, or processing. Each line of the buffer will be written, and a line-break added after each line.
- Parameters:
buffer – The buffer to write.
-
virtual void writeLineBreak() noexcept = 0
Write a line-break.
This will move the cursor to the beginning of the next line.
-
class CursorWriter
The shared interface for buffers/terminals that support cursor-based output.
Subclassed by erbsland::cterm::CursorBuffer, erbsland::cterm::Terminal
Public Functions
-
virtual Color color() const noexcept = 0
Get the current color.
- Returns:
The currently tracked terminal color state.
-
virtual BlockAttributes blockAttributes() const noexcept = 0
Get the current character attributes.
- Returns:
The currently tracked character attribute state.
-
inline BlockStyle style() const noexcept
Get the current combined text style.
- Returns:
The currently tracked terminal style.
-
virtual void setColor(Color color) noexcept = 0
Set foreground and background color.
Note
Inheritedcolors are converted toDefaultcolors.- Parameters:
color – The new combined color.
-
virtual void setBlockAttributes(BlockAttributes attributes) noexcept = 0
Set all character attributes.
Unspecified attributes are treated as disabled.
- Parameters:
attributes – The new character attributes.
-
inline void setStyle(const BlockStyle style) noexcept
Set the full terminal style.
Inherited colors are converted to defaults and unspecified attributes are treated as disabled.
- Parameters:
style – The new combined style.
-
inline void setColor(const Foreground foregroundColor, const Background backgroundColor) noexcept
Set foreground and background color.
Note
Inheritedcolors are converted toDefaultcolors.- Parameters:
foregroundColor – The new foreground color.
backgroundColor – The new background color.
-
virtual void setForeground(Foreground color) noexcept = 0
Set the foreground color.
Note
Inheritedcolors are converted toDefaultcolors.- Parameters:
color – The new foreground color.
-
virtual void setBackground(Background color) noexcept = 0
Set the background color.
Note
Inheritedcolors are converted toDefaultcolors.- Parameters:
color – The new background color.
-
inline void setDefaultColor() noexcept
Set the terminal default foreground and background colors.
-
virtual BlockAttributes supportedBlockAttributes() const noexcept = 0
Get the character attributes supported by this writer.
- Returns:
The supported character attributes.
-
inline void setBold(const bool enabled) noexcept
Enable or disable the bold attribute.
- Parameters:
enabled –
trueto enable bold,falseto disable it.
-
inline void setDim(const bool enabled) noexcept
Enable or disable the dim attribute.
- Parameters:
enabled –
trueto enable dim,falseto disable it.
-
inline void setItalic(const bool enabled) noexcept
Enable or disable the italic attribute.
- Parameters:
enabled –
trueto enable italic,falseto disable it.
-
inline void setUnderline(const bool enabled) noexcept
Enable or disable the underline attribute.
- Parameters:
enabled –
trueto enable underline,falseto disable it.
-
inline void setBlink(const bool enabled) noexcept
Enable or disable the blink attribute.
- Parameters:
enabled –
trueto enable blink,falseto disable it.
-
inline void setReverse(const bool enabled) noexcept
Enable or disable the reverse attribute.
- Parameters:
enabled –
trueto enable reverse,falseto disable it.
-
inline void setHidden(const bool enabled) noexcept
Enable or disable the hidden attribute.
- Parameters:
enabled –
trueto enable hidden,falseto disable it.
-
inline void setStrikethrough(const bool enabled) noexcept
Enable or disable the strikethrough attribute.
- Parameters:
enabled –
trueto enable strikethrough,falseto disable it.
-
inline virtual void moveLeft(const block::Coordinate count) noexcept
Move the cursor to the left.
If the resulting position is out of bounds, the result is undefined.
- Parameters:
count – The number of terminal cells to move.
-
inline virtual void moveRight(const block::Coordinate count) noexcept
Move the cursor to the right.
If the resulting position is out of bounds, the result is undefined.
- Parameters:
count – The number of terminal cells to move.
-
inline virtual void moveUp(const block::Coordinate count) noexcept
Move the cursor up.
If the resulting position is out of bounds, the result is undefined.
- Parameters:
count – The number of terminal cells to move.
-
inline virtual void moveDown(const block::Coordinate count) noexcept
Move the cursor down.
If the resulting position is out of bounds, the result is undefined.
- Parameters:
count – The number of terminal cells to move.
-
inline virtual void moveTo(const block::Position pos) noexcept
Move the cursor to the given position.
If the resulting position is out of bounds, the result is undefined.
- Parameters:
pos – The position to move the cursor to.
-
inline virtual void moveHome() noexcept
Moves the cursor to the home position.
-
virtual void moveCursor(block::Position posOrDelta, MoveMode mode) noexcept = 0
Move the cursor absolute or relative.
If the resulting position is out of bounds, the result is undefined.
- Parameters:
posOrDelta – The absolute position or delta for the move.
mode – The move mode, either absolute or relative.
-
inline virtual std::optional<block::Position> cursorPosition() noexcept
Try to get the current cursor position.
Not all implementations support retrieving the cursor position.
- Returns:
The current cursor position, or
std::nulloptif it cannot be determined.
-
virtual void setAutoWrap(bool enabled) noexcept = 0
Enabled/disable auto-wrap.
Auto wrap controls if the cursor automatically wraps to the next line when reaching the right margin. This is a feature that can be enabled or disabled. Do not confuse this with line wrapping, which is a different feature.
- Parameters:
enabled – Whether to enable or disable auto-wrap.
-
inline virtual void setCursorVisible(bool visible) noexcept
Make the cursor visible/invisible.
Not all implementations support changing the cursor visibility.
- Parameters:
visible – Whether to make the cursor visible or invisible.
-
virtual void clearScreen() noexcept = 0
Clears the screen/writing area.
-
virtual void write(const Block &character) noexcept = 0
Write a character at the current cursor position.
Inherited color components resolve against the currently active color. Overwrites the character under the cursor.
- Parameters:
character – The character to write.
-
virtual void write(const BlockString &str) noexcept = 0
Write a string at the current cursor position.
Inherited color components in each character resolve against the currently active color. Overwrites the characters under the cursor.
- Parameters:
str – The string to write.
-
inline virtual void writeResolved(const BlockString &str) noexcept
Write a string whose characters are already fully resolved against the writer state.
This bypasses any additional inherited-style resolution in implementations that can optimize for it.
- Parameters:
str – The already resolved string to write.
-
inline virtual void writeResolved(const Block &character) noexcept
Write a character that is already fully resolved against the writer state.
This bypasses any additional inherited-style resolution in implementations that can optimize for it.
- Parameters:
character – The already resolved character to write.
-
inline virtual void writeRepeated(const Block &character, const int count) noexcept
Write the same character multiple times at the current cursor position.
Inherited color components resolve against the currently active color for each repetition. A non-positive count is ignored.
- Parameters:
character – The character to repeat.
count – The number of repetitions.
-
inline virtual void writeRepeatedResolved(const Block &character, const int count) noexcept
Write the same fully resolved character multiple times at the current cursor position.
This bypasses any additional inherited-style resolution in implementations that can optimize for it. A non-positive count is ignored.
- Parameters:
character – The already resolved character to repeat.
count – The number of repetitions.
-
inline void write(const text::String &text) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Invalid UTF-8 bytes are replaced with the Unicode replacement character.
-
inline void write(const text::U32String &text) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
virtual void write(const ReadableBuffer &buffer) noexcept = 0
Write a buffer at the current cursor position.
This will not perform any additional formatting, clipping, or processing. Each line of the buffer will be written, and a line-break added after each line.
- Parameters:
buffer – The buffer to write.
-
virtual void writeLineBreak() noexcept = 0
Write a line-break.
This will move the cursor to the beginning of the next line.
-
template<PrintableArg... Args>
inline void print(Args... args) noexcept Print elements at the cursor position.
- Parameters:
args – The arguments to print.
-
template<PrintableArg... Args>
inline void printLine(Args... args) noexcept Print elements at the cursor position and add a line break.
- Parameters:
args – The arguments to print.
-
inline auto printParagraph(const BlockString ¶graph, const ParagraphOptions &options = ParagraphOptions::defaultOptions()) noexcept -> int
Print a word-wrapped paragraph at the cursor position.
- Parameters:
paragraph – The paragraph text to write. Can use line breaks and tabs, see documentation.
options – The paragraph options to use.
- Returns:
The number of lines written (including empty lines).
-
inline auto printParagraph(const text::String ¶graph, const ParagraphOptions &options = ParagraphOptions::defaultOptions()) noexcept -> int
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Invalid UTF-8 bytes are replaced with the Unicode replacement character.
-
inline auto printParagraph(const text::U32String ¶graph, const ParagraphOptions &options = ParagraphOptions::defaultOptions()) noexcept -> int
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
virtual Color color() const noexcept = 0
-
class Font
A bitmap font used to render stylized terminal text.
Public Types
Public Functions
-
Font() = default
Create an empty font with height
0.
-
explicit Font(int height) noexcept
Create an empty font with the given glyph height.
- Parameters:
height – The glyph height in bitmap rows.
-
Font(int height, GlyphMap glyphs) noexcept
Create a font with the given glyph height and glyph map.
- Parameters:
height – The glyph height in bitmap rows.
glyphs – The initial glyph map.
-
void addGlyph(const text::String &name, FontGlyph glyph)
Add or replace one glyph in this font.
- Parameters:
name – The UTF-8 encoded character represented by the glyph.
glyph – The bitmap glyph.
-
void setHeight(int height) noexcept
Set the configured font height in bitmap rows.
- Parameters:
height – The new glyph height.
-
int height() const noexcept
Get the configured font height in bitmap rows.
-
Font() = default
-
class FontGlyph : public erbsland::cterm::Bitmap
A bitmap glyph that can be used by a terminal text font.
Public Functions
-
FontGlyph() = default
Create an empty glyph.
Public Static Attributes
-
static constexpr auto cMaxGlyphWidth = 64
Maximum supported glyph width when importing numeric row masks.
-
FontGlyph() = default
-
class FrameBorder
Styling for all line groups of a grid frame.
The default border draws no lines. Use the all-style constructor or
set()to enable individual line groups.Public Types
-
using Element = FrameBorderElement
The named line groups for this border.
Public Functions
-
FrameBorder() = default
Create a border with all elements set to
FrameStyle::None.
-
explicit FrameBorder(FrameStyle style, Color color = {}) noexcept
Create a border with the same style and color for all elements.
- Parameters:
style – The style to apply to all elements.
color – The color to apply to all elements.
-
const Border &border(Element element) const noexcept
Access the style and color for an element.
- Parameters:
element – The element to query.
- Returns:
The configured style and color.
-
FrameStyle style(Element element) const noexcept
Access the frame style for an element.
- Parameters:
element – The element to query.
- Returns:
The configured frame style.
-
Color color(Element element) const noexcept
Access the color for an element.
- Parameters:
element – The element to query.
- Returns:
The configured color.
-
void set(Element element, FrameStyle style, Color color = {}) noexcept
Set the style and color for an element.
- Parameters:
element – The element to change.
style – The new frame style.
color – The new color.
Public Static Functions
-
static bool isLineStyle(FrameStyle style) noexcept
Test if a frame style can be used as a one-cell grid line style.
- Parameters:
style – The style to test.
- Returns:
trueforNoneand supported line frame styles.
-
static Block cornerChar(Border east, Border south, Border west, Border north) noexcept
Resolve the character for a grid corner or joint from its four directed borders.
Color precedence is east, west, south, north; inherited color parts fall through to lower-priority borders.
- Parameters:
east – The border segment going to the right.
south – The border segment going down.
west – The border segment going to the left.
north – The border segment going up.
- Returns:
The resolved joint character.
-
struct Border
Style and color for one border element.
Public Members
-
FrameStyle style = {FrameStyle::None}
The frame style for this element.
-
FrameStyle style = {FrameStyle::None}
-
using Element = FrameBorderElement
-
enum class erbsland::cterm::FrameBorderElement : uint8_t
Named line groups for a grid frame border.
Values:
-
enumerator Top
The top outer line.
-
enumerator Bottom
The bottom outer line.
-
enumerator Left
The left outer line.
-
enumerator Right
The right outer line.
-
enumerator HLine
The horizontal separator lines between rows.
-
enumerator VLine
The vertical separator lines between columns.
-
enumerator Top
-
enum class erbsland::cterm::FrameColorMode : uint8_t
The mode how animated colors are applied to frames.
Values:
-
enumerator OneColor
Uses one color from the sequence for the whole frame or fill area.
The selected sequence entry is
animationCycle + animationOffset.
-
enumerator VerticalStripes
Uses the color sequence in vertical stripes.
The selected sequence entry is
x + animationCycle + animationOffset.
-
enumerator HorizontalStripes
Uses the color sequence in horizontal stripes.
The selected sequence entry is
y + animationCycle + animationOffset.
-
enumerator ForwardDiagonalStripes
Uses the color sequence in forward diagonal stripes.
The selected sequence entry is
x + y + animationCycle + animationOffset.
-
enumerator BackwardDiagonalStripes
Uses the color sequence in backward diagonal stripes.
The selected sequence entry is
-x + y + animationCycle + animationOffset.
-
enumerator ChasingBorderCW
Uses the color sequence along the frame border in clockwise order.
Increasing
animationCyclemakes the colors travel clockwise.
-
enumerator ChasingBorderCCW
Uses the color sequence along the frame border in clockwise order.
Increasing
animationCyclemakes the colors travel counter-clockwise.
-
enumerator OneColor
-
class FrameDrawOptions
The options to draw a frame.
These options define the frame style, optional fill, combination style, and animated color behavior for
Buffer::drawFrame(). The style priority istile9Style(), thenblock16Style(), and finallystyle(). If aTile9Styleis active, it also controls the fill area and overridesfillBlock(). Frame colors are overlaid asbuffer -> frameColor -> tile/block color. Fill colors are overlaid asbuffer -> frameColor -> fillColor -> tile/block color.Note
Creating custom option instances is expensive. Reuse them across multiple
drawFrame()calls.Public Functions
-
FrameDrawOptions() = default
Create default frame draw options.
-
template<typename tColor>
inline explicit FrameDrawOptions(tColor frameColor) Create options for one fixed frame color.
- Parameters:
frameColor – The base frame color.
-
explicit FrameDrawOptions(ColorSequence frameColor, FrameColorMode frameColorMode = FrameColorMode::OneColor)
Create options from a frame color sequence.
- Parameters:
frameColor – The base frame colors.
frameColorMode – The mode used to pick colors from the frame sequence.
-
const ColorSequence &frameColor() const noexcept
The frame color sequence.
If this contains only inherited colors, the frame inherits the full color from the buffer below.
-
void setFrameColor(Foreground foreground, Background background) noexcept
Set explicit foreground and background colors for the frame.
-
void setFrameColorSequence(ColorSequence frameColor, FrameColorMode frameColorMode = FrameColorMode::OneColor) noexcept
Set the frame color sequence.
-
const ColorSequence &fillColor() const noexcept
The fill color sequence.
The fill colors are applied after
frameColor(), which allows subtle adjustments on top of animated borders.
-
void setFillColor(Foreground foreground, Background background) noexcept
Set explicit foreground and background colors for the fill.
-
void setFillColorSequence(ColorSequence fillColor, FrameColorMode fillColorMode = FrameColorMode::OneColor) noexcept
Set the fill color sequence.
-
const Block &fillBlock() const noexcept
The fill block.
An empty block disables filling when no
Tile9Styleis active.
-
FrameStyle style() const noexcept
The predefined frame style.
-
void setStyle(FrameStyle style) noexcept
Set the predefined frame style.
-
const Block16StylePtr &block16Style() const noexcept
The custom Char16 frame style.
This overrides
style()unlesstile9Style()is also set.
-
void setBlock16Style(Block16StylePtr block16Style) noexcept
Set the custom Char16 frame style.
-
const Tile9StylePtr &tile9Style() const noexcept
The custom Tile9 frame style.
This overrides both
block16Style()andstyle(), and also controls the fill area.
-
void setTile9Style(Tile9StylePtr tile9Style) noexcept
Set the custom Tile9 frame style.
-
const BlockCombinationStylePtr &combinationStyle() const noexcept
The combination style used for writing the frame and fill blocks.
-
void setCombinationStyle(BlockCombinationStylePtr combinationStyle) noexcept
Set the combination style.
-
std::size_t animationOffset() const noexcept
The shared animation offset for frame and fill colors.
This value is added to the
animationCyclepassed todrawFrame().
-
void setAnimationOffset(std::size_t offset) noexcept
Set the animation offset for frame and fill colors.
-
FrameColorMode frameColorMode() const noexcept
The frame color mode.
-
void setFrameColorMode(FrameColorMode frameColorMode) noexcept
Set the frame color mode.
-
FrameColorMode fillColorMode() const noexcept
The fill color mode.
ChasingBorderCWandChasingBorderCCWonly affect frame cells.
-
void setFillColorMode(FrameColorMode fillColorMode) noexcept
Set the fill color mode.
Public Static Functions
-
static const FrameDrawOptions &defaultOptions() noexcept
Access the shared object with the default options.
Default options use a light Unicode frame, inherited colors, no fill, and the common box frame combiner.
-
FrameDrawOptions() = default
-
enum class erbsland::cterm::FrameStyle : uint8_t
Various box styles.
Values:
-
enumerator None
No visible frame; regular frame drawing uses colored spaces.
-
enumerator Light
Light box
┌─┐
-
enumerator LightDoubleDash
Light box with double-dashed lines
┌╌┐
-
enumerator LightTripleDash
Light box with triple-dashed lines
┌┄┐
-
enumerator LightQuadrupleDash
Light box with quadruple-dashed lines
┌┈┐
-
enumerator Heavy
Heavy box
┏━┓
-
enumerator HeavyDoubleDash
Heavy box with double-dashed lines
┏╍┓
-
enumerator HeavyTripleDash
Heavy box with triple-dashed lines
┏┅┓
-
enumerator HeavyQuadrupleDash
Heavy box with quadruple-dashed lines
┏┉┓
-
enumerator Double
Double box
╔═╗
-
enumerator LightWithRoundedCorners
Light box with rounded corners
╭─╮
-
enumerator FullBlock
Solid block frame
█
-
enumerator FullBlockWithChamfer
Solid block frame with chamfered corners
◢█◣
-
enumerator OuterHalfBlock
Half-block frame drawn on the outer cell edges.
-
enumerator InnerHalfBlock
Half-block frame drawn on the inner cell edges.
-
enumerator None
-
class GridLayout
Geometry for a grid of content cells.
This class stores only content sizes.
Public Functions
-
GridLayout(std::vector<block::Coordinate> columnWidths, std::vector<block::Coordinate> rowHeights)
Create a grid layout.
- Parameters:
columnWidths – The content width of each column. Each value must be positive.
rowHeights – The content height of each row. Each value must be positive.
- Throws:
err::ParameterError – if either list is empty or contains a non-positive size.
-
GridLayout(std::initializer_list<block::Coordinate> columnWidths, std::initializer_list<block::Coordinate> rowHeights)
Create a grid layout from initializer lists.
- Parameters:
columnWidths – The content width of each column. Each value must be positive.
rowHeights – The content height of each row. Each value must be positive.
- Throws:
err::ParameterError – if either list is empty or contains a non-positive size.
-
std::size_t rowCount() const noexcept
Number of rows in the grid.
-
std::size_t columnCount() const noexcept
Number of columns in the grid.
-
block::Coordinate rowHeight(std::size_t row) const
Access one row height.
- Parameters:
row – The row index.
- Throws:
err::OutOfRangeError – if
rowis outside the layout.- Returns:
The row content height.
-
block::Coordinate columnWidth(std::size_t column) const
Access one column width.
- Parameters:
column – The column index.
- Throws:
err::OutOfRangeError – if
columnis outside the layout.- Returns:
The column content width.
-
const std::vector<block::Coordinate> &rowHeights() const noexcept
Access all row heights.
-
const std::vector<block::Coordinate> &columnWidths() const noexcept
Access all column widths.
-
block::Size size(const FrameBorder &border) const noexcept
Calculate the complete size of this layout for the given border.
- Parameters:
border – Border styles that decide which frame lines occupy cells.
- Returns:
The total grid size including active frame lines.
-
auto cellRect(std::size_t row, std::size_t column, block::Position origin, const FrameBorder &border) const -> block::Rectangle
Calculate the content rectangle for one cell.
- Parameters:
row – The row index.
column – The column index.
origin – The top-left position of the full grid.
border – Border styles that decide which frame lines occupy cells.
- Throws:
err::OutOfRangeError – if
roworcolumnis outside the layout.- Returns:
The cell content rectangle.
-
GridLayout(std::vector<block::Coordinate> columnWidths, std::vector<block::Coordinate> rowHeights)
-
class Input
The input interface.
Subclassed by erbsland::cterm::impl::InputBackend
Public Types
Public Functions
-
virtual void setMode(Mode mode) = 0
Set the current reading mode.
- Parameters:
mode – The new input mode.
-
inline Key readKey(std::chrono::milliseconds timeout = {}) const
Read one key event without blocking longer than the given timeout.
In
Mode::Key, any timeout less than or equal to zero is normalized to zero and performs a non-blocking poll. InMode::ReadLine, the timeout is ignored and this call behaves like a blocking line read converted intoKey.- Parameters:
timeout – Maximum wait time in
Mode::Key.- Returns:
The parsed key event, or an invalid key if no supported input was read before the timeout expired.
-
inline Key readKey(const time::Milliseconds timeout = {}) const
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
inline Key waitForKey() const
Wait until one key event is available.
In
Mode::ReadLine, this call blocks until one line was entered and returns the converted key.- Returns:
The parsed key event.
-
inline virtual void purgePendingInput() noexcept
Securely discard input retained by the terminal backend.
-
virtual void setMode(Mode mode) = 0
-
class Key
A simple representation of a key press.
Supports Unicode text input and common special keys.
Public Types
-
enum Type
Supported key kinds.
Values:
-
enumerator None
No supported key was decoded.
-
enumerator Character
A single Unicode code point.
-
enumerator Combined
Multiple code points that form one combined text input.
-
enumerator Enter
The Enter/Return key.
-
enumerator Tab
The tab key.
-
enumerator BackTab
Reverse tab / Shift+Tab.
-
enumerator Space
The space key.
-
enumerator Escape
The escape key.
-
enumerator Backspace
The backspace key.
-
enumerator Insert
The insert key.
-
enumerator Delete
The delete key.
-
enumerator Home
The home key.
-
enumerator End
The end key.
-
enumerator PageUp
The page up key.
-
enumerator PageDown
The page down key.
-
enumerator Left
The left cursor key.
-
enumerator Right
The right cursor key.
-
enumerator Up
The up cursor key.
-
enumerator Down
The down cursor key.
-
enumerator F1
The function key F1.
-
enumerator F2
The function key F2.
-
enumerator F3
The function key F3.
-
enumerator F4
The function key F4.
-
enumerator F5
The function key F5.
-
enumerator F6
The function key F6.
-
enumerator F7
The function key F7.
-
enumerator F8
The function key F8.
-
enumerator F9
The function key F9.
-
enumerator F10
The function key F10.
-
enumerator F11
The function key F11.
-
enumerator F12
The function key F12.
-
enumerator None
Public Functions
-
Key() = default
Create an invalid key.
-
Key(Type type, text::Char codePoint = {}, KeyModifiers modifiers = {}) noexcept
Create a key with an explicit type and optional Unicode payload.
- Parameters:
type – The key type.
codePoint – The Unicode value for
Type::Character.modifiers – The modifiers pressed together with this key.
-
Key(Type type, KeyModifiers modifiers) noexcept
Create a special key with modifiers.
- Parameters:
type – The key type.
modifiers – The modifiers pressed together with this key.
-
Key(text::Char codePoint, KeyModifiers modifiers = {}) noexcept
Create a single-code-point character key.
- Parameters:
codePoint – The Unicode code point.
modifiers – The modifiers pressed together with this key.
-
Key(Type type, const text::U32String &character, KeyModifiers modifiers = {})
Create a key with an explicit combined Unicode payload.
- Parameters:
type – The key type.
character – The combined Unicode text for
Type::CharacterorType::Combined.modifiers – The modifiers pressed together with this key.
-
Key(Type type, const text::CombinedChar &character, KeyModifiers modifiers = {}) noexcept
Create a key by copying a fixed combined-character payload.
-
bool operator!=(text::Char other) const noexcept
Test if this key differs from a single code point.
-
bool operator==(const text::U32String &other) const noexcept
Compare against a combined key This requires
type()==Combinedandcombined()==other.
-
bool operator!=(const text::U32String &other) const noexcept
Test if this key differs from combined Unicode text.
-
bool operator==(Type type) const noexcept
Compare against a special key.
This requires
type()==typeandtype!=Character|Combined.
-
inline const KeyModifiers &modifiers() const noexcept
Get the modifiers pressed together with this key.
-
inline bool hasModifier(KeyModifier modifier) const noexcept
Test if a modifier is set.
-
char character() const noexcept
Legacy ASCII accessor for
Type::Character.- Deprecated:
Use
unicode()orcombined()to support full Unicode input.
- Returns:
The ASCII character for single-code-point character input, otherwise
0.
-
text::Char unicode() const noexcept
Get the Unicode code point for
Type::Character.- Returns:
The single Unicode code point, or
0if this key does not store exactly one code point.
-
text::U32String combined() const
Get the full combined Unicode payload for character input.
- Returns:
The stored Unicode text, or an empty string for non-character keys.
-
inline const text::CombinedChar &combinedCharacter() const noexcept
Borrow the fixed combined-character payload without creating a string copy.
-
inline bool valid() const noexcept
Test if this object represents a supported key.
-
inline constexpr std::size_t hash() const noexcept
Get a hash for this key.
Public Static Functions
-
static Key fromString(const text::String &text) noexcept
Decode a key from the configuration text.
- Parameters:
text – The textual key name.
- Returns:
The decoded key, or
Type::Noneif the text is unsupported.
-
static Key fromConsoleInput(const text::String &text) noexcept
Decode a key from console input text.
- Parameters:
text – The input text or escape sequence.
- Returns:
The decoded key, or
Type::Noneif the input is unsupported.
-
enum Type
-
enum class erbsland::cterm::KeyModifier : uint8_t
A modifier pressed together with a key.
Values:
-
enumerator Shift
The Shift key.
-
enumerator Control
The Control key.
-
enumerator Alt
The Alt key.
-
enumerator Shift
-
class KeyModifiers
A set of key modifiers.
Public Types
-
using Mask = uint8_t
Unsigned storage type used for the combined modifier bits.
-
using Enum = KeyModifier
The enum type combined by this modifier set.
Public Functions
-
template<typename ...Modifiers>
inline constexpr KeyModifiers(Modifiers... modifiers) Create a combined set of modifiers.
-
inline KeyModifiers operator|(const KeyModifier modifier) const
Combine this modifier set with one additional modifier.
- Parameters:
modifier – The modifier to add.
- Returns:
The combined modifier set.
-
inline constexpr bool empty() const noexcept
Test if this modifier set is empty.
-
inline constexpr bool has(const KeyModifier modifier) const noexcept
Test if a modifier is set.
-
inline void set(const KeyModifier modifier, const bool enabled = true) noexcept
Set a modifier.
-
inline void clear(const KeyModifier modifier) noexcept
Clear a modifier.
Friends
-
inline friend KeyModifiers operator|(const KeyModifier modifier, const KeyModifiers modifiers)
Combine one modifier with an existing modifier set.
- Parameters:
modifier – The modifier to add.
modifiers – The existing modifier set.
- Returns:
The combined modifier set.
-
inline friend KeyModifiers operator|(const KeyModifiers modifiers1, const KeyModifiers modifiers2)
Combine two modifier sets.
- Parameters:
modifiers1 – The first modifier set.
modifiers2 – The second modifier set.
- Returns:
The combined modifier set.
-
using Mask = uint8_t
-
class Keys
An ordered set of unique key presses for key bindings.
Public Types
-
using MainCount = std::size_t
Number of leading keys shown in compact help.
Public Functions
-
Keys() = default
Create an empty key set.
-
Keys(Key::Type keyType)
Create a key set with one special key.
- Parameters:
keyType – The special key type to add.
-
Keys(text::Char character)
Create a key set with one character key.
- Parameters:
character – The character key to add.
-
Keys(std::initializer_list<Key> keys)
Create a key set from a list of keys.
- Parameters:
keys – The keys to add in priority order.
-
Keys(std::vector<Key> keys)
Create a key set from a vector of keys.
- Parameters:
keys – The keys to add in priority order.
-
inline bool empty() const noexcept
Test if this key set is empty.
-
inline std::size_t size() const noexcept
Get the number of keys.
-
std::size_t mainKeyCount() const noexcept
Get the number of main keys.
-
text::StringList mainKeyLabels() const
Get all key labels for the main keys.
-
Keys &setKeys(std::vector<Key> keys)
Replace all keys.
- Parameters:
keys – The keys to add in priority order.
- Returns:
This object.
-
Keys &setKeys(std::initializer_list<Key> keys)
Replace all keys.
- Parameters:
keys – The keys to add in priority order.
- Returns:
This object.
-
Keys &add(Key key)
Add a key if it is not already present.
- Parameters:
key – The key to add.
- Returns:
This object.
-
Keys &add(Key::Type keyType)
Add a special key if it is not already present.
- Parameters:
keyType – The special key type to add.
- Returns:
This object.
-
Keys &add(text::Char character)
Add a character key if it is not already present.
- Parameters:
character – The character key to add.
- Returns:
This object.
-
Keys &clear() noexcept
Clear all keys and reset compact help to show all future keys.
- Returns:
This object.
-
Keys &setMainKeyCount(MainCount mainKeyCount) noexcept
Set how many leading keys are shown in compact help.
- Parameters:
mainKeyCount – The number of leading keys considered main keys.
- Returns:
This object.
-
using MainCount = std::size_t
-
class MatrixBlockCombinationStyle : public erbsland::cterm::BlockCombinationStyle
Combine block characters through an indexed result matrix.
Public Functions
-
MatrixBlockCombinationStyle(const text::U32String &characters, std::span<const uint8_t> resultMatrix)
Create a new matrix-based combination style.
- Parameters:
characters – The supported Unicode characters in matrix index order.
resultMatrix – The result matrix in row-major order using result indexes.
- Throws:
err::ParameterError – If the matrix size is invalid or the character count exceeds 255.
-
virtual Block combine(const Block ¤t, const Block &overlay) const noexcept override
Combines the current char with a new that is placed on top of the current one.
The default implementation just returns the overlay character.
- Parameters:
current – The current (lower) character.
overlay – The new (upper) character that overlays the current one.
- Returns:
The combined character.
-
MatrixBlockCombinationStyle(const text::U32String &characters, std::span<const uint8_t> resultMatrix)
-
enum class erbsland::cterm::MoveMode
The cursor move mode.
Values:
-
enumerator Absolute
Absolute move.
-
enumerator Relative
Relative move.
-
enumerator Absolute
-
enum class erbsland::cterm::ParagraphBackgroundMode : uint8_t
How paragraph rendering extends the background color beyond the visible text.
These modes are most visible when the rendered text uses a non-default background color and the paragraph wraps across multiple physical lines. Depending on the chosen mode, the renderer can extend that background into the unused cells on the right side of a wrapped line, into the indentation area of the continuation line, or both.
For buffer-based text rendering such as
BlockTextandWritableBuffer::drawBlockText(), untouched cells keep the existing buffer background. For cursor-writer output such asCursorWriter::printParagraph(), indentation and padding must be materialized as spaces, so cells not covered by wrapped-text background use the writer’s current background.Values:
-
enumerator Default
Do not extend the wrapped-text background into additional cells.
No extra cells are painted on the right side of wrapped lines. Continuation indents keep the existing background in buffer-based rendering, or use the current cursor-writer background when the paragraph is printed as streamed output.
-
enumerator WrappedLeft
Extend the wrapped-line background into the left indentation area only.
The indentation area of each wrapped continuation line uses the background color of the last visible character on the previous physical line. The right side of the line keeps the existing buffer background in buffer-based rendering, or the current cursor-writer background in streamed output. @code | This is a very long | | <fill here> wrapped line. | @endcode
-
enumerator WrappedRight
Extend the wrapped-line background into the remaining cells on the right side only.
Each wrapped physical line fills the unused cells up to the available width with the background color of its last visible character. Indentation keeps the existing buffer background in buffer-based rendering, or the current cursor-writer background in streamed output. @code | This is a very long <filled here> | | wrapped line. | @endcode
-
enumerator WrappedBoth
Extend the wrapped-line background on both sides of wrapped lines.
Wrapped lines fill the remaining cells on the right side, and the continuation indent on the next physical line uses that same background color. @code | This is a very long <filled here> | | <and here> wrapped line. | @endcode
-
enumerator FullRight
Extend the background into the right-side remainder on every physical line.
This behaves like `WrappedRight`, but also fills the last physical line of the paragraph. @code | This is a very long <filled here> | | wrapped line. <and here> | @endcode
-
enumerator FullBoth
Extend the background on both sides for every physical line.
This behaves like `WrappedBoth`, but also keeps filling the right-side remainder on the last physical line. @code | This is a very long <filled here> | | <and here> wrapped line. <and here> | @endcode
-
enumerator Default
-
class ParagraphIndents
Shared indentation and margin settings for paragraph-like text rendering.
Public Functions
-
constexpr ParagraphIndents() noexcept = default
Create default indents without margins.
-
inline explicit constexpr ParagraphIndents(const int lineIndent) noexcept
Create indents with the same value for all paragraph lines.
- Parameters:
lineIndent – The indent to use for all lines.
-
inline constexpr ParagraphIndents(const int lineIndent, const int firstLineIndent, const int wrappedLineIndent, const block::Margins margins) noexcept
Create indents and margins with explicit values.
- Parameters:
lineIndent – The indent for all lines.
firstLineIndent – The indent for the first line, or
cUseLineIndent.wrappedLineIndent – The indent for wrapped lines, or
cUseLineIndent.margins – The margins around the rendered paragraph area.
-
inline constexpr int lineIndent() const noexcept
Get the indent for all lines.
-
inline constexpr void setLineIndent(const int indent) noexcept
Set the indent for all lines.
- Parameters:
indent – The new indent value.
>=0
-
inline constexpr int firstLineIndent() const noexcept
Get the indent for the first line.
- Returns:
The resolved first-line indent.
-
inline constexpr void setFirstLineIndent(const int indent) noexcept
Set the indent for the first line.
- Parameters:
indent – The new indent value.
>=0orcUseLineIndentto uselineIndent().
-
inline constexpr int wrappedLineIndent() const noexcept
Get the indent for wrapped lines.
- Returns:
The resolved wrapped-line indent.
-
inline constexpr void setWrappedLineIndent(const int indent) noexcept
Set the indent for wrapped lines.
- Parameters:
indent – The new indent value.
>=0orcUseLineIndentto uselineIndent().
Public Static Attributes
-
static constexpr auto cUseLineIndent = -1
Special value that makes
firstLineIndent()orwrappedLineIndent()reuselineIndent().
-
constexpr ParagraphIndents() noexcept = default
-
enum class erbsland::cterm::ParagraphOnError : uint8_t
The fallback to use when paragraph layout becomes impossible.
This can happen when the available width is too small for the chosen indentation, wrap markers, ellipsis marker, or other paragraph settings.
Values:
-
enumerator PlainOutput
Fallback to plain text output and let the terminal handle wrapping.
-
enumerator Empty
Do not output the paragraph at all.
-
enumerator PlainOutput
-
class ParagraphOptions
Options that control paragraph wrapping, indentation, tab handling, and fallback behavior.
These settings are used by
Terminal::printParagraph()and byBlockTextOptions/BlockTextwhen text is laid out inside a rectangle.Note
Creating and copying paragraph options is expensive. Please keep and reuse created instances.
Public Functions
-
inline explicit ParagraphOptions(const geometry::Alignment alignment) noexcept
Create paragraph options with the given alignment.
-
geometry::Alignment alignment() const noexcept
The alignment of the paragraph.
For the
Terminal::printParagraphcalls, vertical alignment is ignored. For thedrawBlockText(BlockText)calls, the vertical alignment is used to align the text in the given rectangle.
-
const ParagraphIndents &indents() const noexcept
Get the configured indents and margins.
-
void setIndents(const ParagraphIndents &indents) noexcept
Replace the configured indents and margins.
- Parameters:
indents – The new indent and margin settings.
-
int lineIndent() const noexcept
The line indent for all lines.
Only valid if the alignment is set to
geometry::Alignment::Left. This indent can be overridden byfirstLineIndentandwrappedLineIndent.
-
void setLineIndent(int indent) noexcept
Set the line indent for all lines.
- Parameters:
indent – The new indent value.
>=0
-
int firstLineIndent() const noexcept
Get the first line indent.
This is the indent for the first line of the paragraph. Only valid if the alignment is set to
geometry::Alignment::Left.1:| <first indent> A long text that is broken | 2:| into multiple lines. |
-
void setFirstLineIndent(int indent) noexcept
Set the first line indent.
- Parameters:
indent – The new indent value.
>=0orcUseLineIndentto uselineIndent
-
int wrappedLineIndent() const noexcept
Get the indent for wrapped lines.
This is the indent for all lines that are wrapped at the terminal width. Only valid if the alignment is set to
geometry::Alignment::Left.1:| <first indent> A long text that is broken | 2:| into multiple lines. |
-
void setWrappedLineIndent(int indent) noexcept
Set the indent for wrapped lines.
- Parameters:
indent – The new indent value.
>=0orcUseLineIndentto uselineIndent
-
void setMargins(block::Margins margins) noexcept
Set the margins around the paragraph.
- Parameters:
margins – The margins around the paragraph area.
-
ParagraphBackgroundMode backgroundMode() const noexcept
Get the background mode.
The background mode determines how the background of the paragraph is handled when lines are wrapped. It also controls how the background is extended for the last line in the paragraph.
With
BlockText/drawBlockText(...), cells outside the wrapped text keep the existing buffer background unless the selected mode fills them from the wrapped text. WithCursorWriter::printParagraph(), indentation and padding are written as spaces, so cells not covered by wrapped-text background use the writer’s current background.
-
void setBackgroundMode(ParagraphBackgroundMode backgroundMode) noexcept
Set the background mode.
When using
CursorWriter::printParagraph(), configure the writer background before printing if indentation or trailing padding should visually match a surrounding panel.
-
const BlockString &lineBreakEndMark() const noexcept
Get the line break end mark.
The line break end mark is appended to wrapped physical lines. The mark is aligned to the right edge of the available paragraph area. If the mark contains color information, it will override the background color.
1:| A long text that is broken <end mark> | 2:| into multiple lines. |
- Returns:
The current line break end mark. Empty for no line break end mark.
-
void setLineBreakEndMark(BlockString mark)
Set the line break end mark.
- Parameters:
mark – The new line break end mark. Must not exceed two characters.
-
const BlockString &lineBreakStartMark() const noexcept
Get the line break start mark.
The line break start mark prepends wrapped continuation lines in left-aligned paragraphs. The mark is inserted after the continuation indentation. If the mark contains color information, it will override the background color.
1:| A long text that is broken | 2:| <start mark> into multiple lines. |
- Returns:
The current line break start mark. Empty for no line break start mark.
-
void setLineBreakStartMark(BlockString mark)
Set the line break start mark.
Unlike the end mark, this decoration may contain an arbitrary number of characters so nested line prefixes and continuation indentation can be represented.
- Parameters:
mark – The new line break start mark.
-
ParagraphSpacing paragraphSpacing() const noexcept
The spacing between paragraphs.
The behavior of the paragraph spacing depends on the used interface. For
Terminal::printParagraph()andCursorBuffer::printParagraph(), embedded newlines are hard line breaks inside one printed paragraph, and the configured spacing is appended once after the whole call. FordrawBlockText(BlockText)calls, each newline starts a new paragraph and spacing is inserted between paragraphs.
-
void setParagraphSpacing(ParagraphSpacing spacing) noexcept
Set the paragraph spacing.
-
text::U32String wordSeparators() const
Get the configured word separators as a canonicalized character string.
Word separators split a source line into words. Consecutive separators are rendered as a single space between words. Tabs use special tab-stop handling in left-aligned paragraphs before separator handling is applied. The returned string is duplicate-free and normalized for comparison and display.
-
const text::CharSet &wordSeparatorSet() const noexcept
Access the shared separator lookup used internally for paragraph layout.
The returned set can be reused by callers that need repeated separator membership checks.
-
void setWordSeparators(const text::U32String &separators)
Set the word separators.
Tabs remain special tab stops in left-aligned paragraphs and act as regular word separators in other alignments when included here. The provided string is canonicalized automatically and mapped to shared defaults for common patterns.
- Parameters:
separators – A string of Unicode characters that are used to split words.
-
const Block &wordBreakMark() const noexcept
Get the word break mark.
The word break mark is used when a long word had to be split in a paragraph.
-
int maximumLineWraps() const noexcept
Get the maximum line wraps.
A value >0 limits the automatic wraps for one source line. Once the limit is reached, the current source line is truncated and
paragraphEllipsisMark()is appended if configured. Embedded line breaks start a new source line and therefore reset the wrap counter.- Returns:
The maximum number of line wraps, or zero for unlimited line wraps.
-
void setMaximumLineWraps(int lines) noexcept
Set the maximum number of line wraps.
- Parameters:
lines – The maximum number of line wraps, or zero for unlimited line wraps.
-
const BlockString ¶graphEllipsisMark() const noexcept
Get the paragraph ellipsis mark.
This string is used to indicate that a paragraph would have to be wrapped over even more lines to be displayed completely. A single character can be used, but a short text like
(more…)works as well. Please note that the width of this mark further reduces the available space for the paragraph text.- Returns:
The paragraph ellipsis mark or an empty string if no ellipsis mark shall be used.
-
void setParagraphEllipsisMark(BlockString mark) noexcept
Set the paragraph ellipsis mark.
We recommend using a single character or a very short text. Longer texts quickly make paragraph rendering impossible.
- Parameters:
mark – The paragraph ellipsis mark. If empty, no ellipsis mark will be used.
-
const std::vector<int> &tabStops() const noexcept
Get the tab stops for the paragraph.
Only valid if the alignment is set to
geometry::Alignment::Left. If a line (text up to a newline character) contains TAB characters, each tab character will pick the next tab-stop columns value from this array. If the column is larger than the current column, spacing is inserted until the cursor reaches the tab-stop column. If the tab column is smaller, or there is no further tab stop in the sequence,tabOverflowBehavior()is used to decide whether the tab becomes a single space or starts a wrapped continuation line. In centered or right-aligned paragraphs, tabs usewordSeparatorsinstead of these tab stops. The special valuecTabWrappedLineIndentcan be used to use the same indent as for wrapped lines.
-
void setTabStops(std::vector<int> tabStops) noexcept
Set the tab stops.
-
TabOverflowBehavior tabOverflowBehavior() const noexcept
Get the overflow handling for non-advancing tab stops.
This mode is used if a TAB resolves to a tab-stop column that is not larger than the current column, or if there is no further configured tab stop.
-
void setTabOverflowBehavior(TabOverflowBehavior behavior) noexcept
Set the overflow handling for non-advancing tab stops.
- Parameters:
behavior – The behavior to use for tabs that do not advance the current line.
-
ParagraphOnError onError() const noexcept
Get the error resolution if a paragraph cannot be rendered with the given settings.
If the screen layout and the given parameters do not allow the paragraph to be rendered properly, this error resolution is used.
- Returns:
The error resolution to use when a paragraph cannot be rendered.
-
void setOnError(ParagraphOnError onError) noexcept
Set the error resolution.
- Parameters:
onError – The error resolution to use when a paragraph cannot be rendered.
Public Static Functions
-
static const ParagraphOptions &defaultOptions() noexcept
Globally shared default options.
- Returns:
A reusable default instance with the library defaults for all paragraph settings.
Public Static Attributes
-
static constexpr auto cUseLineIndent = ParagraphIndents::cUseLineIndent
Special value that makes
firstLineIndent()orwrappedLineIndent()reuselineIndent().
-
static constexpr auto cTabWrappedLineIndent = -1
Special tab-stop value that resolves to the configured
wrappedLineIndent().
-
inline explicit ParagraphOptions(const geometry::Alignment alignment) noexcept
-
enum class erbsland::cterm::ParagraphSpacing : uint8_t
The spacing between explicit newline-separated paragraphs.
Values:
-
enumerator SingleLine
Render the next paragraph directly below the previous paragraph.
-
enumerator DoubleLine
Insert one empty row between paragraphs.
-
enumerator SingleLine
-
class ReadableBuffer
A readable buffer.
Subclassed by erbsland::cterm::BufferViewBase, erbsland::cterm::WritableBuffer
Public Functions
-
virtual block::Size size() const noexcept = 0
Get the configured size of the buffer.
- Returns:
The width and height of the buffer.
-
virtual block::Rectangle rect() const noexcept = 0
Get a rectangle representing this buffer.
- Returns:
The rectangle for this buffer.
-
virtual const Block &get(block::Position pos) const noexcept = 0
Read the block stored at the given position.
- Parameters:
pos – The coordinates within the buffer.
- Returns:
A reference to the stored block.
-
virtual WritableBufferPtr clone() const = 0
Create a writeable copy of this buffer.
This will copy every block from this buffer into a new independent instance.
-
virtual std::size_t countDifferencesTo(const ReadableBuffer &other) const noexcept
Count the differences from this to another buffer.
If the size of
otheris smaller or larger than this buffer, the size change counts to the difference.- Parameters:
other – The other buffer to compare with.
- Returns:
The number of blocks that differ between the two buffers.
-
Bitmap toMask(const text::CharSet &characters, bool invert = false)
Create a mask from this buffer.
All characters that match one of the given characters result in a pixel set in the mask.
- Parameters:
characters – The characters to match. Only one code-point characters are supported.
invert – If true, not-matching characters result in a pixel set in the mask.
- Returns:
A bitmap mask with the same size as this buffer.
-
virtual block::Size size() const noexcept = 0
-
class RemappedBuffer : public erbsland::cterm::WritableBuffer
A buffer that allows fast remapping/shifting/inserting/deleting of rows and columns.
This buffer is useful if you have a large buffer that requires frequent row- or column-based manipulations. It is designed for fast insert/delete/move and shift operations.
This buffer also knows two orientations: vertical and horizontal.
In the vertical orientation, the buffer can efficiently grow vertically, keeping the existing data intact.
In the horizontal orientation, the buffer can efficiently grow horizontally, keeping the existing data intact.
When growing the buffer, memory reallocation may be necessary. Use
reserveto reserve enough memory to avoid frequent reallocations.Use
resize(size, BufferResizeMode::PreserveContent, fillChar)when you need to preserve the visible content.A preserve-content resize that changes only the primary orientation axis is optimized and fast.
A preserve-content resize that changes the secondary axis must rebuild the logical content and can be expensive.
Subclassed by erbsland::cterm::CursorBuffer
Public Types
-
using CoordinateMap = std::vector<block::Coordinate>
A vector mapping one coordinate to another.
Public Functions
-
RemappedBuffer()
Creates a 1x1 vertical buffer filled with a space.
Usually only used as a placeholder until resized.
-
explicit RemappedBuffer(block::Size size, geometry::Orientation orientation = geometry::Orientation::Vertical, Block fillChar = Block::space())
Construct a buffer with the given size and fill it with an initial block.
- Parameters:
size – The dimensions of the buffer. block::Size must be at least 1x1.
orientation – The orientation of the buffer. Cannot be changed after creation.
fillChar – The optional fill character for the buffer.
- Throws:
err::ParameterError – if size is invalid.
-
virtual block::Size size() const noexcept override
Get the current size of the buffer.
- Returns:
The configured width and height.
-
virtual block::Rectangle rect() const noexcept override
Get the rectangle covering the whole buffer.
- Returns:
A rectangle with origin
(0,0)and the current size.
-
virtual const Block &get(block::Position pos) const noexcept override
Read the block stored at the given logical position.
- Parameters:
pos – The logical coordinates inside the buffer.
- Returns:
A reference to the stored block, or a shared space block for invalid positions.
-
virtual WritableBufferPtr clone() const override
Create an independent writable copy of this buffer.
- Returns:
A shared pointer to the cloned buffer.
-
virtual void resize(block::Size newSize) override
Resize this buffer.
This is the fast resize path. The internal mapping is rebuilt and the visible content order is undefined after the operation. Use
resize(size, BufferResizeMode::PreserveContent, fillChar)if you need to preserve the visible order.- Parameters:
newSize – The new size of the buffer.
- Throws:
err::ParameterError – if
newSizeis invalid.
-
virtual void resize(block::Size size, BufferResizeMode mode, Block fillChar) override
Resize this buffer and optionally keep the visible content order.
A preserve-content resize is fast when only the primary orientation axis changes. If the secondary axis changes, preserving content requires rebuilding the logical content and is expensive.
- Parameters:
size – The new size.
mode –
BufferResizeMode::PreserveContentkeeps the visible order and fills new cells withfillChar.BufferResizeMode::Fastresizes using the fastest path and leaves the visible order undefined.fillChar – The fill character for newly created cells in preserve-content mode. In fast mode it is only used to initialize newly appended storage cells.
- Throws:
err::ParameterError – if
sizeis invalid.
-
virtual void set(block::Position pos, const Block &block) noexcept override
Write a block at the given logical position.
This mirrors the wide-character handling from
Buffer: zero-width blocks are ignored, width-2 blocks occupy the next logical cell as an empty continuation cell, and width-2 blocks at the right edge are ignored.- Parameters:
pos – The logical coordinates within the buffer.
block – The block to write.
-
void reserve(block::Size size) noexcept
Reserve memory for the given buffer size.
- Parameters:
size – The size whose capacity should be reserved.
-
void shift(block::Direction direction, Block fillChar, int count = 1)
Shift the buffer in the given direction, fill new cells with a given character.
- Parameters:
direction – The direction of the shift.
fillChar – The character to fill new cells with.
count – The number of cells to shift.
- Throws:
err::ParameterError – if
countis negative or exceeds buffer size.
-
inline void shift(const block::Direction direction, const int count = 1)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
void rotate(block::Direction direction, int count = 1)
Rotate the buffer in the given direction.
Cells are shifted in a circular manner, wrapping around to the other end of the buffer.
- Parameters:
direction – The direction in which to rotate.
count – The number of cells to rotate.
- Throws:
err::ParameterError – if
countis negative or exceeds buffer size.
-
void eraseRows(block::Coordinate startRow, Block fillChar, int count = 1)
Erase rows in the buffer.
This will erase
countrows, starting fromstartRow, and insert empty ones at the end. If you like to actually shrink the buffer, useresizeafter this call.- Parameters:
startRow – The first row to delete.
fillChar – The character to fill new cells with.
count – The number of rows to delete.
- Throws:
err::ParameterError – if
startRowis out of bounds orcountis negative or exceeds buffer size.
-
inline void eraseRows(const block::Coordinate startRow, const int count = 1)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
void eraseColumns(block::Coordinate startColumn, Block fillChar, int count = 1)
Erase columns in the buffer.
This will erase
countcolumns, starting fromstartColumn, and insert empty ones at the end. If you like to actually shrink the buffer, useresizeafter this call.- Parameters:
startColumn – The first column to delete.
fillChar – The character to fill new cells with.
count – The number of columns to delete.
- Throws:
err::ParameterError – if
startColumnis out of bounds orcountis negative or exceeds buffer size.
-
inline void eraseColumns(const block::Coordinate startColumn, const int count = 1)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
void insertRows(block::Coordinate startRow, Block fillChar, int count = 1)
Insert rows in the buffer.
The rows at the bottom of the buffer will be erased to make room for the new rows. If you like to actually grow the buffer, use
resizebefore this call.- Parameters:
startRow – The first row to insert.
fillChar – The character to fill the new rows with.
count – The number of rows to insert.
- Throws:
err::ParameterError – if
startRowis out of bounds orcountis negative or exceeds buffer size.
-
inline void insertRows(const block::Coordinate startRow, const int count = 1)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
void insertColumns(block::Coordinate startColumn, Block fillChar, int count = 1)
Insert columns in the buffer.
The columns on the right side of the buffer will be erased to make room for the new columns. If you like to actually grow the buffer, use
resizebefore this call.- Parameters:
startColumn – The first column to insert.
fillChar – The character to fill the new columns with.
count – The number of columns to insert.
- Throws:
err::ParameterError – if
startColumnis out of bounds orcountis negative or exceeds buffer size.
-
inline void insertColumns(const block::Coordinate startColumn, const int count = 1)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
void moveRows(block::Coordinate startRow, int count, block::Coordinate delta, Block fillChar)
Move rows in the buffer by a given delta.
A positive delta moves rows down, a negative delta moves rows up. This reshuffles the moved rows, but rows that get moved out of the buffer area are deleted and replaced by empty cells using the
fillChar.- Parameters:
startRow – The first row to move.
count – The number of rows to move.
delta – The number of positions to move (positive = down, negative = up).
fillChar – The character to fill vacated cells with.
- Throws:
err::ParameterError – if
startRowis out of bounds orcountis negative or exceeds buffer size.
-
inline void moveRows(const block::Coordinate startRow, const int count, const block::Coordinate delta)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
void moveColumns(block::Coordinate startColumn, int count, block::Coordinate delta, Block fillChar)
Move columns in the buffer by a given delta.
A positive delta moves columns right, a negative delta moves columns left. This reshuffles the moved columns, but columns that get moved out of the buffer area are deleted and replaced by empty cells using the
fillChar.- Parameters:
startColumn – The first column to move.
count – The number of columns to move.
delta – The number of positions to move (positive = right, negative = left).
fillChar – The character to fill vacated cells with.
- Throws:
err::ParameterError – if
startColumnis out of bounds orcountis negative or exceeds buffer size.
-
inline void moveColumns(const block::Coordinate startColumn, const int count, const block::Coordinate delta)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
virtual void fill(const Block &fillBlock) noexcept override
Fill/clear the buffer with the given character.
Note
This will also reset the internal remapping indexes.
- Parameters:
fillBlock – The block to use to fill the buffer.
-
void drawBitmap(const Bitmap &bitmap, block::Position pos, const BitmapDrawOptions &options = BitmapDrawOptions::defaultOptions(), std::size_t animationCycle = 0) noexcept
Draw a bitmap at a given position.
The bitmap is rendered according to
options.scaleMode(). Ifoptions.block16Style()is set, it overrides the scale mode and renders one terminal cell per bitmap pixel. Pixels or rendered cells outside the buffer are ignored.- Parameters:
bitmap – The bitmap to draw.
pos – The position of the top left corner.
options – Bitmap drawing options.
animationCycle – Animation cycle for color animations.
-
void drawBitmap(const Bitmap &bitmap, block::Rectangle rect, geometry::Alignment alignment = geometry::Alignment::TopLeft, const BitmapDrawOptions &options = BitmapDrawOptions::defaultOptions(), std::size_t animationCycle = 0) noexcept
Draw a bitmap into the given rectangle.
The rendered bitmap is aligned inside
rect. If it is larger thanrect, it is cropped according to the alignment.Note
For half-block drawing mode, alignment and cropping happen at rendered cell boundaries, not per pixel.
- Parameters:
bitmap – The bitmap to draw.
rect – The rectangle to draw the bitmap into.
alignment – geometry::Alignment of the bitmap within the rectangle.
options – Bitmap drawing options.
animationCycle – Animation cycle for color animations.
-
virtual void drawBlockText(block::Position pos, const BlockString &str)
Draw a text without warping from the given position.
A newline breaks to the next line, starting at
pos.x. Characters outside this buffer are cut off.- Parameters:
pos – The start position (top-left corner).
str – The text to draw on this buffer.
-
void drawBlockText(const BlockText &text, std::size_t animationCycle = 0)
If fg or bg is set to
Inherited, the current color from the buffer is used.Draw simple text into a rectangle. If fg or bg is set to
Inherited, the current color from the buffer is used.- Parameters:
text – The text description.
animationCycle – Animation cycle for animated text.
-
void drawBlockText(const text::String &text, block::Rectangle rect, geometry::Alignment alignment = geometry::Alignment::TopLeft, BlockStyle style = {}, std::size_t animationCycle = 0)
Draw simple text into a rectangle.
If fg or bg is set to
Inherited, the current color from the buffer is used.- Parameters:
text – The text to render.
rect – The target rectangle.
alignment – The alignment inside the rectangle.
style – The base text style.
animationCycle – Animation cycle for animated text. Invalid UTF-8 bytes are replaced with the Unicode replacement character.
-
void drawBlockText(const text::U32String &text, block::Rectangle rect, geometry::Alignment alignment = geometry::Alignment::TopLeft, BlockStyle style = {}, std::size_t animationCycle = 0)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
void drawBlockText(const BlockString &text, block::Rectangle rect, geometry::Alignment alignment = geometry::Alignment::TopLeft, BlockStyle style = {}, std::size_t animationCycle = 0)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
void drawBlockText(const BlockString &text, block::Rectangle rect, const BlockTextOptions &options, std::size_t animationCycle = 0)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
virtual void fill(const Block &fillBlock) noexcept
Fill/clear the buffer with the given character.
- Parameters:
fillBlock – The block to use to fill the buffer.
-
void fill(block::Rectangle rect, const Block &fillBlock, const BlockCombinationStylePtr &combinationStyle = {}) noexcept
Fill the given rectangle.
Positions outside the buffer are ignored.
- Parameters:
rect – The rectangle to be filled.
fillBlock – The block for filling.
combinationStyle – The combination style for overwriting existing characters.
-
void fill(block::Rectangle rect, const Tile9StylePtr &style, Color baseColor = {}, const BlockCombinationStylePtr &combinationStyle = {}) noexcept
Fill the given rectangle using a repeating 9-tile style.
Positions outside the buffer are ignored.
- Parameters:
rect – The rectangle to be filled.
style – The tile style to repeat across the rectangle.
baseColor – The base color underneath the tile style.
combinationStyle – The combination style for overwriting existing characters.
-
void fill(block::Rectangle rect, const Tile9StylePtr &style, BlockStyle baseStyle, const BlockCombinationStylePtr &combinationStyle = {}) noexcept
Fill the given rectangle using a repeating 9-tile style.
Positions outside the buffer are ignored.
- Parameters:
rect – The rectangle to be filled.
style – The tile style to repeat across the rectangle.
baseStyle – The base style underneath the tile style.
combinationStyle – The combination style for overwriting existing characters.
-
virtual void resize(block::Size newSize) = 0
Resize this buffer in a memory-efficient way.
The content of the resized buffer is undefined and must be filled with new content.
- Parameters:
newSize – The new size for the buffer.
-
virtual void resize(block::Size size, BufferResizeMode mode, Block fillChar)
Resize this buffer and optionally preserve visible content.
The default implementation calls
resize(block::Size)forBufferResizeMode::Fast. ForBufferResizeMode::PreserveContent, it clones the current buffer, resizes it usingresize(block::Size), and restores the visible content withsetFrom(). Implementations can override this when they provide a faster preserve-content path.- Parameters:
size – The new size for the buffer.
mode – How existing content should be handled during resizing.
fillChar – The character to fill newly visible cells with in preserve-content mode.
-
virtual void set(block::Position pos, const Block &block) noexcept = 0
Write a block at the given position.
Note
Writes outside the buffer are ignored.
- Parameters:
pos – The coordinates within the buffer.
block – The block value to store.
-
virtual void set(block::Position pos, const Block &block, const BlockCombinationStylePtr &combinationStyle) noexcept
Write a block at the given position using a combination style.
Note
Writes outside the buffer are ignored.
- Parameters:
pos – The coordinates within the buffer.
block – The block value to store.
combinationStyle – The combination style for overwriting existing characters.
-
virtual void set(block::Position pos, const BlockString &str) noexcept
Write a string at the given position.
NL jumps to the next row. Other control and zero-width characters are ignored. Color (even inherited) overwrites the existing characters. Use
drawBlockText(pos, text)for a color overlay.- Parameters:
pos – The coordinates within the buffer.
str – The string to write.
-
class SimpleBlockCombinationStyle : public erbsland::cterm::BlockCombinationStyle
Combine block characters through a map of current/overlay character pairs.
Public Types
Public Functions
-
SimpleBlockCombinationStyle() = default
Create an empty combination style.
-
virtual Block combine(const Block ¤t, const Block &overlay) const noexcept override
Combines the current char with a new that is placed on top of the current one.
The default implementation just returns the overlay character.
- Parameters:
current – The current (lower) character.
overlay – The new (upper) character that overlays the current one.
- Returns:
The combined character.
-
SimpleBlockCombinationStyle() = default
-
enum class erbsland::cterm::TabOverflowBehavior : uint8_t
The handling for tabs whose configured tab stop does not advance the current line.
This mode is used when a left-aligned paragraph encounters a tab stop that is less than or equal to the current column, or when there is no further configured tab stop.
Values:
-
enumerator AddSpace
Replace the tab with a single space character.
-
enumerator LineBreak
End the current physical line and continue after the tab on the next wrapped line.
-
enumerator AddSpace
-
class Terminal : public erbsland::cterm::CursorWriter
High-level terminal interface for screen control, color output, and key input.
Public Types
-
enum class RefreshMode : uint8_t
Screen clearing strategy used between rendered frames.
Values:
-
enumerator Keep
Do not emit cursor or clear-screen control sequences automatically.
-
enumerator Clear
Clear the full screen before rendering the next frame.
-
enumerator Overwrite
Move the cursor to the top-left corner before rendering the next frame.
-
enumerator Keep
Public Functions
-
explicit Terminal()
Create a new terminal instance with default values.
-
explicit Terminal(TerminalFlags flags)
Create a new terminal instance.
- Parameters:
flags – The terminal flags to use.
-
explicit Terminal(block::Size size, TerminalFlags flags = {})
Create a new terminal instance.
The size is automatically bounded to the minimum and maximum supported sizes.
- Parameters:
size – The fallback terminal size used when automatic detection is unavailable.
flags – The terminal flags to use.
-
explicit Terminal(BackendPtr backend, block::Size size = {80, 25})
Create a new terminal instance with a custom backend.
The size is automatically bounded to the minimum and maximum supported sizes.
- Parameters:
backend – The backend to use for the terminal.
size – The fallback terminal size used when automatic detection is unavailable.
-
virtual Color color() const noexcept override
Get the current color.
- Returns:
The currently tracked terminal color state.
-
virtual BlockAttributes blockAttributes() const noexcept override
Get the current character attributes.
- Returns:
The currently tracked character attribute state.
-
virtual void setColor(Color color) noexcept override
Set foreground and background color.
Note
Inheritedcolors are converted toDefaultcolors.- Parameters:
color – The new combined color.
-
virtual void setBlockAttributes(BlockAttributes attributes) noexcept override
Set all character attributes.
Unspecified attributes are treated as disabled.
- Parameters:
attributes – The new character attributes.
-
virtual void setForeground(Foreground color) noexcept override
Set the foreground color.
Note
Inheritedcolors are converted toDefaultcolors.- Parameters:
color – The new foreground color.
-
virtual void setBackground(Background color) noexcept override
Set the background color.
Note
Inheritedcolors are converted toDefaultcolors.- Parameters:
color – The new background color.
-
virtual BlockAttributes supportedBlockAttributes() const noexcept override
Get the character attributes supported by this writer.
- Returns:
The supported character attributes.
-
virtual void moveLeft(block::Coordinate count) noexcept override
Move the cursor to the left.
If the resulting position is out of bounds, the result is undefined.
- Parameters:
count – The number of terminal cells to move.
-
virtual void moveRight(block::Coordinate count) noexcept override
Move the cursor to the right.
If the resulting position is out of bounds, the result is undefined.
- Parameters:
count – The number of terminal cells to move.
-
virtual void moveUp(block::Coordinate count) noexcept override
Move the cursor up.
If the resulting position is out of bounds, the result is undefined.
- Parameters:
count – The number of terminal cells to move.
-
virtual void moveDown(block::Coordinate count) noexcept override
Move the cursor down.
If the resulting position is out of bounds, the result is undefined.
- Parameters:
count – The number of terminal cells to move.
-
virtual void moveTo(block::Position pos) noexcept override
Move the cursor to the given position.
If the resulting position is out of bounds, the result is undefined.
- Parameters:
pos – The position to move the cursor to.
-
virtual void moveHome() noexcept override
Moves the cursor to the home position.
-
virtual void moveCursor(block::Position posOrDelta, MoveMode mode) noexcept override
Move the cursor absolute or relative.
If the resulting position is out of bounds, the result is undefined.
- Parameters:
posOrDelta – The absolute position or delta for the move.
mode – The move mode, either absolute or relative.
-
virtual void setAutoWrap(bool enabled) noexcept override
Enabled/disable auto-wrap.
Auto wrap controls if the cursor automatically wraps to the next line when reaching the right margin. This is a feature that can be enabled or disabled. Do not confuse this with line wrapping, which is a different feature.
- Parameters:
enabled – Whether to enable or disable auto-wrap.
-
virtual void setCursorVisible(bool visible) noexcept override
Make the cursor visible/invisible.
Not all implementations support changing the cursor visibility.
- Parameters:
visible – Whether to make the cursor visible or invisible.
-
virtual void write(const Block &character) noexcept override
Write a character at the current cursor position.
Inherited color components resolve against the currently active color. Overwrites the character under the cursor.
- Parameters:
character – The character to write.
-
virtual void write(const BlockString &str) noexcept override
Write a string at the current cursor position.
Inherited color components in each character resolve against the currently active color. Overwrites the characters under the cursor.
- Parameters:
str – The string to write.
-
virtual void writeResolved(const Block &character) noexcept override
Write a character that is already fully resolved against the writer state.
This bypasses any additional inherited-style resolution in implementations that can optimize for it.
- Parameters:
character – The already resolved character to write.
-
virtual void writeResolved(const BlockString &str) noexcept override
Write a string whose characters are already fully resolved against the writer state.
This bypasses any additional inherited-style resolution in implementations that can optimize for it.
- Parameters:
str – The already resolved string to write.
-
virtual void write(const ReadableBuffer &buffer) noexcept override
Write a buffer at the current cursor position.
This will not perform any additional formatting, clipping, or processing. Each line of the buffer will be written, and a line-break added after each line.
- Parameters:
buffer – The buffer to write.
-
virtual void writeLineBreak() noexcept override
Write a line-break.
This will move the cursor to the beginning of the next line.
-
void setSize(block::Size size) noexcept
Modify the size of the terminal.
The size is automatically bounded to the minimum and maximum supported sizes. If size detection is enabled, the terminal size will be automatically detected and updated.
- Parameters:
size – The new terminal size.
-
inline RefreshMode refreshMode() const noexcept
Get the refresh mode.
-
inline void setRefreshMode(const RefreshMode mode) noexcept
Set the refresh mode.
- Parameters:
mode – The screen refresh strategy to use.
-
inline OutputMode outputMode() const noexcept
Get the current output mode for the terminal.
-
void setOutputMode(OutputMode outputMode) noexcept
Set the output mode.
Switching to
OutputMode::BlockTextdisables size detection, refresh modes, and back-buffer updates.- Parameters:
outputMode – The output mode to set.
-
bool sizeDetectionEnabled() const noexcept
Check whether dynamic terminal size detection is enabled.
-
void setSizeDetectionEnabled(bool enabled) noexcept
Set if dynamic terminal size detection is enabled.
Can only be enabled while the output mode is
OutputMode::FullControl.- Parameters:
enabled –
trueto enable automatic size detection.
-
bool lineBufferEnabled() const noexcept
Check whether line buffering is enabled for incremental writes.
- Returns:
trueif text output is collected until a newline orflush().
-
void setLineBufferEnabled(bool enabled) noexcept
Enable or disable line buffering for incremental writes.
When enabled, output is accumulated until a newline or
flush()is reached. Line buffering can only be enabled if the backend supports both color and cursor ANSI codes.- Parameters:
enabled –
trueto enable buffered writes.
-
bool safeMarginEnabled() const noexcept
Check whether the compatibility safe margin is enabled.
- Returns:
trueif one column and one row are reserved from the detected terminal size.
-
void setSafeMarginEnabled(bool enabled) noexcept
Enable or disable the compatibility safe margin.
When enabled, the reported drawable size is reduced by one column and one row. Disable this only when the terminal should use its full detected size and newline-free screen updates.
- Parameters:
enabled –
trueto reserve one column and one row from the terminal size.
-
bool backBufferEnabled() const noexcept
Check whether the optional back buffer is enabled for smart overwrite updates.
- Returns:
trueifupdateScreen()keeps the previous rendered frame for diff-based updates.
-
void setBackBufferEnabled(bool enabled) noexcept
Enable or disable the optional back buffer used by smart overwrite updates.
Enabling the back buffer forces the next
updateScreen()call to redraw the full frame once. Can only be enabled while the output mode isOutputMode::FullControl.- Parameters:
enabled –
trueto enable the back buffer.
-
void setBackend(BackendPtr backend) noexcept
Set a custom backend for the terminal.
- Parameters:
backend – The backend to use for the terminal. If
nullptris passed, the default backend is restored.
-
Input &input() noexcept
Access the input interface.
- Returns:
The platform-specific input backend owned by this terminal.
-
void initializeScreen() noexcept
Initialize the console once before the application starts.
Applies platform-specific setup, optionally clears the screen, and tests for the initial screen size. Also hides the cursor by default, as it is usually only made visible when the user makes input. Call this at the start of your application.
-
bool isInteractive() const noexcept
Check whether an interactive terminal is attached to the process.
Call this after
initializeScreen()to see if screen-size detection and terminal control features are active.- Returns:
trueif the backend detected an interactive terminal.
-
void testScreenSize() noexcept
Detect terminal resize changes.
After calling this method,
size()returns a safe size for the terminal.
-
void restoreScreen() noexcept
Restore terminal settings when the application is quit.
Call this at the end of your application. This should restore the terminal to its original state, including cursor visibility and any other settings that were modified during initialization.
-
TerminalOutputGuard synchronizeOutput() const
Exclusively synchronize a sequence of output operations on this terminal.
Individual terminal calls stay independently thread-safe and do not acquire this optional guard.
- Returns:
A move-only guard retaining the recursive output lock until its destruction.
-
virtual void clearScreen() noexcept override
Clears the screen.
In
OutputMode::BlockText, this method has no effect. If you need the screen cleared immediately, callflush()after this method.
-
bool isAlternateScreenActive() const noexcept
Test if the alternate screen is active.
This is no terminal detection, it just returns the internal state.
-
void setAlternateScreen(bool enabled) noexcept
Activate or deactivate the alternate screen.
If activated or deactivated, the buffer is immediately flushed to the terminal.
-
void updateScreen(const ReadableBuffer &buffer, const UpdateSettings &settings = {}) noexcept
Render a buffer onto the terminal.
The buffer is clipped to the drawable area reported by
size()and optionally annotated with crop marks. If the terminal is smaller than the configured minimum size, only the minimum-size marker is rendered. WhenswitchToAlternateBufferistrueand the alternate screen is not active, this call first switches to the alternate screen and then renders the buffer.- Parameters:
buffer – The buffer to render.
settings – Additional rendering settings for crop marks and minimum terminal size handling.
-
void flush() noexcept
Flush the all buffer immediately to the terminal.
-
inline void lineBreak() noexcept
Write a terminal line break.
- Deprecated:
Use
writeLineBreak()instead.
-
inline bool colorEnabled() const noexcept
Test if non-text output mode is active.
- Deprecated:
Use
outputMode()instead.
- Returns:
trueif the terminal is not inOutputMode::BlockText.
-
void setColorEnabled(bool enabled) noexcept
Enable or disable text-only output mode through the legacy boolean API.
- Deprecated:
Use
setOutputMode()instead.
- Parameters:
enabled –
trueto allow color/control output,falsefor plain text mode.
-
virtual void setColor(Color color) noexcept = 0
Set foreground and background color.
Note
Inheritedcolors are converted toDefaultcolors.- Parameters:
color – The new combined color.
-
inline void setColor(const Foreground foregroundColor, const Background backgroundColor) noexcept
Set foreground and background color.
Note
Inheritedcolors are converted toDefaultcolors.- Parameters:
foregroundColor – The new foreground color.
backgroundColor – The new background color.
-
virtual void write(const Block &character) noexcept = 0
Write a character at the current cursor position.
Inherited color components resolve against the currently active color. Overwrites the character under the cursor.
- Parameters:
character – The character to write.
-
virtual void write(const BlockString &str) noexcept = 0
Write a string at the current cursor position.
Inherited color components in each character resolve against the currently active color. Overwrites the characters under the cursor.
- Parameters:
str – The string to write.
-
inline void write(const text::String &text) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. Invalid UTF-8 bytes are replaced with the Unicode replacement character.
-
inline void write(const text::U32String &text) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
virtual void write(const ReadableBuffer &buffer) noexcept = 0
Write a buffer at the current cursor position.
This will not perform any additional formatting, clipping, or processing. Each line of the buffer will be written, and a line-break added after each line.
- Parameters:
buffer – The buffer to write.
-
virtual void writeLineBreak() noexcept = 0
Write a line-break.
This will move the cursor to the beginning of the next line.
-
enum class RefreshMode : uint8_t
-
enum class erbsland::cterm::TerminalFlag : uint8_t
A terminal flag.
Values:
-
enumerator NoSignalHandling
Disables signal handling to restore the screen when the application is terminated.
If this flag is set, you must ensure that the
restoreScreen()method is called when the application is terminated by a signal. Otherwise, the terminal will not be restored properly.
-
enumerator NoSignalHandling
-
class TerminalFlags
A set of terminal flags.
Terminal flags control the behavior of the built-in terminal backend. These flags can only be set at construction time and cannot be modified after that.
Public Types
-
using Mask = uint8_t
Unsigned storage type used for the combined flag bits.
-
using Enum = TerminalFlag
The enum type combined by this flag set.
Public Functions
-
template<typename ...tFlags>
inline constexpr TerminalFlags(tFlags... flags) Create a combined set of flags.
-
inline TerminalFlags operator|(const TerminalFlag flag) const
Combine this flag set with one additional flag.
- Parameters:
flag – The flag to add.
- Returns:
The combined flag set.
-
inline bool has(const TerminalFlag flag) const noexcept
Test if a flag is set.
-
inline void set(const TerminalFlag flag, const bool enabled = true)
Set a flag.
-
inline void clear(const TerminalFlag flag)
Clear a flag.
Friends
-
inline friend TerminalFlags operator|(const TerminalFlag flag, const TerminalFlags flags)
Combine one flag with an existing flag set.
- Parameters:
flag – The flag to add.
flags – The existing flag set.
- Returns:
The combined flag set.
-
inline friend TerminalFlags operator|(const TerminalFlags flags1, const TerminalFlags flags2)
Combine two flag sets.
- Parameters:
flags1 – The first flag set.
flags2 – The second flag set.
- Returns:
The combined flag set.
-
using Mask = uint8_t
-
class TerminalOutputGuard
An exclusive lease for a sequence of terminal output operations.
-
class TerminalSession
A scoped terminal session.
Automatically calls
initializeScreenon construction andrestoreScreenon destruction.
-
class TerminalStream : public erbsland::stream::TextOutputStream
A text output stream that writes to a terminal with a fixed base style.
Public Functions
-
explicit TerminalStream(TerminalPtr terminal, BlockStyle style = BlockStyle::reset(), stream::OutputStreamSettings settings = {})
Create a terminal stream.
- Parameters:
terminal – The terminal to write to.
style – The style applied to every write.
settings – The fixed timeout and buffer settings.
-
virtual text::StringEncoding encoding() const noexcept override
Get the encoding configured for the stream.
-
virtual text::StringEncoding effectiveEncoding() const noexcept override
Get the effective encoding used by the stream.
-
virtual const stream::OutputStreamSettings &outputSettings() const noexcept override
Get the immutable settings selected when this stream was created.
-
virtual stream::StreamState state() const noexcept override
Get the lifecycle state.
-
virtual bool isReady() const noexcept override
Test if the stream has no queued back-buffer data.
For a single producer, a following write within
backBufferLimit()can be accepted without waiting unless the stream state changes. Concurrent producers must inspect each write result.
-
virtual stream::StreamWaitStatus waitForReady() override
Wait up to the configured timeout for the stream to become ready.
-
virtual stream::StreamWriteStatus flush() override
Flush buffered output.
- Throws:
stream::StreamError – If the backing target reports a flush error.
-
virtual stream::StreamCloseStatus close() override
Start or continue graceful close and wait up to the configured timeout.
-
virtual void abort() noexcept override
Immediately abandon queued output and pending native work without waiting.
-
virtual stream::StreamWriteStatus write(text::Char character) override
Write one character.
- Parameters:
character – The character to write.
- Throws:
stream::StreamError – If the stream is closed or the backing target fails.
- Returns:
Successif the character was accepted, orTimeoutif nothing was accepted.
-
virtual stream::StreamWriteStatus write(const text::String &text) override
Write text.
- Parameters:
text – The text to write.
- Throws:
stream::StreamError – If the stream is closed or the backing target fails.
- Returns:
Successif all text was accepted, orTimeoutif nothing was accepted.
-
virtual stream::StreamWriteStatus writeLine() override
Write a line-feed character.
- Throws:
stream::StreamError – If the stream is closed or the backing target fails.
- Returns:
Successif the line feed was accepted, orTimeoutif nothing was accepted.
-
virtual stream::StreamWriteStatus writeLine(const text::String &text) override
Write text followed by a line-feed character.
- Parameters:
text – The text to write before the line-feed.
- Throws:
stream::StreamError – If the stream is closed or the backing target fails.
- Returns:
Successif the complete line was accepted, orTimeoutif nothing was accepted.
-
inline const TerminalPtr &terminal() const noexcept
Get the terminal used by this stream.
-
BlockStyle style() const
Get the style applied to every write.
- Returns:
A thread-safe snapshot of the current base style.
-
void setStyle(BlockStyle style)
Set the style applied to every write.
- Parameters:
style – The base style to capture with subsequently queued writes.
Public Static Functions
-
static auto create(TerminalPtr terminal, BlockStyle style = BlockStyle::reset(), stream::OutputStreamSettings settings = {}) -> TerminalStreamPtr
Create a shared terminal stream.
- Parameters:
terminal – The terminal receiving stream output.
style – The style applied to every write transaction.
settings – The immutable timeout and buffering settings.
- Returns:
A new shared terminal stream.
-
static std::pair<TerminalStreamPtr, TerminalStreamPtr> createStandardStreams(TerminalPtr terminal)
Create synchronized output and error streams for a terminal.
- Parameters:
terminal – The terminal shared by both streams.
- Returns:
An output stream with reset style and an error stream with the terminal’s error style.
-
explicit TerminalStream(TerminalPtr terminal, BlockStyle style = BlockStyle::reset(), stream::OutputStreamSettings settings = {})
-
class Tile9Style
Defines a style for repeating a 3x3 tile pattern across a rectangle.
The 9-tile layout uses this arrangement: top-left, top, top-right, left, center, right, bottom-left, bottom, bottom-right.
Optionally, 7 additional tiles can be provided for degenerate rectangles: single-row left, single-row center, single-row right, single-column top, single-column center, single-column bottom, and the single-cell tile.
Public Types
-
enum class Element : uint8_t
Named elements of the 16-tile style table.
Values:
-
enumerator NorthWest
Top-left tile.
-
enumerator North
Top edge tile.
-
enumerator NorthEast
Top-right tile.
-
enumerator West
Left edge tile.
-
enumerator Center
Center tile.
-
enumerator East
Right edge tile.
-
enumerator SouthWest
Bottom-left tile.
-
enumerator South
Bottom edge tile.
-
enumerator SouthEast
Bottom-right tile.
-
enumerator HorizontalWest
Left tile for one-row rectangles.
-
enumerator HorizontalCenter
Center tile for one-row rectangles.
-
enumerator HorizontalEast
Right tile for one-row rectangles.
-
enumerator VerticalNorth
Top tile for one-column rectangles.
-
enumerator VerticalCenter
Center tile for one-column rectangles.
-
enumerator VerticalSouth
Bottom tile for one-column rectangles.
-
enumerator Single
Single-cell tile.
-
enumerator NorthWest
Public Functions
-
explicit Tile9Style(std::array<Block, 9> tiles) noexcept
Create a new 9-tile style from the repeating 3x3 tile layout.
- Parameters:
tiles – The 3x3 tiles in row-major order.
-
explicit Tile9Style(std::array<Block, 16> tiles) noexcept
Create a new 9-tile style with explicit tiles for degenerate rectangles.
- Parameters:
tiles – The 3x3 tiles followed by 7 degenerate tiles.
-
explicit Tile9Style(std::array<text::Char, 16> tiles, BlockStyle style) noexcept
Create a new 9-tile style from code points and one shared style.
- Parameters:
tiles – The 3x3 tiles followed by 7 degenerate tiles.
style – The shared style for all tiles.
-
explicit Tile9Style(const text::String &tiles)
Create a new 9-tile style from 9 or 16 terminal characters.
- Parameters:
tiles – A sequence of 9 tiles, or 16 tiles including the degenerate cases.
- Throws:
err::ParameterError – If
tilesdoes not contain exactly 9 or 16 terminal characters.
-
explicit Tile9Style(const text::U32String &tiles)
Create a new 9-tile style from 9 or 16 terminal characters.
- Parameters:
tiles – A sequence of 9 tiles, or 16 tiles including the degenerate cases.
- Throws:
err::ParameterError – If
tilesdoes not contain exactly 9 or 16 terminal characters.
-
Block block(block::Rectangle rect, block::Position pos) const noexcept
Resolve the tile for a given position inside a rectangle.
The center and edge tiles are repeated as needed.
- Parameters:
rect – The styled rectangle.
pos – A position inside
rect.
- Returns:
The resolved tile, or an empty character if
posis outsiderect.
Public Static Functions
-
static Tile9StylePtr create(const text::String &tiles)
Create a new shared style from 9 or 16 terminal characters.
- Parameters:
tiles – A sequence of 9 tiles, or 16 tiles including the degenerate cases.
- Throws:
err::ParameterError – If
tilesdoes not contain exactly 9 or 16 terminal characters.- Returns:
A shared style instance.
-
static Tile9StylePtr create(const text::U32String &tiles)
Create a new shared style from 9 or 16 terminal characters.
- Parameters:
tiles – A sequence of 9 tiles, or 16 tiles including the degenerate cases.
- Throws:
err::ParameterError – If
tilesdoes not contain exactly 9 or 16 terminal characters.- Returns:
A shared style instance.
-
static Tile9StylePtr outerHalfBlockFrame()
For drawing half-block frames on the outer cell edges.
-
static Tile9StylePtr innerHalfBlockFrame()
For drawing half-block frames on the inner cell edges.
-
static Tile9StylePtr forStyle(FrameStyle frameStyle)
Get the tile-9 style for a predefined frame style.
- Parameters:
frameStyle – The frame style to resolve.
- Returns:
The matching tile-9 style, or
nullptrif the frame style usesBlock16Style.
-
enum class Element : uint8_t
-
using erbsland::cterm::Tile9StylePtr = std::shared_ptr<Tile9Style>
Shared pointer for Tile9Style.
-
template<typename T>
concept PrintableArg - #include <erbsland/cterm/TypeTraits.hpp>
A value accepted by
Terminal::print()andTerminal::printLine()orBlockStringEditor::append().
-
template<typename ...T>
concept CharColorConstructorArgs - #include <erbsland/cterm/TypeTraits.hpp>
Constructor arguments that can build a
Colorwithout matching the explicitBlockAttributesoverloads.
-
class UpdateSettings
Settings controlling how
Terminal::updateScreen()renders a buffer.Public Functions
-
UpdateSettings() = default
Create default screen update settings.
-
block::Size minimumSize() const noexcept
Get the minimum terminal size required for rendering the buffer.
- Returns:
The minimum supported terminal size.
-
void setMinimumSize(block::Size minimumSize) noexcept
Set the minimum terminal size required for rendering the buffer.
- Parameters:
minimumSize – The minimum supported terminal size.
-
const Block &minimumSizeBackground() const noexcept
Get the background character used if the terminal is too small.
-
void setMinimumSizeBackground(Block character) noexcept
Set the background fill character when the terminal is too small.
- Parameters:
character – The background character
-
const BlockString &minimumSizeMessage() const noexcept
Get the message displayed if the terminal size is too small.
-
void setMinimumSizeMessage(BlockString message) noexcept
Set the message displayed if the terminal is too small.
- Parameters:
message – The displayed message.
-
bool showCropMarks() const noexcept
Check if crop marks are enabled.
-
void setShowCropMarks(bool showCropMarks) noexcept
Enable or disable crop marks.
- Parameters:
showCropMarks –
trueto render crop marks for truncated content.
-
const Block &cropMarkRight() const noexcept
Get the mark rendered when content is cropped on the right.
-
void setCropMarkRight(Block cropMarkRight) noexcept
Set the mark rendered if the content is cropped on the right.
- Parameters:
cropMarkRight – The right crop mark.
-
const Block &cropMarkBottomRight() const noexcept
Get the mark rendered in the bottom right corner when content is cropped.
-
void setCropMarkBottomRight(Block cropMarkBottomRight) noexcept
Set the mark in the bottom right corner if content is cropped on the bottom and right.
- Parameters:
cropMarkBottomRight – The bottom-right crop mark.
-
const Block &cropMarkBottom() const noexcept
Get the mark rendered when content is cropped at the bottom.
-
void setCropMarkBottom(Block cropMarkBottom) noexcept
Set the mark rendered if the content is cropped at the bottom.
- Parameters:
cropMarkBottom – The bottom crop mark.
-
bool switchToAlternateBuffer() const noexcept
Test if the update shall switch to the alternate screen buffer.
-
void setSwitchToAlternateBuffer(bool switchToAlternateBuffer) noexcept
Enable or disable switching to the alternate screen buffer.
- Parameters:
switchToAlternateBuffer –
trueto switch to the alternate screen buffer.
-
void applyTo(BufferViewBase &view) const noexcept
Apply these settings to a BufferView.
-
void setMinimumSizeMark(Block minimumSizeMark) noexcept
Set the minimum-size background character through the legacy name.
- Deprecated:
Use
setMinimumSizeBackground()instead.
- Parameters:
minimumSizeMark – The background character shown when the terminal is too small.
-
const Block &minimumSizeMark() const noexcept
Get the minimum-size background character through the legacy name.
- Deprecated:
Use
minimumSizeBackground()instead.
- Returns:
The background character shown when the terminal is too small.
-
UpdateSettings(block::Size minimumSize, Block minimumSizeBackground, bool showCropMarks, Block cropMarkRight, Block cropMarkBottom) noexcept
Construct update settings using the deprecated aggregate-style compatibility constructor.
- Deprecated:
Construct
UpdateSettings{}and configure it with setters instead.
- Parameters:
minimumSize – The minimum terminal size required for normal rendering.
minimumSizeBackground – The fill character for the size-too-small background.
showCropMarks –
trueto show crop marks for truncated content.cropMarkRight – The crop mark to draw at the right edge.
cropMarkBottom – The crop mark to draw at the bottom edge.
Public Static Functions
-
static const UpdateSettings &defaultSettings() noexcept
Shared default value.
-
UpdateSettings() = default
-
class WritableBuffer : public erbsland::cterm::ReadableBuffer
Abstract writable terminal buffer interface.
This base class combines the read-only
ReadableBufferAPI with mutation and higher-level drawing helpers such as frames, text, and bitmap rendering. Concrete implementations likeBufferprovide the actual storage.Subclassed by erbsland::cterm::Buffer, erbsland::cterm::RemappedBuffer, erbsland::cterm::WriteClippedBufferBase
Public Functions
-
virtual void resize(block::Size newSize) = 0
Resize this buffer in a memory-efficient way.
The content of the resized buffer is undefined and must be filled with new content.
- Parameters:
newSize – The new size for the buffer.
-
virtual void resize(block::Size size, BufferResizeMode mode, Block fillChar)
Resize this buffer and optionally preserve visible content.
The default implementation calls
resize(block::Size)forBufferResizeMode::Fast. ForBufferResizeMode::PreserveContent, it clones the current buffer, resizes it usingresize(block::Size), and restores the visible content withsetFrom(). Implementations can override this when they provide a faster preserve-content path.- Parameters:
size – The new size for the buffer.
mode – How existing content should be handled during resizing.
fillChar – The character to fill newly visible cells with in preserve-content mode.
-
virtual void set(block::Position pos, const Block &block) noexcept = 0
Write a block at the given position.
Note
Writes outside the buffer are ignored.
- Parameters:
pos – The coordinates within the buffer.
block – The block value to store.
-
virtual void setAndResizeFrom(const ReadableBuffer &other)
Copy the content from another buffer and match its size.
This buffer is completely overwritten and resized to the size of
other.- Parameters:
other – The buffer to copy from.
-
virtual void set(block::Position pos, const Block &block, const BlockCombinationStylePtr &combinationStyle) noexcept
Write a block at the given position using a combination style.
Note
Writes outside the buffer are ignored.
- Parameters:
pos – The coordinates within the buffer.
block – The block value to store.
combinationStyle – The combination style for overwriting existing characters.
-
virtual void set(block::Position pos, const BlockString &str) noexcept
Write a string at the given position.
NL jumps to the next row. Other control and zero-width characters are ignored. Color (even inherited) overwrites the existing characters. Use
drawBlockText(pos, text)for a color overlay.- Parameters:
pos – The coordinates within the buffer.
str – The string to write.
-
void setFrom(const ReadableBuffer &other, Block fillChar = Block::space())
Copy the content from another buffer into this one.
This buffer is completely overwritten but not resized. If there is a size mismatch, the contents are either cut off or filled using
fillChar.- Parameters:
other – The buffer to copy from.
fillChar – The character to use for filling if the sizes differ.
-
virtual void fill(const Block &fillBlock) noexcept
Fill/clear the buffer with the given character.
- Parameters:
fillBlock – The block to use to fill the buffer.
-
void fill(block::Rectangle rect, const Block &fillBlock, const BlockCombinationStylePtr &combinationStyle = {}) noexcept
Fill the given rectangle.
Positions outside the buffer are ignored.
- Parameters:
rect – The rectangle to be filled.
fillBlock – The block for filling.
combinationStyle – The combination style for overwriting existing characters.
-
void fill(block::Rectangle rect, const Tile9StylePtr &style, Color baseColor = {}, const BlockCombinationStylePtr &combinationStyle = {}) noexcept
Fill the given rectangle using a repeating 9-tile style.
Positions outside the buffer are ignored.
- Parameters:
rect – The rectangle to be filled.
style – The tile style to repeat across the rectangle.
baseColor – The base color underneath the tile style.
combinationStyle – The combination style for overwriting existing characters.
-
void fill(block::Rectangle rect, const Tile9StylePtr &style, BlockStyle baseStyle, const BlockCombinationStylePtr &combinationStyle = {}) noexcept
Fill the given rectangle using a repeating 9-tile style.
Positions outside the buffer are ignored.
- Parameters:
rect – The rectangle to be filled.
style – The tile style to repeat across the rectangle.
baseStyle – The base style underneath the tile style.
combinationStyle – The combination style for overwriting existing characters.
-
void drawFrame(block::Rectangle rect, const Block &frameBlock, const BlockCombinationStylePtr &combinationStyle = {}) noexcept
Draw a frame inside a given rectangle This will set all blocks at the edge, inside the given rectangle.
- Parameters:
rect – The rectangle for the frame.
frameBlock – The block for the frame.
combinationStyle – The combination style for overwriting existing characters.
-
void drawFrame(block::Rectangle rect, const Block16StylePtr &frameStyle, const BlockCombinationStylePtr &combinationStyle = {}, Color frameColor = {}) noexcept
Draw a frame inside a given rectangle This will set all blocks at the edge, inside the given rectangle.
- Parameters:
rect – The rectangle for the frame.
frameStyle – A custom frame style.
combinationStyle – The combination style for overwriting existing characters.
frameColor – The base frame color. Any color from the frame style overlays this base color.
-
void drawFrame(block::Rectangle rect, const Tile9StylePtr &style, Color frameColor = {}, const BlockCombinationStylePtr &combinationStyle = {}) noexcept
Draw a frame inside a given rectangle using a repeating 9-tile style.
This will set all blocks at the edge, inside the given rectangle.
- Parameters:
rect – The rectangle for the frame.
style – The tile style for the frame.
frameColor – The base frame color. Any color from the style overlays this base color.
combinationStyle – The combination style for overwriting existing characters.
-
void drawFrame(block::Rectangle rect, FrameStyle frameStyle, Color frameColor = {}) noexcept
Draw a frame inside a given rectangle This will set all blocks at the edge, inside the given rectangle.
- Parameters:
rect – The rectangle for the frame.
frameStyle – The predefined frame style.
frameColor – The base frame color. Any color from the frame style overlays this base color.
-
void drawFrame(block::Rectangle rect, const FrameDrawOptions &options = FrameDrawOptions::defaultOptions(), std::size_t animationCycle = 0) noexcept
Draw a frame inside a given rectangle with configurable style, fill, and animated colors.
This will set all blocks at the edge, inside the given rectangle. If
options.fillBlock()is empty and noTile9Styleis active, the interior is left unchanged.- Parameters:
rect – The rectangle for the frame.
options – Frame drawing options.
animationCycle – Animation cycle for frame and fill color animations.
-
void drawGridLayout(block::Position pos, const GridLayout &layout, const FrameBorder &border) noexcept
Draw a grid layout using reusable border styles.
The layout defines only cell geometry;
borderdefines which lines are visible and how they are styled.- Parameters:
pos – The top-left position of the full grid.
layout – The grid cell layout.
border – The frame border styling for the grid lines.
-
void drawFilledFrame(block::Rectangle rect, const Block &frameBlock, const Block &fillBlock, const BlockCombinationStylePtr &combinationStyle = {}) noexcept
Draw a box and fill it.
- Parameters:
rect – The rectangle for the frame.
frameBlock – The block for the frame.
fillBlock – The block for filling.
combinationStyle – The combination style for overwriting existing characters.
-
void drawFilledFrame(block::Rectangle rect, const Block16StylePtr &frameStyle, const Block &fillBlock, const BlockCombinationStylePtr &combinationStyle = {}, Color frameColor = {}) noexcept
Draw a box and fill it.
- Parameters:
rect – The rectangle for the frame.
frameStyle – A custom frame style.
fillBlock – The block for filling.
combinationStyle – The combination style for overwriting existing characters.
frameColor – The base frame color. Any color from the frame style overlays this base color.
-
void drawFilledFrame(block::Rectangle rect, const Tile9StylePtr &style, const Block &fillBlock, const BlockCombinationStylePtr &combinationStyle = {}, Color frameColor = {}) noexcept
Draw a box and fill it using a repeating 9-tile style for the frame.
- Parameters:
rect – The rectangle for the frame.
style – The tile style for the frame.
fillBlock – The block for filling.
combinationStyle – The combination style for overwriting existing characters.
frameColor – The base frame color. Any color from the style overlays this base color.
-
void drawFilledFrame(block::Rectangle rect, FrameStyle frameStyle, const Block &fillBlock, Color frameColor = {}) noexcept
Draw a box and fill it.
- Parameters:
rect – The rectangle for the frame.
frameStyle – The predefined frame style.
fillBlock – The block for filling.
frameColor – The base frame color. Any color from the frame style overlays this base color.
-
virtual void drawBlockText(block::Position pos, const BlockString &str)
Draw a text without warping from the given position.
A newline breaks to the next line, starting at
pos.x. Characters outside this buffer are cut off.- Parameters:
pos – The start position (top-left corner).
str – The text to draw on this buffer.
-
void drawBlockText(const BlockText &text, std::size_t animationCycle = 0)
If fg or bg is set to
Inherited, the current color from the buffer is used.Draw simple text into a rectangle. If fg or bg is set to
Inherited, the current color from the buffer is used.- Parameters:
text – The text description.
animationCycle – Animation cycle for animated text.
-
void drawBlockText(const text::String &text, block::Rectangle rect, geometry::Alignment alignment = geometry::Alignment::TopLeft, BlockStyle style = {}, std::size_t animationCycle = 0)
Draw simple text into a rectangle.
If fg or bg is set to
Inherited, the current color from the buffer is used.- Parameters:
text – The text to render.
rect – The target rectangle.
alignment – The alignment inside the rectangle.
style – The base text style.
animationCycle – Animation cycle for animated text. Invalid UTF-8 bytes are replaced with the Unicode replacement character.
-
void drawBlockText(const text::U32String &text, block::Rectangle rect, geometry::Alignment alignment = geometry::Alignment::TopLeft, BlockStyle style = {}, std::size_t animationCycle = 0)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
void drawBlockText(const BlockString &text, block::Rectangle rect, geometry::Alignment alignment = geometry::Alignment::TopLeft, BlockStyle style = {}, std::size_t animationCycle = 0)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
void drawBlockText(const BlockString &text, block::Rectangle rect, const BlockTextOptions &options, std::size_t animationCycle = 0)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
void drawBitmap(const Bitmap &bitmap, block::Position pos, const BitmapDrawOptions &options = BitmapDrawOptions::defaultOptions(), std::size_t animationCycle = 0) noexcept
Draw a bitmap at a given position.
The bitmap is rendered according to
options.scaleMode(). Ifoptions.block16Style()is set, it overrides the scale mode and renders one terminal cell per bitmap pixel. Pixels or rendered cells outside the buffer are ignored.- Parameters:
bitmap – The bitmap to draw.
pos – The position of the top left corner.
options – Bitmap drawing options.
animationCycle – Animation cycle for color animations.
-
void drawBitmap(const Bitmap &bitmap, block::Rectangle rect, geometry::Alignment alignment = geometry::Alignment::TopLeft, const BitmapDrawOptions &options = BitmapDrawOptions::defaultOptions(), std::size_t animationCycle = 0) noexcept
Draw a bitmap into the given rectangle.
The rendered bitmap is aligned inside
rect. If it is larger thanrect, it is cropped according to the alignment.Note
For half-block drawing mode, alignment and cropping happen at rendered cell boundaries, not per pixel.
- Parameters:
bitmap – The bitmap to draw.
rect – The rectangle to draw the bitmap into.
alignment – geometry::Alignment of the bitmap within the rectangle.
options – Bitmap drawing options.
animationCycle – Animation cycle for color animations.
-
void drawBuffer(const ReadableBuffer &buffer, block::Position targetPos = block::Position{})
Draw the contents of another buffer into this one.
Resulting positions outside the target rectangle are clipped.
- Parameters:
buffer – The buffer to draw.
targetPos – The target position where to draw the top-left corner of the buffer.
- Throws:
err::ParameterError – if
bufferis this buffer.
-
void drawBuffer(const ReadableBuffer &buffer, block::Rectangle targetRect, geometry::Alignment alignment = geometry::Alignment::TopLeft)
Draw the contents of another buffer into this one.
Resulting positions outside the target rectangle are clipped.
- Parameters:
buffer – The buffer to draw.
targetRect – The target rectangle where to draw the buffer. Clips
bufferif larger.alignment – The alignment of the buffer within the target rectangle.
- Throws:
err::ParameterError – if
bufferis this buffer.
-
virtual void drawBuffer(const ReadableBuffer &buffer, const BufferDrawOptions &options)
Draw the contents of another buffer into this one.
- Parameters:
buffer – The buffer to draw.
options – The options for drawing the buffer.
- Throws:
err::ParameterError – if
bufferis this buffer.
Public Static Functions
-
static auto blockTextHeightForWidth(const BlockString &text, block::Coordinate width, const BlockTextOptions &options) noexcept -> block::Coordinate
Calculate the height required to render wrapped text for a given rectangle width.
The given width is the full target rectangle width, including margins configured in
options.- Parameters:
text – The text to measure.
width – The available rectangle width in terminal cells.
options – The text options used for paragraph layout.
- Returns:
The required rectangle height in terminal cells.
-
virtual void resize(block::Size newSize) = 0
-
class WriteClippedBuffer : public erbsland::cterm::WriteClippedBufferBase
A write-clipped buffer that owns a shared pointer to the wrapped buffer.
Public Functions
-
WriteClippedBuffer() = default
Create an empty write-clipped buffer.
-
inline explicit WriteClippedBuffer(block::Size size) noexcept
Create an empty write-clipped buffer with a given visible size.
- Parameters:
size – The visible source size.
-
inline WriteClippedBuffer(WritableBufferPtr content, block::Size size) noexcept
Create a write-clipped buffer with the given content and visible size.
- Parameters:
content – The wrapped writable buffer.
size – The visible source size.
-
inline WriteClippedBuffer(WritableBufferPtr content, block::Rectangle targetRect) noexcept
Create a write-clipped buffer with the given content and target rectangle.
- Parameters:
content – The wrapped writable buffer.
targetRect – The target rectangle in the wrapped buffer.
-
inline WriteClippedBuffer(WritableBufferPtr content, block::Position sourceOffset, block::Rectangle targetRect) noexcept
Create a write-clipped buffer with the given content, source offset, and target rectangle.
- Parameters:
content – The wrapped writable buffer.
sourceOffset – The top-left source coordinate exposed by this wrapper.
targetRect – The target rectangle in the wrapped buffer.
-
inline virtual const Block &get(block::Position pos) const noexcept override
Read a block from the wrapped buffer.
- Parameters:
pos – The source position.
- Returns:
The wrapped block, or a space if the translated target position is outside the wrapped buffer.
-
inline virtual void set(block::Position pos, const Block &block) noexcept override
Write a block into the wrapped buffer.
- Parameters:
pos – The source coordinates.
block – The block to write.
-
inline const WritableBufferPtr &content() const noexcept
Access the wrapped writable buffer.
- Returns:
The wrapped writable buffer pointer.
-
inline void setContent(WritableBufferPtr content) noexcept
Replace the wrapped writable buffer.
- Parameters:
content – The new wrapped writable buffer pointer.
-
inline virtual void resize(block::Size newSize) final
Resize the visible source rectangle.
This only changes the wrapper target size. It never resizes the wrapped buffer.
- Parameters:
newSize – The new visible size.
-
inline virtual void resize(block::Size newSize, BufferResizeMode mode, Block fillChar) final
Resize the visible source rectangle.
The resize mode and fill character are ignored because the wrapped buffer is never resized by this wrapper.
- Parameters:
newSize – The new visible size.
mode – Ignored.
fillChar – Ignored.
-
inline virtual void set(block::Position pos, const Block &block, const BlockCombinationStylePtr &combinationStyle) noexcept final
Write a block at the given source position using a combination style.
- Parameters:
pos – The source coordinates.
block – The block value to store.
combinationStyle – The combination style for overwriting existing characters.
-
WriteClippedBuffer() = default
-
class WriteClippedBufferBase : public erbsland::cterm::WritableBuffer
The shared base for writable buffer clipping wrappers.
A write-clipped buffer exposes a source-coordinate rectangle and maps accepted operations into a target rectangle of another writable buffer. Positions outside the source rectangle are ignored for writes, while reads are translated into the wrapped buffer whenever the translated target position exists.
Subclassed by erbsland::cterm::WriteClippedBuffer, erbsland::cterm::WriteClippedBufferRef
Public Functions
-
WriteClippedBufferBase() = default
Create an empty write-clipped buffer.
-
inline WriteClippedBufferBase(block::Position sourceOffset, block::Rectangle targetRect) noexcept
Create a write-clipped buffer for the given source offset and target rectangle.
- Parameters:
sourceOffset – The top-left source coordinate exposed by this wrapper.
targetRect – The rectangle where accepted operations land in the wrapped buffer.
-
inline virtual block::Size size() const noexcept final
Get the visible source size.
- Returns:
The size of the target rectangle.
-
inline virtual block::Rectangle rect() const noexcept final
Get the visible source rectangle.
- Returns:
The source rectangle exposed by this wrapper.
-
inline virtual WritableBufferPtr clone() const final
Create a zero-based writable copy of the visible clipped content.
- Returns:
A standalone buffer containing the visible clipped content.
-
inline virtual void resize(block::Size newSize) final
Resize the visible source rectangle.
This only changes the wrapper target size. It never resizes the wrapped buffer.
- Parameters:
newSize – The new visible size.
-
inline virtual void resize(block::Size newSize, BufferResizeMode mode, Block fillChar) final
Resize the visible source rectangle.
The resize mode and fill character are ignored because the wrapped buffer is never resized by this wrapper.
- Parameters:
newSize – The new visible size.
mode – Ignored.
fillChar – Ignored.
-
inline virtual void set(block::Position pos, const Block &block, const BlockCombinationStylePtr &combinationStyle) noexcept final
Write a block at the given source position using a combination style.
- Parameters:
pos – The source coordinates.
block – The block value to store.
combinationStyle – The combination style for overwriting existing characters.
-
inline const block::Position &sourceOffset() const noexcept
Get the top-left source coordinate exposed by this wrapper.
- Returns:
The source offset.
-
inline void setSourceOffset(block::Position sourceOffset) noexcept
Set the top-left source coordinate exposed by this wrapper.
- Parameters:
sourceOffset – The new source offset.
-
inline const block::Rectangle &targetRect() const noexcept
Get the target rectangle in the wrapped buffer.
- Returns:
The target rectangle.
-
inline void setTargetRect(block::Rectangle targetRect) noexcept
Set the target rectangle in the wrapped buffer.
- Parameters:
targetRect – The new target rectangle.
-
inline block::Rectangle sourceRect() const noexcept
Get the visible source rectangle.
- Returns:
The rectangle in source coordinates that maps to the target rectangle.
-
void drawBitmap(const Bitmap &bitmap, block::Position pos, const BitmapDrawOptions &options = BitmapDrawOptions::defaultOptions(), std::size_t animationCycle = 0) noexcept
Draw a bitmap at a given position.
The bitmap is rendered according to
options.scaleMode(). Ifoptions.block16Style()is set, it overrides the scale mode and renders one terminal cell per bitmap pixel. Pixels or rendered cells outside the buffer are ignored.- Parameters:
bitmap – The bitmap to draw.
pos – The position of the top left corner.
options – Bitmap drawing options.
animationCycle – Animation cycle for color animations.
-
void drawBitmap(const Bitmap &bitmap, block::Rectangle rect, geometry::Alignment alignment = geometry::Alignment::TopLeft, const BitmapDrawOptions &options = BitmapDrawOptions::defaultOptions(), std::size_t animationCycle = 0) noexcept
Draw a bitmap into the given rectangle.
The rendered bitmap is aligned inside
rect. If it is larger thanrect, it is cropped according to the alignment.Note
For half-block drawing mode, alignment and cropping happen at rendered cell boundaries, not per pixel.
- Parameters:
bitmap – The bitmap to draw.
rect – The rectangle to draw the bitmap into.
alignment – geometry::Alignment of the bitmap within the rectangle.
options – Bitmap drawing options.
animationCycle – Animation cycle for color animations.
-
virtual void drawBlockText(block::Position pos, const BlockString &str)
Draw a text without warping from the given position.
A newline breaks to the next line, starting at
pos.x. Characters outside this buffer are cut off.- Parameters:
pos – The start position (top-left corner).
str – The text to draw on this buffer.
-
void drawBlockText(const BlockText &text, std::size_t animationCycle = 0)
If fg or bg is set to
Inherited, the current color from the buffer is used.Draw simple text into a rectangle. If fg or bg is set to
Inherited, the current color from the buffer is used.- Parameters:
text – The text description.
animationCycle – Animation cycle for animated text.
-
void drawBlockText(const text::String &text, block::Rectangle rect, geometry::Alignment alignment = geometry::Alignment::TopLeft, BlockStyle style = {}, std::size_t animationCycle = 0)
Draw simple text into a rectangle.
If fg or bg is set to
Inherited, the current color from the buffer is used.- Parameters:
text – The text to render.
rect – The target rectangle.
alignment – The alignment inside the rectangle.
style – The base text style.
animationCycle – Animation cycle for animated text. Invalid UTF-8 bytes are replaced with the Unicode replacement character.
-
void drawBlockText(const text::U32String &text, block::Rectangle rect, geometry::Alignment alignment = geometry::Alignment::TopLeft, BlockStyle style = {}, std::size_t animationCycle = 0)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
void drawBlockText(const BlockString &text, block::Rectangle rect, geometry::Alignment alignment = geometry::Alignment::TopLeft, BlockStyle style = {}, std::size_t animationCycle = 0)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
void drawBlockText(const BlockString &text, block::Rectangle rect, const BlockTextOptions &options, std::size_t animationCycle = 0)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
virtual void fill(const Block &fillBlock) noexcept
Fill/clear the buffer with the given character.
- Parameters:
fillBlock – The block to use to fill the buffer.
-
void fill(block::Rectangle rect, const Block &fillBlock, const BlockCombinationStylePtr &combinationStyle = {}) noexcept
Fill the given rectangle.
Positions outside the buffer are ignored.
- Parameters:
rect – The rectangle to be filled.
fillBlock – The block for filling.
combinationStyle – The combination style for overwriting existing characters.
-
void fill(block::Rectangle rect, const Tile9StylePtr &style, Color baseColor = {}, const BlockCombinationStylePtr &combinationStyle = {}) noexcept
Fill the given rectangle using a repeating 9-tile style.
Positions outside the buffer are ignored.
- Parameters:
rect – The rectangle to be filled.
style – The tile style to repeat across the rectangle.
baseColor – The base color underneath the tile style.
combinationStyle – The combination style for overwriting existing characters.
-
void fill(block::Rectangle rect, const Tile9StylePtr &style, BlockStyle baseStyle, const BlockCombinationStylePtr &combinationStyle = {}) noexcept
Fill the given rectangle using a repeating 9-tile style.
Positions outside the buffer are ignored.
- Parameters:
rect – The rectangle to be filled.
style – The tile style to repeat across the rectangle.
baseStyle – The base style underneath the tile style.
combinationStyle – The combination style for overwriting existing characters.
-
virtual void resize(block::Size newSize) = 0
Resize this buffer in a memory-efficient way.
The content of the resized buffer is undefined and must be filled with new content.
- Parameters:
newSize – The new size for the buffer.
-
virtual void resize(block::Size size, BufferResizeMode mode, Block fillChar)
Resize this buffer and optionally preserve visible content.
The default implementation calls
resize(block::Size)forBufferResizeMode::Fast. ForBufferResizeMode::PreserveContent, it clones the current buffer, resizes it usingresize(block::Size), and restores the visible content withsetFrom(). Implementations can override this when they provide a faster preserve-content path.- Parameters:
size – The new size for the buffer.
mode – How existing content should be handled during resizing.
fillChar – The character to fill newly visible cells with in preserve-content mode.
-
virtual void set(block::Position pos, const Block &block) noexcept = 0
Write a block at the given position.
Note
Writes outside the buffer are ignored.
- Parameters:
pos – The coordinates within the buffer.
block – The block value to store.
-
virtual void set(block::Position pos, const Block &block, const BlockCombinationStylePtr &combinationStyle) noexcept
Write a block at the given position using a combination style.
Note
Writes outside the buffer are ignored.
- Parameters:
pos – The coordinates within the buffer.
block – The block value to store.
combinationStyle – The combination style for overwriting existing characters.
-
virtual void set(block::Position pos, const BlockString &str) noexcept
Write a string at the given position.
NL jumps to the next row. Other control and zero-width characters are ignored. Color (even inherited) overwrites the existing characters. Use
drawBlockText(pos, text)for a color overlay.- Parameters:
pos – The coordinates within the buffer.
str – The string to write.
-
WriteClippedBufferBase() = default
-
class WriteClippedBufferRef : public erbsland::cterm::WriteClippedBufferBase
A write-clipped buffer that stores a reference to the wrapped buffer.
This wrapper is intended as a lightweight temporary object on the stack.
Public Functions
-
inline WriteClippedBufferRef(WritableBuffer &buffer, block::Size size) noexcept
Create a write-clipped buffer reference with the given visible size.
- Parameters:
buffer – The wrapped writable buffer.
size – The visible source size.
-
inline WriteClippedBufferRef(WritableBuffer &buffer, block::Rectangle targetRect) noexcept
Create a write-clipped buffer reference with the given target rectangle.
- Parameters:
buffer – The wrapped writable buffer.
targetRect – The target rectangle in the wrapped buffer.
-
inline WriteClippedBufferRef(WritableBuffer &buffer, block::Position sourceOffset, block::Rectangle targetRect) noexcept
Create a write-clipped buffer reference with the given source offset and target rectangle.
- Parameters:
buffer – The wrapped writable buffer.
sourceOffset – The top-left source coordinate exposed by this wrapper.
targetRect – The target rectangle in the wrapped buffer.
-
inline virtual const Block &get(block::Position pos) const noexcept override
Read a block from the wrapped buffer.
- Parameters:
pos – The source position.
- Returns:
The wrapped block, or a space if the translated target position is outside the wrapped buffer.
-
inline virtual void set(block::Position pos, const Block &block) noexcept override
Write a block into the wrapped buffer.
- Parameters:
pos – The source position.
block – The block to write.
-
void drawBitmap(const Bitmap &bitmap, block::Position pos, const BitmapDrawOptions &options = BitmapDrawOptions::defaultOptions(), std::size_t animationCycle = 0) noexcept
Draw a bitmap at a given position.
The bitmap is rendered according to
options.scaleMode(). Ifoptions.block16Style()is set, it overrides the scale mode and renders one terminal cell per bitmap pixel. Pixels or rendered cells outside the buffer are ignored.- Parameters:
bitmap – The bitmap to draw.
pos – The position of the top left corner.
options – Bitmap drawing options.
animationCycle – Animation cycle for color animations.
-
void drawBitmap(const Bitmap &bitmap, block::Rectangle rect, geometry::Alignment alignment = geometry::Alignment::TopLeft, const BitmapDrawOptions &options = BitmapDrawOptions::defaultOptions(), std::size_t animationCycle = 0) noexcept
Draw a bitmap into the given rectangle.
The rendered bitmap is aligned inside
rect. If it is larger thanrect, it is cropped according to the alignment.Note
For half-block drawing mode, alignment and cropping happen at rendered cell boundaries, not per pixel.
- Parameters:
bitmap – The bitmap to draw.
rect – The rectangle to draw the bitmap into.
alignment – geometry::Alignment of the bitmap within the rectangle.
options – Bitmap drawing options.
animationCycle – Animation cycle for color animations.
-
virtual void drawBlockText(block::Position pos, const BlockString &str)
Draw a text without warping from the given position.
A newline breaks to the next line, starting at
pos.x. Characters outside this buffer are cut off.- Parameters:
pos – The start position (top-left corner).
str – The text to draw on this buffer.
-
void drawBlockText(const BlockText &text, std::size_t animationCycle = 0)
If fg or bg is set to
Inherited, the current color from the buffer is used.Draw simple text into a rectangle. If fg or bg is set to
Inherited, the current color from the buffer is used.- Parameters:
text – The text description.
animationCycle – Animation cycle for animated text.
-
void drawBlockText(const text::String &text, block::Rectangle rect, geometry::Alignment alignment = geometry::Alignment::TopLeft, BlockStyle style = {}, std::size_t animationCycle = 0)
Draw simple text into a rectangle.
If fg or bg is set to
Inherited, the current color from the buffer is used.- Parameters:
text – The text to render.
rect – The target rectangle.
alignment – The alignment inside the rectangle.
style – The base text style.
animationCycle – Animation cycle for animated text. Invalid UTF-8 bytes are replaced with the Unicode replacement character.
-
void drawBlockText(const text::U32String &text, block::Rectangle rect, geometry::Alignment alignment = geometry::Alignment::TopLeft, BlockStyle style = {}, std::size_t animationCycle = 0)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
void drawBlockText(const BlockString &text, block::Rectangle rect, geometry::Alignment alignment = geometry::Alignment::TopLeft, BlockStyle style = {}, std::size_t animationCycle = 0)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
void drawBlockText(const BlockString &text, block::Rectangle rect, const BlockTextOptions &options, std::size_t animationCycle = 0)
This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
-
virtual void fill(const Block &fillBlock) noexcept
Fill/clear the buffer with the given character.
- Parameters:
fillBlock – The block to use to fill the buffer.
-
void fill(block::Rectangle rect, const Block &fillBlock, const BlockCombinationStylePtr &combinationStyle = {}) noexcept
Fill the given rectangle.
Positions outside the buffer are ignored.
- Parameters:
rect – The rectangle to be filled.
fillBlock – The block for filling.
combinationStyle – The combination style for overwriting existing characters.
-
void fill(block::Rectangle rect, const Tile9StylePtr &style, Color baseColor = {}, const BlockCombinationStylePtr &combinationStyle = {}) noexcept
Fill the given rectangle using a repeating 9-tile style.
Positions outside the buffer are ignored.
- Parameters:
rect – The rectangle to be filled.
style – The tile style to repeat across the rectangle.
baseColor – The base color underneath the tile style.
combinationStyle – The combination style for overwriting existing characters.
-
void fill(block::Rectangle rect, const Tile9StylePtr &style, BlockStyle baseStyle, const BlockCombinationStylePtr &combinationStyle = {}) noexcept
Fill the given rectangle using a repeating 9-tile style.
Positions outside the buffer are ignored.
- Parameters:
rect – The rectangle to be filled.
style – The tile style to repeat across the rectangle.
baseStyle – The base style underneath the tile style.
combinationStyle – The combination style for overwriting existing characters.
-
inline virtual void resize(block::Size newSize) final
Resize the visible source rectangle.
This only changes the wrapper target size. It never resizes the wrapped buffer.
- Parameters:
newSize – The new visible size.
-
inline virtual void resize(block::Size newSize, BufferResizeMode mode, Block fillChar) final
Resize the visible source rectangle.
The resize mode and fill character are ignored because the wrapped buffer is never resized by this wrapper.
- Parameters:
newSize – The new visible size.
mode – Ignored.
fillChar – Ignored.
-
virtual void resize(block::Size newSize) = 0
Resize this buffer in a memory-efficient way.
The content of the resized buffer is undefined and must be filled with new content.
- Parameters:
newSize – The new size for the buffer.
-
virtual void resize(block::Size size, BufferResizeMode mode, Block fillChar)
Resize this buffer and optionally preserve visible content.
The default implementation calls
resize(block::Size)forBufferResizeMode::Fast. ForBufferResizeMode::PreserveContent, it clones the current buffer, resizes it usingresize(block::Size), and restores the visible content withsetFrom(). Implementations can override this when they provide a faster preserve-content path.- Parameters:
size – The new size for the buffer.
mode – How existing content should be handled during resizing.
fillChar – The character to fill newly visible cells with in preserve-content mode.
-
inline virtual void set(block::Position pos, const Block &block, const BlockCombinationStylePtr &combinationStyle) noexcept final
Write a block at the given source position using a combination style.
- Parameters:
pos – The source coordinates.
block – The block value to store.
combinationStyle – The combination style for overwriting existing characters.
-
virtual void set(block::Position pos, const Block &block) noexcept = 0
Write a block at the given position.
Note
Writes outside the buffer are ignored.
- Parameters:
pos – The coordinates within the buffer.
block – The block value to store.
-
virtual void set(block::Position pos, const Block &block, const BlockCombinationStylePtr &combinationStyle) noexcept
Write a block at the given position using a combination style.
Note
Writes outside the buffer are ignored.
- Parameters:
pos – The coordinates within the buffer.
block – The block value to store.
combinationStyle – The combination style for overwriting existing characters.
-
virtual void set(block::Position pos, const BlockString &str) noexcept
Write a string at the given position.
NL jumps to the next row. Other control and zero-width characters are ignored. Color (even inherited) overwrites the existing characters. Use
drawBlockText(pos, text)for a color overlay.- Parameters:
pos – The coordinates within the buffer.
str – The string to write.
-
inline WriteClippedBufferRef(WritableBuffer &buffer, block::Size size) noexcept