ZenitUI
Retained-mode C++20 UI framework
Loading...
Searching...
No Matches
TextEngine.hpp
Go to the documentation of this file.
1#pragma once
2
13
14#include "Common.hpp"
15#include "CoreTypes.hpp"
16#include "UIEnums.hpp"
17#include "Style.hpp"
18
19#include <cstddef>
20#include <cstdint>
21#include <memory>
22#include <span>
23#include <string>
24#include <string_view>
25#include <vector>
26
27namespace ZenitUI
28{
32
33 class IRenderer;
34
40 {
41 float ascent{0.0f};
42 float descent{0.0f};
43 float lineHeight{0.0f};
44 };
45
59
65 {
66 float maxWidth{0.0f};
67 bool wrap{false};
68 bool ellipsis{false};
69 int maxLines{0};
70 bool preserveSpaces{false};
71 std::string ellipsisText{"..."};
72 };
73
79 {
80 uint32_t fontId{0};
81 uint32_t glyphId{0};
82 uint32_t cluster{0};
83 uint32_t clusterEnd{0};
84 float x{0.0f};
85 float xAdvance{0.0f};
86 float xOffset{0.0f};
87 float yOffset{0.0f};
88 bool rtl{false};
89 };
90
95 struct TextLine
96 {
97 size_t byteStart{0};
98 size_t byteEnd{0};
99 float width{0.0f};
100 float height{0.0f};
101 float yOffset{0.0f};
102 float baselineOffset{0.0f};
103 bool hardBreak{true};
104 bool ellipsized{false};
105 bool isRtl{false};
106 std::vector<ShapedGlyph> glyphs;
107 };
108
114 {
115 std::vector<TextLine> lines;
116 Vec2 size{0.0f, 0.0f};
117 FontMetrics metrics{};
118 std::string ellipsizedText;
119 bool truncated{false};
120 bool synthetic{false};
121 TextDirection resolvedDirection{TextDirection::LTR};
122 };
123
129 {
130 size_t pageCount{0};
131 size_t cachedGlyphs{0};
132 size_t layoutCacheSize{0};
133 uint64_t layoutCacheHits{0};
134 uint64_t layoutCacheMisses{0};
135 };
136
141 class TextEngine
142 {
143 public:
144 TextEngine();
145 ~TextEngine();
146
147 TextEngine(const TextEngine &) = delete;
148 TextEngine &operator=(const TextEngine &) = delete;
149 TextEngine(TextEngine &&) noexcept;
150 TextEngine &operator=(TextEngine &&) noexcept;
151
152 // ---- Font lifecycle ----
153
155 FontHandle loadFont(std::string_view name, std::string_view path);
156
158 FontHandle loadFontFromMemory(std::string_view name, const void *data, size_t size);
159
161 void unloadFont(std::string_view name);
162
164 FontHandle getFont(std::string_view name) const;
165
167 FontHandle resolveFont(const FontStack &stack, FontHandle fallback = {}) const;
168
171
174
176 FontMetrics fontMetrics(FontHandle font, float fontSize) const;
177
178 // ---- Configuration & cache control ----
179
181 void setDpiScale(float scale);
182 float dpiScale() const;
183 void setTargetDpiScale(float scale);
184
186 void setFallbackCharWidth(float width);
187 float fallbackCharWidth() const;
188
190 void setLayoutCacheCapacity(size_t maxEntries);
191
193 void clearAtlas(IRenderer &renderer);
194
197
200
202 using SyntheticDrawCallback = std::function<void(std::string_view)>;
203 void setSyntheticDrawCallback(SyntheticDrawCallback cb);
204
205 // ---- Measurement & Layout ----
206
208 TextLayout layout(std::string_view text,
209 const TextMeasureSpec &spec,
210 const TextLayoutOptions &options = {}) const;
211
213 std::shared_ptr<const TextLayout> layoutCached(std::string_view text,
214 const TextMeasureSpec &spec,
215 const TextLayoutOptions &options = {});
216
218 Vec2 measureText(std::string_view text, const TextMeasureSpec &spec) const;
219
221 static TextDirection detectDirection(std::string_view text);
222
223 // ---- Hit-testing, Caret & Selection ----
224
233 static size_t hitTestLine(std::string_view fullText,
234 const TextLine &line,
235 float localX,
236 bool clampSoftBreak = false);
237
239 static size_t hitTestPoint(std::string_view fullText,
240 const TextLayout &layout,
241 Vec2 localPos,
242 Align textAlign = Align::Start,
243 float boxWidth = 0.0f,
244 bool clampSoftBreak = true);
245
247 static size_t lineIndexForByte(const TextLayout &layout, size_t byteIndex);
248
250 static float caretXOnLine(const TextLine &line, size_t byteIndex);
251
254 size_t byteIndex,
255 float caretWidth = 2.0f,
256 Align textAlign = Align::Start,
257 float boxWidth = 0.0f);
258
260 static std::vector<Rect> selectionRects(const TextLayout &layout,
261 size_t selStart,
262 size_t selEnd,
263 Align textAlign = Align::Start,
264 float boxWidth = 0.0f);
265
266 // ---- Batched Rendering ----
267
281 void draw(IRenderer &renderer,
282 const TextLayout &layout,
283 Rect bounds,
284 Color color,
285 const TextMeasureSpec &spec,
286 Align align = Align::Start,
287 std::string_view fallbackText = {},
288 const Rect *cullRect = nullptr);
289
290 private:
291 struct Impl;
292 std::unique_ptr<Impl> impl_;
293 };
294
296} // namespace ZenitUI
Centralized standard library includes used throughout ZenitUI.
Small value types shared by the layout, rendering and input layers.
The Style / ComputedStyle pair and all style-related value types.
Small enumerations describing layout strategy and interaction state.
Ordered list of font family names to try, first match wins.
Definition CoreTypes.hpp:194
Abstract 2D rendering backend.
Definition UIContext.hpp:106
void setDefaultFont(FontHandle h)
Set the fallback font used when a node specifies no font or an unknown font name.
std::shared_ptr< const TextLayout > layoutCached(std::string_view text, const TextMeasureSpec &spec, const TextLayoutOptions &options={})
Cached variant of layout() backed by the per-engine LRU cache.
static float caretXOnLine(const TextLine &line, size_t byteIndex)
Return the line-local X coordinate of byteIndex on line.
std::function< void(std::string_view)> SyntheticDrawCallback
Optional test hook invoked per visible line when drawing in synthetic fallback mode.
Definition TextEngine.hpp:202
void setLayoutCacheCapacity(size_t maxEntries)
Configure the maximum number of entries kept in the layout LRU cache.
TextLayout layout(std::string_view text, const TextMeasureSpec &spec, const TextLayoutOptions &options={}) const
Shape and lay out text according to spec and options (uncached).
FontHandle loadFontFromMemory(std::string_view name, const void *data, size_t size)
Load a TTF/OTF font from an in-memory buffer under logical name (copies bytes).
void clearLayoutCache()
Clear the cached TextLayout entries without touching GPU atlas textures.
static size_t hitTestLine(std::string_view fullText, const TextLine &line, float localX, bool clampSoftBreak=false)
Map a line-local X coordinate to the closest UTF-8 cluster byte offset.
static size_t lineIndexForByte(const TextLayout &layout, size_t byteIndex)
Return the line index containing byteIndex.
void clearAtlas(IRenderer &renderer)
Destroy all GPU atlas pages on renderer and clear the glyph cache.
static size_t hitTestPoint(std::string_view fullText, const TextLayout &layout, Vec2 localPos, Align textAlign=Align::Start, float boxWidth=0.0f, bool clampSoftBreak=true)
Map a layout-local (x, y) point to the closest UTF-8 cluster byte offset.
FontHandle loadFont(std::string_view name, std::string_view path)
Load a TTF/OTF font file from disk under logical name.
Vec2 measureText(std::string_view text, const TextMeasureSpec &spec) const
Measure a single line (no wrapping, splits on \n) and return its {width, height}.
static std::vector< Rect > selectionRects(const TextLayout &layout, size_t selStart, size_t selEnd, Align textAlign=Align::Start, float boxWidth=0.0f)
Compute selection highlight rectangles in layout-local coordinates for [selStart, selEnd).
static Rect caretRect(const TextLayout &layout, size_t byteIndex, float caretWidth=2.0f, Align textAlign=Align::Start, float boxWidth=0.0f)
Compute the caret rectangle in layout-local coordinates.
void unloadFont(std::string_view name)
Unload a font by logical name and invalidate layout caches.
void setDpiScale(float scale)
Update the active logical-to-physical DPI scale used when rasterizing glyphs.
FontHandle defaultFont() const
Return the current default font handle ({0} if none).
TextAtlasStats stats() const
Return current atlas and layout-cache diagnostics.
static TextDirection detectDirection(std::string_view text)
Detect the strong base direction of text via UAX #9 (RTL or LTR).
void setFallbackCharWidth(float width)
Set the fixed character advance used when no TTF/OTF font is loaded (headless fallback).
void draw(IRenderer &renderer, const TextLayout &layout, Rect bounds, Color color, const TextMeasureSpec &spec, Align align=Align::Start, std::string_view fallbackText={}, const Rect *cullRect=nullptr)
Rasterize any missing glyphs into the atlas and emit batched drawGeometry calls.
FontHandle resolveFont(const FontStack &stack, FontHandle fallback={}) const
Resolve the first loaded font matching stack; falls back to the default font if set.
FontMetrics fontMetrics(FontHandle font, float fontSize) const
Query scaled vertical metrics for font at logical fontSize.
FontHandle getFont(std::string_view name) const
Look up a loaded font by logical name; returns {0} if not found.
Align
Cross-axis alignment for flex items and content.
Definition CoreTypes.hpp:452
TextDirection
Inline / layout writing direction for Bidi text and RTL layout mirroring (ยง6.2).
Definition UIEnums.hpp:83
@ Start
Pack at the leading edge.
Definition CoreTypes.hpp:454
@ Auto
Infer paragraph direction from first strong Bidi character (fallback LTR).
Definition UIEnums.hpp:84
@ LTR
Explicit left-to-right direction.
Definition UIEnums.hpp:85
8-bit-per-channel RGBA color, non-premultiplied.
Definition CoreTypes.hpp:78
Opaque handle to a font loaded by TextEngine.
Definition CoreTypes.hpp:135
Scaled vertical metrics for a font at a given logical pixel size.
Definition TextEngine.hpp:40
float ascent
Distance from baseline to top of ascenders (positive, logical px).
Definition TextEngine.hpp:41
float descent
Distance from baseline to bottom of descenders (positive, logical px).
Definition TextEngine.hpp:42
float lineHeight
Recommended line advance (logical px).
Definition TextEngine.hpp:43
Axis-aligned rectangle in screen coordinates.
Definition CoreTypes.hpp:46
Single shaped glyph positioned along a laid-out line.
Definition TextEngine.hpp:79
float xAdvance
Logical advance including tracking on cluster boundaries.
Definition TextEngine.hpp:85
uint32_t clusterEnd
Exclusive byte offset of this glyph's cluster in the UTF-8 string.
Definition TextEngine.hpp:83
uint32_t cluster
Inclusive byte offset in the original UTF-8 input string.
Definition TextEngine.hpp:82
float x
Pen X offset from the start of the line (logical px).
Definition TextEngine.hpp:84
bool rtl
true if this glyph belongs to a right-to-left Bidi run.
Definition TextEngine.hpp:88
float xOffset
HarfBuzz horizontal glyph offset (logical px).
Definition TextEngine.hpp:86
uint32_t glyphId
Font-specific glyph index (GID).
Definition TextEngine.hpp:81
uint32_t fontId
FontHandle::id that owns glyphId (0 in synthetic fallback mode).
Definition TextEngine.hpp:80
float yOffset
HarfBuzz vertical glyph offset (positive upward, logical px).
Definition TextEngine.hpp:87
Diagnostic counters for the dynamic FreeType glyph atlas.
Definition TextEngine.hpp:129
Wrapping, truncation, and whitespace options for TextEngine::layout.
Definition TextEngine.hpp:65
bool wrap
Enable soft word/cluster wrapping at maxWidth.
Definition TextEngine.hpp:67
bool ellipsis
Append ellipsisText when overflowing maxWidth or maxLines.
Definition TextEngine.hpp:68
float maxWidth
Wrapping / ellipsis width in logical px (<= 0 = unbounded).
Definition TextEngine.hpp:66
int maxLines
Maximum number of visual lines (<= 0 = unlimited).
Definition TextEngine.hpp:69
bool preserveSpaces
Keep spaces contiguous across soft breaks (for editable fields).
Definition TextEngine.hpp:70
std::string ellipsisText
Suffix used when truncating overflowing lines.
Definition TextEngine.hpp:71
Complete laid-out text block ready for sizing, hit-testing, and rendering.
Definition TextEngine.hpp:114
std::string ellipsizedText
Populated with the truncated last line when truncated is true.
Definition TextEngine.hpp:118
bool synthetic
true when measured via synthetic fallback (no loaded fonts).
Definition TextEngine.hpp:120
One visual line produced by TextEngine::layout.
Definition TextEngine.hpp:96
size_t byteEnd
Exclusive UTF-8 byte end in original text.
Definition TextEngine.hpp:98
float yOffset
Top Y offset from the start of the text block.
Definition TextEngine.hpp:101
float width
Measured logical width of this line.
Definition TextEngine.hpp:99
bool hardBreak
true if terminated by \n or end-of-string; false on soft wrap.
Definition TextEngine.hpp:103
float height
Logical height of this line box.
Definition TextEngine.hpp:100
float baselineOffset
Distance from yOffset down to the typographic baseline.
Definition TextEngine.hpp:102
size_t byteStart
Inclusive UTF-8 byte start in original text.
Definition TextEngine.hpp:97
bool ellipsized
true if this line was truncated with ellipsisText.
Definition TextEngine.hpp:104
Typographic parameters governing shaping and measurement.
Definition TextEngine.hpp:51
FontHandle font
Explicit primary font handle (optional when fontStack is set).
Definition TextEngine.hpp:52
FontStack fontStack
Ordered CSS-style font fallback names.
Definition TextEngine.hpp:53
float letterSpacing
Additional horizontal tracking between grapheme clusters (logical px).
Definition TextEngine.hpp:55
TextDirection direction
Base paragraph direction (Auto, LTR, RTL).
Definition TextEngine.hpp:57
float lineHeight
Explicit line height in logical px (<= 0 uses font's natural height).
Definition TextEngine.hpp:56
float fontSize
Logical font size in pixels.
Definition TextEngine.hpp:54
2D vector with component-wise arithmetic.
Definition CoreTypes.hpp:25