Skip to content
Development

Typography ​

mirui shapes text into positioned glyphs, then optionally places those glyphs on a registered vector path. The same Path and PathId types drive drawing, clipping, hit testing, and text baselines.

TextPath
recipes.rs107 lines
1020static WAVE_CREST: Path = path!(M 8 64 Q 60 18 112 64 Q 164 110 216 64);
1021static WAVE_VALLEY: Path = path!(M 8 50 Q 60 96 112 50 Q 164 4 216 50);
1022
1023#[model]
1024pub struct CurveRoute {
1025 crest: PathId,
1026 valley: PathId,
1027 #[observe]
1028 pub inverted: bool,
1029 #[observe]
1030 pub offset: i32,
1031}
1032
1033impl CurveRoute {
1034 pub fn new(crest: PathId, valley: PathId) -> Self {
1035 Self {
1036 crest,
1037 valley,
1038 inverted: false,
1039 offset: 4,
1040 }
1041 }
1042}
1043
1044#[model]
1045impl CurveRoute {
1046 #[observe]
1047 pub fn placement(&self) -> TextPath {
1048 let path = if self.inverted {
1049 self.valley
1050 } else {
1051 self.crest
1052 };
1053 TextPath::new(path).with_offset(Fixed::from_int(self.offset))
1054 }
1055
1056 pub fn flip(&mut self) {
1057 self.inverted = !self.inverted;
1058 }
1059
1060 pub fn advance(&mut self) {
1061 self.offset = (self.offset + 14) % 42;
1062 }
1063}
1064
1065#[compose]
1066fn curve_scene(route: model!(CurveRoute)) {
1067 ui! {
1068 Column (
1069 grow: 1.0,
1070 padding: Padding::all(16),
1071 row_gap: 10,
1072 text_color: ColorToken::OnSurface
1073 ) {
1074 Row (height: 30, column_gap: 6, align: AlignItems::Center) {
1075 Text (
1076 text: ${ format_args!("+{} px", route.offset()) },
1077 capacity: 16,
1078 grow: 1.0,
1079 min_width: 0,
1080 height: 22,
1081 font_size: 13,
1082 text_color: ColorToken::OnSurfaceVariant,
1083 paragraph: ParagraphStyle::label().with_align(TextAlign::Start)
1084 )
1085 Button (
1086 "Slide +14",
1087 width: 72,
1088 height: 28,
1089 font_size: 12,
1090 border_radius: 7,
1091 normal_color: ColorToken::SurfaceVariant,
1092 pressed_color: ColorToken::Outline,
1093 text_color: ColorToken::OnSurface
1094 ) on Tap { route.advance(); }
1095 Button (
1096 "Flip wave",
1097 width: 74,
1098 height: 28,
1099 font_size: 12,
1100 border_radius: 7,
1101 normal_color: ColorToken::Primary,
1102 pressed_color: ColorToken::Secondary,
1103 text_color: ColorToken::OnPrimary
1104 ) on Tap { route.flip(); }
1105 }
1106 View (
1107 grow: 1.0,
1108 bg_color: ColorToken::SurfaceVariant,
1109 border_radius: 12,
1110 clip_children: true
1111 ) {
1112 Text (
1113 "mirui rides the wave",
1114 path: ${ route.placement() },
1115 position: Position::Absolute,
1116 left: 6,
1117 top: 8,
1118 width: Dimension::percent(96),
1119 height: Dimension::percent(88),
1120 font_size: 14,
1121 text_color: ColorToken::Primary
1122 )
1123 }
1124 }
1125 };
1126}
Loading preview…

Tap Slide +18 to advance the leading offset along the Bézier curve, or tap Flip wave to switch the reactive TextPath between crest and valley paths.

Default font and providers ​

Font::default() opens the embedded ASCII MIRX face at 8 px. Its A1 atlas is borrowed from program storage. font_size scales both metrics and drawing. Characters outside ASCII use the face's question-mark glyph unless a font stack supplies coverage. Applications that require more characters can register another MIRX font through App::with_fonts.

font, font_stack, font_size, and text_color are inherited along the UI parent chain. Each field uses the nearest declaration. The root uses the default font stack, the selected font's native size, and ColorToken::OnSurface. Specify font_size: FontSize::Native to use the selected font's native size within a subtree that inherits a different size. Paragraph layout is supplied on each text widget. Custom paint callbacks read the effective values through paint.typography().

Every font uses FontProvider, including the embedded face. A custom provider is shared through the provider: Rc<dyn FontProvider> field of Font; cloning a font shares that provider. Software and accelerated renderers consume the same raster regions and coverage metadata. The software renderer reads exact-size A1 coverage directly and resamples scaled coverage.

Text box overflow ​

LF, CR and CRLF separate paragraph lines without requesting font coverage or glyphs. Leading, consecutive and trailing separators retain empty lines and their caret positions. Text, selection and clipboard offsets refer to the original UTF-8 bytes; CRLF has no caret between its two bytes. TextEditing keeps its single-line appearance and crosses a CRLF pair together during horizontal navigation and deletion.

Assign a finite width when text should wrap or show an ellipsis. Ellipsis also requires a font in the stack that maps U+2026. Explicitly sized axes clip ordinary Text to the transformed text box for both overflow policies; Auto and Content preserve glyph ink overhang within the ancestor clip. Path text uses its placed glyph geometry and ancestor clip because its ink can extend beyond the layout box.

TextOverflow::Ellipsis
1207#[model]
1208#[derive(Default)]
1209pub struct OverflowDemo {
1210 #[observe]
1211 pub wrap: bool,
1212}
1213
1214#[model]
1215impl OverflowDemo {
1216 pub fn toggle(&mut self) {
1217 self.wrap = !self.wrap;
1218 }
1219}
1220
1221#[compose]
1222fn typo_ellipsis_scene(mode: model!(OverflowDemo)) {
1223 ui! {
1224 Column (
1225 grow: 1.0,
1226 padding: Padding::all(18),
1227 justify: JustifyContent::SpaceBetween,
1228 text_color: ColorToken::OnSurface
1229 ) {
1230 Row (height: 32, align: AlignItems::Center) {
1231 Text (
1232 text: ${ if mode.wrap() { "Wrap · max_lines: 2" } else { "NoWrap · Ellipsis (1 line)" } },
1233 grow: 1.0,
1234 height: 20,
1235 font_size: 12,
1236 text_color: ColorToken::OnSurfaceVariant
1237 )
1238 Button (
1239 "Toggle wrap",
1240 width: 96,
1241 height: 30,
1242 font_size: 12,
1243 border_radius: 7,
1244 normal_color: ColorToken::Primary,
1245 pressed_color: ColorToken::Secondary,
1246 text_color: ColorToken::OnPrimary
1247 ) on Tap { mode.toggle(); }
1248 }
1249 View (
1250 height: 68,
1251 padding: Padding::all(14),
1252 bg_color: ColorToken::SurfaceVariant,
1253 border_radius: 10
1254 ) {
1255 Text (
1256 "A long status label that clips with an ellipsis or wraps across two lines when toggled.",
1257 width: Dimension::percent(100),
1258 height: 40,
1259 font_size: 14,
1260 paragraph: ${
1261 ParagraphStyle {
1262 wrap: if mode.wrap() { TextWrap::Word } else { TextWrap::NoWrap },
1263 max_lines: Some(if mode.wrap() { 2 } else { 1 }),
1264 overflow: TextOverflow::Ellipsis,
1265 ..ParagraphStyle::default()
1266 }
1267 }
1268 )
1269 }
1270 }
1271 };
1272}
Loading preview…

Click Toggle wrap to switch between single-line NoWrap with TextOverflow::Ellipsis and two-line TextWrap::Word.

Layout failure reporting ​

App::render() and App::render_dirty() return RenderError::TextLayout when text preparation fails, including TextInput content and placeholders. Drawing, scrolling, and framebuffer flush are skipped for that frame. App::last_text_layout_failure() identifies the text entity, preparation stage, and available capacity details; a successful layout clears the diagnostic.

TextEditing prepares its single-line layout after its final size is known. Glyphs and the cursor read that layout during painting; input edits, placeholder changes, font replacement through App::with_fonts, and cache resets prepare it again. Empty inputs keep the cursor at the start, and long content scrolls horizontally to keep the cursor visible.

Low-level callers use render_system::try_update_layout to receive layout failures and stop before drawing. collect_dirty_region and collect_dirty_regions also return Result with TextLayoutFailure; App::dirty_region() maps failures to RenderError::TextLayout. An empty successful query is distinct from a failed layout. A failed pass also records a TextLayoutFailure World resource and invalidates cached geometry for retry, but does not restore text-cache entries already retired during preparation.

App records painted bounds after successful full and partial renders. Low-level render loops call render_system::seed_prev_rects after drawing successfully and before further state changes; collecting damage does not record a frame as painted.

Bound dynamic content ​

capacity reserves UTF-8 content storage for a Text or Button label. A reactive expression can format directly into a stack buffer and copy a complete value into that storage without allocating during the content update:

rust
#[compose]
fn reading_label(reading: Signal<u16>) {
    ui! {
        Text(text: ${ format_args!("{:03}", reading.get()) }, capacity: 4)
    };
}

The capacity counts UTF-8 bytes, not characters. A value that exceeds it or fails to format leaves the previous valid content intact; the Text component records a TextContentError. If the first value fails, App::render() and App::render_dirty() return RenderError::TextContent before drawing or flushing. App::last_text_content_failure() identifies the entity and error, prioritizing labels without a valid first value. A later valid update clears that diagnostic. Runtime overflow after a valid value does not block rendering of the rest of the UI.

The bounded write covers storage and formatting performed by Text; an expression such as format!(...), .to_string(), or a cloned Signal<String> can allocate before the write. Use format_args! over borrowed or scalar values when the update itself must not allocate. Text shaping, layout, font caches, and backend resources have separate capacity requirements. Bounded content is a plain-text value; use the existing localized-text path when the label must follow locale changes.

Reserve bounded layout storage ​

App::with_text_layout_capacity prepares text-cache storage before the first layout pass. Set TextLayoutLimits first when the default byte budget is unsuitable. The returned error leaves the previous cache installed; calls after text layout has started return TextLayoutError::InUse. App::try_with_text_layout_limits can also change limits after reservation and before layout while preserving the declared capacity; an incompatible limit returns an error without replacing the cache. The existing fluent with_text_layout_limits reports that error by panicking rather than silently removing the bound.

rust
use mirui::text::{TextLayoutCapacity, WorkspaceCapacity};

app.with_text_layout_capacity(TextLayoutCapacity {
    layout_slots: 4,
    measurements: 4,
    lines: 16,
    runs: 32,
    glyphs: 64,
    carets: 64,
    workspace: WorkspaceCapacity {
        runs: 16,
        glyphs: 32,
        scratch_glyphs: 32,
        lines: 16,
    },
})?;

layout_slots covers retained layout handles and their generation storage. The line, run, glyph, and caret capacities cover all retained paragraphs plus one paragraph's temporary output; they are aggregate counts, unlike the per-paragraph limits in TextLayoutLimits. workspace bounds private shaping buffers. The reservation checks actual retained vector capacities and the workspace against TextLayoutLimits::cache_bytes. Later requests above the declared capacities fail explicitly instead of growing those buffers. Other renderer and font caches have separate storage.

A reusable UI module can declare its own module_text_capacity: TextLayoutCapacity with App::require_text_layout_capacity during setup. Requirements for layout slots, measurements, lines, runs, glyphs, and carets add together; shaping-buffer requirements take the maximum because one scratch area is reused. After all modules are composed, call App::prepare_text_layout before the first layout pass:

rust
app.require_text_layout_capacity(module_text_capacity)?;
// Compose the remaining modules before preparing the shared cache.
app.prepare_text_layout()?;

Registration does not replace the cache. Preparation checks the combined request against the active byte budget and leaves the previous cache intact on failure. Calls after layout starts and mixing additive requirements with with_text_layout_capacity return an error rather than discarding another module's reservation. App::render() and App::render_dirty() also prepare a pending requirement before layout; a failure returns RenderError::TextPreparation, with its cause available through App::last_text_layout_preparation_error(). Applications that control startup should call prepare_text_layout explicitly to report failures before entering the frame loop. Without an opt-in requirement, text layout keeps its existing on-demand behavior.

On Web Canvas, a demo can provide an untransformed, 1× per-run ink-extent hint during setup:

rust
app.prefer_text_raster_scratch(256, 8)?;

App takes the maximum width and height across hints and prepares raster slots before each frame using the current viewport scale. It provisions retained slots from the number of constructed bounded Text widgets; each slot retains its RGBA buffer, offscreen canvas, image data, and pixel views. A slot belongs to one text run: unchanged content reuses its raster, while changed content redraws into the same slot without displacing another run. The slots share one software raster scratch. One generation's requested RGBA bytes are capped at 8 MiB; a separate 8 MiB preflight includes the requested RGBA and slot metadata for both the retained generation and its replacement during resize. The glyph cache has its own independent 8 MiB nominal canvas-pixel limit; these are not a combined text-resource budget. The scratch checks bound managed Rust requests, not actual allocator capacity or browser heap usage. A resized viewport or a new bounded widget may require more storage. If preparation fails, the previous slots remain available and drawing continues through the glyph cache where needed; the error is available from App::last_text_raster_scratch_preparation_error(). Identical requests rejected by geometry or budget preflight are not rebuilt on every frame. Pool construction failures retry with at most 64 skipped preparation calls between attempts; a changed request or trim_memory clears the failure state. A memory trim releases the retained scratch and glyph/texture pools before the next preparation. Static text and runs that exceed the prepared extent keep the existing glyph-cache path; the hint is not a strict capacity or a zero-resource-growth guarantee. A bounded Text can produce multiple layout runs; if run identities exceed the prepared slot count, new runs replace the least recently used slot. capacity limits UTF-8 content bytes, not raster dimensions. Transformed text may also exceed the hint.

WebCanvasRendererFactory::text_resource_stats() distinguishes scratch preparation attempts and failures, retained-slot hits, draws, run evictions, and fallbacks from bounded runs that created a glyph-cache surface. Preparation counters count actual new-pool attempts, not cached rejections or skipped calls. bounded_scratch_current and bounded_scratch_peak are WebScratchResourceUsage snapshots. Their Rust capacity covers the RGBA slots and slot table; the peak includes old/new overlap and partial failed construction. Canvas and ImageData fields count retained objects and construction overlap. ImageData byte counts use its declared RGBA pixel length; canvas pixel bytes are only an RGBA-equivalent area, not measured backing allocation. The js_pixels view shares ImageData storage, and the retained rust_view refers to the Rust RGBA buffer. bounded_scratch_upload_bytes counts full-slot uploads after cache misses, not newly allocated bytes; bounded_upload_bytes counts new glyph-cache pixel uploads. Scratch and fallback counters cover native linear bounded text; path-laid-out and projective text use separate routes. These counters exclude the software raster scratch, glyph-cache metadata, browser object overhead, internal Canvas allocations, and delayed garbage collection, so they do not establish a browser-heap limit. Ordinary text and text inputs retain their existing rendering path.

An explicit memory warning retains the bounded text-layout cache and its live handles so that reservation still applies to the next frame. Web Canvas raster scratch and glyph/texture pools are separate reconstructible resources and are released. Unbounded text caches retain their existing trim behavior.

Text on a static path ​

path! stores its commands in the program image. Registering those commands with insert_static keeps the path borrowed and gives it a stable PathId.

Static Path
1274static ARC: Path = path!(M 12 72 Q 114 10 216 72);
1275
1276fn register_arc<B: Surface, F: RendererFactory<B>>(app: &mut App<B, F>) -> PathId {
1277 app.paths()
1278 .insert_static(ARC.commands())
1279 .expect("path capacity")
1280}
1281
1282#[compose]
1283fn curved_title(arc: PathId) {
1284 ui! {
1285 Column (
1286 grow: 1.0,
1287 padding: Padding::all(16),
1288 justify: JustifyContent::Center
1289 ) {
1290 View (
1291 height: 104,
1292 bg_color: ColorToken::SurfaceVariant,
1293 border_radius: 12,
1294 clip_children: true
1295 ) {
1296 Text (
1297 "Status · Ready on arc",
1298 path: arc,
1299 position: Position::Absolute,
1300 left: 8,
1301 top: 10,
1302 width: Dimension::percent(94),
1303 height: 86,
1304 font_size: 14,
1305 text_color: ColorToken::Primary
1306 )
1307 }
1308 }
1309 };
1310}
Loading preview…

insert_static borrows the compile-time ARC commands in ROM/flash and returns a PathId that Text(path: arc) follows from distance 0.

Passing a PathId uses subpath 0, starts at distance 0, follows the path forward, and uses the full available length.

Place multiple lines ​

Each paragraph line uses one consecutive subpath, beginning at TextPath::subpath(). The usable length of each subpath constrains wrapping, alignment, justification, and ellipsis before glyph placement.

Multi-Subpath
1312static LINES: Path = path!(
1313 M 12 30 L 216 30
1314 M 14 66 Q 114 100 214 66
1315);
1316
1317fn register_lines<B: Surface, F: RendererFactory<B>>(app: &mut App<B, F>) -> PathId {
1318 app.paths()
1319 .insert_static(LINES.commands())
1320 .expect("path capacity")
1321}
1322
1323#[compose]
1324fn multiline_label(lines: PathId) {
1325 ui! {
1326 Column (
1327 grow: 1.0,
1328 padding: Padding::all(16),
1329 justify: JustifyContent::Center
1330 ) {
1331 View (
1332 height: 112,
1333 bg_color: ColorToken::SurfaceVariant,
1334 border_radius: 12,
1335 clip_children: true
1336 ) {
1337 Text (
1338 "First line stays straight\nand line two curves.",
1339 path: lines,
1340 position: Position::Absolute,
1341 left: 8,
1342 top: 8,
1343 width: Dimension::percent(94),
1344 height: 96,
1345 font_size: 13,
1346 text_color: ColorToken::OnSurface,
1347 paragraph: ParagraphStyle {
1348 wrap: TextWrap::Word,
1349 max_lines: Some(2),
1350 ..ParagraphStyle::default()
1351 }
1352 )
1353 }
1354 }
1355 };
1356}
Loading preview…

LINES defines two subpaths (M ... L ... and M ... Q ...). Line 1 lays out along the straight segment and line 2 wraps onto the quadratic curve.

No baseline array or copied command buffer is created. Line-only subpaths are sampled directly from Path; curved subpaths reuse the bounded measurement cache. A missing or invalid subpath rejects the path layout before placed glyph or caret frames are published.

Select a range and direction ​

TextPath describes how text consumes a registered path without copying its commands.

Range & Direction
recipes.rs114 lines
1358static RING_PATH: Path = path!(
1359 M 12 24 L 216 24
1360 M 14 66 Q 114 20 214 66
1361);
1362
1363#[model]
1364pub struct RangeControl {
1365 path: PathId,
1366 #[observe]
1367 pub reversed: bool,
1368 #[observe]
1369 pub offset: i32,
1370}
1371
1372#[model]
1373impl RangeControl {
1374 pub fn new(path: PathId) -> Self {
1375 Self {
1376 path,
1377 reversed: false,
1378 offset: 6,
1379 }
1380 }
1381
1382 #[observe]
1383 pub fn placement(&self) -> TextPath {
1384 let dir = if self.reversed {
1385 PathDirection::Reverse
1386 } else {
1387 PathDirection::Forward
1388 };
1389 TextPath::new(self.path)
1390 .with_subpath(1)
1391 .with_range(Fixed::from_int(8)..Fixed::from_int(202))
1392 .with_offset(Fixed::from_int(self.offset))
1393 .with_direction(dir)
1394 }
1395
1396 pub fn flip_dir(&mut self) {
1397 self.reversed = !self.reversed;
1398 }
1399
1400 pub fn step_offset(&mut self) {
1401 self.offset = (self.offset + 12) % 36;
1402 }
1403}
1404
1405#[compose]
1406fn typo_range_scene(state: model!(RangeControl)) {
1407 ui! {
1408 Column (
1409 grow: 1.0,
1410 padding: Padding::all(16),
1411 row_gap: 10,
1412 text_color: ColorToken::OnSurface
1413 ) {
1414 Row (height: 30, column_gap: 6, align: AlignItems::Center) {
1415 Text (
1416 text: ${
1417 format_args!(
1418 "{} · +{} px",
1419 if state.reversed() { "Reverse" } else { "Forward" },
1420 state.offset()
1421 )
1422 },
1423 capacity: 28,
1424 grow: 1.0,
1425 height: 20,
1426 font_size: 12,
1427 text_color: ColorToken::OnSurfaceVariant,
1428 paragraph: ParagraphStyle::label().with_align(TextAlign::Start)
1429 )
1430 Button (
1431 "Offset +12",
1432 width: 78,
1433 height: 28,
1434 font_size: 12,
1435 border_radius: 7,
1436 normal_color: ColorToken::SurfaceVariant,
1437 pressed_color: ColorToken::Outline,
1438 text_color: ColorToken::OnSurface
1439 ) on Tap { state.step_offset(); }
1440 Button (
1441 "Reverse",
1442 width: 68,
1443 height: 28,
1444 font_size: 12,
1445 border_radius: 7,
1446 normal_color: ColorToken::Primary,
1447 pressed_color: ColorToken::Secondary,
1448 text_color: ColorToken::OnPrimary
1449 ) on Tap { state.flip_dir(); }
1450 }
1451 View (
1452 grow: 1.0,
1453 bg_color: ColorToken::SurfaceVariant,
1454 border_radius: 12,
1455 clip_children: true
1456 ) {
1457 Text (
1458 "Range on subpath 1",
1459 path: ${ state.placement() },
1460 position: Position::Absolute,
1461 left: 6,
1462 top: 8,
1463 width: Dimension::percent(95),
1464 height: Dimension::percent(86),
1465 font_size: 14,
1466 text_color: ColorToken::Primary
1467 )
1468 }
1469 }
1470 };
1471}
Loading preview…

Click Offset +16 to advance the leading inset along subpath 1, or click Reverse to flip PathDirection::Forward and PathDirection::Reverse.

with_seam chooses the distance treated as the start of a closed subpath. The selected range remains measured in path-length units after the seam is applied.

with_offset leaves a fixed-point leading inset inside the selected range. Wrapping, alignment, ellipsis, glyphs, and carets use the remaining path length.

Pass the same placement value to a composition:

rust
use mirui::prelude::*;
use mirui::ui::widgets::Text;

#[compose]
fn status_label(placement: TextPath) {
    ui! {
        Text("Status", font_size: 24, path: placement)
    };
}

Switch paths reactively ​

The DSL accepts a Signal<PathId> as a reactive path attribute. Replacing the signal value moves the existing text entity to the new path and transfers its path-change subscription.

Signal<PathId>
1473#[compose]
1474fn selectable_path(first: PathId, second: PathId) {
1475 let selected = Signal::new(first);
1476 let selection = selected.clone();
1477
1478 ui! {
1479 Column (
1480 grow: 1.0,
1481 padding: Padding::all(16),
1482 row_gap: 10,
1483 text_color: ColorToken::OnSurface
1484 ) {
1485 Row (height: 30, align: AlignItems::Center) {
1486 Text (
1487 "Signal<PathId> binding",
1488 grow: 1.0,
1489 height: 20,
1490 font_size: 12,
1491 text_color: ColorToken::OnSurfaceVariant
1492 )
1493 Button (
1494 "Switch path",
1495 width: 90,
1496 height: 28,
1497 font_size: 12,
1498 border_radius: 7,
1499 normal_color: ColorToken::Primary,
1500 pressed_color: ColorToken::Secondary,
1501 text_color: ColorToken::OnPrimary
1502 ) on Tap {
1503 selected.update(|path| {
1504 *path = if *path == first { second } else { first };
1505 });
1506 }
1507 }
1508 View (
1509 grow: 1.0,
1510 bg_color: ColorToken::SurfaceVariant,
1511 border_radius: 12,
1512 clip_children: true
1513 ) {
1514 Text (
1515 "Live route swaps PathId",
1516 path: $selection,
1517 position: Position::Absolute,
1518 left: 6,
1519 top: 10,
1520 width: Dimension::percent(95),
1521 height: Dimension::percent(85),
1522 font_size: 14,
1523 text_color: ColorToken::Primary
1524 )
1525 }
1526 }
1527 };
1528}
Loading preview…

Click Switch path to update selected: Signal<PathId>—the existing Text entity moves between the two registered paths without rebuilding the widget.

Derive path geometry from signals ​

Create one mutable path, reserve its command storage once, and bind its geometry to signals. bind_path installs an owner-bound effect: signal changes edit the existing path, advance its revision, and dirty every subscribed text or drawing entity.

bind_path
1530#[compose]
1531fn elastic_baseline(amplitude: Signal<Fixed>) {
1532 let mut geometry = Path::try_with_capacity(2).expect("path storage");
1533 geometry
1534 .move_to(Point::new(12, 52))
1535 .quad_to(Point::new(114, 52), Point::new(216, 52));
1536 let path = cx.paths().insert(geometry).expect("path capacity");
1537 let live_amplitude = amplitude.clone();
1538 let toggle_amp = amplitude.clone();
1539
1540 cx.bind_path(path, move |geometry| {
1541 let y = Fixed::from_int(52) - live_amplitude.get();
1542 geometry
1543 .set_command(
1544 1,
1545 PathCmd::QuadTo {
1546 ctrl: Point::new(Fixed::from_int(114), y),
1547 end: Point::new(216, 52),
1548 },
1549 )
1550 .expect("stable command shape");
1551 })
1552 .expect("mutable path");
1553
1554 ui! {
1555 Column (
1556 grow: 1.0,
1557 padding: Padding::all(16),
1558 row_gap: 10,
1559 text_color: ColorToken::OnSurface
1560 ) {
1561 Row (height: 30, align: AlignItems::Center) {
1562 Text (
1563 "cx.bind_path(path, ...)",
1564 grow: 1.0,
1565 height: 20,
1566 font_size: 12,
1567 text_color: ColorToken::OnSurfaceVariant
1568 )
1569 Button (
1570 "Invert curve",
1571 width: 96,
1572 height: 28,
1573 font_size: 12,
1574 border_radius: 7,
1575 normal_color: ColorToken::Primary,
1576 pressed_color: ColorToken::Secondary,
1577 text_color: ColorToken::OnPrimary
1578 ) on Tap {
1579 toggle_amp.update(|a| *a = -*a);
1580 }
1581 }
1582 View (
1583 grow: 1.0,
1584 bg_color: ColorToken::SurfaceVariant,
1585 border_radius: 12,
1586 clip_children: true
1587 ) {
1588 Text (
1589 "Signal-driven curve",
1590 path: path,
1591 position: Position::Absolute,
1592 left: 8,
1593 top: 8,
1594 width: Dimension::percent(94),
1595 height: Dimension::percent(86),
1596 font_size: 14,
1597 text_color: ColorToken::Primary
1598 )
1599 }
1600 }
1601 };
1602}
Loading preview…

Click Invert amplitude to flip amplitude: Signal<Fixed>—cx.bind_path updates the quadratic control point in place and re-lays out the text.

The effect retains the path allocation and command capacity. Prefer set_command when the command topology is stable; use clear plus path-building methods when the topology itself changes.

Edit a path from a handler ​

Event callbacks borrow the path store through res!(mut PathStore). Editing by PathId preserves entity identity and updates all consumers of the path.

res!(mut PathStore)
1604#[compose]
1605fn bendable_label(path: PathId) {
1606 ui! {
1607 Column (
1608 grow: 1.0,
1609 padding: Padding::all(16),
1610 justify: JustifyContent::Center
1611 ) {
1612 View (
1613 height: 108,
1614 bg_color: ColorToken::SurfaceVariant,
1615 border_radius: 12,
1616 clip_children: true
1617 ) {
1618 Text (
1619 "Tap text to bend curve",
1620 path: path,
1621 position: Position::Absolute,
1622 left: 8,
1623 top: 10,
1624 width: Dimension::percent(94),
1625 height: 88,
1626 font_size: 14,
1627 text_color: ColorToken::Primary
1628 ) on Tap(|paths: res!(mut PathStore)| {
1629 paths
1630 .edit(path, |geometry| {
1631 let next_y = match geometry.commands().get(1) {
1632 Some(PathCmd::QuadTo { ctrl, .. }) if ctrl.y < Fixed::from_int(40) => 92,
1633 _ => 12,
1634 };
1635 geometry
1636 .set_command(
1637 1,
1638 PathCmd::QuadTo {
1639 ctrl: Point::new(114, next_y),
1640 end: Point::new(216, 58),
1641 },
1642 )
1643 .expect("stable command shape");
1644 })
1645 .expect("mutable path");
1646 })
1647 }
1648 }
1649 };
1650}
Loading preview…

Click directly on the curved text to run its on Tap handler, mutating the path in res!(mut PathStore) with set_command.

Query caret and selection geometry ​

Outputs<TextGeometry> borrows completed geometry for entities with a Text component. A component's #[depends_on(TextGeometry)] declaration requests the result when its View is registered. Layout, glyph placement, and caret placement share retained storage with text painting; reads do not produce or copy geometry.

Outputs<TextGeometry>
1652#[component]
1653#[depends_on(TextGeometry)]
1654struct CaretOverlay;
1655
1656#[view(component = CaretOverlay)]
1657fn caret_overlay(entity: entity!(), geometries: res!(Outputs<TextGeometry>), paint: paint!()) {
1658 let Some(geometry) = geometries.get(entity) else {
1659 return;
1660 };
1661 let mut storage = [PathCaretGeometry::default(); 64];
1662 let Ok(carets) = geometry.carets_into(&mut storage) else {
1663 return;
1664 };
1665 let rect = paint.rect();
1666 for caret in carets {
1667 let [start, end] = caret.segment();
1668 paint.draw(&DrawCommand::Line {
1669 p1: Point::new(rect.x + start.x, rect.y + start.y),
1670 p2: Point::new(rect.x + end.x, rect.y + end.y),
1671 transform: paint.transform(),
1672 color: Color::rgb(70, 160, 255),
1673 width: Fixed::ONE,
1674 opa: 255,
1675 });
1676 }
1677}
1678
1679#[compose]
1680fn typo_carets_scene(arc: PathId) {
1681 ui! {
1682 Column (
1683 grow: 1.0,
1684 padding: Padding::all(16),
1685 justify: JustifyContent::Center
1686 ) {
1687 View (
1688 height: 108,
1689 bg_color: ColorToken::SurfaceVariant,
1690 border_radius: 12,
1691 clip_children: true
1692 ) {
1693 Text (
1694 "Carets along arc",
1695 path: arc,
1696 position: Position::Absolute,
1697 left: 8,
1698 top: 14,
1699 width: Dimension::percent(94),
1700 height: 84,
1701 font_size: 15,
1702 text_color: ColorToken::OnSurface
1703 ) [CaretOverlay]
1704 }
1705 }
1706 };
1707}
Loading preview…

CaretOverlay declares #[depends_on(TextGeometry)] and draws each character's oriented normal caret segment along the curve.

Register caret_overlay::view() and attach CaretOverlay to the path-text node. carets_into and selection_into return source-local geometry into caller-provided buffers. The example adds the current paint origin and applies its transform once. hit_test accepts screen coordinates; transform() provides the prepared source-local-to-screen mapping, including ancestor transforms and scrolling. Linear text exposes its retained layout, font metrics, and local content rectangle through layout(), metrics(), and content_rect().

Mixed-direction selections are split at visual-run and line boundaries. Exhausted caret storage makes interaction geometry unavailable without discarding prepared glyphs. Selection output remains unchanged when capacity validation fails; hit testing through or behind the near plane returns PathTextGeometryError::InvalidProjection. Cache replacement, trimming, hidden sources, and removed text invalidate published geometry until preparation succeeds. TextEditing shares layout storage but does not replace the Text result on the same entity.

Backend behavior ​

HYBRID ENGINE & EXACT FALLBACKPer-command routing across 2D blitters, VG-Lite vector GPUs & bounded fallback

`VgLiteEngine::route` checks `request.command` against the cached `vg_lite_query_feature(gcFEATURE_BIT_VG_*)` table: cubic/quadratic Bézier `FillPath`, `StrokePath`, and 3×3 projective `Blit` return `Ok(RenderRoute::Native)`.

if vg_lite_query_feature(gcFEATURE_BIT_VG_STROKE_PATH) != 0 { return Ok(RenderRoute::Native); }Hardware Bézier tessellation + 3×3 matrix blit
GeometrySoftwareWGPUSDL GPUWeb Canvas
Linear and affinenativenativenative run cachenative canvas path
Posed coverageinverse sampledinstanced atlasbatched scalar atlasper-glyph transform
Posed SDFderivative-awarederivative-awareexact coverage routeexact coverage route
Projective glyphsinverse sampledprojective atlasbounded software targetbounded software target

SDL GPU run textures store straight RGB and glyph coverage separately. Transparent texels retain the text color so linear filtering does not introduce a dark fringe; text color alpha and draw opacity are applied during composition.

SDL GPU posed coverage batches split geometry at the region's outer texel centers, preserving the source sampling scale while clamping interpolation to each glyph. Empty clips do not submit text geometry.

render::PosedGlyphs pairs borrowed positioned glyphs and placement frames for render commands, Canvas calls, and scene replay. Construction rejects mismatched slice lengths without allocating.

SDL GPU and Web Canvas use a ProjectiveFallback supplied through their renderer factory for projective glyphs, fills, borders, and image blits with rounded corners, opacity, and composite modes. Its fixed RGBA storage is both the target and scratch space. ProjectiveFallback::borrowed(&mut bytes) uses a caller-owned fixed buffer; ProjectiveFallback::new(bytes) owns its buffer. Shape and image requests use projected visual bounds to limit the required storage; glyph requests use projected ink bounds. Preflight rejects missing or insufficient capacity before drawing. Unsupported projective commands remain errors. Gallery reserves 2 MiB for this target on Web Canvas and SDL GPU. The complete routing, numeric-domain, and aligned-memory contract is described in Exact backend fallback.

Storage and invalidation ​

  • PathId is a generational handle; removing a path invalidates stale handles.
  • Static entries borrow command slices and reject edits.
  • Mutable entries own or adopt their command storage and expose a monotonically advancing revision.
  • Text entities subscribe to the path selected by their TextPath component.
  • Baseline sampling, posed glyphs, caret frames, ink bounds, and hit testing are cached by path identity and revision.
  • Path edits recompute affected line lengths and invalidate placement through the same path revision.
  • Ordinary text without a TextPath stays on the linear shaping and rendering path.

Set the registry's live-path limit while it is empty. Changing this limit preserves retired ID generations and does not release slot metadata:

rust
app.with_path_capacity(24)?;