Pārlūkot izejas kodu

Add responsive CSS columns and large compressed pages

Johannes Zellner 2 nedēļas atpakaļ
vecāks
revīzija
2b0c3b63bd
4 mainītis faili ar 633 papildinājumiem un 62 dzēšanām
  1. 33 21
      AGENTS.md
  2. 401 37
      browser.c
  3. 193 0
      browser_html.c
  4. 6 4
      browser_html.h

+ 33 - 21
AGENTS.md

@@ -442,15 +442,20 @@ run area), so adding code no longer moves any address.
   inline `<style>` last), tag/class/id and descendant/child selectors,
   colours/`rgba()`, backgrounds, font size (`px`/`%`/`em`/`rem`), numeric
   weights, `!important`, line-height, alignment, margins, padding, borders,
-  `list-style: none`, `text-transform: uppercase`, `display`, and percentage
-  `width`/`height`/`max-width`; selectors with `:`/`[`/`+`/`~` are skipped
-  individually, and `@media`/`@font-face`/`@import` blocks are ignored.
-  `browser.c` owns the layout/render, URL bar, history, status bar and inline
-  `<img>` decoding.  Page and image buffers come from `SYS_MEM_ALLOC`; the DOM
-  uses fixed static arenas.  Images are decoded once into a shared 24 MB
-  arena and copied to a display bitmap at most 1000 px wide (up to 16 images,
-  512 KB files / 8 MP decodes), so 4K screenshots fit the 32 MB heap.  There
-  is no JavaScript, forms, floats, flex/grid or standalone image viewer mode.
+  `list-style: none`, `text-transform: uppercase`, `display`, percentage
+  `width`/`height`/`max-width`, and basic `float: left/right` columns.
+  `@media (min-width/max-width)` blocks are evaluated against a fixed 1000 px
+  desktop viewport; `@font-face`/`@import`/`@keyframes` are skipped.  Inline
+  `<svg>` subtrees and closed `<details>` are skipped (not renderable), and
+  `<video>` gets a placeholder box.  `browser.c` owns a 960x640 window, the
+  layout/render, URL bar, history, status bar and inline `<img>` decoding.
+  Page and image buffers come from `SYS_MEM_ALLOC`; the DOM uses fixed static
+  arenas (2560 nodes, 128 KB attributes, 1792 rules), and page bodies are
+  capped at 2 MB with CSS sheets up to 832 KB (six sheets).  Images are
+  decoded once into a shared 24 MB arena and copied to a display bitmap at
+  most 1000 px wide (up to 16 images, 512 KB files / 8 MP decodes), so 4K
+  screenshots fit the 32 MB heap.  There is no JavaScript, forms, flex/grid,
+  CSS variables, absolute/fixed positioning or standalone image viewer mode.
   `SYS_SPAWN` loads FAT ELFs through `kmalloc` now (the old 16 KB
   `fat_load_buf` is gone) and wraps the load in `sys_fs_enter/exit`, since the
   floppy needs IRQ 6.
@@ -967,18 +972,25 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     within roughly 30 KB of the `0x7F000` wall.  Adding more kernel buffers
     or commands should be paired with reclaiming space elsewhere.
 
-23. Browser limits: no JavaScript, forms, floats, flex/grid, tables with
-    column widths, absolute/fixed positioning, inline-block sizing or
-    standalone image documents.  `@media`/`@font-face`/`@import` are ignored,
-    so only the base CSS applies on a narrow window, and pseudo-classes are
-    never matched (`:hover` styles only via their non-pseudo siblings).
-    `font-size` maps to 1x/2x only, `em`/`rem` both use a 16 px root, and
-    block `width`/`max-width` are not used for centring.  Images are decoded
-    eagerly into a 24 MB shared arena and downscaled to a 1000 px display
-    bitmap (16 images, 512 KB files / 8 MP decodes); a large image-heavy page
-    can still exhaust the 32 MB heap, and the first `<img>` after a big
-    screenshot can transiently need a new heap growth.  `img_draw` rescales
-    the cached bitmap on every repaint.  TLS is phase A (no certificate
+23. Browser limits: no JavaScript, forms, flex/grid, CSS custom properties
+    (`var(--...)`), tables with column widths, absolute/fixed positioning,
+    inline-block sizing or standalone image documents.  Float support is the
+    basic Bootstrap-grid case: consecutive floated blocks are laid side by
+    side with percentage/px widths, `float:right` is treated like left, there
+    is no `clear`, percentage margins are approximated as pixels, and a float
+    without a width uses a text-width estimate.  `@media` blocks are evaluated
+    against a fixed 1000 px desktop viewport (so narrow/adaptive pages get the
+    desktop rules, not their mobile layout), and pseudo-classes are never
+    matched.  `font-size` maps to 1x/2x only, `em`/`rem` both use a 16 px
+    root, and block `width`/`max-width` are not used for centring.  Images
+    are decoded eagerly into a 24 MB shared arena and downscaled to a 1000 px
+    display bitmap (16 images, 512 KB files / 8 MP decodes); a large
+    image-heavy page can still exhaust the 32 MB heap, and the first `<img>`
+    after a big screenshot can transiently need a new heap growth.  `img_draw`
+    rescales the cached bitmap on every repaint.  Video/audio elements are
+    placeholders, and pages that depend on `display:grid`/flex or CSS
+    variables (tagesschau's player and ad slots, for example) can show empty
+    bordered boxes or miss colours.  TLS is phase A (no certificate
     verification); `https` is shown as unverified.  The disk app is loaded
     from FAT at spawn time, so a cold floppy start takes a few seconds; the
     8 KB user stack means the layout state is deliberately static.

+ 401 - 37
browser.c

@@ -1,10 +1,10 @@
 /* browser: a small HTML/CSS browser built on ngui, the image library and the
  * shared uhttp client.
  *
- * No JavaScript, no forms, no external CSS; images are decoded with img.c and
- * drawn inline.  Large buffers (page body, compressed body, image files and
- * decode arenas) live in the per-process SYS_MEM_ALLOC heap; the DOM itself
- * uses the fixed arenas in browser_html.c.
+ * No JavaScript and no forms; external CSS is loaded over uhttp, and images
+ * are decoded with img.c and drawn inline.  Large buffers (page body and the
+ * image decode arena) live in the per-process SYS_MEM_ALLOC heap; the DOM and
+ * the image/CSS I/O scratch use fixed static arenas.
  */
 
 #include "ucmd_lib.h"
@@ -14,20 +14,23 @@
 #include "img.h"
 #include "inflate.h"
 
-#define BR_W            720
-#define BR_H            520
+#define BR_W            960
+#define BR_H            640
+/* CSS media queries are evaluated as a desktop browser. */
+#define BR_VIEWPORT_W   1000
 #define BR_TOOLBAR_H    30
 #define BR_STATUS_H     18
 
 #define BR_HEAP_INIT    (6u * 1024u * 1024u)
 #define BR_HEAP_MAX     (32u * 1024u * 1024u)
-#define BR_PAGE_MAX     (512u * 1024u)
+#define BR_PAGE_MAX     (2u * 1024u * 1024u)
 #define BR_IMG_FILE_MAX (512u * 1024u)
 #define BR_IMG_PIX_MAX  (8u * 1024u * 1024u)
 #define BR_MAX_IMAGES   16
 #define BR_IMG_ARENA    (24u * 1024u * 1024u)
 #define BR_IMG_LAYOUT_W 1000
-#define BR_CSS_MAX      (128u * 1024u)
+#define BR_CSS_MAX      (832u * 1024u)
+#define BR_CSS_COMP_MAX (192u * 1024u)
 #define BR_MAX_SHEETS   6
 #define BR_HISTORY      16
 #define BR_URL_MAX      320
@@ -75,15 +78,23 @@ static unsigned char *heap;
 static unsigned int heap_size = 0;
 static unsigned int heap_used = 0;
 
-/* One reusable file buffer and one shared decode arena: decoded pixels are
+/* One reusable I/O buffer and one shared decode arena: decoded pixels are
  * scaled down to a display bitmap, then the arena is reused for the next
- * image.  This keeps 4K screenshots inside the 32 MB heap. */
-static unsigned char image_file_buf[BR_IMG_FILE_MAX];
-static unsigned char image_comp_buf[BR_IMG_FILE_MAX];
+ * image.  This keeps 4K screenshots inside the 32 MB heap.  The two halves
+ * double as the gzip input scratch for page/CSS fetches, where the heap has
+ * no room for another multi-megabyte body. */
+static unsigned char image_io_buf[2u * BR_IMG_FILE_MAX];
+#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)
 static struct inflate image_inflate_ws;
 static unsigned char *image_arena;
 static unsigned int image_arena_size;
 
+#if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
+#error "CSS scratch must fit in image_io_buf"
+#endif
+
 static char page_url[BR_URL_MAX];
 static char page_title[BR_TITLE_MAX];
 static char cwd[64];
@@ -592,6 +603,74 @@ static int resolve_link(const char *base, const char *href, char *out,
 	return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
 }
 
+/* Best-effort decompression: keep the first `cap` bytes and discard the
+ * rest instead of failing when a page or stylesheet is larger than the
+ * buffer.  The stream is still walked to the end, so a normal page is
+ * verified; a truncated compressed input still returns whatever was decoded
+ * so far. */
+struct trunc_buf {
+	unsigned char *dst;
+	unsigned int cap, pos;
+	int full;
+};
+
+static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
+{
+	struct trunc_buf *m = (struct trunc_buf *)ctx;
+
+	if (len > m->cap - m->pos) {
+		unsigned int room = m->cap - m->pos;
+
+		if (room) {
+			unsigned int i;
+
+			for (i = 0; i < room; i++)
+				m->dst[m->pos + i] = data[i];
+			m->pos += room;
+		}
+		m->full = 1;
+		return 0;
+	}
+	{
+		unsigned int i;
+
+		for (i = 0; i < len; i++)
+			m->dst[m->pos + i] = data[i];
+	}
+	m->pos += len;
+	return 0;
+}
+
+static int inflate_trunc(const unsigned char *src, unsigned int len,
+			 unsigned char *dst, unsigned int cap,
+			 unsigned int *outlen, int gzip, int *truncated)
+{
+	struct inflate_src in;
+	struct inflate_sink sink;
+	struct trunc_buf m;
+	unsigned int got = 0;
+	int r;
+
+	in.p = src;
+	in.len = len;
+	in.more = 0;
+	in.ctx = 0;
+	m.dst = dst;
+	m.cap = cap;
+	m.pos = 0;
+	m.full = 0;
+	sink.write = trunc_write;
+	sink.ctx = &m;
+	inflate_init(&image_inflate_ws, &in, &sink);
+	r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
+		   inflate_zlib(&image_inflate_ws, &got);
+	*outlen = m.pos;
+	*truncated = m.full || r != 0;
+	if (r != 0 && m.pos == 0)
+		return -1;
+	return 0;
+}
+
 /* ---- HTTP / file fetch ---- */
 
 static int read_url(const char *url, unsigned int cap, unsigned char **out,
@@ -650,20 +729,14 @@ static int read_url(const char *url, unsigned int cap, unsigned char **out,
 	if (http.resp.gzip ||
 	    contains_ci(http.resp.content_encoding, "gzip") ||
 	    contains_ci(http.resp.content_encoding, "deflate")) {
-		unsigned char *comp = (unsigned char *)heap_alloc(cap, 16);
-		unsigned int climit = cap * 2;
+		unsigned char *comp = image_io_buf;
+		unsigned int climit = cap;
 		unsigned char *plain;
-		struct inflate *ws;
 		unsigned int plen = 0;
-		int zr;
+		int zr, was_trunc;
 
-		if (climit > 4u * 1024u * 1024u)
-			climit = 4u * 1024u * 1024u;
-		if (!comp) {
-			s_copy(err, "out of memory", errcap);
-			uhttp_close(&http);
-			return -1;
-		}
+		if (climit > BR_PAGE_COMP_MAX)
+			climit = BR_PAGE_COMP_MAX;
 		total = 0;
 		for (;;) {
 			rv = uhttp_read(&http, comp + total, climit - total,
@@ -685,19 +758,22 @@ static int read_url(const char *url, unsigned int cap, unsigned char **out,
 		}
 		uhttp_close(&http);
 		plain = (unsigned char *)heap_alloc(cap, 16);
-		ws = (struct inflate *)heap_alloc(sizeof(struct inflate), 16);
-		if (!plain || !ws) {
+		if (!plain) {
 			s_copy(err, "out of memory", errcap);
 			return -1;
 		}
 		if (contains_ci(http.resp.content_encoding, "deflate"))
-			zr = inflate_zlib_mem(comp, total, plain, cap, &plen, ws);
+			zr = inflate_trunc(comp, total, plain, cap, &plen, 0,
+					   &was_trunc);
 		else
-			zr = inflate_gzip_mem(comp, total, plain, cap, &plen, ws);
+			zr = inflate_trunc(comp, total, plain, cap, &plen, 1,
+					   &was_trunc);
 		if (zr != 0) {
 			s_copy(err, "compressed page is corrupt", errcap);
 			return -1;
 		}
+		if (was_trunc)
+			*truncated = 1;
 		*out = plain;
 		*outlen = plen;
 		return 0;
@@ -842,6 +918,107 @@ static int fetch_image(const char *url, unsigned int cap,
 	return 0;
 }
 
+/* Read one stylesheet into the shared static buffer.  CSS is parsed
+ * immediately, so it does not need the page heap; this leaves the heap for
+ * the 2 MB page body, the decode arena and the scaled image bitmaps. */
+static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
+		     char *err, unsigned int errcap)
+{
+	unsigned int total = 0;
+	int rv;
+
+	*out = 0;
+	*outlen = 0;
+	if (url[0] == '/') {
+		rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
+				(int)BR_CSS_MAX);
+		if (rv < 0) {
+			s_copy(err, "stylesheet not found", errcap);
+			return -1;
+		}
+		*out = image_io_buf;
+		*outlen = (unsigned int)rv;
+		return 0;
+	}
+
+	uhttp_init(&http);
+	http.user_agent = "nebos-browser/0.1";
+	rv = uhttp_open(&http, url, UHTTP_GZIP, 0);
+	if (rv != 0) {
+		s_copy(err, uhttp_error_string(rv), errcap);
+		return -1;
+	}
+	if (http.resp.gzip ||
+	    contains_ci(http.resp.content_encoding, "gzip") ||
+	    contains_ci(http.resp.content_encoding, "deflate")) {
+		unsigned char *comp = image_io_buf + BR_CSS_MAX;
+		unsigned int plen = 0;
+		int zr, was_trunc;
+
+		total = 0;
+		for (;;) {
+			rv = uhttp_read(&http, comp + total,
+					BR_CSS_COMP_MAX - total,
+					UHTTP_IDLE_TIMEOUT_MS);
+			if (rv > 0) {
+				total += (unsigned int)rv;
+				if (total >= BR_CSS_COMP_MAX)
+					break;
+				continue;
+			}
+			if (rv < 0) {
+				s_copy(err, uhttp_error_string(rv), errcap);
+				uhttp_close(&http);
+				return -1;
+			}
+			break;
+		}
+		uhttp_close(&http);
+		if (!total) {
+			s_copy(err, "empty stylesheet", errcap);
+			return -1;
+		}
+		if (contains_ci(http.resp.content_encoding, "deflate"))
+			zr = inflate_trunc(comp, total, image_io_buf,
+					   BR_CSS_MAX, &plen, 0, &was_trunc);
+		else
+			zr = inflate_trunc(comp, total, image_io_buf,
+					   BR_CSS_MAX, &plen, 1, &was_trunc);
+		if (zr != 0) {
+			s_copy(err, "stylesheet is corrupt", errcap);
+			return -1;
+		}
+		*out = image_io_buf;
+		*outlen = plen;
+		return 0;
+	}
+
+	for (;;) {
+		rv = uhttp_read(&http, image_io_buf + total,
+				BR_CSS_MAX - total, UHTTP_IDLE_TIMEOUT_MS);
+		if (rv > 0) {
+			total += (unsigned int)rv;
+			if (total >= BR_CSS_MAX)
+				break;
+			continue;
+		}
+		if (rv < 0) {
+			s_copy(err, uhttp_error_string(rv), errcap);
+			uhttp_close(&http);
+			return -1;
+		}
+		break;
+	}
+	uhttp_close(&http);
+	if (!total) {
+		s_copy(err, "empty stylesheet", errcap);
+		return -1;
+	}
+	*out = image_io_buf;
+	*outlen = total;
+	return 0;
+}
+
 /* ---- page loading ---- */
 
 static void redraw_now(void);
@@ -912,9 +1089,6 @@ static void load_stylesheets(void)
 		char url[BR_URL_MAX];
 		unsigned char *data;
 		unsigned int len;
-		int local, trunc;
-		char ctype[64];
-		char final[BR_URL_MAX];
 		char err[64];
 
 		if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
@@ -927,9 +1101,7 @@ static void load_stylesheets(void)
 			continue;
 		if (resolve_link(page_url, href, url, sizeof(url)) != 0)
 			continue;
-		if (read_url(url, BR_CSS_MAX, &data, &len, &local, ctype,
-			     sizeof(ctype), final, sizeof(final), err,
-			     sizeof(err), &trunc) != 0)
+		if (fetch_css(url, &data, &len, err, sizeof(err)) != 0)
 			continue;
 		if (len)
 			br_parse_css_text(&doc, (const char *)data, len);
@@ -1673,6 +1845,32 @@ static void layout_block(struct lay *l, unsigned int node,
 			ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
 				 l->y + 2, l->right - l->left, 1}, BR_GRAY);
 		l->y += 8;
+	} else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
+		int vw = l->right - l->left;
+		int vh;
+
+		if (doc.nodes[node].width_pct)
+			vw = vw * doc.nodes[node].width_attr / 100;
+		else if (doc.nodes[node].width_attr)
+			vw = doc.nodes[node].width_attr;
+		if (vw > l->right - l->left)
+			vw = l->right - l->left;
+		if (vw < 8)
+			vw = 8;
+		vh = vw * 9 / 16;
+		if (vh > 240)
+			vh = 240;
+		if (vh < 80)
+			vh = 80;
+		if (l->draw) {
+			ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
+							 vw, vh}, 0xD69A);
+			ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
+							 vw, vh}, 0x8410);
+			ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
+				  0x4208);
+		}
+		l->y += vh + 4;
 	} else {
 		if (doc.nodes[node].tag == BR_TAG_LI && !st->no_bullet) {
 			char *m = li_marker[node];
@@ -1712,6 +1910,154 @@ static void layout_block(struct lay *l, unsigned int node,
 	}
 }
 
+
+static int text_node_blank(const struct br_node *nd)
+{
+	const char *t = doc.text + nd->text_off;
+	unsigned int i;
+
+	for (i = 0; i < nd->text_len; i++)
+		if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
+		    t[i] != '\r')
+			return 0;
+	return 1;
+}
+
+/* Rough shrink-to-fit width for a float without an explicit width: sum the
+ * text/image widths in the subtree, plus padding and margins.  This keeps
+ * Bootstrap's floated nav items on one line instead of giving each the whole
+ * row. */
+static int intrinsic_width(unsigned int node, const struct br_style *pst,
+			   int depth)
+{
+	unsigned int c;
+	int w = 0;
+
+	if (depth > 12)
+		return 0;
+	for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
+		struct br_node *nd = &doc.nodes[c];
+		struct br_style cs;
+
+		if (nd->type == BR_NODE_TEXT) {
+			w += (int)nd->text_len * (8 * pst->scale) +
+			     (pst->bold ? 1 : 0);
+			continue;
+		}
+		br_style_for(&doc, c, pst, &cs);
+		if (cs.display == BR_DISPLAY_NONE)
+			continue;
+		if (cs.float_left)
+			w += 8;
+		if (nd->tag == BR_TAG_BR) {
+			w += 8;
+			continue;
+		}
+		if (nd->tag == BR_TAG_IMG) {
+			int idx = nd->img_index;
+
+			if (idx >= 0 && idx < image_count &&
+			    images[idx].state == 1)
+				w += (int)images[idx].img.w;
+			else if (nd->width_attr)
+				w += nd->width_attr;
+			else
+				w += 64;
+			continue;
+		}
+		w += cs.pl + cs.pr + cs.ml + cs.mr;
+		w += intrinsic_width(c, &cs, depth + 1);
+		if (w > 4096)
+			break;
+	}
+	return w;
+}
+
+/* Lay consecutive floated block children side by side.  Bootstrap's grid is
+ * the main user: .row > .col-md-* with float:left and a percentage width.
+ * Each column is laid out with its own left/right edge and the row advances
+ * to the tallest column.  Returns the first child not consumed. */
+static unsigned int layout_float_group(struct lay *l, unsigned int first,
+				       const struct br_style *pst, int depth,
+				       unsigned short link)
+{
+	unsigned int n = first;
+	int row_left = l->left, row_right = l->right;
+	int row_top, row_bottom, x, any = 0;
+
+	flush_line(l);
+	row_top = l->y;
+	row_bottom = l->y;
+	x = row_left;
+	while (n) {
+		struct br_node *nd = &doc.nodes[n];
+		struct br_style cs;
+		int colw;
+
+		if (nd->type == BR_NODE_TEXT) {
+			if (text_node_blank(nd)) {
+				n = nd->next;
+				continue;
+			}
+			break;
+		}
+		br_style_for(&doc, n, pst, &cs);
+		if (cs.display == BR_DISPLAY_NONE) {
+			n = nd->next;
+			continue;
+		}
+		if (!cs.float_left)
+			break;
+		if (cs.width_kind == 2)
+			colw = (row_right - row_left) * (int)cs.width / 100;
+		else if (cs.width_kind == 1)
+			colw = (int)cs.width;
+		else {
+			colw = intrinsic_width(n, &cs, 0) +
+			       cs.pl + cs.pr + cs.ml + cs.mr + 8;
+			if (colw < 8)
+				colw = 8;
+		}
+		if (colw < 8)
+			colw = 8;
+		if (colw > row_right - row_left)
+			colw = row_right - row_left;
+		if (any && x + colw > row_right) {
+			row_top = row_bottom;
+			row_bottom = row_top;
+			x = row_left;
+		}
+		l->left = x;
+		l->right = x + colw;
+		if (l->right < l->left + 8)
+			l->right = l->left + 8;
+		l->y = row_top;
+		l->line_x = l->left;
+		l->run_x = l->left;
+		l->line_y = l->y;
+		l->line_h = 0;
+		l->nruns = 0;
+		l->space_pending = 0;
+		l->align = cs.align;
+		layout_block(l, n, &cs, depth + 1, link);
+		if (l->y > row_bottom)
+			row_bottom = l->y;
+		x += colw;
+		any++;
+		n = nd->next;
+	}
+	l->left = row_left;
+	l->right = row_right;
+	l->y = row_bottom;
+	l->line_x = l->left;
+	l->run_x = l->left;
+	l->line_y = l->y;
+	l->line_h = 0;
+	l->nruns = 0;
+	l->space_pending = 0;
+	return n;
+}
+
 static void layout_children(struct lay *l, unsigned int parent,
 			    const struct br_style *pst, int depth,
 			    unsigned short link)
@@ -1720,7 +2066,8 @@ static void layout_children(struct lay *l, unsigned int parent,
 
 	if (depth > 24)
 		return;
-	for (n = doc.nodes[parent].first; n; n = doc.nodes[n].next) {
+	n = doc.nodes[parent].first;
+	while (n) {
 		struct br_node *nd = &doc.nodes[n];
 		struct br_style cs;
 		unsigned short lk = link;
@@ -1728,15 +2075,19 @@ static void layout_children(struct lay *l, unsigned int parent,
 		if (nd->type == BR_NODE_TEXT) {
 			emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
 				  link, (nd->flags & BR_NODE_PREFORMAT) != 0);
+			n = nd->next;
 			continue;
 		}
 		br_style_for(&doc, n, pst, &cs);
-		if (cs.display == BR_DISPLAY_NONE)
+		if (cs.display == BR_DISPLAY_NONE) {
+			n = nd->next;
 			continue;
+		}
 		if (nd->tag == BR_TAG_A && nd->href_off)
 			lk = (unsigned short)n;
 		if (nd->tag == BR_TAG_BR) {
 			flush_line(l);
+			n = nd->next;
 			continue;
 		}
 		if (nd->tag == BR_TAG_HR) {
@@ -1746,19 +2097,31 @@ static void layout_children(struct lay *l, unsigned int parent,
 					(struct ngui_rect){l->left, l->y + 2,
 					l->right - l->left, 1}, BR_GRAY);
 			l->y += 8;
+			n = nd->next;
 			continue;
 		}
 		if (nd->tag == BR_TAG_IMG) {
 			add_image_run(l, n, &cs, lk);
+			n = nd->next;
 			continue;
 		}
-		if (cs.display == BR_DISPLAY_BLOCK || br_tag_is_block(nd->tag)) {
+		if (nd->tag == BR_TAG_VIDEO) {
 			layout_block(l, n, &cs, depth + 1, lk);
-		} else {
+			n = nd->next;
+			continue;
+		}
+		if (cs.float_left) {
+			n = layout_float_group(l, n, pst, depth, link);
+			continue;
+		}
+		if (cs.display == BR_DISPLAY_BLOCK || br_tag_is_block(nd->tag))
+			layout_block(l, n, &cs, depth + 1, lk);
+		else {
 			layout_children(l, n, &cs, depth + 1, lk);
 			if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
 				l->space_pending = 1;
 		}
+		n = nd->next;
 	}
 }
 
@@ -2070,6 +2433,7 @@ void _start(const char *arg)
 	ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
 	url_in.placeholder = "http://...";
 	br_doc_init(&doc);
+	br_set_viewport(BR_VIEWPORT_W);
 	if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
 		s_copy(cwd, "/", sizeof(cwd));
 	heap_clear();

+ 193 - 0
browser_html.c

@@ -629,6 +629,7 @@ enum {
 	PROP_BORDER_W, PROP_BORDER_COLOR, PROP_LIST_NONE,
 	PROP_WIDTH, PROP_WIDTH_KIND, PROP_MAXW, PROP_MAXW_KIND,
 	PROP_HEIGHT, PROP_HEIGHT_KIND, PROP_LH_PCT, PROP_LH_PX, PROP_UPPER,
+	PROP_FLOAT,
 	PROP_COUNT
 };
 
@@ -1225,6 +1226,16 @@ static void parse_decls(const char *s, unsigned int len, struct br_decl *out,
 			decl_add(out, nout, PROP_DISPLAY,
 				 parse_display(s + vstart, vend - vstart),
 				 important);
+		} else if (str_eq(prop, "float")) {
+			int f = 0;
+
+			if (vend - vstart >= 4 &&
+			    ci_eq_n(s + vstart, "left", 4))
+				f = 1;
+			else if (vend - vstart >= 5 &&
+				 ci_eq_n(s + vstart, "right", 5))
+				f = 2;
+			decl_add(out, nout, PROP_FLOAT, f, important);
 		} else if (str_eq(prop, "width") ||
 			   str_eq(prop, "max-width") ||
 			   str_eq(prop, "height")) {
@@ -1380,6 +1391,124 @@ static unsigned int skip_at_rule(const char *s, unsigned int len,
 	return j;
 }
 
+static unsigned int viewport_w = 1024;
+
+void br_set_viewport(unsigned int width)
+{
+	viewport_w = width ? width : 1024;
+}
+
+static unsigned int media_len_px(const char *s, unsigned int len)
+{
+	unsigned int i = 0, whole = 0, frac = 0, scale = 1, v;
+	int em = 0;
+
+	while (i < len && is_space(s[i]))
+		i++;
+	while (i < len && s[i] >= '0' && s[i] <= '9') {
+		whole = whole * 10 + (unsigned int)(s[i] - '0');
+		i++;
+	}
+	if (i < len && s[i] == '.') {
+		i++;
+		while (i < len && s[i] >= '0' && s[i] <= '9' && scale < 1000) {
+			frac = frac * 10 + (unsigned int)(s[i] - '0');
+			scale *= 10;
+			i++;
+		}
+	}
+	while (i < len && is_space(s[i]))
+		i++;
+	if (i + 2 <= len && ci_eq_n(s + i, "em", 2)) {
+		em = 1;
+		i += 2;
+	} else if (i + 3 <= len && ci_eq_n(s + i, "rem", 3)) {
+		em = 1;
+		i += 3;
+	} else if (i + 2 <= len && ci_eq_n(s + i, "px", 2)) {
+		i += 2;
+	}
+	v = whole * 100 + (scale > 1 ? frac * 100 / scale : 0);
+	if (em)
+		return v * 16 / 100;
+	return v / 100;
+}
+
+/* One parenthesised media feature: min-width/max-width and the modern
+ * (width <= 600px) form.  Unknown features are treated as true. */
+static int media_feature_matches(const char *s, unsigned int len)
+{
+	unsigned int i;
+
+	while (len && is_space(*s)) { s++; len--; }
+	while (len && is_space(s[len - 1])) len--;
+	if (len >= 9 && ci_eq_n(s, "min-width", 9)) {
+		for (i = 9; i < len && s[i] != ':'; i++)
+			;
+		if (i < len)
+			return viewport_w >= media_len_px(s + i + 1,
+							  len - i - 1);
+		return 1;
+	}
+	if (len >= 9 && ci_eq_n(s, "max-width", 9)) {
+		for (i = 9; i < len && s[i] != ':'; i++)
+			;
+		if (i < len)
+			return viewport_w <= media_len_px(s + i + 1,
+							  len - i - 1);
+		return 1;
+	}
+	for (i = 0; i < len; i++) {
+		if (s[i] == '<' || s[i] == '>') {
+			int max = s[i] == '<';
+			unsigned int v = media_len_px(s + i + 1, len - i - 1);
+
+			if (i + 1 < len && s[i + 1] == '=')
+				v = media_len_px(s + i + 2, len - i - 2);
+			return max ? viewport_w <= v : viewport_w >= v;
+		}
+	}
+	return 1;
+}
+
+static int media_query_matches(const char *s, unsigned int len)
+{
+	unsigned int i;
+
+	if (contains_ci_len(s, len, "print") &&
+	    !contains_ci_len(s, len, "screen"))
+		return 0;
+	if (contains_ci_len(s, len, "not "))
+		return 0;
+	for (i = 0; i < len; i++) {
+		if (s[i] == '(') {
+			unsigned int st = ++i;
+
+			while (i < len && s[i] != ')')
+				i++;
+			if (!media_feature_matches(s + st, i - st))
+				return 0;
+		}
+	}
+	return 1;
+}
+
+static int media_list_matches(const char *s, unsigned int len)
+{
+	unsigned int i = 0;
+
+	while (i < len) {
+		unsigned int st = i;
+
+		while (i < len && s[i] != ',')
+			i++;
+		if (media_query_matches(s + st, i - st))
+			return 1;
+		i++;
+	}
+	return 0;
+}
+
 static void parse_css(struct br_doc *d, const char *s, unsigned int len)
 {
 	unsigned int i = 0;
@@ -1401,6 +1530,33 @@ static void parse_css(struct br_doc *d, const char *s, unsigned int len)
 		if (i >= len || s[i] == '}')
 			break;
 		if (s[i] == '@') {
+			if (i + 6 <= len && ci_eq_n(s + i, "@media", 6)) {
+				unsigned int q = i + 6;
+
+				while (q < len && s[q] != '{')
+					q++;
+				if (q < len &&
+				    media_list_matches(s + i + 6,
+						       q - (i + 6))) {
+					unsigned int b = q + 1, e = b;
+					int depth = 1;
+
+					while (e < len && depth) {
+						if (s[e] == '{')
+							depth++;
+						else if (s[e] == '}')
+							depth--;
+						e++;
+					}
+					if (depth == 0)
+						parse_css(d, s + b,
+							 (e - 1) - b);
+					i = e;
+				} else {
+					i = skip_at_rule(s, len, i);
+				}
+				continue;
+			}
 			i = skip_at_rule(s, len, i);
 			continue;
 		}
@@ -1741,6 +1897,9 @@ static void apply_decl(struct br_style *st, const struct br_decl *dcl)
 	case PROP_UPPER:
 		st->uppercase = (unsigned char)(dcl->val != 0);
 		break;
+	case PROP_FLOAT:
+		st->float_left = (unsigned char)dcl->val;
+		break;
 	default:
 		break;
 	}
@@ -1778,6 +1937,7 @@ void br_style_for(struct br_doc *d, unsigned int node,
 
 	*out = *parent;
 	out->has_bg = 0;
+	out->float_left = 0;
 	out->border_w = 0;
 	out->border_color = 0;
 	out->width = out->max_width = out->height = 0;
@@ -1928,6 +2088,21 @@ static void implicit_close(struct br_doc *d, unsigned short *stack,
 	}
 }
 
+static int has_attr_token(const char *s, unsigned int len, const char *name)
+{
+	unsigned int i, n = s_len(name);
+
+	for (i = 0; i + n <= len; i++) {
+		if (i && !is_space(s[i - 1]) && s[i - 1] != '/')
+			continue;
+		if (!ci_eq_n(s + i, name, n))
+			continue;
+		if (i + n == len || is_space(s[i + n]) || s[i + n] == '=')
+			return 1;
+	}
+	return 0;
+}
+
 int br_parse(struct br_doc *d, const char *html, unsigned int len)
 {
 	unsigned short stack[64];
@@ -2066,6 +2241,24 @@ int br_parse(struct br_doc *d, const char *html, unsigned int len)
 					i++;
 				continue;
 			}
+			if (tag == BR_TAG_SVG && !selfclose) {
+				/* Inline SVG is not rendered; skip its subtree so
+				 * logos and icon sprites do not consume the node
+				 * arena. */
+				int p = find_ci(html, len, "</svg>", 6, i);
+				i = p >= 0 ? (unsigned int)p + 6 : len;
+				continue;
+			}
+			if (tag == BR_TAG_DETAILS && !selfclose &&
+			    !has_attr_token(html + attr_start,
+					    attr_end - attr_start, "open")) {
+				/* Closed <details> is collapsed (and this browser has
+				 * no script to open it); skipping the subtree keeps
+				 * mobile mega-menus out of the node arena. */
+				int p = find_ci(html, len, "</details>", 10, i);
+				i = p >= 0 ? (unsigned int)p + 10 : len;
+				continue;
+			}
 			if (tag == BR_TAG_STYLE) {
 				int p = find_ci(html, len, "</style", 7, i);
 				unsigned int end = p >= 0 ? (unsigned int)p : len;

+ 6 - 4
browser_html.h

@@ -6,11 +6,11 @@
 #ifndef BROWSER_HTML_H
 #define BROWSER_HTML_H
 
-#define BR_MAX_NODES     1536
-#define BR_TEXT_SIZE     24576
-#define BR_ATTR_SIZE     64000
+#define BR_MAX_NODES     2560
+#define BR_TEXT_SIZE     32768
+#define BR_ATTR_SIZE     131072
 #define BR_CSS_SIZE      12288
-#define BR_MAX_RULES     1536
+#define BR_MAX_RULES     1792
 #define BR_DECLS         16
 #define BR_TITLE_MAX     96
 
@@ -64,6 +64,7 @@ struct br_style {
 	unsigned char underline;
 	unsigned char align;        /* BR_ALIGN_* */
 	unsigned char display;      /* BR_DISPLAY_* */
+	unsigned char float_left;   /* float: left/right */
 	unsigned char no_bullet;    /* list-style: none (inherited) */
 	unsigned char uppercase;    /* text-transform: uppercase (inherited) */
 	unsigned char border_w;
@@ -142,6 +143,7 @@ unsigned int br_parse_image_doc(struct br_doc *d, const char *src);
 
 /* External CSS is parsed by the browser after br_parse(); parse the inline
  * <style> blocks last so the cascade order matches the document. */
+void br_set_viewport(unsigned int width);
 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_reset_styles(struct br_doc *d);