1// Text in pure Alloy (PLAN.md, stages F4 and F10): TrueType2// faces, text split into runs by script and emoji presentation, shaping3// by the faces' OpenType features, line breaking by UAX #14 with carets4// on grapheme clusters by UAX #29, and glyphs rasterized into coverage5// masks. It knows nothing of the GPU: `pkg::alloy::draw` draws a layout.6// Text is shaped as HarfBuzz shapes it. The bundled font is Inter7// Regular, made bold by thickening it. Two packages install more on the8// fonts (REFOCUS.md, R6d): pkg::alloy::text_scripts the9// complex scripts' shapers and both directions mixed by UAX #9,10// pkg::alloy::text_fonts CFF, variable and color faces (COLR, CBDT,11// sbix, as premultiplied RGBA) and fallback to the system's fonts.12// Without them every run is shaped by the default shaper, left to13// right, and characters Inter lacks show as boxes, the same on every14// target.15//16// ```text17// var fonts = Fonts::create();18// const style = TextStyle::of(fonts.default(), 15.0);19// const layout = Layout::create(&fonts, &"Hello, world.", &style, 300.0);20// const at = layout.hit(40.0, 8.0); // a byte offset on a grapheme boundary21// const caret = layout.caret(at);22// ```23//24// ## How it was built25//26// Notes kept from each stage as it was finished, the sizes and numbers27// of their day; what changed since is in REVIEW.md and the history.28//29// **F4 as built** (2026-10-12):30// - `text`: `text.alloy` the API (`Fonts`, `TextStyle`, `Span`,31// `Layout` with `hit`, `caret`, `selection`, `next_position`,32// `previous_position`, `line_start`, `line_end`), `paragraphs.alloy`33// layout, `font/` (`face.alloy` tables and metrics, `outline.alloy`34// `glyf` with composites, `raster.alloy` coverage), `shaping/`35// (`shaper.alloy` normalization, clusters and the feature list,36// `gsub.alloy`, `gpos.alloy`, `context.alloy`, `opentype.alloy`),37// `unicode/` (`generate.alloy` writing `tables.alloy` from UCD 16.0,38// which `fetch.sh` downloads by pinned SHA-256s; `lines.alloy` UAX #14,39// `graphemes.alloy` UAX #29, `properties.alloy`). Inter 4.1 regular and40// bold, subset, about 100 KB each (`fonts/`, OFL). Shaping applies GSUB41// 1 to 7 and GPOS 1, 2 and 4 to 9 (contexts in formats 1 to 3, lookup flags,42// GDEF classes and mark filtering sets), `kern` where a face has no43// GPOS, and normalizes as HarfBuzz does; each lookup keeps a bit set of44// the glyphs its subtables can start at (`LookupSets`, made when a face45// is read), which made layout four times faster.46// - `draw`: `paint.text(&layout, origin, color)`, decorations as47// rectangles; at encoding each glyph becomes a mask instance from48// `glyphs.alloy`'s cache (coverage per face, glyph, size in quarter49// pixels and quarter-pixel shift, in R8 pages of 1024 pixels, the one50// used least recently cleared past four and the nodes using it encoded51// again), snapped to whole pixels where the node is only moved and52// scaled evenly, transformed otherwise; glyphs well clear of the clip53// are skipped before rasterizing. `canvas.fonts()` makes the54// fonts when first asked, so a program drawing no text carries no faces55// (the cards startup stays 0.82 MB).56// - `window`: `set_text_input(::Some(Area))` and `Event::Preedit(Preedit57// { text, cursor })`, an empty one ending the composition before its58// `Text`: Wayland through `text-input-unstable-v3` (its59// `delete_surrounding_text` ignored, as no surrounding text is sent),60// Win32 through IMM32 (compositions without the system's window, keys61// the input method takes skipped, no input method until asked for), the62// web through a hidden textarea at the caret (paste reaches it as63// `Text`); headless replays keep the area last asked for.64// - Tests: `alloyc test text/tests.alloy` (faces, outlines, rasterizing,65// 13 strings shaped as `hb-shape` shapes them, `tests/shaping.txt` from66// `tests/harfbuzz.sh`, layout, carets, selections, spans), Unicode's67// `LineBreakTest.txt` and `GraphemeBreakTest.txt` passing whole68// (`unicode/conformance.alloy`), two draw tests (a glyph page, eviction),69// `tests/canvas.alloy`'s text scene the same on the CPU device, lavapipe,70// Dawn, the GTX 1660 and the RTX 4070 Ti, the window's composition test,71// and `tests/text_input.alloy` in node's page, whose fake input method72// composes 你 (`tests/web/dom.mjs`), and under weston, which lacks73// text-input-v3. `samples/editor.alloy` is a text field (arrows, Home,74// End, Shift, Ctrl+A, the pointer, Backspace, Delete, Enter,75// compositions underlined); `editor.exe` is in `.alloy\window-tests` on76// the Windows desktop.77// - Benchmarks, the best of five, in milliseconds:78//79// | | lavapipe / biscuit's CPU | GTX 1660 | RTX 4070 Ti |80// |---|---|---|---|81// | laying out 10,000 words in 100 paragraphs | 30 | | 17 |82// | one of those paragraphs again | 0.27 | | 0.15 |83// | rasterizing 94 ASCII glyphs at 12, 16 and 32 px | 1.5 | | 0.84 |84// | a 1920x1080 page of text, glyphs rasterized first | 25 | 6.7 | 3.9 |85// | that page drawn again | 21 | 2.3 | 1.4 |86//87// Hello world with text presents its first frame 64 ms after `main`88// under weston on lavapipe, at 86 MB resident (lavapipe's LLVM again);89// it is 1.23 MB natively and 0.94 MB of wasm, of which the faces are90// 206 KB and the Unicode tables about 70 KB. Release wasm modules no91// longer carry their `name` section (63 KB here; decided 2026-10-12),92// which also took the cards startup to 0.54 MB of wasm.93// - Left for later: CFF and variable fonts, hinting, bidi and complex94// scripts, fallback (F10); GSUB 8 and GPOS 3 (cursive); a layout is95// made whole each time (a paragraph's 0.27 ms96// makes incremental layout F5's to decide); the Wayland and Windows97// input methods wait for a person with one.98//99// **F10a as built** (2026-10-14; decisions/F10.md):100// - Formats: `font/cff.alloy` reads CFF (Type 2 charstrings with local101// and global subroutines, flex, hints skipped, CID-keyed fonts through102// FDSelect 0, 3 and 4) and CFF2 (`blend`, `vsindex`), as cubic103// `PointKind::Cubic` points that `raster.alloy` flattens into lines by104// their deviation; collections (`ttcf`) of either. Variable fonts:105// `fvar` axes and named instances, `avar` 1, `gvar` (shared and private106// points, IUP) and CFF2 blends through `font/variations.alloy`'s item107// variation stores, `HVAR` advances, `MVAR` metrics, GDEF's store for108// GPOS value records and anchors, GSUB's and GPOS's feature variations109// (`rvrn` on). `face.at(values)` makes an instance sharing the file's110// bytes and lookup sets; `FontStore` keeps instances by face, weight111// (when there is a `wght` axis) and size (when there is `opsz`), so a112// style's weight 1-1000 and size pick one, and named instances are a113// family's faces. Left out: `avar` 2, CFF's `seac` accents and114// arithmetic operators, hinting.115// - Itemization: `unicode/generate.alloy` adds Scripts, Script_Extensions,116// emoji properties, Bidi_Brackets and Default_Ignorable to the tables117// (`fetch.sh` pins the UCD 16.0 files and emoji-test.txt);118// `unicode/runs.alloy` splits a paragraph into runs by script (UAX119// #24, Common and Inherited joining their neighbors, a closing bracket120// taking its opening one's script) and by emoji presentation (UTS #51121// sequences: modifiers, flags, keycaps, ZWJ, tags, VS15 and VS16), and122// `paragraphs.alloy` shapes each run in the face covering its clusters,123// never splitting one across faces. The shaper drops a variation124// selector the face has no glyph for (a keycap's VS16); hiding default125// ignorables as HarfBuzz does, with GSUB skipping them, waits for126// F10c's shaping.127// - Fallback (`fallback.alloy`, `system/`): fontconfig's `FcFontSort`128// through `Library` on Linux, DirectWrite's `IDWriteFontFallback`129// through `pkg::alloy::com` (moved out of `window` into `com`130// for this) on Windows, Core Text's `CTFontCreateForString` on macOS,131// and on the web the font files a program serves and names with132// `fonts.fetch(&path)`; a font picked is read whole once and kept as133// a family, answers cached per script, language, weight and block of134// 256 characters (per character where the block's lacks one), the135// families picked for a script tried first. `Fonts::bundled()` leaves136// the system out (the interpreter, `ui`'s trees without a scene);137// `TextStyle.language` is the tag fallback asks with; `face_name`138// gives a face's PostScript name.139// - Tests: `check.alloy` (`check <fonts directory>`, run by140// `scripts/test.sh`) compares 242 glyph outlines of CFF, CID-keyed,141// CFF2 and variable fonts at several instances with fontTools'142// (`tests/outlines.txt` from `tests/outlines.py`) and 14 variable143// shaping runs with `hb-shape --variations` (`tests/variations.txt`),144// on fonts `tests/fonts.sh` fetches at pinned SHA-256s into a cache145// (Source Sans, Source Han Sans, Noto Sans CJK's collection, Inter's146// and Source Sans 3's variable faces, HarfBuzz's test fonts), and asks147// this machine's fontconfig for Han, Arabic, Devanagari and emoji;148// `tests.alloy` the runs; `unicode/conformance.alloy` emoji-test.txt's149// 3988 sequences, each one cluster in emoji presentation; `tests/fallback.alloy` (Windows,150// by hand through `windows-tests.ps1`), `tests/fetch.alloy` in node's151// page and under weston. Sample `samples/world.alloy`: a greeting in152// 15 scripts with a weight slider and a field to type in; `world.exe`153// is in `.alloy\window-tests\ui` on the Windows desktop.154// - Benchmarks, biscuit's CPU, the best of five, in milliseconds: the155// first fallback lookup of a session (fontconfig opened, Noto Sans CJK156// read) 9.9, a 20-character Han line once cached 0.007; the 94 ASCII157// glyphs at 12, 16 and 32 px 0.82 in Inter, 0.82 in Source Sans (CFF),158// 1.2 in Inter's variable face at weight 650 (deltas applied each159// time); the 10,000 words 18.8 and a paragraph 0.17, as before. Hello160// world grew from 1.04 to 1.20 MB natively and from 0.61 to 0.73 MB of161// wasm, F10's whole estimate (question 7).162// - Left for later: when a page's fetched font arrives nothing lays the163// text out again (question 6); emoji are laid out in the color font164// but drawn blank until F10d; Windows' and macOS's fallback wait for a165// person to run them.166//167// **F10b as built** (2026-10-14; decisions/F10.md, "Bidi"):168// - Unicode data: `unicode/generate.alloy` adds Bidi_Class (a `BidiClass`169// enum in a trie of its own, DerivedBidiClass.txt's `@missing` defaults170// included, a MIRRORED bit beside it) and BidiMirroring.txt's pairs;171// about 16 KB of tables. `fetch.sh` pins them with BidiTest.txt and172// BidiCharacterTest.txt.173// - `unicode/bidi.alloy`: UAX #9 whole (P2-P3, X1-X10 with the overflow174// counts, isolating run sequences, W1-W7, N0 with canonical brackets,175// N1-N2, I1-I2, L1, L2); `conformance.alloy` passes BidiTest.txt's176// 770,241 cases and BidiCharacterTest.txt's 91,707.177// - Layout: `TextStyle.direction` (`Direction::Auto` by default: each178// paragraph's first strong character; an empty paragraph keeps the one179// before's), paragraphs being the text between mandatory breaks (so180// U+2028, VT and FF start one too); a paragraph with nothing right to181// left takes one look at each non-ASCII character and stays at level 0.182// Runs of one style and level are shaped in their direction: mirrored183// glyphs, `rtla`, `rtlm` (kept off mirrored clusters), GPOS marks184// resolved backwards as HarfBuzz does, and its modified combining185// classes for every script (Hebrew points in SBL order, shadda first).186// Lines are filled in the text's order, then their glyphs reordered187// (L1 on their clusters, L2): `glyphs` are in visual order, each with188// its cluster; spaces a right-to-left line hangs go to its left;189// `Line.direction`; `Align::Start` and `End` (and `ui`'s `TextAlign`)190// follow each paragraph.191// - Carets: a layout keeps each grapheme's leading and trailing edges in192// visual order (`Line.graphemes`, its text under 4 GiB); `caret(at)` is193// drawn after the grapheme ending at `at`, on its side, or before the194// line's first; `hit` finds the nearest caret; `selection` gives a box195// for each visual stretch; `next_position` and `previous_position` go196// through the carets ordered by x then offset (so two drawn together197// are both reached), past a line's end on to the next line (the198// previous right to left); `next_logical` and `previous_logical` keep199// the text's order, for deletion; `line_of` is exported. A position at200// a direction change has no caret on its other side (question 8).201// - `ui`: `TextField` moves visually, deletes logically, collapses a202// selection at the end shown on the arrow's side, keeps a short203// right-to-left line at its right, and composes in either direction.204// - Tests: layout goldens in `tests.alloy` (visual order, carets as205// boundaries, walks both ways, hits, selections, wrapped lines,206// numbers in Arabic, explicit directions, empty paragraphs), three207// right-to-left runs in Inter and five of pointed Hebrew in Noto Sans208// Hebrew 3.001 shaped as `hb-shape --direction=rtl` shapes them209// (`check.alloy`; Noto Sans Hebrew and Arabic fetched pinned by210// `tests/fonts.sh`), a `TextField` editing Hebrew with Latin, and211// three scenes replayed at scale 2 (`tests/golden/ui/bidi_*.png`) in212// committed fonts (`tests/fonts`, OFL). Latin output is213// unchanged; the access trees too.214// - Benchmarks, biscuit's CPU, the best of five: 10,000 words in Arabic215// 19.4 ms (16.8 without bidi), mixed with Latin in turns of three 22.7216// ms, Latin 19.0 against 18.9 before;217// hello world 1.20 to 1.26 MB natively and 0.73 to 0.78 MB of wasm218// (+59 and +54 KB; question 7).219// - Left for F10c: Arabic's joining and the other shapers (Arabic shows220// unjoined), the face's script and language systems (lookups are still221// `latn`'s or `DFLT`'s), HarfBuzz's reversal of a Latin run forced right222// to left by an override.223//224// **F10c as built** (2026-10-14; decisions/F10.md, "Shaping"):225// - Unicode data: `unicode/generate.alloy` adds General_Category with226// Joining_Type (Syriac's Alaph and Dalath Rish apart), and the Indic227// shaper's category and position and the USE category HarfBuzz 14.1.0's228// generators derive from Indic_Syllabic_Category and229// Indic_Positional_Category with its ms-use overrides (both matching230// them code point for code point), IndicShapingInvalidCluster.txt's231// vowel sequences, Arabic's presentation forms (`shaping_data.alloy`,232// `ucd.alloy` the generators' helpers). `unicode/language_tags.alloy`233// reads hb-ot-tag-table.hh into `shaping/language_tags.alloy`, and234// `unicode/machines.alloy` HarfBuzz's Ragel syllable machines (Indic,235// Khmer, Myanmar, USE) into `shaping/machines.alloy`; `fetch.sh` pins236// them all.237// - Shaping rewritten after hb-ot-shape.cc: `shaping/buffer.alloy`238// (glyph infos with Unicode and glyph props, ligature ids, clusters239// merged as HarfBuzz merges them), `plan.alloy` (a plan per face,240// script, language, direction and features, cached in `Fonts`: mask241// bits, lookups in stages with the shaper's pauses), `tags.alloy` (the242// script's tags, dev3 to deva, and a BCP 47 tag's language systems, so243// `TextStyle.language` picks `locl`'s forms), `normalize.alloy`,244// `apply.alloy` (HarfBuzz's skipping rules, per-syllable matching,245// subtables skipped by their digests), GSUB 8 and GPOS 3, default246// ignorables hidden; the shapers dispatched from `shapers.alloy`:247// `arabic.alloy` (Arabic, Syriac; joining with five characters of248// context either side, `stch`, UTR #53's mark order, presentation-form249// lookups made for faces without the features), `hebrew.alloy`,250// `indic.alloy` (nine scripts: syllables, reph, half, below and post251// forms, pre-base matras, initial and final reordering),252// `khmer.alloy`, `myanmar.alloy`, `universal.alloy` (Tibetan, Sinhala,253// Javanese, Mongolian, N'Ko and the 79 other scripts HarfBuzz sends to254// the USE), `thai.alloy` (Thai, Lao: Sara Am, private-use forms),255// `hangul.alloy`, with `syllables.alloy` (the machines run, dotted256// circles) and `fallback.alloy` (marks placed by combining class where257// GPOS is not applied). The `kern` table's formats 0, 2 and Apple's,258// faces without outlines, cmap 13. A run in a script with no complex259// shaper takes the default shaper and pays for none of the others.260// - Line breaking: the tables keep UAX #14's SA for Thai's, Lao's,261// Khmer's and Myanmar's bases, `lines.alloy` resolving it to AL (LB1),262// so Unicode's break tests pass whole; a line overflowing in such text263// ends at its last grapheme boundary between two SA characters when264// that is past the last opportunity (question 4, A), and a word wider265// than a line breaks only where a glyph cluster starts a grapheme.266// - Tests: `check.alloy` shapes HarfBuzz 14.1.0's own tests of the267// OpenType shapers (`tests/harfbuzz.txt`, 4901 runs; left out: Apple's268// and Microsoft's shapers, vertical text, cluster levels and other269// options text has no equivalent for, a Mac resource fork, a font270// HarfBuzz's sanitizer cuts, two legacy Arabic fonts, Zawgyi) and271// 4986 strings of `tests/scripts.cases` in the pinned Noto fonts of272// fifteen scripts (386 Arabic, 789 Devanagari, 592 Bengali, 436 Tamil,273// 442 Thai, 274 Lao, 322 Khmer, 303 Myanmar, 203 Tibetan, 252274// Mongolian, 202 N'Ko, 236 Javanese, 186 Syriac, 231 Hebrew, 132275// Hangul and Han), every one as `hb-shape` shapes it; `tests.alloy`276// Thai's breaks; the ui goldens gain `complex_scripts` (Khmer typed,277// Devanagari, Thai wrapping) in subsets in `tests/fonts`, and278// `bidi_arabic` changed once, its Arabic now joined.279// - Benchmarks, biscuit's CPU, the best of five, in milliseconds: 10,000280// words of Latin 20.5 (the F10b build measures the same today, 19.6 to281// 20.4), of Arabic 36.0 (19.4 unjoined before), of Devanagari 52.4,282// Arabic mixed with Latin 34.6; HarfBuzz shapes Devanagari about three283// times faster. Hello world 1.51 MB natively and 1.00 MB of wasm, +256284// and +216 KB over F10b, the wasm budget met by 34 bytes (question 7,285// updated).286// - Sample: `samples/world.alloy` in 24 scripts, built for every target;287// `world.exe` in `.alloy\window-tests\ui` on the Windows desktop.288// - Left for later: color emoji (F10d); dictionaries for SA line breaks289// (question 4, B); Zawgyi, vertical text and Apple's `morx`; HarfBuzz's290// buffer flags (a dotted circle before a run starting with a mark) and291// cluster levels.292//293// **F10d as built** (2026-10-15; decisions/F10.md, "Color294// emoji"):295// - `font/color.alloy`: COLR and CPAL, version 0's layers and version 1's296// paint graphs (every format, 1 to 32: layers, solid colors, linear,297// radial and sweep gradients with their three extend modes, glyphs as298// clips, color glyphs with their clip boxes and a guard against cycles,299// every transform, composites in all 28 modes, Porter and Duff's and300// the W3C's blends), varied through COLR's index map and variation store301// at a variable face's position; drawn on the CPU into a surface of302// premultiplied floats as large as the glyph's clip box (else what its303// glyphs cover), gradients interpolated premultiplied, each glyph clip a304// coverage mask from the rasterizer, which takes any affine transform305// now (`rasterize_with`). Palette 0; entry 0xFFFF is the text's color,306// and a glyph using it says so (`ColorMask.foreground`).307// - `font/bitmaps.alloy`: CBDT through CBLC's strikes (index formats 1 to308// 5, image formats 17 to 19) and sbix (`dupe` followed; JPEG and TIFF309// left out), the strike at or just above the size, else the largest;310// its PNG decoded by `font/png.alloy` (moved in from the viewer sample,311// inflate rewritten with nine-bit tables, since F12b in std::deflate),312// premultiplied and resampled,313// a box filter shrinking and bilinear growing.314// - The API: `fonts.glyph_image(face, glyph, size, shift, foreground)`315// gives `GlyphImage::Coverage` or `::Color(ColorMask)`, and316// `fonts.is_color(face, glyph)`; `draw` draws them with no program317// change. An emoji run whose style's face is itself a color font stays318// in it rather than going to fallback, so a program may bundle its emoji319// font; fallback otherwise picks the system's (Noto Color Emoji here,320// Segoe UI Emoji on Windows, Apple Color Emoji on macOS). The321// rasterizer no longer drops an edge a hair left of its mask by322// rounding, which skewed and scaled clips met, and cuts a mask to a323// window (`rasterize_within`, a color glyph's surface). A malformed324// font is bounded: paints nest 64 deep and a glyph visits 20,000,325// composites nest 4 deep, a color glyph is at most 2048 pixels a side,326// transforms past reason draw nothing, and a PNG's header alone327// allocates little.328// - Tests: `tests.alloy` (COLR version 0, CBDT and sbix squares of329// ChromaCheck, the text's color in a COLR version 1 glyph, the fonts'330// API; PNGs `tests/pngs.py` writes, damaged ones, headers out of331// reason); `check.alloy`'s332// `colors` mode draws sheets compared with golden images in333// `tests/golden/text` (`sheets.alloy`): every glyph of Google's334// COLR version 1 test font, at its default and at a position on its 44335// axes, emoji with sequences, a modifier, flags and keycaps in Noto Color336// Emoji 2.048 (COLR version 1), Twemoji Mozilla 0.7.0 (version 0) and337// Twemoji 14.0.2 (CBDT, from Fedora's package), and sbix and CBDT test338// glyphs, all pinned by `tests/fonts.sh`; matched by eye and pixel by339// pixel with `hb-view` 14.1.0 (cairo) while built, which differs only in340// sampling, in a sweep's patches, and in drawing a stop's color where341// cairo draws something near it. 669 emoji strings (every 11th fully342// qualified sequence of emoji-test.txt and 43 harder ones in Noto Color343// Emoji, every 40th in both Twemojis) shape as `hb-shape` shapes them344// (`tests/scripts.cases`). `draw`'s golden `emoji` scene from subsets in345// `tests/fonts`, the same on the CPU, lavapipe and Dawn.346// - Benchmarks, biscuit's CPU, the best of five, in milliseconds: 100347// emoji at 32 pixels drawn into their colors 10.3 in Noto Color Emoji348// (COLR version 1), 10.5 in Twemoji (CBDT: PNGs decoded and shrunk); a349// 1920x1080 page of 1914 emoji of 100 kinds, rasterized and packed first350// 23.7 on lavapipe, drawn again 13.2; ASCII rasterized as before (0.9).351// Hello world 1.60 MB natively and 1.08 MB of wasm, F10d adding about352// 85 KB to each (question 7: budgets of 1.1 MB of wasm and 1.7 MB353// natively).354// - Sample: `samples/world.alloy` with emoji sequences, skin tones, flags,355// keycaps and tags, in color.356// - Left for later: SVG glyphs (`SVG `, not one of the four formats),357// palettes other than the first, JPEG and TIFF in sbix, hinting.358//359// **F14b as built** (2026-10-20; decisions/F14.md, "Words"):360// UAX #29's word boundaries (Unicode 16.0) in `unicode/words.alloy`, from361// `WordBreakProperty.txt`, pinned by `unicode/fetch.sh` and generated by362// `generate.alloy` into `WORD_BREAKS` (1888 runs, the property in the363// low five bits) and the `WordBreak` enum; `Extended_Pictographic` is the364// tables' own. `word_boundaries` gives every boundary, WB1 to WB999 with365// WB4's ignored characters standing for what they follow;366// `word_starts(text)` the boundaries before a letter, a digit, Katakana,367// an ideograph (line breaking's ID), an emoji or a flag, never inside a368// run of Thai, Lao, Khmer or Myanmar (line breaking's SA, no dictionary369// here), so a word runs from its start to the next one's, the spaces370// after it included. `unicode/conformance.alloy words` passes all 1826371// cases of `WordBreakTest.txt` (pinned beside the tables and run by372// `scripts/test.sh` with the other UCD tests there rather than in373// `tests.alloy`, which checks the starts: an apostrophe, a decimal374// number, snake case, a decomposed "é", Arabic, Thai, Japanese, a family375// emoji). About 7.5 KB of table and 5 KB of code in every376// ui program, which `ui`'s maps and `TextField`'s word moves reach.377// `Layout::graphemes_in_order` gives each grapheme drawn, its bytes and378// its left and right edges, in the text's order, for those maps.379//380// **F14 question 11A as built** (2026-10-20): `Direction::AutoRightToLeft`381// reads a paragraph by its first strong character as Auto does, but right382// to left without one (`bidi_levels`' `fallback`, HL1), an empty text and383// an empty first paragraph too, as an element reading right to left does384// with dir=auto: "-5 (2/3)" shows "(2/3) 5-", "›" its mirror. Tested in385// `tests.alloy`.386//387// **F14c as built** (2026-10-20; decisions/F14.md, question388// 10A): the system's fallback faces (`fallback.alloy`'s `system_family`)389// and the files `fetch_font` reads natively are mapped through std::fs's390// `KeptMappedFile` (`FaceBytes::Mapped`), not read whole, so only the391// parts touched (directory, cmap, the glyphs drawn) are resident and the392// system may drop them again; they stay mapped as long as the program393// runs, as their faces do (question 13). Where nothing maps (the web,394// WASI, `alloyc run`) the file is read whole as before. In the glyph395// cache's long run (`tests/glyph_memory.alloy`, 24 scripts and emoji)396// fontconfig gives 18 files, 30.7 MB (Noto Sans CJK's collection 19 MB),397// of which 8.9 MB are resident at the end; read whole, the run was about398// 25 MB larger (73.5 MB against 48.6 MB). About 4 KB natively and 2.4 KB399// of wasm in every program drawing text.400//401// **R6d as built** (2026-10-22; REFOCUS.md, questions 5A, 6B402// and 7B):403// - Out to pkg::alloy::text_scripts: the eight complex shapers, the404// syllable machines, HarfBuzz's language tags, the scripts' Unicode405// tables (`unicode/generate.alloy` writes them into406// `../text_scripts/unicode/script_tables.alloy` beside `tables.alloy`),407// bidi, and Thai's, Lao's, Khmer's and Myanmar's breaks between408// graphemes. Text keeps hooks: `ScriptHooks` (the shaper for a run, a409// tag's language systems, mirrors, a paragraph's levels, a line's410// order), each plan's `ComplexShaper` object, which `shapers.alloy`411// calls at the shaper's points; `Fonts::install_scripts`.412// - Out to pkg::alloy::text_fonts: CFF and CFF2, variations, COLR,413// CBDT, sbix, PNG, `fallback.alloy` and `system/`, `sheets.alloy`.414// Text keeps `FontFormats` (a struct of functions each face read after415// keeps: reading the tables, instances, varied advances and deltas,416// color glyphs), the `Outlines` interface CFF's glyph table is, and417// the `FontFallback` object `fallback` and `fetch` call;418// `Fonts::install_formats`.419// - The bundled font: Inter Regular with HarfBuzz's default features and420// `tnum` (`fonts/subset.sh`, 75,544 bytes; the tests' fuller regular421// and bold in `tests/fonts`). A weight of 600 or more on a lighter422// face with no weight axis gets an instance with `Face.embolden` (em /423// 24): outlines thickened as FreeType's FT_Outline_EmboldenXY, moved424// up and right by half as HarfBuzz's synthetic bold, advances other425// than 0 and extents wider by the strength. `FontStore.instances` is426// keyed by `InstanceKey`.427// - The counter 1,214,688 bytes natively and 710,130 of wasm, from428// 1,633,488 and 1,087,148; the measures in REFOCUS.md.429430import std::string;431import std::vector;432import std::option;433import std::macros;434import std::math;435import std::map;436import std::sync;437import std::process;438439import font::reader;440import font::face;441import font::outline;442import font::raster;443import shaping::shaper;444import shaping::shapers;445import shaping::plan;446import shaping::tags;447import unicode::tables;448import unicode::properties;449import unicode::graphemes;450import unicode::words;451import paragraphs;452453const INTER_REGULAR = #read_file("fonts/Inter-Regular.ttf");454455/* --- Fonts --- */456457// The faces a program lays text out with, in families: the bundled Inter458// (regular, bold made by thickening it) first, then the fonts a program adds and those459// fallback finds for characters a style's faces lack, once460// pkg::alloy::text_fonts is installed. Laying text out adds faces (a461// variable face's instances at the weights and sizes styles ask for),462// so they are kept behind a lock, reached through a `&Fonts`.463exp type Fonts = struct {464 store: Mutex<FontStore>,465};466467exp type FontStore = struct {468 // each face boxed, so that it never moves: a reference to one lasts469 // as long as the fonts470 exp faces: Vector<*Face>,471 exp families: Vector<Vector<u32>>, // each family's faces472 // a variable face's instances and faces made bold473 instances: Map<InstanceKey, u32>,474 // whether fallback may ask the system for its fonts (`Fonts::create`)475 exp system: bool,476 // what text_scripts and text_fonts install477 exp scripts: Option<ScriptHooks>,478 exp formats: Option<FontFormats>,479 exp fallback: Option<*var FontFallback>,480 // shaping plans, each boxed so that it never moves481 plans: Vector<*Plan>,482};483484// A family of faces, of different weights.485exp type Family = struct {486 exp index: u32,487};488489// Weights, as OS/2's usWeightClass gives them.490exp const REGULAR: u32 = 400;491exp const SEMIBOLD: u32 = 600;492exp const BOLD: u32 = 700;493494// What pkg::alloy::text_scripts installs on the fonts (`install_scripts`):495// the complex shapers, the language systems of BCP 47 tags, and bidi.496// Without it every run is shaped by the default shaper and laid out left497// to right.498exp type ScriptHooks = struct {499 // the complex shaper for a run of the script in a face whose GSUB was500 // read for the tag, none for the default shaper501 exp shaper: (Script, u32) -> Option<*var ComplexShaper>,502 // the language systems the BCP 47 tag names, in the order a face's503 // are searched504 exp languages: (&[u8]) -> Tags,505 // the character mirroring the code point (Bidi_Mirroring_Glyph)506 exp mirror: (u32) -> Option<u32>,507 // the levels of the paragraph's bytes from start to end (UAX #9)508 exp levels: (&[u8], u64, u64, Direction) -> ParagraphLevels,509 // a line's glyphs in visual order (L1, L2): from the code points510 // their clusters start with and their levels, and the paragraph's511 // level, the levels L1 resets and the glyphs' order from the left512 exp reorder: (&[u32], &var [u8], u8, &var [u64]),513};514515// What pkg::alloy::text_fonts installs for characters a style's faces516// lack: faces from the system's fonts, and from files a program fetches.517exp interface FontFallback {518 // a face covering the grapheme cluster from start to end that the519 // face `primary` lacks520 fn face(521 self: &var,522 store: &var FontStore,523 text: &[u8],524 start: u64,525 end: u64,526 wanted: &Wanted,527 primary: u32528 ) -> Option<u32>;529 // starts fetching a font file served beside the program530 fn fetch(self: &var, store: &var FontStore, path: &[u8]);531}532533// What a run asks fallback for: its script, language, weight and size,534// and whether it is in emoji presentation.535exp type Wanted = struct {536 exp script: Script,537 exp language: &[u8],538 exp weight: u32,539 exp size: f32,540 exp emoji: bool,541};542543exp fn Fonts::create() -> Fonts => Fonts::made(true);544545// The bundled family alone, fallback never asking the system: the same546// faces on every machine, for tests and programs carrying the fonts547// they need (`add`, and text_fonts' `fetch`).548exp fn Fonts::bundled() -> Fonts => Fonts::made(false);549550fn Fonts::made(system: bool) -> Fonts {551 var store = FontStore {552 .faces = Vector<*Face>::empty(),553 .families = Vector<Vector<u32>>::empty(),554 .instances = Map<InstanceKey, u32>::empty(),555 .system = system,556 .scripts = ::None,557 .formats = ::None,558 .fallback = ::None,559 .plans = Vector<*Plan>::empty()560 };561 var inter = Vector<u32>::empty();562 if (Face::read(FaceBytes::Static(&INTER_REGULAR), 0, ::None) is ::Some |move face|) {563 inter.push(store.keep(move face));564 }565 store.families.push(move inter);566 return Fonts { .store = Mutex<FontStore>::from(move store) };567}568569// Installs the complex shapers and bidi (pkg::alloy::text_scripts' `install_into`),570// for text laid out from here on.571exp fn install_scripts(self fonts: &var Fonts, hooks: ScriptHooks) {572 var guard = fonts.store.lock();573 defer guard.dispose();574 const store = &var guard.value();575 store.scripts = ::Some(hooks);576 store.plans.clear(); // made without them577}578579// Installs the font formats and fallback (pkg::alloy::text_fonts'580// `install_into`), for the fonts added from here on.581exp fn install_formats(self fonts: &var Fonts, formats: FontFormats, fallback: *var FontFallback) {582 var guard = fonts.store.lock();583 defer guard.dispose();584 const store = &var guard.value();585 store.formats = ::Some(formats);586 store.fallback = ::Some(move fallback);587}588589// What text_scripts installed, if it was.590exp fn scripts(self fonts: &Fonts) -> Option<ScriptHooks> {591 var guard = fonts.store.lock();592 defer guard.dispose();593 return guard.value().scripts;594}595596// The face of the font's bytes (a collection's by index), read with the597// formats installed; None when it does not read.598exp fn read_face(self store: &FontStore, bytes: FaceBytes, index: u32) -> Option<Face> {599 return Face::read(move bytes, index, store.formats);600}601602// Keeps the face, giving its index.603exp fn keep(self store: &var FontStore, face: Face) -> u32 {604 store.faces.push(new face);605 return (store.faces.length() - 1) to u32;606}607608// Keeps the face as a family of its own, giving the family's index.609exp fn family_of(self store: &var FontStore, face: Face) -> u32 {610 var family = Vector<u32>::empty();611 family.push(store.keep(move face));612 store.families.push(move family);613 return (store.families.length() - 1) to u32;614}615616// A face covering the grapheme cluster from start to end that the face617// `primary` lacks, from text_fonts' fallback.618exp fn fallback(619 self fonts: &Fonts,620 text: &[u8],621 start: u64,622 end: u64,623 wanted: &Wanted,624 primary: u32625) -> Option<u32> {626 var guard = fonts.store.lock();627 defer guard.dispose();628 const store = &var guard.value();629 var taken = move store.fallback;630 store.fallback = ::None;631 var found: Option<u32> = ::None;632 if (taken is ::Some |&var f|) {633 found = f.face(&var store, &text, start, end, &wanted, primary);634 }635 store.fallback = move taken;636 return found;637}638639// Starts fetching a font file served beside the program, for fallback640// once pkg::alloy::text_fonts is installed (on the web, which gives a641// page no system fonts): characters it covers lay out in it once it has642// arrived, which pkg::alloy::window tells as `Event::FontsArrived`, for643// laying text out again. Elsewhere the file is read now.644exp fn fetch(self fonts: &Fonts, path: &[u8]) {645 var guard = fonts.store.lock();646 defer guard.dispose();647 const store = &var guard.value();648 var taken = move store.fallback;649 store.fallback = ::None;650 if (taken is ::Some |&var f|) {651 f.fetch(&var store, &path);652 }653 store.fallback = move taken;654}655656// The plan for shaping runs of the script, language, direction and657// features in the face, made the first time it is asked for.658exp fn plan(659 self fonts: &Fonts,660 face: u32,661 script: Script,662 language: &[u8],663 rtl: bool,664 features: &[Feature]665) -> &Plan {666 var guard = fonts.store.lock();667 defer guard.dispose();668 const store = &var guard.value();669 for (store.plans.view()) |&p| {670 if (671 p.face == face672 && p.script to u8 == script to u8673 && p.rtl == rtl674 && p.language.view() == language675 && same_features(&p.settings.view(), &features)676 ) {677 return &p;678 }679 }680 const f = &store.faces.get(face to u64);681 store.plans.push(new Plan::compile(682 face,683 &f,684 script,685 &language,686 rtl,687 &features,688 &store.scripts689 ));690 return &store.plans.last();691}692693fn same_features(a: &[Feature], b: &[Feature]) -> bool {694 if (a.length() != b.length()) {695 return false;696 }697 for (a, b) |&x, &y| {698 if (x.tag != y.tag || x.on != y.on) {699 return false;700 }701 }702 return true;703}704705// The bundled family, Inter.706exp fn default(self fonts: &Fonts) -> Family {707 return Family { .index = 0 };708}709710// A font's face (a `.ttf` or `.otf` file's bytes, TrueType, CFF or CFF2711// outlines, or a collection's first face) as a family of its own: a712// variable face's named instances are the family's faces. None when it713// does not read.714exp fn add(self fonts: &var Fonts, bytes: Vector<u8>) -> Option<Family> {715 var guard = fonts.store.lock();716 defer guard.dispose();717 const store = &var guard.value();718 var family = Vector<u32>::empty();719 if (!store.add_faces(&var family, move bytes)) {720 return ::None;721 }722 store.families.push(move family);723 return ::Some(Family { .index = store.families.length() to u32 - 1 });724}725726// Adds a face of another weight to the family (a variable face's named727// instances); false when it does not read.728exp fn add_to(self fonts: &var Fonts, family: Family, bytes: Vector<u8>) -> bool {729 var guard = fonts.store.lock();730 defer guard.dispose();731 const store = &var guard.value();732 var faces = Vector<u32>::empty();733 if (!store.add_faces(&var faces, move bytes)) {734 return false;735 }736 store.families.get_var(family.index to u64).append(&faces.view());737 return true;738}739740// Keeps the font's first face and puts in `family` the faces it gives:741// a variable face's named instances, or the face itself.742fn add_faces(self store: &var FontStore, family: &var Vector<u32>, bytes: Vector<u8>) -> bool {743 var read = if (744 store.read_face(FaceBytes::Owned(move bytes), 0) is ::Some |move f|745 ) move f else {746 return false;747 };748 const base = store.keep(move read);749 const face = &store.faces.get(base to u64);750 const formats = if (face.formats is ::Some |f| && face.variable()) f else {751 family.push(base);752 return true;753 };754 const named = (formats.named_instances)(&face);755 if (named.length() == 0) {756 family.push(base);757 return true;758 }759 for (named.view()) |&instance| {760 var at = (formats.at)(&face, &instance.values.view());761 family.push(store.keep(move at));762 }763 return true;764}765766// How many faces the family has.767exp fn family_size(self fonts: &Fonts, family: Family) -> u64 {768 var guard = fonts.store.lock();769 defer guard.dispose();770 return guard.value().families.get(family.index to u64).length();771}772773// The PostScript name of the face at the index (a placed glyph's), as774// its font names it.775exp fn face_name(self fonts: &Fonts, face: u32) -> String => fonts.face(face).postscript_name();776777// The face at the index.778exp fn face(self fonts: &Fonts, index: u32) -> &Face {779 var guard = fonts.store.lock();780 defer guard.dispose();781 return &guard.value().faces.get(index to u64);782}783784// The family's face nearest the weight; a variable one at the weight785// and, with an optical size axis, the size in pixels.786exp fn face_for(self fonts: &Fonts, family: Family, weight: u32, size: f32) -> u32 {787 var guard = fonts.store.lock();788 defer guard.dispose();789 return guard.value().face_for(family, weight, size);790}791792exp fn face_for(self store: &var FontStore, family: Family, weight: u32, size: f32) -> u32 {793 var best: u32 = 0;794 var distance: u32 = 0xFFFFFFFF;795 for (store.families.get(family.index to u64).view()) |f| {796 const w = store.faces.get(f to u64).weight;797 const d = if (w > weight) w - weight else weight - w;798 if (d < distance) {799 distance = d;800 best = f;801 }802 }803 const face = &store.faces.get(best to u64);804 const wght = face.axis(&"wght");805 const opsz = face.axis(&"opsz");806 // a weight of 600 or more from a lighter face with no weight axis807 // made bold, as browsers do808 const bold = wght is ::None && weight >= 600 && face.weight < 600;809 const varies = face.formats is ::Some && (wght is ::Some || opsz is ::Some);810 if (!bold && !varies) {811 return best;812 }813 const key = InstanceKey {814 .face = best,815 .weight = if (wght is ::Some) weight else 0,816 .size = if (opsz is ::Some) clamp(round(size), 0.0, 65535.0) to u32 else 0,817 .bold = bold818 };819 if (store.instances.try_get(&key) is ::Some |&found|) {820 return found;821 }822 const values = face.values_at(weight, key.size);823 var at = if (varies && face.formats is ::Some |formats|) (formats.at)(824 &face,825 &values.view()826 ) else face.shared();827 if (bold) {828 at.embolden = round(face.units_per_em / 24.0);829 }830 const index = store.keep(move at);831 store.instances.insert(key, index);832 return index;833}834835// A variable face's values on its axes at the weight and optical size.836fn values_at(self face: &Face, weight: u32, size: u32) -> Vector<f32> {837 var values = copy face.values;838 if (values.length() == 0) {839 for (face.axes.view()) |&a| {840 values.push(a.default);841 }842 }843 if (face.axis(&"wght") is ::Some |k|) {844 values.get_var(k) = weight to f32;845 }846 if (face.axis(&"opsz") is ::Some |k|) {847 values.get_var(k) = size to f32;848 }849 return move values;850}851852// An instance of a face: a variable one's at a weight and optical size,853// or a face made bold.854type InstanceKey = struct {855 face: u32,856 weight: u32,857 size: u32,858 bold: bool,859};860861// A glyph's coverage at the size in pixels, moved right by `shift`, a862// fraction of a pixel.863exp type GlyphMask = struct {864 exp width: u32,865 exp height: u32,866 exp left: i32, // from the pen, on the baseline, to the mask's top left867 exp top: i32,868 exp coverage: Vector<u8>, // a byte a pixel, row after row869};870871exp fn glyph_mask(self fonts: &Fonts, face: u32, glyph: u32, size: f32, shift: f32) -> GlyphMask {872 const f = &fonts.face(face);873 return rasterize(&f.outline(glyph), size / f.units_per_em, shift);874}875876// A color glyph's pixels (COLR's layers or paints, a CBDT or sbix877// bitmap): premultiplied RGBA, four bytes a pixel, placed as a mask is.878exp type ColorMask = struct {879 exp width: u32,880 exp height: u32,881 exp left: i32,882 exp top: i32,883 exp pixels: Vector<u8>,884 // whether it shows the text's color (a palette entry 0xFFFF), so is885 // drawn anew for text of another color886 exp foreground: bool,887};888889// A glyph's pixels: an outline's coverage, or a color glyph's colors.890exp type GlyphImage = enum {891 Coverage: GlyphMask,892 Color: ColorMask,893};894895// Whether the face draws the glyph in color (COLR, CBDT or sbix), whole896// pixels apart rather than at quarter-pixel shifts.897exp fn is_color(self fonts: &Fonts, face: u32, glyph: u32) -> bool {898 const f = &fonts.face(face);899 if (f.formats is ::Some |formats| && f.colors.any()) {900 return (formats.is_color)(&f, glyph);901 }902 return false;903}904905// The glyph's pixels at the size in pixels, moved right by `shift`, a906// fraction of a pixel (an outline's): a color glyph's in its own colors,907// whatever the text's but where its palette takes the `foreground`, the908// text's color.909exp fn glyph_image(910 self fonts: &Fonts,911 face: u32,912 glyph: u32,913 size: f32,914 shift: f32,915 foreground: TextColor916) -> GlyphImage {917 const f = &fonts.face(face);918 if (f.formats is ::Some |formats| && f.colors.any()) {919 if ((formats.color_glyph)(&f, glyph, size, shift, &foreground) is ::Some |move c|) {920 return ::Color(move c);921 }922 }923 return ::Coverage(rasterize(&f.outline(glyph), size / f.units_per_em, shift));924}925926/* --- Styles --- */927928// A color, in sRGB with straight alpha, for spans drawn in another color929// than the text's.930exp type TextColor = struct {931 exp r: f32,932 exp g: f32,933 exp b: f32,934 exp a: f32,935};936937exp fn TextColor::rgb(r: f32, g: f32, b: f32) -> TextColor {938 return TextColor { .r = r, .g = g, .b = b, .a = 1.0 };939}940941// An OpenType feature turned on or off: `Feature::on(&"tnum")`.942exp type Feature = struct {943 exp tag: u32,944 exp on: bool,945};946947exp fn Feature::on(name: &[u8]) -> Feature {948 return Feature { .tag = tag(&name), .on = true };949}950951exp fn Feature::off(name: &[u8]) -> Feature {952 return Feature { .tag = tag(&name), .on = false };953}954955// The direction a paragraph reads in: Auto takes its first strong956// character's (UAX #9's P2 and P3), left to right without one;957// AutoRightToLeft too, but right to left without one, as text in an958// element reading right to left does with dir=auto.959exp type Direction = enum {960 Auto,961 AutoRightToLeft,962 LeftToRight,963 RightToLeft,964};965966exp type TextStyle = struct {967 exp family: Family,968 exp size: f32, // pixels969 exp weight: u32, // REGULAR, BOLD or between970 exp line_height: f32, // a multiple of the size, or 0 for the face's own spacing971 exp color: Option<TextColor>, // None: the color the text is drawn in972 exp underline: bool,973 exp strikethrough: bool,974 exp features: Vector<Feature>,975 // a BCP 47 tag, as "ar" or "zh-Hant", none for the user's: the976 // language fallback asks fonts for977 exp language: String,978 // the paragraphs' direction, by the style of their first byte979 exp direction: Direction,980};981982exp fn TextStyle::of(family: Family, size: f32) -> TextStyle {983 return TextStyle {984 .family = family,985 .size = size,986 .weight = REGULAR,987 .line_height = 0.0,988 .color = ::None,989 .underline = false,990 .strikethrough = false,991 .features = Vector<Feature>::empty(),992 .language = String::empty(),993 .direction = Direction::Auto994 };995}996997// A range of the text, in bytes, in its own style.998exp type Span = struct {999 exp start: u64,1000 exp end: u64,1001 exp style: TextStyle,1002};10031004// Where lines go across the layout: Start and End on each paragraph's1005// own side (the left left to right, the right right to left), Left and1006// Right on those whatever the paragraph: a box's start, as `ui` aligns a1007// text by its element's direction.1008exp type Align = enum {1009 Start,1010 Center,1011 End,1012 Left,1013 Right,1014};10151016/* --- Layout --- */10171018// A glyph placed: its face's index in the fonts, its pen position from1019// the layout's top left, y on the baseline, and the byte offset of the1020// text it shows; a line's glyphs are in visual order, from the left.1021exp type PlacedGlyph = struct {1022 exp face: u32,1023 exp glyph: u32,1024 exp size: f32,1025 exp x: f32,1026 exp y: f32,1027 exp cluster: u64,1028 exp color: Option<TextColor>,1029};10301031// A line: its bytes, glyphs and box (spaces hanging past its end left1032// out); `baseline` is from the layout's top; its paragraph's direction,1033// LeftToRight or RightToLeft.1034exp type Line = struct {1035 exp start: u64,1036 exp end: u64,1037 exp glyphs: [u64 : 2],1038 exp top: f32,1039 exp baseline: f32,1040 exp height: f32,1041 exp x: f32,1042 exp width: f32,1043 exp direction: Direction,1044 exp graphemes: [u64 : 2], // its graphemes in the layout's1045};10461047// A rectangle, in the layout's coordinates.1048exp type TextBox = struct {1049 exp x: f32,1050 exp y: f32,1051 exp width: f32,1052 exp height: f32,1053};10541055// An underline or strikethrough.1056exp type Decoration = struct {1057 exp box: TextBox,1058 exp color: Option<TextColor>,1059};10601061// A grapheme cluster placed on its line: its bytes (a layout's text1062// stays under 4 GiB), and the edges of its share of its glyphs' advance1063// where a caret before and after it is drawn: its left and right, or its1064// right and left right to left. A line's are in visual order, from the1065// left.1066exp type Grapheme = struct {1067 exp at: u32,1068 exp length: u32,1069 exp leading: f32,1070 exp trailing: f32,1071};10721073exp fn start(self g: &Grapheme) -> u64 => g.at to u64;1074exp fn end(self g: &Grapheme) -> u64 => g.at to u64 + g.length to u64;1075exp fn left(self g: &Grapheme) -> f32 => if (g.leading < g.trailing) g.leading else g.trailing;1076exp fn right(self g: &Grapheme) -> f32 => if (g.leading < g.trailing) g.trailing else g.leading;10771078exp type Layout = struct {1079 exp text: String,1080 exp glyphs: Vector<PlacedGlyph>,1081 exp lines: Vector<Line>,1082 exp decorations: Vector<Decoration>,1083 exp width: f32,1084 exp height: f32,1085 exp graphemes: Vector<Grapheme>,1086};10871088// The text in one style, broken into lines no wider than `width` (any1089// width at all with `f32` infinity or 0), aligned at the start.1090exp fn Layout::create(fonts: &Fonts, text: &[u8], style: &TextStyle, width: f32) -> Layout {1091 const spans: [Span : 1] = [Span { .start = 0, .end = text.length(), .style = copy style }];1092 return lay_out(&fonts, &text, &spans, width, Align::Start, false);1093}10941095// The text in spans of styles, which cover it in order (a byte no span1096// covers takes the first span's style).1097exp fn Layout::spans(1098 fonts: &Fonts,1099 text: &[u8],1100 spans: &[Span],1101 width: f32,1102 align: Align1103) -> Layout {1104 if (spans.length() == 0) {1105 panic "pkg::alloy::text: a layout needs a span";1106 }1107 return lay_out(&fonts, &text, &spans, width, align, false);1108}11091110// The text in one style broken at `width` as `create` breaks it, but as1111// wide as its widest line: one line as wide as the text when it fits.1112exp fn Layout::fitted(fonts: &Fonts, text: &[u8], style: &TextStyle, width: f32) -> Layout {1113 return Layout::fitted(&fonts, &text, &style, width, Align::Start);1114}11151116// `fitted`, its lines aligned so within its widest.1117exp fn Layout::fitted(1118 fonts: &Fonts,1119 text: &[u8],1120 style: &TextStyle,1121 width: f32,1122 align: Align1123) -> Layout {1124 const spans: [Span : 1] = [Span { .start = 0, .end = text.length(), .style = copy style }];1125 return lay_out(&fonts, &text, &spans, width, align, true);1126}11271128// The byte offset nearest the point, on a grapheme boundary: of the1129// carets drawn on the line at the point's height, the nearest.1130exp fn hit(self layout: &Layout, x: f32, y: f32) -> u64 {1131 if (layout.lines.length() == 0) {1132 return 0;1133 }1134 var k = layout.lines.length() - 1;1135 for (layout.lines.view(), [..layout.lines.length()]) |&l, index| {1136 if (y < l.top + l.height) {1137 k = index;1138 break;1139 }1140 }1141 const line = &layout.lines.get(k);1142 var best = line.start;1143 var distance = absolute(layout.caret_x(k, line.start) - x);1144 for (layout.line_graphemes(k)) |&g| {1145 const d = absolute(g.trailing - x);1146 if (d < distance) {1147 distance = d;1148 best = g.end();1149 }1150 }1151 return best;1152}11531154fn absolute(x: f32) -> f32 => if (x < 0.0) -x else x;11551156// The caret's box at the byte offset: on the line it starts, one pixel1157// wide, after the character before it (on that character's side where1158// the direction changes: the side of the run the text was typed into),1159// or before the line's first one at its start.1160exp fn caret(self layout: &Layout, at: u64) -> TextBox {1161 if (layout.lines.length() == 0) {1162 return TextBox { .x = 0.0, .y = 0.0, .width = 1.0, .height = 0.0 };1163 }1164 const k = layout.line_of(at);1165 const line = &layout.lines.get(k);1166 return TextBox {1167 .x = layout.caret_x(k, at),1168 .y = line.top,1169 .width = 1.0,1170 .height = line.height1171 };1172}11731174// The boxes covering the bytes from start to end: one a line, or more1175// on a line where the range runs on in another direction.1176exp fn selection(self layout: &Layout, start: u64, end: u64) -> Vector<TextBox> {1177 var out = Vector<TextBox>::empty();1178 if (start >= end) {1179 return move out;1180 }1181 for (layout.lines.view(), [..layout.lines.length()]) |&line, k| {1182 if (line.end < start || line.start >= end) {1183 continue;1184 }1185 var open = false; // whether the last box goes on1186 for (layout.line_graphemes(k)) |&g| {1187 if (g.start() >= end || g.end() <= start) {1188 open = false;1189 continue;1190 }1191 if (open) {1192 const last = &var out.get_var(out.length() - 1);1193 last.width = g.right() - last.x;1194 } else {1195 out.push(TextBox {1196 .x = g.left(),1197 .y = line.top,1198 .width = g.right() - g.left(),1199 .height = line.height1200 });1201 open = true;1202 }1203 }1204 }1205 return move out;1206}12071208// The caret position drawn next right of the offset's1209// (decisions/F10.md, question 3): on its line, or past the line's right1210// end the next line's leftmost (the previous line's right to left).1211exp fn next_position(self layout: &Layout, at: u64) -> u64 {1212 if (layout.lines.length() == 0) {1213 return at;1214 }1215 const k = layout.line_of(at);1216 const x = layout.caret_x(k, at);1217 if (layout.nearest(k, x, at, true) is ::Some |next|) {1218 return next;1219 }1220 const rtl = layout.lines.get(k).direction is ::RightToLeft;1221 if (rtl && k > 0) {1222 return layout.outermost(k - 1, at, false).unwrap_or(at);1223 }1224 if (!rtl && k + 1 < layout.lines.length()) {1225 return layout.outermost(k + 1, at, false).unwrap_or(at);1226 }1227 return at;1228}12291230// The caret position drawn next left of the offset's: on its line, or1231// past the line's left end the previous line's rightmost (the next1232// line's right to left).1233exp fn previous_position(self layout: &Layout, at: u64) -> u64 {1234 if (layout.lines.length() == 0) {1235 return at;1236 }1237 const k = layout.line_of(at);1238 const x = layout.caret_x(k, at);1239 if (layout.nearest(k, x, at, false) is ::Some |next|) {1240 return next;1241 }1242 const rtl = layout.lines.get(k).direction is ::RightToLeft;1243 if (!rtl && k > 0) {1244 return layout.outermost(k - 1, at, true).unwrap_or(at);1245 }1246 if (rtl && k + 1 < layout.lines.length()) {1247 return layout.outermost(k + 1, at, true).unwrap_or(at);1248 }1249 return at;1250}12511252// The grapheme boundary after the offset in the text, or the text's end:1253// the next character for Delete and screen readers, whatever its side.1254exp fn next_logical(self layout: &Layout, at: u64) -> u64 {1255 return next_grapheme(&layout.text.view(), at);1256}12571258// The grapheme boundary before the offset in the text, or 0.1259exp fn previous_logical(self layout: &Layout, at: u64) -> u64 {1260 // scanned from the start of the last line starting before it, a1261 // boundary, rather than from the text's start1262 var from: u64 = 0;1263 for (layout.lines.view()) |&line| {1264 if (line.start < at) {1265 from = line.start;1266 }1267 }1268 return previous_grapheme_from(&layout.text.view(), from, at);1269}12701271// The start of the line holding the offset, for a Home key.1272exp fn line_start(self layout: &Layout, at: u64) -> u64 {1273 if (layout.lines.length() == 0) {1274 return 0;1275 }1276 return layout.lines.get(layout.line_of(at)).start;1277}12781279// The end of the line holding the offset, for an End key: before the1280// spaces a wrapped line hangs past its width.1281exp fn line_end(self layout: &Layout, at: u64) -> u64 {1282 if (layout.lines.length() == 0) {1283 return 0;1284 }1285 const k = layout.line_of(at);1286 const line = &layout.lines.get(k);1287 var end = line.end;1288 if (k + 1 < layout.lines.length() && layout.lines.get(k + 1).start == line.end) {1289 while (end > line.start && layout.text.get(end - 1) == ' ') {1290 end -= 1;1291 }1292 }1293 return end;1294}12951296// A grapheme as a layout draws it: its bytes in the text, and its left1297// and right on its line.1298exp type PlacedGrapheme = struct {1299 exp start: u32,1300 exp end: u32,1301 exp left: f32,1302 exp right: f32,1303};13041305// The layout's graphemes in the text's order, as screen readers walk1306// them; what draws nothing, a line's break, is left out.1307exp fn graphemes_in_order(self layout: &Layout) -> Vector<PlacedGrapheme> {1308 // each grapheme's index plus one at the byte it starts at1309 var starting = Vector<u32>::filled(0, layout.text.length());1310 for (layout.graphemes.view(), [..layout.graphemes.length()]) |&g, k| {1311 starting.get_var(g.start()) = (k + 1) to u32;1312 }1313 var out = Vector<PlacedGrapheme>::with_capacity(layout.graphemes.length());1314 for (starting.view()) |k| {1315 if (k > 0) {1316 const g = &layout.graphemes.get((k - 1) to u64);1317 out.push(PlacedGrapheme {1318 .start = g.at,1319 .end = g.at + g.length,1320 .left = g.left(),1321 .right = g.right()1322 });1323 }1324 }1325 return move out;1326}13271328// The line holding the offset: a line's end is the next line's start.1329exp fn line_of(self layout: &Layout, at: u64) -> u64 {1330 for ([..layout.lines.length()]) |k| {1331 const line = &layout.lines.get(k);1332 if (at < line.end || (at == line.end && k + 1 == layout.lines.length())) {1333 return k;1334 }1335 if (at == line.end && layout.lines.get(k + 1).start > at) {1336 return k; // a hard break's line keeps its end1337 }1338 }1339 return layout.lines.length() - 1;1340}13411342// The line's graphemes, from the left.1343exp fn line_graphemes(self layout: &Layout, k: u64) -> &[Grapheme] {1344 const range = layout.lines.get(k).graphemes;1345 return &layout.graphemes.view()[range[0]..range[1]];1346}13471348// Where the caret at the offset is drawn on the line: after the1349// grapheme ending there, or at the line's start before its first.1350exp fn caret_x(self layout: &Layout, k: u64, at: u64) -> f32 {1351 const line = &layout.lines.get(k);1352 const graphemes = &layout.line_graphemes(k);1353 if (at > line.start) {1354 for (graphemes) |&g| {1355 if (g.start() < at && at <= g.end()) {1356 return g.trailing;1357 }1358 }1359 }1360 for (graphemes) |&g| {1361 if (g.start() == line.start) {1362 return g.leading;1363 }1364 }1365 return line.x;1366}13671368// Of the carets on the line in visual order, by their x then their1369// offsets (so that each of two drawn together is reached), the next1370// right (or left) of the one at `x` and `at`; a wrapped line's end left1371// out, as it is the next line's start.1372fn nearest(self layout: &Layout, k: u64, x: f32, at: u64, right: bool) -> Option<u64> {1373 const line = &layout.lines.get(k);1374 const wrapped = k + 1 < layout.lines.length() && layout.lines.get(k + 1).start == line.end;1375 var found: Option<u64> = ::None;1376 var best: f32 = 0.0;1377 var candidate = line.start;1378 var candidate_x = layout.caret_x(k, line.start);1379 const graphemes = &layout.line_graphemes(k);1380 for ([..graphemes.length() + 1]) |j| {1381 if (j > 0) {1382 const g = &graphemes[j - 1];1383 candidate = g.end();1384 candidate_x = g.trailing;1385 }1386 if (candidate == at || (wrapped && candidate == line.end)) {1387 continue;1388 }1389 if (!before(x, at, candidate_x, candidate, right)) {1390 continue;1391 }1392 if (found is ::None || before(candidate_x, candidate, best, found.unwrap_or(0), right)) {1393 found = ::Some(candidate);1394 best = candidate_x;1395 }1396 }1397 return found;1398}13991400// Whether the caret at `b_x` and offset `b` comes after (right of, or1401// left of with `!right`) the one at `a_x` and `a`, in visual order.1402fn before(a_x: f32, a: u64, b_x: f32, b: u64, right: bool) -> bool {1403 if (absolute(a_x - b_x) <= 0.01) {1404 return if (right) b > a else b < a;1405 }1406 return if (right) b_x > a_x else b_x < a_x;1407}14081409// The line's leftmost caret (or rightmost) at another offset than `at`.1410fn outermost(self layout: &Layout, k: u64, at: u64, right: bool) -> Option<u64> {1411 const x: f32 = if (right) 1000000000.0 else -1000000000.0;1412 return layout.nearest(k, x, at, !right);1413}14141415// How many grapheme clusters the text has (UAX #29), as a person counts1416// its characters: "é" written as two code points is one, and so is a1417// family emoji.1418exp fn grapheme_count(text: &[u8]) -> u64 {1419 var count: u64 = 0;1420 var at: u64 = 0;1421 while (at < text.length()) {1422 at = next_grapheme(&text, at);1423 count += 1;1424 }1425 return count;1426}14271428// Where the text's grapheme clusters end (UAX #29), one offset a cluster1429// in order, the last the text's length: none for empty text.1430exp fn grapheme_ends(text: &[u8]) -> Vector<u64> {1431 var ends = Vector<u64>::empty();1432 var at: u64 = 0;1433 while (at < text.length()) {1434 at = next_grapheme(&text, at);1435 ends.push(at);1436 }1437 return move ends;1438}14391440// Where the text's words start (UAX #29), in bytes: before each letter,1441// digit, ideograph or emoji that a word boundary comes before, a word1442// running on to the next one's start, the spaces after it included. A1443// run of Thai, Lao, Khmer or Myanmar is one word, as no dictionary splits1444// it.1445exp fn word_starts(text: &[u8]) -> Vector<u32> => find_word_starts(&text);14461447// The code point's simple case folding (Unicode's CaseFolding.txt, its C1448// and S mappings), by which text compares whatever its case: `A` is `a`,1449// `Σ` and `ς` are `σ`.1450exp fn fold_case(c: u32) -> u32 => fold(c);14511452// Whether the text starts with the prefix, code point by code point after1453// simple case folding: "Hamlet" starts with "ha".1454exp fn starts_folded(text: &[u8], prefix: &[u8]) -> bool {1455 var at: u64 = 0;1456 var k: u64 = 0;1457 while (k < prefix.length()) {1458 if (at >= text.length()) {1459 return false;1460 }1461 const a = decode(&text, at);1462 const b = decode(&prefix, k);1463 if (fold(a.c) != fold(b.c)) {1464 return false;1465 }1466 at += a.length;1467 k += b.length;1468 }1469 return true;1470}