Browse Source

Add browser getComputedStyle values

Johannes Zellner 1 week ago
parent
commit
0436dba5ea

+ 4 - 3
AGENTS.md

@@ -831,7 +831,7 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   `@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–041 and 030a pass (036a needs the
+  (`make compat-serve`); pages 010–042 and 030a pass (036a needs the
   POST echo server).  Inline
   `<svg>` subtrees and closed `<details>` are skipped (not renderable), and
   `<video>` gets a placeholder box.  The default page canvas follows
@@ -1542,8 +1542,9 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     Also missing: `type="module"`,
     `defer`/`async`, `MutationObserver`/`IntersectionObserver`,
     `XMLHttpRequest`/`fetch`, `DOMParser`, canvas/2D contexts and
-    pseudo-class/element selectors.  `getComputedStyle` is a
-    stub (it returns empty values), `outerHTML` returns only the string last
+    pseudo-class/element selectors.  `getComputedStyle` returns the engine's
+    known properties (display, box metrics, colours, fonts, borders,
+    background and transform state), `outerHTML` returns only the string last
     assigned to `innerHTML`, and `style`/`dataset` cover inline state rather
     than computed style.  Libraries that need those APIs (jQuery plugins
     beyond Bootstrap's tooltip, Angular apps that use `$http`) still log

+ 294 - 0
browser.c

@@ -11,6 +11,7 @@
  */
 
 #include <stdlib.h>
+#include <stdio.h>
 #include <string.h>
 #include <math.h>
 #include <ucmd_heap.h>
@@ -233,6 +234,7 @@ static unsigned int s_len(const char *s);
 static int s_eq(const char *a, const char *b);
 static void form_key(int k);
 static void form_click(unsigned int node);
+static void style_for_node(unsigned int node, struct br_style *out);
 
 static int form_disabled(unsigned int node)
 {
@@ -774,6 +776,297 @@ static int js_host_form_reset(unsigned int form)
 	return 1;
 }
 
+static void css_computed_name(const char *p, char *out, int cap)
+{
+	int n = 0;
+
+	for (; p && *p && n + 2 < cap; p++) {
+		char c = *p;
+
+		if (c >= 'A' && c <= 'Z') {
+			out[n++] = '-';
+			c = (char)(c - 'A' + 'a');
+		} else if (c == '_') {
+			c = '-';
+		} else if (c >= 'a' && c <= 'z') {
+			/* keep */
+		}
+		out[n++] = c;
+	}
+	out[n] = '\0';
+	if (!strcmp(out, "css-float"))
+		strcpy(out, "float");
+}
+
+static void css_rgb(unsigned short c, char *buf, int cap)
+{
+	int r = ((c >> 11) & 31) * 255 / 31;
+	int g = ((c >> 5) & 63) * 255 / 63;
+	int b = (c & 31) * 255 / 31;
+
+	snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
+}
+
+static void css_mp_value(char *buf, int cap, int raw, int unit, int px)
+{
+	if (unit == 4) {
+		snprintf(buf, cap, "auto");
+	} else if (unit == 0) {
+		snprintf(buf, cap, "%dpx", raw);
+	} else if (unit == 1) {
+		snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
+	} else if (unit == 2) {
+		snprintf(buf, cap, "%d.%02dem", raw / 100, raw % 100);
+	} else if (unit == 3) {
+		snprintf(buf, cap, "%d.%02drem", raw / 100, raw % 100);
+	} else {
+		snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
+			 raw / 100, raw % 100, px);
+	}
+}
+
+static int js_host_computed(unsigned int node, const char *property,
+			    char *buf, int cap)
+{
+	struct br_style st;
+	char name[40];
+
+	if (!buf || cap <= 0 || node >= doc.nnode || node == 0)
+		return 0;
+	buf[0] = '\0';
+	css_computed_name(property, name, sizeof(name));
+	style_for_node(node, &st);
+
+	if (!strcmp(name, "display")) {
+		const char *v = "inline";
+
+		if (st.display == BR_DISPLAY_BLOCK)
+			v = "block";
+		else if (st.display == BR_DISPLAY_NONE)
+			v = "none";
+		else if (st.display == BR_DISPLAY_FLEX)
+			v = "flex";
+		else if (st.display == BR_DISPLAY_GRID)
+			v = "grid";
+		else if (st.display == BR_DISPLAY_INLINE_BLOCK)
+			v = "inline-block";
+		snprintf(buf, cap, "%s", v);
+	} else if (!strcmp(name, "position")) {
+		static const char *pos[] = {
+			"static", "absolute", "fixed", "relative", "sticky"
+		};
+		snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
+	} else if (!strcmp(name, "width") || !strcmp(name, "height")) {
+		int is_w = name[0] == 'w';
+		int kind = is_w ? st.width_kind : st.height_kind;
+		int val = is_w ? st.width : st.height;
+
+		if (kind == 3) {
+			if (is_w)
+				snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
+					 st.width_calc_pct / 100,
+					 st.width_calc_pct % 100,
+					 st.width_calc_px);
+			else
+				snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
+					 st.height_calc_pct / 100,
+					 st.height_calc_pct % 100,
+					 st.height_calc_px);
+		} else if (kind == 1) {
+			snprintf(buf, cap, "%dpx", val);
+		} else if (kind == 2) {
+			snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
+		} else {
+			snprintf(buf, cap, "auto");
+		}
+	} else if (!strcmp(name, "color") ||
+		   !strcmp(name, "background-color")) {
+		if (!strcmp(name, "background-color") && !st.has_bg)
+			snprintf(buf, cap, "rgba(0, 0, 0, 0)");
+		else
+			css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
+	} else if (!strcmp(name, "font-size")) {
+		snprintf(buf, cap, "%dpx", st.font_px);
+	} else if (!strcmp(name, "font-weight")) {
+		snprintf(buf, cap, "%s", st.bold ? "700" : "400");
+	} else if (!strcmp(name, "font-style")) {
+		snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
+	} else if (!strcmp(name, "font-family")) {
+		if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
+		    br_font_face_family(st.font_face)[0])
+			snprintf(buf, cap, "%s",
+				 br_font_face_family(st.font_face));
+		else
+			snprintf(buf, cap, "%s",
+				 st.mono ? "monospace" : "sans-serif");
+	} else if (!strcmp(name, "text-align")) {
+		static const char *al[] = { "left", "center", "right", "justify" };
+		snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
+	} else if (!strcmp(name, "float")) {
+		snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
+				 st.float_left == 2 ? "right" : "none");
+	} else if (!strcmp(name, "clear")) {
+		static const char *cl[] = { "none", "left", "right", "both" };
+		snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
+	} else if (!strcmp(name, "opacity")) {
+		snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
+	} else if (!strcmp(name, "visibility")) {
+		snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
+	} else if (!strcmp(name, "overflow")) {
+		snprintf(buf, cap, "%s",
+			 st.overflow_hidden ? "hidden" : "visible");
+	} else if (!strcmp(name, "white-space")) {
+		snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
+	} else if (!strcmp(name, "text-transform")) {
+		snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
+	} else if (!strcmp(name, "box-sizing")) {
+		snprintf(buf, cap, "%s",
+			 st.box_sizing ? "border-box" : "content-box");
+	} else if (!strcmp(name, "line-height")) {
+		if (st.line_h_px)
+			snprintf(buf, cap, "%dpx", st.line_h_px);
+		else if (st.line_h_pct)
+			snprintf(buf, cap, "%d%%", st.line_h_pct);
+		else
+			snprintf(buf, cap, "normal");
+	} else if (!strcmp(name, "z-index")) {
+		if (st.z_set)
+			snprintf(buf, cap, "%d", st.z_index);
+		else
+			snprintf(buf, cap, "auto");
+	} else if (!strcmp(name, "top") || !strcmp(name, "left") ||
+		   !strcmp(name, "right") || !strcmp(name, "bottom")) {
+		int set = name[0] == 't' ? st.top_set :
+			  name[0] == 'l' ? st.left_set :
+			  name[0] == 'r' ? st.right_set : st.bottom_set;
+		int v = name[0] == 't' ? st.top :
+			name[0] == 'l' ? st.left :
+			name[0] == 'r' ? st.right : st.bottom;
+
+		if (set)
+			snprintf(buf, cap, "%dpx", v);
+		else
+			snprintf(buf, cap, "auto");
+	} else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
+		   !strcmp(name, "margin-bottom") ||
+		   !strcmp(name, "margin-left") ||
+		   !strcmp(name, "padding-top") ||
+		   !strcmp(name, "padding-right") ||
+		   !strcmp(name, "padding-bottom") ||
+		   !strcmp(name, "padding-left")) {
+		int is_pad = name[0] == 'p';
+		int side = name[strlen(name) - 1] == 'p' ? 0 :
+			   name[strlen(name) - 1] == 't' ? 1 :
+			   name[strlen(name) - 1] == 'm' ? 2 : 3;
+
+		/* last letter: top p, right t, bottom m, left t (ambiguity). */
+		if (!strcmp(name, "margin-right") ||
+		    !strcmp(name, "padding-right"))
+			side = 1;
+		else if (!strcmp(name, "margin-bottom") ||
+			 !strcmp(name, "padding-bottom"))
+			side = 2;
+		else if (!strcmp(name, "margin-left") ||
+			 !strcmp(name, "padding-left"))
+			side = 3;
+		else
+			side = 0;
+		side += is_pad ? 4 : 0;
+		css_mp_value(buf, cap,
+			     side == 0 ? st.mt : side == 1 ? st.mr :
+			     side == 2 ? st.mb : side == 3 ? st.ml :
+			     side == 4 ? st.pt : side == 5 ? st.pr :
+			     side == 6 ? st.pb : st.pl,
+			     st.mp_unit[side], st.mp_calc_px[side]);
+	} else if (!strcmp(name, "border-top-width") ||
+		   !strcmp(name, "border-right-width") ||
+		   !strcmp(name, "border-bottom-width") ||
+		   !strcmp(name, "border-left-width")) {
+		int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
+			   name[7] == 'b' ? 2 : 3;
+		snprintf(buf, cap, "%dpx", st.border_w[side]);
+	} else if (!strcmp(name, "border-top-color") ||
+		   !strcmp(name, "border-right-color") ||
+		   !strcmp(name, "border-bottom-color") ||
+		   !strcmp(name, "border-left-color")) {
+		int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
+			   name[7] == 'b' ? 2 : 3;
+		if (st.border_w[side])
+			css_rgb(st.border_c[side], buf, cap);
+		else
+			snprintf(buf, cap, "rgba(0, 0, 0, 0)");
+	} else if (!strcmp(name, "background-image")) {
+		if (st.bg_image)
+			snprintf(buf, cap, "url(\"%s\")",
+				 br_bg_image_url(st.bg_image - 1));
+		else
+			snprintf(buf, cap, "none");
+	} else if (!strcmp(name, "background-repeat")) {
+		static const char *rp[] = {
+			"repeat", "no-repeat", "repeat-x", "repeat-y"
+		};
+		snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
+					 st.bg_repeat : 0]);
+	} else if (!strcmp(name, "background-position")) {
+		if (st.bg_pos_x_kind == 1)
+			snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
+				 st.bg_pos_y);
+		else
+			snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
+				 st.bg_pos_y);
+	} else if (!strcmp(name, "background-size")) {
+		if (st.bg_size_kind == 3)
+			snprintf(buf, cap, "cover");
+		else if (st.bg_size_kind == 4)
+			snprintf(buf, cap, "contain");
+		else if (st.bg_size_kind == 1)
+			snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
+				 st.bg_size_h);
+		else if (st.bg_size_kind == 2)
+			snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
+				 st.bg_size_h);
+		else
+			snprintf(buf, cap, "auto");
+	} else if (!strcmp(name, "transform")) {
+		char tmp[128];
+		unsigned int n = 0;
+
+		if (!st.transform_set) {
+			snprintf(buf, cap, "none");
+		} else {
+			tmp[0] = '\0';
+			if (st.tx || st.ty) {
+				snprintf(tmp + n, sizeof(tmp) - n,
+					 "translate(%dpx, %dpx)", st.tx, st.ty);
+				n = (unsigned int)strlen(tmp);
+			}
+			if (st.transform_scale) {
+				snprintf(tmp + n, sizeof(tmp) - n,
+					 "%sscale(%d.%02d, %d.%02d)",
+					 n ? " " : "", st.scale_x / 100,
+					 st.scale_x % 100, st.scale_y / 100,
+					 st.scale_y % 100);
+				n = (unsigned int)strlen(tmp);
+				if (st.rotate_x100) {
+					snprintf(tmp + n, sizeof(tmp) - n,
+						 " rotate(%d.%02ddeg)",
+						 st.rotate_x100 / 100,
+						 st.rotate_x100 % 100);
+				}
+			} else if (st.rotate_x100) {
+				snprintf(tmp + n, sizeof(tmp) - n,
+					 "%srotate(%d.%02ddeg)",
+					 n ? " " : "", st.rotate_x100 / 100,
+					 st.rotate_x100 % 100);
+			}
+			snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
+		}
+	} else {
+		return 0;
+	}
+	return buf[0] != '\0';
+}
+
 static int js_host_click(unsigned int node)
 {
 	char url[BR_URL_MAX];
@@ -840,6 +1133,7 @@ static void run_page_scripts(void)
 	host.form_submit = js_host_form_submit;
 	host.form_reset = js_host_form_reset;
 	host.click = js_host_click;
+	host.computed = js_host_computed;
 	host.page_url = page_url;
 	host.width = ui.w;
 	host.height = ui.h;

+ 1 - 1
browser_html.h

@@ -18,7 +18,7 @@
 #define BR_MAX_VARS      512
 #define BR_TAG_MAX       128
 #define BR_RULE_HASH     256
-#define BR_DECLS         24
+#define BR_DECLS         48
 #define BR_TITLE_MAX     96
 #define BR_MAX_SCRIPTS   32
 

File diff suppressed because it is too large
+ 0 - 0
docs/userland.html


+ 60 - 5
js_browser.c

@@ -2554,17 +2554,72 @@ static void win_performance_now(js_State *state)
 	js_pushnumber(state, (double)u_ticks_ms());
 }
 
-static void win_getproperty(js_State *state)
+struct computed_prop {
+	const char *js;
+	const char *css;
+};
+
+static const struct computed_prop computed_props[] = {
+	{ "display", "display" }, { "position", "position" },
+	{ "width", "width" }, { "height", "height" },
+	{ "color", "color" }, { "backgroundColor", "background-color" },
+	{ "fontSize", "font-size" }, { "fontWeight", "font-weight" },
+	{ "fontStyle", "font-style" }, { "fontFamily", "font-family" },
+	{ "textAlign", "text-align" }, { "float", "float" },
+	{ "cssFloat", "float" }, { "clear", "clear" },
+	{ "opacity", "opacity" }, { "visibility", "visibility" },
+	{ "overflow", "overflow" }, { "whiteSpace", "white-space" },
+	{ "textTransform", "text-transform" }, { "boxSizing", "box-sizing" },
+	{ "lineHeight", "line-height" }, { "zIndex", "z-index" },
+	{ "top", "top" }, { "left", "left" }, { "right", "right" },
+	{ "bottom", "bottom" },
+	{ "marginTop", "margin-top" }, { "marginRight", "margin-right" },
+	{ "marginBottom", "margin-bottom" }, { "marginLeft", "margin-left" },
+	{ "paddingTop", "padding-top" }, { "paddingRight", "padding-right" },
+	{ "paddingBottom", "padding-bottom" },
+	{ "paddingLeft", "padding-left" },
+	{ "borderTopWidth", "border-top-width" },
+	{ "borderRightWidth", "border-right-width" },
+	{ "borderBottomWidth", "border-bottom-width" },
+	{ "borderLeftWidth", "border-left-width" },
+	{ "backgroundImage", "background-image" },
+	{ "backgroundRepeat", "background-repeat" },
+	{ "backgroundPosition", "background-position" },
+	{ "backgroundSize", "background-size" },
+	{ "transform", "transform" },
+	{ 0, 0 }
+};
+
+static void computed_get(js_State *state)
 {
-	(void)state;
-	js_pushstring(state, "");
+	unsigned int node = node_of(js_currentfunctiondata(state));
+	const char *prop = js_tostring(state, 1);
+	char buf[192];
+
+	if (host.computed && host.computed(node, prop, buf, sizeof(buf)))
+		js_pushstring(state, buf);
+	else
+		js_pushstring(state, "");
 }
 
 static void win_getcomputedstyle(js_State *state)
 {
-	(void)state;
+	unsigned int node = 0;
+	char buf[192];
+	int i;
+
+	if (js_isuserdata(state, 1, "node"))
+		node = node_of(js_touserdata(state, 1, "node"));
 	js_newobject(state);
-	def_func(state, "getPropertyValue", win_getproperty, 1);
+	def_func_data(state, "getPropertyValue", computed_get, 1, node + 1);
+	for (i = 0; computed_props[i].js; i++) {
+		if (!host.computed ||
+		    !host.computed(node, computed_props[i].css, buf,
+				   sizeof(buf)))
+			continue;
+		js_pushstring(state, buf);
+		js_setproperty(state, -2, computed_props[i].js);
+	}
 	js_pushstring(state, "");
 	js_setproperty(state, -2, "cssText");
 }

+ 3 - 0
js_browser.h

@@ -29,6 +29,9 @@ struct js_browser_host {
 	int (*form_submit)(unsigned int form);  /* JS submit(), no event */
 	int (*form_reset)(unsigned int form);   /* JS reset(), fires reset */
 	int (*click)(unsigned int node);        /* element.click() */
+	/* Computed style for getComputedStyle(); return 1 when known. */
+	int (*computed)(unsigned int node, const char *property, char *buf,
+			int cap);
 	const char *page_url;   /* location.href for every script on the page */
 	unsigned int width;     /* viewport size for window.inner* */
 	unsigned int height;

+ 69 - 0
testdata/browser/compat/042-computed-style.html

@@ -0,0 +1,69 @@
+<!doctype html>
+<html>
+<head>
+<meta charset="utf-8">
+<title>042 computed style</title>
+<style>
+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; }
+#t { display: block; position: relative; left: 12px; top: 7px;
+     width: 150px; height: 40px; margin-left: 20px; padding: 6px;
+     background-color: #ff0000; color: #0000ff; font-size: 18px;
+     font-weight: bold; font-style: italic; text-align: center;
+     z-index: 5; white-space: nowrap;
+     transform: translate(3px, 4px) scale(1.5);
+     border-top: 2px solid #00ff00; }
+#n { display: none; }
+#result { margin-top: 12px; padding: 8px; background: #eeeeee; color: #000000;
+          font-family: monospace; font-weight: bold; }
+</style>
+</head>
+<body>
+<h1>042 &middot; getComputedStyle</h1>
+<p>The script checks the computed values of the styled box and a hidden element.</p>
+<div id="t">styled box</div>
+<div id="n">hidden</div>
+<div id="result">checking...</div>
+<script>
+setTimeout(function () {
+  var cs = getComputedStyle(document.getElementById('t'));
+  var hs = getComputedStyle(document.getElementById('n'));
+  var checks = [
+    ['display', 'block'], ['position', 'relative'], ['width', '150px'],
+    ['height', '40px'], ['margin-left', '20px'], ['padding-left', '6px'],
+    ['color', 'rgb(0, 0, 255)'], ['background-color', 'rgb(255, 0, 0)'],
+    ['font-size', '18px'], ['font-weight', '700'], ['font-style', 'italic'],
+    ['text-align', 'center'], ['z-index', '5'], ['left', '12px'],
+    ['top', '7px'], ['border-top-width', '2px'],
+    ['border-top-color', 'rgb(0, 255, 0)']
+  ];
+  var ok = true, details = [];
+  for (var i = 0; i < checks.length; i++) {
+    var got = cs.getPropertyValue(checks[i][0]);
+    if (got !== checks[i][1]) {
+      ok = false;
+      details.push(checks[i][0] + '="' + got + '" want "' + checks[i][1] + '"');
+    }
+  }
+  if (cs.marginLeft !== '20px' || cs.backgroundColor !== 'rgb(255, 0, 0)') {
+    ok = false;
+    details.push('direct properties');
+  }
+  if (hs.getPropertyValue('display') !== 'none') {
+    ok = false;
+    details.push('hidden display=' + hs.getPropertyValue('display'));
+  }
+  if (cs.transform.indexOf('scale(1.5') < 0) {
+    ok = false;
+    details.push('transform=' + cs.transform);
+  }
+  var out = document.getElementById('result');
+  out.textContent = ok ? 'PASS: computed style properties' :
+    ('FAIL: ' + details.join('; '));
+  out.style.background = ok ? '#ccffcc' : '#ffcccc';
+}, 600);
+</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-041 and 030a pass.  036a needs the POST echo server:
+Status: 010-042 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

@@ -64,6 +64,7 @@ a { color: #0645ad; }
 <tr><td>039</td><td><a href="039-transform-scale-rotate.html">transform</a></td><td>scale, rotate, transform-origin on images and boxes</td><td class="pass">PASS</td></tr>
 <tr><td>040</td><td><a href="040-sticky-bottom.html">sticky edges</a></td><td>sticky top/bottom clamped to the containing block</td><td class="pass">PASS</td></tr>
 <tr><td>041</td><td><a href="041-calc-boxes.html">calc boxes</a></td><td>calc() in margins/padding, heights and min/max</td><td class="pass">PASS</td></tr>
+<tr><td>042</td><td><a href="042-computed-style.html">computed style</a></td><td>getComputedStyle values and the display:none case</td><td class="pass">PASS</td></tr>
 </table>
 </body>
 </html>

Some files were not shown because too many files changed in this diff