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

Add browser @font-face support

Johannes Zellner 1 неделя назад
Родитель
Сommit
05c59ad9d6
12 измененных файлов с 623 добавлено и 92 удалено
  1. 16 10
      AGENTS.md
  2. 141 61
      browser.c
  3. 318 1
      browser_html.c
  4. 12 0
      browser_html.h
  5. 1 1
      docs/userland.html
  6. 48 12
      ngui.c
  7. 14 0
      ngui.h
  8. 66 0
      testdata/browser/compat/037-font-face.html
  9. 4 5
      testdata/browser/compat/README
  10. 1 0
      testdata/browser/compat/index.html
  11. 1 1
      ufont.h
  12. 1 1
      ufont_internal.h

+ 16 - 10
AGENTS.md

@@ -419,8 +419,9 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   fixed-point (26.6, no FPU) TrueType parser and antialiased rasterizer for
   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/
   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
   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`
+  `/ramfs/fonts`.  `ufont` owns one 512 KB `malloc` arena for face data and
+  glyph masks; the five built-in faces plus up to 11 `@font-face` faces share
+  it.  `ngui_font_attach/detach` (ngui) and `usurf_font_attach`
   (`uwm_lib`) load faces and leave the 8×16 bitmap fallback when they are
   (`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
   absent.  The **browser calls `ngui_font_detach` before `heap_reset()` and
   reattaches after `heap_start()`**, because its page heap is reset on every
   reattaches after `heap_start()`**, because its page heap is reset on every
@@ -822,9 +823,11 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `align-items`, two-column grids, table colspan and percentage columns,
   `align-items`, two-column grids, table colspan and percentage columns,
   and basic `float: left/right` columns.
   and basic `float: left/right` columns.
   `@media (min-width/max-width)` blocks are evaluated against the browser
   `@media (min-width/max-width)` blocks are evaluated against the browser
-  canvas width when the page is parsed; `@font-face`/`@import`/`@keyframes` are
-  skipped.  The compatibility ladder is `testdata/browser/compat/`
-  (`make compat-serve`); pages 010–036 and 030a pass (036a needs the
+  canvas width when the page is parsed; `@import`/`@keyframes` are skipped.
+  `@font-face` loads one regular TTF per family from a local path or HTTP URL
+  (the browser fetches remote faces before layout).  The compatibility
+  ladder is `testdata/browser/compat/`
+  (`make compat-serve`); pages 010–037 and 030a pass (036a needs the
   POST echo server).  Inline
   POST echo server).  Inline
   `<svg>` subtrees and closed `<details>` are skipped (not renderable), and
   `<svg>` subtrees and closed `<details>` are skipped (not renderable), and
   `<video>` gets a placeholder box.  The default page canvas follows
   `<video>` gets a placeholder box.  The default page canvas follows
@@ -1540,7 +1543,7 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     assigned to `innerHTML`, and `style`/`dataset` cover inline state rather
     assigned to `innerHTML`, and `style`/`dataset` cover inline state rather
     than computed style.  Libraries that need those APIs (jQuery plugins
     than computed style.  Libraries that need those APIs (jQuery plugins
     beyond Bootstrap's tooltip, Angular apps that use `$http`) still log
     beyond Bootstrap's tooltip, Angular apps that use `$http`) still log
-    errors even though the static page renders.  CSS also lacks `@font-face`,
+    errors even though the static page renders.  CSS also lacks
     `background-repeat`/`position`/`size` (a background image is stretched
     `background-repeat`/`position`/`size` (a background image is stretched
     to its box), the rest of `transform` (`translate` only), sticky beyond
     to its box), the rest of `transform` (`translate` only), sticky beyond
     the top edge, border-radius clipping of descendant content, gradients/
     the top edge, border-radius clipping of descendant content, gradients/
@@ -1574,7 +1577,10 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     margin/padding percentages/`em` resolve against the containing
     margin/padding percentages/`em` resolve against the containing
     width/element font (root for `rem`).  Text
     width/element font (root for `rem`).  Text
     is Latin-1 only (non-Latin-1 characters become `?`); there is no shaping,
     is Latin-1 only (non-Latin-1 characters become `?`); there is no shaping,
-    bidi, `@font-face` or full-Unicode fallback.
+    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`).
     Pages that need multi-row grid templates, `color-mix()` or full
     Pages that need multi-row grid templates, `color-mix()` or full
     transforms can still lay out imperfectly.  Images are decoded into a per-image `img_estimate()`-sized
     transforms can still lay out imperfectly.  Images are decoded into a per-image `img_estimate()`-sized
     arena that is freed after the 1000 px display bitmap is made (16 images,
     arena that is freed after the 1000 px display bitmap is made (16 images,
@@ -1639,9 +1645,9 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
 26. Fonts: `ufont` is a Latin-1-only, unhinted fixed-point TrueType subset;
 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
     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
     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
+    bitmap font.  The 512 KB arena is shared by five built-in faces, up to
+    11 `@font-face` faces and 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()`; terminal/editor cell grids stay on the 8×16 bitmap font,
     `heap_reset()`; terminal/editor cell grids stay on the 8×16 bitmap font,
     while ngui text fields use the proportional face.
     while ngui text fields use the proportional face.
 
 

+ 141 - 61
browser.c

@@ -21,6 +21,7 @@
 #include "uhttp.h"
 #include "uhttp.h"
 #include "img.h"
 #include "img.h"
 #include "inflate.h"
 #include "inflate.h"
+#include "ufont.h"
 
 
 /* Start wide enough for the desktop nav; smaller screens fall back to
 /* Start wide enough for the desktop nav; smaller screens fall back to
  * 960x640 and 780x540, which still fit a 1024x768 panel. */
  * 960x640 and 780x540, which still fit a 1024x768 panel. */
@@ -119,6 +120,7 @@ static unsigned short img_h[BR_MAX_NODES];
  * for page/CSS fetches, where the heap has no room for another multi-megabyte
  * for page/CSS fetches, where the heap has no room for another multi-megabyte
  * body.  Decode arenas are allocated per image instead of living here. */
  * body.  Decode arenas are allocated per image instead of living here. */
 static unsigned char *image_io_buf;
 static unsigned char *image_io_buf;
+static struct ufont_face *font_faces[BR_MAX_FACES];
 #define image_file_buf (image_io_buf)
 #define image_file_buf (image_io_buf)
 #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
 #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
 #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
 #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
@@ -172,7 +174,7 @@ struct lay_run {
 	signed short dy;       /* inline image vertical offset */
 	signed short dy;       /* inline image vertical offset */
 	unsigned short iw, ih;
 	unsigned short iw, ih;
 	unsigned short w;
 	unsigned short w;
-	unsigned char font_px, bold, italic, mono, underline;
+	unsigned char font_px, bold, italic, mono, underline, font_face;
 	unsigned char has_lit;
 	unsigned char has_lit;
 	unsigned int form;          /* node + 1, 0 = not a control */
 	unsigned int form;          /* node + 1, 0 = not a control */
 	unsigned char form_kind;
 	unsigned char form_kind;
@@ -503,6 +505,7 @@ static int heap_start(void)
 
 
 static void heap_clear(void)
 static void heap_clear(void)
 {
 {
+	memset(font_faces, 0, sizeof(font_faces));
 	ngui_font_detach(&ui);
 	ngui_font_detach(&ui);
 	heap_reset();
 	heap_reset();
 	image_io_buf = 0;
 	image_io_buf = 0;
@@ -1823,6 +1826,48 @@ static int read_url(const char *url, unsigned int cap, unsigned char **out,
 	return 0;
 	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 void load_font_faces(void)
+{
+	unsigned int i;
+
+	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];
+
+		if (!url || !url[0])
+			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);
+		}
+	}
+}
+
 /* Remote scripts are cached under /share for the current boot, like the
 /* Remote scripts are cached under /share for the current boot, like the
  * stylesheet cache, so reloads and later visits skip the network. */
  * stylesheet cache, so reloads and later visits skip the network. */
 static int script_cache_count;
 static int script_cache_count;
@@ -2252,11 +2297,15 @@ static int load_stylesheets(void)
 			return FETCH_ABORT;
 			return FETCH_ABORT;
 		if (rv != 0)
 		if (rv != 0)
 			continue;
 			continue;
-		if (len)
+		if (len) {
+			br_set_font_base(url);
 			br_parse_css_text(&doc, (const char *)data, len);
 			br_parse_css_text(&doc, (const char *)data, len);
+		}
 		sheets++;
 		sheets++;
 	}
 	}
+	br_set_font_base(page_url);
 	br_parse_inline_css(&doc);
 	br_parse_inline_css(&doc);
+	load_font_faces();
 	br_reset_styles(&doc);
 	br_reset_styles(&doc);
 	layout_valid = 0;
 	layout_valid = 0;
 	return 0;
 	return 0;
@@ -2843,6 +2892,53 @@ static void navigate(const char *input, int push)
 
 
 /* ---- layout ---- */
 /* ---- layout ---- */
 
 
+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;
+}
+
+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;
+}
+
+static unsigned int face_text_width(struct ngui *gui,
+				    const struct br_style *st,
+				    const char *s, unsigned int n)
+{
+	return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
+				    st->bold, st->italic, st->mono);
+}
+
+static int face_line_height(struct ngui *gui, const struct br_style *st)
+{
+	return ngui_text_line_height_face(gui, style_face(st), st->font_px,
+					  st->mono);
+}
+
+static unsigned int run_text_width(struct ngui *gui,
+				   const struct lay_run *r,
+				   const char *s, unsigned int n)
+{
+	return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
+				    r->bold, r->italic, r->mono);
+}
+
+static int run_line_height(struct ngui *gui, const struct lay_run *r)
+{
+	return ngui_text_line_height_face(gui, run_face(r), r->font_px,
+					  r->mono);
+}
+
+static int run_ascent(struct ngui *gui, const struct lay_run *r)
+{
+	return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
+}
+
 static struct br_style base_style(void)
 static struct br_style base_style(void)
 {
 {
 	struct br_style s = { 0 };
 	struct br_style s = { 0 };
@@ -3065,10 +3161,11 @@ static void flush_line(struct lay *l)
 					ngui_frame(l->ui, box,
 					ngui_frame(l->ui, box,
 						   focused ? l->ui->theme.accent :
 						   focused ? l->ui->theme.accent :
 						   l->ui->theme.border);
 						   l->ui->theme.border);
-					ngui_text_px(l->ui, x + 6, ry + 2,
-						     r->lit, s_len(r->lit), fg,
-						     r->font_px, r->bold,
-						     r->italic, r->mono);
+					ngui_text_px_face(l->ui, run_face(r),
+							  x + 6, ry + 2,
+							  r->lit, s_len(r->lit),
+							  fg, r->font_px, r->bold,
+							  r->italic, r->mono);
 					if (focused && fs &&
 					if (focused && fs &&
 					    (r->form_kind == FORM_TEXT ||
 					    (r->form_kind == FORM_TEXT ||
 					     r->form_kind == FORM_PASSWORD ||
 					     r->form_kind == FORM_PASSWORD ||
@@ -3076,12 +3173,10 @@ static void flush_line(struct lay *l)
 						int cw = 0;
 						int cw = 0;
 
 
 						if (fs->len && fs->caret)
 						if (fs->len && fs->caret)
-							cw = (int)ngui_text_width_px(
-								l->ui, r->lit,
+							cw = (int)run_text_width(
+								l->ui, r, r->lit,
 								fs->caret < fs->len ?
 								fs->caret < fs->len ?
-								fs->caret : fs->len,
-								r->font_px, r->bold,
-								r->italic, r->mono);
+								fs->caret : fs->len);
 						ngui_fill_rect(l->ui,
 						ngui_fill_rect(l->ui,
 							(struct ngui_rect){
 							(struct ngui_rect){
 								x + 6 + cw,
 								x + 6 + cw,
@@ -3105,10 +3200,11 @@ static void flush_line(struct lay *l)
 				ngui_frame(l->ui,
 				ngui_frame(l->ui,
 					(struct ngui_rect){x, ry, w, hh},
 					(struct ngui_rect){x, ry, w, hh},
 					l->ui->theme.border);
 					l->ui->theme.border);
-				ngui_text_px(l->ui, x + 6, ry + 2,
-					     r->lit, s_len(r->lit), r->color,
-					     r->font_px, r->bold, r->italic,
-					     r->mono);
+				ngui_text_px_face(l->ui, run_face(r),
+						  x + 6, ry + 2, r->lit,
+						  s_len(r->lit), r->color,
+						  r->font_px, r->bold, r->italic,
+						  r->mono);
 			} else if (r->img >= 0) {
 			} else if (r->img >= 0) {
 				struct br_image *bi = &images[r->img];
 				struct br_image *bi = &images[r->img];
 				if (bi->state == 1) {
 				if (bi->state == 1) {
@@ -3134,16 +3230,13 @@ static void flush_line(struct lay *l)
 						doc.text + r->off;
 						doc.text + r->off;
 				unsigned int n = r->has_lit ? s_len(r->lit) :
 				unsigned int n = r->has_lit ? s_len(r->lit) :
 						r->len;
 						r->len;
-				ngui_text_px(l->ui, x, ry, s, n,
-					     r->color, r->font_px, r->bold,
-					     r->italic, r->mono);
+				ngui_text_px_face(l->ui, run_face(r), x, ry,
+						  s, n, r->color, r->font_px,
+						  r->bold, r->italic, r->mono);
 				if (r->underline)
 				if (r->underline)
 					ngui_fill_rect(l->ui,
 					ngui_fill_rect(l->ui,
 						(struct ngui_rect){x,
 						(struct ngui_rect){x,
-						 ry +
-						 ngui_text_ascent(l->ui,
-								  r->font_px,
-								  r->mono) + 2,
+						 ry + run_ascent(l->ui, r) + 2,
 						 w, 1}, r->color);
 						 w, 1}, r->color);
 			}
 			}
 			if (r->form || r->href) {
 			if (r->form || r->href) {
@@ -3153,8 +3246,7 @@ static void flush_line(struct lay *l)
 						r->form - 1 : r->href;
 						r->form - 1 : r->href;
 					int hh = (r->form || r->img >= 0) ?
 					int hh = (r->form || r->img >= 0) ?
 						 r->ih :
 						 r->ih :
-						 ngui_text_line_height(l->ui,
-						 r->font_px, r->mono);
+						 run_line_height(l->ui, r);
 					int merge = nhits > 0 &&
 					int merge = nhits > 0 &&
 						hits[nhits - 1].node == target &&
 						hits[nhits - 1].node == target &&
 						hits[nhits - 1].y == ry &&
 						hits[nhits - 1].y == ry &&
@@ -3197,8 +3289,7 @@ static void add_run(struct lay *l, unsigned short off, unsigned short len,
 {
 {
 	unsigned int n = lit ? s_len(lit) : len;
 	unsigned int n = lit ? s_len(lit) : len;
 	const char *tp = lit ? lit : doc.text + off;
 	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);
+	int w = (int)face_text_width(l->ui, st, tp, n);
 
 
 	if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
 	if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
 		flush_line(l);
 		flush_line(l);
@@ -3237,28 +3328,27 @@ static void add_run(struct lay *l, unsigned short off, unsigned short len,
 		r->bold = st->bold;
 		r->bold = st->bold;
 		r->italic = st->italic;
 		r->italic = st->italic;
 		r->mono = st->mono;
 		r->mono = st->mono;
+		r->font_face = st->font_face;
 		/* A control with its own background is a button, not body copy;
 		/* A control with its own background is a button, not body copy;
 		 * an inherited link underline would strike through the fill. */
 		 * an inherited link underline would strike through the fill. */
 		r->underline = st->underline && !st->has_bg;
 		r->underline = st->underline && !st->has_bg;
 		r->w = (unsigned short)w;
 		r->w = (unsigned short)w;
 		if (r->has_lit)
 		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);
+			r->w = (unsigned short)run_text_width(
+				l->ui, r, r->lit, s_len(r->lit));
 		w = r->w;
 		w = r->w;
 	}
 	}
 	l->line_x += w;
 	l->line_x += w;
 	l->run_x = l->line_x;
 	l->run_x = l->line_x;
 	{
 	{
-		int lh = ngui_text_line_height(l->ui, st->font_px, st->mono);
+		int lh = face_line_height(l->ui, st);
 
 
 		if (st->line_h_px)
 		if (st->line_h_px)
 			lh = st->line_h_px;
 			lh = st->line_h_px;
 		else if (st->line_h_pct)
 		else if (st->line_h_pct)
 			lh = st->font_px * st->line_h_pct / 100;
 			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 (lh < face_line_height(l->ui, st))
+			lh = face_line_height(l->ui, st);
 		if (l->line_h < lh)
 		if (l->line_h < lh)
 			l->line_h = lh;
 			l->line_h = lh;
 	}
 	}
@@ -3277,9 +3367,7 @@ static void add_image_run(struct lay *l, unsigned int node,
 		start_line(l, st);
 		start_line(l, st);
 	if (l->space_pending &&
 	if (l->space_pending &&
 	    (l->nruns > 0 || l->line_x > l->line_left)) {
 	    (l->nruns > 0 || l->line_x > l->line_left)) {
-		int sp = (int)ngui_text_width_px(l->ui, " ", 1, st->font_px,
-						 st->bold, st->italic,
-						 st->mono);
+		int sp = (int)face_text_width(l->ui, st, " ", 1);
 		if (l->line_x + sp <= l->line_right)
 		if (l->line_x + sp <= l->line_right)
 			l->line_x += sp;
 			l->line_x += sp;
 	}
 	}
@@ -3296,16 +3384,14 @@ static void add_image_run(struct lay *l, unsigned int node,
 		s_append(tmp, &n, "[", sizeof(tmp));
 		s_append(tmp, &n, "[", sizeof(tmp));
 		s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
 		s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
 		s_append(tmp, &n, "]", sizeof(tmp));
 		s_append(tmp, &n, "]", sizeof(tmp));
-		w = (int)ngui_text_width_px(l->ui, tmp, n, gs.font_px,
-					    gs.bold, gs.italic, gs.mono);
+		w = (int)face_text_width(l->ui, &gs, tmp, n);
 		if (l->line_x + w > l->line_right &&
 		if (l->line_x + w > l->line_right &&
 		    (l->nruns > 0 || l->line_x > l->line_left))
 		    (l->nruns > 0 || l->line_x > l->line_left))
 			flush_line(l);
 			flush_line(l);
 		add_run(l, 0, 0, &gs, href, tmp);
 		add_run(l, 0, 0, &gs, href, tmp);
 		if (!l->draw) {
 		if (!l->draw) {
 			int t = l->line_y < 0 ? 0 : l->line_y;
 			int t = l->line_y < 0 ? 0 : l->line_y;
-			int hh = ngui_text_line_height(l->ui, gs.font_px,
-						       gs.mono);
+			int hh = face_line_height(l->ui, &gs);
 
 
 			if (t > 65535)
 			if (t > 65535)
 				t = 65535;
 				t = 65535;
@@ -3434,6 +3520,7 @@ static void add_image_run(struct lay *l, unsigned int node,
 		r->bold = st->bold;
 		r->bold = st->bold;
 		r->italic = st->italic;
 		r->italic = st->italic;
 		r->mono = st->mono;
 		r->mono = st->mono;
+		r->font_face = st->font_face;
 		r->underline = 0;
 		r->underline = 0;
 	}
 	}
 	if (node < BR_MAX_NODES) {
 	if (node < BR_MAX_NODES) {
@@ -3454,8 +3541,7 @@ static void add_image_run(struct lay *l, unsigned int node,
 static int text_width(struct lay *l, const char *s, unsigned int n,
 static int text_width(struct lay *l, const char *s, unsigned int n,
 		      const struct br_style *st)
 		      const struct br_style *st)
 {
 {
-	return (int)ngui_text_width_px(l->ui, s, n, st->font_px,
-				       st->bold, st->italic, st->mono);
+	return (int)face_text_width(l->ui, st, s, n);
 }
 }
 
 
 /* Longest prefix that fits in maxw, at least one byte. */
 /* Longest prefix that fits in maxw, at least one byte. */
@@ -3521,8 +3607,7 @@ static void emit_text(struct lay *l, const char *s, unsigned int len,
 {
 {
 	unsigned int i = 0;
 	unsigned int i = 0;
 	unsigned int base;
 	unsigned int base;
-	int space_w = (int)ngui_text_width_px(l->ui, " ", 1, st->font_px,
-					      st->bold, st->italic, st->mono);
+	int space_w = (int)face_text_width(l->ui, st, " ", 1);
 
 
 	if (!s || !len)
 	if (!s || !len)
 		return;
 		return;
@@ -3648,8 +3733,7 @@ static void add_form_run(struct lay *l, unsigned int node,
 			h = 40;
 			h = 40;
 		}
 		}
 	}
 	}
-	tw = (int)ngui_text_width_px(l->ui, text, s_len(text), st->font_px,
-				     st->bold, st->italic, st->mono);
+	tw = (int)face_text_width(l->ui, st, text, s_len(text));
 	if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
 	if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
 		w = tw + 18;
 		w = tw + 18;
 		if (w < 64)
 		if (w < 64)
@@ -3692,6 +3776,7 @@ static void add_form_run(struct lay *l, unsigned int node,
 	r->bold = st->bold;
 	r->bold = st->bold;
 	r->italic = st->italic;
 	r->italic = st->italic;
 	r->mono = st->mono;
 	r->mono = st->mono;
+	r->font_face = st->font_face;
 	r->underline = 0;
 	r->underline = 0;
 	r->form = node + 1;
 	r->form = node + 1;
 	r->form_kind = (unsigned char)kind;
 	r->form_kind = (unsigned char)kind;
@@ -3990,11 +4075,11 @@ static void draw_svg(struct ngui *ui, unsigned node,
 				continue;
 				continue;
 			s = doc.text + doc.nodes[t].text_off;
 			s = doc.text + doc.nodes[t].text_off;
 			n = doc.nodes[t].text_len;
 			n = doc.nodes[t].text_len;
-			tw = ngui_text_width_px(ui, s, n, px, st.bold,
-						st.italic, st.mono);
+			tw = face_text_width(ui, &st, s, n);
 			tx = ox + (int)nd->svg_x * dw / vw;
 			tx = ox + (int)nd->svg_x * dw / vw;
 			ty = oy + (int)nd->svg_y * dh / vh -
 			ty = oy + (int)nd->svg_y * dh / vh -
-			     ngui_text_ascent(ui, px, st.mono);
+			     ngui_text_ascent_face(ui, style_face(&st), px,
+						   st.mono);
 			anchor = st.align;
 			anchor = st.align;
 			if (nd->attr_flags & BR_ATTR_ANCHOR_MIDDLE)
 			if (nd->attr_flags & BR_ATTR_ANCHOR_MIDDLE)
 				anchor = BR_ALIGN_CENTER;
 				anchor = BR_ALIGN_CENTER;
@@ -4004,8 +4089,9 @@ static void draw_svg(struct ngui *ui, unsigned node,
 				tx -= (int)tw / 2;
 				tx -= (int)tw / 2;
 			else if (anchor == BR_ALIGN_RIGHT)
 			else if (anchor == BR_ALIGN_RIGHT)
 				tx -= (int)tw;
 				tx -= (int)tw;
-			ngui_text_px(ui, tx, ty, s, n, st.color, px,
-				     st.bold, st.italic, st.mono);
+			ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
+					  st.color, px, st.bold, st.italic,
+					  st.mono);
 		}
 		}
 	}
 	}
 }
 }
@@ -4422,16 +4508,12 @@ static int intrinsic_width(struct ngui *ui, unsigned int node,
 			unsigned int tn = nd->text_len;
 			unsigned int tn = nd->text_len;
 
 
 			if (doc.nodes[node].tag == BR_TAG_PRE) {
 			if (doc.nodes[node].tag == BR_TAG_PRE) {
-				w += (int)ngui_text_width_px(ui, t, tn,
-					pst->font_px, pst->bold, pst->italic,
-					pst->mono);
+				w += (int)face_text_width(ui, pst, t, tn);
 			} else {
 			} else {
 				unsigned int ti = 0;
 				unsigned int ti = 0;
 				int first = 1;
 				int first = 1;
 				int lead = w > 0 && tn > 0 && text_space(t[0]);
 				int lead = w > 0 && tn > 0 && text_space(t[0]);
-				int sp = (int)ngui_text_width_px(ui, " ", 1,
-					pst->font_px, pst->bold, pst->italic,
-					pst->mono);
+				int sp = (int)face_text_width(ui, pst, " ", 1);
 
 
 				while (ti < tn) {
 				while (ti < tn) {
 					unsigned int ts;
 					unsigned int ts;
@@ -4446,10 +4528,8 @@ static int intrinsic_width(struct ngui *ui, unsigned int node,
 					if (!first || lead)
 					if (!first || lead)
 						w += sp;
 						w += sp;
 					lead = 0;
 					lead = 0;
-					w += (int)ngui_text_width_px(ui,
-						t + ts, ti - ts,
-						pst->font_px, pst->bold,
-						pst->italic, pst->mono);
+					w += (int)face_text_width(ui, pst,
+						t + ts, ti - ts);
 					first = 0;
 					first = 0;
 				}
 				}
 			}
 			}

+ 318 - 1
browser_html.c

@@ -3,6 +3,7 @@
  * implements the properties in the browser's documented subset. */
  * implements the properties in the browser's documented subset. */
 
 
 #include "browser_html.h"
 #include "browser_html.h"
+#include <string.h>
 
 
 static int is_space(char c);
 static int is_space(char c);
 static int is_ident(char c);
 static int is_ident(char c);
@@ -19,6 +20,65 @@ static int root_font_px = 16;
 static char bg_urls[BR_BG_URLS][192];
 static char bg_urls[BR_BG_URLS][192];
 static unsigned int bg_url_count;
 static unsigned int bg_url_count;
 
 
+/* @font-face definitions, one document at a time.  The URL is resolved by
+ * the browser against `base` (the sheet URL, or the page URL for <style>). */
+struct br_font_def {
+	char family[BR_FACE_FAMILY];
+	char url[BR_FACE_URL];
+	char base[192];
+	unsigned char used;
+};
+static struct br_font_def font_defs[BR_MAX_FACES];
+static int font_face_count;
+static char font_base[192];
+
+static void font_reset(void)
+{
+	memset(font_defs, 0, sizeof(font_defs));
+	font_face_count = 0;
+	font_base[0] = '\0';
+}
+
+void br_set_font_base(const char *base)
+{
+	unsigned int i = 0;
+
+	if (!base)
+		base = "";
+	while (base[i] && i + 1 < sizeof(font_base)) {
+		font_base[i] = base[i];
+		i++;
+	}
+	font_base[i] = '\0';
+}
+
+int br_font_face_count(void)
+{
+	return font_face_count;
+}
+
+const char *br_font_face_url(int id)
+{
+	if (id < 1 || id > font_face_count)
+		return "";
+	return font_defs[id - 1].url;
+}
+
+const char *br_font_face_base(int id)
+{
+	if (id < 1 || id > font_face_count)
+		return "";
+	return font_defs[id - 1].base[0] ? font_defs[id - 1].base :
+					   font_base;
+}
+
+const char *br_font_face_family(int id)
+{
+	if (id < 1 || id > font_face_count)
+		return "";
+	return font_defs[id - 1].family;
+}
+
 const char *br_bg_image_url(unsigned int idx)
 const char *br_bg_image_url(unsigned int idx)
 {
 {
 	if (idx >= bg_url_count)
 	if (idx >= bg_url_count)
@@ -744,6 +804,7 @@ void br_doc_init(struct br_doc *d)
 		d->var_slot[vi] = 0;
 		d->var_slot[vi] = 0;
 	root_font_px = 16;
 	root_font_px = 16;
 	bg_url_count = 0;
 	bg_url_count = 0;
+	font_reset();
 }
 }
 
 
 void br_set_rule_store(struct br_doc *d, struct br_rule *buf,
 void br_set_rule_store(struct br_doc *d, struct br_rule *buf,
@@ -780,6 +841,7 @@ static void doc_reset(struct br_doc *d)
 	d->script_src = 0;
 	d->script_src = 0;
 	d->nscripts = 0;
 	d->nscripts = 0;
 	d->scripts_truncated = 0;
 	d->scripts_truncated = 0;
+	font_reset();
 	for (i = 0; i < BR_MAX_NODES; i++) {
 	for (i = 0; i < BR_MAX_NODES; i++) {
 		d->nodes[i].type = BR_NODE_ELEM;
 		d->nodes[i].type = BR_NODE_ELEM;
 		d->nodes[i].tag = BR_TAG_UNKNOWN;
 		d->nodes[i].tag = BR_TAG_UNKNOWN;
@@ -2217,7 +2279,7 @@ static int str_eq(const char *a, const char *b)
 
 
 enum {
 enum {
 	PROP_COLOR, PROP_BG, PROP_BG_IMAGE, PROP_FONT_PX, PROP_FONT_UNIT,
 	PROP_COLOR, PROP_BG, PROP_BG_IMAGE, PROP_FONT_PX, PROP_FONT_UNIT,
-	PROP_BOLD, PROP_ITALIC, PROP_MONO,
+	PROP_BOLD, PROP_ITALIC, PROP_MONO, PROP_FONT_FACE,
 	PROP_ALIGN, PROP_UNDERLINE,
 	PROP_ALIGN, PROP_UNDERLINE,
 	PROP_DISPLAY, PROP_MT, PROP_MR, PROP_MB, PROP_ML,
 	PROP_DISPLAY, PROP_MT, PROP_MR, PROP_MB, PROP_ML,
 	PROP_PT, PROP_PR, PROP_PB, PROP_PL,
 	PROP_PT, PROP_PR, PROP_PB, PROP_PL,
@@ -3430,6 +3492,253 @@ static unsigned int css_skip_nested(const char *s, unsigned int len,
 	return i;
 	return i;
 }
 }
 
 
+/* ---- @font-face ------------------------------------------------------- */
+
+static void font_trim(const char **sp, unsigned int *len)
+{
+	const char *s = *sp;
+	unsigned int n = *len;
+
+	while (n && is_space(*s)) {
+		s++;
+		n--;
+	}
+	while (n && is_space(s[n - 1]))
+		n--;
+	if (n >= 2 && (s[0] == '"' || s[0] == '\'') && s[n - 1] == s[0]) {
+		s++;
+		n -= 2;
+	}
+	*sp = s;
+	*len = n;
+}
+
+static void font_add(const char *family, unsigned int flen,
+		     const char *url, unsigned int ulen)
+{
+	unsigned int i, n = 0, k;
+
+	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)
+			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)
+			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';
+		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->used = 1;
+		font_face_count++;
+	}
+}
+
+/* Look up the first name in a font-family list that has an @font-face. */
+static int font_family_id(const char *s, unsigned int len)
+{
+	unsigned int i = 0;
+
+	while (i < len) {
+		unsigned int start, end, q = 0;
+
+		while (i < len && (is_space(s[i]) || s[i] == ','))
+			i++;
+		if (i >= len)
+			break;
+		if (s[i] == '"' || s[i] == '\'') {
+			char quote = s[i++];
+
+			start = i;
+			while (i < len && s[i] != quote)
+				i++;
+			end = i;
+			if (i < len)
+				i++;
+		} else {
+			start = i;
+			while (i < len && s[i] != ',')
+				i++;
+			end = i;
+			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 (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;
+			}
+		}
+	}
+	return 0;
+}
+
+/* Pre-scan a stylesheet for @font-face blocks.  The main rule parser skips
+ * at-rules, so faces must be registered before any font-family declaration
+ * in the same sheet is resolved. */
+static void scan_font_faces(const char *s, unsigned int len)
+{
+	unsigned int i = 0;
+
+	while (i + 10 <= 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;
+
+		if (s[i] != '@' || !ci_eq_n(s + i, "@font-face", 10)) {
+			i++;
+			continue;
+		}
+		j = i + 10;
+		while (j < len && s[j] != '{' && s[j] != ';')
+			j++;
+		if (j >= len || s[j] == ';') {
+			i = j + 1;
+			continue;
+		}
+		end = css_skip_nested(s, len, j + 1);
+		p = j + 1;
+		while (p < end) {
+			unsigned int ds, de, vs, ve;
+
+			while (p < end && (is_space(s[p]) || s[p] == ';'))
+				p++;
+			if (p >= end)
+				break;
+			ds = p;
+			while (p < end && s[p] != ':' && s[p] != ';')
+				p++;
+			de = p;
+			if (p >= end || s[p] != ':') {
+				while (p < end && s[p] != ';')
+					p++;
+				continue;
+			}
+			p++;
+			vs = p;
+			while (p < end && s[p] != ';')
+				p++;
+			ve = p;
+			while (ds < de && is_space(s[ds]))
+				ds++;
+			while (de > ds && is_space(s[de - 1]))
+				de--;
+			while (vs < ve && is_space(s[vs]))
+				vs++;
+			while (ve > vs && is_space(s[ve - 1]))
+				ve--;
+			if (de - ds == 11 &&
+			    ci_eq_n(s + ds, "font-family", 11)) {
+				const char *fp = s + vs;
+				unsigned int fn = ve - vs;
+
+				font_trim(&fp, &fn);
+				if (fn && fn < sizeof(family)) {
+					unsigned int k;
+
+					for (k = 0; k < fn; k++)
+						family[k] = fp[k];
+					family[fn] = '\0';
+					flen = fn;
+					have_family = 1;
+				}
+			} 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;
+						}
+					}
+				}
+			}
+		}
+		if (have_family && have_url)
+			font_add(family, flen, url, ulen);
+		i = end;
+	}
+}
+
 /* One border-radius length.  Unlike parse_size(), percentages keep their
 /* One border-radius length.  Unlike parse_size(), percentages keep their
  * kind: the drawer scales them to the box, not the viewport. */
  * kind: the drawer scales them to the box, not the viewport. */
 static int parse_radius_value(const char *s, unsigned int len,
 static int parse_radius_value(const char *s, unsigned int len,
@@ -3569,6 +3878,7 @@ static void add_font_shorthand(struct br_decl *out, unsigned int *nout,
 	decl_add(out, nout, PROP_BOLD, bold, important);
 	decl_add(out, nout, PROP_BOLD, bold, important);
 	decl_add(out, nout, PROP_ITALIC, italic, important);
 	decl_add(out, nout, PROP_ITALIC, italic, important);
 	decl_add(out, nout, PROP_MONO, mono, important);
 	decl_add(out, nout, PROP_MONO, mono, important);
+	decl_add(out, nout, PROP_FONT_FACE, 0, important);
 	decl_add(out, nout, PROP_LH_PX, lh_px, important);
 	decl_add(out, nout, PROP_LH_PX, lh_px, important);
 	decl_add(out, nout, PROP_LH_PCT, lh_pct, important);
 	decl_add(out, nout, PROP_LH_PCT, lh_pct, important);
 }
 }
@@ -3752,10 +4062,12 @@ static void parse_decls(struct br_doc *d, const char *s,
 		} else if (str_eq(prop, "font-family")) {
 		} else if (str_eq(prop, "font-family")) {
 			unsigned int j;
 			unsigned int j;
 			int mono = 0;
 			int mono = 0;
+			int face = font_family_id(s + vstart, vend - vstart);
 
 
 			for (j = vstart; j + 4 <= vend; j++)
 			for (j = vstart; j + 4 <= vend; j++)
 				if (ci_eq_n(s + j, "mono", 4))
 				if (ci_eq_n(s + j, "mono", 4))
 					mono = 1;
 					mono = 1;
+			decl_add(out, nout, PROP_FONT_FACE, face, important);
 			decl_add(out, nout, PROP_MONO, mono, important);
 			decl_add(out, nout, PROP_MONO, mono, important);
 		} else if (str_eq(prop, "font")) {
 		} else if (str_eq(prop, "font")) {
 			add_font_shorthand(out, nout, s + vstart,
 			add_font_shorthand(out, nout, s + vstart,
@@ -5038,6 +5350,7 @@ static void detect_root_font(const char *s, unsigned int len)
 
 
 void br_parse_css_text(struct br_doc *d, const char *css, unsigned int len)
 void br_parse_css_text(struct br_doc *d, const char *css, unsigned int len)
 {
 {
+	scan_font_faces(css, len);
 	detect_root_font(css, len);
 	detect_root_font(css, len);
 	css_collect_only = 1;
 	css_collect_only = 1;
 	parse_css(d, css, len);
 	parse_css(d, css, len);
@@ -5048,6 +5361,7 @@ void br_parse_css_text(struct br_doc *d, const char *css, unsigned int len)
 void br_parse_inline_css(struct br_doc *d)
 void br_parse_inline_css(struct br_doc *d)
 {
 {
 	if (d->inline_css_len) {
 	if (d->inline_css_len) {
+		scan_font_faces(css_store, d->inline_css_len);
 		detect_root_font(css_store, d->inline_css_len);
 		detect_root_font(css_store, d->inline_css_len);
 		css_collect_only = 1;
 		css_collect_only = 1;
 		parse_css(d, css_store, d->inline_css_len);
 		parse_css(d, css_store, d->inline_css_len);
@@ -5496,6 +5810,9 @@ static void apply_decl(struct br_style *st, const struct br_decl *dcl)
 	case PROP_MONO:
 	case PROP_MONO:
 		st->mono = (unsigned char)(dcl->val != 0);
 		st->mono = (unsigned char)(dcl->val != 0);
 		break;
 		break;
+	case PROP_FONT_FACE:
+		st->font_face = (unsigned char)dcl->val;
+		break;
 	case PROP_ALIGN:
 	case PROP_ALIGN:
 		st->align = (unsigned char)dcl->val;
 		st->align = (unsigned char)dcl->val;
 		break;
 		break;

+ 12 - 0
browser_html.h

@@ -12,6 +12,9 @@
 #define BR_CSS_SIZE      12288
 #define BR_CSS_SIZE      12288
 #define BR_MAX_RULES     4608
 #define BR_MAX_RULES     4608
 #define BR_RULE_FALLBACK 256
 #define BR_RULE_FALLBACK 256
+#define BR_MAX_FACES     8
+#define BR_FACE_FAMILY   40
+#define BR_FACE_URL      192
 #define BR_MAX_VARS      512
 #define BR_MAX_VARS      512
 #define BR_TAG_MAX       128
 #define BR_TAG_MAX       128
 #define BR_RULE_HASH     256
 #define BR_RULE_HASH     256
@@ -94,6 +97,7 @@ struct br_style {
 	unsigned char bold;
 	unsigned char bold;
 	unsigned char italic;
 	unsigned char italic;
 	unsigned char mono;
 	unsigned char mono;
+	unsigned char font_face;    /* 1-based @font-face id, 0 = built-in */
 	unsigned char underline;
 	unsigned char underline;
 	unsigned char align;        /* BR_ALIGN_* */
 	unsigned char align;        /* BR_ALIGN_* */
 	unsigned char display;      /* BR_DISPLAY_* */
 	unsigned char display;      /* BR_DISPLAY_* */
@@ -269,6 +273,14 @@ unsigned int br_tag_from_name(const char *name);
 const char *br_bg_image_url(unsigned int idx);
 const char *br_bg_image_url(unsigned int idx);
 unsigned int br_root_font_px(void);
 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. */
+int br_font_face_count(void);
+const char *br_font_face_url(int id);
+const char *br_font_face_base(int id);
+const char *br_font_face_family(int id);
+void br_set_font_base(const char *base);
+
 /* Runtime DOM helpers used by the JavaScript bindings.  br_find_id returns
 /* Runtime DOM helpers used by the JavaScript bindings.  br_find_id returns
  * node + 1 (0 means no match); br_text_content concatenates the subtree's
  * node + 1 (0 means no match); br_text_content concatenates the subtree's
  * text nodes into out and returns the (possibly truncated) length. */
  * text nodes into out and returns the (possibly truncated) length. */

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


+ 48 - 12
ngui.c

@@ -718,9 +718,10 @@ static void ngui_clip_bounds(struct ngui *ui, int *cx, int *cy,
 	*ch = r.h;
 	*ch = r.h;
 }
 }
 
 
-int ngui_text_ascent(struct ngui *ui, int px, int mono)
+int ngui_text_ascent_face(struct ngui *ui, struct ufont_face *face, int px,
+			  int mono)
 {
 {
-	struct ufont_face *f = ngui_face(ui, 0, 0, mono);
+	struct ufont_face *f = face ? face : ngui_face(ui, 0, 0, mono);
 	struct ufont_metrics m;
 	struct ufont_metrics m;
 
 
 	if (f) {
 	if (f) {
@@ -730,9 +731,15 @@ int ngui_text_ascent(struct ngui *ui, int px, int mono)
 	return 16 * (px >= 24 ? 2 : 1);
 	return 16 * (px >= 24 ? 2 : 1);
 }
 }
 
 
-int ngui_text_line_height(struct ngui *ui, int px, int mono)
+int ngui_text_ascent(struct ngui *ui, int px, int mono)
+{
+	return ngui_text_ascent_face(ui, 0, px, mono);
+}
+
+int ngui_text_line_height_face(struct ngui *ui, struct ufont_face *face,
+			       int px, int mono)
 {
 {
-	struct ufont_face *f = ngui_face(ui, 0, 0, mono);
+	struct ufont_face *f = face ? face : ngui_face(ui, 0, 0, mono);
 	struct ufont_metrics m;
 	struct ufont_metrics m;
 
 
 	if (f) {
 	if (f) {
@@ -742,10 +749,16 @@ int ngui_text_line_height(struct ngui *ui, int px, int mono)
 	return 16 * (px >= 24 ? 2 : 1);
 	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)
+int ngui_text_line_height(struct ngui *ui, int px, int mono)
+{
+	return ngui_text_line_height_face(ui, 0, px, mono);
+}
+
+unsigned int ngui_text_width_face(struct ngui *ui, struct ufont_face *face,
+				  const char *s, unsigned int n, int px,
+				  int bold, int italic, int mono)
 {
 {
-	struct ufont_face *f = ngui_face(ui, bold, italic, mono);
+	struct ufont_face *f = face ? face : ngui_face(ui, bold, italic, mono);
 	int scale;
 	int scale;
 
 
 	if (f)
 	if (f)
@@ -754,6 +767,12 @@ unsigned int ngui_text_width_px(struct ngui *ui, const char *s, unsigned int n,
 	return n * 8u * (unsigned int)scale;
 	return n * 8u * (unsigned int)scale;
 }
 }
 
 
+unsigned int ngui_text_width_px(struct ngui *ui, const char *s, unsigned int n,
+				int px, int bold, int italic, int mono)
+{
+	return ngui_text_width_face(ui, 0, s, n, px, bold, italic, mono);
+}
+
 unsigned int ngui_text_width_ui(struct ngui *ui, const char *s)
 unsigned int ngui_text_width_ui(struct ngui *ui, const char *s)
 {
 {
 	return ngui_text_width_px(ui, s, slen(s),
 	return ngui_text_width_px(ui, s, slen(s),
@@ -773,11 +792,12 @@ unsigned int ngui_text_width_n(const char *s, unsigned int n, int scale)
 	return n * 8u * (unsigned 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)
+static void ngui_text_px_common(struct ngui *ui, struct ufont_face *face,
+				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);
+	struct ufont_face *f = face ? face : ngui_face(ui, bold, italic, mono);
 	int scale, i, pen = 0, ascent;
 	int scale, i, pen = 0, ascent;
 	int cx, cy, cw, ch;
 	int cx, cy, cw, ch;
 
 
@@ -791,7 +811,7 @@ void ngui_text_px(struct ngui *ui, int x, int y, const char *s,
 					  scale, bold);
 					  scale, bold);
 		return;
 		return;
 	}
 	}
-	ascent = ngui_text_ascent(ui, px, mono);
+	ascent = ngui_text_ascent_face(ui, face, px, mono);
 	ngui_clip_bounds(ui, &cx, &cy, &cw, &ch);
 	ngui_clip_bounds(ui, &cx, &cy, &cw, &ch);
 	for (i = 0; i < (int)n && s[i]; i++) {
 	for (i = 0; i < (int)n && s[i]; i++) {
 		const struct ufont_glyph *g =
 		const struct ufont_glyph *g =
@@ -808,6 +828,22 @@ void ngui_text_px(struct ngui *ui, int x, int y, const char *s,
 	}
 	}
 }
 }
 
 
+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)
+{
+	ngui_text_px_common(ui, 0, x, y, s, n, color, px, bold, italic, mono);
+}
+
+void ngui_text_px_face(struct ngui *ui, struct ufont_face *face, int x,
+		       int y, const char *s, unsigned int n,
+		       unsigned short color, int px, int bold, int italic,
+		       int mono)
+{
+	ngui_text_px_common(ui, face, x, y, s, n, color, px, bold, italic,
+			    mono);
+}
+
 void ngui_text_n(struct ngui *ui, int x, int y, const char *s, unsigned int n,
 void ngui_text_n(struct ngui *ui, int x, int y, const char *s, unsigned int n,
 		 unsigned short color)
 		 unsigned short color)
 {
 {

+ 14 - 0
ngui.h

@@ -205,6 +205,20 @@ unsigned int ngui_text_width_px(struct ngui *ui, const char *s, unsigned int n,
 				int px, int bold, int italic, int mono);
 				int px, int bold, int italic, int mono);
 int ngui_text_ascent(struct ngui *ui, int px, 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);
 int ngui_text_line_height(struct ngui *ui, int px, int mono);
+
+/* Face-aware variants: a non-NULL `face` (an @font-face loaded by the
+ * caller) overrides the built-in regular/bold/italic/mono selection. */
+unsigned int ngui_text_width_face(struct ngui *ui, struct ufont_face *face,
+				  const char *s, unsigned int n, int px,
+				  int bold, int italic, int mono);
+int ngui_text_ascent_face(struct ngui *ui, struct ufont_face *face, int px,
+			  int mono);
+int ngui_text_line_height_face(struct ngui *ui, struct ufont_face *face,
+			       int px, int mono);
+void ngui_text_px_face(struct ngui *ui, struct ufont_face *face, int x,
+		       int y, const char *s, unsigned int n,
+		       unsigned short color, int px, int bold, int italic,
+		       int mono);
 void ngui_icon(struct ngui *ui, struct ngui_rect r, enum ngui_icon icon,
 void ngui_icon(struct ngui *ui, struct ngui_rect r, enum ngui_icon icon,
 	       unsigned short color);
 	       unsigned short color);
 
 

+ 66 - 0
testdata/browser/compat/037-font-face.html

@@ -0,0 +1,66 @@
+<!doctype html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>037 font-face</title>
+<style>
+@font-face {
+  font-family: "Ladder Mono";
+  src: url("/ramfs/fonts/mono.ttf") format("truetype");
+}
+@font-face {
+  font-family: "Missing Face";
+  src: url("/ramfs/fonts/does-not-exist.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: 220px; background: #f4f4f4; border: 1px solid #999999; padding: 6px; }
+.custom { font-family: "Ladder Mono"; font-size: 15px; }
+.mono { font-family: monospace; font-size: 15px; }
+.missing { font-family: "Missing Face", sans-serif; font-size: 15px; }
+.plain { font-family: sans-serif; font-size: 15px; }
+#result { clear: both; margin-top: 14px; padding: 8px; background: #eeeeee; color: #000000; font-family: monospace; font-weight: bold; }
+</style>
+</head>
+<body>
+<h1>037 &middot; @font-face</h1>
+<p>The custom face must load from the pack and measure like the built-in mono face; a missing URL must fall back to sans.</p>
+<div class="pane">
+  <div class="label">A &middot; @font-face</div>
+  <div class="box"><span class="custom">The quick brown fox jumps over the lazy dog and the five boxing wizards jump quickly.</span></div>
+  <div class="box" style="margin-top:8px"><span class="missing">Missing face falls back to the inherited sans text.</span></div>
+</div>
+<div class="pane">
+  <div class="label">B &middot; reference</div>
+  <div class="box"><span class="mono">The quick brown fox jumps over the lazy dog and the five boxing wizards jump quickly.</span></div>
+  <div class="box" style="margin-top:8px"><span class="plain">Missing face falls back to the inherited sans text.</span></div>
+</div>
+<p id="metrics" style="clear:both;margin-top:12px">checking...</p>
+<span id="custom-run" class="custom" style="display:inline-block">AVAVAVAVAV</span>
+<span id="mono-run" class="mono" style="display:inline-block">AVAVAVAVAV</span>
+<span id="missing-run" class="missing" style="display:inline-block">AVAVAVAVAV</span>
+<span id="plain-run" class="plain" style="display:inline-block">AVAVAVAVAV</span>
+<div id="result">checking...</div>
+<script>
+setTimeout(function () {
+  var ca = document.getElementById('custom-run').getBoundingClientRect();
+  var cb = document.getElementById('mono-run').getBoundingClientRect();
+  var cm = document.getElementById('missing-run').getBoundingClientRect();
+  var cp = document.getElementById('plain-run').getBoundingClientRect();
+  var ok = Math.abs(ca.width - cb.width) <= 1 &&
+           Math.abs(cm.width - cp.width) <= 1 &&
+           ca.width > 0 && cb.width > 0;
+  var msg = 'custom=' + Math.round(ca.width) + ' mono=' + Math.round(cb.width) +
+            ' missing=' + Math.round(cm.width) + ' sans=' + Math.round(cp.width);
+  var out = document.getElementById('result');
+  out.textContent = ok ? 'PASS: @font-face metrics (' + msg + ')' :
+                         'FAIL: @font-face metrics (' + msg + ')';
+  out.style.background = ok ? '#ccffcc' : '#ffcccc';
+}, 600);
+</script>
+</body>
+</html>

+ 4 - 5
testdata/browser/compat/README

@@ -17,20 +17,19 @@ Serve this directory from the host and open it on the board:
   browser http://<host>:8000/            # board
   browser http://<host>:8000/            # board
   browser http://10.0.2.2:8000/         # QEMU with -netdev user
   browser http://10.0.2.2:8000/         # QEMU with -netdev user
 
 
-Status: 010-036 and 030a pass.  036a needs the POST echo server:
+Status: 010-037 and 030a pass.  036a needs the POST echo server:
 
 
   python3 testdata/browser/compat/post_server.py
   python3 testdata/browser/compat/post_server.py
   browser /floppy1/036a.htm      # action is http://10.0.2.2:8765/echo
   browser /floppy1/036a.htm      # action is http://10.0.2.2:8765/echo
 
 
-Still missing from the ladder: @font-face, background repeat/position/size,
-the rest of transform, sticky bottom/container clamping, and calc() beyond
-widths.
+Still missing from the ladder: background repeat/position/size, the rest of
+transform, sticky bottom/container clamping, and calc() beyond widths.
 
 
 Rules for new pages:
 Rules for new pages:
   - one behaviour per page;
   - one behaviour per page;
   - no network assets outside this directory (036a is the one explicit
   - no network assets outside this directory (036a is the one explicit
     POST test and documents its server);
     POST test and documents its server);
-  - pages up to 034 are static; 035/036 use JavaScript and assert their own
+  - pages up to 034 are static; 035-037 use JavaScript and assert their own
     PASS/FAIL line;
     PASS/FAIL line;
   - explicit white background and dark text;
   - explicit white background and dark text;
   - page chrome uses only primitives introduced earlier in the ladder;
   - page chrome uses only primitives introduced earlier in the ladder;

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

@@ -59,6 +59,7 @@ a { color: #0645ad; }
 <tr><td>035</td><td><a href="035-form-js.html">form JS state</a></td><td>live value / checked / selectedIndex</td><td class="pass">PASS</td></tr>
 <tr><td>035</td><td><a href="035-form-js.html">form JS state</a></td><td>live value / checked / selectedIndex</td><td class="pass">PASS</td></tr>
 <tr><td>036</td><td><a href="036-form-events.html">form events</a></td><td>addEventListener, bubbling, preventDefault, form.elements</td><td class="pass">PASS</td></tr>
 <tr><td>036</td><td><a href="036-form-events.html">form events</a></td><td>addEventListener, bubbling, preventDefault, form.elements</td><td class="pass">PASS</td></tr>
 <tr><td>036a</td><td><a href="036a-post.html">POST form</a></td><td>POST submission to <code>/echo</code> (needs <code>post_server.py</code>)</td><td class="pass">PASS</td></tr>
 <tr><td>036a</td><td><a href="036a-post.html">POST form</a></td><td>POST submission to <code>/echo</code> (needs <code>post_server.py</code>)</td><td class="pass">PASS</td></tr>
+<tr><td>037</td><td><a href="037-font-face.html">@font-face</a></td><td>custom TTF family and missing-URL fallback</td><td class="pass">PASS</td></tr>
 </table>
 </table>
 </body>
 </body>
 </html>
 </html>

+ 1 - 1
ufont.h

@@ -10,7 +10,7 @@
 
 
 #include <stddef.h>
 #include <stddef.h>
 
 
-#define UFONT_ARENA_BYTES   (256u * 1024u)
+#define UFONT_ARENA_BYTES   (512u * 1024u)
 #define UFONT_MAX_FILE      (256u * 1024u)
 #define UFONT_MAX_FILE      (256u * 1024u)
 #define UFONT_CACHE_SLOTS   512
 #define UFONT_CACHE_SLOTS   512
 
 

+ 1 - 1
ufont_internal.h

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

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