Selaa lähdekoodia

Add fixed-point TrueType UI fonts

Replace the single 8x16 userland bitmap font with a fixed-point TrueType engine for ngui, the WM chrome and the browser.  Arimo regular/bold/italic/bold-italic and Liberation Mono subsets are packed under /ramfs/fonts; text fields, the terminal and the editor keep the 8x16 cell grid.

- ufont: 26.6 parser/rasterizer, Latin-1, malloc arena, glyph cache
- ngui/WM: measured text, font attach/detach, bitmap fallback
- browser: real CSS font sizes/weights/styles, mono, measured layout
- rootfs: copy the pack directly to high memory with INT 15h AH=87h; raise the cap to 512 KB
- tests: make test-font / test-font-asan; update AGENTS and docs
Johannes Zellner 1 viikko sitten
vanhempi
sitoutus
d962008231
42 muutettua tiedostoa jossa 2621 lisäystä ja 357 poistoa
  1. 2 0
      .gitignore
  2. 67 37
      AGENTS.md
  3. 67 27
      Makefile
  4. 207 120
      browser.c
  5. 51 7
      browser_html.c
  6. 3 1
      browser_html.h
  7. 16 14
      docs/boot.html
  8. 4 0
      docs/development.html
  9. 5 5
      docs/filesystems.html
  10. 16 1
      docs/graphics.html
  11. 2 2
      docs/index.html
  12. 3 3
      docs/memory.html
  13. 13 1
      docs/userland.html
  14. 73 0
      fonts/LICENSE-Apache-2.0
  15. 102 0
      fonts/LICENSE-OFL
  16. 40 0
      fonts/README
  17. BIN
      fonts/mono.ttf
  18. BIN
      fonts/sans-b.ttf
  19. BIN
      fonts/sans-bi.ttf
  20. BIN
      fonts/sans-i.ttf
  21. BIN
      fonts/sans.ttf
  22. 9 8
      gallery.c
  23. 5 8
      kernel.ld
  24. 238 31
      ngui.c
  25. 23 0
      ngui.h
  26. 4 1
      testdata/browser/demo.html
  27. 19 0
      tools/subset_fonts.sh
  28. 6 5
      ucmd_files.c
  29. 2 1
      ucmd_mines.c
  30. 5 2
      ucmd_solitaire.c
  31. 4 2
      ucmd_view.c
  32. 19 14
      ucmd_wm.c
  33. 303 0
      ufont.c
  34. 66 0
      ufont.h
  35. 126 0
      ufont_draw.c
  36. 31 0
      ufont_file.c
  37. 55 0
      ufont_internal.h
  38. 124 0
      ufont_test.c
  39. 785 0
      ufont_ttf.c
  40. 51 2
      uwm_lib.c
  41. 6 0
      uwm_lib.h
  42. 69 65
      vesa_stage.S

+ 2 - 0
.gitignore

@@ -13,6 +13,8 @@ tls_test
 img_test
 img_test_asan
 text_canvas_test
+ufont_test
+ufont_test_asan
 libc.a
 malloc_test
 mkrootfs

+ 67 - 37
AGENTS.md

@@ -75,6 +75,9 @@ make flash      # write the dual-boot image (legacy BIOS + UEFI) to a USB stick
 make test-usb   # headless USB mouse/keyboard regression tests (QEMU + python3)
 make test-images  # host image-decoder + blit tests (ASan variant: test-images-asan)
 make test-libc  # host stress test for the ring-3 malloc
+make test-font  # host TrueType parser/rasterizer specimen test
+make test-font-asan  # ASan/UBSan variant
+make fonts      # regenerate fonts/*.ttf with pyftsubset + system fonts
 make clean
 ```
 
@@ -114,17 +117,18 @@ make clean
 1. `boot.S` — 512-byte boot sector (FAT16 BPB). Loads contiguous kernel sectors
    to `0x7E00` (CHS for floppy, INT 13h AH=42h LBA for hard disk), jumps there.
 2. `vesa_stage.S` — real-mode VESA stage. Probes INT 15h E820 into `0x1000`,
-   reads the `NBROOT1` rootfs header at the boot sector's `pack_lba` field
-   and stages the gzip pack in the low gap at `0x60000..0x9FBFF`
-   (16 KB staging chunks at `0x3000`, `rep movsb`; no protected-mode BIOS
-   call), picks the best VBE mode (≥16 bpp, LFB, fits VRAM, ≤1280px), writes
-   mode info to `0x600` and the 12-dword `struct boot_info`
-   (magic/checksum/rsdp/flags/pack range) to `0x500`, enables A20, enters
-   protected mode, copies the pack to `PACK_HIGH_ADDR` (`0x900000`, above the
-   VGA-shadow reserve) and rewrites the boot-info pack address before jumping
-   to `kernel_entry` (`entry.S`, re-points ESP to the current stack top, then
-   `kernel_main`).  The copy lets the kernel image's BSS/boot stack extend
-   past `0x60000`.  The stage prints
+   enables A20, reads the `NBROOT1` rootfs header at the boot sector's
+   `pack_lba` field and copies the gzip pack directly to `PACK_HIGH_ADDR`
+   (`0x900000`, above the 8 MB VGA-shadow reserve) in 16 KB chunks through
+   the `0x3000` staging buffer with INT 15h AH=87h.  The BIOS block move uses
+   24-bit descriptor bases; `paging_prepare_cpu()` clears the CR4/EFER state
+   the X201's BIOS leaves behind.  The stage then picks the best VBE mode
+   (≥16 bpp, LFB, fits VRAM, ≤1280px), writes mode info to `0x600` and the
+   12-dword `struct boot_info` (magic/checksum/rsdp/flags/pack range) to
+   `0x500`, enters protected mode and jumps to `kernel_entry` (`entry.S`,
+   re-points ESP to the current stack top, then `kernel_main`).  The pack
+   never occupies the low gap, so the cap is `PACK_MAX` (512 KB) and the
+   kernel BSS/boot stack may extend past `0x60000`.  The stage prints
    `Loading rootfs [d=<drive> lba=<hex> e=<0|1> m=<C|L>]...`, then a dot
    after the header and one per 16 KB chunk, so a BIOS hang is localised.
    Drives below 0x80 use CHS (the same path the boot sector's kernel load
@@ -167,10 +171,10 @@ a Pentium 1 (and a Pentium II board without ACPI) on the UP path.
 | `0x6000`  | AP real/protected-mode trampoline (`ap_tramp.S`/`ap_tramp.ld`; SIPI vector 0x06, image ends below `0x6C00`) |
 | `0x6C00`  | AP trampoline real-mode stack top (grows down) |
 | `0x6F00`  | AP startup info block (CR3, stack top, C entry, CPU index) |
-| `0x60000` | Legacy rootfs pack staging (`vesa_stage.S`; compressed gzip data, up to `PACK_LOW_MAX` 0x3FBFF, ending below the EBDA at `0x9FC00`).  Temporary: copied to `0x900000` in protected mode before the kernel starts, so the kernel BSS/boot stack may extend past this address |
-| `_end`    | Kernel end (linker symbol; `kernel.ld` ASSERTs `__bss_start <= 0x60000` so the loaded image stays below the legacy staging gap, and `_end <= 0x90000` so the top of the staging gap and the EBDA stay untouched).  BSS and the boot stack may extend past `0x60000` |
+| `0x60000` | No longer a rootfs staging area: the legacy stage copies each 16 KB chunk straight to `0x900000`.  The kernel BSS/boot stack may use this range |
+| `_end`    | Kernel end (linker symbol; `kernel.ld` keeps `_end <= 0x90000` so the top of the low-memory gap and the EBDA stay untouched).  BSS and the boot stack may extend past `0x60000` |
 | (in-image) | Bootstrap/protected-mode stack: 8 KB `.stack` NOLOAD section, `__boot_stack_top`/`__boot_stack_bottom` (travels with the kernel) |
-| `0x900000`| Legacy boot-time rootfs pack after `vesa_stage.S` relocates it (reserved by `mm_init` until `ramfs_init` takes its copy, then freed; process stacks and kexec staging also start here) |
+| `0x900000`| Legacy boot-time rootfs pack written directly by `vesa_stage.S` (reserved by `mm_init` until `ramfs_init` takes its copy, then freed; process stacks and kexec staging also start here) |
 | `0x100000`| VGA shadow buffer (`VGA_SHADOW_BASE`, `vga.h`) |
 
 The legacy stage uses `0x3000..0x6FFF` as a 16 KB-chunk rootfs staging
@@ -179,8 +183,7 @@ buffer (`0x4000`) and AP trampoline (`0x6000`) reinitialize those addresses
 later.
 
 The boot-time rootfs pack placement depends on the boot path: the legacy
-stage stages it in the low gap `0x60000..0x9FBFF` and copies it to
-`0x900000` before the kernel starts, the UEFI loader puts it at the top of
+stage copies it directly to `0x900000`, the UEFI loader puts it at the top of
 RAM below 128 MB, and kexec leaves it in the staging buffer
 (≥ `0x900000`).  `mm_init` reserves `[pack_addr, pack_addr+pack_size)` from
 boot info when it is above the low 1 MB, so the legacy pack is protected
@@ -369,7 +372,21 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   buffer (`screen.c`, used by `io.c`'s fallback screen and `bootcon`).  The
   ring-3 terminal renders its own rows into its canvas; the kernel window
   manager has no text-cell content path.  `screen_damage_*` remains for the
-  boot console's own bookkeeping.
+  boot console's own bookkeeping.  The kernel console stays 8×8; userland
+  proportional text uses `ufont` (below).
+- **Fonts**: `ufont.c/h`, `ufont_ttf.c`, `ufont_draw.c`, `ufont_file.c` — a
+  fixed-point (26.6, no FPU) TrueType parser and antialiased rasterizer for
+  ring-3 text.  Latin-1 only for now; the faces are the Arimo regular/bold/
+  italic/bold-italic and Liberation Mono subsets in `fonts/`, packed into
+  `/ramfs/fonts`.  `ufont` owns one 256 KB `malloc` arena for face data and
+  glyph masks; `ngui_font_attach/detach` (ngui) and `usurf_font_attach`
+  (`uwm_lib`) load faces and leave the 8×16 bitmap fallback when they are
+  absent.  The **browser calls `ngui_font_detach` before `heap_reset()` and
+  reattaches after `heap_start()`**, because its page heap is reset on every
+  navigation.  Terminal/editor/text fields deliberately keep the 8×16 cell
+  grid.  Host test: `make test-font` (`ufont_test.c`); `make fonts`
+  regenerates the subsets.  No hinting, CFF/variable fonts, shaping, bidi or
+  full Unicode yet.
 - **Shell**: `ucmd_term.c` is the windowed shell (rows, scrollback, Tab,
   builtins `cd`, `path`, `help`, `clear`).  `terminal.c` keeps the privileged
   kernel command registry and `term_kcmd_spawn()` used through `SYS_SPAWN_KCMD`;
@@ -590,8 +607,9 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `USER_BASE` (`0x40000000`), packed by `mkpack` into `cmds.pack` (as
   `bin/<name>`), gzipped to `cmds_pack_gz.bin` and wrapped by `mkrootfs`
   with a `NBROOT1` header.  The pack is the system rootfs: the boot path
-  loads it into RAM (legacy low gap / UEFI / kexec staging) and `ramfs_init`
-  takes a private page-allocated copy, mounted read-only at `/ramfs`.  The
+  loads it into RAM (legacy high-memory AH=87h copy / UEFI / kexec staging)
+  and `ramfs_init` takes a private page-allocated copy, mounted read-only at
+  `/ramfs`.  The
   shell finds them through PATH (`/ramfs/bin` by default), loads the whole
   ELF through the VFS and spawns it as a ring-3 process; `hello` is just
   `bin/hello`.  New command: add `ucmd_<name>.c` to UCMDS — the pack, the
@@ -824,15 +842,15 @@ The commands live in `cmds.pack` (`bin/<name>` entries, built by `mkpack`),
 compressed with `libdeflate-gzip -12` when it is installed (falling back to
 `gzip -9`) to `cmds_pack_gz.bin` and wrapped by `mkrootfs` with a
 one-sector `NBROOT1` header (magic, version, exact `pack_bytes`, checksum,
-gzip flag).  The build rejects a legacy pack above the `PACK_LOW_MAX` cap;
-`libdeflate` buys several KB over `gzip -9` and is currently needed to fit.
-The boot path loads the gz pack into RAM — the legacy stage stages it in
-the low gap at `0x60000` and relocates it to `0x900000` before the kernel
-starts, the UEFI loader via an embedded copy at the top of
-RAM below 128 MB, kexec via its staging buffer — and `ramfs_init()` inflates
-it into page-allocated memory and mounts it read-only at `/ramfs`.  The
-kernel image no longer contains it, so the pack no longer moves `_end`; the
-legacy staging gap has its own size cap (known issue 9).
+gzip flag).  The build rejects a pack above the `PACK_MAX` cap (512 KB);
+`libdeflate` buys several KB over `gzip -9` and is still preferred.  The boot
+path loads the gz pack into RAM — the legacy stage copies it directly to
+`0x900000` with INT 15h AH=87h, the UEFI loader via an embedded copy at the
+top of RAM below 128 MB, kexec via its staging buffer — and `ramfs_init()`
+inflates it into page-allocated memory and mounts it read-only at `/ramfs`.
+The kernel image no longer contains it, so the pack no longer moves `_end`;
+the high-memory legacy path supports up to 512 KB (known issue 8).  The UI
+font subsets live in the pack under `fonts/`.
 
 `rootfs.bin` is the floppy append (header + pack); `cmds.img` is the 8 MB
 rootfs partition image written to USB partition 2.  `cmds-dev`/`net-cmds`
@@ -1179,13 +1197,12 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
 8. The rootfs pack is inflated into one contiguous page-allocated run at
    boot, capped by `RAMFS_MAX_DECOMPRESSED` (8 MB); a larger pack fails to
    load (the USB rootfs partition is 8 MB, so this only bites if the cap is
-   raised without a bigger partition).  The legacy stage still stages the
-   compressed pack through the `0x60000..0x9FBFF` gap before copying it to
-   `0x900000`, so `PACK_LOW_MAX` (0x3FBFF, ~255 KB compressed) still caps the
-   legacy path; a larger pack needs the UEFI/kexec path or a chunked
-   high-memory loader.  The browser and its ring-3 dependencies are compiled
-   with function sections and linked with `--gc-sections`; the current pack
-   is ~243 KiB (248428 bytes), leaving ~12 KB under the cap.  Command growth
+   raised without a bigger partition).  The legacy stage now copies the
+   compressed pack directly to `0x900000` with INT 15h AH=87h, so the cap is
+   `PACK_MAX` 512 KB (not the old ~255 KB low-gap limit).  The browser and
+   its ring-3 dependencies are compiled with function sections and linked
+   with `--gc-sections`; the current pack with the UI fonts is ~343 KiB
+   (351180 bytes), leaving ~169 KiB under the cap.  Command growth
    still needs care because `libdeflate-gzip -12` is already required (plain
    `gzip -9` is over the cap).
 9. SMP is **ACPI/MADT only**: no Intel MP-table fallback, so a Pentium II SMP
@@ -1260,8 +1277,12 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     a float without a width uses a text-width estimate.  `@media` width
     blocks are evaluated against a fixed 1000 px desktop viewport (so
     narrow/adaptive pages get the desktop rules, not their mobile layout),
-    and pseudo-classes are never matched.  `font-size` maps to 1x/2x only,
-    `em`/`rem` both use a 16 px root, and `line-height` is approximate.
+    and pseudo-classes are never matched.  `font-size` now maps to real pixel
+    sizes (8..48), `font-weight` selects the bold face, `font-style: italic`
+    selects the italic face, `font-family: monospace` selects Liberation Mono,
+    and `em`/`rem` use a 16 px root.  Text is Latin-1 only (non-Latin-1
+    characters become `?`); there is no shaping, bidi, `@font-face` or
+    full-Unicode fallback.
     Pages that need flex alignment/justification, multi-row grid templates
     or CSS variables inside `calc()`/`color-mix()` can still lay out
     imperfectly.  Images are decoded into a per-image `img_estimate()`-sized
@@ -1324,3 +1345,12 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     block headers are charged to the same cap.  The `libc.a` members are only
     pulled into commands that reference them; the legacy pack still needs
     every added byte checked against `CMDS_GZ_MAX`.
+
+26. Fonts: `ufont` is a Latin-1-only, unhinted fixed-point TrueType subset;
+    there is no shaping/bidi/kerning, CFF or variable-font support, and no
+    full-Unicode fallback.  Small sizes (below ~12 px) are softer than the
+    bitmap font.  The 256 KB arena is shared by five faces plus glyph masks;
+    a very text-heavy page can exhaust it and fall back to re-rasterizing
+    evicted glyphs.  The browser must detach/re-attach its font arena around
+    `heap_reset()`, and terminal/editor/text-input cell grids intentionally
+    stay on the 8×16 bitmap font.

+ 67 - 27
Makefile

@@ -24,6 +24,9 @@ LIBC_HEADERS = libc/include/stddef.h libc/include/stdint.h \
                libc/include/assert.h libc/include/ucmd_heap.h
 LIBC_OBJS = libc/malloc.o libc/string.o libc/strdup.o \
             libc/stdlib.o libc/ucmd_mem.o
+
+# Fixed-point TrueType text engine, linked only into GUI commands.
+UFONT_OBJS = ufont.o ufont_ttf.o ufont_draw.o ufont_file.o
 ASFLAGS  = --32 -I.
 BOOT_LDFLAGS   = -T linker.ld -nostdlib -m elf_i386
 KERNEL_LDFLAGS = -T kernel.ld -nostdlib -m elf_i386
@@ -46,7 +49,7 @@ EFI_LDFLAGS = -nostdlib -Wl,--subsystem,10 -Wl,-e,efi_main \
               -Wl,--image-base,0x0 -Wl,--dynamicbase \
               -Wl,--enable-reloc-section -Wl,--no-insert-timestamp
 
-.PHONY: all clean run run-smp run-floppy run-usb run-uhci run-ehci run-ehci-asix run-xhci run-xhci-asix run-net run-e1000 run-ahci test-usb run-serial floppy usb uefi run-uefi test-uefi flash dev net-dev cmds-dev net-cmds browser-dev gallery-dev netmon monitor test-crypto test-images test-images-asan kernel-dev kernel-net-dev rootfs
+.PHONY: all clean run run-smp run-floppy run-usb run-uhci run-ehci run-ehci-asix run-xhci run-xhci-asix run-net run-e1000 run-ahci test-usb run-serial floppy usb uefi run-uefi test-uefi flash dev net-dev cmds-dev net-cmds browser-dev gallery-dev netmon monitor test-crypto test-images test-images-asan test-libc test-font test-font-asan fonts kernel-dev kernel-net-dev rootfs
 
 all: floppy.img usb.img final.bin root.img
 
@@ -413,6 +416,11 @@ floppy.img: boot.bin kernel.bin rootfs.bin
 	PAD=$$(( SECTORS * 512 - $$(stat -c%s kernel.bin) )); \
 	dd if=/dev/zero bs=1 count=$$PAD 2>/dev/null >> $@; \
 	cat rootfs.bin >> $@; \
+	SIZE=$$(stat -c%s $@); \
+	if [ $$SIZE -gt 1474560 ]; then \
+		echo "error: floppy.img is $$SIZE bytes; max is 1474560"; \
+		rm -f $@; exit 1; \
+	fi; \
 	truncate -s 1474560 $@; \
 	rm -f $@.boot.tmp
 
@@ -554,6 +562,32 @@ libc.a: $(LIBC_OBJS)
 	rm -f $@
 	ar rcs $@ $^
 
+ufont.o: ufont.c ufont.h ufont_internal.h $(LIBC_HEADERS)
+	$(CC) $(CFLAGS) -Os $(SECTION_CFLAGS) -Ilibc/include -o $@ $<
+
+ufont_ttf.o: ufont_ttf.c ufont_internal.h $(LIBC_HEADERS)
+	$(CC) $(CFLAGS) -O2 $(SECTION_CFLAGS) -Ilibc/include -o $@ $<
+
+ufont_draw.o: ufont_draw.c ufont.h $(LIBC_HEADERS)
+	$(CC) $(CFLAGS) -Os $(SECTION_CFLAGS) -Ilibc/include -o $@ $<
+
+ufont_file.o: ufont_file.c ufont.h ucmd_lib.h syscall.h $(LIBC_HEADERS)
+	$(CC) $(CFLAGS) -Os $(SECTION_CFLAGS) -Ilibc/include -o $@ $<
+
+UFONT_TEST_SRCS = ufont_test.c ufont.c ufont_ttf.c ufont_draw.c
+ufont_test: $(UFONT_TEST_SRCS) ufont.h ufont_internal.h
+	gcc -O2 -Wall -Wextra -I. -o $@ $(UFONT_TEST_SRCS)
+
+test-font: ufont_test
+	./ufont_test
+
+test-font-asan: $(UFONT_TEST_SRCS) ufont.h ufont_internal.h
+	gcc -O1 -g -fsanitize=address,undefined -I. -o ufont_test_asan $(UFONT_TEST_SRCS)
+	./ufont_test_asan
+
+fonts:
+	tools/subset_fonts.sh
+
 ucmd_%.o: ucmd_%.c ucmd_lib.h syscall.h $(LIBC_HEADERS)
 	$(CC) $(CFLAGS) -Ilibc/include -o $@ $<
 
@@ -578,47 +612,47 @@ ucmd_edit.elf: ucmd_edit.o font_8x16.o ucmd.ld
 ucmd_wm.o: ucmd_wm.c ucmd_lib.h syscall.h wm_abi.h uwm_lib.h version.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-uwm_lib.o: uwm_lib.c uwm_lib.h font_8x16.h
-	$(CC) $(CFLAGS) -o $@ $<
+uwm_lib.o: uwm_lib.c uwm_lib.h font_8x16.h ufont.h
+	$(CC) $(CFLAGS) -Os $(SECTION_CFLAGS) -Ilibc/include -o $@ $<
 
-ucmd_wm.elf: ucmd_wm.o uwm_lib.o font_8x16.o ucmd.ld
-	$(LD) -T ucmd.ld -z max-page-size=0x100 -nostdlib -m elf_i386 -o $@ $(filter %.o,$^)
+ucmd_wm.elf: ucmd_wm.o uwm_lib.o font_8x16.o $(UFONT_OBJS) ucmd.ld libc.a
+	$(LD) -T ucmd.ld -z max-page-size=0x100 --gc-sections -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
 	$(OBJCOPY) --strip-all $@ $@
 
 ucmd_term.o: ucmd_term.c ucmd_lib.h syscall.h wm_abi.h uwm_lib.h io.h vfs.h $(LIBC_HEADERS)
 	$(CC) $(CFLAGS) -Ilibc/include -o $@ $<
 
-ucmd_term.elf: ucmd_term.o uwm_lib.o font_8x16.o ucmd.ld libc.a
+ucmd_term.elf: ucmd_term.o uwm_lib.o font_8x16.o $(UFONT_OBJS) ucmd.ld libc.a
 	$(LD) -T ucmd.ld -z max-page-size=0x100 --gc-sections -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
 	$(OBJCOPY) --strip-all $@ $@
 
 # ngui: the userland immediate-mode GUI toolkit and its apps.
-# -Os: every GUI app links the whole toolkit, and the legacy rootfs pack has
-# a hard 255 KB cap; -Os saves ~10 KB compressed across the pack.
-ngui.o: ngui.c ngui.h ucmd_lib.h syscall.h wm_abi.h font_8x16.h
-	$(CC) $(CFLAGS) -Os $(SECTION_CFLAGS) -o $@ $<
+# -Os: every GUI app links the whole toolkit, and the rootfs pack has a
+# 512 KB cap; -Os saves ~10 KB compressed across the pack.
+ngui.o: ngui.c ngui.h ucmd_lib.h syscall.h wm_abi.h font_8x16.h ufont.h
+	$(CC) $(CFLAGS) -Os $(SECTION_CFLAGS) -Ilibc/include -o $@ $<
 
 ucmd_files.o: ucmd_files.c ucmd_lib.h syscall.h wm_abi.h ngui.h img.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-ucmd_files.elf: ucmd_files.o ngui.o font_8x16.o ucmd.ld
-	$(LD) -T ucmd.ld -z max-page-size=0x100 -nostdlib -m elf_i386 -o $@ $(filter %.o,$^)
+ucmd_files.elf: ucmd_files.o ngui.o font_8x16.o $(UFONT_OBJS) ucmd.ld libc.a
+	$(LD) -T ucmd.ld -z max-page-size=0x100 --gc-sections -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
 	$(OBJCOPY) --strip-all $@ $@
 
 # mines is a second ngui canvas app; it links the same toolkit.
 ucmd_mines.o: ucmd_mines.c ucmd_lib.h syscall.h wm_abi.h ngui.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-ucmd_mines.elf: ucmd_mines.o ngui.o font_8x16.o ucmd.ld
-	$(LD) -T ucmd.ld -z max-page-size=0x100 -nostdlib -m elf_i386 -o $@ $(filter %.o,$^)
+ucmd_mines.elf: ucmd_mines.o ngui.o font_8x16.o $(UFONT_OBJS) ucmd.ld libc.a
+	$(LD) -T ucmd.ld -z max-page-size=0x100 --gc-sections -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
 	$(OBJCOPY) --strip-all $@ $@
 
 # solitaire: a Windows 95 style Klondike game on the same canvas toolkit.
 ucmd_solitaire.o: ucmd_solitaire.c ucmd_lib.h syscall.h wm_abi.h ngui.h
 	$(CC) $(CFLAGS) -Os -o $@ $<
 
-ucmd_solitaire.elf: ucmd_solitaire.o ngui.o font_8x16.o ucmd.ld
-	$(LD) -T ucmd.ld -z max-page-size=0x100 -nostdlib -m elf_i386 -o $@ $(filter %.o,$^)
+ucmd_solitaire.elf: ucmd_solitaire.o ngui.o font_8x16.o $(UFONT_OBJS) ucmd.ld libc.a
+	$(LD) -T ucmd.ld -z max-page-size=0x100 --gc-sections -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
 	$(OBJCOPY) --strip-all $@ $@
 
 # gallery: a live showcase of every ngui widget and primitive.  The real ELF
@@ -627,8 +661,8 @@ ucmd_solitaire.elf: ucmd_solitaire.o ngui.o font_8x16.o ucmd.ld
 gallery.o: gallery.c ucmd_lib.h syscall.h wm_abi.h ngui.h
 	$(CC) $(CFLAGS) -o $@ $<
 
-gallery.elf: gallery.o ngui.o font_8x16.o ucmd.ld
-	$(LD) -T ucmd.ld -z max-page-size=0x100 -nostdlib -m elf_i386 -o $@ $(filter %.o,$^)
+gallery.elf: gallery.o ngui.o font_8x16.o $(UFONT_OBJS) ucmd.ld libc.a
+	$(LD) -T ucmd.ld -z max-page-size=0x100 --gc-sections -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
 	$(OBJCOPY) --strip-all $@ $@
 
 # Image library: pure freestanding decoders + RGB565 compositing.  Only the
@@ -645,7 +679,7 @@ img_jpeg.o: CFLAGS += -fwrapv
 ucmd_view.o: ucmd_view.c ucmd_lib.h syscall.h wm_abi.h ngui.h img.h img_file.h $(LIBC_HEADERS)
 	$(CC) $(CFLAGS) -Ilibc/include -o $@ $<
 
-ucmd_view.elf: ucmd_view.o $(IMGLIB_OBJS) inflate.o ngui.o font_8x16.o ucmd.ld libc.a
+ucmd_view.elf: ucmd_view.o $(IMGLIB_OBJS) inflate.o ngui.o font_8x16.o $(UFONT_OBJS) ucmd.ld libc.a
 	$(LD) -T ucmd.ld -z max-page-size=0x100 --gc-sections -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
 	$(OBJCOPY) --strip-all $@ $@
 
@@ -666,14 +700,14 @@ ucmd_curl.elf: ucmd_curl.o uhttp.o $(TLSLIB_OBJS) ucmd.ld libc.a
 # image library, TLS and uhttp.  ucmd_browser.c is the tiny PATH launcher.
 # Compile this graph with function sections and link it with --gc-sections:
 # unreachable image, TLS and UI paths are dropped, leaving room under the
-# legacy rootfs pack's low-memory cap.
+# 512 KB rootfs pack cap.
 browser_html.o: browser_html.c browser_html.h
 	$(CC) $(CFLAGS) -Os $(SECTION_CFLAGS) -o $@ $<
 
 browser.o: browser.c ucmd_lib.h syscall.h wm_abi.h ngui.h browser_html.h uhttp.h img.h inflate.h $(LIBC_HEADERS)
 	$(CC) $(CFLAGS) -Os $(SECTION_CFLAGS) -Ilibc/include -o $@ $<
 
-browser.elf: browser.o browser_html.o uhttp.o ngui.o font_8x16.o $(IMGLIB_OBJS) inflate.o $(TLSLIB_OBJS) ucmd.ld libc.a
+browser.elf: browser.o browser_html.o uhttp.o ngui.o font_8x16.o $(UFONT_OBJS) $(IMGLIB_OBJS) inflate.o $(TLSLIB_OBJS) ucmd.ld libc.a
 	$(LD) -T ucmd.ld -z max-page-size=0x100 --gc-sections -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
 	$(OBJCOPY) --strip-all $@ $@
 
@@ -744,26 +778,32 @@ mkpack: mkpack.c
 # Command pack (the system rootfs): the ring-3 command ELFs plus hello and the
 # browser/gallery apps, packed into bin/<name>.  See mkpack.c, rootfs.h and
 # ramfs.h.
+FONT_FILES = fonts/sans.ttf fonts/sans-b.ttf fonts/sans-i.ttf \
+             fonts/sans-bi.ttf fonts/mono.ttf
+
 PACK_FILES = $(foreach f,$(UCMDS),bin/$(patsubst ucmd_%,%,$(f))=$(f).elf) \
              bin/hello=hello.elf \
              bin/browser.app=browser.elf \
-             bin/gallery.app=gallery.elf
+             bin/gallery.app=gallery.elf \
+             $(foreach f,$(FONT_FILES),$(f)=$(f))
 
-cmds.pack: $(addsuffix .elf,$(UCMDS)) hello.elf browser.elf gallery.elf mkpack
+cmds.pack: $(addsuffix .elf,$(UCMDS)) hello.elf browser.elf gallery.elf \
+           $(FONT_FILES) mkpack
 	./mkpack $@ $(PACK_FILES)
 
 # The boot-time rootfs is gzip-compressed; the raw cmds.pack is still what
 # cmds-dev/net-cmds send for a runtime replacement.  Prefer libdeflate's
 # level 12 when it is installed: it saves about 8 KB over gzip -9 on the
-# current pack, which matters for the legacy low-memory pack (0x3FBFF).
+# current pack.  The high-memory rootfs loader supports up to 512 KB, which
+# leaves room for the font subsystem without touching the kernel image.
 CMDS_GZ     = $(shell command -v libdeflate-gzip >/dev/null 2>&1 && \
 		     echo "libdeflate-gzip -12 -n -c" || echo "gzip -9 -n -c")
-CMDS_GZ_MAX = 261119
+CMDS_GZ_MAX = 524288
 cmds_pack_gz.bin: cmds.pack
 	$(CMDS_GZ) $< > $@
 	@sz=$$(stat -c%s $@); \
 	if [ $$sz -gt $(CMDS_GZ_MAX) ]; then \
-		echo "error: cmds_pack_gz.bin is $$sz bytes; the legacy low pack cap is $(CMDS_GZ_MAX) (install libdeflate-gzip)"; \
+		echo "error: cmds_pack_gz.bin is $$sz bytes; the legacy rootfs cap is $(CMDS_GZ_MAX)"; \
 		rm -f $@; exit 1; \
 	fi
 
@@ -1024,4 +1064,4 @@ kernel-net-dev: kernel.bin netkexec_send
 	./netkexec_send $(BOARD_IP) $(NETKEXEC_PORT) 0x$$entry kernel.bin
 
 clean:
-	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o sched.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o disk.o serial.o serial_ring_buf.o serial_loop.o vga.o blit.o cpu.o thermal.o it87.o tpec.o power.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o intel.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o font_8x16.o fbtext.o gfx.o display.o mouse.o uhci.o ohci.o ehci.o xhci.o asix.o usb.o usbhid.o lsusb.o panic.o bootcon.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_mem.o inflate.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o e1000e.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o acpi.o lapic.o smp.o ap_tramp.o ap_tramp.elf ap_tramp.bin ap_tramp_embed.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img hello.elf cmds.pack cmds_pack_gz.bin cmds_pack.o rootfs.bin cmds.img mkrootfs ramfs.o share.o payload.o mkpack uwm_lib.o ngui.o img.o img_mem.o img_blit.o img_png.o img_bmp.o img_gif.o img_jpeg.o img_tga.o img_pnm.o img_ico.o img_pam.o img_gif_anim.o img_file.o browser.o browser_html.o uhttp.o browser.elf img_test img_test_asan *.boot.tmp $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) gallery.o gallery.elf $(TLSLIB_OBJS) tls_test kexec_send netkexec_send netmonitor BOOTX64.EFI esp.img usb-efi.img efi/main.o efi/payload.o efi/tramp.o efi/tramp.elf efi/tramp.bin efi/efi_entry.h libc.a libc/*.o malloc_test
+	rm -f boot.o vesa_stage.o entry.o kernel.o timer.o switch.o sched.o process.o mm.o kmalloc.o paging.o elf.o tss.o syscall.o sys_wm.o syscall_stub.o screen.o io.o tty.o rtc.o terminal.o wm.o hello.o reboot.o poweroff.o fat.o disk.o serial.o serial_ring_buf.o serial_loop.o vga.o blit.o cpu.o thermal.o it87.o tpec.o power.o vga_copy.o gfxbench.o gpu.o ati.o cirrus.o intel.o nvidia.o nv50.o radeon.o mtrr.o font_8x8.o font_8x16.o fbtext.o gfx.o display.o mouse.o uhci.o ohci.o ehci.o xhci.o asix.o usb.o usbhid.o lsusb.o panic.o bootcon.o blkdev.o ata.o ahci.o fatdetect.o fatformat.o format.o vfs.o sys_fs.o sys_info.o sys_mem.o inflate.o idle.o kexec.o kexec_tramp.o dbg.o lspci.o peek.o ne2000.o r8168.o e1000e.o netdev.o net.o netkexec.o netlog.o dhcp.o dns.o tcp.o acpi.o lapic.o smp.o ap_tramp.o ap_tramp.elf ap_tramp.bin ap_tramp_embed.o mbr.o boot.elf kernel.elf mbr.elf boot.bin mbr.bin kernel.bin boot.bin.tmp boot.bin.patched image.bin floppy.img usb.img final.bin root.img hello.elf cmds.pack cmds_pack_gz.bin cmds_pack.o rootfs.bin cmds.img mkrootfs ramfs.o share.o payload.o mkpack uwm_lib.o ngui.o img.o img_mem.o img_blit.o img_png.o img_bmp.o img_gif.o img_jpeg.o img_tga.o img_pnm.o img_ico.o img_pam.o img_gif_anim.o img_file.o browser.o browser_html.o uhttp.o browser.elf img_test img_test_asan *.boot.tmp $(addsuffix .o,$(UCMDS)) $(addsuffix .elf,$(UCMDS)) gallery.o gallery.elf $(TLSLIB_OBJS) tls_test kexec_send netkexec_send netmonitor BOOTX64.EFI esp.img usb-efi.img efi/main.o efi/payload.o efi/tramp.o efi/tramp.elf efi/tramp.bin efi/efi_entry.h libc.a libc/*.o malloc_test ufont.o ufont_ttf.o ufont_draw.o ufont_file.o ufont_test ufont_test_asan

+ 207 - 120
browser.c

@@ -145,7 +145,8 @@ struct lay_run {
 	char lit[28];
 	short img;
 	unsigned short iw, ih;
-	unsigned char scale, bold, underline;
+	unsigned short w;
+	unsigned char font_px, bold, italic, mono, underline;
 	unsigned char has_lit;
 };
 
@@ -294,6 +295,7 @@ static int heap_start(void)
 
 static void heap_clear(void)
 {
+	ngui_font_detach(&ui);
 	heap_reset();
 	image_io_buf = 0;
 	page_backbuf = 0;
@@ -1274,7 +1276,7 @@ static int node_hidden(unsigned int node)
 		p = doc.nodes[p].parent;
 	}
 	parent = (struct br_style){0};
-	parent.scale = 1;
+	parent.font_px = 16;
 	parent.display = BR_DISPLAY_BLOCK;
 	for (i = n; i > 0; i--) {
 		br_style_for(&doc, path[i - 1], &parent, &st);
@@ -1450,6 +1452,7 @@ static void load_page(const char *url, int local, int push)
 		show_error("Out of memory", "Cannot allocate the page buffer");
 		return;
 	}
+	ngui_font_attach(&ui);
 	browser_rules_alloc();
 	rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
 		     sizeof(ctype), final, sizeof(final), err, sizeof(err),
@@ -1546,6 +1549,7 @@ static void load_home(int push)
 		show_error("Out of memory", "Cannot allocate the browser heap");
 		return;
 	}
+	ngui_font_attach(&ui);
 	browser_rules_alloc();
 	{
 		static const char home[] =
@@ -1643,8 +1647,10 @@ static struct br_style base_style(void)
 	s.bg = ui.theme.bg;
 	s.has_bg = 0;
 	s.border_color = 0;
-	s.scale = 1;
+	s.font_px = 16;
 	s.bold = 0;
+	s.italic = 0;
+	s.mono = 0;
 	s.underline = 0;
 	s.align = BR_ALIGN_LEFT;
 	s.display = BR_DISPLAY_BLOCK;
@@ -1666,11 +1672,7 @@ static int run_width(const struct lay_run *r)
 		return r->iw;
 	if (r->img == -2)
 		return r->iw;
-	{
-		unsigned int n = r->has_lit ? s_len(r->lit) : r->len;
-		return (int)(n * (unsigned int)(8 * r->scale) +
-			     (r->bold ? 1u : 0u));
-	}
+	return (int)r->w;
 }
 
 static void flush_line(struct lay *l)
@@ -1711,9 +1713,10 @@ static void flush_line(struct lay *l)
 				ngui_frame(l->ui,
 					(struct ngui_rect){x, l->line_y, w, hh},
 					l->ui->theme.border);
-				ngui_text_styled(l->ui, x + 6, l->line_y + 2,
-						 r->lit, s_len(r->lit), r->color,
-						 r->scale, r->bold);
+				ngui_text_px(l->ui, x + 6, l->line_y + 2,
+					     r->lit, s_len(r->lit), r->color,
+					     r->font_px, r->bold, r->italic,
+					     r->mono);
 			} else if (r->img >= 0) {
 				struct br_image *bi = &images[r->img];
 				if (bi->state == 1) {
@@ -1739,19 +1742,24 @@ static void flush_line(struct lay *l)
 						doc.text + r->off;
 				unsigned int n = r->has_lit ? s_len(r->lit) :
 						r->len;
-				ngui_text_styled(l->ui, x, l->line_y, s, n,
-						 r->color, r->scale, r->bold);
+				ngui_text_px(l->ui, x, l->line_y, s, n,
+					     r->color, r->font_px, r->bold,
+					     r->italic, r->mono);
 				if (r->underline)
 					ngui_fill_rect(l->ui,
 						(struct ngui_rect){x,
-						 l->line_y + 16 * r->scale - 2,
+						 l->line_y +
+						 ngui_text_ascent(l->ui,
+								  r->font_px,
+								  r->mono) + 2,
 						 w, 1}, r->color);
 			}
 			if (r->href) {
 				if (nhits < HIT_MAX) {
 					struct hit *h = &hits[nhits];
 					int hh = r->img >= 0 ? r->ih :
-						 16 * r->scale;
+						 ngui_text_line_height(l->ui,
+						 r->font_px, r->mono);
 					int merge = nhits > 0 &&
 						hits[nhits - 1].node == r->href &&
 						hits[nhits - 1].y == l->line_y &&
@@ -1789,8 +1797,9 @@ static void add_run(struct lay *l, unsigned short off, unsigned short len,
 		    const char *lit)
 {
 	unsigned int n = lit ? s_len(lit) : len;
-	int w = (int)(n * (unsigned int)(8 * st->scale) +
-		      (st->bold ? 1u : 0u));
+	const char *tp = lit ? lit : doc.text + off;
+	int w = (int)ngui_text_width_px(l->ui, tp, n, st->font_px,
+					st->bold, st->italic, st->mono);
 
 	if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
 		flush_line(l);
@@ -1820,23 +1829,32 @@ static void add_run(struct lay *l, unsigned short off, unsigned short len,
 		}
 		r->img = -1;
 		r->iw = r->ih = 0;
-		r->scale = st->scale;
+		r->font_px = st->font_px;
 		r->bold = st->bold;
+		r->italic = st->italic;
+		r->mono = st->mono;
 		/* A control with its own background is a button, not body copy;
 		 * an inherited link underline would strike through the fill. */
 		r->underline = st->underline && !st->has_bg;
+		r->w = (unsigned short)w;
+		if (r->has_lit)
+			r->w = (unsigned short)ngui_text_width_px(
+				l->ui, r->lit, s_len(r->lit), r->font_px,
+				r->bold, r->italic, r->mono);
+		w = r->w;
 	}
 	l->line_x += w;
 	l->run_x = l->line_x;
 	{
-		int lh = 16 * st->scale;
+		int lh = ngui_text_line_height(l->ui, st->font_px, st->mono);
 
 		if (st->line_h_px)
 			lh = st->line_h_px;
 		else if (st->line_h_pct)
-			lh = (16 * st->scale) * st->line_h_pct / 100;
-		if (lh < 16 * st->scale)
-			lh = 16 * st->scale;
+			lh = st->font_px * st->line_h_pct / 100;
+		if (lh < ngui_text_line_height(l->ui, st->font_px, st->mono))
+			lh = ngui_text_line_height(l->ui, st->font_px,
+						   st->mono);
 		if (l->line_h < lh)
 			l->line_h = lh;
 	}
@@ -1852,8 +1870,11 @@ static void add_image_run(struct lay *l, unsigned int node,
 	if (idx >= 0 && idx < image_count && images[idx].state == 1)
 		bi = &images[idx];
 	if (l->space_pending && (l->nruns > 0 || l->line_x > l->left)) {
-		if (l->line_x + 8 <= l->right)
-			l->line_x += 8;
+		int sp = (int)ngui_text_width_px(l->ui, " ", 1, st->font_px,
+						 st->bold, st->italic,
+						 st->mono);
+		if (l->line_x + sp <= l->right)
+			l->line_x += sp;
 	}
 	l->space_pending = 0;
 	if (!bi) {
@@ -1868,14 +1889,16 @@ static void add_image_run(struct lay *l, unsigned int node,
 		s_append(tmp, &n, "[", sizeof(tmp));
 		s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
 		s_append(tmp, &n, "]", sizeof(tmp));
-		w = (int)(n * (unsigned int)(8 * gs.scale));
+		w = (int)ngui_text_width_px(l->ui, tmp, n, gs.font_px,
+					    gs.bold, gs.italic, gs.mono);
 		if (l->line_x + w > l->right &&
 		    (l->nruns > 0 || l->line_x > l->left))
 			flush_line(l);
 		add_run(l, 0, 0, &gs, href, tmp);
 		if (!l->draw) {
 			int t = l->line_y < 0 ? 0 : l->line_y;
-			int hh = 16 * gs.scale;
+			int hh = ngui_text_line_height(l->ui, gs.font_px,
+						       gs.mono);
 
 			if (t > 65535)
 				t = 65535;
@@ -1983,8 +2006,11 @@ static void add_image_run(struct lay *l, unsigned int node,
 		r->img = (short)idx;
 		r->iw = (unsigned short)dw;
 		r->ih = (unsigned short)dh;
-		r->scale = 1;
-		r->bold = 0;
+		r->w = (unsigned short)dw;
+		r->font_px = st->font_px;
+		r->bold = st->bold;
+		r->italic = st->italic;
+		r->mono = st->mono;
 		r->underline = 0;
 	}
 	l->line_x += dw;
@@ -1993,16 +2019,68 @@ static void add_image_run(struct lay *l, unsigned int node,
 		l->line_h = dh;
 }
 
+static int text_width(struct lay *l, const char *s, unsigned int n,
+		      const struct br_style *st)
+{
+	return (int)ngui_text_width_px(l->ui, s, n, st->font_px,
+				       st->bold, st->italic, st->mono);
+}
+
+/* Longest prefix that fits in maxw, at least one byte. */
+static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
+			       const struct br_style *st, int maxw)
+{
+	unsigned int take = 0;
+
+	while (take < n) {
+		if (text_width(l, s, take + 1, st) > maxw)
+			break;
+		take++;
+	}
+	return take ? take : 1;
+}
+
+static void emit_word(struct lay *l, const char *s, unsigned int start,
+		      unsigned int n, unsigned int base,
+		      const struct br_style *st, unsigned short href)
+{
+	int avail = l->right - l->left;
+	int w = text_width(l, s + start, n, st);
+	unsigned int off = start;
+
+	if (l->line_x + w > l->right &&
+	    (l->nruns > 0 || l->line_x > l->left))
+		flush_line(l);
+	if (w <= avail) {
+		if (n)
+			add_run(l, (unsigned short)(base + start),
+				(unsigned short)n, st, href, 0);
+		return;
+	}
+	while (n > 0) {
+		unsigned int take = fit_prefix(l, s + off, n, st, avail);
+
+		add_run(l, (unsigned short)(base + off),
+			(unsigned short)take, st, href, 0);
+		off += take;
+		n -= take;
+		if (n)
+			flush_line(l);
+	}
+}
+
 static void emit_text(struct lay *l, const char *s, unsigned int len,
 		      const struct br_style *st, unsigned short href, int pre)
 {
 	unsigned int i = 0;
 	unsigned int base;
-	int cw = 8 * st->scale;
-	int adv = cw + (st->bold ? 1 : 0);
+	int space_w = (int)ngui_text_width_px(l->ui, " ", 1, st->font_px,
+					      st->bold, st->italic, st->mono);
 
 	if (!s || !len)
 		return;
+	if (space_w <= 0)
+		space_w = 8;
 	base = (unsigned int)(s - doc.text);
 	if (st->uppercase) {
 		char *p = (char *)s;
@@ -2022,52 +2100,23 @@ static void emit_text(struct lay *l, const char *s, unsigned int len,
 				continue;
 			}
 			if (s[i] == ' ') {
-				if (l->line_x + cw > l->right &&
+				if (l->line_x + space_w > l->right &&
 				    (l->nruns > 0 || l->line_x > l->left))
 					flush_line(l);
 				else
-					l->line_x += cw;
+					l->line_x += space_w;
 				i++;
 				continue;
 			}
 			start = i;
 			while (i < len && s[i] != ' ' && s[i] != '\n')
 				i++;
-			{
-				unsigned int n = i - start;
-				int w = (int)(n * (unsigned int)adv);
-
-				if (l->line_x + w > l->right &&
-				    (l->nruns > 0 || l->line_x > l->left))
-					flush_line(l);
-				if (w > l->right - l->left) {
-					int maxc = (l->right - l->left) / adv;
-					unsigned int off = start;
-					if (maxc < 1)
-						maxc = 1;
-					while (n > 0) {
-						unsigned int take = n >
-							(unsigned int)maxc ?
-							(unsigned int)maxc : n;
-						add_run(l, (unsigned short)(base + off),
-							(unsigned short)take,
-							st, href, 0);
-						off += take;
-						n -= take;
-						if (n)
-							flush_line(l);
-					}
-				} else {
-					add_run(l, (unsigned short)(base + start),
-						(unsigned short)n, st, href, 0);
-				}
-			}
+			emit_word(l, s, start, i - start, base, st, href);
 		}
 		return;
 	}
 	while (i < len) {
 		unsigned int start, n;
-		int w;
 
 		if (s[i] == ' ') {
 			l->space_pending = 1;
@@ -2078,36 +2127,13 @@ static void emit_text(struct lay *l, const char *s, unsigned int len,
 		while (i < len && s[i] != ' ')
 			i++;
 		n = i - start;
-		w = (int)(n * (unsigned int)adv);
 		if (l->space_pending &&
 		    (l->nruns > 0 || l->line_x > l->left)) {
-			if (l->line_x + cw <= l->right)
-				l->line_x += cw;
+			if (l->line_x + space_w <= l->right)
+				l->line_x += space_w;
 		}
 		l->space_pending = 0;
-		if (l->line_x + w > l->right &&
-		    (l->nruns > 0 || l->line_x > l->left))
-			flush_line(l);
-		if (w > l->right - l->left) {
-			int maxc = (l->right - l->left) / adv;
-			unsigned int off = start;
-
-			if (maxc < 1)
-				maxc = 1;
-			while (n > 0) {
-				unsigned int take = n > (unsigned int)maxc ?
-					(unsigned int)maxc : n;
-				add_run(l, (unsigned short)(base + off),
-					(unsigned short)take, st, href, 0);
-				off += take;
-				n -= take;
-				if (n)
-					flush_line(l);
-			}
-		} else if (n) {
-			add_run(l, (unsigned short)(base + start),
-				(unsigned short)n, st, href, 0);
-		}
+		emit_word(l, s, start, n, base, st, href);
 	}
 }
 
@@ -2148,11 +2174,15 @@ static void add_form_run(struct lay *l, unsigned int node,
 {
 	const char *text = form_text(node);
 	struct lay_run *r;
-	int tw, w, h = 20, i;
+	int tw, w, h, i;
 
 	if (!text)
 		return;
-	tw = (int)s_len(text) * 8 * st->scale;
+	tw = (int)ngui_text_width_px(l->ui, text, s_len(text), st->font_px,
+				     st->bold, st->italic, st->mono);
+	h = ngui_text_line_height(l->ui, st->font_px, st->mono) + 4;
+	if (h < 20)
+		h = 20;
 	if (st->width_kind == 1)
 		w = st->width;
 	else if (st->width_kind == 2)
@@ -2182,8 +2212,11 @@ static void add_form_run(struct lay *l, unsigned int node,
 	r->img = -2;
 	r->iw = (unsigned short)w;
 	r->ih = (unsigned short)h;
-	r->scale = st->scale;
+	r->w = (unsigned short)w;
+	r->font_px = st->font_px;
 	r->bold = st->bold;
+	r->italic = st->italic;
+	r->mono = st->mono;
 	r->underline = 0;
 	l->line_x += w;
 	l->run_x = l->line_x;
@@ -2459,19 +2492,18 @@ static void draw_svg(struct ngui *ui, unsigned node,
 			unsigned int t = nd->first;
 			const char *s;
 			unsigned int n, tw;
-			int scale = st.scale ? st.scale : 1;
+			int px = st.font_px ? st.font_px : 16;
 			int tx, ty, anchor;
 
 			if (!t || doc.nodes[t].type != BR_NODE_TEXT)
 				continue;
 			s = doc.text + doc.nodes[t].text_off;
 			n = doc.nodes[t].text_len;
-			tw = ngui_text_width_n(s, n, scale);
-			if (st.bold)
-				tw += n;
+			tw = ngui_text_width_px(ui, s, n, px, st.bold,
+						st.italic, st.mono);
 			tx = ox + (int)nd->svg_x * dw / vw;
 			ty = oy + (int)nd->svg_y * dh / vh -
-			     12 * scale;
+			     ngui_text_ascent(ui, px, st.mono);
 			anchor = st.align;
 			if (nd->attr_flags & BR_ATTR_ANCHOR_MIDDLE)
 				anchor = BR_ALIGN_CENTER;
@@ -2481,8 +2513,8 @@ static void draw_svg(struct ngui *ui, unsigned node,
 				tx -= (int)tw / 2;
 			else if (anchor == BR_ALIGN_RIGHT)
 				tx -= (int)tw;
-			ngui_text_styled(ui, tx, ty, s, n, st.color,
-					 scale, st.bold);
+			ngui_text_px(ui, tx, ty, s, n, st.color, px,
+				     st.bold, st.italic, st.mono);
 		}
 	}
 }
@@ -2652,7 +2684,7 @@ static void layout_block(struct lay *l, unsigned int node,
 				}
 			}
 			if (l->draw) {
-				int mw = (int)s_len(m) * 8;
+				int mw = (int)ngui_text_width_ui(l->ui, m);
 				ngui_text(l->ui, l->left - mw - 6, l->y, m,
 					  st->color);
 			}
@@ -2716,8 +2748,8 @@ static int text_node_blank(const struct br_node *nd)
  * text/image widths in the subtree, plus padding and margins.  This keeps
  * Bootstrap's floated nav items on one line instead of giving each the whole
  * row. */
-static int intrinsic_width(unsigned int node, const struct br_style *pst,
-			   int depth)
+static int intrinsic_width(struct ngui *ui, unsigned int node,
+			   const struct br_style *pst, int depth)
 {
 	unsigned int c;
 	int w = 0;
@@ -2729,8 +2761,10 @@ static int intrinsic_width(unsigned int node, const struct br_style *pst,
 		struct br_style cs;
 
 		if (nd->type == BR_NODE_TEXT) {
-			w += (int)nd->text_len * (8 * pst->scale) +
-			     (pst->bold ? 1 : 0);
+			w += (int)ngui_text_width_px(ui,
+				doc.text + nd->text_off, nd->text_len,
+				pst->font_px, pst->bold, pst->italic,
+				pst->mono);
 			continue;
 		}
 		br_style_for(&doc, c, pst, &cs);
@@ -2755,7 +2789,7 @@ static int intrinsic_width(unsigned int node, const struct br_style *pst,
 			continue;
 		}
 		w += cs.pl + cs.pr + cs.ml + cs.mr;
-		w += intrinsic_width(c, &cs, depth + 1);
+		w += intrinsic_width(ui, c, &cs, depth + 1);
 		if (w > 4096)
 			break;
 	}
@@ -2805,7 +2839,7 @@ static unsigned int layout_float_group(struct lay *l, unsigned int first,
 		else if (cs.width_kind == 1)
 			colw = (int)cs.width;
 		else {
-			colw = intrinsic_width(n, &cs, 0) +
+			colw = intrinsic_width(l->ui, n, &cs, 0) +
 			       cs.pl + cs.pr + cs.ml + cs.mr + 8;
 			if (colw < 8)
 				colw = 8;
@@ -2877,7 +2911,7 @@ static int flex_item_width(struct lay *l, unsigned int n,
 		else
 			w = 64;
 	} else {
-		w = intrinsic_width(n, cs, 0);
+		w = intrinsic_width(l->ui, n, cs, 0);
 		w += cs->pl + cs->pr + cs->ml + cs->mr;
 	}
 	if (w < 24)
@@ -3331,15 +3365,60 @@ static void layout_grid_auto(struct lay *l, unsigned int parent,
 	l->space_pending = 0;
 }
 
-/* Table rows: cells share the row line, with widths proportional to their
- * intrinsic content.  Border-collapse and colspans are not modelled, but a
- * two-column reference table reads as a table instead of a vertical list. */
+/* Column widths are the widest cell in each column across every row, so all
+ * rows line up.  The table model is still deliberately basic: no colspan,
+ * border-collapse or percentage columns. */
+static void table_columns(struct lay *l, unsigned int table,
+			  const struct br_style *pst, int *raw, int maxcols,
+			  int *out_cols, int *out_total)
+{
+	unsigned int r, c;
+	int cols = 0, total = 0;
+
+	for (c = 0; c < (unsigned int)maxcols; c++)
+		raw[c] = 0;
+	for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
+		struct br_node *rn = &doc.nodes[r];
+		int col = 0;
+
+		if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
+			continue;
+		for (c = rn->first; c; c = doc.nodes[c].next) {
+			struct br_node *cn = &doc.nodes[c];
+			struct br_style cs;
+			int w;
+
+			if (cn->type != BR_NODE_ELEM ||
+			    (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
+				continue;
+			if (col >= maxcols)
+				break;
+			br_style_for(&doc, c, pst, &cs);
+			if (cs.display == BR_DISPLAY_NONE)
+				continue;
+			w = intrinsic_width(l->ui, c, &cs, 0) + cs.pl + cs.pr +
+			    cs.ml + cs.mr;
+			if (w < 24)
+				w = 24;
+			if (w > raw[col])
+				raw[col] = w;
+			if (col + 1 > cols)
+				cols = col + 1;
+			col++;
+		}
+	}
+	for (c = 0; c < (unsigned int)cols; c++)
+		total += raw[c];
+	*out_cols = cols;
+	*out_total = total;
+}
+
 static void layout_table_row(struct lay *l, unsigned int row,
 			     const struct br_style *pst, int depth,
 			     unsigned short link)
 {
 	unsigned int n, cell[12];
-	int raw[12], ncell = 0, total = 0;
+	int raw[12], ncell = 0, total = 0, cols = 0;
 	int row_left = l->left, row_right = l->right;
 	int avail = row_right - row_left;
 	int x = row_left, y = l->y, bottom = l->y;
@@ -3366,17 +3445,27 @@ static void layout_table_row(struct lay *l, unsigned int row,
 			return;
 		}
 		cell[ncell] = n;
-		raw[ncell] = intrinsic_width(n, &cs, 0) + cs.pl + cs.pr +
-			     cs.ml + cs.mr;
-		if (raw[ncell] < 24)
-			raw[ncell] = 24;
-		total += raw[ncell];
 		ncell++;
 	}
-	if (ncell < 2 || total <= 0 || avail < 32) {
+	if (ncell < 2 || avail < 32) {
 		layout_children(l, row, pst, depth, link);
 		return;
 	}
+	table_columns(l, doc.nodes[row].parent, pst, raw, 12, &cols, &total);
+	if (cols < 2 || total <= 0) {
+		int c;
+
+		for (c = 0; c < ncell; c++) {
+			struct br_style cs;
+
+			br_style_for(&doc, cell[c], pst, &cs);
+			raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0) +
+				 cs.pl + cs.pr + cs.ml + cs.mr;
+			if (raw[c] < 24)
+				raw[c] = 24;
+			total += raw[c];
+		}
+	}
 	for (n = 0; n < (unsigned int)ncell; n++) {
 		struct br_style cs;
 		int w = (int)((long)raw[n] * avail / total);
@@ -3384,8 +3473,6 @@ static void layout_table_row(struct lay *l, unsigned int row,
 		br_style_for(&doc, cell[n], pst, &cs);
 		if (w < 24)
 			w = 24;
-		if (n == (unsigned int)ncell - 1)
-			w = row_right - x;
 		if (w < 8)
 			w = 8;
 		l->left = x;
@@ -3740,7 +3827,7 @@ static void draw_page(struct ngui_rect page)
 	ngui_fill_rect(&ui, page, ui.theme.bg);
 	if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
 		const char *s = page_loading ? "Loading..." : "No page";
-		int w = (int)ngui_text_width(s);
+		int w = (int)ngui_text_width_ui(&ui, s);
 		ngui_text(&ui, page.x + (page.w - w) / 2,
 			  page.y + page.h / 2 - 8, s, ui.theme.text_dim);
 		page_scroll.content_h = 0;
@@ -3840,7 +3927,7 @@ static void draw_status(struct ngui_rect r)
 	       (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
 	ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
 	{
-		int kw = (int)ngui_text_width(kind);
+		int kw = (int)ngui_text_width_ui(&ui, kind);
 		ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
 			  ui.theme.text_dim);
 	}

+ 51 - 7
browser_html.c

@@ -1038,7 +1038,8 @@ static int str_eq(const char *a, const char *b)
 /* ---- CSS ---- */
 
 enum {
-	PROP_COLOR, PROP_BG, PROP_SCALE, PROP_BOLD, PROP_ALIGN, PROP_UNDERLINE,
+	PROP_COLOR, PROP_BG, PROP_FONT_PX, PROP_BOLD, PROP_ITALIC, PROP_MONO,
+	PROP_ALIGN, PROP_UNDERLINE,
 	PROP_DISPLAY, PROP_MT, PROP_MR, PROP_MB, PROP_ML,
 	PROP_PT, PROP_PR, PROP_PB, PROP_PL,
 	PROP_BORDER_W, PROP_BORDER_COLOR,
@@ -2199,8 +2200,8 @@ static void parse_decls(struct br_doc *d, const char *s,
 		} else if (str_eq(prop, "font-size")) {
 			int px = parse_font_px(s + vstart, vend - vstart);
 			if (px > 0)
-				decl_add(out, nout, PROP_SCALE,
-					 px >= 24 ? 2 : 1, important);
+				decl_add(out, nout, PROP_FONT_PX, px,
+					 important);
 		} else if (str_eq(prop, "font-weight")) {
 			int bold = 0;
 			unsigned int j;
@@ -2217,6 +2218,19 @@ static void parse_decls(struct br_doc *d, const char *s,
 					bold = 1;
 			}
 			decl_add(out, nout, PROP_BOLD, bold, important);
+		} else if (str_eq(prop, "font-style")) {
+			int italic = (vend - vstart >= 6 &&
+				      ci_eq_n(s + vstart, "italic", 6));
+
+			decl_add(out, nout, PROP_ITALIC, italic, important);
+		} else if (str_eq(prop, "font-family")) {
+			unsigned int j;
+			int mono = 0;
+
+			for (j = vstart; j + 4 <= vend; j++)
+				if (ci_eq_n(s + j, "mono", 4))
+					mono = 1;
+			decl_add(out, nout, PROP_MONO, mono, important);
 		} else if (str_eq(prop, "text-align")) {
 			int a = BR_ALIGN_LEFT;
 			if (vend - vstart >= 6 &&
@@ -3517,12 +3531,23 @@ static void apply_decl(struct br_style *st, const struct br_decl *dcl)
 		st->bg = (unsigned short)dcl->val;
 		st->has_bg = 1;
 		break;
-	case PROP_SCALE:
-		st->scale = (unsigned char)(dcl->val >= 2 ? 2 : 1);
+	case PROP_FONT_PX:
+		if (dcl->val < 8)
+			st->font_px = 8;
+		else if (dcl->val > 48)
+			st->font_px = 48;
+		else
+			st->font_px = (unsigned char)dcl->val;
 		break;
 	case PROP_BOLD:
 		st->bold = (unsigned char)(dcl->val != 0);
 		break;
+	case PROP_ITALIC:
+		st->italic = (unsigned char)(dcl->val != 0);
+		break;
+	case PROP_MONO:
+		st->mono = (unsigned char)(dcl->val != 0);
+		break;
 	case PROP_ALIGN:
 		st->align = (unsigned char)dcl->val;
 		break;
@@ -3711,15 +3736,23 @@ void br_style_for(struct br_doc *d, unsigned int node,
 		out->mt = out->mb = 8;
 		break;
 	case BR_TAG_H1:
-		out->scale = 2; out->bold = 1;
+		out->font_px = 32; out->bold = 1;
 		out->mt = 10; out->mb = 6;
 		break;
 	case BR_TAG_H2:
-		out->scale = 2; out->bold = 1;
+		out->font_px = 24; out->bold = 1;
 		out->mt = 8; out->mb = 4;
 		break;
 	case BR_TAG_H3: case BR_TAG_H4: case BR_TAG_H5: case BR_TAG_H6:
 		out->bold = 1; out->mt = 6; out->mb = 3;
+		if (tag == BR_TAG_H3)
+			out->font_px = 19;
+		else if (tag == BR_TAG_H4)
+			out->font_px = 17;
+		else if (tag == BR_TAG_H5)
+			out->font_px = 15;
+		else
+			out->font_px = 13;
 		break;
 	case BR_TAG_UL: case BR_TAG_OL:
 		out->mt = out->mb = 6; out->pl = 20;
@@ -3733,6 +3766,7 @@ void br_style_for(struct br_doc *d, unsigned int node,
 	case BR_TAG_PRE:
 		out->mt = out->mb = 8; out->pl = 8;
 		out->has_bg = 1; out->bg = theme_panel;
+		out->mono = 1;
 		break;
 	case BR_TAG_CENTER:
 		out->align = BR_ALIGN_CENTER;
@@ -3743,8 +3777,18 @@ void br_style_for(struct br_doc *d, unsigned int node,
 	case BR_TAG_B: case BR_TAG_STRONG:
 		out->bold = 1;
 		break;
+	case BR_TAG_I: case BR_TAG_EM:
+		out->italic = 1;
+		break;
 	case BR_TAG_CODE:
 		out->color = 0x8010;
+		out->mono = 1;
+		break;
+	case BR_TAG_SMALL:
+		out->font_px = 13;
+		break;
+	case BR_TAG_BIG:
+		out->font_px = 20;
 		break;
 	case BR_TAG_TD: case BR_TAG_TH:
 		out->pr = 12;

+ 3 - 1
browser_html.h

@@ -82,8 +82,10 @@ struct br_style {
 	unsigned short bg;
 	unsigned short border_color;
 	unsigned char has_bg;
-	unsigned char scale;        /* 1 or 2 */
+	unsigned char font_px;      /* 8..48 */
 	unsigned char bold;
+	unsigned char italic;
+	unsigned char mono;
 	unsigned char underline;
 	unsigned char align;        /* BR_ALIGN_* */
 	unsigned char display;      /* BR_DISPLAY_* */

+ 16 - 14
docs/boot.html

@@ -162,25 +162,27 @@
 		</p>
 		<ol>
 			<li>Probe the <code>INT 15h</code> E820 memory map into <code>0x1000</code>.</li>
-			<li>Read the <code>NBROOT1</code> rootfs header at the boot sector's <code>pack_lba</code> field.</li>
-			<li>Stage the compressed pack in the low gap <code>0x60000..0x9FBFF</code>, using 16 KB staging chunks at <code>0x3000</code> and <code>rep movsb</code>. No protected-mode BIOS call is required.</li>
+			<li>Enable A20 and read the <code>NBROOT1</code> rootfs header at the boot sector's <code>pack_lba</code> field.</li>
+			<li>Copy the compressed pack directly to <code>0x900000</code> above the 8 MB VGA-shadow reserve, in 16 KB staging chunks at <code>0x3000</code>, using the BIOS block move <code>INT 15h AH=87h</code>.</li>
 			<li>Pick the best VBE mode: at least 16 bpp, a linear framebuffer, it must fit the card's VRAM, and the width must be at most 1280 pixels. Mode information is written to <code>0x600</code>; the 12-dword boot-info block goes to <code>0x500</code>.</li>
-			<li>Enable A20, enter protected mode, copy the pack to <code>0x900000</code> above the 8 MB VGA-shadow reserve, rewrite the boot-info pack address, and jump to <code>kernel_entry</code>.</li>
+			<li>Enter protected mode and jump to <code>kernel_entry</code>.</li>
 		</ol>
 		<p>
-			The staging gap is why the compressed pack has a hard cap of
-			<code>0x3FBFF</code> (~255 KB), ending below the EBDA at
-			<code>0x9FC00</code>. The kernel image itself must stay below the
-			same gap, which <span class="file">kernel.ld</span> enforces with
-			link-time assertions.
+			The pack no longer occupies the old <code>0x60000..0x9FBFF</code>
+			low gap, so the legacy cap is <code>PACK_MAX</code> (512 KB) and the
+			kernel BSS/boot stack may use the gap. The kernel image only has to
+			stay below <code>0x90000</code> so the top of low memory and the
+			EBDA remain untouched; <span class="file">kernel.ld</span> enforces
+			that with a link-time assertion.
 		</p>
 
 		<div class="note">
-			<p><strong>Why copy the pack again?</strong> The low gap is temporary:
-			the kernel BSS and boot stack may extend past <code>0x60000</code>.
-			Moving the pack to <code>0x900000</code> before <code>kernel_main</code>
-			keeps it safe until <span class="file">ramfs.c</span> takes a private
-			page-allocated copy and releases the boot region.</p>
+			<p><strong>BIOS state after the move.</strong> The X201's BIOS
+			leaves translation bits behind after <code>AH=87h</code>;
+			<span class="file">paging.c</span> clears CR4.PAE/PGE/LA57/PCIDE/
+			SMEP/SMAP and EFER.LME before it enables paging. The block move
+			keeps the pack safe until <span class="file">ramfs.c</span> takes a
+			private page-allocated copy and releases the boot region.</p>
 		</div>
 	</section>
 
@@ -382,7 +384,7 @@
 		<h2>Failure modes to know</h2>
 		<ul>
 			<li><strong>No VBE mode.</strong> The legacy stage cannot produce a framebuffer; the kernel may start headless or the boot stops in the stage.</li>
-			<li><strong>Pack larger than the low gap.</strong> The legacy path rejects a compressed pack above <code>PACK_LOW_MAX</code>. UEFI and kexec can carry more.</li>
+			<li><strong>Pack larger than the cap.</strong> The legacy and kexec paths share the 512 KB <code>PACK_MAX</code>; a larger pack needs the UEFI path or a bigger cap and loader change.</li>
 			<li><strong>PIT not ticking.</strong> <code>kernel_main</code> prints <code>*** PIT NOT TICKING ***</code> and halts; no process scheduling is possible.</li>
 			<li><strong>UEFI Secure Boot.</strong> The unsigned <code>BOOTX64.EFI</code> is rejected before any NebOS code runs.</li>
 			<li><strong>Stale boot info.</strong> The checksum makes an invalid <code>0x500</code> block read as absent rather than as a bogus pack or RSDP.</li>

+ 4 - 0
docs/development.html

@@ -178,6 +178,8 @@
 					<tr><td><code>make test-images</code> / <code>test-images-asan</code></td><td>Host image-decoder and blit tests, with an AddressSanitizer variant.</td></tr>
 					<tr><td><code>make test-crypto</code></td><td>Host vectors for SHA-256, ChaCha20-Poly1305, X25519 and TLS helpers.</td></tr>
 					<tr><td><code>make test-libc</code></td><td>Host stress test for the ring-3 <code>malloc</code>, realloc, calloc and <code>heap_reset</code>.</td></tr>
+					<tr><td><code>make test-font</code> / <code>test-font-asan</code></td><td>Host specimen test for the fixed-point TrueType parser/rasterizer and glyph cache, with an AddressSanitizer/UBSan variant.</td></tr>
+					<tr><td><code>make fonts</code></td><td>Regenerate the checked-in Arimo/Liberation Mono subsets with <code>pyftsubset</code>.</td></tr>
 				</tbody>
 			</table>
 		</div>
@@ -254,6 +256,7 @@ make net-cmds                   # replace /ramfs only</code></pre>
 			<li><strong>Image library.</strong> <code>make test-images</code> decodes a corpus of PNG/JPEG/GIF/BMP/TGA/PNM/ICO/PAM files and checks blits; the ASan variant catches memory errors.</li>
 			<li><strong>Crypto.</strong> <code>make test-crypto</code> runs host vectors for the freestanding crypto code.</li>
 			<li><strong>Ring-3 libc.</strong> <code>make test-libc</code> runs a deterministic allocation/free/realloc stress test and a browser-like large-buffer sequence; the backend simulates the fixed 32 MB arena and poisons new pages.</li>
+			<li><strong>Fonts.</strong> <code>make test-font</code> parses the checked-in Arimo subset on the host, measures Latin-1 text, renders composites (for example <code>Äé</code>) and writes a specimen PPM. The browser must also be exercised across a navigation to verify detach/reattach around <code>heap_reset()</code>.</li>
 			<li><strong>UEFI.</strong> <code>make test-uefi</code> boots the dual image under OVMF headless and greps the serial log for the boot line.</li>
 			<li><strong>Compositor stats.</strong> The ring-3 WM overwrites <code>/share/wmstats</code> every two seconds with <code>frames</code>, total and worst compositing time in milliseconds, and the pixels drawn in the interval. Read it in a terminal or fetch it over WebDAV to measure a target.</li>
 		</ul>
@@ -323,6 +326,7 @@ make net-cmds                   # replace /ramfs only</code></pre>
 		<ul class="filelist">
 			<li><code>Makefile</code> — targets and image rules</li>
 			<li><code>libc/</code>, <code>libc.a</code> — optional ring-3 libc and its host test</li>
+			<li><code>ufont.c</code>, <code>ufont_ttf.c</code>, <code>fonts/</code> — UI font engine and subsets; <code>ufont_test.c</code> host test</li>
 			<li><code>kexec.c</code>, <code>kexec_send.c</code> — serial reload</li>
 			<li><code>netkexec.c</code>, <code>netkexec_send.c</code> — network reload</li>
 			<li><code>netlog.c</code>, <code>netmonitor.c</code> — UDP console</li>

+ 5 - 5
docs/filesystems.html

@@ -236,8 +236,8 @@
 			<figcaption>
 				<strong>The pack is the root filesystem.</strong> The kernel no
 				longer embeds it, so command growth does not move <code>_end</code>.
-				The legacy boot path still caps the compressed pack at about 255 KB;
-				UEFI and kexec can carry more.
+				The high-memory legacy loader caps the compressed pack at 512 KB;
+				the 8 MB rootfs partition and ramfs cap remain the larger limits.
 			</figcaption>
 		</figure>
 
@@ -333,7 +333,7 @@
 	<section id="capacity">
 		<h2>Capacity chart</h2>
 		<figure class="figure">
-			<div class="bars" role="img" aria-label="Capacity limits: /share 16 MB, ramfs decompressed pack 8 MB, USB rootfs image 8 MB, legacy compressed pack about 255 KB. Bar widths are relative to 16 MB.">
+			<div class="bars" role="img" aria-label="Capacity limits: /share 16 MB, ramfs decompressed pack 8 MB, USB rootfs image 8 MB, legacy compressed pack 512 KB. Bar widths are relative to 16 MB.">
 				<div class="bar-row">
 					<span class="bar-label">/share</span>
 					<div class="bar-track"><span class="bar-fill green" style="--w:100%"></span></div>
@@ -351,8 +351,8 @@
 				</div>
 				<div class="bar-row">
 					<span class="bar-label">legacy pack</span>
-					<div class="bar-track"><span class="bar-fill" style="--w:1.56%"></span></div>
-					<span class="bar-value">~255 KB</span>
+					<div class="bar-track"><span class="bar-fill" style="--w:3.125%"></span></div>
+					<span class="bar-value">512 KB</span>
 				</div>
 			</div>
 			<figcaption>

+ 16 - 1
docs/graphics.html

@@ -263,11 +263,24 @@
 			<code>solitaire</code> and the real <code>gallery.elf</code>.
 		</p>
 		<ul>
-			<li><strong>Text fields</strong> support drag-selection, double-click select-all, Ctrl+Left/Right word jumps, Ctrl+Delete/Backspace word deletion and Ctrl+A.</li>
+			<li><strong>Text fields</strong> support drag-selection, double-click select-all, Ctrl+Left/Right word jumps, Ctrl+Delete/Backspace word deletion and Ctrl+A. Their cell grid stays on the 8×16 bitmap font.</li>
 			<li><strong>Clip stack</strong> keeps nested panes and popups inside their parents.</li>
 			<li><strong>Layout cuts</strong> split a rectangle into rows, columns and fixed margins without a constraint solver.</li>
 			<li><strong>No retained widget tree.</strong> Apps redraw from state every frame, which keeps the toolkit small and predictable.</li>
 		</ul>
+		<p>
+			Proportional text comes from <span class="file">ufont.c</span>: a
+			fixed-point, integer-only TrueType parser and antialiased rasterizer.
+			The pack carries Latin-1 Arimo regular/bold/italic/bold-italic and
+			Liberation Mono subsets under <code>/ramfs/fonts</code>. The browser,
+			ngui apps and the WM chrome use real pixel sizes from 8 to 48 px;
+			the browser maps CSS <code>font-size</code>, <code>font-weight</code>,
+			<code>font-style</code> and <code>font-family: monospace</code> to
+			the faces. Missing fonts fall back to the 8×16 bitmap. The browser
+			detaches the font arena before <code>heap_reset()</code> and
+			reattaches after <code>heap_start()</code>; terminal content, the
+			editor and text fields keep the bitmap cells.
+		</p>
 	</section>
 
 	<section id="apps">
@@ -339,6 +352,8 @@
 			<li><code>sys_wm.c</code>, <code>sys_wm.h</code> — WM/window ABI</li>
 			<li><code>browser.c</code>, <code>browser_html.c</code> — HTML/CSS renderer and inline SVG</li>
 			<li><code>ngui.c</code>, <code>ngui.h</code> — toolkit</li>
+			<li><code>ufont.c</code>, <code>ufont_ttf.c</code>, <code>ufont_draw.c</code> — fixed-point TrueType text</li>
+			<li><code>fonts/*.ttf</code> — Arimo / Liberation Mono subsets in the pack</li>
 			<li><code>ucmd_files.c</code>, <code>gallery.c</code>, <code>ucmd_solitaire.c</code></li>
 			<li><code>img*.c</code> — image codecs</li>
 			<li><code>ati.c</code>, <code>nvidia.c</code>, <code>intel.c</code>, <code>nv50.c</code></li>

+ 2 - 2
docs/index.html

@@ -212,7 +212,7 @@
 			</a>
 			<a class="card" href="graphics.html">
 				<h3>Graphics &amp; UI</h3>
-				<p>VBE framebuffer, shadow buffer, damage rectangles, compositor, canvas ABI, ngui and image codecs.</p>
+				<p>VBE framebuffer, shadow buffer, damage rectangles, compositor, canvas ABI, ngui, the fixed-point TrueType text engine and image codecs.</p>
 				<span class="card-tag">graphics.html</span>
 			</a>
 			<a class="card" href="network.html">
@@ -269,7 +269,7 @@
 					</tr>
 					<tr>
 						<td>Userland</td>
-						<td><span class="file">ucmd_*.c</span> <span class="file">ucmd_lib.h</span> <span class="file">libc/</span> <span class="file">ngui.c</span> <span class="file">browser.c</span> <span class="file">gallery.c</span></td>
+						<td><span class="file">ucmd_*.c</span> <span class="file">ucmd_lib.h</span> <span class="file">libc/</span> <span class="file">ngui.c</span> <span class="file">ufont.c</span> <span class="file">ufont_ttf.c</span> <span class="file">fonts/</span> <span class="file">browser.c</span> <span class="file">gallery.c</span></td>
 					</tr>
 					<tr>
 						<td>Build &amp; pack</td>

+ 3 - 3
docs/memory.html

@@ -130,9 +130,9 @@
 					<tr><td><code>0x6000</code></td><td>AP real/protected-mode trampoline</td><td>SIPI vector <code>0x06</code>; image ends below <code>0x6C00</code></td></tr>
 					<tr><td><code>0x6C00</code></td><td>AP trampoline real-mode stack top</td><td>Grows down</td></tr>
 					<tr><td><code>0x6F00</code></td><td>AP startup info block</td><td>CR3, stack top, C entry, CPU index</td></tr>
-					<tr><td><code>0x60000</code></td><td>Legacy rootfs staging</td><td><code>0x60000..0x9FBFF</code>, compressed pack only</td></tr>
+					<tr><td><code>0x60000</code></td><td>Former rootfs staging</td><td>No longer used by the loader; kernel BSS/stack may use it</td></tr>
 					<tr><td><code>_end</code></td><td>Kernel end</td><td><code>kernel.ld</code> asserts <code>_end ≤ 0x90000</code></td></tr>
-					<tr><td><code>0x900000</code></td><td>Boot pack after relocation; dynamic stacks and kexec staging</td><td>Freed after <code>ramfs_init</code> takes its copy</td></tr>
+					<tr><td><code>0x900000</code></td><td>Boot pack (written directly by the legacy stage); dynamic stacks and kexec staging</td><td>Freed after <code>ramfs_init</code> takes its copy</td></tr>
 					<tr><td><code>0x100000</code></td><td>VGA shadow buffer base</td><td><code>VGA_SHADOW_BASE</code>; 8 MB reserved</td></tr>
 					<tr><td><code>0x40000000</code></td><td>Ring-3 ELF link/load address</td><td><code>USER_BASE</code>, 2 MB window up to <code>0x40200000</code></td></tr>
 					<tr><td><code>0x50000000</code></td><td>Ring-3 window canvas</td><td><code>USER_WIN_BASE</code>, 4 MB slot</td></tr>
@@ -293,7 +293,7 @@
 	<section id="pack">
 		<h2>Rootfs pack lifetime</h2>
 		<ol>
-			<li>The boot path places the gzip pack in RAM: the legacy stage in the low gap and then <code>0x900000</code>, UEFI at the top of RAM below 128 MB, kexec in its staging buffer.</li>
+			<li>The boot path places the gzip pack in RAM: the legacy stage copies it directly to <code>0x900000</code> with <code>INT 15h AH=87h</code>, UEFI at the top of RAM below 128 MB, kexec in its staging buffer.</li>
 			<li><code>mm_init</code> reserves <code>[pack_addr, pack_addr + pack_size)</code> so the frame allocator cannot reuse it.</li>
 			<li><code>ramfs_init</code> takes a private page-allocated copy, validates the <code>NBROOT1</code> header and inflates the pack into it.</li>
 			<li><code>mm_free_range</code> releases the boot region when it is above the VGA shadow reserve. The private copy lives until <code>ramfs_replace</code> or reboot.</li>

+ 13 - 1
docs/userland.html

@@ -303,6 +303,16 @@
 			<li><strong>clock</strong> / <strong>colors</strong> — small window canvas demos.</li>
 			<li><strong>wm</strong> / <strong>term</strong> — the ring-3 window manager and terminal launcher used by the desktop.</li>
 		</ul>
+		<p>
+			The WM chrome, ngui labels and the browser use the fixed-point
+			TrueType engine in <span class="file">ufont.c</span> with the Arimo
+			and Liberation Mono subsets in the pack. CSS and ngui can select
+			regular/bold/italic/mono faces at 8–48 px; missing faces fall back to
+			the 8×16 bitmap. Terminal contents, the editor and text-input cells
+			stay bitmap. The browser detaches the font arena before
+			<code>heap_reset()</code> and reattaches after the page heap is
+			mapped.
+		</p>
 	</section>
 
 	<section id="browser">
@@ -316,7 +326,7 @@
 			drawing and scrolling.
 		</p>
 		<ul>
-			<li><strong>HTML/CSS subset.</strong> External and inline stylesheets, tag/class/id and descendant/child selectors, colours, backgrounds, font size, weights, margins, padding, borders, alignment, percentage widths, basic floats and <code>@media</code> blocks evaluated at a fixed 1000 px viewport.</li>
+			<li><strong>HTML/CSS subset.</strong> External and inline stylesheets, tag/class/id and descendant/child selectors, colours, backgrounds, real <code>font-size</code> (8–48 px), bold/italic faces, <code>font-family: monospace</code>, margins, padding, borders, alignment, percentage widths, basic floats and <code>@media</code> blocks evaluated at a fixed 1000 px viewport. Text is Latin-1; there is no shaping, bidi or <code>@font-face</code> yet.</li>
 			<li><strong>Not supported.</strong> JavaScript, forms, pseudo-classes, border-radius clipping of descendants, gradients/box-shadow/transitions and CSS <code>color-mix</code>. Flex rows, card grids, basic tables, inline SVG and CSS variables are supported.</li>
 			<li><strong>Caps.</strong> 2 MB page body, 832 KB CSS, 6144 DOM nodes, 4608 rules, 16 images. Each image gets an <code>img_estimate()</code>-sized decode arena that is freed after the scaled bitmap is made; navigation calls <code>heap_reset()</code> and unmaps the page heap.</li>
 			<li><strong>Fetching.</strong> Each network fetch starts a one-shot helper process and a fresh TCP/TLS connection; images load one per loop within the viewport plus 160 px.</li>
@@ -345,6 +355,8 @@
 			<li><code>ucmd.ld</code> — ring-3 link address</li>
 			<li><code>Makefile</code> — <code>UCMDS</code> and pack rules</li>
 			<li><code>ucmd_*.c</code> — commands</li>
+			<li><code>ufont.c</code>, <code>ufont_ttf.c</code> — fixed-point TrueType text</li>
+			<li><code>ngui.c</code> — GUI toolkit; <code>fonts/*.ttf</code> — UI subsets</li>
 			<li><code>browser.c</code>, <code>browser_html.c</code>, <code>gallery.c</code></li>
 		</ul>
 	</section>

+ 73 - 0
fonts/LICENSE-Apache-2.0

@@ -0,0 +1,73 @@
+Apache License
+Version 2.0, January 2004
+http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
+
+"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
+
+"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
+
+"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
+
+"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
+
+"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
+
+"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
+
+"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
+
+"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
+
+"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
+
+     (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
+
+     (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
+
+     (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
+
+     (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
+
+     You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!)  The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.

+ 102 - 0
fonts/LICENSE-OFL

@@ -0,0 +1,102 @@
+Digitized data copyright (c) 2010 Google Corporation
+	with Reserved Font Arimo, Tinos and Cousine.
+Copyright (c) 2012 Red Hat, Inc.
+	with Reserved Font Name Liberation.
+
+This Font Software is licensed under the SIL Open Font License,
+Version 1.1.
+
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+
+PREAMBLE The goals of the Open Font License (OFL) are to stimulate
+worldwide development of collaborative font projects, to support the font
+creation efforts of academic and linguistic communities, and to provide
+a free and open framework in which fonts may be shared and improved in
+partnership with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves.
+The fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works.  The fonts and derivatives,
+however, cannot be released under any other type of license.  The
+requirement for fonts to remain under this license does not apply to
+any document created using the fonts or their derivatives.
+
+ 
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such.
+This may include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components
+as distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting ? in part or in whole ?
+any of the components of the Original Version, by changing formats or
+by porting the Font Software to a new environment.
+
+"Author" refers to any designer, engineer, programmer, technical writer
+or other person who contributed to the Font Software.
+
+
+PERMISSION & CONDITIONS
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,in
+   Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+   redistributed and/or sold with any software, provided that each copy
+   contains the above copyright notice and this license. These can be
+   included either as stand-alone text files, human-readable headers or
+   in the appropriate machine-readable metadata fields within text or
+   binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+   Name(s) unless explicit written permission is granted by the
+   corresponding Copyright Holder. This restriction only applies to the
+   primary font name as presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+   Software shall not be used to promote, endorse or advertise any
+   Modified Version, except to acknowledge the contribution(s) of the
+   Copyright Holder(s) and the Author(s) or with their explicit written
+   permission.
+
+5) The Font Software, modified or unmodified, in part or in whole, must
+   be distributed entirely under this license, and must not be distributed
+   under any other license. The requirement for fonts to remain under
+   this license does not apply to any document created using the Font
+   Software.
+
+
+ 
+TERMINATION
+This license becomes null and void if any of the above conditions are not met.
+
+ 
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT.  IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER
+DEALINGS IN THE FONT SOFTWARE.
+

+ 40 - 0
fonts/README

@@ -0,0 +1,40 @@
+NebOS UI fonts
+==============
+
+The window manager, ngui applications and the browser use the fixed-point
+TrueType engine in ufont.c / ufont_ttf.c.  The kernel boot console keeps the
+built-in 8x8 font; the terminal, editor and text fields keep the 8x16 bitmap
+font for their cell grids.
+
+Files
+-----
+
+  sans.ttf      Arimo Regular, Latin-1 + common punctuation
+  sans-b.ttf    Arimo Bold
+  sans-i.ttf    Arimo Italic
+  sans-bi.ttf   Arimo BoldItalic
+  mono.ttf      Liberation Mono Regular (browser <pre>/<code>)
+
+The Arimo faces are Copyright 2020 The Arimo Project Authors and are
+distributed under the Apache License 2.0 (see LICENSE-Apache-2.0).  Liberation
+Mono is copyright (c) 2012 Red Hat, Inc. with Reserved Font Name Liberation
+and is distributed under the SIL Open Font License 1.1 (see LICENSE-OFL).
+The subsetting removes unused glyphs and OpenType layout features and keeps
+the files small enough for the rootfs pack.
+
+Regenerating
+------------
+
+Install fonttools (`python3 -m pip install fonttools`) and run:
+
+  make fonts
+
+or manually:
+
+  pyftsubset /usr/share/fonts/croscore/Arimo-Regular.ttf \
+    --unicodes='U+0020-00FF,U+20AC,U+2013-2014,U+2018-2019,U+201C-201D,U+2022,U+2026,U+00A0' \
+    --layout-features='' --output-file=fonts/sans.ttf
+
+The checked-in files are the canonical build inputs; a normal `make` does not
+need fonttools or the original system fonts.  Do not edit the generated TTFs
+by hand.

BIN
fonts/mono.ttf


BIN
fonts/sans-b.ttf


BIN
fonts/sans-bi.ttf


BIN
fonts/sans-i.ttf


BIN
fonts/sans.ttf


+ 9 - 8
gallery.c

@@ -287,7 +287,7 @@ static int gallery_input(struct ngui *g, unsigned int id,
 static void center_text(struct ngui *g, struct ngui_rect r, const char *s,
 			unsigned short color)
 {
-	int tw = (int)ngui_text_width(s);
+	int tw = (int)ngui_text_width_ui(g, s);
 	int x = r.x + (r.w - tw) / 2;
 	int y = r.y + (r.h - 16) / 2;
 
@@ -413,7 +413,7 @@ static void draw_nav(struct ngui *g, struct ngui_rect r)
 		       g->theme.border);
 
 	for (i = 0; i < SEC_COUNT; i++) {
-		int w = (int)ngui_text_width(sec_titles[i]) + 20;
+		int w = (int)ngui_text_width_ui(g, sec_titles[i]) + 20;
 
 		if (x + w > r.x + r.w - 12)
 			break;
@@ -451,7 +451,7 @@ static void draw_section_head(struct ngui *g, int x, int y, int w, int idx)
 	ngui_text_styled(g, x + 34, y + 6, sec_titles[idx],
 			 s_len(sec_titles[idx]), g->theme.text, 1, 1);
 
-	dx = x + 34 + (int)ngui_text_width(sec_titles[idx]) + 14;
+	dx = x + 34 + (int)ngui_text_width_ui(g, sec_titles[idx]) + 14;
 	if (dx < x + w - 16)
 		ngui_text_ellipsis(g, rect_make(dx, y + 6, x + w - dx, 16),
 				   dx, y + 6, sec_descs[idx],
@@ -520,7 +520,7 @@ static void draw_typography(struct ngui *g, struct ngui_rect card)
 	ngui_text(g, x, y + 2, "ngui_text_width", g->theme.text_dim);
 	n = 0;
 	s_append(buf, &n, "ngui_text_width(\"ngui\") = ", sizeof(buf));
-	s_append_uint(buf, &n, ngui_text_width("ngui"), sizeof(buf));
+	s_append_uint(buf, &n, ngui_text_width_ui(g, "ngui"), sizeof(buf));
 	s_append(buf, &n, " px", sizeof(buf));
 	ngui_text_ellipsis(g, rect_make(value_x, y + 2, value_w, 16),
 			   value_x, y + 2, buf, g->theme.text);
@@ -666,7 +666,7 @@ static void draw_icons(struct ngui *g, struct ngui_rect card)
 			ngui_invalidate(g);
 		}
 
-		tw = (int)ngui_text_width(icon_names[i]);
+		tw = (int)ngui_text_width_ui(g, icon_names[i]);
 		tx = cx + (cell - tw) / 2;
 		lr = rect_make(cx + 2, ly, cell - 4, 16);
 		if (tx < lr.x)
@@ -683,7 +683,7 @@ static void draw_icons(struct ngui *g, struct ngui_rect card)
 			   "Click an icon button - every one is live",
 			   g->theme.text_dim);
 	if (card.w > 650) {
-		int cw = (int)ngui_text_width(count);
+		int cw = (int)ngui_text_width_ui(g, count);
 
 		ngui_text(g, card.x + card.w - CARD_PAD - cw,
 			  card.y + 74, count, g->theme.text_dim);
@@ -743,7 +743,7 @@ static void draw_buttons(struct ngui *g, struct ngui_rect card)
 	s_append_uint(num, &n, (unsigned int)button_clicks, sizeof(num));
 	if (card.w > 620) {
 		int right = card.x + card.w - CARD_PAD;
-		int vw = (int)ngui_text_width_n(num, n, 2);
+		int vw = (int)ngui_text_width_px(g, num, n, g->font_px * 2, 1, 0, 0);
 
 		ngui_text(g, right - 96, card.y + 18, "TOTAL CLICKS",
 			  g->theme.text_dim);
@@ -1138,7 +1138,7 @@ static void draw_status(struct ngui *g, struct ngui_rect r)
 		      sizeof(right));
 	s_append(right, &m, "%", sizeof(right));
 
-	rw = (int)ngui_text_width(right);
+	rw = (int)ngui_text_width_ui(g, right);
 	rx = r.x + r.w - rw - 10;
 	ngui_text(g, rx, r.y + 4, right, g->theme.text_dim);
 
@@ -1254,6 +1254,7 @@ void _start(const char *arg)
 
 	ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width,
 		  (int)wi.height);
+	ngui_font_attach(&ui);
 
 	name_in.placeholder = "Type a name";
 	email_in.placeholder = "you@example.com";

+ 5 - 8
kernel.ld

@@ -28,11 +28,8 @@ SECTIONS
 	}
 	_end = .;
 }
-/* The legacy stage stages the compressed rootfs at 0x60000 before copying it
- * to PACK_HIGH_ADDR; the loaded image (text/rodata/data) must not reach that
- * staging area.  BSS and the boot stack may extend past it: the stage copy
- * happens before the kernel clears BSS and starts using its stack.  Keep the
- * kernel end below 0x90000 so the top of the staging gap and the EBDA stay
- * untouched. */
-ASSERT(__bss_start <= 0x60000, "Kernel image too large: legacy pack staging would overwrite it");
-ASSERT(_end <= 0x90000, "Kernel too large: would reach the top of the low-memory staging gap");
+/* The legacy stage now copies each rootfs chunk straight to PACK_HIGH_ADDR,
+ * so the old 0x60000..0x9FBFF low staging gap is no longer used.  BSS and
+ * the boot stack may occupy that range.  Keep the kernel end below 0x90000
+ * so the top of the low-memory gap and the EBDA stay untouched. */
+ASSERT(_end <= 0x90000, "Kernel too large: would reach the top of the low-memory gap");

+ 238 - 31
ngui.c

@@ -3,6 +3,7 @@
 #include "ngui.h"
 #include "ucmd_lib.h"
 #include "font_8x16.h"
+#include "ufont.h"
 
 const struct ngui_theme ngui_theme_dark = {
 	.bg          = NGUI_RGB(24, 28, 40),
@@ -90,6 +91,7 @@ void ngui_init(struct ngui *ui, unsigned short *fb, int w, int h)
 	ui->w = w;
 	ui->h = h;
 	ui->theme = ngui_theme_dark;
+	ui->font_px = 14;
 	ui->nclip = 0;
 	ui->dirty = 1;
 	ui->caret_on = 1;
@@ -99,6 +101,38 @@ void ngui_init(struct ngui *ui, unsigned short *fb, int w, int h)
 	ui->last_mouse_y = -1;
 }
 
+void ngui_font_attach(struct ngui *ui)
+{
+	if (!ui || ui->font)
+		return;
+	ui->font_px = 14;
+	ui->font = ufont_face_open_path("/ramfs/fonts/sans.ttf");
+	if (!ui->font)
+		return;
+	ui->font_bold = ufont_face_open_path("/ramfs/fonts/sans-b.ttf");
+	ui->font_italic = ufont_face_open_path("/ramfs/fonts/sans-i.ttf");
+	ui->font_bold_italic = ufont_face_open_path("/ramfs/fonts/sans-bi.ttf");
+	ui->font_mono = ufont_face_open_path("/ramfs/fonts/mono.ttf");
+	if (!ui->font_bold)
+		ui->font_bold = ui->font;
+	if (!ui->font_italic)
+		ui->font_italic = ui->font;
+	if (!ui->font_bold_italic)
+		ui->font_bold_italic = ui->font_bold;
+}
+
+void ngui_font_detach(struct ngui *ui)
+{
+	if (!ui)
+		return;
+	ui->font = 0;
+	ui->font_bold = 0;
+	ui->font_italic = 0;
+	ui->font_bold_italic = 0;
+	ui->font_mono = 0;
+	ufont_reset();
+}
+
 void ngui_invalidate(struct ngui *ui)
 {
 	ui->dirty = 1;
@@ -609,8 +643,8 @@ void ngui_line(struct ngui *ui, int x0, int y0, int x1, int y1,
 	}
 }
 
-static void ngui_glyph(struct ngui *ui, int x, int y, unsigned char c,
-		       unsigned short color, int scale, int bold)
+static void ngui_bitmap_glyph(struct ngui *ui, int x, int y, unsigned char c,
+			      unsigned short color, int scale, int bold)
 {
 	const unsigned char *g = &font_8x16[(unsigned int)c * FONT_8X16_ROWS];
 	int row, col, sx, sy;
@@ -641,6 +675,101 @@ static void ngui_glyph(struct ngui *ui, int x, int y, unsigned char c,
 	}
 }
 
+static void ngui_bitmap_text(struct ngui *ui, int x, int y, const char *s,
+			     unsigned short color)
+{
+	unsigned int i;
+
+	for (i = 0; s && s[i]; i++)
+		ngui_bitmap_glyph(ui, x + (int)i * 8, y,
+				  (unsigned char)s[i], color, 1, 0);
+}
+
+static struct ufont_face *ngui_face(struct ngui *ui, int bold, int italic,
+				    int mono)
+{
+	struct ufont_face *f;
+
+	if (!ui)
+		return 0;
+	if (mono && ui->font_mono)
+		f = ui->font_mono;
+	else if (bold && italic)
+		f = ui->font_bold_italic;
+	else if (bold)
+		f = ui->font_bold;
+	else if (italic)
+		f = ui->font_italic;
+	else
+		f = ui->font;
+	if (!f)
+		f = ui->font;
+	return f;
+}
+
+static void ngui_clip_bounds(struct ngui *ui, int *cx, int *cy,
+			     int *cw, int *ch)
+{
+	struct ngui_rect r = { 0, 0, ui->w, ui->h };
+	int i;
+
+	for (i = 0; i < ui->nclip; i++) {
+		struct ngui_rect out;
+
+		if (!rect_intersect(&r, &ui->clip[i], &out)) {
+			r.w = r.h = 0;
+			break;
+		}
+		r = out;
+	}
+	*cx = r.x;
+	*cy = r.y;
+	*cw = r.w;
+	*ch = r.h;
+}
+
+int ngui_text_ascent(struct ngui *ui, int px, int mono)
+{
+	struct ufont_face *f = ngui_face(ui, 0, 0, mono);
+	struct ufont_metrics m;
+
+	if (f) {
+		ufont_metrics(f, px, &m);
+		return m.ascent;
+	}
+	return 16 * (px >= 24 ? 2 : 1);
+}
+
+int ngui_text_line_height(struct ngui *ui, int px, int mono)
+{
+	struct ufont_face *f = ngui_face(ui, 0, 0, mono);
+	struct ufont_metrics m;
+
+	if (f) {
+		ufont_metrics(f, px, &m);
+		return m.line_height;
+	}
+	return 16 * (px >= 24 ? 2 : 1);
+}
+
+unsigned int ngui_text_width_px(struct ngui *ui, const char *s, unsigned int n,
+				int px, int bold, int italic, int mono)
+{
+	struct ufont_face *f = ngui_face(ui, bold, italic, mono);
+	int scale;
+
+	if (f)
+		return (unsigned int)ufont_text_width(f, px, s, (int)n, 0);
+	scale = px >= 24 ? 2 : 1;
+	return n * 8u * (unsigned int)scale;
+}
+
+unsigned int ngui_text_width_ui(struct ngui *ui, const char *s)
+{
+	return ngui_text_width_px(ui, s, slen(s),
+				  ui ? ui->font_px : 14, 0, 0, 0);
+}
+
 unsigned int ngui_text_width(const char *s)
 {
 	return slen(s) * 8;
@@ -654,13 +783,46 @@ unsigned int ngui_text_width_n(const char *s, unsigned int n, int scale)
 	return n * 8u * (unsigned int)scale;
 }
 
+void ngui_text_px(struct ngui *ui, int x, int y, const char *s,
+		  unsigned int n, unsigned short color, int px, int bold,
+		  int italic, int mono)
+{
+	struct ufont_face *f = ngui_face(ui, bold, italic, mono);
+	int scale, i, pen = 0, ascent;
+	int cx, cy, cw, ch;
+
+	if (!ui || !ui->px || !s)
+		return;
+	if (!f) {
+		scale = px >= 24 ? 2 : 1;
+		for (i = 0; i < (int)n && s[i]; i++)
+			ngui_bitmap_glyph(ui, x + i * 8 * scale, y,
+					  (unsigned char)s[i], color,
+					  scale, bold);
+		return;
+	}
+	ascent = ngui_text_ascent(ui, px, mono);
+	ngui_clip_bounds(ui, &cx, &cy, &cw, &ch);
+	for (i = 0; i < (int)n && s[i]; i++) {
+		const struct ufont_glyph *g =
+			ufont_glyph(f, px, (unsigned char)s[i]);
+
+		if (!g) {
+			pen += 8 << 6;
+			continue;
+		}
+		ufont_blit_rgb565(ui->px, ui->w, ui->h,
+				  x + (pen >> 6), y + ascent, g, color,
+				  cx, cy, cw, ch);
+		pen += g->advance;
+	}
+}
+
 void ngui_text_n(struct ngui *ui, int x, int y, const char *s, unsigned int n,
 		 unsigned short color)
 {
-	unsigned int i;
-
-	for (i = 0; i < n && s && s[i]; i++)
-		ngui_glyph(ui, x + (int)i * 8, y, (unsigned char)s[i], color, 1, 0);
+	ngui_text_px(ui, x, y, s, n, color,
+		     ui ? ui->font_px : 14, 0, 0, 0);
 }
 
 void ngui_text(struct ngui *ui, int x, int y, const char *s,
@@ -672,13 +834,21 @@ void ngui_text(struct ngui *ui, int x, int y, const char *s,
 void ngui_text_styled(struct ngui *ui, int x, int y, const char *s,
 		      unsigned int n, unsigned short color, int scale, int bold)
 {
-	unsigned int i;
-
 	if (scale < 1)
 		scale = 1;
-	for (i = 0; i < n && s && s[i]; i++)
-		ngui_glyph(ui, x + (int)i * 8 * scale, y, (unsigned char)s[i],
-			   color, scale, bold);
+	if (ui && ui->font) {
+		ngui_text_px(ui, x, y, s, n, color,
+			     ui->font_px * scale, bold, 0, 0);
+		return;
+	}
+	{
+		unsigned int i;
+
+		for (i = 0; i < n && s && s[i]; i++)
+			ngui_bitmap_glyph(ui, x + (int)i * 8 * scale, y,
+					  (unsigned char)s[i], color,
+					  scale, bold);
+	}
 }
 
 /* Draw a string upside down.  The whole n-character block is rotated, so the
@@ -716,22 +886,55 @@ void ngui_text_ellipsis(struct ngui *ui, struct ngui_rect r, int x, int y,
 			const char *s, unsigned short color)
 {
 	unsigned int n = slen(s);
-	int max = (r.x + r.w - x) / 8;
-	unsigned int i;
+	int avail = r.x + r.w - x;
+	unsigned int i, best = 0;
+	int dots;
 
-	if (max <= 0)
+	if (avail <= 0)
 		return;
-	if (n <= (unsigned int)max || max < 4) {
-		for (i = 0; i < n && (int)i < max; i++)
-			ngui_glyph(ui, x + (int)i * 8, y,
-				   (unsigned char)s[i], color, 1, 0);
+	if (ui && ui->font) {
+		dots = (int)ngui_text_width_px(ui, "...", 3, ui->font_px,
+					      0, 0, 0);
+		for (i = 0; i <= n; i++) {
+			int w = (int)ngui_text_width_px(ui, s, i, ui->font_px,
+							0, 0, 0);
+
+			if (w > avail)
+				break;
+			best = i;
+		}
+		if (best == n) {
+			ngui_text_n(ui, x, y, s, n, color);
+			return;
+		}
+		while (best > 0 &&
+		       (int)ngui_text_width_px(ui, s, best, ui->font_px,
+					       0, 0, 0) + dots > avail)
+			best--;
+		ngui_text_n(ui, x, y, s, best, color);
+		ngui_text_n(ui, x + (int)ngui_text_width_px(ui, s, best,
+							   ui->font_px, 0, 0, 0),
+			    y, "...", 3, color);
 		return;
 	}
-	for (i = 0; i < (unsigned int)(max - 3); i++)
-		ngui_glyph(ui, x + (int)i * 8, y, (unsigned char)s[i], color, 1, 0);
-	ngui_glyph(ui, x + (max - 3) * 8, y, '.', color, 1, 0);
-	ngui_glyph(ui, x + (max - 2) * 8, y, '.', color, 1, 0);
-	ngui_glyph(ui, x + (max - 1) * 8, y, '.', color, 1, 0);
+	{
+		int max = avail / 8;
+
+		if (max <= 0)
+			return;
+		if (n <= (unsigned int)max || max < 4) {
+			for (i = 0; i < n && (int)i < max; i++)
+				ngui_bitmap_glyph(ui, x + (int)i * 8, y,
+						  (unsigned char)s[i], color, 1, 0);
+			return;
+		}
+		for (i = 0; i < (unsigned int)(max - 3); i++)
+			ngui_bitmap_glyph(ui, x + (int)i * 8, y,
+					  (unsigned char)s[i], color, 1, 0);
+		ngui_bitmap_glyph(ui, x + (max - 3) * 8, y, '.', color, 1, 0);
+		ngui_bitmap_glyph(ui, x + (max - 2) * 8, y, '.', color, 1, 0);
+		ngui_bitmap_glyph(ui, x + (max - 1) * 8, y, '.', color, 1, 0);
+	}
 }
 
 void ngui_icon(struct ngui *ui, struct ngui_rect r, enum ngui_icon icon,
@@ -822,9 +1025,11 @@ int ngui_button(struct ngui *ui, unsigned int id, struct ngui_rect r,
 	ngui_frame(ui, r, hot ? ui->theme.accent : ui->theme.border);
 
 	if (label && label[0]) {
-		tw = (int)ngui_text_width(label);
+		tw = (int)ngui_text_width_ui(ui, label);
 		tx = r.x + (r.w - tw) / 2;
-		ty = r.y + (r.h - 16) / 2;
+		ty = r.y + (r.h - ngui_text_line_height(ui, ui->font_px, 0)) / 2;
+		if (ty < r.y)
+			ty = r.y;
 		ngui_push_clip(ui, r);
 		ngui_text(ui, tx, ty, label, ui->theme.text);
 		ngui_pop_clip(ui);
@@ -864,7 +1069,9 @@ int ngui_menu_item(struct ngui *ui, unsigned int id, struct ngui_rect r,
 	fg = selected ? NGUI_RGB(255, 255, 255) : ui->theme.text;
 	ngui_fill_rect(ui, r, bg);
 
-	ty = r.y + (r.h - 16) / 2;
+	ty = r.y + (r.h - ngui_text_line_height(ui, ui->font_px, 0)) / 2;
+	if (ty < r.y)
+		ty = r.y;
 	ngui_push_clip(ui, r);
 	if (checked) {
 		ngui_line(ui, r.x + 8, ty + 10, r.x + 10, ty + 13, fg);
@@ -873,7 +1080,7 @@ int ngui_menu_item(struct ngui *ui, unsigned int id, struct ngui_rect r,
 	if (label)
 		ngui_text(ui, r.x + 22, ty, label, fg);
 	if (shortcut) {
-		int sw = (int)ngui_text_width(shortcut);
+		int sw = (int)ngui_text_width_ui(ui, shortcut);
 
 		ngui_text(ui, r.x + r.w - 8 - sw, ty, shortcut, fg);
 	}
@@ -1245,13 +1452,13 @@ int ngui_text_input(struct ngui *ui, unsigned int id, struct ngui_rect r,
 
 	ngui_push_clip(ui, inner);
 	if (in->len == 0 && in->placeholder) {
-		ngui_text(ui, inner.x, inner.y, in->placeholder,
-			  ui->theme.text_dim);
+		ngui_bitmap_text(ui, inner.x, inner.y, in->placeholder,
+				 ui->theme.text_dim);
 	} else {
 		if (focused)
 			input_draw_selection(ui, in, inner, cols);
-		ngui_text(ui, inner.x, inner.y, in->text + in->scroll,
-			  ui->theme.text);
+		ngui_bitmap_text(ui, inner.x, inner.y, in->text + in->scroll,
+				 ui->theme.text);
 	}
 
 	if (focused && ui->caret_on) {

+ 23 - 0
ngui.h

@@ -38,6 +38,8 @@
 #define NGUI_RGB(r, g, b) \
 	((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
 
+struct ufont_face;
+
 struct ngui_rect {
 	int x, y, w, h;
 };
@@ -98,6 +100,16 @@ struct ngui {
 	int w, h;
 	struct ngui_theme theme;
 
+	/* Fonts are owned by ufont.c's heap arena.  ngui_font_attach() opens
+	 * them; ngui_font_detach() frees the arena (the browser calls it before
+	 * heap_reset()).  NULL means the 8x16 bitmap fallback. */
+	struct ufont_face *font;
+	struct ufont_face *font_bold;
+	struct ufont_face *font_italic;
+	struct ufont_face *font_bold_italic;
+	struct ufont_face *font_mono;
+	int font_px;
+
 	/* Current pointer state, content-relative. */
 	int mouse_x, mouse_y;
 	unsigned int buttons;
@@ -137,6 +149,8 @@ struct ngui {
 };
 
 void ngui_init(struct ngui *ui, unsigned short *fb, int w, int h);
+void ngui_font_attach(struct ngui *ui);  /* opens /ramfs/fonts; no-op if absent */
+void ngui_font_detach(struct ngui *ui);  /* frees the ufont arena */
 int  ngui_begin(struct ngui *ui);       /* 1 = app should redraw */
 void ngui_end(struct ngui *ui);
 /* Same bookkeeping, but only publish the canvas when `present` is nonzero.
@@ -175,12 +189,21 @@ void ngui_text_n(struct ngui *ui, int x, int y, const char *s,
 		 unsigned int n, unsigned short color);
 void ngui_text_styled(struct ngui *ui, int x, int y, const char *s,
 		      unsigned int n, unsigned short color, int scale, int bold);
+/* Browser-oriented style: arbitrary pixel size, optional italic and mono. */
+void ngui_text_px(struct ngui *ui, int x, int y, const char *s,
+		  unsigned int n, unsigned short color, int px, int bold,
+		  int italic, int mono);
 void ngui_text_rot180(struct ngui *ui, int x, int y, const char *s,
 		      unsigned int n, unsigned short color);
 void ngui_text_ellipsis(struct ngui *ui, struct ngui_rect r, int x, int y,
 			const char *s, unsigned short color);
 unsigned int ngui_text_width(const char *s);
 unsigned int ngui_text_width_n(const char *s, unsigned int n, int scale);
+unsigned int ngui_text_width_ui(struct ngui *ui, const char *s);
+unsigned int ngui_text_width_px(struct ngui *ui, const char *s, unsigned int n,
+				int px, int bold, int italic, int mono);
+int ngui_text_ascent(struct ngui *ui, int px, int mono);
+int ngui_text_line_height(struct ngui *ui, int px, int mono);
 void ngui_icon(struct ngui *ui, struct ngui_rect r, enum ngui_icon icon,
 	       unsigned short color);
 

+ 4 - 1
testdata/browser/demo.html

@@ -20,7 +20,10 @@ NebOS browser: HTML, a little CSS and an inline image, with no JavaScript.</p>
 <b>Inline styles and classes:</b>
 <span style="color:#7ee787;">green span</span>,
 <span style="background-color:#32384a;">light background</span>,
-<b>bold</b>, <u>underlined</u> and <a href="TEST.TXT">a relative link</a>.
+<b>bold</b>, <i>italic</i>, <u>underlined</u>,
+<span style="font-size:20px;">20px text</span>,
+<span style="font-family:monospace;">mono text</span> and
+<a href="TEST.TXT">a relative link</a>.
 </div>
 
 <h2>Lists</h2>

+ 19 - 0
tools/subset_fonts.sh

@@ -0,0 +1,19 @@
+#!/bin/sh
+# Regenerate the checked-in UI font subsets.  Requires pyftsubset (fonttools)
+# and the Croscore/Liberation source fonts; normal builds use the checked-in
+# files and do not run this script.
+set -e
+cd "$(dirname "$0")/.."
+U='U+0020-00FF,U+20AC,U+2013-2014,U+2018-2019,U+201C-201D,U+2022,U+2026,U+00A0'
+SUB=${PYFTSUBSET:-pyftsubset}
+
+"$SUB" /usr/share/fonts/croscore/Arimo-Regular.ttf --unicodes="$U" \
+	--layout-features='' --output-file=fonts/sans.ttf
+"$SUB" /usr/share/fonts/croscore/Arimo-Bold.ttf --unicodes="$U" \
+	--layout-features='' --output-file=fonts/sans-b.ttf
+"$SUB" /usr/share/fonts/croscore/Arimo-Italic.ttf --unicodes="$U" \
+	--layout-features='' --output-file=fonts/sans-i.ttf
+"$SUB" /usr/share/fonts/croscore/Arimo-BoldItalic.ttf --unicodes="$U" \
+	--layout-features='' --output-file=fonts/sans-bi.ttf
+"$SUB" /usr/share/fonts/liberation/LiberationMono-Regular.ttf --unicodes="$U" \
+	--layout-features='' --output-file=fonts/mono.ttf

+ 6 - 5
ucmd_files.c

@@ -661,21 +661,21 @@ static void draw_toolbar(struct ngui *g, struct ngui_rect r, unsigned int *actio
 	} else {
 		int w;
 
-		w = (int)ngui_text_width("Up") + 18;
+		w = (int)ngui_text_width_ui(g, "Up") + 18;
 		if (ngui_button(g, ID_UP, (struct ngui_rect){x, y, w, h}, "Up"))
 			*action |= ACT_UP;
 		x += w + 6;
-		w = (int)ngui_text_width("Home") + 18;
+		w = (int)ngui_text_width_ui(g, "Home") + 18;
 		if (ngui_button(g, ID_HOME, (struct ngui_rect){x, y, w, h},
 				"Home"))
 			*action |= ACT_HOME;
 		x += w + 6;
-		w = (int)ngui_text_width("Refresh") + 18;
+		w = (int)ngui_text_width_ui(g, "Refresh") + 18;
 		if (ngui_button(g, ID_REFRESH, (struct ngui_rect){x, y, w, h},
 				"Refresh"))
 			*action |= ACT_REFRESH;
 		x += w + 6;
-		w = (int)ngui_text_width("New Folder") + 18;
+		w = (int)ngui_text_width_ui(g, "New Folder") + 18;
 		if (ngui_button(g, ID_NEW, (struct ngui_rect){x, y, w, h},
 				"New Folder"))
 			*action |= ACT_NEW;
@@ -857,7 +857,7 @@ static void draw_list(struct ngui *g, struct ngui_rect r, unsigned int *action)
 		} else {
 			format_size(e->size, detail, sizeof(detail));
 		}
-		detail_x = r.x + row_w - 6 - (int)ngui_text_width(detail);
+		detail_x = r.x + row_w - 6 - (int)ngui_text_width_ui(g, detail);
 		if (detail_x < r.x + 30) {
 			detail[0] = '\0';
 			detail_x = r.x + row_w;
@@ -1081,6 +1081,7 @@ void _start(const char *arg)
 		u_exit(1);
 	}
 	ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
+	ngui_font_attach(&ui);
 	path_in.placeholder = "/path";
 	new_in.placeholder = "NAME";
 	list_scroll.offset = 0;

+ 2 - 1
ucmd_mines.c

@@ -570,7 +570,7 @@ static void draw_footer(struct ngui *ui, const struct mines_layout *l)
 		msg = "left: reveal  right: flag";
 		color = C_DIM;
 	}
-	tw = (int)ngui_text_width(msg);
+	tw = (int)ngui_text_width_ui(ui, msg);
 	x = (ui->w - tw) / 2;
 	if (x < 4)
 		x = 4;
@@ -649,6 +649,7 @@ void _start(const char *arg)
 	}
 	ngui_init(&ui, (unsigned short *)info.fb, (int)info.width,
 		  (int)info.height);
+	ngui_font_attach(&ui);
 	reset_game();
 	quit = 0;
 	prev_right = 0;

+ 5 - 2
ucmd_solitaire.c

@@ -2042,8 +2042,10 @@ static int menu_bar_button(struct ngui *ui, unsigned int id,
 
 static void draw_menu_bar(struct ngui *ui, const struct sol_layout *l)
 {
-	struct ngui_rect gr = rect_make(6, 2, 44, 18);
-	struct ngui_rect hr = rect_make(52, 2, 44, 18);
+	int gw = (int)ngui_text_width_ui(ui, "Game") + 18;
+	int hw = (int)ngui_text_width_ui(ui, "Help") + 18;
+	struct ngui_rect gr = rect_make(6, 2, gw, 18);
+	struct ngui_rect hr = rect_make(6 + gw + 2, 2, hw, 18);
 
 	(void)l;
 	ngui_fill_rect(ui, rect_make(0, 0, ui->w, MENU_H), C_MENU);
@@ -2635,6 +2637,7 @@ void _start(const char *arg)
 
 	ngui_init(&ui, (unsigned short *)info.fb, (int)info.width,
 		  (int)info.height);
+	ngui_font_attach(&ui);
 	setup_theme(&ui);
 	draw_three = 0;
 	deck_style = 0;

+ 4 - 2
ucmd_view.c

@@ -261,7 +261,7 @@ static void format_status(char *buf, unsigned int cap)
 static void draw_message(struct ngui *ui, struct ngui_rect body,
 			 const char *msg)
 {
-	int tw = (int)ngui_text_width(msg);
+	int tw = (int)ngui_text_width_ui(ui, msg);
 	int x = body.x + (body.w - tw) / 2;
 	int y = body.y + body.h / 2 - 8;
 
@@ -270,7 +270,7 @@ static void draw_message(struct ngui *ui, struct ngui_rect body,
 	ngui_text(ui, x, y, msg, ui->theme.text);
 	if (!v.loading) {
 		const char *hint = "Esc closes";
-		int hw = (int)ngui_text_width(hint);
+		int hw = (int)ngui_text_width_ui(ui, hint);
 
 		ngui_text(ui, body.x + (body.w - hw) / 2, y + 24, hint,
 			  ui->theme.text_dim);
@@ -438,6 +438,7 @@ static void error_exit(const char *msg)
 		u_exit(1);
 	}
 	ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
+	ngui_font_attach(&ui);
 	v.error = 1;
 	s_copy(v.err, msg, sizeof(v.err));
 	v.have_img = 0;
@@ -520,6 +521,7 @@ void _start(const char *arg)
 		u_exit(1);
 	}
 	ngui_init(&v.ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
+	ngui_font_attach(&v.ui);
 	v.fit = 1;
 	v.zoom = 65536;
 	v.loading = 1;

+ 19 - 14
ucmd_wm.c

@@ -106,12 +106,10 @@ static void fill_clip(int x, int y, unsigned int w, unsigned int h,
 static void bar_button(unsigned int x, unsigned int y, unsigned int w,
 		       unsigned int h, const char *label)
 {
-	unsigned int n = 0;
+	int tw = (int)usurf_text_width(&screen, label);
 
 	usurf_fill(&screen, x, y, w, h, 0x963CD2u);
-	while (label[n])
-		n++;
-	usurf_text(&screen, (int)(x + (w - n * 8) / 2), (int)(y + 3),
+	usurf_text(&screen, (int)x + ((int)w - tw) / 2, (int)(y + 3),
 		   label, COL_WHITE, 0, 0, fbw, WM_BAR_H);
 }
 
@@ -221,8 +219,9 @@ static void draw_bar(void)
 			dt[n + i] = (i < dots) ? '.' : ' ';
 		n += 12;
 		dt[n] = '\0';
-		usurf_text(&screen, (int)fbw - (int)n * 8 - 4, 5, dt,
-			   0xFFC864u, 0, 0, fbw, WM_BAR_H);
+		usurf_text(&screen,
+			   (int)fbw - (int)usurf_text_width(&screen, dt) - 4,
+			   5, dt, 0xFFC864u, 0, 0, fbw, WM_BAR_H);
 	} else {
 		unsigned int clock_chars = 0;
 		int right = (int)fbw - 4;
@@ -232,16 +231,19 @@ static void draw_bar(void)
 			n = 0;
 			while (dt[n] && n < sizeof(dt) - 1)
 				n++;
-			usurf_text(&screen, right - (int)n * 8, 5, dt,
-				   COL_BANNER, 0, 0, fbw, WM_BAR_H);
-			clock_chars = n;
+			usurf_text(&screen,
+				   right - (int)usurf_text_width(&screen, dt),
+				   5, dt, COL_BANNER, 0, 0, fbw, WM_BAR_H);
+			clock_chars = (unsigned int)usurf_text_width(&screen, dt);
 		}
 		if (clock_chars)
-			right -= (int)clock_chars * 8 + 8;
+			right -= (int)clock_chars + 8;
 		if (bar_temp_c >= 0) {
 			char tb[12];
-			unsigned int tn = temp_text(tb, bar_temp_c);
-			int tx = right - (int)tn * 8;
+			int tx;
+
+			(void)temp_text(tb, bar_temp_c);
+			tx = right - (int)usurf_text_width(&screen, tb);
 
 			if (tx >= min_x) {
 				usurf_text(&screen, tx, 5, tb,
@@ -252,8 +254,10 @@ static void draw_bar(void)
 		}
 		if (bar_batt_pct >= 0) {
 			char bb[10];
-			unsigned int bn = batt_text(bb, bar_batt_pct);
-			int bx = right - (int)bn * 8;
+			int bx;
+
+			(void)batt_text(bb, bar_batt_pct);
+			bx = right - (int)usurf_text_width(&screen, bb);
 
 			if (bx >= min_x)
 				usurf_text(&screen, bx, 5, bb,
@@ -1029,6 +1033,7 @@ void _start(const char *arg)
 	if (u_wm_attach(&si) != 0)
 		u_exit(1);
 	usurf_init(&screen, si.fb, si.width, si.height, si.pitch, si.bpp);
+	usurf_font_attach(&screen, "/ramfs/fonts/sans.ttf", 14);
 	fbw = si.width;
 	fbh = si.height;
 	for (i = 0; i < WM_MAX_WINDOWS; i++) {

+ 303 - 0
ufont.c

@@ -0,0 +1,303 @@
+/* ufont: face registry, glyph cache and text metrics on top of the
+ * fixed-point TrueType backend in ufont_ttf.c. */
+#include "ufont.h"
+#include "ufont_internal.h"
+#include <stdlib.h>
+#include <string.h>
+
+struct ufont_cache_ent {
+	const struct ufont_face *face;
+	unsigned int cp;
+	unsigned char px;
+	unsigned char used;
+	struct ufont_glyph g;
+};
+
+static unsigned char *arena;
+static unsigned int arena_cap;
+static unsigned int arena_used;
+static unsigned int glyph_base;
+static struct ufont_face *faces[UFONT_MAX_FACES];
+static int nfaces;
+static struct ufont_cache_ent cache[UFONT_CACHE_SLOTS];
+
+void *ufont_arena_alloc(unsigned int bytes, unsigned int align)
+{
+	unsigned int p;
+
+	if (!arena || align == 0)
+		return 0;
+	p = (arena_used + align - 1u) & ~(align - 1u);
+	if (p > arena_cap || bytes > arena_cap - p)
+		return 0;
+	arena_used = p + bytes;
+	return arena + p;
+}
+
+void ufont_arena_mark(unsigned int mark)
+{
+	if (mark <= arena_cap)
+		arena_used = mark;
+}
+
+unsigned int ufont_arena_used(void)
+{
+	return arena_used;
+}
+
+static void cache_clear(void)
+{
+	unsigned int i;
+
+	for (i = 0; i < UFONT_CACHE_SLOTS; i++)
+		cache[i].used = 0;
+	if (glyph_base)
+		arena_used = glyph_base;
+}
+
+int ufont_arena_init(void)
+{
+	if (arena)
+		return 0;
+	arena = (unsigned char *)malloc(UFONT_ARENA_BYTES);
+	if (!arena)
+		return -1;
+	arena_cap = UFONT_ARENA_BYTES;
+	arena_used = 0;
+	glyph_base = 0;
+	nfaces = 0;
+	memset(faces, 0, sizeof(faces));
+	memset(cache, 0, sizeof(cache));
+	return 0;
+}
+
+void ufont_reset(void)
+{
+	if (arena)
+		free(arena);
+	arena = 0;
+	arena_cap = 0;
+	arena_used = 0;
+	glyph_base = 0;
+	nfaces = 0;
+	memset(faces, 0, sizeof(faces));
+	memset(cache, 0, sizeof(cache));
+}
+
+struct ufont_face *ufont_face_open_mem(const void *data, unsigned int len)
+{
+	struct ufont_face *f;
+	unsigned char *copy;
+	unsigned int mark;
+
+	if (!data || len == 0 || len > UFONT_MAX_FILE)
+		return 0;
+	if (ufont_arena_init() != 0)
+		return 0;
+	if (nfaces >= UFONT_MAX_FACES)
+		return 0;
+	if (glyph_base)
+		cache_clear();
+	mark = arena_used;
+	copy = (unsigned char *)ufont_arena_alloc(len, 4);
+	if (!copy) {
+		ufont_arena_mark(mark);
+		return 0;
+	}
+	memcpy(copy, data, len);
+	f = (struct ufont_face *)ufont_arena_alloc(sizeof(*f), 8);
+	if (!f) {
+		ufont_arena_mark(mark);
+		return 0;
+	}
+	memset(f, 0, sizeof(*f));
+	f->id = (unsigned int)nfaces;
+	if (ufont_ttf_load(f, copy, len) != 0) {
+		ufont_arena_mark(mark);
+		return 0;
+	}
+	faces[nfaces++] = f;
+	glyph_base = arena_used;
+	return f;
+}
+
+void ufont_metrics(const struct ufont_face *f, int px, struct ufont_metrics *m)
+{
+	int asc, desc, gap;
+
+	if (!m)
+		return;
+	memset(m, 0, sizeof(*m));
+	if (!f || px < 4)
+		return;
+	asc = (int)(((long)f->ascent * px + f->upem / 2) / f->upem);
+	desc = (int)(((long)-f->descent * px + f->upem / 2) / f->upem);
+	gap = (int)(((long)f->line_gap * px + f->upem / 2) / f->upem);
+	if (asc < 1)
+		asc = px - 2;
+	if (desc < 1)
+		desc = 2;
+	if (gap < 0)
+		gap = 0;
+	m->ascent = asc;
+	m->descent = desc;
+	m->line_gap = gap;
+	m->line_height = asc + desc + gap;
+}
+
+static unsigned int next_cp(const char *s, int *i, int n, int utf8)
+{
+	unsigned int c;
+	int p = *i;
+
+	if (!utf8) {
+		c = (unsigned char)s[p];
+		*i = p + 1;
+		return c;
+	}
+	c = (unsigned char)s[p++];
+	if (c < 0x80) {
+		*i = p;
+		return c;
+	}
+	if ((c & 0xE0) == 0xC0 && (n < 0 || p < n)) {
+		unsigned int c2 = (unsigned char)s[p];
+		if ((c2 & 0xC0) == 0x80) {
+			*i = p + 1;
+			return ((c & 0x1F) << 6) | (c2 & 0x3F);
+		}
+	} else if ((c & 0xF0) == 0xE0 && (n < 0 || p + 1 < n)) {
+		unsigned int c2 = (unsigned char)s[p];
+		unsigned int c3 = (unsigned char)s[p + 1];
+		if ((c2 & 0xC0) == 0x80 && (c3 & 0xC0) == 0x80) {
+			*i = p + 2;
+			return ((c & 0x0F) << 12) | ((c2 & 0x3F) << 6) |
+			       (c3 & 0x3F);
+		}
+	} else if ((c & 0xF8) == 0xF0 && (n < 0 || p + 2 < n)) {
+		unsigned int c2 = (unsigned char)s[p];
+		unsigned int c3 = (unsigned char)s[p + 1];
+		unsigned int c4 = (unsigned char)s[p + 2];
+		if ((c2 & 0xC0) == 0x80 && (c3 & 0xC0) == 0x80 &&
+		    (c4 & 0xC0) == 0x80) {
+			*i = p + 3;
+			return ((c & 0x07) << 18) | ((c2 & 0x3F) << 12) |
+			       ((c3 & 0x3F) << 6) | (c4 & 0x3F);
+		}
+	}
+	*i = p;
+	return 0xFFFD;
+}
+
+int ufont_text_width(const struct ufont_face *f, int px,
+		     const char *s, int n, int utf8)
+{
+	int i = 0, total = 0;
+
+	if (!f || !s || px < 4)
+		return 0;
+	if (n < 0) {
+		n = 0;
+		while (s[n])
+			n++;
+	}
+	while (i < n) {
+		unsigned int cp = next_cp(s, &i, n, utf8);
+		int glyph = ufont_ttf_glyph_index(f, cp);
+
+		total += ufont_ttf_advance(f, glyph, px);
+	}
+	return (total + 32) >> 6;
+}
+
+static struct ufont_cache_ent *cache_lookup(const struct ufont_face *f,
+					    int px, unsigned int cp)
+{
+	unsigned int start, i;
+
+	start = (cp * 2654435761u) ^ ((unsigned int)px << 16) ^
+		(f->id * 0x9E3779B1u);
+	start &= UFONT_CACHE_SLOTS - 1u;
+	for (i = 0; i < UFONT_CACHE_SLOTS; i++) {
+		struct ufont_cache_ent *e =
+			&cache[(start + i) & (UFONT_CACHE_SLOTS - 1u)];
+
+		if (!e->used)
+			return 0;
+		if (e->face == f && e->px == (unsigned char)px && e->cp == cp)
+			return e;
+	}
+	return 0;
+}
+
+static struct ufont_cache_ent *cache_free_slot(const struct ufont_face *f,
+					       int px, unsigned int cp)
+{
+	unsigned int start, i;
+
+	start = (cp * 2654435761u) ^ ((unsigned int)px << 16) ^
+		(f->id * 0x9E3779B1u);
+	start &= UFONT_CACHE_SLOTS - 1u;
+	for (i = 0; i < UFONT_CACHE_SLOTS; i++) {
+		struct ufont_cache_ent *e =
+			&cache[(start + i) & (UFONT_CACHE_SLOTS - 1u)];
+
+		if (!e->used) {
+			e->used = 1;
+			e->face = f;
+			e->px = (unsigned char)px;
+			e->cp = cp;
+			memset(&e->g, 0, sizeof(e->g));
+			return e;
+		}
+	}
+	return 0;
+}
+
+const struct ufont_glyph *ufont_glyph(const struct ufont_face *f, int px,
+				      unsigned int cp)
+{
+	struct ufont_cache_ent *e;
+	int glyph, advance, xoff, yoff, w, h;
+	unsigned char *mask;
+	int attempt;
+
+	if (!f || px < 4)
+		return 0;
+	if (px > 96)
+		px = 96;
+	e = cache_lookup(f, px, cp);
+	if (e)
+		return &e->g;
+
+	for (attempt = 0; attempt < 2; attempt++) {
+		e = cache_free_slot(f, px, cp);
+		if (!e) {
+			cache_clear();
+			continue;
+		}
+		glyph = ufont_ttf_glyph_index(f, cp);
+		advance = ufont_ttf_advance(f, glyph, px);
+		xoff = yoff = w = h = 0;
+		ufont_ttf_bbox(f, glyph, px, &xoff, &yoff, &w, &h);
+		e->g.advance = advance;
+		e->g.xoff = (short)xoff;
+		e->g.yoff = (short)yoff;
+		e->g.w = (unsigned short)w;
+		e->g.h = (unsigned short)h;
+		if (w <= 0 || h <= 0)
+			return &e->g;
+		mask = (unsigned char *)ufont_arena_alloc(
+			(unsigned int)w * (unsigned int)h, 1);
+		if (!mask) {
+			e->used = 0;
+			cache_clear();
+			continue;
+		}
+		memset(mask, 0, (unsigned int)w * (unsigned int)h);
+		ufont_ttf_raster(f, glyph, px, xoff, yoff, w, h, mask);
+		e->g.mask = mask;
+		return &e->g;
+	}
+	return 0;
+}

+ 66 - 0
ufont.h

@@ -0,0 +1,66 @@
+/* Userland text engine: fixed-point TrueType faces, Latin-1/UTF-8 text
+ * measurement and antialiased glyph bitmaps.
+ *
+ * Faces and glyph masks live in one heap arena owned by this module.  The
+ * arena is deliberately reset by ngui_font_detach()/ufont_reset() because the
+ * browser calls heap_reset() on navigation; no pointer from this module may
+ * survive that call. */
+#ifndef UFONT_H
+#define UFONT_H
+
+#include <stddef.h>
+
+#define UFONT_ARENA_BYTES   (256u * 1024u)
+#define UFONT_MAX_FILE      (256u * 1024u)
+#define UFONT_CACHE_SLOTS   512
+
+struct ufont_face;
+
+struct ufont_glyph {
+	const unsigned char *mask;  /* alpha, w*h bytes, row-major */
+	unsigned short w, h;
+	short xoff, yoff;           /* bitmap origin relative to pen/baseline */
+	int advance;                /* 26.6 pixels */
+};
+
+struct ufont_metrics {
+	int ascent;                 /* pixels above the baseline */
+	int descent;                /* pixels below the baseline */
+	int line_gap;
+	int line_height;
+};
+
+/* Allocate the shared arena (256 KB).  Returns 0 on success. */
+int ufont_arena_init(void);
+void ufont_reset(void);
+
+/* Open a face from memory or from a VFS path.  The path form lives in
+ * ufont_file.c and is not linked into the host tests. */
+struct ufont_face *ufont_face_open_mem(const void *data, unsigned int len);
+struct ufont_face *ufont_face_open_path(const char *path);
+
+void ufont_metrics(const struct ufont_face *face, int px,
+		   struct ufont_metrics *out);
+
+/* Width in whole pixels.  n < 0 means NUL-terminated; utf8 selects the
+ * decoder (0 = Latin-1 / one byte per codepoint). */
+int ufont_text_width(const struct ufont_face *face, int px,
+		     const char *s, int n, int utf8);
+
+/* Cached alpha bitmap for one codepoint. */
+const struct ufont_glyph *ufont_glyph(const struct ufont_face *face, int px,
+				      unsigned int cp);
+
+/* Alpha blend one glyph.  The mask is positioned at
+ * (x + g->xoff, baseline + g->yoff).  Returns the number of touched pixels. */
+int ufont_blit_rgb565(unsigned short *px, int w, int h,
+		      int x, int baseline, const struct ufont_glyph *g,
+		      unsigned short color,
+		      int cx, int cy, int cw, int ch);
+
+int ufont_blit_rgb(void *px, int w, int h, int pitch, int bpp,
+		   int x, int baseline, const struct ufont_glyph *g,
+		   unsigned int rgb,
+		   int cx, int cy, int cw, int ch);
+
+#endif

+ 126 - 0
ufont_draw.c

@@ -0,0 +1,126 @@
+/* Alpha-blended glyph blitters.  Separate from the rasterizer so ngui
+ * (RGB565 canvas) and uwm_lib (16/24/32-bit shadow) share the same math. */
+#include "ufont.h"
+
+int ufont_blit_rgb565(unsigned short *px, int w, int h,
+		      int x, int baseline, const struct ufont_glyph *g,
+		      unsigned short color,
+		      int cx, int cy, int cw, int ch)
+{
+	int row, col, touched = 0;
+	int fr, fg, fb;
+
+	if (!px || !g || !g->mask || w <= 0 || h <= 0)
+		return 0;
+	fr = (color >> 11) & 0x1F;
+	fg = (color >> 5) & 0x3F;
+	fb = color & 0x1F;
+	for (row = 0; row < (int)g->h; row++) {
+		int py = baseline + g->yoff + row;
+
+		if (py < 0 || py >= h || py < cy || py >= cy + ch)
+			continue;
+		for (col = 0; col < (int)g->w; col++) {
+			int px_x = x + g->xoff + col;
+			unsigned int a;
+
+			if (px_x < 0 || px_x >= w || px_x < cx ||
+			    px_x >= cx + cw)
+				continue;
+			a = g->mask[row * (int)g->w + col];
+			if (!a)
+				continue;
+			if (a >= 255) {
+				px[py * w + px_x] = color;
+			} else {
+				unsigned int d = px[py * w + px_x];
+				unsigned int dr = (d >> 11) & 0x1F;
+				unsigned int dg = (d >> 5) & 0x3F;
+				unsigned int db = d & 0x1F;
+				unsigned int r = (fr * a + dr * (255 - a) +
+						  127) / 255;
+				unsigned int gg = (fg * a + dg * (255 - a) +
+						   127) / 255;
+				unsigned int b = (fb * a + db * (255 - a) +
+						  127) / 255;
+
+				px[py * w + px_x] =
+					(unsigned short)((r << 11) |
+							 (gg << 5) | b);
+			}
+			touched++;
+		}
+	}
+	return touched;
+}
+
+int ufont_blit_rgb(void *pxv, int w, int h, int pitch, int bpp,
+		   int x, int baseline, const struct ufont_glyph *g,
+		   unsigned int rgb,
+		   int cx, int cy, int cw, int ch)
+{
+	unsigned char *px = (unsigned char *)pxv;
+	unsigned int fr = (rgb >> 16) & 0xFF;
+	unsigned int fg = (rgb >> 8) & 0xFF;
+	unsigned int fb = rgb & 0xFF;
+	int row, col, touched = 0;
+
+	if (!px || !g || !g->mask || w <= 0 || h <= 0)
+		return 0;
+	for (row = 0; row < (int)g->h; row++) {
+		int py = baseline + g->yoff + row;
+		unsigned char *line;
+
+		if (py < 0 || py >= h || py < cy || py >= cy + ch)
+			continue;
+		line = px + (unsigned long)py * (unsigned int)pitch;
+		for (col = 0; col < (int)g->w; col++) {
+			int gx = x + g->xoff + col;
+			unsigned int a;
+			unsigned char *d;
+
+			if (gx < 0 || gx >= w || gx < cx || gx >= cx + cw)
+				continue;
+			a = g->mask[row * (int)g->w + col];
+			if (!a)
+				continue;
+			if (bpp == 16) {
+				unsigned short *sp = (unsigned short *)line;
+				unsigned short dst = sp[gx];
+				unsigned int dr = (dst >> 11) & 0x1F;
+				unsigned int dg = (dst >> 5) & 0x3F;
+				unsigned int db = dst & 0x1F;
+				unsigned int sr = (fr >> 3);
+				unsigned int sg = (fg >> 2);
+				unsigned int sb = (fb >> 3);
+				unsigned int r = (sr * a + dr * (255 - a) +
+						  127) / 255;
+				unsigned int gg = (sg * a + dg * (255 - a) +
+						   127) / 255;
+				unsigned int b = (sb * a + db * (255 - a) +
+						  127) / 255;
+
+				sp[gx] = (unsigned short)((r << 11) |
+							  (gg << 5) | b);
+			} else {
+				d = line + (unsigned int)gx * (unsigned int)(bpp / 8);
+				if (a >= 255) {
+					d[0] = (unsigned char)fb;
+					d[1] = (unsigned char)fg;
+					d[2] = (unsigned char)fr;
+				} else {
+					d[0] = (unsigned char)((fb * a +
+						d[0] * (255 - a) + 127) / 255);
+					d[1] = (unsigned char)((fg * a +
+						d[1] * (255 - a) + 127) / 255);
+					d[2] = (unsigned char)((fr * a +
+						d[2] * (255 - a) + 127) / 255);
+				}
+				if (bpp == 32)
+					d[3] = 0xFF;
+			}
+			touched++;
+		}
+	}
+	return touched;
+}

+ 31 - 0
ufont_file.c

@@ -0,0 +1,31 @@
+/* VFS face loading for ring-3 commands.  The host tests use
+ * ufont_face_open_mem() and do not link this file. */
+#include "ufont.h"
+#include "ucmd_lib.h"
+#include <stdlib.h>
+#include <string.h>
+
+struct ufont_face *ufont_face_open_path(const char *path)
+{
+	struct sys_stat st;
+	unsigned char *buf;
+	struct ufont_face *f;
+	int n;
+
+	if (!path || u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
+	    st.size > UFONT_MAX_FILE - 512u)
+		return 0;
+	/* FAT reads may write a final partial sector past the requested
+	 * length; keep the slack inside the buffer. */
+	buf = (unsigned char *)malloc(st.size + 512u);
+	if (!buf)
+		return 0;
+	n = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
+	if (n != (int)st.size) {
+		free(buf);
+		return 0;
+	}
+	f = ufont_face_open_mem(buf, st.size);
+	free(buf);
+	return f;
+}

+ 55 - 0
ufont_internal.h

@@ -0,0 +1,55 @@
+/* Internal interfaces between the ufont cache/metrics layer and the
+ * fixed-point TrueType parser/rasterizer.  Not part of the app ABI. */
+#ifndef UFONT_INTERNAL_H
+#define UFONT_INTERNAL_H
+
+#define UFONT_MAX_FACES   8
+#define UFONT_MAX_POINTS  256
+#define UFONT_MAX_CONTOURS 16
+
+struct ufont_face {
+	unsigned int id;
+	const unsigned char *data;
+	unsigned int len;
+
+	int upem;
+	int num_glyphs;
+	int loca_short;
+	int num_hmetrics;
+
+	int ascent;        /* font units, hhea */
+	int descent;       /* font units, negative */
+	int line_gap;      /* font units */
+
+	const unsigned char *loca;
+	const unsigned char *glyf;
+	unsigned int glyf_len;
+	const unsigned char *hmtx;
+	const unsigned char *cmap4;
+	unsigned int cmap4_len;
+};
+
+/* Parse the sfnt directory and fill the face; 0 on success. */
+int ufont_ttf_load(struct ufont_face *f, const unsigned char *data,
+		   unsigned int len);
+
+int ufont_ttf_glyph_index(const struct ufont_face *f, unsigned int cp);
+
+/* Advance in 26.6 pixels. */
+int ufont_ttf_advance(const struct ufont_face *f, int glyph, int px);
+
+/* Bitmap box relative to the pen origin (x right, y down from baseline).
+ * Returns 0 on success; w/h are 0 for an empty glyph. */
+int ufont_ttf_bbox(const struct ufont_face *f, int glyph, int px,
+		   int *xoff, int *yoff, int *w, int *h);
+
+/* Rasterize into mask[w*h] (zeroed by the caller); 0 on success. */
+int ufont_ttf_raster(const struct ufont_face *f, int glyph, int px,
+		     int xoff, int yoff, int w, int h, unsigned char *mask);
+
+/* Arena helpers shared with ufont.c. */
+void *ufont_arena_alloc(unsigned int bytes, unsigned int align);
+void ufont_arena_mark(unsigned int mark);
+unsigned int ufont_arena_used(void);
+
+#endif

+ 124 - 0
ufont_test.c

@@ -0,0 +1,124 @@
+/* Host-side ufont smoke test: parse the bundled Arimo subset, measure and
+ * render a specimen to /tmp/opencode/ufont-test.ppm. */
+#include "ufont.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+static unsigned char *read_file(const char *path, unsigned int *len)
+{
+	FILE *f = fopen(path, "rb");
+	long n;
+	unsigned char *p;
+
+	if (!f)
+		return 0;
+	fseek(f, 0, SEEK_END);
+	n = ftell(f);
+	fseek(f, 0, SEEK_SET);
+	if (n <= 0 || n > (long)UFONT_MAX_FILE) {
+		fclose(f);
+		return 0;
+	}
+	p = (unsigned char *)malloc((size_t)n);
+	if (!p || fread(p, 1, (size_t)n, f) != (size_t)n) {
+		free(p);
+		fclose(f);
+		return 0;
+	}
+	fclose(f);
+	*len = (unsigned int)n;
+	return p;
+}
+
+static int draw_text(unsigned short *fb, int w, int h, int x, int baseline,
+		     const struct ufont_face *face, int px, const char *s)
+{
+	int pen = 0;
+	unsigned short color = 0xFFFF;
+
+	while (*s) {
+		const struct ufont_glyph *g =
+			ufont_glyph(face, px, (unsigned char)*s);
+
+		if (g) {
+			ufont_blit_rgb565(fb, w, h, x + (pen >> 6), baseline,
+					  g, color, 0, 0, w, h);
+			pen += g->advance;
+		}
+		s++;
+	}
+	return (pen + 32) >> 6;
+}
+
+int main(void)
+{
+	unsigned char *data;
+	unsigned int len = 0;
+	struct ufont_face *face;
+	struct ufont_metrics m;
+	int sizes[] = { 12, 16, 24, 32 };
+	unsigned int si;
+	unsigned short *fb;
+	int W = 720, H = 440;
+	FILE *out;
+	int i;
+
+	data = read_file("fonts/sans.ttf", &len);
+	if (!data) {
+		fprintf(stderr, "cannot read fonts/sans.ttf\n");
+		return 1;
+	}
+	/* A truncated sfnt must be rejected without touching the arena. */
+	if (ufont_face_open_mem(data, 64) != 0) {
+		fprintf(stderr, "truncated font was accepted\n");
+		return 1;
+	}
+	face = ufont_face_open_mem(data, len);
+	if (!face) {
+		fprintf(stderr, "cannot parse font\n");
+		return 1;
+	}
+	ufont_metrics(face, 16, &m);
+	printf("16px: ascent=%d descent=%d gap=%d line=%d\n",
+	       m.ascent, m.descent, m.line_gap, m.line_height);
+	printf("width 'Hello, world!' 16=%d 24=%d 32=%d\n",
+	       ufont_text_width(face, 16, "Hello, world!", -1, 0),
+	       ufont_text_width(face, 24, "Hello, world!", -1, 0),
+	       ufont_text_width(face, 32, "Hello, world!", -1, 0));
+	printf("width composite 'Äé' 16=%d\n",
+	       ufont_text_width(face, 16, "\xC3\x84\xC3\xA9", -1, 1));
+
+	fb = (unsigned short *)calloc((size_t)W * H, sizeof(unsigned short));
+	if (!fb)
+		return 1;
+	for (si = 0; si < sizeof(sizes) / sizeof(sizes[0]); si++) {
+		int px = sizes[si];
+		int y = 20 + (int)si * 100;
+
+		ufont_metrics(face, px, &m);
+		draw_text(fb, W, H, 8, y, face, px,
+			  "The quick brown fox jumps over 1234567890");
+		draw_text(fb, W, H, 8, y + 34, face, px,
+			  "\xC4rger \xE9 \xFC \xDF \xA9 \xAE \xB0 \xB1");
+	}
+	out = fopen("/tmp/opencode/ufont-test.ppm", "wb");
+	if (!out)
+		return 1;
+	fprintf(out, "P6\n%d %d\n255\n", W, H);
+	for (i = 0; i < W * H; i++) {
+		unsigned short c = fb[i];
+		unsigned char rgb[3];
+
+		rgb[0] = (unsigned char)(((c >> 11) & 0x1F) * 255 / 31);
+		rgb[1] = (unsigned char)(((c >> 5) & 0x3F) * 255 / 63);
+		rgb[2] = (unsigned char)((c & 0x1F) * 255 / 31);
+		fwrite(rgb, 1, 3, out);
+	}
+	fclose(out);
+	printf("wrote /tmp/opencode/ufont-test.ppm\n");
+	ufont_reset();
+	free(fb);
+	free(data);
+	return 0;
+}

+ 785 - 0
ufont_ttf.c

@@ -0,0 +1,785 @@
+/* Minimal fixed-point TrueType parser and rasterizer.
+ *
+ * No floats, no hinting, no CFF.  Supports the tables and glyph forms that the
+ * Latin-1 Arimo/Liberation subsets use: simple and composite glyphs, cmap
+ * format 4, short/long loca, hmtx advances.  Coordinates are scaled to 26.6
+ * pixels; coverage is 4x vertical supersampling with exact horizontal spans.
+ */
+#include "ufont_internal.h"
+#include <string.h>
+
+#define TTF_MAX_EDGES 2048
+
+struct ttf_point {
+	int x, y;
+	unsigned char on;
+};
+
+struct ttf_outline {
+	int npoints;
+	int ncontours;
+	unsigned short ends[UFONT_MAX_CONTOURS];
+	struct ttf_point points[UFONT_MAX_POINTS];
+};
+
+struct ttf_seq_point {
+	int x, y;
+	unsigned char on;
+};
+
+struct ttf_edge {
+	int x0, y0, x1, y1;
+	signed char dir;
+};
+
+static struct ttf_outline comp_outline[4];
+static struct ttf_seq_point seq_points[UFONT_MAX_POINTS * 2];
+static struct ttf_edge edges[TTF_MAX_EDGES];
+static int n_edges;
+
+static unsigned int be16(const unsigned char *p)
+{
+	return ((unsigned int)p[0] << 8) | p[1];
+}
+
+static int sbe16(const unsigned char *p)
+{
+	return (int)(short)be16(p);
+}
+
+static unsigned int be32(const unsigned char *p)
+{
+	return ((unsigned int)p[0] << 24) | ((unsigned int)p[1] << 16) |
+	       ((unsigned int)p[2] << 8) | p[3];
+}
+
+static int tag_eq(const unsigned char *p, const char *tag)
+{
+	return p[0] == (unsigned char)tag[0] &&
+	       p[1] == (unsigned char)tag[1] &&
+	       p[2] == (unsigned char)tag[2] &&
+	       p[3] == (unsigned char)tag[3];
+}
+
+static const unsigned char *find_table(const unsigned char *data,
+				       unsigned int len, const char *tag,
+				       unsigned int *out_len)
+{
+	unsigned int n, i;
+	const unsigned char *dir;
+
+	if (len < 12)
+		return 0;
+	n = be16(data + 4);
+	dir = data + 12;
+	if (n > 64 || 12u + n * 16u > len)
+		return 0;
+	for (i = 0; i < n; i++) {
+		const unsigned char *r = dir + i * 16;
+		unsigned int off = be32(r + 8);
+		unsigned int l = be32(r + 12);
+
+		if (!tag_eq(r, tag))
+			continue;
+		if (off > len || l > len - off)
+			return 0;
+		if (out_len)
+			*out_len = l;
+		return data + off;
+	}
+	return 0;
+}
+
+int ufont_ttf_load(struct ufont_face *f, const unsigned char *data,
+		   unsigned int len)
+{
+	const unsigned char *head, *maxp, *hhea, *hmtx, *loca, *glyf, *cmap;
+	unsigned int head_len, maxp_len, hhea_len, hmtx_len, loca_len;
+	unsigned int glyf_len, cmap_len, i, nrec;
+	unsigned int cmap4_off = 0;
+
+	if (len < 12)
+		return -1;
+	/* 0x00010000 is TrueType; "true" also appears in older files. */
+	if (!((data[0] == 0 && data[1] == 1 && data[2] == 0 && data[3] == 0) ||
+	      (data[0] == 't' && data[1] == 'r' && data[2] == 'u' &&
+	       data[3] == 'e')))
+		return -1;
+	head = find_table(data, len, "head", &head_len);
+	maxp = find_table(data, len, "maxp", &maxp_len);
+	hhea = find_table(data, len, "hhea", &hhea_len);
+	hmtx = find_table(data, len, "hmtx", &hmtx_len);
+	loca = find_table(data, len, "loca", &loca_len);
+	glyf = find_table(data, len, "glyf", &glyf_len);
+	cmap = find_table(data, len, "cmap", &cmap_len);
+	if (!head || !maxp || !hhea || !hmtx || !loca || !glyf || !cmap)
+		return -1;
+	if (head_len < 54 || maxp_len < 6 || hhea_len < 36)
+		return -1;
+	if (be32(head + 12) != 0x5F0F3CF5u)   /* head.magicNumber */
+		return -1;
+
+	f->data = data;
+	f->len = len;
+	f->upem = be16(head + 18);
+	f->loca_short = sbe16(head + 50) == 0;
+	f->num_glyphs = be16(maxp + 4);
+	f->ascent = sbe16(hhea + 4);
+	f->descent = sbe16(hhea + 6);
+	f->line_gap = sbe16(hhea + 8);
+	f->num_hmetrics = be16(hhea + 34);
+	if (f->upem < 16 || f->upem > 16384 || f->num_glyphs < 1 ||
+	    f->num_glyphs > 65535)
+		return -1;
+	if (f->num_hmetrics < 1 || f->num_hmetrics > f->num_glyphs)
+		return -1;
+	if (loca_len < (f->loca_short ? (unsigned int)f->num_glyphs * 2u + 2u
+				      : (unsigned int)f->num_glyphs * 4u + 4u))
+		return -1;
+	if (hmtx_len < (unsigned int)f->num_hmetrics * 4u)
+		return -1;
+
+	/* Pick a format 4 Unicode cmap. */
+	if (cmap_len < 4)
+		return -1;
+	nrec = be16(cmap + 2);
+	if (nrec > 64 || 4u + nrec * 8u > cmap_len)
+		return -1;
+	for (i = 0; i < nrec; i++) {
+		const unsigned char *r = cmap + 4 + i * 8;
+		unsigned int off = be32(r + 4);
+		unsigned int plat = be16(r);
+		unsigned int enc = be16(r + 2);
+
+		if (off + 2 > cmap_len)
+			continue;
+		if (be16(cmap + off) != 4)
+			continue;
+		if (plat == 3 && (enc == 0 || enc == 1)) {
+			cmap4_off = off;
+			break;
+		}
+		if (plat == 0 && enc == 3 && !cmap4_off)
+			cmap4_off = off;
+	}
+	if (!cmap4_off || cmap4_off + 16 > cmap_len)
+		return -1;
+	if (be16(cmap + cmap4_off + 2) > cmap_len - cmap4_off)
+		return -1;
+
+	f->loca = loca;
+	f->glyf = glyf;
+	f->glyf_len = glyf_len;
+	f->hmtx = hmtx;
+	f->cmap4 = cmap + cmap4_off;
+	f->cmap4_len = be16(cmap + cmap4_off + 2);
+	return 0;
+}
+
+int ufont_ttf_glyph_index(const struct ufont_face *f, unsigned int cp)
+{
+	const unsigned char *c = f->cmap4;
+	unsigned int seg, i, end, start, delta, range;
+
+	if (cp > 0xFFFFu || !c || f->cmap4_len < 16)
+		return 0;
+	seg = be16(c + 6) / 2u;
+	if (seg == 0 || 16u + seg * 8u > f->cmap4_len)
+		return 0;
+	for (i = 0; i < seg; i++) {
+		end = be16(c + 14 + i * 2);
+		if (cp > end)
+			continue;
+		start = be16(c + 16 + seg * 2 + i * 2);
+		if (cp < start)
+			return 0;
+		delta = be16(c + 16 + seg * 4 + i * 2);
+		range = be16(c + 16 + seg * 6 + i * 2);
+		if (range == 0)
+			return (int)((cp + delta) & 0xFFFFu);
+		{
+			unsigned int ro = 16u + seg * 6u + i * 2u;
+			unsigned int addr = ro + range + (cp - start) * 2u;
+			unsigned int g;
+
+			if (addr + 2u > f->cmap4_len)
+				return 0;
+			g = be16(c + addr);
+			if (g)
+				g = (g + delta) & 0xFFFFu;
+			return (int)g;
+		}
+	}
+	return 0;
+}
+
+static const unsigned char *glyph_data(const struct ufont_face *f, int glyph,
+				       unsigned int *size)
+{
+	unsigned int a, b;
+
+	if (glyph < 0 || glyph >= f->num_glyphs)
+		return 0;
+	if (f->loca_short) {
+		a = be16(f->loca + glyph * 2u) * 2u;
+		b = be16(f->loca + glyph * 2u + 2u) * 2u;
+	} else {
+		a = be32(f->loca + glyph * 4u);
+		b = be32(f->loca + glyph * 4u + 4u);
+	}
+	if (b <= a || b > f->glyf_len)
+		return 0;
+	if (size)
+		*size = b - a;
+	return f->glyf + a;
+}
+
+int ufont_ttf_advance(const struct ufont_face *f, int glyph, int px)
+{
+	unsigned int units;
+
+	if (glyph < 0 || glyph >= f->num_glyphs)
+		glyph = 0;
+	if (glyph >= f->num_hmetrics)
+		glyph = f->num_hmetrics - 1;
+	units = be16(f->hmtx + glyph * 4u);
+	return (int)((units * (unsigned int)px * 64u + (unsigned int)f->upem / 2u)
+		     / (unsigned int)f->upem);
+}
+
+static int load_simple(const struct ufont_face *f, const unsigned char *g,
+		       unsigned int glen, struct ttf_outline *out)
+{
+	int ncontours = sbe16(g);
+	(void)f;
+	int i, j, npoints, flags, repeats;
+	unsigned int off;
+	unsigned char flag;
+	int x, y;
+
+	if (ncontours < 0 || ncontours > UFONT_MAX_CONTOURS)
+		return -1;
+	if (glen < 12u + (unsigned int)ncontours * 2u)
+		return -1;
+	out->ncontours = ncontours;
+	for (i = 0; i < ncontours; i++)
+		out->ends[i] = be16(g + 10 + i * 2);
+	npoints = ncontours ? (int)out->ends[ncontours - 1] + 1 : 0;
+	if (npoints < 0 || npoints > UFONT_MAX_POINTS)
+		return -1;
+	off = 10u + (unsigned int)ncontours * 2u;
+	if (off + 2u > glen)
+		return -1;
+	off += 2u + be16(g + off);     /* skip instructions */
+	if (off > glen)
+		return -1;
+
+	/* Flags, with the repeat bit expanded. */
+	{
+		unsigned char flags_buf[UFONT_MAX_POINTS];
+		int n = 0;
+
+		while (n < npoints) {
+			if (off >= glen)
+				return -1;
+			flag = g[off++];
+			flags_buf[n++] = flag;
+			if (flag & 0x08) {
+				if (off >= glen)
+					return -1;
+				repeats = g[off++];
+				while (repeats-- > 0 && n < npoints)
+					flags_buf[n++] = flag;
+			}
+		}
+		for (i = 0; i < npoints; i++) {
+			flags = flags_buf[i];
+			out->points[i].on = (flags & 0x01) != 0;
+			out->points[i].x = 0;
+			out->points[i].y = 0;
+		}
+		/* X deltas. */
+		x = 0;
+		for (i = 0; i < npoints; i++) {
+			flags = flags_buf[i];
+			if (flags & 0x02) {
+				if (off >= glen)
+					return -1;
+				j = g[off++];
+				x += (flags & 0x10) ? j : -j;
+			} else if (!(flags & 0x10)) {
+				if (off + 2u > glen)
+					return -1;
+				x += sbe16(g + off);
+				off += 2;
+			}
+			out->points[i].x = x;
+		}
+		/* Y deltas. */
+		y = 0;
+		for (i = 0; i < npoints; i++) {
+			flags = flags_buf[i];
+			if (flags & 0x04) {
+				if (off >= glen)
+					return -1;
+				j = g[off++];
+				y += (flags & 0x20) ? j : -j;
+			} else if (!(flags & 0x20)) {
+				if (off + 2u > glen)
+					return -1;
+				y += sbe16(g + off);
+				off += 2;
+			}
+			out->points[i].y = y;
+		}
+	}
+	out->npoints = npoints;
+	return 0;
+}
+
+static int load_glyph(const struct ufont_face *f, int glyph,
+		      struct ttf_outline *out, int depth);
+
+static int load_composite(const struct ufont_face *f, const unsigned char *g,
+			  unsigned int glen, struct ttf_outline *out, int depth)
+{
+	unsigned int off = 10;
+	int any = 0;
+
+	out->npoints = 0;
+	out->ncontours = 0;
+	if (depth >= 4)
+		return -1;
+	for (;;) {
+		unsigned int flags, comp, args[2];
+		int dx, dy, i, a, b, c, d;
+		struct ttf_outline *co;
+
+		if (off + 4u > glen)
+			return -1;
+		flags = be16(g + off);
+		comp = be16(g + off + 2);
+		off += 4;
+		if (flags & 0x0001) {
+			if (off + 4u > glen)
+				return -1;
+			args[0] = (unsigned int)sbe16(g + off);
+			args[1] = (unsigned int)sbe16(g + off + 2);
+			off += 4;
+		} else {
+			if (off + 2u > glen)
+				return -1;
+			args[0] = (unsigned int)(signed char)g[off];
+			args[1] = (unsigned int)(signed char)g[off + 1];
+			off += 2;
+		}
+		a = 0x10000; b = 0; c = 0; d = 0x10000;
+		if (flags & 0x0008) {
+			if (off + 2u > glen)
+				return -1;
+			a = d = sbe16(g + off) * 4;       /* F2Dot14 -> 16.16 */
+			off += 2;
+		} else if (flags & 0x0040) {
+			if (off + 4u > glen)
+				return -1;
+			a = sbe16(g + off) * 4;
+			d = sbe16(g + off + 2) * 4;
+			off += 4;
+		} else if (flags & 0x0080) {
+			if (off + 8u > glen)
+				return -1;
+			a = sbe16(g + off) * 4;
+			b = sbe16(g + off + 2) * 4;
+			c = sbe16(g + off + 4) * 4;
+			d = sbe16(g + off + 6) * 4;
+			off += 8;
+		}
+		if (comp >= (unsigned int)f->num_glyphs ||
+		    depth + 1 >= 4)
+			return -1;
+		co = &comp_outline[depth + 1];
+		if (load_glyph(f, (int)comp, co, depth + 1) != 0)
+			return -1;
+
+		/* Apply the component transform in font units. */
+		for (i = 0; i < co->npoints; i++) {
+			int x = co->points[i].x;
+			int y = co->points[i].y;
+
+			co->points[i].x = (a * x + c * y) >> 16;
+			co->points[i].y = (b * x + d * y) >> 16;
+		}
+		dx = 0;
+		dy = 0;
+		if (flags & 0x0002) {
+			dx = (int)args[0];
+			dy = (int)args[1];
+			if ((flags & 0x0800) && !(flags & 0x1000)) {
+				int tx = (a * dx + c * dy) >> 16;
+				int ty = (b * dx + d * dy) >> 16;
+
+				dx = tx;
+				dy = ty;
+			}
+		} else {
+			int p1 = (int)args[0];
+			int p2 = (int)args[1];
+
+			if (p1 >= 0 && p1 < out->npoints &&
+			    p2 >= 0 && p2 < co->npoints) {
+				dx = out->points[p1].x - co->points[p2].x;
+				dy = out->points[p1].y - co->points[p2].y;
+			}
+		}
+		if (out->npoints + co->npoints > UFONT_MAX_POINTS ||
+		    out->ncontours + co->ncontours > UFONT_MAX_CONTOURS)
+			return -1;
+		for (i = 0; i < co->npoints; i++) {
+			out->points[out->npoints + i] = co->points[i];
+			out->points[out->npoints + i].x += dx;
+			out->points[out->npoints + i].y += dy;
+		}
+		for (i = 0; i < co->ncontours; i++)
+			out->ends[out->ncontours + i] =
+				(unsigned short)(co->ends[i] + out->npoints);
+		out->npoints += co->npoints;
+		out->ncontours += co->ncontours;
+		any = 1;
+		if (!(flags & 0x0020))
+			break;
+	}
+	return any ? 0 : -1;
+}
+
+static int load_glyph(const struct ufont_face *f, int glyph,
+		      struct ttf_outline *out, int depth)
+{
+	const unsigned char *g;
+	unsigned int glen;
+	int ncontours;
+
+	g = glyph_data(f, glyph, &glen);
+	if (!g)
+		return -1;
+	if (glen < 10)
+		return -1;
+	ncontours = sbe16(g);
+	if (ncontours >= 0)
+		return load_simple(f, g, glen, out);
+	return load_composite(f, g, glen, out, depth);
+}
+
+static int scale_coord(const struct ufont_face *f, int v, int px)
+{
+	return (int)(((long)v * (long)px * 64L +
+		      (long)f->upem / 2L) / (long)f->upem);
+}
+
+static int floor_div64(int v)
+{
+	return v >= 0 ? v / 64 : -((-v + 63) / 64);
+}
+
+static int ceil_div64(int v)
+{
+	return v >= 0 ? (v + 63) / 64 : -((-v) / 64);
+}
+
+int ufont_ttf_bbox(const struct ufont_face *f, int glyph, int px,
+		   int *xoff, int *yoff, int *w, int *h)
+{
+	static struct ttf_outline out;
+	int i, minx, miny, maxx, maxy, x0, y0, x1, y1;
+
+	*xoff = 0;
+	*yoff = 0;
+	*w = 0;
+	*h = 0;
+	if (load_glyph(f, glyph, &out, 0) != 0 || out.npoints == 0)
+		return 0;
+	minx = maxx = scale_coord(f, out.points[0].x, px);
+	miny = maxy = -scale_coord(f, out.points[0].y, px);
+	for (i = 1; i < out.npoints; i++) {
+		int x = scale_coord(f, out.points[i].x, px);
+		int y = -scale_coord(f, out.points[i].y, px);
+
+		if (x < minx) minx = x;
+		if (x > maxx) maxx = x;
+		if (y < miny) miny = y;
+		if (y > maxy) maxy = y;
+	}
+	x0 = floor_div64(minx);
+	y0 = floor_div64(miny);
+	x1 = ceil_div64(maxx);
+	y1 = ceil_div64(maxy);
+	if (x1 <= x0) x1 = x0 + 1;
+	if (y1 <= y0) y1 = y0 + 1;
+	*xoff = x0;
+	*yoff = y0;
+	*w = x1 - x0;
+	*h = y1 - y0;
+	if (*w > 512 || *h > 512) {
+		*w = *h = 0;
+		return 0;
+	}
+	return 0;
+}
+
+static void add_edge(int x0, int y0, int x1, int y1)
+{
+	signed char dir;
+
+	if (y0 == y1 || n_edges >= TTF_MAX_EDGES)
+		return;
+	dir = 1;
+	if (y0 > y1) {
+		int t;
+		t = x0; x0 = x1; x1 = t;
+		t = y0; y0 = y1; y1 = t;
+		dir = -1;
+	}
+	edges[n_edges].x0 = x0;
+	edges[n_edges].y0 = y0;
+	edges[n_edges].x1 = x1;
+	edges[n_edges].y1 = y1;
+	edges[n_edges].dir = dir;
+	n_edges++;
+}
+
+static void flatten_quad(int x0, int y0, int cx, int cy, int x1, int y1,
+			 int depth)
+{
+	long dx = (long)x1 - x0;
+	long dy = (long)y1 - y0;
+	long cross = dx * ((long)cy - y0) - dy * ((long)cx - x0);
+	long lim = (dx < 0 ? -dx : dx) + (dy < 0 ? -dy : dy);
+
+	if (lim < 1)
+		lim = 1;
+	if (cross < 0)
+		cross = -cross;
+	if (depth >= 8 || cross <= lim * 2L) {
+		add_edge(x0, y0, x1, y1);
+		return;
+	}
+	{
+		int q0x = (x0 + cx) / 2, q0y = (y0 + cy) / 2;
+		int q1x = (cx + x1) / 2, q1y = (cy + y1) / 2;
+		int mx = (q0x + q1x) / 2, my = (q0y + q1y) / 2;
+
+		flatten_quad(x0, y0, q0x, q0y, mx, my, depth + 1);
+		flatten_quad(mx, my, q1x, q1y, x1, y1, depth + 1);
+	}
+}
+
+static void build_edges(const struct ufont_face *f, int px,
+			const struct ttf_outline *out)
+{
+	int c, start = 0;
+
+	n_edges = 0;
+	for (c = 0; c < out->ncontours; c++) {
+		int end = out->ends[c];
+		int count = end - start + 1;
+		int first_on = -1, i, n = 0;
+
+		if (count <= 1) {
+			start = end + 1;
+			continue;
+		}
+		for (i = 0; i < count; i++)
+			if (out->points[start + i].on) {
+				first_on = i;
+				break;
+			}
+		if (first_on < 0) {
+			/* All off-curve: insert a midpoint between every pair
+			 * and start at the midpoint before the first point. */
+			for (i = 0; i < count; i++) {
+				int a = start + i;
+				int b = start + ((i + 1) % count);
+
+				if (n < (int)(sizeof(seq_points) /
+					      sizeof(seq_points[0]))) {
+					seq_points[n].x =
+						(out->points[a].x +
+						 out->points[b].x) / 2;
+					seq_points[n].y =
+						(out->points[a].y +
+						 out->points[b].y) / 2;
+					seq_points[n].on = 1;
+					n++;
+				}
+				if (n < (int)(sizeof(seq_points) /
+					      sizeof(seq_points[0]))) {
+					seq_points[n] = (struct ttf_seq_point){
+						out->points[b].x,
+						out->points[b].y,
+						out->points[b].on
+					};
+					n++;
+				}
+			}
+		} else {
+			/* Rotate to the first on-curve point and insert
+			 * midpoints between consecutive off-curve points. */
+			for (i = 0; i < count; i++) {
+				int idx = start + (first_on + i) % count;
+				struct ttf_seq_point p;
+
+				p.x = out->points[idx].x;
+				p.y = out->points[idx].y;
+				p.on = out->points[idx].on;
+				if (n > 0 && !seq_points[n - 1].on && !p.on) {
+					seq_points[n].x =
+						(seq_points[n - 1].x + p.x) / 2;
+					seq_points[n].y =
+						(seq_points[n - 1].y + p.y) / 2;
+					seq_points[n].on = 1;
+					n++;
+				}
+				seq_points[n++] = p;
+				if (n >= (int)(sizeof(seq_points) /
+					       sizeof(seq_points[0])))
+					break;
+			}
+		}
+
+		for (i = 0; i < n; i++) {
+			struct ttf_seq_point a = seq_points[i];
+			struct ttf_seq_point b = seq_points[(i + 1) % n];
+			int ax = scale_coord(f, a.x, px);
+			int ay = -scale_coord(f, a.y, px);
+			int bx = scale_coord(f, b.x, px);
+			int by = -scale_coord(f, b.y, px);
+
+			if (b.on) {
+				add_edge(ax, ay, bx, by);
+			} else {
+				struct ttf_seq_point d =
+					seq_points[(i + 2) % n];
+				int cx = bx, cy = by;
+				int dx = scale_coord(f, d.x, px);
+				int dy = -scale_coord(f, d.y, px);
+
+				flatten_quad(ax, ay, cx, cy, dx, dy, 0);
+				i++;    /* the next point is consumed */
+			}
+		}
+		start = end + 1;
+	}
+}
+
+/* Add horizontal coverage of [xa, xb] (26.6, relative to xoff) to mask. */
+static void add_span(unsigned char *mask, int w, int h, int row,
+		     int xa, int xb)
+{
+	int pa, pb, p;
+	(void)h;
+
+	if (xa < 0)
+		xa = 0;
+	if (xb > w * 64)
+		xb = w * 64;
+	if (xb <= xa)
+		return;
+	pa = xa / 64;
+	pb = (xb + 63) / 64;
+	if (pa < 0)
+		pa = 0;
+	if (pb > w)
+		pb = w;
+	for (p = pa; p < pb; p++) {
+		int l = p * 64;
+		int r = (p + 1) * 64;
+		int cov;
+		int v;
+
+		if (l < xa) l = xa;
+		if (r > xb) r = xb;
+		cov = r - l;
+		if (cov <= 0)
+			continue;
+		v = mask[row * w + p] + cov;
+		if (v > 255)
+			v = 255;
+		mask[row * w + p] = (unsigned char)v;
+	}
+}
+
+int ufont_ttf_raster(const struct ufont_face *f, int glyph, int px,
+		     int xoff, int yoff, int w, int h, unsigned char *mask)
+{
+	static struct ttf_outline out;
+	int row, sub;
+
+	if (w <= 0 || h <= 0 || !mask)
+		return 0;
+	if (load_glyph(f, glyph, &out, 0) != 0 || out.npoints == 0)
+		return 0;
+	build_edges(f, px, &out);
+	if (n_edges == 0)
+		return 0;
+
+	for (row = 0; row < h; row++) {
+		for (sub = 0; sub < 4; sub++) {
+			int sy = ((yoff + row) * 64) + sub * 16 + 8;
+			static int xs[TTF_MAX_EDGES];
+			static signed char dirs[TTF_MAX_EDGES];
+			int n = 0, i, j, wind = 0, span = 0, span_x = 0;
+
+			for (i = 0; i < n_edges; i++) {
+				const struct ttf_edge *e = &edges[i];
+				long dy, num, x;
+
+				if (sy < e->y0 || sy >= e->y1)
+					continue;
+				dy = (long)e->y1 - e->y0;
+				if (dy == 0)
+					continue;
+				num = (long)(sy - e->y0) *
+				      ((long)e->x1 - e->x0);
+				x = e->x0 + num / dy;
+				if (n < TTF_MAX_EDGES) {
+					xs[n] = (int)x;
+					dirs[n] = e->dir;
+					n++;
+				}
+			}
+			/* Insertion sort by x. */
+			for (i = 1; i < n; i++) {
+				int xv = xs[i];
+				signed char dv = dirs[i];
+
+				j = i - 1;
+				while (j >= 0 && xs[j] > xv) {
+					xs[j + 1] = xs[j];
+					dirs[j + 1] = dirs[j];
+					j--;
+				}
+				xs[j + 1] = xv;
+				dirs[j + 1] = dv;
+			}
+			wind = 0;
+			span = 0;
+			span_x = 0;
+			for (i = 0; i < n; i++) {
+				if (wind == 0) {
+					span_x = xs[i];
+					span = 1;
+				}
+				wind += dirs[i];
+				if (wind == 0 && span) {
+					int xa = span_x - (xoff * 64);
+					int xb = xs[i] - (xoff * 64);
+
+					if (xb > xa)
+						add_span(mask, w, h, row,
+							 xa, xb);
+					span = 0;
+				}
+			}
+		}
+	}
+	return 0;
+}

+ 51 - 2
uwm_lib.c

@@ -3,6 +3,7 @@
 
 #include "uwm_lib.h"
 #include "font_8x16.h"
+#include "ufont.h"
 
 #define FONT_H 16
 
@@ -26,6 +27,30 @@ void usurf_init(struct usurf *s, void *px, unsigned int w, unsigned int h,
 	s->h = h;
 	s->pitch = pitch;
 	s->bpp = bpp;
+	s->font = 0;
+	s->font_px = 16;
+}
+
+void usurf_font_attach(struct usurf *s, const char *path, int px)
+{
+	if (!s)
+		return;
+	s->font_px = px;
+	s->font = ufont_face_open_path(path);
+}
+
+unsigned int usurf_text_width(struct usurf *s, const char *str)
+{
+	unsigned int n = 0;
+
+	if (!str)
+		return 0;
+	if (s && s->font)
+		return (unsigned int)ufont_text_width(s->font, s->font_px,
+						     str, -1, 0);
+	while (str[n])
+		n++;
+	return n * 8;
 }
 
 static void put_px(struct usurf *s, unsigned int x, unsigned int y,
@@ -226,10 +251,34 @@ void usurf_text(struct usurf *s, int x, int y, const char *str,
 		int cx, int cy, unsigned int cw, unsigned int ch)
 {
 	unsigned int i = 0;
+	struct ufont_metrics m;
+	int ascent, pen = 0;
 
+	if (!s || !str)
+		return;
+	if (!s->font) {
+		while (str[i]) {
+			usurf_glyph(s, x + (int)i * 8, y,
+				    (unsigned char)str[i], fg, 0, 1,
+				    FONT_H, cx, cy, cw, ch);
+			i++;
+		}
+		return;
+	}
+	ufont_metrics(s->font, s->font_px, &m);
+	ascent = m.ascent;
 	while (str[i]) {
-		usurf_glyph(s, x + (int)i * 8, y, (unsigned char)str[i],
-			    fg, 0, 1, FONT_H, cx, cy, cw, ch);
+		const struct ufont_glyph *g =
+			ufont_glyph(s->font, s->font_px,
+				    (unsigned char)str[i]);
+
+		if (g) {
+			usurf_pixels += (unsigned int)ufont_blit_rgb(
+				s->px, (int)s->w, (int)s->h, (int)s->pitch,
+				(int)s->bpp, x + (pen >> 6), y + ascent,
+				g, fg, cx, cy, cw, ch);
+			pen += g->advance;
+		}
 		i++;
 	}
 }

+ 6 - 0
uwm_lib.h

@@ -4,10 +4,14 @@
 #ifndef UWM_LIB_H
 #define UWM_LIB_H
 
+struct ufont_face;
+
 struct usurf {
 	unsigned char *px;
 	unsigned int w, h, pitch;
 	unsigned int bpp;          /* 16, 24 or 32 */
+	struct ufont_face *font;   /* NULL = 8x16 bitmap text */
+	int font_px;
 };
 
 struct uwm_canvas {
@@ -31,6 +35,8 @@ void usurf_glyph(struct usurf *s, int x, int y, unsigned char c,
 void usurf_text(struct usurf *s, int x, int y, const char *str,
 		unsigned int fg,
 		int cx, int cy, unsigned int cw, unsigned int ch);
+unsigned int usurf_text_width(struct usurf *s, const char *str);
+void usurf_font_attach(struct usurf *s, const char *path, int px);
 void usurf_cells(struct usurf *s, const unsigned short *cells,
 		 unsigned int cols, unsigned int rows,
 		 int x0, int y0,

+ 69 - 65
vesa_stage.S

@@ -2,14 +2,15 @@
  * VESA real-mode stage: runs at 0x7E00 before protected mode.
  *
  * Called by the boot sector in real mode (CS=0, IP=0x7E00).
- * Probes the E820 map, loads the compressed command-pack rootfs into the
- * low gap at 0x60000..0x9FBFF (16 KB staging chunks at 0x3000, BIOS disk
- * reads only), walks the VBE mode list and picks the best mode (highest
- * resolution, >= 16 bpp, LFB, fits in VRAM), writes the mode info to 0x600
- * and the boot info to 0x500, then enables A20, enters protected mode,
- * copies the pack above the 8 MB VGA-shadow reserve (PACK_HIGH_ADDR) and
- * jumps to kernel_entry.  Relocating the pack before the kernel runs lets
- * the kernel's BSS/boot stack extend past 0x60000.
+ * Probes the E820 map, loads the compressed command-pack rootfs in 16 KB
+ * chunks through the 0x3000 staging buffer and copies each chunk straight
+ * above the 8 MB VGA-shadow reserve (PACK_HIGH_ADDR) with the BIOS block
+ * move (INT 15h AH=87h), walks the VBE mode list and picks the best mode (highest resolution,
+ * >= 16 bpp, LFB, fits in VRAM), writes the mode info to 0x600 and the boot
+ * info to 0x500, then enables A20, enters protected mode and jumps to
+ * kernel_entry.  Because the pack never occupies the low gap behind the
+ * kernel, the pack size is bounded by RAM, not by 0x60000..0x9FBFF, and the
+ * kernel BSS/boot stack may extend far past 0x60000.
  *
  * If no VESA mode works, boots in text mode (valid=0 at 0x600).
  */
@@ -24,8 +25,7 @@
 
 /* Rootfs/boot-info constants (must match rootfs.h / bootinfo.h). */
 .equ ROOTFS_VERSION,   1
-.equ PACK_LOW_ADDR,    0x60000       /* low gap behind the kernel */
-.equ PACK_LOW_MAX,     0x3FBFF       /* 0x60000..0x9FBFF */
+.equ PACK_MAX,         0x80000       /* 512 KB compressed rootfs cap */
 .equ PACK_HIGH_ADDR,   0x900000      /* above the 8 MB VGA-shadow reserve */
 .equ BOOT_INFO_MAGIC,  0x4E425349
 .equ BOOT_INFO_VERSION, 2
@@ -90,11 +90,15 @@ e820_loop:
 	jmp   e820_loop
 e820_done:
 
-	/* ---- Rootfs: load the command pack into the low gap ----
+	/* ---- Rootfs: load the command pack directly to high memory ----
 	 * The pack is a gzip blob behind a one-sector NBROOT1 header (rootfs.h).
-	 * Keep the destination at 0x60000..0x9FBFF: above the kernel BSS/boot
-	 * stack, below the EBDA, and inside the low 1 MB the frame allocator
-	 * already reserves. */
+	 * Each 16 KB chunk is read into 0x3000 and copied to PACK_HIGH_ADDR with
+	 * INT 15h AH=87h, so the size is no longer limited by the
+	 * 0x60000..0x9FBFF low gap.  A20 must be on before the first high write;
+	 * the old path enabled it only at stage_finish.  The kernel sanitizes
+	 * CR4/EFER after this BIOS call (the X201 leaves translation state
+	 * behind). */
+	call  enable_a20
 	xorw  %ax, %ax
 	movw  %ax, %ds
 	movw  %ax, %es
@@ -159,7 +163,7 @@ e820_done:
 	movl  12(%esi), %eax          /* pack_bytes */
 	testl %eax, %eax
 	jz    pack_fail
-	cmpl  $PACK_LOW_MAX, %eax
+	cmpl  $PACK_MAX, %eax
 	ja    pack_fail
 	movl  %eax, pack_bytes
 	movw  $msg_dot, %si
@@ -187,10 +191,11 @@ load_loop:
 	movl  chunk_sectors, %eax
 	shll  $9, %eax
 	movl  %eax, copy_len
-	movl  $PACK_LOW_ADDR, %eax
+	movl  $PACK_HIGH_ADDR, %eax
 	addl  pack_off, %eax
 	movl  %eax, copy_dst
-	call  copy_low
+	call  bios_copy
+	jc    pack_fail
 	movl  chunk_sectors, %eax
 	shll  $9, %eax
 	addl  %eax, pack_off
@@ -199,7 +204,7 @@ load_loop:
 	jmp   load_loop
 
 load_ok:
-	movl  $PACK_LOW_ADDR, pack_addr
+	movl  $PACK_HIGH_ADDR, pack_addr
 	movw  $msg_ok, %si
 	call  print_str
 	jmp   pack_done
@@ -348,8 +353,8 @@ vesa_no_vbe:
 	movb  $0, (%bx)
 
 stage_finish:
-	/* The pack is loaded; enable A20 and enter protected mode. */
-	call  enable_a20
+	/* The pack is loaded (A20 is already on); finish boot info and enter
+	 * protected mode. */
 	call  write_bootinfo
 	jmp   enter_pm
 
@@ -465,27 +470,31 @@ print_str:
 	popw  %ax
 	ret
 
-/* ---- Copy the 16 KB staging chunk to the low pack destination --------- */
-copy_low:
-	/* Read the stage variables with DS=0 first; only then switch DS to the
-	 * staging segment.  Save both segment registers: the load loop and the
-	 * progress prints keep using DS=0/ES=0. */
+/* ---- Copy a chunk to high memory with INT 15h AH=87h ------------------
+ * in: copy_dst (24-bit), copy_len; source is 0x3000.
+ * Copies in 16-bit words; returns with CF set on failure.  The kernel's
+ * paging_prepare_cpu() sanitizes the CR4/EFER state this BIOS call can
+ * leave behind on the X201. */
+bios_copy:
 	movl  copy_dst, %eax
+	movw  %ax, bios_gdt + 0x1A      /* dest base 15:0 */
+	shrl  $16, %eax
+	movb  %al, bios_gdt + 0x1C      /* dest base 23:16 */
 	movl  copy_len, %ecx
-	movl  %eax, %ebx
-	shrl  $4, %eax
-	pushw %ds
-	pushw %es
+	addl  $1, %ecx                  /* round up for an odd final byte */
+	shrl  $1, %ecx                  /* AH=87h counts words */
+	jz    bios_copy_done
+	xorw  %ax, %ax
 	movw  %ax, %es
-	andl  $0x0000000F, %ebx
-	movw  %bx, %di
-	movw  $0x0300, %ax
-	movw  %ax, %ds
-	xorw  %si, %si
-	cld
-	rep movsb
-	popw  %es
-	popw  %ds
+	movw  $bios_gdt, %si
+	movw  $0x8700, %ax
+	int   $0x15
+	jc    bios_copy_fail
+bios_copy_done:
+	clc
+	ret
+bios_copy_fail:
+	stc
 	ret
 
 /* ---- Hex print (EAX, 8 digits) ----------------------------------------- */
@@ -565,33 +574,6 @@ stage2_pm:
 	movw  %ax, %gs
 	movw  %ax, %ss
 	movl  $__boot_stack_top, %esp
-
-	/* Move the pack out of the low gap before the kernel clears its BSS
-	 * or uses the boot stack (both may now live above 0x60000). */
-	cld
-	movl  pack_addr, %esi
-	testl %esi, %esi
-	jz    2f
-	movl  pack_bytes, %ecx
-	testl %ecx, %ecx
-	jz    2f
-	movl  $PACK_HIGH_ADDR, %edi
-	rep   movsb
-	movl  $PACK_HIGH_ADDR, pack_addr
-
-	/* Rewrite boot info: zero checksum, new pack address, recompute the
-	 * twelve-word sum (must match bootinfo.h / write_bootinfo). */
-	movl  $0, 0x508
-	movl  $PACK_HIGH_ADDR, 0x514
-	xorl  %eax, %eax
-	movl  $0x500, %esi
-	movl  $BOOT_INFO_WORDS, %ecx
-1:	addl  (%esi), %eax
-	addl  $4, %esi
-	loop  1b
-	negl  %eax
-	movl  %eax, 0x508
-2:
 	jmp   kernel_entry
 
 .align 4
@@ -606,6 +588,28 @@ stage2_gdtr:
 	.word stage2_gdt_end - stage2_gdt - 1
 	.long stage2_gdt
 
+/* ---- INT 15h AH=87h descriptor table (48 bytes) -----------------------
+ * 16 zero bytes, source descriptor at 0x10 (0x3000, 64 KB), destination
+ * at 0x18 (patched per chunk), 16 zero bytes. */
+.align 16
+bios_gdt:
+	.quad 0
+	.quad 0
+	/* source: limit 0xFFFF, base 0x3000, access 0x93, 16-bit data */
+	.word 0xFFFF
+	.word 0x3000
+	.byte 0x00
+	.byte 0x93
+	.word 0x0000
+	/* destination: limit 0xFFFF, base patched, access 0x93 */
+	.word 0xFFFF
+	.word 0x0000
+	.byte 0x00
+	.byte 0x93
+	.word 0x0000
+	.quad 0
+	.quad 0
+
 /* ---- Stage variables --------------------------------------------------- */
 .align 4
 stage_drive:    .byte 0