Просмотр исходного кода

browser: web fonts with WOFF, weight/style variants and lazy loading

@font-face used to take one regular TTF per family and load every
declared face.  Now:

- ufont_woff.c rebuilds the sfnt from a WOFF 1.0 file's per-table zlib
  streams (browser and host test only, since it needs inflate); WOFF2 is
  detected and skipped.
- The src list picks the first url() whose format() hint or extension
  is TrueType/OpenType/WOFF, skipping local(), woff2, eot, svg and data:.
- Each (family, weight or weight range, style) is its own entry;
  font_pick[family][bold*2+italic] holds the CSS font-matching choice,
  which layout reads.  Non-Latin unicode-range subsets are dropped.
- Only families named by font-family or the font shorthand (which now
  resolves custom families) are fetched, regular first; HTTP errors are
  refused and fonts are cached as /share/bfont-* for the boot.
- The browser's ufont arena is 3 MB (ufont_set_arena_bytes), the file
  cap 1 MB and the face table 32.
- FontFace and a set-like document.fonts exist for scripts.

make test-font covers the WOFF round trip (testdata/fonts/sans.woff,
built by tools/mkwoff.py); compat page 074 checks variants, src choice,
unicode-range and the shorthand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Johannes Zellner 2 дней назад
Родитель
Сommit
10f099b15c

+ 53 - 16
AGENTS.md

@@ -16,7 +16,7 @@ Targets i586 (first-gen Pentium); runs under QEMU or on real hardware.
 | `user/` | `ucmd_lib.h` (the ring-3 syscall wrappers) and `ucmd.ld` |
 | `user/apps/<name>/` | One ring-3 program per directory: entry file `ucmd_<name>.c` plus private modules (`browser/` holds `browser.c`, `browser_html.c`, `js_*.c`, `svg_raster.c`; `chat/` holds `chat_login.c`; `gallery/` holds the real `gallery.c` behind the `ucmd_gallery.c` launcher; `hello/` has its own `hello.ld`) |
 | `user/lib/<lib>/` | Ring-3 libraries: `libc`, `ngui`, `ufont`, `img`, `tls` (crypto incl. `wpa_crypto.c`), `uhttp`, `ujson`, `uwm` (`uwm_lib.c`), `wifi` (`wifi_store.c`, `wpa.c`); host tests live next to their library |
-| `tools/` | Host tools (`mkpack.c`, `mkrootfs.c`, `mkrtwtbl.c`, `mkcursors.c`, `mkicons.c`, `kexec_send.c`, `netkexec_send.c`, `netmonitor.c`, `flash.sh`, `xcursor_trim.py`), the QMP test scripts and `cursor_test.c` |
+| `tools/` | Host tools (`mkpack.c`, `mkrootfs.c`, `mkrtwtbl.c`, `mkcursors.c`, `mkicons.c`, `mkwoff.py`, `kexec_send.c`, `netkexec_send.c`, `netmonitor.c`, `flash.sh`, `xcursor_trim.py`), the QMP test scripts and `cursor_test.c` |
 | `assets/` | Imported assets: `assets/cursors/adwaita/` (the Adwaita 24 px Xcursor files) and `assets/icons/adwaita/` (the Adwaita symbolic SVGs used as UI icons), both LGPL-3 / CC-BY-SA-3.0, with README and licences |
 | `host/` | Linux SDL3 browser harness |
 
@@ -734,7 +734,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   NTP" button fetches UTC through `SYS_NTP_SYNC` and writes it with
   `SYS_RTC_SET`; the `date` command prints the classic `date` line and a
   small `+FORMAT` subset.
-- **Fonts**: `ufont.c/h`, `ufont_ttf.c`, `ufont_draw.c`, `ufont_file.c` — a
+- **Fonts**: `ufont.c/h`, `ufont_ttf.c`, `ufont_draw.c`, `ufont_file.c`,
+  `ufont_woff.c` — a
   fixed-point (26.6, no FPU) TrueType parser and antialiased rasterizer for
   ring-3 text.  The byte/Latin-1 path remains the default; cmap format 4 and
   format 12 are supported, and the new UTF-8 `ngui_text_utf8*`/
@@ -744,16 +745,23 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   Mono subsets plus Noto Emoji in `fonts/`, packed into `/ramfs/fonts`.  The
   emoji subset is limited to common single-codepoint glyphs that fit the
   rasterizer (256 points / 16 contours); ZWJ sequences, flags, color glyphs
-  and shaping are not supported.  `ufont` owns one 512 KB `malloc` arena for
-  face data and glyph masks; the built-in faces plus up to 11 `@font-face`
-  faces share it.  `ngui_font_attach/detach` (ngui) and `usurf_font_attach`
+  and shaping are not supported.  `ufont` owns one `malloc` arena for face
+  data and glyph masks (512 KB, `UFONT_ARENA_BYTES`; the browser asks for
+  3 MB with `ufont_set_arena_bytes()` before `ngui_init`, since its web
+  fonts live there too); up to 32 faces (`UFONT_MAX_FACES`), files up to
+  1 MB (`UFONT_MAX_FILE`).  `ufont_woff.c` (linked only into the browser
+  and the host test, because it needs `inflate`) rebuilds the sfnt from a
+  WOFF 1.0 file's per-table zlib streams; WOFF2 is detected
+  (`ufont_is_woff2`) but not decoded.  `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 and editor cells deliberately keep the 8×16 bitmap
   grid; ngui text fields use the proportional face with measured caret,
   selection and horizontal scrolling.  Host test: `make test-font`
-  (`ufont_test.c`); `make fonts`
+  (`ufont_test.c`, including the WOFF round trip against
+  `testdata/fonts/sans.woff`, which `tools/mkwoff.py` builds from
+  `fonts/sans.ttf` with stdlib zlib); `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,
@@ -1664,10 +1672,32 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   starts at the canvas edge.  Every new box context resets `line_left` with
   `line_x`; a stale one made `flush_line()` emit an empty line and pushed
   later flex items, grid columns and table cells down 2 px.
-  `@font-face` loads one regular TTF per family from a local path or HTTP URL
-  (the browser fetches remote faces before layout).  The compatibility
+  **Web fonts**: `scan_font_faces()` registers every `@font-face` as one
+  entry per (family, `font-weight` value or variable-font range,
+  `font-style`) in a 16-entry table (`BR_MAX_FACES`, `struct br_font_def`);
+  a later rule with the same triple replaces the URL.  From the `src` list
+  it takes the first `url()` whose `format()` hint (or, without one, the
+  extension) is TrueType/OpenType or WOFF 1.0, skipping `local()`, WOFF2,
+  EOT, SVG and `data:` entries; a face whose `unicode-range` does not cover
+  ASCII is dropped (Google Fonts lists the cyrillic/greek/latin-ext subsets
+  of one family/weight before the latin one).  `font-family` and the
+  `font` shorthand store the family's first entry id in
+  `br_style.font_face` and mark the family used.  `load_font_faces()` runs
+  after the sheets are parsed and before layout, fetches only used
+  families (regular first, then bold, italic, the rest, so a full arena
+  drops the rarest variants), unwraps WOFF and opens each face; it then
+  fills `font_pick[family][bold*2+italic]` with the face CSS font matching
+  picks (style first, then the nearest weight, heavier for bold), which
+  `style_face()`/`run_face()` read at layout.  A family without a loaded
+  face uses the built-in set.  Local paths are read directly; remote fonts
+  go through a fetch helper (a non-2xx answer is refused) and are cached
+  for the boot as `/share/bfont-<hash>` (8 files).  Every outcome is logged
+  as `[font] loaded|skipped|failed`.  `FontFace` and `document.fonts`
+  exist in the prelude (a set that accepts faces, `ready`/`load` resolve at
+  once, `check` is true), but a script-built face is not rendered.  The
+  compatibility
   ladder is `testdata/browser/compat/`
-  (`make compat-serve`); pages 010–070 and 030a pass (036a needs the
+  (`make compat-serve`); pages 010–074 and 030a pass (036a needs the
   POST echo server).  Closed `<details>` are skipped and `<video>` gets a
   placeholder box.  Inline `<svg>` is rendered by `svg_raster.c/h`
   (freestanding, host test `make test-svg`): every path command including
@@ -2953,10 +2983,15 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     margin/padding percentages/`em` resolve against the containing
     width/element font (root for `rem`).  Text
     is Latin-1 only (non-Latin-1 characters become `?`); there is no shaping,
-    bidi, WOFF/unicode-range or full-Unicode fallback.  `@font-face` supports
-    one regular TTF/OTF per family; bold/italic/inherited weights fall back to
-    the installed faces, and the `font` shorthand does not resolve a custom
-    family (use `font-family`).
+    bidi or full-Unicode fallback.  `@font-face` takes TrueType-outline
+    TTF/OTF and WOFF 1.0 (no WOFF2, CFF outlines, `data:` sources or
+    `local()` lookups); variable fonts render their default instance; a
+    missing bold/italic variant uses the nearest loaded face of the family
+    (no synthetic bold/oblique); a family is resolved when its rule is
+    parsed, so an `@font-face` in a later sheet than the rule that names it,
+    or a family named only in a `style` attribute or a per-element
+    `var()` re-expansion, is not loaded; faces are fetched one at a time,
+    and `FontFace`/`document.fonts.add()` faces are not rendered.
     Pages that need multi-row grid templates, `color-mix()` or full
     transforms can still lay out imperfectly.  Remote `<img>` decodes in the
     fetch helper at its CSS/attribute box (the helper request carries
@@ -3046,9 +3081,11 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     subset and only covers single-codepoint glyphs that fit the 256-point /
     16-contour rasterizer: ZWJ sequences, flags, skin-tone sequences and
     color glyphs fall back to a tofu/`?`.  Small sizes (below ~12 px) are
-    softer than the bitmap font.  The 512 KB arena is shared by the built-in
-    faces (including emoji), up to 11 `@font-face` faces and glyph masks; a
-    very text-heavy page can exhaust it and fall back to re-rasterizing
+    softer than the bitmap font.  The arena (512 KB, 3 MB in the browser) is
+    shared by the built-in faces (including emoji), the page's `@font-face`
+    files and glyph masks; a web font whose file does not fit is skipped and
+    its text uses the built-in faces, and 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()`; terminal/editor cell grids stay on the 8×16 bitmap font,
     while ngui text fields use the proportional face.

+ 11 - 7
Makefile

@@ -325,6 +325,10 @@ UFONT_OBJS = $(addprefix $(UL)/ufont/,ufont.o ufont_ttf.o ufont_draw.o ufont_fil
 $(UFONT_OBJS): OPT = -Os
 $(UFONT_OBJS): XFLAGS = $(SECTION_CFLAGS) $(LIBC_INC)
 $(UL)/ufont/ufont_ttf.o: OPT = -O2
+# WOFF 1.0 unwrapping needs inflate, so only the browser links it.
+UFONT_WOFF = $(UL)/ufont/ufont_woff.o
+$(UFONT_WOFF): OPT = -Os
+$(UFONT_WOFF): XFLAGS = $(SECTION_CFLAGS) $(LIBC_INC)
 
 # ngui: the userland immediate-mode GUI toolkit.  -Os: every GUI app links
 # the whole toolkit, and the rootfs pack has a cap.
@@ -502,7 +506,7 @@ $(BROWSER_OBJS): XFLAGS = $(SECTION_CFLAGS) $(LIBC_INC)
 $(BR)/browser_html.o: XFLAGS = $(SECTION_CFLAGS)
 $(BR)/js_mu.o: XFLAGS = $(SECTION_CFLAGS) -Wno-unused-parameter $(LIBC_INC) -I$(QJS_DIR)
 
-browser.elf: $(BR)/browser.o $(BR)/browser_html.o $(BR)/svg_raster.o $(BR)/js_browser.o $(BR)/js_prelude.o $(UHTTP_OBJS) $(NGUI_APP) $(IMGLIB_OBJS) $(INFLATE) $(TLSLIB_OBJS) $(BR)/js_mu.o $(QJS_OBJS) $(UCMD_LD) $(LIBC_A)
+browser.elf: $(BR)/browser.o $(BR)/browser_html.o $(BR)/svg_raster.o $(BR)/js_browser.o $(BR)/js_prelude.o $(UHTTP_OBJS) $(NGUI_APP) $(UFONT_WOFF) $(IMGLIB_OBJS) $(INFLATE) $(TLSLIB_OBJS) $(BR)/js_mu.o $(QJS_OBJS) $(UCMD_LD) $(LIBC_A)
 	$(ULINK)
 
 # hello: the first ring-3 test program (its own linker script).
@@ -550,7 +554,7 @@ HOST_BROWSER_APP_SRCS = $(addprefix user/apps/browser/,browser.c \
                         $(HOST_UHTTP_SRCS) user/lib/ngui/ngui.c \
                         common/font_8x16.c \
                         $(addprefix user/lib/ufont/,ufont.c ufont_ttf.c \
-                        ufont_draw.c ufont_file.c) \
+                        ufont_draw.c ufont_file.c ufont_woff.c) \
                         $(HOST_IMGLIB_SRCS) common/inflate.c $(HOST_TLS_SRCS) \
                         user/apps/browser/js_mu.c user/lib/libc/malloc.c \
                         $(HOST_QUERY_SRCS)
@@ -593,15 +597,15 @@ host-curl: $(HOST_CURL_OBJS)
 
 # ---- Host tests (no kernel needed) -----------------------------------------
 
-UFONT_TEST_SRCS = $(addprefix user/lib/ufont/,ufont_test.c ufont.c ufont_ttf.c ufont_draw.c)
-ufont_test: $(UFONT_TEST_SRCS) user/lib/ufont/ufont.h user/lib/ufont/ufont_internal.h fonts/emoji.ttf
-	gcc -O2 -Wall -Wextra -Iinclude -o $@ $(UFONT_TEST_SRCS)
+UFONT_TEST_SRCS = $(addprefix user/lib/ufont/,ufont_test.c ufont.c ufont_ttf.c ufont_draw.c ufont_woff.c) common/inflate.c
+ufont_test: $(UFONT_TEST_SRCS) user/lib/ufont/ufont.h user/lib/ufont/ufont_internal.h fonts/emoji.ttf testdata/fonts/sans.woff
+	gcc -O2 -Wall -Wextra -Iinclude -Icommon -o $@ $(UFONT_TEST_SRCS)
 
 test-font: ufont_test
 	./ufont_test
 
-test-font-asan: $(UFONT_TEST_SRCS) user/lib/ufont/ufont.h user/lib/ufont/ufont_internal.h fonts/emoji.ttf
-	gcc -O1 -g -fsanitize=address,undefined -Iinclude -o ufont_test_asan $(UFONT_TEST_SRCS)
+test-font-asan: $(UFONT_TEST_SRCS) user/lib/ufont/ufont.h user/lib/ufont/ufont_internal.h fonts/emoji.ttf testdata/fonts/sans.woff
+	gcc -O1 -g -fsanitize=address,undefined -Iinclude -Icommon -o ufont_test_asan $(UFONT_TEST_SRCS)
 	./ufont_test_asan
 
 fonts:

+ 1 - 1
docs/development.html

@@ -422,7 +422,7 @@ make net-cmds                   # replace /ramfs only</code></pre>
 			<li><code>user/lib/libc/</code>, <code>libc.a</code> — optional ring-3 libc and its host test</li>
 			<li><code>third_party/quickjs/</code> (see its <code>VENDOR</code>), <code>user/apps/browser/js_mu.c/h</code>, <code>user/apps/browser/js_browser.c/h</code> — vendored JavaScript engine, its MuJS-style stack API and the browser bindings; <code>user/apps/browser/js_test.c</code> host tests</li>
 			<li><code>host/</code> — Linux SDL3 browser harness: <code>host/syscall.c</code> implements the <code>SYS_*</code> ABI, <code>host/window_sdl3.c</code> the Wayland window/input, <code>host/fs.c</code>/<code>host/net.c</code>/<code>host/proc.c</code> the host file, socket and <code>curl __serve</code> services, and <code>host/window_headless.c</code> the screenshot mode; <span class="file">ucmd_lib.h</span> selects the host prototypes with <code>UCMD_HOST</code></li>
-			<li><code>user/lib/ufont/ufont.c</code>, <code>user/lib/ufont/ufont_ttf.c</code>, <code>fonts/</code> — UI font engine and subsets; <code>user/lib/ufont/ufont_test.c</code> host test</li>
+			<li><code>user/lib/ufont/ufont.c</code>, <code>user/lib/ufont/ufont_ttf.c</code>, <code>fonts/</code> — UI font engine and subsets; <code>user/lib/ufont/ufont_test.c</code> host test (with the <code>testdata/fonts/sans.woff</code> round trip; <code>tools/mkwoff.py</code> rebuilds it)</li>
 			<li><code>kernel/kexec.c</code>, <code>tools/kexec_send.c</code> — serial reload</li>
 			<li><code>kernel/netkexec.c</code>, <code>tools/netkexec_send.c</code> — network reload</li>
 			<li><code>kernel/netlog.c</code>, <code>tools/netmonitor.c</code> — UDP console</li>

+ 8 - 1
docs/graphics.html

@@ -411,7 +411,13 @@
 			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
+			the faces. Pages may bring their own faces with
+			<code>@font-face</code>: TrueType/OpenType (TrueType outlines) or
+			WOFF&nbsp;1.0, which <span class="file">ufont_woff.c</span>
+			unwraps by inflating each table; per family the browser keeps one
+			face per weight/style and picks the nearest one at layout. Its
+			arena is 3&nbsp;MB instead of the default 512&nbsp;KB so web fonts
+			fit beside the built-in set. 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 and
 			the editor keep the bitmap cells.
@@ -586,6 +592,7 @@
 			<li><code>user/apps/browser/browser.c</code>, <code>user/apps/browser/browser_html.c</code> — HTML/CSS renderer and inline SVG</li>
 			<li><code>user/lib/ngui/ngui.c</code>, <code>user/lib/ngui/ngui.h</code> — toolkit</li>
 			<li><code>user/lib/ufont/ufont.c</code>, <code>user/lib/ufont/ufont_ttf.c</code>, <code>user/lib/ufont/ufont_draw.c</code> — fixed-point TrueType text</li>
+			<li><code>user/lib/ufont/ufont_woff.c</code> — WOFF 1.0 to sfnt (browser only)</li>
 			<li><code>fonts/*.ttf</code> — Arimo / Liberation Mono / Noto Emoji subsets in the pack</li>
 			<li><code>user/apps/files/ucmd_files.c</code>, <code>user/apps/process/ucmd_process.c</code>, <code>user/apps/gallery/gallery.c</code>, <code>user/apps/solitaire/ucmd_solitaire.c</code>, <code>user/apps/chat/ucmd_chat.c</code></li>
 			<li><code>user/lib/img/img*.c</code> — image codecs</li>

Разница между файлами не показана из-за своего большого размера
+ 0 - 0
docs/userland.html


+ 78 - 0
testdata/browser/compat/074-font-variants.html

@@ -0,0 +1,78 @@
+<!doctype html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>074 font-face variants</title>
+<style>
+/* The regular face lists WOFF2 first (unsupported, skipped) and a WOFF 1.0
+ * copy of the built-in mono face second. */
+@font-face {
+  font-family: "Ladder Var";
+  src: local("Ladder Var"), url("ladder-mono.woff2") format("woff2"),
+       url("ladder-mono.woff") format("woff");
+}
+/* The bold face of the same family is the built-in sans bold. */
+@font-face {
+  font-family: "Ladder Var";
+  font-weight: 700;
+  src: url("ladder-sans-b.ttf") format("truetype");
+}
+/* A non-Latin subset with the same family/weight/style must not replace
+ * the regular face (Google Fonts lists latin last). */
+@font-face {
+  font-family: "Ladder Var";
+  unicode-range: U+0400-045F, U+0490-0491;
+  src: url("does-not-exist-cyrillic.ttf") format("truetype");
+}
+/* Never referenced: must not be fetched (check the [font] log). */
+@font-face {
+  font-family: "Never Used";
+  src: url("never-used.ttf") format("truetype");
+}
+html, body { margin: 0; padding: 0; background: #ffffff; color: #202020; }
+body { font-family: sans-serif; font-size: 13px; padding: 10px; }
+h1 { font-size: 20px; margin: 0 0 6px 0; }
+p { margin: 0 0 10px 0; }
+.pane { float: left; width: 440px; margin-left: 10px; }
+.label { background: #eeeeee; padding: 4px 6px; margin-bottom: 4px; }
+.box { width: 400px; background: #f4f4f4; border: 1px solid #999999; padding: 6px; margin-bottom: 8px; }
+.var { font-family: "Ladder Var", sans-serif; font-size: 15px; }
+.var-b { font-family: "Ladder Var", sans-serif; font-size: 15px; font-weight: bold; }
+.short { font: 15px "Ladder Var", sans-serif; }
+.mono { font-family: monospace; font-size: 15px; }
+.sans-b { font-family: sans-serif; font-size: 15px; font-weight: bold; }
+#result { clear: both; margin-top: 14px; padding: 8px; background: #eeeeee; color: #000000; font-family: monospace; font-weight: bold; }
+</style>
+</head>
+<body>
+<h1>074 &middot; @font-face variants</h1>
+<p>One family with a WOFF regular face and a TTF bold face; the font shorthand names the family too.  Each A row must look like its B row.</p>
+<div class="pane">
+  <div class="label">A &middot; "Ladder Var"</div>
+  <div class="box"><span class="var">Regular: the quick brown fox 0123</span></div>
+  <div class="box"><span class="var-b">Bold: the quick brown fox 0123</span></div>
+  <div class="box"><span class="short">Shorthand: the quick brown fox 0123</span></div>
+</div>
+<div class="pane">
+  <div class="label">B &middot; reference</div>
+  <div class="box"><span class="mono">Regular: the quick brown fox 0123</span></div>
+  <div class="box"><span class="sans-b">Bold: the quick brown fox 0123</span></div>
+  <div class="box"><span class="mono">Shorthand: the quick brown fox 0123</span></div>
+</div>
+<div id="result">checking...</div>
+<script>
+/* The font rendering itself is the A/B comparison above (A must look like
+ * B row by row).  The script checks the CSS Font Loading API surface. */
+setTimeout(function () {
+  var ok = typeof FontFace === 'function' &&
+           new FontFace('X', 'url(x.ttf)').status === 'loaded' &&
+           document.fonts.size === 0 &&
+           document.fonts.check('15px "Ladder Var"') &&
+           typeof document.fonts.ready.then === 'function';
+  var out = document.getElementById('result');
+  out.textContent = (ok ? 'PASS' : 'FAIL') + ': FontFace / document.fonts API';
+  out.style.background = ok ? '#ccffcc' : '#ffcccc';
+}, 300);
+</script>
+</body>
+</html>

+ 1 - 1
testdata/browser/compat/README

@@ -17,7 +17,7 @@ Serve this directory from the host and open it on the board:
   browser http://<host>:8000/            # board
   browser http://10.0.2.2:8000/         # QEMU with -netdev user
 
-Status: 010-073 and 030a pass.  036a needs the POST echo server:
+Status: 010-074 and 030a pass.  036a needs the POST echo server:
 
   python3 testdata/browser/compat/post_server.py
   browser /floppy1/036a.htm      # action is http://10.0.2.2:8765/echo

+ 1 - 0
testdata/browser/compat/index.html

@@ -96,6 +96,7 @@ a { color: #0645ad; }
 <tr><td>071</td><td><a href="071-modern-js.html">modern JavaScript</a></td><td>classes, private fields, arrows, templates, destructuring, Map/Set, optional chaining, async/await</td><td class="pass">PASS</td></tr>
 <tr><td>072</td><td><a href="072-styled-controls.html">author-styled controls</a></td><td>inputs/textarea with author background, border, radius, padding and height; forced-colors media is false</td><td class="pass">PASS</td></tr>
 <tr><td>073</td><td><a href="073-noscript.html">noscript</a></td><td>with scripting on, noscript content (style, meta refresh) is inert</td><td class="pass">PASS</td></tr>
+<tr><td>074</td><td><a href="074-font-variants.html">@font-face variants</a></td><td>WOFF regular + TTF bold face of one family, src/format choice, unicode-range subsets, font shorthand family</td><td class="pass">PASS</td></tr>
 </table>
 </body>
 </html>

BIN
testdata/browser/compat/ladder-mono.woff


BIN
testdata/browser/compat/ladder-sans-b.ttf


BIN
testdata/fonts/sans.woff


+ 40 - 0
tools/mkwoff.py

@@ -0,0 +1,40 @@
+#!/usr/bin/env python3
+"""Wrap a TrueType/OpenType file as WOFF 1.0 (stdlib zlib only).
+
+Used to build the ufont WOFF test fixture: testdata/fonts/sans.woff is
+`tools/mkwoff.py fonts/sans.ttf testdata/fonts/sans.woff`.  Tables that do
+not shrink are stored uncompressed, as the spec requires."""
+import struct
+import sys
+import zlib
+
+
+def main(src, dst):
+    data = open(src, "rb").read()
+    flavor, ntables = struct.unpack(">IH", data[:6])
+    tables = []
+    for i in range(ntables):
+        tag, csum, off, length = struct.unpack(">4sIII",
+                                               data[12 + i * 16:28 + i * 16])
+        raw = data[off:off + length]
+        comp = zlib.compress(raw, 9)
+        if len(comp) >= len(raw):
+            comp = raw
+        tables.append((tag, csum, raw, comp))
+    tables.sort(key=lambda t: t[0])
+    off = 44 + 20 * ntables
+    dirs, body = b"", b""
+    total = 12 + 16 * ntables
+    for tag, csum, raw, comp in tables:
+        dirs += struct.pack(">4sIIII", tag, off + len(body), len(comp),
+                            len(raw), csum)
+        body += comp + b"\0" * (-len(comp) % 4)
+        total += len(raw) + (-len(raw) % 4)
+    length = off + len(body)
+    hdr = struct.pack(">4sIIHHIHHIIIII", b"wOFF", flavor, length, ntables,
+                      0, total, 1, 0, 0, 0, 0, 0, 0)
+    open(dst, "wb").write(hdr + dirs + body)
+
+
+if __name__ == "__main__":
+    main(sys.argv[1], sys.argv[2])

+ 244 - 38
user/apps/browser/browser.c

@@ -72,6 +72,12 @@ static unsigned int decode_arena_size;
 #define SCRIPT_CACHE_MAX      24
 #define SCRIPT_CACHE_FILE_MAX BR_SCRIPT_MAX
 #define SCRIPT_CACHE_PREFIX   "bjs-"
+/* Web fonts cached for the boot; /share holds 64 entries / 16 MB in all. */
+#define FONT_CACHE_MAX        8
+#define FONT_CACHE_PREFIX     "bfont-"
+/* The ufont arena (built-in faces, @font-face files and glyph masks); the
+ * 512 KB default holds the built-in set but not a page's web fonts. */
+#define BR_FONT_ARENA         (3u * 1024u * 1024u)
 #define BR_MAX_SHEETS   6
 #define BR_HISTORY      16
 #define BR_URL_MAX      4096   /* = UHTTP_PATH_MAX: google.com's JS URL is ~3.7 KB */
@@ -181,6 +187,8 @@ static unsigned short img_h[BR_MAX_NODES];
  * body.  Decode arenas are allocated per image instead of living here. */
 static unsigned char *image_io_buf;
 static struct ufont_face *font_faces[BR_MAX_FACES];
+/* [family id - 1][bold * 2 + italic] -> 1-based face id, 0 = built-in. */
+static unsigned char font_pick[BR_MAX_FACES][4];
 #define image_file_buf (image_io_buf)
 #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
 #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
@@ -655,6 +663,7 @@ static int heap_start(void)
 static void heap_clear(void)
 {
 	memset(font_faces, 0, sizeof(font_faces));
+	memset(font_pick, 0, sizeof(font_pick));
 	ngui_font_detach(&ui);
 	svg_cache_clear();
 	decode_arena = 0;        /* lives in the page heap too */
@@ -3973,44 +3982,233 @@ static int read_url(const char *url, unsigned int cap, unsigned char **out,
 	return 0;
 }
 
-/* Load every @font-face the parser registered.  Local files go through
- * ufont_face_open_path(); remote files use the fetch helper (identity, the
- * TTF parser has no gzip).  A failed face stays NULL: layout then falls back
- * to the built-in regular/bold/italic/mono set. */
+static unsigned int css_cache_hash(const char *s);
+
+/* Remote fonts are cached under /share for the current boot like the
+ * stylesheets, as the raw response (a WOFF stays compressed). */
+static int font_cache_count;
+
+static void font_cache_path(const char *url, char *out, unsigned int cap)
+{
+	unsigned int n = 0;
+
+	s_append(out, &n, "/share/" FONT_CACHE_PREFIX, cap);
+	s_append_dec(out, &n, css_cache_hash(url), cap);
+}
+
+static void font_cache_init(void)
+{
+	struct sys_dirent d;
+	int i;
+
+	font_cache_count = 0;
+	for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
+			       (int)&d) == 1; i++)
+		if (starts_with(d.name, FONT_CACHE_PREFIX))
+			font_cache_count++;
+}
+
+/* Read one font file (local path, boot cache or network) into a fresh
+ * malloc'ed buffer.  Returns its length, or -1. */
+static int font_fetch(const char *abs, unsigned char **out)
+{
+	unsigned char *buf;
+	char path[96];
+	int rv;
+
+	*out = 0;
+	buf = (unsigned char *)malloc(UFONT_MAX_FILE + 512u);
+	if (!buf)
+		return -1;
+	if (abs[0] == '/') {
+		struct sys_stat st;
+
+		/* FAT reads may write past the length: the 512 bytes of
+		 * slack above cover the final partial sector. */
+		if (u_stat(abs, &st) != 0 || st.is_dir || st.size == 0 ||
+		    st.size > UFONT_MAX_FILE) {
+			free(buf);
+			return -1;
+		}
+		rv = u_syscall3(SYS_READ_FILE, (int)abs, (int)buf,
+				(int)st.size);
+		if (rv != (int)st.size) {
+			free(buf);
+			return -1;
+		}
+		*out = buf;
+		return rv;
+	}
+	if (!is_http(abs)) {
+		free(buf);
+		return -1;
+	}
+	font_cache_path(abs, path, sizeof(path));
+	rv = u_syscall3(SYS_READ_FILE, (int)path, (int)buf,
+			(int)UFONT_MAX_FILE);
+	if (rv > 0 && (unsigned int)rv < UFONT_MAX_FILE) {
+		*out = buf;
+		return rv;
+	}
+	{
+		char err[64];
+		int tr = 0;
+
+		rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
+				  UFONT_MAX_FILE, image_io_buf,
+				  BR_PAGE_COMP_MAX, &fetch_meta, &tr, err,
+				  sizeof(err));
+		/* An error page is not a font: never parse or cache it. */
+		if (rv > 0 && !tr && fetch_meta.status >= 300) {
+			snprintf(err, sizeof(err), "HTTP %d", fetch_meta.status);
+			rv = 0;
+		}
+		if (rv <= 0 || tr) {
+			u_puts("[font] failed: ");
+			u_puts(abs);
+			u_puts(rv <= 0 ? " " : " truncated ");
+			u_puts(rv <= 0 ? err : "");
+			u_putc('\n');
+			free(buf);
+			return -1;
+		}
+	}
+	if (font_cache_count < FONT_CACHE_MAX &&
+	    u_syscall3(SYS_WRITE_FILE, (int)path, (int)buf, rv) >= 0)
+		font_cache_count++;
+	*out = buf;
+	return rv;
+}
+
+/* Open one @font-face entry: fetch, unwrap WOFF, parse into the ufont
+ * arena.  A WOFF2 or CFF (OTTO) file is reported and left unloaded. */
+static struct ufont_face *font_open_entry(int id)
+{
+	const char *url = br_font_face_url(id);
+	const char *base = br_font_face_base(id);
+	char abs[BR_URL_MAX];
+	unsigned char *buf, *sfnt;
+	unsigned int slen = 0;
+	struct ufont_face *f = 0;
+	const char *why = 0;
+	int n;
+
+	if (!url || !url[0] ||
+	    resolve_link(base && base[0] ? base : page_url, url, abs,
+			 sizeof(abs)) != 0)
+		return 0;
+	n = font_fetch(abs, &buf);
+	if (n <= 0)
+		return 0;
+	sfnt = buf;
+	slen = (unsigned int)n;
+	if (ufont_is_woff2(buf, slen)) {
+		why = "WOFF2 not supported";
+	} else if (ufont_is_woff(buf, slen)) {
+		sfnt = ufont_woff_decode(buf, slen, &slen);
+		if (!sfnt)
+			why = "bad WOFF";
+	}
+	if (!why) {
+		f = ufont_face_open_mem(sfnt, slen);
+		if (!f)
+			why = (slen >= 4 && sfnt[0] == 'O' && sfnt[1] == 'T' &&
+			       sfnt[2] == 'T' && sfnt[3] == 'O') ?
+				"CFF outlines not supported" :
+				"not a TrueType font or arena full";
+	}
+	if (sfnt && sfnt != buf)
+		free(sfnt);
+	free(buf);
+	u_puts(f ? "[font] loaded " : "[font] skipped ");
+	u_puts(br_font_face_family(id));
+	u_puts(": ");
+	u_puts(abs);
+	if (why) {
+		u_puts(" (");
+		u_puts(why);
+		u_putc(')');
+	}
+	u_putc('\n');
+	return f;
+}
+
+/* Distance of a face from the requested weight: 0 inside its range.  A
+ * bold request prefers heavier faces and a normal one lighter faces, as
+ * the CSS font-matching steps do. */
+static unsigned int font_weight_dist(const struct br_font_face_info *fi,
+				     unsigned int want)
+{
+	if (want >= fi->wmin && want <= fi->wmax)
+		return 0;
+	if (want > fi->wmax)
+		return (want - fi->wmax) * 2u + (want >= 500 ? 1u : 0u);
+	return (fi->wmin - want) * 2u + (want < 500 ? 1u : 0u);
+}
+
+/* Load the @font-face entries a font-family declaration named: per family
+ * the regular face first, then bold, italic and the rest, so a full arena
+ * drops the least common variants.  Then precompute, for every family and
+ * (bold, italic) combination, the loaded face CSS font matching picks;
+ * layout reads only that table.  A family with no loaded face keeps
+ * font_pick 0, and its text uses the built-in set. */
 static void load_font_faces(void)
 {
-	unsigned int i;
+	int n = br_font_face_count(), pass, id;
 
 	memset(font_faces, 0, sizeof(font_faces));
-	for (i = 1; i <= (unsigned int)br_font_face_count() &&
-	     i <= BR_MAX_FACES; i++) {
-		const char *url = br_font_face_url((int)i);
-		const char *base = br_font_face_base((int)i);
-		char abs[BR_URL_MAX];
+	memset(font_pick, 0, sizeof(font_pick));
+	if (n > BR_MAX_FACES)
+		n = BR_MAX_FACES;
+	for (pass = 0; pass < 4; pass++) {
+		for (id = 1; id <= n; id++) {
+			struct br_font_face_info fi;
+			int cls;
+
+			if (br_font_face_info(id, &fi) != 0 || !fi.used)
+				continue;
+			if (!fi.italic && fi.wmin <= 400 && fi.wmax >= 400)
+				cls = 0;
+			else if (!fi.italic && fi.wmin <= 700 &&
+				 fi.wmax >= 700)
+				cls = 1;
+			else if (fi.italic && fi.wmin <= 400 &&
+				 fi.wmax >= 400)
+				cls = 2;
+			else
+				cls = 3;
+			if (cls == pass)
+				font_faces[id - 1] = font_open_entry(id);
+		}
+	}
+	for (id = 1; id <= n; id++) {
+		struct br_font_face_info fam;
+		int combo;
 
-		if (!url || !url[0])
+		if (br_font_face_info(id, &fam) != 0 || fam.family_id != id)
 			continue;
-		if (resolve_link(base && base[0] ? base : page_url, url, abs,
-				 sizeof(abs)) != 0)
-			continue;
-		if (abs[0] == '/') {
-			font_faces[i - 1] = ufont_face_open_path(abs);
-		} else if (is_http(abs)) {
-			unsigned char *buf;
-			char err[64];
-			int rv, tr = 0;
-
-			buf = (unsigned char *)malloc(UFONT_MAX_FILE);
-			if (!buf)
-				continue;
-			rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
-					  UFONT_MAX_FILE, image_io_buf,
-					  BR_PAGE_COMP_MAX, &fetch_meta, &tr,
-					  err, sizeof(err));
-			if (rv > 0)
-				font_faces[i - 1] = ufont_face_open_mem(buf,
-									rv);
-			free(buf);
+		for (combo = 0; combo < 4; combo++) {
+			unsigned int want = (combo & 2) ? 700u : 400u;
+			int italic = combo & 1, k, best = 0;
+			unsigned int best_score = 0;
+
+			for (k = 1; k <= n; k++) {
+				struct br_font_face_info fi;
+				unsigned int score;
+
+				if (!font_faces[k - 1] ||
+				    br_font_face_info(k, &fi) != 0 ||
+				    fi.family_id != id)
+					continue;
+				score = font_weight_dist(&fi, want) +
+					((fi.italic != 0) != (italic != 0) ?
+					 100000u : 0u);
+				if (!best || score < best_score) {
+					best = k;
+					best_score = score;
+				}
+			}
+			font_pick[id - 1][combo] = (unsigned char)best;
 		}
 	}
 }
@@ -6066,18 +6264,24 @@ static void navigate(const char *input, int push)
 
 /* ---- layout ---- */
 
+static struct ufont_face *face_for(unsigned int family, int bold, int italic)
+{
+	unsigned int id;
+
+	if (!family || family > BR_MAX_FACES)
+		return 0;
+	id = font_pick[family - 1][(bold ? 2 : 0) | (italic ? 1 : 0)];
+	return id ? font_faces[id - 1] : 0;
+}
+
 static struct ufont_face *style_face(const struct br_style *st)
 {
-	if (st && st->font_face && st->font_face <= BR_MAX_FACES)
-		return font_faces[st->font_face - 1];
-	return 0;
+	return st ? face_for(st->font_face, st->bold, st->italic) : 0;
 }
 
 static struct ufont_face *run_face(const struct lay_run *r)
 {
-	if (r->font_face && r->font_face <= BR_MAX_FACES)
-		return font_faces[r->font_face - 1];
-	return 0;
+	return face_for(r->font_face, r->bold, r->italic);
 }
 
 static unsigned int face_text_width(struct ngui *gui,
@@ -13457,6 +13661,7 @@ void _start(const char *arg)
 		u_puts("browser: no graphics window\n");
 		u_exit(1);
 	}
+	ufont_set_arena_bytes(BR_FONT_ARENA);
 	ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
 	url_in.placeholder = "http://...";
 	br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
@@ -13468,6 +13673,7 @@ void _start(const char *arg)
 	origin_cache_load();
 	css_cache_init();
 	script_cache_init();
+	font_cache_init();
 	persist_restore();
 	hist_load();
 	page_scroll.offset = 0;

+ 327 - 104
user/apps/browser/browser_html.c

@@ -36,7 +36,11 @@ struct br_font_def {
 	char family[BR_FACE_FAMILY];
 	char url[BR_FACE_URL];
 	char base[192];
-	unsigned char used;
+	unsigned short wmin, wmax;  /* font-weight descriptor (a range for
+				     * variable fonts) */
+	unsigned char italic;       /* font-style italic/oblique */
+	unsigned char family_id;    /* first entry of the same family */
+	unsigned char used;         /* a font-family declaration names it */
 };
 static struct br_font_def font_defs[BR_MAX_FACES];
 static int font_face_count;
@@ -89,6 +93,21 @@ const char *br_font_face_family(int id)
 	return font_defs[id - 1].family;
 }
 
+int br_font_face_info(int id, struct br_font_face_info *out)
+{
+	const struct br_font_def *f;
+
+	if (id < 1 || id > font_face_count || !out)
+		return -1;
+	f = &font_defs[id - 1];
+	out->family_id = f->family_id;
+	out->wmin = f->wmin;
+	out->wmax = f->wmax;
+	out->italic = f->italic;
+	out->used = f->used;
+	return 0;
+}
+
 const char *br_bg_image_url(unsigned int idx)
 {
 	if (idx >= bg_url_count)
@@ -4431,72 +4450,91 @@ static void font_trim(const char **sp, unsigned int *len)
 	*len = n;
 }
 
+static int font_name_eq(const char *a, const char *b, unsigned int blen)
+{
+	unsigned int k;
+
+	if (s_len(a) != blen)
+		return 0;
+	for (k = 0; k < blen; k++) {
+		char x = a[k], y = b[k];
+
+		if (x >= 'A' && x <= 'Z')
+			x = (char)(x - 'A' + 'a');
+		if (y >= 'A' && y <= 'Z')
+			y = (char)(y - 'A' + 'a');
+		if (x != y)
+			return 0;
+	}
+	return 1;
+}
+
+static void font_copy(char *dst, unsigned int cap, const char *src,
+		      unsigned int n)
+{
+	unsigned int k;
+
+	for (k = 0; k < n && src[k] && k + 1 < cap; k++)
+		dst[k] = src[k];
+	dst[k] = '\0';
+}
+
+/* Register one @font-face.  Every (family, weight range, style) is its own
+ * entry; a later rule with the same triple replaces the URL, as the CSS
+ * font-face collection does.  family_id is the 1-based id of the family's
+ * first entry, which is what font-family declarations store. */
 static void font_add(const char *family, unsigned int flen,
-		     const char *url, unsigned int ulen)
+		     const char *url, unsigned int ulen,
+		     unsigned int wmin, unsigned int wmax, int italic)
 {
-	unsigned int i, n = 0, k;
+	unsigned int i;
+	int fam = 0;
+	struct br_font_def *f;
 
 	font_trim(&family, &flen);
 	font_trim(&url, &ulen);
 	if (!flen || !ulen || flen >= BR_FACE_FAMILY || ulen >= BR_FACE_URL)
 		return;
 	for (i = 0; i < (unsigned int)font_face_count; i++) {
-		struct br_font_def *f = &font_defs[i];
-
-		if (s_len(f->family) != flen)
+		f = &font_defs[i];
+		if (!font_name_eq(f->family, family, flen))
 			continue;
-		for (k = 0; k < flen; k++) {
-			char a = f->family[k], b = family[k];
-
-			if (a >= 'A' && a <= 'Z')
-				a = (char)(a - 'A' + 'a');
-			if (b >= 'A' && b <= 'Z')
-				b = (char)(b - 'A' + 'a');
-			if (a != b)
-				break;
-		}
-		if (k != flen)
+		if (!fam)
+			fam = f->family_id;
+		if (f->wmin != wmin || f->wmax != wmax ||
+		    f->italic != (unsigned char)italic)
 			continue;
-		n = 0;
-		while (url[n] && n + 1 < sizeof(f->url)) {
-			f->url[n] = url[n];
-			n++;
-		}
-		f->url[n] = '\0';
-		n = 0;
-		while (font_base[n] && n + 1 < sizeof(f->base)) {
-			f->base[n] = font_base[n];
-			n++;
-		}
-		f->base[n] = '\0';
+		font_copy(f->url, sizeof(f->url), url, ulen);
+		font_copy(f->base, sizeof(f->base), font_base, s_len(font_base));
 		return;
 	}
 	if (font_face_count >= BR_MAX_FACES)
 		return;
-	{
-		struct br_font_def *f = &font_defs[font_face_count];
-
-		for (n = 0; n < flen; n++)
-			f->family[n] = family[n];
-		f->family[n] = '\0';
-		for (n = 0; n < ulen; n++)
-			f->url[n] = url[n];
-		f->url[n] = '\0';
-		for (n = 0; font_base[n] && n + 1 < sizeof(f->base); n++)
-			f->base[n] = font_base[n];
-		f->base[n] = '\0';
+	f = &font_defs[font_face_count];
+	font_copy(f->family, sizeof(f->family), family, flen);
+	font_copy(f->url, sizeof(f->url), url, ulen);
+	font_copy(f->base, sizeof(f->base), font_base, s_len(font_base));
+	f->wmin = (unsigned short)wmin;
+	f->wmax = (unsigned short)wmax;
+	f->italic = (unsigned char)italic;
+	f->used = 0;
+	font_face_count++;
+	f->family_id = (unsigned char)(fam ? fam : font_face_count);
+	/* A family that a font-family declaration already resolved (an
+	 * earlier @font-face of it) stays wanted for its new variants. */
+	if (fam && font_defs[fam - 1].used)
 		f->used = 1;
-		font_face_count++;
-	}
 }
 
-/* Look up the first name in a font-family list that has an @font-face. */
+/* Look up the first name in a font-family list that has an @font-face and
+ * mark that family as used, so the browser only downloads faces the page
+ * refers to. */
 static int font_family_id(const char *s, unsigned int len)
 {
 	unsigned int i = 0;
 
 	while (i < len) {
-		unsigned int start, end, q = 0;
+		unsigned int start, end, q;
 
 		while (i < len && (is_space(s[i]) || s[i] == ','))
 			i++;
@@ -4519,27 +4557,213 @@ static int font_family_id(const char *s, unsigned int len)
 			while (end > start && is_space(s[end - 1]))
 				end--;
 		}
-		if (end > start) {
-			for (q = 0; q < (unsigned int)font_face_count; q++) {
-				const char *f = font_defs[q].family;
-				unsigned int fl = s_len(f), k;
+		if (end <= start)
+			continue;
+		for (q = 0; q < (unsigned int)font_face_count; q++) {
+			int fam;
+			unsigned int k;
+
+			if (!font_name_eq(font_defs[q].family, s + start,
+					  end - start))
+				continue;
+			fam = font_defs[q].family_id;
+			for (k = 0; k < (unsigned int)font_face_count; k++)
+				if (font_defs[k].family_id == fam)
+					font_defs[k].used = 1;
+			return fam;
+		}
+	}
+	return 0;
+}
 
-				if (fl != end - start)
-					continue;
-				for (k = 0; k < fl; k++) {
-					char a = f[k], b = s[start + k];
-
-					if (a >= 'A' && a <= 'Z')
-						a = (char)(a - 'A' + 'a');
-					if (b >= 'A' && b <= 'Z')
-						b = (char)(b - 'A' + 'a');
-					if (a != b)
-						break;
-				}
-				if (k == fl)
-					return (int)q + 1;
+/* font-weight descriptor: `normal`, `bold`, a number, or a variable font's
+ * `100 900` range. */
+static void font_parse_weight(const char *s, unsigned int len,
+			      unsigned int *wmin, unsigned int *wmax)
+{
+	unsigned int i = 0, n = 0, w[2] = { 400, 400 };
+
+	while (i < len && n < 2) {
+		unsigned int v = 0, st;
+
+		while (i < len && is_space(s[i]))
+			i++;
+		st = i;
+		while (i < len && !is_space(s[i]))
+			i++;
+		if (i == st)
+			break;
+		if (i - st == 4 && ci_eq_n(s + st, "bold", 4)) {
+			v = 700;
+		} else if (i - st == 6 && ci_eq_n(s + st, "bolder", 6)) {
+			v = 700;
+		} else if (i - st == 7 && ci_eq_n(s + st, "lighter", 7)) {
+			v = 300;
+		} else if (s[st] >= '0' && s[st] <= '9') {
+			unsigned int k;
+
+			for (k = st; k < i && s[k] >= '0' && s[k] <= '9'; k++)
+				v = v * 10 + (unsigned int)(s[k] - '0');
+		} else {
+			v = 400;
+		}
+		if (v < 1)
+			v = 1;
+		if (v > 1000)
+			v = 1000;
+		w[n++] = v;
+	}
+	if (n == 1)
+		w[1] = w[0];
+	if (w[0] > w[1]) {
+		unsigned int t = w[0];
+
+		w[0] = w[1];
+		w[1] = t;
+	}
+	*wmin = w[0];
+	*wmax = w[1];
+}
+
+static int font_hex(char c)
+{
+	if (c >= '0' && c <= '9')
+		return c - '0';
+	if (c >= 'a' && c <= 'f')
+		return c - 'a' + 10;
+	if (c >= 'A' && c <= 'F')
+		return c - 'A' + 10;
+	return -1;
+}
+
+/* Whether a unicode-range list covers basic Latin.  Google Fonts splits a
+ * family into per-script subsets with the same family/weight/style; only
+ * the one holding ASCII is useful here (the text path is Latin-1). */
+static int font_range_has_latin(const char *s, unsigned int len)
+{
+	unsigned int i = 0;
+
+	while (i < len) {
+		unsigned int lo = 0, hi, digits = 0, wild = 0;
+
+		while (i < len && (is_space(s[i]) || s[i] == ','))
+			i++;
+		if (i + 2 > len || (s[i] != 'U' && s[i] != 'u') ||
+		    s[i + 1] != '+') {
+			while (i < len && s[i] != ',')
+				i++;
+			continue;
+		}
+		i += 2;
+		while (i < len && digits < 6 &&
+		       (font_hex(s[i]) >= 0 || s[i] == '?')) {
+			if (s[i] == '?') {
+				lo <<= 4;
+				wild++;
+			} else {
+				lo = (lo << 4) | (unsigned int)font_hex(s[i]);
 			}
+			digits++;
+			i++;
 		}
+		hi = lo | ((1u << (wild * 4)) - 1u);
+		if (!wild && i < len && s[i] == '-') {
+			hi = 0;
+			i++;
+			while (i < len && font_hex(s[i]) >= 0) {
+				hi = (hi << 4) | (unsigned int)font_hex(s[i]);
+				i++;
+			}
+		}
+		if (digits && lo <= 'a' && hi >= 'a')
+			return 1;
+		while (i < len && s[i] != ',')
+			i++;
+	}
+	return 0;
+}
+
+/* Pick the first `src` entry the text engine can load: a TrueType/OpenType
+ * file or WOFF 1.0, by its format() hint or, without one, by its
+ * extension.  local() names, WOFF2, EOT, SVG fonts and data: URLs (they do
+ * not fit BR_FACE_URL) are skipped. */
+static int font_pick_src(const char *s, unsigned int len, char *url,
+			 unsigned int cap, unsigned int *ulen)
+{
+	unsigned int i = 0;
+
+	while (i < len) {
+		unsigned int is_ = i, ie, us = 0, ue = 0, q, depth = 0;
+		int quote = 0, ok;
+		const char *up;
+		unsigned int un;
+
+		/* One comma-separated item, commas inside url()/quotes kept. */
+		while (i < len) {
+			char c = s[i];
+
+			if (quote) {
+				if (c == quote)
+					quote = 0;
+			} else if (c == '"' || c == '\'') {
+				quote = c;
+			} else if (c == '(') {
+				depth++;
+			} else if (c == ')') {
+				if (depth)
+					depth--;
+			} else if (c == ',' && !depth) {
+				break;
+			}
+			i++;
+		}
+		ie = i;
+		i++;
+		for (q = is_; q + 4 <= ie; q++)
+			if (ci_eq_n(s + q, "url(", 4))
+				break;
+		if (q + 4 > ie)
+			continue;
+		us = q + 4;
+		for (ue = us; ue < ie && s[ue] != ')'; ue++)
+			if (s[ue] == '"' || s[ue] == '\'') {
+				char qc = s[ue++];
+
+				while (ue < ie && s[ue] != qc)
+					ue++;
+			}
+		up = s + us;
+		un = ue - us;
+		font_trim(&up, &un);
+		if (!un || un >= cap || (un >= 5 && ci_eq_n(up, "data:", 5)))
+			continue;
+		ok = 1;
+		if (contains_ci_len(s + ue, ie - ue, "format(")) {
+			const char *fp = s + ue;
+			unsigned int fn = ie - ue;
+
+			ok = (contains_ci_len(fp, fn, "truetype") ||
+			      contains_ci_len(fp, fn, "opentype") ||
+			      contains_ci_len(fp, fn, "woff")) &&
+			     !contains_ci_len(fp, fn, "woff2") &&
+			     !contains_ci_len(fp, fn, "embedded");
+		} else {
+			unsigned int e = 0;
+
+			while (e < un && up[e] != '?' && up[e] != '#')
+				e++;
+			if ((e >= 6 && ci_eq_n(up + e - 6, ".woff2", 6)) ||
+			    (e >= 4 && ci_eq_n(up + e - 4, ".eot", 4)) ||
+			    (e >= 4 && ci_eq_n(up + e - 4, ".svg", 4)))
+				ok = 0;
+		}
+		if (!ok)
+			continue;
+		for (q = 0; q < un; q++)
+			url[q] = up[q];
+		url[un] = '\0';
+		*ulen = un;
+		return 1;
 	}
 	return 0;
 }
@@ -4555,7 +4779,8 @@ static void scan_font_faces(const char *s, unsigned int len)
 		unsigned int j, end;
 		char family[BR_FACE_FAMILY], url[BR_FACE_URL];
 		unsigned int flen = 0, ulen = 0, p;
-		int have_family = 0, have_url = 0;
+		unsigned int wmin = 400, wmax = 400;
+		int have_family = 0, have_url = 0, italic = 0, latin = 1;
 
 		if (s[i] != '@' || !ci_eq_n(s + i, "@font-face", 10)) {
 			i++;
@@ -4571,14 +4796,15 @@ static void scan_font_faces(const char *s, unsigned int len)
 		end = css_skip_nested(s, len, j + 1);
 		p = j + 1;
 		while (p < end) {
-			unsigned int ds, de, vs, ve;
+			unsigned int ds, de, vs, ve, quote = 0;
 
 			while (p < end && (is_space(s[p]) || s[p] == ';'))
 				p++;
 			if (p >= end)
 				break;
 			ds = p;
-			while (p < end && s[p] != ':' && s[p] != ';')
+			while (p < end && s[p] != ':' && s[p] != ';' &&
+			       s[p] != '}')
 				p++;
 			de = p;
 			if (p >= end || s[p] != ':') {
@@ -4588,8 +4814,15 @@ static void scan_font_faces(const char *s, unsigned int len)
 			}
 			p++;
 			vs = p;
-			while (p < end && s[p] != ';')
+			/* A quoted URL may contain ';' (data: URLs do). */
+			while (p < end && (quote || (s[p] != ';' &&
+						     s[p] != '}'))) {
+				if (quote && s[p] == (char)quote)
+					quote = 0;
+				else if (!quote && (s[p] == '"' || s[p] == '\''))
+					quote = (unsigned char)s[p];
 				p++;
+			}
 			ve = p;
 			while (ds < de && is_space(s[ds]))
 				ds++;
@@ -4616,43 +4849,29 @@ static void scan_font_faces(const char *s, unsigned int len)
 				}
 			} else if (de - ds == 3 &&
 				   ci_eq_n(s + ds, "src", 3)) {
-				unsigned int q = vs;
-
-				while (q + 4 <= ve) {
-					unsigned int us, ue;
-
-					if (!ci_eq_n(s + q, "url(", 4)) {
-						q++;
-						continue;
-					}
-					q += 4;
-					us = q;
-					while (q < ve && s[q] != ')')
-						q++;
-					ue = q;
-					{
-						const char *up = s + us;
-						unsigned int un = ue - us;
-
-						font_trim(&up, &un);
-						if (un && un < sizeof(url) &&
-						    !contains_ci_len(up, un,
-								     "woff")) {
-							unsigned int k;
-
-							for (k = 0; k < un; k++)
-								url[k] = up[k];
-							url[un] = '\0';
-							ulen = un;
-							have_url = 1;
-							break;
-						}
-					}
-				}
+				/* A later src (the old IE `src: eot;` hack
+				 * is followed by the real list) wins when
+				 * it has a usable entry. */
+				if (font_pick_src(s + vs, ve - vs, url,
+						  sizeof(url), &ulen))
+					have_url = 1;
+			} else if (de - ds == 11 &&
+				   ci_eq_n(s + ds, "font-weight", 11)) {
+				font_parse_weight(s + vs, ve - vs, &wmin,
+						  &wmax);
+			} else if (de - ds == 10 &&
+				   ci_eq_n(s + ds, "font-style", 10)) {
+				italic = contains_ci_len(s + vs, ve - vs,
+							 "italic") ||
+					 contains_ci_len(s + vs, ve - vs,
+							 "oblique");
+			} else if (de - ds == 13 &&
+				   ci_eq_n(s + ds, "unicode-range", 13)) {
+				latin = font_range_has_latin(s + vs, ve - vs);
 			}
 		}
-		if (have_family && have_url)
-			font_add(family, flen, url, ulen);
+		if (have_family && have_url && latin)
+			font_add(family, flen, url, ulen, wmin, wmax, italic);
 		i = end;
 	}
 }
@@ -4730,7 +4949,8 @@ static void add_font_shorthand(struct br_decl *out, unsigned int *nout,
 	unsigned char size_unit = 0;
 	int have_size = 0;
 	int bold = 0, italic = 0;
-	int lh_px = 0, lh_pct = 0, mono = 0;
+	int lh_px = 0, lh_pct = 0, mono = 0, face;
+	unsigned int fam_at = len;
 
 	while (next_token(v, len, &pos, &ts, &te)) {
 		unsigned int tl = te - ts;
@@ -4779,6 +4999,8 @@ static void add_font_shorthand(struct br_decl *out, unsigned int *nout,
 			size_raw = raw;
 			size_unit = unit;
 		}
+		if (!have_size)
+			fam_at = te;    /* the family list follows the size */
 		have_size = 1;
 		if (slash < tl) {
 			unsigned int lstart = ts + slash + 1;
@@ -4798,12 +5020,13 @@ static void add_font_shorthand(struct br_decl *out, unsigned int *nout,
 	if (!have_size)
 		return;
 	mono = contains_ci_len(v, len, "mono");
+	face = font_family_id(v + fam_at, len - fam_at);
 	decl_add(out, nout, PROP_FONT_PX, size_raw, important);
 	decl_add(out, nout, PROP_FONT_UNIT, size_unit, important);
 	decl_add(out, nout, PROP_BOLD, bold, important);
 	decl_add(out, nout, PROP_ITALIC, italic, important);
 	decl_add(out, nout, PROP_MONO, mono, important);
-	decl_add(out, nout, PROP_FONT_FACE, 0, important);
+	decl_add(out, nout, PROP_FONT_FACE, face, important);
 	decl_add(out, nout, PROP_LH_PX, lh_px, important);
 	decl_add(out, nout, PROP_LH_PCT, lh_pct, important);
 }

+ 11 - 2
user/apps/browser/browser_html.h

@@ -16,7 +16,7 @@
 #define BR_CSS_SIZE      262144  /* inline <style> text; google.com has ~94 KB */
 #define BR_MAX_RULES     8192
 #define BR_RULE_FALLBACK 256
-#define BR_MAX_FACES     8
+#define BR_MAX_FACES     16
 #define BR_FACE_FAMILY   40
 #define BR_FACE_URL      192
 #define BR_MAX_VARS      512
@@ -386,8 +386,17 @@ const char *br_bg_image_url(unsigned int idx);
 unsigned int br_root_font_px(void);
 
 /* @font-face table.  Ids are 1-based; the browser resolves URLs against the
- * stored base (the stylesheet URL or the page URL) and loads the faces. */
+ * stored base (the stylesheet URL or the page URL) and loads the faces.
+ * Each (family, weight, style) is one entry; br_style.font_face holds the
+ * family's first entry and the browser picks the variant at layout. */
+struct br_font_face_info {
+	int family_id;              /* 1-based id of the family's first face */
+	unsigned int wmin, wmax;    /* weight range, 400 = normal */
+	int italic;
+	int used;                   /* named by a font-family declaration */
+};
 int br_font_face_count(void);
+int br_font_face_info(int id, struct br_font_face_info *out);
 const char *br_font_face_url(int id);
 const char *br_font_face_base(int id);
 const char *br_font_face_family(int id);

+ 37 - 4
user/apps/browser/js_prelude.js

@@ -1396,10 +1396,43 @@ doc.charset = "UTF-8";
 doc.contentType = "text/html";
 doc.referrer = "";
 doc.dir = "";
-doc.fonts = { ready: Promise.resolve(), add: function () {},
-	      load: function () { return Promise.resolve([]); },
-	      check: function () { return true; },
-	      addEventListener: function () {} };
+/* CSS Font Loading API surface.  Faces come from the stylesheets'
+ * @font-face rules, loaded before layout; a script-built FontFace resolves
+ * at once but is not rendered (the cascade resolves families at parse). */
+g.FontFace = function (family, source, desc) {
+	this.family = String(family);
+	this.source = source;
+	desc = desc || {};
+	this.style = desc.style || "normal";
+	this.weight = String(desc.weight || "normal");
+	this.display = desc.display || "auto";
+	this.unicodeRange = desc.unicodeRange || "U+0-10FFFF";
+	this.status = "loaded";
+	this.loaded = Promise.resolve(this);
+};
+g.FontFace.prototype.load = function () { return this.loaded; };
+(function () {
+	var faces = [];
+	var fonts = {
+		status: "loaded", ready: null, onloading: null,
+		onloadingdone: null, onloadingerror: null,
+		add: function (f) { if (faces.indexOf(f) < 0) faces.push(f); return fonts; },
+		delete: function (f) { var i = faces.indexOf(f); if (i < 0) return false; faces.splice(i, 1); return true; },
+		has: function (f) { return faces.indexOf(f) >= 0; },
+		clear: function () { faces.length = 0; },
+		forEach: function (cb, t) { faces.slice().forEach(function (f) { cb.call(t, f, f, fonts); }); },
+		values: function () { return faces.slice()[Symbol.iterator](); },
+		load: function () { return Promise.resolve([]); },
+		check: function () { return true; },
+		addEventListener: function () {},
+		removeEventListener: function () {}
+	};
+	fonts.ready = Promise.resolve(fonts);
+	fonts.keys = fonts.values;
+	fonts[Symbol.iterator] = fonts.values;
+	Object.defineProperty(fonts, "size", { get: function () { return faces.length; } });
+	doc.fonts = fonts;
+})();
 /* A separate inert document (jQuery's parseHTML context, DOMPurify): its
  * nodes live in the page's node arena but are detached, so writing to its
  * body never touches the page.  Returning the page document here made

+ 8 - 2
user/lib/ufont/ufont.c

@@ -15,6 +15,7 @@ struct ufont_cache_ent {
 
 static unsigned char *arena;
 static unsigned int arena_cap;
+static unsigned int arena_req = UFONT_ARENA_BYTES;
 static unsigned int arena_used;
 static unsigned int glyph_base;
 static struct ufont_face *faces[UFONT_MAX_FACES];
@@ -55,14 +56,19 @@ static void cache_clear(void)
 		arena_used = glyph_base;
 }
 
+void ufont_set_arena_bytes(unsigned int bytes)
+{
+	arena_req = bytes ? bytes : UFONT_ARENA_BYTES;
+}
+
 int ufont_arena_init(void)
 {
 	if (arena)
 		return 0;
-	arena = (unsigned char *)malloc(UFONT_ARENA_BYTES);
+	arena = (unsigned char *)malloc(arena_req);
 	if (!arena)
 		return -1;
-	arena_cap = UFONT_ARENA_BYTES;
+	arena_cap = arena_req;
 	arena_used = 0;
 	glyph_base = 0;
 	nfaces = 0;

+ 16 - 2
user/lib/ufont/ufont.h

@@ -11,7 +11,7 @@
 #include <stddef.h>
 
 #define UFONT_ARENA_BYTES   (512u * 1024u)
-#define UFONT_MAX_FILE      (256u * 1024u)
+#define UFONT_MAX_FILE      (1024u * 1024u)
 #define UFONT_CACHE_SLOTS   512
 
 struct ufont_face;
@@ -30,15 +30,29 @@ struct ufont_metrics {
 	int line_height;
 };
 
-/* Allocate the shared arena (256 KB).  Returns 0 on success. */
+/* Allocate the shared arena (UFONT_ARENA_BYTES unless
+ * ufont_set_arena_bytes() asked for more).  Returns 0 on success. */
 int ufont_arena_init(void);
 void ufont_reset(void);
+/* Arena size for the next ufont_arena_init(); an app that loads web fonts
+ * (the browser) raises it before its first face is opened.  0 restores the
+ * default.  It does not resize an arena that already exists. */
+void ufont_set_arena_bytes(unsigned int bytes);
 
 /* 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);
 
+/* WOFF 1.0 support (ufont_woff.c, needs inflate): rebuild the sfnt from the
+ * per-table zlib streams.  Returns a malloc'ed TrueType/OpenType image (the
+ * caller frees it after ufont_face_open_mem()) or 0.  WOFF2 is detected but
+ * not decoded. */
+int ufont_is_woff(const void *data, unsigned int len);
+int ufont_is_woff2(const void *data, unsigned int len);
+unsigned char *ufont_woff_decode(const void *data, unsigned int len,
+				 unsigned int *out_len);
+
 void ufont_metrics(const struct ufont_face *face, int px,
 		   struct ufont_metrics *out);
 

+ 1 - 1
user/lib/ufont/ufont_internal.h

@@ -3,7 +3,7 @@
 #ifndef UFONT_INTERNAL_H
 #define UFONT_INTERNAL_H
 
-#define UFONT_MAX_FACES   16
+#define UFONT_MAX_FACES   32
 #define UFONT_MAX_POINTS  256
 #define UFONT_MAX_CONTOURS 16
 

+ 43 - 0
user/lib/ufont/ufont_test.c

@@ -126,6 +126,49 @@ int main(void)
 		       ufont_advance_cp(ef, 16, 0x1F349),
 		       ufont_advance_cp(ef, 16, 0x1F600));
 	}
+	{
+		/* WOFF 1.0: the same Arimo subset wrapped by tools/mkwoff.py
+		 * must decode to a face that measures exactly like the TTF. */
+		unsigned char *wdata = read_file("testdata/fonts/sans.woff",
+						 &len);
+		unsigned char *sfnt;
+		unsigned int slen = 0;
+		struct ufont_face *wf;
+		const char *t = "Hello, world! \xC4\xE9";
+
+		if (!wdata || !ufont_is_woff(wdata, len) ||
+		    ufont_is_woff2(wdata, len)) {
+			fprintf(stderr, "cannot read the WOFF fixture\n");
+			return 1;
+		}
+		/* Corrupted length field and truncated input are refused. */
+		wdata[11] ^= 1;
+		if (ufont_woff_decode(wdata, len, &slen) != 0) {
+			fprintf(stderr, "bad WOFF length was accepted\n");
+			return 1;
+		}
+		wdata[11] ^= 1;
+		if (ufont_woff_decode(wdata, len - 100, &slen) != 0) {
+			fprintf(stderr, "truncated WOFF was accepted\n");
+			return 1;
+		}
+		sfnt = ufont_woff_decode(wdata, len, &slen);
+		free(wdata);
+		wf = sfnt ? ufont_face_open_mem(sfnt, slen) : 0;
+		free(sfnt);
+		if (!wf) {
+			fprintf(stderr, "cannot decode the WOFF fixture\n");
+			return 1;
+		}
+		if (ufont_text_width(wf, 16, t, -1, 0) !=
+		    ufont_text_width(face, 16, t, -1, 0) ||
+		    ufont_text_width(wf, 31, t, -1, 0) !=
+		    ufont_text_width(face, 31, t, -1, 0)) {
+			fprintf(stderr, "WOFF face measures differently\n");
+			return 1;
+		}
+		printf("woff: %u-byte sfnt, widths match the TTF\n", slen);
+	}
 	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);

+ 139 - 0
user/lib/ufont/ufont_woff.c

@@ -0,0 +1,139 @@
+/* WOFF 1.0 -> sfnt.  A WOFF file is an sfnt whose tables were each
+ * zlib-compressed on their own, behind a 44-byte header and a 20-byte
+ * directory entry per table; rebuilding the TrueType file only means
+ * writing a new 12-byte offset table, 16-byte directory entries and the
+ * inflated tables, 4-byte aligned.  WOFF2 (Brotli plus glyf/loca
+ * transforms) is not handled.
+ *
+ * Separate from ufont.c so only the browser (and the host tests) link it
+ * together with inflate. */
+#include "ufont.h"
+#include "inflate.h"
+#include <stdlib.h>
+#include <string.h>
+
+#define WOFF_HDR   44u
+#define WOFF_DIR   20u
+#define WOFF_MAX_TABLES 64u
+
+static unsigned int be16(const unsigned char *p)
+{
+	return ((unsigned int)p[0] << 8) | p[1];
+}
+
+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 void put16(unsigned char *p, unsigned int v)
+{
+	p[0] = (unsigned char)(v >> 8);
+	p[1] = (unsigned char)v;
+}
+
+static void put32(unsigned char *p, unsigned int v)
+{
+	p[0] = (unsigned char)(v >> 24);
+	p[1] = (unsigned char)(v >> 16);
+	p[2] = (unsigned char)(v >> 8);
+	p[3] = (unsigned char)v;
+}
+
+int ufont_is_woff(const void *data, unsigned int len)
+{
+	const unsigned char *p = (const unsigned char *)data;
+
+	return len >= WOFF_HDR && p[0] == 'w' && p[1] == 'O' &&
+	       p[2] == 'F' && p[3] == 'F';
+}
+
+int ufont_is_woff2(const void *data, unsigned int len)
+{
+	const unsigned char *p = (const unsigned char *)data;
+
+	return len >= 4 && p[0] == 'w' && p[1] == 'O' && p[2] == 'F' &&
+	       p[3] == '2';
+}
+
+unsigned char *ufont_woff_decode(const void *data, unsigned int len,
+				 unsigned int *out_len)
+{
+	const unsigned char *src = (const unsigned char *)data;
+	unsigned int ntables, total, i, need, off, sel, pow2;
+	unsigned char *out, *ws = 0;
+
+	if (out_len)
+		*out_len = 0;
+	if (!ufont_is_woff(src, len) || be32(src + 8) != len)
+		return 0;
+	ntables = be16(src + 12);
+	total = be32(src + 16);
+	if (ntables == 0 || ntables > WOFF_MAX_TABLES ||
+	    WOFF_HDR + ntables * WOFF_DIR > len || total > UFONT_MAX_FILE)
+		return 0;
+	/* totalSfntSize is advisory; recompute the real need and refuse a
+	 * file whose tables would not fit in it. */
+	need = 12u + ntables * 16u;
+	for (i = 0; i < ntables; i++) {
+		const unsigned char *d = src + WOFF_HDR + i * WOFF_DIR;
+		unsigned int orig = be32(d + 12);
+
+		if (orig > UFONT_MAX_FILE)
+			return 0;
+		need += (orig + 3u) & ~3u;
+		if (need > UFONT_MAX_FILE)
+			return 0;
+	}
+	out = (unsigned char *)malloc(need);
+	if (!out)
+		return 0;
+	memset(out, 0, need);
+	put32(out, be32(src + 4));            /* sfnt flavor */
+	put16(out + 4, ntables);
+	for (sel = 0, pow2 = 1; pow2 * 2u <= ntables; sel++)
+		pow2 *= 2u;
+	put16(out + 6, pow2 * 16u);           /* searchRange */
+	put16(out + 8, sel);                  /* entrySelector */
+	put16(out + 10, ntables * 16u - pow2 * 16u);
+	off = 12u + ntables * 16u;
+	for (i = 0; i < ntables; i++) {
+		const unsigned char *d = src + WOFF_HDR + i * WOFF_DIR;
+		unsigned char *r = out + 12u + i * 16u;
+		unsigned int toff = be32(d + 4);
+		unsigned int comp = be32(d + 8);
+		unsigned int orig = be32(d + 12);
+
+		if (toff > len || comp > len - toff || comp > orig)
+			goto fail;
+		memcpy(r, d, 4);                  /* tag */
+		put32(r + 4, be32(d + 16));       /* checksum */
+		put32(r + 8, off);
+		put32(r + 12, orig);
+		if (comp == orig) {
+			memcpy(out + off, src + toff, orig);
+		} else {
+			unsigned int got = 0;
+
+			if (!ws) {
+				ws = (unsigned char *)malloc(
+					sizeof(struct inflate));
+				if (!ws)
+					goto fail;
+			}
+			if (inflate_zlib_mem(src + toff, comp, out + off, orig,
+					     &got, ws) != 0 || got != orig)
+				goto fail;
+		}
+		off += (orig + 3u) & ~3u;
+	}
+	free(ws);
+	if (out_len)
+		*out_len = off;
+	return out;
+fail:
+	free(ws);
+	free(out);
+	return 0;
+}

Некоторые файлы не были показаны из-за большого количества измененных файлов